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
73 int transport_stream_id;
74 int original_network_id;
83 /* a PES packet header is generated every DEFAULT_PES_HEADER_FREQ packets */
84 #define DEFAULT_PES_HEADER_FREQ 16
85 #define DEFAULT_PES_PAYLOAD_SIZE ((DEFAULT_PES_HEADER_FREQ - 1) * 184 + 170)
87 static const AVOption options[] = {
88 { "mpegts_transport_stream_id", "Set transport_stream_id field.",
89 offsetof(MpegTSWrite, transport_stream_id), AV_OPT_TYPE_INT, {.dbl = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
90 { "mpegts_original_network_id", "Set original_network_id field.",
91 offsetof(MpegTSWrite, original_network_id), AV_OPT_TYPE_INT, {.dbl = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
92 { "mpegts_service_id", "Set service_id field.",
93 offsetof(MpegTSWrite, service_id), AV_OPT_TYPE_INT, {.dbl = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
94 { "mpegts_pmt_start_pid", "Set the first pid of the PMT.",
95 offsetof(MpegTSWrite, pmt_start_pid), AV_OPT_TYPE_INT, {.dbl = 0x1000 }, 0x1000, 0x1f00, AV_OPT_FLAG_ENCODING_PARAM},
96 { "mpegts_start_pid", "Set the first pid.",
97 offsetof(MpegTSWrite, start_pid), AV_OPT_TYPE_INT, {.dbl = 0x0100 }, 0x0100, 0x0f00, AV_OPT_FLAG_ENCODING_PARAM},
98 { "muxrate", NULL, offsetof(MpegTSWrite, mux_rate), AV_OPT_TYPE_INT, {1}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
99 { "pes_payload_size", "Minimum PES packet payload in bytes",
100 offsetof(MpegTSWrite, pes_payload_size), AV_OPT_TYPE_INT, {DEFAULT_PES_PAYLOAD_SIZE}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
101 { "resend_headers", "Reemit PAT/PMT before writing the next packet",
102 offsetof(MpegTSWrite, reemit_pat_pmt), AV_OPT_TYPE_INT, {0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
106 static const AVClass mpegts_muxer_class = {
107 .class_name = "MPEGTS muxer",
108 .item_name = av_default_item_name,
110 .version = LIBAVUTIL_VERSION_INT,
113 /* NOTE: 4 bytes must be left at the end for the crc32 */
114 static void mpegts_write_section(MpegTSSection *s, uint8_t *buf, int len)
117 unsigned char packet[TS_PACKET_SIZE];
118 const unsigned char *buf_ptr;
120 int first, b, len1, left;
122 crc = av_bswap32(av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1, buf, len - 4));
123 buf[len - 4] = (crc >> 24) & 0xff;
124 buf[len - 3] = (crc >> 16) & 0xff;
125 buf[len - 2] = (crc >> 8) & 0xff;
126 buf[len - 1] = (crc) & 0xff;
128 /* send each packet */
131 first = (buf == buf_ptr);
139 s->cc = (s->cc + 1) & 0xf;
142 *q++ = 0; /* 0 offset */
143 len1 = TS_PACKET_SIZE - (q - packet);
146 memcpy(q, buf_ptr, len1);
148 /* add known padding data */
149 left = TS_PACKET_SIZE - (q - packet);
151 memset(q, 0xff, left);
153 s->write_packet(s, packet);
160 static inline void put16(uint8_t **q_ptr, int val)
169 static int mpegts_write_section1(MpegTSSection *s, int tid, int id,
170 int version, int sec_num, int last_sec_num,
171 uint8_t *buf, int len)
173 uint8_t section[1024], *q;
174 unsigned int tot_len;
175 /* reserved_future_use field must be set to 1 for SDT */
176 unsigned int flags = tid == SDT_TID ? 0xf000 : 0xb000;
178 tot_len = 3 + 5 + len + 4;
179 /* check if not too big */
185 put16(&q, flags | (len + 5 + 4)); /* 5 byte header + 4 byte CRC */
187 *q++ = 0xc1 | (version << 1); /* current_next_indicator = 1 */
192 mpegts_write_section(s, section, tot_len);
196 /*********************************************/
199 #define DEFAULT_PROVIDER_NAME "Libav"
200 #define DEFAULT_SERVICE_NAME "Service01"
202 /* we retransmit the SI info at this rate */
203 #define SDT_RETRANS_TIME 500
204 #define PAT_RETRANS_TIME 100
205 #define PCR_RETRANS_TIME 20
207 typedef struct MpegTSWriteStream {
208 struct MpegTSService *service;
209 int pid; /* stream associated pid */
212 int first_pts_check; ///< first pts check needed
220 static void mpegts_write_pat(AVFormatContext *s)
222 MpegTSWrite *ts = s->priv_data;
223 MpegTSService *service;
224 uint8_t data[1012], *q;
228 for(i = 0; i < ts->nb_services; i++) {
229 service = ts->services[i];
230 put16(&q, service->sid);
231 put16(&q, 0xe000 | service->pmt.pid);
233 mpegts_write_section1(&ts->pat, PAT_TID, ts->tsid, 0, 0, 0,
237 static void mpegts_write_pmt(AVFormatContext *s, MpegTSService *service)
239 // MpegTSWrite *ts = s->priv_data;
240 uint8_t data[1012], *q, *desc_length_ptr, *program_info_length_ptr;
241 int val, stream_type, i;
244 put16(&q, 0xe000 | service->pcr_pid);
246 program_info_length_ptr = q;
247 q += 2; /* patched after */
249 /* put program info here */
251 val = 0xf000 | (q - program_info_length_ptr - 2);
252 program_info_length_ptr[0] = val >> 8;
253 program_info_length_ptr[1] = val;
255 for(i = 0; i < s->nb_streams; i++) {
256 AVStream *st = s->streams[i];
257 MpegTSWriteStream *ts_st = st->priv_data;
258 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
259 switch(st->codec->codec_id) {
260 case CODEC_ID_MPEG1VIDEO:
261 case CODEC_ID_MPEG2VIDEO:
262 stream_type = STREAM_TYPE_VIDEO_MPEG2;
265 stream_type = STREAM_TYPE_VIDEO_MPEG4;
268 stream_type = STREAM_TYPE_VIDEO_H264;
271 stream_type = STREAM_TYPE_VIDEO_DIRAC;
275 stream_type = STREAM_TYPE_AUDIO_MPEG1;
278 stream_type = STREAM_TYPE_AUDIO_AAC;
280 case CODEC_ID_AAC_LATM:
281 stream_type = STREAM_TYPE_AUDIO_AAC_LATM;
284 stream_type = STREAM_TYPE_AUDIO_AC3;
287 stream_type = STREAM_TYPE_PRIVATE_DATA;
291 put16(&q, 0xe000 | ts_st->pid);
293 q += 2; /* patched after */
295 /* write optional descriptors here */
296 switch(st->codec->codec_type) {
297 case AVMEDIA_TYPE_AUDIO:
300 char *next = lang->value;
303 *q++ = 0x0a; /* ISO 639 language descriptor */
307 for (p = lang->value; next && *len_ptr < 255 / 4 * 4; p = next + 1) {
308 next = strchr(p, ',');
309 if (strlen(p) != 3 && (!next || next != p + 3))
310 continue; /* not a 3-letter code */
316 if (st->disposition & AV_DISPOSITION_CLEAN_EFFECTS)
318 else if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
320 else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
323 *q++ = 0; /* undefined type */
329 q -= 2; /* no language codes were written */
332 case AVMEDIA_TYPE_SUBTITLE:
334 const char *language;
335 language = lang && strlen(lang->value)==3 ? lang->value : "eng";
341 *q++ = 0x10; /* normal subtitles (0x20 = if hearing pb) */
342 if(st->codec->extradata_size == 4) {
343 memcpy(q, st->codec->extradata, 4);
346 put16(&q, 1); /* page id */
347 put16(&q, 1); /* ancillary page id */
351 case AVMEDIA_TYPE_VIDEO:
352 if (stream_type == STREAM_TYPE_VIDEO_DIRAC) {
353 *q++ = 0x05; /*MPEG-2 registration descriptor*/
363 val = 0xf000 | (q - desc_length_ptr - 2);
364 desc_length_ptr[0] = val >> 8;
365 desc_length_ptr[1] = val;
367 mpegts_write_section1(&service->pmt, PMT_TID, service->sid, 0, 0, 0,
371 /* NOTE: str == NULL is accepted for an empty string */
372 static void putstr8(uint8_t **q_ptr, const char *str)
388 static void mpegts_write_sdt(AVFormatContext *s)
390 MpegTSWrite *ts = s->priv_data;
391 MpegTSService *service;
392 uint8_t data[1012], *q, *desc_list_len_ptr, *desc_len_ptr;
393 int i, running_status, free_ca_mode, val;
398 for(i = 0; i < ts->nb_services; i++) {
399 service = ts->services[i];
400 put16(&q, service->sid);
401 *q++ = 0xfc | 0x00; /* currently no EIT info */
402 desc_list_len_ptr = q;
404 running_status = 4; /* running */
407 /* write only one descriptor for the service name and provider */
411 *q++ = 0x01; /* digital television service */
412 putstr8(&q, service->provider_name);
413 putstr8(&q, service->name);
414 desc_len_ptr[0] = q - desc_len_ptr - 1;
416 /* fill descriptor length */
417 val = (running_status << 13) | (free_ca_mode << 12) |
418 (q - desc_list_len_ptr - 2);
419 desc_list_len_ptr[0] = val >> 8;
420 desc_list_len_ptr[1] = val;
422 mpegts_write_section1(&ts->sdt, SDT_TID, ts->tsid, 0, 0, 0,
426 static MpegTSService *mpegts_add_service(MpegTSWrite *ts,
428 const char *provider_name,
431 MpegTSService *service;
433 service = av_mallocz(sizeof(MpegTSService));
436 service->pmt.pid = ts->pmt_start_pid + ts->nb_services;
438 service->provider_name = av_strdup(provider_name);
439 service->name = av_strdup(name);
440 service->pcr_pid = 0x1fff;
441 dynarray_add(&ts->services, &ts->nb_services, service);
445 static void section_write_packet(MpegTSSection *s, const uint8_t *packet)
447 AVFormatContext *ctx = s->opaque;
448 avio_write(ctx->pb, packet, TS_PACKET_SIZE);
451 static int mpegts_write_header(AVFormatContext *s)
453 MpegTSWrite *ts = s->priv_data;
454 MpegTSWriteStream *ts_st;
455 MpegTSService *service;
456 AVStream *st, *pcr_st = NULL;
457 AVDictionaryEntry *title, *provider;
459 const char *service_name;
460 const char *provider_name;
463 // round up to a whole number of TS packets
464 ts->pes_payload_size = (ts->pes_payload_size + 14 + 183) / 184 * 184 - 14;
466 ts->tsid = ts->transport_stream_id;
467 ts->onid = ts->original_network_id;
468 /* allocate a single DVB service */
469 title = av_dict_get(s->metadata, "service_name", NULL, 0);
471 title = av_dict_get(s->metadata, "title", NULL, 0);
472 service_name = title ? title->value : DEFAULT_SERVICE_NAME;
473 provider = av_dict_get(s->metadata, "service_provider", NULL, 0);
474 provider_name = provider ? provider->value : DEFAULT_PROVIDER_NAME;
475 service = mpegts_add_service(ts, ts->service_id, provider_name, service_name);
476 service->pmt.write_packet = section_write_packet;
477 service->pmt.opaque = s;
478 service->pmt.cc = 15;
480 ts->pat.pid = PAT_PID;
481 ts->pat.cc = 15; // Initialize at 15 so that it wraps and be equal to 0 for the first packet we write
482 ts->pat.write_packet = section_write_packet;
485 ts->sdt.pid = SDT_PID;
487 ts->sdt.write_packet = section_write_packet;
490 pids = av_malloc(s->nb_streams * sizeof(*pids));
492 return AVERROR(ENOMEM);
494 /* assign pids to each stream */
495 for(i = 0;i < s->nb_streams; i++) {
497 avpriv_set_pts_info(st, 33, 1, 90000);
498 ts_st = av_mallocz(sizeof(MpegTSWriteStream));
501 st->priv_data = ts_st;
502 ts_st->payload = av_mallocz(ts->pes_payload_size);
505 ts_st->service = service;
506 /* MPEG pid values < 16 are reserved. Applications which set st->id in
507 * this range are assigned a calculated pid. */
509 ts_st->pid = ts->start_pid + i;
510 } else if (st->id < 0x1FFF) {
513 av_log(s, AV_LOG_ERROR, "Invalid stream id %d, must be less than 8191\n", st->id);
516 if (ts_st->pid == service->pmt.pid) {
517 av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
520 for (j = 0; j < i; j++)
521 if (pids[j] == ts_st->pid) {
522 av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
525 pids[i] = ts_st->pid;
526 ts_st->payload_pts = AV_NOPTS_VALUE;
527 ts_st->payload_dts = AV_NOPTS_VALUE;
528 ts_st->first_pts_check = 1;
530 /* update PCR pid by using the first video stream */
531 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
532 service->pcr_pid == 0x1fff) {
533 service->pcr_pid = ts_st->pid;
536 if (st->codec->codec_id == CODEC_ID_AAC &&
537 st->codec->extradata_size > 0) {
538 ts_st->adts = av_mallocz(sizeof(*ts_st->adts));
541 if (ff_adts_decode_extradata(s, ts_st->adts, st->codec->extradata,
542 st->codec->extradata_size) < 0)
549 /* if no video stream, use the first stream as PCR */
550 if (service->pcr_pid == 0x1fff && s->nb_streams > 0) {
551 pcr_st = s->streams[0];
552 ts_st = pcr_st->priv_data;
553 service->pcr_pid = ts_st->pid;
556 if (ts->mux_rate > 1) {
557 service->pcr_packet_period = (ts->mux_rate * PCR_RETRANS_TIME) /
558 (TS_PACKET_SIZE * 8 * 1000);
559 ts->sdt_packet_period = (ts->mux_rate * SDT_RETRANS_TIME) /
560 (TS_PACKET_SIZE * 8 * 1000);
561 ts->pat_packet_period = (ts->mux_rate * PAT_RETRANS_TIME) /
562 (TS_PACKET_SIZE * 8 * 1000);
564 ts->first_pcr = av_rescale(s->max_delay, PCR_TIME_BASE, AV_TIME_BASE);
566 /* Arbitrary values, PAT/PMT could be written on key frames */
567 ts->sdt_packet_period = 200;
568 ts->pat_packet_period = 40;
569 if (pcr_st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
570 if (!pcr_st->codec->frame_size) {
571 av_log(s, AV_LOG_WARNING, "frame size not set\n");
572 service->pcr_packet_period =
573 pcr_st->codec->sample_rate/(10*512);
575 service->pcr_packet_period =
576 pcr_st->codec->sample_rate/(10*pcr_st->codec->frame_size);
579 // max delta PCR 0.1s
580 service->pcr_packet_period =
581 pcr_st->codec->time_base.den/(10*pcr_st->codec->time_base.num);
585 // output a PCR as soon as possible
586 service->pcr_packet_count = service->pcr_packet_period;
587 ts->pat_packet_count = ts->pat_packet_period-1;
588 ts->sdt_packet_count = ts->sdt_packet_period-1;
590 if (ts->mux_rate == 1)
591 av_log(s, AV_LOG_INFO, "muxrate VBR, ");
593 av_log(s, AV_LOG_INFO, "muxrate %d, ", ts->mux_rate);
594 av_log(s, AV_LOG_INFO, "pcr every %d pkts, "
595 "sdt every %d, pat/pmt every %d pkts\n",
596 service->pcr_packet_period,
597 ts->sdt_packet_period, ts->pat_packet_period);
605 for(i = 0;i < s->nb_streams; i++) {
606 MpegTSWriteStream *ts_st;
608 ts_st = st->priv_data;
610 av_freep(&ts_st->payload);
611 av_freep(&ts_st->adts);
613 av_freep(&st->priv_data);
618 /* send SDT, PAT and PMT tables regulary */
619 static void retransmit_si_info(AVFormatContext *s)
621 MpegTSWrite *ts = s->priv_data;
624 if (++ts->sdt_packet_count == ts->sdt_packet_period) {
625 ts->sdt_packet_count = 0;
628 if (++ts->pat_packet_count == ts->pat_packet_period) {
629 ts->pat_packet_count = 0;
631 for(i = 0; i < ts->nb_services; i++) {
632 mpegts_write_pmt(s, ts->services[i]);
637 static int64_t get_pcr(const MpegTSWrite *ts, AVIOContext *pb)
639 return av_rescale(avio_tell(pb) + 11, 8 * PCR_TIME_BASE, ts->mux_rate) +
643 static int write_pcr_bits(uint8_t *buf, int64_t pcr)
645 int64_t pcr_low = pcr % 300, pcr_high = pcr / 300;
647 *buf++ = pcr_high >> 25;
648 *buf++ = pcr_high >> 17;
649 *buf++ = pcr_high >> 9;
650 *buf++ = pcr_high >> 1;
651 *buf++ = pcr_high << 7 | pcr_low >> 8 | 0x7e;
657 /* Write a single null transport stream packet */
658 static void mpegts_insert_null_packet(AVFormatContext *s)
661 uint8_t buf[TS_PACKET_SIZE];
668 memset(q, 0x0FF, TS_PACKET_SIZE - (q - buf));
669 avio_write(s->pb, buf, TS_PACKET_SIZE);
672 /* Write a single transport stream packet with a PCR and no payload */
673 static void mpegts_insert_pcr_only(AVFormatContext *s, AVStream *st)
675 MpegTSWrite *ts = s->priv_data;
676 MpegTSWriteStream *ts_st = st->priv_data;
678 uint8_t buf[TS_PACKET_SIZE];
682 *q++ = ts_st->pid >> 8;
684 *q++ = 0x20 | ts_st->cc; /* Adaptation only */
685 /* Continuity Count field does not increment (see 13818-1 section 2.4.3.3) */
686 *q++ = TS_PACKET_SIZE - 5; /* Adaptation Field Length */
687 *q++ = 0x10; /* Adaptation flags: PCR present */
689 /* PCR coded into 6 bytes */
690 q += write_pcr_bits(q, get_pcr(ts, s->pb));
693 memset(q, 0xFF, TS_PACKET_SIZE - (q - buf));
694 avio_write(s->pb, buf, TS_PACKET_SIZE);
697 static void write_pts(uint8_t *q, int fourbits, int64_t pts)
701 val = fourbits << 4 | (((pts >> 30) & 0x07) << 1) | 1;
703 val = (((pts >> 15) & 0x7fff) << 1) | 1;
706 val = (((pts) & 0x7fff) << 1) | 1;
711 /* Set an adaptation field flag in an MPEG-TS packet*/
712 static void set_af_flag(uint8_t *pkt, int flag)
714 // expect at least one flag to set
717 if ((pkt[3] & 0x20) == 0) {
718 // no AF yet, set adaptation field flag
720 // 1 byte length, no flags
727 /* Extend the adaptation field by size bytes */
728 static void extend_af(uint8_t *pkt, int size)
730 // expect already existing adaptation field
731 assert(pkt[3] & 0x20);
735 /* Get a pointer to MPEG-TS payload (right after TS packet header) */
736 static uint8_t *get_ts_payload_start(uint8_t *pkt)
739 return pkt + 5 + pkt[4];
744 /* Add a pes header to the front of payload, and segment into an integer number of
745 * ts packets. The final ts packet is padded using an over-sized adaptation header
746 * to exactly fill the last ts packet.
747 * NOTE: 'payload' contains a complete PES payload.
749 static void mpegts_write_pes(AVFormatContext *s, AVStream *st,
750 const uint8_t *payload, int payload_size,
751 int64_t pts, int64_t dts, int key)
753 MpegTSWriteStream *ts_st = st->priv_data;
754 MpegTSWrite *ts = s->priv_data;
755 uint8_t buf[TS_PACKET_SIZE];
757 int val, is_start, len, header_len, write_pcr, private_code, flags;
758 int afc_len, stuffing_len;
759 int64_t pcr = -1; /* avoid warning */
760 int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE);
763 while (payload_size > 0) {
764 retransmit_si_info(s);
767 if (ts_st->pid == ts_st->service->pcr_pid) {
768 if (ts->mux_rate > 1 || is_start) // VBR pcr period is based on frames
769 ts_st->service->pcr_packet_count++;
770 if (ts_st->service->pcr_packet_count >=
771 ts_st->service->pcr_packet_period) {
772 ts_st->service->pcr_packet_count = 0;
777 if (ts->mux_rate > 1 && dts != AV_NOPTS_VALUE &&
778 (dts - get_pcr(ts, s->pb)/300) > delay) {
779 /* pcr insert gets priority over null packet insert */
781 mpegts_insert_pcr_only(s, st);
783 mpegts_insert_null_packet(s);
784 continue; /* recalculate write_pcr and possibly retransmit si_info */
787 /* prepare packet header */
790 val = (ts_st->pid >> 8);
795 ts_st->cc = (ts_st->cc + 1) & 0xf;
796 *q++ = 0x10 | ts_st->cc; // payload indicator + CC
797 if (key && is_start && pts != AV_NOPTS_VALUE) {
798 // set Random Access for key frames
799 if (ts_st->pid == ts_st->service->pcr_pid)
801 set_af_flag(buf, 0x40);
802 q = get_ts_payload_start(buf);
805 set_af_flag(buf, 0x10);
806 q = get_ts_payload_start(buf);
807 // add 11, pcr references the last byte of program clock reference base
808 if (ts->mux_rate > 1)
809 pcr = get_pcr(ts, s->pb);
811 pcr = (dts - delay)*300;
812 if (dts != AV_NOPTS_VALUE && dts < pcr / 300)
813 av_log(s, AV_LOG_WARNING, "dts < pcr, TS is invalid\n");
814 extend_af(buf, write_pcr_bits(q, pcr));
815 q = get_ts_payload_start(buf);
818 int pes_extension = 0;
819 /* write PES header */
824 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
825 if (st->codec->codec_id == CODEC_ID_DIRAC) {
829 } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
830 (st->codec->codec_id == CODEC_ID_MP2 ||
831 st->codec->codec_id == CODEC_ID_MP3 ||
832 st->codec->codec_id == CODEC_ID_AAC)) {
836 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
842 if (pts != AV_NOPTS_VALUE) {
846 if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
850 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
851 st->codec->codec_id == CODEC_ID_DIRAC) {
852 /* set PES_extension_flag */
857 * One byte for PES2 extension flag +
858 * one byte for extension length +
859 * one byte for extension id
863 len = payload_size + header_len + 3;
864 if (private_code != 0)
871 /* data alignment indicator is required for subtitle data */
872 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)
877 if (pts != AV_NOPTS_VALUE) {
878 write_pts(q, flags >> 6, pts);
881 if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
882 write_pts(q, 1, dts);
885 if (pes_extension && st->codec->codec_id == CODEC_ID_DIRAC) {
886 flags = 0x01; /* set PES_extension_flag_2 */
888 *q++ = 0x80 | 0x01; /* marker bit + extension length */
890 * Set the stream id extension flag bit to 0 and
891 * write the extended stream id
895 if (private_code != 0)
900 header_len = q - buf;
902 len = TS_PACKET_SIZE - header_len;
903 if (len > payload_size)
905 stuffing_len = TS_PACKET_SIZE - header_len - len;
906 if (stuffing_len > 0) {
907 /* add stuffing with AFC */
909 /* stuffing already present: increase its size */
910 afc_len = buf[4] + 1;
911 memmove(buf + 4 + afc_len + stuffing_len,
913 header_len - (4 + afc_len));
914 buf[4] += stuffing_len;
915 memset(buf + 4 + afc_len, 0xff, stuffing_len);
918 memmove(buf + 4 + stuffing_len, buf + 4, header_len - 4);
920 buf[4] = stuffing_len - 1;
921 if (stuffing_len >= 2) {
923 memset(buf + 6, 0xff, stuffing_len - 2);
927 memcpy(buf + TS_PACKET_SIZE - len, payload, len);
930 avio_write(s->pb, buf, TS_PACKET_SIZE);
935 static int mpegts_write_packet(AVFormatContext *s, AVPacket *pkt)
937 AVStream *st = s->streams[pkt->stream_index];
938 int size = pkt->size;
939 uint8_t *buf= pkt->data;
941 MpegTSWrite *ts = s->priv_data;
942 MpegTSWriteStream *ts_st = st->priv_data;
943 const uint64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE)*2;
944 int64_t dts = AV_NOPTS_VALUE, pts = AV_NOPTS_VALUE;
946 if (ts->reemit_pat_pmt) {
947 ts->pat_packet_count = ts->pat_packet_period - 1;
948 ts->sdt_packet_count = ts->sdt_packet_period - 1;
949 ts->reemit_pat_pmt = 0;
952 if (pkt->pts != AV_NOPTS_VALUE)
953 pts = pkt->pts + delay;
954 if (pkt->dts != AV_NOPTS_VALUE)
955 dts = pkt->dts + delay;
957 if (ts_st->first_pts_check && pts == AV_NOPTS_VALUE) {
958 av_log(s, AV_LOG_ERROR, "first pts value must set\n");
961 ts_st->first_pts_check = 0;
963 if (st->codec->codec_id == CODEC_ID_H264) {
964 const uint8_t *p = buf, *buf_end = p+size;
967 if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001) {
968 av_log(s, AV_LOG_ERROR, "H.264 bitstream malformed, "
969 "no startcode found, use -bsf h264_mp4toannexb\n");
974 p = avpriv_mpv_find_start_code(p, buf_end, &state);
975 //av_log(s, AV_LOG_INFO, "nal %d\n", state & 0x1f);
976 } while (p < buf_end && (state & 0x1f) != 9 &&
977 (state & 0x1f) != 5 && (state & 0x1f) != 1);
979 if ((state & 0x1f) != 9) { // AUD NAL
980 data = av_malloc(pkt->size+6);
983 memcpy(data+6, pkt->data, pkt->size);
984 AV_WB32(data, 0x00000001);
986 data[5] = 0xf0; // any slice type (0xe) + rbsp stop one bit
990 } else if (st->codec->codec_id == CODEC_ID_AAC) {
993 if ((AV_RB16(pkt->data) & 0xfff0) != 0xfff0) {
994 ADTSContext *adts = ts_st->adts;
997 av_log(s, AV_LOG_ERROR, "aac bitstream not in adts format "
998 "and extradata missing\n");
1001 new_size = ADTS_HEADER_SIZE+adts->pce_size+pkt->size;
1002 if ((unsigned)new_size >= INT_MAX)
1004 data = av_malloc(new_size);
1006 return AVERROR(ENOMEM);
1007 err = ff_adts_write_frame_header(adts, data, pkt->size,
1013 if (adts->pce_size) {
1014 memcpy(data+ADTS_HEADER_SIZE, adts->pce_data, adts->pce_size);
1017 memcpy(data+ADTS_HEADER_SIZE+adts->pce_size, pkt->data, pkt->size);
1023 if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO) {
1024 // for video and subtitle, write a single pes packet
1025 mpegts_write_pes(s, st, buf, size, pts, dts, pkt->flags & AV_PKT_FLAG_KEY);
1030 if (ts_st->payload_size + size > ts->pes_payload_size) {
1031 if (ts_st->payload_size) {
1032 mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_size,
1033 ts_st->payload_pts, ts_st->payload_dts,
1034 ts_st->payload_flags & AV_PKT_FLAG_KEY);
1035 ts_st->payload_size = 0;
1037 if (size > ts->pes_payload_size) {
1038 mpegts_write_pes(s, st, buf, size, pts, dts,
1039 pkt->flags & AV_PKT_FLAG_KEY);
1045 if (!ts_st->payload_size) {
1046 ts_st->payload_pts = pts;
1047 ts_st->payload_dts = dts;
1048 ts_st->payload_flags = pkt->flags;
1051 memcpy(ts_st->payload + ts_st->payload_size, buf, size);
1052 ts_st->payload_size += size;
1059 static int mpegts_write_end(AVFormatContext *s)
1061 MpegTSWrite *ts = s->priv_data;
1062 MpegTSWriteStream *ts_st;
1063 MpegTSService *service;
1067 /* flush current packets */
1068 for(i = 0; i < s->nb_streams; i++) {
1070 ts_st = st->priv_data;
1071 if (ts_st->payload_size > 0) {
1072 mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_size,
1073 ts_st->payload_pts, ts_st->payload_dts,
1074 ts_st->payload_flags & AV_PKT_FLAG_KEY);
1076 av_freep(&ts_st->payload);
1077 av_freep(&ts_st->adts);
1081 for(i = 0; i < ts->nb_services; i++) {
1082 service = ts->services[i];
1083 av_freep(&service->provider_name);
1084 av_freep(&service->name);
1087 av_free(ts->services);
1092 AVOutputFormat ff_mpegts_muxer = {
1094 .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
1095 .mime_type = "video/x-mpegts",
1096 .extensions = "ts,m2t",
1097 .priv_data_size = sizeof(MpegTSWrite),
1098 .audio_codec = CODEC_ID_MP2,
1099 .video_codec = CODEC_ID_MPEG2VIDEO,
1100 .write_header = mpegts_write_header,
1101 .write_packet = mpegts_write_packet,
1102 .write_trailer = mpegts_write_end,
1103 .priv_class = &mpegts_muxer_class,