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/opt.h"
25 #include "libavcodec/mpegvideo.h"
31 #define PCR_TIME_BASE 27000000
33 /* write DVB SI sections */
35 /*********************************************/
36 /* mpegts section writer */
38 typedef struct MpegTSSection {
41 void (*write_packet)(struct MpegTSSection *s, const uint8_t *packet);
45 typedef struct MpegTSService {
46 MpegTSSection pmt; /* MPEG2 pmt table context */
47 int sid; /* service ID */
52 int pcr_packet_period;
55 typedef struct MpegTSWrite {
56 MpegTSSection pat; /* MPEG2 pat table */
57 MpegTSSection sdt; /* MPEG2 sdt table context */
58 MpegTSService **services;
60 int sdt_packet_period;
62 int pat_packet_period;
67 int mux_rate; ///< set to 1 when VBR
69 int transport_stream_id;
70 int original_network_id;
77 static const AVOption options[] = {
78 { "mpegts_transport_stream_id", "Set transport_stream_id field.",
79 offsetof(MpegTSWrite, transport_stream_id), FF_OPT_TYPE_INT, {.dbl = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
80 { "mpegts_original_network_id", "Set original_network_id field.",
81 offsetof(MpegTSWrite, original_network_id), FF_OPT_TYPE_INT, {.dbl = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
82 { "mpegts_service_id", "Set service_id field.",
83 offsetof(MpegTSWrite, service_id), FF_OPT_TYPE_INT, {.dbl = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
84 { "mpegts_pmt_start_pid", "Set the first pid of the PMT.",
85 offsetof(MpegTSWrite, pmt_start_pid), FF_OPT_TYPE_INT, {.dbl = 0x1000 }, 0x1000, 0x1f00, AV_OPT_FLAG_ENCODING_PARAM},
86 { "mpegts_start_pid", "Set the first pid.",
87 offsetof(MpegTSWrite, start_pid), FF_OPT_TYPE_INT, {.dbl = 0x0100 }, 0x0100, 0x0f00, AV_OPT_FLAG_ENCODING_PARAM},
91 static const AVClass mpegts_muxer_class = {
92 .class_name = "MPEGTS muxer",
93 .item_name = av_default_item_name,
95 .version = LIBAVUTIL_VERSION_INT,
98 /* NOTE: 4 bytes must be left at the end for the crc32 */
99 static void mpegts_write_section(MpegTSSection *s, uint8_t *buf, int len)
102 unsigned char packet[TS_PACKET_SIZE];
103 const unsigned char *buf_ptr;
105 int first, b, len1, left;
107 crc = av_bswap32(av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1, buf, len - 4));
108 buf[len - 4] = (crc >> 24) & 0xff;
109 buf[len - 3] = (crc >> 16) & 0xff;
110 buf[len - 2] = (crc >> 8) & 0xff;
111 buf[len - 1] = (crc) & 0xff;
113 /* send each packet */
116 first = (buf == buf_ptr);
124 s->cc = (s->cc + 1) & 0xf;
127 *q++ = 0; /* 0 offset */
128 len1 = TS_PACKET_SIZE - (q - packet);
131 memcpy(q, buf_ptr, len1);
133 /* add known padding data */
134 left = TS_PACKET_SIZE - (q - packet);
136 memset(q, 0xff, left);
138 s->write_packet(s, packet);
145 static inline void put16(uint8_t **q_ptr, int val)
154 static int mpegts_write_section1(MpegTSSection *s, int tid, int id,
155 int version, int sec_num, int last_sec_num,
156 uint8_t *buf, int len)
158 uint8_t section[1024], *q;
159 unsigned int tot_len;
160 /* reserved_future_use field must be set to 1 for SDT */
161 unsigned int flags = tid == SDT_TID ? 0xf000 : 0xb000;
163 tot_len = 3 + 5 + len + 4;
164 /* check if not too big */
170 put16(&q, flags | (len + 5 + 4)); /* 5 byte header + 4 byte CRC */
172 *q++ = 0xc1 | (version << 1); /* current_next_indicator = 1 */
177 mpegts_write_section(s, section, tot_len);
181 /*********************************************/
184 #define DEFAULT_PROVIDER_NAME "FFmpeg"
185 #define DEFAULT_SERVICE_NAME "Service01"
187 /* a PES packet header is generated every DEFAULT_PES_HEADER_FREQ packets */
188 #define DEFAULT_PES_HEADER_FREQ 16
189 #define DEFAULT_PES_PAYLOAD_SIZE ((DEFAULT_PES_HEADER_FREQ - 1) * 184 + 170)
191 /* we retransmit the SI info at this rate */
192 #define SDT_RETRANS_TIME 500
193 #define PAT_RETRANS_TIME 100
194 #define PCR_RETRANS_TIME 20
196 typedef struct MpegTSWriteStream {
197 struct MpegTSService *service;
198 int pid; /* stream associated pid */
201 int first_pts_check; ///< first pts check needed
204 uint8_t payload[DEFAULT_PES_PAYLOAD_SIZE];
208 static void mpegts_write_pat(AVFormatContext *s)
210 MpegTSWrite *ts = s->priv_data;
211 MpegTSService *service;
212 uint8_t data[1012], *q;
216 for(i = 0; i < ts->nb_services; i++) {
217 service = ts->services[i];
218 put16(&q, service->sid);
219 put16(&q, 0xe000 | service->pmt.pid);
221 mpegts_write_section1(&ts->pat, PAT_TID, ts->tsid, 0, 0, 0,
225 static void mpegts_write_pmt(AVFormatContext *s, MpegTSService *service)
227 // MpegTSWrite *ts = s->priv_data;
228 uint8_t data[1012], *q, *desc_length_ptr, *program_info_length_ptr;
229 int val, stream_type, i;
232 put16(&q, 0xe000 | service->pcr_pid);
234 program_info_length_ptr = q;
235 q += 2; /* patched after */
237 /* put program info here */
239 val = 0xf000 | (q - program_info_length_ptr - 2);
240 program_info_length_ptr[0] = val >> 8;
241 program_info_length_ptr[1] = val;
243 for(i = 0; i < s->nb_streams; i++) {
244 AVStream *st = s->streams[i];
245 MpegTSWriteStream *ts_st = st->priv_data;
246 AVMetadataTag *lang = av_metadata_get(st->metadata, "language", NULL,0);
247 switch(st->codec->codec_id) {
248 case CODEC_ID_MPEG1VIDEO:
249 case CODEC_ID_MPEG2VIDEO:
250 stream_type = STREAM_TYPE_VIDEO_MPEG2;
253 stream_type = STREAM_TYPE_VIDEO_MPEG4;
256 stream_type = STREAM_TYPE_VIDEO_H264;
259 stream_type = STREAM_TYPE_VIDEO_DIRAC;
263 stream_type = STREAM_TYPE_AUDIO_MPEG1;
266 stream_type = STREAM_TYPE_AUDIO_AAC;
268 case CODEC_ID_AAC_LATM:
269 stream_type = STREAM_TYPE_AUDIO_AAC_LATM;
272 stream_type = STREAM_TYPE_AUDIO_AC3;
275 stream_type = STREAM_TYPE_PRIVATE_DATA;
279 put16(&q, 0xe000 | ts_st->pid);
281 q += 2; /* patched after */
283 /* write optional descriptors here */
284 switch(st->codec->codec_type) {
285 case AVMEDIA_TYPE_AUDIO:
288 char *next = lang->value;
291 *q++ = 0x0a; /* ISO 639 language descriptor */
295 for (p = lang->value; next && *len_ptr < 255 / 4 * 4; p = next + 1) {
296 next = strchr(p, ',');
297 if (strlen(p) != 3 && (!next || next != p + 3))
298 continue; /* not a 3-letter code */
304 if (st->disposition & AV_DISPOSITION_CLEAN_EFFECTS)
306 else if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
308 else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
311 *q++ = 0; /* undefined type */
317 q -= 2; /* no language codes were written */
320 case AVMEDIA_TYPE_SUBTITLE:
322 const char *language;
323 language = lang && strlen(lang->value)==3 ? lang->value : "eng";
329 *q++ = 0x10; /* normal subtitles (0x20 = if hearing pb) */
330 if(st->codec->extradata_size == 4) {
331 memcpy(q, st->codec->extradata, 4);
334 put16(&q, 1); /* page id */
335 put16(&q, 1); /* ancillary page id */
339 case AVMEDIA_TYPE_VIDEO:
340 if (stream_type == STREAM_TYPE_VIDEO_DIRAC) {
341 *q++ = 0x05; /*MPEG-2 registration descriptor*/
351 val = 0xf000 | (q - desc_length_ptr - 2);
352 desc_length_ptr[0] = val >> 8;
353 desc_length_ptr[1] = val;
355 mpegts_write_section1(&service->pmt, PMT_TID, service->sid, 0, 0, 0,
359 /* NOTE: str == NULL is accepted for an empty string */
360 static void putstr8(uint8_t **q_ptr, const char *str)
376 static void mpegts_write_sdt(AVFormatContext *s)
378 MpegTSWrite *ts = s->priv_data;
379 MpegTSService *service;
380 uint8_t data[1012], *q, *desc_list_len_ptr, *desc_len_ptr;
381 int i, running_status, free_ca_mode, val;
386 for(i = 0; i < ts->nb_services; i++) {
387 service = ts->services[i];
388 put16(&q, service->sid);
389 *q++ = 0xfc | 0x00; /* currently no EIT info */
390 desc_list_len_ptr = q;
392 running_status = 4; /* running */
395 /* write only one descriptor for the service name and provider */
399 *q++ = 0x01; /* digital television service */
400 putstr8(&q, service->provider_name);
401 putstr8(&q, service->name);
402 desc_len_ptr[0] = q - desc_len_ptr - 1;
404 /* fill descriptor length */
405 val = (running_status << 13) | (free_ca_mode << 12) |
406 (q - desc_list_len_ptr - 2);
407 desc_list_len_ptr[0] = val >> 8;
408 desc_list_len_ptr[1] = val;
410 mpegts_write_section1(&ts->sdt, SDT_TID, ts->tsid, 0, 0, 0,
414 static MpegTSService *mpegts_add_service(MpegTSWrite *ts,
416 const char *provider_name,
419 MpegTSService *service;
421 service = av_mallocz(sizeof(MpegTSService));
424 service->pmt.pid = ts->pmt_start_pid + ts->nb_services;
426 service->provider_name = av_strdup(provider_name);
427 service->name = av_strdup(name);
428 service->pcr_pid = 0x1fff;
429 dynarray_add(&ts->services, &ts->nb_services, service);
433 static void section_write_packet(MpegTSSection *s, const uint8_t *packet)
435 AVFormatContext *ctx = s->opaque;
436 avio_write(ctx->pb, packet, TS_PACKET_SIZE);
439 static int mpegts_write_header(AVFormatContext *s)
441 MpegTSWrite *ts = s->priv_data;
442 MpegTSWriteStream *ts_st;
443 MpegTSService *service;
444 AVStream *st, *pcr_st = NULL;
445 AVMetadataTag *title, *provider;
447 const char *service_name;
448 const char *provider_name;
451 ts->tsid = ts->transport_stream_id;
452 ts->onid = ts->original_network_id;
453 /* allocate a single DVB service */
454 title = av_metadata_get(s->metadata, "service_name", NULL, 0);
456 title = av_metadata_get(s->metadata, "title", NULL, 0);
457 service_name = title ? title->value : DEFAULT_SERVICE_NAME;
458 provider = av_metadata_get(s->metadata, "service_provider", NULL, 0);
459 provider_name = provider ? provider->value : DEFAULT_PROVIDER_NAME;
460 service = mpegts_add_service(ts, ts->service_id, provider_name, service_name);
461 service->pmt.write_packet = section_write_packet;
462 service->pmt.opaque = s;
463 service->pmt.cc = 15;
465 ts->pat.pid = PAT_PID;
466 ts->pat.cc = 15; // Initialize at 15 so that it wraps and be equal to 0 for the first packet we write
467 ts->pat.write_packet = section_write_packet;
470 ts->sdt.pid = SDT_PID;
472 ts->sdt.write_packet = section_write_packet;
475 pids = av_malloc(s->nb_streams * sizeof(*pids));
477 return AVERROR(ENOMEM);
479 /* assign pids to each stream */
480 for(i = 0;i < s->nb_streams; i++) {
482 av_set_pts_info(st, 33, 1, 90000);
483 ts_st = av_mallocz(sizeof(MpegTSWriteStream));
486 st->priv_data = ts_st;
487 ts_st->service = service;
488 /* MPEG pid values < 16 are reserved. Applications which set st->id in
489 * this range are assigned a calculated pid. */
491 ts_st->pid = ts->start_pid + i;
492 } else if (st->id < 0x1FFF) {
495 av_log(s, AV_LOG_ERROR, "Invalid stream id %d, must be less than 8191\n", st->id);
498 if (ts_st->pid == service->pmt.pid) {
499 av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
502 for (j = 0; j < i; j++)
503 if (pids[j] == ts_st->pid) {
504 av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
507 pids[i] = ts_st->pid;
508 ts_st->payload_pts = AV_NOPTS_VALUE;
509 ts_st->payload_dts = AV_NOPTS_VALUE;
510 ts_st->first_pts_check = 1;
512 /* update PCR pid by using the first video stream */
513 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
514 service->pcr_pid == 0x1fff) {
515 service->pcr_pid = ts_st->pid;
518 if (st->codec->codec_id == CODEC_ID_AAC &&
519 st->codec->extradata_size > 0) {
520 ts_st->adts = av_mallocz(sizeof(*ts_st->adts));
522 return AVERROR(ENOMEM);
523 if (ff_adts_decode_extradata(s, ts_st->adts, st->codec->extradata,
524 st->codec->extradata_size) < 0)
531 /* if no video stream, use the first stream as PCR */
532 if (service->pcr_pid == 0x1fff && s->nb_streams > 0) {
533 pcr_st = s->streams[0];
534 ts_st = pcr_st->priv_data;
535 service->pcr_pid = ts_st->pid;
538 ts->mux_rate = s->mux_rate ? s->mux_rate : 1;
540 if (ts->mux_rate > 1) {
541 service->pcr_packet_period = (ts->mux_rate * PCR_RETRANS_TIME) /
542 (TS_PACKET_SIZE * 8 * 1000);
543 ts->sdt_packet_period = (ts->mux_rate * SDT_RETRANS_TIME) /
544 (TS_PACKET_SIZE * 8 * 1000);
545 ts->pat_packet_period = (ts->mux_rate * PAT_RETRANS_TIME) /
546 (TS_PACKET_SIZE * 8 * 1000);
548 ts->first_pcr = av_rescale(s->max_delay, PCR_TIME_BASE, AV_TIME_BASE);
550 /* Arbitrary values, PAT/PMT could be written on key frames */
551 ts->sdt_packet_period = 200;
552 ts->pat_packet_period = 40;
553 if (pcr_st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
554 if (!pcr_st->codec->frame_size) {
555 av_log(s, AV_LOG_WARNING, "frame size not set\n");
556 service->pcr_packet_period =
557 pcr_st->codec->sample_rate/(10*512);
559 service->pcr_packet_period =
560 pcr_st->codec->sample_rate/(10*pcr_st->codec->frame_size);
563 // max delta PCR 0.1s
564 service->pcr_packet_period =
565 pcr_st->codec->time_base.den/(10*pcr_st->codec->time_base.num);
569 // output a PCR as soon as possible
570 service->pcr_packet_count = service->pcr_packet_period;
571 ts->pat_packet_count = ts->pat_packet_period-1;
572 ts->sdt_packet_count = ts->sdt_packet_period-1;
574 if (ts->mux_rate == 1)
575 av_log(s, AV_LOG_INFO, "muxrate VBR, ");
577 av_log(s, AV_LOG_INFO, "muxrate %d, ", ts->mux_rate);
578 av_log(s, AV_LOG_INFO, "pcr every %d pkts, "
579 "sdt every %d, pat/pmt every %d pkts\n",
580 service->pcr_packet_period,
581 ts->sdt_packet_period, ts->pat_packet_period);
589 for(i = 0;i < s->nb_streams; i++) {
591 av_free(st->priv_data);
596 /* send SDT, PAT and PMT tables regulary */
597 static void retransmit_si_info(AVFormatContext *s)
599 MpegTSWrite *ts = s->priv_data;
602 if (++ts->sdt_packet_count == ts->sdt_packet_period) {
603 ts->sdt_packet_count = 0;
606 if (++ts->pat_packet_count == ts->pat_packet_period) {
607 ts->pat_packet_count = 0;
609 for(i = 0; i < ts->nb_services; i++) {
610 mpegts_write_pmt(s, ts->services[i]);
615 static int64_t get_pcr(const MpegTSWrite *ts, AVIOContext *pb)
617 return av_rescale(avio_tell(pb) + 11, 8 * PCR_TIME_BASE, ts->mux_rate) +
621 static uint8_t* write_pcr_bits(uint8_t *buf, int64_t pcr)
623 int64_t pcr_low = pcr % 300, pcr_high = pcr / 300;
625 *buf++ = pcr_high >> 25;
626 *buf++ = pcr_high >> 17;
627 *buf++ = pcr_high >> 9;
628 *buf++ = pcr_high >> 1;
629 *buf++ = pcr_high << 7 | pcr_low >> 8 | 0x7e;
635 /* Write a single null transport stream packet */
636 static void mpegts_insert_null_packet(AVFormatContext *s)
639 uint8_t buf[TS_PACKET_SIZE];
646 memset(q, 0x0FF, TS_PACKET_SIZE - (q - buf));
647 avio_write(s->pb, buf, TS_PACKET_SIZE);
650 /* Write a single transport stream packet with a PCR and no payload */
651 static void mpegts_insert_pcr_only(AVFormatContext *s, AVStream *st)
653 MpegTSWrite *ts = s->priv_data;
654 MpegTSWriteStream *ts_st = st->priv_data;
656 uint8_t buf[TS_PACKET_SIZE];
660 *q++ = ts_st->pid >> 8;
662 *q++ = 0x20 | ts_st->cc; /* Adaptation only */
663 /* Continuity Count field does not increment (see 13818-1 section 2.4.3.3) */
664 *q++ = TS_PACKET_SIZE - 5; /* Adaptation Field Length */
665 *q++ = 0x10; /* Adaptation flags: PCR present */
667 /* PCR coded into 6 bytes */
668 q = write_pcr_bits(q, get_pcr(ts, s->pb));
671 memset(q, 0xFF, TS_PACKET_SIZE - (q - buf));
672 avio_write(s->pb, buf, TS_PACKET_SIZE);
675 static void write_pts(uint8_t *q, int fourbits, int64_t pts)
679 val = fourbits << 4 | (((pts >> 30) & 0x07) << 1) | 1;
681 val = (((pts >> 15) & 0x7fff) << 1) | 1;
684 val = (((pts) & 0x7fff) << 1) | 1;
689 /* Add a pes header to the front of payload, and segment into an integer number of
690 * ts packets. The final ts packet is padded using an over-sized adaptation header
691 * to exactly fill the last ts packet.
692 * NOTE: 'payload' contains a complete PES payload.
694 static void mpegts_write_pes(AVFormatContext *s, AVStream *st,
695 const uint8_t *payload, int payload_size,
696 int64_t pts, int64_t dts)
698 MpegTSWriteStream *ts_st = st->priv_data;
699 MpegTSWrite *ts = s->priv_data;
700 uint8_t buf[TS_PACKET_SIZE];
702 int val, is_start, len, header_len, write_pcr, private_code, flags;
703 int afc_len, stuffing_len;
704 int64_t pcr = -1; /* avoid warning */
705 int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE);
708 while (payload_size > 0) {
709 retransmit_si_info(s);
712 if (ts_st->pid == ts_st->service->pcr_pid) {
713 if (ts->mux_rate > 1 || is_start) // VBR pcr period is based on frames
714 ts_st->service->pcr_packet_count++;
715 if (ts_st->service->pcr_packet_count >=
716 ts_st->service->pcr_packet_period) {
717 ts_st->service->pcr_packet_count = 0;
722 if (ts->mux_rate > 1 && dts != AV_NOPTS_VALUE &&
723 (dts - get_pcr(ts, s->pb)/300) > delay) {
724 /* pcr insert gets priority over null packet insert */
726 mpegts_insert_pcr_only(s, st);
728 mpegts_insert_null_packet(s);
729 continue; /* recalculate write_pcr and possibly retransmit si_info */
732 /* prepare packet header */
735 val = (ts_st->pid >> 8);
740 ts_st->cc = (ts_st->cc + 1) & 0xf;
741 *q++ = 0x10 | ts_st->cc | (write_pcr ? 0x20 : 0);
743 // add 11, pcr references the last byte of program clock reference base
744 if (ts->mux_rate > 1)
745 pcr = get_pcr(ts, s->pb);
747 pcr = (dts - delay)*300;
748 if (dts != AV_NOPTS_VALUE && dts < pcr / 300)
749 av_log(s, AV_LOG_WARNING, "dts < pcr, TS is invalid\n");
750 *q++ = 7; /* AFC length */
751 *q++ = 0x10; /* flags: PCR present */
752 q = write_pcr_bits(q, pcr);
755 int pes_extension = 0;
756 /* write PES header */
761 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
762 if (st->codec->codec_id == CODEC_ID_DIRAC) {
766 } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
767 (st->codec->codec_id == CODEC_ID_MP2 ||
768 st->codec->codec_id == CODEC_ID_MP3 ||
769 st->codec->codec_id == CODEC_ID_AAC)) {
773 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
779 if (pts != AV_NOPTS_VALUE) {
783 if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
787 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
788 st->codec->codec_id == CODEC_ID_DIRAC) {
789 /* set PES_extension_flag */
794 * One byte for PES2 extension flag +
795 * one byte for extension length +
796 * one byte for extension id
800 len = payload_size + header_len + 3;
801 if (private_code != 0)
808 /* data alignment indicator is required for subtitle data */
809 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)
814 if (pts != AV_NOPTS_VALUE) {
815 write_pts(q, flags >> 6, pts);
818 if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
819 write_pts(q, 1, dts);
822 if (pes_extension && st->codec->codec_id == CODEC_ID_DIRAC) {
823 flags = 0x01; /* set PES_extension_flag_2 */
825 *q++ = 0x80 | 0x01; /* marker bit + extension length */
827 * Set the stream id extension flag bit to 0 and
828 * write the extended stream id
832 if (private_code != 0)
837 header_len = q - buf;
839 len = TS_PACKET_SIZE - header_len;
840 if (len > payload_size)
842 stuffing_len = TS_PACKET_SIZE - header_len - len;
843 if (stuffing_len > 0) {
844 /* add stuffing with AFC */
846 /* stuffing already present: increase its size */
847 afc_len = buf[4] + 1;
848 memmove(buf + 4 + afc_len + stuffing_len,
850 header_len - (4 + afc_len));
851 buf[4] += stuffing_len;
852 memset(buf + 4 + afc_len, 0xff, stuffing_len);
855 memmove(buf + 4 + stuffing_len, buf + 4, header_len - 4);
857 buf[4] = stuffing_len - 1;
858 if (stuffing_len >= 2) {
860 memset(buf + 6, 0xff, stuffing_len - 2);
864 memcpy(buf + TS_PACKET_SIZE - len, payload, len);
867 avio_write(s->pb, buf, TS_PACKET_SIZE);
872 static int mpegts_write_packet(AVFormatContext *s, AVPacket *pkt)
874 AVStream *st = s->streams[pkt->stream_index];
875 int size = pkt->size;
876 uint8_t *buf= pkt->data;
878 MpegTSWriteStream *ts_st = st->priv_data;
879 const uint64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE)*2;
880 int64_t dts = AV_NOPTS_VALUE, pts = AV_NOPTS_VALUE;
882 if (pkt->pts != AV_NOPTS_VALUE)
883 pts = pkt->pts + delay;
884 if (pkt->dts != AV_NOPTS_VALUE)
885 dts = pkt->dts + delay;
887 if (ts_st->first_pts_check && pts == AV_NOPTS_VALUE) {
888 av_log(s, AV_LOG_ERROR, "first pts value must set\n");
891 ts_st->first_pts_check = 0;
893 if (st->codec->codec_id == CODEC_ID_H264) {
894 const uint8_t *p = buf, *buf_end = p+size;
897 if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001) {
898 av_log(s, AV_LOG_ERROR, "h264 bitstream malformated, "
899 "no startcode found, use -vbsf h264_mp4toannexb\n");
904 p = ff_find_start_code(p, buf_end, &state);
905 //av_log(s, AV_LOG_INFO, "nal %d\n", state & 0x1f);
906 } while (p < buf_end && (state & 0x1f) != 9 &&
907 (state & 0x1f) != 5 && (state & 0x1f) != 1);
909 if ((state & 0x1f) != 9) { // AUD NAL
910 data = av_malloc(pkt->size+6);
913 memcpy(data+6, pkt->data, pkt->size);
914 AV_WB32(data, 0x00000001);
916 data[5] = 0xf0; // any slice type (0xe) + rbsp stop one bit
920 } else if (st->codec->codec_id == CODEC_ID_AAC) {
923 if ((AV_RB16(pkt->data) & 0xfff0) != 0xfff0) {
924 ADTSContext *adts = ts_st->adts;
927 av_log(s, AV_LOG_ERROR, "aac bitstream not in adts format "
928 "and extradata missing\n");
931 new_size = ADTS_HEADER_SIZE+adts->pce_size+pkt->size;
932 if ((unsigned)new_size >= INT_MAX)
934 data = av_malloc(new_size);
936 return AVERROR(ENOMEM);
937 ff_adts_write_frame_header(adts, data, pkt->size, adts->pce_size);
938 if (adts->pce_size) {
939 memcpy(data+ADTS_HEADER_SIZE, adts->pce_data, adts->pce_size);
942 memcpy(data+ADTS_HEADER_SIZE+adts->pce_size, pkt->data, pkt->size);
948 if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO) {
949 // for video and subtitle, write a single pes packet
950 mpegts_write_pes(s, st, buf, size, pts, dts);
955 if (ts_st->payload_index + size > DEFAULT_PES_PAYLOAD_SIZE) {
956 mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_index,
957 ts_st->payload_pts, ts_st->payload_dts);
958 ts_st->payload_index = 0;
961 if (!ts_st->payload_index) {
962 ts_st->payload_pts = pts;
963 ts_st->payload_dts = dts;
966 memcpy(ts_st->payload + ts_st->payload_index, buf, size);
967 ts_st->payload_index += size;
974 static int mpegts_write_end(AVFormatContext *s)
976 MpegTSWrite *ts = s->priv_data;
977 MpegTSWriteStream *ts_st;
978 MpegTSService *service;
982 /* flush current packets */
983 for(i = 0; i < s->nb_streams; i++) {
985 ts_st = st->priv_data;
986 if (ts_st->payload_index > 0) {
987 mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_index,
988 ts_st->payload_pts, ts_st->payload_dts);
990 av_freep(&ts_st->adts);
994 for(i = 0; i < ts->nb_services; i++) {
995 service = ts->services[i];
996 av_freep(&service->provider_name);
997 av_freep(&service->name);
1000 av_free(ts->services);
1005 AVOutputFormat ff_mpegts_muxer = {
1007 NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
1010 sizeof(MpegTSWrite),
1012 CODEC_ID_MPEG2VIDEO,
1013 mpegts_write_header,
1014 mpegts_write_packet,
1016 .priv_class = &mpegts_muxer_class,