2 * MPEG2 transport stream (aka DVB) muxer
3 * Copyright (c) 2003 Fabrice Bellard
5 * This file is part of FFmpeg.
7 * FFmpeg 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.
12 * FFmpeg 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.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 #include "libavutil/bswap.h"
23 #include "libavutil/crc.h"
24 #include "libavutil/dict.h"
25 #include "libavutil/intreadwrite.h"
26 #include "libavutil/mathematics.h"
27 #include "libavutil/opt.h"
28 #include "libavutil/avassert.h"
29 #include "libavcodec/internal.h"
34 #define PCR_TIME_BASE 27000000
36 /* write DVB SI sections */
38 /*********************************************/
39 /* mpegts section writer */
41 typedef struct MpegTSSection {
44 void (*write_packet)(struct MpegTSSection *s, const uint8_t *packet);
48 typedef struct MpegTSService {
49 MpegTSSection pmt; /* MPEG2 pmt table context */
50 int sid; /* service ID */
55 int pcr_packet_period;
58 typedef struct MpegTSWrite {
59 const AVClass *av_class;
60 MpegTSSection pat; /* MPEG2 pat table */
61 MpegTSSection sdt; /* MPEG2 sdt table context */
62 MpegTSService **services;
64 int sdt_packet_period;
66 int pat_packet_period;
71 int mux_rate; ///< set to 1 when VBR
74 int transport_stream_id;
75 int original_network_id;
82 int reemit_pat_pmt; // backward compatibility
84 #define MPEGTS_FLAG_REEMIT_PAT_PMT 0x01
85 #define MPEGTS_FLAG_AAC_LATM 0x02
91 /* a PES packet header is generated every DEFAULT_PES_HEADER_FREQ packets */
92 #define DEFAULT_PES_HEADER_FREQ 16
93 #define DEFAULT_PES_PAYLOAD_SIZE ((DEFAULT_PES_HEADER_FREQ - 1) * 184 + 170)
95 static const AVOption options[] = {
96 { "mpegts_transport_stream_id", "Set transport_stream_id field.",
97 offsetof(MpegTSWrite, transport_stream_id), AV_OPT_TYPE_INT, {.i64 = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
98 { "mpegts_original_network_id", "Set original_network_id field.",
99 offsetof(MpegTSWrite, original_network_id), AV_OPT_TYPE_INT, {.i64 = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
100 { "mpegts_service_id", "Set service_id field.",
101 offsetof(MpegTSWrite, service_id), AV_OPT_TYPE_INT, {.i64 = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
102 { "mpegts_pmt_start_pid", "Set the first pid of the PMT.",
103 offsetof(MpegTSWrite, pmt_start_pid), AV_OPT_TYPE_INT, {.i64 = 0x1000 }, 0x0010, 0x1f00, AV_OPT_FLAG_ENCODING_PARAM},
104 { "mpegts_start_pid", "Set the first pid.",
105 offsetof(MpegTSWrite, start_pid), AV_OPT_TYPE_INT, {.i64 = 0x0100 }, 0x0100, 0x0f00, AV_OPT_FLAG_ENCODING_PARAM},
106 {"mpegts_m2ts_mode", "Enable m2ts mode.",
107 offsetof(MpegTSWrite, m2ts_mode), AV_OPT_TYPE_INT, {.i64 = -1 },
108 -1,1, AV_OPT_FLAG_ENCODING_PARAM},
109 { "muxrate", NULL, offsetof(MpegTSWrite, mux_rate), AV_OPT_TYPE_INT, {.i64 = 1}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
110 { "pes_payload_size", "Minimum PES packet payload in bytes",
111 offsetof(MpegTSWrite, pes_payload_size), AV_OPT_TYPE_INT, {.i64 = DEFAULT_PES_PAYLOAD_SIZE}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
112 { "mpegts_flags", "MPEG-TS muxing flags", offsetof(MpegTSWrite, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, 0, INT_MAX,
113 AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags" },
114 { "resend_headers", "Reemit PAT/PMT before writing the next packet",
115 0, AV_OPT_TYPE_CONST, {.i64 = MPEGTS_FLAG_REEMIT_PAT_PMT}, 0, INT_MAX,
116 AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags"},
117 { "latm", "Use LATM packetization for AAC",
118 0, AV_OPT_TYPE_CONST, {.i64 = MPEGTS_FLAG_AAC_LATM}, 0, INT_MAX,
119 AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags"},
120 // backward compatibility
121 { "resend_headers", "Reemit PAT/PMT before writing the next packet",
122 offsetof(MpegTSWrite, reemit_pat_pmt), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
123 { "mpegts_copyts", "don't offset dts/pts",
124 offsetof(MpegTSWrite, copyts), AV_OPT_TYPE_INT, {.i64=-1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
125 { "tables_version", "set PAT, PMT and SDT version",
126 offsetof(MpegTSWrite, tables_version), AV_OPT_TYPE_INT, {.i64=0}, 0, 31, AV_OPT_FLAG_ENCODING_PARAM},
130 static const AVClass mpegts_muxer_class = {
131 .class_name = "MPEGTS muxer",
132 .item_name = av_default_item_name,
134 .version = LIBAVUTIL_VERSION_INT,
137 /* NOTE: 4 bytes must be left at the end for the crc32 */
138 static void mpegts_write_section(MpegTSSection *s, uint8_t *buf, int len)
141 unsigned char packet[TS_PACKET_SIZE];
142 const unsigned char *buf_ptr;
144 int first, b, len1, left;
146 crc = av_bswap32(av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1, buf, len - 4));
147 buf[len - 4] = (crc >> 24) & 0xff;
148 buf[len - 3] = (crc >> 16) & 0xff;
149 buf[len - 2] = (crc >> 8) & 0xff;
150 buf[len - 1] = (crc) & 0xff;
152 /* send each packet */
155 first = (buf == buf_ptr);
163 s->cc = (s->cc + 1) & 0xf;
166 *q++ = 0; /* 0 offset */
167 len1 = TS_PACKET_SIZE - (q - packet);
170 memcpy(q, buf_ptr, len1);
172 /* add known padding data */
173 left = TS_PACKET_SIZE - (q - packet);
175 memset(q, 0xff, left);
177 s->write_packet(s, packet);
184 static inline void put16(uint8_t **q_ptr, int val)
193 static int mpegts_write_section1(MpegTSSection *s, int tid, int id,
194 int version, int sec_num, int last_sec_num,
195 uint8_t *buf, int len)
197 uint8_t section[1024], *q;
198 unsigned int tot_len;
199 /* reserved_future_use field must be set to 1 for SDT */
200 unsigned int flags = tid == SDT_TID ? 0xf000 : 0xb000;
202 tot_len = 3 + 5 + len + 4;
203 /* check if not too big */
205 return AVERROR_INVALIDDATA;
209 put16(&q, flags | (len + 5 + 4)); /* 5 byte header + 4 byte CRC */
211 *q++ = 0xc1 | (version << 1); /* current_next_indicator = 1 */
216 mpegts_write_section(s, section, tot_len);
220 /*********************************************/
223 #define DEFAULT_PROVIDER_NAME "FFmpeg"
224 #define DEFAULT_SERVICE_NAME "Service01"
226 /* we retransmit the SI info at this rate */
227 #define SDT_RETRANS_TIME 500
228 #define PAT_RETRANS_TIME 100
229 #define PCR_RETRANS_TIME 20
231 typedef struct MpegTSWriteStream {
232 struct MpegTSService *service;
233 int pid; /* stream associated pid */
236 int first_pts_check; ///< first pts check needed
237 int prev_payload_key;
242 AVFormatContext *amux;
245 static void mpegts_write_pat(AVFormatContext *s)
247 MpegTSWrite *ts = s->priv_data;
248 MpegTSService *service;
249 uint8_t data[1012], *q;
253 for(i = 0; i < ts->nb_services; i++) {
254 service = ts->services[i];
255 put16(&q, service->sid);
256 put16(&q, 0xe000 | service->pmt.pid);
258 mpegts_write_section1(&ts->pat, PAT_TID, ts->tsid, ts->tables_version, 0, 0,
262 static void mpegts_write_pmt(AVFormatContext *s, MpegTSService *service)
264 MpegTSWrite *ts = s->priv_data;
265 uint8_t data[1012], *q, *desc_length_ptr, *program_info_length_ptr;
266 int val, stream_type, i;
269 put16(&q, 0xe000 | service->pcr_pid);
271 program_info_length_ptr = q;
272 q += 2; /* patched after */
274 /* put program info here */
276 val = 0xf000 | (q - program_info_length_ptr - 2);
277 program_info_length_ptr[0] = val >> 8;
278 program_info_length_ptr[1] = val;
280 for(i = 0; i < s->nb_streams; i++) {
281 AVStream *st = s->streams[i];
282 MpegTSWriteStream *ts_st = st->priv_data;
283 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
284 switch(st->codec->codec_id) {
285 case AV_CODEC_ID_MPEG1VIDEO:
286 case AV_CODEC_ID_MPEG2VIDEO:
287 stream_type = STREAM_TYPE_VIDEO_MPEG2;
289 case AV_CODEC_ID_MPEG4:
290 stream_type = STREAM_TYPE_VIDEO_MPEG4;
292 case AV_CODEC_ID_H264:
293 stream_type = STREAM_TYPE_VIDEO_H264;
295 case AV_CODEC_ID_CAVS:
296 stream_type = STREAM_TYPE_VIDEO_CAVS;
298 case AV_CODEC_ID_DIRAC:
299 stream_type = STREAM_TYPE_VIDEO_DIRAC;
301 case AV_CODEC_ID_MP2:
302 case AV_CODEC_ID_MP3:
303 stream_type = STREAM_TYPE_AUDIO_MPEG1;
305 case AV_CODEC_ID_AAC:
306 stream_type = (ts->flags & MPEGTS_FLAG_AAC_LATM) ? STREAM_TYPE_AUDIO_AAC_LATM : STREAM_TYPE_AUDIO_AAC;
308 case AV_CODEC_ID_AAC_LATM:
309 stream_type = STREAM_TYPE_AUDIO_AAC_LATM;
311 case AV_CODEC_ID_AC3:
312 stream_type = STREAM_TYPE_AUDIO_AC3;
315 stream_type = STREAM_TYPE_PRIVATE_DATA;
319 put16(&q, 0xe000 | ts_st->pid);
321 q += 2; /* patched after */
323 /* write optional descriptors here */
324 switch(st->codec->codec_type) {
325 case AVMEDIA_TYPE_AUDIO:
326 if(st->codec->codec_id==AV_CODEC_ID_EAC3){
327 *q++=0x7a; // EAC3 descriptor see A038 DVB SI
328 *q++=1; // 1 byte, all flags sets to 0
329 *q++=0; // omit all fields...
331 if(st->codec->codec_id==AV_CODEC_ID_S302M){
332 *q++ = 0x05; /* MPEG-2 registration descriptor*/
342 char *next = lang->value;
345 *q++ = 0x0a; /* ISO 639 language descriptor */
349 for (p = lang->value; next && *len_ptr < 255 / 4 * 4; p = next + 1) {
350 next = strchr(p, ',');
351 if (strlen(p) != 3 && (!next || next != p + 3))
352 continue; /* not a 3-letter code */
358 if (st->disposition & AV_DISPOSITION_CLEAN_EFFECTS)
360 else if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
362 else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
365 *q++ = 0; /* undefined type */
371 q -= 2; /* no language codes were written */
374 case AVMEDIA_TYPE_SUBTITLE:
376 const char *language;
377 language = lang && strlen(lang->value)==3 ? lang->value : "eng";
383 *q++ = 0x10; /* normal subtitles (0x20 = if hearing pb) */
384 if(st->codec->extradata_size == 4) {
385 memcpy(q, st->codec->extradata, 4);
388 put16(&q, 1); /* page id */
389 put16(&q, 1); /* ancillary page id */
393 case AVMEDIA_TYPE_VIDEO:
394 if (stream_type == STREAM_TYPE_VIDEO_DIRAC) {
395 *q++ = 0x05; /*MPEG-2 registration descriptor*/
403 case AVMEDIA_TYPE_DATA:
404 if (st->codec->codec_id == AV_CODEC_ID_SMPTE_KLV) {
405 *q++ = 0x05; /* MPEG-2 registration descriptor */
415 val = 0xf000 | (q - desc_length_ptr - 2);
416 desc_length_ptr[0] = val >> 8;
417 desc_length_ptr[1] = val;
419 mpegts_write_section1(&service->pmt, PMT_TID, service->sid, ts->tables_version, 0, 0,
423 /* NOTE: str == NULL is accepted for an empty string */
424 static void putstr8(uint8_t **q_ptr, const char *str)
440 static void mpegts_write_sdt(AVFormatContext *s)
442 MpegTSWrite *ts = s->priv_data;
443 MpegTSService *service;
444 uint8_t data[1012], *q, *desc_list_len_ptr, *desc_len_ptr;
445 int i, running_status, free_ca_mode, val;
450 for(i = 0; i < ts->nb_services; i++) {
451 service = ts->services[i];
452 put16(&q, service->sid);
453 *q++ = 0xfc | 0x00; /* currently no EIT info */
454 desc_list_len_ptr = q;
456 running_status = 4; /* running */
459 /* write only one descriptor for the service name and provider */
463 *q++ = 0x01; /* digital television service */
464 putstr8(&q, service->provider_name);
465 putstr8(&q, service->name);
466 desc_len_ptr[0] = q - desc_len_ptr - 1;
468 /* fill descriptor length */
469 val = (running_status << 13) | (free_ca_mode << 12) |
470 (q - desc_list_len_ptr - 2);
471 desc_list_len_ptr[0] = val >> 8;
472 desc_list_len_ptr[1] = val;
474 mpegts_write_section1(&ts->sdt, SDT_TID, ts->tsid, ts->tables_version, 0, 0,
478 static MpegTSService *mpegts_add_service(MpegTSWrite *ts,
480 const char *provider_name,
483 MpegTSService *service;
485 service = av_mallocz(sizeof(MpegTSService));
488 service->pmt.pid = ts->pmt_start_pid + ts->nb_services;
490 service->provider_name = av_strdup(provider_name);
491 service->name = av_strdup(name);
492 service->pcr_pid = 0x1fff;
493 dynarray_add(&ts->services, &ts->nb_services, service);
497 static int64_t get_pcr(const MpegTSWrite *ts, AVIOContext *pb)
499 return av_rescale(avio_tell(pb) + 11, 8 * PCR_TIME_BASE, ts->mux_rate) +
503 static void mpegts_prefix_m2ts_header(AVFormatContext *s)
505 MpegTSWrite *ts = s->priv_data;
507 int64_t pcr = get_pcr(s->priv_data, s->pb);
508 uint32_t tp_extra_header = pcr % 0x3fffffff;
509 tp_extra_header = AV_RB32(&tp_extra_header);
510 avio_write(s->pb, (unsigned char *) &tp_extra_header,
511 sizeof(tp_extra_header));
515 static void section_write_packet(MpegTSSection *s, const uint8_t *packet)
517 AVFormatContext *ctx = s->opaque;
518 mpegts_prefix_m2ts_header(ctx);
519 avio_write(ctx->pb, packet, TS_PACKET_SIZE);
522 static int mpegts_write_header(AVFormatContext *s)
524 MpegTSWrite *ts = s->priv_data;
525 MpegTSWriteStream *ts_st;
526 MpegTSService *service;
527 AVStream *st, *pcr_st = NULL;
528 AVDictionaryEntry *title, *provider;
530 const char *service_name;
531 const char *provider_name;
535 if (s->max_delay < 0) /* Not set by the caller */
538 // round up to a whole number of TS packets
539 ts->pes_payload_size = (ts->pes_payload_size + 14 + 183) / 184 * 184 - 14;
541 ts->tsid = ts->transport_stream_id;
542 ts->onid = ts->original_network_id;
543 /* allocate a single DVB service */
544 title = av_dict_get(s->metadata, "service_name", NULL, 0);
546 title = av_dict_get(s->metadata, "title", NULL, 0);
547 service_name = title ? title->value : DEFAULT_SERVICE_NAME;
548 provider = av_dict_get(s->metadata, "service_provider", NULL, 0);
549 provider_name = provider ? provider->value : DEFAULT_PROVIDER_NAME;
550 service = mpegts_add_service(ts, ts->service_id, provider_name, service_name);
551 service->pmt.write_packet = section_write_packet;
552 service->pmt.opaque = s;
553 service->pmt.cc = 15;
555 ts->pat.pid = PAT_PID;
556 ts->pat.cc = 15; // Initialize at 15 so that it wraps and be equal to 0 for the first packet we write
557 ts->pat.write_packet = section_write_packet;
560 ts->sdt.pid = SDT_PID;
562 ts->sdt.write_packet = section_write_packet;
565 pids = av_malloc(s->nb_streams * sizeof(*pids));
567 return AVERROR(ENOMEM);
569 /* assign pids to each stream */
570 for(i = 0;i < s->nb_streams; i++) {
572 avpriv_set_pts_info(st, 33, 1, 90000);
573 ts_st = av_mallocz(sizeof(MpegTSWriteStream));
575 ret = AVERROR(ENOMEM);
578 st->priv_data = ts_st;
579 ts_st->payload = av_mallocz(ts->pes_payload_size);
580 if (!ts_st->payload) {
581 ret = AVERROR(ENOMEM);
584 ts_st->service = service;
585 /* MPEG pid values < 16 are reserved. Applications which set st->id in
586 * this range are assigned a calculated pid. */
588 ts_st->pid = ts->start_pid + i;
589 } else if (st->id < 0x1FFF) {
592 av_log(s, AV_LOG_ERROR, "Invalid stream id %d, must be less than 8191\n", st->id);
593 ret = AVERROR(EINVAL);
596 if (ts_st->pid == service->pmt.pid) {
597 av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
598 ret = AVERROR(EINVAL);
601 for (j = 0; j < i; j++)
602 if (pids[j] == ts_st->pid) {
603 av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
604 ret = AVERROR(EINVAL);
607 pids[i] = ts_st->pid;
608 ts_st->payload_pts = AV_NOPTS_VALUE;
609 ts_st->payload_dts = AV_NOPTS_VALUE;
610 ts_st->first_pts_check = 1;
612 /* update PCR pid by using the first video stream */
613 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
614 service->pcr_pid == 0x1fff) {
615 service->pcr_pid = ts_st->pid;
618 if (st->codec->codec_id == AV_CODEC_ID_AAC &&
619 st->codec->extradata_size > 0)
622 ts_st->amux = avformat_alloc_context();
624 ret = AVERROR(ENOMEM);
627 ts_st->amux->oformat = av_guess_format((ts->flags & MPEGTS_FLAG_AAC_LATM) ? "latm" : "adts", NULL, NULL);
628 if (!ts_st->amux->oformat) {
629 ret = AVERROR(EINVAL);
632 ast = avformat_new_stream(ts_st->amux, NULL);
633 ret = avcodec_copy_context(ast->codec, st->codec);
636 ret = avformat_write_header(ts_st->amux, NULL);
644 /* if no video stream, use the first stream as PCR */
645 if (service->pcr_pid == 0x1fff && s->nb_streams > 0) {
646 pcr_st = s->streams[0];
647 ts_st = pcr_st->priv_data;
648 service->pcr_pid = ts_st->pid;
651 if (ts->mux_rate > 1) {
652 service->pcr_packet_period = (ts->mux_rate * PCR_RETRANS_TIME) /
653 (TS_PACKET_SIZE * 8 * 1000);
654 ts->sdt_packet_period = (ts->mux_rate * SDT_RETRANS_TIME) /
655 (TS_PACKET_SIZE * 8 * 1000);
656 ts->pat_packet_period = (ts->mux_rate * PAT_RETRANS_TIME) /
657 (TS_PACKET_SIZE * 8 * 1000);
660 ts->first_pcr = av_rescale(s->max_delay, PCR_TIME_BASE, AV_TIME_BASE);
662 /* Arbitrary values, PAT/PMT will also be written on video key frames */
663 ts->sdt_packet_period = 200;
664 ts->pat_packet_period = 40;
665 if (pcr_st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
666 if (!pcr_st->codec->frame_size) {
667 av_log(s, AV_LOG_WARNING, "frame size not set\n");
668 service->pcr_packet_period =
669 pcr_st->codec->sample_rate/(10*512);
671 service->pcr_packet_period =
672 pcr_st->codec->sample_rate/(10*pcr_st->codec->frame_size);
675 // max delta PCR 0.1s
676 service->pcr_packet_period =
677 pcr_st->codec->time_base.den/(10*pcr_st->codec->time_base.num);
679 if(!service->pcr_packet_period)
680 service->pcr_packet_period = 1;
683 // output a PCR as soon as possible
684 service->pcr_packet_count = service->pcr_packet_period;
685 ts->pat_packet_count = ts->pat_packet_period-1;
686 ts->sdt_packet_count = ts->sdt_packet_period-1;
688 if (ts->mux_rate == 1)
689 av_log(s, AV_LOG_VERBOSE, "muxrate VBR, ");
691 av_log(s, AV_LOG_VERBOSE, "muxrate %d, ", ts->mux_rate);
692 av_log(s, AV_LOG_VERBOSE, "pcr every %d pkts, "
693 "sdt every %d, pat/pmt every %d pkts\n",
694 service->pcr_packet_period,
695 ts->sdt_packet_period, ts->pat_packet_period);
697 if (ts->m2ts_mode == -1) {
698 if (av_match_ext(s->filename, "m2ts")) {
711 for(i = 0;i < s->nb_streams; i++) {
712 MpegTSWriteStream *ts_st;
714 ts_st = st->priv_data;
716 av_freep(&ts_st->payload);
718 avformat_free_context(ts_st->amux);
722 av_freep(&st->priv_data);
727 /* send SDT, PAT and PMT tables regulary */
728 static void retransmit_si_info(AVFormatContext *s, int force_pat)
730 MpegTSWrite *ts = s->priv_data;
733 if (++ts->sdt_packet_count == ts->sdt_packet_period) {
734 ts->sdt_packet_count = 0;
737 if (++ts->pat_packet_count == ts->pat_packet_period || force_pat) {
738 ts->pat_packet_count = 0;
740 for(i = 0; i < ts->nb_services; i++) {
741 mpegts_write_pmt(s, ts->services[i]);
746 static int write_pcr_bits(uint8_t *buf, int64_t pcr)
748 int64_t pcr_low = pcr % 300, pcr_high = pcr / 300;
750 *buf++ = pcr_high >> 25;
751 *buf++ = pcr_high >> 17;
752 *buf++ = pcr_high >> 9;
753 *buf++ = pcr_high >> 1;
754 *buf++ = pcr_high << 7 | pcr_low >> 8 | 0x7e;
760 /* Write a single null transport stream packet */
761 static void mpegts_insert_null_packet(AVFormatContext *s)
764 uint8_t buf[TS_PACKET_SIZE];
771 memset(q, 0x0FF, TS_PACKET_SIZE - (q - buf));
772 mpegts_prefix_m2ts_header(s);
773 avio_write(s->pb, buf, TS_PACKET_SIZE);
776 /* Write a single transport stream packet with a PCR and no payload */
777 static void mpegts_insert_pcr_only(AVFormatContext *s, AVStream *st)
779 MpegTSWrite *ts = s->priv_data;
780 MpegTSWriteStream *ts_st = st->priv_data;
782 uint8_t buf[TS_PACKET_SIZE];
786 *q++ = ts_st->pid >> 8;
788 *q++ = 0x20 | ts_st->cc; /* Adaptation only */
789 /* Continuity Count field does not increment (see 13818-1 section 2.4.3.3) */
790 *q++ = TS_PACKET_SIZE - 5; /* Adaptation Field Length */
791 *q++ = 0x10; /* Adaptation flags: PCR present */
793 /* PCR coded into 6 bytes */
794 q += write_pcr_bits(q, get_pcr(ts, s->pb));
797 memset(q, 0xFF, TS_PACKET_SIZE - (q - buf));
798 mpegts_prefix_m2ts_header(s);
799 avio_write(s->pb, buf, TS_PACKET_SIZE);
802 static void write_pts(uint8_t *q, int fourbits, int64_t pts)
806 val = fourbits << 4 | (((pts >> 30) & 0x07) << 1) | 1;
808 val = (((pts >> 15) & 0x7fff) << 1) | 1;
811 val = (((pts) & 0x7fff) << 1) | 1;
816 /* Set an adaptation field flag in an MPEG-TS packet*/
817 static void set_af_flag(uint8_t *pkt, int flag)
819 // expect at least one flag to set
822 if ((pkt[3] & 0x20) == 0) {
823 // no AF yet, set adaptation field flag
825 // 1 byte length, no flags
832 /* Extend the adaptation field by size bytes */
833 static void extend_af(uint8_t *pkt, int size)
835 // expect already existing adaptation field
836 av_assert0(pkt[3] & 0x20);
840 /* Get a pointer to MPEG-TS payload (right after TS packet header) */
841 static uint8_t *get_ts_payload_start(uint8_t *pkt)
844 return pkt + 5 + pkt[4];
849 /* Add a pes header to the front of payload, and segment into an integer number of
850 * ts packets. The final ts packet is padded using an over-sized adaptation header
851 * to exactly fill the last ts packet.
852 * NOTE: 'payload' contains a complete PES payload.
854 static void mpegts_write_pes(AVFormatContext *s, AVStream *st,
855 const uint8_t *payload, int payload_size,
856 int64_t pts, int64_t dts, int key)
858 MpegTSWriteStream *ts_st = st->priv_data;
859 MpegTSWrite *ts = s->priv_data;
860 uint8_t buf[TS_PACKET_SIZE];
862 int val, is_start, len, header_len, write_pcr, private_code, flags;
863 int afc_len, stuffing_len;
864 int64_t pcr = -1; /* avoid warning */
865 int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE);
866 int force_pat = st->codec->codec_type == AVMEDIA_TYPE_VIDEO && key && !ts_st->prev_payload_key;
869 while (payload_size > 0) {
870 retransmit_si_info(s, force_pat);
874 if (ts_st->pid == ts_st->service->pcr_pid) {
875 if (ts->mux_rate > 1 || is_start) // VBR pcr period is based on frames
876 ts_st->service->pcr_packet_count++;
877 if (ts_st->service->pcr_packet_count >=
878 ts_st->service->pcr_packet_period) {
879 ts_st->service->pcr_packet_count = 0;
884 if (ts->mux_rate > 1 && dts != AV_NOPTS_VALUE &&
885 (dts - get_pcr(ts, s->pb)/300) > delay) {
886 /* pcr insert gets priority over null packet insert */
888 mpegts_insert_pcr_only(s, st);
890 mpegts_insert_null_packet(s);
891 continue; /* recalculate write_pcr and possibly retransmit si_info */
894 /* prepare packet header */
897 val = (ts_st->pid >> 8);
902 ts_st->cc = (ts_st->cc + 1) & 0xf;
903 *q++ = 0x10 | ts_st->cc; // payload indicator + CC
904 if (key && is_start && pts != AV_NOPTS_VALUE) {
905 // set Random Access for key frames
906 if (ts_st->pid == ts_st->service->pcr_pid)
908 set_af_flag(buf, 0x40);
909 q = get_ts_payload_start(buf);
912 set_af_flag(buf, 0x10);
913 q = get_ts_payload_start(buf);
914 // add 11, pcr references the last byte of program clock reference base
915 if (ts->mux_rate > 1)
916 pcr = get_pcr(ts, s->pb);
918 pcr = (dts - delay)*300;
919 if (dts != AV_NOPTS_VALUE && dts < pcr / 300)
920 av_log(s, AV_LOG_WARNING, "dts < pcr, TS is invalid\n");
921 extend_af(buf, write_pcr_bits(q, pcr));
922 q = get_ts_payload_start(buf);
925 int pes_extension = 0;
926 /* write PES header */
931 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
932 if (st->codec->codec_id == AV_CODEC_ID_DIRAC) {
936 } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
937 (st->codec->codec_id == AV_CODEC_ID_MP2 ||
938 st->codec->codec_id == AV_CODEC_ID_MP3 ||
939 st->codec->codec_id == AV_CODEC_ID_AAC)) {
941 } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
942 st->codec->codec_id == AV_CODEC_ID_AC3 &&
947 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
953 if (pts != AV_NOPTS_VALUE) {
957 if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
961 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
962 st->codec->codec_id == AV_CODEC_ID_DIRAC) {
963 /* set PES_extension_flag */
968 * One byte for PES2 extension flag +
969 * one byte for extension length +
970 * one byte for extension id
974 /* for Blu-ray AC3 Audio the PES Extension flag should be as follow
975 * otherwise it will not play sound on blu-ray
978 st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
979 st->codec->codec_id == AV_CODEC_ID_AC3) {
980 /* set PES_extension_flag */
985 len = payload_size + header_len + 3;
986 if (private_code != 0)
993 /* data alignment indicator is required for subtitle and data streams */
994 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE || st->codec->codec_type == AVMEDIA_TYPE_DATA)
999 if (pts != AV_NOPTS_VALUE) {
1000 write_pts(q, flags >> 6, pts);
1003 if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
1004 write_pts(q, 1, dts);
1007 if (pes_extension && st->codec->codec_id == AV_CODEC_ID_DIRAC) {
1008 flags = 0x01; /* set PES_extension_flag_2 */
1010 *q++ = 0x80 | 0x01; /* marker bit + extension length */
1012 * Set the stream id extension flag bit to 0 and
1013 * write the extended stream id
1017 /* For Blu-ray AC3 Audio Setting extended flags */
1018 if (ts->m2ts_mode &&
1020 st->codec->codec_id == AV_CODEC_ID_AC3) {
1021 flags = 0x01; /* set PES_extension_flag_2 */
1023 *q++ = 0x80 | 0x01; /* marker bit + extension length */
1024 *q++ = 0x00 | 0x71; /* for AC3 Audio (specifically on blue-rays) */
1028 if (private_code != 0)
1029 *q++ = private_code;
1033 header_len = q - buf;
1035 len = TS_PACKET_SIZE - header_len;
1036 if (len > payload_size)
1038 stuffing_len = TS_PACKET_SIZE - header_len - len;
1039 if (stuffing_len > 0) {
1040 /* add stuffing with AFC */
1041 if (buf[3] & 0x20) {
1042 /* stuffing already present: increase its size */
1043 afc_len = buf[4] + 1;
1044 memmove(buf + 4 + afc_len + stuffing_len,
1046 header_len - (4 + afc_len));
1047 buf[4] += stuffing_len;
1048 memset(buf + 4 + afc_len, 0xff, stuffing_len);
1051 memmove(buf + 4 + stuffing_len, buf + 4, header_len - 4);
1053 buf[4] = stuffing_len - 1;
1054 if (stuffing_len >= 2) {
1056 memset(buf + 6, 0xff, stuffing_len - 2);
1060 memcpy(buf + TS_PACKET_SIZE - len, payload, len);
1062 payload_size -= len;
1063 mpegts_prefix_m2ts_header(s);
1064 avio_write(s->pb, buf, TS_PACKET_SIZE);
1067 ts_st->prev_payload_key = key;
1070 static int mpegts_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
1072 AVStream *st = s->streams[pkt->stream_index];
1073 int size = pkt->size;
1074 uint8_t *buf= pkt->data;
1075 uint8_t *data= NULL;
1076 MpegTSWrite *ts = s->priv_data;
1077 MpegTSWriteStream *ts_st = st->priv_data;
1078 const int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE)*2;
1079 int64_t dts = pkt->dts, pts = pkt->pts;
1081 if (ts->reemit_pat_pmt) {
1082 av_log(s, AV_LOG_WARNING, "resend_headers option is deprecated, use -mpegts_flags resend_headers\n");
1083 ts->reemit_pat_pmt = 0;
1084 ts->flags |= MPEGTS_FLAG_REEMIT_PAT_PMT;
1087 if (ts->flags & MPEGTS_FLAG_REEMIT_PAT_PMT) {
1088 ts->pat_packet_count = ts->pat_packet_period - 1;
1089 ts->sdt_packet_count = ts->sdt_packet_period - 1;
1090 ts->flags &= ~MPEGTS_FLAG_REEMIT_PAT_PMT;
1094 if (pts != AV_NOPTS_VALUE)
1096 if (dts != AV_NOPTS_VALUE)
1100 if (ts_st->first_pts_check && pts == AV_NOPTS_VALUE) {
1101 av_log(s, AV_LOG_ERROR, "first pts value must be set\n");
1102 return AVERROR_INVALIDDATA;
1104 ts_st->first_pts_check = 0;
1106 if (st->codec->codec_id == AV_CODEC_ID_H264) {
1107 const uint8_t *p = buf, *buf_end = p+size;
1108 uint32_t state = -1;
1110 if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001) {
1111 if (!st->nb_frames) {
1112 av_log(s, AV_LOG_ERROR, "H.264 bitstream malformed, "
1113 "no startcode found, use the h264_mp4toannexb bitstream filter (-bsf h264_mp4toannexb)\n");
1114 return AVERROR(EINVAL);
1116 av_log(s, AV_LOG_WARNING, "H.264 bitstream error, startcode missing\n");
1120 p = avpriv_find_start_code(p, buf_end, &state);
1121 av_dlog(s, "nal %d\n", state & 0x1f);
1122 } while (p < buf_end && (state & 0x1f) != 9 &&
1123 (state & 0x1f) != 5 && (state & 0x1f) != 1);
1125 if ((state & 0x1f) != 9) { // AUD NAL
1126 data = av_malloc(pkt->size+6);
1128 return AVERROR(ENOMEM);
1129 memcpy(data+6, pkt->data, pkt->size);
1130 AV_WB32(data, 0x00000001);
1132 data[5] = 0xf0; // any slice type (0xe) + rbsp stop one bit
1136 } else if (st->codec->codec_id == AV_CODEC_ID_AAC) {
1137 if (pkt->size < 2) {
1138 av_log(s, AV_LOG_ERROR, "AAC packet too short\n");
1139 return AVERROR_INVALIDDATA;
1141 if ((AV_RB16(pkt->data) & 0xfff0) != 0xfff0) {
1146 av_log(s, AV_LOG_ERROR, "AAC bitstream not in ADTS format "
1147 "and extradata missing\n");
1148 return AVERROR_INVALIDDATA;
1151 av_init_packet(&pkt2);
1152 pkt2.data = pkt->data;
1153 pkt2.size = pkt->size;
1154 ret = avio_open_dyn_buf(&ts_st->amux->pb);
1156 return AVERROR(ENOMEM);
1158 ret = av_write_frame(ts_st->amux, &pkt2);
1160 avio_close_dyn_buf(ts_st->amux->pb, &data);
1161 ts_st->amux->pb = NULL;
1165 size = avio_close_dyn_buf(ts_st->amux->pb, &data);
1166 ts_st->amux->pb = NULL;
1171 if (pkt->dts != AV_NOPTS_VALUE) {
1173 for(i=0; i<s->nb_streams; i++){
1174 AVStream *st2 = s->streams[i];
1175 MpegTSWriteStream *ts_st2 = st2->priv_data;
1176 if( ts_st2->payload_size
1177 && (ts_st2->payload_dts == AV_NOPTS_VALUE || dts - ts_st2->payload_dts > delay/2)){
1178 mpegts_write_pes(s, st2, ts_st2->payload, ts_st2->payload_size,
1179 ts_st2->payload_pts, ts_st2->payload_dts,
1180 ts_st2->payload_flags & AV_PKT_FLAG_KEY);
1181 ts_st2->payload_size = 0;
1186 if (ts_st->payload_size && ts_st->payload_size + size > ts->pes_payload_size) {
1187 mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_size,
1188 ts_st->payload_pts, ts_st->payload_dts,
1189 ts_st->payload_flags & AV_PKT_FLAG_KEY);
1190 ts_st->payload_size = 0;
1193 if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO || size > ts->pes_payload_size) {
1194 av_assert0(!ts_st->payload_size);
1195 // for video and subtitle, write a single pes packet
1196 mpegts_write_pes(s, st, buf, size, pts, dts, pkt->flags & AV_PKT_FLAG_KEY);
1201 if (!ts_st->payload_size) {
1202 ts_st->payload_pts = pts;
1203 ts_st->payload_dts = dts;
1204 ts_st->payload_flags = pkt->flags;
1207 memcpy(ts_st->payload + ts_st->payload_size, buf, size);
1208 ts_st->payload_size += size;
1215 static void mpegts_write_flush(AVFormatContext *s)
1219 /* flush current packets */
1220 for(i = 0; i < s->nb_streams; i++) {
1221 AVStream *st = s->streams[i];
1222 MpegTSWriteStream *ts_st = st->priv_data;
1223 if (ts_st->payload_size > 0) {
1224 mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_size,
1225 ts_st->payload_pts, ts_st->payload_dts,
1226 ts_st->payload_flags & AV_PKT_FLAG_KEY);
1227 ts_st->payload_size = 0;
1233 static int mpegts_write_packet(AVFormatContext *s, AVPacket *pkt)
1236 mpegts_write_flush(s);
1239 return mpegts_write_packet_internal(s, pkt);
1243 static int mpegts_write_end(AVFormatContext *s)
1245 MpegTSWrite *ts = s->priv_data;
1246 MpegTSService *service;
1249 mpegts_write_flush(s);
1251 for(i = 0; i < s->nb_streams; i++) {
1252 AVStream *st = s->streams[i];
1253 MpegTSWriteStream *ts_st = st->priv_data;
1254 av_freep(&ts_st->payload);
1256 avformat_free_context(ts_st->amux);
1261 for(i = 0; i < ts->nb_services; i++) {
1262 service = ts->services[i];
1263 av_freep(&service->provider_name);
1264 av_freep(&service->name);
1267 av_free(ts->services);
1272 AVOutputFormat ff_mpegts_muxer = {
1274 .long_name = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
1275 .mime_type = "video/x-mpegts",
1276 .extensions = "ts,m2t,m2ts,mts",
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,
1283 .flags = AVFMT_ALLOW_FLUSH,
1284 .priv_class = &mpegts_muxer_class,