FFmpeg
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/mem.h"
29 #include "libavutil/opt.h"
30 
32 #include "libavcodec/bytestream.h"
33 #include "libavcodec/defs.h"
34 #include "libavcodec/h264.h"
35 #include "libavcodec/hevc/hevc.h"
36 #include "libavcodec/vvc.h"
37 #include "libavcodec/startcode.h"
38 
39 #include "avformat.h"
40 #include "avio_internal.h"
41 #include "internal.h"
42 #include "mpegts.h"
43 #include "mux.h"
44 
45 #define PCR_TIME_BASE 27000000
46 
47 /* write DVB SI sections */
48 
49 #define DVB_PRIVATE_NETWORK_START 0xff01
50 
51 /*********************************************/
52 /* mpegts section writer */
53 
54 typedef struct MpegTSSection {
55  int pid;
56  int cc;
58  void (*write_packet)(struct MpegTSSection *s, const uint8_t *packet);
59  void *opaque;
60  int remaining;
62 
63 typedef struct MpegTSService {
64  MpegTSSection pmt; /* MPEG-2 PMT table context */
65  int sid; /* service ID */
66  uint8_t name[256];
67  uint8_t provider_name[256];
68  int pcr_pid;
71 
72 // service_type values as defined in ETSI 300 468
73 enum {
82 };
83 typedef struct MpegTSWrite {
84  const AVClass *av_class;
85  MpegTSSection pat; /* MPEG-2 PAT table */
86  MpegTSSection sdt; /* MPEG-2 SDT table context */
87  MpegTSSection nit; /* MPEG-2 NIT table context */
90  int64_t sdt_period; /* SDT period in PCR time base */
91  int64_t pat_period; /* PAT/PMT period in PCR time base */
92  int64_t nit_period; /* NIT period in PCR time base */
97  int mux_rate; ///< set to 1 when VBR
100 
105 
113 
115 #define MPEGTS_FLAG_REEMIT_PAT_PMT 0x01
116 #define MPEGTS_FLAG_AAC_LATM 0x02
117 #define MPEGTS_FLAG_PAT_PMT_AT_FRAMES 0x04
118 #define MPEGTS_FLAG_SYSTEM_B 0x08
119 #define MPEGTS_FLAG_DISCONT 0x10
120 #define MPEGTS_FLAG_NIT 0x20
121 #define MPEGTS_FLAG_OMIT_RAI 0x40
122  int flags;
123  int copyts;
131 
132  uint8_t provider_name[256];
133 
135 } MpegTSWrite;
136 
137 /* a PES packet header is generated every DEFAULT_PES_HEADER_FREQ packets */
138 #define DEFAULT_PES_HEADER_FREQ 16
139 #define DEFAULT_PES_PAYLOAD_SIZE ((DEFAULT_PES_HEADER_FREQ - 1) * 184 + 170)
140 
141 /* The section length is 12 bits. The first 2 are set to 0, the remaining
142  * 10 bits should not exceed 1021. */
143 #define SECTION_LENGTH 1020
144 
145 /* NOTE: 4 bytes must be left at the end for the crc32 */
146 static void mpegts_write_section(MpegTSSection *s, uint8_t *buf, int len)
147 {
148  unsigned int crc;
149  unsigned char packet[TS_PACKET_SIZE];
150  const unsigned char *buf_ptr;
151  unsigned char *q;
152  int first, b, len1, left;
153 
155  -1, buf, len - 4));
156 
157  buf[len - 4] = (crc >> 24) & 0xff;
158  buf[len - 3] = (crc >> 16) & 0xff;
159  buf[len - 2] = (crc >> 8) & 0xff;
160  buf[len - 1] = crc & 0xff;
161 
162  /* send each packet */
163  buf_ptr = buf;
164  while (len > 0) {
165  first = buf == buf_ptr;
166  q = packet;
167  *q++ = SYNC_BYTE;
168  b = s->pid >> 8;
169  if (first)
170  b |= 0x40;
171  *q++ = b;
172  *q++ = s->pid;
173  s->cc = s->cc + 1 & 0xf;
174  *q++ = 0x10 | s->cc;
175  if (s->discontinuity) {
176  q[-1] |= 0x20;
177  *q++ = 1;
178  *q++ = 0x80;
179  s->discontinuity = 0;
180  }
181  if (first)
182  *q++ = 0; /* 0 offset */
183  len1 = TS_PACKET_SIZE - (q - packet);
184  if (len1 > len)
185  len1 = len;
186  memcpy(q, buf_ptr, len1);
187  q += len1;
188  /* add known padding data */
189  left = TS_PACKET_SIZE - (q - packet);
190  if (left > 0)
191  memset(q, STUFFING_BYTE, left);
192 
193  s->write_packet(s, packet);
194 
195  buf_ptr += len1;
196  len -= len1;
197  }
198 }
199 
200 static inline void put16(uint8_t **q_ptr, int val)
201 {
202  uint8_t *q;
203  q = *q_ptr;
204  *q++ = val >> 8;
205  *q++ = val;
206  *q_ptr = q;
207 }
208 
209 static int mpegts_write_section1(MpegTSSection *s, int tid, int id,
210  int version, int sec_num, int last_sec_num,
211  uint8_t *buf, int len)
212 {
213  uint8_t section[1024], *q;
214  unsigned int tot_len;
215  /* reserved_future_use field must be set to 1 for SDT and NIT */
216  unsigned int flags = (tid == SDT_TID || tid == NIT_TID) ? 0xf000 : 0xb000;
217 
218  tot_len = 3 + 5 + len + 4;
219  /* check if not too big */
220  if (tot_len > 1024)
221  return AVERROR_INVALIDDATA;
222 
223  q = section;
224  *q++ = tid;
225  put16(&q, flags | (len + 5 + 4)); /* 5 byte header + 4 byte CRC */
226  put16(&q, id);
227  *q++ = 0xc1 | (version << 1); /* current_next_indicator = 1 */
228  *q++ = sec_num;
229  *q++ = last_sec_num;
230  memcpy(q, buf, len);
231 
232  mpegts_write_section(s, section, tot_len);
233  return 0;
234 }
235 
236 /*********************************************/
237 /* mpegts writer */
238 
239 #define DEFAULT_PROVIDER_NAME "FFmpeg"
240 #define DEFAULT_SERVICE_NAME "Service"
241 
242 /* we retransmit the SI info at this rate */
243 #define SDT_RETRANS_TIME 500
244 #define PAT_RETRANS_TIME 100
245 #define PCR_RETRANS_TIME 20
246 #define NIT_RETRANS_TIME 500
247 
248 typedef struct MpegTSWriteStream {
249  int pid; /* stream associated pid */
250  int cc;
253  int first_timestamp_checked; ///< first pts/dts check needed
258  uint8_t *payload;
261 
262  int64_t pcr_period; /* PCR period in PCR time base */
264 
265  /* For Opus */
268 
271 
273 {
274  MpegTSWrite *ts = s->priv_data;
275  MpegTSService *service;
276  uint8_t data[SECTION_LENGTH], *q;
277  int i;
278 
279  q = data;
280  if (ts->flags & MPEGTS_FLAG_NIT) {
281  put16(&q, 0x0000);
282  put16(&q, NIT_PID);
283  }
284  for (i = 0; i < ts->nb_services; i++) {
285  service = ts->services[i];
286  put16(&q, service->sid);
287  put16(&q, 0xe000 | service->pmt.pid);
288  }
290  data, q - data);
291 }
292 
293 static void putbuf(uint8_t **q_ptr, const uint8_t *buf, size_t len)
294 {
295  memcpy(*q_ptr, buf, len);
296  *q_ptr += len;
297 }
298 
299 static int put_arib_caption_descriptor(AVFormatContext *s, uint8_t **q_ptr,
300  AVCodecParameters *codecpar)
301 {
302  uint8_t stream_identifier;
303  uint16_t data_component_id;
304  uint8_t *q = *q_ptr;
305 
306  switch (codecpar->profile) {
308  stream_identifier = 0x30;
309  data_component_id = 0x0008;
310  break;
312  stream_identifier = 0x87;
313  data_component_id = 0x0012;
314  break;
315  default:
317  "Unset/unknown ARIB caption profile %d utilized!\n",
318  codecpar->profile);
319  return AVERROR_INVALIDDATA;
320  }
321 
322  // stream_identifier_descriptor
323  *q++ = STREAM_IDENTIFIER_DESCRIPTOR; // descriptor_tag
324  *q++ = 1; // descriptor_length
325  *q++ = stream_identifier; // component_tag: stream_identifier
326 
327  // data_component_descriptor, defined in ARIB STD-B10, part 2, 6.2.20
328  *q++ = DATA_COMPONENT_DESCRIPTOR; // descriptor_tag: ARIB data coding type descriptor
329  *q++ = 3; // descriptor_length
330  put16(&q, data_component_id); // data_component_id
331  // additional_arib_caption_info: defined in ARIB STD-B24, fascicle 1, Part 3, 9.6.1
332  // Here we utilize a pre-defined set of values defined in ARIB TR-B14,
333  // Fascicle 2, 4.2.8.5 for PMT usage, with the reserved bits in the middle
334  // set to 1 (as that is what every broadcaster seems to be doing in
335  // production).
336  *q++ = 0x3D; // DMF('0011'), Reserved('11'), Timing('01')
337 
338  *q_ptr = q;
339 
340  return 0;
341 }
342 
343 static void put_registration_descriptor(uint8_t **q_ptr, uint32_t tag)
344 {
345  uint8_t *q = *q_ptr;
347  *q++ = 4;
348  *q++ = tag;
349  *q++ = tag >> 8;
350  *q++ = tag >> 16;
351  *q++ = tag >> 24;
352  *q_ptr = q;
353 }
354 
356 {
357  MpegTSWrite *ts = s->priv_data;
358  MpegTSWriteStream *ts_st = st->priv_data;
359  int stream_type;
360 
361  switch (st->codecpar->codec_id) {
364  stream_type = STREAM_TYPE_VIDEO_MPEG2;
365  break;
366  case AV_CODEC_ID_MPEG4:
367  stream_type = STREAM_TYPE_VIDEO_MPEG4;
368  break;
369  case AV_CODEC_ID_H264:
370  stream_type = STREAM_TYPE_VIDEO_H264;
371  break;
372  case AV_CODEC_ID_HEVC:
373  stream_type = STREAM_TYPE_VIDEO_HEVC;
374  break;
375  case AV_CODEC_ID_VVC:
376  stream_type = STREAM_TYPE_VIDEO_VVC;
377  break;
378  case AV_CODEC_ID_CAVS:
379  stream_type = STREAM_TYPE_VIDEO_CAVS;
380  break;
381  case AV_CODEC_ID_AVS2:
382  stream_type = STREAM_TYPE_VIDEO_AVS2;
383  break;
384  case AV_CODEC_ID_AVS3:
385  stream_type = STREAM_TYPE_VIDEO_AVS3;
386  break;
387  case AV_CODEC_ID_DIRAC:
388  stream_type = STREAM_TYPE_VIDEO_DIRAC;
389  break;
390  case AV_CODEC_ID_VC1:
391  stream_type = STREAM_TYPE_VIDEO_VC1;
392  break;
393  case AV_CODEC_ID_MP2:
394  case AV_CODEC_ID_MP3:
395  if ( st->codecpar->sample_rate > 0
396  && st->codecpar->sample_rate < 32000) {
397  stream_type = STREAM_TYPE_AUDIO_MPEG2;
398  } else {
399  stream_type = STREAM_TYPE_AUDIO_MPEG1;
400  }
401  break;
402  case AV_CODEC_ID_AAC:
403  stream_type = (ts->flags & MPEGTS_FLAG_AAC_LATM)
406  break;
408  stream_type = STREAM_TYPE_AUDIO_AAC_LATM;
409  break;
410  case AV_CODEC_ID_AC3:
411  stream_type = (ts->flags & MPEGTS_FLAG_SYSTEM_B)
414  break;
415  case AV_CODEC_ID_EAC3:
416  stream_type = (ts->flags & MPEGTS_FLAG_SYSTEM_B)
419  break;
420  case AV_CODEC_ID_DTS:
421  stream_type = STREAM_TYPE_BLURAY_AUDIO_DTS; // should be STREAM_TYPE_PRIVATE_DATA (ETSI TS 101 154), needs a DTS_descriptor() (ETSI EN 300 468)
422  break;
423  case AV_CODEC_ID_TRUEHD:
424  stream_type = STREAM_TYPE_BLURAY_AUDIO_TRUEHD; // should be STREAM_TYPE_PRIVATE_DATA (ETSI TS 101 154), needs a DTS-HD_descriptor() (ETSI EN 300 468)
425  break;
426  case AV_CODEC_ID_OPUS:
427  stream_type = STREAM_TYPE_PRIVATE_DATA;
428  break;
430  stream_type = STREAM_TYPE_METADATA;
431  break;
433  stream_type = STREAM_TYPE_PRIVATE_DATA;
434  break;
438  stream_type = STREAM_TYPE_PRIVATE_DATA;
439  break;
441  if (st->codecpar->profile == AV_PROFILE_KLVA_SYNC) {
442  stream_type = STREAM_TYPE_METADATA;
443  } else {
444  stream_type = STREAM_TYPE_PRIVATE_DATA;
445  }
446  break;
447  default:
449  "Stream %d, codec %s, is muxed as a private data stream "
450  "and may not be recognized upon reading.\n", st->index,
452  stream_type = STREAM_TYPE_PRIVATE_DATA;
453  break;
454  }
455 
456  return stream_type;
457 }
458 
460 {
461  int stream_type;
462  MpegTSWriteStream *ts_st = st->priv_data;
463 
464  switch (st->codecpar->codec_id) {
466  stream_type = STREAM_TYPE_VIDEO_MPEG2;
467  break;
468  case AV_CODEC_ID_H264:
469  stream_type = STREAM_TYPE_VIDEO_H264;
470  break;
471  case AV_CODEC_ID_VC1:
472  stream_type = STREAM_TYPE_VIDEO_VC1;
473  break;
474  case AV_CODEC_ID_HEVC:
475  stream_type = STREAM_TYPE_VIDEO_HEVC;
476  break;
479  break;
480  case AV_CODEC_ID_AC3:
481  stream_type = STREAM_TYPE_BLURAY_AUDIO_AC3;
482  break;
483  case AV_CODEC_ID_DTS:
484  stream_type = (st->codecpar->ch_layout.nb_channels > 6) ?
487  break;
488  case AV_CODEC_ID_TRUEHD:
489  stream_type = STREAM_TYPE_BLURAY_AUDIO_TRUEHD;
490  break;
491  case AV_CODEC_ID_EAC3:
492  stream_type = STREAM_TYPE_BLURAY_AUDIO_EAC3;
493  break;
495  stream_type = STREAM_TYPE_BLURAY_SUBTITLE_PGS;
496  break;
498  stream_type = STREAM_TYPE_BLURAY_SUBTITLE_TEXT;
499  break;
500  default:
502  "Stream %d, codec %s, is muxed as a private data stream "
503  "and may not be recognized upon reading.\n", st->index,
505  stream_type = STREAM_TYPE_PRIVATE_DATA;
506  break;
507  }
508 
509  return stream_type;
510 }
511 
513 {
514  MpegTSWrite *ts = s->priv_data;
515  uint8_t data[SECTION_LENGTH], *q, *desc_length_ptr, *program_info_length_ptr;
516  int val, stream_type, i, err = 0;
517 
518  q = data;
519  put16(&q, 0xe000 | service->pcr_pid);
520 
521  program_info_length_ptr = q;
522  q += 2; /* patched after */
523 
524  /* put program info here */
525  if (ts->m2ts_mode) {
526  put_registration_descriptor(&q, MKTAG('H', 'D', 'M', 'V'));
527  *q++ = 0x88; // descriptor_tag - hdmv_copy_control_descriptor
528  *q++ = 0x04; // descriptor_length
529  put16(&q, 0x0fff); // CA_System_ID
530  *q++ = 0xfc; // private_data_byte
531  *q++ = 0xfc; // private_data_byte
532  }
533 
534  val = 0xf000 | (q - program_info_length_ptr - 2);
535  program_info_length_ptr[0] = val >> 8;
536  program_info_length_ptr[1] = val;
537 
538  for (i = 0; i < s->nb_streams; i++) {
539  AVStream *st = s->streams[i];
540  MpegTSWriteStream *ts_st = st->priv_data;
541  AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL, 0);
542  const char default_language[] = "und";
543  const char *language = lang && strlen(lang->value) >= 3 ? lang->value : default_language;
544  enum AVCodecID codec_id = st->codecpar->codec_id;
545 
546  if (s->nb_programs) {
547  int k, found = 0;
548  AVProgram *program = service->program;
549 
550  for (k = 0; k < program->nb_stream_indexes; k++)
551  if (program->stream_index[k] == i) {
552  found = 1;
553  break;
554  }
555 
556  if (!found)
557  continue;
558  }
559 
560  if (q - data > SECTION_LENGTH - 32) {
561  err = 1;
562  break;
563  }
564 
565  stream_type = ts->m2ts_mode ? get_m2ts_stream_type(s, st) : get_dvb_stream_type(s, st);
566 
567  *q++ = stream_type;
568  put16(&q, 0xe000 | ts_st->pid);
569  desc_length_ptr = q;
570  q += 2; /* patched after */
571 
572  /* write optional descriptors here */
573  switch (st->codecpar->codec_type) {
574  case AVMEDIA_TYPE_AUDIO:
575  if (codec_id == AV_CODEC_ID_AC3)
576  put_registration_descriptor(&q, MKTAG('A', 'C', '-', '3'));
577  if (codec_id == AV_CODEC_ID_EAC3)
578  put_registration_descriptor(&q, MKTAG('E', 'A', 'C', '3'));
579  if (ts->flags & MPEGTS_FLAG_SYSTEM_B) {
580  if (codec_id == AV_CODEC_ID_AC3) {
581  DVBAC3Descriptor *dvb_ac3_desc = ts_st->dvb_ac3_desc;
582 
583  *q++= AC3_DESCRIPTOR; // AC3 descriptor see A038 DVB SI
584  if (dvb_ac3_desc) {
585  int len = 1 +
586  !!(dvb_ac3_desc->component_type_flag) +
587  !!(dvb_ac3_desc->bsid_flag) +
588  !!(dvb_ac3_desc->mainid_flag) +
589  !!(dvb_ac3_desc->asvc_flag);
590 
591  *q++ = len;
592  *q++ = dvb_ac3_desc->component_type_flag << 7 | dvb_ac3_desc->bsid_flag << 6 |
593  dvb_ac3_desc->mainid_flag << 5 | dvb_ac3_desc->asvc_flag << 4;
594 
595  if (dvb_ac3_desc->component_type_flag) *q++ = dvb_ac3_desc->component_type;
596  if (dvb_ac3_desc->bsid_flag) *q++ = dvb_ac3_desc->bsid;
597  if (dvb_ac3_desc->mainid_flag) *q++ = dvb_ac3_desc->mainid;
598  if (dvb_ac3_desc->asvc_flag) *q++ = dvb_ac3_desc->asvc;
599  } else {
600  *q++=1; // 1 byte, all flags sets to 0
601  *q++=0; // omit all fields...
602  }
603  } else if (codec_id == AV_CODEC_ID_EAC3) {
604  *q++= ENHANCED_AC3_DESCRIPTOR; // EAC3 descriptor see A038 DVB SI
605  *q++=1; // 1 byte, all flags sets to 0
606  *q++=0; // omit all fields...
607  }
608  }
610  put_registration_descriptor(&q, MKTAG('B', 'S', 'S', 'D'));
611  if (codec_id == AV_CODEC_ID_OPUS) {
612  int ch = st->codecpar->ch_layout.nb_channels;
613 
614  /* 6 bytes registration descriptor, 4 bytes Opus audio descriptor */
615  if (q - data > SECTION_LENGTH - 6 - 4) {
616  err = 1;
617  break;
618  }
619 
620  put_registration_descriptor(&q, MKTAG('O', 'p', 'u', 's'));
621 
623  *q++ = 2;
624  *q++ = 0x80;
625 
626  if (st->codecpar->extradata && st->codecpar->extradata_size >= 19) {
627  if (st->codecpar->extradata[18] == 0 && ch <= 2) {
628  /* RTP mapping family */
629  *q++ = ch;
630  } else if (st->codecpar->extradata[18] == 1 && ch <= 8 &&
631  st->codecpar->extradata_size >= 21 + ch) {
632  static const uint8_t coupled_stream_counts[9] = {
633  1, 0, 1, 1, 2, 2, 2, 3, 3
634  };
635  static const uint8_t channel_map_a[8][8] = {
636  {0},
637  {0, 1},
638  {0, 2, 1},
639  {0, 1, 2, 3},
640  {0, 4, 1, 2, 3},
641  {0, 4, 1, 2, 3, 5},
642  {0, 4, 1, 2, 3, 5, 6},
643  {0, 6, 1, 2, 3, 4, 5, 7},
644  };
645  static const uint8_t channel_map_b[8][8] = {
646  {0},
647  {0, 1},
648  {0, 1, 2},
649  {0, 1, 2, 3},
650  {0, 1, 2, 3, 4},
651  {0, 1, 2, 3, 4, 5},
652  {0, 1, 2, 3, 4, 5, 6},
653  {0, 1, 2, 3, 4, 5, 6, 7},
654  };
655  /* Vorbis mapping family */
656 
657  if (st->codecpar->extradata[19] == ch - coupled_stream_counts[ch] &&
658  st->codecpar->extradata[20] == coupled_stream_counts[ch] &&
659  memcmp(&st->codecpar->extradata[21], channel_map_a[ch - 1], ch) == 0) {
660  *q++ = ch;
661  } else if (ch >= 2 && st->codecpar->extradata[19] == ch &&
662  st->codecpar->extradata[20] == 0 &&
663  memcmp(&st->codecpar->extradata[21], channel_map_b[ch - 1], ch) == 0) {
664  *q++ = ch | 0x80;
665  } else {
666  /* Unsupported, could write an extended descriptor here */
667  av_log(s, AV_LOG_ERROR, "Unsupported Opus Vorbis-style channel mapping");
668  *q++ = 0xff;
669  }
670  } else {
671  /* Unsupported */
672  av_log(s, AV_LOG_ERROR, "Unsupported Opus channel mapping for family %d", st->codecpar->extradata[18]);
673  *q++ = 0xff;
674  }
675  } else if (ch <= 2) {
676  /* Assume RTP mapping family */
677  *q++ = ch;
678  } else {
679  /* Unsupported */
680  av_log(s, AV_LOG_ERROR, "Unsupported Opus channel mapping");
681  *q++ = 0xff;
682  }
683  }
684 
685  if (language != default_language ||
689  const char *p, *next;
690  uint8_t *len_ptr;
691 
693  len_ptr = q++;
694  *len_ptr = 0;
695 
696  for (p = next = language; next && *len_ptr < 255 / 4 * 4; p = next + 1) {
697  if (q - data > SECTION_LENGTH - 4) {
698  err = 1;
699  break;
700  }
701  next = strchr(p, ',');
702  if (strlen(p) != 3 && (!next || next != p + 3))
703  continue; /* not a 3-letter code */
704 
705  *q++ = *p++;
706  *q++ = *p++;
707  *q++ = *p++;
708 
710  *q++ = 0x01;
712  *q++ = 0x02;
714  *q++ = 0x03;
715  else
716  *q++ = 0; /* undefined type */
717 
718  *len_ptr += 4;
719  }
720 
721  if (*len_ptr == 0)
722  q -= 2; /* no language codes were written */
723  }
724  break;
727  uint8_t *len_ptr;
728  int extradata_copied = 0;
729 
730  *q++ = SUBTITLING_DESCRIPTOR; /* subtitling_descriptor */
731  len_ptr = q++;
732 
733  while (strlen(language) >= 3) {
734  if (sizeof(data) - (q - data) < 8) { /* 8 bytes per DVB subtitle substream data */
735  err = 1;
736  break;
737  }
738  *q++ = *language++;
739  *q++ = *language++;
740  *q++ = *language++;
741  /* Skip comma */
742  if (*language != '\0')
743  language++;
744 
745  if (st->codecpar->extradata_size - extradata_copied >= 5) {
746  *q++ = st->codecpar->extradata[extradata_copied + 4]; /* subtitling_type */
747  memcpy(q, st->codecpar->extradata + extradata_copied, 4); /* composition_page_id and ancillary_page_id */
748  extradata_copied += 5;
749  q += 4;
750  } else {
751  /* subtitling_type:
752  * 0x10 - normal with no monitor aspect ratio criticality
753  * 0x20 - for the hard of hearing with no monitor aspect ratio criticality */
754  *q++ = (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED) ? 0x20 : 0x10;
755  if ((st->codecpar->extradata_size == 4) && (extradata_copied == 0)) {
756  /* support of old 4-byte extradata format */
757  memcpy(q, st->codecpar->extradata, 4); /* composition_page_id and ancillary_page_id */
758  extradata_copied += 4;
759  q += 4;
760  } else {
761  put16(&q, 1); /* composition_page_id */
762  put16(&q, 1); /* ancillary_page_id */
763  }
764  }
765  }
766 
767  *len_ptr = q - len_ptr - 1;
768  } else if (codec_id == AV_CODEC_ID_DVB_TELETEXT) {
769  uint8_t *len_ptr = NULL;
770  int extradata_copied = 0;
771 
772  /* The descriptor tag. teletext_descriptor */
773  *q++ = TELETEXT_DESCRIPTOR;
774  len_ptr = q++;
775 
776  while (strlen(language) >= 3 && q - data < sizeof(data) - 6) {
777  *q++ = *language++;
778  *q++ = *language++;
779  *q++ = *language++;
780  /* Skip comma */
781  if (*language != '\0')
782  language++;
783 
784  if (st->codecpar->extradata_size - 1 > extradata_copied) {
785  memcpy(q, st->codecpar->extradata + extradata_copied, 2);
786  extradata_copied += 2;
787  q += 2;
788  } else {
789  /* The Teletext descriptor:
790  * teletext_type: This 5-bit field indicates the type of Teletext page indicated. (0x01 Initial Teletext page)
791  * teletext_magazine_number: This is a 3-bit field which identifies the magazine number.
792  * teletext_page_number: This is an 8-bit field giving two 4-bit hex digits identifying the page number. */
793  *q++ = 0x08;
794  *q++ = 0x00;
795  }
796  }
797 
798  *len_ptr = q - len_ptr - 1;
799  } else if (codec_id == AV_CODEC_ID_ARIB_CAPTION) {
800  if (put_arib_caption_descriptor(s, &q, st->codecpar) < 0)
801  break;
802  }
803  break;
804  case AVMEDIA_TYPE_VIDEO:
805  if (stream_type == STREAM_TYPE_VIDEO_DIRAC) {
806  put_registration_descriptor(&q, MKTAG('d', 'r', 'a', 'c'));
807  } else if (stream_type == STREAM_TYPE_VIDEO_VC1) {
808  put_registration_descriptor(&q, MKTAG('V', 'C', '-', '1'));
809  } else if (stream_type == STREAM_TYPE_VIDEO_HEVC && s->strict_std_compliance <= FF_COMPLIANCE_NORMAL) {
810  put_registration_descriptor(&q, MKTAG('H', 'E', 'V', 'C'));
811  } else if (stream_type == STREAM_TYPE_VIDEO_CAVS || stream_type == STREAM_TYPE_VIDEO_AVS2 ||
812  stream_type == STREAM_TYPE_VIDEO_AVS3) {
813  put_registration_descriptor(&q, MKTAG('A', 'V', 'S', 'V'));
814  }
815  break;
816  case AVMEDIA_TYPE_DATA:
818  put_registration_descriptor(&q, MKTAG('K', 'L', 'V', 'A'));
819  } else if (codec_id == AV_CODEC_ID_SMPTE_2038) {
820  put_registration_descriptor(&q, MKTAG('V', 'A', 'N', 'C'));
821  } else if (codec_id == AV_CODEC_ID_TIMED_ID3) {
822  const char *tag = "ID3 ";
823  *q++ = METADATA_DESCRIPTOR;
824  *q++ = 13;
825  put16(&q, 0xffff); /* metadata application format */
826  putbuf(&q, tag, strlen(tag));
827  *q++ = 0xff; /* metadata format */
828  putbuf(&q, tag, strlen(tag));
829  *q++ = 0; /* metadata service ID */
830  *q++ = 0xF; /* metadata_locator_record_flag|MPEG_carriage_flags|reserved */
831  }
832  break;
833  }
834 
835  val = 0xf000 | (q - desc_length_ptr - 2);
836  desc_length_ptr[0] = val >> 8;
837  desc_length_ptr[1] = val;
838  }
839 
840  if (err)
842  "The PMT section cannot fit stream %d and all following streams.\n"
843  "Try reducing the number of languages in the audio streams "
844  "or the total number of streams.\n", i);
845 
846  mpegts_write_section1(&service->pmt, PMT_TID, service->sid, ts->tables_version, 0, 0,
847  data, q - data);
848  return 0;
849 }
850 
852 {
853  MpegTSWrite *ts = s->priv_data;
854  MpegTSService *service;
855  uint8_t data[SECTION_LENGTH], *q, *desc_list_len_ptr, *desc_len_ptr;
856  int i, running_status, free_ca_mode, val;
857 
858  q = data;
859  put16(&q, ts->original_network_id);
860  *q++ = 0xff;
861  for (i = 0; i < ts->nb_services; i++) {
862  service = ts->services[i];
863  put16(&q, service->sid);
864  *q++ = 0xfc | 0x00; /* currently no EIT info */
865  desc_list_len_ptr = q;
866  q += 2;
867  running_status = 4; /* running */
868  free_ca_mode = 0;
869 
870  /* write only one descriptor for the service name and provider */
871  *q++ = SERVICE_DESCRIPTOR;
872  desc_len_ptr = q;
873  q++;
874  *q++ = ts->service_type;
875  putbuf(&q, service->provider_name, service->provider_name[0] + 1);
876  putbuf(&q, service->name, service->name[0] + 1);
877  desc_len_ptr[0] = q - desc_len_ptr - 1;
878 
879  /* fill descriptor length */
880  val = (running_status << 13) | (free_ca_mode << 12) |
881  (q - desc_list_len_ptr - 2);
882  desc_list_len_ptr[0] = val >> 8;
883  desc_list_len_ptr[1] = val;
884  }
886  data, q - data);
887 }
888 
890 {
891  MpegTSWrite *ts = s->priv_data;
892  uint8_t data[SECTION_LENGTH], *q, *desc_len_ptr, *loop_len_ptr;
893 
894  q = data;
895 
896  //network_descriptors_length
897  put16(&q, 0xf000 | (ts->provider_name[0] + 2));
898 
899  //network_name_descriptor
901  putbuf(&q, ts->provider_name, ts->provider_name[0] + 1);
902 
903  //transport_stream_loop_length
904  loop_len_ptr = q;
905  q += 2;
906 
907  put16(&q, ts->transport_stream_id);
908  put16(&q, ts->original_network_id);
909 
910  //transport_descriptors_length
911  desc_len_ptr = q;
912  q += 2;
913 
914  //service_list_descriptor
916  *q++ = 3 * ts->nb_services;
917  for (int i = 0; i < ts->nb_services; i++) {
918  put16(&q, ts->services[i]->sid);
919  *q++ = ts->service_type;
920  }
921 
922  //calculate lengths
923  put16(&desc_len_ptr, 0xf000 | q - (desc_len_ptr + 2));
924  put16(&loop_len_ptr, 0xf000 | q - (loop_len_ptr + 2));
925 
927  data, q - data);
928 }
929 
930 /* This stores a string in buf with the correct encoding and also sets the
931  * first byte as the length. !str is accepted for an empty string.
932  * If the string is already encoded, invalid UTF-8 or has no multibyte sequence
933  * then we keep it as is, otherwise we signal UTF-8 encoding. */
934 static int encode_str8(uint8_t *buf, const char *str)
935 {
936  size_t str_len;
937  if (!str)
938  str = "";
939  str_len = strlen(str);
940  if (str[0] && (unsigned)str[0] >= 0x20) { /* Make sure the string is not already encoded. */
941  const uint8_t *q = str;
942  int has_multibyte = 0;
943  while (*q) {
944  uint32_t code;
945  GET_UTF8(code, *q++, goto invalid;) /* Is it valid UTF-8? */
946  has_multibyte |= (code > 127); /* Does it have multibyte UTF-8 chars in it? */
947  }
948  if (has_multibyte) { /* If we have multibyte chars and valid UTF-8, then encode as such! */
949  if (str_len > 254)
950  return AVERROR(EINVAL);
951  buf[0] = str_len + 1;
952  buf[1] = 0x15;
953  memcpy(&buf[2], str, str_len);
954  return 0;
955  }
956  }
957 invalid:
958  /* Otherwise let's just encode the string as is! */
959  if (str_len > 255)
960  return AVERROR(EINVAL);
961  buf[0] = str_len;
962  memcpy(&buf[1], str, str_len);
963  return 0;
964 }
965 
966 static int64_t get_pcr(const MpegTSWrite *ts)
967 {
968  return av_rescale(ts->total_size + 11, 8 * PCR_TIME_BASE, ts->mux_rate) +
969  ts->first_pcr;
970 }
971 
972 static void write_packet(AVFormatContext *s, const uint8_t *packet)
973 {
974  MpegTSWrite *ts = s->priv_data;
975  if (ts->m2ts_mode) {
976  int64_t pcr = get_pcr(s->priv_data);
977  uint32_t tp_extra_header = pcr % 0x3fffffff;
978  tp_extra_header = AV_RB32(&tp_extra_header);
979  avio_write(s->pb, (unsigned char *) &tp_extra_header,
980  sizeof(tp_extra_header));
981  }
982  avio_write(s->pb, packet, TS_PACKET_SIZE);
983  ts->total_size += TS_PACKET_SIZE;
984 }
985 
986 static void section_write_packet(MpegTSSection *s, const uint8_t *packet)
987 {
988  AVFormatContext *ctx = s->opaque;
989  write_packet(ctx, packet);
990 }
991 
993  const AVDictionary *metadata,
995 {
996  MpegTSWrite *ts = s->priv_data;
997  MpegTSService *service;
998  AVDictionaryEntry *title, *provider;
999  char default_service_name[32];
1000  const char *service_name;
1001  const char *provider_name;
1002 
1003  title = av_dict_get(metadata, "service_name", NULL, 0);
1004  if (!title)
1005  title = av_dict_get(metadata, "title", NULL, 0);
1006  snprintf(default_service_name, sizeof(default_service_name), "%s%02d", DEFAULT_SERVICE_NAME, ts->nb_services + 1);
1007  service_name = title ? title->value : default_service_name;
1008  provider = av_dict_get(metadata, "service_provider", NULL, 0);
1009  provider_name = provider ? provider->value : DEFAULT_PROVIDER_NAME;
1010 
1011  service = av_mallocz(sizeof(MpegTSService));
1012  if (!service)
1013  return NULL;
1014  service->pmt.pid = ts->pmt_start_pid + ts->nb_services;
1015  service->sid = sid;
1016  service->pcr_pid = 0x1fff;
1017  if (encode_str8(service->provider_name, provider_name) < 0 ||
1018  encode_str8(service->name, service_name) < 0) {
1019  av_log(s, AV_LOG_ERROR, "Too long service or provider name\n");
1020  goto fail;
1021  }
1022  ts->sdt.remaining -= 10 + service->provider_name[0] + service->name[0];
1023  if (ts->sdt.remaining < 0)
1024  goto fail;
1025 
1026  if (av_dynarray_add_nofree(&ts->services, &ts->nb_services, service) < 0)
1027  goto fail;
1028 
1030  service->pmt.opaque = s;
1031  service->pmt.cc = 15;
1032  service->pmt.discontinuity= ts->flags & MPEGTS_FLAG_DISCONT;
1033  service->program = program;
1034 
1035  return service;
1036 fail:
1037  av_free(service);
1038  return NULL;
1039 }
1040 
1042 {
1043  MpegTSWrite *ts = s->priv_data;
1044  MpegTSWriteStream *ts_st = pcr_st->priv_data;
1045 
1046  if (ts->mux_rate > 1 || ts->pcr_period_ms >= 0) {
1047  int pcr_period_ms = ts->pcr_period_ms == -1 ? PCR_RETRANS_TIME : ts->pcr_period_ms;
1048  ts_st->pcr_period = av_rescale(pcr_period_ms, PCR_TIME_BASE, 1000);
1049  } else {
1050  /* By default, for VBR we select the highest multiple of frame duration which is less than 100 ms. */
1051  int64_t frame_period = 0;
1052  if (pcr_st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
1054  if (!frame_size) {
1055  av_log(s, AV_LOG_WARNING, "frame size not set\n");
1056  frame_size = 512;
1057  }
1059  } else if (pcr_st->avg_frame_rate.num) {
1060  frame_period = av_rescale_rnd(pcr_st->avg_frame_rate.den, PCR_TIME_BASE, pcr_st->avg_frame_rate.num, AV_ROUND_UP);
1061  }
1062  if (frame_period > 0 && frame_period <= PCR_TIME_BASE / 10)
1063  ts_st->pcr_period = frame_period * (PCR_TIME_BASE / 10 / frame_period);
1064  else
1065  ts_st->pcr_period = 1;
1066  }
1067 
1068  // output a PCR as soon as possible
1069  ts_st->last_pcr = ts->first_pcr - ts_st->pcr_period;
1070 }
1071 
1073 {
1074  MpegTSWrite *ts = s->priv_data;
1075 
1076  for (int i = 0; i < ts->nb_services; i++) {
1077  MpegTSService *service = ts->services[i];
1078  AVStream *pcr_st = NULL;
1079  AVProgram *program = service->program;
1080  int nb_streams = program ? program->nb_stream_indexes : s->nb_streams;
1081 
1082  for (int j = 0; j < nb_streams; j++) {
1083  AVStream *st = s->streams[program ? program->stream_index[j] : j];
1084  if (!pcr_st ||
1086  {
1087  pcr_st = st;
1088  }
1089  }
1090 
1091  if (pcr_st) {
1092  MpegTSWriteStream *ts_st = pcr_st->priv_data;
1093  service->pcr_pid = ts_st->pid;
1095  av_log(s, AV_LOG_VERBOSE, "service %i using PCR in pid=%i, pcr_period=%"PRId64"ms\n",
1096  service->sid, service->pcr_pid, av_rescale(ts_st->pcr_period, 1000, PCR_TIME_BASE));
1097  }
1098  }
1099 }
1100 
1102 {
1103  MpegTSWrite *ts = s->priv_data;
1104  AVDictionaryEntry *provider;
1105  const char *provider_name;
1106  int i, j;
1107  int ret;
1108 
1109  if (ts->m2ts_mode == -1) {
1110  if (av_match_ext(s->url, "m2ts")) {
1111  ts->m2ts_mode = 1;
1112  } else {
1113  ts->m2ts_mode = 0;
1114  }
1115  }
1116 
1121 
1122  if (ts->m2ts_mode) {
1124  if (s->nb_programs > 1) {
1125  av_log(s, AV_LOG_ERROR, "Only one program is allowed in m2ts mode!\n");
1126  return AVERROR(EINVAL);
1127  }
1128  }
1129 
1130  if (s->max_delay < 0) /* Not set by the caller */
1131  s->max_delay = 0;
1132 
1133  // round up to a whole number of TS packets
1134  ts->pes_payload_size = (ts->pes_payload_size + 14 + 183) / 184 * 184 - 14;
1135 
1136  ts->sdt.remaining = SECTION_LENGTH - 3;
1137 
1138  if (!s->nb_programs) {
1139  /* allocate a single DVB service */
1140  if (!mpegts_add_service(s, ts->service_id, s->metadata, NULL))
1141  return AVERROR(ENOMEM);
1142  } else {
1143  for (i = 0; i < s->nb_programs; i++) {
1144  AVProgram *program = s->programs[i];
1145  if (!mpegts_add_service(s, program->id, program->metadata, program))
1146  return AVERROR(ENOMEM);
1147  }
1148  }
1149 
1150  ts->pat.pid = PAT_PID;
1151  /* Initialize at 15 so that it wraps and is equal to 0 for the
1152  * first packet we write. */
1153  ts->pat.cc = 15;
1156  ts->pat.opaque = s;
1157 
1158  ts->sdt.pid = SDT_PID;
1159  ts->sdt.cc = 15;
1162  ts->sdt.opaque = s;
1163 
1164  ts->nit.pid = NIT_PID;
1165  ts->nit.cc = 15;
1168  ts->nit.opaque = s;
1169 
1170  ts->pkt = ffformatcontext(s)->pkt;
1171 
1172  /* assign pids to each stream */
1173  for (i = 0; i < s->nb_streams; i++) {
1174  AVStream *st = s->streams[i];
1175  MpegTSWriteStream *ts_st;
1176 
1177  ts_st = av_mallocz(sizeof(MpegTSWriteStream));
1178  if (!ts_st) {
1179  return AVERROR(ENOMEM);
1180  }
1181  st->priv_data = ts_st;
1182 
1183  avpriv_set_pts_info(st, 33, 1, 90000);
1184 
1185  ts_st->payload = av_mallocz(ts->pes_payload_size);
1186  if (!ts_st->payload) {
1187  return AVERROR(ENOMEM);
1188  }
1189 
1190  /* MPEG pid values < 16 are reserved. Applications which set st->id in
1191  * this range are assigned a calculated pid. */
1192  if (st->id < 16) {
1193  if (ts->m2ts_mode) {
1194  switch (st->codecpar->codec_type) {
1195  case AVMEDIA_TYPE_VIDEO:
1196  ts_st->pid = ts->m2ts_video_pid++;
1197  break;
1198  case AVMEDIA_TYPE_AUDIO:
1199  ts_st->pid = ts->m2ts_audio_pid++;
1200  break;
1201  case AVMEDIA_TYPE_SUBTITLE:
1202  switch (st->codecpar->codec_id) {
1204  ts_st->pid = ts->m2ts_pgssub_pid++;
1205  break;
1207  ts_st->pid = ts->m2ts_textsub_pid++;
1208  break;
1209  }
1210  break;
1211  }
1212  if (ts->m2ts_video_pid > M2TS_VIDEO_PID + 1 ||
1213  ts->m2ts_audio_pid > M2TS_AUDIO_START_PID + 32 ||
1215  ts->m2ts_textsub_pid > M2TS_TEXTSUB_PID + 1 ||
1216  ts_st->pid < 16) {
1217  av_log(s, AV_LOG_ERROR, "Cannot automatically assign PID for stream %d\n", st->index);
1218  return AVERROR(EINVAL);
1219  }
1220  } else {
1221  ts_st->pid = ts->start_pid + i;
1222  }
1223  } else {
1224  ts_st->pid = st->id;
1225  }
1226  if (ts_st->pid >= 0x1FFF) {
1228  "Invalid stream id %d, must be less than 8191\n", st->id);
1229  return AVERROR(EINVAL);
1230  }
1231  for (j = 0; j < ts->nb_services; j++) {
1232  if (ts->services[j]->pmt.pid > LAST_OTHER_PID) {
1234  "Invalid PMT PID %d, must be less than %d\n", ts->services[j]->pmt.pid, LAST_OTHER_PID + 1);
1235  return AVERROR(EINVAL);
1236  }
1237  if (ts_st->pid == ts->services[j]->pmt.pid) {
1238  av_log(s, AV_LOG_ERROR, "PID %d cannot be both elementary and PMT PID\n", ts_st->pid);
1239  return AVERROR(EINVAL);
1240  }
1241  }
1242  for (j = 0; j < i; j++) {
1243  MpegTSWriteStream *ts_st_prev = s->streams[j]->priv_data;
1244  if (ts_st_prev->pid == ts_st->pid) {
1245  av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
1246  return AVERROR(EINVAL);
1247  }
1248  }
1249  ts_st->payload_pts = AV_NOPTS_VALUE;
1250  ts_st->payload_dts = AV_NOPTS_VALUE;
1251  ts_st->cc = 15;
1252  ts_st->discontinuity = ts->flags & MPEGTS_FLAG_DISCONT;
1253  if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
1254  st->codecpar->extradata_size > 0) {
1255  AVStream *ast;
1256  ts_st->amux = avformat_alloc_context();
1257  if (!ts_st->amux) {
1258  return AVERROR(ENOMEM);
1259  }
1260  ts_st->amux->oformat =
1261  av_guess_format((ts->flags & MPEGTS_FLAG_AAC_LATM) ? "latm" : "adts",
1262  NULL, NULL);
1263  if (!ts_st->amux->oformat) {
1264  return AVERROR(EINVAL);
1265  }
1266  if (!(ast = avformat_new_stream(ts_st->amux, NULL))) {
1267  return AVERROR(ENOMEM);
1268  }
1270  if (ret != 0)
1271  return ret;
1272  ast->time_base = st->time_base;
1273  ret = avformat_write_header(ts_st->amux, NULL);
1274  if (ret < 0)
1275  return ret;
1276  }
1277  if (st->codecpar->codec_id == AV_CODEC_ID_OPUS) {
1279  }
1280  }
1281 
1282  if (ts->copyts < 1)
1283  ts->first_pcr = av_rescale(s->max_delay, PCR_TIME_BASE, AV_TIME_BASE);
1284 
1286 
1293 
1294  /* assign provider name */
1295  provider = av_dict_get(s->metadata, "service_provider", NULL, 0);
1296  provider_name = provider ? provider->value : DEFAULT_PROVIDER_NAME;
1297  if (encode_str8(ts->provider_name, provider_name) < 0) {
1298  av_log(s, AV_LOG_ERROR, "Too long provider name\n");
1299  return AVERROR(EINVAL);
1300  }
1301 
1302  if (ts->mux_rate == 1)
1303  av_log(s, AV_LOG_VERBOSE, "muxrate VBR, ");
1304  else
1305  av_log(s, AV_LOG_VERBOSE, "muxrate %d, ", ts->mux_rate);
1307  "sdt every %"PRId64" ms, pat/pmt every %"PRId64" ms",
1308  av_rescale(ts->sdt_period, 1000, PCR_TIME_BASE),
1309  av_rescale(ts->pat_period, 1000, PCR_TIME_BASE));
1310  if (ts->flags & MPEGTS_FLAG_NIT)
1311  av_log(s, AV_LOG_VERBOSE, ", nit every %"PRId64" ms", av_rescale(ts->nit_period, 1000, PCR_TIME_BASE));
1312  av_log(s, AV_LOG_VERBOSE, "\n");
1313 
1314  return 0;
1315 }
1316 
1317 /* send SDT, NIT, PAT and PMT tables regularly */
1318 static void retransmit_si_info(AVFormatContext *s, int force_pat, int force_sdt, int force_nit, int64_t pcr)
1319 {
1320  MpegTSWrite *ts = s->priv_data;
1321  int i;
1322 
1323  if ((pcr != AV_NOPTS_VALUE && ts->last_sdt_ts == AV_NOPTS_VALUE) ||
1324  (pcr != AV_NOPTS_VALUE && pcr - ts->last_sdt_ts >= ts->sdt_period) ||
1325  force_sdt
1326  ) {
1327  if (pcr != AV_NOPTS_VALUE)
1328  ts->last_sdt_ts = FFMAX(pcr, ts->last_sdt_ts);
1330  }
1331  if ((pcr != AV_NOPTS_VALUE && ts->last_pat_ts == AV_NOPTS_VALUE) ||
1332  (pcr != AV_NOPTS_VALUE && pcr - ts->last_pat_ts >= ts->pat_period) ||
1333  force_pat) {
1334  if (pcr != AV_NOPTS_VALUE)
1335  ts->last_pat_ts = FFMAX(pcr, ts->last_pat_ts);
1337  for (i = 0; i < ts->nb_services; i++)
1338  mpegts_write_pmt(s, ts->services[i]);
1339  }
1340  if ((pcr != AV_NOPTS_VALUE && ts->last_nit_ts == AV_NOPTS_VALUE) ||
1341  (pcr != AV_NOPTS_VALUE && pcr - ts->last_nit_ts >= ts->nit_period) ||
1342  force_nit
1343  ) {
1344  if (pcr != AV_NOPTS_VALUE)
1345  ts->last_nit_ts = FFMAX(pcr, ts->last_nit_ts);
1346  if (ts->flags & MPEGTS_FLAG_NIT)
1348  }
1349 }
1350 
1351 static int write_pcr_bits(uint8_t *buf, int64_t pcr)
1352 {
1353  int64_t pcr_low = pcr % SYSTEM_CLOCK_FREQUENCY_DIVISOR, pcr_high = pcr / SYSTEM_CLOCK_FREQUENCY_DIVISOR;
1354 
1355  *buf++ = pcr_high >> 25;
1356  *buf++ = pcr_high >> 17;
1357  *buf++ = pcr_high >> 9;
1358  *buf++ = pcr_high >> 1;
1359  *buf++ = pcr_high << 7 | pcr_low >> 8 | 0x7e;
1360  *buf++ = pcr_low;
1361 
1362  return 6;
1363 }
1364 
1365 /* Write a single null transport stream packet */
1367 {
1368  uint8_t *q;
1369  uint8_t buf[TS_PACKET_SIZE];
1370 
1371  q = buf;
1372  *q++ = SYNC_BYTE;
1373  *q++ = 0x00 | (NULL_PID >> 8);
1374  *q++ = NULL_PID & 0xff;
1375  *q++ = 0x10;
1376  memset(q, STUFFING_BYTE, TS_PACKET_SIZE - (q - buf)); /* data_bytes may be assigned any value */
1377  write_packet(s, buf);
1378 }
1379 
1380 /* Write a single transport stream packet with a PCR and no payload */
1382 {
1383  MpegTSWrite *ts = s->priv_data;
1384  MpegTSWriteStream *ts_st = st->priv_data;
1385  uint8_t *q;
1386  uint8_t buf[TS_PACKET_SIZE];
1387 
1388  q = buf;
1389  *q++ = SYNC_BYTE;
1390  *q++ = ts_st->pid >> 8;
1391  *q++ = ts_st->pid;
1392  *q++ = 0x20 | ts_st->cc; /* Adaptation only */
1393  /* Continuity Count field does not increment (see 13818-1 section 2.4.3.3) */
1394  *q++ = TS_PACKET_SIZE - 5; /* Adaptation Field Length */
1395  *q++ = 0x10; /* Adaptation flags: PCR present */
1396  if (ts_st->discontinuity) {
1397  q[-1] |= 0x80;
1398  ts_st->discontinuity = 0;
1399  }
1400 
1401  /* PCR coded into 6 bytes */
1402  q += write_pcr_bits(q, get_pcr(ts));
1403 
1404  /* stuffing bytes */
1405  memset(q, STUFFING_BYTE, TS_PACKET_SIZE - (q - buf));
1406  write_packet(s, buf);
1407 }
1408 
1409 static void write_pts(uint8_t *q, int fourbits, int64_t pts)
1410 {
1411  int val;
1412 
1413  val = fourbits << 4 | (((pts >> 30) & 0x07) << 1) | 1;
1414  *q++ = val;
1415  val = (((pts >> 15) & 0x7fff) << 1) | 1;
1416  *q++ = val >> 8;
1417  *q++ = val;
1418  val = (((pts) & 0x7fff) << 1) | 1;
1419  *q++ = val >> 8;
1420  *q++ = val;
1421 }
1422 
1423 /* Set an adaptation field flag in an MPEG-TS packet*/
1424 static void set_af_flag(uint8_t *pkt, int flag)
1425 {
1426  // expect at least one flag to set
1427  av_assert0(flag);
1428 
1429  if ((pkt[3] & 0x20) == 0) {
1430  // no AF yet, set adaptation field flag
1431  pkt[3] |= 0x20;
1432  // 1 byte length, no flags
1433  pkt[4] = 1;
1434  pkt[5] = 0;
1435  }
1436  pkt[5] |= flag;
1437 }
1438 
1439 /* Extend the adaptation field by size bytes */
1440 static void extend_af(uint8_t *pkt, int size)
1441 {
1442  // expect already existing adaptation field
1443  av_assert0(pkt[3] & 0x20);
1444  pkt[4] += size;
1445 }
1446 
1447 /* Get a pointer to MPEG-TS payload (right after TS packet header) */
1448 static uint8_t *get_ts_payload_start(uint8_t *pkt)
1449 {
1450  if (pkt[3] & 0x20)
1451  return pkt + 5 + pkt[4];
1452  else
1453  return pkt + 4;
1454 }
1455 
1456 static int get_pes_stream_id(AVFormatContext *s, AVStream *st, int stream_id, int *async)
1457 {
1458  MpegTSWrite *ts = s->priv_data;
1459  *async = 0;
1460  if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
1461  if (st->codecpar->codec_id == AV_CODEC_ID_DIRAC)
1463  else
1464  return STREAM_ID_VIDEO_STREAM_0;
1465  } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
1466  (st->codecpar->codec_id == AV_CODEC_ID_MP2 ||
1467  st->codecpar->codec_id == AV_CODEC_ID_MP3 ||
1468  st->codecpar->codec_id == AV_CODEC_ID_AAC)) {
1469  return STREAM_ID_AUDIO_STREAM_0;
1470  } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
1471  st->codecpar->codec_id == AV_CODEC_ID_AC3 &&
1472  ts->m2ts_mode) {
1474  } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA &&
1477  } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
1478  if (st->codecpar->codec_id == AV_CODEC_ID_SMPTE_KLV &&
1479  stream_id == STREAM_ID_PRIVATE_STREAM_1) /* asynchronous KLV */
1480  *async = 1;
1481  return stream_id != -1 ? stream_id : STREAM_ID_METADATA_STREAM;
1482  } else {
1484  }
1485 }
1486 
1487 /* Add a PES header to the front of the payload, and segment into an integer
1488  * number of TS packets. The final TS packet is padded using an oversized
1489  * adaptation header to exactly fill the last TS packet.
1490  * NOTE: 'payload' contains a complete PES payload. */
1492  const uint8_t *payload, int payload_size,
1493  int64_t pts, int64_t dts, int key, int stream_id)
1494 {
1495  MpegTSWriteStream *ts_st = st->priv_data;
1496  MpegTSWrite *ts = s->priv_data;
1497  uint8_t buf[TS_PACKET_SIZE];
1498  uint8_t *q;
1499  int val, is_start, len, header_len, write_pcr, flags;
1500  int afc_len, stuffing_len;
1501  int is_dvb_subtitle = (st->codecpar->codec_id == AV_CODEC_ID_DVB_SUBTITLE);
1502  int is_dvb_teletext = (st->codecpar->codec_id == AV_CODEC_ID_DVB_TELETEXT);
1503  int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE);
1504  int force_pat = st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && key && !ts_st->prev_payload_key;
1505  int force_sdt = 0;
1506  int force_nit = 0;
1507 
1508  av_assert0(ts_st->payload != buf || st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO);
1510  force_pat = 1;
1511  }
1512 
1513  if (ts->flags & MPEGTS_FLAG_REEMIT_PAT_PMT) {
1514  force_pat = 1;
1515  force_sdt = 1;
1516  force_nit = 1;
1518  }
1519 
1520  is_start = 1;
1521  while (payload_size > 0) {
1522  int64_t pcr = AV_NOPTS_VALUE;
1523  if (ts->mux_rate > 1)
1524  pcr = get_pcr(ts);
1525  else if (dts != AV_NOPTS_VALUE)
1526  pcr = (dts - delay) * SYSTEM_CLOCK_FREQUENCY_DIVISOR;
1527 
1528  retransmit_si_info(s, force_pat, force_sdt, force_nit, pcr);
1529  force_pat = 0;
1530  force_sdt = 0;
1531  force_nit = 0;
1532 
1533  write_pcr = 0;
1534  if (ts->mux_rate > 1) {
1535  /* Send PCR packets for all PCR streams if needed */
1536  pcr = get_pcr(ts);
1537  if (pcr >= ts->next_pcr) {
1538  int64_t next_pcr = INT64_MAX;
1539  for (int i = 0; i < s->nb_streams; i++) {
1540  /* Make the current stream the last, because for that we
1541  * can insert the pcr into the payload later */
1542  int st2_index = i < st->index ? i : (i + 1 == s->nb_streams ? st->index : i + 1);
1543  AVStream *st2 = s->streams[st2_index];
1544  MpegTSWriteStream *ts_st2 = st2->priv_data;
1545  if (ts_st2->pcr_period) {
1546  if (pcr - ts_st2->last_pcr >= ts_st2->pcr_period) {
1547  ts_st2->last_pcr = FFMAX(pcr - ts_st2->pcr_period, ts_st2->last_pcr + ts_st2->pcr_period);
1548  if (st2 != st) {
1549  mpegts_insert_pcr_only(s, st2);
1550  pcr = get_pcr(ts);
1551  } else {
1552  write_pcr = 1;
1553  }
1554  }
1555  next_pcr = FFMIN(next_pcr, ts_st2->last_pcr + ts_st2->pcr_period);
1556  }
1557  }
1558  ts->next_pcr = next_pcr;
1559  }
1560  if (dts != AV_NOPTS_VALUE && (dts - pcr / SYSTEM_CLOCK_FREQUENCY_DIVISOR) > delay) {
1561  /* pcr insert gets priority over null packet insert */
1562  if (write_pcr)
1564  else
1566  /* recalculate write_pcr and possibly retransmit si_info */
1567  continue;
1568  }
1569  } else if (ts_st->pcr_period && pcr != AV_NOPTS_VALUE) {
1570  if (pcr - ts_st->last_pcr >= ts_st->pcr_period && is_start) {
1571  ts_st->last_pcr = FFMAX(pcr - ts_st->pcr_period, ts_st->last_pcr + ts_st->pcr_period);
1572  write_pcr = 1;
1573  }
1574  }
1575 
1576  /* prepare packet header */
1577  q = buf;
1578  *q++ = SYNC_BYTE;
1579  val = ts_st->pid >> 8;
1580  if (ts->m2ts_mode && st->codecpar->codec_id == AV_CODEC_ID_AC3)
1581  val |= 0x20;
1582  if (is_start)
1583  val |= 0x40;
1584  *q++ = val;
1585  *q++ = ts_st->pid;
1586  ts_st->cc = ts_st->cc + 1 & 0xf;
1587  *q++ = 0x10 | ts_st->cc; // payload indicator + CC
1588  if (ts_st->discontinuity) {
1589  set_af_flag(buf, 0x80);
1590  q = get_ts_payload_start(buf);
1591  ts_st->discontinuity = 0;
1592  }
1593  if (!(ts->flags & MPEGTS_FLAG_OMIT_RAI) &&
1594  key && is_start && pts != AV_NOPTS_VALUE &&
1595  !is_dvb_teletext /* adaptation+payload forbidden for teletext (ETSI EN 300 472 V1.3.1 4.1) */) {
1596  // set Random Access for key frames
1597  if (ts_st->pcr_period)
1598  write_pcr = 1;
1599  set_af_flag(buf, 0x40);
1600  q = get_ts_payload_start(buf);
1601  }
1602  if (write_pcr) {
1603  set_af_flag(buf, 0x10);
1604  q = get_ts_payload_start(buf);
1605  // add 11, pcr references the last byte of program clock reference base
1606  if (dts != AV_NOPTS_VALUE && dts < pcr / SYSTEM_CLOCK_FREQUENCY_DIVISOR)
1607  av_log(s, AV_LOG_WARNING, "dts < pcr, TS is invalid\n");
1608  extend_af(buf, write_pcr_bits(q, pcr));
1609  q = get_ts_payload_start(buf);
1610  }
1611  if (is_start) {
1612  int pes_extension = 0;
1613  int pes_header_stuffing_bytes = 0;
1614  int async;
1615  /* write PES header */
1616  *q++ = 0x00;
1617  *q++ = 0x00;
1618  *q++ = 0x01;
1619  *q++ = stream_id = get_pes_stream_id(s, st, stream_id, &async);
1620  if (async)
1621  pts = dts = AV_NOPTS_VALUE;
1622 
1623  header_len = 0;
1624 
1625  if (stream_id != STREAM_ID_PROGRAM_STREAM_MAP &&
1626  stream_id != STREAM_ID_PADDING_STREAM &&
1627  stream_id != STREAM_ID_PRIVATE_STREAM_2 &&
1628  stream_id != STREAM_ID_ECM_STREAM &&
1629  stream_id != STREAM_ID_EMM_STREAM &&
1630  stream_id != STREAM_ID_PROGRAM_STREAM_DIRECTORY &&
1631  stream_id != STREAM_ID_DSMCC_STREAM &&
1632  stream_id != STREAM_ID_TYPE_E_STREAM) {
1633 
1634  flags = 0;
1635  if (pts != AV_NOPTS_VALUE) {
1636  header_len += 5;
1637  flags |= 0x80;
1638  }
1639  if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
1640  header_len += 5;
1641  flags |= 0x40;
1642  }
1643  if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
1645  /* set PES_extension_flag */
1646  pes_extension = 1;
1647  flags |= 0x01;
1648 
1649  /* One byte for PES2 extension flag +
1650  * one byte for extension length +
1651  * one byte for extension id */
1652  header_len += 3;
1653  }
1654  /* for Blu-ray AC3 Audio the PES Extension flag should be as follow
1655  * otherwise it will not play sound on blu-ray
1656  */
1657  if (ts->m2ts_mode &&
1659  st->codecpar->codec_id == AV_CODEC_ID_AC3) {
1660  /* set PES_extension_flag */
1661  pes_extension = 1;
1662  flags |= 0x01;
1663  header_len += 3;
1664  }
1665  if (is_dvb_teletext) {
1666  pes_header_stuffing_bytes = 0x24 - header_len;
1667  header_len = 0x24;
1668  }
1669  len = payload_size + header_len + 3;
1670  /* 3 extra bytes should be added to DVB subtitle payload: 0x20 0x00 at the beginning and trailing 0xff */
1671  if (is_dvb_subtitle) {
1672  len += 3;
1673  payload_size++;
1674  }
1675  if (len > 0xffff)
1676  len = 0;
1678  len = 0;
1679  }
1680  *q++ = len >> 8;
1681  *q++ = len;
1682  val = 0x80;
1683  /* data alignment indicator is required for subtitle and data streams */
1685  val |= 0x04;
1686  *q++ = val;
1687  *q++ = flags;
1688  *q++ = header_len;
1689  if (pts != AV_NOPTS_VALUE) {
1690  write_pts(q, flags >> 6, pts);
1691  q += 5;
1692  }
1693  if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
1694  write_pts(q, 1, dts);
1695  q += 5;
1696  }
1697  if (pes_extension && st->codecpar->codec_id == AV_CODEC_ID_DIRAC) {
1698  flags = 0x01; /* set PES_extension_flag_2 */
1699  *q++ = flags;
1700  *q++ = 0x80 | 0x01; /* marker bit + extension length */
1701  /* Set the stream ID extension flag bit to 0 and
1702  * write the extended stream ID. */
1703  *q++ = 0x00 | 0x60;
1704  }
1705  /* For Blu-ray AC3 Audio Setting extended flags */
1706  if (ts->m2ts_mode &&
1707  pes_extension &&
1708  st->codecpar->codec_id == AV_CODEC_ID_AC3) {
1709  flags = 0x01; /* set PES_extension_flag_2 */
1710  *q++ = flags;
1711  *q++ = 0x80 | 0x01; /* marker bit + extension length */
1712  *q++ = 0x00 | 0x71; /* for AC3 Audio (specifically on blue-rays) */
1713  }
1714 
1715 
1716  if (is_dvb_subtitle) {
1717  /* First two fields of DVB subtitles PES data:
1718  * data_identifier: for DVB subtitle streams shall be coded with the value 0x20
1719  * subtitle_stream_id: for DVB subtitle stream shall be identified by the value 0x00 */
1720  *q++ = 0x20;
1721  *q++ = 0x00;
1722  }
1723  if (is_dvb_teletext) {
1724  memset(q, STUFFING_BYTE, pes_header_stuffing_bytes);
1725  q += pes_header_stuffing_bytes;
1726  }
1727  } else {
1728  len = payload_size;
1729  *q++ = len >> 8;
1730  *q++ = len;
1731  }
1732  is_start = 0;
1733  }
1734  /* header size */
1735  header_len = q - buf;
1736  /* data len */
1737  len = TS_PACKET_SIZE - header_len;
1738  if (len > payload_size)
1739  len = payload_size;
1740  stuffing_len = TS_PACKET_SIZE - header_len - len;
1741  if (stuffing_len > 0) {
1742  /* add stuffing with AFC */
1743  if (buf[3] & 0x20) {
1744  /* stuffing already present: increase its size */
1745  afc_len = buf[4] + 1;
1746  memmove(buf + 4 + afc_len + stuffing_len,
1747  buf + 4 + afc_len,
1748  header_len - (4 + afc_len));
1749  buf[4] += stuffing_len;
1750  memset(buf + 4 + afc_len, STUFFING_BYTE, stuffing_len);
1751  } else {
1752  /* add stuffing */
1753  memmove(buf + 4 + stuffing_len, buf + 4, header_len - 4);
1754  buf[3] |= 0x20;
1755  buf[4] = stuffing_len - 1;
1756  if (stuffing_len >= 2) {
1757  buf[5] = 0x00;
1758  memset(buf + 6, STUFFING_BYTE, stuffing_len - 2);
1759  }
1760  }
1761  }
1762 
1763  if (is_dvb_subtitle && payload_size == len) {
1764  memcpy(buf + TS_PACKET_SIZE - len, payload, len - 1);
1765  buf[TS_PACKET_SIZE - 1] = 0xff; /* end_of_PES_data_field_marker: an 8-bit field with fixed contents 0xff for DVB subtitle */
1766  } else {
1767  memcpy(buf + TS_PACKET_SIZE - len, payload, len);
1768  }
1769 
1770  payload += len;
1771  payload_size -= len;
1772  write_packet(s, buf);
1773  }
1774  ts_st->prev_payload_key = key;
1775 }
1776 
1777 static int check_h26x_startcode(AVFormatContext *s, const AVStream *st, const AVPacket *pkt, const char *codec)
1778 {
1779  if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001 && AV_RB24(pkt->data) != 0x000001) {
1780  if (!st->nb_frames) {
1781  av_log(s, AV_LOG_ERROR, "%s bitstream malformed, "
1782  "no startcode found, use the video bitstream filter '%s_mp4toannexb' to fix it "
1783  "('-bsf:v %s_mp4toannexb' option with ffmpeg)\n", codec, codec, codec);
1784  return AVERROR_INVALIDDATA;
1785  }
1786  av_log(s, AV_LOG_WARNING, "%s bitstream error, startcode missing, size %d", codec, pkt->size);
1787  if (pkt->size)
1788  av_log(s, AV_LOG_WARNING, " data %08"PRIX32, AV_RB32(pkt->data));
1789  av_log(s, AV_LOG_WARNING, "\n");
1790  }
1791  return 0;
1792 }
1793 
1795 {
1796  return check_h26x_startcode(s, st, pkt, "h264");
1797 }
1798 
1799 /* Based on GStreamer's gst-plugins-base/ext/ogg/gstoggstream.c
1800  * Released under the LGPL v2.1+, written by
1801  * Vincent Penquerc'h <vincent.penquerch@collabora.co.uk>
1802  */
1804 {
1805  static const int durations[32] = {
1806  480, 960, 1920, 2880, /* Silk NB */
1807  480, 960, 1920, 2880, /* Silk MB */
1808  480, 960, 1920, 2880, /* Silk WB */
1809  480, 960, /* Hybrid SWB */
1810  480, 960, /* Hybrid FB */
1811  120, 240, 480, 960, /* CELT NB */
1812  120, 240, 480, 960, /* CELT NB */
1813  120, 240, 480, 960, /* CELT NB */
1814  120, 240, 480, 960, /* CELT NB */
1815  };
1816  int toc, frame_duration, nframes, duration;
1817 
1818  if (pkt->size < 1)
1819  return 0;
1820 
1821  toc = pkt->data[0];
1822 
1823  frame_duration = durations[toc >> 3];
1824  switch (toc & 3) {
1825  case 0:
1826  nframes = 1;
1827  break;
1828  case 1:
1829  nframes = 2;
1830  break;
1831  case 2:
1832  nframes = 2;
1833  break;
1834  case 3:
1835  if (pkt->size < 2)
1836  return 0;
1837  nframes = pkt->data[1] & 63;
1838  break;
1839  }
1840 
1841  duration = nframes * frame_duration;
1842  if (duration > 5760) {
1844  "Opus packet duration > 120 ms, invalid");
1845  return 0;
1846  }
1847 
1848  return duration;
1849 }
1850 
1851 static uint8_t *h26x_prefix_aud(const uint8_t *aud, const int aud_size,
1852  const uint8_t *extra_data, const int extra_size, AVPacket *pkt, int *size)
1853 {
1854  const int sz = 4; //start code size
1855  uint8_t *data = av_malloc(pkt->size + sz + aud_size + extra_size);
1856  if (!data)
1857  return NULL;
1858  AV_WB32(data, 0x00000001);
1859  memcpy(data + sz, aud, aud_size);
1860  memcpy(data + sz + aud_size, extra_data, extra_size);
1861  memcpy(data + sz + aud_size + extra_size, pkt->data, pkt->size);
1862  *size = pkt->size + sz + aud_size + extra_size;
1863  return data;
1864 }
1865 
1866 #define H264_NAL_TYPE(state) (state & 0x1f)
1867 #define HEVC_NAL_TYPE(state) ((state & 0x7e) >> 1)
1868 #define VVC_NAL_TYPE(state) ((state >> 11) & 0x1f)
1870 {
1871  AVStream *st = s->streams[pkt->stream_index];
1872  int size = pkt->size;
1873  const uint8_t *buf = pkt->data;
1874  uint8_t *data = NULL;
1875  MpegTSWrite *ts = s->priv_data;
1876  MpegTSWriteStream *ts_st = st->priv_data;
1877  const int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE) * 2;
1878  const int64_t max_audio_delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE) / 2;
1879  int64_t dts = pkt->dts, pts = pkt->pts;
1880  int opus_samples = 0;
1881  size_t side_data_size;
1882  uint8_t *side_data = NULL;
1883  int stream_id = -1;
1884 
1885  side_data = av_packet_get_side_data(pkt,
1887  &side_data_size);
1888  if (side_data)
1889  stream_id = side_data[0];
1890 
1891  if (!ts->first_dts_checked && dts != AV_NOPTS_VALUE) {
1893  ts->first_dts_checked = 1;
1894  }
1895 
1896  if (ts->copyts < 1) {
1897  if (pts != AV_NOPTS_VALUE)
1898  pts += delay;
1899  if (dts != AV_NOPTS_VALUE)
1900  dts += delay;
1901  }
1902 
1903  if (!ts_st->first_timestamp_checked && (pts == AV_NOPTS_VALUE || dts == AV_NOPTS_VALUE)) {
1904  av_log(s, AV_LOG_ERROR, "first pts and dts value must be set\n");
1905  return AVERROR_INVALIDDATA;
1906  }
1907  ts_st->first_timestamp_checked = 1;
1908 
1909  if (st->codecpar->codec_id == AV_CODEC_ID_H264) {
1910  const uint8_t *p = buf, *buf_end = p + size;
1911  const uint8_t *found_aud = NULL, *found_aud_end = NULL;
1912  int nal_type;
1913  uint32_t state = -1;
1914  int extradd = (pkt->flags & AV_PKT_FLAG_KEY) ? st->codecpar->extradata_size : 0;
1915  int ret = ff_check_h264_startcode(s, st, pkt);
1916  if (ret < 0)
1917  return ret;
1918 
1919  if (extradd && AV_RB24(st->codecpar->extradata) > 1)
1920  extradd = 0;
1921 
1922  /* Ensure that all pictures are prefixed with an AUD, and that
1923  * IDR pictures are also prefixed with SPS and PPS. SPS and PPS
1924  * are assumed to be available in 'extradata' if not found in-band. */
1925  do {
1926  p = avpriv_find_start_code(p, buf_end, &state);
1927  nal_type = H264_NAL_TYPE(state);
1928  av_log(s, AV_LOG_TRACE, "nal %"PRId32"\n", nal_type);
1929  if (nal_type == H264_NAL_SPS)
1930  extradd = 0;
1931  if (nal_type == H264_NAL_AUD) {
1932  found_aud = p - 4; // start of the 0x000001 start code.
1933  found_aud_end = p + 1; // first byte past the AUD.
1934  if (found_aud < buf)
1935  found_aud = buf;
1936  if (buf_end < found_aud_end)
1937  found_aud_end = buf_end;
1938  }
1939  } while (p < buf_end
1940  && nal_type != H264_NAL_IDR_SLICE
1941  && nal_type != H264_NAL_SLICE
1942  && (extradd > 0 || !found_aud));
1943  if (nal_type != H264_NAL_IDR_SLICE)
1944  extradd = 0;
1945 
1946  if (!found_aud) {
1947  /* Prefix 'buf' with the missing AUD, and extradata if needed. */
1948  const uint8_t aud[] = {
1949  H264_NAL_AUD,
1950  0xf0, // any slice type (0xe) + rbsp stop one bit
1951  };
1953  st->codecpar->extradata, extradd, pkt, &size);
1954  if (!data)
1955  return AVERROR(ENOMEM);
1956  } else if (extradd != 0) {
1957  /* Move the AUD up to the beginning of the frame, where the H.264
1958  * spec requires it to appear. Emit the extradata after it. */
1959  PutByteContext pb;
1960  const int new_pkt_size = pkt->size + 1 + extradd;
1961  data = av_malloc(new_pkt_size);
1962  if (!data)
1963  return AVERROR(ENOMEM);
1964  bytestream2_init_writer(&pb, data, new_pkt_size);
1965  bytestream2_put_byte(&pb, 0x00);
1966  bytestream2_put_buffer(&pb, found_aud, found_aud_end - found_aud);
1967  bytestream2_put_buffer(&pb, st->codecpar->extradata, extradd);
1968  bytestream2_put_buffer(&pb, pkt->data, found_aud - pkt->data);
1969  bytestream2_put_buffer(&pb, found_aud_end, buf_end - found_aud_end);
1970  av_assert0(new_pkt_size == bytestream2_tell_p(&pb));
1971  buf = data;
1972  size = new_pkt_size;
1973  }
1974  } else if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
1975  if (pkt->size < 2) {
1976  av_log(s, AV_LOG_ERROR, "AAC packet too short\n");
1977  return AVERROR_INVALIDDATA;
1978  }
1979  if ((AV_RB16(pkt->data) & 0xfff0) != 0xfff0) {
1980  int ret;
1981  AVPacket *pkt2 = ts->pkt;
1982 
1983  if (!ts_st->amux) {
1984  av_log(s, AV_LOG_ERROR, "AAC bitstream not in ADTS format "
1985  "and extradata missing\n");
1986  } else {
1987  av_packet_unref(pkt2);
1988  pkt2->data = pkt->data;
1989  pkt2->size = pkt->size;
1991  pkt2->dts = av_rescale_q(pkt->dts, st->time_base, ts_st->amux->streams[0]->time_base);
1992 
1993  ret = avio_open_dyn_buf(&ts_st->amux->pb);
1994  if (ret < 0)
1995  return ret;
1996 
1997  ret = av_write_frame(ts_st->amux, pkt2);
1998  if (ret < 0) {
1999  ffio_free_dyn_buf(&ts_st->amux->pb);
2000  return ret;
2001  }
2002  size = avio_close_dyn_buf(ts_st->amux->pb, &data);
2003  ts_st->amux->pb = NULL;
2004  buf = data;
2005  }
2006  }
2007  } else if (st->codecpar->codec_id == AV_CODEC_ID_HEVC) {
2008  const uint8_t *p = buf, *buf_end = p + size;
2009  uint32_t state = -1;
2010  int nal_type;
2011  int extradd = (pkt->flags & AV_PKT_FLAG_KEY) ? st->codecpar->extradata_size : 0;
2012  int ret = check_h26x_startcode(s, st, pkt, "hevc");
2013  if (ret < 0)
2014  return ret;
2015 
2016  if (extradd && AV_RB24(st->codecpar->extradata) > 1)
2017  extradd = 0;
2018 
2019  do {
2020  p = avpriv_find_start_code(p, buf_end, &state);
2021  nal_type = HEVC_NAL_TYPE(state);
2022  av_log(s, AV_LOG_TRACE, "nal %"PRId32"\n", nal_type);
2023  if (nal_type == HEVC_NAL_VPS)
2024  extradd = 0;
2025  } while (p < buf_end && nal_type != HEVC_NAL_AUD && nal_type >= HEVC_NAL_VPS);
2026 
2027  if (nal_type < HEVC_NAL_BLA_W_LP || nal_type >= HEVC_NAL_RSV_VCL24)
2028  extradd = 0;
2029  if (nal_type != HEVC_NAL_AUD) { // AUD NAL
2030  const uint8_t aud[] = {
2031  (HEVC_NAL_AUD << 1),
2032  0x01,
2033  0x50, // any slice type (0x4) + rbsp stop one bit
2034  };
2036  st->codecpar->extradata, extradd, pkt, &size);
2037  if (!data)
2038  return AVERROR(ENOMEM);
2039  }
2040  } else if (st->codecpar->codec_id == AV_CODEC_ID_VVC) {
2041  const uint8_t *p = buf, *buf_end = p + size;
2042  uint32_t state = -1;
2043  uint32_t nal_type = -1;
2044  int extradd = (pkt->flags & AV_PKT_FLAG_KEY) ? st->codecpar->extradata_size : 0;
2045  int ret = check_h26x_startcode(s, st, pkt, "vvc");
2046  if (ret < 0)
2047  return ret;
2048 
2049  if (extradd && AV_RB24(st->codecpar->extradata) > 1)
2050  extradd = 0;
2051 
2052  do {
2053  p = avpriv_find_start_code(p, buf_end, &state);
2054  // state contains byte behind start code, p points 2 bytes behind start code
2055  nal_type = VVC_NAL_TYPE(state);
2056  av_log(s, AV_LOG_TRACE, "nal %"PRId32"\n", nal_type );
2057  if (nal_type == VVC_VPS_NUT)
2058  extradd = 0;
2059  } while (p < buf_end && nal_type != VVC_AUD_NUT && nal_type >= VVC_OPI_NUT);
2060 
2061  if (nal_type >= VVC_OPI_NUT)
2062  extradd = 0;
2063  if (nal_type != VVC_AUD_NUT) { // AUD NAL
2064  const uint8_t aud[] = {
2065  0, // forbidden_zero_bit, nuh_reserved_zero_bit, nuh_layer_id
2066  (VVC_AUD_NUT << 3) | 1, // nal_unit_type, nuh_temporal_id_plus1(1)
2067  (pkt->flags & AV_PKT_FLAG_KEY) << 7 | 0x28, // aud_irap_or_gdr_flag, aud_pic_type(2), rbsp_stop_one_bit
2068  };
2069  buf = data = h26x_prefix_aud(aud, FF_ARRAY_ELEMS(aud), st->codecpar->extradata, extradd, pkt, &size);
2070  if (!data)
2071  return AVERROR(ENOMEM);
2072  }
2073  } else if (st->codecpar->codec_id == AV_CODEC_ID_OPUS) {
2074  if (pkt->size < 2) {
2075  av_log(s, AV_LOG_ERROR, "Opus packet too short\n");
2076  return AVERROR_INVALIDDATA;
2077  }
2078 
2079  /* Add Opus control header */
2080  if ((AV_RB16(pkt->data) >> 5) != 0x3ff) {
2081  uint8_t *side_data;
2082  size_t side_data_size;
2083  int i, n;
2084  int ctrl_header_size;
2085  int trim_start = 0, trim_end = 0;
2086 
2087  opus_samples = opus_get_packet_samples(s, pkt);
2088 
2089  side_data = av_packet_get_side_data(pkt,
2091  &side_data_size);
2092 
2093  if (side_data && side_data_size >= 10) {
2094  trim_end = AV_RL32(side_data + 4) * 48000 / st->codecpar->sample_rate;
2095  }
2096 
2097  ctrl_header_size = pkt->size + 2 + pkt->size / 255 + 1;
2098  if (ts_st->opus_pending_trim_start)
2099  ctrl_header_size += 2;
2100  if (trim_end)
2101  ctrl_header_size += 2;
2102 
2103  data = av_malloc(ctrl_header_size);
2104  if (!data)
2105  return AVERROR(ENOMEM);
2106 
2107  data[0] = 0x7f;
2108  data[1] = 0xe0;
2109  if (ts_st->opus_pending_trim_start)
2110  data[1] |= 0x10;
2111  if (trim_end)
2112  data[1] |= 0x08;
2113 
2114  n = pkt->size;
2115  i = 2;
2116  do {
2117  data[i] = FFMIN(n, 255);
2118  n -= 255;
2119  i++;
2120  } while (n >= 0);
2121 
2122  av_assert0(2 + pkt->size / 255 + 1 == i);
2123 
2124  if (ts_st->opus_pending_trim_start) {
2125  trim_start = FFMIN(ts_st->opus_pending_trim_start, opus_samples);
2126  AV_WB16(data + i, trim_start);
2127  i += 2;
2128  ts_st->opus_pending_trim_start -= trim_start;
2129  }
2130  if (trim_end) {
2131  trim_end = FFMIN(trim_end, opus_samples - trim_start);
2132  AV_WB16(data + i, trim_end);
2133  i += 2;
2134  }
2135 
2136  memcpy(data + i, pkt->data, pkt->size);
2137  buf = data;
2138  size = ctrl_header_size;
2139  } else {
2140  /* TODO: Can we get TS formatted data here? If so we will
2141  * need to count the samples of that too! */
2142  av_log(s, AV_LOG_WARNING, "Got MPEG-TS formatted Opus data, unhandled");
2143  }
2144  } else if (st->codecpar->codec_id == AV_CODEC_ID_AC3 && !ts_st->dvb_ac3_desc) {
2145  AC3HeaderInfo *hdr = NULL;
2146 
2147  if (avpriv_ac3_parse_header(&hdr, pkt->data, pkt->size) >= 0) {
2148  uint8_t number_of_channels_flag;
2149  uint8_t service_type_flag;
2150  uint8_t full_service_flag = 1;
2151  DVBAC3Descriptor *dvb_ac3_desc;
2152 
2153  dvb_ac3_desc = av_mallocz(sizeof(*dvb_ac3_desc));
2154  if (!dvb_ac3_desc) {
2155  av_free(hdr);
2156  return AVERROR(ENOMEM);
2157  }
2158 
2159  service_type_flag = hdr->bitstream_mode;
2160  switch (hdr->channel_mode) {
2161  case AC3_CHMODE_DUALMONO:
2162  number_of_channels_flag = 1;
2163  break;
2164  case AC3_CHMODE_MONO:
2165  number_of_channels_flag = 0;
2166  break;
2167  case AC3_CHMODE_STEREO:
2168  if (hdr->dolby_surround_mode == AC3_DSURMOD_ON)
2169  number_of_channels_flag = 3;
2170  else
2171  number_of_channels_flag = 2;
2172  break;
2173  case AC3_CHMODE_3F:
2174  case AC3_CHMODE_2F1R:
2175  case AC3_CHMODE_3F1R:
2176  case AC3_CHMODE_2F2R:
2177  case AC3_CHMODE_3F2R:
2178  number_of_channels_flag = 4;
2179  break;
2180  default: /* reserved */
2181  number_of_channels_flag = 7;
2182  break;
2183  }
2184 
2185  if (service_type_flag == 1 || service_type_flag == 4 ||
2186  (service_type_flag == 7 && !number_of_channels_flag))
2187  full_service_flag = 0;
2188 
2189  dvb_ac3_desc->component_type_flag = 1;
2190  dvb_ac3_desc->component_type = (full_service_flag << 6) |
2191  ((service_type_flag & 0x7) << 3) |
2192  (number_of_channels_flag & 0x7);
2193  dvb_ac3_desc->bsid_flag = 1;
2194  dvb_ac3_desc->bsid = hdr->bitstream_id;
2195  dvb_ac3_desc->mainid_flag = 0;
2196  dvb_ac3_desc->asvc_flag = 0;
2197 
2198  ts_st->dvb_ac3_desc = dvb_ac3_desc;
2199  }
2200  av_free(hdr);
2201  } else if (st->codecpar->codec_id == AV_CODEC_ID_PCM_BLURAY && ts->m2ts_mode) {
2202  mpegts_write_pes(s, st, buf, size, pts, dts,
2203  pkt->flags & AV_PKT_FLAG_KEY, stream_id);
2204  return 0;
2205  }
2206 
2207  if (ts_st->payload_size && (ts_st->payload_size + size > ts->pes_payload_size ||
2208  (dts != AV_NOPTS_VALUE && ts_st->payload_dts != AV_NOPTS_VALUE &&
2209  dts - ts_st->payload_dts >= max_audio_delay) ||
2210  ts_st->opus_queued_samples + opus_samples >= 5760 /* 120ms */)) {
2211  mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_size,
2212  ts_st->payload_pts, ts_st->payload_dts,
2213  ts_st->payload_flags & AV_PKT_FLAG_KEY, stream_id);
2214  ts_st->payload_size = 0;
2215  ts_st->opus_queued_samples = 0;
2216  }
2217 
2219  av_assert0(!ts_st->payload_size);
2220  // for video and subtitle, write a single pes packet
2221  mpegts_write_pes(s, st, buf, size, pts, dts,
2222  pkt->flags & AV_PKT_FLAG_KEY, stream_id);
2223  ts_st->opus_queued_samples = 0;
2224  av_free(data);
2225  return 0;
2226  }
2227 
2228  if (!ts_st->payload_size) {
2229  ts_st->payload_pts = pts;
2230  ts_st->payload_dts = dts;
2231  ts_st->payload_flags = pkt->flags;
2232  }
2233 
2234  memcpy(ts_st->payload + ts_st->payload_size, buf, size);
2235  ts_st->payload_size += size;
2236  ts_st->opus_queued_samples += opus_samples;
2237 
2238  av_free(data);
2239 
2240  return 0;
2241 }
2242 
2244 {
2245  MpegTSWrite *ts = s->priv_data;
2246  int i;
2247 
2248  /* flush current packets */
2249  for (i = 0; i < s->nb_streams; i++) {
2250  AVStream *st = s->streams[i];
2251  MpegTSWriteStream *ts_st = st->priv_data;
2252  if (ts_st->payload_size > 0) {
2253  mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_size,
2254  ts_st->payload_pts, ts_st->payload_dts,
2255  ts_st->payload_flags & AV_PKT_FLAG_KEY, -1);
2256  ts_st->payload_size = 0;
2257  ts_st->opus_queued_samples = 0;
2258  }
2259  }
2260 
2261  if (ts->m2ts_mode) {
2262  int packets = (avio_tell(s->pb) / (TS_PACKET_SIZE + 4)) % 32;
2263  while (packets++ < 32)
2265  }
2266 }
2267 
2269 {
2270  if (!pkt) {
2272  return 1;
2273  } else {
2275  }
2276 }
2277 
2279 {
2280  if (s->pb)
2282 
2283  return 0;
2284 }
2285 
2287 {
2288  MpegTSWrite *ts = s->priv_data;
2289  MpegTSService *service;
2290  int i;
2291 
2292  for (i = 0; i < s->nb_streams; i++) {
2293  AVStream *st = s->streams[i];
2294  MpegTSWriteStream *ts_st = st->priv_data;
2295  if (ts_st) {
2296  av_freep(&ts_st->dvb_ac3_desc);
2297  av_freep(&ts_st->payload);
2298  if (ts_st->amux) {
2299  avformat_free_context(ts_st->amux);
2300  ts_st->amux = NULL;
2301  }
2302  }
2303  }
2304 
2305  for (i = 0; i < ts->nb_services; i++) {
2306  service = ts->services[i];
2307  av_freep(&service);
2308  }
2309  av_freep(&ts->services);
2310 }
2311 
2313  const AVPacket *pkt)
2314 {
2315  const struct Entry {
2316  enum AVCodecID id;
2317  const char *bsf_name;
2318  uint8_t mask;
2319  uint8_t value;
2320  } list[] = {
2321  { AV_CODEC_ID_H264, "h264_mp4toannexb", 0xff, 0x01 /* configurationVersion in AVCDecoderConfigurationRecord */},
2322  { AV_CODEC_ID_HEVC, "hevc_mp4toannexb", 0xff, 0x01 /* configurationVersion in HEVCDecoderConfigurationRecord */},
2323  { AV_CODEC_ID_VVC, "vvc_mp4toannexb", 0xf8, 0xf8 /* reserved '11111'b in VVCDecoderConfigurationRecord */},
2324  };
2325 
2326  for (int i = 0; i < FF_ARRAY_ELEMS(list); i++) {
2327  const struct Entry *e = list + i;
2328  if (e->id == st->codecpar->codec_id &&
2329  pkt->size >= 5 && AV_RB32(pkt->data) != 0x0000001 &&
2330  (AV_RB24(pkt->data) != 0x000001 ||
2331  (st->codecpar->extradata_size > 0 &&
2332  ((st->codecpar->extradata[0] & e->mask) == e->value))))
2333  return ff_stream_add_bitstream_filter(st, e->bsf_name, NULL);
2334  }
2335  return 1;
2336 }
2337 
2338 #define OFFSET(x) offsetof(MpegTSWrite, x)
2339 #define ENC AV_OPT_FLAG_ENCODING_PARAM
2340 static const AVOption options[] = {
2341  { "mpegts_transport_stream_id", "Set transport_stream_id field.",
2342  OFFSET(transport_stream_id), AV_OPT_TYPE_INT, { .i64 = 0x0001 }, 0x0001, 0xffff, ENC },
2343  { "mpegts_original_network_id", "Set original_network_id field.",
2344  OFFSET(original_network_id), AV_OPT_TYPE_INT, { .i64 = DVB_PRIVATE_NETWORK_START }, 0x0001, 0xffff, ENC },
2345  { "mpegts_service_id", "Set service_id field.",
2346  OFFSET(service_id), AV_OPT_TYPE_INT, { .i64 = 0x0001 }, 0x0001, 0xffff, ENC },
2347  { "mpegts_service_type", "Set service_type field.",
2348  OFFSET(service_type), AV_OPT_TYPE_INT, { .i64 = 0x01 }, 0x01, 0xff, ENC, .unit = "mpegts_service_type" },
2349  { "digital_tv", "Digital Television.",
2350  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_DIGITAL_TV }, 0x01, 0xff, ENC, .unit = "mpegts_service_type" },
2351  { "digital_radio", "Digital Radio.",
2352  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_DIGITAL_RADIO }, 0x01, 0xff, ENC, .unit = "mpegts_service_type" },
2353  { "teletext", "Teletext.",
2354  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_TELETEXT }, 0x01, 0xff, ENC, .unit = "mpegts_service_type" },
2355  { "advanced_codec_digital_radio", "Advanced Codec Digital Radio.",
2356  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_ADVANCED_CODEC_DIGITAL_RADIO }, 0x01, 0xff, ENC, .unit = "mpegts_service_type" },
2357  { "mpeg2_digital_hdtv", "MPEG2 Digital HDTV.",
2358  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_MPEG2_DIGITAL_HDTV }, 0x01, 0xff, ENC, .unit = "mpegts_service_type" },
2359  { "advanced_codec_digital_sdtv", "Advanced Codec Digital SDTV.",
2360  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_ADVANCED_CODEC_DIGITAL_SDTV }, 0x01, 0xff, ENC, .unit = "mpegts_service_type" },
2361  { "advanced_codec_digital_hdtv", "Advanced Codec Digital HDTV.",
2362  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_ADVANCED_CODEC_DIGITAL_HDTV }, 0x01, 0xff, ENC, .unit = "mpegts_service_type" },
2363  { "hevc_digital_hdtv", "HEVC Digital Television Service.",
2364  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_HEVC_DIGITAL_HDTV }, 0x01, 0xff, ENC, .unit = "mpegts_service_type" },
2365  { "mpegts_pmt_start_pid", "Set the first pid of the PMT.",
2366  OFFSET(pmt_start_pid), AV_OPT_TYPE_INT, { .i64 = 0x1000 }, FIRST_OTHER_PID, LAST_OTHER_PID, ENC },
2367  { "mpegts_start_pid", "Set the first pid.",
2368  OFFSET(start_pid), AV_OPT_TYPE_INT, { .i64 = 0x0100 }, FIRST_OTHER_PID, LAST_OTHER_PID, ENC },
2369  { "mpegts_m2ts_mode", "Enable m2ts mode.", OFFSET(m2ts_mode), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, ENC },
2370  { "muxrate", NULL, OFFSET(mux_rate), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, INT_MAX, ENC },
2371  { "pes_payload_size", "Minimum PES packet payload in bytes",
2372  OFFSET(pes_payload_size), AV_OPT_TYPE_INT, { .i64 = DEFAULT_PES_PAYLOAD_SIZE }, 0, INT_MAX, ENC },
2373  { "mpegts_flags", "MPEG-TS muxing flags", OFFSET(flags), AV_OPT_TYPE_FLAGS, { .i64 = 0 }, 0, INT_MAX, ENC, .unit = "mpegts_flags" },
2374  { "resend_headers", "Reemit PAT/PMT before writing the next packet",
2375  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_FLAG_REEMIT_PAT_PMT }, 0, INT_MAX, ENC, .unit = "mpegts_flags" },
2376  { "latm", "Use LATM packetization for AAC",
2377  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_FLAG_AAC_LATM }, 0, INT_MAX, ENC, .unit = "mpegts_flags" },
2378  { "pat_pmt_at_frames", "Reemit PAT and PMT at each video frame",
2379  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_FLAG_PAT_PMT_AT_FRAMES}, 0, INT_MAX, ENC, .unit = "mpegts_flags" },
2380  { "system_b", "Conform to System B (DVB) instead of System A (ATSC)",
2381  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_FLAG_SYSTEM_B }, 0, INT_MAX, ENC, .unit = "mpegts_flags" },
2382  { "initial_discontinuity", "Mark initial packets as discontinuous",
2383  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_FLAG_DISCONT }, 0, INT_MAX, ENC, .unit = "mpegts_flags" },
2384  { "nit", "Enable NIT transmission",
2385  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_FLAG_NIT}, 0, INT_MAX, ENC, .unit = "mpegts_flags" },
2386  { "omit_rai", "Disable writing of random access indicator",
2387  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_FLAG_OMIT_RAI }, 0, INT_MAX, ENC, .unit = "mpegts_flags" },
2388  { "mpegts_copyts", "don't offset dts/pts", OFFSET(copyts), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, ENC },
2389  { "tables_version", "set PAT, PMT, SDT and NIT version", OFFSET(tables_version), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 31, ENC },
2390  { "omit_video_pes_length", "Omit the PES packet length for video packets",
2391  OFFSET(omit_video_pes_length), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, ENC },
2392  { "pcr_period", "PCR retransmission time in milliseconds",
2393  OFFSET(pcr_period_ms), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, ENC },
2394  { "pat_period", "PAT/PMT retransmission time limit in seconds",
2395  OFFSET(pat_period_us), AV_OPT_TYPE_DURATION, { .i64 = PAT_RETRANS_TIME * 1000LL }, 0, INT64_MAX, ENC },
2396  { "sdt_period", "SDT retransmission time limit in seconds",
2397  OFFSET(sdt_period_us), AV_OPT_TYPE_DURATION, { .i64 = SDT_RETRANS_TIME * 1000LL }, 0, INT64_MAX, ENC },
2398  { "nit_period", "NIT retransmission time limit in seconds",
2399  OFFSET(nit_period_us), AV_OPT_TYPE_DURATION, { .i64 = NIT_RETRANS_TIME * 1000LL }, 0, INT64_MAX, ENC },
2400  { NULL },
2401 };
2402 
2403 static const AVClass mpegts_muxer_class = {
2404  .class_name = "MPEGTS muxer",
2405  .item_name = av_default_item_name,
2406  .option = options,
2407  .version = LIBAVUTIL_VERSION_INT,
2408 };
2409 
2411  .p.name = "mpegts",
2412  .p.long_name = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
2413  .p.mime_type = "video/MP2T",
2414  .p.extensions = "ts,m2t,m2ts,mts",
2415  .priv_data_size = sizeof(MpegTSWrite),
2416  .p.audio_codec = AV_CODEC_ID_MP2,
2417  .p.video_codec = AV_CODEC_ID_MPEG2VIDEO,
2418  .init = mpegts_init,
2419  .write_packet = mpegts_write_packet,
2420  .write_trailer = mpegts_write_end,
2421  .deinit = mpegts_deinit,
2422  .check_bitstream = mpegts_check_bitstream,
2424  .flags_internal = FF_OFMT_FLAG_ALLOW_FLUSH,
2425  .p.priv_class = &mpegts_muxer_class,
2426 };
HEVC_NAL_AUD
@ HEVC_NAL_AUD
Definition: hevc.h:64
flags
const SwsFlags flags[]
Definition: swscale.c:61
AC3_CHMODE_3F
@ AC3_CHMODE_3F
Definition: ac3defs.h:71
av_packet_unref
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition: packet.c:432
AV_ROUND_UP
@ AV_ROUND_UP
Round toward +infinity.
Definition: mathematics.h:134
DEFAULT_PROVIDER_NAME
#define DEFAULT_PROVIDER_NAME
Definition: mpegtsenc.c:239
AVMEDIA_TYPE_SUBTITLE
@ AVMEDIA_TYPE_SUBTITLE
Definition: avutil.h:203
AV_LOG_WARNING
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:216
MpegTSService::pcr_pid
int pcr_pid
Definition: mpegtsenc.c:68
AV_PROFILE_KLVA_SYNC
#define AV_PROFILE_KLVA_SYNC
Definition: defs.h:194
AVCodecParameters::extradata
uint8_t * extradata
Extra binary data needed for initializing the decoder, codec-dependent.
Definition: codec_par.h:69
AV_CODEC_ID_AC3
@ AV_CODEC_ID_AC3
Definition: codec_id.h:463
program
Undefined Behavior In the C some operations are like signed integer dereferencing freed accessing outside allocated Undefined Behavior must not occur in a C program
Definition: undefined.txt:6
MpegTSWrite::last_sdt_ts
int64_t last_sdt_ts
Definition: mpegtsenc.c:129
AC3HeaderInfo::dolby_surround_mode
int dolby_surround_mode
Definition: ac3_parser_internal.h:52
AVOutputFormat::name
const char * name
Definition: avformat.h:506
AVERROR
Filter the word “frame” indicates either a video frame or a group of audio as stored in an AVFrame structure Format for each input and each output the list of supported formats For video that means pixel format For audio that means channel sample they are references to shared objects When the negotiation mechanism computes the intersection of the formats supported at each end of a all references to both lists are replaced with a reference to the intersection And when a single format is eventually chosen for a link amongst the remaining all references to the list are updated That means that if a filter requires that its input and output have the same format amongst a supported all it has to do is use a reference to the same list of formats query_formats can leave some formats unset and return AVERROR(EAGAIN) to cause the negotiation mechanism toagain later. That can be used by filters with complex requirements to use the format negotiated on one link to set the formats supported on another. Frame references ownership and permissions
MPEGTS_FLAG_AAC_LATM
#define MPEGTS_FLAG_AAC_LATM
Definition: mpegtsenc.c:116
opt.h
SYSTEM_CLOCK_FREQUENCY_DIVISOR
#define SYSTEM_CLOCK_FREQUENCY_DIVISOR
Definition: mpegts.h:38
AV_CODEC_ID_PCM_BLURAY
@ AV_CODEC_ID_PCM_BLURAY
Definition: codec_id.h:362
PAT_PID
#define PAT_PID
Definition: mpegts.h:41
AVCodecParameters::codec_type
enum AVMediaType codec_type
General type of the encoded data.
Definition: codec_par.h:51
mpegts.h
MpegTSService::provider_name
uint8_t provider_name[256]
Definition: mpegtsenc.c:67
AVFMT_NODIMENSIONS
#define AVFMT_NODIMENSIONS
Format does not need width/height.
Definition: avformat.h:482
section_write_packet
static void section_write_packet(MpegTSSection *s, const uint8_t *packet)
Definition: mpegtsenc.c:986
h26x_prefix_aud
static uint8_t * h26x_prefix_aud(const uint8_t *aud, const int aud_size, const uint8_t *extra_data, const int extra_size, AVPacket *pkt, int *size)
Definition: mpegtsenc.c:1851
STREAM_TYPE_AUDIO_AAC
#define STREAM_TYPE_AUDIO_AAC
Definition: mpeg.h:55
MpegTSWriteStream::discontinuity
int discontinuity
Definition: mpegtsenc.c:251
AVCodecParameters
This struct describes the properties of an encoded stream.
Definition: codec_par.h:47
check_h26x_startcode
static int check_h26x_startcode(AVFormatContext *s, const AVStream *st, const AVPacket *pkt, const char *codec)
Definition: mpegtsenc.c:1777
MpegTSWriteStream::pid
int pid
Definition: mpegtsenc.c:249
ffformatcontext
static av_always_inline FFFormatContext * ffformatcontext(AVFormatContext *s)
Definition: internal.h:123
STREAM_TYPE_VIDEO_VC1
#define STREAM_TYPE_VIDEO_VC1
Definition: mpegts.h:152
STREAM_TYPE_PRIVATE_DATA
#define STREAM_TYPE_PRIVATE_DATA
Definition: mpeg.h:54
avformat_new_stream
AVStream * avformat_new_stream(AVFormatContext *s, const struct AVCodec *c)
Add a new stream to a media file.
AVStream::priv_data
void * priv_data
Definition: avformat.h:769
AVFMT_VARIABLE_FPS
#define AVFMT_VARIABLE_FPS
Format allows variable fps.
Definition: avformat.h:481
MpegTSWriteStream::payload_dts
int64_t payload_dts
Definition: mpegtsenc.c:256
mpegts_write_flush
static void mpegts_write_flush(AVFormatContext *s)
Definition: mpegtsenc.c:2243
STREAM_ID_EMM_STREAM
#define STREAM_ID_EMM_STREAM
Definition: mpegts.h:190
HEVC_NAL_TYPE
#define HEVC_NAL_TYPE(state)
Definition: mpegtsenc.c:1867
MpegTSWrite::pmt_start_pid
int pmt_start_pid
Definition: mpegtsenc.c:106
MpegTSService::program
AVProgram * program
Definition: mpegtsenc.c:69
MpegTSWriteStream
Definition: mpegtsenc.c:248
STREAM_ID_PADDING_STREAM
#define STREAM_ID_PADDING_STREAM
Definition: mpegts.h:185
MpegTSWriteStream::first_timestamp_checked
int first_timestamp_checked
first pts/dts check needed
Definition: mpegtsenc.c:253
AV_CODEC_ID_DIRAC
@ AV_CODEC_ID_DIRAC
Definition: codec_id.h:168
int64_t
long long int64_t
Definition: coverity.c:34
STREAM_ID_PROGRAM_STREAM_MAP
#define STREAM_ID_PROGRAM_STREAM_MAP
Definition: mpegts.h:183
MpegTSWrite::m2ts_mode
int m2ts_mode
Definition: mpegtsenc.c:108
M2TS_AUDIO_START_PID
#define M2TS_AUDIO_START_PID
Definition: mpegts.h:76
mask
int mask
Definition: mediacodecdec_common.c:154
AV_CODEC_ID_MPEG4
@ AV_CODEC_ID_MPEG4
Definition: codec_id.h:64
set_af_flag
static void set_af_flag(uint8_t *pkt, int flag)
Definition: mpegtsenc.c:1424
NIT_TID
#define NIT_TID
Definition: mpegts.h:89
MpegTSWrite::pcr_period_ms
int pcr_period_ms
Definition: mpegtsenc.c:114
SECTION_LENGTH
#define SECTION_LENGTH
Definition: mpegtsenc.c:143
STREAM_TYPE_AUDIO_MPEG1
#define STREAM_TYPE_AUDIO_MPEG1
Definition: mpeg.h:51
AVFormatContext::streams
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:1332
mpegts_deinit
static void mpegts_deinit(AVFormatContext *s)
Definition: mpegtsenc.c:2286
STREAM_TYPE_VIDEO_VVC
#define STREAM_TYPE_VIDEO_VVC
Definition: mpeg.h:59
AVPacket::data
uint8_t * data
Definition: packet.h:588
AV_CODEC_ID_DVB_TELETEXT
@ AV_CODEC_ID_DVB_TELETEXT
Definition: codec_id.h:579
NIT_PID
#define NIT_PID
Definition: mpegts.h:46
AVOption
AVOption.
Definition: opt.h:429
NULL_PID
#define NULL_PID
Definition: mpegts.h:70
b
#define b
Definition: input.c:42
AVStream::avg_frame_rate
AVRational avg_frame_rate
Average framerate.
Definition: avformat.h:833
get_pcr
static int64_t get_pcr(const MpegTSWrite *ts)
Definition: mpegtsenc.c:966
mpegts_check_bitstream
static int mpegts_check_bitstream(AVFormatContext *s, AVStream *st, const AVPacket *pkt)
Definition: mpegtsenc.c:2312
AV_CODEC_ID_AVS2
@ AV_CODEC_ID_AVS2
Definition: codec_id.h:248
data
const char data[16]
Definition: mxf.c:149
AV_OPT_TYPE_DURATION
@ AV_OPT_TYPE_DURATION
Underlying C type is int64_t.
Definition: opt.h:319
DVB_EXTENSION_DESCRIPTOR
#define DVB_EXTENSION_DESCRIPTOR
Definition: mpegts.h:223
DVBAC3Descriptor::component_type
uint8_t component_type
Definition: mpegts.h:276
NIT_RETRANS_TIME
#define NIT_RETRANS_TIME
Definition: mpegtsenc.c:246
MpegTSWrite::nit_period_us
int64_t nit_period_us
Definition: mpegtsenc.c:127
AV_LOG_VERBOSE
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:226
MpegTSWriteStream::payload_pts
int64_t payload_pts
Definition: mpegtsenc.c:255
MPEGTS_FLAG_PAT_PMT_AT_FRAMES
#define MPEGTS_FLAG_PAT_PMT_AT_FRAMES
Definition: mpegtsenc.c:117
mathematics.h
AVDictionary
Definition: dict.c:32
FFMAX
#define FFMAX(a, b)
Definition: macros.h:47
FIRST_OTHER_PID
#define FIRST_OTHER_PID
Definition: mpegts.h:65
AV_PROFILE_ARIB_PROFILE_C
#define AV_PROFILE_ARIB_PROFILE_C
Definition: defs.h:192
MpegTSSection::opaque
void * opaque
Definition: mpegtsenc.c:59
AVChannelLayout::nb_channels
int nb_channels
Number of channels in this layout.
Definition: channel_layout.h:329
AV_CODEC_ID_HDMV_PGS_SUBTITLE
@ AV_CODEC_ID_HDMV_PGS_SUBTITLE
Definition: codec_id.h:578
VVC_AUD_NUT
@ VVC_AUD_NUT
Definition: vvc.h:49
opus_get_packet_samples
static int opus_get_packet_samples(AVFormatContext *s, AVPacket *pkt)
Definition: mpegtsenc.c:1803
MpegTSWrite::nit_period
int64_t nit_period
Definition: mpegtsenc.c:92
AV_CODEC_ID_TRUEHD
@ AV_CODEC_ID_TRUEHD
Definition: codec_id.h:504
AV_PKT_FLAG_KEY
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: packet.h:643
mpegts_write_end
static int mpegts_write_end(AVFormatContext *s)
Definition: mpegtsenc.c:2278
MpegTSWrite::av_class
const AVClass * av_class
Definition: mpegtsenc.c:84
MPEGTS_SERVICE_TYPE_TELETEXT
@ MPEGTS_SERVICE_TYPE_TELETEXT
Definition: mpegtsenc.c:76
FFOutputFormat::p
AVOutputFormat p
The public AVOutputFormat.
Definition: mux.h:65
ENHANCED_AC3_DESCRIPTOR
#define ENHANCED_AC3_DESCRIPTOR
Definition: mpegts.h:221
STREAM_TYPE_AUDIO_MPEG2
#define STREAM_TYPE_AUDIO_MPEG2
Definition: mpeg.h:52
put_registration_descriptor
static void put_registration_descriptor(uint8_t **q_ptr, uint32_t tag)
Definition: mpegtsenc.c:343
MpegTSSection::pid
int pid
Definition: mpegtsenc.c:55
NETWORK_NAME_DESCRIPTOR
#define NETWORK_NAME_DESCRIPTOR
Definition: mpegts.h:214
crc.h
mpegts_write_packet
static int mpegts_write_packet(AVFormatContext *s, AVPacket *pkt)
Definition: mpegtsenc.c:2268
AV_PROFILE_ARIB_PROFILE_A
#define AV_PROFILE_ARIB_PROFILE_A
Definition: defs.h:191
OFFSET
#define OFFSET(x)
Definition: mpegtsenc.c:2338
METADATA_DESCRIPTOR
#define METADATA_DESCRIPTOR
Definition: mpegts.h:204
avpriv_set_pts_info
void avpriv_set_pts_info(AVStream *st, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den)
Set the time base and wrapping info for a given stream.
Definition: avformat.c:780
REGISTRATION_DESCRIPTOR
#define REGISTRATION_DESCRIPTOR
Definition: mpegts.h:199
mpegts_write_pes
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:1491
STREAM_TYPE_VIDEO_AVS2
#define STREAM_TYPE_VIDEO_AVS2
Definition: mpegts.h:150
STREAM_TYPE_VIDEO_AVS3
#define STREAM_TYPE_VIDEO_AVS3
Definition: mpegts.h:151
fail
#define fail()
Definition: checkasm.h:218
STREAM_ID_DSMCC_STREAM
#define STREAM_ID_DSMCC_STREAM
Definition: mpegts.h:191
MpegTSWriteStream::last_pcr
int64_t last_pcr
Definition: mpegtsenc.c:263
get_m2ts_stream_type
static int get_m2ts_stream_type(AVFormatContext *s, AVStream *st)
Definition: mpegtsenc.c:459
AC3HeaderInfo
Definition: ac3_parser_internal.h:34
AC3_CHMODE_3F1R
@ AC3_CHMODE_3F1R
Definition: ac3defs.h:73
STREAM_TYPE_ATSC_AUDIO_EAC3
#define STREAM_TYPE_ATSC_AUDIO_EAC3
Definition: mpegts.h:171
avio_tell
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition: avio.h:494
get_dvb_stream_type
static int get_dvb_stream_type(AVFormatContext *s, AVStream *st)
Definition: mpegtsenc.c:355
val
static double val(void *priv, double ch)
Definition: aeval.c:77
MpegTSSection::write_packet
void(* write_packet)(struct MpegTSSection *s, const uint8_t *packet)
Definition: mpegtsenc.c:58
DVBAC3Descriptor::asvc_flag
uint8_t asvc_flag
Definition: mpegts.h:274
AC3HeaderInfo::channel_mode
uint8_t channel_mode
Definition: ac3_parser_internal.h:43
DEFAULT_SERVICE_NAME
#define DEFAULT_SERVICE_NAME
Definition: mpegtsenc.c:240
MPEGTS_SERVICE_TYPE_DIGITAL_RADIO
@ MPEGTS_SERVICE_TYPE_DIGITAL_RADIO
Definition: mpegtsenc.c:75
pts
static int64_t pts
Definition: transcode_aac.c:644
SDT_PID
#define SDT_PID
Definition: mpegts.h:47
H264_NAL_TYPE
#define H264_NAL_TYPE(state)
Definition: mpegtsenc.c:1866
AV_CODEC_ID_MP3
@ AV_CODEC_ID_MP3
preferred ID for decoding MPEG audio layer 1, 2 or 3
Definition: codec_id.h:461
MpegTSWrite::pat_period
int64_t pat_period
Definition: mpegtsenc.c:91
MpegTSWrite::provider_name
uint8_t provider_name[256]
Definition: mpegtsenc.c:132
AVRational::num
int num
Numerator.
Definition: rational.h:59
STREAM_ID_METADATA_STREAM
#define STREAM_ID_METADATA_STREAM
Definition: mpegts.h:193
MpegTSWrite::total_size
int64_t total_size
Definition: mpegtsenc.c:99
AV_CODEC_ID_DVB_SUBTITLE
@ AV_CODEC_ID_DVB_SUBTITLE
Definition: codec_id.h:573
GET_UTF8
#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:488
AV_DISPOSITION_CLEAN_EFFECTS
#define AV_DISPOSITION_CLEAN_EFFECTS
The audio stream contains music and sound effects without voice.
Definition: avformat.h:662
MpegTSWrite::last_nit_ts
int64_t last_nit_ts
Definition: mpegtsenc.c:130
avio_close_dyn_buf
int avio_close_dyn_buf(AVIOContext *s, uint8_t **pbuffer)
Return the written size and a pointer to the buffer.
Definition: aviobuf.c:1410
SUBTITLING_DESCRIPTOR
#define SUBTITLING_DESCRIPTOR
Definition: mpegts.h:219
first
trying all byte sequences megabyte in length and selecting the best looking sequence will yield cases to try But first
Definition: rate_distortion.txt:12
avassert.h
AV_LOG_TRACE
#define AV_LOG_TRACE
Extremely verbose debugging, useful for libav* development.
Definition: log.h:236
AV_LOG_ERROR
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:210
STREAM_TYPE_BLURAY_AUDIO_AC3
#define STREAM_TYPE_BLURAY_AUDIO_AC3
Definition: mpegts.h:157
MpegTSWrite::next_pcr
int64_t next_pcr
Definition: mpegtsenc.c:96
FF_ARRAY_ELEMS
#define FF_ARRAY_ELEMS(a)
Definition: sinewin_tablegen.c:29
select_pcr_streams
static void select_pcr_streams(AVFormatContext *s)
Definition: mpegtsenc.c:1072
STREAM_ID_EXTENDED_STREAM_ID
#define STREAM_ID_EXTENDED_STREAM_ID
Definition: mpegts.h:194
MpegTSWrite::original_network_id
int original_network_id
Definition: mpegtsenc.c:102
MpegTSWrite::start_pid
int start_pid
Definition: mpegtsenc.c:107
bytestream2_init_writer
static av_always_inline void bytestream2_init_writer(PutByteContext *p, uint8_t *buf, int buf_size)
Definition: bytestream.h:147
write_pcr_bits
static int write_pcr_bits(uint8_t *buf, int64_t pcr)
Definition: mpegtsenc.c:1351
avio_open_dyn_buf
int avio_open_dyn_buf(AVIOContext **s)
Open a write only memory stream.
Definition: aviobuf.c:1365
av_dict_get
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:60
AV_CODEC_ID_S302M
@ AV_CODEC_ID_S302M
Definition: codec_id.h:364
STREAM_TYPE_VIDEO_MPEG4
#define STREAM_TYPE_VIDEO_MPEG4
Definition: mpeg.h:56
intreadwrite.h
s
#define s(width, name)
Definition: cbs_vp9.c:198
MPEGTS_FLAG_SYSTEM_B
#define MPEGTS_FLAG_SYSTEM_B
Definition: mpegtsenc.c:118
MpegTSService::name
uint8_t name[256]
Definition: mpegtsenc.c:66
MPEGTS_SERVICE_TYPE_HEVC_DIGITAL_HDTV
@ MPEGTS_SERVICE_TYPE_HEVC_DIGITAL_HDTV
Definition: mpegtsenc.c:81
TELETEXT_DESCRIPTOR
#define TELETEXT_DESCRIPTOR
Definition: mpegts.h:218
bytestream2_tell_p
static av_always_inline int bytestream2_tell_p(const PutByteContext *p)
Definition: bytestream.h:197
frame_size
int frame_size
Definition: mxfenc.c:2487
bytestream2_put_buffer
static av_always_inline unsigned int bytestream2_put_buffer(PutByteContext *p, const uint8_t *src, unsigned int size)
Definition: bytestream.h:286
AVMEDIA_TYPE_AUDIO
@ AVMEDIA_TYPE_AUDIO
Definition: avutil.h:201
STUFFING_BYTE
#define STUFFING_BYTE
Definition: mpegts.h:37
AV_CODEC_ID_MP2
@ AV_CODEC_ID_MP2
Definition: codec_id.h:460
HEVC_NAL_VPS
@ HEVC_NAL_VPS
Definition: hevc.h:61
av_match_ext
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:41
STREAM_TYPE_BLURAY_AUDIO_TRUEHD
#define STREAM_TYPE_BLURAY_AUDIO_TRUEHD
Definition: mpegts.h:159
av_assert0
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:42
options
static const AVOption options[]
Definition: mpegtsenc.c:2340
SYNC_BYTE
#define SYNC_BYTE
Definition: mpegts.h:36
AV_LOG_DEBUG
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:231
ctx
static AVFormatContext * ctx
Definition: movenc.c:49
hevc.h
STREAM_ID_TYPE_E_STREAM
#define STREAM_ID_TYPE_E_STREAM
Definition: mpegts.h:192
nb_streams
static int nb_streams
Definition: ffprobe.c:348
av_rescale_q
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
PMT_TID
#define PMT_TID
Definition: mpegts.h:85
mpegts_init
static int mpegts_init(AVFormatContext *s)
Definition: mpegtsenc.c:1101
MpegTSWriteStream::cc
int cc
Definition: mpegtsenc.c:250
extend_af
static void extend_af(uint8_t *pkt, int size)
Definition: mpegtsenc.c:1440
codec_id
enum AVCodecID codec_id
Definition: vaapi_decode.c:410
LAST_OTHER_PID
#define LAST_OTHER_PID
Definition: mpegts.h:66
key
const char * key
Definition: hwcontext_opencl.c:189
AVMEDIA_TYPE_DATA
@ AVMEDIA_TYPE_DATA
Opaque data information usually continuous.
Definition: avutil.h:202
av_mallocz
#define av_mallocz(s)
Definition: tableprint_vlc.h:31
DVBAC3Descriptor::component_type_flag
uint8_t component_type_flag
Definition: mpegts.h:271
AV_CODEC_ID_H264
@ AV_CODEC_ID_H264
Definition: codec_id.h:79
MpegTSWrite::sdt_period
int64_t sdt_period
Definition: mpegtsenc.c:90
avformat_write_header
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:467
AV_CODEC_ID_ARIB_CAPTION
@ AV_CODEC_ID_ARIB_CAPTION
Definition: codec_id.h:597
MpegTSWrite::first_dts_checked
int first_dts_checked
Definition: mpegtsenc.c:95
retransmit_si_info
static void retransmit_si_info(AVFormatContext *s, int force_pat, int force_sdt, int force_nit, int64_t pcr)
Definition: mpegtsenc.c:1318
MpegTSWrite::m2ts_textsub_pid
int m2ts_textsub_pid
Definition: mpegtsenc.c:112
mpegts_insert_null_packet
static void mpegts_insert_null_packet(AVFormatContext *s)
Definition: mpegtsenc.c:1366
AV_CODEC_ID_AVS3
@ AV_CODEC_ID_AVS3
Definition: codec_id.h:250
AVFormatContext
Format I/O context.
Definition: avformat.h:1264
internal.h
AVStream::codecpar
AVCodecParameters * codecpar
Codec parameters associated with this stream.
Definition: avformat.h:767
LIBAVUTIL_VERSION_INT
#define LIBAVUTIL_VERSION_INT
Definition: version.h:85
AVClass
Describe the class of an AVClass context structure.
Definition: log.h:76
M2TS_VIDEO_PID
#define M2TS_VIDEO_PID
Definition: mpegts.h:75
PCR_TIME_BASE
#define PCR_TIME_BASE
Definition: mpegtsenc.c:45
metadata
Stream codec metadata
Definition: ogg-flac-chained-meta.txt:2
AVStream::time_base
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
Definition: avformat.h:783
STREAM_TYPE_ATSC_AUDIO_AC3
#define STREAM_TYPE_ATSC_AUDIO_AC3
Definition: mpegts.h:170
NULL
#define NULL
Definition: coverity.c:32
MPEGTS_SERVICE_TYPE_MPEG2_DIGITAL_HDTV
@ MPEGTS_SERVICE_TYPE_MPEG2_DIGITAL_HDTV
Definition: mpegtsenc.c:78
mpegts_write_section
static void mpegts_write_section(MpegTSSection *s, uint8_t *buf, int len)
Definition: mpegtsenc.c:146
AV_CODEC_ID_TIMED_ID3
@ AV_CODEC_ID_TIMED_ID3
Definition: codec_id.h:612
AV_WB16
#define AV_WB16(p, v)
Definition: intreadwrite.h:401
MpegTSWrite::nb_services
int nb_services
Definition: mpegtsenc.c:93
state
static struct @553 state
STREAM_ID_PRIVATE_STREAM_1
#define STREAM_ID_PRIVATE_STREAM_1
Definition: mpegts.h:184
M2TS_TEXTSUB_PID
#define M2TS_TEXTSUB_PID
Definition: mpegts.h:78
MpegTSWrite::tables_version
int tables_version
Definition: mpegtsenc.c:124
MpegTSWrite::nit
MpegTSSection nit
Definition: mpegtsenc.c:87
av_default_item_name
const char * av_default_item_name(void *ptr)
Return the context name.
Definition: log.c:242
H264_NAL_IDR_SLICE
@ H264_NAL_IDR_SLICE
Definition: h264.h:39
AVFormatContext::pb
AVIOContext * pb
I/O context.
Definition: avformat.h:1306
list
Filter the word “frame” indicates either a video frame or a group of audio as stored in an AVFrame structure Format for each input and each output the list of supported formats For video that means pixel format For audio that means channel sample they are references to shared objects When the negotiation mechanism computes the intersection of the formats supported at each end of a all references to both lists are replaced with a reference to the intersection And when a single format is eventually chosen for a link amongst the remaining list
Definition: filter_design.txt:25
M2TS_PGSSUB_START_PID
#define M2TS_PGSSUB_START_PID
Definition: mpegts.h:77
options
Definition: swscale.c:43
AVStream::metadata
AVDictionary * metadata
Definition: avformat.h:824
avpriv_find_start_code
const uint8_t * avpriv_find_start_code(const uint8_t *p, const uint8_t *end, uint32_t *state)
FFOutputFormat
Definition: mux.h:61
MpegTSService::sid
int sid
Definition: mpegtsenc.c:65
AV_CODEC_ID_SMPTE_KLV
@ AV_CODEC_ID_SMPTE_KLV
Definition: codec_id.h:610
av_write_frame
int av_write_frame(AVFormatContext *s, AVPacket *pkt)
Write a packet to an output media file.
Definition: mux.c:1176
AVCodecParameters::ch_layout
AVChannelLayout ch_layout
Audio only.
Definition: codec_par.h:180
MpegTSWrite::m2ts_pgssub_pid
int m2ts_pgssub_pid
Definition: mpegtsenc.c:111
MPEGTS_FLAG_REEMIT_PAT_PMT
#define MPEGTS_FLAG_REEMIT_PAT_PMT
Definition: mpegtsenc.c:115
MpegTSWrite::sdt_period_us
int64_t sdt_period_us
Definition: mpegtsenc.c:126
MpegTSWrite::service_type
int service_type
Definition: mpegtsenc.c:104
AVCodecParameters::sample_rate
int sample_rate
Audio only.
Definition: codec_par.h:184
AV_CODEC_ID_MPEG1VIDEO
@ AV_CODEC_ID_MPEG1VIDEO
Definition: codec_id.h:53
AVStream::nb_frames
int64_t nb_frames
number of frames in this stream if known or 0
Definition: avformat.h:805
AVCodecID
AVCodecID
Identify the syntax and semantics of the bitstream.
Definition: codec_id.h:49
AV_CODEC_ID_EAC3
@ AV_CODEC_ID_EAC3
Definition: codec_id.h:500
AVCodecParameters::extradata_size
int extradata_size
Size of the extradata content in bytes.
Definition: codec_par.h:73
AV_WB32
#define AV_WB32(p, v)
Definition: intreadwrite.h:415
enable_pcr_generation_for_stream
static void enable_pcr_generation_for_stream(AVFormatContext *s, AVStream *pcr_st)
Definition: mpegtsenc.c:1041
SDT_TID
#define SDT_TID
Definition: mpegts.h:91
AV_CODEC_ID_AAC
@ AV_CODEC_ID_AAC
Definition: codec_id.h:462
M2TS_PMT_PID
#define M2TS_PMT_PID
Definition: mpegts.h:73
MpegTSWrite::copyts
int copyts
Definition: mpegtsenc.c:123
PutByteContext
Definition: bytestream.h:37
MpegTSWriteStream::amux
AVFormatContext * amux
Definition: mpegtsenc.c:259
startcode.h
aud
static int FUNC() aud(CodedBitstreamContext *ctx, RWContext *rw, H264RawAUD *current)
Definition: cbs_h264_syntax_template.c:875
av_rescale_rnd
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
MPEGTS_SERVICE_TYPE_DIGITAL_TV
@ MPEGTS_SERVICE_TYPE_DIGITAL_TV
Definition: mpegtsenc.c:74
ac3_parser_internal.h
AC3_CHMODE_STEREO
@ AC3_CHMODE_STEREO
Definition: ac3defs.h:70
AVPacket::size
int size
Definition: packet.h:589
NULL_IF_CONFIG_SMALL
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification.
Definition: internal.h:94
avformat_alloc_context
AVFormatContext * avformat_alloc_context(void)
Allocate an AVFormatContext.
Definition: options.c:163
FF_OFMT_FLAG_ALLOW_FLUSH
#define FF_OFMT_FLAG_ALLOW_FLUSH
This flag indicates that the muxer stores data internally and supports flushing it.
Definition: mux.h:38
SERVICE_LIST_DESCRIPTOR
#define SERVICE_LIST_DESCRIPTOR
Definition: mpegts.h:215
STREAM_TYPE_VIDEO_HEVC
#define STREAM_TYPE_VIDEO_HEVC
Definition: mpeg.h:58
VVC_VPS_NUT
@ VVC_VPS_NUT
Definition: vvc.h:43
MpegTSWriteStream::data_st_warning
int data_st_warning
Definition: mpegtsenc.c:260
DVBAC3Descriptor::bsid_flag
uint8_t bsid_flag
Definition: mpegts.h:272
mpegts_write_packet_internal
static int mpegts_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
Definition: mpegtsenc.c:1869
av_bswap32
#define av_bswap32
Definition: bswap.h:47
VVC_NAL_TYPE
#define VVC_NAL_TYPE(state)
Definition: mpegtsenc.c:1868
MpegTSWriteStream::opus_queued_samples
int opus_queued_samples
Definition: mpegtsenc.c:266
AV_CODEC_ID_DTS
@ AV_CODEC_ID_DTS
Definition: codec_id.h:464
size
int size
Definition: twinvq_data.h:10344
mpegts_write_pat
static void mpegts_write_pat(AVFormatContext *s)
Definition: mpegtsenc.c:272
MPEGTS_SERVICE_TYPE_ADVANCED_CODEC_DIGITAL_HDTV
@ MPEGTS_SERVICE_TYPE_ADVANCED_CODEC_DIGITAL_HDTV
Definition: mpegtsenc.c:80
AV_NOPTS_VALUE
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:247
AV_RB32
uint64_t_TMPL AV_WL64 unsigned int_TMPL AV_WL32 unsigned int_TMPL AV_WL24 unsigned int_TMPL AV_WL16 uint64_t_TMPL AV_WB64 unsigned int_TMPL AV_RB32
Definition: bytestream.h:96
STREAM_ID_PRIVATE_STREAM_2
#define STREAM_ID_PRIVATE_STREAM_2
Definition: mpegts.h:186
av_get_audio_frame_duration2
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:816
AVCodecParameters::profile
int profile
Codec-specific bitstream restrictions that the stream conforms to.
Definition: codec_par.h:128
AV_CODEC_ID_OPUS
@ AV_CODEC_ID_OPUS
Definition: codec_id.h:520
ff_mpegts_muxer
const FFOutputFormat ff_mpegts_muxer
Definition: mpegtsenc.c:2410
mpegts_add_service
static MpegTSService * mpegts_add_service(AVFormatContext *s, int sid, const AVDictionary *metadata, AVProgram *program)
Definition: mpegtsenc.c:992
STREAM_IDENTIFIER_DESCRIPTOR
#define STREAM_IDENTIFIER_DESCRIPTOR
Definition: mpegts.h:217
MpegTSWrite::last_pat_ts
int64_t last_pat_ts
Definition: mpegtsenc.c:128
AV_DISPOSITION_HEARING_IMPAIRED
#define AV_DISPOSITION_HEARING_IMPAIRED
The stream is intended for hearing impaired audiences.
Definition: avformat.h:654
MpegTSWrite::m2ts_video_pid
int m2ts_video_pid
Definition: mpegtsenc.c:109
AVPacket::dts
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed.
Definition: packet.h:587
avio_write
void avio_write(AVIOContext *s, const unsigned char *buf, int size)
Definition: aviobuf.c:206
FF_COMPLIANCE_NORMAL
#define FF_COMPLIANCE_NORMAL
Definition: defs.h:60
STREAM_TYPE_VIDEO_MPEG2
#define STREAM_TYPE_VIDEO_MPEG2
Definition: mpeg.h:50
AV_CODEC_ID_VVC
@ AV_CODEC_ID_VVC
Definition: codec_id.h:252
av_crc_get_table
const AVCRC * av_crc_get_table(AVCRCId crc_id)
Get an initialized standard CRC table.
Definition: crc.c:385
MpegTSWrite::sdt
MpegTSSection sdt
Definition: mpegtsenc.c:86
PCR_RETRANS_TIME
#define PCR_RETRANS_TIME
Definition: mpegtsenc.c:245
MpegTSWrite::services
MpegTSService ** services
Definition: mpegtsenc.c:88
write_packet
static void write_packet(AVFormatContext *s, const uint8_t *packet)
Definition: mpegtsenc.c:972
AC3HeaderInfo::bitstream_mode
uint8_t bitstream_mode
Definition: ac3_parser_internal.h:42
AVPacket::flags
int flags
A combination of AV_PKT_FLAG values.
Definition: packet.h:594
MpegTSWriteStream::prev_payload_key
int prev_payload_key
Definition: mpegtsenc.c:254
MpegTSWrite::pes_payload_size
int pes_payload_size
Definition: mpegtsenc.c:98
version
version
Definition: libkvazaar.c:313
STREAM_TYPE_AUDIO_AAC_LATM
#define STREAM_TYPE_AUDIO_AAC_LATM
Definition: mpegts.h:131
vvc.h
HEVC_NAL_RSV_VCL24
@ HEVC_NAL_RSV_VCL24
Definition: hevc.h:53
DATA_COMPONENT_DESCRIPTOR
#define DATA_COMPONENT_DESCRIPTOR
Definition: mpegts.h:233
avcodec_get_name
const char * avcodec_get_name(enum AVCodecID id)
Get the name of a codec.
Definition: utils.c:406
STREAM_TYPE_VIDEO_DIRAC
#define STREAM_TYPE_VIDEO_DIRAC
Definition: mpegts.h:153
ISO_639_LANGUAGE_DESCRIPTOR
#define ISO_639_LANGUAGE_DESCRIPTOR
Definition: mpegts.h:200
i
#define i(width, name, range_min, range_max)
Definition: cbs_h2645.c:256
AVPacket::pts
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: packet.h:581
code
and forward the test the status of outputs and forward it to the corresponding return FFERROR_NOT_READY If the filters stores internally one or a few frame for some it can consider them to be part of the FIFO and delay acknowledging a status change accordingly Example code
Definition: filter_design.txt:178
avio_internal.h
av_packet_get_side_data
uint8_t * av_packet_get_side_data(const AVPacket *pkt, enum AVPacketSideDataType type, size_t *size)
Get side information from packet.
Definition: packet.c:252
put16
static void put16(uint8_t **q_ptr, int val)
Definition: mpegtsenc.c:200
SDT_RETRANS_TIME
#define SDT_RETRANS_TIME
Definition: mpegtsenc.c:243
mpegts_write_section1
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:209
AV_CODEC_ID_SMPTE_2038
@ AV_CODEC_ID_SMPTE_2038
Definition: codec_id.h:614
STREAM_TYPE_BLURAY_SUBTITLE_TEXT
#define STREAM_TYPE_BLURAY_SUBTITLE_TEXT
Definition: mpegts.h:166
AV_TIME_BASE
#define AV_TIME_BASE
Internal time base represented as integer.
Definition: avutil.h:253
PAT_TID
#define PAT_TID
Definition: mpegts.h:83
AV_CODEC_ID_CAVS
@ AV_CODEC_ID_CAVS
Definition: codec_id.h:139
AC3_CHMODE_DUALMONO
@ AC3_CHMODE_DUALMONO
Definition: ac3defs.h:68
avpriv_ac3_parse_header
int avpriv_ac3_parse_header(AC3HeaderInfo **phdr, const uint8_t *buf, size_t size)
Definition: ac3_parser.c:491
AV_CODEC_ID_HEVC
@ AV_CODEC_ID_HEVC
Definition: codec_id.h:228
value
it s the only field you need to keep assuming you have a context There is some magic you don t need to care about around this just let it vf default value
Definition: writing_filters.txt:86
MpegTSWrite::m2ts_audio_pid
int m2ts_audio_pid
Definition: mpegtsenc.c:110
FFMIN
#define FFMIN(a, b)
Definition: macros.h:49
MPEGTS_FLAG_NIT
#define MPEGTS_FLAG_NIT
Definition: mpegtsenc.c:120
putbuf
static void putbuf(uint8_t **q_ptr, const uint8_t *buf, size_t len)
Definition: mpegtsenc.c:293
write_pts
static void write_pts(uint8_t *q, int fourbits, int64_t pts)
Definition: mpegtsenc.c:1409
ENC
#define ENC
Definition: mpegtsenc.c:2339
AV_PKT_DATA_MPEGTS_STREAM_ID
@ 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:212
AVProgram
New fields can be added to the end with minor version bumps.
Definition: avformat.h:1188
AV_CODEC_ID_VC1
@ AV_CODEC_ID_VC1
Definition: codec_id.h:122
MPEGTS_FLAG_DISCONT
#define MPEGTS_FLAG_DISCONT
Definition: mpegtsenc.c:119
len
int len
Definition: vorbis_enc_data.h:426
STREAM_TYPE_BLURAY_AUDIO_DTS_HD
#define STREAM_TYPE_BLURAY_AUDIO_DTS_HD
Definition: mpegts.h:161
DVBAC3Descriptor::asvc
uint8_t asvc
Definition: mpegts.h:279
av_rescale
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
MpegTSWrite
Definition: mpegtsenc.c:83
MpegTSWriteStream::opus_pending_trim_start
int opus_pending_trim_start
Definition: mpegtsenc.c:267
AV_CRC_32_IEEE
@ AV_CRC_32_IEEE
Definition: crc.h:52
MpegTSWrite::service_id
int service_id
Definition: mpegtsenc.c:103
SERVICE_DESCRIPTOR
#define SERVICE_DESCRIPTOR
Definition: mpegts.h:216
PAT_RETRANS_TIME
#define PAT_RETRANS_TIME
Definition: mpegtsenc.c:244
AC3_CHMODE_MONO
@ AC3_CHMODE_MONO
Definition: ac3defs.h:69
mpegts_write_pmt
static int mpegts_write_pmt(AVFormatContext *s, MpegTSService *service)
Definition: mpegtsenc.c:512
AC3_CHMODE_3F2R
@ AC3_CHMODE_3F2R
Definition: ac3defs.h:75
MpegTSWriteStream::payload_size
int payload_size
Definition: mpegtsenc.c:252
AC3_CHMODE_2F1R
@ AC3_CHMODE_2F1R
Definition: ac3defs.h:72
MpegTSWrite::flags
int flags
Definition: mpegtsenc.c:122
MpegTSWrite::first_pcr
int64_t first_pcr
Definition: mpegtsenc.c:94
language
Undefined Behavior In the C language
Definition: undefined.txt:3
MpegTSWriteStream::dvb_ac3_desc
DVBAC3Descriptor * dvb_ac3_desc
Definition: mpegtsenc.c:269
AVStream::disposition
int disposition
Stream disposition - a combination of AV_DISPOSITION_* flags.
Definition: avformat.h:813
AV_DISPOSITION_VISUAL_IMPAIRED
#define AV_DISPOSITION_VISUAL_IMPAIRED
The stream is intended for visually impaired audiences.
Definition: avformat.h:658
STREAM_ID_VIDEO_STREAM_0
#define STREAM_ID_VIDEO_STREAM_0
Definition: mpegts.h:188
tag
uint32_t tag
Definition: movenc.c:2032
ffio_free_dyn_buf
void ffio_free_dyn_buf(AVIOContext **s)
Free a dynamic buffer.
Definition: aviobuf.c:1438
AVStream::id
int id
Format-specific stream ID.
Definition: avformat.h:756
ret
ret
Definition: filter_design.txt:187
AVStream
Stream structure.
Definition: avformat.h:744
bswap.h
AVClass::class_name
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:81
AVFormatContext::oformat
const struct AVOutputFormat * oformat
The output container format.
Definition: avformat.h:1283
H264_NAL_SLICE
@ H264_NAL_SLICE
Definition: h264.h:35
av_malloc
void * av_malloc(size_t size)
Allocate a memory block with alignment suitable for all memory accesses (including vectors if availab...
Definition: mem.c:98
AC3_CHMODE_2F2R
@ AC3_CHMODE_2F2R
Definition: ac3defs.h:74
STREAM_TYPE_BLURAY_AUDIO_EAC3
#define STREAM_TYPE_BLURAY_AUDIO_EAC3
Definition: mpegts.h:160
MpegTSSection
Definition: mpegtsenc.c:54
AC3_DESCRIPTOR
#define AC3_DESCRIPTOR
Definition: mpegts.h:220
avformat.h
dict.h
flag
#define flag(name)
Definition: cbs_av1.c:496
id
enum AVCodecID id
Definition: dts2pts.c:549
left
Tag MUST be and< 10hcoeff half pel interpolation filter coefficients, hcoeff[0] are the 2 middle coefficients[1] are the next outer ones and so on, resulting in a filter like:...eff[2], hcoeff[1], hcoeff[0], hcoeff[0], hcoeff[1], hcoeff[2] ... the sign of the coefficients is not explicitly stored but alternates after each coeff and coeff[0] is positive, so ...,+,-,+,-,+,+,-,+,-,+,... hcoeff[0] is not explicitly stored but found by subtracting the sum of all stored coefficients with signs from 32 hcoeff[0]=32 - hcoeff[1] - hcoeff[2] - ... a good choice for hcoeff and htaps is htaps=6 hcoeff={40,-10, 2} an alternative which requires more computations at both encoder and decoder side and may or may not be better is htaps=8 hcoeff={42,-14, 6,-2}ref_frames minimum of the number of available reference frames and max_ref_frames for example the first frame after a key frame always has ref_frames=1spatial_decomposition_type wavelet type 0 is a 9/7 symmetric compact integer wavelet 1 is a 5/3 symmetric compact integer wavelet others are reserved stored as delta from last, last is reset to 0 if always_reset||keyframeqlog quality(logarithmic quantizer scale) stored as delta from last, last is reset to 0 if always_reset||keyframemv_scale stored as delta from last, last is reset to 0 if always_reset||keyframe FIXME check that everything works fine if this changes between framesqbias dequantization bias stored as delta from last, last is reset to 0 if always_reset||keyframeblock_max_depth maximum depth of the block tree stored as delta from last, last is reset to 0 if always_reset||keyframequant_table quantization tableHighlevel bitstream structure:==============================--------------------------------------------|Header|--------------------------------------------|------------------------------------|||Block0||||split?||||yes no||||......... intra?||||:Block01 :yes no||||:Block02 :....... ..........||||:Block03 ::y DC ::ref index:||||:Block04 ::cb DC ::motion x :||||......... :cr DC ::motion y :||||....... ..........|||------------------------------------||------------------------------------|||Block1|||...|--------------------------------------------|------------ ------------ ------------|||Y subbands||Cb subbands||Cr subbands||||--- ---||--- ---||--- ---|||||LL0||HL0||||LL0||HL0||||LL0||HL0|||||--- ---||--- ---||--- ---||||--- ---||--- ---||--- ---|||||LH0||HH0||||LH0||HH0||||LH0||HH0|||||--- ---||--- ---||--- ---||||--- ---||--- ---||--- ---|||||HL1||LH1||||HL1||LH1||||HL1||LH1|||||--- ---||--- ---||--- ---||||--- ---||--- ---||--- ---|||||HH1||HL2||||HH1||HL2||||HH1||HL2|||||...||...||...|||------------ ------------ ------------|--------------------------------------------Decoding process:=================------------|||Subbands|------------||||------------|Intra DC||||LL0 subband prediction ------------|\ Dequantization ------------------- \||Reference frames|\ IDWT|------- -------|Motion \|||Frame 0||Frame 1||Compensation . OBMC v -------|------- -------|--------------. \------> Frame n output Frame Frame<----------------------------------/|...|------------------- Range Coder:============Binary Range Coder:------------------- The implemented range coder is an adapted version based upon "Range encoding: an algorithm for removing redundancy from a digitised message." by G. N. N. Martin. The symbols encoded by the Snow range coder are bits(0|1). The associated probabilities are not fix but change depending on the symbol mix seen so far. bit seen|new state ---------+----------------------------------------------- 0|256 - state_transition_table[256 - old_state];1|state_transition_table[old_state];state_transition_table={ 0, 0, 0, 0, 0, 0, 0, 0, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 190, 191, 192, 194, 194, 195, 196, 197, 198, 199, 200, 201, 202, 202, 204, 205, 206, 207, 208, 209, 209, 210, 211, 212, 213, 215, 215, 216, 217, 218, 219, 220, 220, 222, 223, 224, 225, 226, 227, 227, 229, 229, 230, 231, 232, 234, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 248, 0, 0, 0, 0, 0, 0, 0};FIXME Range Coding of integers:------------------------- FIXME Neighboring Blocks:===================left and top are set to the respective blocks unless they are outside of the image in which case they are set to the Null block top-left is set to the top left block unless it is outside of the image in which case it is set to the left block if this block has no larger parent block or it is at the left side of its parent block and the top right block is not outside of the image then the top right block is used for top-right else the top-left block is used Null block y, cb, cr are 128 level, ref, mx and my are 0 Motion Vector Prediction:=========================1. the motion vectors of all the neighboring blocks are scaled to compensate for the difference of reference frames scaled_mv=(mv *(256 *(current_reference+1)/(mv.reference+1))+128)> the median of the scaled left
Definition: snow.txt:386
AV_RL32
uint64_t_TMPL AV_WL64 unsigned int_TMPL AV_RL32
Definition: bytestream.h:92
MPEGTS_SERVICE_TYPE_ADVANCED_CODEC_DIGITAL_RADIO
@ MPEGTS_SERVICE_TYPE_ADVANCED_CODEC_DIGITAL_RADIO
Definition: mpegtsenc.c:77
MpegTSWrite::pkt
AVPacket * pkt
Definition: mpegtsenc.c:89
STREAM_TYPE_BLURAY_AUDIO_PCM_BLURAY
#define STREAM_TYPE_BLURAY_AUDIO_PCM_BLURAY
Definition: mpegts.h:156
av_dynarray_add_nofree
int av_dynarray_add_nofree(void *tab_ptr, int *nb_ptr, void *elem)
Add an element to a dynamic array.
Definition: mem.c:315
AC3_DSURMOD_ON
@ AC3_DSURMOD_ON
Definition: ac3defs.h:82
H264_NAL_SPS
@ H264_NAL_SPS
Definition: h264.h:41
MPEGTS_SERVICE_TYPE_ADVANCED_CODEC_DIGITAL_SDTV
@ MPEGTS_SERVICE_TYPE_ADVANCED_CODEC_DIGITAL_SDTV
Definition: mpegtsenc.c:79
AVStream::index
int index
stream index in AVFormatContext
Definition: avformat.h:750
MpegTSWrite::pat
MpegTSSection pat
Definition: mpegtsenc.c:85
STREAM_TYPE_VIDEO_H264
#define STREAM_TYPE_VIDEO_H264
Definition: mpeg.h:57
mpegts_write_sdt
static void mpegts_write_sdt(AVFormatContext *s)
Definition: mpegtsenc.c:851
av_crc
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:417
AVRational::den
int den
Denominator.
Definition: rational.h:60
mpegts_write_nit
static void mpegts_write_nit(AVFormatContext *s)
Definition: mpegtsenc.c:889
AV_OPT_TYPE_INT
@ AV_OPT_TYPE_INT
Underlying C type is int.
Definition: opt.h:259
defs.h
MpegTSSection::cc
int cc
Definition: mpegtsenc.c:56
avformat_free_context
void avformat_free_context(AVFormatContext *s)
Free an AVFormatContext and all its streams.
Definition: avformat.c:143
STREAM_TYPE_VIDEO_CAVS
#define STREAM_TYPE_VIDEO_CAVS
Definition: mpeg.h:60
MpegTSWriteStream::payload
uint8_t * payload
Definition: mpegtsenc.c:258
AV_PKT_DATA_SKIP_SAMPLES
@ AV_PKT_DATA_SKIP_SAMPLES
Recommends skipping the specified number of samples.
Definition: packet.h:153
MpegTSWriteStream::pcr_period
int64_t pcr_period
Definition: mpegtsenc.c:262
Windows::Graphics::DirectX::Direct3D11::p
IDirect3DDxgiInterfaceAccess _COM_Outptr_ void ** p
Definition: vsrc_gfxcapture_winrt.hpp:53
AVPacket::stream_index
int stream_index
Definition: packet.h:590
DVBAC3Descriptor
Definition: mpegts.h:270
MpegTSService::pmt
MpegTSSection pmt
Definition: mpegtsenc.c:64
MpegTSSection::remaining
int remaining
Definition: mpegtsenc.c:60
mpegts_muxer_class
static const AVClass mpegts_muxer_class
Definition: mpegtsenc.c:2403
av_log_once
void av_log_once(void *avcl, int initial_level, int subsequent_level, int *state, const char *fmt,...)
Definition: log.c:451
MpegTSWriteStream::payload_flags
int payload_flags
Definition: mpegtsenc.c:257
VVC_OPI_NUT
@ VVC_OPI_NUT
Definition: vvc.h:41
AC3HeaderInfo::bitstream_id
uint8_t bitstream_id
Definition: ac3_parser_internal.h:41
AVMEDIA_TYPE_VIDEO
@ AVMEDIA_TYPE_VIDEO
Definition: avutil.h:200
av_guess_format
const 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:79
mem.h
STREAM_ID_AUDIO_STREAM_0
#define STREAM_ID_AUDIO_STREAM_0
Definition: mpegts.h:187
DVBAC3Descriptor::mainid
uint8_t mainid
Definition: mpegts.h:278
FFFormatContext::pkt
AVPacket * pkt
Used to hold temporary packets for the generic demuxing code.
Definition: internal.h:111
MpegTSService
Definition: mpegtsenc.c:63
STREAM_TYPE_METADATA
#define STREAM_TYPE_METADATA
Definition: mpegts.h:139
MpegTSWrite::transport_stream_id
int transport_stream_id
Definition: mpegtsenc.c:101
STREAM_ID_ECM_STREAM
#define STREAM_ID_ECM_STREAM
Definition: mpegts.h:189
DVBAC3Descriptor::bsid
uint8_t bsid
Definition: mpegts.h:277
av_free
#define av_free(p)
Definition: tableprint_vlc.h:34
AVDictionaryEntry
Definition: dict.h:90
AVCodecParameters::codec_id
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition: codec_par.h:55
AVPacket
This structure stores compressed data.
Definition: packet.h:565
AV_OPT_TYPE_BOOL
@ AV_OPT_TYPE_BOOL
Underlying C type is int.
Definition: opt.h:327
STREAM_ID_PROGRAM_STREAM_DIRECTORY
#define STREAM_ID_PROGRAM_STREAM_DIRECTORY
Definition: mpegts.h:195
MpegTSWrite::pat_period_us
int64_t pat_period_us
Definition: mpegtsenc.c:125
av_freep
#define av_freep(p)
Definition: tableprint_vlc.h:35
get_pes_stream_id
static int get_pes_stream_id(AVFormatContext *s, AVStream *st, int stream_id, int *async)
Definition: mpegtsenc.c:1456
AV_OPT_TYPE_FLAGS
@ AV_OPT_TYPE_FLAGS
Underlying C type is unsigned int.
Definition: opt.h:255
bytestream.h
h264.h
MpegTSWrite::omit_video_pes_length
int omit_video_pes_length
Definition: mpegtsenc.c:134
av_log
#define av_log(a,...)
Definition: tableprint_vlc.h:27
AV_CODEC_ID_AAC_LATM
@ AV_CODEC_ID_AAC_LATM
Definition: codec_id.h:509
AVERROR_INVALIDDATA
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:61
H264_NAL_AUD
@ H264_NAL_AUD
Definition: h264.h:43
get_ts_payload_start
static uint8_t * get_ts_payload_start(uint8_t *pkt)
Definition: mpegtsenc.c:1448
STREAM_TYPE_BLURAY_AUDIO_DTS
#define STREAM_TYPE_BLURAY_AUDIO_DTS
Definition: mpegts.h:158
AV_CODEC_ID_HDMV_TEXT_SUBTITLE
@ AV_CODEC_ID_HDMV_TEXT_SUBTITLE
Definition: codec_id.h:595
TS_PACKET_SIZE
#define TS_PACKET_SIZE
Definition: mpegts.h:29
mpegts_insert_pcr_only
static void mpegts_insert_pcr_only(AVFormatContext *s, AVStream *st)
Definition: mpegtsenc.c:1381
MKTAG
#define MKTAG(a, b, c, d)
Definition: macros.h:55
DVB_PRIVATE_NETWORK_START
#define DVB_PRIVATE_NETWORK_START
Definition: mpegtsenc.c:49
AVDictionaryEntry::value
char * value
Definition: dict.h:92
pkt
static AVPacket * pkt
Definition: demux_decode.c:55
AV_RB24
uint64_t_TMPL AV_WL64 unsigned int_TMPL AV_WL32 unsigned int_TMPL AV_WL24 unsigned int_TMPL AV_WL16 uint64_t_TMPL AV_WB64 unsigned int_TMPL AV_WB32 unsigned int_TMPL AV_RB24
Definition: bytestream.h:97
DEFAULT_PES_PAYLOAD_SIZE
#define DEFAULT_PES_PAYLOAD_SIZE
Definition: mpegtsenc.c:139
STREAM_TYPE_BLURAY_SUBTITLE_PGS
#define STREAM_TYPE_BLURAY_SUBTITLE_PGS
Definition: mpegts.h:165
AV_CODEC_ID_MPEG2VIDEO
@ AV_CODEC_ID_MPEG2VIDEO
preferred ID for MPEG-1/2 video decoding
Definition: codec_id.h:54
AV_OPT_TYPE_CONST
@ AV_OPT_TYPE_CONST
Special option type for declaring named constants.
Definition: opt.h:299
snprintf
#define snprintf
Definition: snprintf.h:34
AVCodecParameters::initial_padding
int initial_padding
Audio only.
Definition: codec_par.h:203
ff_stream_add_bitstream_filter
int ff_stream_add_bitstream_filter(AVStream *st, const char *name, const char *args)
Add a bitstream filter to a stream.
Definition: mux.c:1294
DVBAC3Descriptor::mainid_flag
uint8_t mainid_flag
Definition: mpegts.h:273
MpegTSSection::discontinuity
int discontinuity
Definition: mpegtsenc.c:57
MPEGTS_FLAG_OMIT_RAI
#define MPEGTS_FLAG_OMIT_RAI
Definition: mpegtsenc.c:121
encode_str8
static int encode_str8(uint8_t *buf, const char *str)
Definition: mpegtsenc.c:934
duration
static int64_t duration
Definition: ffplay.c:329
avcodec_parameters_copy
int avcodec_parameters_copy(AVCodecParameters *dst, const AVCodecParameters *src)
Copy the contents of src to dst.
Definition: codec_par.c:107
MpegTSWrite::mux_rate
int mux_rate
set to 1 when VBR
Definition: mpegtsenc.c:97
AV_RB16
uint64_t_TMPL AV_WL64 unsigned int_TMPL AV_WL32 unsigned int_TMPL AV_WL24 unsigned int_TMPL AV_WL16 uint64_t_TMPL AV_WB64 unsigned int_TMPL AV_WB32 unsigned int_TMPL AV_WB24 unsigned int_TMPL AV_RB16
Definition: bytestream.h:98
ff_check_h264_startcode
int ff_check_h264_startcode(AVFormatContext *s, const AVStream *st, const AVPacket *pkt)
Check presence of H264 startcode.
Definition: mpegtsenc.c:1794
put_arib_caption_descriptor
static int put_arib_caption_descriptor(AVFormatContext *s, uint8_t **q_ptr, AVCodecParameters *codecpar)
Definition: mpegtsenc.c:299
mux.h