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) {
1242  *q++ = stream_id != -1 ? stream_id : 0xfc;
1243 
1244  if (stream_id == 0xbd) /* asynchronous KLV */
1245  pts = dts = AV_NOPTS_VALUE;
1246  } else {
1247  *q++ = 0xbd;
1250  is_dvb_subtitle = 1;
1251  } else if (st->codecpar->codec_id == AV_CODEC_ID_DVB_TELETEXT) {
1252  is_dvb_teletext = 1;
1253  }
1254  }
1255  }
1256  header_len = 0;
1257  flags = 0;
1258  if (pts != AV_NOPTS_VALUE) {
1259  header_len += 5;
1260  flags |= 0x80;
1261  }
1262  if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
1263  header_len += 5;
1264  flags |= 0x40;
1265  }
1266  if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
1268  /* set PES_extension_flag */
1269  pes_extension = 1;
1270  flags |= 0x01;
1271 
1272  /* One byte for PES2 extension flag +
1273  * one byte for extension length +
1274  * one byte for extension id */
1275  header_len += 3;
1276  }
1277  /* for Blu-ray AC3 Audio the PES Extension flag should be as follow
1278  * otherwise it will not play sound on blu-ray
1279  */
1280  if (ts->m2ts_mode &&
1282  st->codecpar->codec_id == AV_CODEC_ID_AC3) {
1283  /* set PES_extension_flag */
1284  pes_extension = 1;
1285  flags |= 0x01;
1286  header_len += 3;
1287  }
1288  if (is_dvb_teletext) {
1289  pes_header_stuffing_bytes = 0x24 - header_len;
1290  header_len = 0x24;
1291  }
1292  len = payload_size + header_len + 3;
1293  /* 3 extra bytes should be added to DVB subtitle payload: 0x20 0x00 at the beginning and trailing 0xff */
1294  if (is_dvb_subtitle) {
1295  len += 3;
1296  payload_size++;
1297  }
1298  if (len > 0xffff)
1299  len = 0;
1301  len = 0;
1302  }
1303  *q++ = len >> 8;
1304  *q++ = len;
1305  val = 0x80;
1306  /* data alignment indicator is required for subtitle and data streams */
1308  val |= 0x04;
1309  *q++ = val;
1310  *q++ = flags;
1311  *q++ = header_len;
1312  if (pts != AV_NOPTS_VALUE) {
1313  write_pts(q, flags >> 6, pts);
1314  q += 5;
1315  }
1316  if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
1317  write_pts(q, 1, dts);
1318  q += 5;
1319  }
1320  if (pes_extension && st->codecpar->codec_id == AV_CODEC_ID_DIRAC) {
1321  flags = 0x01; /* set PES_extension_flag_2 */
1322  *q++ = flags;
1323  *q++ = 0x80 | 0x01; /* marker bit + extension length */
1324  /* Set the stream ID extension flag bit to 0 and
1325  * write the extended stream ID. */
1326  *q++ = 0x00 | 0x60;
1327  }
1328  /* For Blu-ray AC3 Audio Setting extended flags */
1329  if (ts->m2ts_mode &&
1330  pes_extension &&
1331  st->codecpar->codec_id == AV_CODEC_ID_AC3) {
1332  flags = 0x01; /* set PES_extension_flag_2 */
1333  *q++ = flags;
1334  *q++ = 0x80 | 0x01; /* marker bit + extension length */
1335  *q++ = 0x00 | 0x71; /* for AC3 Audio (specifically on blue-rays) */
1336  }
1337 
1338 
1339  if (is_dvb_subtitle) {
1340  /* First two fields of DVB subtitles PES data:
1341  * data_identifier: for DVB subtitle streams shall be coded with the value 0x20
1342  * subtitle_stream_id: for DVB subtitle stream shall be identified by the value 0x00 */
1343  *q++ = 0x20;
1344  *q++ = 0x00;
1345  }
1346  if (is_dvb_teletext) {
1347  memset(q, 0xff, pes_header_stuffing_bytes);
1348  q += pes_header_stuffing_bytes;
1349  }
1350  is_start = 0;
1351  }
1352  /* header size */
1353  header_len = q - buf;
1354  /* data len */
1355  len = TS_PACKET_SIZE - header_len;
1356  if (len > payload_size)
1357  len = payload_size;
1358  stuffing_len = TS_PACKET_SIZE - header_len - len;
1359  if (stuffing_len > 0) {
1360  /* add stuffing with AFC */
1361  if (buf[3] & 0x20) {
1362  /* stuffing already present: increase its size */
1363  afc_len = buf[4] + 1;
1364  memmove(buf + 4 + afc_len + stuffing_len,
1365  buf + 4 + afc_len,
1366  header_len - (4 + afc_len));
1367  buf[4] += stuffing_len;
1368  memset(buf + 4 + afc_len, 0xff, stuffing_len);
1369  } else {
1370  /* add stuffing */
1371  memmove(buf + 4 + stuffing_len, buf + 4, header_len - 4);
1372  buf[3] |= 0x20;
1373  buf[4] = stuffing_len - 1;
1374  if (stuffing_len >= 2) {
1375  buf[5] = 0x00;
1376  memset(buf + 6, 0xff, stuffing_len - 2);
1377  }
1378  }
1379  }
1380 
1381  if (is_dvb_subtitle && payload_size == len) {
1382  memcpy(buf + TS_PACKET_SIZE - len, payload, len - 1);
1383  buf[TS_PACKET_SIZE - 1] = 0xff; /* end_of_PES_data_field_marker: an 8-bit field with fixed contents 0xff for DVB subtitle */
1384  } else {
1385  memcpy(buf + TS_PACKET_SIZE - len, payload, len);
1386  }
1387 
1388  payload += len;
1389  payload_size -= len;
1391  avio_write(s->pb, buf, TS_PACKET_SIZE);
1392  }
1393  ts_st->prev_payload_key = key;
1394 }
1395 
1397 {
1398  if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001 && AV_RB24(pkt->data) != 0x000001) {
1399  if (!st->nb_frames) {
1400  av_log(s, AV_LOG_ERROR, "H.264 bitstream malformed, "
1401  "no startcode found, use the video bitstream filter 'h264_mp4toannexb' to fix it "
1402  "('-bsf:v h264_mp4toannexb' option with ffmpeg)\n");
1403  return AVERROR_INVALIDDATA;
1404  }
1405  av_log(s, AV_LOG_WARNING, "H.264 bitstream error, startcode missing, size %d", pkt->size);
1406  if (pkt->size) av_log(s, AV_LOG_WARNING, " data %08X", AV_RB32(pkt->data));
1407  av_log(s, AV_LOG_WARNING, "\n");
1408  }
1409  return 0;
1410 }
1411 
1413 {
1414  if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001 && AV_RB24(pkt->data) != 0x000001) {
1415  if (!st->nb_frames) {
1416  av_log(s, AV_LOG_ERROR, "HEVC bitstream malformed, no startcode found\n");
1417  return AVERROR_PATCHWELCOME;
1418  }
1419  av_log(s, AV_LOG_WARNING, "HEVC bitstream error, startcode missing, size %d", pkt->size);
1420  if (pkt->size) av_log(s, AV_LOG_WARNING, " data %08X", AV_RB32(pkt->data));
1421  av_log(s, AV_LOG_WARNING, "\n");
1422  }
1423  return 0;
1424 }
1425 
1426 /* Based on GStreamer's gst-plugins-base/ext/ogg/gstoggstream.c
1427  * Released under the LGPL v2.1+, written by
1428  * Vincent Penquerc'h <vincent.penquerch@collabora.co.uk>
1429  */
1431 {
1432  static const int durations[32] = {
1433  480, 960, 1920, 2880, /* Silk NB */
1434  480, 960, 1920, 2880, /* Silk MB */
1435  480, 960, 1920, 2880, /* Silk WB */
1436  480, 960, /* Hybrid SWB */
1437  480, 960, /* Hybrid FB */
1438  120, 240, 480, 960, /* CELT NB */
1439  120, 240, 480, 960, /* CELT NB */
1440  120, 240, 480, 960, /* CELT NB */
1441  120, 240, 480, 960, /* CELT NB */
1442  };
1443  int toc, frame_duration, nframes, duration;
1444 
1445  if (pkt->size < 1)
1446  return 0;
1447 
1448  toc = pkt->data[0];
1449 
1450  frame_duration = durations[toc >> 3];
1451  switch (toc & 3) {
1452  case 0:
1453  nframes = 1;
1454  break;
1455  case 1:
1456  nframes = 2;
1457  break;
1458  case 2:
1459  nframes = 2;
1460  break;
1461  case 3:
1462  if (pkt->size < 2)
1463  return 0;
1464  nframes = pkt->data[1] & 63;
1465  break;
1466  }
1467 
1468  duration = nframes * frame_duration;
1469  if (duration > 5760) {
1471  "Opus packet duration > 120 ms, invalid");
1472  return 0;
1473  }
1474 
1475  return duration;
1476 }
1477 
1479 {
1480  AVStream *st = s->streams[pkt->stream_index];
1481  int size = pkt->size;
1482  uint8_t *buf = pkt->data;
1483  uint8_t *data = NULL;
1484  MpegTSWrite *ts = s->priv_data;
1485  MpegTSWriteStream *ts_st = st->priv_data;
1486  const int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE) * 2;
1487  int64_t dts = pkt->dts, pts = pkt->pts;
1488  int opus_samples = 0;
1489  int side_data_size;
1490  char *side_data = NULL;
1491  int stream_id = -1;
1492 
1493  side_data = av_packet_get_side_data(pkt,
1495  &side_data_size);
1496  if (side_data)
1497  stream_id = side_data[0];
1498 
1499  if (ts->reemit_pat_pmt) {
1501  "resend_headers option is deprecated, use -mpegts_flags resend_headers\n");
1502  ts->reemit_pat_pmt = 0;
1504  }
1505 
1506  if (ts->flags & MPEGTS_FLAG_REEMIT_PAT_PMT) {
1507  ts->pat_packet_count = ts->pat_packet_period - 1;
1508  ts->sdt_packet_count = ts->sdt_packet_period - 1;
1510  }
1511 
1512  if (ts->copyts < 1) {
1513  if (pts != AV_NOPTS_VALUE)
1514  pts += delay;
1515  if (dts != AV_NOPTS_VALUE)
1516  dts += delay;
1517  }
1518 
1519  if (ts_st->first_pts_check && pts == AV_NOPTS_VALUE) {
1520  av_log(s, AV_LOG_ERROR, "first pts value must be set\n");
1521  return AVERROR_INVALIDDATA;
1522  }
1523  ts_st->first_pts_check = 0;
1524 
1525  if (st->codecpar->codec_id == AV_CODEC_ID_H264) {
1526  const uint8_t *p = buf, *buf_end = p + size;
1527  uint32_t state = -1;
1528  int extradd = (pkt->flags & AV_PKT_FLAG_KEY) ? st->codecpar->extradata_size : 0;
1529  int ret = ff_check_h264_startcode(s, st, pkt);
1530  if (ret < 0)
1531  return ret;
1532 
1533  if (extradd && AV_RB24(st->codecpar->extradata) > 1)
1534  extradd = 0;
1535 
1536  do {
1537  p = avpriv_find_start_code(p, buf_end, &state);
1538  av_log(s, AV_LOG_TRACE, "nal %d\n", state & 0x1f);
1539  if ((state & 0x1f) == 7)
1540  extradd = 0;
1541  } while (p < buf_end && (state & 0x1f) != 9 &&
1542  (state & 0x1f) != 5 && (state & 0x1f) != 1);
1543 
1544  if ((state & 0x1f) != 5)
1545  extradd = 0;
1546  if ((state & 0x1f) != 9) { // AUD NAL
1547  data = av_malloc(pkt->size + 6 + extradd);
1548  if (!data)
1549  return AVERROR(ENOMEM);
1550  memcpy(data + 6, st->codecpar->extradata, extradd);
1551  memcpy(data + 6 + extradd, pkt->data, pkt->size);
1552  AV_WB32(data, 0x00000001);
1553  data[4] = 0x09;
1554  data[5] = 0xf0; // any slice type (0xe) + rbsp stop one bit
1555  buf = data;
1556  size = pkt->size + 6 + extradd;
1557  }
1558  } else if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
1559  if (pkt->size < 2) {
1560  av_log(s, AV_LOG_ERROR, "AAC packet too short\n");
1561  return AVERROR_INVALIDDATA;
1562  }
1563  if ((AV_RB16(pkt->data) & 0xfff0) != 0xfff0) {
1564  int ret;
1565  AVPacket pkt2;
1566 
1567  if (!ts_st->amux) {
1568  av_log(s, AV_LOG_ERROR, "AAC bitstream not in ADTS format "
1569  "and extradata missing\n");
1570  } else {
1571  av_init_packet(&pkt2);
1572  pkt2.data = pkt->data;
1573  pkt2.size = pkt->size;
1574  av_assert0(pkt->dts != AV_NOPTS_VALUE);
1575  pkt2.dts = av_rescale_q(pkt->dts, st->time_base, ts_st->amux->streams[0]->time_base);
1576 
1577  ret = avio_open_dyn_buf(&ts_st->amux->pb);
1578  if (ret < 0)
1579  return AVERROR(ENOMEM);
1580 
1581  ret = av_write_frame(ts_st->amux, &pkt2);
1582  if (ret < 0) {
1583  ffio_free_dyn_buf(&ts_st->amux->pb);
1584  return ret;
1585  }
1586  size = avio_close_dyn_buf(ts_st->amux->pb, &data);
1587  ts_st->amux->pb = NULL;
1588  buf = data;
1589  }
1590  }
1591  } else if (st->codecpar->codec_id == AV_CODEC_ID_HEVC) {
1592  int ret = check_hevc_startcode(s, st, pkt);
1593  if (ret < 0)
1594  return ret;
1595  } else if (st->codecpar->codec_id == AV_CODEC_ID_OPUS) {
1596  if (pkt->size < 2) {
1597  av_log(s, AV_LOG_ERROR, "Opus packet too short\n");
1598  return AVERROR_INVALIDDATA;
1599  }
1600 
1601  /* Add Opus control header */
1602  if ((AV_RB16(pkt->data) >> 5) != 0x3ff) {
1603  uint8_t *side_data;
1604  int side_data_size;
1605  int i, n;
1606  int ctrl_header_size;
1607  int trim_start = 0, trim_end = 0;
1608 
1609  opus_samples = opus_get_packet_samples(s, pkt);
1610 
1611  side_data = av_packet_get_side_data(pkt,
1613  &side_data_size);
1614 
1615  if (side_data && side_data_size >= 10) {
1616  trim_end = AV_RL32(side_data + 4) * 48000 / st->codecpar->sample_rate;
1617  }
1618 
1619  ctrl_header_size = pkt->size + 2 + pkt->size / 255 + 1;
1620  if (ts_st->opus_pending_trim_start)
1621  ctrl_header_size += 2;
1622  if (trim_end)
1623  ctrl_header_size += 2;
1624 
1625  data = av_malloc(ctrl_header_size);
1626  if (!data)
1627  return AVERROR(ENOMEM);
1628 
1629  data[0] = 0x7f;
1630  data[1] = 0xe0;
1631  if (ts_st->opus_pending_trim_start)
1632  data[1] |= 0x10;
1633  if (trim_end)
1634  data[1] |= 0x08;
1635 
1636  n = pkt->size;
1637  i = 2;
1638  do {
1639  data[i] = FFMIN(n, 255);
1640  n -= 255;
1641  i++;
1642  } while (n >= 0);
1643 
1644  av_assert0(2 + pkt->size / 255 + 1 == i);
1645 
1646  if (ts_st->opus_pending_trim_start) {
1647  trim_start = FFMIN(ts_st->opus_pending_trim_start, opus_samples);
1648  AV_WB16(data + i, trim_start);
1649  i += 2;
1650  ts_st->opus_pending_trim_start -= trim_start;
1651  }
1652  if (trim_end) {
1653  trim_end = FFMIN(trim_end, opus_samples - trim_start);
1654  AV_WB16(data + i, trim_end);
1655  i += 2;
1656  }
1657 
1658  memcpy(data + i, pkt->data, pkt->size);
1659  buf = data;
1660  size = ctrl_header_size;
1661  } else {
1662  /* TODO: Can we get TS formatted data here? If so we will
1663  * need to count the samples of that too! */
1664  av_log(s, AV_LOG_WARNING, "Got MPEG-TS formatted Opus data, unhandled");
1665  }
1666  }
1667 
1668  if (pkt->dts != AV_NOPTS_VALUE) {
1669  int i;
1670  for(i=0; i<s->nb_streams; i++) {
1671  AVStream *st2 = s->streams[i];
1672  MpegTSWriteStream *ts_st2 = st2->priv_data;
1673  if ( ts_st2->payload_size
1674  && (ts_st2->payload_dts == AV_NOPTS_VALUE || dts - ts_st2->payload_dts > delay/2)) {
1675  mpegts_write_pes(s, st2, ts_st2->payload, ts_st2->payload_size,
1676  ts_st2->payload_pts, ts_st2->payload_dts,
1677  ts_st2->payload_flags & AV_PKT_FLAG_KEY, stream_id);
1678  ts_st2->payload_size = 0;
1679  }
1680  }
1681  }
1682 
1683  if (ts_st->payload_size && (ts_st->payload_size + size > ts->pes_payload_size ||
1684  (dts != AV_NOPTS_VALUE && ts_st->payload_dts != AV_NOPTS_VALUE &&
1685  av_compare_ts(dts - ts_st->payload_dts, st->time_base,
1686  s->max_delay, AV_TIME_BASE_Q) >= 0) ||
1687  ts_st->opus_queued_samples + opus_samples >= 5760 /* 120ms */)) {
1688  mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_size,
1689  ts_st->payload_pts, ts_st->payload_dts,
1690  ts_st->payload_flags & AV_PKT_FLAG_KEY, stream_id);
1691  ts_st->payload_size = 0;
1692  ts_st->opus_queued_samples = 0;
1693  }
1694 
1695  if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO || size > ts->pes_payload_size) {
1696  av_assert0(!ts_st->payload_size);
1697  // for video and subtitle, write a single pes packet
1698  mpegts_write_pes(s, st, buf, size, pts, dts,
1699  pkt->flags & AV_PKT_FLAG_KEY, stream_id);
1700  ts_st->opus_queued_samples = 0;
1701  av_free(data);
1702  return 0;
1703  }
1704 
1705  if (!ts_st->payload_size) {
1706  ts_st->payload_pts = pts;
1707  ts_st->payload_dts = dts;
1708  ts_st->payload_flags = pkt->flags;
1709  }
1710 
1711  memcpy(ts_st->payload + ts_st->payload_size, buf, size);
1712  ts_st->payload_size += size;
1713  ts_st->opus_queued_samples += opus_samples;
1714 
1715  av_free(data);
1716 
1717  return 0;
1718 }
1719 
1721 {
1722  int i;
1723 
1724  /* flush current packets */
1725  for (i = 0; i < s->nb_streams; i++) {
1726  AVStream *st = s->streams[i];
1727  MpegTSWriteStream *ts_st = st->priv_data;
1728  if (ts_st->payload_size > 0) {
1729  mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_size,
1730  ts_st->payload_pts, ts_st->payload_dts,
1731  ts_st->payload_flags & AV_PKT_FLAG_KEY, -1);
1732  ts_st->payload_size = 0;
1733  ts_st->opus_queued_samples = 0;
1734  }
1735  }
1736 }
1737 
1739 {
1740  if (!pkt) {
1741  mpegts_write_flush(s);
1742  return 1;
1743  } else {
1744  return mpegts_write_packet_internal(s, pkt);
1745  }
1746 }
1747 
1749 {
1750  if (s->pb)
1751  mpegts_write_flush(s);
1752 
1753  return 0;
1754 }
1755 
1757 {
1758  MpegTSWrite *ts = s->priv_data;
1759  MpegTSService *service;
1760  int i;
1761 
1762  for (i = 0; i < s->nb_streams; i++) {
1763  AVStream *st = s->streams[i];
1764  MpegTSWriteStream *ts_st = st->priv_data;
1765  if (ts_st) {
1766  av_freep(&ts_st->payload);
1767  if (ts_st->amux) {
1768  avformat_free_context(ts_st->amux);
1769  ts_st->amux = NULL;
1770  }
1771  }
1772  }
1773 
1774  for (i = 0; i < ts->nb_services; i++) {
1775  service = ts->services[i];
1776  av_freep(&service->provider_name);
1777  av_freep(&service->name);
1778  av_freep(&service);
1779  }
1780  av_freep(&ts->services);
1781 }
1782 
1784 {
1785  int ret = 1;
1786  AVStream *st = s->streams[pkt->stream_index];
1787 
1788  if (st->codecpar->codec_id == AV_CODEC_ID_H264) {
1789  if (pkt->size >= 5 && AV_RB32(pkt->data) != 0x0000001 &&
1790  AV_RB24(pkt->data) != 0x000001)
1791  ret = ff_stream_add_bitstream_filter(st, "h264_mp4toannexb", NULL);
1792  } else if (st->codecpar->codec_id == AV_CODEC_ID_HEVC) {
1793  if (pkt->size >= 5 && AV_RB32(pkt->data) != 0x0000001 &&
1794  AV_RB24(pkt->data) != 0x000001)
1795  ret = ff_stream_add_bitstream_filter(st, "hevc_mp4toannexb", NULL);
1796  }
1797 
1798  return ret;
1799 }
1800 
1801 static const AVOption options[] = {
1802  { "mpegts_transport_stream_id", "Set transport_stream_id field.",
1803  offsetof(MpegTSWrite, transport_stream_id), AV_OPT_TYPE_INT,
1804  { .i64 = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM },
1805  { "mpegts_original_network_id", "Set original_network_id field.",
1806  offsetof(MpegTSWrite, original_network_id), AV_OPT_TYPE_INT,
1807  { .i64 = DVB_PRIVATE_NETWORK_START }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM },
1808  { "mpegts_service_id", "Set service_id field.",
1809  offsetof(MpegTSWrite, service_id), AV_OPT_TYPE_INT,
1810  { .i64 = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM },
1811  { "mpegts_service_type", "Set service_type field.",
1812  offsetof(MpegTSWrite, service_type), AV_OPT_TYPE_INT,
1813  { .i64 = 0x01 }, 0x01, 0xff, AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1814  { "digital_tv", "Digital Television.",
1815  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_DIGITAL_TV }, 0x01, 0xff,
1816  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1817  { "digital_radio", "Digital Radio.",
1818  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_DIGITAL_RADIO }, 0x01, 0xff,
1819  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1820  { "teletext", "Teletext.",
1821  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_TELETEXT }, 0x01, 0xff,
1822  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1823  { "advanced_codec_digital_radio", "Advanced Codec Digital Radio.",
1825  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1826  { "mpeg2_digital_hdtv", "MPEG2 Digital HDTV.",
1827  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_MPEG2_DIGITAL_HDTV }, 0x01, 0xff,
1828  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1829  { "advanced_codec_digital_sdtv", "Advanced Codec Digital SDTV.",
1831  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1832  { "advanced_codec_digital_hdtv", "Advanced Codec Digital HDTV.",
1834  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1835  { "hevc_digital_hdtv", "HEVC Digital Television Service.",
1836  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_HEVC_DIGITAL_HDTV }, 0x01, 0xff,
1837  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1838  { "mpegts_pmt_start_pid", "Set the first pid of the PMT.",
1839  offsetof(MpegTSWrite, pmt_start_pid), AV_OPT_TYPE_INT,
1840  { .i64 = 0x1000 }, 0x0010, 0x1f00, AV_OPT_FLAG_ENCODING_PARAM },
1841  { "mpegts_start_pid", "Set the first pid.",
1842  offsetof(MpegTSWrite, start_pid), AV_OPT_TYPE_INT,
1843  { .i64 = 0x0100 }, 0x0020, 0x0f00, AV_OPT_FLAG_ENCODING_PARAM },
1844  { "mpegts_m2ts_mode", "Enable m2ts mode.",
1845  offsetof(MpegTSWrite, m2ts_mode), AV_OPT_TYPE_BOOL,
1846  { .i64 = -1 }, -1, 1, AV_OPT_FLAG_ENCODING_PARAM },
1847  { "muxrate", NULL,
1848  offsetof(MpegTSWrite, mux_rate), AV_OPT_TYPE_INT,
1849  { .i64 = 1 }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
1850  { "pes_payload_size", "Minimum PES packet payload in bytes",
1851  offsetof(MpegTSWrite, pes_payload_size), AV_OPT_TYPE_INT,
1852  { .i64 = DEFAULT_PES_PAYLOAD_SIZE }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
1853  { "mpegts_flags", "MPEG-TS muxing flags",
1854  offsetof(MpegTSWrite, flags), AV_OPT_TYPE_FLAGS, { .i64 = 0 }, 0, INT_MAX,
1855  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags" },
1856  { "resend_headers", "Reemit PAT/PMT before writing the next packet",
1857  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_FLAG_REEMIT_PAT_PMT }, 0, INT_MAX,
1858  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags" },
1859  { "latm", "Use LATM packetization for AAC",
1860  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_FLAG_AAC_LATM }, 0, INT_MAX,
1861  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags" },
1862  { "pat_pmt_at_frames", "Reemit PAT and PMT at each video frame",
1863  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_FLAG_PAT_PMT_AT_FRAMES}, 0, INT_MAX,
1864  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags" },
1865  { "system_b", "Conform to System B (DVB) instead of System A (ATSC)",
1866  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_FLAG_SYSTEM_B }, 0, INT_MAX,
1867  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags" },
1868  // backward compatibility
1869  { "resend_headers", "Reemit PAT/PMT before writing the next packet",
1870  offsetof(MpegTSWrite, reemit_pat_pmt), AV_OPT_TYPE_INT,
1871  { .i64 = 0 }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
1872  { "mpegts_copyts", "don't offset dts/pts",
1873  offsetof(MpegTSWrite, copyts), AV_OPT_TYPE_BOOL,
1874  { .i64 = -1 }, -1, 1, AV_OPT_FLAG_ENCODING_PARAM },
1875  { "tables_version", "set PAT, PMT and SDT version",
1876  offsetof(MpegTSWrite, tables_version), AV_OPT_TYPE_INT,
1877  { .i64 = 0 }, 0, 31, AV_OPT_FLAG_ENCODING_PARAM },
1878  { "omit_video_pes_length", "Omit the PES packet length for video packets",
1879  offsetof(MpegTSWrite, omit_video_pes_length), AV_OPT_TYPE_BOOL,
1880  { .i64 = 1 }, 0, 1, AV_OPT_FLAG_ENCODING_PARAM },
1881  { "pcr_period", "PCR retransmission time",
1882  offsetof(MpegTSWrite, pcr_period), AV_OPT_TYPE_INT,
1883  { .i64 = PCR_RETRANS_TIME }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
1884  { "pat_period", "PAT/PMT retransmission time limit in seconds",
1885  offsetof(MpegTSWrite, pat_period), AV_OPT_TYPE_DOUBLE,
1886  { .dbl = INT_MAX }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
1887  { "sdt_period", "SDT retransmission time limit in seconds",
1888  offsetof(MpegTSWrite, sdt_period), AV_OPT_TYPE_DOUBLE,
1889  { .dbl = INT_MAX }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
1890  { NULL },
1891 };
1892 
1893 static const AVClass mpegts_muxer_class = {
1894  .class_name = "MPEGTS muxer",
1895  .item_name = av_default_item_name,
1896  .option = options,
1897  .version = LIBAVUTIL_VERSION_INT,
1898 };
1899 
1901  .name = "mpegts",
1902  .long_name = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
1903  .mime_type = "video/MP2T",
1904  .extensions = "ts,m2t,m2ts,mts",
1905  .priv_data_size = sizeof(MpegTSWrite),
1906  .audio_codec = AV_CODEC_ID_MP2,
1907  .video_codec = AV_CODEC_ID_MPEG2VIDEO,
1908  .init = mpegts_init,
1911  .deinit = mpegts_deinit,
1912  .check_bitstream = mpegts_check_bitstream,
1914  .priv_class = &mpegts_muxer_class,
1915 };
#define NULL
Definition: coverity.c:32
#define SDT_PID
Definition: mpegts.h:37
const char const char void * val
Definition: avisynth_c.h:634
const char * s
Definition: avisynth_c.h:631
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:1272
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:820
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:182
#define LIBAVUTIL_VERSION_INT
Definition: version.h:70
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:4427
#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:3922
char * name
Definition: mpegtsenc.c:56
int num
numerator
Definition: rational.h:44
int size
Definition: avcodec.h:1581
const char * b
Definition: vf_curves.c:109
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:842
#define STREAM_TYPE_AUDIO_EAC3
Definition: mpegts.h:64
void * priv_data
Definition: avformat.h:891
#define AV_DISPOSITION_CLEAN_EFFECTS
stream without voice
Definition: avformat.h:844
int version
Definition: avisynth_c.h:629
#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:493
int avio_open_dyn_buf(AVIOContext **s)
Open a write only memory stream.
Definition: aviobuf.c:1260
double pat_period
Definition: mpegtsenc.c:110
Format I/O context.
Definition: avformat.h:1325
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:1257
#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:195
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:883
AVStream * avformat_new_stream(AVFormatContext *s, const AVCodec *c)
Add a new stream to a media file.
Definition: utils.c:4065
static int mpegts_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
Definition: mpegtsenc.c:1783
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:1393
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:1738
int initial_padding
Audio only.
Definition: avcodec.h:4051
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:39
static void mpegts_insert_null_packet(AVFormatContext *s)
Definition: mpegtsenc.c:1050
uint8_t * data
Definition: avcodec.h:1580
#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
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:1256
#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:1344
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: avcodec.h:1612
#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:1511
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:3846
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:4059
#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:1539
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
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 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:1478
#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:515
enum AVMediaType codec_type
General type of the encoded data.
Definition: avcodec.h:3918
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:1478
New fields can be added to the end with minor version bumps.
Definition: avformat.h:1252
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:3657
#define fail()
Definition: checkasm.h:81
#define MPEGTS_FLAG_SYSTEM_B
Definition: mpegtsenc.c:106
int flags
A combination of AV_PKT_FLAG values.
Definition: avcodec.h:1586
int av_compare_ts(int64_t ts_a, AVRational tb_a, int64_t ts_b, AVRational tb_b)
Compare 2 timestamps each in its own timebases.
Definition: mathematics.c:147
int extradata_size
Size of the extradata content in bytes.
Definition: avcodec.h:3940
double sdt_period
Definition: mpegtsenc.c:111
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
Definition: avformat.h:1381
#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:1396
static const AVOption options[]
Definition: mpegtsenc.c:1801
char filename[1024]
input or output filename
Definition: avformat.h:1401
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:246
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:522
#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:1412
AVOutputFormat ff_mpegts_muxer
Definition: mpegtsenc.c:1900
int n
Definition: avisynth_c.h:547
AVFormatContext * amux
Definition: mpegtsenc.c:233
AVDictionary * metadata
Definition: avformat.h:945
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:194
#define STREAM_TYPE_VIDEO_MPEG4
Definition: mpeg.h:56
static void mpegts_deinit(AVFormatContext *s)
Definition: mpegtsenc.c:1756
int pmt_start_pid
Definition: mpegtsenc.c:96
void ffio_free_dyn_buf(AVIOContext **s)
Free a dynamic buffer.
Definition: aviobuf.c:1300
int service_type
Definition: mpegtsenc.c:94
#define AV_DISPOSITION_VISUAL_IMPAIRED
stream for visual impaired audiences
Definition: avformat.h:843
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:97
#define STREAM_TYPE_METADATA
Definition: mpegts.h:54
#define av_bswap32
Definition: bswap.h:33
int frame_size
Definition: mxfenc.c:1821
#define DVB_PRIVATE_NETWORK_START
Definition: mpegtsenc.c:41
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:252
char * av_strdup(const char *s)
Duplicate the string s.
Definition: mem.c:267
int sdt_packet_period
Definition: mpegtsenc.c:81
AVIOContext * pb
I/O context.
Definition: avformat.h:1367
#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:553
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:1430
int original_network_id
Definition: mpegtsenc.c:92
#define AV_WB32(p, v)
Definition: intreadwrite.h:419
rational number numerator/denominator
Definition: rational.h:43
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:1452
byte swapping routines
static int mpegts_write_end(AVFormatContext *s)
Definition: mpegtsenc.c:1748
#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:4001
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
static struct @228 state
uint8_t * payload
Definition: mpegtsenc.c:232
AVDictionary * metadata
Definition: avformat.h:1258
static int64_t pts
Global timestamp for the audio frames.
static void mpegts_write_flush(AVFormatContext *s)
Definition: mpegtsenc.c:1720
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:4032
#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:934
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:932
int den
denominator
Definition: rational.h:45
#define AVFMT_VARIABLE_FPS
Format allows variable fps.
Definition: avformat.h:487
#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:4991
void * priv_data
Format private data.
Definition: avformat.h:1353
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:3936
int channels
Audio only.
Definition: avcodec.h:4028
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed...
Definition: avcodec.h:1579
int pat_packet_count
Definition: mpegtsenc.c:82
static const AVClass mpegts_muxer_class
Definition: mpegtsenc.c:1893
#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:334
AVCodecParameters * codecpar
Definition: avformat.h:1006
#define av_malloc_array(a, b)
int opus_pending_trim_start
Definition: mpegtsenc.c:238
int stream_index
Definition: avcodec.h:1582
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avformat.h:913
#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:1557
static int write_packet(AVFormatContext *s1, AVPacket *pkt)
Definition: v4l2enc.c:86
static void mpegts_write_section(MpegTSSection *s, uint8_t *buf, int len)
Definition: mpegtsenc.c:127
void * av_mallocz(size_t size)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
Definition: mem.c:252
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: avcodec.h:1573
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:240
#define STREAM_TYPE_AUDIO_TRUEHD
Definition: mpegts.h:63
AVProgram ** programs
Definition: avformat.h:1479
#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