2 * MPEG2 transport stream (aka DVB) muxer
3 * Copyright (c) 2003 Fabrice Bellard
5 * This file is part of Libav.
7 * Libav is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * Libav is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 #include "libavutil/bswap.h"
23 #include "libavutil/crc.h"
24 #include "libavutil/dict.h"
25 #include "libavutil/mathematics.h"
26 #include "libavutil/opt.h"
27 #include "libavcodec/mpegvideo.h"
33 #define PCR_TIME_BASE 27000000
35 /* write DVB SI sections */
37 /*********************************************/
38 /* mpegts section writer */
40 typedef struct MpegTSSection {
43 void (*write_packet)(struct MpegTSSection *s, const uint8_t *packet);
47 typedef struct MpegTSService {
48 MpegTSSection pmt; /* MPEG2 pmt table context */
49 int sid; /* service ID */
54 int pcr_packet_period;
57 typedef struct MpegTSWrite {
58 const AVClass *av_class;
59 MpegTSSection pat; /* MPEG2 pat table */
60 MpegTSSection sdt; /* MPEG2 sdt table context */
61 MpegTSService **services;
63 int sdt_packet_period;
65 int pat_packet_period;
70 int mux_rate; ///< set to 1 when VBR
72 int transport_stream_id;
73 int original_network_id;
80 static const AVOption options[] = {
81 { "mpegts_transport_stream_id", "Set transport_stream_id field.",
82 offsetof(MpegTSWrite, transport_stream_id), AV_OPT_TYPE_INT, {.dbl = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
83 { "mpegts_original_network_id", "Set original_network_id field.",
84 offsetof(MpegTSWrite, original_network_id), AV_OPT_TYPE_INT, {.dbl = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
85 { "mpegts_service_id", "Set service_id field.",
86 offsetof(MpegTSWrite, service_id), AV_OPT_TYPE_INT, {.dbl = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
87 { "mpegts_pmt_start_pid", "Set the first pid of the PMT.",
88 offsetof(MpegTSWrite, pmt_start_pid), AV_OPT_TYPE_INT, {.dbl = 0x1000 }, 0x1000, 0x1f00, AV_OPT_FLAG_ENCODING_PARAM},
89 { "mpegts_start_pid", "Set the first pid.",
90 offsetof(MpegTSWrite, start_pid), AV_OPT_TYPE_INT, {.dbl = 0x0100 }, 0x0100, 0x0f00, AV_OPT_FLAG_ENCODING_PARAM},
91 { "muxrate", NULL, offsetof(MpegTSWrite, mux_rate), AV_OPT_TYPE_INT, {1}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
95 static const AVClass mpegts_muxer_class = {
96 .class_name = "MPEGTS muxer",
97 .item_name = av_default_item_name,
99 .version = LIBAVUTIL_VERSION_INT,
102 /* NOTE: 4 bytes must be left at the end for the crc32 */
103 static void mpegts_write_section(MpegTSSection *s, uint8_t *buf, int len)
106 unsigned char packet[TS_PACKET_SIZE];
107 const unsigned char *buf_ptr;
109 int first, b, len1, left;
111 crc = av_bswap32(av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1, buf, len - 4));
112 buf[len - 4] = (crc >> 24) & 0xff;
113 buf[len - 3] = (crc >> 16) & 0xff;
114 buf[len - 2] = (crc >> 8) & 0xff;
115 buf[len - 1] = (crc) & 0xff;
117 /* send each packet */
120 first = (buf == buf_ptr);
128 s->cc = (s->cc + 1) & 0xf;
131 *q++ = 0; /* 0 offset */
132 len1 = TS_PACKET_SIZE - (q - packet);
135 memcpy(q, buf_ptr, len1);
137 /* add known padding data */
138 left = TS_PACKET_SIZE - (q - packet);
140 memset(q, 0xff, left);
142 s->write_packet(s, packet);
149 static inline void put16(uint8_t **q_ptr, int val)
158 static int mpegts_write_section1(MpegTSSection *s, int tid, int id,
159 int version, int sec_num, int last_sec_num,
160 uint8_t *buf, int len)
162 uint8_t section[1024], *q;
163 unsigned int tot_len;
164 /* reserved_future_use field must be set to 1 for SDT */
165 unsigned int flags = tid == SDT_TID ? 0xf000 : 0xb000;
167 tot_len = 3 + 5 + len + 4;
168 /* check if not too big */
174 put16(&q, flags | (len + 5 + 4)); /* 5 byte header + 4 byte CRC */
176 *q++ = 0xc1 | (version << 1); /* current_next_indicator = 1 */
181 mpegts_write_section(s, section, tot_len);
185 /*********************************************/
188 #define DEFAULT_PROVIDER_NAME "Libav"
189 #define DEFAULT_SERVICE_NAME "Service01"
191 /* a PES packet header is generated every DEFAULT_PES_HEADER_FREQ packets */
192 #define DEFAULT_PES_HEADER_FREQ 16
193 #define DEFAULT_PES_PAYLOAD_SIZE ((DEFAULT_PES_HEADER_FREQ - 1) * 184 + 170)
195 /* we retransmit the SI info at this rate */
196 #define SDT_RETRANS_TIME 500
197 #define PAT_RETRANS_TIME 100
198 #define PCR_RETRANS_TIME 20
200 typedef struct MpegTSWriteStream {
201 struct MpegTSService *service;
202 int pid; /* stream associated pid */
205 int first_pts_check; ///< first pts check needed
209 uint8_t payload[DEFAULT_PES_PAYLOAD_SIZE];
213 static void mpegts_write_pat(AVFormatContext *s)
215 MpegTSWrite *ts = s->priv_data;
216 MpegTSService *service;
217 uint8_t data[1012], *q;
221 for(i = 0; i < ts->nb_services; i++) {
222 service = ts->services[i];
223 put16(&q, service->sid);
224 put16(&q, 0xe000 | service->pmt.pid);
226 mpegts_write_section1(&ts->pat, PAT_TID, ts->tsid, 0, 0, 0,
230 static void mpegts_write_pmt(AVFormatContext *s, MpegTSService *service)
232 // MpegTSWrite *ts = s->priv_data;
233 uint8_t data[1012], *q, *desc_length_ptr, *program_info_length_ptr;
234 int val, stream_type, i;
237 put16(&q, 0xe000 | service->pcr_pid);
239 program_info_length_ptr = q;
240 q += 2; /* patched after */
242 /* put program info here */
244 val = 0xf000 | (q - program_info_length_ptr - 2);
245 program_info_length_ptr[0] = val >> 8;
246 program_info_length_ptr[1] = val;
248 for(i = 0; i < s->nb_streams; i++) {
249 AVStream *st = s->streams[i];
250 MpegTSWriteStream *ts_st = st->priv_data;
251 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
252 switch(st->codec->codec_id) {
253 case CODEC_ID_MPEG1VIDEO:
254 case CODEC_ID_MPEG2VIDEO:
255 stream_type = STREAM_TYPE_VIDEO_MPEG2;
258 stream_type = STREAM_TYPE_VIDEO_MPEG4;
261 stream_type = STREAM_TYPE_VIDEO_H264;
264 stream_type = STREAM_TYPE_VIDEO_DIRAC;
268 stream_type = STREAM_TYPE_AUDIO_MPEG1;
271 stream_type = STREAM_TYPE_AUDIO_AAC;
273 case CODEC_ID_AAC_LATM:
274 stream_type = STREAM_TYPE_AUDIO_AAC_LATM;
277 stream_type = STREAM_TYPE_AUDIO_AC3;
280 stream_type = STREAM_TYPE_PRIVATE_DATA;
284 put16(&q, 0xe000 | ts_st->pid);
286 q += 2; /* patched after */
288 /* write optional descriptors here */
289 switch(st->codec->codec_type) {
290 case AVMEDIA_TYPE_AUDIO:
293 char *next = lang->value;
296 *q++ = 0x0a; /* ISO 639 language descriptor */
300 for (p = lang->value; next && *len_ptr < 255 / 4 * 4; p = next + 1) {
301 next = strchr(p, ',');
302 if (strlen(p) != 3 && (!next || next != p + 3))
303 continue; /* not a 3-letter code */
309 if (st->disposition & AV_DISPOSITION_CLEAN_EFFECTS)
311 else if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
313 else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
316 *q++ = 0; /* undefined type */
322 q -= 2; /* no language codes were written */
325 case AVMEDIA_TYPE_SUBTITLE:
327 const char *language;
328 language = lang && strlen(lang->value)==3 ? lang->value : "eng";
334 *q++ = 0x10; /* normal subtitles (0x20 = if hearing pb) */
335 if(st->codec->extradata_size == 4) {
336 memcpy(q, st->codec->extradata, 4);
339 put16(&q, 1); /* page id */
340 put16(&q, 1); /* ancillary page id */
344 case AVMEDIA_TYPE_VIDEO:
345 if (stream_type == STREAM_TYPE_VIDEO_DIRAC) {
346 *q++ = 0x05; /*MPEG-2 registration descriptor*/
356 val = 0xf000 | (q - desc_length_ptr - 2);
357 desc_length_ptr[0] = val >> 8;
358 desc_length_ptr[1] = val;
360 mpegts_write_section1(&service->pmt, PMT_TID, service->sid, 0, 0, 0,
364 /* NOTE: str == NULL is accepted for an empty string */
365 static void putstr8(uint8_t **q_ptr, const char *str)
381 static void mpegts_write_sdt(AVFormatContext *s)
383 MpegTSWrite *ts = s->priv_data;
384 MpegTSService *service;
385 uint8_t data[1012], *q, *desc_list_len_ptr, *desc_len_ptr;
386 int i, running_status, free_ca_mode, val;
391 for(i = 0; i < ts->nb_services; i++) {
392 service = ts->services[i];
393 put16(&q, service->sid);
394 *q++ = 0xfc | 0x00; /* currently no EIT info */
395 desc_list_len_ptr = q;
397 running_status = 4; /* running */
400 /* write only one descriptor for the service name and provider */
404 *q++ = 0x01; /* digital television service */
405 putstr8(&q, service->provider_name);
406 putstr8(&q, service->name);
407 desc_len_ptr[0] = q - desc_len_ptr - 1;
409 /* fill descriptor length */
410 val = (running_status << 13) | (free_ca_mode << 12) |
411 (q - desc_list_len_ptr - 2);
412 desc_list_len_ptr[0] = val >> 8;
413 desc_list_len_ptr[1] = val;
415 mpegts_write_section1(&ts->sdt, SDT_TID, ts->tsid, 0, 0, 0,
419 static MpegTSService *mpegts_add_service(MpegTSWrite *ts,
421 const char *provider_name,
424 MpegTSService *service;
426 service = av_mallocz(sizeof(MpegTSService));
429 service->pmt.pid = ts->pmt_start_pid + ts->nb_services;
431 service->provider_name = av_strdup(provider_name);
432 service->name = av_strdup(name);
433 service->pcr_pid = 0x1fff;
434 dynarray_add(&ts->services, &ts->nb_services, service);
438 static void section_write_packet(MpegTSSection *s, const uint8_t *packet)
440 AVFormatContext *ctx = s->opaque;
441 avio_write(ctx->pb, packet, TS_PACKET_SIZE);
444 static int mpegts_write_header(AVFormatContext *s)
446 MpegTSWrite *ts = s->priv_data;
447 MpegTSWriteStream *ts_st;
448 MpegTSService *service;
449 AVStream *st, *pcr_st = NULL;
450 AVDictionaryEntry *title, *provider;
452 const char *service_name;
453 const char *provider_name;
456 ts->tsid = ts->transport_stream_id;
457 ts->onid = ts->original_network_id;
458 /* allocate a single DVB service */
459 title = av_dict_get(s->metadata, "service_name", NULL, 0);
461 title = av_dict_get(s->metadata, "title", NULL, 0);
462 service_name = title ? title->value : DEFAULT_SERVICE_NAME;
463 provider = av_dict_get(s->metadata, "service_provider", NULL, 0);
464 provider_name = provider ? provider->value : DEFAULT_PROVIDER_NAME;
465 service = mpegts_add_service(ts, ts->service_id, provider_name, service_name);
466 service->pmt.write_packet = section_write_packet;
467 service->pmt.opaque = s;
468 service->pmt.cc = 15;
470 ts->pat.pid = PAT_PID;
471 ts->pat.cc = 15; // Initialize at 15 so that it wraps and be equal to 0 for the first packet we write
472 ts->pat.write_packet = section_write_packet;
475 ts->sdt.pid = SDT_PID;
477 ts->sdt.write_packet = section_write_packet;
480 pids = av_malloc(s->nb_streams * sizeof(*pids));
482 return AVERROR(ENOMEM);
484 /* assign pids to each stream */
485 for(i = 0;i < s->nb_streams; i++) {
487 avpriv_set_pts_info(st, 33, 1, 90000);
488 ts_st = av_mallocz(sizeof(MpegTSWriteStream));
491 st->priv_data = ts_st;
492 ts_st->service = service;
493 /* MPEG pid values < 16 are reserved. Applications which set st->id in
494 * this range are assigned a calculated pid. */
496 ts_st->pid = ts->start_pid + i;
497 } else if (st->id < 0x1FFF) {
500 av_log(s, AV_LOG_ERROR, "Invalid stream id %d, must be less than 8191\n", st->id);
503 if (ts_st->pid == service->pmt.pid) {
504 av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
507 for (j = 0; j < i; j++)
508 if (pids[j] == ts_st->pid) {
509 av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
512 pids[i] = ts_st->pid;
513 ts_st->payload_pts = AV_NOPTS_VALUE;
514 ts_st->payload_dts = AV_NOPTS_VALUE;
515 ts_st->first_pts_check = 1;
517 /* update PCR pid by using the first video stream */
518 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
519 service->pcr_pid == 0x1fff) {
520 service->pcr_pid = ts_st->pid;
523 if (st->codec->codec_id == CODEC_ID_AAC &&
524 st->codec->extradata_size > 0) {
525 ts_st->adts = av_mallocz(sizeof(*ts_st->adts));
527 return AVERROR(ENOMEM);
528 if (ff_adts_decode_extradata(s, ts_st->adts, st->codec->extradata,
529 st->codec->extradata_size) < 0)
536 /* if no video stream, use the first stream as PCR */
537 if (service->pcr_pid == 0x1fff && s->nb_streams > 0) {
538 pcr_st = s->streams[0];
539 ts_st = pcr_st->priv_data;
540 service->pcr_pid = ts_st->pid;
545 ts->mux_rate = s->mux_rate;
548 if (ts->mux_rate > 1) {
549 service->pcr_packet_period = (ts->mux_rate * PCR_RETRANS_TIME) /
550 (TS_PACKET_SIZE * 8 * 1000);
551 ts->sdt_packet_period = (ts->mux_rate * SDT_RETRANS_TIME) /
552 (TS_PACKET_SIZE * 8 * 1000);
553 ts->pat_packet_period = (ts->mux_rate * PAT_RETRANS_TIME) /
554 (TS_PACKET_SIZE * 8 * 1000);
556 ts->first_pcr = av_rescale(s->max_delay, PCR_TIME_BASE, AV_TIME_BASE);
558 /* Arbitrary values, PAT/PMT could be written on key frames */
559 ts->sdt_packet_period = 200;
560 ts->pat_packet_period = 40;
561 if (pcr_st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
562 if (!pcr_st->codec->frame_size) {
563 av_log(s, AV_LOG_WARNING, "frame size not set\n");
564 service->pcr_packet_period =
565 pcr_st->codec->sample_rate/(10*512);
567 service->pcr_packet_period =
568 pcr_st->codec->sample_rate/(10*pcr_st->codec->frame_size);
571 // max delta PCR 0.1s
572 service->pcr_packet_period =
573 pcr_st->codec->time_base.den/(10*pcr_st->codec->time_base.num);
577 // output a PCR as soon as possible
578 service->pcr_packet_count = service->pcr_packet_period;
579 ts->pat_packet_count = ts->pat_packet_period-1;
580 ts->sdt_packet_count = ts->sdt_packet_period-1;
582 if (ts->mux_rate == 1)
583 av_log(s, AV_LOG_INFO, "muxrate VBR, ");
585 av_log(s, AV_LOG_INFO, "muxrate %d, ", ts->mux_rate);
586 av_log(s, AV_LOG_INFO, "pcr every %d pkts, "
587 "sdt every %d, pat/pmt every %d pkts\n",
588 service->pcr_packet_period,
589 ts->sdt_packet_period, ts->pat_packet_period);
597 for(i = 0;i < s->nb_streams; i++) {
599 av_freep(&st->priv_data);
604 /* send SDT, PAT and PMT tables regulary */
605 static void retransmit_si_info(AVFormatContext *s)
607 MpegTSWrite *ts = s->priv_data;
610 if (++ts->sdt_packet_count == ts->sdt_packet_period) {
611 ts->sdt_packet_count = 0;
614 if (++ts->pat_packet_count == ts->pat_packet_period) {
615 ts->pat_packet_count = 0;
617 for(i = 0; i < ts->nb_services; i++) {
618 mpegts_write_pmt(s, ts->services[i]);
623 static int64_t get_pcr(const MpegTSWrite *ts, AVIOContext *pb)
625 return av_rescale(avio_tell(pb) + 11, 8 * PCR_TIME_BASE, ts->mux_rate) +
629 static int write_pcr_bits(uint8_t *buf, int64_t pcr)
631 int64_t pcr_low = pcr % 300, pcr_high = pcr / 300;
633 *buf++ = pcr_high >> 25;
634 *buf++ = pcr_high >> 17;
635 *buf++ = pcr_high >> 9;
636 *buf++ = pcr_high >> 1;
637 *buf++ = pcr_high << 7 | pcr_low >> 8 | 0x7e;
643 /* Write a single null transport stream packet */
644 static void mpegts_insert_null_packet(AVFormatContext *s)
647 uint8_t buf[TS_PACKET_SIZE];
654 memset(q, 0x0FF, TS_PACKET_SIZE - (q - buf));
655 avio_write(s->pb, buf, TS_PACKET_SIZE);
658 /* Write a single transport stream packet with a PCR and no payload */
659 static void mpegts_insert_pcr_only(AVFormatContext *s, AVStream *st)
661 MpegTSWrite *ts = s->priv_data;
662 MpegTSWriteStream *ts_st = st->priv_data;
664 uint8_t buf[TS_PACKET_SIZE];
668 *q++ = ts_st->pid >> 8;
670 *q++ = 0x20 | ts_st->cc; /* Adaptation only */
671 /* Continuity Count field does not increment (see 13818-1 section 2.4.3.3) */
672 *q++ = TS_PACKET_SIZE - 5; /* Adaptation Field Length */
673 *q++ = 0x10; /* Adaptation flags: PCR present */
675 /* PCR coded into 6 bytes */
676 q += write_pcr_bits(q, get_pcr(ts, s->pb));
679 memset(q, 0xFF, TS_PACKET_SIZE - (q - buf));
680 avio_write(s->pb, buf, TS_PACKET_SIZE);
683 static void write_pts(uint8_t *q, int fourbits, int64_t pts)
687 val = fourbits << 4 | (((pts >> 30) & 0x07) << 1) | 1;
689 val = (((pts >> 15) & 0x7fff) << 1) | 1;
692 val = (((pts) & 0x7fff) << 1) | 1;
697 /* Set an adaptation field flag in an MPEG-TS packet*/
698 static void set_af_flag(uint8_t *pkt, int flag)
700 // expect at least one flag to set
703 if ((pkt[3] & 0x20) == 0) {
704 // no AF yet, set adaptation field flag
706 // 1 byte length, no flags
713 /* Extend the adaptation field by size bytes */
714 static void extend_af(uint8_t *pkt, int size)
716 // expect already existing adaptation field
717 assert(pkt[3] & 0x20);
721 /* Get a pointer to MPEG-TS payload (right after TS packet header) */
722 static uint8_t *get_ts_payload_start(uint8_t *pkt)
725 return pkt + 5 + pkt[4];
730 /* Add a pes header to the front of payload, and segment into an integer number of
731 * ts packets. The final ts packet is padded using an over-sized adaptation header
732 * to exactly fill the last ts packet.
733 * NOTE: 'payload' contains a complete PES payload.
735 static void mpegts_write_pes(AVFormatContext *s, AVStream *st,
736 const uint8_t *payload, int payload_size,
737 int64_t pts, int64_t dts, int key)
739 MpegTSWriteStream *ts_st = st->priv_data;
740 MpegTSWrite *ts = s->priv_data;
741 uint8_t buf[TS_PACKET_SIZE];
743 int val, is_start, len, header_len, write_pcr, private_code, flags;
744 int afc_len, stuffing_len;
745 int64_t pcr = -1; /* avoid warning */
746 int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE);
749 while (payload_size > 0) {
750 retransmit_si_info(s);
753 if (ts_st->pid == ts_st->service->pcr_pid) {
754 if (ts->mux_rate > 1 || is_start) // VBR pcr period is based on frames
755 ts_st->service->pcr_packet_count++;
756 if (ts_st->service->pcr_packet_count >=
757 ts_st->service->pcr_packet_period) {
758 ts_st->service->pcr_packet_count = 0;
763 if (ts->mux_rate > 1 && dts != AV_NOPTS_VALUE &&
764 (dts - get_pcr(ts, s->pb)/300) > delay) {
765 /* pcr insert gets priority over null packet insert */
767 mpegts_insert_pcr_only(s, st);
769 mpegts_insert_null_packet(s);
770 continue; /* recalculate write_pcr and possibly retransmit si_info */
773 /* prepare packet header */
776 val = (ts_st->pid >> 8);
781 ts_st->cc = (ts_st->cc + 1) & 0xf;
782 *q++ = 0x10 | ts_st->cc; // payload indicator + CC
783 if (key && is_start && pts != AV_NOPTS_VALUE) {
784 // set Random Access for key frames
785 if (ts_st->pid == ts_st->service->pcr_pid)
787 set_af_flag(buf, 0x40);
788 q = get_ts_payload_start(buf);
791 set_af_flag(buf, 0x10);
792 q = get_ts_payload_start(buf);
793 // add 11, pcr references the last byte of program clock reference base
794 if (ts->mux_rate > 1)
795 pcr = get_pcr(ts, s->pb);
797 pcr = (dts - delay)*300;
798 if (dts != AV_NOPTS_VALUE && dts < pcr / 300)
799 av_log(s, AV_LOG_WARNING, "dts < pcr, TS is invalid\n");
800 extend_af(buf, write_pcr_bits(q, pcr));
801 q = get_ts_payload_start(buf);
804 int pes_extension = 0;
805 /* write PES header */
810 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
811 if (st->codec->codec_id == CODEC_ID_DIRAC) {
815 } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
816 (st->codec->codec_id == CODEC_ID_MP2 ||
817 st->codec->codec_id == CODEC_ID_MP3 ||
818 st->codec->codec_id == CODEC_ID_AAC)) {
822 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
828 if (pts != AV_NOPTS_VALUE) {
832 if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
836 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
837 st->codec->codec_id == CODEC_ID_DIRAC) {
838 /* set PES_extension_flag */
843 * One byte for PES2 extension flag +
844 * one byte for extension length +
845 * one byte for extension id
849 len = payload_size + header_len + 3;
850 if (private_code != 0)
857 /* data alignment indicator is required for subtitle data */
858 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)
863 if (pts != AV_NOPTS_VALUE) {
864 write_pts(q, flags >> 6, pts);
867 if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
868 write_pts(q, 1, dts);
871 if (pes_extension && st->codec->codec_id == CODEC_ID_DIRAC) {
872 flags = 0x01; /* set PES_extension_flag_2 */
874 *q++ = 0x80 | 0x01; /* marker bit + extension length */
876 * Set the stream id extension flag bit to 0 and
877 * write the extended stream id
881 if (private_code != 0)
886 header_len = q - buf;
888 len = TS_PACKET_SIZE - header_len;
889 if (len > payload_size)
891 stuffing_len = TS_PACKET_SIZE - header_len - len;
892 if (stuffing_len > 0) {
893 /* add stuffing with AFC */
895 /* stuffing already present: increase its size */
896 afc_len = buf[4] + 1;
897 memmove(buf + 4 + afc_len + stuffing_len,
899 header_len - (4 + afc_len));
900 buf[4] += stuffing_len;
901 memset(buf + 4 + afc_len, 0xff, stuffing_len);
904 memmove(buf + 4 + stuffing_len, buf + 4, header_len - 4);
906 buf[4] = stuffing_len - 1;
907 if (stuffing_len >= 2) {
909 memset(buf + 6, 0xff, stuffing_len - 2);
913 memcpy(buf + TS_PACKET_SIZE - len, payload, len);
916 avio_write(s->pb, buf, TS_PACKET_SIZE);
921 static int mpegts_write_packet(AVFormatContext *s, AVPacket *pkt)
923 AVStream *st = s->streams[pkt->stream_index];
924 int size = pkt->size;
925 uint8_t *buf= pkt->data;
927 MpegTSWriteStream *ts_st = st->priv_data;
928 const uint64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE)*2;
929 int64_t dts = AV_NOPTS_VALUE, pts = AV_NOPTS_VALUE;
931 if (pkt->pts != AV_NOPTS_VALUE)
932 pts = pkt->pts + delay;
933 if (pkt->dts != AV_NOPTS_VALUE)
934 dts = pkt->dts + delay;
936 if (ts_st->first_pts_check && pts == AV_NOPTS_VALUE) {
937 av_log(s, AV_LOG_ERROR, "first pts value must set\n");
940 ts_st->first_pts_check = 0;
942 if (st->codec->codec_id == CODEC_ID_H264) {
943 const uint8_t *p = buf, *buf_end = p+size;
946 if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001) {
947 av_log(s, AV_LOG_ERROR, "h264 bitstream malformated, "
948 "no startcode found, use -vbsf h264_mp4toannexb\n");
953 p = avpriv_mpv_find_start_code(p, buf_end, &state);
954 //av_log(s, AV_LOG_INFO, "nal %d\n", state & 0x1f);
955 } while (p < buf_end && (state & 0x1f) != 9 &&
956 (state & 0x1f) != 5 && (state & 0x1f) != 1);
958 if ((state & 0x1f) != 9) { // AUD NAL
959 data = av_malloc(pkt->size+6);
962 memcpy(data+6, pkt->data, pkt->size);
963 AV_WB32(data, 0x00000001);
965 data[5] = 0xf0; // any slice type (0xe) + rbsp stop one bit
969 } else if (st->codec->codec_id == CODEC_ID_AAC) {
972 if ((AV_RB16(pkt->data) & 0xfff0) != 0xfff0) {
973 ADTSContext *adts = ts_st->adts;
976 av_log(s, AV_LOG_ERROR, "aac bitstream not in adts format "
977 "and extradata missing\n");
980 new_size = ADTS_HEADER_SIZE+adts->pce_size+pkt->size;
981 if ((unsigned)new_size >= INT_MAX)
983 data = av_malloc(new_size);
985 return AVERROR(ENOMEM);
986 err = ff_adts_write_frame_header(adts, data, pkt->size,
992 if (adts->pce_size) {
993 memcpy(data+ADTS_HEADER_SIZE, adts->pce_data, adts->pce_size);
996 memcpy(data+ADTS_HEADER_SIZE+adts->pce_size, pkt->data, pkt->size);
1002 if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO) {
1003 // for video and subtitle, write a single pes packet
1004 mpegts_write_pes(s, st, buf, size, pts, dts, pkt->flags & AV_PKT_FLAG_KEY);
1009 if (ts_st->payload_index + size > DEFAULT_PES_PAYLOAD_SIZE) {
1010 mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_index,
1011 ts_st->payload_pts, ts_st->payload_dts,
1012 ts_st->payload_flags & AV_PKT_FLAG_KEY);
1013 ts_st->payload_index = 0;
1016 if (!ts_st->payload_index) {
1017 ts_st->payload_pts = pts;
1018 ts_st->payload_dts = dts;
1019 ts_st->payload_flags = pkt->flags;
1022 memcpy(ts_st->payload + ts_st->payload_index, buf, size);
1023 ts_st->payload_index += size;
1030 static int mpegts_write_end(AVFormatContext *s)
1032 MpegTSWrite *ts = s->priv_data;
1033 MpegTSWriteStream *ts_st;
1034 MpegTSService *service;
1038 /* flush current packets */
1039 for(i = 0; i < s->nb_streams; i++) {
1041 ts_st = st->priv_data;
1042 if (ts_st->payload_index > 0) {
1043 mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_index,
1044 ts_st->payload_pts, ts_st->payload_dts,
1045 ts_st->payload_flags & AV_PKT_FLAG_KEY);
1047 av_freep(&ts_st->adts);
1051 for(i = 0; i < ts->nb_services; i++) {
1052 service = ts->services[i];
1053 av_freep(&service->provider_name);
1054 av_freep(&service->name);
1057 av_free(ts->services);
1062 AVOutputFormat ff_mpegts_muxer = {
1064 .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
1065 .mime_type = "video/x-mpegts",
1066 .extensions = "ts,m2t",
1067 .priv_data_size = sizeof(MpegTSWrite),
1068 .audio_codec = CODEC_ID_MP2,
1069 .video_codec = CODEC_ID_MPEG2VIDEO,
1070 .write_header = mpegts_write_header,
1071 .write_packet = mpegts_write_packet,
1072 .write_trailer = mpegts_write_end,
1073 .priv_class = &mpegts_muxer_class,