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/mathematics.h"
26 #include "libavutil/opt.h"
27 #include "libavutil/avassert.h"
28 #include "libavcodec/mpegvideo.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
73 int transport_stream_id;
74 int original_network_id;
82 static const AVOption options[] = {
83 { "mpegts_transport_stream_id", "Set transport_stream_id field.",
84 offsetof(MpegTSWrite, transport_stream_id), AV_OPT_TYPE_INT, {.dbl = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
85 { "mpegts_original_network_id", "Set original_network_id field.",
86 offsetof(MpegTSWrite, original_network_id), AV_OPT_TYPE_INT, {.dbl = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
87 { "mpegts_service_id", "Set service_id field.",
88 offsetof(MpegTSWrite, service_id), AV_OPT_TYPE_INT, {.dbl = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
89 { "mpegts_pmt_start_pid", "Set the first pid of the PMT.",
90 offsetof(MpegTSWrite, pmt_start_pid), AV_OPT_TYPE_INT, {.dbl = 0x1000 }, 0x0010, 0x1f00, AV_OPT_FLAG_ENCODING_PARAM},
91 { "mpegts_start_pid", "Set the first pid.",
92 offsetof(MpegTSWrite, start_pid), AV_OPT_TYPE_INT, {.dbl = 0x0100 }, 0x0100, 0x0f00, AV_OPT_FLAG_ENCODING_PARAM},
93 {"mpegts_m2ts_mode", "Enable m2ts mode.",
94 offsetof(MpegTSWrite, m2ts_mode), AV_OPT_TYPE_INT, {.dbl = -1 },
95 -1,1, AV_OPT_FLAG_ENCODING_PARAM},
96 { "muxrate", NULL, offsetof(MpegTSWrite, mux_rate), AV_OPT_TYPE_INT, {1}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
100 static const AVClass mpegts_muxer_class = {
101 .class_name = "MPEGTS muxer",
102 .item_name = av_default_item_name,
104 .version = LIBAVUTIL_VERSION_INT,
107 /* NOTE: 4 bytes must be left at the end for the crc32 */
108 static void mpegts_write_section(MpegTSSection *s, uint8_t *buf, int len)
111 unsigned char packet[TS_PACKET_SIZE];
112 const unsigned char *buf_ptr;
114 int first, b, len1, left;
116 crc = av_bswap32(av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1, buf, len - 4));
117 buf[len - 4] = (crc >> 24) & 0xff;
118 buf[len - 3] = (crc >> 16) & 0xff;
119 buf[len - 2] = (crc >> 8) & 0xff;
120 buf[len - 1] = (crc) & 0xff;
122 /* send each packet */
125 first = (buf == buf_ptr);
133 s->cc = (s->cc + 1) & 0xf;
136 *q++ = 0; /* 0 offset */
137 len1 = TS_PACKET_SIZE - (q - packet);
140 memcpy(q, buf_ptr, len1);
142 /* add known padding data */
143 left = TS_PACKET_SIZE - (q - packet);
145 memset(q, 0xff, left);
147 s->write_packet(s, packet);
154 static inline void put16(uint8_t **q_ptr, int val)
163 static int mpegts_write_section1(MpegTSSection *s, int tid, int id,
164 int version, int sec_num, int last_sec_num,
165 uint8_t *buf, int len)
167 uint8_t section[1024], *q;
168 unsigned int tot_len;
169 /* reserved_future_use field must be set to 1 for SDT */
170 unsigned int flags = tid == SDT_TID ? 0xf000 : 0xb000;
172 tot_len = 3 + 5 + len + 4;
173 /* check if not too big */
179 put16(&q, flags | (len + 5 + 4)); /* 5 byte header + 4 byte CRC */
181 *q++ = 0xc1 | (version << 1); /* current_next_indicator = 1 */
186 mpegts_write_section(s, section, tot_len);
190 /*********************************************/
193 #define DEFAULT_PROVIDER_NAME "FFmpeg"
194 #define DEFAULT_SERVICE_NAME "Service01"
196 /* a PES packet header is generated every DEFAULT_PES_HEADER_FREQ packets */
197 #define DEFAULT_PES_HEADER_FREQ 16
198 #define DEFAULT_PES_PAYLOAD_SIZE ((DEFAULT_PES_HEADER_FREQ - 1) * 184 + 170)
200 /* we retransmit the SI info at this rate */
201 #define SDT_RETRANS_TIME 500
202 #define PAT_RETRANS_TIME 100
203 #define PCR_RETRANS_TIME 20
205 typedef struct MpegTSWriteStream {
206 struct MpegTSService *service;
207 int pid; /* stream associated pid */
210 int first_pts_check; ///< first pts check needed
214 uint8_t payload[DEFAULT_PES_PAYLOAD_SIZE];
218 static void mpegts_write_pat(AVFormatContext *s)
220 MpegTSWrite *ts = s->priv_data;
221 MpegTSService *service;
222 uint8_t data[1012], *q;
226 for(i = 0; i < ts->nb_services; i++) {
227 service = ts->services[i];
228 put16(&q, service->sid);
229 put16(&q, 0xe000 | service->pmt.pid);
231 mpegts_write_section1(&ts->pat, PAT_TID, ts->tsid, 0, 0, 0,
235 static void mpegts_write_pmt(AVFormatContext *s, MpegTSService *service)
237 // MpegTSWrite *ts = s->priv_data;
238 uint8_t data[1012], *q, *desc_length_ptr, *program_info_length_ptr;
239 int val, stream_type, i;
242 put16(&q, 0xe000 | service->pcr_pid);
244 program_info_length_ptr = q;
245 q += 2; /* patched after */
247 /* put program info here */
249 val = 0xf000 | (q - program_info_length_ptr - 2);
250 program_info_length_ptr[0] = val >> 8;
251 program_info_length_ptr[1] = val;
253 for(i = 0; i < s->nb_streams; i++) {
254 AVStream *st = s->streams[i];
255 MpegTSWriteStream *ts_st = st->priv_data;
256 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
257 switch(st->codec->codec_id) {
258 case CODEC_ID_MPEG1VIDEO:
259 case CODEC_ID_MPEG2VIDEO:
260 stream_type = STREAM_TYPE_VIDEO_MPEG2;
263 stream_type = STREAM_TYPE_VIDEO_MPEG4;
266 stream_type = STREAM_TYPE_VIDEO_H264;
269 stream_type = STREAM_TYPE_VIDEO_DIRAC;
273 stream_type = STREAM_TYPE_AUDIO_MPEG1;
276 stream_type = STREAM_TYPE_AUDIO_AAC;
278 case CODEC_ID_AAC_LATM:
279 stream_type = STREAM_TYPE_AUDIO_AAC_LATM;
282 stream_type = STREAM_TYPE_AUDIO_AC3;
285 stream_type = STREAM_TYPE_PRIVATE_DATA;
289 put16(&q, 0xe000 | ts_st->pid);
291 q += 2; /* patched after */
293 /* write optional descriptors here */
294 switch(st->codec->codec_type) {
295 case AVMEDIA_TYPE_AUDIO:
296 if(st->codec->codec_id==CODEC_ID_EAC3){
297 *q++=0x7a; // EAC3 descriptor see A038 DVB SI
298 *q++=1; // 1 byte, all flags sets to 0
299 *q++=0; // omit all fields...
304 char *next = lang->value;
307 *q++ = 0x0a; /* ISO 639 language descriptor */
311 for (p = lang->value; next && *len_ptr < 255 / 4 * 4; p = next + 1) {
312 next = strchr(p, ',');
313 if (strlen(p) != 3 && (!next || next != p + 3))
314 continue; /* not a 3-letter code */
320 if (st->disposition & AV_DISPOSITION_CLEAN_EFFECTS)
322 else if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
324 else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
327 *q++ = 0; /* undefined type */
333 q -= 2; /* no language codes were written */
336 case AVMEDIA_TYPE_SUBTITLE:
338 const char *language;
339 language = lang && strlen(lang->value)==3 ? lang->value : "eng";
345 *q++ = 0x10; /* normal subtitles (0x20 = if hearing pb) */
346 if(st->codec->extradata_size == 4) {
347 memcpy(q, st->codec->extradata, 4);
350 put16(&q, 1); /* page id */
351 put16(&q, 1); /* ancillary page id */
355 case AVMEDIA_TYPE_VIDEO:
356 if (stream_type == STREAM_TYPE_VIDEO_DIRAC) {
357 *q++ = 0x05; /*MPEG-2 registration descriptor*/
367 val = 0xf000 | (q - desc_length_ptr - 2);
368 desc_length_ptr[0] = val >> 8;
369 desc_length_ptr[1] = val;
371 mpegts_write_section1(&service->pmt, PMT_TID, service->sid, 0, 0, 0,
375 /* NOTE: str == NULL is accepted for an empty string */
376 static void putstr8(uint8_t **q_ptr, const char *str)
392 static void mpegts_write_sdt(AVFormatContext *s)
394 MpegTSWrite *ts = s->priv_data;
395 MpegTSService *service;
396 uint8_t data[1012], *q, *desc_list_len_ptr, *desc_len_ptr;
397 int i, running_status, free_ca_mode, val;
402 for(i = 0; i < ts->nb_services; i++) {
403 service = ts->services[i];
404 put16(&q, service->sid);
405 *q++ = 0xfc | 0x00; /* currently no EIT info */
406 desc_list_len_ptr = q;
408 running_status = 4; /* running */
411 /* write only one descriptor for the service name and provider */
415 *q++ = 0x01; /* digital television service */
416 putstr8(&q, service->provider_name);
417 putstr8(&q, service->name);
418 desc_len_ptr[0] = q - desc_len_ptr - 1;
420 /* fill descriptor length */
421 val = (running_status << 13) | (free_ca_mode << 12) |
422 (q - desc_list_len_ptr - 2);
423 desc_list_len_ptr[0] = val >> 8;
424 desc_list_len_ptr[1] = val;
426 mpegts_write_section1(&ts->sdt, SDT_TID, ts->tsid, 0, 0, 0,
430 static MpegTSService *mpegts_add_service(MpegTSWrite *ts,
432 const char *provider_name,
435 MpegTSService *service;
437 service = av_mallocz(sizeof(MpegTSService));
440 service->pmt.pid = ts->pmt_start_pid + ts->nb_services;
442 service->provider_name = av_strdup(provider_name);
443 service->name = av_strdup(name);
444 service->pcr_pid = 0x1fff;
445 dynarray_add(&ts->services, &ts->nb_services, service);
449 static int64_t get_pcr(const MpegTSWrite *ts, AVIOContext *pb)
451 return av_rescale(avio_tell(pb) + 11, 8 * PCR_TIME_BASE, ts->mux_rate) +
455 static void mpegts_prefix_m2ts_header(AVFormatContext *s)
457 MpegTSWrite *ts = s->priv_data;
459 int64_t pcr = get_pcr(s->priv_data, s->pb);
460 uint32_t tp_extra_header = pcr % 0x3fffffff;
461 tp_extra_header = AV_RB32(&tp_extra_header);
462 avio_write(s->pb, (unsigned char *) &tp_extra_header,
463 sizeof(tp_extra_header));
467 static void section_write_packet(MpegTSSection *s, const uint8_t *packet)
469 AVFormatContext *ctx = s->opaque;
470 mpegts_prefix_m2ts_header(ctx);
471 avio_write(ctx->pb, packet, TS_PACKET_SIZE);
474 static int mpegts_write_header(AVFormatContext *s)
476 MpegTSWrite *ts = s->priv_data;
477 MpegTSWriteStream *ts_st;
478 MpegTSService *service;
479 AVStream *st, *pcr_st = NULL;
480 AVDictionaryEntry *title, *provider;
482 const char *service_name;
483 const char *provider_name;
486 ts->tsid = ts->transport_stream_id;
487 ts->onid = ts->original_network_id;
488 /* allocate a single DVB service */
489 title = av_dict_get(s->metadata, "service_name", NULL, 0);
491 title = av_dict_get(s->metadata, "title", NULL, 0);
492 service_name = title ? title->value : DEFAULT_SERVICE_NAME;
493 provider = av_dict_get(s->metadata, "service_provider", NULL, 0);
494 provider_name = provider ? provider->value : DEFAULT_PROVIDER_NAME;
495 service = mpegts_add_service(ts, ts->service_id, provider_name, service_name);
496 service->pmt.write_packet = section_write_packet;
497 service->pmt.opaque = s;
498 service->pmt.cc = 15;
500 ts->pat.pid = PAT_PID;
501 ts->pat.cc = 15; // Initialize at 15 so that it wraps and be equal to 0 for the first packet we write
502 ts->pat.write_packet = section_write_packet;
505 ts->sdt.pid = SDT_PID;
507 ts->sdt.write_packet = section_write_packet;
510 pids = av_malloc(s->nb_streams * sizeof(*pids));
512 return AVERROR(ENOMEM);
514 /* assign pids to each stream */
515 for(i = 0;i < s->nb_streams; i++) {
517 avpriv_set_pts_info(st, 33, 1, 90000);
518 ts_st = av_mallocz(sizeof(MpegTSWriteStream));
521 st->priv_data = ts_st;
522 ts_st->service = service;
523 /* MPEG pid values < 16 are reserved. Applications which set st->id in
524 * this range are assigned a calculated pid. */
526 ts_st->pid = ts->start_pid + i;
527 } else if (st->id < 0x1FFF) {
530 av_log(s, AV_LOG_ERROR, "Invalid stream id %d, must be less than 8191\n", st->id);
533 if (ts_st->pid == service->pmt.pid) {
534 av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
537 for (j = 0; j < i; j++)
538 if (pids[j] == ts_st->pid) {
539 av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
542 pids[i] = ts_st->pid;
543 ts_st->payload_pts = AV_NOPTS_VALUE;
544 ts_st->payload_dts = AV_NOPTS_VALUE;
545 ts_st->first_pts_check = 1;
547 /* update PCR pid by using the first video stream */
548 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
549 service->pcr_pid == 0x1fff) {
550 service->pcr_pid = ts_st->pid;
553 if (st->codec->codec_id == CODEC_ID_AAC &&
554 st->codec->extradata_size > 0) {
555 ts_st->adts = av_mallocz(sizeof(*ts_st->adts));
557 return AVERROR(ENOMEM);
558 if (ff_adts_decode_extradata(s, ts_st->adts, st->codec->extradata,
559 st->codec->extradata_size) < 0)
566 /* if no video stream, use the first stream as PCR */
567 if (service->pcr_pid == 0x1fff && s->nb_streams > 0) {
568 pcr_st = s->streams[0];
569 ts_st = pcr_st->priv_data;
570 service->pcr_pid = ts_st->pid;
575 ts->mux_rate = s->mux_rate;
578 if (ts->mux_rate > 1) {
579 service->pcr_packet_period = (ts->mux_rate * PCR_RETRANS_TIME) /
580 (TS_PACKET_SIZE * 8 * 1000);
581 ts->sdt_packet_period = (ts->mux_rate * SDT_RETRANS_TIME) /
582 (TS_PACKET_SIZE * 8 * 1000);
583 ts->pat_packet_period = (ts->mux_rate * PAT_RETRANS_TIME) /
584 (TS_PACKET_SIZE * 8 * 1000);
586 ts->first_pcr = av_rescale(s->max_delay, PCR_TIME_BASE, AV_TIME_BASE);
588 /* Arbitrary values, PAT/PMT could be written on key frames */
589 ts->sdt_packet_period = 200;
590 ts->pat_packet_period = 40;
591 if (pcr_st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
592 if (!pcr_st->codec->frame_size) {
593 av_log(s, AV_LOG_WARNING, "frame size not set\n");
594 service->pcr_packet_period =
595 pcr_st->codec->sample_rate/(10*512);
597 service->pcr_packet_period =
598 pcr_st->codec->sample_rate/(10*pcr_st->codec->frame_size);
601 // max delta PCR 0.1s
602 service->pcr_packet_period =
603 pcr_st->codec->time_base.den/(10*pcr_st->codec->time_base.num);
607 // output a PCR as soon as possible
608 service->pcr_packet_count = service->pcr_packet_period;
609 ts->pat_packet_count = ts->pat_packet_period-1;
610 ts->sdt_packet_count = ts->sdt_packet_period-1;
612 if (ts->mux_rate == 1)
613 av_log(s, AV_LOG_INFO, "muxrate VBR, ");
615 av_log(s, AV_LOG_INFO, "muxrate %d, ", ts->mux_rate);
616 av_log(s, AV_LOG_INFO, "pcr every %d pkts, "
617 "sdt every %d, pat/pmt every %d pkts\n",
618 service->pcr_packet_period,
619 ts->sdt_packet_period, ts->pat_packet_period);
621 if (ts->m2ts_mode == -1) {
622 if (av_match_ext(s->filename, "m2ts")) {
635 for(i = 0;i < s->nb_streams; i++) {
637 av_freep(&st->priv_data);
642 /* send SDT, PAT and PMT tables regulary */
643 static void retransmit_si_info(AVFormatContext *s)
645 MpegTSWrite *ts = s->priv_data;
648 if (++ts->sdt_packet_count == ts->sdt_packet_period) {
649 ts->sdt_packet_count = 0;
652 if (++ts->pat_packet_count == ts->pat_packet_period) {
653 ts->pat_packet_count = 0;
655 for(i = 0; i < ts->nb_services; i++) {
656 mpegts_write_pmt(s, ts->services[i]);
661 static int write_pcr_bits(uint8_t *buf, int64_t pcr)
663 int64_t pcr_low = pcr % 300, pcr_high = pcr / 300;
665 *buf++ = pcr_high >> 25;
666 *buf++ = pcr_high >> 17;
667 *buf++ = pcr_high >> 9;
668 *buf++ = pcr_high >> 1;
669 *buf++ = pcr_high << 7 | pcr_low >> 8 | 0x7e;
675 /* Write a single null transport stream packet */
676 static void mpegts_insert_null_packet(AVFormatContext *s)
679 uint8_t buf[TS_PACKET_SIZE];
686 memset(q, 0x0FF, TS_PACKET_SIZE - (q - buf));
687 mpegts_prefix_m2ts_header(s);
688 avio_write(s->pb, buf, TS_PACKET_SIZE);
691 /* Write a single transport stream packet with a PCR and no payload */
692 static void mpegts_insert_pcr_only(AVFormatContext *s, AVStream *st)
694 MpegTSWrite *ts = s->priv_data;
695 MpegTSWriteStream *ts_st = st->priv_data;
697 uint8_t buf[TS_PACKET_SIZE];
701 *q++ = ts_st->pid >> 8;
703 *q++ = 0x20 | ts_st->cc; /* Adaptation only */
704 /* Continuity Count field does not increment (see 13818-1 section 2.4.3.3) */
705 *q++ = TS_PACKET_SIZE - 5; /* Adaptation Field Length */
706 *q++ = 0x10; /* Adaptation flags: PCR present */
708 /* PCR coded into 6 bytes */
709 q += write_pcr_bits(q, get_pcr(ts, s->pb));
712 memset(q, 0xFF, TS_PACKET_SIZE - (q - buf));
713 mpegts_prefix_m2ts_header(s);
714 avio_write(s->pb, buf, TS_PACKET_SIZE);
717 static void write_pts(uint8_t *q, int fourbits, int64_t pts)
721 val = fourbits << 4 | (((pts >> 30) & 0x07) << 1) | 1;
723 val = (((pts >> 15) & 0x7fff) << 1) | 1;
726 val = (((pts) & 0x7fff) << 1) | 1;
731 /* Set an adaptation field flag in an MPEG-TS packet*/
732 static void set_af_flag(uint8_t *pkt, int flag)
734 // expect at least one flag to set
737 if ((pkt[3] & 0x20) == 0) {
738 // no AF yet, set adaptation field flag
740 // 1 byte length, no flags
747 /* Extend the adaptation field by size bytes */
748 static void extend_af(uint8_t *pkt, int size)
750 // expect already existing adaptation field
751 assert(pkt[3] & 0x20);
755 /* Get a pointer to MPEG-TS payload (right after TS packet header) */
756 static uint8_t *get_ts_payload_start(uint8_t *pkt)
759 return pkt + 5 + pkt[4];
764 /* Add a pes header to the front of payload, and segment into an integer number of
765 * ts packets. The final ts packet is padded using an over-sized adaptation header
766 * to exactly fill the last ts packet.
767 * NOTE: 'payload' contains a complete PES payload.
769 static void mpegts_write_pes(AVFormatContext *s, AVStream *st,
770 const uint8_t *payload, int payload_size,
771 int64_t pts, int64_t dts, int key)
773 MpegTSWriteStream *ts_st = st->priv_data;
774 MpegTSWrite *ts = s->priv_data;
775 uint8_t buf[TS_PACKET_SIZE];
777 int val, is_start, len, header_len, write_pcr, private_code, flags;
778 int afc_len, stuffing_len;
779 int64_t pcr = -1; /* avoid warning */
780 int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE);
783 while (payload_size > 0) {
784 retransmit_si_info(s);
787 if (ts_st->pid == ts_st->service->pcr_pid) {
788 if (ts->mux_rate > 1 || is_start) // VBR pcr period is based on frames
789 ts_st->service->pcr_packet_count++;
790 if (ts_st->service->pcr_packet_count >=
791 ts_st->service->pcr_packet_period) {
792 ts_st->service->pcr_packet_count = 0;
797 if (ts->mux_rate > 1 && dts != AV_NOPTS_VALUE &&
798 (dts - get_pcr(ts, s->pb)/300) > delay) {
799 /* pcr insert gets priority over null packet insert */
801 mpegts_insert_pcr_only(s, st);
803 mpegts_insert_null_packet(s);
804 continue; /* recalculate write_pcr and possibly retransmit si_info */
807 /* prepare packet header */
810 val = (ts_st->pid >> 8);
815 ts_st->cc = (ts_st->cc + 1) & 0xf;
816 *q++ = 0x10 | ts_st->cc; // payload indicator + CC
817 if (key && is_start && pts != AV_NOPTS_VALUE) {
818 // set Random Access for key frames
819 if (ts_st->pid == ts_st->service->pcr_pid)
821 set_af_flag(buf, 0x40);
822 q = get_ts_payload_start(buf);
825 set_af_flag(buf, 0x10);
826 q = get_ts_payload_start(buf);
827 // add 11, pcr references the last byte of program clock reference base
828 if (ts->mux_rate > 1)
829 pcr = get_pcr(ts, s->pb);
831 pcr = (dts - delay)*300;
832 if (dts != AV_NOPTS_VALUE && dts < pcr / 300)
833 av_log(s, AV_LOG_WARNING, "dts < pcr, TS is invalid\n");
834 extend_af(buf, write_pcr_bits(q, pcr));
835 q = get_ts_payload_start(buf);
838 int pes_extension = 0;
839 /* write PES header */
844 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
845 if (st->codec->codec_id == CODEC_ID_DIRAC) {
849 } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
850 (st->codec->codec_id == CODEC_ID_MP2 ||
851 st->codec->codec_id == CODEC_ID_MP3 ||
852 st->codec->codec_id == CODEC_ID_AAC)) {
856 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
862 if (pts != AV_NOPTS_VALUE) {
866 if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
870 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
871 st->codec->codec_id == CODEC_ID_DIRAC) {
872 /* set PES_extension_flag */
877 * One byte for PES2 extension flag +
878 * one byte for extension length +
879 * one byte for extension id
883 len = payload_size + header_len + 3;
884 if (private_code != 0)
891 /* data alignment indicator is required for subtitle data */
892 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)
897 if (pts != AV_NOPTS_VALUE) {
898 write_pts(q, flags >> 6, pts);
901 if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
902 write_pts(q, 1, dts);
905 if (pes_extension && st->codec->codec_id == CODEC_ID_DIRAC) {
906 flags = 0x01; /* set PES_extension_flag_2 */
908 *q++ = 0x80 | 0x01; /* marker bit + extension length */
910 * Set the stream id extension flag bit to 0 and
911 * write the extended stream id
915 if (private_code != 0)
920 header_len = q - buf;
922 len = TS_PACKET_SIZE - header_len;
923 if (len > payload_size)
925 stuffing_len = TS_PACKET_SIZE - header_len - len;
926 if (stuffing_len > 0) {
927 /* add stuffing with AFC */
929 /* stuffing already present: increase its size */
930 afc_len = buf[4] + 1;
931 memmove(buf + 4 + afc_len + stuffing_len,
933 header_len - (4 + afc_len));
934 buf[4] += stuffing_len;
935 memset(buf + 4 + afc_len, 0xff, stuffing_len);
938 memmove(buf + 4 + stuffing_len, buf + 4, header_len - 4);
940 buf[4] = stuffing_len - 1;
941 if (stuffing_len >= 2) {
943 memset(buf + 6, 0xff, stuffing_len - 2);
947 memcpy(buf + TS_PACKET_SIZE - len, payload, len);
950 mpegts_prefix_m2ts_header(s);
951 avio_write(s->pb, buf, TS_PACKET_SIZE);
956 static int mpegts_write_packet(AVFormatContext *s, AVPacket *pkt)
958 AVStream *st = s->streams[pkt->stream_index];
959 int size = pkt->size;
960 uint8_t *buf= pkt->data;
962 MpegTSWriteStream *ts_st = st->priv_data;
963 const uint64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE)*2;
964 int64_t dts = AV_NOPTS_VALUE, pts = AV_NOPTS_VALUE;
966 if (pkt->pts != AV_NOPTS_VALUE)
967 pts = pkt->pts + delay;
968 if (pkt->dts != AV_NOPTS_VALUE)
969 dts = pkt->dts + delay;
971 if (ts_st->first_pts_check && pts == AV_NOPTS_VALUE) {
972 av_log(s, AV_LOG_ERROR, "first pts value must set\n");
975 ts_st->first_pts_check = 0;
977 if (st->codec->codec_id == CODEC_ID_H264) {
978 const uint8_t *p = buf, *buf_end = p+size;
981 if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001) {
982 av_log(s, AV_LOG_ERROR, "H.264 bitstream malformed, "
983 "no startcode found, use -vbsf h264_mp4toannexb\n");
988 p = avpriv_mpv_find_start_code(p, buf_end, &state);
989 //av_log(s, AV_LOG_INFO, "nal %d\n", state & 0x1f);
990 } while (p < buf_end && (state & 0x1f) != 9 &&
991 (state & 0x1f) != 5 && (state & 0x1f) != 1);
993 if ((state & 0x1f) != 9) { // AUD NAL
994 data = av_malloc(pkt->size+6);
997 memcpy(data+6, pkt->data, pkt->size);
998 AV_WB32(data, 0x00000001);
1000 data[5] = 0xf0; // any slice type (0xe) + rbsp stop one bit
1004 } else if (st->codec->codec_id == CODEC_ID_AAC) {
1007 if ((AV_RB16(pkt->data) & 0xfff0) != 0xfff0) {
1008 ADTSContext *adts = ts_st->adts;
1011 av_log(s, AV_LOG_ERROR, "aac bitstream not in adts format "
1012 "and extradata missing\n");
1015 new_size = ADTS_HEADER_SIZE+adts->pce_size+pkt->size;
1016 if ((unsigned)new_size >= INT_MAX)
1018 data = av_malloc(new_size);
1020 return AVERROR(ENOMEM);
1021 err = ff_adts_write_frame_header(adts, data, pkt->size,
1027 if (adts->pce_size) {
1028 memcpy(data+ADTS_HEADER_SIZE, adts->pce_data, adts->pce_size);
1031 memcpy(data+ADTS_HEADER_SIZE+adts->pce_size, pkt->data, pkt->size);
1037 if (ts_st->payload_size && ts_st->payload_size + size > DEFAULT_PES_PAYLOAD_SIZE) {
1038 mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_size,
1039 ts_st->payload_pts, ts_st->payload_dts,
1040 ts_st->payload_flags & AV_PKT_FLAG_KEY);
1041 ts_st->payload_size = 0;
1044 if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO || size > DEFAULT_PES_PAYLOAD_SIZE) {
1045 av_assert0(!ts_st->payload_size);
1046 // for video and subtitle, write a single pes packet
1047 mpegts_write_pes(s, st, buf, size, pts, dts, pkt->flags & AV_PKT_FLAG_KEY);
1052 if (!ts_st->payload_size) {
1053 ts_st->payload_pts = pts;
1054 ts_st->payload_dts = dts;
1055 ts_st->payload_flags = pkt->flags;
1058 memcpy(ts_st->payload + ts_st->payload_size, buf, size);
1059 ts_st->payload_size += size;
1066 static int mpegts_write_end(AVFormatContext *s)
1068 MpegTSWrite *ts = s->priv_data;
1069 MpegTSWriteStream *ts_st;
1070 MpegTSService *service;
1074 /* flush current packets */
1075 for(i = 0; i < s->nb_streams; i++) {
1077 ts_st = st->priv_data;
1078 if (ts_st->payload_size > 0) {
1079 mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_size,
1080 ts_st->payload_pts, ts_st->payload_dts,
1081 ts_st->payload_flags & AV_PKT_FLAG_KEY);
1083 av_freep(&ts_st->adts);
1087 for(i = 0; i < ts->nb_services; i++) {
1088 service = ts->services[i];
1089 av_freep(&service->provider_name);
1090 av_freep(&service->name);
1093 av_free(ts->services);
1098 AVOutputFormat ff_mpegts_muxer = {
1100 .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
1101 .mime_type = "video/x-mpegts",
1102 .extensions = "ts,m2t,m2ts,mts",
1103 .priv_data_size = sizeof(MpegTSWrite),
1104 .audio_codec = CODEC_ID_MP2,
1105 .video_codec = CODEC_ID_MPEG2VIDEO,
1106 .write_header = mpegts_write_header,
1107 .write_packet = mpegts_write_packet,
1108 .write_trailer = mpegts_write_end,
1109 .priv_class = &mpegts_muxer_class,