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
74 int transport_stream_id;
75 int original_network_id;
85 /* a PES packet header is generated every DEFAULT_PES_HEADER_FREQ packets */
86 #define DEFAULT_PES_HEADER_FREQ 16
87 #define DEFAULT_PES_PAYLOAD_SIZE ((DEFAULT_PES_HEADER_FREQ - 1) * 184 + 170)
89 static const AVOption options[] = {
90 { "mpegts_transport_stream_id", "Set transport_stream_id field.",
91 offsetof(MpegTSWrite, transport_stream_id), AV_OPT_TYPE_INT, {.dbl = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
92 { "mpegts_original_network_id", "Set original_network_id field.",
93 offsetof(MpegTSWrite, original_network_id), AV_OPT_TYPE_INT, {.dbl = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
94 { "mpegts_service_id", "Set service_id field.",
95 offsetof(MpegTSWrite, service_id), AV_OPT_TYPE_INT, {.dbl = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
96 { "mpegts_pmt_start_pid", "Set the first pid of the PMT.",
97 offsetof(MpegTSWrite, pmt_start_pid), AV_OPT_TYPE_INT, {.dbl = 0x1000 }, 0x0010, 0x1f00, AV_OPT_FLAG_ENCODING_PARAM},
98 { "mpegts_start_pid", "Set the first pid.",
99 offsetof(MpegTSWrite, start_pid), AV_OPT_TYPE_INT, {.dbl = 0x0100 }, 0x0100, 0x0f00, AV_OPT_FLAG_ENCODING_PARAM},
100 {"mpegts_m2ts_mode", "Enable m2ts mode.",
101 offsetof(MpegTSWrite, m2ts_mode), AV_OPT_TYPE_INT, {.dbl = -1 },
102 -1,1, AV_OPT_FLAG_ENCODING_PARAM},
103 { "muxrate", NULL, offsetof(MpegTSWrite, mux_rate), AV_OPT_TYPE_INT, {1}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
104 { "pes_payload_size", "Minimum PES packet payload in bytes",
105 offsetof(MpegTSWrite, pes_payload_size), AV_OPT_TYPE_INT, {DEFAULT_PES_PAYLOAD_SIZE}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
106 { "resend_headers", "Reemit PAT/PMT before writing the next packet",
107 offsetof(MpegTSWrite, reemit_pat_pmt), AV_OPT_TYPE_INT, {0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
111 static const AVClass mpegts_muxer_class = {
112 .class_name = "MPEGTS muxer",
113 .item_name = av_default_item_name,
115 .version = LIBAVUTIL_VERSION_INT,
118 /* NOTE: 4 bytes must be left at the end for the crc32 */
119 static void mpegts_write_section(MpegTSSection *s, uint8_t *buf, int len)
122 unsigned char packet[TS_PACKET_SIZE];
123 const unsigned char *buf_ptr;
125 int first, b, len1, left;
127 crc = av_bswap32(av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1, buf, len - 4));
128 buf[len - 4] = (crc >> 24) & 0xff;
129 buf[len - 3] = (crc >> 16) & 0xff;
130 buf[len - 2] = (crc >> 8) & 0xff;
131 buf[len - 1] = (crc) & 0xff;
133 /* send each packet */
136 first = (buf == buf_ptr);
144 s->cc = (s->cc + 1) & 0xf;
147 *q++ = 0; /* 0 offset */
148 len1 = TS_PACKET_SIZE - (q - packet);
151 memcpy(q, buf_ptr, len1);
153 /* add known padding data */
154 left = TS_PACKET_SIZE - (q - packet);
156 memset(q, 0xff, left);
158 s->write_packet(s, packet);
165 static inline void put16(uint8_t **q_ptr, int val)
174 static int mpegts_write_section1(MpegTSSection *s, int tid, int id,
175 int version, int sec_num, int last_sec_num,
176 uint8_t *buf, int len)
178 uint8_t section[1024], *q;
179 unsigned int tot_len;
180 /* reserved_future_use field must be set to 1 for SDT */
181 unsigned int flags = tid == SDT_TID ? 0xf000 : 0xb000;
183 tot_len = 3 + 5 + len + 4;
184 /* check if not too big */
186 return AVERROR_INVALIDDATA;
190 put16(&q, flags | (len + 5 + 4)); /* 5 byte header + 4 byte CRC */
192 *q++ = 0xc1 | (version << 1); /* current_next_indicator = 1 */
197 mpegts_write_section(s, section, tot_len);
201 /*********************************************/
204 #define DEFAULT_PROVIDER_NAME "FFmpeg"
205 #define DEFAULT_SERVICE_NAME "Service01"
207 /* we retransmit the SI info at this rate */
208 #define SDT_RETRANS_TIME 500
209 #define PAT_RETRANS_TIME 100
210 #define PCR_RETRANS_TIME 20
212 typedef struct MpegTSWriteStream {
213 struct MpegTSService *service;
214 int pid; /* stream associated pid */
217 int first_pts_check; ///< first pts check needed
218 int prev_payload_key;
226 static void mpegts_write_pat(AVFormatContext *s)
228 MpegTSWrite *ts = s->priv_data;
229 MpegTSService *service;
230 uint8_t data[1012], *q;
234 for(i = 0; i < ts->nb_services; i++) {
235 service = ts->services[i];
236 put16(&q, service->sid);
237 put16(&q, 0xe000 | service->pmt.pid);
239 mpegts_write_section1(&ts->pat, PAT_TID, ts->tsid, 0, 0, 0,
243 static void mpegts_write_pmt(AVFormatContext *s, MpegTSService *service)
245 // MpegTSWrite *ts = s->priv_data;
246 uint8_t data[1012], *q, *desc_length_ptr, *program_info_length_ptr;
247 int val, stream_type, i;
250 put16(&q, 0xe000 | service->pcr_pid);
252 program_info_length_ptr = q;
253 q += 2; /* patched after */
255 /* put program info here */
257 val = 0xf000 | (q - program_info_length_ptr - 2);
258 program_info_length_ptr[0] = val >> 8;
259 program_info_length_ptr[1] = val;
261 for(i = 0; i < s->nb_streams; i++) {
262 AVStream *st = s->streams[i];
263 MpegTSWriteStream *ts_st = st->priv_data;
264 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
265 switch(st->codec->codec_id) {
266 case CODEC_ID_MPEG1VIDEO:
267 case CODEC_ID_MPEG2VIDEO:
268 stream_type = STREAM_TYPE_VIDEO_MPEG2;
271 stream_type = STREAM_TYPE_VIDEO_MPEG4;
274 stream_type = STREAM_TYPE_VIDEO_H264;
277 stream_type = STREAM_TYPE_VIDEO_DIRAC;
281 stream_type = STREAM_TYPE_AUDIO_MPEG1;
284 stream_type = STREAM_TYPE_AUDIO_AAC;
286 case CODEC_ID_AAC_LATM:
287 stream_type = STREAM_TYPE_AUDIO_AAC_LATM;
290 stream_type = STREAM_TYPE_AUDIO_AC3;
293 stream_type = STREAM_TYPE_PRIVATE_DATA;
297 put16(&q, 0xe000 | ts_st->pid);
299 q += 2; /* patched after */
301 /* write optional descriptors here */
302 switch(st->codec->codec_type) {
303 case AVMEDIA_TYPE_AUDIO:
304 if(st->codec->codec_id==CODEC_ID_EAC3){
305 *q++=0x7a; // EAC3 descriptor see A038 DVB SI
306 *q++=1; // 1 byte, all flags sets to 0
307 *q++=0; // omit all fields...
312 char *next = lang->value;
315 *q++ = 0x0a; /* ISO 639 language descriptor */
319 for (p = lang->value; next && *len_ptr < 255 / 4 * 4; p = next + 1) {
320 next = strchr(p, ',');
321 if (strlen(p) != 3 && (!next || next != p + 3))
322 continue; /* not a 3-letter code */
328 if (st->disposition & AV_DISPOSITION_CLEAN_EFFECTS)
330 else if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
332 else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
335 *q++ = 0; /* undefined type */
341 q -= 2; /* no language codes were written */
344 case AVMEDIA_TYPE_SUBTITLE:
346 const char *language;
347 language = lang && strlen(lang->value)==3 ? lang->value : "eng";
353 *q++ = 0x10; /* normal subtitles (0x20 = if hearing pb) */
354 if(st->codec->extradata_size == 4) {
355 memcpy(q, st->codec->extradata, 4);
358 put16(&q, 1); /* page id */
359 put16(&q, 1); /* ancillary page id */
363 case AVMEDIA_TYPE_VIDEO:
364 if (stream_type == STREAM_TYPE_VIDEO_DIRAC) {
365 *q++ = 0x05; /*MPEG-2 registration descriptor*/
375 val = 0xf000 | (q - desc_length_ptr - 2);
376 desc_length_ptr[0] = val >> 8;
377 desc_length_ptr[1] = val;
379 mpegts_write_section1(&service->pmt, PMT_TID, service->sid, 0, 0, 0,
383 /* NOTE: str == NULL is accepted for an empty string */
384 static void putstr8(uint8_t **q_ptr, const char *str)
400 static void mpegts_write_sdt(AVFormatContext *s)
402 MpegTSWrite *ts = s->priv_data;
403 MpegTSService *service;
404 uint8_t data[1012], *q, *desc_list_len_ptr, *desc_len_ptr;
405 int i, running_status, free_ca_mode, val;
410 for(i = 0; i < ts->nb_services; i++) {
411 service = ts->services[i];
412 put16(&q, service->sid);
413 *q++ = 0xfc | 0x00; /* currently no EIT info */
414 desc_list_len_ptr = q;
416 running_status = 4; /* running */
419 /* write only one descriptor for the service name and provider */
423 *q++ = 0x01; /* digital television service */
424 putstr8(&q, service->provider_name);
425 putstr8(&q, service->name);
426 desc_len_ptr[0] = q - desc_len_ptr - 1;
428 /* fill descriptor length */
429 val = (running_status << 13) | (free_ca_mode << 12) |
430 (q - desc_list_len_ptr - 2);
431 desc_list_len_ptr[0] = val >> 8;
432 desc_list_len_ptr[1] = val;
434 mpegts_write_section1(&ts->sdt, SDT_TID, ts->tsid, 0, 0, 0,
438 static MpegTSService *mpegts_add_service(MpegTSWrite *ts,
440 const char *provider_name,
443 MpegTSService *service;
445 service = av_mallocz(sizeof(MpegTSService));
448 service->pmt.pid = ts->pmt_start_pid + ts->nb_services;
450 service->provider_name = av_strdup(provider_name);
451 service->name = av_strdup(name);
452 service->pcr_pid = 0x1fff;
453 dynarray_add(&ts->services, &ts->nb_services, service);
457 static int64_t get_pcr(const MpegTSWrite *ts, AVIOContext *pb)
459 return av_rescale(avio_tell(pb) + 11, 8 * PCR_TIME_BASE, ts->mux_rate) +
463 static void mpegts_prefix_m2ts_header(AVFormatContext *s)
465 MpegTSWrite *ts = s->priv_data;
467 int64_t pcr = get_pcr(s->priv_data, s->pb);
468 uint32_t tp_extra_header = pcr % 0x3fffffff;
469 tp_extra_header = AV_RB32(&tp_extra_header);
470 avio_write(s->pb, (unsigned char *) &tp_extra_header,
471 sizeof(tp_extra_header));
475 static void section_write_packet(MpegTSSection *s, const uint8_t *packet)
477 AVFormatContext *ctx = s->opaque;
478 mpegts_prefix_m2ts_header(ctx);
479 avio_write(ctx->pb, packet, TS_PACKET_SIZE);
482 static int mpegts_write_header(AVFormatContext *s)
484 MpegTSWrite *ts = s->priv_data;
485 MpegTSWriteStream *ts_st;
486 MpegTSService *service;
487 AVStream *st, *pcr_st = NULL;
488 AVDictionaryEntry *title, *provider;
490 const char *service_name;
491 const char *provider_name;
494 // round up to a whole number of TS packets
495 ts->pes_payload_size = (ts->pes_payload_size + 14 + 183) / 184 * 184 - 14;
497 ts->tsid = ts->transport_stream_id;
498 ts->onid = ts->original_network_id;
499 /* allocate a single DVB service */
500 title = av_dict_get(s->metadata, "service_name", NULL, 0);
502 title = av_dict_get(s->metadata, "title", NULL, 0);
503 service_name = title ? title->value : DEFAULT_SERVICE_NAME;
504 provider = av_dict_get(s->metadata, "service_provider", NULL, 0);
505 provider_name = provider ? provider->value : DEFAULT_PROVIDER_NAME;
506 service = mpegts_add_service(ts, ts->service_id, provider_name, service_name);
507 service->pmt.write_packet = section_write_packet;
508 service->pmt.opaque = s;
509 service->pmt.cc = 15;
511 ts->pat.pid = PAT_PID;
512 ts->pat.cc = 15; // Initialize at 15 so that it wraps and be equal to 0 for the first packet we write
513 ts->pat.write_packet = section_write_packet;
516 ts->sdt.pid = SDT_PID;
518 ts->sdt.write_packet = section_write_packet;
521 pids = av_malloc(s->nb_streams * sizeof(*pids));
523 return AVERROR(ENOMEM);
525 /* assign pids to each stream */
526 for(i = 0;i < s->nb_streams; i++) {
528 avpriv_set_pts_info(st, 33, 1, 90000);
529 ts_st = av_mallocz(sizeof(MpegTSWriteStream));
532 st->priv_data = ts_st;
533 ts_st->payload = av_mallocz(ts->pes_payload_size);
536 ts_st->service = service;
537 /* MPEG pid values < 16 are reserved. Applications which set st->id in
538 * this range are assigned a calculated pid. */
540 ts_st->pid = ts->start_pid + i;
541 } else if (st->id < 0x1FFF) {
544 av_log(s, AV_LOG_ERROR, "Invalid stream id %d, must be less than 8191\n", st->id);
547 if (ts_st->pid == service->pmt.pid) {
548 av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
551 for (j = 0; j < i; j++)
552 if (pids[j] == ts_st->pid) {
553 av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
556 pids[i] = ts_st->pid;
557 ts_st->payload_pts = AV_NOPTS_VALUE;
558 ts_st->payload_dts = AV_NOPTS_VALUE;
559 ts_st->first_pts_check = 1;
561 /* update PCR pid by using the first video stream */
562 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
563 service->pcr_pid == 0x1fff) {
564 service->pcr_pid = ts_st->pid;
567 if (st->codec->codec_id == CODEC_ID_AAC &&
568 st->codec->extradata_size > 0) {
569 ts_st->adts = av_mallocz(sizeof(*ts_st->adts));
572 if (ff_adts_decode_extradata(s, ts_st->adts, st->codec->extradata,
573 st->codec->extradata_size) < 0)
580 /* if no video stream, use the first stream as PCR */
581 if (service->pcr_pid == 0x1fff && s->nb_streams > 0) {
582 pcr_st = s->streams[0];
583 ts_st = pcr_st->priv_data;
584 service->pcr_pid = ts_st->pid;
587 if (ts->mux_rate > 1) {
588 service->pcr_packet_period = (ts->mux_rate * PCR_RETRANS_TIME) /
589 (TS_PACKET_SIZE * 8 * 1000);
590 ts->sdt_packet_period = (ts->mux_rate * SDT_RETRANS_TIME) /
591 (TS_PACKET_SIZE * 8 * 1000);
592 ts->pat_packet_period = (ts->mux_rate * PAT_RETRANS_TIME) /
593 (TS_PACKET_SIZE * 8 * 1000);
595 ts->first_pcr = av_rescale(s->max_delay, PCR_TIME_BASE, AV_TIME_BASE);
597 /* Arbitrary values, PAT/PMT will also be written on video key frames */
598 ts->sdt_packet_period = 200;
599 ts->pat_packet_period = 40;
600 if (pcr_st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
601 if (!pcr_st->codec->frame_size) {
602 av_log(s, AV_LOG_WARNING, "frame size not set\n");
603 service->pcr_packet_period =
604 pcr_st->codec->sample_rate/(10*512);
606 service->pcr_packet_period =
607 pcr_st->codec->sample_rate/(10*pcr_st->codec->frame_size);
610 // max delta PCR 0.1s
611 service->pcr_packet_period =
612 pcr_st->codec->time_base.den/(10*pcr_st->codec->time_base.num);
616 // output a PCR as soon as possible
617 service->pcr_packet_count = service->pcr_packet_period;
618 ts->pat_packet_count = ts->pat_packet_period-1;
619 ts->sdt_packet_count = ts->sdt_packet_period-1;
621 if (ts->mux_rate == 1)
622 av_log(s, AV_LOG_INFO, "muxrate VBR, ");
624 av_log(s, AV_LOG_INFO, "muxrate %d, ", ts->mux_rate);
625 av_log(s, AV_LOG_INFO, "pcr every %d pkts, "
626 "sdt every %d, pat/pmt every %d pkts\n",
627 service->pcr_packet_period,
628 ts->sdt_packet_period, ts->pat_packet_period);
630 if (ts->m2ts_mode == -1) {
631 if (av_match_ext(s->filename, "m2ts")) {
644 for(i = 0;i < s->nb_streams; i++) {
645 MpegTSWriteStream *ts_st;
647 ts_st = st->priv_data;
649 av_freep(&ts_st->payload);
650 av_freep(&ts_st->adts);
652 av_freep(&st->priv_data);
654 return AVERROR(EINVAL);
657 /* send SDT, PAT and PMT tables regulary */
658 static void retransmit_si_info(AVFormatContext *s, int force_pat)
660 MpegTSWrite *ts = s->priv_data;
663 if (++ts->sdt_packet_count == ts->sdt_packet_period) {
664 ts->sdt_packet_count = 0;
667 if (++ts->pat_packet_count == ts->pat_packet_period || force_pat) {
668 ts->pat_packet_count = 0;
670 for(i = 0; i < ts->nb_services; i++) {
671 mpegts_write_pmt(s, ts->services[i]);
676 static int write_pcr_bits(uint8_t *buf, int64_t pcr)
678 int64_t pcr_low = pcr % 300, pcr_high = pcr / 300;
680 *buf++ = pcr_high >> 25;
681 *buf++ = pcr_high >> 17;
682 *buf++ = pcr_high >> 9;
683 *buf++ = pcr_high >> 1;
684 *buf++ = pcr_high << 7 | pcr_low >> 8 | 0x7e;
690 /* Write a single null transport stream packet */
691 static void mpegts_insert_null_packet(AVFormatContext *s)
694 uint8_t buf[TS_PACKET_SIZE];
701 memset(q, 0x0FF, TS_PACKET_SIZE - (q - buf));
702 mpegts_prefix_m2ts_header(s);
703 avio_write(s->pb, buf, TS_PACKET_SIZE);
706 /* Write a single transport stream packet with a PCR and no payload */
707 static void mpegts_insert_pcr_only(AVFormatContext *s, AVStream *st)
709 MpegTSWrite *ts = s->priv_data;
710 MpegTSWriteStream *ts_st = st->priv_data;
712 uint8_t buf[TS_PACKET_SIZE];
716 *q++ = ts_st->pid >> 8;
718 *q++ = 0x20 | ts_st->cc; /* Adaptation only */
719 /* Continuity Count field does not increment (see 13818-1 section 2.4.3.3) */
720 *q++ = TS_PACKET_SIZE - 5; /* Adaptation Field Length */
721 *q++ = 0x10; /* Adaptation flags: PCR present */
723 /* PCR coded into 6 bytes */
724 q += write_pcr_bits(q, get_pcr(ts, s->pb));
727 memset(q, 0xFF, TS_PACKET_SIZE - (q - buf));
728 mpegts_prefix_m2ts_header(s);
729 avio_write(s->pb, buf, TS_PACKET_SIZE);
732 static void write_pts(uint8_t *q, int fourbits, int64_t pts)
736 val = fourbits << 4 | (((pts >> 30) & 0x07) << 1) | 1;
738 val = (((pts >> 15) & 0x7fff) << 1) | 1;
741 val = (((pts) & 0x7fff) << 1) | 1;
746 /* Set an adaptation field flag in an MPEG-TS packet*/
747 static void set_af_flag(uint8_t *pkt, int flag)
749 // expect at least one flag to set
752 if ((pkt[3] & 0x20) == 0) {
753 // no AF yet, set adaptation field flag
755 // 1 byte length, no flags
762 /* Extend the adaptation field by size bytes */
763 static void extend_af(uint8_t *pkt, int size)
765 // expect already existing adaptation field
766 assert(pkt[3] & 0x20);
770 /* Get a pointer to MPEG-TS payload (right after TS packet header) */
771 static uint8_t *get_ts_payload_start(uint8_t *pkt)
774 return pkt + 5 + pkt[4];
779 /* Add a pes header to the front of payload, and segment into an integer number of
780 * ts packets. The final ts packet is padded using an over-sized adaptation header
781 * to exactly fill the last ts packet.
782 * NOTE: 'payload' contains a complete PES payload.
784 static void mpegts_write_pes(AVFormatContext *s, AVStream *st,
785 const uint8_t *payload, int payload_size,
786 int64_t pts, int64_t dts, int key)
788 MpegTSWriteStream *ts_st = st->priv_data;
789 MpegTSWrite *ts = s->priv_data;
790 uint8_t buf[TS_PACKET_SIZE];
792 int val, is_start, len, header_len, write_pcr, private_code, flags;
793 int afc_len, stuffing_len;
794 int64_t pcr = -1; /* avoid warning */
795 int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE);
796 int force_pat = st->codec->codec_type == AVMEDIA_TYPE_VIDEO && key && !ts_st->prev_payload_key;
799 while (payload_size > 0) {
800 retransmit_si_info(s, force_pat);
804 if (ts_st->pid == ts_st->service->pcr_pid) {
805 if (ts->mux_rate > 1 || is_start) // VBR pcr period is based on frames
806 ts_st->service->pcr_packet_count++;
807 if (ts_st->service->pcr_packet_count >=
808 ts_st->service->pcr_packet_period) {
809 ts_st->service->pcr_packet_count = 0;
814 if (ts->mux_rate > 1 && dts != AV_NOPTS_VALUE &&
815 (dts - get_pcr(ts, s->pb)/300) > delay) {
816 /* pcr insert gets priority over null packet insert */
818 mpegts_insert_pcr_only(s, st);
820 mpegts_insert_null_packet(s);
821 continue; /* recalculate write_pcr and possibly retransmit si_info */
824 /* prepare packet header */
827 val = (ts_st->pid >> 8);
832 ts_st->cc = (ts_st->cc + 1) & 0xf;
833 *q++ = 0x10 | ts_st->cc; // payload indicator + CC
834 if (key && is_start && pts != AV_NOPTS_VALUE) {
835 // set Random Access for key frames
836 if (ts_st->pid == ts_st->service->pcr_pid)
838 set_af_flag(buf, 0x40);
839 q = get_ts_payload_start(buf);
842 set_af_flag(buf, 0x10);
843 q = get_ts_payload_start(buf);
844 // add 11, pcr references the last byte of program clock reference base
845 if (ts->mux_rate > 1)
846 pcr = get_pcr(ts, s->pb);
848 pcr = (dts - delay)*300;
849 if (dts != AV_NOPTS_VALUE && dts < pcr / 300)
850 av_log(s, AV_LOG_WARNING, "dts < pcr, TS is invalid\n");
851 extend_af(buf, write_pcr_bits(q, pcr));
852 q = get_ts_payload_start(buf);
855 int pes_extension = 0;
856 /* write PES header */
861 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
862 if (st->codec->codec_id == CODEC_ID_DIRAC) {
866 } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
867 (st->codec->codec_id == CODEC_ID_MP2 ||
868 st->codec->codec_id == CODEC_ID_MP3 ||
869 st->codec->codec_id == CODEC_ID_AAC)) {
873 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
879 if (pts != AV_NOPTS_VALUE) {
883 if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
887 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
888 st->codec->codec_id == CODEC_ID_DIRAC) {
889 /* set PES_extension_flag */
894 * One byte for PES2 extension flag +
895 * one byte for extension length +
896 * one byte for extension id
900 len = payload_size + header_len + 3;
901 if (private_code != 0)
908 /* data alignment indicator is required for subtitle data */
909 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)
914 if (pts != AV_NOPTS_VALUE) {
915 write_pts(q, flags >> 6, pts);
918 if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
919 write_pts(q, 1, dts);
922 if (pes_extension && st->codec->codec_id == CODEC_ID_DIRAC) {
923 flags = 0x01; /* set PES_extension_flag_2 */
925 *q++ = 0x80 | 0x01; /* marker bit + extension length */
927 * Set the stream id extension flag bit to 0 and
928 * write the extended stream id
932 if (private_code != 0)
937 header_len = q - buf;
939 len = TS_PACKET_SIZE - header_len;
940 if (len > payload_size)
942 stuffing_len = TS_PACKET_SIZE - header_len - len;
943 if (stuffing_len > 0) {
944 /* add stuffing with AFC */
946 /* stuffing already present: increase its size */
947 afc_len = buf[4] + 1;
948 memmove(buf + 4 + afc_len + stuffing_len,
950 header_len - (4 + afc_len));
951 buf[4] += stuffing_len;
952 memset(buf + 4 + afc_len, 0xff, stuffing_len);
955 memmove(buf + 4 + stuffing_len, buf + 4, header_len - 4);
957 buf[4] = stuffing_len - 1;
958 if (stuffing_len >= 2) {
960 memset(buf + 6, 0xff, stuffing_len - 2);
964 memcpy(buf + TS_PACKET_SIZE - len, payload, len);
967 mpegts_prefix_m2ts_header(s);
968 avio_write(s->pb, buf, TS_PACKET_SIZE);
971 ts_st->prev_payload_key = key;
974 static int mpegts_write_packet(AVFormatContext *s, AVPacket *pkt)
976 AVStream *st = s->streams[pkt->stream_index];
977 int size = pkt->size;
978 uint8_t *buf= pkt->data;
980 MpegTSWrite *ts = s->priv_data;
981 MpegTSWriteStream *ts_st = st->priv_data;
982 const uint64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE)*2;
983 int64_t dts = AV_NOPTS_VALUE, pts = AV_NOPTS_VALUE;
985 if (ts->reemit_pat_pmt) {
986 ts->pat_packet_count = ts->pat_packet_period - 1;
987 ts->sdt_packet_count = ts->sdt_packet_period - 1;
988 ts->reemit_pat_pmt = 0;
991 if (pkt->pts != AV_NOPTS_VALUE)
992 pts = pkt->pts + delay;
993 if (pkt->dts != AV_NOPTS_VALUE)
994 dts = pkt->dts + delay;
996 if (ts_st->first_pts_check && pts == AV_NOPTS_VALUE) {
997 av_log(s, AV_LOG_ERROR, "first pts value must set\n");
998 return AVERROR_INVALIDDATA;
1000 ts_st->first_pts_check = 0;
1002 if (st->codec->codec_id == CODEC_ID_H264) {
1003 const uint8_t *p = buf, *buf_end = p+size;
1004 uint32_t state = -1;
1006 if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001) {
1007 av_log(s, AV_LOG_ERROR, "H.264 bitstream malformed, "
1008 "no startcode found, use the h264_mp4toannexb bitstream filter (-bsf h264_mp4toannexb)\n");
1009 return AVERROR_INVALIDDATA;
1013 p = avpriv_mpv_find_start_code(p, buf_end, &state);
1014 //av_log(s, AV_LOG_INFO, "nal %d\n", state & 0x1f);
1015 } while (p < buf_end && (state & 0x1f) != 9 &&
1016 (state & 0x1f) != 5 && (state & 0x1f) != 1);
1018 if ((state & 0x1f) != 9) { // AUD NAL
1019 data = av_malloc(pkt->size+6);
1021 return AVERROR(ENOMEM);
1022 memcpy(data+6, pkt->data, pkt->size);
1023 AV_WB32(data, 0x00000001);
1025 data[5] = 0xf0; // any slice type (0xe) + rbsp stop one bit
1029 } else if (st->codec->codec_id == CODEC_ID_AAC) {
1031 return AVERROR_INVALIDDATA;
1032 if ((AV_RB16(pkt->data) & 0xfff0) != 0xfff0) {
1033 ADTSContext *adts = ts_st->adts;
1036 av_log(s, AV_LOG_ERROR, "AAC bitstream not in ADTS format "
1037 "and extradata missing\n");
1038 return AVERROR_INVALIDDATA;
1040 new_size = ADTS_HEADER_SIZE+adts->pce_size+pkt->size;
1041 if ((unsigned)new_size >= INT_MAX)
1042 return AVERROR_INVALIDDATA;
1043 data = av_malloc(new_size);
1045 return AVERROR(ENOMEM);
1046 err = ff_adts_write_frame_header(adts, data, pkt->size,
1052 if (adts->pce_size) {
1053 memcpy(data+ADTS_HEADER_SIZE, adts->pce_data, adts->pce_size);
1056 memcpy(data+ADTS_HEADER_SIZE+adts->pce_size, pkt->data, pkt->size);
1062 if (ts_st->payload_size && ts_st->payload_size + size > ts->pes_payload_size) {
1063 mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_size,
1064 ts_st->payload_pts, ts_st->payload_dts,
1065 ts_st->payload_flags & AV_PKT_FLAG_KEY);
1066 ts_st->payload_size = 0;
1069 if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO || size > ts->pes_payload_size) {
1070 av_assert0(!ts_st->payload_size);
1071 // for video and subtitle, write a single pes packet
1072 mpegts_write_pes(s, st, buf, size, pts, dts, pkt->flags & AV_PKT_FLAG_KEY);
1077 if (!ts_st->payload_size) {
1078 ts_st->payload_pts = pts;
1079 ts_st->payload_dts = dts;
1080 ts_st->payload_flags = pkt->flags;
1083 memcpy(ts_st->payload + ts_st->payload_size, buf, size);
1084 ts_st->payload_size += size;
1091 static int mpegts_write_end(AVFormatContext *s)
1093 MpegTSWrite *ts = s->priv_data;
1094 MpegTSWriteStream *ts_st;
1095 MpegTSService *service;
1099 /* flush current packets */
1100 for(i = 0; i < s->nb_streams; i++) {
1102 ts_st = st->priv_data;
1103 if (ts_st->payload_size > 0) {
1104 mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_size,
1105 ts_st->payload_pts, ts_st->payload_dts,
1106 ts_st->payload_flags & AV_PKT_FLAG_KEY);
1108 av_freep(&ts_st->payload);
1109 av_freep(&ts_st->adts);
1113 for(i = 0; i < ts->nb_services; i++) {
1114 service = ts->services[i];
1115 av_freep(&service->provider_name);
1116 av_freep(&service->name);
1119 av_free(ts->services);
1124 AVOutputFormat ff_mpegts_muxer = {
1126 .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
1127 .mime_type = "video/x-mpegts",
1128 .extensions = "ts,m2t,m2ts,mts",
1129 .priv_data_size = sizeof(MpegTSWrite),
1130 .audio_codec = CODEC_ID_MP2,
1131 .video_codec = CODEC_ID_MPEG2VIDEO,
1132 .write_header = mpegts_write_header,
1133 .write_packet = mpegts_write_packet,
1134 .write_trailer = mpegts_write_end,
1135 .priv_class = &mpegts_muxer_class,