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
90 /* a PES packet header is generated every DEFAULT_PES_HEADER_FREQ packets */
91 #define DEFAULT_PES_HEADER_FREQ 16
92 #define DEFAULT_PES_PAYLOAD_SIZE ((DEFAULT_PES_HEADER_FREQ - 1) * 184 + 170)
94 static const AVOption options[] = {
95 { "mpegts_transport_stream_id", "Set transport_stream_id field.",
96 offsetof(MpegTSWrite, transport_stream_id), AV_OPT_TYPE_INT, {.i64 = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
97 { "mpegts_original_network_id", "Set original_network_id field.",
98 offsetof(MpegTSWrite, original_network_id), AV_OPT_TYPE_INT, {.i64 = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
99 { "mpegts_service_id", "Set service_id field.",
100 offsetof(MpegTSWrite, service_id), AV_OPT_TYPE_INT, {.i64 = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
101 { "mpegts_pmt_start_pid", "Set the first pid of the PMT.",
102 offsetof(MpegTSWrite, pmt_start_pid), AV_OPT_TYPE_INT, {.i64 = 0x1000 }, 0x0010, 0x1f00, AV_OPT_FLAG_ENCODING_PARAM},
103 { "mpegts_start_pid", "Set the first pid.",
104 offsetof(MpegTSWrite, start_pid), AV_OPT_TYPE_INT, {.i64 = 0x0100 }, 0x0100, 0x0f00, AV_OPT_FLAG_ENCODING_PARAM},
105 {"mpegts_m2ts_mode", "Enable m2ts mode.",
106 offsetof(MpegTSWrite, m2ts_mode), AV_OPT_TYPE_INT, {.i64 = -1 },
107 -1,1, AV_OPT_FLAG_ENCODING_PARAM},
108 { "muxrate", NULL, offsetof(MpegTSWrite, mux_rate), AV_OPT_TYPE_INT, {.i64 = 1}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
109 { "pes_payload_size", "Minimum PES packet payload in bytes",
110 offsetof(MpegTSWrite, pes_payload_size), AV_OPT_TYPE_INT, {.i64 = DEFAULT_PES_PAYLOAD_SIZE}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
111 { "mpegts_flags", "MPEG-TS muxing flags", offsetof(MpegTSWrite, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, 0, INT_MAX,
112 AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags" },
113 { "resend_headers", "Reemit PAT/PMT before writing the next packet",
114 0, AV_OPT_TYPE_CONST, {.i64 = MPEGTS_FLAG_REEMIT_PAT_PMT}, 0, INT_MAX,
115 AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags"},
116 { "latm", "Use LATM packetization for AAC",
117 0, AV_OPT_TYPE_CONST, {.i64 = MPEGTS_FLAG_AAC_LATM}, 0, INT_MAX,
118 AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags"},
119 // backward compatibility
120 { "resend_headers", "Reemit PAT/PMT before writing the next packet",
121 offsetof(MpegTSWrite, reemit_pat_pmt), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
122 { "mpegts_copyts", "don't offset dts/pts",
123 offsetof(MpegTSWrite, copyts), AV_OPT_TYPE_INT, {.i64=-1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
127 static const AVClass mpegts_muxer_class = {
128 .class_name = "MPEGTS muxer",
129 .item_name = av_default_item_name,
131 .version = LIBAVUTIL_VERSION_INT,
134 /* NOTE: 4 bytes must be left at the end for the crc32 */
135 static void mpegts_write_section(MpegTSSection *s, uint8_t *buf, int len)
138 unsigned char packet[TS_PACKET_SIZE];
139 const unsigned char *buf_ptr;
141 int first, b, len1, left;
143 crc = av_bswap32(av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1, buf, len - 4));
144 buf[len - 4] = (crc >> 24) & 0xff;
145 buf[len - 3] = (crc >> 16) & 0xff;
146 buf[len - 2] = (crc >> 8) & 0xff;
147 buf[len - 1] = (crc) & 0xff;
149 /* send each packet */
152 first = (buf == buf_ptr);
160 s->cc = (s->cc + 1) & 0xf;
163 *q++ = 0; /* 0 offset */
164 len1 = TS_PACKET_SIZE - (q - packet);
167 memcpy(q, buf_ptr, len1);
169 /* add known padding data */
170 left = TS_PACKET_SIZE - (q - packet);
172 memset(q, 0xff, left);
174 s->write_packet(s, packet);
181 static inline void put16(uint8_t **q_ptr, int val)
190 static int mpegts_write_section1(MpegTSSection *s, int tid, int id,
191 int version, int sec_num, int last_sec_num,
192 uint8_t *buf, int len)
194 uint8_t section[1024], *q;
195 unsigned int tot_len;
196 /* reserved_future_use field must be set to 1 for SDT */
197 unsigned int flags = tid == SDT_TID ? 0xf000 : 0xb000;
199 tot_len = 3 + 5 + len + 4;
200 /* check if not too big */
202 return AVERROR_INVALIDDATA;
206 put16(&q, flags | (len + 5 + 4)); /* 5 byte header + 4 byte CRC */
208 *q++ = 0xc1 | (version << 1); /* current_next_indicator = 1 */
213 mpegts_write_section(s, section, tot_len);
217 /*********************************************/
220 #define DEFAULT_PROVIDER_NAME "FFmpeg"
221 #define DEFAULT_SERVICE_NAME "Service01"
223 /* we retransmit the SI info at this rate */
224 #define SDT_RETRANS_TIME 500
225 #define PAT_RETRANS_TIME 100
226 #define PCR_RETRANS_TIME 20
228 typedef struct MpegTSWriteStream {
229 struct MpegTSService *service;
230 int pid; /* stream associated pid */
233 int first_pts_check; ///< first pts check needed
234 int prev_payload_key;
239 AVFormatContext *amux;
242 static void mpegts_write_pat(AVFormatContext *s)
244 MpegTSWrite *ts = s->priv_data;
245 MpegTSService *service;
246 uint8_t data[1012], *q;
250 for(i = 0; i < ts->nb_services; i++) {
251 service = ts->services[i];
252 put16(&q, service->sid);
253 put16(&q, 0xe000 | service->pmt.pid);
255 mpegts_write_section1(&ts->pat, PAT_TID, ts->tsid, 0, 0, 0,
259 static void mpegts_write_pmt(AVFormatContext *s, MpegTSService *service)
261 MpegTSWrite *ts = s->priv_data;
262 uint8_t data[1012], *q, *desc_length_ptr, *program_info_length_ptr;
263 int val, stream_type, i;
266 put16(&q, 0xe000 | service->pcr_pid);
268 program_info_length_ptr = q;
269 q += 2; /* patched after */
271 /* put program info here */
273 val = 0xf000 | (q - program_info_length_ptr - 2);
274 program_info_length_ptr[0] = val >> 8;
275 program_info_length_ptr[1] = val;
277 for(i = 0; i < s->nb_streams; i++) {
278 AVStream *st = s->streams[i];
279 MpegTSWriteStream *ts_st = st->priv_data;
280 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
281 switch(st->codec->codec_id) {
282 case AV_CODEC_ID_MPEG1VIDEO:
283 case AV_CODEC_ID_MPEG2VIDEO:
284 stream_type = STREAM_TYPE_VIDEO_MPEG2;
286 case AV_CODEC_ID_MPEG4:
287 stream_type = STREAM_TYPE_VIDEO_MPEG4;
289 case AV_CODEC_ID_H264:
290 stream_type = STREAM_TYPE_VIDEO_H264;
292 case AV_CODEC_ID_CAVS:
293 stream_type = STREAM_TYPE_VIDEO_CAVS;
295 case AV_CODEC_ID_DIRAC:
296 stream_type = STREAM_TYPE_VIDEO_DIRAC;
298 case AV_CODEC_ID_MP2:
299 case AV_CODEC_ID_MP3:
300 stream_type = STREAM_TYPE_AUDIO_MPEG1;
302 case AV_CODEC_ID_AAC:
303 stream_type = (ts->flags & MPEGTS_FLAG_AAC_LATM) ? STREAM_TYPE_AUDIO_AAC_LATM : STREAM_TYPE_AUDIO_AAC;
305 case AV_CODEC_ID_AAC_LATM:
306 stream_type = STREAM_TYPE_AUDIO_AAC_LATM;
308 case AV_CODEC_ID_AC3:
309 stream_type = STREAM_TYPE_AUDIO_AC3;
312 stream_type = STREAM_TYPE_PRIVATE_DATA;
316 put16(&q, 0xe000 | ts_st->pid);
318 q += 2; /* patched after */
320 /* write optional descriptors here */
321 switch(st->codec->codec_type) {
322 case AVMEDIA_TYPE_AUDIO:
323 if(st->codec->codec_id==AV_CODEC_ID_EAC3){
324 *q++=0x7a; // EAC3 descriptor see A038 DVB SI
325 *q++=1; // 1 byte, all flags sets to 0
326 *q++=0; // omit all fields...
328 if(st->codec->codec_id==AV_CODEC_ID_S302M){
329 *q++ = 0x05; /* MPEG-2 registration descriptor*/
339 char *next = lang->value;
342 *q++ = 0x0a; /* ISO 639 language descriptor */
346 for (p = lang->value; next && *len_ptr < 255 / 4 * 4; p = next + 1) {
347 next = strchr(p, ',');
348 if (strlen(p) != 3 && (!next || next != p + 3))
349 continue; /* not a 3-letter code */
355 if (st->disposition & AV_DISPOSITION_CLEAN_EFFECTS)
357 else if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
359 else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
362 *q++ = 0; /* undefined type */
368 q -= 2; /* no language codes were written */
371 case AVMEDIA_TYPE_SUBTITLE:
373 const char *language;
374 language = lang && strlen(lang->value)==3 ? lang->value : "eng";
380 *q++ = 0x10; /* normal subtitles (0x20 = if hearing pb) */
381 if(st->codec->extradata_size == 4) {
382 memcpy(q, st->codec->extradata, 4);
385 put16(&q, 1); /* page id */
386 put16(&q, 1); /* ancillary page id */
390 case AVMEDIA_TYPE_VIDEO:
391 if (stream_type == STREAM_TYPE_VIDEO_DIRAC) {
392 *q++ = 0x05; /*MPEG-2 registration descriptor*/
400 case AVMEDIA_TYPE_DATA:
401 if (st->codec->codec_id == AV_CODEC_ID_SMPTE_KLV) {
402 *q++ = 0x05; /* MPEG-2 registration descriptor */
412 val = 0xf000 | (q - desc_length_ptr - 2);
413 desc_length_ptr[0] = val >> 8;
414 desc_length_ptr[1] = val;
416 mpegts_write_section1(&service->pmt, PMT_TID, service->sid, 0, 0, 0,
420 /* NOTE: str == NULL is accepted for an empty string */
421 static void putstr8(uint8_t **q_ptr, const char *str)
437 static void mpegts_write_sdt(AVFormatContext *s)
439 MpegTSWrite *ts = s->priv_data;
440 MpegTSService *service;
441 uint8_t data[1012], *q, *desc_list_len_ptr, *desc_len_ptr;
442 int i, running_status, free_ca_mode, val;
447 for(i = 0; i < ts->nb_services; i++) {
448 service = ts->services[i];
449 put16(&q, service->sid);
450 *q++ = 0xfc | 0x00; /* currently no EIT info */
451 desc_list_len_ptr = q;
453 running_status = 4; /* running */
456 /* write only one descriptor for the service name and provider */
460 *q++ = 0x01; /* digital television service */
461 putstr8(&q, service->provider_name);
462 putstr8(&q, service->name);
463 desc_len_ptr[0] = q - desc_len_ptr - 1;
465 /* fill descriptor length */
466 val = (running_status << 13) | (free_ca_mode << 12) |
467 (q - desc_list_len_ptr - 2);
468 desc_list_len_ptr[0] = val >> 8;
469 desc_list_len_ptr[1] = val;
471 mpegts_write_section1(&ts->sdt, SDT_TID, ts->tsid, 0, 0, 0,
475 static MpegTSService *mpegts_add_service(MpegTSWrite *ts,
477 const char *provider_name,
480 MpegTSService *service;
482 service = av_mallocz(sizeof(MpegTSService));
485 service->pmt.pid = ts->pmt_start_pid + ts->nb_services;
487 service->provider_name = av_strdup(provider_name);
488 service->name = av_strdup(name);
489 service->pcr_pid = 0x1fff;
490 dynarray_add(&ts->services, &ts->nb_services, service);
494 static int64_t get_pcr(const MpegTSWrite *ts, AVIOContext *pb)
496 return av_rescale(avio_tell(pb) + 11, 8 * PCR_TIME_BASE, ts->mux_rate) +
500 static void mpegts_prefix_m2ts_header(AVFormatContext *s)
502 MpegTSWrite *ts = s->priv_data;
504 int64_t pcr = get_pcr(s->priv_data, s->pb);
505 uint32_t tp_extra_header = pcr % 0x3fffffff;
506 tp_extra_header = AV_RB32(&tp_extra_header);
507 avio_write(s->pb, (unsigned char *) &tp_extra_header,
508 sizeof(tp_extra_header));
512 static void section_write_packet(MpegTSSection *s, const uint8_t *packet)
514 AVFormatContext *ctx = s->opaque;
515 mpegts_prefix_m2ts_header(ctx);
516 avio_write(ctx->pb, packet, TS_PACKET_SIZE);
519 static int mpegts_write_header(AVFormatContext *s)
521 MpegTSWrite *ts = s->priv_data;
522 MpegTSWriteStream *ts_st;
523 MpegTSService *service;
524 AVStream *st, *pcr_st = NULL;
525 AVDictionaryEntry *title, *provider;
527 const char *service_name;
528 const char *provider_name;
532 if (s->max_delay < 0) /* Not set by the caller */
535 // round up to a whole number of TS packets
536 ts->pes_payload_size = (ts->pes_payload_size + 14 + 183) / 184 * 184 - 14;
538 ts->tsid = ts->transport_stream_id;
539 ts->onid = ts->original_network_id;
540 /* allocate a single DVB service */
541 title = av_dict_get(s->metadata, "service_name", NULL, 0);
543 title = av_dict_get(s->metadata, "title", NULL, 0);
544 service_name = title ? title->value : DEFAULT_SERVICE_NAME;
545 provider = av_dict_get(s->metadata, "service_provider", NULL, 0);
546 provider_name = provider ? provider->value : DEFAULT_PROVIDER_NAME;
547 service = mpegts_add_service(ts, ts->service_id, provider_name, service_name);
548 service->pmt.write_packet = section_write_packet;
549 service->pmt.opaque = s;
550 service->pmt.cc = 15;
552 ts->pat.pid = PAT_PID;
553 ts->pat.cc = 15; // Initialize at 15 so that it wraps and be equal to 0 for the first packet we write
554 ts->pat.write_packet = section_write_packet;
557 ts->sdt.pid = SDT_PID;
559 ts->sdt.write_packet = section_write_packet;
562 pids = av_malloc(s->nb_streams * sizeof(*pids));
564 return AVERROR(ENOMEM);
566 /* assign pids to each stream */
567 for(i = 0;i < s->nb_streams; i++) {
569 avpriv_set_pts_info(st, 33, 1, 90000);
570 ts_st = av_mallocz(sizeof(MpegTSWriteStream));
572 ret = AVERROR(ENOMEM);
575 st->priv_data = ts_st;
576 ts_st->payload = av_mallocz(ts->pes_payload_size);
577 if (!ts_st->payload) {
578 ret = AVERROR(ENOMEM);
581 ts_st->service = service;
582 /* MPEG pid values < 16 are reserved. Applications which set st->id in
583 * this range are assigned a calculated pid. */
585 ts_st->pid = ts->start_pid + i;
586 } else if (st->id < 0x1FFF) {
589 av_log(s, AV_LOG_ERROR, "Invalid stream id %d, must be less than 8191\n", st->id);
590 ret = AVERROR(EINVAL);
593 if (ts_st->pid == service->pmt.pid) {
594 av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
595 ret = AVERROR(EINVAL);
598 for (j = 0; j < i; j++)
599 if (pids[j] == ts_st->pid) {
600 av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
601 ret = AVERROR(EINVAL);
604 pids[i] = ts_st->pid;
605 ts_st->payload_pts = AV_NOPTS_VALUE;
606 ts_st->payload_dts = AV_NOPTS_VALUE;
607 ts_st->first_pts_check = 1;
609 /* update PCR pid by using the first video stream */
610 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
611 service->pcr_pid == 0x1fff) {
612 service->pcr_pid = ts_st->pid;
615 if (st->codec->codec_id == AV_CODEC_ID_AAC &&
616 st->codec->extradata_size > 0)
619 ts_st->amux = avformat_alloc_context();
621 ret = AVERROR(ENOMEM);
624 ts_st->amux->oformat = av_guess_format((ts->flags & MPEGTS_FLAG_AAC_LATM) ? "latm" : "adts", NULL, NULL);
625 if (!ts_st->amux->oformat) {
626 ret = AVERROR(EINVAL);
629 ast = avformat_new_stream(ts_st->amux, NULL);
630 ret = avcodec_copy_context(ast->codec, st->codec);
633 ret = avformat_write_header(ts_st->amux, NULL);
641 /* if no video stream, use the first stream as PCR */
642 if (service->pcr_pid == 0x1fff && s->nb_streams > 0) {
643 pcr_st = s->streams[0];
644 ts_st = pcr_st->priv_data;
645 service->pcr_pid = ts_st->pid;
648 if (ts->mux_rate > 1) {
649 service->pcr_packet_period = (ts->mux_rate * PCR_RETRANS_TIME) /
650 (TS_PACKET_SIZE * 8 * 1000);
651 ts->sdt_packet_period = (ts->mux_rate * SDT_RETRANS_TIME) /
652 (TS_PACKET_SIZE * 8 * 1000);
653 ts->pat_packet_period = (ts->mux_rate * PAT_RETRANS_TIME) /
654 (TS_PACKET_SIZE * 8 * 1000);
657 ts->first_pcr = av_rescale(s->max_delay, PCR_TIME_BASE, AV_TIME_BASE);
659 /* Arbitrary values, PAT/PMT will also be written on video key frames */
660 ts->sdt_packet_period = 200;
661 ts->pat_packet_period = 40;
662 if (pcr_st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
663 if (!pcr_st->codec->frame_size) {
664 av_log(s, AV_LOG_WARNING, "frame size not set\n");
665 service->pcr_packet_period =
666 pcr_st->codec->sample_rate/(10*512);
668 service->pcr_packet_period =
669 pcr_st->codec->sample_rate/(10*pcr_st->codec->frame_size);
672 // max delta PCR 0.1s
673 service->pcr_packet_period =
674 pcr_st->codec->time_base.den/(10*pcr_st->codec->time_base.num);
676 if(!service->pcr_packet_period)
677 service->pcr_packet_period = 1;
680 // output a PCR as soon as possible
681 service->pcr_packet_count = service->pcr_packet_period;
682 ts->pat_packet_count = ts->pat_packet_period-1;
683 ts->sdt_packet_count = ts->sdt_packet_period-1;
685 if (ts->mux_rate == 1)
686 av_log(s, AV_LOG_VERBOSE, "muxrate VBR, ");
688 av_log(s, AV_LOG_VERBOSE, "muxrate %d, ", ts->mux_rate);
689 av_log(s, AV_LOG_VERBOSE, "pcr every %d pkts, "
690 "sdt every %d, pat/pmt every %d pkts\n",
691 service->pcr_packet_period,
692 ts->sdt_packet_period, ts->pat_packet_period);
694 if (ts->m2ts_mode == -1) {
695 if (av_match_ext(s->filename, "m2ts")) {
708 for(i = 0;i < s->nb_streams; i++) {
709 MpegTSWriteStream *ts_st;
711 ts_st = st->priv_data;
713 av_freep(&ts_st->payload);
715 avformat_free_context(ts_st->amux);
719 av_freep(&st->priv_data);
724 /* send SDT, PAT and PMT tables regulary */
725 static void retransmit_si_info(AVFormatContext *s, int force_pat)
727 MpegTSWrite *ts = s->priv_data;
730 if (++ts->sdt_packet_count == ts->sdt_packet_period) {
731 ts->sdt_packet_count = 0;
734 if (++ts->pat_packet_count == ts->pat_packet_period || force_pat) {
735 ts->pat_packet_count = 0;
737 for(i = 0; i < ts->nb_services; i++) {
738 mpegts_write_pmt(s, ts->services[i]);
743 static int write_pcr_bits(uint8_t *buf, int64_t pcr)
745 int64_t pcr_low = pcr % 300, pcr_high = pcr / 300;
747 *buf++ = pcr_high >> 25;
748 *buf++ = pcr_high >> 17;
749 *buf++ = pcr_high >> 9;
750 *buf++ = pcr_high >> 1;
751 *buf++ = pcr_high << 7 | pcr_low >> 8 | 0x7e;
757 /* Write a single null transport stream packet */
758 static void mpegts_insert_null_packet(AVFormatContext *s)
761 uint8_t buf[TS_PACKET_SIZE];
768 memset(q, 0x0FF, TS_PACKET_SIZE - (q - buf));
769 mpegts_prefix_m2ts_header(s);
770 avio_write(s->pb, buf, TS_PACKET_SIZE);
773 /* Write a single transport stream packet with a PCR and no payload */
774 static void mpegts_insert_pcr_only(AVFormatContext *s, AVStream *st)
776 MpegTSWrite *ts = s->priv_data;
777 MpegTSWriteStream *ts_st = st->priv_data;
779 uint8_t buf[TS_PACKET_SIZE];
783 *q++ = ts_st->pid >> 8;
785 *q++ = 0x20 | ts_st->cc; /* Adaptation only */
786 /* Continuity Count field does not increment (see 13818-1 section 2.4.3.3) */
787 *q++ = TS_PACKET_SIZE - 5; /* Adaptation Field Length */
788 *q++ = 0x10; /* Adaptation flags: PCR present */
790 /* PCR coded into 6 bytes */
791 q += write_pcr_bits(q, get_pcr(ts, s->pb));
794 memset(q, 0xFF, TS_PACKET_SIZE - (q - buf));
795 mpegts_prefix_m2ts_header(s);
796 avio_write(s->pb, buf, TS_PACKET_SIZE);
799 static void write_pts(uint8_t *q, int fourbits, int64_t pts)
803 val = fourbits << 4 | (((pts >> 30) & 0x07) << 1) | 1;
805 val = (((pts >> 15) & 0x7fff) << 1) | 1;
808 val = (((pts) & 0x7fff) << 1) | 1;
813 /* Set an adaptation field flag in an MPEG-TS packet*/
814 static void set_af_flag(uint8_t *pkt, int flag)
816 // expect at least one flag to set
819 if ((pkt[3] & 0x20) == 0) {
820 // no AF yet, set adaptation field flag
822 // 1 byte length, no flags
829 /* Extend the adaptation field by size bytes */
830 static void extend_af(uint8_t *pkt, int size)
832 // expect already existing adaptation field
833 av_assert0(pkt[3] & 0x20);
837 /* Get a pointer to MPEG-TS payload (right after TS packet header) */
838 static uint8_t *get_ts_payload_start(uint8_t *pkt)
841 return pkt + 5 + pkt[4];
846 /* Add a pes header to the front of payload, and segment into an integer number of
847 * ts packets. The final ts packet is padded using an over-sized adaptation header
848 * to exactly fill the last ts packet.
849 * NOTE: 'payload' contains a complete PES payload.
851 static void mpegts_write_pes(AVFormatContext *s, AVStream *st,
852 const uint8_t *payload, int payload_size,
853 int64_t pts, int64_t dts, int key)
855 MpegTSWriteStream *ts_st = st->priv_data;
856 MpegTSWrite *ts = s->priv_data;
857 uint8_t buf[TS_PACKET_SIZE];
859 int val, is_start, len, header_len, write_pcr, private_code, flags;
860 int afc_len, stuffing_len;
861 int64_t pcr = -1; /* avoid warning */
862 int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE);
863 int force_pat = st->codec->codec_type == AVMEDIA_TYPE_VIDEO && key && !ts_st->prev_payload_key;
866 while (payload_size > 0) {
867 retransmit_si_info(s, force_pat);
871 if (ts_st->pid == ts_st->service->pcr_pid) {
872 if (ts->mux_rate > 1 || is_start) // VBR pcr period is based on frames
873 ts_st->service->pcr_packet_count++;
874 if (ts_st->service->pcr_packet_count >=
875 ts_st->service->pcr_packet_period) {
876 ts_st->service->pcr_packet_count = 0;
881 if (ts->mux_rate > 1 && dts != AV_NOPTS_VALUE &&
882 (dts - get_pcr(ts, s->pb)/300) > delay) {
883 /* pcr insert gets priority over null packet insert */
885 mpegts_insert_pcr_only(s, st);
887 mpegts_insert_null_packet(s);
888 continue; /* recalculate write_pcr and possibly retransmit si_info */
891 /* prepare packet header */
894 val = (ts_st->pid >> 8);
899 ts_st->cc = (ts_st->cc + 1) & 0xf;
900 *q++ = 0x10 | ts_st->cc; // payload indicator + CC
901 if (key && is_start && pts != AV_NOPTS_VALUE) {
902 // set Random Access for key frames
903 if (ts_st->pid == ts_st->service->pcr_pid)
905 set_af_flag(buf, 0x40);
906 q = get_ts_payload_start(buf);
909 set_af_flag(buf, 0x10);
910 q = get_ts_payload_start(buf);
911 // add 11, pcr references the last byte of program clock reference base
912 if (ts->mux_rate > 1)
913 pcr = get_pcr(ts, s->pb);
915 pcr = (dts - delay)*300;
916 if (dts != AV_NOPTS_VALUE && dts < pcr / 300)
917 av_log(s, AV_LOG_WARNING, "dts < pcr, TS is invalid\n");
918 extend_af(buf, write_pcr_bits(q, pcr));
919 q = get_ts_payload_start(buf);
922 int pes_extension = 0;
923 /* write PES header */
928 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
929 if (st->codec->codec_id == AV_CODEC_ID_DIRAC) {
933 } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
934 (st->codec->codec_id == AV_CODEC_ID_MP2 ||
935 st->codec->codec_id == AV_CODEC_ID_MP3 ||
936 st->codec->codec_id == AV_CODEC_ID_AAC)) {
938 } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
939 st->codec->codec_id == AV_CODEC_ID_AC3 &&
944 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
950 if (pts != AV_NOPTS_VALUE) {
954 if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
958 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
959 st->codec->codec_id == AV_CODEC_ID_DIRAC) {
960 /* set PES_extension_flag */
965 * One byte for PES2 extension flag +
966 * one byte for extension length +
967 * one byte for extension id
971 /* for Blu-ray AC3 Audio the PES Extension flag should be as follow
972 * otherwise it will not play sound on blu-ray
975 st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
976 st->codec->codec_id == AV_CODEC_ID_AC3) {
977 /* set PES_extension_flag */
982 len = payload_size + header_len + 3;
983 if (private_code != 0)
990 /* data alignment indicator is required for subtitle and data streams */
991 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE || st->codec->codec_type == AVMEDIA_TYPE_DATA)
996 if (pts != AV_NOPTS_VALUE) {
997 write_pts(q, flags >> 6, pts);
1000 if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
1001 write_pts(q, 1, dts);
1004 if (pes_extension && st->codec->codec_id == AV_CODEC_ID_DIRAC) {
1005 flags = 0x01; /* set PES_extension_flag_2 */
1007 *q++ = 0x80 | 0x01; /* marker bit + extension length */
1009 * Set the stream id extension flag bit to 0 and
1010 * write the extended stream id
1014 /* For Blu-ray AC3 Audio Setting extended flags */
1015 if (ts->m2ts_mode &&
1017 st->codec->codec_id == AV_CODEC_ID_AC3) {
1018 flags = 0x01; /* set PES_extension_flag_2 */
1020 *q++ = 0x80 | 0x01; /* marker bit + extension length */
1021 *q++ = 0x00 | 0x71; /* for AC3 Audio (specifically on blue-rays) */
1025 if (private_code != 0)
1026 *q++ = private_code;
1030 header_len = q - buf;
1032 len = TS_PACKET_SIZE - header_len;
1033 if (len > payload_size)
1035 stuffing_len = TS_PACKET_SIZE - header_len - len;
1036 if (stuffing_len > 0) {
1037 /* add stuffing with AFC */
1038 if (buf[3] & 0x20) {
1039 /* stuffing already present: increase its size */
1040 afc_len = buf[4] + 1;
1041 memmove(buf + 4 + afc_len + stuffing_len,
1043 header_len - (4 + afc_len));
1044 buf[4] += stuffing_len;
1045 memset(buf + 4 + afc_len, 0xff, stuffing_len);
1048 memmove(buf + 4 + stuffing_len, buf + 4, header_len - 4);
1050 buf[4] = stuffing_len - 1;
1051 if (stuffing_len >= 2) {
1053 memset(buf + 6, 0xff, stuffing_len - 2);
1057 memcpy(buf + TS_PACKET_SIZE - len, payload, len);
1059 payload_size -= len;
1060 mpegts_prefix_m2ts_header(s);
1061 avio_write(s->pb, buf, TS_PACKET_SIZE);
1064 ts_st->prev_payload_key = key;
1067 static int mpegts_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
1069 AVStream *st = s->streams[pkt->stream_index];
1070 int size = pkt->size;
1071 uint8_t *buf= pkt->data;
1072 uint8_t *data= NULL;
1073 MpegTSWrite *ts = s->priv_data;
1074 MpegTSWriteStream *ts_st = st->priv_data;
1075 const int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE)*2;
1076 int64_t dts = pkt->dts, pts = pkt->pts;
1078 if (ts->reemit_pat_pmt) {
1079 av_log(s, AV_LOG_WARNING, "resend_headers option is deprecated, use -mpegts_flags resend_headers\n");
1080 ts->reemit_pat_pmt = 0;
1081 ts->flags |= MPEGTS_FLAG_REEMIT_PAT_PMT;
1084 if (ts->flags & MPEGTS_FLAG_REEMIT_PAT_PMT) {
1085 ts->pat_packet_count = ts->pat_packet_period - 1;
1086 ts->sdt_packet_count = ts->sdt_packet_period - 1;
1087 ts->flags &= ~MPEGTS_FLAG_REEMIT_PAT_PMT;
1091 if (pts != AV_NOPTS_VALUE)
1093 if (dts != AV_NOPTS_VALUE)
1097 if (ts_st->first_pts_check && pts == AV_NOPTS_VALUE) {
1098 av_log(s, AV_LOG_ERROR, "first pts value must be set\n");
1099 return AVERROR_INVALIDDATA;
1101 ts_st->first_pts_check = 0;
1103 if (st->codec->codec_id == AV_CODEC_ID_H264) {
1104 const uint8_t *p = buf, *buf_end = p+size;
1105 uint32_t state = -1;
1107 if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001) {
1108 if (!st->nb_frames) {
1109 av_log(s, AV_LOG_ERROR, "H.264 bitstream malformed, "
1110 "no startcode found, use the h264_mp4toannexb bitstream filter (-bsf h264_mp4toannexb)\n");
1111 return AVERROR(EINVAL);
1113 av_log(s, AV_LOG_WARNING, "H.264 bitstream error, startcode missing\n");
1117 p = avpriv_find_start_code(p, buf_end, &state);
1118 av_dlog(s, "nal %d\n", state & 0x1f);
1119 } while (p < buf_end && (state & 0x1f) != 9 &&
1120 (state & 0x1f) != 5 && (state & 0x1f) != 1);
1122 if ((state & 0x1f) != 9) { // AUD NAL
1123 data = av_malloc(pkt->size+6);
1125 return AVERROR(ENOMEM);
1126 memcpy(data+6, pkt->data, pkt->size);
1127 AV_WB32(data, 0x00000001);
1129 data[5] = 0xf0; // any slice type (0xe) + rbsp stop one bit
1133 } else if (st->codec->codec_id == AV_CODEC_ID_AAC) {
1134 if (pkt->size < 2) {
1135 av_log(s, AV_LOG_ERROR, "AAC packet too short\n");
1136 return AVERROR_INVALIDDATA;
1138 if ((AV_RB16(pkt->data) & 0xfff0) != 0xfff0) {
1143 av_log(s, AV_LOG_ERROR, "AAC bitstream not in ADTS format "
1144 "and extradata missing\n");
1145 return AVERROR_INVALIDDATA;
1148 av_init_packet(&pkt2);
1149 pkt2.data = pkt->data;
1150 pkt2.size = pkt->size;
1151 ret = avio_open_dyn_buf(&ts_st->amux->pb);
1153 return AVERROR(ENOMEM);
1155 ret = av_write_frame(ts_st->amux, &pkt2);
1157 avio_close_dyn_buf(ts_st->amux->pb, &data);
1158 ts_st->amux->pb = NULL;
1162 size = avio_close_dyn_buf(ts_st->amux->pb, &data);
1163 ts_st->amux->pb = NULL;
1168 if (pkt->dts != AV_NOPTS_VALUE) {
1170 for(i=0; i<s->nb_streams; i++){
1171 AVStream *st2 = s->streams[i];
1172 MpegTSWriteStream *ts_st2 = st2->priv_data;
1173 if( ts_st2->payload_size
1174 && (ts_st2->payload_dts == AV_NOPTS_VALUE || dts - ts_st2->payload_dts > delay/2)){
1175 mpegts_write_pes(s, st2, ts_st2->payload, ts_st2->payload_size,
1176 ts_st2->payload_pts, ts_st2->payload_dts,
1177 ts_st2->payload_flags & AV_PKT_FLAG_KEY);
1178 ts_st2->payload_size = 0;
1183 if (ts_st->payload_size && ts_st->payload_size + size > ts->pes_payload_size) {
1184 mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_size,
1185 ts_st->payload_pts, ts_st->payload_dts,
1186 ts_st->payload_flags & AV_PKT_FLAG_KEY);
1187 ts_st->payload_size = 0;
1190 if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO || size > ts->pes_payload_size) {
1191 av_assert0(!ts_st->payload_size);
1192 // for video and subtitle, write a single pes packet
1193 mpegts_write_pes(s, st, buf, size, pts, dts, pkt->flags & AV_PKT_FLAG_KEY);
1198 if (!ts_st->payload_size) {
1199 ts_st->payload_pts = pts;
1200 ts_st->payload_dts = dts;
1201 ts_st->payload_flags = pkt->flags;
1204 memcpy(ts_st->payload + ts_st->payload_size, buf, size);
1205 ts_st->payload_size += size;
1212 static void mpegts_write_flush(AVFormatContext *s)
1216 /* flush current packets */
1217 for(i = 0; i < s->nb_streams; i++) {
1218 AVStream *st = s->streams[i];
1219 MpegTSWriteStream *ts_st = st->priv_data;
1220 if (ts_st->payload_size > 0) {
1221 mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_size,
1222 ts_st->payload_pts, ts_st->payload_dts,
1223 ts_st->payload_flags & AV_PKT_FLAG_KEY);
1224 ts_st->payload_size = 0;
1230 static int mpegts_write_packet(AVFormatContext *s, AVPacket *pkt)
1233 mpegts_write_flush(s);
1236 return mpegts_write_packet_internal(s, pkt);
1240 static int mpegts_write_end(AVFormatContext *s)
1242 MpegTSWrite *ts = s->priv_data;
1243 MpegTSService *service;
1246 mpegts_write_flush(s);
1248 for(i = 0; i < s->nb_streams; i++) {
1249 AVStream *st = s->streams[i];
1250 MpegTSWriteStream *ts_st = st->priv_data;
1251 av_freep(&ts_st->payload);
1253 avformat_free_context(ts_st->amux);
1258 for(i = 0; i < ts->nb_services; i++) {
1259 service = ts->services[i];
1260 av_freep(&service->provider_name);
1261 av_freep(&service->name);
1264 av_free(ts->services);
1269 AVOutputFormat ff_mpegts_muxer = {
1271 .long_name = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
1272 .mime_type = "video/x-mpegts",
1273 .extensions = "ts,m2t,m2ts,mts",
1274 .priv_data_size = sizeof(MpegTSWrite),
1275 .audio_codec = AV_CODEC_ID_MP2,
1276 .video_codec = AV_CODEC_ID_MPEG2VIDEO,
1277 .write_header = mpegts_write_header,
1278 .write_packet = mpegts_write_packet,
1279 .write_trailer = mpegts_write_end,
1280 .flags = AVFMT_ALLOW_FLUSH,
1281 .priv_class = &mpegts_muxer_class,