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