FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
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 
30 #include "libavcodec/internal.h"
31 
32 #include "avformat.h"
33 #include "avio_internal.h"
34 #include "internal.h"
35 #include "mpegts.h"
36 
37 #define PCR_TIME_BASE 27000000
38 
39 /* write DVB SI sections */
40 
41 #define DVB_PRIVATE_NETWORK_START 0xff01
42 
43 /*********************************************/
44 /* mpegts section writer */
45 
46 typedef struct MpegTSSection {
47  int pid;
48  int cc;
49  void (*write_packet)(struct MpegTSSection *s, const uint8_t *packet);
50  void *opaque;
52 
53 typedef struct MpegTSService {
54  MpegTSSection pmt; /* MPEG-2 PMT table context */
55  int sid; /* service ID */
56  char *name;
58  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 */
85  int onid;
86  int tsid;
87  int64_t first_pcr;
88  int mux_rate; ///< set to 1 when VBR
90 
95 
97  int start_pid;
98  int m2ts_mode;
99 
100  int reemit_pat_pmt; // backward compatibility
101 
103 #define MPEGTS_FLAG_REEMIT_PAT_PMT 0x01
104 #define MPEGTS_FLAG_AAC_LATM 0x02
105 #define MPEGTS_FLAG_PAT_PMT_AT_FRAMES 0x04
106 #define MPEGTS_FLAG_SYSTEM_B 0x08
107  int flags;
108  int copyts;
110  double pat_period;
111  double sdt_period;
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 (first)
157  *q++ = 0; /* 0 offset */
158  len1 = TS_PACKET_SIZE - (q - packet);
159  if (len1 > len)
160  len1 = len;
161  memcpy(q, buf_ptr, len1);
162  q += len1;
163  /* add known padding data */
164  left = TS_PACKET_SIZE - (q - packet);
165  if (left > 0)
166  memset(q, 0xff, left);
167 
168  s->write_packet(s, packet);
169 
170  buf_ptr += len1;
171  len -= len1;
172  }
173 }
174 
175 static inline void put16(uint8_t **q_ptr, int val)
176 {
177  uint8_t *q;
178  q = *q_ptr;
179  *q++ = val >> 8;
180  *q++ = val;
181  *q_ptr = q;
182 }
183 
184 static int mpegts_write_section1(MpegTSSection *s, int tid, int id,
185  int version, int sec_num, int last_sec_num,
186  uint8_t *buf, int len)
187 {
188  uint8_t section[1024], *q;
189  unsigned int tot_len;
190  /* reserved_future_use field must be set to 1 for SDT */
191  unsigned int flags = tid == SDT_TID ? 0xf000 : 0xb000;
192 
193  tot_len = 3 + 5 + len + 4;
194  /* check if not too big */
195  if (tot_len > 1024)
196  return AVERROR_INVALIDDATA;
197 
198  q = section;
199  *q++ = tid;
200  put16(&q, flags | (len + 5 + 4)); /* 5 byte header + 4 byte CRC */
201  put16(&q, id);
202  *q++ = 0xc1 | (version << 1); /* current_next_indicator = 1 */
203  *q++ = sec_num;
204  *q++ = last_sec_num;
205  memcpy(q, buf, len);
206 
207  mpegts_write_section(s, section, tot_len);
208  return 0;
209 }
210 
211 /*********************************************/
212 /* mpegts writer */
213 
214 #define DEFAULT_PROVIDER_NAME "FFmpeg"
215 #define DEFAULT_SERVICE_NAME "Service01"
216 
217 /* we retransmit the SI info at this rate */
218 #define SDT_RETRANS_TIME 500
219 #define PAT_RETRANS_TIME 100
220 #define PCR_RETRANS_TIME 20
221 
222 typedef struct MpegTSWriteStream {
224  int pid; /* stream associated pid */
225  int cc;
227  int first_pts_check; ///< first pts check needed
229  int64_t payload_pts;
230  int64_t payload_dts;
235 
236  /* For Opus */
240 
242 {
243  MpegTSWrite *ts = s->priv_data;
244  MpegTSService *service;
246  int i;
247 
248  q = data;
249  for (i = 0; i < ts->nb_services; i++) {
250  service = ts->services[i];
251  put16(&q, service->sid);
252  put16(&q, 0xe000 | service->pmt.pid);
253  }
254  mpegts_write_section1(&ts->pat, PAT_TID, ts->tsid, ts->tables_version, 0, 0,
255  data, q - data);
256 }
257 
259 {
260  MpegTSWrite *ts = s->priv_data;
261  uint8_t data[SECTION_LENGTH], *q, *desc_length_ptr, *program_info_length_ptr;
262  int val, stream_type, i, err = 0;
263 
264  q = data;
265  put16(&q, 0xe000 | service->pcr_pid);
266 
267  program_info_length_ptr = q;
268  q += 2; /* patched after */
269 
270  /* put program info here */
271 
272  val = 0xf000 | (q - program_info_length_ptr - 2);
273  program_info_length_ptr[0] = val >> 8;
274  program_info_length_ptr[1] = val;
275 
276  for (i = 0; i < s->nb_streams; i++) {
277  AVStream *st = s->streams[i];
278  MpegTSWriteStream *ts_st = st->priv_data;
279  AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL, 0);
280 
281  if (s->nb_programs) {
282  int k, found = 0;
283  AVProgram *program = service->program;
284 
285  for (k = 0; k < program->nb_stream_indexes; k++)
286  if (program->stream_index[k] == i) {
287  found = 1;
288  break;
289  }
290 
291  if (!found)
292  continue;
293  }
294 
295  if (q - data > SECTION_LENGTH - 32) {
296  err = 1;
297  break;
298  }
299  switch (st->codecpar->codec_id) {
302  stream_type = STREAM_TYPE_VIDEO_MPEG2;
303  break;
304  case AV_CODEC_ID_MPEG4:
305  stream_type = STREAM_TYPE_VIDEO_MPEG4;
306  break;
307  case AV_CODEC_ID_H264:
308  stream_type = STREAM_TYPE_VIDEO_H264;
309  break;
310  case AV_CODEC_ID_HEVC:
311  stream_type = STREAM_TYPE_VIDEO_HEVC;
312  break;
313  case AV_CODEC_ID_CAVS:
314  stream_type = STREAM_TYPE_VIDEO_CAVS;
315  break;
316  case AV_CODEC_ID_DIRAC:
317  stream_type = STREAM_TYPE_VIDEO_DIRAC;
318  break;
319  case AV_CODEC_ID_VC1:
320  stream_type = STREAM_TYPE_VIDEO_VC1;
321  break;
322  case AV_CODEC_ID_MP2:
323  case AV_CODEC_ID_MP3:
324  if ( st->codecpar->sample_rate > 0
325  && st->codecpar->sample_rate < 32000) {
326  stream_type = STREAM_TYPE_AUDIO_MPEG2;
327  } else {
328  stream_type = STREAM_TYPE_AUDIO_MPEG1;
329  }
330  break;
331  case AV_CODEC_ID_AAC:
332  stream_type = (ts->flags & MPEGTS_FLAG_AAC_LATM)
335  break;
337  stream_type = STREAM_TYPE_AUDIO_AAC_LATM;
338  break;
339  case AV_CODEC_ID_AC3:
340  stream_type = (ts->flags & MPEGTS_FLAG_SYSTEM_B)
343  break;
344  case AV_CODEC_ID_EAC3:
345  stream_type = (ts->flags & MPEGTS_FLAG_SYSTEM_B)
348  break;
349  case AV_CODEC_ID_DTS:
350  stream_type = STREAM_TYPE_AUDIO_DTS;
351  break;
352  case AV_CODEC_ID_TRUEHD:
353  stream_type = STREAM_TYPE_AUDIO_TRUEHD;
354  break;
355  case AV_CODEC_ID_OPUS:
356  stream_type = STREAM_TYPE_PRIVATE_DATA;
357  break;
359  stream_type = STREAM_TYPE_METADATA;
360  break;
361  default:
362  stream_type = STREAM_TYPE_PRIVATE_DATA;
363  break;
364  }
365 
366  *q++ = stream_type;
367  put16(&q, 0xe000 | ts_st->pid);
368  desc_length_ptr = q;
369  q += 2; /* patched after */
370 
371  /* write optional descriptors here */
372  switch (st->codecpar->codec_type) {
373  case AVMEDIA_TYPE_AUDIO:
375  *q++=0x6a; // AC3 descriptor see A038 DVB SI
376  *q++=1; // 1 byte, all flags sets to 0
377  *q++=0; // omit all fields...
378  }
380  *q++=0x7a; // EAC3 descriptor see A038 DVB SI
381  *q++=1; // 1 byte, all flags sets to 0
382  *q++=0; // omit all fields...
383  }
384  if (st->codecpar->codec_id==AV_CODEC_ID_S302M) {
385  *q++ = 0x05; /* MPEG-2 registration descriptor*/
386  *q++ = 4;
387  *q++ = 'B';
388  *q++ = 'S';
389  *q++ = 'S';
390  *q++ = 'D';
391  }
392  if (st->codecpar->codec_id==AV_CODEC_ID_OPUS) {
393  /* 6 bytes registration descriptor, 4 bytes Opus audio descriptor */
394  if (q - data > SECTION_LENGTH - 6 - 4) {
395  err = 1;
396  break;
397  }
398 
399  *q++ = 0x05; /* MPEG-2 registration descriptor*/
400  *q++ = 4;
401  *q++ = 'O';
402  *q++ = 'p';
403  *q++ = 'u';
404  *q++ = 's';
405 
406  *q++ = 0x7f; /* DVB extension descriptor */
407  *q++ = 2;
408  *q++ = 0x80;
409 
410  if (st->codecpar->extradata && st->codecpar->extradata_size >= 19) {
411  if (st->codecpar->extradata[18] == 0 && st->codecpar->channels <= 2) {
412  /* RTP mapping family */
413  *q++ = st->codecpar->channels;
414  } else if (st->codecpar->extradata[18] == 1 && st->codecpar->channels <= 8 &&
415  st->codecpar->extradata_size >= 21 + st->codecpar->channels) {
416  static const uint8_t coupled_stream_counts[9] = {
417  1, 0, 1, 1, 2, 2, 2, 3, 3
418  };
419  static const uint8_t channel_map_a[8][8] = {
420  {0},
421  {0, 1},
422  {0, 2, 1},
423  {0, 1, 2, 3},
424  {0, 4, 1, 2, 3},
425  {0, 4, 1, 2, 3, 5},
426  {0, 4, 1, 2, 3, 5, 6},
427  {0, 6, 1, 2, 3, 4, 5, 7},
428  };
429  static const uint8_t channel_map_b[8][8] = {
430  {0},
431  {0, 1},
432  {0, 1, 2},
433  {0, 1, 2, 3},
434  {0, 1, 2, 3, 4},
435  {0, 1, 2, 3, 4, 5},
436  {0, 1, 2, 3, 4, 5, 6},
437  {0, 1, 2, 3, 4, 5, 6, 7},
438  };
439  /* Vorbis mapping family */
440 
441  if (st->codecpar->extradata[19] == st->codecpar->channels - coupled_stream_counts[st->codecpar->channels] &&
442  st->codecpar->extradata[20] == coupled_stream_counts[st->codecpar->channels] &&
443  memcmp(&st->codecpar->extradata[21], channel_map_a[st->codecpar->channels-1], st->codecpar->channels) == 0) {
444  *q++ = st->codecpar->channels;
445  } else if (st->codecpar->channels >= 2 && st->codecpar->extradata[19] == st->codecpar->channels &&
446  st->codecpar->extradata[20] == 0 &&
447  memcmp(&st->codecpar->extradata[21], channel_map_b[st->codecpar->channels-1], st->codecpar->channels) == 0) {
448  *q++ = st->codecpar->channels | 0x80;
449  } else {
450  /* Unsupported, could write an extended descriptor here */
451  av_log(s, AV_LOG_ERROR, "Unsupported Opus Vorbis-style channel mapping");
452  *q++ = 0xff;
453  }
454  } else {
455  /* Unsupported */
456  av_log(s, AV_LOG_ERROR, "Unsupported Opus channel mapping for family %d", st->codecpar->extradata[18]);
457  *q++ = 0xff;
458  }
459  } else if (st->codecpar->channels <= 2) {
460  /* Assume RTP mapping family */
461  *q++ = st->codecpar->channels;
462  } else {
463  /* Unsupported */
464  av_log(s, AV_LOG_ERROR, "Unsupported Opus channel mapping");
465  *q++ = 0xff;
466  }
467  }
468 
469  if (lang) {
470  char *p;
471  char *next = lang->value;
472  uint8_t *len_ptr;
473 
474  *q++ = 0x0a; /* ISO 639 language descriptor */
475  len_ptr = q++;
476  *len_ptr = 0;
477 
478  for (p = lang->value; next && *len_ptr < 255 / 4 * 4; p = next + 1) {
479  if (q - data > SECTION_LENGTH - 4) {
480  err = 1;
481  break;
482  }
483  next = strchr(p, ',');
484  if (strlen(p) != 3 && (!next || next != p + 3))
485  continue; /* not a 3-letter code */
486 
487  *q++ = *p++;
488  *q++ = *p++;
489  *q++ = *p++;
490 
492  *q++ = 0x01;
494  *q++ = 0x02;
496  *q++ = 0x03;
497  else
498  *q++ = 0; /* undefined type */
499 
500  *len_ptr += 4;
501  }
502 
503  if (*len_ptr == 0)
504  q -= 2; /* no language codes were written */
505  }
506  break;
508  {
509  const char default_language[] = "und";
510  const char *language = lang && strlen(lang->value) >= 3 ? lang->value : default_language;
511 
513  uint8_t *len_ptr;
514  int extradata_copied = 0;
515 
516  *q++ = 0x59; /* subtitling_descriptor */
517  len_ptr = q++;
518 
519  while (strlen(language) >= 3) {
520  if (sizeof(data) - (q - data) < 8) { /* 8 bytes per DVB subtitle substream data */
521  err = 1;
522  break;
523  }
524  *q++ = *language++;
525  *q++ = *language++;
526  *q++ = *language++;
527  /* Skip comma */
528  if (*language != '\0')
529  language++;
530 
531  if (st->codecpar->extradata_size - extradata_copied >= 5) {
532  *q++ = st->codecpar->extradata[extradata_copied + 4]; /* subtitling_type */
533  memcpy(q, st->codecpar->extradata + extradata_copied, 4); /* composition_page_id and ancillary_page_id */
534  extradata_copied += 5;
535  q += 4;
536  } else {
537  /* subtitling_type:
538  * 0x10 - normal with no monitor aspect ratio criticality
539  * 0x20 - for the hard of hearing with no monitor aspect ratio criticality */
540  *q++ = (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED) ? 0x20 : 0x10;
541  if ((st->codecpar->extradata_size == 4) && (extradata_copied == 0)) {
542  /* support of old 4-byte extradata format */
543  memcpy(q, st->codecpar->extradata, 4); /* composition_page_id and ancillary_page_id */
544  extradata_copied += 4;
545  q += 4;
546  } else {
547  put16(&q, 1); /* composition_page_id */
548  put16(&q, 1); /* ancillary_page_id */
549  }
550  }
551  }
552 
553  *len_ptr = q - len_ptr - 1;
554  } else if (st->codecpar->codec_id == AV_CODEC_ID_DVB_TELETEXT) {
555  uint8_t *len_ptr = NULL;
556  int extradata_copied = 0;
557 
558  /* The descriptor tag. teletext_descriptor */
559  *q++ = 0x56;
560  len_ptr = q++;
561 
562  while (strlen(language) >= 3 && q - data < sizeof(data) - 6) {
563  *q++ = *language++;
564  *q++ = *language++;
565  *q++ = *language++;
566  /* Skip comma */
567  if (*language != '\0')
568  language++;
569 
570  if (st->codecpar->extradata_size - 1 > extradata_copied) {
571  memcpy(q, st->codecpar->extradata + extradata_copied, 2);
572  extradata_copied += 2;
573  q += 2;
574  } else {
575  /* The Teletext descriptor:
576  * teletext_type: This 5-bit field indicates the type of Teletext page indicated. (0x01 Initial Teletext page)
577  * teletext_magazine_number: This is a 3-bit field which identifies the magazine number.
578  * teletext_page_number: This is an 8-bit field giving two 4-bit hex digits identifying the page number. */
579  *q++ = 0x08;
580  *q++ = 0x00;
581  }
582  }
583 
584  *len_ptr = q - len_ptr - 1;
585  }
586  }
587  break;
588  case AVMEDIA_TYPE_VIDEO:
589  if (stream_type == STREAM_TYPE_VIDEO_DIRAC) {
590  *q++ = 0x05; /*MPEG-2 registration descriptor*/
591  *q++ = 4;
592  *q++ = 'd';
593  *q++ = 'r';
594  *q++ = 'a';
595  *q++ = 'c';
596  } else if (stream_type == STREAM_TYPE_VIDEO_VC1) {
597  *q++ = 0x05; /*MPEG-2 registration descriptor*/
598  *q++ = 4;
599  *q++ = 'V';
600  *q++ = 'C';
601  *q++ = '-';
602  *q++ = '1';
603  }
604  break;
605  case AVMEDIA_TYPE_DATA:
607  *q++ = 0x05; /* MPEG-2 registration descriptor */
608  *q++ = 4;
609  *q++ = 'K';
610  *q++ = 'L';
611  *q++ = 'V';
612  *q++ = 'A';
613  } else if (st->codecpar->codec_id == AV_CODEC_ID_TIMED_ID3) {
614  *q++ = 0x5; /* MPEG-2 registration descriptor */
615  *q++ = 4;
616  *q++ = 'I';
617  *q++ = 'D';
618  *q++ = '3';
619  *q++ = ' ';
620  }
621  break;
622  }
623 
624  val = 0xf000 | (q - desc_length_ptr - 2);
625  desc_length_ptr[0] = val >> 8;
626  desc_length_ptr[1] = val;
627  }
628 
629  if (err)
630  av_log(s, AV_LOG_ERROR,
631  "The PMT section cannot fit stream %d and all following streams.\n"
632  "Try reducing the number of languages in the audio streams "
633  "or the total number of streams.\n", i);
634 
635  mpegts_write_section1(&service->pmt, PMT_TID, service->sid, ts->tables_version, 0, 0,
636  data, q - data);
637  return 0;
638 }
639 
640 /* NOTE: !str is accepted for an empty string */
641 static void putstr8(uint8_t **q_ptr, const char *str)
642 {
643  uint8_t *q;
644  int len;
645 
646  q = *q_ptr;
647  if (!str)
648  len = 0;
649  else
650  len = strlen(str);
651  *q++ = len;
652  memcpy(q, str, len);
653  q += len;
654  *q_ptr = q;
655 }
656 
658 {
659  MpegTSWrite *ts = s->priv_data;
660  MpegTSService *service;
661  uint8_t data[SECTION_LENGTH], *q, *desc_list_len_ptr, *desc_len_ptr;
662  int i, running_status, free_ca_mode, val;
663 
664  q = data;
665  put16(&q, ts->onid);
666  *q++ = 0xff;
667  for (i = 0; i < ts->nb_services; i++) {
668  service = ts->services[i];
669  put16(&q, service->sid);
670  *q++ = 0xfc | 0x00; /* currently no EIT info */
671  desc_list_len_ptr = q;
672  q += 2;
673  running_status = 4; /* running */
674  free_ca_mode = 0;
675 
676  /* write only one descriptor for the service name and provider */
677  *q++ = 0x48;
678  desc_len_ptr = q;
679  q++;
680  *q++ = ts->service_type;
681  putstr8(&q, service->provider_name);
682  putstr8(&q, service->name);
683  desc_len_ptr[0] = q - desc_len_ptr - 1;
684 
685  /* fill descriptor length */
686  val = (running_status << 13) | (free_ca_mode << 12) |
687  (q - desc_list_len_ptr - 2);
688  desc_list_len_ptr[0] = val >> 8;
689  desc_list_len_ptr[1] = val;
690  }
691  mpegts_write_section1(&ts->sdt, SDT_TID, ts->tsid, ts->tables_version, 0, 0,
692  data, q - data);
693 }
694 
696  const char *provider_name,
697  const char *name)
698 {
699  MpegTSService *service;
700 
701  service = av_mallocz(sizeof(MpegTSService));
702  if (!service)
703  return NULL;
704  service->pmt.pid = ts->pmt_start_pid + ts->nb_services;
705  service->sid = sid;
706  service->pcr_pid = 0x1fff;
707  service->provider_name = av_strdup(provider_name);
708  service->name = av_strdup(name);
709  if (!service->provider_name || !service->name)
710  goto fail;
711  if (av_dynarray_add_nofree(&ts->services, &ts->nb_services, service) < 0)
712  goto fail;
713 
714  return service;
715 fail:
716  av_freep(&service->provider_name);
717  av_freep(&service->name);
718  av_free(service);
719  return NULL;
720 }
721 
722 static int64_t get_pcr(const MpegTSWrite *ts, AVIOContext *pb)
723 {
724  return av_rescale(avio_tell(pb) + 11, 8 * PCR_TIME_BASE, ts->mux_rate) +
725  ts->first_pcr;
726 }
727 
729 {
730  MpegTSWrite *ts = s->priv_data;
731  if (ts->m2ts_mode) {
732  int64_t pcr = get_pcr(s->priv_data, s->pb);
733  uint32_t tp_extra_header = pcr % 0x3fffffff;
734  tp_extra_header = AV_RB32(&tp_extra_header);
735  avio_write(s->pb, (unsigned char *) &tp_extra_header,
736  sizeof(tp_extra_header));
737  }
738 }
739 
740 static void section_write_packet(MpegTSSection *s, const uint8_t *packet)
741 {
742  AVFormatContext *ctx = s->opaque;
744  avio_write(ctx->pb, packet, TS_PACKET_SIZE);
745 }
746 
748 {
749  MpegTSWrite *ts = s->priv_data;
750  MpegTSWriteStream *ts_st;
751  MpegTSService *service;
752  AVStream *st, *pcr_st = NULL;
753  AVDictionaryEntry *title, *provider;
754  int i, j;
755  const char *service_name;
756  const char *provider_name;
757  int *pids;
758  int ret;
759 
760  if (s->max_delay < 0) /* Not set by the caller */
761  s->max_delay = 0;
762 
763  // round up to a whole number of TS packets
764  ts->pes_payload_size = (ts->pes_payload_size + 14 + 183) / 184 * 184 - 14;
765 
766  ts->tsid = ts->transport_stream_id;
767  ts->onid = ts->original_network_id;
768  if (!s->nb_programs) {
769  /* allocate a single DVB service */
770  title = av_dict_get(s->metadata, "service_name", NULL, 0);
771  if (!title)
772  title = av_dict_get(s->metadata, "title", NULL, 0);
773  service_name = title ? title->value : DEFAULT_SERVICE_NAME;
774  provider = av_dict_get(s->metadata, "service_provider", NULL, 0);
775  provider_name = provider ? provider->value : DEFAULT_PROVIDER_NAME;
776  service = mpegts_add_service(ts, ts->service_id,
777  provider_name, service_name);
778 
779  if (!service)
780  return AVERROR(ENOMEM);
781 
783  service->pmt.opaque = s;
784  service->pmt.cc = 15;
785  } else {
786  for (i = 0; i < s->nb_programs; i++) {
787  AVProgram *program = s->programs[i];
788  title = av_dict_get(program->metadata, "service_name", NULL, 0);
789  if (!title)
790  title = av_dict_get(program->metadata, "title", NULL, 0);
791  service_name = title ? title->value : DEFAULT_SERVICE_NAME;
792  provider = av_dict_get(program->metadata, "service_provider", NULL, 0);
793  provider_name = provider ? provider->value : DEFAULT_PROVIDER_NAME;
794  service = mpegts_add_service(ts, program->id,
795  provider_name, service_name);
796 
797  if (!service)
798  return AVERROR(ENOMEM);
799 
801  service->pmt.opaque = s;
802  service->pmt.cc = 15;
803  service->program = program;
804  }
805  }
806 
807  ts->pat.pid = PAT_PID;
808  /* Initialize at 15 so that it wraps and is equal to 0 for the
809  * first packet we write. */
810  ts->pat.cc = 15;
812  ts->pat.opaque = s;
813 
814  ts->sdt.pid = SDT_PID;
815  ts->sdt.cc = 15;
817  ts->sdt.opaque = s;
818 
819  pids = av_malloc_array(s->nb_streams, sizeof(*pids));
820  if (!pids) {
821  ret = AVERROR(ENOMEM);
822  goto fail;
823  }
824 
825  /* assign pids to each stream */
826  for (i = 0; i < s->nb_streams; i++) {
828  st = s->streams[i];
829 
830  ts_st = av_mallocz(sizeof(MpegTSWriteStream));
831  if (!ts_st) {
832  ret = AVERROR(ENOMEM);
833  goto fail;
834  }
835  st->priv_data = ts_st;
836 
837  ts_st->user_tb = st->time_base;
838  avpriv_set_pts_info(st, 33, 1, 90000);
839 
840  ts_st->payload = av_mallocz(ts->pes_payload_size);
841  if (!ts_st->payload) {
842  ret = AVERROR(ENOMEM);
843  goto fail;
844  }
845 
846  program = av_find_program_from_stream(s, NULL, i);
847  if (program) {
848  for (j = 0; j < ts->nb_services; j++) {
849  if (ts->services[j]->program == program) {
850  service = ts->services[j];
851  break;
852  }
853  }
854  }
855 
856  ts_st->service = service;
857  /* MPEG pid values < 16 are reserved. Applications which set st->id in
858  * this range are assigned a calculated pid. */
859  if (st->id < 16) {
860  ts_st->pid = ts->start_pid + i;
861  } else if (st->id < 0x1FFF) {
862  ts_st->pid = st->id;
863  } else {
864  av_log(s, AV_LOG_ERROR,
865  "Invalid stream id %d, must be less than 8191\n", st->id);
866  ret = AVERROR(EINVAL);
867  goto fail;
868  }
869  if (ts_st->pid == service->pmt.pid) {
870  av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
871  ret = AVERROR(EINVAL);
872  goto fail;
873  }
874  for (j = 0; j < i; j++) {
875  if (pids[j] == ts_st->pid) {
876  av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
877  ret = AVERROR(EINVAL);
878  goto fail;
879  }
880  }
881  pids[i] = ts_st->pid;
882  ts_st->payload_pts = AV_NOPTS_VALUE;
883  ts_st->payload_dts = AV_NOPTS_VALUE;
884  ts_st->first_pts_check = 1;
885  ts_st->cc = 15;
886  /* update PCR pid by using the first video stream */
887  if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
888  service->pcr_pid == 0x1fff) {
889  service->pcr_pid = ts_st->pid;
890  pcr_st = st;
891  }
892  if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
893  st->codecpar->extradata_size > 0) {
894  AVStream *ast;
895  ts_st->amux = avformat_alloc_context();
896  if (!ts_st->amux) {
897  ret = AVERROR(ENOMEM);
898  goto fail;
899  }
900  ts_st->amux->oformat =
901  av_guess_format((ts->flags & MPEGTS_FLAG_AAC_LATM) ? "latm" : "adts",
902  NULL, NULL);
903  if (!ts_st->amux->oformat) {
904  ret = AVERROR(EINVAL);
905  goto fail;
906  }
907  if (!(ast = avformat_new_stream(ts_st->amux, NULL))) {
908  ret = AVERROR(ENOMEM);
909  goto fail;
910  }
911  ret = avcodec_parameters_copy(ast->codecpar, st->codecpar);
912  if (ret != 0)
913  goto fail;
914  ast->time_base = st->time_base;
915  ret = avformat_write_header(ts_st->amux, NULL);
916  if (ret < 0)
917  goto fail;
918  }
919  if (st->codecpar->codec_id == AV_CODEC_ID_OPUS) {
921  }
922  }
923 
924  av_freep(&pids);
925 
926  /* if no video stream, use the first stream as PCR */
927  if (service->pcr_pid == 0x1fff && s->nb_streams > 0) {
928  pcr_st = s->streams[0];
929  ts_st = pcr_st->priv_data;
930  service->pcr_pid = ts_st->pid;
931  } else
932  ts_st = pcr_st->priv_data;
933 
934  if (ts->mux_rate > 1) {
935  service->pcr_packet_period = (int64_t)ts->mux_rate * ts->pcr_period /
936  (TS_PACKET_SIZE * 8 * 1000);
937  ts->sdt_packet_period = (int64_t)ts->mux_rate * SDT_RETRANS_TIME /
938  (TS_PACKET_SIZE * 8 * 1000);
939  ts->pat_packet_period = (int64_t)ts->mux_rate * PAT_RETRANS_TIME /
940  (TS_PACKET_SIZE * 8 * 1000);
941 
942  if (ts->copyts < 1)
944  } else {
945  /* Arbitrary values, PAT/PMT will also be written on video key frames */
946  ts->sdt_packet_period = 200;
947  ts->pat_packet_period = 40;
948  if (pcr_st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
950  if (!frame_size) {
951  av_log(s, AV_LOG_WARNING, "frame size not set\n");
952  service->pcr_packet_period =
953  pcr_st->codecpar->sample_rate / (10 * 512);
954  } else {
955  service->pcr_packet_period =
956  pcr_st->codecpar->sample_rate / (10 * frame_size);
957  }
958  } else {
959  // max delta PCR 0.1s
960  // TODO: should be avg_frame_rate
961  service->pcr_packet_period =
962  ts_st->user_tb.den / (10 * ts_st->user_tb.num);
963  }
964  if (!service->pcr_packet_period)
965  service->pcr_packet_period = 1;
966  }
967 
970  // The user specified a period, use only it
971  if (ts->pat_period < INT_MAX/2) {
972  ts->pat_packet_period = INT_MAX;
973  }
974  if (ts->sdt_period < INT_MAX/2) {
975  ts->sdt_packet_period = INT_MAX;
976  }
977 
978  // output a PCR as soon as possible
979  service->pcr_packet_count = service->pcr_packet_period;
980  ts->pat_packet_count = ts->pat_packet_period - 1;
981  ts->sdt_packet_count = ts->sdt_packet_period - 1;
982 
983  if (ts->mux_rate == 1)
984  av_log(s, AV_LOG_VERBOSE, "muxrate VBR, ");
985  else
986  av_log(s, AV_LOG_VERBOSE, "muxrate %d, ", ts->mux_rate);
988  "pcr every %d pkts, sdt every %d, pat/pmt every %d pkts\n",
989  service->pcr_packet_period,
991 
992  if (ts->m2ts_mode == -1) {
993  if (av_match_ext(s->filename, "m2ts")) {
994  ts->m2ts_mode = 1;
995  } else {
996  ts->m2ts_mode = 0;
997  }
998  }
999 
1000  return 0;
1001 
1002 fail:
1003  av_freep(&pids);
1004  return ret;
1005 }
1006 
1007 /* send SDT, PAT and PMT tables regularly */
1008 static void retransmit_si_info(AVFormatContext *s, int force_pat, int64_t dts)
1009 {
1010  MpegTSWrite *ts = s->priv_data;
1011  int i;
1012 
1013  if (++ts->sdt_packet_count == ts->sdt_packet_period ||
1014  (dts != AV_NOPTS_VALUE && ts->last_sdt_ts == AV_NOPTS_VALUE) ||
1015  (dts != AV_NOPTS_VALUE && dts - ts->last_sdt_ts >= ts->sdt_period*90000.0)
1016  ) {
1017  ts->sdt_packet_count = 0;
1018  if (dts != AV_NOPTS_VALUE)
1019  ts->last_sdt_ts = FFMAX(dts, ts->last_sdt_ts);
1020  mpegts_write_sdt(s);
1021  }
1022  if (++ts->pat_packet_count == ts->pat_packet_period ||
1023  (dts != AV_NOPTS_VALUE && ts->last_pat_ts == AV_NOPTS_VALUE) ||
1024  (dts != AV_NOPTS_VALUE && dts - ts->last_pat_ts >= ts->pat_period*90000.0) ||
1025  force_pat) {
1026  ts->pat_packet_count = 0;
1027  if (dts != AV_NOPTS_VALUE)
1028  ts->last_pat_ts = FFMAX(dts, ts->last_pat_ts);
1029  mpegts_write_pat(s);
1030  for (i = 0; i < ts->nb_services; i++)
1031  mpegts_write_pmt(s, ts->services[i]);
1032  }
1033 }
1034 
1035 static int write_pcr_bits(uint8_t *buf, int64_t pcr)
1036 {
1037  int64_t pcr_low = pcr % 300, pcr_high = pcr / 300;
1038 
1039  *buf++ = pcr_high >> 25;
1040  *buf++ = pcr_high >> 17;
1041  *buf++ = pcr_high >> 9;
1042  *buf++ = pcr_high >> 1;
1043  *buf++ = pcr_high << 7 | pcr_low >> 8 | 0x7e;
1044  *buf++ = pcr_low;
1045 
1046  return 6;
1047 }
1048 
1049 /* Write a single null transport stream packet */
1051 {
1052  uint8_t *q;
1054 
1055  q = buf;
1056  *q++ = 0x47;
1057  *q++ = 0x00 | 0x1f;
1058  *q++ = 0xff;
1059  *q++ = 0x10;
1060  memset(q, 0x0FF, TS_PACKET_SIZE - (q - buf));
1062  avio_write(s->pb, buf, TS_PACKET_SIZE);
1063 }
1064 
1065 /* Write a single transport stream packet with a PCR and no payload */
1067 {
1068  MpegTSWrite *ts = s->priv_data;
1069  MpegTSWriteStream *ts_st = st->priv_data;
1070  uint8_t *q;
1072 
1073  q = buf;
1074  *q++ = 0x47;
1075  *q++ = ts_st->pid >> 8;
1076  *q++ = ts_st->pid;
1077  *q++ = 0x20 | ts_st->cc; /* Adaptation only */
1078  /* Continuity Count field does not increment (see 13818-1 section 2.4.3.3) */
1079  *q++ = TS_PACKET_SIZE - 5; /* Adaptation Field Length */
1080  *q++ = 0x10; /* Adaptation flags: PCR present */
1081 
1082  /* PCR coded into 6 bytes */
1083  q += write_pcr_bits(q, get_pcr(ts, s->pb));
1084 
1085  /* stuffing bytes */
1086  memset(q, 0xFF, TS_PACKET_SIZE - (q - buf));
1088  avio_write(s->pb, buf, TS_PACKET_SIZE);
1089 }
1090 
1091 static void write_pts(uint8_t *q, int fourbits, int64_t pts)
1092 {
1093  int val;
1094 
1095  val = fourbits << 4 | (((pts >> 30) & 0x07) << 1) | 1;
1096  *q++ = val;
1097  val = (((pts >> 15) & 0x7fff) << 1) | 1;
1098  *q++ = val >> 8;
1099  *q++ = val;
1100  val = (((pts) & 0x7fff) << 1) | 1;
1101  *q++ = val >> 8;
1102  *q++ = val;
1103 }
1104 
1105 /* Set an adaptation field flag in an MPEG-TS packet*/
1106 static void set_af_flag(uint8_t *pkt, int flag)
1107 {
1108  // expect at least one flag to set
1109  av_assert0(flag);
1110 
1111  if ((pkt[3] & 0x20) == 0) {
1112  // no AF yet, set adaptation field flag
1113  pkt[3] |= 0x20;
1114  // 1 byte length, no flags
1115  pkt[4] = 1;
1116  pkt[5] = 0;
1117  }
1118  pkt[5] |= flag;
1119 }
1120 
1121 /* Extend the adaptation field by size bytes */
1122 static void extend_af(uint8_t *pkt, int size)
1123 {
1124  // expect already existing adaptation field
1125  av_assert0(pkt[3] & 0x20);
1126  pkt[4] += size;
1127 }
1128 
1129 /* Get a pointer to MPEG-TS payload (right after TS packet header) */
1131 {
1132  if (pkt[3] & 0x20)
1133  return pkt + 5 + pkt[4];
1134  else
1135  return pkt + 4;
1136 }
1137 
1138 /* Add a PES header to the front of the payload, and segment into an integer
1139  * number of TS packets. The final TS packet is padded using an oversized
1140  * adaptation header to exactly fill the last TS packet.
1141  * NOTE: 'payload' contains a complete PES payload. */
1143  const uint8_t *payload, int payload_size,
1144  int64_t pts, int64_t dts, int key, int stream_id)
1145 {
1146  MpegTSWriteStream *ts_st = st->priv_data;
1147  MpegTSWrite *ts = s->priv_data;
1149  uint8_t *q;
1150  int val, is_start, len, header_len, write_pcr, is_dvb_subtitle, is_dvb_teletext, flags;
1151  int afc_len, stuffing_len;
1152  int64_t pcr = -1; /* avoid warning */
1153  int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE);
1154  int force_pat = st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && key && !ts_st->prev_payload_key;
1155 
1156  av_assert0(ts_st->payload != buf || st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO);
1158  force_pat = 1;
1159  }
1160 
1161  is_start = 1;
1162  while (payload_size > 0) {
1163  retransmit_si_info(s, force_pat, dts);
1164  force_pat = 0;
1165 
1166  write_pcr = 0;
1167  if (ts_st->pid == ts_st->service->pcr_pid) {
1168  if (ts->mux_rate > 1 || is_start) // VBR pcr period is based on frames
1169  ts_st->service->pcr_packet_count++;
1170  if (ts_st->service->pcr_packet_count >=
1171  ts_st->service->pcr_packet_period) {
1172  ts_st->service->pcr_packet_count = 0;
1173  write_pcr = 1;
1174  }
1175  }
1176 
1177  if (ts->mux_rate > 1 && dts != AV_NOPTS_VALUE &&
1178  (dts - get_pcr(ts, s->pb) / 300) > delay) {
1179  /* pcr insert gets priority over null packet insert */
1180  if (write_pcr)
1181  mpegts_insert_pcr_only(s, st);
1182  else
1184  /* recalculate write_pcr and possibly retransmit si_info */
1185  continue;
1186  }
1187 
1188  /* prepare packet header */
1189  q = buf;
1190  *q++ = 0x47;
1191  val = ts_st->pid >> 8;
1192  if (is_start)
1193  val |= 0x40;
1194  *q++ = val;
1195  *q++ = ts_st->pid;
1196  ts_st->cc = ts_st->cc + 1 & 0xf;
1197  *q++ = 0x10 | ts_st->cc; // payload indicator + CC
1198  if (key && is_start && pts != AV_NOPTS_VALUE) {
1199  // set Random Access for key frames
1200  if (ts_st->pid == ts_st->service->pcr_pid)
1201  write_pcr = 1;
1202  set_af_flag(buf, 0x40);
1203  q = get_ts_payload_start(buf);
1204  }
1205  if (write_pcr) {
1206  set_af_flag(buf, 0x10);
1207  q = get_ts_payload_start(buf);
1208  // add 11, pcr references the last byte of program clock reference base
1209  if (ts->mux_rate > 1)
1210  pcr = get_pcr(ts, s->pb);
1211  else
1212  pcr = (dts - delay) * 300;
1213  if (dts != AV_NOPTS_VALUE && dts < pcr / 300)
1214  av_log(s, AV_LOG_WARNING, "dts < pcr, TS is invalid\n");
1215  extend_af(buf, write_pcr_bits(q, pcr));
1216  q = get_ts_payload_start(buf);
1217  }
1218  if (is_start) {
1219  int pes_extension = 0;
1220  int pes_header_stuffing_bytes = 0;
1221  /* write PES header */
1222  *q++ = 0x00;
1223  *q++ = 0x00;
1224  *q++ = 0x01;
1225  is_dvb_subtitle = 0;
1226  is_dvb_teletext = 0;
1227  if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
1228  if (st->codecpar->codec_id == AV_CODEC_ID_DIRAC)
1229  *q++ = 0xfd;
1230  else
1231  *q++ = 0xe0;
1232  } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
1233  (st->codecpar->codec_id == AV_CODEC_ID_MP2 ||
1234  st->codecpar->codec_id == AV_CODEC_ID_MP3 ||
1235  st->codecpar->codec_id == AV_CODEC_ID_AAC)) {
1236  *q++ = 0xc0;
1237  } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
1238  st->codecpar->codec_id == AV_CODEC_ID_AC3 &&
1239  ts->m2ts_mode) {
1240  *q++ = 0xfd;
1241  } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA &&
1243  *q++ = 0xbd;
1244  } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
1245  *q++ = stream_id != -1 ? stream_id : 0xfc;
1246 
1247  if (stream_id == 0xbd) /* asynchronous KLV */
1248  pts = dts = AV_NOPTS_VALUE;
1249  } else {
1250  *q++ = 0xbd;
1253  is_dvb_subtitle = 1;
1254  } else if (st->codecpar->codec_id == AV_CODEC_ID_DVB_TELETEXT) {
1255  is_dvb_teletext = 1;
1256  }
1257  }
1258  }
1259  header_len = 0;
1260  flags = 0;
1261  if (pts != AV_NOPTS_VALUE) {
1262  header_len += 5;
1263  flags |= 0x80;
1264  }
1265  if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
1266  header_len += 5;
1267  flags |= 0x40;
1268  }
1269  if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
1271  /* set PES_extension_flag */
1272  pes_extension = 1;
1273  flags |= 0x01;
1274 
1275  /* One byte for PES2 extension flag +
1276  * one byte for extension length +
1277  * one byte for extension id */
1278  header_len += 3;
1279  }
1280  /* for Blu-ray AC3 Audio the PES Extension flag should be as follow
1281  * otherwise it will not play sound on blu-ray
1282  */
1283  if (ts->m2ts_mode &&
1285  st->codecpar->codec_id == AV_CODEC_ID_AC3) {
1286  /* set PES_extension_flag */
1287  pes_extension = 1;
1288  flags |= 0x01;
1289  header_len += 3;
1290  }
1291  if (is_dvb_teletext) {
1292  pes_header_stuffing_bytes = 0x24 - header_len;
1293  header_len = 0x24;
1294  }
1295  len = payload_size + header_len + 3;
1296  /* 3 extra bytes should be added to DVB subtitle payload: 0x20 0x00 at the beginning and trailing 0xff */
1297  if (is_dvb_subtitle) {
1298  len += 3;
1299  payload_size++;
1300  }
1301  if (len > 0xffff)
1302  len = 0;
1304  len = 0;
1305  }
1306  *q++ = len >> 8;
1307  *q++ = len;
1308  val = 0x80;
1309  /* data alignment indicator is required for subtitle and data streams */
1311  val |= 0x04;
1312  *q++ = val;
1313  *q++ = flags;
1314  *q++ = header_len;
1315  if (pts != AV_NOPTS_VALUE) {
1316  write_pts(q, flags >> 6, pts);
1317  q += 5;
1318  }
1319  if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
1320  write_pts(q, 1, dts);
1321  q += 5;
1322  }
1323  if (pes_extension && st->codecpar->codec_id == AV_CODEC_ID_DIRAC) {
1324  flags = 0x01; /* set PES_extension_flag_2 */
1325  *q++ = flags;
1326  *q++ = 0x80 | 0x01; /* marker bit + extension length */
1327  /* Set the stream ID extension flag bit to 0 and
1328  * write the extended stream ID. */
1329  *q++ = 0x00 | 0x60;
1330  }
1331  /* For Blu-ray AC3 Audio Setting extended flags */
1332  if (ts->m2ts_mode &&
1333  pes_extension &&
1334  st->codecpar->codec_id == AV_CODEC_ID_AC3) {
1335  flags = 0x01; /* set PES_extension_flag_2 */
1336  *q++ = flags;
1337  *q++ = 0x80 | 0x01; /* marker bit + extension length */
1338  *q++ = 0x00 | 0x71; /* for AC3 Audio (specifically on blue-rays) */
1339  }
1340 
1341 
1342  if (is_dvb_subtitle) {
1343  /* First two fields of DVB subtitles PES data:
1344  * data_identifier: for DVB subtitle streams shall be coded with the value 0x20
1345  * subtitle_stream_id: for DVB subtitle stream shall be identified by the value 0x00 */
1346  *q++ = 0x20;
1347  *q++ = 0x00;
1348  }
1349  if (is_dvb_teletext) {
1350  memset(q, 0xff, pes_header_stuffing_bytes);
1351  q += pes_header_stuffing_bytes;
1352  }
1353  is_start = 0;
1354  }
1355  /* header size */
1356  header_len = q - buf;
1357  /* data len */
1358  len = TS_PACKET_SIZE - header_len;
1359  if (len > payload_size)
1360  len = payload_size;
1361  stuffing_len = TS_PACKET_SIZE - header_len - len;
1362  if (stuffing_len > 0) {
1363  /* add stuffing with AFC */
1364  if (buf[3] & 0x20) {
1365  /* stuffing already present: increase its size */
1366  afc_len = buf[4] + 1;
1367  memmove(buf + 4 + afc_len + stuffing_len,
1368  buf + 4 + afc_len,
1369  header_len - (4 + afc_len));
1370  buf[4] += stuffing_len;
1371  memset(buf + 4 + afc_len, 0xff, stuffing_len);
1372  } else {
1373  /* add stuffing */
1374  memmove(buf + 4 + stuffing_len, buf + 4, header_len - 4);
1375  buf[3] |= 0x20;
1376  buf[4] = stuffing_len - 1;
1377  if (stuffing_len >= 2) {
1378  buf[5] = 0x00;
1379  memset(buf + 6, 0xff, stuffing_len - 2);
1380  }
1381  }
1382  }
1383 
1384  if (is_dvb_subtitle && payload_size == len) {
1385  memcpy(buf + TS_PACKET_SIZE - len, payload, len - 1);
1386  buf[TS_PACKET_SIZE - 1] = 0xff; /* end_of_PES_data_field_marker: an 8-bit field with fixed contents 0xff for DVB subtitle */
1387  } else {
1388  memcpy(buf + TS_PACKET_SIZE - len, payload, len);
1389  }
1390 
1391  payload += len;
1392  payload_size -= len;
1394  avio_write(s->pb, buf, TS_PACKET_SIZE);
1395  }
1396  ts_st->prev_payload_key = key;
1397 }
1398 
1400 {
1401  if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001 && AV_RB24(pkt->data) != 0x000001) {
1402  if (!st->nb_frames) {
1403  av_log(s, AV_LOG_ERROR, "H.264 bitstream malformed, "
1404  "no startcode found, use the video bitstream filter 'h264_mp4toannexb' to fix it "
1405  "('-bsf:v h264_mp4toannexb' option with ffmpeg)\n");
1406  return AVERROR_INVALIDDATA;
1407  }
1408  av_log(s, AV_LOG_WARNING, "H.264 bitstream error, startcode missing, size %d", pkt->size);
1409  if (pkt->size) av_log(s, AV_LOG_WARNING, " data %08X", AV_RB32(pkt->data));
1410  av_log(s, AV_LOG_WARNING, "\n");
1411  }
1412  return 0;
1413 }
1414 
1416 {
1417  if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001 && AV_RB24(pkt->data) != 0x000001) {
1418  if (!st->nb_frames) {
1419  av_log(s, AV_LOG_ERROR, "HEVC bitstream malformed, no startcode found\n");
1420  return AVERROR_PATCHWELCOME;
1421  }
1422  av_log(s, AV_LOG_WARNING, "HEVC bitstream error, startcode missing, size %d", pkt->size);
1423  if (pkt->size) av_log(s, AV_LOG_WARNING, " data %08X", AV_RB32(pkt->data));
1424  av_log(s, AV_LOG_WARNING, "\n");
1425  }
1426  return 0;
1427 }
1428 
1429 /* Based on GStreamer's gst-plugins-base/ext/ogg/gstoggstream.c
1430  * Released under the LGPL v2.1+, written by
1431  * Vincent Penquerc'h <vincent.penquerch@collabora.co.uk>
1432  */
1434 {
1435  static const int durations[32] = {
1436  480, 960, 1920, 2880, /* Silk NB */
1437  480, 960, 1920, 2880, /* Silk MB */
1438  480, 960, 1920, 2880, /* Silk WB */
1439  480, 960, /* Hybrid SWB */
1440  480, 960, /* Hybrid FB */
1441  120, 240, 480, 960, /* CELT NB */
1442  120, 240, 480, 960, /* CELT NB */
1443  120, 240, 480, 960, /* CELT NB */
1444  120, 240, 480, 960, /* CELT NB */
1445  };
1446  int toc, frame_duration, nframes, duration;
1447 
1448  if (pkt->size < 1)
1449  return 0;
1450 
1451  toc = pkt->data[0];
1452 
1453  frame_duration = durations[toc >> 3];
1454  switch (toc & 3) {
1455  case 0:
1456  nframes = 1;
1457  break;
1458  case 1:
1459  nframes = 2;
1460  break;
1461  case 2:
1462  nframes = 2;
1463  break;
1464  case 3:
1465  if (pkt->size < 2)
1466  return 0;
1467  nframes = pkt->data[1] & 63;
1468  break;
1469  }
1470 
1471  duration = nframes * frame_duration;
1472  if (duration > 5760) {
1474  "Opus packet duration > 120 ms, invalid");
1475  return 0;
1476  }
1477 
1478  return duration;
1479 }
1480 
1482 {
1483  AVStream *st = s->streams[pkt->stream_index];
1484  int size = pkt->size;
1485  uint8_t *buf = pkt->data;
1486  uint8_t *data = NULL;
1487  MpegTSWrite *ts = s->priv_data;
1488  MpegTSWriteStream *ts_st = st->priv_data;
1489  const int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE) * 2;
1490  int64_t dts = pkt->dts, pts = pkt->pts;
1491  int opus_samples = 0;
1492  int side_data_size;
1493  char *side_data = NULL;
1494  int stream_id = -1;
1495 
1496  side_data = av_packet_get_side_data(pkt,
1498  &side_data_size);
1499  if (side_data)
1500  stream_id = side_data[0];
1501 
1502  if (ts->reemit_pat_pmt) {
1504  "resend_headers option is deprecated, use -mpegts_flags resend_headers\n");
1505  ts->reemit_pat_pmt = 0;
1507  }
1508 
1509  if (ts->flags & MPEGTS_FLAG_REEMIT_PAT_PMT) {
1510  ts->pat_packet_count = ts->pat_packet_period - 1;
1511  ts->sdt_packet_count = ts->sdt_packet_period - 1;
1513  }
1514 
1515  if (ts->copyts < 1) {
1516  if (pts != AV_NOPTS_VALUE)
1517  pts += delay;
1518  if (dts != AV_NOPTS_VALUE)
1519  dts += delay;
1520  }
1521 
1522  if (ts_st->first_pts_check && pts == AV_NOPTS_VALUE) {
1523  av_log(s, AV_LOG_ERROR, "first pts value must be set\n");
1524  return AVERROR_INVALIDDATA;
1525  }
1526  ts_st->first_pts_check = 0;
1527 
1528  if (st->codecpar->codec_id == AV_CODEC_ID_H264) {
1529  const uint8_t *p = buf, *buf_end = p + size;
1530  uint32_t state = -1;
1531  int extradd = (pkt->flags & AV_PKT_FLAG_KEY) ? st->codecpar->extradata_size : 0;
1532  int ret = ff_check_h264_startcode(s, st, pkt);
1533  if (ret < 0)
1534  return ret;
1535 
1536  if (extradd && AV_RB24(st->codecpar->extradata) > 1)
1537  extradd = 0;
1538 
1539  do {
1540  p = avpriv_find_start_code(p, buf_end, &state);
1541  av_log(s, AV_LOG_TRACE, "nal %d\n", state & 0x1f);
1542  if ((state & 0x1f) == 7)
1543  extradd = 0;
1544  } while (p < buf_end && (state & 0x1f) != 9 &&
1545  (state & 0x1f) != 5 && (state & 0x1f) != 1);
1546 
1547  if ((state & 0x1f) != 5)
1548  extradd = 0;
1549  if ((state & 0x1f) != 9) { // AUD NAL
1550  data = av_malloc(pkt->size + 6 + extradd);
1551  if (!data)
1552  return AVERROR(ENOMEM);
1553  memcpy(data + 6, st->codecpar->extradata, extradd);
1554  memcpy(data + 6 + extradd, pkt->data, pkt->size);
1555  AV_WB32(data, 0x00000001);
1556  data[4] = 0x09;
1557  data[5] = 0xf0; // any slice type (0xe) + rbsp stop one bit
1558  buf = data;
1559  size = pkt->size + 6 + extradd;
1560  }
1561  } else if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
1562  if (pkt->size < 2) {
1563  av_log(s, AV_LOG_ERROR, "AAC packet too short\n");
1564  return AVERROR_INVALIDDATA;
1565  }
1566  if ((AV_RB16(pkt->data) & 0xfff0) != 0xfff0) {
1567  int ret;
1568  AVPacket pkt2;
1569 
1570  if (!ts_st->amux) {
1571  av_log(s, AV_LOG_ERROR, "AAC bitstream not in ADTS format "
1572  "and extradata missing\n");
1573  } else {
1574  av_init_packet(&pkt2);
1575  pkt2.data = pkt->data;
1576  pkt2.size = pkt->size;
1577  av_assert0(pkt->dts != AV_NOPTS_VALUE);
1578  pkt2.dts = av_rescale_q(pkt->dts, st->time_base, ts_st->amux->streams[0]->time_base);
1579 
1580  ret = avio_open_dyn_buf(&ts_st->amux->pb);
1581  if (ret < 0)
1582  return AVERROR(ENOMEM);
1583 
1584  ret = av_write_frame(ts_st->amux, &pkt2);
1585  if (ret < 0) {
1586  ffio_free_dyn_buf(&ts_st->amux->pb);
1587  return ret;
1588  }
1589  size = avio_close_dyn_buf(ts_st->amux->pb, &data);
1590  ts_st->amux->pb = NULL;
1591  buf = data;
1592  }
1593  }
1594  } else if (st->codecpar->codec_id == AV_CODEC_ID_HEVC) {
1595  int ret = check_hevc_startcode(s, st, pkt);
1596  if (ret < 0)
1597  return ret;
1598  } else if (st->codecpar->codec_id == AV_CODEC_ID_OPUS) {
1599  if (pkt->size < 2) {
1600  av_log(s, AV_LOG_ERROR, "Opus packet too short\n");
1601  return AVERROR_INVALIDDATA;
1602  }
1603 
1604  /* Add Opus control header */
1605  if ((AV_RB16(pkt->data) >> 5) != 0x3ff) {
1606  uint8_t *side_data;
1607  int side_data_size;
1608  int i, n;
1609  int ctrl_header_size;
1610  int trim_start = 0, trim_end = 0;
1611 
1612  opus_samples = opus_get_packet_samples(s, pkt);
1613 
1614  side_data = av_packet_get_side_data(pkt,
1616  &side_data_size);
1617 
1618  if (side_data && side_data_size >= 10) {
1619  trim_end = AV_RL32(side_data + 4) * 48000 / st->codecpar->sample_rate;
1620  }
1621 
1622  ctrl_header_size = pkt->size + 2 + pkt->size / 255 + 1;
1623  if (ts_st->opus_pending_trim_start)
1624  ctrl_header_size += 2;
1625  if (trim_end)
1626  ctrl_header_size += 2;
1627 
1628  data = av_malloc(ctrl_header_size);
1629  if (!data)
1630  return AVERROR(ENOMEM);
1631 
1632  data[0] = 0x7f;
1633  data[1] = 0xe0;
1634  if (ts_st->opus_pending_trim_start)
1635  data[1] |= 0x10;
1636  if (trim_end)
1637  data[1] |= 0x08;
1638 
1639  n = pkt->size;
1640  i = 2;
1641  do {
1642  data[i] = FFMIN(n, 255);
1643  n -= 255;
1644  i++;
1645  } while (n >= 0);
1646 
1647  av_assert0(2 + pkt->size / 255 + 1 == i);
1648 
1649  if (ts_st->opus_pending_trim_start) {
1650  trim_start = FFMIN(ts_st->opus_pending_trim_start, opus_samples);
1651  AV_WB16(data + i, trim_start);
1652  i += 2;
1653  ts_st->opus_pending_trim_start -= trim_start;
1654  }
1655  if (trim_end) {
1656  trim_end = FFMIN(trim_end, opus_samples - trim_start);
1657  AV_WB16(data + i, trim_end);
1658  i += 2;
1659  }
1660 
1661  memcpy(data + i, pkt->data, pkt->size);
1662  buf = data;
1663  size = ctrl_header_size;
1664  } else {
1665  /* TODO: Can we get TS formatted data here? If so we will
1666  * need to count the samples of that too! */
1667  av_log(s, AV_LOG_WARNING, "Got MPEG-TS formatted Opus data, unhandled");
1668  }
1669  }
1670 
1671  if (pkt->dts != AV_NOPTS_VALUE) {
1672  int i;
1673  for(i=0; i<s->nb_streams; i++) {
1674  AVStream *st2 = s->streams[i];
1675  MpegTSWriteStream *ts_st2 = st2->priv_data;
1676  if ( ts_st2->payload_size
1677  && (ts_st2->payload_dts == AV_NOPTS_VALUE || dts - ts_st2->payload_dts > delay/2)) {
1678  mpegts_write_pes(s, st2, ts_st2->payload, ts_st2->payload_size,
1679  ts_st2->payload_pts, ts_st2->payload_dts,
1680  ts_st2->payload_flags & AV_PKT_FLAG_KEY, stream_id);
1681  ts_st2->payload_size = 0;
1682  }
1683  }
1684  }
1685 
1686  if (ts_st->payload_size && (ts_st->payload_size + size > ts->pes_payload_size ||
1687  (dts != AV_NOPTS_VALUE && ts_st->payload_dts != AV_NOPTS_VALUE &&
1688  av_compare_ts(dts - ts_st->payload_dts, st->time_base,
1689  s->max_delay, AV_TIME_BASE_Q) >= 0) ||
1690  ts_st->opus_queued_samples + opus_samples >= 5760 /* 120ms */)) {
1691  mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_size,
1692  ts_st->payload_pts, ts_st->payload_dts,
1693  ts_st->payload_flags & AV_PKT_FLAG_KEY, stream_id);
1694  ts_st->payload_size = 0;
1695  ts_st->opus_queued_samples = 0;
1696  }
1697 
1698  if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO || size > ts->pes_payload_size) {
1699  av_assert0(!ts_st->payload_size);
1700  // for video and subtitle, write a single pes packet
1701  mpegts_write_pes(s, st, buf, size, pts, dts,
1702  pkt->flags & AV_PKT_FLAG_KEY, stream_id);
1703  ts_st->opus_queued_samples = 0;
1704  av_free(data);
1705  return 0;
1706  }
1707 
1708  if (!ts_st->payload_size) {
1709  ts_st->payload_pts = pts;
1710  ts_st->payload_dts = dts;
1711  ts_st->payload_flags = pkt->flags;
1712  }
1713 
1714  memcpy(ts_st->payload + ts_st->payload_size, buf, size);
1715  ts_st->payload_size += size;
1716  ts_st->opus_queued_samples += opus_samples;
1717 
1718  av_free(data);
1719 
1720  return 0;
1721 }
1722 
1724 {
1725  int i;
1726 
1727  /* flush current packets */
1728  for (i = 0; i < s->nb_streams; i++) {
1729  AVStream *st = s->streams[i];
1730  MpegTSWriteStream *ts_st = st->priv_data;
1731  if (ts_st->payload_size > 0) {
1732  mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_size,
1733  ts_st->payload_pts, ts_st->payload_dts,
1734  ts_st->payload_flags & AV_PKT_FLAG_KEY, -1);
1735  ts_st->payload_size = 0;
1736  ts_st->opus_queued_samples = 0;
1737  }
1738  }
1739 }
1740 
1742 {
1743  if (!pkt) {
1744  mpegts_write_flush(s);
1745  return 1;
1746  } else {
1747  return mpegts_write_packet_internal(s, pkt);
1748  }
1749 }
1750 
1752 {
1753  if (s->pb)
1754  mpegts_write_flush(s);
1755 
1756  return 0;
1757 }
1758 
1760 {
1761  MpegTSWrite *ts = s->priv_data;
1762  MpegTSService *service;
1763  int i;
1764 
1765  for (i = 0; i < s->nb_streams; i++) {
1766  AVStream *st = s->streams[i];
1767  MpegTSWriteStream *ts_st = st->priv_data;
1768  if (ts_st) {
1769  av_freep(&ts_st->payload);
1770  if (ts_st->amux) {
1771  avformat_free_context(ts_st->amux);
1772  ts_st->amux = NULL;
1773  }
1774  }
1775  }
1776 
1777  for (i = 0; i < ts->nb_services; i++) {
1778  service = ts->services[i];
1779  av_freep(&service->provider_name);
1780  av_freep(&service->name);
1781  av_freep(&service);
1782  }
1783  av_freep(&ts->services);
1784 }
1785 
1787 {
1788  int ret = 1;
1789  AVStream *st = s->streams[pkt->stream_index];
1790 
1791  if (st->codecpar->codec_id == AV_CODEC_ID_H264) {
1792  if (pkt->size >= 5 && AV_RB32(pkt->data) != 0x0000001 &&
1793  AV_RB24(pkt->data) != 0x000001)
1794  ret = ff_stream_add_bitstream_filter(st, "h264_mp4toannexb", NULL);
1795  } else if (st->codecpar->codec_id == AV_CODEC_ID_HEVC) {
1796  if (pkt->size >= 5 && AV_RB32(pkt->data) != 0x0000001 &&
1797  AV_RB24(pkt->data) != 0x000001)
1798  ret = ff_stream_add_bitstream_filter(st, "hevc_mp4toannexb", NULL);
1799  }
1800 
1801  return ret;
1802 }
1803 
1804 static const AVOption options[] = {
1805  { "mpegts_transport_stream_id", "Set transport_stream_id field.",
1806  offsetof(MpegTSWrite, transport_stream_id), AV_OPT_TYPE_INT,
1807  { .i64 = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM },
1808  { "mpegts_original_network_id", "Set original_network_id field.",
1809  offsetof(MpegTSWrite, original_network_id), AV_OPT_TYPE_INT,
1810  { .i64 = DVB_PRIVATE_NETWORK_START }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM },
1811  { "mpegts_service_id", "Set service_id field.",
1812  offsetof(MpegTSWrite, service_id), AV_OPT_TYPE_INT,
1813  { .i64 = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM },
1814  { "mpegts_service_type", "Set service_type field.",
1815  offsetof(MpegTSWrite, service_type), AV_OPT_TYPE_INT,
1816  { .i64 = 0x01 }, 0x01, 0xff, AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1817  { "digital_tv", "Digital Television.",
1818  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_DIGITAL_TV }, 0x01, 0xff,
1819  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1820  { "digital_radio", "Digital Radio.",
1821  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_DIGITAL_RADIO }, 0x01, 0xff,
1822  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1823  { "teletext", "Teletext.",
1824  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_TELETEXT }, 0x01, 0xff,
1825  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1826  { "advanced_codec_digital_radio", "Advanced Codec Digital Radio.",
1828  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1829  { "mpeg2_digital_hdtv", "MPEG2 Digital HDTV.",
1830  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_MPEG2_DIGITAL_HDTV }, 0x01, 0xff,
1831  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1832  { "advanced_codec_digital_sdtv", "Advanced Codec Digital SDTV.",
1834  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1835  { "advanced_codec_digital_hdtv", "Advanced Codec Digital HDTV.",
1837  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1838  { "hevc_digital_hdtv", "HEVC Digital Television Service.",
1839  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_HEVC_DIGITAL_HDTV }, 0x01, 0xff,
1840  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1841  { "mpegts_pmt_start_pid", "Set the first pid of the PMT.",
1842  offsetof(MpegTSWrite, pmt_start_pid), AV_OPT_TYPE_INT,
1843  { .i64 = 0x1000 }, 0x0010, 0x1f00, AV_OPT_FLAG_ENCODING_PARAM },
1844  { "mpegts_start_pid", "Set the first pid.",
1845  offsetof(MpegTSWrite, start_pid), AV_OPT_TYPE_INT,
1846  { .i64 = 0x0100 }, 0x0020, 0x0f00, AV_OPT_FLAG_ENCODING_PARAM },
1847  { "mpegts_m2ts_mode", "Enable m2ts mode.",
1848  offsetof(MpegTSWrite, m2ts_mode), AV_OPT_TYPE_BOOL,
1849  { .i64 = -1 }, -1, 1, AV_OPT_FLAG_ENCODING_PARAM },
1850  { "muxrate", NULL,
1851  offsetof(MpegTSWrite, mux_rate), AV_OPT_TYPE_INT,
1852  { .i64 = 1 }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
1853  { "pes_payload_size", "Minimum PES packet payload in bytes",
1854  offsetof(MpegTSWrite, pes_payload_size), AV_OPT_TYPE_INT,
1855  { .i64 = DEFAULT_PES_PAYLOAD_SIZE }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
1856  { "mpegts_flags", "MPEG-TS muxing flags",
1857  offsetof(MpegTSWrite, flags), AV_OPT_TYPE_FLAGS, { .i64 = 0 }, 0, INT_MAX,
1858  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags" },
1859  { "resend_headers", "Reemit PAT/PMT before writing the next packet",
1860  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_FLAG_REEMIT_PAT_PMT }, 0, INT_MAX,
1861  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags" },
1862  { "latm", "Use LATM packetization for AAC",
1863  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_FLAG_AAC_LATM }, 0, INT_MAX,
1864  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags" },
1865  { "pat_pmt_at_frames", "Reemit PAT and PMT at each video frame",
1866  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_FLAG_PAT_PMT_AT_FRAMES}, 0, INT_MAX,
1867  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags" },
1868  { "system_b", "Conform to System B (DVB) instead of System A (ATSC)",
1869  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_FLAG_SYSTEM_B }, 0, INT_MAX,
1870  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags" },
1871  // backward compatibility
1872  { "resend_headers", "Reemit PAT/PMT before writing the next packet",
1873  offsetof(MpegTSWrite, reemit_pat_pmt), AV_OPT_TYPE_INT,
1874  { .i64 = 0 }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
1875  { "mpegts_copyts", "don't offset dts/pts",
1876  offsetof(MpegTSWrite, copyts), AV_OPT_TYPE_BOOL,
1877  { .i64 = -1 }, -1, 1, AV_OPT_FLAG_ENCODING_PARAM },
1878  { "tables_version", "set PAT, PMT and SDT version",
1879  offsetof(MpegTSWrite, tables_version), AV_OPT_TYPE_INT,
1880  { .i64 = 0 }, 0, 31, AV_OPT_FLAG_ENCODING_PARAM },
1881  { "omit_video_pes_length", "Omit the PES packet length for video packets",
1882  offsetof(MpegTSWrite, omit_video_pes_length), AV_OPT_TYPE_BOOL,
1883  { .i64 = 1 }, 0, 1, AV_OPT_FLAG_ENCODING_PARAM },
1884  { "pcr_period", "PCR retransmission time",
1885  offsetof(MpegTSWrite, pcr_period), AV_OPT_TYPE_INT,
1886  { .i64 = PCR_RETRANS_TIME }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
1887  { "pat_period", "PAT/PMT retransmission time limit in seconds",
1888  offsetof(MpegTSWrite, pat_period), AV_OPT_TYPE_DOUBLE,
1889  { .dbl = INT_MAX }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
1890  { "sdt_period", "SDT retransmission time limit in seconds",
1891  offsetof(MpegTSWrite, sdt_period), AV_OPT_TYPE_DOUBLE,
1892  { .dbl = INT_MAX }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
1893  { NULL },
1894 };
1895 
1896 static const AVClass mpegts_muxer_class = {
1897  .class_name = "MPEGTS muxer",
1898  .item_name = av_default_item_name,
1899  .option = options,
1900  .version = LIBAVUTIL_VERSION_INT,
1901 };
1902 
1904  .name = "mpegts",
1905  .long_name = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
1906  .mime_type = "video/MP2T",
1907  .extensions = "ts,m2t,m2ts,mts",
1908  .priv_data_size = sizeof(MpegTSWrite),
1909  .audio_codec = AV_CODEC_ID_MP2,
1910  .video_codec = AV_CODEC_ID_MPEG2VIDEO,
1911  .init = mpegts_init,
1914  .deinit = mpegts_deinit,
1915  .check_bitstream = mpegts_check_bitstream,
1917  .priv_class = &mpegts_muxer_class,
1918 };
#define NULL
Definition: coverity.c:32
#define SDT_PID
Definition: mpegts.h:37
const char const char void * val
Definition: avisynth_c.h:771
const char * s
Definition: avisynth_c.h:768
Bytestream IO Context.
Definition: avio.h:147
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:59
#define PMT_TID
Definition: mpegts.h:41
#define SECTION_LENGTH
Definition: mpegtsenc.c:124
int pat_packet_period
Definition: mpegtsenc.c:83
#define STREAM_TYPE_AUDIO_MPEG2
Definition: mpeg.h:52
MpegTSSection pmt
Definition: mpegtsenc.c:54
int avio_close_dyn_buf(AVIOContext *s, uint8_t **pbuffer)
Return the written size and a pointer to the buffer.
Definition: aviobuf.c:1278
AVOption.
Definition: opt.h:245
ptrdiff_t const GLvoid * data
Definition: opengl_enc.c:101
int pcr_packet_count
Definition: mpegtsenc.c:59
int sdt_packet_count
Definition: mpegtsenc.c:80
int av_write_frame(AVFormatContext *s, AVPacket *pkt)
Write a packet to an output media file.
Definition: mux.c:883
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:182
#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:4549
#define STREAM_TYPE_VIDEO_CAVS
Definition: mpeg.h:58
static av_cold int init(AVCodecContext *avctx)
Definition: avrndec.c:35
int64_t payload_dts
Definition: mpegtsenc.c:230
static int mpegts_init(AVFormatContext *s)
Definition: mpegtsenc.c:747
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition: avcodec.h:3969
char * name
Definition: mpegtsenc.c:56
int num
Numerator.
Definition: rational.h:59
int size
Definition: avcodec.h:1601
const char * b
Definition: vf_curves.c:113
int flag
Definition: cpu.c:34
int64_t last_sdt_ts
Definition: mpegtsenc.c:113
#define PCR_TIME_BASE
Definition: mpegtsenc.c:37
#define AV_DISPOSITION_HEARING_IMPAIRED
stream for hearing impaired audiences
Definition: avformat.h:847
#define STREAM_TYPE_AUDIO_EAC3
Definition: mpegts.h:64
void * priv_data
Definition: avformat.h:896
#define AV_DISPOSITION_CLEAN_EFFECTS
stream without voice
Definition: avformat.h:849
int version
Definition: avisynth_c.h:766
void * av_mallocz(size_t size)
Allocate a memory block with alignment suitable for all memory accesses (including vectors if availab...
Definition: mem.c:252
#define PCR_RETRANS_TIME
Definition: mpegtsenc.c:220
static AVPacket pkt
int64_t first_pcr
Definition: mpegtsenc.c:87
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:495
int avio_open_dyn_buf(AVIOContext **s)
Open a write only memory stream.
Definition: aviobuf.c:1266
double pat_period
Definition: mpegtsenc.c:110
Format I/O context.
Definition: avformat.h:1330
char * provider_name
Definition: mpegtsenc.c:57
int first_pts_check
first pts check needed
Definition: mpegtsenc.c:227
unsigned int nb_stream_indexes
Definition: avformat.h:1262
static void write_packet(AVFormatContext *s, AVPacket *pkt, OutputStream *ost)
Definition: ffmpeg.c:634
#define SDT_RETRANS_TIME
Definition: mpegtsenc.c:218
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
#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:258
int64_t payload_pts
Definition: mpegtsenc.c:229
uint8_t
#define av_malloc(s)
Opaque data information usually continuous.
Definition: avutil.h:197
AVOptions.
#define AV_LOG_TRACE
Extremely verbose debugging, useful for libav* development.
Definition: log.h:202
void * opaque
Definition: mpegtsenc.c:50
#define DEFAULT_PES_PAYLOAD_SIZE
Definition: mpegtsenc.c:120
int id
Format-specific stream ID.
Definition: avformat.h:888
AVStream * avformat_new_stream(AVFormatContext *s, const AVCodec *c)
Add a new stream to a media file.
Definition: utils.c:4182
static int mpegts_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
Definition: mpegtsenc.c:1786
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:1398
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:132
static int mpegts_write_packet(AVFormatContext *s, AVPacket *pkt)
Definition: mpegtsenc.c:1741
Public header for CRC hash function implementation.
int initial_padding
Audio only.
Definition: avcodec.h:4098
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:1050
uint8_t * data
Definition: avcodec.h:1600
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:192
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:85
int av_dynarray_add_nofree(void *tab_ptr, int *nb_ptr, void *elem)
Add an element to a dynamic array.
Definition: mem.c:310
static void mpegts_write_sdt(AVFormatContext *s)
Definition: mpegtsenc.c:657
ptrdiff_t size
Definition: opengl_enc.c:101
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition: avio.h:511
void avio_write(AVIOContext *s, const unsigned char *buf, int size)
Definition: aviobuf.c:204
#define STREAM_TYPE_VIDEO_VC1
Definition: mpegts.h:58
#define AV_WB16(p, v)
Definition: intreadwrite.h:405
static void extend_af(uint8_t *pkt, int size)
Definition: mpegtsenc.c:1122
unsigned int * stream_index
Definition: avformat.h:1261
#define MPEGTS_FLAG_AAC_LATM
Definition: mpegtsenc.c:104
#define av_log(a,...)
#define PAT_TID
Definition: mpegts.h:40
#define AV_OPT_FLAG_ENCODING_PARAM
a generic parameter which can be set by the user for muxing or encoding
Definition: opt.h:275
const uint8_t * avpriv_find_start_code(const uint8_t *p, const uint8_t *end, uint32_t *state)
struct AVOutputFormat * oformat
The output container format.
Definition: avformat.h:1349
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: avcodec.h:1632
#define STREAM_TYPE_AUDIO_AAC
Definition: mpeg.h:55
MPEGTS stream ID, this is required to pass the stream ID information from the demuxer to the correspo...
Definition: avcodec.h:1531
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
struct MpegTSService * service
Definition: mpegtsenc.c:223
#define STREAM_TYPE_AUDIO_DTS
Definition: mpegts.h:62
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:1142
AVProgram * av_find_program_from_stream(AVFormatContext *ic, AVProgram *last, int s)
Find the programs which belong to a given stream.
Definition: utils.c:3906
static void mpegts_prefix_m2ts_header(AVFormatContext *s)
Definition: mpegtsenc.c:728
int avcodec_parameters_copy(AVCodecParameters *dst, const AVCodecParameters *src)
Copy the contents of src to dst.
Definition: utils.c:4086
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:176
AVDictionary * metadata
Metadata that applies to the whole file.
Definition: avformat.h:1546
AVProgram * program
Definition: mpegtsenc.c:61
static void put16(uint8_t **q_ptr, int val)
Definition: mpegtsenc.c:175
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:184
static void write_pts(uint8_t *q, int fourbits, int64_t pts)
Definition: mpegtsenc.c:1091
av_default_item_name
#define AVERROR(e)
Definition: error.h:43
int pes_payload_size
Definition: mpegtsenc.c:89
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:176
static uint8_t * get_ts_payload_start(uint8_t *pkt)
Definition: mpegtsenc.c:1130
unsigned int nb_programs
Definition: avformat.h:1485
#define STREAM_TYPE_VIDEO_DIRAC
Definition: mpegts.h:59
static void set_af_flag(uint8_t *pkt, int flag)
Definition: mpegtsenc.c:1106
preferred ID for decoding MPEG audio layer 1, 2 or 3
Definition: avcodec.h:517
enum AVMediaType codec_type
General type of the encoded data.
Definition: avcodec.h:3965
static void mpegts_insert_pcr_only(AVFormatContext *s, AVStream *st)
Definition: mpegtsenc.c:1066
simple assert() macros that are a bit more flexible than ISO C assert().
int nb_services
Definition: mpegtsenc.c:84
AVRational user_tb
Definition: mpegtsenc.c:234
#define PAT_RETRANS_TIME
Definition: mpegtsenc.c:219
int mux_rate
set to 1 when VBR
Definition: mpegtsenc.c:88
static int mpegts_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
Definition: mpegtsenc.c:1481
New fields can be added to the end with minor version bumps.
Definition: avformat.h:1257
static int write_pcr_bits(uint8_t *buf, int64_t pcr)
Definition: mpegtsenc.c:1035
#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:3684
#define fail()
Definition: checkasm.h:82
#define MPEGTS_FLAG_SYSTEM_B
Definition: mpegtsenc.c:106
int flags
A combination of AV_PKT_FLAG values.
Definition: avcodec.h:1606
int av_compare_ts(int64_t ts_a, AVRational tb_a, int64_t ts_b, AVRational tb_b)
Compare two timestamps each in its own time base.
Definition: mathematics.c:147
int extradata_size
Size of the extradata content in bytes.
Definition: avcodec.h:3987
double sdt_period
Definition: mpegtsenc.c:111
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
Definition: avformat.h:1386
#define STREAM_TYPE_AUDIO_AAC_LATM
Definition: mpegts.h:52
int ff_check_h264_startcode(AVFormatContext *s, const AVStream *st, const AVPacket *pkt)
Check presence of H264 startcode.
Definition: mpegtsenc.c:1399
static const AVOption options[]
Definition: mpegtsenc.c:1804
char filename[1024]
input or output filename
Definition: avformat.h:1406
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:248
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:496
#define FFMIN(a, b)
Definition: common.h:96
static void putstr8(uint8_t **q_ptr, const char *str)
Definition: mpegtsenc.c:641
#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:94
const char * name
Definition: avformat.h:524
#define DEFAULT_PROVIDER_NAME
Definition: mpegtsenc.c:214
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:357
static int check_hevc_startcode(AVFormatContext *s, const AVStream *st, const AVPacket *pkt)
Definition: mpegtsenc.c:1415
AVOutputFormat ff_mpegts_muxer
Definition: mpegtsenc.c:1903
int n
Definition: avisynth_c.h:684
AVFormatContext * amux
Definition: mpegtsenc.c:233
AVDictionary * metadata
Definition: avformat.h:950
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:98
#define MPEGTS_FLAG_REEMIT_PAT_PMT
Definition: mpegtsenc.c:103
preferred ID for MPEG-1/2 video decoding
Definition: avcodec.h:196
#define STREAM_TYPE_VIDEO_MPEG4
Definition: mpeg.h:56
static void mpegts_deinit(AVFormatContext *s)
Definition: mpegtsenc.c:1759
int pmt_start_pid
Definition: mpegtsenc.c:96
void ffio_free_dyn_buf(AVIOContext **s)
Free a dynamic buffer.
Definition: aviobuf.c:1306
int service_type
Definition: mpegtsenc.c:94
#define AV_DISPOSITION_VISUAL_IMPAIRED
stream for visual impaired audiences
Definition: avformat.h:848
Stream structure.
Definition: avformat.h:881
#define AVERROR_PATCHWELCOME
Not yet implemented in FFmpeg, patches welcome.
Definition: error.h:62
int start_pid
Definition: mpegtsenc.c:97
#define STREAM_TYPE_METADATA
Definition: mpegts.h:54
#define av_bswap32
Definition: bswap.h:33
int frame_size
Definition: mxfenc.c:1822
#define DVB_PRIVATE_NETWORK_START
Definition: mpegtsenc.c:41
char * av_strdup(const char *s)
Duplicate a string.
Definition: mem.c:267
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
#define AV_TIME_BASE_Q
Internal time base represented as fractional value.
Definition: avutil.h:254
int sdt_packet_period
Definition: mpegtsenc.c:81
AVIOContext * pb
I/O context.
Definition: avformat.h:1372
#define MPEGTS_FLAG_PAT_PMT_AT_FRAMES
Definition: mpegtsenc.c:105
const AVClass * av_class
Definition: mpegtsenc.c:76
#define STREAM_TYPE_PRIVATE_DATA
Definition: mpeg.h:54
void * buf
Definition: avisynth_c.h:690
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:1433
int original_network_id
Definition: mpegtsenc.c:92
#define AV_WB32(p, v)
Definition: intreadwrite.h:419
Rational number (pair of numerator and denominator).
Definition: rational.h:58
int pcr_packet_period
Definition: mpegtsenc.c:60
int service_id
Definition: mpegtsenc.c:93
Recommmends skipping the specified number of samples.
Definition: avcodec.h:1472
byte swapping routines
static int mpegts_write_end(AVFormatContext *s)
Definition: mpegtsenc.c:1751
#define STREAM_TYPE_AUDIO_AC3
Definition: mpeg.h:60
void avformat_free_context(AVFormatContext *s)
Free an AVFormatContext and all its streams.
Definition: utils.c:4118
static void retransmit_si_info(AVFormatContext *s, int force_pat, int64_t dts)
Definition: mpegtsenc.c:1008
int transport_stream_id
Definition: mpegtsenc.c:91
MpegTSService ** services
Definition: mpegtsenc.c:79
static void section_write_packet(MpegTSSection *s, const uint8_t *packet)
Definition: mpegtsenc.c:740
uint8_t * payload
Definition: mpegtsenc.c:232
AVDictionary * metadata
Definition: avformat.h:1263
static struct @244 state
static int64_t pts
Global timestamp for the audio frames.
static void mpegts_write_flush(AVFormatContext *s)
Definition: mpegtsenc.c:1723
static int flags
Definition: cpu.c:47
int m2ts_mode
Definition: mpegtsenc.c:98
#define STREAM_TYPE_VIDEO_HEVC
Definition: mpegts.h:56
const AVCRC * av_crc_get_table(AVCRCId crc_id)
Get an initialized standard CRC table.
Definition: crc.c:343
int sample_rate
Audio only.
Definition: avcodec.h:4079
#define DEFAULT_SERVICE_NAME
Definition: mpegtsenc.c:215
Main libavformat public API header.
common internal api header.
int64_t last_pat_ts
Definition: mpegtsenc.c:112
static int64_t get_pcr(const MpegTSWrite *ts, AVIOContext *pb)
Definition: mpegtsenc.c:722
int disposition
AV_DISPOSITION_* bit field.
Definition: avformat.h:939
int pcr_period
Definition: mpegtsenc.c:102
void av_init_packet(AVPacket *pkt)
Initialize optional fields of a packet with default values.
Definition: avpacket.c:33
int64_t nb_frames
number of frames in this stream if known or 0
Definition: avformat.h:937
int den
Denominator.
Definition: rational.h:60
#define AVFMT_VARIABLE_FPS
Format allows variable fps.
Definition: avformat.h:489
#define av_free(p)
char * value
Definition: dict.h:87
void(* write_packet)(struct MpegTSSection *s, const uint8_t *packet)
Definition: mpegtsenc.c:49
int len
#define PAT_PID
Definition: mpegts.h:36
#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:5119
void * priv_data
Format private data.
Definition: avformat.h:1358
MpegTSSection pat
Definition: mpegtsenc.c:77
int reemit_pat_pmt
Definition: mpegtsenc.c:100
static void mpegts_write_pat(AVFormatContext *s)
Definition: mpegtsenc.c:241
MpegTSSection sdt
Definition: mpegtsenc.c:78
uint8_t * extradata
Extra binary data needed for initializing the decoder, codec-dependent.
Definition: avcodec.h:3983
int channels
Audio only.
Definition: avcodec.h:4075
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed...
Definition: avcodec.h:1599
int pat_packet_count
Definition: mpegtsenc.c:82
static const AVClass mpegts_muxer_class
Definition: mpegtsenc.c:1896
#define av_freep(p)
uint8_t * av_packet_get_side_data(AVPacket *pkt, enum AVPacketSideDataType type, int *size)
Get side information from packet.
Definition: avpacket.c:338
AVCodecParameters * codecpar
Definition: avformat.h:1233
#define av_malloc_array(a, b)
int opus_pending_trim_start
Definition: mpegtsenc.c:238
int stream_index
Definition: avcodec.h:1602
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avformat.h:918
#define STREAM_TYPE_AUDIO_MPEG1
Definition: mpeg.h:51
uint64_t_TMPL AV_WL64 unsigned int_TMPL AV_RL32
Definition: bytestream.h:87
This structure stores compressed data.
Definition: avcodec.h:1577
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: avcodec.h:1593
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:242
#define STREAM_TYPE_AUDIO_TRUEHD
Definition: mpegts.h:63
AVProgram ** programs
Definition: avformat.h:1486
#define SDT_TID
Definition: mpegts.h:43
int tables_version
Definition: mpegtsenc.c:109
const char * name
Definition: opengl_enc.c:103
static MpegTSService * mpegts_add_service(MpegTSWrite *ts, int sid, const char *provider_name, const char *name)
Definition: mpegtsenc.c:695