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