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