LCOV - code coverage report
Current view: top level - libavformat - mpegtsenc.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 575 1116 51.5 %
Date: 2017-12-15 18:13:28 Functions: 25 30 83.3 %

          Line data    Source code
       1             : /*
       2             :  * MPEG-2 transport stream (aka DVB) muxer
       3             :  * Copyright (c) 2003 Fabrice Bellard
       4             :  *
       5             :  * This file is part of FFmpeg.
       6             :  *
       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.
      11             :  *
      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.
      16             :  *
      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
      20             :  */
      21             : 
      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"
      29             : 
      30             : #include "libavcodec/internal.h"
      31             : 
      32             : #include "avformat.h"
      33             : #include "avio_internal.h"
      34             : #include "internal.h"
      35             : #include "mpegts.h"
      36             : 
      37             : #define PCR_TIME_BASE 27000000
      38             : 
      39             : /* write DVB SI sections */
      40             : 
      41             : #define DVB_PRIVATE_NETWORK_START 0xff01
      42             : 
      43             : /*********************************************/
      44             : /* mpegts section writer */
      45             : 
      46             : typedef struct MpegTSSection {
      47             :     int pid;
      48             :     int cc;
      49             :     int discontinuity;
      50             :     void (*write_packet)(struct MpegTSSection *s, const uint8_t *packet);
      51             :     void *opaque;
      52             : } MpegTSSection;
      53             : 
      54             : typedef struct MpegTSService {
      55             :     MpegTSSection pmt; /* MPEG-2 PMT table context */
      56             :     int sid;           /* service ID */
      57             :     char *name;
      58             :     char *provider_name;
      59             :     int pcr_pid;
      60             :     int pcr_packet_count;
      61             :     int pcr_packet_period;
      62             :     AVProgram *program;
      63             : } MpegTSService;
      64             : 
      65             : // service_type values as defined in ETSI 300 468
      66             : enum {
      67             :     MPEGTS_SERVICE_TYPE_DIGITAL_TV                   = 0x01,
      68             :     MPEGTS_SERVICE_TYPE_DIGITAL_RADIO                = 0x02,
      69             :     MPEGTS_SERVICE_TYPE_TELETEXT                     = 0x03,
      70             :     MPEGTS_SERVICE_TYPE_ADVANCED_CODEC_DIGITAL_RADIO = 0x0A,
      71             :     MPEGTS_SERVICE_TYPE_MPEG2_DIGITAL_HDTV           = 0x11,
      72             :     MPEGTS_SERVICE_TYPE_ADVANCED_CODEC_DIGITAL_SDTV  = 0x16,
      73             :     MPEGTS_SERVICE_TYPE_ADVANCED_CODEC_DIGITAL_HDTV  = 0x19,
      74             :     MPEGTS_SERVICE_TYPE_HEVC_DIGITAL_HDTV            = 0x1F,
      75             : };
      76             : typedef struct MpegTSWrite {
      77             :     const AVClass *av_class;
      78             :     MpegTSSection pat; /* MPEG-2 PAT table */
      79             :     MpegTSSection sdt; /* MPEG-2 SDT table context */
      80             :     MpegTSService **services;
      81             :     int sdt_packet_count;
      82             :     int sdt_packet_period;
      83             :     int pat_packet_count;
      84             :     int pat_packet_period;
      85             :     int nb_services;
      86             :     int onid;
      87             :     int tsid;
      88             :     int64_t first_pcr;
      89             :     int mux_rate; ///< set to 1 when VBR
      90             :     int pes_payload_size;
      91             : 
      92             :     int transport_stream_id;
      93             :     int original_network_id;
      94             :     int service_id;
      95             :     int service_type;
      96             : 
      97             :     int pmt_start_pid;
      98             :     int start_pid;
      99             :     int m2ts_mode;
     100             : 
     101             :     int reemit_pat_pmt; // backward compatibility
     102             : 
     103             :     int pcr_period;
     104             : #define MPEGTS_FLAG_REEMIT_PAT_PMT  0x01
     105             : #define MPEGTS_FLAG_AAC_LATM        0x02
     106             : #define MPEGTS_FLAG_PAT_PMT_AT_FRAMES           0x04
     107             : #define MPEGTS_FLAG_SYSTEM_B        0x08
     108             : #define MPEGTS_FLAG_DISCONT         0x10
     109             :     int flags;
     110             :     int copyts;
     111             :     int tables_version;
     112             :     double pat_period;
     113             :     double sdt_period;
     114             :     int64_t last_pat_ts;
     115             :     int64_t last_sdt_ts;
     116             : 
     117             :     int omit_video_pes_length;
     118             : } MpegTSWrite;
     119             : 
     120             : /* a PES packet header is generated every DEFAULT_PES_HEADER_FREQ packets */
     121             : #define DEFAULT_PES_HEADER_FREQ  16
     122             : #define DEFAULT_PES_PAYLOAD_SIZE ((DEFAULT_PES_HEADER_FREQ - 1) * 184 + 170)
     123             : 
     124             : /* The section length is 12 bits. The first 2 are set to 0, the remaining
     125             :  * 10 bits should not exceed 1021. */
     126             : #define SECTION_LENGTH 1020
     127             : 
     128             : /* NOTE: 4 bytes must be left at the end for the crc32 */
     129        1277 : static void mpegts_write_section(MpegTSSection *s, uint8_t *buf, int len)
     130             : {
     131             :     unsigned int crc;
     132             :     unsigned char packet[TS_PACKET_SIZE];
     133             :     const unsigned char *buf_ptr;
     134             :     unsigned char *q;
     135             :     int first, b, len1, left;
     136             : 
     137        1277 :     crc = av_bswap32(av_crc(av_crc_get_table(AV_CRC_32_IEEE),
     138        1277 :                             -1, buf, len - 4));
     139             : 
     140        1277 :     buf[len - 4] = (crc >> 24) & 0xff;
     141        1277 :     buf[len - 3] = (crc >> 16) & 0xff;
     142        1277 :     buf[len - 2] = (crc >>  8) & 0xff;
     143        1277 :     buf[len - 1] =  crc        & 0xff;
     144             : 
     145             :     /* send each packet */
     146        1277 :     buf_ptr = buf;
     147        3831 :     while (len > 0) {
     148        1277 :         first = buf == buf_ptr;
     149        1277 :         q     = packet;
     150        1277 :         *q++  = 0x47;
     151        1277 :         b     = s->pid >> 8;
     152        1277 :         if (first)
     153        1277 :             b |= 0x40;
     154        1277 :         *q++  = b;
     155        1277 :         *q++  = s->pid;
     156        1277 :         s->cc = s->cc + 1 & 0xf;
     157        1277 :         *q++  = 0x10 | s->cc;
     158        1277 :         if (s->discontinuity) {
     159           0 :             q[-1] |= 0x20;
     160           0 :             *q++ = 1;
     161           0 :             *q++ = 0x80;
     162           0 :             s->discontinuity = 0;
     163             :         }
     164        1277 :         if (first)
     165        1277 :             *q++ = 0; /* 0 offset */
     166        1277 :         len1 = TS_PACKET_SIZE - (q - packet);
     167        1277 :         if (len1 > len)
     168        1277 :             len1 = len;
     169        1277 :         memcpy(q, buf_ptr, len1);
     170        1277 :         q += len1;
     171             :         /* add known padding data */
     172        1277 :         left = TS_PACKET_SIZE - (q - packet);
     173        1277 :         if (left > 0)
     174        1277 :             memset(q, 0xff, left);
     175             : 
     176        1277 :         s->write_packet(s, packet);
     177             : 
     178        1277 :         buf_ptr += len1;
     179        1277 :         len     -= len1;
     180             :     }
     181        1277 : }
     182             : 
     183        5160 : static inline void put16(uint8_t **q_ptr, int val)
     184             : {
     185             :     uint8_t *q;
     186        5160 :     q      = *q_ptr;
     187        5160 :     *q++   = val >> 8;
     188        5160 :     *q++   = val;
     189        5160 :     *q_ptr = q;
     190        5160 : }
     191             : 
     192        1277 : static int mpegts_write_section1(MpegTSSection *s, int tid, int id,
     193             :                                  int version, int sec_num, int last_sec_num,
     194             :                                  uint8_t *buf, int len)
     195             : {
     196             :     uint8_t section[1024], *q;
     197             :     unsigned int tot_len;
     198             :     /* reserved_future_use field must be set to 1 for SDT */
     199        1277 :     unsigned int flags = tid == SDT_TID ? 0xf000 : 0xb000;
     200             : 
     201        1277 :     tot_len = 3 + 5 + len + 4;
     202             :     /* check if not too big */
     203        1277 :     if (tot_len > 1024)
     204           0 :         return AVERROR_INVALIDDATA;
     205             : 
     206        1277 :     q    = section;
     207        1277 :     *q++ = tid;
     208        1277 :     put16(&q, flags | (len + 5 + 4)); /* 5 byte header + 4 byte CRC */
     209        1277 :     put16(&q, id);
     210        1277 :     *q++ = 0xc1 | (version << 1); /* current_next_indicator = 1 */
     211        1277 :     *q++ = sec_num;
     212        1277 :     *q++ = last_sec_num;
     213        1277 :     memcpy(q, buf, len);
     214             : 
     215        1277 :     mpegts_write_section(s, section, tot_len);
     216        1277 :     return 0;
     217             : }
     218             : 
     219             : /*********************************************/
     220             : /* mpegts writer */
     221             : 
     222             : #define DEFAULT_PROVIDER_NAME   "FFmpeg"
     223             : #define DEFAULT_SERVICE_NAME    "Service01"
     224             : 
     225             : /* we retransmit the SI info at this rate */
     226             : #define SDT_RETRANS_TIME 500
     227             : #define PAT_RETRANS_TIME 100
     228             : #define PCR_RETRANS_TIME 20
     229             : 
     230             : typedef struct MpegTSWriteStream {
     231             :     struct MpegTSService *service;
     232             :     int pid; /* stream associated pid */
     233             :     int cc;
     234             :     int discontinuity;
     235             :     int payload_size;
     236             :     int first_pts_check; ///< first pts check needed
     237             :     int prev_payload_key;
     238             :     int64_t payload_pts;
     239             :     int64_t payload_dts;
     240             :     int payload_flags;
     241             :     uint8_t *payload;
     242             :     AVFormatContext *amux;
     243             :     AVRational user_tb;
     244             : 
     245             :     /* For Opus */
     246             :     int opus_queued_samples;
     247             :     int opus_pending_trim_start;
     248             : } MpegTSWriteStream;
     249             : 
     250         578 : static void mpegts_write_pat(AVFormatContext *s)
     251             : {
     252         578 :     MpegTSWrite *ts = s->priv_data;
     253             :     MpegTSService *service;
     254             :     uint8_t data[SECTION_LENGTH], *q;
     255             :     int i;
     256             : 
     257         578 :     q = data;
     258        1156 :     for (i = 0; i < ts->nb_services; i++) {
     259         578 :         service = ts->services[i];
     260         578 :         put16(&q, service->sid);
     261         578 :         put16(&q, 0xe000 | service->pmt.pid);
     262             :     }
     263         578 :     mpegts_write_section1(&ts->pat, PAT_TID, ts->tsid, ts->tables_version, 0, 0,
     264         578 :                           data, q - data);
     265         578 : }
     266             : 
     267             : /* NOTE: !str is accepted for an empty string */
     268         242 : static void putstr8(uint8_t **q_ptr, const char *str, int write_len)
     269             : {
     270             :     uint8_t *q;
     271             :     int len;
     272             : 
     273         242 :     q = *q_ptr;
     274         242 :     if (!str)
     275           0 :         len = 0;
     276             :     else
     277         242 :         len = strlen(str);
     278         242 :     if (write_len)
     279         242 :         *q++ = len;
     280         242 :     if (!str) {
     281           0 :         *q_ptr = q;
     282           0 :         return;
     283             :     }
     284         242 :     memcpy(q, str, len);
     285         242 :     q     += len;
     286         242 :     *q_ptr = q;
     287             : }
     288             : 
     289         578 : static int mpegts_write_pmt(AVFormatContext *s, MpegTSService *service)
     290             : {
     291         578 :     MpegTSWrite *ts = s->priv_data;
     292             :     uint8_t data[SECTION_LENGTH], *q, *desc_length_ptr, *program_info_length_ptr;
     293         578 :     int val, stream_type, i, err = 0;
     294             : 
     295         578 :     q = data;
     296         578 :     put16(&q, 0xe000 | service->pcr_pid);
     297             : 
     298         578 :     program_info_length_ptr = q;
     299         578 :     q += 2; /* patched after */
     300             : 
     301             :     /* put program info here */
     302             : 
     303         578 :     val = 0xf000 | (q - program_info_length_ptr - 2);
     304         578 :     program_info_length_ptr[0] = val >> 8;
     305         578 :     program_info_length_ptr[1] = val;
     306             : 
     307        1208 :     for (i = 0; i < s->nb_streams; i++) {
     308         630 :         AVStream *st = s->streams[i];
     309         630 :         MpegTSWriteStream *ts_st = st->priv_data;
     310         630 :         AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL, 0);
     311             : 
     312         630 :         if (s->nb_programs) {
     313           0 :             int k, found = 0;
     314           0 :             AVProgram *program = service->program;
     315             : 
     316           0 :             for (k = 0; k < program->nb_stream_indexes; k++)
     317           0 :                 if (program->stream_index[k] == i) {
     318           0 :                     found = 1;
     319           0 :                     break;
     320             :                 }
     321             : 
     322           0 :             if (!found)
     323           0 :                 continue;
     324             :         }
     325             : 
     326         630 :         if (q - data > SECTION_LENGTH - 32) {
     327           0 :             err = 1;
     328           0 :             break;
     329             :         }
     330         630 :         switch (st->codecpar->codec_id) {
     331          52 :         case AV_CODEC_ID_MPEG1VIDEO:
     332             :         case AV_CODEC_ID_MPEG2VIDEO:
     333          52 :             stream_type = STREAM_TYPE_VIDEO_MPEG2;
     334          52 :             break;
     335           0 :         case AV_CODEC_ID_MPEG4:
     336           0 :             stream_type = STREAM_TYPE_VIDEO_MPEG4;
     337           0 :             break;
     338          51 :         case AV_CODEC_ID_H264:
     339          51 :             stream_type = STREAM_TYPE_VIDEO_H264;
     340          51 :             break;
     341           0 :         case AV_CODEC_ID_HEVC:
     342           0 :             stream_type = STREAM_TYPE_VIDEO_HEVC;
     343           0 :             break;
     344           0 :         case AV_CODEC_ID_CAVS:
     345           0 :             stream_type = STREAM_TYPE_VIDEO_CAVS;
     346           0 :             break;
     347           0 :         case AV_CODEC_ID_DIRAC:
     348           0 :             stream_type = STREAM_TYPE_VIDEO_DIRAC;
     349           0 :             break;
     350           0 :         case AV_CODEC_ID_VC1:
     351           0 :             stream_type = STREAM_TYPE_VIDEO_VC1;
     352           0 :             break;
     353         326 :         case AV_CODEC_ID_MP2:
     354             :         case AV_CODEC_ID_MP3:
     355         326 :             if (   st->codecpar->sample_rate > 0
     356         326 :                 && st->codecpar->sample_rate < 32000) {
     357           0 :                 stream_type = STREAM_TYPE_AUDIO_MPEG2;
     358             :             } else {
     359         326 :                 stream_type = STREAM_TYPE_AUDIO_MPEG1;
     360             :             }
     361         326 :             break;
     362           0 :         case AV_CODEC_ID_AAC:
     363           0 :             stream_type = (ts->flags & MPEGTS_FLAG_AAC_LATM)
     364             :                           ? STREAM_TYPE_AUDIO_AAC_LATM
     365           0 :                           : STREAM_TYPE_AUDIO_AAC;
     366           0 :             break;
     367           0 :         case AV_CODEC_ID_AAC_LATM:
     368           0 :             stream_type = STREAM_TYPE_AUDIO_AAC_LATM;
     369           0 :             break;
     370           0 :         case AV_CODEC_ID_AC3:
     371           0 :             stream_type = (ts->flags & MPEGTS_FLAG_SYSTEM_B)
     372             :                           ? STREAM_TYPE_PRIVATE_DATA
     373           0 :                           : STREAM_TYPE_AUDIO_AC3;
     374           0 :             break;
     375           0 :         case AV_CODEC_ID_EAC3:
     376           0 :             stream_type = (ts->flags & MPEGTS_FLAG_SYSTEM_B)
     377             :                           ? STREAM_TYPE_PRIVATE_DATA
     378           0 :                           : STREAM_TYPE_AUDIO_EAC3;
     379           0 :             break;
     380           0 :         case AV_CODEC_ID_DTS:
     381           0 :             stream_type = STREAM_TYPE_AUDIO_DTS;
     382           0 :             break;
     383           0 :         case AV_CODEC_ID_TRUEHD:
     384           0 :             stream_type = STREAM_TYPE_AUDIO_TRUEHD;
     385           0 :             break;
     386           0 :         case AV_CODEC_ID_OPUS:
     387           0 :             stream_type = STREAM_TYPE_PRIVATE_DATA;
     388           0 :             break;
     389           0 :         case AV_CODEC_ID_TIMED_ID3:
     390           0 :             stream_type = STREAM_TYPE_METADATA;
     391           0 :             break;
     392         201 :         default:
     393         201 :             stream_type = STREAM_TYPE_PRIVATE_DATA;
     394         201 :             break;
     395             :         }
     396             : 
     397         630 :         *q++ = stream_type;
     398         630 :         put16(&q, 0xe000 | ts_st->pid);
     399         630 :         desc_length_ptr = q;
     400         630 :         q += 2; /* patched after */
     401             : 
     402             :         /* write optional descriptors here */
     403         630 :         switch (st->codecpar->codec_type) {
     404         527 :         case AVMEDIA_TYPE_AUDIO:
     405         527 :             if (st->codecpar->codec_id==AV_CODEC_ID_AC3 && (ts->flags & MPEGTS_FLAG_SYSTEM_B)) {
     406           0 :                 *q++=0x6a; // AC3 descriptor see A038 DVB SI
     407           0 :                 *q++=1; // 1 byte, all flags sets to 0
     408           0 :                 *q++=0; // omit all fields...
     409             :             }
     410         527 :             if (st->codecpar->codec_id==AV_CODEC_ID_EAC3 && (ts->flags & MPEGTS_FLAG_SYSTEM_B)) {
     411           0 :                 *q++=0x7a; // EAC3 descriptor see A038 DVB SI
     412           0 :                 *q++=1; // 1 byte, all flags sets to 0
     413           0 :                 *q++=0; // omit all fields...
     414             :             }
     415         527 :             if (st->codecpar->codec_id==AV_CODEC_ID_S302M) {
     416         201 :                 *q++ = 0x05; /* MPEG-2 registration descriptor*/
     417         201 :                 *q++ = 4;
     418         201 :                 *q++ = 'B';
     419         201 :                 *q++ = 'S';
     420         201 :                 *q++ = 'S';
     421         201 :                 *q++ = 'D';
     422             :             }
     423         527 :             if (st->codecpar->codec_id==AV_CODEC_ID_OPUS) {
     424             :                 /* 6 bytes registration descriptor, 4 bytes Opus audio descriptor */
     425           0 :                 if (q - data > SECTION_LENGTH - 6 - 4) {
     426           0 :                     err = 1;
     427           0 :                     break;
     428             :                 }
     429             : 
     430           0 :                 *q++ = 0x05; /* MPEG-2 registration descriptor*/
     431           0 :                 *q++ = 4;
     432           0 :                 *q++ = 'O';
     433           0 :                 *q++ = 'p';
     434           0 :                 *q++ = 'u';
     435           0 :                 *q++ = 's';
     436             : 
     437           0 :                 *q++ = 0x7f; /* DVB extension descriptor */
     438           0 :                 *q++ = 2;
     439           0 :                 *q++ = 0x80;
     440             : 
     441           0 :                 if (st->codecpar->extradata && st->codecpar->extradata_size >= 19) {
     442           0 :                     if (st->codecpar->extradata[18] == 0 && st->codecpar->channels <= 2) {
     443             :                         /* RTP mapping family */
     444           0 :                         *q++ = st->codecpar->channels;
     445           0 :                     } else if (st->codecpar->extradata[18] == 1 && st->codecpar->channels <= 8 &&
     446           0 :                                st->codecpar->extradata_size >= 21 + st->codecpar->channels) {
     447             :                         static const uint8_t coupled_stream_counts[9] = {
     448             :                             1, 0, 1, 1, 2, 2, 2, 3, 3
     449             :                         };
     450             :                         static const uint8_t channel_map_a[8][8] = {
     451             :                             {0},
     452             :                             {0, 1},
     453             :                             {0, 2, 1},
     454             :                             {0, 1, 2, 3},
     455             :                             {0, 4, 1, 2, 3},
     456             :                             {0, 4, 1, 2, 3, 5},
     457             :                             {0, 4, 1, 2, 3, 5, 6},
     458             :                             {0, 6, 1, 2, 3, 4, 5, 7},
     459             :                         };
     460             :                         static const uint8_t channel_map_b[8][8] = {
     461             :                             {0},
     462             :                             {0, 1},
     463             :                             {0, 1, 2},
     464             :                             {0, 1, 2, 3},
     465             :                             {0, 1, 2, 3, 4},
     466             :                             {0, 1, 2, 3, 4, 5},
     467             :                             {0, 1, 2, 3, 4, 5, 6},
     468             :                             {0, 1, 2, 3, 4, 5, 6, 7},
     469             :                         };
     470             :                         /* Vorbis mapping family */
     471             : 
     472           0 :                         if (st->codecpar->extradata[19] == st->codecpar->channels - coupled_stream_counts[st->codecpar->channels] &&
     473           0 :                             st->codecpar->extradata[20] == coupled_stream_counts[st->codecpar->channels] &&
     474           0 :                             memcmp(&st->codecpar->extradata[21], channel_map_a[st->codecpar->channels-1], st->codecpar->channels) == 0) {
     475           0 :                             *q++ = st->codecpar->channels;
     476           0 :                         } else if (st->codecpar->channels >= 2 && st->codecpar->extradata[19] == st->codecpar->channels &&
     477           0 :                                    st->codecpar->extradata[20] == 0 &&
     478           0 :                                    memcmp(&st->codecpar->extradata[21], channel_map_b[st->codecpar->channels-1], st->codecpar->channels) == 0) {
     479           0 :                             *q++ = st->codecpar->channels | 0x80;
     480             :                         } else {
     481             :                             /* Unsupported, could write an extended descriptor here */
     482           0 :                             av_log(s, AV_LOG_ERROR, "Unsupported Opus Vorbis-style channel mapping");
     483           0 :                             *q++ = 0xff;
     484             :                         }
     485             :                     } else {
     486             :                         /* Unsupported */
     487           0 :                         av_log(s, AV_LOG_ERROR, "Unsupported Opus channel mapping for family %d", st->codecpar->extradata[18]);
     488           0 :                         *q++ = 0xff;
     489             :                     }
     490           0 :                 } else if (st->codecpar->channels <= 2) {
     491             :                     /* Assume RTP mapping family */
     492           0 :                     *q++ = st->codecpar->channels;
     493             :                 } else {
     494             :                     /* Unsupported */
     495           0 :                     av_log(s, AV_LOG_ERROR, "Unsupported Opus channel mapping");
     496           0 :                     *q++ = 0xff;
     497             :                 }
     498             :             }
     499             : 
     500         527 :             if (lang) {
     501             :                 char *p;
     502           0 :                 char *next = lang->value;
     503             :                 uint8_t *len_ptr;
     504             : 
     505           0 :                 *q++     = 0x0a; /* ISO 639 language descriptor */
     506           0 :                 len_ptr  = q++;
     507           0 :                 *len_ptr = 0;
     508             : 
     509           0 :                 for (p = lang->value; next && *len_ptr < 255 / 4 * 4; p = next + 1) {
     510           0 :                     if (q - data > SECTION_LENGTH - 4) {
     511           0 :                         err = 1;
     512           0 :                         break;
     513             :                     }
     514           0 :                     next = strchr(p, ',');
     515           0 :                     if (strlen(p) != 3 && (!next || next != p + 3))
     516           0 :                         continue; /* not a 3-letter code */
     517             : 
     518           0 :                     *q++ = *p++;
     519           0 :                     *q++ = *p++;
     520           0 :                     *q++ = *p++;
     521             : 
     522           0 :                     if (st->disposition & AV_DISPOSITION_CLEAN_EFFECTS)
     523           0 :                         *q++ = 0x01;
     524           0 :                     else if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
     525           0 :                         *q++ = 0x02;
     526           0 :                     else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
     527           0 :                         *q++ = 0x03;
     528             :                     else
     529           0 :                         *q++ = 0; /* undefined type */
     530             : 
     531           0 :                     *len_ptr += 4;
     532             :                 }
     533             : 
     534           0 :                 if (*len_ptr == 0)
     535           0 :                     q -= 2; /* no language codes were written */
     536             :             }
     537         527 :             break;
     538           0 :         case AVMEDIA_TYPE_SUBTITLE:
     539             :         {
     540           0 :            const char default_language[] = "und";
     541           0 :            const char *language = lang && strlen(lang->value) >= 3 ? lang->value : default_language;
     542             : 
     543           0 :            if (st->codecpar->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
     544             :                uint8_t *len_ptr;
     545           0 :                int extradata_copied = 0;
     546             : 
     547           0 :                *q++ = 0x59; /* subtitling_descriptor */
     548           0 :                len_ptr = q++;
     549             : 
     550           0 :                while (strlen(language) >= 3) {
     551           0 :                    if (sizeof(data) - (q - data) < 8) { /* 8 bytes per DVB subtitle substream data */
     552           0 :                        err = 1;
     553           0 :                        break;
     554             :                    }
     555           0 :                    *q++ = *language++;
     556           0 :                    *q++ = *language++;
     557           0 :                    *q++ = *language++;
     558             :                    /* Skip comma */
     559           0 :                    if (*language != '\0')
     560           0 :                        language++;
     561             : 
     562           0 :                    if (st->codecpar->extradata_size - extradata_copied >= 5) {
     563           0 :                        *q++ = st->codecpar->extradata[extradata_copied + 4]; /* subtitling_type */
     564           0 :                        memcpy(q, st->codecpar->extradata + extradata_copied, 4); /* composition_page_id and ancillary_page_id */
     565           0 :                        extradata_copied += 5;
     566           0 :                        q += 4;
     567             :                    } else {
     568             :                        /* subtitling_type:
     569             :                         * 0x10 - normal with no monitor aspect ratio criticality
     570             :                         * 0x20 - for the hard of hearing with no monitor aspect ratio criticality */
     571           0 :                        *q++ = (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED) ? 0x20 : 0x10;
     572           0 :                        if ((st->codecpar->extradata_size == 4) && (extradata_copied == 0)) {
     573             :                            /* support of old 4-byte extradata format */
     574           0 :                            memcpy(q, st->codecpar->extradata, 4); /* composition_page_id and ancillary_page_id */
     575           0 :                            extradata_copied += 4;
     576           0 :                            q += 4;
     577             :                        } else {
     578           0 :                            put16(&q, 1); /* composition_page_id */
     579           0 :                            put16(&q, 1); /* ancillary_page_id */
     580             :                        }
     581             :                    }
     582             :                }
     583             : 
     584           0 :                *len_ptr = q - len_ptr - 1;
     585           0 :            } else if (st->codecpar->codec_id == AV_CODEC_ID_DVB_TELETEXT) {
     586           0 :                uint8_t *len_ptr = NULL;
     587           0 :                int extradata_copied = 0;
     588             : 
     589             :                /* The descriptor tag. teletext_descriptor */
     590           0 :                *q++ = 0x56;
     591           0 :                len_ptr = q++;
     592             : 
     593           0 :                while (strlen(language) >= 3 && q - data < sizeof(data) - 6) {
     594           0 :                    *q++ = *language++;
     595           0 :                    *q++ = *language++;
     596           0 :                    *q++ = *language++;
     597             :                    /* Skip comma */
     598           0 :                    if (*language != '\0')
     599           0 :                        language++;
     600             : 
     601           0 :                    if (st->codecpar->extradata_size - 1 > extradata_copied) {
     602           0 :                        memcpy(q, st->codecpar->extradata + extradata_copied, 2);
     603           0 :                        extradata_copied += 2;
     604           0 :                        q += 2;
     605             :                    } else {
     606             :                        /* The Teletext descriptor:
     607             :                         * teletext_type: This 5-bit field indicates the type of Teletext page indicated. (0x01 Initial Teletext page)
     608             :                         * teletext_magazine_number: This is a 3-bit field which identifies the magazine number.
     609             :                         * teletext_page_number: This is an 8-bit field giving two 4-bit hex digits identifying the page number. */
     610           0 :                        *q++ = 0x08;
     611           0 :                        *q++ = 0x00;
     612             :                    }
     613             :                }
     614             : 
     615           0 :                *len_ptr = q - len_ptr - 1;
     616             :             }
     617             :         }
     618           0 :         break;
     619         103 :         case AVMEDIA_TYPE_VIDEO:
     620         103 :             if (stream_type == STREAM_TYPE_VIDEO_DIRAC) {
     621           0 :                 *q++ = 0x05; /*MPEG-2 registration descriptor*/
     622           0 :                 *q++ = 4;
     623           0 :                 *q++ = 'd';
     624           0 :                 *q++ = 'r';
     625           0 :                 *q++ = 'a';
     626           0 :                 *q++ = 'c';
     627         103 :             } else if (stream_type == STREAM_TYPE_VIDEO_VC1) {
     628           0 :                 *q++ = 0x05; /*MPEG-2 registration descriptor*/
     629           0 :                 *q++ = 4;
     630           0 :                 *q++ = 'V';
     631           0 :                 *q++ = 'C';
     632           0 :                 *q++ = '-';
     633           0 :                 *q++ = '1';
     634             :             }
     635         103 :             break;
     636           0 :         case AVMEDIA_TYPE_DATA:
     637           0 :             if (st->codecpar->codec_id == AV_CODEC_ID_SMPTE_KLV) {
     638           0 :                 *q++ = 0x05; /* MPEG-2 registration descriptor */
     639           0 :                 *q++ = 4;
     640           0 :                 *q++ = 'K';
     641           0 :                 *q++ = 'L';
     642           0 :                 *q++ = 'V';
     643           0 :                 *q++ = 'A';
     644           0 :             } else if (st->codecpar->codec_id == AV_CODEC_ID_TIMED_ID3) {
     645           0 :                 const char *tag = "ID3 ";
     646           0 :                 *q++ = 0x26; /* metadata descriptor */
     647           0 :                 *q++ = 13;
     648           0 :                 put16(&q, 0xffff);    /* metadata application format */
     649           0 :                 putstr8(&q, tag, 0);
     650           0 :                 *q++ = 0xff;        /* metadata format */
     651           0 :                 putstr8(&q, tag, 0);
     652           0 :                 *q++ = 0;            /* metadata service ID */
     653           0 :                 *q++ = 0xF;          /* metadata_locator_record_flag|MPEG_carriage_flags|reserved */
     654             :             }
     655           0 :             break;
     656             :         }
     657             : 
     658         630 :         val = 0xf000 | (q - desc_length_ptr - 2);
     659         630 :         desc_length_ptr[0] = val >> 8;
     660         630 :         desc_length_ptr[1] = val;
     661             :     }
     662             : 
     663         578 :     if (err)
     664           0 :         av_log(s, AV_LOG_ERROR,
     665             :                "The PMT section cannot fit stream %d and all following streams.\n"
     666             :                "Try reducing the number of languages in the audio streams "
     667             :                "or the total number of streams.\n", i);
     668             : 
     669         578 :     mpegts_write_section1(&service->pmt, PMT_TID, service->sid, ts->tables_version, 0, 0,
     670         578 :                           data, q - data);
     671         578 :     return 0;
     672             : }
     673             : 
     674         121 : static void mpegts_write_sdt(AVFormatContext *s)
     675             : {
     676         121 :     MpegTSWrite *ts = s->priv_data;
     677             :     MpegTSService *service;
     678             :     uint8_t data[SECTION_LENGTH], *q, *desc_list_len_ptr, *desc_len_ptr;
     679             :     int i, running_status, free_ca_mode, val;
     680             : 
     681         121 :     q = data;
     682         121 :     put16(&q, ts->onid);
     683         121 :     *q++ = 0xff;
     684         242 :     for (i = 0; i < ts->nb_services; i++) {
     685         121 :         service = ts->services[i];
     686         121 :         put16(&q, service->sid);
     687         121 :         *q++              = 0xfc | 0x00; /* currently no EIT info */
     688         121 :         desc_list_len_ptr = q;
     689         121 :         q                += 2;
     690         121 :         running_status    = 4; /* running */
     691         121 :         free_ca_mode      = 0;
     692             : 
     693             :         /* write only one descriptor for the service name and provider */
     694         121 :         *q++         = 0x48;
     695         121 :         desc_len_ptr = q;
     696         121 :         q++;
     697         121 :         *q++         = ts->service_type;
     698         121 :         putstr8(&q, service->provider_name, 1);
     699         121 :         putstr8(&q, service->name, 1);
     700         121 :         desc_len_ptr[0] = q - desc_len_ptr - 1;
     701             : 
     702             :         /* fill descriptor length */
     703         242 :         val = (running_status << 13) | (free_ca_mode << 12) |
     704         121 :               (q - desc_list_len_ptr - 2);
     705         121 :         desc_list_len_ptr[0] = val >> 8;
     706         121 :         desc_list_len_ptr[1] = val;
     707             :     }
     708         121 :     mpegts_write_section1(&ts->sdt, SDT_TID, ts->tsid, ts->tables_version, 0, 0,
     709         121 :                           data, q - data);
     710         121 : }
     711             : 
     712          12 : static MpegTSService *mpegts_add_service(MpegTSWrite *ts, int sid,
     713             :                                          const char *provider_name,
     714             :                                          const char *name)
     715             : {
     716             :     MpegTSService *service;
     717             : 
     718          12 :     service = av_mallocz(sizeof(MpegTSService));
     719          12 :     if (!service)
     720           0 :         return NULL;
     721          12 :     service->pmt.pid       = ts->pmt_start_pid + ts->nb_services;
     722          12 :     service->sid           = sid;
     723          12 :     service->pcr_pid       = 0x1fff;
     724          12 :     service->provider_name = av_strdup(provider_name);
     725          12 :     service->name          = av_strdup(name);
     726          12 :     if (!service->provider_name || !service->name)
     727             :         goto fail;
     728          12 :     if (av_dynarray_add_nofree(&ts->services, &ts->nb_services, service) < 0)
     729           0 :         goto fail;
     730             : 
     731          12 :     return service;
     732           0 : fail:
     733           0 :     av_freep(&service->provider_name);
     734           0 :     av_freep(&service->name);
     735           0 :     av_free(service);
     736           0 :     return NULL;
     737             : }
     738             : 
     739           0 : static int64_t get_pcr(const MpegTSWrite *ts, AVIOContext *pb)
     740             : {
     741           0 :     return av_rescale(avio_tell(pb) + 11, 8 * PCR_TIME_BASE, ts->mux_rate) +
     742           0 :            ts->first_pcr;
     743             : }
     744             : 
     745       29374 : static void mpegts_prefix_m2ts_header(AVFormatContext *s)
     746             : {
     747       29374 :     MpegTSWrite *ts = s->priv_data;
     748       29374 :     if (ts->m2ts_mode) {
     749           0 :         int64_t pcr = get_pcr(s->priv_data, s->pb);
     750           0 :         uint32_t tp_extra_header = pcr % 0x3fffffff;
     751           0 :         tp_extra_header = AV_RB32(&tp_extra_header);
     752           0 :         avio_write(s->pb, (unsigned char *) &tp_extra_header,
     753             :                    sizeof(tp_extra_header));
     754             :     }
     755       29374 : }
     756             : 
     757        1277 : static void section_write_packet(MpegTSSection *s, const uint8_t *packet)
     758             : {
     759        1277 :     AVFormatContext *ctx = s->opaque;
     760        1277 :     mpegts_prefix_m2ts_header(ctx);
     761        1277 :     avio_write(ctx->pb, packet, TS_PACKET_SIZE);
     762        1277 : }
     763             : 
     764          12 : static int mpegts_init(AVFormatContext *s)
     765             : {
     766          12 :     MpegTSWrite *ts = s->priv_data;
     767             :     MpegTSWriteStream *ts_st;
     768             :     MpegTSService *service;
     769          12 :     AVStream *st, *pcr_st = NULL;
     770             :     AVDictionaryEntry *title, *provider;
     771             :     int i, j;
     772             :     const char *service_name;
     773             :     const char *provider_name;
     774             :     int *pids;
     775             :     int ret;
     776             : 
     777          12 :     if (s->max_delay < 0) /* Not set by the caller */
     778           0 :         s->max_delay = 0;
     779             : 
     780             :     // round up to a whole number of TS packets
     781          12 :     ts->pes_payload_size = (ts->pes_payload_size + 14 + 183) / 184 * 184 - 14;
     782             : 
     783          12 :     ts->tsid = ts->transport_stream_id;
     784          12 :     ts->onid = ts->original_network_id;
     785          12 :     if (!s->nb_programs) {
     786             :         /* allocate a single DVB service */
     787          12 :         title = av_dict_get(s->metadata, "service_name", NULL, 0);
     788          12 :         if (!title)
     789          12 :             title = av_dict_get(s->metadata, "title", NULL, 0);
     790          12 :         service_name  = title ? title->value : DEFAULT_SERVICE_NAME;
     791          12 :         provider      = av_dict_get(s->metadata, "service_provider", NULL, 0);
     792          12 :         provider_name = provider ? provider->value : DEFAULT_PROVIDER_NAME;
     793          12 :         service       = mpegts_add_service(ts, ts->service_id,
     794             :                                            provider_name, service_name);
     795             : 
     796          12 :         if (!service)
     797           0 :             return AVERROR(ENOMEM);
     798             : 
     799          12 :         service->pmt.write_packet = section_write_packet;
     800          12 :         service->pmt.opaque       = s;
     801          12 :         service->pmt.cc           = 15;
     802          12 :         service->pmt.discontinuity= ts->flags & MPEGTS_FLAG_DISCONT;
     803             :     } else {
     804           0 :         for (i = 0; i < s->nb_programs; i++) {
     805           0 :             AVProgram *program = s->programs[i];
     806           0 :             title = av_dict_get(program->metadata, "service_name", NULL, 0);
     807           0 :             if (!title)
     808           0 :                 title = av_dict_get(program->metadata, "title", NULL, 0);
     809           0 :             service_name  = title ? title->value : DEFAULT_SERVICE_NAME;
     810           0 :             provider      = av_dict_get(program->metadata, "service_provider", NULL, 0);
     811           0 :             provider_name = provider ? provider->value : DEFAULT_PROVIDER_NAME;
     812           0 :             service       = mpegts_add_service(ts, program->id,
     813             :                                                provider_name, service_name);
     814             : 
     815           0 :             if (!service)
     816           0 :                 return AVERROR(ENOMEM);
     817             : 
     818           0 :             service->pmt.write_packet = section_write_packet;
     819           0 :             service->pmt.opaque       = s;
     820           0 :             service->pmt.cc           = 15;
     821           0 :             service->pmt.discontinuity= ts->flags & MPEGTS_FLAG_DISCONT;
     822           0 :             service->program          = program;
     823             :         }
     824             :     }
     825             : 
     826          12 :     ts->pat.pid          = PAT_PID;
     827             :     /* Initialize at 15 so that it wraps and is equal to 0 for the
     828             :      * first packet we write. */
     829          12 :     ts->pat.cc           = 15;
     830          12 :     ts->pat.discontinuity= ts->flags & MPEGTS_FLAG_DISCONT;
     831          12 :     ts->pat.write_packet = section_write_packet;
     832          12 :     ts->pat.opaque       = s;
     833             : 
     834          12 :     ts->sdt.pid          = SDT_PID;
     835          12 :     ts->sdt.cc           = 15;
     836          12 :     ts->sdt.discontinuity= ts->flags & MPEGTS_FLAG_DISCONT;
     837          12 :     ts->sdt.write_packet = section_write_packet;
     838          12 :     ts->sdt.opaque       = s;
     839             : 
     840          12 :     pids = av_malloc_array(s->nb_streams, sizeof(*pids));
     841          12 :     if (!pids) {
     842           0 :         ret = AVERROR(ENOMEM);
     843           0 :         goto fail;
     844             :     }
     845             : 
     846             :     /* assign pids to each stream */
     847          25 :     for (i = 0; i < s->nb_streams; i++) {
     848             :         AVProgram *program;
     849          13 :         st = s->streams[i];
     850             : 
     851          13 :         ts_st = av_mallocz(sizeof(MpegTSWriteStream));
     852          13 :         if (!ts_st) {
     853           0 :             ret = AVERROR(ENOMEM);
     854           0 :             goto fail;
     855             :         }
     856          13 :         st->priv_data = ts_st;
     857             : 
     858          13 :         ts_st->user_tb = st->time_base;
     859          13 :         avpriv_set_pts_info(st, 33, 1, 90000);
     860             : 
     861          13 :         ts_st->payload = av_mallocz(ts->pes_payload_size);
     862          13 :         if (!ts_st->payload) {
     863           0 :             ret = AVERROR(ENOMEM);
     864           0 :             goto fail;
     865             :         }
     866             : 
     867          13 :         program = av_find_program_from_stream(s, NULL, i);
     868          13 :         if (program) {
     869           0 :             for (j = 0; j < ts->nb_services; j++) {
     870           0 :                 if (ts->services[j]->program == program) {
     871           0 :                     service = ts->services[j];
     872           0 :                     break;
     873             :                 }
     874             :             }
     875             :         }
     876             : 
     877          13 :         ts_st->service = service;
     878             :         /* MPEG pid values < 16 are reserved. Applications which set st->id in
     879             :          * this range are assigned a calculated pid. */
     880          13 :         if (st->id < 16) {
     881          13 :             ts_st->pid = ts->start_pid + i;
     882           0 :         } else if (st->id < 0x1FFF) {
     883           0 :             ts_st->pid = st->id;
     884             :         } else {
     885           0 :             av_log(s, AV_LOG_ERROR,
     886             :                    "Invalid stream id %d, must be less than 8191\n", st->id);
     887           0 :             ret = AVERROR(EINVAL);
     888           0 :             goto fail;
     889             :         }
     890          13 :         if (ts_st->pid == service->pmt.pid) {
     891           0 :             av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
     892           0 :             ret = AVERROR(EINVAL);
     893           0 :             goto fail;
     894             :         }
     895          14 :         for (j = 0; j < i; j++) {
     896           1 :             if (pids[j] == ts_st->pid) {
     897           0 :                 av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
     898           0 :                 ret = AVERROR(EINVAL);
     899           0 :                 goto fail;
     900             :             }
     901             :         }
     902          13 :         pids[i]                = ts_st->pid;
     903          13 :         ts_st->payload_pts     = AV_NOPTS_VALUE;
     904          13 :         ts_st->payload_dts     = AV_NOPTS_VALUE;
     905          13 :         ts_st->first_pts_check = 1;
     906          13 :         ts_st->cc              = 15;
     907          13 :         ts_st->discontinuity   = ts->flags & MPEGTS_FLAG_DISCONT;
     908             :         /* update PCR pid by using the first video stream */
     909          19 :         if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
     910           6 :             service->pcr_pid == 0x1fff) {
     911           6 :             service->pcr_pid = ts_st->pid;
     912           6 :             pcr_st           = st;
     913             :         }
     914          13 :         if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
     915           0 :             st->codecpar->extradata_size > 0) {
     916             :             AVStream *ast;
     917           0 :             ts_st->amux = avformat_alloc_context();
     918           0 :             if (!ts_st->amux) {
     919           0 :                 ret = AVERROR(ENOMEM);
     920           0 :                 goto fail;
     921             :             }
     922           0 :             ts_st->amux->oformat =
     923           0 :                 av_guess_format((ts->flags & MPEGTS_FLAG_AAC_LATM) ? "latm" : "adts",
     924             :                                 NULL, NULL);
     925           0 :             if (!ts_st->amux->oformat) {
     926           0 :                 ret = AVERROR(EINVAL);
     927           0 :                 goto fail;
     928             :             }
     929           0 :             if (!(ast = avformat_new_stream(ts_st->amux, NULL))) {
     930           0 :                 ret = AVERROR(ENOMEM);
     931           0 :                 goto fail;
     932             :             }
     933           0 :             ret = avcodec_parameters_copy(ast->codecpar, st->codecpar);
     934           0 :             if (ret != 0)
     935           0 :                 goto fail;
     936           0 :             ast->time_base = st->time_base;
     937           0 :             ret = avformat_write_header(ts_st->amux, NULL);
     938           0 :             if (ret < 0)
     939           0 :                 goto fail;
     940             :         }
     941          13 :         if (st->codecpar->codec_id == AV_CODEC_ID_OPUS) {
     942           0 :             ts_st->opus_pending_trim_start = st->codecpar->initial_padding * 48000 / st->codecpar->sample_rate;
     943             :         }
     944             :     }
     945             : 
     946          12 :     av_freep(&pids);
     947             : 
     948             :     /* if no video stream, use the first stream as PCR */
     949          12 :     if (service->pcr_pid == 0x1fff && s->nb_streams > 0) {
     950           6 :         pcr_st           = s->streams[0];
     951           6 :         ts_st            = pcr_st->priv_data;
     952           6 :         service->pcr_pid = ts_st->pid;
     953             :     } else
     954           6 :         ts_st = pcr_st->priv_data;
     955             : 
     956          12 :     if (ts->mux_rate > 1) {
     957           0 :         service->pcr_packet_period = (int64_t)ts->mux_rate * ts->pcr_period /
     958             :                                      (TS_PACKET_SIZE * 8 * 1000);
     959           0 :         ts->sdt_packet_period      = (int64_t)ts->mux_rate * SDT_RETRANS_TIME /
     960             :                                      (TS_PACKET_SIZE * 8 * 1000);
     961           0 :         ts->pat_packet_period      = (int64_t)ts->mux_rate * PAT_RETRANS_TIME /
     962             :                                      (TS_PACKET_SIZE * 8 * 1000);
     963             : 
     964           0 :         if (ts->copyts < 1)
     965           0 :             ts->first_pcr = av_rescale(s->max_delay, PCR_TIME_BASE, AV_TIME_BASE);
     966             :     } else {
     967             :         /* Arbitrary values, PAT/PMT will also be written on video key frames */
     968          12 :         ts->sdt_packet_period = 200;
     969          12 :         ts->pat_packet_period = 40;
     970          12 :         if (pcr_st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
     971           6 :             int frame_size = av_get_audio_frame_duration2(pcr_st->codecpar, 0);
     972           6 :             if (!frame_size) {
     973           1 :                 av_log(s, AV_LOG_WARNING, "frame size not set\n");
     974           1 :                 service->pcr_packet_period =
     975           1 :                     pcr_st->codecpar->sample_rate / (10 * 512);
     976             :             } else {
     977           5 :                 service->pcr_packet_period =
     978           5 :                     pcr_st->codecpar->sample_rate / (10 * frame_size);
     979             :             }
     980             :         } else {
     981             :             // max delta PCR 0.1s
     982             :             // TODO: should be avg_frame_rate
     983           6 :             service->pcr_packet_period =
     984           6 :                 ts_st->user_tb.den / (10 * ts_st->user_tb.num);
     985             :         }
     986          12 :         if (!service->pcr_packet_period)
     987           0 :             service->pcr_packet_period = 1;
     988             :     }
     989             : 
     990          12 :     ts->last_pat_ts = AV_NOPTS_VALUE;
     991          12 :     ts->last_sdt_ts = AV_NOPTS_VALUE;
     992             :     // The user specified a period, use only it
     993          12 :     if (ts->pat_period < INT_MAX/2) {
     994           1 :         ts->pat_packet_period = INT_MAX;
     995             :     }
     996          12 :     if (ts->sdt_period < INT_MAX/2) {
     997           1 :         ts->sdt_packet_period = INT_MAX;
     998             :     }
     999             : 
    1000             :     // output a PCR as soon as possible
    1001          12 :     service->pcr_packet_count = service->pcr_packet_period;
    1002          12 :     ts->pat_packet_count      = ts->pat_packet_period - 1;
    1003          12 :     ts->sdt_packet_count      = ts->sdt_packet_period - 1;
    1004             : 
    1005          12 :     if (ts->mux_rate == 1)
    1006          12 :         av_log(s, AV_LOG_VERBOSE, "muxrate VBR, ");
    1007             :     else
    1008           0 :         av_log(s, AV_LOG_VERBOSE, "muxrate %d, ", ts->mux_rate);
    1009          12 :     av_log(s, AV_LOG_VERBOSE,
    1010             :            "pcr every %d pkts, sdt every %d, pat/pmt every %d pkts\n",
    1011             :            service->pcr_packet_period,
    1012             :            ts->sdt_packet_period, ts->pat_packet_period);
    1013             : 
    1014          12 :     if (ts->m2ts_mode == -1) {
    1015          12 :         if (av_match_ext(s->filename, "m2ts")) {
    1016           0 :             ts->m2ts_mode = 1;
    1017             :         } else {
    1018          12 :             ts->m2ts_mode = 0;
    1019             :         }
    1020             :     }
    1021             : 
    1022          12 :     return 0;
    1023             : 
    1024           0 : fail:
    1025           0 :     av_freep(&pids);
    1026           0 :     return ret;
    1027             : }
    1028             : 
    1029             : /* send SDT, PAT and PMT tables regularly */
    1030       28097 : static void retransmit_si_info(AVFormatContext *s, int force_pat, int64_t dts)
    1031             : {
    1032       28097 :     MpegTSWrite *ts = s->priv_data;
    1033             :     int i;
    1034             : 
    1035       28097 :     if (++ts->sdt_packet_count == ts->sdt_packet_period ||
    1036       27976 :         (dts != AV_NOPTS_VALUE && ts->last_sdt_ts == AV_NOPTS_VALUE) ||
    1037       27976 :         (dts != AV_NOPTS_VALUE && dts - ts->last_sdt_ts >= ts->sdt_period*90000.0)
    1038             :     ) {
    1039         121 :         ts->sdt_packet_count = 0;
    1040         121 :         if (dts != AV_NOPTS_VALUE)
    1041         121 :             ts->last_sdt_ts = FFMAX(dts, ts->last_sdt_ts);
    1042         121 :         mpegts_write_sdt(s);
    1043             :     }
    1044       28097 :     if (++ts->pat_packet_count == ts->pat_packet_period ||
    1045       27522 :         (dts != AV_NOPTS_VALUE && ts->last_pat_ts == AV_NOPTS_VALUE) ||
    1046       27522 :         (dts != AV_NOPTS_VALUE && dts - ts->last_pat_ts >= ts->pat_period*90000.0) ||
    1047             :         force_pat) {
    1048         578 :         ts->pat_packet_count = 0;
    1049         578 :         if (dts != AV_NOPTS_VALUE)
    1050         578 :             ts->last_pat_ts = FFMAX(dts, ts->last_pat_ts);
    1051         578 :         mpegts_write_pat(s);
    1052        1156 :         for (i = 0; i < ts->nb_services; i++)
    1053         578 :             mpegts_write_pmt(s, ts->services[i]);
    1054             :     }
    1055       28097 : }
    1056             : 
    1057        1440 : static int write_pcr_bits(uint8_t *buf, int64_t pcr)
    1058             : {
    1059        1440 :     int64_t pcr_low = pcr % 300, pcr_high = pcr / 300;
    1060             : 
    1061        1440 :     *buf++ = pcr_high >> 25;
    1062        1440 :     *buf++ = pcr_high >> 17;
    1063        1440 :     *buf++ = pcr_high >>  9;
    1064        1440 :     *buf++ = pcr_high >>  1;
    1065        1440 :     *buf++ = pcr_high <<  7 | pcr_low >> 8 | 0x7e;
    1066        1440 :     *buf++ = pcr_low;
    1067             : 
    1068        1440 :     return 6;
    1069             : }
    1070             : 
    1071             : /* Write a single null transport stream packet */
    1072           0 : static void mpegts_insert_null_packet(AVFormatContext *s)
    1073             : {
    1074             :     uint8_t *q;
    1075             :     uint8_t buf[TS_PACKET_SIZE];
    1076             : 
    1077           0 :     q    = buf;
    1078           0 :     *q++ = 0x47;
    1079           0 :     *q++ = 0x00 | 0x1f;
    1080           0 :     *q++ = 0xff;
    1081           0 :     *q++ = 0x10;
    1082           0 :     memset(q, 0x0FF, TS_PACKET_SIZE - (q - buf));
    1083           0 :     mpegts_prefix_m2ts_header(s);
    1084           0 :     avio_write(s->pb, buf, TS_PACKET_SIZE);
    1085           0 : }
    1086             : 
    1087             : /* Write a single transport stream packet with a PCR and no payload */
    1088           0 : static void mpegts_insert_pcr_only(AVFormatContext *s, AVStream *st)
    1089             : {
    1090           0 :     MpegTSWrite *ts = s->priv_data;
    1091           0 :     MpegTSWriteStream *ts_st = st->priv_data;
    1092             :     uint8_t *q;
    1093             :     uint8_t buf[TS_PACKET_SIZE];
    1094             : 
    1095           0 :     q    = buf;
    1096           0 :     *q++ = 0x47;
    1097           0 :     *q++ = ts_st->pid >> 8;
    1098           0 :     *q++ = ts_st->pid;
    1099           0 :     *q++ = 0x20 | ts_st->cc;   /* Adaptation only */
    1100             :     /* Continuity Count field does not increment (see 13818-1 section 2.4.3.3) */
    1101           0 :     *q++ = TS_PACKET_SIZE - 5; /* Adaptation Field Length */
    1102           0 :     *q++ = 0x10;               /* Adaptation flags: PCR present */
    1103           0 :     if (ts_st->discontinuity) {
    1104           0 :         q[-1] |= 0x80;
    1105           0 :         ts_st->discontinuity = 0;
    1106             :     }
    1107             : 
    1108             :     /* PCR coded into 6 bytes */
    1109           0 :     q += write_pcr_bits(q, get_pcr(ts, s->pb));
    1110             : 
    1111             :     /* stuffing bytes */
    1112           0 :     memset(q, 0xFF, TS_PACKET_SIZE - (q - buf));
    1113           0 :     mpegts_prefix_m2ts_header(s);
    1114           0 :     avio_write(s->pb, buf, TS_PACKET_SIZE);
    1115           0 : }
    1116             : 
    1117        1686 : static void write_pts(uint8_t *q, int fourbits, int64_t pts)
    1118             : {
    1119             :     int val;
    1120             : 
    1121        1686 :     val  = fourbits << 4 | (((pts >> 30) & 0x07) << 1) | 1;
    1122        1686 :     *q++ = val;
    1123        1686 :     val  = (((pts >> 15) & 0x7fff) << 1) | 1;
    1124        1686 :     *q++ = val >> 8;
    1125        1686 :     *q++ = val;
    1126        1686 :     val  = (((pts) & 0x7fff) << 1) | 1;
    1127        1686 :     *q++ = val >> 8;
    1128        1686 :     *q++ = val;
    1129        1686 : }
    1130             : 
    1131             : /* Set an adaptation field flag in an MPEG-TS packet*/
    1132        2863 : static void set_af_flag(uint8_t *pkt, int flag)
    1133             : {
    1134             :     // expect at least one flag to set
    1135        2863 :     av_assert0(flag);
    1136             : 
    1137        2863 :     if ((pkt[3] & 0x20) == 0) {
    1138             :         // no AF yet, set adaptation field flag
    1139        1443 :         pkt[3] |= 0x20;
    1140             :         // 1 byte length, no flags
    1141        1443 :         pkt[4] = 1;
    1142        1443 :         pkt[5] = 0;
    1143             :     }
    1144        2863 :     pkt[5] |= flag;
    1145        2863 : }
    1146             : 
    1147             : /* Extend the adaptation field by size bytes */
    1148        1440 : static void extend_af(uint8_t *pkt, int size)
    1149             : {
    1150             :     // expect already existing adaptation field
    1151        1440 :     av_assert0(pkt[3] & 0x20);
    1152        1440 :     pkt[4] += size;
    1153        1440 : }
    1154             : 
    1155             : /* Get a pointer to MPEG-TS payload (right after TS packet header) */
    1156        4303 : static uint8_t *get_ts_payload_start(uint8_t *pkt)
    1157             : {
    1158        4303 :     if (pkt[3] & 0x20)
    1159        4303 :         return pkt + 5 + pkt[4];
    1160             :     else
    1161           0 :         return pkt + 4;
    1162             : }
    1163             : 
    1164             : /* Add a PES header to the front of the payload, and segment into an integer
    1165             :  * number of TS packets. The final TS packet is padded using an oversized
    1166             :  * adaptation header to exactly fill the last TS packet.
    1167             :  * NOTE: 'payload' contains a complete PES payload. */
    1168        1565 : static void mpegts_write_pes(AVFormatContext *s, AVStream *st,
    1169             :                              const uint8_t *payload, int payload_size,
    1170             :                              int64_t pts, int64_t dts, int key, int stream_id)
    1171             : {
    1172        1565 :     MpegTSWriteStream *ts_st = st->priv_data;
    1173        1565 :     MpegTSWrite *ts = s->priv_data;
    1174             :     uint8_t buf[TS_PACKET_SIZE];
    1175             :     uint8_t *q;
    1176             :     int val, is_start, len, header_len, write_pcr, is_dvb_subtitle, is_dvb_teletext, flags;
    1177             :     int afc_len, stuffing_len;
    1178        1565 :     int64_t pcr = -1; /* avoid warning */
    1179        1565 :     int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE);
    1180        1565 :     int force_pat = st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && key && !ts_st->prev_payload_key;
    1181             : 
    1182        1565 :     av_assert0(ts_st->payload != buf || st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO);
    1183        1565 :     if (ts->flags & MPEGTS_FLAG_PAT_PMT_AT_FRAMES && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
    1184           0 :         force_pat = 1;
    1185             :     }
    1186             : 
    1187        1565 :     is_start = 1;
    1188       31227 :     while (payload_size > 0) {
    1189       28097 :         retransmit_si_info(s, force_pat, dts);
    1190       28097 :         force_pat = 0;
    1191             : 
    1192       28097 :         write_pcr = 0;
    1193       28097 :         if (ts_st->pid == ts_st->service->pcr_pid) {
    1194       28052 :             if (ts->mux_rate > 1 || is_start) // VBR pcr period is based on frames
    1195        1562 :                 ts_st->service->pcr_packet_count++;
    1196       56104 :             if (ts_st->service->pcr_packet_count >=
    1197       28052 :                 ts_st->service->pcr_packet_period) {
    1198         441 :                 ts_st->service->pcr_packet_count = 0;
    1199         441 :                 write_pcr = 1;
    1200             :             }
    1201             :         }
    1202             : 
    1203       28097 :         if (ts->mux_rate > 1 && dts != AV_NOPTS_VALUE &&
    1204           0 :             (dts - get_pcr(ts, s->pb) / 300) > delay) {
    1205             :             /* pcr insert gets priority over null packet insert */
    1206           0 :             if (write_pcr)
    1207           0 :                 mpegts_insert_pcr_only(s, st);
    1208             :             else
    1209           0 :                 mpegts_insert_null_packet(s);
    1210             :             /* recalculate write_pcr and possibly retransmit si_info */
    1211           0 :             continue;
    1212             :         }
    1213             : 
    1214             :         /* prepare packet header */
    1215       28097 :         q    = buf;
    1216       28097 :         *q++ = 0x47;
    1217       28097 :         val  = ts_st->pid >> 8;
    1218       28097 :         if (is_start)
    1219        1565 :             val |= 0x40;
    1220       28097 :         *q++      = val;
    1221       28097 :         *q++      = ts_st->pid;
    1222       28097 :         ts_st->cc = ts_st->cc + 1 & 0xf;
    1223       28097 :         *q++      = 0x10 | ts_st->cc; // payload indicator + CC
    1224       28097 :         if (ts_st->discontinuity) {
    1225           0 :             set_af_flag(buf, 0x80);
    1226           0 :             q = get_ts_payload_start(buf);
    1227           0 :             ts_st->discontinuity = 0;
    1228             :         }
    1229       28097 :         if (key && is_start && pts != AV_NOPTS_VALUE) {
    1230             :             // set Random Access for key frames
    1231        1423 :             if (ts_st->pid == ts_st->service->pcr_pid)
    1232        1420 :                 write_pcr = 1;
    1233        1423 :             set_af_flag(buf, 0x40);
    1234        1423 :             q = get_ts_payload_start(buf);
    1235             :         }
    1236       28097 :         if (write_pcr) {
    1237        1440 :             set_af_flag(buf, 0x10);
    1238        1440 :             q = get_ts_payload_start(buf);
    1239             :             // add 11, pcr references the last byte of program clock reference base
    1240        1440 :             if (ts->mux_rate > 1)
    1241           0 :                 pcr = get_pcr(ts, s->pb);
    1242             :             else
    1243        1440 :                 pcr = (dts - delay) * 300;
    1244        1440 :             if (dts != AV_NOPTS_VALUE && dts < pcr / 300)
    1245           0 :                 av_log(s, AV_LOG_WARNING, "dts < pcr, TS is invalid\n");
    1246        1440 :             extend_af(buf, write_pcr_bits(q, pcr));
    1247        1440 :             q = get_ts_payload_start(buf);
    1248             :         }
    1249       28097 :         if (is_start) {
    1250        1565 :             int pes_extension = 0;
    1251        1565 :             int pes_header_stuffing_bytes = 0;
    1252             :             /* write PES header */
    1253        1565 :             *q++ = 0x00;
    1254        1565 :             *q++ = 0x00;
    1255        1565 :             *q++ = 0x01;
    1256        1565 :             is_dvb_subtitle = 0;
    1257        1565 :             is_dvb_teletext = 0;
    1258        1565 :             if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
    1259         151 :                 if (st->codecpar->codec_id == AV_CODEC_ID_DIRAC)
    1260           0 :                     *q++ = 0xfd;
    1261             :                 else
    1262         151 :                     *q++ = 0xe0;
    1263        2828 :             } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
    1264        1673 :                        (st->codecpar->codec_id == AV_CODEC_ID_MP2 ||
    1265         518 :                         st->codecpar->codec_id == AV_CODEC_ID_MP3 ||
    1266         259 :                         st->codecpar->codec_id == AV_CODEC_ID_AAC)) {
    1267        1155 :                 *q++ = 0xc0;
    1268         518 :             } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
    1269         259 :                         st->codecpar->codec_id == AV_CODEC_ID_AC3 &&
    1270           0 :                         ts->m2ts_mode) {
    1271           0 :                 *q++ = 0xfd;
    1272         259 :             } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA &&
    1273           0 :                        st->codecpar->codec_id == AV_CODEC_ID_TIMED_ID3) {
    1274           0 :                 *q++ = 0xbd;
    1275         259 :             } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
    1276           0 :                 *q++ = stream_id != -1 ? stream_id : 0xfc;
    1277             : 
    1278           0 :                 if (stream_id == 0xbd) /* asynchronous KLV */
    1279           0 :                     pts = dts = AV_NOPTS_VALUE;
    1280             :             } else {
    1281         259 :                 *q++ = 0xbd;
    1282         259 :                 if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
    1283           0 :                     if (st->codecpar->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
    1284           0 :                         is_dvb_subtitle = 1;
    1285           0 :                     } else if (st->codecpar->codec_id == AV_CODEC_ID_DVB_TELETEXT) {
    1286           0 :                         is_dvb_teletext = 1;
    1287             :                     }
    1288             :                 }
    1289             :             }
    1290        1565 :             header_len = 0;
    1291        1565 :             flags      = 0;
    1292        1565 :             if (pts != AV_NOPTS_VALUE) {
    1293        1565 :                 header_len += 5;
    1294        1565 :                 flags      |= 0x80;
    1295             :             }
    1296        1565 :             if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
    1297         121 :                 header_len += 5;
    1298         121 :                 flags      |= 0x40;
    1299             :             }
    1300        1716 :             if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
    1301         151 :                 st->codecpar->codec_id == AV_CODEC_ID_DIRAC) {
    1302             :                 /* set PES_extension_flag */
    1303           0 :                 pes_extension = 1;
    1304           0 :                 flags        |= 0x01;
    1305             : 
    1306             :                 /* One byte for PES2 extension flag +
    1307             :                  * one byte for extension length +
    1308             :                  * one byte for extension id */
    1309           0 :                 header_len += 3;
    1310             :             }
    1311             :             /* for Blu-ray AC3 Audio the PES Extension flag should be as follow
    1312             :              * otherwise it will not play sound on blu-ray
    1313             :              */
    1314        1565 :             if (ts->m2ts_mode &&
    1315           0 :                 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
    1316           0 :                 st->codecpar->codec_id == AV_CODEC_ID_AC3) {
    1317             :                         /* set PES_extension_flag */
    1318           0 :                         pes_extension = 1;
    1319           0 :                         flags |= 0x01;
    1320           0 :                         header_len += 3;
    1321             :             }
    1322        1565 :             if (is_dvb_teletext) {
    1323           0 :                 pes_header_stuffing_bytes = 0x24 - header_len;
    1324           0 :                 header_len = 0x24;
    1325             :             }
    1326        1565 :             len = payload_size + header_len + 3;
    1327             :             /* 3 extra bytes should be added to DVB subtitle payload: 0x20 0x00 at the beginning and trailing 0xff */
    1328        1565 :             if (is_dvb_subtitle) {
    1329           0 :                 len += 3;
    1330           0 :                 payload_size++;
    1331             :             }
    1332        1565 :             if (len > 0xffff)
    1333           0 :                 len = 0;
    1334        1565 :             if (ts->omit_video_pes_length && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
    1335         151 :                 len = 0;
    1336             :             }
    1337        1565 :             *q++ = len >> 8;
    1338        1565 :             *q++ = len;
    1339        1565 :             val  = 0x80;
    1340             :             /* data alignment indicator is required for subtitle and data streams */
    1341        1565 :             if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE || st->codecpar->codec_type == AVMEDIA_TYPE_DATA)
    1342           0 :                 val |= 0x04;
    1343        1565 :             *q++ = val;
    1344        1565 :             *q++ = flags;
    1345        1565 :             *q++ = header_len;
    1346        1565 :             if (pts != AV_NOPTS_VALUE) {
    1347        1565 :                 write_pts(q, flags >> 6, pts);
    1348        1565 :                 q += 5;
    1349             :             }
    1350        1565 :             if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
    1351         121 :                 write_pts(q, 1, dts);
    1352         121 :                 q += 5;
    1353             :             }
    1354        1565 :             if (pes_extension && st->codecpar->codec_id == AV_CODEC_ID_DIRAC) {
    1355           0 :                 flags = 0x01;  /* set PES_extension_flag_2 */
    1356           0 :                 *q++  = flags;
    1357           0 :                 *q++  = 0x80 | 0x01; /* marker bit + extension length */
    1358             :                 /* Set the stream ID extension flag bit to 0 and
    1359             :                  * write the extended stream ID. */
    1360           0 :                 *q++ = 0x00 | 0x60;
    1361             :             }
    1362             :             /* For Blu-ray AC3 Audio Setting extended flags */
    1363        1565 :           if (ts->m2ts_mode &&
    1364           0 :               pes_extension &&
    1365           0 :               st->codecpar->codec_id == AV_CODEC_ID_AC3) {
    1366           0 :                       flags = 0x01; /* set PES_extension_flag_2 */
    1367           0 :                       *q++ = flags;
    1368           0 :                       *q++ = 0x80 | 0x01; /* marker bit + extension length */
    1369           0 :                       *q++ = 0x00 | 0x71; /* for AC3 Audio (specifically on blue-rays) */
    1370             :               }
    1371             : 
    1372             : 
    1373        1565 :             if (is_dvb_subtitle) {
    1374             :                 /* First two fields of DVB subtitles PES data:
    1375             :                  * data_identifier: for DVB subtitle streams shall be coded with the value 0x20
    1376             :                  * subtitle_stream_id: for DVB subtitle stream shall be identified by the value 0x00 */
    1377           0 :                 *q++ = 0x20;
    1378           0 :                 *q++ = 0x00;
    1379             :             }
    1380        1565 :             if (is_dvb_teletext) {
    1381           0 :                 memset(q, 0xff, pes_header_stuffing_bytes);
    1382           0 :                 q += pes_header_stuffing_bytes;
    1383             :             }
    1384        1565 :             is_start = 0;
    1385             :         }
    1386             :         /* header size */
    1387       28097 :         header_len = q - buf;
    1388             :         /* data len */
    1389       28097 :         len = TS_PACKET_SIZE - header_len;
    1390       28097 :         if (len > payload_size)
    1391        1564 :             len = payload_size;
    1392       28097 :         stuffing_len = TS_PACKET_SIZE - header_len - len;
    1393       28097 :         if (stuffing_len > 0) {
    1394             :             /* add stuffing with AFC */
    1395        1564 :             if (buf[3] & 0x20) {
    1396             :                 /* stuffing already present: increase its size */
    1397           0 :                 afc_len = buf[4] + 1;
    1398           0 :                 memmove(buf + 4 + afc_len + stuffing_len,
    1399           0 :                         buf + 4 + afc_len,
    1400           0 :                         header_len - (4 + afc_len));
    1401           0 :                 buf[4] += stuffing_len;
    1402           0 :                 memset(buf + 4 + afc_len, 0xff, stuffing_len);
    1403             :             } else {
    1404             :                 /* add stuffing */
    1405        1564 :                 memmove(buf + 4 + stuffing_len, buf + 4, header_len - 4);
    1406        1564 :                 buf[3] |= 0x20;
    1407        1564 :                 buf[4]  = stuffing_len - 1;
    1408        1564 :                 if (stuffing_len >= 2) {
    1409        1561 :                     buf[5] = 0x00;
    1410        1561 :                     memset(buf + 6, 0xff, stuffing_len - 2);
    1411             :                 }
    1412             :             }
    1413             :         }
    1414             : 
    1415       28097 :         if (is_dvb_subtitle && payload_size == len) {
    1416           0 :             memcpy(buf + TS_PACKET_SIZE - len, payload, len - 1);
    1417           0 :             buf[TS_PACKET_SIZE - 1] = 0xff; /* end_of_PES_data_field_marker: an 8-bit field with fixed contents 0xff for DVB subtitle */
    1418             :         } else {
    1419       28097 :             memcpy(buf + TS_PACKET_SIZE - len, payload, len);
    1420             :         }
    1421             : 
    1422       28097 :         payload      += len;
    1423       28097 :         payload_size -= len;
    1424       28097 :         mpegts_prefix_m2ts_header(s);
    1425       28097 :         avio_write(s->pb, buf, TS_PACKET_SIZE);
    1426             :     }
    1427        1565 :     ts_st->prev_payload_key = key;
    1428        1565 : }
    1429             : 
    1430         205 : int ff_check_h264_startcode(AVFormatContext *s, const AVStream *st, const AVPacket *pkt)
    1431             : {
    1432         205 :     if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001 && AV_RB24(pkt->data) != 0x000001) {
    1433           0 :         if (!st->nb_frames) {
    1434           0 :             av_log(s, AV_LOG_ERROR, "H.264 bitstream malformed, "
    1435             :                    "no startcode found, use the video bitstream filter 'h264_mp4toannexb' to fix it "
    1436             :                    "('-bsf:v h264_mp4toannexb' option with ffmpeg)\n");
    1437           0 :             return AVERROR_INVALIDDATA;
    1438             :         }
    1439           0 :         av_log(s, AV_LOG_WARNING, "H.264 bitstream error, startcode missing, size %d", pkt->size);
    1440           0 :         if (pkt->size)
    1441           0 :             av_log(s, AV_LOG_WARNING, " data %08"PRIX32, AV_RB32(pkt->data));
    1442           0 :         av_log(s, AV_LOG_WARNING, "\n");
    1443             :     }
    1444         205 :     return 0;
    1445             : }
    1446             : 
    1447           0 : static int check_hevc_startcode(AVFormatContext *s, const AVStream *st, const AVPacket *pkt)
    1448             : {
    1449           0 :     if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001 && AV_RB24(pkt->data) != 0x000001) {
    1450           0 :         if (!st->nb_frames) {
    1451           0 :             av_log(s, AV_LOG_ERROR, "HEVC bitstream malformed, no startcode found\n");
    1452           0 :             return AVERROR_PATCHWELCOME;
    1453             :         }
    1454           0 :         av_log(s, AV_LOG_WARNING, "HEVC bitstream error, startcode missing, size %d", pkt->size);
    1455           0 :         if (pkt->size)
    1456           0 :             av_log(s, AV_LOG_WARNING, " data %08"PRIX32, AV_RB32(pkt->data));
    1457           0 :         av_log(s, AV_LOG_WARNING, "\n");
    1458             :     }
    1459           0 :     return 0;
    1460             : }
    1461             : 
    1462             : /* Based on GStreamer's gst-plugins-base/ext/ogg/gstoggstream.c
    1463             :  * Released under the LGPL v2.1+, written by
    1464             :  * Vincent Penquerc'h <vincent.penquerch@collabora.co.uk>
    1465             :  */
    1466           0 : static int opus_get_packet_samples(AVFormatContext *s, AVPacket *pkt)
    1467             : {
    1468             :     static const int durations[32] = {
    1469             :       480, 960, 1920, 2880,       /* Silk NB */
    1470             :       480, 960, 1920, 2880,       /* Silk MB */
    1471             :       480, 960, 1920, 2880,       /* Silk WB */
    1472             :       480, 960,                   /* Hybrid SWB */
    1473             :       480, 960,                   /* Hybrid FB */
    1474             :       120, 240, 480, 960,         /* CELT NB */
    1475             :       120, 240, 480, 960,         /* CELT NB */
    1476             :       120, 240, 480, 960,         /* CELT NB */
    1477             :       120, 240, 480, 960,         /* CELT NB */
    1478             :     };
    1479             :     int toc, frame_duration, nframes, duration;
    1480             : 
    1481           0 :     if (pkt->size < 1)
    1482           0 :         return 0;
    1483             : 
    1484           0 :     toc = pkt->data[0];
    1485             : 
    1486           0 :     frame_duration = durations[toc >> 3];
    1487           0 :     switch (toc & 3) {
    1488           0 :     case 0:
    1489           0 :         nframes = 1;
    1490           0 :         break;
    1491           0 :     case 1:
    1492           0 :         nframes = 2;
    1493           0 :         break;
    1494           0 :     case 2:
    1495           0 :         nframes = 2;
    1496           0 :         break;
    1497           0 :     case 3:
    1498           0 :         if (pkt->size < 2)
    1499           0 :             return 0;
    1500           0 :         nframes = pkt->data[1] & 63;
    1501           0 :         break;
    1502             :     }
    1503             : 
    1504           0 :     duration = nframes * frame_duration;
    1505           0 :     if (duration > 5760) {
    1506           0 :         av_log(s, AV_LOG_WARNING,
    1507             :                "Opus packet duration > 120 ms, invalid");
    1508           0 :         return 0;
    1509             :     }
    1510             : 
    1511           0 :     return duration;
    1512             : }
    1513             : 
    1514        2748 : static int mpegts_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
    1515             : {
    1516        2748 :     AVStream *st = s->streams[pkt->stream_index];
    1517        2748 :     int size = pkt->size;
    1518        2748 :     uint8_t *buf = pkt->data;
    1519        2748 :     uint8_t *data = NULL;
    1520        2748 :     MpegTSWrite *ts = s->priv_data;
    1521        2748 :     MpegTSWriteStream *ts_st = st->priv_data;
    1522        2748 :     const int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE) * 2;
    1523        2748 :     int64_t dts = pkt->dts, pts = pkt->pts;
    1524        2748 :     int opus_samples = 0;
    1525             :     int side_data_size;
    1526        2748 :     char *side_data = NULL;
    1527        2748 :     int stream_id = -1;
    1528             : 
    1529        2748 :     side_data = av_packet_get_side_data(pkt,
    1530             :                                         AV_PKT_DATA_MPEGTS_STREAM_ID,
    1531             :                                         &side_data_size);
    1532        2748 :     if (side_data)
    1533           0 :         stream_id = side_data[0];
    1534             : 
    1535        2748 :     if (ts->reemit_pat_pmt) {
    1536           0 :         av_log(s, AV_LOG_WARNING,
    1537             :                "resend_headers option is deprecated, use -mpegts_flags resend_headers\n");
    1538           0 :         ts->reemit_pat_pmt = 0;
    1539           0 :         ts->flags         |= MPEGTS_FLAG_REEMIT_PAT_PMT;
    1540             :     }
    1541             : 
    1542        2748 :     if (ts->flags & MPEGTS_FLAG_REEMIT_PAT_PMT) {
    1543           8 :         ts->pat_packet_count = ts->pat_packet_period - 1;
    1544           8 :         ts->sdt_packet_count = ts->sdt_packet_period - 1;
    1545           8 :         ts->flags           &= ~MPEGTS_FLAG_REEMIT_PAT_PMT;
    1546             :     }
    1547             : 
    1548        2748 :     if (ts->copyts < 1) {
    1549        2748 :         if (pts != AV_NOPTS_VALUE)
    1550        2748 :             pts += delay;
    1551        2748 :         if (dts != AV_NOPTS_VALUE)
    1552        2748 :             dts += delay;
    1553             :     }
    1554             : 
    1555        2748 :     if (ts_st->first_pts_check && pts == AV_NOPTS_VALUE) {
    1556           0 :         av_log(s, AV_LOG_ERROR, "first pts value must be set\n");
    1557           0 :         return AVERROR_INVALIDDATA;
    1558             :     }
    1559        2748 :     ts_st->first_pts_check = 0;
    1560             : 
    1561        2748 :     if (st->codecpar->codec_id == AV_CODEC_ID_H264) {
    1562         126 :         const uint8_t *p = buf, *buf_end = p + size;
    1563         126 :         uint32_t state = -1;
    1564         126 :         int extradd = (pkt->flags & AV_PKT_FLAG_KEY) ? st->codecpar->extradata_size : 0;
    1565         126 :         int ret = ff_check_h264_startcode(s, st, pkt);
    1566         126 :         if (ret < 0)
    1567           0 :             return ret;
    1568             : 
    1569         126 :         if (extradd && AV_RB24(st->codecpar->extradata) > 1)
    1570           6 :             extradd = 0;
    1571             : 
    1572             :         do {
    1573         127 :             p = avpriv_find_start_code(p, buf_end, &state);
    1574         127 :             av_log(s, AV_LOG_TRACE, "nal %"PRId32"\n", state & 0x1f);
    1575         127 :             if ((state & 0x1f) == 7)
    1576           0 :                 extradd = 0;
    1577         128 :         } while (p < buf_end && (state & 0x1f) != 9 &&
    1578         129 :                  (state & 0x1f) != 5 && (state & 0x1f) != 1);
    1579             : 
    1580         126 :         if ((state & 0x1f) != 5)
    1581         126 :             extradd = 0;
    1582         126 :         if ((state & 0x1f) != 9) { // AUD NAL
    1583           0 :             data = av_malloc(pkt->size + 6 + extradd);
    1584           0 :             if (!data)
    1585           0 :                 return AVERROR(ENOMEM);
    1586           0 :             memcpy(data + 6, st->codecpar->extradata, extradd);
    1587           0 :             memcpy(data + 6 + extradd, pkt->data, pkt->size);
    1588           0 :             AV_WB32(data, 0x00000001);
    1589           0 :             data[4] = 0x09;
    1590           0 :             data[5] = 0xf0; // any slice type (0xe) + rbsp stop one bit
    1591           0 :             buf     = data;
    1592           0 :             size    = pkt->size + 6 + extradd;
    1593             :         }
    1594        2622 :     } else if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
    1595           0 :         if (pkt->size < 2) {
    1596           0 :             av_log(s, AV_LOG_ERROR, "AAC packet too short\n");
    1597           0 :             return AVERROR_INVALIDDATA;
    1598             :         }
    1599           0 :         if ((AV_RB16(pkt->data) & 0xfff0) != 0xfff0) {
    1600             :             int ret;
    1601             :             AVPacket pkt2;
    1602             : 
    1603           0 :             if (!ts_st->amux) {
    1604           0 :                 av_log(s, AV_LOG_ERROR, "AAC bitstream not in ADTS format "
    1605             :                                         "and extradata missing\n");
    1606             :             } else {
    1607           0 :             av_init_packet(&pkt2);
    1608           0 :             pkt2.data = pkt->data;
    1609           0 :             pkt2.size = pkt->size;
    1610           0 :             av_assert0(pkt->dts != AV_NOPTS_VALUE);
    1611           0 :             pkt2.dts = av_rescale_q(pkt->dts, st->time_base, ts_st->amux->streams[0]->time_base);
    1612             : 
    1613           0 :             ret = avio_open_dyn_buf(&ts_st->amux->pb);
    1614           0 :             if (ret < 0)
    1615           0 :                 return AVERROR(ENOMEM);
    1616             : 
    1617           0 :             ret = av_write_frame(ts_st->amux, &pkt2);
    1618           0 :             if (ret < 0) {
    1619           0 :                 ffio_free_dyn_buf(&ts_st->amux->pb);
    1620           0 :                 return ret;
    1621             :             }
    1622           0 :             size            = avio_close_dyn_buf(ts_st->amux->pb, &data);
    1623           0 :             ts_st->amux->pb = NULL;
    1624           0 :             buf             = data;
    1625             :             }
    1626             :         }
    1627        2622 :     } else if (st->codecpar->codec_id == AV_CODEC_ID_HEVC) {
    1628           0 :         const uint8_t *p = buf, *buf_end = p + size;
    1629           0 :         uint32_t state = -1;
    1630           0 :         int extradd = (pkt->flags & AV_PKT_FLAG_KEY) ? st->codecpar->extradata_size : 0;
    1631           0 :         int ret = check_hevc_startcode(s, st, pkt);
    1632           0 :         if (ret < 0)
    1633           0 :             return ret;
    1634             : 
    1635           0 :         if (extradd && AV_RB24(st->codecpar->extradata) > 1)
    1636           0 :             extradd = 0;
    1637             : 
    1638             :         do {
    1639           0 :             p = avpriv_find_start_code(p, buf_end, &state);
    1640           0 :             av_log(s, AV_LOG_TRACE, "nal %"PRId32"\n", (state & 0x7e)>>1);
    1641           0 :             if ((state & 0x7e) == 2*32)
    1642           0 :                 extradd = 0;
    1643           0 :         } while (p < buf_end && (state & 0x7e) != 2*35 &&
    1644           0 :                  (state & 0x7e) >= 2*32);
    1645             : 
    1646           0 :         if ((state & 0x7e) < 2*16 && (state & 0x7e) >= 2*24)
    1647           0 :             extradd = 0;
    1648           0 :         if ((state & 0x7e) != 2*35) { // AUD NAL
    1649           0 :             data = av_malloc(pkt->size + 7 + extradd);
    1650           0 :             if (!data)
    1651           0 :                 return AVERROR(ENOMEM);
    1652           0 :             memcpy(data + 7, st->codecpar->extradata, extradd);
    1653           0 :             memcpy(data + 7 + extradd, pkt->data, pkt->size);
    1654           0 :             AV_WB32(data, 0x00000001);
    1655           0 :             data[4] = 2*35;
    1656           0 :             data[5] = 1;
    1657           0 :             data[6] = 0x50; // any slice type (0x4) + rbsp stop one bit
    1658           0 :             buf     = data;
    1659           0 :             size    = pkt->size + 7 + extradd;
    1660             :         }
    1661        2622 :     } else if (st->codecpar->codec_id == AV_CODEC_ID_OPUS) {
    1662           0 :         if (pkt->size < 2) {
    1663           0 :             av_log(s, AV_LOG_ERROR, "Opus packet too short\n");
    1664           0 :             return AVERROR_INVALIDDATA;
    1665             :         }
    1666             : 
    1667             :         /* Add Opus control header */
    1668           0 :         if ((AV_RB16(pkt->data) >> 5) != 0x3ff) {
    1669             :             uint8_t *side_data;
    1670             :             int side_data_size;
    1671             :             int i, n;
    1672             :             int ctrl_header_size;
    1673           0 :             int trim_start = 0, trim_end = 0;
    1674             : 
    1675           0 :             opus_samples = opus_get_packet_samples(s, pkt);
    1676             : 
    1677           0 :             side_data = av_packet_get_side_data(pkt,
    1678             :                                                 AV_PKT_DATA_SKIP_SAMPLES,
    1679             :                                                 &side_data_size);
    1680             : 
    1681           0 :             if (side_data && side_data_size >= 10) {
    1682           0 :                 trim_end = AV_RL32(side_data + 4) * 48000 / st->codecpar->sample_rate;
    1683             :             }
    1684             : 
    1685           0 :             ctrl_header_size = pkt->size + 2 + pkt->size / 255 + 1;
    1686           0 :             if (ts_st->opus_pending_trim_start)
    1687           0 :               ctrl_header_size += 2;
    1688           0 :             if (trim_end)
    1689           0 :               ctrl_header_size += 2;
    1690             : 
    1691           0 :             data = av_malloc(ctrl_header_size);
    1692           0 :             if (!data)
    1693           0 :                 return AVERROR(ENOMEM);
    1694             : 
    1695           0 :             data[0] = 0x7f;
    1696           0 :             data[1] = 0xe0;
    1697           0 :             if (ts_st->opus_pending_trim_start)
    1698           0 :                 data[1] |= 0x10;
    1699           0 :             if (trim_end)
    1700           0 :                 data[1] |= 0x08;
    1701             : 
    1702           0 :             n = pkt->size;
    1703           0 :             i = 2;
    1704             :             do {
    1705           0 :                 data[i] = FFMIN(n, 255);
    1706           0 :                 n -= 255;
    1707           0 :                 i++;
    1708           0 :             } while (n >= 0);
    1709             : 
    1710           0 :             av_assert0(2 + pkt->size / 255 + 1 == i);
    1711             : 
    1712           0 :             if (ts_st->opus_pending_trim_start) {
    1713           0 :                 trim_start = FFMIN(ts_st->opus_pending_trim_start, opus_samples);
    1714           0 :                 AV_WB16(data + i, trim_start);
    1715           0 :                 i += 2;
    1716           0 :                 ts_st->opus_pending_trim_start -= trim_start;
    1717             :             }
    1718           0 :             if (trim_end) {
    1719           0 :                 trim_end = FFMIN(trim_end, opus_samples - trim_start);
    1720           0 :                 AV_WB16(data + i, trim_end);
    1721           0 :                 i += 2;
    1722             :             }
    1723             : 
    1724           0 :             memcpy(data + i, pkt->data, pkt->size);
    1725           0 :             buf     = data;
    1726           0 :             size    = ctrl_header_size;
    1727             :         } else {
    1728             :             /* TODO: Can we get TS formatted data here? If so we will
    1729             :              * need to count the samples of that too! */
    1730           0 :             av_log(s, AV_LOG_WARNING, "Got MPEG-TS formatted Opus data, unhandled");
    1731             :         }
    1732             :     }
    1733             : 
    1734        2748 :     if (pkt->dts != AV_NOPTS_VALUE) {
    1735             :         int i;
    1736        5560 :         for(i=0; i<s->nb_streams; i++) {
    1737        2812 :             AVStream *st2 = s->streams[i];
    1738        2812 :             MpegTSWriteStream *ts_st2 = st2->priv_data;
    1739        2812 :             if (   ts_st2->payload_size
    1740        2355 :                && (ts_st2->payload_dts == AV_NOPTS_VALUE || dts - ts_st2->payload_dts > delay/2)) {
    1741           0 :                 mpegts_write_pes(s, st2, ts_st2->payload, ts_st2->payload_size,
    1742             :                                  ts_st2->payload_pts, ts_st2->payload_dts,
    1743           0 :                                  ts_st2->payload_flags & AV_PKT_FLAG_KEY, stream_id);
    1744           0 :                 ts_st2->payload_size = 0;
    1745             :             }
    1746             :         }
    1747             :     }
    1748             : 
    1749        2748 :     if (ts_st->payload_size && (ts_st->payload_size + size > ts->pes_payload_size ||
    1750        2366 :         (dts != AV_NOPTS_VALUE && ts_st->payload_dts != AV_NOPTS_VALUE &&
    1751        1183 :          av_compare_ts(dts - ts_st->payload_dts, st->time_base,
    1752        2366 :                        s->max_delay, AV_TIME_BASE_Q) >= 0) ||
    1753        1183 :         ts_st->opus_queued_samples + opus_samples >= 5760 /* 120ms */)) {
    1754        1148 :         mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_size,
    1755             :                          ts_st->payload_pts, ts_st->payload_dts,
    1756        1148 :                          ts_st->payload_flags & AV_PKT_FLAG_KEY, stream_id);
    1757        1148 :         ts_st->payload_size = 0;
    1758        1148 :         ts_st->opus_queued_samples = 0;
    1759             :     }
    1760             : 
    1761        2748 :     if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO || size > ts->pes_payload_size) {
    1762         409 :         av_assert0(!ts_st->payload_size);
    1763             :         // for video and subtitle, write a single pes packet
    1764         409 :         mpegts_write_pes(s, st, buf, size, pts, dts,
    1765         409 :                          pkt->flags & AV_PKT_FLAG_KEY, stream_id);
    1766         409 :         ts_st->opus_queued_samples = 0;
    1767         409 :         av_free(data);
    1768         409 :         return 0;
    1769             :     }
    1770             : 
    1771        2339 :     if (!ts_st->payload_size) {
    1772        1156 :         ts_st->payload_pts   = pts;
    1773        1156 :         ts_st->payload_dts   = dts;
    1774        1156 :         ts_st->payload_flags = pkt->flags;
    1775             :     }
    1776             : 
    1777        2339 :     memcpy(ts_st->payload + ts_st->payload_size, buf, size);
    1778        2339 :     ts_st->payload_size += size;
    1779        2339 :     ts_st->opus_queued_samples += opus_samples;
    1780             : 
    1781        2339 :     av_free(data);
    1782             : 
    1783        2339 :     return 0;
    1784             : }
    1785             : 
    1786          22 : static void mpegts_write_flush(AVFormatContext *s)
    1787             : {
    1788             :     int i;
    1789             : 
    1790             :     /* flush current packets */
    1791          45 :     for (i = 0; i < s->nb_streams; i++) {
    1792          23 :         AVStream *st = s->streams[i];
    1793          23 :         MpegTSWriteStream *ts_st = st->priv_data;
    1794          23 :         if (ts_st->payload_size > 0) {
    1795           8 :             mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_size,
    1796             :                              ts_st->payload_pts, ts_st->payload_dts,
    1797           8 :                              ts_st->payload_flags & AV_PKT_FLAG_KEY, -1);
    1798           8 :             ts_st->payload_size = 0;
    1799           8 :             ts_st->opus_queued_samples = 0;
    1800             :         }
    1801             :     }
    1802          22 : }
    1803             : 
    1804        2758 : static int mpegts_write_packet(AVFormatContext *s, AVPacket *pkt)
    1805             : {
    1806        2758 :     if (!pkt) {
    1807          10 :         mpegts_write_flush(s);
    1808          10 :         return 1;
    1809             :     } else {
    1810        2748 :         return mpegts_write_packet_internal(s, pkt);
    1811             :     }
    1812             : }
    1813             : 
    1814          12 : static int mpegts_write_end(AVFormatContext *s)
    1815             : {
    1816          12 :     if (s->pb)
    1817          12 :         mpegts_write_flush(s);
    1818             : 
    1819          12 :     return 0;
    1820             : }
    1821             : 
    1822          12 : static void mpegts_deinit(AVFormatContext *s)
    1823             : {
    1824          12 :     MpegTSWrite *ts = s->priv_data;
    1825             :     MpegTSService *service;
    1826             :     int i;
    1827             : 
    1828          25 :     for (i = 0; i < s->nb_streams; i++) {
    1829          13 :         AVStream *st = s->streams[i];
    1830          13 :         MpegTSWriteStream *ts_st = st->priv_data;
    1831          13 :         if (ts_st) {
    1832          13 :             av_freep(&ts_st->payload);
    1833          13 :             if (ts_st->amux) {
    1834           0 :                 avformat_free_context(ts_st->amux);
    1835           0 :                 ts_st->amux = NULL;
    1836             :             }
    1837             :         }
    1838             :     }
    1839             : 
    1840          24 :     for (i = 0; i < ts->nb_services; i++) {
    1841          12 :         service = ts->services[i];
    1842          12 :         av_freep(&service->provider_name);
    1843          12 :         av_freep(&service->name);
    1844          12 :         av_freep(&service);
    1845             :     }
    1846          12 :     av_freep(&ts->services);
    1847          12 : }
    1848             : 
    1849           7 : static int mpegts_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
    1850             : {
    1851           7 :     int ret = 1;
    1852           7 :     AVStream *st = s->streams[pkt->stream_index];
    1853             : 
    1854           7 :     if (st->codecpar->codec_id == AV_CODEC_ID_H264) {
    1855           2 :         if (pkt->size >= 5 && AV_RB32(pkt->data) != 0x0000001 &&
    1856           1 :                              (AV_RB24(pkt->data) != 0x000001 ||
    1857           0 :                               (st->codecpar->extradata_size > 0 &&
    1858           0 :                                st->codecpar->extradata[0] == 1)))
    1859           1 :             ret = ff_stream_add_bitstream_filter(st, "h264_mp4toannexb", NULL);
    1860           6 :     } else if (st->codecpar->codec_id == AV_CODEC_ID_HEVC) {
    1861           0 :         if (pkt->size >= 5 && AV_RB32(pkt->data) != 0x0000001 &&
    1862           0 :                              (AV_RB24(pkt->data) != 0x000001 ||
    1863           0 :                               (st->codecpar->extradata_size > 0 &&
    1864           0 :                                st->codecpar->extradata[0] == 1)))
    1865           0 :             ret = ff_stream_add_bitstream_filter(st, "hevc_mp4toannexb", NULL);
    1866             :     }
    1867             : 
    1868           7 :     return ret;
    1869             : }
    1870             : 
    1871             : static const AVOption options[] = {
    1872             :     { "mpegts_transport_stream_id", "Set transport_stream_id field.",
    1873             :       offsetof(MpegTSWrite, transport_stream_id), AV_OPT_TYPE_INT,
    1874             :       { .i64 = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM },
    1875             :     { "mpegts_original_network_id", "Set original_network_id field.",
    1876             :       offsetof(MpegTSWrite, original_network_id), AV_OPT_TYPE_INT,
    1877             :       { .i64 = DVB_PRIVATE_NETWORK_START }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM },
    1878             :     { "mpegts_service_id", "Set service_id field.",
    1879             :       offsetof(MpegTSWrite, service_id), AV_OPT_TYPE_INT,
    1880             :       { .i64 = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM },
    1881             :     { "mpegts_service_type", "Set service_type field.",
    1882             :       offsetof(MpegTSWrite, service_type), AV_OPT_TYPE_INT,
    1883             :       { .i64 = 0x01 }, 0x01, 0xff, AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
    1884             :     { "digital_tv", "Digital Television.",
    1885             :       0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_DIGITAL_TV }, 0x01, 0xff,
    1886             :       AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
    1887             :     { "digital_radio", "Digital Radio.",
    1888             :       0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_DIGITAL_RADIO }, 0x01, 0xff,
    1889             :       AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
    1890             :     { "teletext", "Teletext.",
    1891             :       0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_TELETEXT }, 0x01, 0xff,
    1892             :       AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
    1893             :     { "advanced_codec_digital_radio", "Advanced Codec Digital Radio.",
    1894             :       0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_ADVANCED_CODEC_DIGITAL_RADIO }, 0x01, 0xff,
    1895             :       AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
    1896             :     { "mpeg2_digital_hdtv", "MPEG2 Digital HDTV.",
    1897             :       0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_MPEG2_DIGITAL_HDTV }, 0x01, 0xff,
    1898             :       AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
    1899             :     { "advanced_codec_digital_sdtv", "Advanced Codec Digital SDTV.",
    1900             :       0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_ADVANCED_CODEC_DIGITAL_SDTV }, 0x01, 0xff,
    1901             :       AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
    1902             :     { "advanced_codec_digital_hdtv", "Advanced Codec Digital HDTV.",
    1903             :       0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_ADVANCED_CODEC_DIGITAL_HDTV }, 0x01, 0xff,
    1904             :       AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
    1905             :     { "hevc_digital_hdtv", "HEVC Digital Television Service.",
    1906             :       0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_HEVC_DIGITAL_HDTV }, 0x01, 0xff,
    1907             :       AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
    1908             :     { "mpegts_pmt_start_pid", "Set the first pid of the PMT.",
    1909             :       offsetof(MpegTSWrite, pmt_start_pid), AV_OPT_TYPE_INT,
    1910             :       { .i64 = 0x1000 }, 0x0010, 0x1f00, AV_OPT_FLAG_ENCODING_PARAM },
    1911             :     { "mpegts_start_pid", "Set the first pid.",
    1912             :       offsetof(MpegTSWrite, start_pid), AV_OPT_TYPE_INT,
    1913             :       { .i64 = 0x0100 }, 0x0010, 0x0f00, AV_OPT_FLAG_ENCODING_PARAM },
    1914             :     { "mpegts_m2ts_mode", "Enable m2ts mode.",
    1915             :       offsetof(MpegTSWrite, m2ts_mode), AV_OPT_TYPE_BOOL,
    1916             :       { .i64 = -1 }, -1, 1, AV_OPT_FLAG_ENCODING_PARAM },
    1917             :     { "muxrate", NULL,
    1918             :       offsetof(MpegTSWrite, mux_rate), AV_OPT_TYPE_INT,
    1919             :       { .i64 = 1 }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
    1920             :     { "pes_payload_size", "Minimum PES packet payload in bytes",
    1921             :       offsetof(MpegTSWrite, pes_payload_size), AV_OPT_TYPE_INT,
    1922             :       { .i64 = DEFAULT_PES_PAYLOAD_SIZE }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
    1923             :     { "mpegts_flags", "MPEG-TS muxing flags",
    1924             :       offsetof(MpegTSWrite, flags), AV_OPT_TYPE_FLAGS, { .i64 = 0 }, 0, INT_MAX,
    1925             :       AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags" },
    1926             :     { "resend_headers", "Reemit PAT/PMT before writing the next packet",
    1927             :       0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_FLAG_REEMIT_PAT_PMT }, 0, INT_MAX,
    1928             :       AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags" },
    1929             :     { "latm", "Use LATM packetization for AAC",
    1930             :       0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_FLAG_AAC_LATM }, 0, INT_MAX,
    1931             :       AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags" },
    1932             :     { "pat_pmt_at_frames", "Reemit PAT and PMT at each video frame",
    1933             :       0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_FLAG_PAT_PMT_AT_FRAMES}, 0, INT_MAX,
    1934             :       AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags" },
    1935             :     { "system_b", "Conform to System B (DVB) instead of System A (ATSC)",
    1936             :       0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_FLAG_SYSTEM_B }, 0, INT_MAX,
    1937             :       AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags" },
    1938             :     { "initial_discontinuity", "Mark initial packets as discontinuous",
    1939             :       0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_FLAG_DISCONT }, 0, INT_MAX,
    1940             :       AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags" },
    1941             :     // backward compatibility
    1942             :     { "resend_headers", "Reemit PAT/PMT before writing the next packet",
    1943             :       offsetof(MpegTSWrite, reemit_pat_pmt), AV_OPT_TYPE_INT,
    1944             :       { .i64 = 0 }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
    1945             :     { "mpegts_copyts", "don't offset dts/pts",
    1946             :       offsetof(MpegTSWrite, copyts), AV_OPT_TYPE_BOOL,
    1947             :       { .i64 = -1 }, -1, 1, AV_OPT_FLAG_ENCODING_PARAM },
    1948             :     { "tables_version", "set PAT, PMT and SDT version",
    1949             :       offsetof(MpegTSWrite, tables_version), AV_OPT_TYPE_INT,
    1950             :       { .i64 = 0 }, 0, 31, AV_OPT_FLAG_ENCODING_PARAM },
    1951             :     { "omit_video_pes_length", "Omit the PES packet length for video packets",
    1952             :       offsetof(MpegTSWrite, omit_video_pes_length), AV_OPT_TYPE_BOOL,
    1953             :       { .i64 = 1 }, 0, 1, AV_OPT_FLAG_ENCODING_PARAM },
    1954             :     { "pcr_period", "PCR retransmission time in milliseconds",
    1955             :       offsetof(MpegTSWrite, pcr_period), AV_OPT_TYPE_INT,
    1956             :       { .i64 = PCR_RETRANS_TIME }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
    1957             :     { "pat_period", "PAT/PMT retransmission time limit in seconds",
    1958             :       offsetof(MpegTSWrite, pat_period), AV_OPT_TYPE_DOUBLE,
    1959             :       { .dbl = INT_MAX }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
    1960             :     { "sdt_period", "SDT retransmission time limit in seconds",
    1961             :       offsetof(MpegTSWrite, sdt_period), AV_OPT_TYPE_DOUBLE,
    1962             :       { .dbl = INT_MAX }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
    1963             :     { NULL },
    1964             : };
    1965             : 
    1966             : static const AVClass mpegts_muxer_class = {
    1967             :     .class_name = "MPEGTS muxer",
    1968             :     .item_name  = av_default_item_name,
    1969             :     .option     = options,
    1970             :     .version    = LIBAVUTIL_VERSION_INT,
    1971             : };
    1972             : 
    1973             : AVOutputFormat ff_mpegts_muxer = {
    1974             :     .name           = "mpegts",
    1975             :     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
    1976             :     .mime_type      = "video/MP2T",
    1977             :     .extensions     = "ts,m2t,m2ts,mts",
    1978             :     .priv_data_size = sizeof(MpegTSWrite),
    1979             :     .audio_codec    = AV_CODEC_ID_MP2,
    1980             :     .video_codec    = AV_CODEC_ID_MPEG2VIDEO,
    1981             :     .init           = mpegts_init,
    1982             :     .write_packet   = mpegts_write_packet,
    1983             :     .write_trailer  = mpegts_write_end,
    1984             :     .deinit         = mpegts_deinit,
    1985             :     .check_bitstream = mpegts_check_bitstream,
    1986             :     .flags          = AVFMT_ALLOW_FLUSH | AVFMT_VARIABLE_FPS,
    1987             :     .priv_class     = &mpegts_muxer_class,
    1988             : };

Generated by: LCOV version 1.13