mpegts: properly output large audio packets
[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"
0ebcdf5c 25#include "libavutil/mathematics.h"
445996aa 26#include "libavutil/opt.h"
de34dc39 27#include "libavcodec/mpegvideo.h"
5dbafeb7 28#include "avformat.h"
9a2cb05f 29#include "internal.h"
5dbafeb7 30#include "mpegts.h"
8fdd542c 31#include "adts.h"
5dbafeb7 32
66be80d6
TH
33#define PCR_TIME_BASE 27000000
34
5dbafeb7
FB
35/* write DVB SI sections */
36
5dbafeb7
FB
37/*********************************************/
38/* mpegts section writer */
39
40typedef 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
b5931348
BC
47typedef 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;
1aae3489 54 int pcr_packet_period;
b5931348
BC
55} MpegTSService;
56
57typedef struct MpegTSWrite {
50fefa10 58 const AVClass *av_class;
b5931348
BC
59 MpegTSSection pat; /* MPEG2 pat table */
60 MpegTSSection sdt; /* MPEG2 sdt table context */
61 MpegTSService **services;
62 int sdt_packet_count;
1aae3489 63 int sdt_packet_period;
b5931348 64 int pat_packet_count;
1aae3489 65 int pat_packet_period;
b5931348
BC
66 int nb_services;
67 int onid;
68 int tsid;
66be80d6 69 int64_t first_pcr;
7082ea56 70 int mux_rate; ///< set to 1 when VBR
445996aa
GC
71
72 int transport_stream_id;
73 int original_network_id;
74 int service_id;
75
76 int pmt_start_pid;
77 int start_pid;
b5931348
BC
78} MpegTSWrite;
79
445996aa
GC
80static const AVOption options[] = {
81 { "mpegts_transport_stream_id", "Set transport_stream_id field.",
145f741e 82 offsetof(MpegTSWrite, transport_stream_id), AV_OPT_TYPE_INT, {.dbl = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
445996aa 83 { "mpegts_original_network_id", "Set original_network_id field.",
145f741e 84 offsetof(MpegTSWrite, original_network_id), AV_OPT_TYPE_INT, {.dbl = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
445996aa 85 { "mpegts_service_id", "Set service_id field.",
145f741e 86 offsetof(MpegTSWrite, service_id), AV_OPT_TYPE_INT, {.dbl = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
445996aa 87 { "mpegts_pmt_start_pid", "Set the first pid of the PMT.",
145f741e 88 offsetof(MpegTSWrite, pmt_start_pid), AV_OPT_TYPE_INT, {.dbl = 0x1000 }, 0x1000, 0x1f00, AV_OPT_FLAG_ENCODING_PARAM},
445996aa 89 { "mpegts_start_pid", "Set the first pid.",
145f741e 90 offsetof(MpegTSWrite, start_pid), AV_OPT_TYPE_INT, {.dbl = 0x0100 }, 0x0100, 0x0f00, AV_OPT_FLAG_ENCODING_PARAM},
5a9ee315 91 { "muxrate", NULL, offsetof(MpegTSWrite, mux_rate), AV_OPT_TYPE_INT, {1}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
445996aa
GC
92 { NULL },
93};
94
95static const AVClass mpegts_muxer_class = {
f0029cbc
AK
96 .class_name = "MPEGTS muxer",
97 .item_name = av_default_item_name,
98 .option = options,
99 .version = LIBAVUTIL_VERSION_INT,
445996aa
GC
100};
101
5dbafeb7 102/* NOTE: 4 bytes must be left at the end for the crc32 */
7b49ce2e 103static void mpegts_write_section(MpegTSSection *s, uint8_t *buf, int len)
5dbafeb7
FB
104{
105 unsigned int crc;
106 unsigned char packet[TS_PACKET_SIZE];
107 const unsigned char *buf_ptr;
108 unsigned char *q;
109 int first, b, len1, left;
110
8fc0162a 111 crc = av_bswap32(av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1, buf, len - 4));
5dbafeb7
FB
112 buf[len - 4] = (crc >> 24) & 0xff;
113 buf[len - 3] = (crc >> 16) & 0xff;
114 buf[len - 2] = (crc >> 8) & 0xff;
115 buf[len - 1] = (crc) & 0xff;
115329f1 116
5dbafeb7
FB
117 /* send each packet */
118 buf_ptr = buf;
119 while (len > 0) {
120 first = (buf == buf_ptr);
121 q = packet;
122 *q++ = 0x47;
123 b = (s->pid >> 8);
124 if (first)
125 b |= 0x40;
126 *q++ = b;
127 *q++ = s->pid;
3654a16d 128 s->cc = (s->cc + 1) & 0xf;
8d819221 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;
145 len -= len1;
146 }
147}
148
149static inline void put16(uint8_t **q_ptr, int val)
150{
151 uint8_t *q;
152 q = *q_ptr;
153 *q++ = val >> 8;
154 *q++ = val;
155 *q_ptr = q;
156}
157
7b49ce2e 158static int mpegts_write_section1(MpegTSSection *s, int tid, int id,
5dbafeb7
FB
159 int version, int sec_num, int last_sec_num,
160 uint8_t *buf, int len)
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)
170 return -1;
171
172 q = section;
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/* a PES packet header is generated every DEFAULT_PES_HEADER_FREQ packets */
192#define DEFAULT_PES_HEADER_FREQ 16
69ef9450 193#define DEFAULT_PES_PAYLOAD_SIZE ((DEFAULT_PES_HEADER_FREQ - 1) * 184 + 170)
5dbafeb7
FB
194
195/* we retransmit the SI info at this rate */
196#define SDT_RETRANS_TIME 500
197#define PAT_RETRANS_TIME 100
8b475508 198#define PCR_RETRANS_TIME 20
5dbafeb7
FB
199
200typedef struct MpegTSWriteStream {
8b475508 201 struct MpegTSService *service;
5dbafeb7
FB
202 int pid; /* stream associated pid */
203 int cc;
1c668624 204 int payload_size;
b69017af 205 int first_pts_check; ///< first pts check needed
69ef9450 206 int64_t payload_pts;
700b9711 207 int64_t payload_dts;
575c38d7 208 int payload_flags;
69ef9450 209 uint8_t payload[DEFAULT_PES_PAYLOAD_SIZE];
8fdd542c 210 ADTSContext *adts;
5dbafeb7
FB
211} MpegTSWriteStream;
212
5dbafeb7
FB
213static void mpegts_write_pat(AVFormatContext *s)
214{
215 MpegTSWrite *ts = s->priv_data;
216 MpegTSService *service;
217 uint8_t data[1012], *q;
218 int i;
115329f1 219
5dbafeb7
FB
220 q = data;
221 for(i = 0; i < ts->nb_services; i++) {
222 service = ts->services[i];
223 put16(&q, service->sid);
224 put16(&q, 0xe000 | service->pmt.pid);
225 }
226 mpegts_write_section1(&ts->pat, PAT_TID, ts->tsid, 0, 0, 0,
227 data, q - data);
228}
229
230static void mpegts_write_pmt(AVFormatContext *s, MpegTSService *service)
231{
232 // MpegTSWrite *ts = s->priv_data;
233 uint8_t data[1012], *q, *desc_length_ptr, *program_info_length_ptr;
234 int val, stream_type, i;
235
236 q = data;
237 put16(&q, 0xe000 | service->pcr_pid);
238
239 program_info_length_ptr = q;
240 q += 2; /* patched after */
241
242 /* put program info here */
243
244 val = 0xf000 | (q - program_info_length_ptr - 2);
245 program_info_length_ptr[0] = val >> 8;
246 program_info_length_ptr[1] = val;
115329f1 247
5dbafeb7
FB
248 for(i = 0; i < s->nb_streams; i++) {
249 AVStream *st = s->streams[i];
250 MpegTSWriteStream *ts_st = st->priv_data;
d2d67e42 251 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
01f4895c 252 switch(st->codec->codec_id) {
278de475
MR
253 case CODEC_ID_MPEG1VIDEO:
254 case CODEC_ID_MPEG2VIDEO:
255 stream_type = STREAM_TYPE_VIDEO_MPEG2;
5dbafeb7 256 break;
278de475
MR
257 case CODEC_ID_MPEG4:
258 stream_type = STREAM_TYPE_VIDEO_MPEG4;
259 break;
260 case CODEC_ID_H264:
261 stream_type = STREAM_TYPE_VIDEO_H264;
262 break;
f4bba201
AS
263 case CODEC_ID_DIRAC:
264 stream_type = STREAM_TYPE_VIDEO_DIRAC;
265 break;
278de475
MR
266 case CODEC_ID_MP2:
267 case CODEC_ID_MP3:
ce34182d 268 stream_type = STREAM_TYPE_AUDIO_MPEG1;
5dbafeb7 269 break;
278de475
MR
270 case CODEC_ID_AAC:
271 stream_type = STREAM_TYPE_AUDIO_AAC;
272 break;
4d54df8e
PR
273 case CODEC_ID_AAC_LATM:
274 stream_type = STREAM_TYPE_AUDIO_AAC_LATM;
275 break;
278de475 276 case CODEC_ID_AC3:
a1f42882 277 stream_type = STREAM_TYPE_AUDIO_AC3;
278de475 278 break;
5dbafeb7
FB
279 default:
280 stream_type = STREAM_TYPE_PRIVATE_DATA;
281 break;
282 }
283 *q++ = stream_type;
284 put16(&q, 0xe000 | ts_st->pid);
285 desc_length_ptr = q;
286 q += 2; /* patched after */
287
288 /* write optional descriptors here */
01f4895c 289 switch(st->codec->codec_type) {
72415b2a 290 case AVMEDIA_TYPE_AUDIO:
435cebd0
AH
291 if (lang) {
292 char *p;
293 char *next = lang->value;
294 uint8_t *len_ptr;
295
8b475508 296 *q++ = 0x0a; /* ISO 639 language descriptor */
435cebd0
AH
297 len_ptr = q++;
298 *len_ptr = 0;
299
300 for (p = lang->value; next && *len_ptr < 255 / 4 * 4; p = next + 1) {
301 next = strchr(p, ',');
302 if (strlen(p) != 3 && (!next || next != p + 3))
303 continue; /* not a 3-letter code */
304
305 *q++ = *p++;
306 *q++ = *p++;
307 *q++ = *p++;
308
3f2d3a19
AH
309 if (st->disposition & AV_DISPOSITION_CLEAN_EFFECTS)
310 *q++ = 0x01;
311 else if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
312 *q++ = 0x02;
313 else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
314 *q++ = 0x03;
315 else
2dd1ee4b 316 *q++ = 0; /* undefined type */
435cebd0
AH
317
318 *len_ptr += 4;
319 }
320
321 if (*len_ptr == 0)
322 q -= 2; /* no language codes were written */
8b475508
FB
323 }
324 break;
72415b2a 325 case AVMEDIA_TYPE_SUBTITLE:
8b475508
FB
326 {
327 const char *language;
4b358c3e 328 language = lang && strlen(lang->value)==3 ? lang->value : "eng";
8b475508
FB
329 *q++ = 0x59;
330 *q++ = 8;
331 *q++ = language[0];
332 *q++ = language[1];
333 *q++ = language[2];
334 *q++ = 0x10; /* normal subtitles (0x20 = if hearing pb) */
d1ac0351
TH
335 if(st->codec->extradata_size == 4) {
336 memcpy(q, st->codec->extradata, 4);
337 q += 4;
338 } else {
16209390
TH
339 put16(&q, 1); /* page id */
340 put16(&q, 1); /* ancillary page id */
d1ac0351 341 }
8b475508
FB
342 }
343 break;
72415b2a 344 case AVMEDIA_TYPE_VIDEO:
f4bba201
AS
345 if (stream_type == STREAM_TYPE_VIDEO_DIRAC) {
346 *q++ = 0x05; /*MPEG-2 registration descriptor*/
347 *q++ = 4;
348 *q++ = 'd';
349 *q++ = 'r';
350 *q++ = 'a';
351 *q++ = 'c';
352 }
353 break;
8b475508 354 }
5dbafeb7
FB
355
356 val = 0xf000 | (q - desc_length_ptr - 2);
357 desc_length_ptr[0] = val >> 8;
358 desc_length_ptr[1] = val;
359 }
360 mpegts_write_section1(&service->pmt, PMT_TID, service->sid, 0, 0, 0,
361 data, q - data);
115329f1 362}
5dbafeb7
FB
363
364/* NOTE: str == NULL is accepted for an empty string */
365static void putstr8(uint8_t **q_ptr, const char *str)
366{
367 uint8_t *q;
368 int len;
369
370 q = *q_ptr;
371 if (!str)
372 len = 0;
373 else
374 len = strlen(str);
375 *q++ = len;
376 memcpy(q, str, len);
377 q += len;
378 *q_ptr = q;
379}
380
381static void mpegts_write_sdt(AVFormatContext *s)
382{
383 MpegTSWrite *ts = s->priv_data;
384 MpegTSService *service;
385 uint8_t data[1012], *q, *desc_list_len_ptr, *desc_len_ptr;
386 int i, running_status, free_ca_mode, val;
115329f1 387
5dbafeb7
FB
388 q = data;
389 put16(&q, ts->onid);
390 *q++ = 0xff;
391 for(i = 0; i < ts->nb_services; i++) {
392 service = ts->services[i];
393 put16(&q, service->sid);
394 *q++ = 0xfc | 0x00; /* currently no EIT info */
395 desc_list_len_ptr = q;
396 q += 2;
397 running_status = 4; /* running */
398 free_ca_mode = 0;
399
400 /* write only one descriptor for the service name and provider */
401 *q++ = 0x48;
402 desc_len_ptr = q;
403 q++;
404 *q++ = 0x01; /* digital television service */
405 putstr8(&q, service->provider_name);
406 putstr8(&q, service->name);
407 desc_len_ptr[0] = q - desc_len_ptr - 1;
408
409 /* fill descriptor length */
115329f1 410 val = (running_status << 13) | (free_ca_mode << 12) |
5dbafeb7
FB
411 (q - desc_list_len_ptr - 2);
412 desc_list_len_ptr[0] = val >> 8;
413 desc_list_len_ptr[1] = val;
414 }
415 mpegts_write_section1(&ts->sdt, SDT_TID, ts->tsid, 0, 0, 0,
416 data, q - data);
417}
418
115329f1
DB
419static MpegTSService *mpegts_add_service(MpegTSWrite *ts,
420 int sid,
421 const char *provider_name,
5dbafeb7
FB
422 const char *name)
423{
424 MpegTSService *service;
425
426 service = av_mallocz(sizeof(MpegTSService));
427 if (!service)
428 return NULL;
f8fec050 429 service->pmt.pid = ts->pmt_start_pid + ts->nb_services;
5dbafeb7
FB
430 service->sid = sid;
431 service->provider_name = av_strdup(provider_name);
432 service->name = av_strdup(name);
433 service->pcr_pid = 0x1fff;
434 dynarray_add(&ts->services, &ts->nb_services, service);
435 return service;
436}
437
438static void section_write_packet(MpegTSSection *s, const uint8_t *packet)
439{
440 AVFormatContext *ctx = s->opaque;
77eb5504 441 avio_write(ctx->pb, packet, TS_PACKET_SIZE);
5dbafeb7
FB
442}
443
444static int mpegts_write_header(AVFormatContext *s)
445{
446 MpegTSWrite *ts = s->priv_data;
447 MpegTSWriteStream *ts_st;
448 MpegTSService *service;
7082ea56 449 AVStream *st, *pcr_st = NULL;
d2d67e42 450 AVDictionaryEntry *title, *provider;
5fd48573 451 int i, j;
8b475508 452 const char *service_name;
69688e71 453 const char *provider_name;
5fd48573 454 int *pids;
115329f1 455
445996aa
GC
456 ts->tsid = ts->transport_stream_id;
457 ts->onid = ts->original_network_id;
5dbafeb7 458 /* allocate a single DVB service */
d2d67e42 459 title = av_dict_get(s->metadata, "service_name", NULL, 0);
69688e71 460 if (!title)
d2d67e42 461 title = av_dict_get(s->metadata, "title", NULL, 0);
4b358c3e 462 service_name = title ? title->value : DEFAULT_SERVICE_NAME;
d2d67e42 463 provider = av_dict_get(s->metadata, "service_provider", NULL, 0);
69688e71 464 provider_name = provider ? provider->value : DEFAULT_PROVIDER_NAME;
445996aa 465 service = mpegts_add_service(ts, ts->service_id, provider_name, service_name);
5dbafeb7
FB
466 service->pmt.write_packet = section_write_packet;
467 service->pmt.opaque = s;
677a1144 468 service->pmt.cc = 15;
5dbafeb7
FB
469
470 ts->pat.pid = PAT_PID;
8d819221 471 ts->pat.cc = 15; // Initialize at 15 so that it wraps and be equal to 0 for the first packet we write
5dbafeb7
FB
472 ts->pat.write_packet = section_write_packet;
473 ts->pat.opaque = s;
474
475 ts->sdt.pid = SDT_PID;
8d819221 476 ts->sdt.cc = 15;
5dbafeb7
FB
477 ts->sdt.write_packet = section_write_packet;
478 ts->sdt.opaque = s;
479
ea59f489 480 pids = av_malloc(s->nb_streams * sizeof(*pids));
5fd48573
MS
481 if (!pids)
482 return AVERROR(ENOMEM);
483
5dbafeb7 484 /* assign pids to each stream */
5dbafeb7
FB
485 for(i = 0;i < s->nb_streams; i++) {
486 st = s->streams[i];
c3f9ebf7 487 avpriv_set_pts_info(st, 33, 1, 90000);
5dbafeb7
FB
488 ts_st = av_mallocz(sizeof(MpegTSWriteStream));
489 if (!ts_st)
490 goto fail;
491 st->priv_data = ts_st;
8b475508 492 ts_st->service = service;
5fd48573
MS
493 /* MPEG pid values < 16 are reserved. Applications which set st->id in
494 * this range are assigned a calculated pid. */
495 if (st->id < 16) {
445996aa 496 ts_st->pid = ts->start_pid + i;
5fd48573
MS
497 } else if (st->id < 0x1FFF) {
498 ts_st->pid = st->id;
499 } else {
500 av_log(s, AV_LOG_ERROR, "Invalid stream id %d, must be less than 8191\n", st->id);
501 goto fail;
502 }
503 if (ts_st->pid == service->pmt.pid) {
504 av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
505 goto fail;
506 }
507 for (j = 0; j < i; j++)
508 if (pids[j] == ts_st->pid) {
509 av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
510 goto fail;
511 }
512 pids[i] = ts_st->pid;
69ef9450 513 ts_st->payload_pts = AV_NOPTS_VALUE;
700b9711 514 ts_st->payload_dts = AV_NOPTS_VALUE;
b69017af 515 ts_st->first_pts_check = 1;
d73a458f 516 ts_st->cc = 15;
8b475508 517 /* update PCR pid by using the first video stream */
72415b2a 518 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
7082ea56 519 service->pcr_pid == 0x1fff) {
5dbafeb7 520 service->pcr_pid = ts_st->pid;
7082ea56 521 pcr_st = st;
9deba199 522 }
8fdd542c
BC
523 if (st->codec->codec_id == CODEC_ID_AAC &&
524 st->codec->extradata_size > 0) {
525 ts_st->adts = av_mallocz(sizeof(*ts_st->adts));
526 if (!ts_st->adts)
2874c81c 527 return AVERROR(ENOMEM);
8fdd542c
BC
528 if (ff_adts_decode_extradata(s, ts_st->adts, st->codec->extradata,
529 st->codec->extradata_size) < 0)
530 return -1;
531 }
5dbafeb7 532 }
115329f1 533
5fd48573
MS
534 av_free(pids);
535
8b475508
FB
536 /* if no video stream, use the first stream as PCR */
537 if (service->pcr_pid == 0x1fff && s->nb_streams > 0) {
7082ea56
BC
538 pcr_st = s->streams[0];
539 ts_st = pcr_st->priv_data;
8b475508
FB
540 service->pcr_pid = ts_st->pid;
541 }
542
5a9ee315
AK
543#if FF_API_MUXRATE
544 if (s->mux_rate)
545 ts->mux_rate = s->mux_rate;
546#endif
3d0a94f6 547
7082ea56 548 if (ts->mux_rate > 1) {
e3433702
BC
549 service->pcr_packet_period = (ts->mux_rate * PCR_RETRANS_TIME) /
550 (TS_PACKET_SIZE * 8 * 1000);
551 ts->sdt_packet_period = (ts->mux_rate * SDT_RETRANS_TIME) /
552 (TS_PACKET_SIZE * 8 * 1000);
553 ts->pat_packet_period = (ts->mux_rate * PAT_RETRANS_TIME) /
554 (TS_PACKET_SIZE * 8 * 1000);
555
66be80d6 556 ts->first_pcr = av_rescale(s->max_delay, PCR_TIME_BASE, AV_TIME_BASE);
7082ea56
BC
557 } else {
558 /* Arbitrary values, PAT/PMT could be written on key frames */
559 ts->sdt_packet_period = 200;
560 ts->pat_packet_period = 40;
72415b2a 561 if (pcr_st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
7082ea56
BC
562 if (!pcr_st->codec->frame_size) {
563 av_log(s, AV_LOG_WARNING, "frame size not set\n");
564 service->pcr_packet_period =
565 pcr_st->codec->sample_rate/(10*512);
566 } else {
567 service->pcr_packet_period =
568 pcr_st->codec->sample_rate/(10*pcr_st->codec->frame_size);
569 }
570 } else {
571 // max delta PCR 0.1s
572 service->pcr_packet_period =
573 pcr_st->codec->time_base.den/(10*pcr_st->codec->time_base.num);
574 }
575 }
576
6b18a3f5
MS
577 // output a PCR as soon as possible
578 service->pcr_packet_count = service->pcr_packet_period;
7082ea56
BC
579 ts->pat_packet_count = ts->pat_packet_period-1;
580 ts->sdt_packet_count = ts->sdt_packet_period-1;
6b18a3f5 581
efdccce5
BC
582 if (ts->mux_rate == 1)
583 av_log(s, AV_LOG_INFO, "muxrate VBR, ");
584 else
585 av_log(s, AV_LOG_INFO, "muxrate %d, ", ts->mux_rate);
586 av_log(s, AV_LOG_INFO, "pcr every %d pkts, "
907d9166 587 "sdt every %d, pat/pmt every %d pkts\n",
efdccce5 588 service->pcr_packet_period,
7082ea56 589 ts->sdt_packet_period, ts->pat_packet_period);
907d9166 590
b7f2fdde 591 avio_flush(s->pb);
5dbafeb7
FB
592
593 return 0;
594
595 fail:
5fd48573 596 av_free(pids);
5dbafeb7
FB
597 for(i = 0;i < s->nb_streams; i++) {
598 st = s->streams[i];
ed87375d 599 av_freep(&st->priv_data);
5dbafeb7
FB
600 }
601 return -1;
602}
603
604/* send SDT, PAT and PMT tables regulary */
605static void retransmit_si_info(AVFormatContext *s)
606{
607 MpegTSWrite *ts = s->priv_data;
608 int i;
609
1aae3489 610 if (++ts->sdt_packet_count == ts->sdt_packet_period) {
5dbafeb7
FB
611 ts->sdt_packet_count = 0;
612 mpegts_write_sdt(s);
613 }
1aae3489 614 if (++ts->pat_packet_count == ts->pat_packet_period) {
5dbafeb7
FB
615 ts->pat_packet_count = 0;
616 mpegts_write_pat(s);
617 for(i = 0; i < ts->nb_services; i++) {
618 mpegts_write_pmt(s, ts->services[i]);
619 }
620 }
621}
622
ae628ec1 623static int64_t get_pcr(const MpegTSWrite *ts, AVIOContext *pb)
66be80d6 624{
a2704c97 625 return av_rescale(avio_tell(pb) + 11, 8 * PCR_TIME_BASE, ts->mux_rate) +
66be80d6
TH
626 ts->first_pcr;
627}
628
575c38d7 629static int write_pcr_bits(uint8_t *buf, int64_t pcr)
66be80d6
TH
630{
631 int64_t pcr_low = pcr % 300, pcr_high = pcr / 300;
632
633 *buf++ = pcr_high >> 25;
634 *buf++ = pcr_high >> 17;
635 *buf++ = pcr_high >> 9;
636 *buf++ = pcr_high >> 1;
535638b5 637 *buf++ = pcr_high << 7 | pcr_low >> 8 | 0x7e;
66be80d6
TH
638 *buf++ = pcr_low;
639
575c38d7 640 return 6;
66be80d6
TH
641}
642
4df3bbbc
MS
643/* Write a single null transport stream packet */
644static void mpegts_insert_null_packet(AVFormatContext *s)
645{
4df3bbbc
MS
646 uint8_t *q;
647 uint8_t buf[TS_PACKET_SIZE];
648
649 q = buf;
650 *q++ = 0x47;
651 *q++ = 0x00 | 0x1f;
652 *q++ = 0xff;
653 *q++ = 0x10;
654 memset(q, 0x0FF, TS_PACKET_SIZE - (q - buf));
77eb5504 655 avio_write(s->pb, buf, TS_PACKET_SIZE);
4df3bbbc
MS
656}
657
658/* Write a single transport stream packet with a PCR and no payload */
659static void mpegts_insert_pcr_only(AVFormatContext *s, AVStream *st)
660{
661 MpegTSWrite *ts = s->priv_data;
662 MpegTSWriteStream *ts_st = st->priv_data;
663 uint8_t *q;
4df3bbbc
MS
664 uint8_t buf[TS_PACKET_SIZE];
665
666 q = buf;
667 *q++ = 0x47;
668 *q++ = ts_st->pid >> 8;
669 *q++ = ts_st->pid;
670 *q++ = 0x20 | ts_st->cc; /* Adaptation only */
671 /* Continuity Count field does not increment (see 13818-1 section 2.4.3.3) */
672 *q++ = TS_PACKET_SIZE - 5; /* Adaptation Field Length */
673 *q++ = 0x10; /* Adaptation flags: PCR present */
674
675 /* PCR coded into 6 bytes */
575c38d7 676 q += write_pcr_bits(q, get_pcr(ts, s->pb));
4df3bbbc
MS
677
678 /* stuffing bytes */
679 memset(q, 0xFF, TS_PACKET_SIZE - (q - buf));
77eb5504 680 avio_write(s->pb, buf, TS_PACKET_SIZE);
4df3bbbc
MS
681}
682
700b9711
MR
683static void write_pts(uint8_t *q, int fourbits, int64_t pts)
684{
685 int val;
686
687 val = fourbits << 4 | (((pts >> 30) & 0x07) << 1) | 1;
688 *q++ = val;
689 val = (((pts >> 15) & 0x7fff) << 1) | 1;
690 *q++ = val >> 8;
691 *q++ = val;
692 val = (((pts) & 0x7fff) << 1) | 1;
693 *q++ = val >> 8;
694 *q++ = val;
695}
696
575c38d7
JM
697/* Set an adaptation field flag in an MPEG-TS packet*/
698static void set_af_flag(uint8_t *pkt, int flag)
699{
700 // expect at least one flag to set
701 assert(flag);
702
703 if ((pkt[3] & 0x20) == 0) {
704 // no AF yet, set adaptation field flag
705 pkt[3] |= 0x20;
706 // 1 byte length, no flags
707 pkt[4] = 1;
708 pkt[5] = 0;
709 }
710 pkt[5] |= flag;
711}
712
713/* Extend the adaptation field by size bytes */
714static void extend_af(uint8_t *pkt, int size)
715{
716 // expect already existing adaptation field
717 assert(pkt[3] & 0x20);
718 pkt[4] += size;
719}
720
721/* Get a pointer to MPEG-TS payload (right after TS packet header) */
722static uint8_t *get_ts_payload_start(uint8_t *pkt)
723{
724 if (pkt[3] & 0x20)
725 return pkt + 5 + pkt[4];
726 else
727 return pkt + 4;
728}
729
c054f372
MS
730/* Add a pes header to the front of payload, and segment into an integer number of
731 * ts packets. The final ts packet is padded using an over-sized adaptation header
732 * to exactly fill the last ts packet.
733 * NOTE: 'payload' contains a complete PES payload.
734 */
69ef9450
FB
735static void mpegts_write_pes(AVFormatContext *s, AVStream *st,
736 const uint8_t *payload, int payload_size,
575c38d7 737 int64_t pts, int64_t dts, int key)
5dbafeb7 738{
5dbafeb7 739 MpegTSWriteStream *ts_st = st->priv_data;
b5931348 740 MpegTSWrite *ts = s->priv_data;
69ef9450 741 uint8_t buf[TS_PACKET_SIZE];
5dbafeb7 742 uint8_t *q;
700b9711 743 int val, is_start, len, header_len, write_pcr, private_code, flags;
8b475508
FB
744 int afc_len, stuffing_len;
745 int64_t pcr = -1; /* avoid warning */
4df3bbbc 746 int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE);
5dbafeb7 747
69ef9450
FB
748 is_start = 1;
749 while (payload_size > 0) {
750 retransmit_si_info(s);
5dbafeb7 751
8b475508
FB
752 write_pcr = 0;
753 if (ts_st->pid == ts_st->service->pcr_pid) {
7082ea56
BC
754 if (ts->mux_rate > 1 || is_start) // VBR pcr period is based on frames
755 ts_st->service->pcr_packet_count++;
115329f1 756 if (ts_st->service->pcr_packet_count >=
1aae3489 757 ts_st->service->pcr_packet_period) {
8b475508
FB
758 ts_st->service->pcr_packet_count = 0;
759 write_pcr = 1;
8b475508
FB
760 }
761 }
762
7082ea56 763 if (ts->mux_rate > 1 && dts != AV_NOPTS_VALUE &&
66be80d6 764 (dts - get_pcr(ts, s->pb)/300) > delay) {
4df3bbbc
MS
765 /* pcr insert gets priority over null packet insert */
766 if (write_pcr)
767 mpegts_insert_pcr_only(s, st);
768 else
769 mpegts_insert_null_packet(s);
770 continue; /* recalculate write_pcr and possibly retransmit si_info */
771 }
772
69ef9450
FB
773 /* prepare packet header */
774 q = buf;
775 *q++ = 0x47;
776 val = (ts_st->pid >> 8);
777 if (is_start)
778 val |= 0x40;
779 *q++ = val;
780 *q++ = ts_st->pid;
69ef9450 781 ts_st->cc = (ts_st->cc + 1) & 0xf;
575c38d7
JM
782 *q++ = 0x10 | ts_st->cc; // payload indicator + CC
783 if (key && is_start && pts != AV_NOPTS_VALUE) {
784 // set Random Access for key frames
785 if (ts_st->pid == ts_st->service->pcr_pid)
786 write_pcr = 1;
787 set_af_flag(buf, 0x40);
788 q = get_ts_payload_start(buf);
789 }
8b475508 790 if (write_pcr) {
575c38d7
JM
791 set_af_flag(buf, 0x10);
792 q = get_ts_payload_start(buf);
b5931348 793 // add 11, pcr references the last byte of program clock reference base
7082ea56 794 if (ts->mux_rate > 1)
66be80d6 795 pcr = get_pcr(ts, s->pb);
7082ea56 796 else
66be80d6
TH
797 pcr = (dts - delay)*300;
798 if (dts != AV_NOPTS_VALUE && dts < pcr / 300)
811a0aa7 799 av_log(s, AV_LOG_WARNING, "dts < pcr, TS is invalid\n");
575c38d7
JM
800 extend_af(buf, write_pcr_bits(q, pcr));
801 q = get_ts_payload_start(buf);
8b475508 802 }
69ef9450 803 if (is_start) {
f4bba201 804 int pes_extension = 0;
69ef9450
FB
805 /* write PES header */
806 *q++ = 0x00;
807 *q++ = 0x00;
808 *q++ = 0x01;
8b475508 809 private_code = 0;
72415b2a 810 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
f4bba201
AS
811 if (st->codec->codec_id == CODEC_ID_DIRAC) {
812 *q++ = 0xfd;
813 } else
814 *q++ = 0xe0;
72415b2a 815 } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
01f4895c 816 (st->codec->codec_id == CODEC_ID_MP2 ||
6c065f0a
TS
817 st->codec->codec_id == CODEC_ID_MP3 ||
818 st->codec->codec_id == CODEC_ID_AAC)) {
115329f1 819 *q++ = 0xc0;
8b475508
FB
820 } else {
821 *q++ = 0xbd;
72415b2a 822 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
8b475508
FB
823 private_code = 0x20;
824 }
825 }
700b9711
MR
826 header_len = 0;
827 flags = 0;
828 if (pts != AV_NOPTS_VALUE) {
829 header_len += 5;
830 flags |= 0x80;
831 }
8f14cdee 832 if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
700b9711
MR
833 header_len += 5;
834 flags |= 0x40;
835 }
72415b2a 836 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
f4bba201
AS
837 st->codec->codec_id == CODEC_ID_DIRAC) {
838 /* set PES_extension_flag */
839 pes_extension = 1;
840 flags |= 0x01;
841
842 /*
843 * One byte for PES2 extension flag +
844 * one byte for extension length +
845 * one byte for extension id
846 */
847 header_len += 3;
848 }
700b9711 849 len = payload_size + header_len + 3;
8b475508 850 if (private_code != 0)
700b9711 851 len++;
e4358e70
BC
852 if (len > 0xffff)
853 len = 0;
69ef9450
FB
854 *q++ = len >> 8;
855 *q++ = len;
8b475508
FB
856 val = 0x80;
857 /* data alignment indicator is required for subtitle data */
72415b2a 858 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)
8b475508
FB
859 val |= 0x04;
860 *q++ = val;
700b9711
MR
861 *q++ = flags;
862 *q++ = header_len;
69ef9450 863 if (pts != AV_NOPTS_VALUE) {
700b9711
MR
864 write_pts(q, flags >> 6, pts);
865 q += 5;
866 }
8f14cdee 867 if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
700b9711
MR
868 write_pts(q, 1, dts);
869 q += 5;
5dbafeb7 870 }
f4bba201
AS
871 if (pes_extension && st->codec->codec_id == CODEC_ID_DIRAC) {
872 flags = 0x01; /* set PES_extension_flag_2 */
873 *q++ = flags;
874 *q++ = 0x80 | 0x01; /* marker bit + extension length */
875 /*
876 * Set the stream id extension flag bit to 0 and
877 * write the extended stream id
878 */
879 *q++ = 0x00 | 0x60;
880 }
8b475508
FB
881 if (private_code != 0)
882 *q++ = private_code;
69ef9450 883 is_start = 0;
5dbafeb7 884 }
8b475508
FB
885 /* header size */
886 header_len = q - buf;
887 /* data len */
888 len = TS_PACKET_SIZE - header_len;
69ef9450
FB
889 if (len > payload_size)
890 len = payload_size;
8b475508
FB
891 stuffing_len = TS_PACKET_SIZE - header_len - len;
892 if (stuffing_len > 0) {
893 /* add stuffing with AFC */
894 if (buf[3] & 0x20) {
895 /* stuffing already present: increase its size */
896 afc_len = buf[4] + 1;
897 memmove(buf + 4 + afc_len + stuffing_len,
115329f1 898 buf + 4 + afc_len,
8b475508
FB
899 header_len - (4 + afc_len));
900 buf[4] += stuffing_len;
901 memset(buf + 4 + afc_len, 0xff, stuffing_len);
902 } else {
903 /* add stuffing */
904 memmove(buf + 4 + stuffing_len, buf + 4, header_len - 4);
905 buf[3] |= 0x20;
906 buf[4] = stuffing_len - 1;
907 if (stuffing_len >= 2) {
908 buf[5] = 0x00;
909 memset(buf + 6, 0xff, stuffing_len - 2);
910 }
911 }
912 }
913 memcpy(buf + TS_PACKET_SIZE - len, payload, len);
69ef9450
FB
914 payload += len;
915 payload_size -= len;
77eb5504 916 avio_write(s->pb, buf, TS_PACKET_SIZE);
5dbafeb7 917 }
b7f2fdde 918 avio_flush(s->pb);
69ef9450
FB
919}
920
e928649b 921static int mpegts_write_packet(AVFormatContext *s, AVPacket *pkt)
69ef9450 922{
e928649b 923 AVStream *st = s->streams[pkt->stream_index];
01d6bd52 924 int size = pkt->size;
e928649b 925 uint8_t *buf= pkt->data;
a57fb91c 926 uint8_t *data= NULL;
69ef9450 927 MpegTSWriteStream *ts_st = st->priv_data;
7082ea56 928 const uint64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE)*2;
f3ba7c54
BC
929 int64_t dts = AV_NOPTS_VALUE, pts = AV_NOPTS_VALUE;
930
931 if (pkt->pts != AV_NOPTS_VALUE)
932 pts = pkt->pts + delay;
933 if (pkt->dts != AV_NOPTS_VALUE)
934 dts = pkt->dts + delay;
69ef9450 935
b69017af
BC
936 if (ts_st->first_pts_check && pts == AV_NOPTS_VALUE) {
937 av_log(s, AV_LOG_ERROR, "first pts value must set\n");
938 return -1;
939 }
940 ts_st->first_pts_check = 0;
941
e4358e70 942 if (st->codec->codec_id == CODEC_ID_H264) {
e17d77bb
BC
943 const uint8_t *p = buf, *buf_end = p+size;
944 uint32_t state = -1;
945
a57fb91c 946 if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001) {
da9cea77 947 av_log(s, AV_LOG_ERROR, "H.264 bitstream malformed, "
e17d77bb 948 "no startcode found, use -vbsf h264_mp4toannexb\n");
a57fb91c
BC
949 return -1;
950 }
e17d77bb
BC
951
952 do {
773375c3 953 p = avpriv_mpv_find_start_code(p, buf_end, &state);
e17d77bb
BC
954 //av_log(s, AV_LOG_INFO, "nal %d\n", state & 0x1f);
955 } while (p < buf_end && (state & 0x1f) != 9 &&
956 (state & 0x1f) != 5 && (state & 0x1f) != 1);
957
958 if ((state & 0x1f) != 9) { // AUD NAL
a57fb91c
BC
959 data = av_malloc(pkt->size+6);
960 if (!data)
961 return -1;
962 memcpy(data+6, pkt->data, pkt->size);
963 AV_WB32(data, 0x00000001);
964 data[4] = 0x09;
ef011e6d 965 data[5] = 0xf0; // any slice type (0xe) + rbsp stop one bit
a57fb91c
BC
966 buf = data;
967 size = pkt->size+6;
968 }
8fdd542c
BC
969 } else if (st->codec->codec_id == CODEC_ID_AAC) {
970 if (pkt->size < 2)
971 return -1;
972 if ((AV_RB16(pkt->data) & 0xfff0) != 0xfff0) {
973 ADTSContext *adts = ts_st->adts;
ac47e014 974 int new_size, err;
8fdd542c
BC
975 if (!adts) {
976 av_log(s, AV_LOG_ERROR, "aac bitstream not in adts format "
977 "and extradata missing\n");
978 return -1;
979 }
980 new_size = ADTS_HEADER_SIZE+adts->pce_size+pkt->size;
981 if ((unsigned)new_size >= INT_MAX)
982 return -1;
983 data = av_malloc(new_size);
984 if (!data)
2874c81c 985 return AVERROR(ENOMEM);
ac47e014
AC
986 err = ff_adts_write_frame_header(adts, data, pkt->size,
987 adts->pce_size);
988 if (err < 0) {
989 av_free(data);
990 return err;
991 }
8fdd542c
BC
992 if (adts->pce_size) {
993 memcpy(data+ADTS_HEADER_SIZE, adts->pce_data, adts->pce_size);
994 adts->pce_size = 0;
995 }
996 memcpy(data+ADTS_HEADER_SIZE+adts->pce_size, pkt->data, pkt->size);
997 buf = data;
998 size = new_size;
999 }
de34dc39
BC
1000 }
1001
72415b2a 1002 if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO) {
e4358e70 1003 // for video and subtitle, write a single pes packet
575c38d7 1004 mpegts_write_pes(s, st, buf, size, pts, dts, pkt->flags & AV_PKT_FLAG_KEY);
24ac5052 1005 av_free(data);
e4358e70
BC
1006 return 0;
1007 }
1008
1c668624 1009 if (ts_st->payload_size + size > DEFAULT_PES_PAYLOAD_SIZE) {
6fa9843b
JM
1010 if (ts_st->payload_size) {
1011 mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_size,
1012 ts_st->payload_pts, ts_st->payload_dts,
1013 ts_st->payload_flags & AV_PKT_FLAG_KEY);
1014 ts_st->payload_size = 0;
1015 }
1016 if (size > DEFAULT_PES_PAYLOAD_SIZE) {
1017 mpegts_write_pes(s, st, buf, size, pts, dts,
1018 pkt->flags & AV_PKT_FLAG_KEY);
1019 av_free(data);
1020 return 0;
1021 }
84df78b4
BC
1022 }
1023
1c668624 1024 if (!ts_st->payload_size) {
01d6bd52
BC
1025 ts_st->payload_pts = pts;
1026 ts_st->payload_dts = dts;
575c38d7 1027 ts_st->payload_flags = pkt->flags;
69ef9450 1028 }
a57fb91c 1029
1c668624
LB
1030 memcpy(ts_st->payload + ts_st->payload_size, buf, size);
1031 ts_st->payload_size += size;
01d6bd52 1032
83c2bc7a
BC
1033 av_free(data);
1034
5dbafeb7
FB
1035 return 0;
1036}
1037
1038static int mpegts_write_end(AVFormatContext *s)
1039{
1040 MpegTSWrite *ts = s->priv_data;
1041 MpegTSWriteStream *ts_st;
1042 MpegTSService *service;
1043 AVStream *st;
1044 int i;
1045
1046 /* flush current packets */
1047 for(i = 0; i < s->nb_streams; i++) {
1048 st = s->streams[i];
1049 ts_st = st->priv_data;
1c668624
LB
1050 if (ts_st->payload_size > 0) {
1051 mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_size,
575c38d7
JM
1052 ts_st->payload_pts, ts_st->payload_dts,
1053 ts_st->payload_flags & AV_PKT_FLAG_KEY);
5dbafeb7 1054 }
83c2bc7a 1055 av_freep(&ts_st->adts);
5dbafeb7 1056 }
b7f2fdde 1057 avio_flush(s->pb);
115329f1 1058
5dbafeb7
FB
1059 for(i = 0; i < ts->nb_services; i++) {
1060 service = ts->services[i];
1061 av_freep(&service->provider_name);
1062 av_freep(&service->name);
1063 av_free(service);
1064 }
1065 av_free(ts->services);
1066
5dbafeb7
FB
1067 return 0;
1068}
1069
c6610a21 1070AVOutputFormat ff_mpegts_muxer = {
dfc2c4d9
AK
1071 .name = "mpegts",
1072 .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
1073 .mime_type = "video/x-mpegts",
1074 .extensions = "ts,m2t",
1075 .priv_data_size = sizeof(MpegTSWrite),
1076 .audio_codec = CODEC_ID_MP2,
1077 .video_codec = CODEC_ID_MPEG2VIDEO,
1078 .write_header = mpegts_write_header,
1079 .write_packet = mpegts_write_packet,
1080 .write_trailer = mpegts_write_end,
445996aa 1081 .priv_class = &mpegts_muxer_class,
5dbafeb7 1082};