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