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