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