2 * MPEG-2 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/avassert.h"
23 #include "libavutil/bswap.h"
24 #include "libavutil/crc.h"
25 #include "libavutil/dict.h"
26 #include "libavutil/intreadwrite.h"
27 #include "libavutil/mathematics.h"
28 #include "libavutil/opt.h"
30 #include "libavcodec/internal.h"
33 #include "avio_internal.h"
37 #define PCR_TIME_BASE 27000000
39 /* write DVB SI sections */
41 #define DVB_PRIVATE_NETWORK_START 0xff01
43 /*********************************************/
44 /* mpegts section writer */
46 typedef struct MpegTSSection {
50 void (*write_packet)(struct MpegTSSection *s, const uint8_t *packet);
54 typedef struct MpegTSService {
55 MpegTSSection pmt; /* MPEG-2 PMT table context */
56 int sid; /* service ID */
58 uint8_t provider_name[256];
63 // service_type values as defined in ETSI 300 468
65 MPEGTS_SERVICE_TYPE_DIGITAL_TV = 0x01,
66 MPEGTS_SERVICE_TYPE_DIGITAL_RADIO = 0x02,
67 MPEGTS_SERVICE_TYPE_TELETEXT = 0x03,
68 MPEGTS_SERVICE_TYPE_ADVANCED_CODEC_DIGITAL_RADIO = 0x0A,
69 MPEGTS_SERVICE_TYPE_MPEG2_DIGITAL_HDTV = 0x11,
70 MPEGTS_SERVICE_TYPE_ADVANCED_CODEC_DIGITAL_SDTV = 0x16,
71 MPEGTS_SERVICE_TYPE_ADVANCED_CODEC_DIGITAL_HDTV = 0x19,
72 MPEGTS_SERVICE_TYPE_HEVC_DIGITAL_HDTV = 0x1F,
74 typedef struct MpegTSWrite {
75 const AVClass *av_class;
76 MpegTSSection pat; /* MPEG-2 PAT table */
77 MpegTSSection sdt; /* MPEG-2 SDT table context */
78 MpegTSService **services;
79 int64_t sdt_period; /* SDT period in PCR time base */
80 int64_t pat_period; /* PAT/PMT period in PCR time base */
86 int mux_rate; ///< set to 1 when VBR
89 int transport_stream_id;
90 int original_network_id;
99 #define MPEGTS_FLAG_REEMIT_PAT_PMT 0x01
100 #define MPEGTS_FLAG_AAC_LATM 0x02
101 #define MPEGTS_FLAG_PAT_PMT_AT_FRAMES 0x04
102 #define MPEGTS_FLAG_SYSTEM_B 0x08
103 #define MPEGTS_FLAG_DISCONT 0x10
107 int64_t pat_period_us;
108 int64_t sdt_period_us;
112 int omit_video_pes_length;
115 /* a PES packet header is generated every DEFAULT_PES_HEADER_FREQ packets */
116 #define DEFAULT_PES_HEADER_FREQ 16
117 #define DEFAULT_PES_PAYLOAD_SIZE ((DEFAULT_PES_HEADER_FREQ - 1) * 184 + 170)
119 /* The section length is 12 bits. The first 2 are set to 0, the remaining
120 * 10 bits should not exceed 1021. */
121 #define SECTION_LENGTH 1020
123 /* NOTE: 4 bytes must be left at the end for the crc32 */
124 static void mpegts_write_section(MpegTSSection *s, uint8_t *buf, int len)
127 unsigned char packet[TS_PACKET_SIZE];
128 const unsigned char *buf_ptr;
130 int first, b, len1, left;
132 crc = av_bswap32(av_crc(av_crc_get_table(AV_CRC_32_IEEE),
135 buf[len - 4] = (crc >> 24) & 0xff;
136 buf[len - 3] = (crc >> 16) & 0xff;
137 buf[len - 2] = (crc >> 8) & 0xff;
138 buf[len - 1] = crc & 0xff;
140 /* send each packet */
143 first = buf == buf_ptr;
151 s->cc = s->cc + 1 & 0xf;
153 if (s->discontinuity) {
157 s->discontinuity = 0;
160 *q++ = 0; /* 0 offset */
161 len1 = TS_PACKET_SIZE - (q - packet);
164 memcpy(q, buf_ptr, len1);
166 /* add known padding data */
167 left = TS_PACKET_SIZE - (q - packet);
169 memset(q, 0xff, left);
171 s->write_packet(s, packet);
178 static inline void put16(uint8_t **q_ptr, int val)
187 static int mpegts_write_section1(MpegTSSection *s, int tid, int id,
188 int version, int sec_num, int last_sec_num,
189 uint8_t *buf, int len)
191 uint8_t section[1024], *q;
192 unsigned int tot_len;
193 /* reserved_future_use field must be set to 1 for SDT */
194 unsigned int flags = tid == SDT_TID ? 0xf000 : 0xb000;
196 tot_len = 3 + 5 + len + 4;
197 /* check if not too big */
199 return AVERROR_INVALIDDATA;
203 put16(&q, flags | (len + 5 + 4)); /* 5 byte header + 4 byte CRC */
205 *q++ = 0xc1 | (version << 1); /* current_next_indicator = 1 */
210 mpegts_write_section(s, section, tot_len);
214 /*********************************************/
217 #define DEFAULT_PROVIDER_NAME "FFmpeg"
218 #define DEFAULT_SERVICE_NAME "Service"
220 /* we retransmit the SI info at this rate */
221 #define SDT_RETRANS_TIME 500
222 #define PAT_RETRANS_TIME 100
223 #define PCR_RETRANS_TIME 20
225 typedef struct MpegTSWriteStream {
226 int pid; /* stream associated pid */
230 int first_pts_check; ///< first pts check needed
231 int prev_payload_key;
236 AVFormatContext *amux;
238 int64_t pcr_period; /* PCR period in PCR time base */
242 int opus_queued_samples;
243 int opus_pending_trim_start;
246 static void mpegts_write_pat(AVFormatContext *s)
248 MpegTSWrite *ts = s->priv_data;
249 MpegTSService *service;
250 uint8_t data[SECTION_LENGTH], *q;
254 for (i = 0; i < ts->nb_services; i++) {
255 service = ts->services[i];
256 put16(&q, service->sid);
257 put16(&q, 0xe000 | service->pmt.pid);
259 mpegts_write_section1(&ts->pat, PAT_TID, ts->tsid, ts->tables_version, 0, 0,
263 static void putbuf(uint8_t **q_ptr, const uint8_t *buf, size_t len)
265 memcpy(*q_ptr, buf, len);
269 static void put_registration_descriptor(uint8_t **q_ptr, uint32_t tag)
272 *q++ = 0x05; /* MPEG-2 registration descriptor*/
281 static int mpegts_write_pmt(AVFormatContext *s, MpegTSService *service)
283 MpegTSWrite *ts = s->priv_data;
284 uint8_t data[SECTION_LENGTH], *q, *desc_length_ptr, *program_info_length_ptr;
285 int val, stream_type, i, err = 0;
288 put16(&q, 0xe000 | service->pcr_pid);
290 program_info_length_ptr = q;
291 q += 2; /* patched after */
293 /* put program info here */
295 val = 0xf000 | (q - program_info_length_ptr - 2);
296 program_info_length_ptr[0] = val >> 8;
297 program_info_length_ptr[1] = val;
299 for (i = 0; i < s->nb_streams; i++) {
300 AVStream *st = s->streams[i];
301 MpegTSWriteStream *ts_st = st->priv_data;
302 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL, 0);
304 if (s->nb_programs) {
306 AVProgram *program = service->program;
308 for (k = 0; k < program->nb_stream_indexes; k++)
309 if (program->stream_index[k] == i) {
318 if (q - data > SECTION_LENGTH - 32) {
322 switch (st->codecpar->codec_id) {
323 case AV_CODEC_ID_MPEG1VIDEO:
324 case AV_CODEC_ID_MPEG2VIDEO:
325 stream_type = STREAM_TYPE_VIDEO_MPEG2;
327 case AV_CODEC_ID_MPEG4:
328 stream_type = STREAM_TYPE_VIDEO_MPEG4;
330 case AV_CODEC_ID_H264:
331 stream_type = STREAM_TYPE_VIDEO_H264;
333 case AV_CODEC_ID_HEVC:
334 stream_type = STREAM_TYPE_VIDEO_HEVC;
336 case AV_CODEC_ID_CAVS:
337 stream_type = STREAM_TYPE_VIDEO_CAVS;
339 case AV_CODEC_ID_DIRAC:
340 stream_type = STREAM_TYPE_VIDEO_DIRAC;
342 case AV_CODEC_ID_VC1:
343 stream_type = STREAM_TYPE_VIDEO_VC1;
345 case AV_CODEC_ID_MP2:
346 case AV_CODEC_ID_MP3:
347 if ( st->codecpar->sample_rate > 0
348 && st->codecpar->sample_rate < 32000) {
349 stream_type = STREAM_TYPE_AUDIO_MPEG2;
351 stream_type = STREAM_TYPE_AUDIO_MPEG1;
354 case AV_CODEC_ID_AAC:
355 stream_type = (ts->flags & MPEGTS_FLAG_AAC_LATM)
356 ? STREAM_TYPE_AUDIO_AAC_LATM
357 : STREAM_TYPE_AUDIO_AAC;
359 case AV_CODEC_ID_AAC_LATM:
360 stream_type = STREAM_TYPE_AUDIO_AAC_LATM;
362 case AV_CODEC_ID_AC3:
363 stream_type = (ts->flags & MPEGTS_FLAG_SYSTEM_B)
364 ? STREAM_TYPE_PRIVATE_DATA
365 : STREAM_TYPE_AUDIO_AC3;
367 case AV_CODEC_ID_EAC3:
368 stream_type = (ts->flags & MPEGTS_FLAG_SYSTEM_B)
369 ? STREAM_TYPE_PRIVATE_DATA
370 : STREAM_TYPE_AUDIO_EAC3;
372 case AV_CODEC_ID_DTS:
373 stream_type = STREAM_TYPE_AUDIO_DTS;
375 case AV_CODEC_ID_TRUEHD:
376 stream_type = STREAM_TYPE_AUDIO_TRUEHD;
378 case AV_CODEC_ID_OPUS:
379 stream_type = STREAM_TYPE_PRIVATE_DATA;
381 case AV_CODEC_ID_TIMED_ID3:
382 stream_type = STREAM_TYPE_METADATA;
385 av_log(s, AV_LOG_WARNING, "Stream %d, codec %s, is muxed as a private data stream "
386 "and may not be recognized upon reading.\n", i, avcodec_get_name(st->codecpar->codec_id));
387 stream_type = STREAM_TYPE_PRIVATE_DATA;
392 put16(&q, 0xe000 | ts_st->pid);
394 q += 2; /* patched after */
396 /* write optional descriptors here */
397 switch (st->codecpar->codec_type) {
398 case AVMEDIA_TYPE_AUDIO:
399 if (st->codecpar->codec_id==AV_CODEC_ID_AC3 && (ts->flags & MPEGTS_FLAG_SYSTEM_B)) {
400 *q++=0x6a; // AC3 descriptor see A038 DVB SI
401 *q++=1; // 1 byte, all flags sets to 0
402 *q++=0; // omit all fields...
404 if (st->codecpar->codec_id==AV_CODEC_ID_EAC3 && (ts->flags & MPEGTS_FLAG_SYSTEM_B)) {
405 *q++=0x7a; // EAC3 descriptor see A038 DVB SI
406 *q++=1; // 1 byte, all flags sets to 0
407 *q++=0; // omit all fields...
409 if (st->codecpar->codec_id==AV_CODEC_ID_S302M)
410 put_registration_descriptor(&q, MKTAG('B', 'S', 'S', 'D'));
411 if (st->codecpar->codec_id==AV_CODEC_ID_OPUS) {
412 /* 6 bytes registration descriptor, 4 bytes Opus audio descriptor */
413 if (q - data > SECTION_LENGTH - 6 - 4) {
418 put_registration_descriptor(&q, MKTAG('O', 'p', 'u', 's'));
420 *q++ = 0x7f; /* DVB extension descriptor */
424 if (st->codecpar->extradata && st->codecpar->extradata_size >= 19) {
425 if (st->codecpar->extradata[18] == 0 && st->codecpar->channels <= 2) {
426 /* RTP mapping family */
427 *q++ = st->codecpar->channels;
428 } else if (st->codecpar->extradata[18] == 1 && st->codecpar->channels <= 8 &&
429 st->codecpar->extradata_size >= 21 + st->codecpar->channels) {
430 static const uint8_t coupled_stream_counts[9] = {
431 1, 0, 1, 1, 2, 2, 2, 3, 3
433 static const uint8_t channel_map_a[8][8] = {
440 {0, 4, 1, 2, 3, 5, 6},
441 {0, 6, 1, 2, 3, 4, 5, 7},
443 static const uint8_t channel_map_b[8][8] = {
450 {0, 1, 2, 3, 4, 5, 6},
451 {0, 1, 2, 3, 4, 5, 6, 7},
453 /* Vorbis mapping family */
455 if (st->codecpar->extradata[19] == st->codecpar->channels - coupled_stream_counts[st->codecpar->channels] &&
456 st->codecpar->extradata[20] == coupled_stream_counts[st->codecpar->channels] &&
457 memcmp(&st->codecpar->extradata[21], channel_map_a[st->codecpar->channels-1], st->codecpar->channels) == 0) {
458 *q++ = st->codecpar->channels;
459 } else if (st->codecpar->channels >= 2 && st->codecpar->extradata[19] == st->codecpar->channels &&
460 st->codecpar->extradata[20] == 0 &&
461 memcmp(&st->codecpar->extradata[21], channel_map_b[st->codecpar->channels-1], st->codecpar->channels) == 0) {
462 *q++ = st->codecpar->channels | 0x80;
464 /* Unsupported, could write an extended descriptor here */
465 av_log(s, AV_LOG_ERROR, "Unsupported Opus Vorbis-style channel mapping");
470 av_log(s, AV_LOG_ERROR, "Unsupported Opus channel mapping for family %d", st->codecpar->extradata[18]);
473 } else if (st->codecpar->channels <= 2) {
474 /* Assume RTP mapping family */
475 *q++ = st->codecpar->channels;
478 av_log(s, AV_LOG_ERROR, "Unsupported Opus channel mapping");
485 char *next = lang->value;
488 *q++ = 0x0a; /* ISO 639 language descriptor */
492 for (p = lang->value; next && *len_ptr < 255 / 4 * 4; p = next + 1) {
493 if (q - data > SECTION_LENGTH - 4) {
497 next = strchr(p, ',');
498 if (strlen(p) != 3 && (!next || next != p + 3))
499 continue; /* not a 3-letter code */
505 if (st->disposition & AV_DISPOSITION_CLEAN_EFFECTS)
507 else if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
509 else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
512 *q++ = 0; /* undefined type */
518 q -= 2; /* no language codes were written */
521 case AVMEDIA_TYPE_SUBTITLE:
523 const char default_language[] = "und";
524 const char *language = lang && strlen(lang->value) >= 3 ? lang->value : default_language;
526 if (st->codecpar->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
528 int extradata_copied = 0;
530 *q++ = 0x59; /* subtitling_descriptor */
533 while (strlen(language) >= 3) {
534 if (sizeof(data) - (q - data) < 8) { /* 8 bytes per DVB subtitle substream data */
542 if (*language != '\0')
545 if (st->codecpar->extradata_size - extradata_copied >= 5) {
546 *q++ = st->codecpar->extradata[extradata_copied + 4]; /* subtitling_type */
547 memcpy(q, st->codecpar->extradata + extradata_copied, 4); /* composition_page_id and ancillary_page_id */
548 extradata_copied += 5;
552 * 0x10 - normal with no monitor aspect ratio criticality
553 * 0x20 - for the hard of hearing with no monitor aspect ratio criticality */
554 *q++ = (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED) ? 0x20 : 0x10;
555 if ((st->codecpar->extradata_size == 4) && (extradata_copied == 0)) {
556 /* support of old 4-byte extradata format */
557 memcpy(q, st->codecpar->extradata, 4); /* composition_page_id and ancillary_page_id */
558 extradata_copied += 4;
561 put16(&q, 1); /* composition_page_id */
562 put16(&q, 1); /* ancillary_page_id */
567 *len_ptr = q - len_ptr - 1;
568 } else if (st->codecpar->codec_id == AV_CODEC_ID_DVB_TELETEXT) {
569 uint8_t *len_ptr = NULL;
570 int extradata_copied = 0;
572 /* The descriptor tag. teletext_descriptor */
576 while (strlen(language) >= 3 && q - data < sizeof(data) - 6) {
581 if (*language != '\0')
584 if (st->codecpar->extradata_size - 1 > extradata_copied) {
585 memcpy(q, st->codecpar->extradata + extradata_copied, 2);
586 extradata_copied += 2;
589 /* The Teletext descriptor:
590 * teletext_type: This 5-bit field indicates the type of Teletext page indicated. (0x01 Initial Teletext page)
591 * teletext_magazine_number: This is a 3-bit field which identifies the magazine number.
592 * teletext_page_number: This is an 8-bit field giving two 4-bit hex digits identifying the page number. */
598 *len_ptr = q - len_ptr - 1;
602 case AVMEDIA_TYPE_VIDEO:
603 if (stream_type == STREAM_TYPE_VIDEO_DIRAC) {
604 put_registration_descriptor(&q, MKTAG('d', 'r', 'a', 'c'));
605 } else if (stream_type == STREAM_TYPE_VIDEO_VC1) {
606 put_registration_descriptor(&q, MKTAG('V', 'C', '-', '1'));
607 } else if (stream_type == STREAM_TYPE_VIDEO_HEVC && s->strict_std_compliance <= FF_COMPLIANCE_NORMAL) {
608 put_registration_descriptor(&q, MKTAG('H', 'E', 'V', 'C'));
611 case AVMEDIA_TYPE_DATA:
612 if (st->codecpar->codec_id == AV_CODEC_ID_SMPTE_KLV) {
613 put_registration_descriptor(&q, MKTAG('K', 'L', 'V', 'A'));
614 } else if (st->codecpar->codec_id == AV_CODEC_ID_TIMED_ID3) {
615 const char *tag = "ID3 ";
616 *q++ = 0x26; /* metadata descriptor */
618 put16(&q, 0xffff); /* metadata application format */
619 putbuf(&q, tag, strlen(tag));
620 *q++ = 0xff; /* metadata format */
621 putbuf(&q, tag, strlen(tag));
622 *q++ = 0; /* metadata service ID */
623 *q++ = 0xF; /* metadata_locator_record_flag|MPEG_carriage_flags|reserved */
628 val = 0xf000 | (q - desc_length_ptr - 2);
629 desc_length_ptr[0] = val >> 8;
630 desc_length_ptr[1] = val;
634 av_log(s, AV_LOG_ERROR,
635 "The PMT section cannot fit stream %d and all following streams.\n"
636 "Try reducing the number of languages in the audio streams "
637 "or the total number of streams.\n", i);
639 mpegts_write_section1(&service->pmt, PMT_TID, service->sid, ts->tables_version, 0, 0,
644 static void mpegts_write_sdt(AVFormatContext *s)
646 MpegTSWrite *ts = s->priv_data;
647 MpegTSService *service;
648 uint8_t data[SECTION_LENGTH], *q, *desc_list_len_ptr, *desc_len_ptr;
649 int i, running_status, free_ca_mode, val;
654 for (i = 0; i < ts->nb_services; i++) {
655 service = ts->services[i];
656 put16(&q, service->sid);
657 *q++ = 0xfc | 0x00; /* currently no EIT info */
658 desc_list_len_ptr = q;
660 running_status = 4; /* running */
663 /* write only one descriptor for the service name and provider */
667 *q++ = ts->service_type;
668 putbuf(&q, service->provider_name, service->provider_name[0] + 1);
669 putbuf(&q, service->name, service->name[0] + 1);
670 desc_len_ptr[0] = q - desc_len_ptr - 1;
672 /* fill descriptor length */
673 val = (running_status << 13) | (free_ca_mode << 12) |
674 (q - desc_list_len_ptr - 2);
675 desc_list_len_ptr[0] = val >> 8;
676 desc_list_len_ptr[1] = val;
678 mpegts_write_section1(&ts->sdt, SDT_TID, ts->tsid, ts->tables_version, 0, 0,
682 /* This stores a string in buf with the correct encoding and also sets the
683 * first byte as the length. !str is accepted for an empty string.
684 * If the string is already encoded, invalid UTF-8 or has no multibyte sequence
685 * then we keep it as is, otherwise we signal UTF-8 encoding. */
686 static int encode_str8(uint8_t *buf, const char *str)
691 str_len = strlen(str);
692 if (str[0] && (unsigned)str[0] >= 0x20) { /* Make sure the string is not already encoded. */
693 const uint8_t *q = str;
694 int has_multibyte = 0;
697 GET_UTF8(code, *q++, goto invalid;) /* Is it valid UTF-8? */
698 has_multibyte |= (code > 127); /* Does it have multibyte UTF-8 chars in it? */
700 if (has_multibyte) { /* If we have multibyte chars and valid UTF-8, then encode as such! */
702 return AVERROR(EINVAL);
703 buf[0] = str_len + 1;
705 memcpy(&buf[2], str, str_len);
710 /* Otherwise let's just encode the string as is! */
712 return AVERROR(EINVAL);
714 memcpy(&buf[1], str, str_len);
718 static int64_t get_pcr(const MpegTSWrite *ts, AVIOContext *pb)
720 return av_rescale(avio_tell(pb) + 11, 8 * PCR_TIME_BASE, ts->mux_rate) +
724 static void write_packet(AVFormatContext *s, const uint8_t *packet)
726 MpegTSWrite *ts = s->priv_data;
728 int64_t pcr = get_pcr(s->priv_data, s->pb);
729 uint32_t tp_extra_header = pcr % 0x3fffffff;
730 tp_extra_header = AV_RB32(&tp_extra_header);
731 avio_write(s->pb, (unsigned char *) &tp_extra_header,
732 sizeof(tp_extra_header));
734 avio_write(s->pb, packet, TS_PACKET_SIZE);
737 static void section_write_packet(MpegTSSection *s, const uint8_t *packet)
739 AVFormatContext *ctx = s->opaque;
740 write_packet(ctx, packet);
743 static MpegTSService *mpegts_add_service(AVFormatContext *s, int sid,
744 const AVDictionary *metadata,
747 MpegTSWrite *ts = s->priv_data;
748 MpegTSService *service;
749 AVDictionaryEntry *title, *provider;
750 char default_service_name[32];
751 const char *service_name;
752 const char *provider_name;
754 title = av_dict_get(metadata, "service_name", NULL, 0);
756 title = av_dict_get(metadata, "title", NULL, 0);
757 snprintf(default_service_name, sizeof(default_service_name), "%s%02d", DEFAULT_SERVICE_NAME, ts->nb_services + 1);
758 service_name = title ? title->value : default_service_name;
759 provider = av_dict_get(metadata, "service_provider", NULL, 0);
760 provider_name = provider ? provider->value : DEFAULT_PROVIDER_NAME;
762 service = av_mallocz(sizeof(MpegTSService));
765 service->pmt.pid = ts->pmt_start_pid + ts->nb_services;
767 service->pcr_pid = 0x1fff;
768 if (encode_str8(service->provider_name, provider_name) < 0 ||
769 encode_str8(service->name, service_name) < 0) {
770 av_log(s, AV_LOG_ERROR, "Too long service or provider name\n");
773 if (av_dynarray_add_nofree(&ts->services, &ts->nb_services, service) < 0)
776 service->pmt.write_packet = section_write_packet;
777 service->pmt.opaque = s;
778 service->pmt.cc = 15;
779 service->pmt.discontinuity= ts->flags & MPEGTS_FLAG_DISCONT;
780 service->program = program;
788 static void enable_pcr_generation_for_stream(AVFormatContext *s, AVStream *pcr_st)
790 MpegTSWrite *ts = s->priv_data;
791 MpegTSWriteStream *ts_st = pcr_st->priv_data;
793 if (ts->mux_rate > 1 || ts->pcr_period_ms >= 0) {
794 int pcr_period_ms = ts->pcr_period_ms == -1 ? PCR_RETRANS_TIME : ts->pcr_period_ms;
795 ts_st->pcr_period = av_rescale(pcr_period_ms, PCR_TIME_BASE, 1000);
797 /* By default, for VBR we select the highest multiple of frame duration which is less than 100 ms. */
798 int64_t frame_period = 0;
799 if (pcr_st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
800 int frame_size = av_get_audio_frame_duration2(pcr_st->codecpar, 0);
802 av_log(s, AV_LOG_WARNING, "frame size not set\n");
805 frame_period = av_rescale_rnd(frame_size, PCR_TIME_BASE, pcr_st->codecpar->sample_rate, AV_ROUND_UP);
806 } else if (pcr_st->avg_frame_rate.num) {
807 frame_period = av_rescale_rnd(pcr_st->avg_frame_rate.den, PCR_TIME_BASE, pcr_st->avg_frame_rate.num, AV_ROUND_UP);
809 if (frame_period > 0 && frame_period <= PCR_TIME_BASE / 10)
810 ts_st->pcr_period = frame_period * (PCR_TIME_BASE / 10 / frame_period);
812 ts_st->pcr_period = 1;
815 // output a PCR as soon as possible
816 ts_st->last_pcr = ts->first_pcr - ts_st->pcr_period;
819 static void select_pcr_streams(AVFormatContext *s)
821 MpegTSWrite *ts = s->priv_data;
823 for (int i = 0; i < ts->nb_services; i++) {
824 MpegTSService *service = ts->services[i];
825 AVStream *pcr_st = NULL;
826 AVProgram *program = service->program;
827 int nb_streams = program ? program->nb_stream_indexes : s->nb_streams;
829 for (int j = 0; j < nb_streams; j++) {
830 AVStream *st = s->streams[program ? program->stream_index[j] : j];
832 pcr_st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
839 MpegTSWriteStream *ts_st = pcr_st->priv_data;
840 service->pcr_pid = ts_st->pid;
841 enable_pcr_generation_for_stream(s, pcr_st);
842 av_log(s, AV_LOG_VERBOSE, "service %i using PCR in pid=%i, pcr_period=%"PRId64"ms\n",
843 service->sid, service->pcr_pid, av_rescale(ts_st->pcr_period, 1000, PCR_TIME_BASE));
848 static int mpegts_init(AVFormatContext *s)
850 MpegTSWrite *ts = s->priv_data;
855 if (ts->m2ts_mode == -1) {
856 if (av_match_ext(s->url, "m2ts")) {
863 if (s->max_delay < 0) /* Not set by the caller */
866 // round up to a whole number of TS packets
867 ts->pes_payload_size = (ts->pes_payload_size + 14 + 183) / 184 * 184 - 14;
869 ts->tsid = ts->transport_stream_id;
870 ts->onid = ts->original_network_id;
871 if (!s->nb_programs) {
872 /* allocate a single DVB service */
873 if (!mpegts_add_service(s, ts->service_id, s->metadata, NULL))
874 return AVERROR(ENOMEM);
876 for (i = 0; i < s->nb_programs; i++) {
877 AVProgram *program = s->programs[i];
878 if (!mpegts_add_service(s, program->id, program->metadata, program))
879 return AVERROR(ENOMEM);
883 ts->pat.pid = PAT_PID;
884 /* Initialize at 15 so that it wraps and is equal to 0 for the
885 * first packet we write. */
887 ts->pat.discontinuity= ts->flags & MPEGTS_FLAG_DISCONT;
888 ts->pat.write_packet = section_write_packet;
891 ts->sdt.pid = SDT_PID;
893 ts->sdt.discontinuity= ts->flags & MPEGTS_FLAG_DISCONT;
894 ts->sdt.write_packet = section_write_packet;
897 pids = av_malloc_array(s->nb_streams, sizeof(*pids));
899 ret = AVERROR(ENOMEM);
903 /* assign pids to each stream */
904 for (i = 0; i < s->nb_streams; i++) {
905 AVStream *st = s->streams[i];
906 MpegTSWriteStream *ts_st;
908 ts_st = av_mallocz(sizeof(MpegTSWriteStream));
910 ret = AVERROR(ENOMEM);
913 st->priv_data = ts_st;
915 avpriv_set_pts_info(st, 33, 1, 90000);
917 ts_st->payload = av_mallocz(ts->pes_payload_size);
918 if (!ts_st->payload) {
919 ret = AVERROR(ENOMEM);
923 /* MPEG pid values < 16 are reserved. Applications which set st->id in
924 * this range are assigned a calculated pid. */
926 ts_st->pid = ts->start_pid + i;
930 if (ts_st->pid >= 0x1FFF) {
931 av_log(s, AV_LOG_ERROR,
932 "Invalid stream id %d, must be less than 8191\n", st->id);
933 ret = AVERROR(EINVAL);
936 for (j = 0; j < ts->nb_services; j++) {
937 if (ts->services[j]->pmt.pid > LAST_OTHER_PID) {
938 av_log(s, AV_LOG_ERROR,
939 "Invalid PMT PID %d, must be less than %d\n", ts->services[j]->pmt.pid, LAST_OTHER_PID + 1);
940 ret = AVERROR(EINVAL);
943 if (ts_st->pid == ts->services[j]->pmt.pid) {
944 av_log(s, AV_LOG_ERROR, "PID %d cannot be both elementary and PMT PID\n", ts_st->pid);
945 ret = AVERROR(EINVAL);
949 for (j = 0; j < i; j++) {
950 if (pids[j] == ts_st->pid) {
951 av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
952 ret = AVERROR(EINVAL);
956 pids[i] = ts_st->pid;
957 ts_st->payload_pts = AV_NOPTS_VALUE;
958 ts_st->payload_dts = AV_NOPTS_VALUE;
959 ts_st->first_pts_check = 1;
961 ts_st->discontinuity = ts->flags & MPEGTS_FLAG_DISCONT;
962 if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
963 st->codecpar->extradata_size > 0) {
965 ts_st->amux = avformat_alloc_context();
967 ret = AVERROR(ENOMEM);
970 ts_st->amux->oformat =
971 av_guess_format((ts->flags & MPEGTS_FLAG_AAC_LATM) ? "latm" : "adts",
973 if (!ts_st->amux->oformat) {
974 ret = AVERROR(EINVAL);
977 if (!(ast = avformat_new_stream(ts_st->amux, NULL))) {
978 ret = AVERROR(ENOMEM);
981 ret = avcodec_parameters_copy(ast->codecpar, st->codecpar);
984 ast->time_base = st->time_base;
985 ret = avformat_write_header(ts_st->amux, NULL);
989 if (st->codecpar->codec_id == AV_CODEC_ID_OPUS) {
990 ts_st->opus_pending_trim_start = st->codecpar->initial_padding * 48000 / st->codecpar->sample_rate;
997 ts->first_pcr = av_rescale(s->max_delay, PCR_TIME_BASE, AV_TIME_BASE);
999 select_pcr_streams(s);
1001 ts->last_pat_ts = AV_NOPTS_VALUE;
1002 ts->last_sdt_ts = AV_NOPTS_VALUE;
1003 ts->pat_period = av_rescale(ts->pat_period_us, PCR_TIME_BASE, AV_TIME_BASE);
1004 ts->sdt_period = av_rescale(ts->sdt_period_us, PCR_TIME_BASE, AV_TIME_BASE);
1006 if (ts->mux_rate == 1)
1007 av_log(s, AV_LOG_VERBOSE, "muxrate VBR, ");
1009 av_log(s, AV_LOG_VERBOSE, "muxrate %d, ", ts->mux_rate);
1010 av_log(s, AV_LOG_VERBOSE,
1011 "sdt every %"PRId64" ms, pat/pmt every %"PRId64" ms\n",
1012 av_rescale(ts->sdt_period, 1000, PCR_TIME_BASE),
1013 av_rescale(ts->pat_period, 1000, PCR_TIME_BASE));
1022 /* send SDT, PAT and PMT tables regularly */
1023 static void retransmit_si_info(AVFormatContext *s, int force_pat, int force_sdt, int64_t pcr)
1025 MpegTSWrite *ts = s->priv_data;
1028 if ((pcr != AV_NOPTS_VALUE && ts->last_sdt_ts == AV_NOPTS_VALUE) ||
1029 (pcr != AV_NOPTS_VALUE && pcr - ts->last_sdt_ts >= ts->sdt_period) ||
1032 if (pcr != AV_NOPTS_VALUE)
1033 ts->last_sdt_ts = FFMAX(pcr, ts->last_sdt_ts);
1034 mpegts_write_sdt(s);
1036 if ((pcr != AV_NOPTS_VALUE && ts->last_pat_ts == AV_NOPTS_VALUE) ||
1037 (pcr != AV_NOPTS_VALUE && pcr - ts->last_pat_ts >= ts->pat_period) ||
1039 if (pcr != AV_NOPTS_VALUE)
1040 ts->last_pat_ts = FFMAX(pcr, ts->last_pat_ts);
1041 mpegts_write_pat(s);
1042 for (i = 0; i < ts->nb_services; i++)
1043 mpegts_write_pmt(s, ts->services[i]);
1047 static int write_pcr_bits(uint8_t *buf, int64_t pcr)
1049 int64_t pcr_low = pcr % 300, pcr_high = pcr / 300;
1051 *buf++ = pcr_high >> 25;
1052 *buf++ = pcr_high >> 17;
1053 *buf++ = pcr_high >> 9;
1054 *buf++ = pcr_high >> 1;
1055 *buf++ = pcr_high << 7 | pcr_low >> 8 | 0x7e;
1061 /* Write a single null transport stream packet */
1062 static void mpegts_insert_null_packet(AVFormatContext *s)
1065 uint8_t buf[TS_PACKET_SIZE];
1072 memset(q, 0x0FF, TS_PACKET_SIZE - (q - buf));
1073 write_packet(s, buf);
1076 /* Write a single transport stream packet with a PCR and no payload */
1077 static void mpegts_insert_pcr_only(AVFormatContext *s, AVStream *st)
1079 MpegTSWrite *ts = s->priv_data;
1080 MpegTSWriteStream *ts_st = st->priv_data;
1082 uint8_t buf[TS_PACKET_SIZE];
1086 *q++ = ts_st->pid >> 8;
1088 *q++ = 0x20 | ts_st->cc; /* Adaptation only */
1089 /* Continuity Count field does not increment (see 13818-1 section 2.4.3.3) */
1090 *q++ = TS_PACKET_SIZE - 5; /* Adaptation Field Length */
1091 *q++ = 0x10; /* Adaptation flags: PCR present */
1092 if (ts_st->discontinuity) {
1094 ts_st->discontinuity = 0;
1097 /* PCR coded into 6 bytes */
1098 q += write_pcr_bits(q, get_pcr(ts, s->pb));
1100 /* stuffing bytes */
1101 memset(q, 0xFF, TS_PACKET_SIZE - (q - buf));
1102 write_packet(s, buf);
1105 static void write_pts(uint8_t *q, int fourbits, int64_t pts)
1109 val = fourbits << 4 | (((pts >> 30) & 0x07) << 1) | 1;
1111 val = (((pts >> 15) & 0x7fff) << 1) | 1;
1114 val = (((pts) & 0x7fff) << 1) | 1;
1119 /* Set an adaptation field flag in an MPEG-TS packet*/
1120 static void set_af_flag(uint8_t *pkt, int flag)
1122 // expect at least one flag to set
1125 if ((pkt[3] & 0x20) == 0) {
1126 // no AF yet, set adaptation field flag
1128 // 1 byte length, no flags
1135 /* Extend the adaptation field by size bytes */
1136 static void extend_af(uint8_t *pkt, int size)
1138 // expect already existing adaptation field
1139 av_assert0(pkt[3] & 0x20);
1143 /* Get a pointer to MPEG-TS payload (right after TS packet header) */
1144 static uint8_t *get_ts_payload_start(uint8_t *pkt)
1147 return pkt + 5 + pkt[4];
1152 /* Add a PES header to the front of the payload, and segment into an integer
1153 * number of TS packets. The final TS packet is padded using an oversized
1154 * adaptation header to exactly fill the last TS packet.
1155 * NOTE: 'payload' contains a complete PES payload. */
1156 static void mpegts_write_pes(AVFormatContext *s, AVStream *st,
1157 const uint8_t *payload, int payload_size,
1158 int64_t pts, int64_t dts, int key, int stream_id)
1160 MpegTSWriteStream *ts_st = st->priv_data;
1161 MpegTSWrite *ts = s->priv_data;
1162 uint8_t buf[TS_PACKET_SIZE];
1164 int val, is_start, len, header_len, write_pcr, is_dvb_subtitle, is_dvb_teletext, flags;
1165 int afc_len, stuffing_len;
1166 int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE);
1167 int force_pat = st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && key && !ts_st->prev_payload_key;
1170 av_assert0(ts_st->payload != buf || st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO);
1171 if (ts->flags & MPEGTS_FLAG_PAT_PMT_AT_FRAMES && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
1175 if (ts->flags & MPEGTS_FLAG_REEMIT_PAT_PMT) {
1178 ts->flags &= ~MPEGTS_FLAG_REEMIT_PAT_PMT;
1182 while (payload_size > 0) {
1183 int64_t pcr = AV_NOPTS_VALUE;
1184 if (ts->mux_rate > 1)
1185 pcr = get_pcr(ts, s->pb);
1186 else if (dts != AV_NOPTS_VALUE)
1187 pcr = (dts - delay) * 300;
1189 retransmit_si_info(s, force_pat, force_sdt, pcr);
1194 if (ts->mux_rate > 1) {
1195 /* Send PCR packets for all PCR streams if needed */
1196 pcr = get_pcr(ts, s->pb);
1197 if (pcr >= ts->next_pcr) {
1198 int64_t next_pcr = INT64_MAX;
1199 for (int i = 0; i < s->nb_streams; i++) {
1200 /* Make the current stream the last, because for that we
1201 * can insert the pcr into the payload later */
1202 int st2_index = i < st->index ? i : (i + 1 == s->nb_streams ? st->index : i + 1);
1203 AVStream *st2 = s->streams[st2_index];
1204 MpegTSWriteStream *ts_st2 = st2->priv_data;
1205 if (ts_st2->pcr_period) {
1206 if (pcr - ts_st2->last_pcr >= ts_st2->pcr_period) {
1207 ts_st2->last_pcr = FFMAX(pcr - ts_st2->pcr_period, ts_st2->last_pcr + ts_st2->pcr_period);
1209 mpegts_insert_pcr_only(s, st2);
1210 pcr = get_pcr(ts, s->pb);
1215 next_pcr = FFMIN(next_pcr, ts_st2->last_pcr + ts_st2->pcr_period);
1218 ts->next_pcr = next_pcr;
1220 if (dts != AV_NOPTS_VALUE && (dts - pcr / 300) > delay) {
1221 /* pcr insert gets priority over null packet insert */
1223 mpegts_insert_pcr_only(s, st);
1225 mpegts_insert_null_packet(s);
1226 /* recalculate write_pcr and possibly retransmit si_info */
1229 } else if (ts_st->pcr_period && pcr != AV_NOPTS_VALUE) {
1230 if (pcr - ts_st->last_pcr >= ts_st->pcr_period && is_start) {
1231 ts_st->last_pcr = FFMAX(pcr - ts_st->pcr_period, ts_st->last_pcr + ts_st->pcr_period);
1236 /* prepare packet header */
1239 val = ts_st->pid >> 8;
1240 if (ts->m2ts_mode && st->codecpar->codec_id == AV_CODEC_ID_AC3)
1246 ts_st->cc = ts_st->cc + 1 & 0xf;
1247 *q++ = 0x10 | ts_st->cc; // payload indicator + CC
1248 if (ts_st->discontinuity) {
1249 set_af_flag(buf, 0x80);
1250 q = get_ts_payload_start(buf);
1251 ts_st->discontinuity = 0;
1253 if (key && is_start && pts != AV_NOPTS_VALUE) {
1254 // set Random Access for key frames
1255 if (ts_st->pcr_period)
1257 set_af_flag(buf, 0x40);
1258 q = get_ts_payload_start(buf);
1261 set_af_flag(buf, 0x10);
1262 q = get_ts_payload_start(buf);
1263 // add 11, pcr references the last byte of program clock reference base
1264 if (dts != AV_NOPTS_VALUE && dts < pcr / 300)
1265 av_log(s, AV_LOG_WARNING, "dts < pcr, TS is invalid\n");
1266 extend_af(buf, write_pcr_bits(q, pcr));
1267 q = get_ts_payload_start(buf);
1270 int pes_extension = 0;
1271 int pes_header_stuffing_bytes = 0;
1272 /* write PES header */
1276 is_dvb_subtitle = 0;
1277 is_dvb_teletext = 0;
1278 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
1279 if (st->codecpar->codec_id == AV_CODEC_ID_DIRAC)
1283 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
1284 (st->codecpar->codec_id == AV_CODEC_ID_MP2 ||
1285 st->codecpar->codec_id == AV_CODEC_ID_MP3 ||
1286 st->codecpar->codec_id == AV_CODEC_ID_AAC)) {
1288 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
1289 st->codecpar->codec_id == AV_CODEC_ID_AC3 &&
1292 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA &&
1293 st->codecpar->codec_id == AV_CODEC_ID_TIMED_ID3) {
1295 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
1296 *q++ = stream_id != -1 ? stream_id : 0xfc;
1298 if (stream_id == 0xbd) /* asynchronous KLV */
1299 pts = dts = AV_NOPTS_VALUE;
1302 if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1303 if (st->codecpar->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
1304 is_dvb_subtitle = 1;
1305 } else if (st->codecpar->codec_id == AV_CODEC_ID_DVB_TELETEXT) {
1306 is_dvb_teletext = 1;
1312 if (pts != AV_NOPTS_VALUE) {
1316 if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
1320 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
1321 st->codecpar->codec_id == AV_CODEC_ID_DIRAC) {
1322 /* set PES_extension_flag */
1326 /* One byte for PES2 extension flag +
1327 * one byte for extension length +
1328 * one byte for extension id */
1331 /* for Blu-ray AC3 Audio the PES Extension flag should be as follow
1332 * otherwise it will not play sound on blu-ray
1334 if (ts->m2ts_mode &&
1335 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
1336 st->codecpar->codec_id == AV_CODEC_ID_AC3) {
1337 /* set PES_extension_flag */
1342 if (is_dvb_teletext) {
1343 pes_header_stuffing_bytes = 0x24 - header_len;
1346 len = payload_size + header_len + 3;
1347 /* 3 extra bytes should be added to DVB subtitle payload: 0x20 0x00 at the beginning and trailing 0xff */
1348 if (is_dvb_subtitle) {
1354 if (ts->omit_video_pes_length && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
1360 /* data alignment indicator is required for subtitle and data streams */
1361 if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE || st->codecpar->codec_type == AVMEDIA_TYPE_DATA)
1366 if (pts != AV_NOPTS_VALUE) {
1367 write_pts(q, flags >> 6, pts);
1370 if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
1371 write_pts(q, 1, dts);
1374 if (pes_extension && st->codecpar->codec_id == AV_CODEC_ID_DIRAC) {
1375 flags = 0x01; /* set PES_extension_flag_2 */
1377 *q++ = 0x80 | 0x01; /* marker bit + extension length */
1378 /* Set the stream ID extension flag bit to 0 and
1379 * write the extended stream ID. */
1382 /* For Blu-ray AC3 Audio Setting extended flags */
1383 if (ts->m2ts_mode &&
1385 st->codecpar->codec_id == AV_CODEC_ID_AC3) {
1386 flags = 0x01; /* set PES_extension_flag_2 */
1388 *q++ = 0x80 | 0x01; /* marker bit + extension length */
1389 *q++ = 0x00 | 0x71; /* for AC3 Audio (specifically on blue-rays) */
1393 if (is_dvb_subtitle) {
1394 /* First two fields of DVB subtitles PES data:
1395 * data_identifier: for DVB subtitle streams shall be coded with the value 0x20
1396 * subtitle_stream_id: for DVB subtitle stream shall be identified by the value 0x00 */
1400 if (is_dvb_teletext) {
1401 memset(q, 0xff, pes_header_stuffing_bytes);
1402 q += pes_header_stuffing_bytes;
1407 header_len = q - buf;
1409 len = TS_PACKET_SIZE - header_len;
1410 if (len > payload_size)
1412 stuffing_len = TS_PACKET_SIZE - header_len - len;
1413 if (stuffing_len > 0) {
1414 /* add stuffing with AFC */
1415 if (buf[3] & 0x20) {
1416 /* stuffing already present: increase its size */
1417 afc_len = buf[4] + 1;
1418 memmove(buf + 4 + afc_len + stuffing_len,
1420 header_len - (4 + afc_len));
1421 buf[4] += stuffing_len;
1422 memset(buf + 4 + afc_len, 0xff, stuffing_len);
1425 memmove(buf + 4 + stuffing_len, buf + 4, header_len - 4);
1427 buf[4] = stuffing_len - 1;
1428 if (stuffing_len >= 2) {
1430 memset(buf + 6, 0xff, stuffing_len - 2);
1435 if (is_dvb_subtitle && payload_size == len) {
1436 memcpy(buf + TS_PACKET_SIZE - len, payload, len - 1);
1437 buf[TS_PACKET_SIZE - 1] = 0xff; /* end_of_PES_data_field_marker: an 8-bit field with fixed contents 0xff for DVB subtitle */
1439 memcpy(buf + TS_PACKET_SIZE - len, payload, len);
1443 payload_size -= len;
1444 write_packet(s, buf);
1446 ts_st->prev_payload_key = key;
1449 int ff_check_h264_startcode(AVFormatContext *s, const AVStream *st, const AVPacket *pkt)
1451 if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001 && AV_RB24(pkt->data) != 0x000001) {
1452 if (!st->nb_frames) {
1453 av_log(s, AV_LOG_ERROR, "H.264 bitstream malformed, "
1454 "no startcode found, use the video bitstream filter 'h264_mp4toannexb' to fix it "
1455 "('-bsf:v h264_mp4toannexb' option with ffmpeg)\n");
1456 return AVERROR_INVALIDDATA;
1458 av_log(s, AV_LOG_WARNING, "H.264 bitstream error, startcode missing, size %d", pkt->size);
1460 av_log(s, AV_LOG_WARNING, " data %08"PRIX32, AV_RB32(pkt->data));
1461 av_log(s, AV_LOG_WARNING, "\n");
1466 static int check_hevc_startcode(AVFormatContext *s, const AVStream *st, const AVPacket *pkt)
1468 if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001 && AV_RB24(pkt->data) != 0x000001) {
1469 if (!st->nb_frames) {
1470 av_log(s, AV_LOG_ERROR, "HEVC bitstream malformed, no startcode found\n");
1471 return AVERROR_PATCHWELCOME;
1473 av_log(s, AV_LOG_WARNING, "HEVC bitstream error, startcode missing, size %d", pkt->size);
1475 av_log(s, AV_LOG_WARNING, " data %08"PRIX32, AV_RB32(pkt->data));
1476 av_log(s, AV_LOG_WARNING, "\n");
1481 /* Based on GStreamer's gst-plugins-base/ext/ogg/gstoggstream.c
1482 * Released under the LGPL v2.1+, written by
1483 * Vincent Penquerc'h <vincent.penquerch@collabora.co.uk>
1485 static int opus_get_packet_samples(AVFormatContext *s, AVPacket *pkt)
1487 static const int durations[32] = {
1488 480, 960, 1920, 2880, /* Silk NB */
1489 480, 960, 1920, 2880, /* Silk MB */
1490 480, 960, 1920, 2880, /* Silk WB */
1491 480, 960, /* Hybrid SWB */
1492 480, 960, /* Hybrid FB */
1493 120, 240, 480, 960, /* CELT NB */
1494 120, 240, 480, 960, /* CELT NB */
1495 120, 240, 480, 960, /* CELT NB */
1496 120, 240, 480, 960, /* CELT NB */
1498 int toc, frame_duration, nframes, duration;
1505 frame_duration = durations[toc >> 3];
1519 nframes = pkt->data[1] & 63;
1523 duration = nframes * frame_duration;
1524 if (duration > 5760) {
1525 av_log(s, AV_LOG_WARNING,
1526 "Opus packet duration > 120 ms, invalid");
1533 static int mpegts_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
1535 AVStream *st = s->streams[pkt->stream_index];
1536 int size = pkt->size;
1537 uint8_t *buf = pkt->data;
1538 uint8_t *data = NULL;
1539 MpegTSWrite *ts = s->priv_data;
1540 MpegTSWriteStream *ts_st = st->priv_data;
1541 const int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE) * 2;
1542 const int64_t max_audio_delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE) / 2;
1543 int64_t dts = pkt->dts, pts = pkt->pts;
1544 int opus_samples = 0;
1546 uint8_t *side_data = NULL;
1549 side_data = av_packet_get_side_data(pkt,
1550 AV_PKT_DATA_MPEGTS_STREAM_ID,
1553 stream_id = side_data[0];
1555 if (ts->copyts < 1) {
1556 if (pts != AV_NOPTS_VALUE)
1558 if (dts != AV_NOPTS_VALUE)
1562 if (ts_st->first_pts_check && pts == AV_NOPTS_VALUE) {
1563 av_log(s, AV_LOG_ERROR, "first pts value must be set\n");
1564 return AVERROR_INVALIDDATA;
1566 ts_st->first_pts_check = 0;
1568 if (st->codecpar->codec_id == AV_CODEC_ID_H264) {
1569 const uint8_t *p = buf, *buf_end = p + size;
1570 uint32_t state = -1;
1571 int extradd = (pkt->flags & AV_PKT_FLAG_KEY) ? st->codecpar->extradata_size : 0;
1572 int ret = ff_check_h264_startcode(s, st, pkt);
1576 if (extradd && AV_RB24(st->codecpar->extradata) > 1)
1580 p = avpriv_find_start_code(p, buf_end, &state);
1581 av_log(s, AV_LOG_TRACE, "nal %"PRId32"\n", state & 0x1f);
1582 if ((state & 0x1f) == 7)
1584 } while (p < buf_end && (state & 0x1f) != 9 &&
1585 (state & 0x1f) != 5 && (state & 0x1f) != 1);
1587 if ((state & 0x1f) != 5)
1589 if ((state & 0x1f) != 9) { // AUD NAL
1590 data = av_malloc(pkt->size + 6 + extradd);
1592 return AVERROR(ENOMEM);
1593 memcpy(data + 6, st->codecpar->extradata, extradd);
1594 memcpy(data + 6 + extradd, pkt->data, pkt->size);
1595 AV_WB32(data, 0x00000001);
1597 data[5] = 0xf0; // any slice type (0xe) + rbsp stop one bit
1599 size = pkt->size + 6 + extradd;
1601 } else if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
1602 if (pkt->size < 2) {
1603 av_log(s, AV_LOG_ERROR, "AAC packet too short\n");
1604 return AVERROR_INVALIDDATA;
1606 if ((AV_RB16(pkt->data) & 0xfff0) != 0xfff0) {
1611 av_log(s, AV_LOG_ERROR, "AAC bitstream not in ADTS format "
1612 "and extradata missing\n");
1614 av_init_packet(&pkt2);
1615 pkt2.data = pkt->data;
1616 pkt2.size = pkt->size;
1617 av_assert0(pkt->dts != AV_NOPTS_VALUE);
1618 pkt2.dts = av_rescale_q(pkt->dts, st->time_base, ts_st->amux->streams[0]->time_base);
1620 ret = avio_open_dyn_buf(&ts_st->amux->pb);
1624 ret = av_write_frame(ts_st->amux, &pkt2);
1626 ffio_free_dyn_buf(&ts_st->amux->pb);
1629 size = avio_close_dyn_buf(ts_st->amux->pb, &data);
1630 ts_st->amux->pb = NULL;
1634 } else if (st->codecpar->codec_id == AV_CODEC_ID_HEVC) {
1635 const uint8_t *p = buf, *buf_end = p + size;
1636 uint32_t state = -1;
1637 int extradd = (pkt->flags & AV_PKT_FLAG_KEY) ? st->codecpar->extradata_size : 0;
1638 int ret = check_hevc_startcode(s, st, pkt);
1642 if (extradd && AV_RB24(st->codecpar->extradata) > 1)
1646 p = avpriv_find_start_code(p, buf_end, &state);
1647 av_log(s, AV_LOG_TRACE, "nal %"PRId32"\n", (state & 0x7e)>>1);
1648 if ((state & 0x7e) == 2*32)
1650 } while (p < buf_end && (state & 0x7e) != 2*35 &&
1651 (state & 0x7e) >= 2*32);
1653 if ((state & 0x7e) < 2*16 || (state & 0x7e) >= 2*24)
1655 if ((state & 0x7e) != 2*35) { // AUD NAL
1656 data = av_malloc(pkt->size + 7 + extradd);
1658 return AVERROR(ENOMEM);
1659 memcpy(data + 7, st->codecpar->extradata, extradd);
1660 memcpy(data + 7 + extradd, pkt->data, pkt->size);
1661 AV_WB32(data, 0x00000001);
1664 data[6] = 0x50; // any slice type (0x4) + rbsp stop one bit
1666 size = pkt->size + 7 + extradd;
1668 } else if (st->codecpar->codec_id == AV_CODEC_ID_OPUS) {
1669 if (pkt->size < 2) {
1670 av_log(s, AV_LOG_ERROR, "Opus packet too short\n");
1671 return AVERROR_INVALIDDATA;
1674 /* Add Opus control header */
1675 if ((AV_RB16(pkt->data) >> 5) != 0x3ff) {
1679 int ctrl_header_size;
1680 int trim_start = 0, trim_end = 0;
1682 opus_samples = opus_get_packet_samples(s, pkt);
1684 side_data = av_packet_get_side_data(pkt,
1685 AV_PKT_DATA_SKIP_SAMPLES,
1688 if (side_data && side_data_size >= 10) {
1689 trim_end = AV_RL32(side_data + 4) * 48000 / st->codecpar->sample_rate;
1692 ctrl_header_size = pkt->size + 2 + pkt->size / 255 + 1;
1693 if (ts_st->opus_pending_trim_start)
1694 ctrl_header_size += 2;
1696 ctrl_header_size += 2;
1698 data = av_malloc(ctrl_header_size);
1700 return AVERROR(ENOMEM);
1704 if (ts_st->opus_pending_trim_start)
1712 data[i] = FFMIN(n, 255);
1717 av_assert0(2 + pkt->size / 255 + 1 == i);
1719 if (ts_st->opus_pending_trim_start) {
1720 trim_start = FFMIN(ts_st->opus_pending_trim_start, opus_samples);
1721 AV_WB16(data + i, trim_start);
1723 ts_st->opus_pending_trim_start -= trim_start;
1726 trim_end = FFMIN(trim_end, opus_samples - trim_start);
1727 AV_WB16(data + i, trim_end);
1731 memcpy(data + i, pkt->data, pkt->size);
1733 size = ctrl_header_size;
1735 /* TODO: Can we get TS formatted data here? If so we will
1736 * need to count the samples of that too! */
1737 av_log(s, AV_LOG_WARNING, "Got MPEG-TS formatted Opus data, unhandled");
1741 if (ts_st->payload_size && (ts_st->payload_size + size > ts->pes_payload_size ||
1742 (dts != AV_NOPTS_VALUE && ts_st->payload_dts != AV_NOPTS_VALUE &&
1743 dts - ts_st->payload_dts >= max_audio_delay) ||
1744 ts_st->opus_queued_samples + opus_samples >= 5760 /* 120ms */)) {
1745 mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_size,
1746 ts_st->payload_pts, ts_st->payload_dts,
1747 ts_st->payload_flags & AV_PKT_FLAG_KEY, stream_id);
1748 ts_st->payload_size = 0;
1749 ts_st->opus_queued_samples = 0;
1752 if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO || size > ts->pes_payload_size) {
1753 av_assert0(!ts_st->payload_size);
1754 // for video and subtitle, write a single pes packet
1755 mpegts_write_pes(s, st, buf, size, pts, dts,
1756 pkt->flags & AV_PKT_FLAG_KEY, stream_id);
1757 ts_st->opus_queued_samples = 0;
1762 if (!ts_st->payload_size) {
1763 ts_st->payload_pts = pts;
1764 ts_st->payload_dts = dts;
1765 ts_st->payload_flags = pkt->flags;
1768 memcpy(ts_st->payload + ts_st->payload_size, buf, size);
1769 ts_st->payload_size += size;
1770 ts_st->opus_queued_samples += opus_samples;
1777 static void mpegts_write_flush(AVFormatContext *s)
1779 MpegTSWrite *ts = s->priv_data;
1782 /* flush current packets */
1783 for (i = 0; i < s->nb_streams; i++) {
1784 AVStream *st = s->streams[i];
1785 MpegTSWriteStream *ts_st = st->priv_data;
1786 if (ts_st->payload_size > 0) {
1787 mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_size,
1788 ts_st->payload_pts, ts_st->payload_dts,
1789 ts_st->payload_flags & AV_PKT_FLAG_KEY, -1);
1790 ts_st->payload_size = 0;
1791 ts_st->opus_queued_samples = 0;
1795 if (ts->m2ts_mode) {
1796 int packets = (avio_tell(s->pb) / (TS_PACKET_SIZE + 4)) % 32;
1797 while (packets++ < 32)
1798 mpegts_insert_null_packet(s);
1802 static int mpegts_write_packet(AVFormatContext *s, AVPacket *pkt)
1805 mpegts_write_flush(s);
1808 return mpegts_write_packet_internal(s, pkt);
1812 static int mpegts_write_end(AVFormatContext *s)
1815 mpegts_write_flush(s);
1820 static void mpegts_deinit(AVFormatContext *s)
1822 MpegTSWrite *ts = s->priv_data;
1823 MpegTSService *service;
1826 for (i = 0; i < s->nb_streams; i++) {
1827 AVStream *st = s->streams[i];
1828 MpegTSWriteStream *ts_st = st->priv_data;
1830 av_freep(&ts_st->payload);
1832 avformat_free_context(ts_st->amux);
1838 for (i = 0; i < ts->nb_services; i++) {
1839 service = ts->services[i];
1842 av_freep(&ts->services);
1845 static int mpegts_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
1848 AVStream *st = s->streams[pkt->stream_index];
1850 if (st->codecpar->codec_id == AV_CODEC_ID_H264) {
1851 if (pkt->size >= 5 && AV_RB32(pkt->data) != 0x0000001 &&
1852 (AV_RB24(pkt->data) != 0x000001 ||
1853 (st->codecpar->extradata_size > 0 &&
1854 st->codecpar->extradata[0] == 1)))
1855 ret = ff_stream_add_bitstream_filter(st, "h264_mp4toannexb", NULL);
1856 } else if (st->codecpar->codec_id == AV_CODEC_ID_HEVC) {
1857 if (pkt->size >= 5 && AV_RB32(pkt->data) != 0x0000001 &&
1858 (AV_RB24(pkt->data) != 0x000001 ||
1859 (st->codecpar->extradata_size > 0 &&
1860 st->codecpar->extradata[0] == 1)))
1861 ret = ff_stream_add_bitstream_filter(st, "hevc_mp4toannexb", NULL);
1867 static const AVOption options[] = {
1868 { "mpegts_transport_stream_id", "Set transport_stream_id field.",
1869 offsetof(MpegTSWrite, transport_stream_id), AV_OPT_TYPE_INT,
1870 { .i64 = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM },
1871 { "mpegts_original_network_id", "Set original_network_id field.",
1872 offsetof(MpegTSWrite, original_network_id), AV_OPT_TYPE_INT,
1873 { .i64 = DVB_PRIVATE_NETWORK_START }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM },
1874 { "mpegts_service_id", "Set service_id field.",
1875 offsetof(MpegTSWrite, service_id), AV_OPT_TYPE_INT,
1876 { .i64 = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM },
1877 { "mpegts_service_type", "Set service_type field.",
1878 offsetof(MpegTSWrite, service_type), AV_OPT_TYPE_INT,
1879 { .i64 = 0x01 }, 0x01, 0xff, AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1880 { "digital_tv", "Digital Television.",
1881 0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_DIGITAL_TV }, 0x01, 0xff,
1882 AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1883 { "digital_radio", "Digital Radio.",
1884 0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_DIGITAL_RADIO }, 0x01, 0xff,
1885 AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1886 { "teletext", "Teletext.",
1887 0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_TELETEXT }, 0x01, 0xff,
1888 AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1889 { "advanced_codec_digital_radio", "Advanced Codec Digital Radio.",
1890 0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_ADVANCED_CODEC_DIGITAL_RADIO }, 0x01, 0xff,
1891 AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1892 { "mpeg2_digital_hdtv", "MPEG2 Digital HDTV.",
1893 0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_MPEG2_DIGITAL_HDTV }, 0x01, 0xff,
1894 AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1895 { "advanced_codec_digital_sdtv", "Advanced Codec Digital SDTV.",
1896 0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_ADVANCED_CODEC_DIGITAL_SDTV }, 0x01, 0xff,
1897 AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1898 { "advanced_codec_digital_hdtv", "Advanced Codec Digital HDTV.",
1899 0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_ADVANCED_CODEC_DIGITAL_HDTV }, 0x01, 0xff,
1900 AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1901 { "hevc_digital_hdtv", "HEVC Digital Television Service.",
1902 0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_HEVC_DIGITAL_HDTV }, 0x01, 0xff,
1903 AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1904 { "mpegts_pmt_start_pid", "Set the first pid of the PMT.",
1905 offsetof(MpegTSWrite, pmt_start_pid), AV_OPT_TYPE_INT,
1906 { .i64 = 0x1000 }, FIRST_OTHER_PID, LAST_OTHER_PID, AV_OPT_FLAG_ENCODING_PARAM },
1907 { "mpegts_start_pid", "Set the first pid.",
1908 offsetof(MpegTSWrite, start_pid), AV_OPT_TYPE_INT,
1909 { .i64 = 0x0100 }, FIRST_OTHER_PID, LAST_OTHER_PID, AV_OPT_FLAG_ENCODING_PARAM },
1910 { "mpegts_m2ts_mode", "Enable m2ts mode.",
1911 offsetof(MpegTSWrite, m2ts_mode), AV_OPT_TYPE_BOOL,
1912 { .i64 = -1 }, -1, 1, AV_OPT_FLAG_ENCODING_PARAM },
1914 offsetof(MpegTSWrite, mux_rate), AV_OPT_TYPE_INT,
1915 { .i64 = 1 }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
1916 { "pes_payload_size", "Minimum PES packet payload in bytes",
1917 offsetof(MpegTSWrite, pes_payload_size), AV_OPT_TYPE_INT,
1918 { .i64 = DEFAULT_PES_PAYLOAD_SIZE }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
1919 { "mpegts_flags", "MPEG-TS muxing flags",
1920 offsetof(MpegTSWrite, flags), AV_OPT_TYPE_FLAGS, { .i64 = 0 }, 0, INT_MAX,
1921 AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags" },
1922 { "resend_headers", "Reemit PAT/PMT before writing the next packet",
1923 0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_FLAG_REEMIT_PAT_PMT }, 0, INT_MAX,
1924 AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags" },
1925 { "latm", "Use LATM packetization for AAC",
1926 0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_FLAG_AAC_LATM }, 0, INT_MAX,
1927 AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags" },
1928 { "pat_pmt_at_frames", "Reemit PAT and PMT at each video frame",
1929 0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_FLAG_PAT_PMT_AT_FRAMES}, 0, INT_MAX,
1930 AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags" },
1931 { "system_b", "Conform to System B (DVB) instead of System A (ATSC)",
1932 0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_FLAG_SYSTEM_B }, 0, INT_MAX,
1933 AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags" },
1934 { "initial_discontinuity", "Mark initial packets as discontinuous",
1935 0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_FLAG_DISCONT }, 0, INT_MAX,
1936 AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags" },
1937 { "mpegts_copyts", "don't offset dts/pts",
1938 offsetof(MpegTSWrite, copyts), AV_OPT_TYPE_BOOL,
1939 { .i64 = -1 }, -1, 1, AV_OPT_FLAG_ENCODING_PARAM },
1940 { "tables_version", "set PAT, PMT and SDT version",
1941 offsetof(MpegTSWrite, tables_version), AV_OPT_TYPE_INT,
1942 { .i64 = 0 }, 0, 31, AV_OPT_FLAG_ENCODING_PARAM },
1943 { "omit_video_pes_length", "Omit the PES packet length for video packets",
1944 offsetof(MpegTSWrite, omit_video_pes_length), AV_OPT_TYPE_BOOL,
1945 { .i64 = 1 }, 0, 1, AV_OPT_FLAG_ENCODING_PARAM },
1946 { "pcr_period", "PCR retransmission time in milliseconds",
1947 offsetof(MpegTSWrite, pcr_period_ms), AV_OPT_TYPE_INT,
1948 { .i64 = -1 }, -1, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
1949 { "pat_period", "PAT/PMT retransmission time limit in seconds",
1950 offsetof(MpegTSWrite, pat_period_us), AV_OPT_TYPE_DURATION,
1951 { .i64 = PAT_RETRANS_TIME * 1000LL }, 0, INT64_MAX, AV_OPT_FLAG_ENCODING_PARAM },
1952 { "sdt_period", "SDT retransmission time limit in seconds",
1953 offsetof(MpegTSWrite, sdt_period_us), AV_OPT_TYPE_DURATION,
1954 { .i64 = SDT_RETRANS_TIME * 1000LL }, 0, INT64_MAX, AV_OPT_FLAG_ENCODING_PARAM },
1958 static const AVClass mpegts_muxer_class = {
1959 .class_name = "MPEGTS muxer",
1960 .item_name = av_default_item_name,
1962 .version = LIBAVUTIL_VERSION_INT,
1965 AVOutputFormat ff_mpegts_muxer = {
1967 .long_name = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
1968 .mime_type = "video/MP2T",
1969 .extensions = "ts,m2t,m2ts,mts",
1970 .priv_data_size = sizeof(MpegTSWrite),
1971 .audio_codec = AV_CODEC_ID_MP2,
1972 .video_codec = AV_CODEC_ID_MPEG2VIDEO,
1973 .init = mpegts_init,
1974 .write_packet = mpegts_write_packet,
1975 .write_trailer = mpegts_write_end,
1976 .deinit = mpegts_deinit,
1977 .check_bitstream = mpegts_check_bitstream,
1978 .flags = AVFMT_ALLOW_FLUSH | AVFMT_VARIABLE_FPS | AVFMT_NODIMENSIONS,
1979 .priv_class = &mpegts_muxer_class,