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