]> git.sesse.net Git - ffmpeg/blob - libavformat/mpegtsenc.c
Merge commit '5cbae5651d7c1ce9b0691dfbf2d474cb2b0ebb9a'
[ffmpeg] / libavformat / mpegtsenc.c
1 /*
2  * MPEG2 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 "internal.h"
34 #include "mpegts.h"
35
36 #define PCR_TIME_BASE 27000000
37
38 /* write DVB SI sections */
39
40 /*********************************************/
41 /* mpegts section writer */
42
43 typedef struct MpegTSSection {
44     int pid;
45     int cc;
46     void (*write_packet)(struct MpegTSSection *s, const uint8_t *packet);
47     void *opaque;
48 } MpegTSSection;
49
50 typedef struct MpegTSService {
51     MpegTSSection pmt; /* MPEG2 pmt table context */
52     int sid;           /* service ID */
53     char *name;
54     char *provider_name;
55     int pcr_pid;
56     int pcr_packet_count;
57     int pcr_packet_period;
58 } MpegTSService;
59
60 // service_type values as defined in ETSI 300 468
61 enum {
62     MPEGTS_SERVICE_TYPE_DIGITAL_TV                   = 0x01,
63     MPEGTS_SERVICE_TYPE_DIGITAL_RADIO                = 0x02,
64     MPEGTS_SERVICE_TYPE_TELETEXT                     = 0x03,
65     MPEGTS_SERVICE_TYPE_ADVANCED_CODEC_DIGITAL_RADIO = 0x0A,
66     MPEGTS_SERVICE_TYPE_MPEG2_DIGITAL_HDTV           = 0x11,
67     MPEGTS_SERVICE_TYPE_ADVANCED_CODEC_DIGITAL_SDTV  = 0x16,
68     MPEGTS_SERVICE_TYPE_ADVANCED_CODEC_DIGITAL_HDTV  = 0x19
69 };
70 typedef struct MpegTSWrite {
71     const AVClass *av_class;
72     MpegTSSection pat; /* MPEG2 pat table */
73     MpegTSSection sdt; /* MPEG2 sdt table context */
74     MpegTSService **services;
75     int sdt_packet_count;
76     int sdt_packet_period;
77     int pat_packet_count;
78     int pat_packet_period;
79     int nb_services;
80     int onid;
81     int tsid;
82     int64_t first_pcr;
83     int mux_rate; ///< set to 1 when VBR
84     int pes_payload_size;
85
86     int transport_stream_id;
87     int original_network_id;
88     int service_id;
89     int service_type;
90
91     int pmt_start_pid;
92     int start_pid;
93     int m2ts_mode;
94
95     int reemit_pat_pmt; // backward compatibility
96
97     int pcr_period;
98 #define MPEGTS_FLAG_REEMIT_PAT_PMT  0x01
99 #define MPEGTS_FLAG_AAC_LATM        0x02
100     int flags;
101     int copyts;
102     int tables_version;
103
104     int omit_video_pes_length;
105 } MpegTSWrite;
106
107 /* a PES packet header is generated every DEFAULT_PES_HEADER_FREQ packets */
108 #define DEFAULT_PES_HEADER_FREQ  16
109 #define DEFAULT_PES_PAYLOAD_SIZE ((DEFAULT_PES_HEADER_FREQ - 1) * 184 + 170)
110
111 /* The section length is 12 bits. The first 2 are set to 0, the remaining
112  * 10 bits should not exceed 1021. */
113 #define SECTION_LENGTH 1020
114
115 /* NOTE: 4 bytes must be left at the end for the crc32 */
116 static void mpegts_write_section(MpegTSSection *s, uint8_t *buf, int len)
117 {
118     unsigned int crc;
119     unsigned char packet[TS_PACKET_SIZE];
120     const unsigned char *buf_ptr;
121     unsigned char *q;
122     int first, b, len1, left;
123
124     crc = av_bswap32(av_crc(av_crc_get_table(AV_CRC_32_IEEE),
125                             -1, buf, len - 4));
126
127     buf[len - 4] = (crc >> 24) & 0xff;
128     buf[len - 3] = (crc >> 16) & 0xff;
129     buf[len - 2] = (crc >>  8) & 0xff;
130     buf[len - 1] =  crc        & 0xff;
131
132     /* send each packet */
133     buf_ptr = buf;
134     while (len > 0) {
135         first = buf == buf_ptr;
136         q     = packet;
137         *q++  = 0x47;
138         b     = s->pid >> 8;
139         if (first)
140             b |= 0x40;
141         *q++  = b;
142         *q++  = s->pid;
143         s->cc = s->cc + 1 & 0xf;
144         *q++  = 0x10 | s->cc;
145         if (first)
146             *q++ = 0; /* 0 offset */
147         len1 = TS_PACKET_SIZE - (q - packet);
148         if (len1 > len)
149             len1 = len;
150         memcpy(q, buf_ptr, len1);
151         q += len1;
152         /* add known padding data */
153         left = TS_PACKET_SIZE - (q - packet);
154         if (left > 0)
155             memset(q, 0xff, left);
156
157         s->write_packet(s, packet);
158
159         buf_ptr += len1;
160         len     -= len1;
161     }
162 }
163
164 static inline void put16(uint8_t **q_ptr, int val)
165 {
166     uint8_t *q;
167     q      = *q_ptr;
168     *q++   = val >> 8;
169     *q++   = val;
170     *q_ptr = q;
171 }
172
173 static int mpegts_write_section1(MpegTSSection *s, int tid, int id,
174                                  int version, int sec_num, int last_sec_num,
175                                  uint8_t *buf, int len)
176 {
177     uint8_t section[1024], *q;
178     unsigned int tot_len;
179     /* reserved_future_use field must be set to 1 for SDT */
180     unsigned int flags = tid == SDT_TID ? 0xf000 : 0xb000;
181
182     tot_len = 3 + 5 + len + 4;
183     /* check if not too big */
184     if (tot_len > 1024)
185         return AVERROR_INVALIDDATA;
186
187     q    = section;
188     *q++ = tid;
189     put16(&q, flags | (len + 5 + 4)); /* 5 byte header + 4 byte CRC */
190     put16(&q, id);
191     *q++ = 0xc1 | (version << 1); /* current_next_indicator = 1 */
192     *q++ = sec_num;
193     *q++ = last_sec_num;
194     memcpy(q, buf, len);
195
196     mpegts_write_section(s, section, tot_len);
197     return 0;
198 }
199
200 /*********************************************/
201 /* mpegts writer */
202
203 #define DEFAULT_PROVIDER_NAME   "FFmpeg"
204 #define DEFAULT_SERVICE_NAME    "Service01"
205
206 /* we retransmit the SI info at this rate */
207 #define SDT_RETRANS_TIME 500
208 #define PAT_RETRANS_TIME 100
209 #define PCR_RETRANS_TIME 20
210
211 typedef struct MpegTSWriteStream {
212     struct MpegTSService *service;
213     int pid; /* stream associated pid */
214     int cc;
215     int payload_size;
216     int first_pts_check; ///< first pts check needed
217     int prev_payload_key;
218     int64_t payload_pts;
219     int64_t payload_dts;
220     int payload_flags;
221     uint8_t *payload;
222     AVFormatContext *amux;
223     AVRational user_tb;
224 } MpegTSWriteStream;
225
226 static void mpegts_write_pat(AVFormatContext *s)
227 {
228     MpegTSWrite *ts = s->priv_data;
229     MpegTSService *service;
230     uint8_t data[SECTION_LENGTH], *q;
231     int i;
232
233     q = data;
234     for (i = 0; i < ts->nb_services; i++) {
235         service = ts->services[i];
236         put16(&q, service->sid);
237         put16(&q, 0xe000 | service->pmt.pid);
238     }
239     mpegts_write_section1(&ts->pat, PAT_TID, ts->tsid, ts->tables_version, 0, 0,
240                           data, q - data);
241 }
242
243 static int mpegts_write_pmt(AVFormatContext *s, MpegTSService *service)
244 {
245     MpegTSWrite *ts = s->priv_data;
246     uint8_t data[SECTION_LENGTH], *q, *desc_length_ptr, *program_info_length_ptr;
247     int val, stream_type, i, err = 0;
248
249     q = data;
250     put16(&q, 0xe000 | service->pcr_pid);
251
252     program_info_length_ptr = q;
253     q += 2; /* patched after */
254
255     /* put program info here */
256
257     val = 0xf000 | (q - program_info_length_ptr - 2);
258     program_info_length_ptr[0] = val >> 8;
259     program_info_length_ptr[1] = val;
260
261     for (i = 0; i < s->nb_streams; i++) {
262         AVStream *st = s->streams[i];
263         MpegTSWriteStream *ts_st = st->priv_data;
264         AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL, 0);
265
266         if (q - data > SECTION_LENGTH - 32) {
267             err = 1;
268             break;
269         }
270         switch (st->codec->codec_id) {
271         case AV_CODEC_ID_MPEG1VIDEO:
272         case AV_CODEC_ID_MPEG2VIDEO:
273             stream_type = STREAM_TYPE_VIDEO_MPEG2;
274             break;
275         case AV_CODEC_ID_MPEG4:
276             stream_type = STREAM_TYPE_VIDEO_MPEG4;
277             break;
278         case AV_CODEC_ID_H264:
279             stream_type = STREAM_TYPE_VIDEO_H264;
280             break;
281         case AV_CODEC_ID_HEVC:
282             stream_type = STREAM_TYPE_VIDEO_HEVC;
283             break;
284         case AV_CODEC_ID_CAVS:
285             stream_type = STREAM_TYPE_VIDEO_CAVS;
286             break;
287         case AV_CODEC_ID_DIRAC:
288             stream_type = STREAM_TYPE_VIDEO_DIRAC;
289             break;
290         case AV_CODEC_ID_MP2:
291         case AV_CODEC_ID_MP3:
292             stream_type = STREAM_TYPE_AUDIO_MPEG1;
293             break;
294         case AV_CODEC_ID_AAC:
295             stream_type = (ts->flags & MPEGTS_FLAG_AAC_LATM)
296                           ? STREAM_TYPE_AUDIO_AAC_LATM
297                           : STREAM_TYPE_AUDIO_AAC;
298             break;
299         case AV_CODEC_ID_AAC_LATM:
300             stream_type = STREAM_TYPE_AUDIO_AAC_LATM;
301             break;
302         case AV_CODEC_ID_AC3:
303             stream_type = STREAM_TYPE_AUDIO_AC3;
304             break;
305         case AV_CODEC_ID_DTS:
306             stream_type = STREAM_TYPE_AUDIO_DTS;
307             break;
308         case AV_CODEC_ID_TRUEHD:
309             stream_type = STREAM_TYPE_AUDIO_TRUEHD;
310             break;
311         default:
312             stream_type = STREAM_TYPE_PRIVATE_DATA;
313             break;
314         }
315
316         *q++ = stream_type;
317         put16(&q, 0xe000 | ts_st->pid);
318         desc_length_ptr = q;
319         q += 2; /* patched after */
320
321         /* write optional descriptors here */
322         switch (st->codec->codec_type) {
323         case AVMEDIA_TYPE_AUDIO:
324             if (st->codec->codec_id==AV_CODEC_ID_EAC3) {
325                 *q++=0x7a; // EAC3 descriptor see A038 DVB SI
326                 *q++=1; // 1 byte, all flags sets to 0
327                 *q++=0; // omit all fields...
328             }
329             if (st->codec->codec_id==AV_CODEC_ID_S302M) {
330                 *q++ = 0x05; /* MPEG-2 registration descriptor*/
331                 *q++ = 4;
332                 *q++ = 'B';
333                 *q++ = 'S';
334                 *q++ = 'S';
335                 *q++ = 'D';
336             }
337
338             if (lang) {
339                 char *p;
340                 char *next = lang->value;
341                 uint8_t *len_ptr;
342
343                 *q++     = 0x0a; /* ISO 639 language descriptor */
344                 len_ptr  = q++;
345                 *len_ptr = 0;
346
347                 for (p = lang->value; next && *len_ptr < 255 / 4 * 4; p = next + 1) {
348                     if (q - data > SECTION_LENGTH - 4) {
349                         err = 1;
350                         break;
351                     }
352                     next = strchr(p, ',');
353                     if (strlen(p) != 3 && (!next || next != p + 3))
354                         continue; /* not a 3-letter code */
355
356                     *q++ = *p++;
357                     *q++ = *p++;
358                     *q++ = *p++;
359
360                     if (st->disposition & AV_DISPOSITION_CLEAN_EFFECTS)
361                         *q++ = 0x01;
362                     else if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
363                         *q++ = 0x02;
364                     else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
365                         *q++ = 0x03;
366                     else
367                         *q++ = 0; /* undefined type */
368
369                     *len_ptr += 4;
370                 }
371
372                 if (*len_ptr == 0)
373                     q -= 2; /* no language codes were written */
374             }
375             break;
376         case AVMEDIA_TYPE_SUBTITLE:
377         {
378            const char default_language[] = "und";
379            const char *language = lang && strlen(lang->value) >= 3 ? lang->value : default_language;
380
381            if (st->codec->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
382                uint8_t *len_ptr;
383                int extradata_copied = 0;
384
385                *q++ = 0x59; /* subtitling_descriptor */
386                len_ptr = q++;
387
388                while (strlen(language) >= 3) {
389                    if (sizeof(data) - (q - data) < 8) { /* 8 bytes per DVB subtitle substream data */
390                        err = 1;
391                        break;
392                    }
393                    *q++ = *language++;
394                    *q++ = *language++;
395                    *q++ = *language++;
396                    /* Skip comma */
397                    if (*language != '\0')
398                        language++;
399
400                    if (st->codec->extradata_size - extradata_copied >= 5) {
401                        *q++ = st->codec->extradata[extradata_copied + 4]; /* subtitling_type */
402                        memcpy(q, st->codec->extradata + extradata_copied, 4); /* composition_page_id and ancillary_page_id */
403                        extradata_copied += 5;
404                        q += 4;
405                    } else {
406                        /* subtitling_type:
407                         * 0x10 - normal with no monitor aspect ratio criticality
408                         * 0x20 - for the hard of hearing with no monitor aspect ratio criticality */
409                        *q++ = (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED) ? 0x20 : 0x10;
410                        if ((st->codec->extradata_size == 4) && (extradata_copied == 0)) {
411                            /* support of old 4-byte extradata format */
412                            memcpy(q, st->codec->extradata, 4); /* composition_page_id and ancillary_page_id */
413                            extradata_copied += 4;
414                            q += 4;
415                        } else {
416                            put16(&q, 1); /* composition_page_id */
417                            put16(&q, 1); /* ancillary_page_id */
418                        }
419                    }
420                }
421
422                *len_ptr = q - len_ptr - 1;
423            } else if (st->codec->codec_id == AV_CODEC_ID_DVB_TELETEXT) {
424                uint8_t *len_ptr = NULL;
425                int extradata_copied = 0;
426
427                /* The descriptor tag. teletext_descriptor */
428                *q++ = 0x56;
429                len_ptr = q++;
430
431                while (strlen(language) >= 3 && q - data < sizeof(data) - 6) {
432                    *q++ = *language++;
433                    *q++ = *language++;
434                    *q++ = *language++;
435                    /* Skip comma */
436                    if (*language != '\0')
437                        language++;
438
439                    if (st->codec->extradata_size - 1 > extradata_copied) {
440                        memcpy(q, st->codec->extradata + extradata_copied, 2);
441                        extradata_copied += 2;
442                        q += 2;
443                    } else {
444                        /* The Teletext descriptor:
445                         * teletext_type: This 5-bit field indicates the type of Teletext page indicated. (0x01 Initial Teletext page)
446                         * teletext_magazine_number: This is a 3-bit field which identifies the magazine number.
447                         * teletext_page_number: This is an 8-bit field giving two 4-bit hex digits identifying the page number. */
448                        *q++ = 0x08;
449                        *q++ = 0x00;
450                    }
451                }
452
453                *len_ptr = q - len_ptr - 1;
454             }
455         }
456         break;
457         case AVMEDIA_TYPE_VIDEO:
458             if (stream_type == STREAM_TYPE_VIDEO_DIRAC) {
459                 *q++ = 0x05; /*MPEG-2 registration descriptor*/
460                 *q++ = 4;
461                 *q++ = 'd';
462                 *q++ = 'r';
463                 *q++ = 'a';
464                 *q++ = 'c';
465             }
466             break;
467         case AVMEDIA_TYPE_DATA:
468             if (st->codec->codec_id == AV_CODEC_ID_SMPTE_KLV) {
469                 *q++ = 0x05; /* MPEG-2 registration descriptor */
470                 *q++ = 4;
471                 *q++ = 'K';
472                 *q++ = 'L';
473                 *q++ = 'V';
474                 *q++ = 'A';
475             }
476             break;
477         }
478
479         val = 0xf000 | (q - desc_length_ptr - 2);
480         desc_length_ptr[0] = val >> 8;
481         desc_length_ptr[1] = val;
482     }
483
484     if (err)
485         av_log(s, AV_LOG_ERROR,
486                "The PMT section cannot fit stream %d and all following streams.\n"
487                "Try reducing the number of languages in the audio streams "
488                "or the total number of streams.\n", i);
489
490     mpegts_write_section1(&service->pmt, PMT_TID, service->sid, ts->tables_version, 0, 0,
491                           data, q - data);
492     return 0;
493 }
494
495 /* NOTE: !str is accepted for an empty string */
496 static void putstr8(uint8_t **q_ptr, const char *str)
497 {
498     uint8_t *q;
499     int len;
500
501     q = *q_ptr;
502     if (!str)
503         len = 0;
504     else
505         len = strlen(str);
506     *q++ = len;
507     memcpy(q, str, len);
508     q     += len;
509     *q_ptr = q;
510 }
511
512 static void mpegts_write_sdt(AVFormatContext *s)
513 {
514     MpegTSWrite *ts = s->priv_data;
515     MpegTSService *service;
516     uint8_t data[SECTION_LENGTH], *q, *desc_list_len_ptr, *desc_len_ptr;
517     int i, running_status, free_ca_mode, val;
518
519     q = data;
520     put16(&q, ts->onid);
521     *q++ = 0xff;
522     for (i = 0; i < ts->nb_services; i++) {
523         service = ts->services[i];
524         put16(&q, service->sid);
525         *q++              = 0xfc | 0x00; /* currently no EIT info */
526         desc_list_len_ptr = q;
527         q                += 2;
528         running_status    = 4; /* running */
529         free_ca_mode      = 0;
530
531         /* write only one descriptor for the service name and provider */
532         *q++         = 0x48;
533         desc_len_ptr = q;
534         q++;
535         *q++         = ts->service_type;
536         putstr8(&q, service->provider_name);
537         putstr8(&q, service->name);
538         desc_len_ptr[0] = q - desc_len_ptr - 1;
539
540         /* fill descriptor length */
541         val = (running_status << 13) | (free_ca_mode << 12) |
542               (q - desc_list_len_ptr - 2);
543         desc_list_len_ptr[0] = val >> 8;
544         desc_list_len_ptr[1] = val;
545     }
546     mpegts_write_section1(&ts->sdt, SDT_TID, ts->tsid, ts->tables_version, 0, 0,
547                           data, q - data);
548 }
549
550 static MpegTSService *mpegts_add_service(MpegTSWrite *ts, int sid,
551                                          const char *provider_name,
552                                          const char *name)
553 {
554     MpegTSService *service;
555
556     service = av_mallocz(sizeof(MpegTSService));
557     if (!service)
558         return NULL;
559     service->pmt.pid       = ts->pmt_start_pid + ts->nb_services;
560     service->sid           = sid;
561     service->pcr_pid       = 0x1fff;
562     service->provider_name = av_strdup(provider_name);
563     service->name          = av_strdup(name);
564     if (!service->provider_name || !service->name)
565         goto fail;
566     if (av_dynarray_add_nofree(&ts->services, &ts->nb_services, service) < 0)
567         goto fail;
568
569     return service;
570 fail:
571     av_freep(&service->provider_name);
572     av_freep(&service->name);
573     av_free(service);
574     return NULL;
575 }
576
577 static int64_t get_pcr(const MpegTSWrite *ts, AVIOContext *pb)
578 {
579     return av_rescale(avio_tell(pb) + 11, 8 * PCR_TIME_BASE, ts->mux_rate) +
580            ts->first_pcr;
581 }
582
583 static void mpegts_prefix_m2ts_header(AVFormatContext *s)
584 {
585     MpegTSWrite *ts = s->priv_data;
586     if (ts->m2ts_mode) {
587         int64_t pcr = get_pcr(s->priv_data, s->pb);
588         uint32_t tp_extra_header = pcr % 0x3fffffff;
589         tp_extra_header = AV_RB32(&tp_extra_header);
590         avio_write(s->pb, (unsigned char *) &tp_extra_header,
591                    sizeof(tp_extra_header));
592     }
593 }
594
595 static void section_write_packet(MpegTSSection *s, const uint8_t *packet)
596 {
597     AVFormatContext *ctx = s->opaque;
598     mpegts_prefix_m2ts_header(ctx);
599     avio_write(ctx->pb, packet, TS_PACKET_SIZE);
600 }
601
602 static int mpegts_write_header(AVFormatContext *s)
603 {
604     MpegTSWrite *ts = s->priv_data;
605     MpegTSWriteStream *ts_st;
606     MpegTSService *service;
607     AVStream *st, *pcr_st = NULL;
608     AVDictionaryEntry *title, *provider;
609     int i, j;
610     const char *service_name;
611     const char *provider_name;
612     int *pids;
613     int ret;
614
615     if (s->max_delay < 0) /* Not set by the caller */
616         s->max_delay = 0;
617
618     // round up to a whole number of TS packets
619     ts->pes_payload_size = (ts->pes_payload_size + 14 + 183) / 184 * 184 - 14;
620
621     ts->tsid = ts->transport_stream_id;
622     ts->onid = ts->original_network_id;
623     /* allocate a single DVB service */
624     title = av_dict_get(s->metadata, "service_name", NULL, 0);
625     if (!title)
626         title = av_dict_get(s->metadata, "title", NULL, 0);
627     service_name  = title ? title->value : DEFAULT_SERVICE_NAME;
628     provider      = av_dict_get(s->metadata, "service_provider", NULL, 0);
629     provider_name = provider ? provider->value : DEFAULT_PROVIDER_NAME;
630     service       = mpegts_add_service(ts, ts->service_id,
631                                        provider_name, service_name);
632
633     if (!service)
634         return AVERROR(ENOMEM);
635
636     service->pmt.write_packet = section_write_packet;
637     service->pmt.opaque       = s;
638     service->pmt.cc           = 15;
639
640     ts->pat.pid          = PAT_PID;
641     /* Initialize at 15 so that it wraps and is equal to 0 for the
642      * first packet we write. */
643     ts->pat.cc           = 15;
644     ts->pat.write_packet = section_write_packet;
645     ts->pat.opaque       = s;
646
647     ts->sdt.pid          = SDT_PID;
648     ts->sdt.cc           = 15;
649     ts->sdt.write_packet = section_write_packet;
650     ts->sdt.opaque       = s;
651
652     pids = av_malloc_array(s->nb_streams, sizeof(*pids));
653     if (!pids) {
654         ret = AVERROR(ENOMEM);
655         goto fail;
656     }
657
658     /* assign pids to each stream */
659     for (i = 0; i < s->nb_streams; i++) {
660         st = s->streams[i];
661
662         ts_st = av_mallocz(sizeof(MpegTSWriteStream));
663         if (!ts_st) {
664             ret = AVERROR(ENOMEM);
665             goto fail;
666         }
667         st->priv_data = ts_st;
668
669         ts_st->user_tb = st->time_base;
670         avpriv_set_pts_info(st, 33, 1, 90000);
671
672         ts_st->payload = av_mallocz(ts->pes_payload_size);
673         if (!ts_st->payload) {
674             ret = AVERROR(ENOMEM);
675             goto fail;
676         }
677         ts_st->service = service;
678         /* MPEG pid values < 16 are reserved. Applications which set st->id in
679          * this range are assigned a calculated pid. */
680         if (st->id < 16) {
681             ts_st->pid = ts->start_pid + i;
682         } else if (st->id < 0x1FFF) {
683             ts_st->pid = st->id;
684         } else {
685             av_log(s, AV_LOG_ERROR,
686                    "Invalid stream id %d, must be less than 8191\n", st->id);
687             ret = AVERROR(EINVAL);
688             goto fail;
689         }
690         if (ts_st->pid == service->pmt.pid) {
691             av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
692             ret = AVERROR(EINVAL);
693             goto fail;
694         }
695         for (j = 0; j < i; j++) {
696             if (pids[j] == ts_st->pid) {
697                 av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
698                 ret = AVERROR(EINVAL);
699                 goto fail;
700             }
701         }
702         pids[i]                = ts_st->pid;
703         ts_st->payload_pts     = AV_NOPTS_VALUE;
704         ts_st->payload_dts     = AV_NOPTS_VALUE;
705         ts_st->first_pts_check = 1;
706         ts_st->cc              = 15;
707         /* update PCR pid by using the first video stream */
708         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
709             service->pcr_pid == 0x1fff) {
710             service->pcr_pid = ts_st->pid;
711             pcr_st           = st;
712         }
713         if (st->codec->codec_id == AV_CODEC_ID_AAC &&
714             st->codec->extradata_size > 0) {
715             AVStream *ast;
716             ts_st->amux = avformat_alloc_context();
717             if (!ts_st->amux) {
718                 ret = AVERROR(ENOMEM);
719                 goto fail;
720             }
721             ts_st->amux->oformat =
722                 av_guess_format((ts->flags & MPEGTS_FLAG_AAC_LATM) ? "latm" : "adts",
723                                 NULL, NULL);
724             if (!ts_st->amux->oformat) {
725                 ret = AVERROR(EINVAL);
726                 goto fail;
727             }
728             if (!(ast = avformat_new_stream(ts_st->amux, NULL))) {
729                 ret = AVERROR(ENOMEM);
730                 goto fail;
731             }
732             ret = avcodec_copy_context(ast->codec, st->codec);
733             if (ret != 0)
734                 goto fail;
735             ast->time_base = st->time_base;
736             ret = avformat_write_header(ts_st->amux, NULL);
737             if (ret < 0)
738                 goto fail;
739         }
740     }
741
742     av_freep(&pids);
743
744     /* if no video stream, use the first stream as PCR */
745     if (service->pcr_pid == 0x1fff && s->nb_streams > 0) {
746         pcr_st           = s->streams[0];
747         ts_st            = pcr_st->priv_data;
748         service->pcr_pid = ts_st->pid;
749     } else
750         ts_st = pcr_st->priv_data;
751
752     if (ts->mux_rate > 1) {
753         service->pcr_packet_period = (ts->mux_rate * ts->pcr_period) /
754                                      (TS_PACKET_SIZE * 8 * 1000);
755         ts->sdt_packet_period      = (ts->mux_rate * SDT_RETRANS_TIME) /
756                                      (TS_PACKET_SIZE * 8 * 1000);
757         ts->pat_packet_period      = (ts->mux_rate * PAT_RETRANS_TIME) /
758                                      (TS_PACKET_SIZE * 8 * 1000);
759
760         if (ts->copyts < 1)
761             ts->first_pcr = av_rescale(s->max_delay, PCR_TIME_BASE, AV_TIME_BASE);
762     } else {
763         /* Arbitrary values, PAT/PMT will also be written on video key frames */
764         ts->sdt_packet_period = 200;
765         ts->pat_packet_period = 40;
766         if (pcr_st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
767             if (!pcr_st->codec->frame_size) {
768                 av_log(s, AV_LOG_WARNING, "frame size not set\n");
769                 service->pcr_packet_period =
770                     pcr_st->codec->sample_rate / (10 * 512);
771             } else {
772                 service->pcr_packet_period =
773                     pcr_st->codec->sample_rate / (10 * pcr_st->codec->frame_size);
774             }
775         } else {
776             // max delta PCR 0.1s
777             // TODO: should be avg_frame_rate
778             service->pcr_packet_period =
779                 ts_st->user_tb.den / (10 * ts_st->user_tb.num);
780         }
781         if (!service->pcr_packet_period)
782             service->pcr_packet_period = 1;
783     }
784
785     // output a PCR as soon as possible
786     service->pcr_packet_count = service->pcr_packet_period;
787     ts->pat_packet_count      = ts->pat_packet_period - 1;
788     ts->sdt_packet_count      = ts->sdt_packet_period - 1;
789
790     if (ts->mux_rate == 1)
791         av_log(s, AV_LOG_VERBOSE, "muxrate VBR, ");
792     else
793         av_log(s, AV_LOG_VERBOSE, "muxrate %d, ", ts->mux_rate);
794     av_log(s, AV_LOG_VERBOSE,
795            "pcr every %d pkts, sdt every %d, pat/pmt every %d pkts\n",
796            service->pcr_packet_period,
797            ts->sdt_packet_period, ts->pat_packet_period);
798
799     if (ts->m2ts_mode == -1) {
800         if (av_match_ext(s->filename, "m2ts")) {
801             ts->m2ts_mode = 1;
802         } else {
803             ts->m2ts_mode = 0;
804         }
805     }
806
807     return 0;
808
809 fail:
810     av_freep(&pids);
811     for (i = 0; i < s->nb_streams; i++) {
812         st    = s->streams[i];
813         ts_st = st->priv_data;
814         if (ts_st) {
815             av_freep(&ts_st->payload);
816             if (ts_st->amux) {
817                 avformat_free_context(ts_st->amux);
818                 ts_st->amux = NULL;
819             }
820         }
821         av_freep(&st->priv_data);
822     }
823
824     for (i = 0; i < ts->nb_services; i++) {
825         service = ts->services[i];
826         av_freep(&service->provider_name);
827         av_freep(&service->name);
828         av_freep(&service);
829     }
830     av_freep(&ts->services);
831     return ret;
832 }
833
834 /* send SDT, PAT and PMT tables regulary */
835 static void retransmit_si_info(AVFormatContext *s, int force_pat)
836 {
837     MpegTSWrite *ts = s->priv_data;
838     int i;
839
840     if (++ts->sdt_packet_count == ts->sdt_packet_period) {
841         ts->sdt_packet_count = 0;
842         mpegts_write_sdt(s);
843     }
844     if (++ts->pat_packet_count == ts->pat_packet_period || force_pat) {
845         ts->pat_packet_count = 0;
846         mpegts_write_pat(s);
847         for (i = 0; i < ts->nb_services; i++)
848             mpegts_write_pmt(s, ts->services[i]);
849     }
850 }
851
852 static int write_pcr_bits(uint8_t *buf, int64_t pcr)
853 {
854     int64_t pcr_low = pcr % 300, pcr_high = pcr / 300;
855
856     *buf++ = pcr_high >> 25;
857     *buf++ = pcr_high >> 17;
858     *buf++ = pcr_high >>  9;
859     *buf++ = pcr_high >>  1;
860     *buf++ = pcr_high <<  7 | pcr_low >> 8 | 0x7e;
861     *buf++ = pcr_low;
862
863     return 6;
864 }
865
866 /* Write a single null transport stream packet */
867 static void mpegts_insert_null_packet(AVFormatContext *s)
868 {
869     uint8_t *q;
870     uint8_t buf[TS_PACKET_SIZE];
871
872     q    = buf;
873     *q++ = 0x47;
874     *q++ = 0x00 | 0x1f;
875     *q++ = 0xff;
876     *q++ = 0x10;
877     memset(q, 0x0FF, TS_PACKET_SIZE - (q - buf));
878     mpegts_prefix_m2ts_header(s);
879     avio_write(s->pb, buf, TS_PACKET_SIZE);
880 }
881
882 /* Write a single transport stream packet with a PCR and no payload */
883 static void mpegts_insert_pcr_only(AVFormatContext *s, AVStream *st)
884 {
885     MpegTSWrite *ts = s->priv_data;
886     MpegTSWriteStream *ts_st = st->priv_data;
887     uint8_t *q;
888     uint8_t buf[TS_PACKET_SIZE];
889
890     q    = buf;
891     *q++ = 0x47;
892     *q++ = ts_st->pid >> 8;
893     *q++ = ts_st->pid;
894     *q++ = 0x20 | ts_st->cc;   /* Adaptation only */
895     /* Continuity Count field does not increment (see 13818-1 section 2.4.3.3) */
896     *q++ = TS_PACKET_SIZE - 5; /* Adaptation Field Length */
897     *q++ = 0x10;               /* Adaptation flags: PCR present */
898
899     /* PCR coded into 6 bytes */
900     q += write_pcr_bits(q, get_pcr(ts, s->pb));
901
902     /* stuffing bytes */
903     memset(q, 0xFF, TS_PACKET_SIZE - (q - buf));
904     mpegts_prefix_m2ts_header(s);
905     avio_write(s->pb, buf, TS_PACKET_SIZE);
906 }
907
908 static void write_pts(uint8_t *q, int fourbits, int64_t pts)
909 {
910     int val;
911
912     val  = fourbits << 4 | (((pts >> 30) & 0x07) << 1) | 1;
913     *q++ = val;
914     val  = (((pts >> 15) & 0x7fff) << 1) | 1;
915     *q++ = val >> 8;
916     *q++ = val;
917     val  = (((pts) & 0x7fff) << 1) | 1;
918     *q++ = val >> 8;
919     *q++ = val;
920 }
921
922 /* Set an adaptation field flag in an MPEG-TS packet*/
923 static void set_af_flag(uint8_t *pkt, int flag)
924 {
925     // expect at least one flag to set
926     av_assert0(flag);
927
928     if ((pkt[3] & 0x20) == 0) {
929         // no AF yet, set adaptation field flag
930         pkt[3] |= 0x20;
931         // 1 byte length, no flags
932         pkt[4] = 1;
933         pkt[5] = 0;
934     }
935     pkt[5] |= flag;
936 }
937
938 /* Extend the adaptation field by size bytes */
939 static void extend_af(uint8_t *pkt, int size)
940 {
941     // expect already existing adaptation field
942     av_assert0(pkt[3] & 0x20);
943     pkt[4] += size;
944 }
945
946 /* Get a pointer to MPEG-TS payload (right after TS packet header) */
947 static uint8_t *get_ts_payload_start(uint8_t *pkt)
948 {
949     if (pkt[3] & 0x20)
950         return pkt + 5 + pkt[4];
951     else
952         return pkt + 4;
953 }
954
955 /* Add a PES header to the front of the payload, and segment into an integer
956  * number of TS packets. The final TS packet is padded using an oversized
957  * adaptation header to exactly fill the last TS packet.
958  * NOTE: 'payload' contains a complete PES payload. */
959 static void mpegts_write_pes(AVFormatContext *s, AVStream *st,
960                              const uint8_t *payload, int payload_size,
961                              int64_t pts, int64_t dts, int key)
962 {
963     MpegTSWriteStream *ts_st = st->priv_data;
964     MpegTSWrite *ts = s->priv_data;
965     uint8_t buf[TS_PACKET_SIZE];
966     uint8_t *q;
967     int val, is_start, len, header_len, write_pcr, is_dvb_subtitle, is_dvb_teletext, flags;
968     int afc_len, stuffing_len;
969     int64_t pcr = -1; /* avoid warning */
970     int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE);
971     int force_pat = st->codec->codec_type == AVMEDIA_TYPE_VIDEO && key && !ts_st->prev_payload_key;
972
973     is_start = 1;
974     while (payload_size > 0) {
975         retransmit_si_info(s, force_pat);
976         force_pat = 0;
977
978         write_pcr = 0;
979         if (ts_st->pid == ts_st->service->pcr_pid) {
980             if (ts->mux_rate > 1 || is_start) // VBR pcr period is based on frames
981                 ts_st->service->pcr_packet_count++;
982             if (ts_st->service->pcr_packet_count >=
983                 ts_st->service->pcr_packet_period) {
984                 ts_st->service->pcr_packet_count = 0;
985                 write_pcr = 1;
986             }
987         }
988
989         if (ts->mux_rate > 1 && dts != AV_NOPTS_VALUE &&
990             (dts - get_pcr(ts, s->pb) / 300) > delay) {
991             /* pcr insert gets priority over null packet insert */
992             if (write_pcr)
993                 mpegts_insert_pcr_only(s, st);
994             else
995                 mpegts_insert_null_packet(s);
996             /* recalculate write_pcr and possibly retransmit si_info */
997             continue;
998         }
999
1000         /* prepare packet header */
1001         q    = buf;
1002         *q++ = 0x47;
1003         val  = ts_st->pid >> 8;
1004         if (is_start)
1005             val |= 0x40;
1006         *q++      = val;
1007         *q++      = ts_st->pid;
1008         ts_st->cc = ts_st->cc + 1 & 0xf;
1009         *q++      = 0x10 | ts_st->cc; // payload indicator + CC
1010         if (key && is_start && pts != AV_NOPTS_VALUE) {
1011             // set Random Access for key frames
1012             if (ts_st->pid == ts_st->service->pcr_pid)
1013                 write_pcr = 1;
1014             set_af_flag(buf, 0x40);
1015             q = get_ts_payload_start(buf);
1016         }
1017         if (write_pcr) {
1018             set_af_flag(buf, 0x10);
1019             q = get_ts_payload_start(buf);
1020             // add 11, pcr references the last byte of program clock reference base
1021             if (ts->mux_rate > 1)
1022                 pcr = get_pcr(ts, s->pb);
1023             else
1024                 pcr = (dts - delay) * 300;
1025             if (dts != AV_NOPTS_VALUE && dts < pcr / 300)
1026                 av_log(s, AV_LOG_WARNING, "dts < pcr, TS is invalid\n");
1027             extend_af(buf, write_pcr_bits(q, pcr));
1028             q = get_ts_payload_start(buf);
1029         }
1030         if (is_start) {
1031             int pes_extension = 0;
1032             int pes_header_stuffing_bytes = 0;
1033             /* write PES header */
1034             *q++ = 0x00;
1035             *q++ = 0x00;
1036             *q++ = 0x01;
1037             is_dvb_subtitle = 0;
1038             is_dvb_teletext = 0;
1039             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1040                 if (st->codec->codec_id == AV_CODEC_ID_DIRAC)
1041                     *q++ = 0xfd;
1042                 else
1043                     *q++ = 0xe0;
1044             } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1045                        (st->codec->codec_id == AV_CODEC_ID_MP2 ||
1046                         st->codec->codec_id == AV_CODEC_ID_MP3 ||
1047                         st->codec->codec_id == AV_CODEC_ID_AAC)) {
1048                 *q++ = 0xc0;
1049             } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1050                         st->codec->codec_id == AV_CODEC_ID_AC3 &&
1051                         ts->m2ts_mode) {
1052                 *q++ = 0xfd;
1053             } else {
1054                 *q++ = 0xbd;
1055                 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1056                     if (st->codec->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
1057                         is_dvb_subtitle = 1;
1058                     } else if (st->codec->codec_id == AV_CODEC_ID_DVB_TELETEXT) {
1059                         is_dvb_teletext = 1;
1060                     }
1061                 }
1062             }
1063             header_len = 0;
1064             flags      = 0;
1065             if (pts != AV_NOPTS_VALUE) {
1066                 header_len += 5;
1067                 flags      |= 0x80;
1068             }
1069             if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
1070                 header_len += 5;
1071                 flags      |= 0x40;
1072             }
1073             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
1074                 st->codec->codec_id == AV_CODEC_ID_DIRAC) {
1075                 /* set PES_extension_flag */
1076                 pes_extension = 1;
1077                 flags        |= 0x01;
1078
1079                 /* One byte for PES2 extension flag +
1080                  * one byte for extension length +
1081                  * one byte for extension id */
1082                 header_len += 3;
1083             }
1084             /* for Blu-ray AC3 Audio the PES Extension flag should be as follow
1085              * otherwise it will not play sound on blu-ray
1086              */
1087             if (ts->m2ts_mode &&
1088                 st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1089                 st->codec->codec_id == AV_CODEC_ID_AC3) {
1090                         /* set PES_extension_flag */
1091                         pes_extension = 1;
1092                         flags |= 0x01;
1093                         header_len += 3;
1094             }
1095             if (is_dvb_teletext) {
1096                 pes_header_stuffing_bytes = 0x24 - header_len;
1097                 header_len = 0x24;
1098             }
1099             len = payload_size + header_len + 3;
1100             /* 3 extra bytes should be added to DVB subtitle payload: 0x20 0x00 at the beginning and trailing 0xff */
1101             if (is_dvb_subtitle) {
1102                 len += 3;
1103                 payload_size++;
1104             }
1105             if (len > 0xffff)
1106                 len = 0;
1107             if (ts->omit_video_pes_length && st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1108                 len = 0;
1109             }
1110             *q++ = len >> 8;
1111             *q++ = len;
1112             val  = 0x80;
1113             /* data alignment indicator is required for subtitle and data streams */
1114             if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE || st->codec->codec_type == AVMEDIA_TYPE_DATA)
1115                 val |= 0x04;
1116             *q++ = val;
1117             *q++ = flags;
1118             *q++ = header_len;
1119             if (pts != AV_NOPTS_VALUE) {
1120                 write_pts(q, flags >> 6, pts);
1121                 q += 5;
1122             }
1123             if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
1124                 write_pts(q, 1, dts);
1125                 q += 5;
1126             }
1127             if (pes_extension && st->codec->codec_id == AV_CODEC_ID_DIRAC) {
1128                 flags = 0x01;  /* set PES_extension_flag_2 */
1129                 *q++  = flags;
1130                 *q++  = 0x80 | 0x01; /* marker bit + extension length */
1131                 /* Set the stream ID extension flag bit to 0 and
1132                  * write the extended stream ID. */
1133                 *q++ = 0x00 | 0x60;
1134             }
1135             /* For Blu-ray AC3 Audio Setting extended flags */
1136           if (ts->m2ts_mode &&
1137               pes_extension &&
1138               st->codec->codec_id == AV_CODEC_ID_AC3) {
1139                       flags = 0x01; /* set PES_extension_flag_2 */
1140                       *q++ = flags;
1141                       *q++ = 0x80 | 0x01; /* marker bit + extension length */
1142                       *q++ = 0x00 | 0x71; /* for AC3 Audio (specifically on blue-rays) */
1143               }
1144
1145
1146             if (is_dvb_subtitle) {
1147                 /* First two fields of DVB subtitles PES data:
1148                  * data_identifier: for DVB subtitle streams shall be coded with the value 0x20
1149                  * subtitle_stream_id: for DVB subtitle stream shall be identified by the value 0x00 */
1150                 *q++ = 0x20;
1151                 *q++ = 0x00;
1152             }
1153             if (is_dvb_teletext) {
1154                 memset(q, 0xff, pes_header_stuffing_bytes);
1155                 q += pes_header_stuffing_bytes;
1156             }
1157             is_start = 0;
1158         }
1159         /* header size */
1160         header_len = q - buf;
1161         /* data len */
1162         len = TS_PACKET_SIZE - header_len;
1163         if (len > payload_size)
1164             len = payload_size;
1165         stuffing_len = TS_PACKET_SIZE - header_len - len;
1166         if (stuffing_len > 0) {
1167             /* add stuffing with AFC */
1168             if (buf[3] & 0x20) {
1169                 /* stuffing already present: increase its size */
1170                 afc_len = buf[4] + 1;
1171                 memmove(buf + 4 + afc_len + stuffing_len,
1172                         buf + 4 + afc_len,
1173                         header_len - (4 + afc_len));
1174                 buf[4] += stuffing_len;
1175                 memset(buf + 4 + afc_len, 0xff, stuffing_len);
1176             } else {
1177                 /* add stuffing */
1178                 memmove(buf + 4 + stuffing_len, buf + 4, header_len - 4);
1179                 buf[3] |= 0x20;
1180                 buf[4]  = stuffing_len - 1;
1181                 if (stuffing_len >= 2) {
1182                     buf[5] = 0x00;
1183                     memset(buf + 6, 0xff, stuffing_len - 2);
1184                 }
1185             }
1186         }
1187
1188         if (is_dvb_subtitle && payload_size == len) {
1189             memcpy(buf + TS_PACKET_SIZE - len, payload, len - 1);
1190             buf[TS_PACKET_SIZE - 1] = 0xff; /* end_of_PES_data_field_marker: an 8-bit field with fixed contents 0xff for DVB subtitle */
1191         } else {
1192             memcpy(buf + TS_PACKET_SIZE - len, payload, len);
1193         }
1194
1195         payload      += len;
1196         payload_size -= len;
1197         mpegts_prefix_m2ts_header(s);
1198         avio_write(s->pb, buf, TS_PACKET_SIZE);
1199     }
1200     ts_st->prev_payload_key = key;
1201 }
1202
1203 int ff_check_h264_startcode(AVFormatContext *s, const AVStream *st, const AVPacket *pkt)
1204 {
1205     if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001) {
1206         if (!st->nb_frames) {
1207             av_log(s, AV_LOG_ERROR, "H.264 bitstream malformed, "
1208                    "no startcode found, use the video bitstream filter 'h264_mp4toannexb' to fix it "
1209                    "('-bsf:v h264_mp4toannexb' option with ffmpeg)\n");
1210             return AVERROR_INVALIDDATA;
1211         }
1212         av_log(s, AV_LOG_WARNING, "H.264 bitstream error, startcode missing, size %d", pkt->size);
1213         if (pkt->size) av_log(s, AV_LOG_WARNING, " data %08X", AV_RB32(pkt->data));
1214         av_log(s, AV_LOG_WARNING, "\n");
1215     }
1216     return 0;
1217 }
1218
1219 static int check_hevc_startcode(AVFormatContext *s, const AVStream *st, const AVPacket *pkt)
1220 {
1221     if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001) {
1222         if (!st->nb_frames) {
1223             av_log(s, AV_LOG_ERROR, "HEVC bitstream malformed, no startcode found\n");
1224             return AVERROR_PATCHWELCOME;
1225         }
1226         av_log(s, AV_LOG_WARNING, "HEVC bitstream error, startcode missing, size %d", pkt->size);
1227         if (pkt->size) av_log(s, AV_LOG_WARNING, " data %08X", AV_RB32(pkt->data));
1228         av_log(s, AV_LOG_WARNING, "\n");
1229     }
1230     return 0;
1231 }
1232
1233 static int mpegts_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
1234 {
1235     AVStream *st = s->streams[pkt->stream_index];
1236     int size = pkt->size;
1237     uint8_t *buf = pkt->data;
1238     uint8_t *data = NULL;
1239     MpegTSWrite *ts = s->priv_data;
1240     MpegTSWriteStream *ts_st = st->priv_data;
1241     const int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE) * 2;
1242     int64_t dts = pkt->dts, pts = pkt->pts;
1243
1244     if (ts->reemit_pat_pmt) {
1245         av_log(s, AV_LOG_WARNING,
1246                "resend_headers option is deprecated, use -mpegts_flags resend_headers\n");
1247         ts->reemit_pat_pmt = 0;
1248         ts->flags         |= MPEGTS_FLAG_REEMIT_PAT_PMT;
1249     }
1250
1251     if (ts->flags & MPEGTS_FLAG_REEMIT_PAT_PMT) {
1252         ts->pat_packet_count = ts->pat_packet_period - 1;
1253         ts->sdt_packet_count = ts->sdt_packet_period - 1;
1254         ts->flags           &= ~MPEGTS_FLAG_REEMIT_PAT_PMT;
1255     }
1256
1257     if (ts->copyts < 1) {
1258         if (pts != AV_NOPTS_VALUE)
1259             pts += delay;
1260         if (dts != AV_NOPTS_VALUE)
1261             dts += delay;
1262     }
1263
1264     if (ts_st->first_pts_check && pts == AV_NOPTS_VALUE) {
1265         av_log(s, AV_LOG_ERROR, "first pts value must be set\n");
1266         return AVERROR_INVALIDDATA;
1267     }
1268     ts_st->first_pts_check = 0;
1269
1270     if (st->codec->codec_id == AV_CODEC_ID_H264) {
1271         const uint8_t *p = buf, *buf_end = p + size;
1272         uint32_t state = -1;
1273         int extradd = (pkt->flags & AV_PKT_FLAG_KEY) ? st->codec->extradata_size : 0;
1274         int ret = ff_check_h264_startcode(s, st, pkt);
1275         if (ret < 0)
1276             return ret;
1277
1278         if (extradd && AV_RB24(st->codec->extradata) > 1)
1279             extradd = 0;
1280
1281         do {
1282             p = avpriv_find_start_code(p, buf_end, &state);
1283             av_dlog(s, "nal %d\n", state & 0x1f);
1284             if ((state & 0x1f) == 7)
1285                 extradd = 0;
1286         } while (p < buf_end && (state & 0x1f) != 9 &&
1287                  (state & 0x1f) != 5 && (state & 0x1f) != 1);
1288
1289         if ((state & 0x1f) != 5)
1290             extradd = 0;
1291         if ((state & 0x1f) != 9) { // AUD NAL
1292             data = av_malloc(pkt->size + 6 + extradd);
1293             if (!data)
1294                 return AVERROR(ENOMEM);
1295             memcpy(data + 6, st->codec->extradata, extradd);
1296             memcpy(data + 6 + extradd, pkt->data, pkt->size);
1297             AV_WB32(data, 0x00000001);
1298             data[4] = 0x09;
1299             data[5] = 0xf0; // any slice type (0xe) + rbsp stop one bit
1300             buf     = data;
1301             size    = pkt->size + 6 + extradd;
1302         }
1303     } else if (st->codec->codec_id == AV_CODEC_ID_AAC) {
1304         if (pkt->size < 2) {
1305             av_log(s, AV_LOG_ERROR, "AAC packet too short\n");
1306             return AVERROR_INVALIDDATA;
1307         }
1308         if ((AV_RB16(pkt->data) & 0xfff0) != 0xfff0) {
1309             int ret;
1310             AVPacket pkt2;
1311
1312             if (!ts_st->amux) {
1313                 av_log(s, AV_LOG_ERROR, "AAC bitstream not in ADTS format "
1314                                         "and extradata missing\n");
1315                 return AVERROR_INVALIDDATA;
1316             }
1317
1318             av_init_packet(&pkt2);
1319             pkt2.data = pkt->data;
1320             pkt2.size = pkt->size;
1321             av_assert0(pkt->dts != AV_NOPTS_VALUE);
1322             pkt2.dts = av_rescale_q(pkt->dts, st->time_base, ts_st->amux->streams[0]->time_base);
1323
1324             ret = avio_open_dyn_buf(&ts_st->amux->pb);
1325             if (ret < 0)
1326                 return AVERROR(ENOMEM);
1327
1328             ret = av_write_frame(ts_st->amux, &pkt2);
1329             if (ret < 0) {
1330                 avio_close_dyn_buf(ts_st->amux->pb, &data);
1331                 ts_st->amux->pb = NULL;
1332                 av_free(data);
1333                 return ret;
1334             }
1335             size            = avio_close_dyn_buf(ts_st->amux->pb, &data);
1336             ts_st->amux->pb = NULL;
1337             buf             = data;
1338         }
1339     } else if (st->codec->codec_id == AV_CODEC_ID_HEVC) {
1340         int ret = check_hevc_startcode(s, st, pkt);
1341         if (ret < 0)
1342             return ret;
1343     }
1344
1345     if (pkt->dts != AV_NOPTS_VALUE) {
1346         int i;
1347         for(i=0; i<s->nb_streams; i++) {
1348             AVStream *st2 = s->streams[i];
1349             MpegTSWriteStream *ts_st2 = st2->priv_data;
1350             if (   ts_st2->payload_size
1351                && (ts_st2->payload_dts == AV_NOPTS_VALUE || dts - ts_st2->payload_dts > delay/2)) {
1352                 mpegts_write_pes(s, st2, ts_st2->payload, ts_st2->payload_size,
1353                                 ts_st2->payload_pts, ts_st2->payload_dts,
1354                                 ts_st2->payload_flags & AV_PKT_FLAG_KEY);
1355                 ts_st2->payload_size = 0;
1356             }
1357         }
1358     }
1359
1360     if (ts_st->payload_size && ts_st->payload_size + size > ts->pes_payload_size) {
1361         mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_size,
1362                          ts_st->payload_pts, ts_st->payload_dts,
1363                          ts_st->payload_flags & AV_PKT_FLAG_KEY);
1364         ts_st->payload_size = 0;
1365     }
1366
1367     if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO || size > ts->pes_payload_size) {
1368         av_assert0(!ts_st->payload_size);
1369         // for video and subtitle, write a single pes packet
1370         mpegts_write_pes(s, st, buf, size, pts, dts,
1371                          pkt->flags & AV_PKT_FLAG_KEY);
1372         av_free(data);
1373         return 0;
1374     }
1375
1376     if (!ts_st->payload_size) {
1377         ts_st->payload_pts   = pts;
1378         ts_st->payload_dts   = dts;
1379         ts_st->payload_flags = pkt->flags;
1380     }
1381
1382     memcpy(ts_st->payload + ts_st->payload_size, buf, size);
1383     ts_st->payload_size += size;
1384
1385     av_free(data);
1386
1387     return 0;
1388 }
1389
1390 static void mpegts_write_flush(AVFormatContext *s)
1391 {
1392     int i;
1393
1394     /* flush current packets */
1395     for (i = 0; i < s->nb_streams; i++) {
1396         AVStream *st = s->streams[i];
1397         MpegTSWriteStream *ts_st = st->priv_data;
1398         if (ts_st->payload_size > 0) {
1399             mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_size,
1400                              ts_st->payload_pts, ts_st->payload_dts,
1401                              ts_st->payload_flags & AV_PKT_FLAG_KEY);
1402             ts_st->payload_size = 0;
1403         }
1404     }
1405 }
1406
1407 static int mpegts_write_packet(AVFormatContext *s, AVPacket *pkt)
1408 {
1409     if (!pkt) {
1410         mpegts_write_flush(s);
1411         return 1;
1412     } else {
1413         return mpegts_write_packet_internal(s, pkt);
1414     }
1415 }
1416
1417 static int mpegts_write_end(AVFormatContext *s)
1418 {
1419     MpegTSWrite *ts = s->priv_data;
1420     MpegTSService *service;
1421     int i;
1422
1423     if (s->pb)
1424         mpegts_write_flush(s);
1425
1426     for (i = 0; i < s->nb_streams; i++) {
1427         AVStream *st = s->streams[i];
1428         MpegTSWriteStream *ts_st = st->priv_data;
1429         av_freep(&ts_st->payload);
1430         if (ts_st->amux) {
1431             avformat_free_context(ts_st->amux);
1432             ts_st->amux = NULL;
1433         }
1434     }
1435
1436     for (i = 0; i < ts->nb_services; i++) {
1437         service = ts->services[i];
1438         av_freep(&service->provider_name);
1439         av_freep(&service->name);
1440         av_freep(&service);
1441     }
1442     av_freep(&ts->services);
1443
1444     return 0;
1445 }
1446
1447 static const AVOption options[] = {
1448     { "mpegts_transport_stream_id", "Set transport_stream_id field.",
1449       offsetof(MpegTSWrite, transport_stream_id), AV_OPT_TYPE_INT,
1450       { .i64 = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM },
1451     { "mpegts_original_network_id", "Set original_network_id field.",
1452       offsetof(MpegTSWrite, original_network_id), AV_OPT_TYPE_INT,
1453       { .i64 = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM },
1454     { "mpegts_service_id", "Set service_id field.",
1455       offsetof(MpegTSWrite, service_id), AV_OPT_TYPE_INT,
1456       { .i64 = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM },
1457     { "mpegts_service_type", "Set service_type field.",
1458       offsetof(MpegTSWrite, service_type), AV_OPT_TYPE_INT,
1459       { .i64 = 0x01 }, 0x01, 0xff, AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1460     { "digital_tv", "Digital Television.",
1461       0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_DIGITAL_TV }, 0x01, 0xff,
1462       AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1463     { "digital_radio", "Digital Radio.",
1464       0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_DIGITAL_RADIO }, 0x01, 0xff,
1465       AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1466     { "teletext", "Teletext.",
1467       0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_TELETEXT }, 0x01, 0xff,
1468       AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1469     { "advanced_codec_digital_radio", "Advanced Codec Digital Radio.",
1470       0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_ADVANCED_CODEC_DIGITAL_RADIO }, 0x01, 0xff,
1471       AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1472     { "mpeg2_digital_hdtv", "MPEG2 Digital HDTV.",
1473       0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_MPEG2_DIGITAL_HDTV }, 0x01, 0xff,
1474       AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1475     { "advanced_codec_digital_sdtv", "Advanced Codec Digital SDTV.",
1476       0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_ADVANCED_CODEC_DIGITAL_SDTV }, 0x01, 0xff,
1477       AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1478     { "advanced_codec_digital_hdtv", "Advanced Codec Digital HDTV.",
1479       0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_ADVANCED_CODEC_DIGITAL_HDTV }, 0x01, 0xff,
1480       AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1481     { "mpegts_pmt_start_pid", "Set the first pid of the PMT.",
1482       offsetof(MpegTSWrite, pmt_start_pid), AV_OPT_TYPE_INT,
1483       { .i64 = 0x1000 }, 0x0010, 0x1f00, AV_OPT_FLAG_ENCODING_PARAM },
1484     { "mpegts_start_pid", "Set the first pid.",
1485       offsetof(MpegTSWrite, start_pid), AV_OPT_TYPE_INT,
1486       { .i64 = 0x0100 }, 0x0020, 0x0f00, AV_OPT_FLAG_ENCODING_PARAM },
1487     { "mpegts_m2ts_mode", "Enable m2ts mode.",
1488       offsetof(MpegTSWrite, m2ts_mode), AV_OPT_TYPE_INT,
1489       { .i64 = -1 }, -1, 1, AV_OPT_FLAG_ENCODING_PARAM },
1490     { "muxrate", NULL,
1491       offsetof(MpegTSWrite, mux_rate), AV_OPT_TYPE_INT,
1492       { .i64 = 1 }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
1493     { "pes_payload_size", "Minimum PES packet payload in bytes",
1494       offsetof(MpegTSWrite, pes_payload_size), AV_OPT_TYPE_INT,
1495       { .i64 = DEFAULT_PES_PAYLOAD_SIZE }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
1496     { "mpegts_flags", "MPEG-TS muxing flags",
1497       offsetof(MpegTSWrite, flags), AV_OPT_TYPE_FLAGS, { .i64 = 0 }, 0, INT_MAX,
1498       AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags" },
1499     { "resend_headers", "Reemit PAT/PMT before writing the next packet",
1500       0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_FLAG_REEMIT_PAT_PMT }, 0, INT_MAX,
1501       AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags" },
1502     { "latm", "Use LATM packetization for AAC",
1503       0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_FLAG_AAC_LATM }, 0, INT_MAX,
1504       AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags" },
1505     // backward compatibility
1506     { "resend_headers", "Reemit PAT/PMT before writing the next packet",
1507       offsetof(MpegTSWrite, reemit_pat_pmt), AV_OPT_TYPE_INT,
1508       { .i64 = 0 }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
1509     { "mpegts_copyts", "don't offset dts/pts",
1510       offsetof(MpegTSWrite, copyts), AV_OPT_TYPE_INT,
1511       { .i64 = -1 }, -1, 1, AV_OPT_FLAG_ENCODING_PARAM },
1512     { "tables_version", "set PAT, PMT and SDT version",
1513       offsetof(MpegTSWrite, tables_version), AV_OPT_TYPE_INT,
1514       { .i64 = 0 }, 0, 31, AV_OPT_FLAG_ENCODING_PARAM },
1515     { "omit_video_pes_length", "Omit the PES packet length for video packets",
1516       offsetof(MpegTSWrite, omit_video_pes_length), AV_OPT_TYPE_INT,
1517       { .i64 = 1 }, 0, 1, AV_OPT_FLAG_ENCODING_PARAM },
1518     { "pcr_period", "PCR retransmission time",
1519       offsetof(MpegTSWrite, pcr_period), AV_OPT_TYPE_INT,
1520       { .i64 = PCR_RETRANS_TIME }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
1521     { NULL },
1522 };
1523
1524 static const AVClass mpegts_muxer_class = {
1525     .class_name = "MPEGTS muxer",
1526     .item_name  = av_default_item_name,
1527     .option     = options,
1528     .version    = LIBAVUTIL_VERSION_INT,
1529 };
1530
1531 AVOutputFormat ff_mpegts_muxer = {
1532     .name           = "mpegts",
1533     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
1534     .mime_type      = "video/MP2T",
1535     .extensions     = "ts,m2t,m2ts,mts",
1536     .priv_data_size = sizeof(MpegTSWrite),
1537     .audio_codec    = AV_CODEC_ID_MP2,
1538     .video_codec    = AV_CODEC_ID_MPEG2VIDEO,
1539     .write_header   = mpegts_write_header,
1540     .write_packet   = mpegts_write_packet,
1541     .write_trailer  = mpegts_write_end,
1542     .flags          = AVFMT_ALLOW_FLUSH,
1543     .priv_class     = &mpegts_muxer_class,
1544 };