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