lavc: Rename avpriv_mpv_find_start_code after moving out from mpegvideo
[libav.git] / libavformat / mpegtsenc.c
1 /*
2 * MPEG2 transport stream (aka DVB) muxer
3 * Copyright (c) 2003 Fabrice Bellard
4 *
5 * This file is part of Libav.
6 *
7 * Libav is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * Libav is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22 #include "libavutil/bswap.h"
23 #include "libavutil/crc.h"
24 #include "libavutil/dict.h"
25 #include "libavutil/intreadwrite.h"
26 #include "libavutil/mathematics.h"
27 #include "libavutil/opt.h"
28 #include "libavcodec/internal.h"
29 #include "avformat.h"
30 #include "internal.h"
31 #include "mpegts.h"
32
33 #define PCR_TIME_BASE 27000000
34
35 /* write DVB SI sections */
36
37 /*********************************************/
38 /* mpegts section writer */
39
40 typedef struct MpegTSSection {
41 int pid;
42 int cc;
43 void (*write_packet)(struct MpegTSSection *s, const uint8_t *packet);
44 void *opaque;
45 } MpegTSSection;
46
47 typedef struct MpegTSService {
48 MpegTSSection pmt; /* MPEG2 pmt table context */
49 int sid; /* service ID */
50 char *name;
51 char *provider_name;
52 int pcr_pid;
53 int pcr_packet_count;
54 int pcr_packet_period;
55 } MpegTSService;
56
57 typedef struct MpegTSWrite {
58 const AVClass *av_class;
59 MpegTSSection pat; /* MPEG2 pat table */
60 MpegTSSection sdt; /* MPEG2 sdt table context */
61 MpegTSService **services;
62 int sdt_packet_count;
63 int sdt_packet_period;
64 int pat_packet_count;
65 int pat_packet_period;
66 int nb_services;
67 int onid;
68 int tsid;
69 int64_t first_pcr;
70 int mux_rate; ///< set to 1 when VBR
71 int pes_payload_size;
72
73 int transport_stream_id;
74 int original_network_id;
75 int service_id;
76
77 int pmt_start_pid;
78 int start_pid;
79
80 int reemit_pat_pmt; // backward compatibility
81
82 #define MPEGTS_FLAG_REEMIT_PAT_PMT 0x01
83 #define MPEGTS_FLAG_AAC_LATM 0x02
84 int flags;
85 } MpegTSWrite;
86
87 /* a PES packet header is generated every DEFAULT_PES_HEADER_FREQ packets */
88 #define DEFAULT_PES_HEADER_FREQ 16
89 #define DEFAULT_PES_PAYLOAD_SIZE ((DEFAULT_PES_HEADER_FREQ - 1) * 184 + 170)
90
91 static const AVOption options[] = {
92 { "mpegts_transport_stream_id", "Set transport_stream_id field.",
93 offsetof(MpegTSWrite, transport_stream_id), AV_OPT_TYPE_INT, {.i64 = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
94 { "mpegts_original_network_id", "Set original_network_id field.",
95 offsetof(MpegTSWrite, original_network_id), AV_OPT_TYPE_INT, {.i64 = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
96 { "mpegts_service_id", "Set service_id field.",
97 offsetof(MpegTSWrite, service_id), AV_OPT_TYPE_INT, {.i64 = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
98 { "mpegts_pmt_start_pid", "Set the first pid of the PMT.",
99 offsetof(MpegTSWrite, pmt_start_pid), AV_OPT_TYPE_INT, {.i64 = 0x1000 }, 0x1000, 0x1f00, AV_OPT_FLAG_ENCODING_PARAM},
100 { "mpegts_start_pid", "Set the first pid.",
101 offsetof(MpegTSWrite, start_pid), AV_OPT_TYPE_INT, {.i64 = 0x0100 }, 0x0100, 0x0f00, AV_OPT_FLAG_ENCODING_PARAM},
102 { "muxrate", NULL, offsetof(MpegTSWrite, mux_rate), AV_OPT_TYPE_INT, {.i64 = 1}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
103 { "pes_payload_size", "Minimum PES packet payload in bytes",
104 offsetof(MpegTSWrite, pes_payload_size), AV_OPT_TYPE_INT, {.i64 = DEFAULT_PES_PAYLOAD_SIZE}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
105 { "mpegts_flags", "MPEG-TS muxing flags", offsetof(MpegTSWrite, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, 0, INT_MAX,
106 AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags" },
107 { "resend_headers", "Reemit PAT/PMT before writing the next packet",
108 0, AV_OPT_TYPE_CONST, {.i64 = MPEGTS_FLAG_REEMIT_PAT_PMT}, 0, INT_MAX,
109 AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags"},
110 { "latm", "Use LATM packetization for AAC",
111 0, AV_OPT_TYPE_CONST, {.i64 = MPEGTS_FLAG_AAC_LATM}, 0, INT_MAX,
112 AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags"},
113 // backward compatibility
114 { "resend_headers", "Reemit PAT/PMT before writing the next packet",
115 offsetof(MpegTSWrite, reemit_pat_pmt), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
116 { NULL },
117 };
118
119 static const AVClass mpegts_muxer_class = {
120 .class_name = "MPEGTS muxer",
121 .item_name = av_default_item_name,
122 .option = options,
123 .version = LIBAVUTIL_VERSION_INT,
124 };
125
126 /* NOTE: 4 bytes must be left at the end for the crc32 */
127 static void mpegts_write_section(MpegTSSection *s, uint8_t *buf, int len)
128 {
129 unsigned int crc;
130 unsigned char packet[TS_PACKET_SIZE];
131 const unsigned char *buf_ptr;
132 unsigned char *q;
133 int first, b, len1, left;
134
135 crc = av_bswap32(av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1, buf, len - 4));
136 buf[len - 4] = (crc >> 24) & 0xff;
137 buf[len - 3] = (crc >> 16) & 0xff;
138 buf[len - 2] = (crc >> 8) & 0xff;
139 buf[len - 1] = (crc) & 0xff;
140
141 /* send each packet */
142 buf_ptr = buf;
143 while (len > 0) {
144 first = (buf == buf_ptr);
145 q = packet;
146 *q++ = 0x47;
147 b = (s->pid >> 8);
148 if (first)
149 b |= 0x40;
150 *q++ = b;
151 *q++ = s->pid;
152 s->cc = (s->cc + 1) & 0xf;
153 *q++ = 0x10 | s->cc;
154 if (first)
155 *q++ = 0; /* 0 offset */
156 len1 = TS_PACKET_SIZE - (q - packet);
157 if (len1 > len)
158 len1 = len;
159 memcpy(q, buf_ptr, len1);
160 q += len1;
161 /* add known padding data */
162 left = TS_PACKET_SIZE - (q - packet);
163 if (left > 0)
164 memset(q, 0xff, left);
165
166 s->write_packet(s, packet);
167
168 buf_ptr += len1;
169 len -= len1;
170 }
171 }
172
173 static inline void put16(uint8_t **q_ptr, int val)
174 {
175 uint8_t *q;
176 q = *q_ptr;
177 *q++ = val >> 8;
178 *q++ = val;
179 *q_ptr = q;
180 }
181
182 static int mpegts_write_section1(MpegTSSection *s, int tid, int id,
183 int version, int sec_num, int last_sec_num,
184 uint8_t *buf, int len)
185 {
186 uint8_t section[1024], *q;
187 unsigned int tot_len;
188 /* reserved_future_use field must be set to 1 for SDT */
189 unsigned int flags = tid == SDT_TID ? 0xf000 : 0xb000;
190
191 tot_len = 3 + 5 + len + 4;
192 /* check if not too big */
193 if (tot_len > 1024)
194 return -1;
195
196 q = section;
197 *q++ = tid;
198 put16(&q, flags | (len + 5 + 4)); /* 5 byte header + 4 byte CRC */
199 put16(&q, id);
200 *q++ = 0xc1 | (version << 1); /* current_next_indicator = 1 */
201 *q++ = sec_num;
202 *q++ = last_sec_num;
203 memcpy(q, buf, len);
204
205 mpegts_write_section(s, section, tot_len);
206 return 0;
207 }
208
209 /*********************************************/
210 /* mpegts writer */
211
212 #define DEFAULT_PROVIDER_NAME "Libav"
213 #define DEFAULT_SERVICE_NAME "Service01"
214
215 /* we retransmit the SI info at this rate */
216 #define SDT_RETRANS_TIME 500
217 #define PAT_RETRANS_TIME 100
218 #define PCR_RETRANS_TIME 20
219
220 typedef struct MpegTSWriteStream {
221 struct MpegTSService *service;
222 int pid; /* stream associated pid */
223 int cc;
224 int payload_size;
225 int first_pts_check; ///< first pts check needed
226 int64_t payload_pts;
227 int64_t payload_dts;
228 int payload_flags;
229 uint8_t *payload;
230 AVFormatContext *amux;
231 } MpegTSWriteStream;
232
233 static void mpegts_write_pat(AVFormatContext *s)
234 {
235 MpegTSWrite *ts = s->priv_data;
236 MpegTSService *service;
237 uint8_t data[1012], *q;
238 int i;
239
240 q = data;
241 for(i = 0; i < ts->nb_services; i++) {
242 service = ts->services[i];
243 put16(&q, service->sid);
244 put16(&q, 0xe000 | service->pmt.pid);
245 }
246 mpegts_write_section1(&ts->pat, PAT_TID, ts->tsid, 0, 0, 0,
247 data, q - data);
248 }
249
250 static void mpegts_write_pmt(AVFormatContext *s, MpegTSService *service)
251 {
252 MpegTSWrite *ts = s->priv_data;
253 uint8_t data[1012], *q, *desc_length_ptr, *program_info_length_ptr;
254 int val, stream_type, i;
255
256 q = data;
257 put16(&q, 0xe000 | service->pcr_pid);
258
259 program_info_length_ptr = q;
260 q += 2; /* patched after */
261
262 /* put program info here */
263
264 val = 0xf000 | (q - program_info_length_ptr - 2);
265 program_info_length_ptr[0] = val >> 8;
266 program_info_length_ptr[1] = val;
267
268 for(i = 0; i < s->nb_streams; i++) {
269 AVStream *st = s->streams[i];
270 MpegTSWriteStream *ts_st = st->priv_data;
271 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
272 switch(st->codec->codec_id) {
273 case AV_CODEC_ID_MPEG1VIDEO:
274 case AV_CODEC_ID_MPEG2VIDEO:
275 stream_type = STREAM_TYPE_VIDEO_MPEG2;
276 break;
277 case AV_CODEC_ID_MPEG4:
278 stream_type = STREAM_TYPE_VIDEO_MPEG4;
279 break;
280 case AV_CODEC_ID_H264:
281 stream_type = STREAM_TYPE_VIDEO_H264;
282 break;
283 case AV_CODEC_ID_CAVS:
284 stream_type = STREAM_TYPE_VIDEO_CAVS;
285 break;
286 case AV_CODEC_ID_DIRAC:
287 stream_type = STREAM_TYPE_VIDEO_DIRAC;
288 break;
289 case AV_CODEC_ID_MP2:
290 case AV_CODEC_ID_MP3:
291 stream_type = STREAM_TYPE_AUDIO_MPEG1;
292 break;
293 case AV_CODEC_ID_AAC:
294 stream_type = (ts->flags & MPEGTS_FLAG_AAC_LATM) ? STREAM_TYPE_AUDIO_AAC_LATM : STREAM_TYPE_AUDIO_AAC;
295 break;
296 case AV_CODEC_ID_AAC_LATM:
297 stream_type = STREAM_TYPE_AUDIO_AAC_LATM;
298 break;
299 case AV_CODEC_ID_AC3:
300 stream_type = STREAM_TYPE_AUDIO_AC3;
301 break;
302 default:
303 stream_type = STREAM_TYPE_PRIVATE_DATA;
304 break;
305 }
306 *q++ = stream_type;
307 put16(&q, 0xe000 | ts_st->pid);
308 desc_length_ptr = q;
309 q += 2; /* patched after */
310
311 /* write optional descriptors here */
312 switch(st->codec->codec_type) {
313 case AVMEDIA_TYPE_AUDIO:
314 if (lang) {
315 char *p;
316 char *next = lang->value;
317 uint8_t *len_ptr;
318
319 *q++ = 0x0a; /* ISO 639 language descriptor */
320 len_ptr = q++;
321 *len_ptr = 0;
322
323 for (p = lang->value; next && *len_ptr < 255 / 4 * 4; p = next + 1) {
324 next = strchr(p, ',');
325 if (strlen(p) != 3 && (!next || next != p + 3))
326 continue; /* not a 3-letter code */
327
328 *q++ = *p++;
329 *q++ = *p++;
330 *q++ = *p++;
331
332 if (st->disposition & AV_DISPOSITION_CLEAN_EFFECTS)
333 *q++ = 0x01;
334 else if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
335 *q++ = 0x02;
336 else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
337 *q++ = 0x03;
338 else
339 *q++ = 0; /* undefined type */
340
341 *len_ptr += 4;
342 }
343
344 if (*len_ptr == 0)
345 q -= 2; /* no language codes were written */
346 }
347 break;
348 case AVMEDIA_TYPE_SUBTITLE:
349 {
350 const char *language;
351 language = lang && strlen(lang->value)==3 ? lang->value : "eng";
352 *q++ = 0x59;
353 *q++ = 8;
354 *q++ = language[0];
355 *q++ = language[1];
356 *q++ = language[2];
357 *q++ = 0x10; /* normal subtitles (0x20 = if hearing pb) */
358 if(st->codec->extradata_size == 4) {
359 memcpy(q, st->codec->extradata, 4);
360 q += 4;
361 } else {
362 put16(&q, 1); /* page id */
363 put16(&q, 1); /* ancillary page id */
364 }
365 }
366 break;
367 case AVMEDIA_TYPE_VIDEO:
368 if (stream_type == STREAM_TYPE_VIDEO_DIRAC) {
369 *q++ = 0x05; /*MPEG-2 registration descriptor*/
370 *q++ = 4;
371 *q++ = 'd';
372 *q++ = 'r';
373 *q++ = 'a';
374 *q++ = 'c';
375 }
376 break;
377 }
378
379 val = 0xf000 | (q - desc_length_ptr - 2);
380 desc_length_ptr[0] = val >> 8;
381 desc_length_ptr[1] = val;
382 }
383 mpegts_write_section1(&service->pmt, PMT_TID, service->sid, 0, 0, 0,
384 data, q - data);
385 }
386
387 /* NOTE: str == NULL is accepted for an empty string */
388 static void putstr8(uint8_t **q_ptr, const char *str)
389 {
390 uint8_t *q;
391 int len;
392
393 q = *q_ptr;
394 if (!str)
395 len = 0;
396 else
397 len = strlen(str);
398 *q++ = len;
399 memcpy(q, str, len);
400 q += len;
401 *q_ptr = q;
402 }
403
404 static void mpegts_write_sdt(AVFormatContext *s)
405 {
406 MpegTSWrite *ts = s->priv_data;
407 MpegTSService *service;
408 uint8_t data[1012], *q, *desc_list_len_ptr, *desc_len_ptr;
409 int i, running_status, free_ca_mode, val;
410
411 q = data;
412 put16(&q, ts->onid);
413 *q++ = 0xff;
414 for(i = 0; i < ts->nb_services; i++) {
415 service = ts->services[i];
416 put16(&q, service->sid);
417 *q++ = 0xfc | 0x00; /* currently no EIT info */
418 desc_list_len_ptr = q;
419 q += 2;
420 running_status = 4; /* running */
421 free_ca_mode = 0;
422
423 /* write only one descriptor for the service name and provider */
424 *q++ = 0x48;
425 desc_len_ptr = q;
426 q++;
427 *q++ = 0x01; /* digital television service */
428 putstr8(&q, service->provider_name);
429 putstr8(&q, service->name);
430 desc_len_ptr[0] = q - desc_len_ptr - 1;
431
432 /* fill descriptor length */
433 val = (running_status << 13) | (free_ca_mode << 12) |
434 (q - desc_list_len_ptr - 2);
435 desc_list_len_ptr[0] = val >> 8;
436 desc_list_len_ptr[1] = val;
437 }
438 mpegts_write_section1(&ts->sdt, SDT_TID, ts->tsid, 0, 0, 0,
439 data, q - data);
440 }
441
442 static MpegTSService *mpegts_add_service(MpegTSWrite *ts,
443 int sid,
444 const char *provider_name,
445 const char *name)
446 {
447 MpegTSService *service;
448
449 service = av_mallocz(sizeof(MpegTSService));
450 if (!service)
451 return NULL;
452 service->pmt.pid = ts->pmt_start_pid + ts->nb_services;
453 service->sid = sid;
454 service->provider_name = av_strdup(provider_name);
455 service->name = av_strdup(name);
456 service->pcr_pid = 0x1fff;
457 dynarray_add(&ts->services, &ts->nb_services, service);
458 return service;
459 }
460
461 static void section_write_packet(MpegTSSection *s, const uint8_t *packet)
462 {
463 AVFormatContext *ctx = s->opaque;
464 avio_write(ctx->pb, packet, TS_PACKET_SIZE);
465 }
466
467 static int mpegts_write_header(AVFormatContext *s)
468 {
469 MpegTSWrite *ts = s->priv_data;
470 MpegTSWriteStream *ts_st;
471 MpegTSService *service;
472 AVStream *st, *pcr_st = NULL;
473 AVDictionaryEntry *title, *provider;
474 int i, j;
475 const char *service_name;
476 const char *provider_name;
477 int *pids;
478 int ret;
479
480 if (s->max_delay < 0) /* Not set by the caller */
481 s->max_delay = 0;
482
483 // round up to a whole number of TS packets
484 ts->pes_payload_size = (ts->pes_payload_size + 14 + 183) / 184 * 184 - 14;
485
486 ts->tsid = ts->transport_stream_id;
487 ts->onid = ts->original_network_id;
488 /* allocate a single DVB service */
489 title = av_dict_get(s->metadata, "service_name", NULL, 0);
490 if (!title)
491 title = av_dict_get(s->metadata, "title", NULL, 0);
492 service_name = title ? title->value : DEFAULT_SERVICE_NAME;
493 provider = av_dict_get(s->metadata, "service_provider", NULL, 0);
494 provider_name = provider ? provider->value : DEFAULT_PROVIDER_NAME;
495 service = mpegts_add_service(ts, ts->service_id, provider_name, service_name);
496 service->pmt.write_packet = section_write_packet;
497 service->pmt.opaque = s;
498 service->pmt.cc = 15;
499
500 ts->pat.pid = PAT_PID;
501 ts->pat.cc = 15; // Initialize at 15 so that it wraps and be equal to 0 for the first packet we write
502 ts->pat.write_packet = section_write_packet;
503 ts->pat.opaque = s;
504
505 ts->sdt.pid = SDT_PID;
506 ts->sdt.cc = 15;
507 ts->sdt.write_packet = section_write_packet;
508 ts->sdt.opaque = s;
509
510 pids = av_malloc(s->nb_streams * sizeof(*pids));
511 if (!pids)
512 return AVERROR(ENOMEM);
513
514 /* assign pids to each stream */
515 for(i = 0;i < s->nb_streams; i++) {
516 st = s->streams[i];
517 avpriv_set_pts_info(st, 33, 1, 90000);
518 ts_st = av_mallocz(sizeof(MpegTSWriteStream));
519 if (!ts_st) {
520 ret = AVERROR(ENOMEM);
521 goto fail;
522 }
523 st->priv_data = ts_st;
524 ts_st->payload = av_mallocz(ts->pes_payload_size);
525 if (!ts_st->payload) {
526 ret = AVERROR(ENOMEM);
527 goto fail;
528 }
529 ts_st->service = service;
530 /* MPEG pid values < 16 are reserved. Applications which set st->id in
531 * this range are assigned a calculated pid. */
532 if (st->id < 16) {
533 ts_st->pid = ts->start_pid + i;
534 } else if (st->id < 0x1FFF) {
535 ts_st->pid = st->id;
536 } else {
537 av_log(s, AV_LOG_ERROR, "Invalid stream id %d, must be less than 8191\n", st->id);
538 ret = AVERROR(EINVAL);
539 goto fail;
540 }
541 if (ts_st->pid == service->pmt.pid) {
542 av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
543 ret = AVERROR(EINVAL);
544 goto fail;
545 }
546 for (j = 0; j < i; j++)
547 if (pids[j] == ts_st->pid) {
548 av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
549 ret = AVERROR(EINVAL);
550 goto fail;
551 }
552 pids[i] = ts_st->pid;
553 ts_st->payload_pts = AV_NOPTS_VALUE;
554 ts_st->payload_dts = AV_NOPTS_VALUE;
555 ts_st->first_pts_check = 1;
556 ts_st->cc = 15;
557 /* update PCR pid by using the first video stream */
558 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
559 service->pcr_pid == 0x1fff) {
560 service->pcr_pid = ts_st->pid;
561 pcr_st = st;
562 }
563 if (st->codec->codec_id == AV_CODEC_ID_AAC &&
564 st->codec->extradata_size > 0)
565 {
566 AVStream *ast;
567 ts_st->amux = avformat_alloc_context();
568 if (!ts_st->amux) {
569 ret = AVERROR(ENOMEM);
570 goto fail;
571 }
572 ts_st->amux->oformat = av_guess_format((ts->flags & MPEGTS_FLAG_AAC_LATM) ? "latm" : "adts", NULL, NULL);
573 if (!ts_st->amux->oformat) {
574 ret = AVERROR(EINVAL);
575 goto fail;
576 }
577 ast = avformat_new_stream(ts_st->amux, NULL);
578 ret = avcodec_copy_context(ast->codec, st->codec);
579 if (ret != 0)
580 goto fail;
581 ret = avformat_write_header(ts_st->amux, NULL);
582 if (ret < 0)
583 goto fail;
584 }
585 }
586
587 av_free(pids);
588
589 /* if no video stream, use the first stream as PCR */
590 if (service->pcr_pid == 0x1fff && s->nb_streams > 0) {
591 pcr_st = s->streams[0];
592 ts_st = pcr_st->priv_data;
593 service->pcr_pid = ts_st->pid;
594 }
595
596 if (ts->mux_rate > 1) {
597 service->pcr_packet_period = (ts->mux_rate * PCR_RETRANS_TIME) /
598 (TS_PACKET_SIZE * 8 * 1000);
599 ts->sdt_packet_period = (ts->mux_rate * SDT_RETRANS_TIME) /
600 (TS_PACKET_SIZE * 8 * 1000);
601 ts->pat_packet_period = (ts->mux_rate * PAT_RETRANS_TIME) /
602 (TS_PACKET_SIZE * 8 * 1000);
603
604 ts->first_pcr = av_rescale(s->max_delay, PCR_TIME_BASE, AV_TIME_BASE);
605 } else {
606 /* Arbitrary values, PAT/PMT could be written on key frames */
607 ts->sdt_packet_period = 200;
608 ts->pat_packet_period = 40;
609 if (pcr_st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
610 if (!pcr_st->codec->frame_size) {
611 av_log(s, AV_LOG_WARNING, "frame size not set\n");
612 service->pcr_packet_period =
613 pcr_st->codec->sample_rate/(10*512);
614 } else {
615 service->pcr_packet_period =
616 pcr_st->codec->sample_rate/(10*pcr_st->codec->frame_size);
617 }
618 } else {
619 // max delta PCR 0.1s
620 service->pcr_packet_period =
621 pcr_st->codec->time_base.den/(10*pcr_st->codec->time_base.num);
622 }
623 }
624
625 // output a PCR as soon as possible
626 service->pcr_packet_count = service->pcr_packet_period;
627 ts->pat_packet_count = ts->pat_packet_period-1;
628 ts->sdt_packet_count = ts->sdt_packet_period-1;
629
630 if (ts->mux_rate == 1)
631 av_log(s, AV_LOG_VERBOSE, "muxrate VBR, ");
632 else
633 av_log(s, AV_LOG_VERBOSE, "muxrate %d, ", ts->mux_rate);
634 av_log(s, AV_LOG_VERBOSE, "pcr every %d pkts, "
635 "sdt every %d, pat/pmt every %d pkts\n",
636 service->pcr_packet_period,
637 ts->sdt_packet_period, ts->pat_packet_period);
638
639 avio_flush(s->pb);
640
641 return 0;
642
643 fail:
644 av_free(pids);
645 for(i = 0;i < s->nb_streams; i++) {
646 MpegTSWriteStream *ts_st;
647 st = s->streams[i];
648 ts_st = st->priv_data;
649 if (ts_st) {
650 av_freep(&ts_st->payload);
651 if (ts_st->amux) {
652 avformat_free_context(ts_st->amux);
653 ts_st->amux = NULL;
654 }
655 }
656 av_freep(&st->priv_data);
657 }
658 return ret;
659 }
660
661 /* send SDT, PAT and PMT tables regulary */
662 static void retransmit_si_info(AVFormatContext *s)
663 {
664 MpegTSWrite *ts = s->priv_data;
665 int i;
666
667 if (++ts->sdt_packet_count == ts->sdt_packet_period) {
668 ts->sdt_packet_count = 0;
669 mpegts_write_sdt(s);
670 }
671 if (++ts->pat_packet_count == ts->pat_packet_period) {
672 ts->pat_packet_count = 0;
673 mpegts_write_pat(s);
674 for(i = 0; i < ts->nb_services; i++) {
675 mpegts_write_pmt(s, ts->services[i]);
676 }
677 }
678 }
679
680 static int64_t get_pcr(const MpegTSWrite *ts, AVIOContext *pb)
681 {
682 return av_rescale(avio_tell(pb) + 11, 8 * PCR_TIME_BASE, ts->mux_rate) +
683 ts->first_pcr;
684 }
685
686 static int write_pcr_bits(uint8_t *buf, int64_t pcr)
687 {
688 int64_t pcr_low = pcr % 300, pcr_high = pcr / 300;
689
690 *buf++ = pcr_high >> 25;
691 *buf++ = pcr_high >> 17;
692 *buf++ = pcr_high >> 9;
693 *buf++ = pcr_high >> 1;
694 *buf++ = pcr_high << 7 | pcr_low >> 8 | 0x7e;
695 *buf++ = pcr_low;
696
697 return 6;
698 }
699
700 /* Write a single null transport stream packet */
701 static void mpegts_insert_null_packet(AVFormatContext *s)
702 {
703 uint8_t *q;
704 uint8_t buf[TS_PACKET_SIZE];
705
706 q = buf;
707 *q++ = 0x47;
708 *q++ = 0x00 | 0x1f;
709 *q++ = 0xff;
710 *q++ = 0x10;
711 memset(q, 0x0FF, TS_PACKET_SIZE - (q - buf));
712 avio_write(s->pb, buf, TS_PACKET_SIZE);
713 }
714
715 /* Write a single transport stream packet with a PCR and no payload */
716 static void mpegts_insert_pcr_only(AVFormatContext *s, AVStream *st)
717 {
718 MpegTSWrite *ts = s->priv_data;
719 MpegTSWriteStream *ts_st = st->priv_data;
720 uint8_t *q;
721 uint8_t buf[TS_PACKET_SIZE];
722
723 q = buf;
724 *q++ = 0x47;
725 *q++ = ts_st->pid >> 8;
726 *q++ = ts_st->pid;
727 *q++ = 0x20 | ts_st->cc; /* Adaptation only */
728 /* Continuity Count field does not increment (see 13818-1 section 2.4.3.3) */
729 *q++ = TS_PACKET_SIZE - 5; /* Adaptation Field Length */
730 *q++ = 0x10; /* Adaptation flags: PCR present */
731
732 /* PCR coded into 6 bytes */
733 q += write_pcr_bits(q, get_pcr(ts, s->pb));
734
735 /* stuffing bytes */
736 memset(q, 0xFF, TS_PACKET_SIZE - (q - buf));
737 avio_write(s->pb, buf, TS_PACKET_SIZE);
738 }
739
740 static void write_pts(uint8_t *q, int fourbits, int64_t pts)
741 {
742 int val;
743
744 val = fourbits << 4 | (((pts >> 30) & 0x07) << 1) | 1;
745 *q++ = val;
746 val = (((pts >> 15) & 0x7fff) << 1) | 1;
747 *q++ = val >> 8;
748 *q++ = val;
749 val = (((pts) & 0x7fff) << 1) | 1;
750 *q++ = val >> 8;
751 *q++ = val;
752 }
753
754 /* Set an adaptation field flag in an MPEG-TS packet*/
755 static void set_af_flag(uint8_t *pkt, int flag)
756 {
757 // expect at least one flag to set
758 assert(flag);
759
760 if ((pkt[3] & 0x20) == 0) {
761 // no AF yet, set adaptation field flag
762 pkt[3] |= 0x20;
763 // 1 byte length, no flags
764 pkt[4] = 1;
765 pkt[5] = 0;
766 }
767 pkt[5] |= flag;
768 }
769
770 /* Extend the adaptation field by size bytes */
771 static void extend_af(uint8_t *pkt, int size)
772 {
773 // expect already existing adaptation field
774 assert(pkt[3] & 0x20);
775 pkt[4] += size;
776 }
777
778 /* Get a pointer to MPEG-TS payload (right after TS packet header) */
779 static uint8_t *get_ts_payload_start(uint8_t *pkt)
780 {
781 if (pkt[3] & 0x20)
782 return pkt + 5 + pkt[4];
783 else
784 return pkt + 4;
785 }
786
787 /* Add a pes header to the front of payload, and segment into an integer number of
788 * ts packets. The final ts packet is padded using an over-sized adaptation header
789 * to exactly fill the last ts packet.
790 * NOTE: 'payload' contains a complete PES payload.
791 */
792 static void mpegts_write_pes(AVFormatContext *s, AVStream *st,
793 const uint8_t *payload, int payload_size,
794 int64_t pts, int64_t dts, int key)
795 {
796 MpegTSWriteStream *ts_st = st->priv_data;
797 MpegTSWrite *ts = s->priv_data;
798 uint8_t buf[TS_PACKET_SIZE];
799 uint8_t *q;
800 int val, is_start, len, header_len, write_pcr, private_code, flags;
801 int afc_len, stuffing_len;
802 int64_t pcr = -1; /* avoid warning */
803 int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE);
804
805 is_start = 1;
806 while (payload_size > 0) {
807 retransmit_si_info(s);
808
809 write_pcr = 0;
810 if (ts_st->pid == ts_st->service->pcr_pid) {
811 if (ts->mux_rate > 1 || is_start) // VBR pcr period is based on frames
812 ts_st->service->pcr_packet_count++;
813 if (ts_st->service->pcr_packet_count >=
814 ts_st->service->pcr_packet_period) {
815 ts_st->service->pcr_packet_count = 0;
816 write_pcr = 1;
817 }
818 }
819
820 if (ts->mux_rate > 1 && dts != AV_NOPTS_VALUE &&
821 (dts - get_pcr(ts, s->pb)/300) > delay) {
822 /* pcr insert gets priority over null packet insert */
823 if (write_pcr)
824 mpegts_insert_pcr_only(s, st);
825 else
826 mpegts_insert_null_packet(s);
827 continue; /* recalculate write_pcr and possibly retransmit si_info */
828 }
829
830 /* prepare packet header */
831 q = buf;
832 *q++ = 0x47;
833 val = (ts_st->pid >> 8);
834 if (is_start)
835 val |= 0x40;
836 *q++ = val;
837 *q++ = ts_st->pid;
838 ts_st->cc = (ts_st->cc + 1) & 0xf;
839 *q++ = 0x10 | ts_st->cc; // payload indicator + CC
840 if (key && is_start && pts != AV_NOPTS_VALUE) {
841 // set Random Access for key frames
842 if (ts_st->pid == ts_st->service->pcr_pid)
843 write_pcr = 1;
844 set_af_flag(buf, 0x40);
845 q = get_ts_payload_start(buf);
846 }
847 if (write_pcr) {
848 set_af_flag(buf, 0x10);
849 q = get_ts_payload_start(buf);
850 // add 11, pcr references the last byte of program clock reference base
851 if (ts->mux_rate > 1)
852 pcr = get_pcr(ts, s->pb);
853 else
854 pcr = (dts - delay)*300;
855 if (dts != AV_NOPTS_VALUE && dts < pcr / 300)
856 av_log(s, AV_LOG_WARNING, "dts < pcr, TS is invalid\n");
857 extend_af(buf, write_pcr_bits(q, pcr));
858 q = get_ts_payload_start(buf);
859 }
860 if (is_start) {
861 int pes_extension = 0;
862 /* write PES header */
863 *q++ = 0x00;
864 *q++ = 0x00;
865 *q++ = 0x01;
866 private_code = 0;
867 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
868 if (st->codec->codec_id == AV_CODEC_ID_DIRAC) {
869 *q++ = 0xfd;
870 } else
871 *q++ = 0xe0;
872 } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
873 (st->codec->codec_id == AV_CODEC_ID_MP2 ||
874 st->codec->codec_id == AV_CODEC_ID_MP3 ||
875 st->codec->codec_id == AV_CODEC_ID_AAC)) {
876 *q++ = 0xc0;
877 } else {
878 *q++ = 0xbd;
879 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
880 private_code = 0x20;
881 }
882 }
883 header_len = 0;
884 flags = 0;
885 if (pts != AV_NOPTS_VALUE) {
886 header_len += 5;
887 flags |= 0x80;
888 }
889 if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
890 header_len += 5;
891 flags |= 0x40;
892 }
893 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
894 st->codec->codec_id == AV_CODEC_ID_DIRAC) {
895 /* set PES_extension_flag */
896 pes_extension = 1;
897 flags |= 0x01;
898
899 /*
900 * One byte for PES2 extension flag +
901 * one byte for extension length +
902 * one byte for extension id
903 */
904 header_len += 3;
905 }
906 len = payload_size + header_len + 3;
907 if (private_code != 0)
908 len++;
909 if (len > 0xffff)
910 len = 0;
911 *q++ = len >> 8;
912 *q++ = len;
913 val = 0x80;
914 /* data alignment indicator is required for subtitle data */
915 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)
916 val |= 0x04;
917 *q++ = val;
918 *q++ = flags;
919 *q++ = header_len;
920 if (pts != AV_NOPTS_VALUE) {
921 write_pts(q, flags >> 6, pts);
922 q += 5;
923 }
924 if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
925 write_pts(q, 1, dts);
926 q += 5;
927 }
928 if (pes_extension && st->codec->codec_id == AV_CODEC_ID_DIRAC) {
929 flags = 0x01; /* set PES_extension_flag_2 */
930 *q++ = flags;
931 *q++ = 0x80 | 0x01; /* marker bit + extension length */
932 /*
933 * Set the stream id extension flag bit to 0 and
934 * write the extended stream id
935 */
936 *q++ = 0x00 | 0x60;
937 }
938 if (private_code != 0)
939 *q++ = private_code;
940 is_start = 0;
941 }
942 /* header size */
943 header_len = q - buf;
944 /* data len */
945 len = TS_PACKET_SIZE - header_len;
946 if (len > payload_size)
947 len = payload_size;
948 stuffing_len = TS_PACKET_SIZE - header_len - len;
949 if (stuffing_len > 0) {
950 /* add stuffing with AFC */
951 if (buf[3] & 0x20) {
952 /* stuffing already present: increase its size */
953 afc_len = buf[4] + 1;
954 memmove(buf + 4 + afc_len + stuffing_len,
955 buf + 4 + afc_len,
956 header_len - (4 + afc_len));
957 buf[4] += stuffing_len;
958 memset(buf + 4 + afc_len, 0xff, stuffing_len);
959 } else {
960 /* add stuffing */
961 memmove(buf + 4 + stuffing_len, buf + 4, header_len - 4);
962 buf[3] |= 0x20;
963 buf[4] = stuffing_len - 1;
964 if (stuffing_len >= 2) {
965 buf[5] = 0x00;
966 memset(buf + 6, 0xff, stuffing_len - 2);
967 }
968 }
969 }
970 memcpy(buf + TS_PACKET_SIZE - len, payload, len);
971 payload += len;
972 payload_size -= len;
973 avio_write(s->pb, buf, TS_PACKET_SIZE);
974 }
975 avio_flush(s->pb);
976 }
977
978 static int mpegts_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
979 {
980 AVStream *st = s->streams[pkt->stream_index];
981 int size = pkt->size;
982 uint8_t *buf= pkt->data;
983 uint8_t *data= NULL;
984 MpegTSWrite *ts = s->priv_data;
985 MpegTSWriteStream *ts_st = st->priv_data;
986 const uint64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE)*2;
987 int64_t dts = AV_NOPTS_VALUE, pts = AV_NOPTS_VALUE;
988
989 if (ts->reemit_pat_pmt) {
990 av_log(s, AV_LOG_WARNING, "resend_headers option is deprecated, use -mpegts_flags resend_headers\n");
991 ts->reemit_pat_pmt = 0;
992 ts->flags |= MPEGTS_FLAG_REEMIT_PAT_PMT;
993 }
994
995 if (ts->flags & MPEGTS_FLAG_REEMIT_PAT_PMT) {
996 ts->pat_packet_count = ts->pat_packet_period - 1;
997 ts->sdt_packet_count = ts->sdt_packet_period - 1;
998 ts->flags &= ~MPEGTS_FLAG_REEMIT_PAT_PMT;
999 }
1000
1001 if (pkt->pts != AV_NOPTS_VALUE)
1002 pts = pkt->pts + delay;
1003 if (pkt->dts != AV_NOPTS_VALUE)
1004 dts = pkt->dts + delay;
1005
1006 if (ts_st->first_pts_check && pts == AV_NOPTS_VALUE) {
1007 av_log(s, AV_LOG_ERROR, "first pts value must set\n");
1008 return AVERROR(EINVAL);
1009 }
1010 ts_st->first_pts_check = 0;
1011
1012 if (st->codec->codec_id == AV_CODEC_ID_H264) {
1013 const uint8_t *p = buf, *buf_end = p+size;
1014 uint32_t state = -1;
1015
1016 if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001) {
1017 av_log(s, AV_LOG_ERROR, "H.264 bitstream malformed, "
1018 "no startcode found, use -bsf h264_mp4toannexb\n");
1019 return AVERROR(EINVAL);
1020 }
1021
1022 do {
1023 p = avpriv_find_start_code(p, buf_end, &state);
1024 av_dlog(s, "nal %d\n", state & 0x1f);
1025 } while (p < buf_end && (state & 0x1f) != 9 &&
1026 (state & 0x1f) != 5 && (state & 0x1f) != 1);
1027
1028 if ((state & 0x1f) != 9) { // AUD NAL
1029 data = av_malloc(pkt->size+6);
1030 if (!data)
1031 return AVERROR(ENOMEM);
1032 memcpy(data+6, pkt->data, pkt->size);
1033 AV_WB32(data, 0x00000001);
1034 data[4] = 0x09;
1035 data[5] = 0xf0; // any slice type (0xe) + rbsp stop one bit
1036 buf = data;
1037 size = pkt->size+6;
1038 }
1039 } else if (st->codec->codec_id == AV_CODEC_ID_AAC) {
1040 if (pkt->size < 2) {
1041 av_log(s, AV_LOG_ERROR, "AAC packet too short\n");
1042 return AVERROR(EINVAL);
1043 }
1044 if ((AV_RB16(pkt->data) & 0xfff0) != 0xfff0) {
1045 int ret;
1046 AVPacket pkt2;
1047
1048 if (!ts_st->amux) {
1049 av_log(s, AV_LOG_ERROR, "AAC bitstream not in ADTS format "
1050 "and extradata missing\n");
1051 return AVERROR(EINVAL);
1052 }
1053
1054 av_init_packet(&pkt2);
1055 pkt2.data = pkt->data;
1056 pkt2.size = pkt->size;
1057 ret = avio_open_dyn_buf(&ts_st->amux->pb);
1058 if (ret < 0)
1059 return AVERROR(ENOMEM);
1060
1061 ret = av_write_frame(ts_st->amux, &pkt2);
1062 if (ret < 0) {
1063 avio_close_dyn_buf(ts_st->amux->pb, &data);
1064 ts_st->amux->pb = NULL;
1065 av_free(data);
1066 return ret;
1067 }
1068 size = avio_close_dyn_buf(ts_st->amux->pb, &data);
1069 ts_st->amux->pb = NULL;
1070 buf = data;
1071 }
1072 }
1073
1074 if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO) {
1075 // for video and subtitle, write a single pes packet
1076 mpegts_write_pes(s, st, buf, size, pts, dts, pkt->flags & AV_PKT_FLAG_KEY);
1077 av_free(data);
1078 return 0;
1079 }
1080
1081 if (ts_st->payload_size + size > ts->pes_payload_size) {
1082 if (ts_st->payload_size) {
1083 mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_size,
1084 ts_st->payload_pts, ts_st->payload_dts,
1085 ts_st->payload_flags & AV_PKT_FLAG_KEY);
1086 ts_st->payload_size = 0;
1087 }
1088 if (size > ts->pes_payload_size) {
1089 mpegts_write_pes(s, st, buf, size, pts, dts,
1090 pkt->flags & AV_PKT_FLAG_KEY);
1091 av_free(data);
1092 return 0;
1093 }
1094 }
1095
1096 if (!ts_st->payload_size) {
1097 ts_st->payload_pts = pts;
1098 ts_st->payload_dts = dts;
1099 ts_st->payload_flags = pkt->flags;
1100 }
1101
1102 memcpy(ts_st->payload + ts_st->payload_size, buf, size);
1103 ts_st->payload_size += size;
1104
1105 av_free(data);
1106
1107 return 0;
1108 }
1109
1110 static void mpegts_write_flush(AVFormatContext *s)
1111 {
1112 int i;
1113
1114 /* flush current packets */
1115 for(i = 0; i < s->nb_streams; i++) {
1116 AVStream *st = s->streams[i];
1117 MpegTSWriteStream *ts_st = st->priv_data;
1118 if (ts_st->payload_size > 0) {
1119 mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_size,
1120 ts_st->payload_pts, ts_st->payload_dts,
1121 ts_st->payload_flags & AV_PKT_FLAG_KEY);
1122 ts_st->payload_size = 0;
1123 }
1124 }
1125 avio_flush(s->pb);
1126 }
1127
1128 static int mpegts_write_packet(AVFormatContext *s, AVPacket *pkt)
1129 {
1130 if (!pkt) {
1131 mpegts_write_flush(s);
1132 return 1;
1133 } else {
1134 return mpegts_write_packet_internal(s, pkt);
1135 }
1136 }
1137
1138 static int mpegts_write_end(AVFormatContext *s)
1139 {
1140 MpegTSWrite *ts = s->priv_data;
1141 MpegTSService *service;
1142 int i;
1143
1144 mpegts_write_flush(s);
1145
1146 for(i = 0; i < s->nb_streams; i++) {
1147 AVStream *st = s->streams[i];
1148 MpegTSWriteStream *ts_st = st->priv_data;
1149 av_freep(&ts_st->payload);
1150 if (ts_st->amux) {
1151 avformat_free_context(ts_st->amux);
1152 ts_st->amux = NULL;
1153 }
1154 }
1155
1156 for(i = 0; i < ts->nb_services; i++) {
1157 service = ts->services[i];
1158 av_freep(&service->provider_name);
1159 av_freep(&service->name);
1160 av_free(service);
1161 }
1162 av_free(ts->services);
1163
1164 return 0;
1165 }
1166
1167 AVOutputFormat ff_mpegts_muxer = {
1168 .name = "mpegts",
1169 .long_name = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
1170 .mime_type = "video/x-mpegts",
1171 .extensions = "ts,m2t",
1172 .priv_data_size = sizeof(MpegTSWrite),
1173 .audio_codec = AV_CODEC_ID_MP2,
1174 .video_codec = AV_CODEC_ID_MPEG2VIDEO,
1175 .write_header = mpegts_write_header,
1176 .write_packet = mpegts_write_packet,
1177 .write_trailer = mpegts_write_end,
1178 .flags = AVFMT_ALLOW_FLUSH,
1179 .priv_class = &mpegts_muxer_class,
1180 };