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