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  int flags;
102  int copyts;
104 
106 } MpegTSWrite;
107 
108 /* a PES packet header is generated every DEFAULT_PES_HEADER_FREQ packets */
109 #define DEFAULT_PES_HEADER_FREQ 16
110 #define DEFAULT_PES_PAYLOAD_SIZE ((DEFAULT_PES_HEADER_FREQ - 1) * 184 + 170)
111 
112 /* The section length is 12 bits. The first 2 are set to 0, the remaining
113  * 10 bits should not exceed 1021. */
114 #define SECTION_LENGTH 1020
115 
116 /* NOTE: 4 bytes must be left at the end for the crc32 */
118 {
119  unsigned int crc;
120  unsigned char packet[TS_PACKET_SIZE];
121  const unsigned char *buf_ptr;
122  unsigned char *q;
123  int first, b, len1, left;
124 
126  -1, buf, len - 4));
127 
128  buf[len - 4] = (crc >> 24) & 0xff;
129  buf[len - 3] = (crc >> 16) & 0xff;
130  buf[len - 2] = (crc >> 8) & 0xff;
131  buf[len - 1] = crc & 0xff;
132 
133  /* send each packet */
134  buf_ptr = buf;
135  while (len > 0) {
136  first = buf == buf_ptr;
137  q = packet;
138  *q++ = 0x47;
139  b = s->pid >> 8;
140  if (first)
141  b |= 0x40;
142  *q++ = b;
143  *q++ = s->pid;
144  s->cc = s->cc + 1 & 0xf;
145  *q++ = 0x10 | s->cc;
146  if (first)
147  *q++ = 0; /* 0 offset */
148  len1 = TS_PACKET_SIZE - (q - packet);
149  if (len1 > len)
150  len1 = len;
151  memcpy(q, buf_ptr, len1);
152  q += len1;
153  /* add known padding data */
154  left = TS_PACKET_SIZE - (q - packet);
155  if (left > 0)
156  memset(q, 0xff, left);
157 
158  s->write_packet(s, packet);
159 
160  buf_ptr += len1;
161  len -= len1;
162  }
163 }
164 
165 static inline void put16(uint8_t **q_ptr, int val)
166 {
167  uint8_t *q;
168  q = *q_ptr;
169  *q++ = val >> 8;
170  *q++ = val;
171  *q_ptr = q;
172 }
173 
174 static int mpegts_write_section1(MpegTSSection *s, int tid, int id,
175  int version, int sec_num, int last_sec_num,
176  uint8_t *buf, int len)
177 {
178  uint8_t section[1024], *q;
179  unsigned int tot_len;
180  /* reserved_future_use field must be set to 1 for SDT */
181  unsigned int flags = tid == SDT_TID ? 0xf000 : 0xb000;
182 
183  tot_len = 3 + 5 + len + 4;
184  /* check if not too big */
185  if (tot_len > 1024)
186  return AVERROR_INVALIDDATA;
187 
188  q = section;
189  *q++ = tid;
190  put16(&q, flags | (len + 5 + 4)); /* 5 byte header + 4 byte CRC */
191  put16(&q, id);
192  *q++ = 0xc1 | (version << 1); /* current_next_indicator = 1 */
193  *q++ = sec_num;
194  *q++ = last_sec_num;
195  memcpy(q, buf, len);
196 
197  mpegts_write_section(s, section, tot_len);
198  return 0;
199 }
200 
201 /*********************************************/
202 /* mpegts writer */
203 
204 #define DEFAULT_PROVIDER_NAME "FFmpeg"
205 #define DEFAULT_SERVICE_NAME "Service01"
206 
207 /* we retransmit the SI info at this rate */
208 #define SDT_RETRANS_TIME 500
209 #define PAT_RETRANS_TIME 100
210 #define PCR_RETRANS_TIME 20
211 
212 typedef struct MpegTSWriteStream {
214  int pid; /* stream associated pid */
215  int cc;
217  int first_pts_check; ///< first pts check needed
219  int64_t payload_pts;
220  int64_t payload_dts;
226 
228 {
229  MpegTSWrite *ts = s->priv_data;
230  MpegTSService *service;
232  int i;
233 
234  q = data;
235  for (i = 0; i < ts->nb_services; i++) {
236  service = ts->services[i];
237  put16(&q, service->sid);
238  put16(&q, 0xe000 | service->pmt.pid);
239  }
240  mpegts_write_section1(&ts->pat, PAT_TID, ts->tsid, ts->tables_version, 0, 0,
241  data, q - data);
242 }
243 
245 {
246  MpegTSWrite *ts = s->priv_data;
247  uint8_t data[SECTION_LENGTH], *q, *desc_length_ptr, *program_info_length_ptr;
248  int val, stream_type, i, err = 0;
249 
250  q = data;
251  put16(&q, 0xe000 | service->pcr_pid);
252 
253  program_info_length_ptr = q;
254  q += 2; /* patched after */
255 
256  /* put program info here */
257 
258  val = 0xf000 | (q - program_info_length_ptr - 2);
259  program_info_length_ptr[0] = val >> 8;
260  program_info_length_ptr[1] = val;
261 
262  for (i = 0; i < s->nb_streams; i++) {
263  AVStream *st = s->streams[i];
264  MpegTSWriteStream *ts_st = st->priv_data;
265  AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL, 0);
266 
267  if (q - data > SECTION_LENGTH - 32) {
268  err = 1;
269  break;
270  }
271  switch (st->codec->codec_id) {
274  stream_type = STREAM_TYPE_VIDEO_MPEG2;
275  break;
276  case AV_CODEC_ID_MPEG4:
277  stream_type = STREAM_TYPE_VIDEO_MPEG4;
278  break;
279  case AV_CODEC_ID_H264:
280  stream_type = STREAM_TYPE_VIDEO_H264;
281  break;
282  case AV_CODEC_ID_HEVC:
283  stream_type = STREAM_TYPE_VIDEO_HEVC;
284  break;
285  case AV_CODEC_ID_CAVS:
286  stream_type = STREAM_TYPE_VIDEO_CAVS;
287  break;
288  case AV_CODEC_ID_DIRAC:
289  stream_type = STREAM_TYPE_VIDEO_DIRAC;
290  break;
291  case AV_CODEC_ID_MP2:
292  case AV_CODEC_ID_MP3:
293  stream_type = STREAM_TYPE_AUDIO_MPEG1;
294  break;
295  case AV_CODEC_ID_AAC:
296  stream_type = (ts->flags & MPEGTS_FLAG_AAC_LATM)
299  break;
301  stream_type = STREAM_TYPE_AUDIO_AAC_LATM;
302  break;
303  case AV_CODEC_ID_AC3:
304  stream_type = STREAM_TYPE_AUDIO_AC3;
305  break;
306  case AV_CODEC_ID_DTS:
307  stream_type = STREAM_TYPE_AUDIO_DTS;
308  break;
309  case AV_CODEC_ID_TRUEHD:
310  stream_type = STREAM_TYPE_AUDIO_TRUEHD;
311  break;
312  default:
313  stream_type = STREAM_TYPE_PRIVATE_DATA;
314  break;
315  }
316 
317  *q++ = stream_type;
318  put16(&q, 0xe000 | ts_st->pid);
319  desc_length_ptr = q;
320  q += 2; /* patched after */
321 
322  /* write optional descriptors here */
323  switch (st->codec->codec_type) {
324  case AVMEDIA_TYPE_AUDIO:
325  if (st->codec->codec_id==AV_CODEC_ID_EAC3) {
326  *q++=0x7a; // EAC3 descriptor see A038 DVB SI
327  *q++=1; // 1 byte, all flags sets to 0
328  *q++=0; // omit all fields...
329  }
330  if (st->codec->codec_id==AV_CODEC_ID_S302M) {
331  *q++ = 0x05; /* MPEG-2 registration descriptor*/
332  *q++ = 4;
333  *q++ = 'B';
334  *q++ = 'S';
335  *q++ = 'S';
336  *q++ = 'D';
337  }
338 
339  if (lang) {
340  char *p;
341  char *next = lang->value;
342  uint8_t *len_ptr;
343 
344  *q++ = 0x0a; /* ISO 639 language descriptor */
345  len_ptr = q++;
346  *len_ptr = 0;
347 
348  for (p = lang->value; next && *len_ptr < 255 / 4 * 4; p = next + 1) {
349  if (q - data > SECTION_LENGTH - 4) {
350  err = 1;
351  break;
352  }
353  next = strchr(p, ',');
354  if (strlen(p) != 3 && (!next || next != p + 3))
355  continue; /* not a 3-letter code */
356 
357  *q++ = *p++;
358  *q++ = *p++;
359  *q++ = *p++;
360 
362  *q++ = 0x01;
364  *q++ = 0x02;
366  *q++ = 0x03;
367  else
368  *q++ = 0; /* undefined type */
369 
370  *len_ptr += 4;
371  }
372 
373  if (*len_ptr == 0)
374  q -= 2; /* no language codes were written */
375  }
376  break;
378  {
379  const char default_language[] = "und";
380  const char *language = lang && strlen(lang->value) >= 3 ? lang->value : default_language;
381 
383  uint8_t *len_ptr;
384  int extradata_copied = 0;
385 
386  *q++ = 0x59; /* subtitling_descriptor */
387  len_ptr = q++;
388 
389  while (strlen(language) >= 3) {
390  if (sizeof(data) - (q - data) < 8) { /* 8 bytes per DVB subtitle substream data */
391  err = 1;
392  break;
393  }
394  *q++ = *language++;
395  *q++ = *language++;
396  *q++ = *language++;
397  /* Skip comma */
398  if (*language != '\0')
399  language++;
400 
401  if (st->codec->extradata_size - extradata_copied >= 5) {
402  *q++ = st->codec->extradata[extradata_copied + 4]; /* subtitling_type */
403  memcpy(q, st->codec->extradata + extradata_copied, 4); /* composition_page_id and ancillary_page_id */
404  extradata_copied += 5;
405  q += 4;
406  } else {
407  /* subtitling_type:
408  * 0x10 - normal with no monitor aspect ratio criticality
409  * 0x20 - for the hard of hearing with no monitor aspect ratio criticality */
410  *q++ = (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED) ? 0x20 : 0x10;
411  if ((st->codec->extradata_size == 4) && (extradata_copied == 0)) {
412  /* support of old 4-byte extradata format */
413  memcpy(q, st->codec->extradata, 4); /* composition_page_id and ancillary_page_id */
414  extradata_copied += 4;
415  q += 4;
416  } else {
417  put16(&q, 1); /* composition_page_id */
418  put16(&q, 1); /* ancillary_page_id */
419  }
420  }
421  }
422 
423  *len_ptr = q - len_ptr - 1;
424  } else if (st->codec->codec_id == AV_CODEC_ID_DVB_TELETEXT) {
425  uint8_t *len_ptr = NULL;
426  int extradata_copied = 0;
427 
428  /* The descriptor tag. teletext_descriptor */
429  *q++ = 0x56;
430  len_ptr = q++;
431 
432  while (strlen(language) >= 3 && q - data < sizeof(data) - 6) {
433  *q++ = *language++;
434  *q++ = *language++;
435  *q++ = *language++;
436  /* Skip comma */
437  if (*language != '\0')
438  language++;
439 
440  if (st->codec->extradata_size - 1 > extradata_copied) {
441  memcpy(q, st->codec->extradata + extradata_copied, 2);
442  extradata_copied += 2;
443  q += 2;
444  } else {
445  /* The Teletext descriptor:
446  * teletext_type: This 5-bit field indicates the type of Teletext page indicated. (0x01 Initial Teletext page)
447  * teletext_magazine_number: This is a 3-bit field which identifies the magazine number.
448  * teletext_page_number: This is an 8-bit field giving two 4-bit hex digits identifying the page number. */
449  *q++ = 0x08;
450  *q++ = 0x00;
451  }
452  }
453 
454  *len_ptr = q - len_ptr - 1;
455  }
456  }
457  break;
458  case AVMEDIA_TYPE_VIDEO:
459  if (stream_type == STREAM_TYPE_VIDEO_DIRAC) {
460  *q++ = 0x05; /*MPEG-2 registration descriptor*/
461  *q++ = 4;
462  *q++ = 'd';
463  *q++ = 'r';
464  *q++ = 'a';
465  *q++ = 'c';
466  }
467  break;
468  case AVMEDIA_TYPE_DATA:
469  if (st->codec->codec_id == AV_CODEC_ID_SMPTE_KLV) {
470  *q++ = 0x05; /* MPEG-2 registration descriptor */
471  *q++ = 4;
472  *q++ = 'K';
473  *q++ = 'L';
474  *q++ = 'V';
475  *q++ = 'A';
476  }
477  break;
478  }
479 
480  val = 0xf000 | (q - desc_length_ptr - 2);
481  desc_length_ptr[0] = val >> 8;
482  desc_length_ptr[1] = val;
483  }
484 
485  if (err)
486  av_log(s, AV_LOG_ERROR,
487  "The PMT section cannot fit stream %d and all following streams.\n"
488  "Try reducing the number of languages in the audio streams "
489  "or the total number of streams.\n", i);
490 
491  mpegts_write_section1(&service->pmt, PMT_TID, service->sid, ts->tables_version, 0, 0,
492  data, q - data);
493  return 0;
494 }
495 
496 /* NOTE: !str is accepted for an empty string */
497 static void putstr8(uint8_t **q_ptr, const char *str)
498 {
499  uint8_t *q;
500  int len;
501 
502  q = *q_ptr;
503  if (!str)
504  len = 0;
505  else
506  len = strlen(str);
507  *q++ = len;
508  memcpy(q, str, len);
509  q += len;
510  *q_ptr = q;
511 }
512 
514 {
515  MpegTSWrite *ts = s->priv_data;
516  MpegTSService *service;
517  uint8_t data[SECTION_LENGTH], *q, *desc_list_len_ptr, *desc_len_ptr;
518  int i, running_status, free_ca_mode, val;
519 
520  q = data;
521  put16(&q, ts->onid);
522  *q++ = 0xff;
523  for (i = 0; i < ts->nb_services; i++) {
524  service = ts->services[i];
525  put16(&q, service->sid);
526  *q++ = 0xfc | 0x00; /* currently no EIT info */
527  desc_list_len_ptr = q;
528  q += 2;
529  running_status = 4; /* running */
530  free_ca_mode = 0;
531 
532  /* write only one descriptor for the service name and provider */
533  *q++ = 0x48;
534  desc_len_ptr = q;
535  q++;
536  *q++ = ts->service_type;
537  putstr8(&q, service->provider_name);
538  putstr8(&q, service->name);
539  desc_len_ptr[0] = q - desc_len_ptr - 1;
540 
541  /* fill descriptor length */
542  val = (running_status << 13) | (free_ca_mode << 12) |
543  (q - desc_list_len_ptr - 2);
544  desc_list_len_ptr[0] = val >> 8;
545  desc_list_len_ptr[1] = val;
546  }
547  mpegts_write_section1(&ts->sdt, SDT_TID, ts->tsid, ts->tables_version, 0, 0,
548  data, q - data);
549 }
550 
552  const char *provider_name,
553  const char *name)
554 {
555  MpegTSService *service;
556 
557  service = av_mallocz(sizeof(MpegTSService));
558  if (!service)
559  return NULL;
560  service->pmt.pid = ts->pmt_start_pid + ts->nb_services;
561  service->sid = sid;
562  service->pcr_pid = 0x1fff;
563  service->provider_name = av_strdup(provider_name);
564  service->name = av_strdup(name);
565  if (!service->provider_name || !service->name)
566  goto fail;
567  if (av_dynarray_add_nofree(&ts->services, &ts->nb_services, service) < 0)
568  goto fail;
569 
570  return service;
571 fail:
572  av_freep(&service->provider_name);
573  av_freep(&service->name);
574  av_free(service);
575  return NULL;
576 }
577 
578 static int64_t get_pcr(const MpegTSWrite *ts, AVIOContext *pb)
579 {
580  return av_rescale(avio_tell(pb) + 11, 8 * PCR_TIME_BASE, ts->mux_rate) +
581  ts->first_pcr;
582 }
583 
585 {
586  MpegTSWrite *ts = s->priv_data;
587  if (ts->m2ts_mode) {
588  int64_t pcr = get_pcr(s->priv_data, s->pb);
589  uint32_t tp_extra_header = pcr % 0x3fffffff;
590  tp_extra_header = AV_RB32(&tp_extra_header);
591  avio_write(s->pb, (unsigned char *) &tp_extra_header,
592  sizeof(tp_extra_header));
593  }
594 }
595 
596 static void section_write_packet(MpegTSSection *s, const uint8_t *packet)
597 {
598  AVFormatContext *ctx = s->opaque;
600  avio_write(ctx->pb, packet, TS_PACKET_SIZE);
601 }
602 
604 {
605  MpegTSWrite *ts = s->priv_data;
606  MpegTSWriteStream *ts_st;
607  MpegTSService *service;
608  AVStream *st, *pcr_st = NULL;
609  AVDictionaryEntry *title, *provider;
610  int i, j;
611  const char *service_name;
612  const char *provider_name;
613  int *pids;
614  int ret;
615 
616  if (s->max_delay < 0) /* Not set by the caller */
617  s->max_delay = 0;
618 
619  // round up to a whole number of TS packets
620  ts->pes_payload_size = (ts->pes_payload_size + 14 + 183) / 184 * 184 - 14;
621 
622  ts->tsid = ts->transport_stream_id;
623  ts->onid = ts->original_network_id;
624  /* allocate a single DVB service */
625  title = av_dict_get(s->metadata, "service_name", NULL, 0);
626  if (!title)
627  title = av_dict_get(s->metadata, "title", NULL, 0);
628  service_name = title ? title->value : DEFAULT_SERVICE_NAME;
629  provider = av_dict_get(s->metadata, "service_provider", NULL, 0);
630  provider_name = provider ? provider->value : DEFAULT_PROVIDER_NAME;
631  service = mpegts_add_service(ts, ts->service_id,
632  provider_name, service_name);
633 
634  if (!service)
635  return AVERROR(ENOMEM);
636 
638  service->pmt.opaque = s;
639  service->pmt.cc = 15;
640 
641  ts->pat.pid = PAT_PID;
642  /* Initialize at 15 so that it wraps and is equal to 0 for the
643  * first packet we write. */
644  ts->pat.cc = 15;
646  ts->pat.opaque = s;
647 
648  ts->sdt.pid = SDT_PID;
649  ts->sdt.cc = 15;
651  ts->sdt.opaque = s;
652 
653  pids = av_malloc_array(s->nb_streams, sizeof(*pids));
654  if (!pids) {
655  ret = AVERROR(ENOMEM);
656  goto fail;
657  }
658 
659  /* assign pids to each stream */
660  for (i = 0; i < s->nb_streams; i++) {
661  st = s->streams[i];
662 
663  ts_st = av_mallocz(sizeof(MpegTSWriteStream));
664  if (!ts_st) {
665  ret = AVERROR(ENOMEM);
666  goto fail;
667  }
668  st->priv_data = ts_st;
669 
670  ts_st->user_tb = st->time_base;
671  avpriv_set_pts_info(st, 33, 1, 90000);
672 
673  ts_st->payload = av_mallocz(ts->pes_payload_size);
674  if (!ts_st->payload) {
675  ret = AVERROR(ENOMEM);
676  goto fail;
677  }
678  ts_st->service = service;
679  /* MPEG pid values < 16 are reserved. Applications which set st->id in
680  * this range are assigned a calculated pid. */
681  if (st->id < 16) {
682  ts_st->pid = ts->start_pid + i;
683  } else if (st->id < 0x1FFF) {
684  ts_st->pid = st->id;
685  } else {
686  av_log(s, AV_LOG_ERROR,
687  "Invalid stream id %d, must be less than 8191\n", st->id);
688  ret = AVERROR(EINVAL);
689  goto fail;
690  }
691  if (ts_st->pid == service->pmt.pid) {
692  av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
693  ret = AVERROR(EINVAL);
694  goto fail;
695  }
696  for (j = 0; j < i; j++) {
697  if (pids[j] == ts_st->pid) {
698  av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
699  ret = AVERROR(EINVAL);
700  goto fail;
701  }
702  }
703  pids[i] = ts_st->pid;
704  ts_st->payload_pts = AV_NOPTS_VALUE;
705  ts_st->payload_dts = AV_NOPTS_VALUE;
706  ts_st->first_pts_check = 1;
707  ts_st->cc = 15;
708  /* update PCR pid by using the first video stream */
709  if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
710  service->pcr_pid == 0x1fff) {
711  service->pcr_pid = ts_st->pid;
712  pcr_st = st;
713  }
714  if (st->codec->codec_id == AV_CODEC_ID_AAC &&
715  st->codec->extradata_size > 0) {
716  AVStream *ast;
717  ts_st->amux = avformat_alloc_context();
718  if (!ts_st->amux) {
719  ret = AVERROR(ENOMEM);
720  goto fail;
721  }
722  ts_st->amux->oformat =
723  av_guess_format((ts->flags & MPEGTS_FLAG_AAC_LATM) ? "latm" : "adts",
724  NULL, NULL);
725  if (!ts_st->amux->oformat) {
726  ret = AVERROR(EINVAL);
727  goto fail;
728  }
729  if (!(ast = avformat_new_stream(ts_st->amux, NULL))) {
730  ret = AVERROR(ENOMEM);
731  goto fail;
732  }
733  ret = avcodec_copy_context(ast->codec, st->codec);
734  if (ret != 0)
735  goto fail;
736  ast->time_base = st->time_base;
737  ret = avformat_write_header(ts_st->amux, NULL);
738  if (ret < 0)
739  goto fail;
740  }
741  }
742 
743  av_freep(&pids);
744 
745  /* if no video stream, use the first stream as PCR */
746  if (service->pcr_pid == 0x1fff && s->nb_streams > 0) {
747  pcr_st = s->streams[0];
748  ts_st = pcr_st->priv_data;
749  service->pcr_pid = ts_st->pid;
750  } else
751  ts_st = pcr_st->priv_data;
752 
753  if (ts->mux_rate > 1) {
754  service->pcr_packet_period = (ts->mux_rate * ts->pcr_period) /
755  (TS_PACKET_SIZE * 8 * 1000);
757  (TS_PACKET_SIZE * 8 * 1000);
759  (TS_PACKET_SIZE * 8 * 1000);
760 
761  if (ts->copyts < 1)
763  } else {
764  /* Arbitrary values, PAT/PMT will also be written on video key frames */
765  ts->sdt_packet_period = 200;
766  ts->pat_packet_period = 40;
767  if (pcr_st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
768  if (!pcr_st->codec->frame_size) {
769  av_log(s, AV_LOG_WARNING, "frame size not set\n");
770  service->pcr_packet_period =
771  pcr_st->codec->sample_rate / (10 * 512);
772  } else {
773  service->pcr_packet_period =
774  pcr_st->codec->sample_rate / (10 * pcr_st->codec->frame_size);
775  }
776  } else {
777  // max delta PCR 0.1s
778  // TODO: should be avg_frame_rate
779  service->pcr_packet_period =
780  ts_st->user_tb.den / (10 * ts_st->user_tb.num);
781  }
782  if (!service->pcr_packet_period)
783  service->pcr_packet_period = 1;
784  }
785 
786  // output a PCR as soon as possible
787  service->pcr_packet_count = service->pcr_packet_period;
788  ts->pat_packet_count = ts->pat_packet_period - 1;
789  ts->sdt_packet_count = ts->sdt_packet_period - 1;
790 
791  if (ts->mux_rate == 1)
792  av_log(s, AV_LOG_VERBOSE, "muxrate VBR, ");
793  else
794  av_log(s, AV_LOG_VERBOSE, "muxrate %d, ", ts->mux_rate);
796  "pcr every %d pkts, sdt every %d, pat/pmt every %d pkts\n",
797  service->pcr_packet_period,
799 
800  if (ts->m2ts_mode == -1) {
801  if (av_match_ext(s->filename, "m2ts")) {
802  ts->m2ts_mode = 1;
803  } else {
804  ts->m2ts_mode = 0;
805  }
806  }
807 
808  return 0;
809 
810 fail:
811  av_freep(&pids);
812  for (i = 0; i < s->nb_streams; i++) {
813  st = s->streams[i];
814  ts_st = st->priv_data;
815  if (ts_st) {
816  av_freep(&ts_st->payload);
817  if (ts_st->amux) {
818  avformat_free_context(ts_st->amux);
819  ts_st->amux = NULL;
820  }
821  }
822  av_freep(&st->priv_data);
823  }
824 
825  for (i = 0; i < ts->nb_services; i++) {
826  service = ts->services[i];
827  av_freep(&service->provider_name);
828  av_freep(&service->name);
829  av_freep(&service);
830  }
831  av_freep(&ts->services);
832  return ret;
833 }
834 
835 /* send SDT, PAT and PMT tables regulary */
836 static void retransmit_si_info(AVFormatContext *s, int force_pat)
837 {
838  MpegTSWrite *ts = s->priv_data;
839  int i;
840 
841  if (++ts->sdt_packet_count == ts->sdt_packet_period) {
842  ts->sdt_packet_count = 0;
843  mpegts_write_sdt(s);
844  }
845  if (++ts->pat_packet_count == ts->pat_packet_period || force_pat) {
846  ts->pat_packet_count = 0;
847  mpegts_write_pat(s);
848  for (i = 0; i < ts->nb_services; i++)
849  mpegts_write_pmt(s, ts->services[i]);
850  }
851 }
852 
853 static int write_pcr_bits(uint8_t *buf, int64_t pcr)
854 {
855  int64_t pcr_low = pcr % 300, pcr_high = pcr / 300;
856 
857  *buf++ = pcr_high >> 25;
858  *buf++ = pcr_high >> 17;
859  *buf++ = pcr_high >> 9;
860  *buf++ = pcr_high >> 1;
861  *buf++ = pcr_high << 7 | pcr_low >> 8 | 0x7e;
862  *buf++ = pcr_low;
863 
864  return 6;
865 }
866 
867 /* Write a single null transport stream packet */
869 {
870  uint8_t *q;
872 
873  q = buf;
874  *q++ = 0x47;
875  *q++ = 0x00 | 0x1f;
876  *q++ = 0xff;
877  *q++ = 0x10;
878  memset(q, 0x0FF, TS_PACKET_SIZE - (q - buf));
880  avio_write(s->pb, buf, TS_PACKET_SIZE);
881 }
882 
883 /* Write a single transport stream packet with a PCR and no payload */
885 {
886  MpegTSWrite *ts = s->priv_data;
887  MpegTSWriteStream *ts_st = st->priv_data;
888  uint8_t *q;
890 
891  q = buf;
892  *q++ = 0x47;
893  *q++ = ts_st->pid >> 8;
894  *q++ = ts_st->pid;
895  *q++ = 0x20 | ts_st->cc; /* Adaptation only */
896  /* Continuity Count field does not increment (see 13818-1 section 2.4.3.3) */
897  *q++ = TS_PACKET_SIZE - 5; /* Adaptation Field Length */
898  *q++ = 0x10; /* Adaptation flags: PCR present */
899 
900  /* PCR coded into 6 bytes */
901  q += write_pcr_bits(q, get_pcr(ts, s->pb));
902 
903  /* stuffing bytes */
904  memset(q, 0xFF, TS_PACKET_SIZE - (q - buf));
906  avio_write(s->pb, buf, TS_PACKET_SIZE);
907 }
908 
909 static void write_pts(uint8_t *q, int fourbits, int64_t pts)
910 {
911  int val;
912 
913  val = fourbits << 4 | (((pts >> 30) & 0x07) << 1) | 1;
914  *q++ = val;
915  val = (((pts >> 15) & 0x7fff) << 1) | 1;
916  *q++ = val >> 8;
917  *q++ = val;
918  val = (((pts) & 0x7fff) << 1) | 1;
919  *q++ = val >> 8;
920  *q++ = val;
921 }
922 
923 /* Set an adaptation field flag in an MPEG-TS packet*/
924 static void set_af_flag(uint8_t *pkt, int flag)
925 {
926  // expect at least one flag to set
927  av_assert0(flag);
928 
929  if ((pkt[3] & 0x20) == 0) {
930  // no AF yet, set adaptation field flag
931  pkt[3] |= 0x20;
932  // 1 byte length, no flags
933  pkt[4] = 1;
934  pkt[5] = 0;
935  }
936  pkt[5] |= flag;
937 }
938 
939 /* Extend the adaptation field by size bytes */
940 static void extend_af(uint8_t *pkt, int size)
941 {
942  // expect already existing adaptation field
943  av_assert0(pkt[3] & 0x20);
944  pkt[4] += size;
945 }
946 
947 /* Get a pointer to MPEG-TS payload (right after TS packet header) */
949 {
950  if (pkt[3] & 0x20)
951  return pkt + 5 + pkt[4];
952  else
953  return pkt + 4;
954 }
955 
956 /* Add a PES header to the front of the payload, and segment into an integer
957  * number of TS packets. The final TS packet is padded using an oversized
958  * adaptation header to exactly fill the last TS packet.
959  * NOTE: 'payload' contains a complete PES payload. */
961  const uint8_t *payload, int payload_size,
962  int64_t pts, int64_t dts, int key)
963 {
964  MpegTSWriteStream *ts_st = st->priv_data;
965  MpegTSWrite *ts = s->priv_data;
967  uint8_t *q;
968  int val, is_start, len, header_len, write_pcr, is_dvb_subtitle, is_dvb_teletext, flags;
969  int afc_len, stuffing_len;
970  int64_t pcr = -1; /* avoid warning */
971  int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE);
972  int force_pat = st->codec->codec_type == AVMEDIA_TYPE_VIDEO && key && !ts_st->prev_payload_key;
973 
974  is_start = 1;
975  while (payload_size > 0) {
976  retransmit_si_info(s, force_pat);
977  force_pat = 0;
978 
979  write_pcr = 0;
980  if (ts_st->pid == ts_st->service->pcr_pid) {
981  if (ts->mux_rate > 1 || is_start) // VBR pcr period is based on frames
982  ts_st->service->pcr_packet_count++;
983  if (ts_st->service->pcr_packet_count >=
984  ts_st->service->pcr_packet_period) {
985  ts_st->service->pcr_packet_count = 0;
986  write_pcr = 1;
987  }
988  }
989 
990  if (ts->mux_rate > 1 && dts != AV_NOPTS_VALUE &&
991  (dts - get_pcr(ts, s->pb) / 300) > delay) {
992  /* pcr insert gets priority over null packet insert */
993  if (write_pcr)
994  mpegts_insert_pcr_only(s, st);
995  else
997  /* recalculate write_pcr and possibly retransmit si_info */
998  continue;
999  }
1000 
1001  /* prepare packet header */
1002  q = buf;
1003  *q++ = 0x47;
1004  val = ts_st->pid >> 8;
1005  if (is_start)
1006  val |= 0x40;
1007  *q++ = val;
1008  *q++ = ts_st->pid;
1009  ts_st->cc = ts_st->cc + 1 & 0xf;
1010  *q++ = 0x10 | ts_st->cc; // payload indicator + CC
1011  if (key && is_start && pts != AV_NOPTS_VALUE) {
1012  // set Random Access for key frames
1013  if (ts_st->pid == ts_st->service->pcr_pid)
1014  write_pcr = 1;
1015  set_af_flag(buf, 0x40);
1016  q = get_ts_payload_start(buf);
1017  }
1018  if (write_pcr) {
1019  set_af_flag(buf, 0x10);
1020  q = get_ts_payload_start(buf);
1021  // add 11, pcr references the last byte of program clock reference base
1022  if (ts->mux_rate > 1)
1023  pcr = get_pcr(ts, s->pb);
1024  else
1025  pcr = (dts - delay) * 300;
1026  if (dts != AV_NOPTS_VALUE && dts < pcr / 300)
1027  av_log(s, AV_LOG_WARNING, "dts < pcr, TS is invalid\n");
1028  extend_af(buf, write_pcr_bits(q, pcr));
1029  q = get_ts_payload_start(buf);
1030  }
1031  if (is_start) {
1032  int pes_extension = 0;
1033  int pes_header_stuffing_bytes = 0;
1034  /* write PES header */
1035  *q++ = 0x00;
1036  *q++ = 0x00;
1037  *q++ = 0x01;
1038  is_dvb_subtitle = 0;
1039  is_dvb_teletext = 0;
1040  if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1041  if (st->codec->codec_id == AV_CODEC_ID_DIRAC)
1042  *q++ = 0xfd;
1043  else
1044  *q++ = 0xe0;
1045  } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1046  (st->codec->codec_id == AV_CODEC_ID_MP2 ||
1047  st->codec->codec_id == AV_CODEC_ID_MP3 ||
1048  st->codec->codec_id == AV_CODEC_ID_AAC)) {
1049  *q++ = 0xc0;
1050  } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1051  st->codec->codec_id == AV_CODEC_ID_AC3 &&
1052  ts->m2ts_mode) {
1053  *q++ = 0xfd;
1054  } else {
1055  *q++ = 0xbd;
1056  if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1057  if (st->codec->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
1058  is_dvb_subtitle = 1;
1059  } else if (st->codec->codec_id == AV_CODEC_ID_DVB_TELETEXT) {
1060  is_dvb_teletext = 1;
1061  }
1062  }
1063  }
1064  header_len = 0;
1065  flags = 0;
1066  if (pts != AV_NOPTS_VALUE) {
1067  header_len += 5;
1068  flags |= 0x80;
1069  }
1070  if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
1071  header_len += 5;
1072  flags |= 0x40;
1073  }
1074  if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
1075  st->codec->codec_id == AV_CODEC_ID_DIRAC) {
1076  /* set PES_extension_flag */
1077  pes_extension = 1;
1078  flags |= 0x01;
1079 
1080  /* One byte for PES2 extension flag +
1081  * one byte for extension length +
1082  * one byte for extension id */
1083  header_len += 3;
1084  }
1085  /* for Blu-ray AC3 Audio the PES Extension flag should be as follow
1086  * otherwise it will not play sound on blu-ray
1087  */
1088  if (ts->m2ts_mode &&
1090  st->codec->codec_id == AV_CODEC_ID_AC3) {
1091  /* set PES_extension_flag */
1092  pes_extension = 1;
1093  flags |= 0x01;
1094  header_len += 3;
1095  }
1096  if (is_dvb_teletext) {
1097  pes_header_stuffing_bytes = 0x24 - header_len;
1098  header_len = 0x24;
1099  }
1100  len = payload_size + header_len + 3;
1101  /* 3 extra bytes should be added to DVB subtitle payload: 0x20 0x00 at the beginning and trailing 0xff */
1102  if (is_dvb_subtitle) {
1103  len += 3;
1104  payload_size++;
1105  }
1106  if (len > 0xffff)
1107  len = 0;
1109  len = 0;
1110  }
1111  *q++ = len >> 8;
1112  *q++ = len;
1113  val = 0x80;
1114  /* data alignment indicator is required for subtitle and data streams */
1116  val |= 0x04;
1117  *q++ = val;
1118  *q++ = flags;
1119  *q++ = header_len;
1120  if (pts != AV_NOPTS_VALUE) {
1121  write_pts(q, flags >> 6, pts);
1122  q += 5;
1123  }
1124  if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
1125  write_pts(q, 1, dts);
1126  q += 5;
1127  }
1128  if (pes_extension && st->codec->codec_id == AV_CODEC_ID_DIRAC) {
1129  flags = 0x01; /* set PES_extension_flag_2 */
1130  *q++ = flags;
1131  *q++ = 0x80 | 0x01; /* marker bit + extension length */
1132  /* Set the stream ID extension flag bit to 0 and
1133  * write the extended stream ID. */
1134  *q++ = 0x00 | 0x60;
1135  }
1136  /* For Blu-ray AC3 Audio Setting extended flags */
1137  if (ts->m2ts_mode &&
1138  pes_extension &&
1139  st->codec->codec_id == AV_CODEC_ID_AC3) {
1140  flags = 0x01; /* set PES_extension_flag_2 */
1141  *q++ = flags;
1142  *q++ = 0x80 | 0x01; /* marker bit + extension length */
1143  *q++ = 0x00 | 0x71; /* for AC3 Audio (specifically on blue-rays) */
1144  }
1145 
1146 
1147  if (is_dvb_subtitle) {
1148  /* First two fields of DVB subtitles PES data:
1149  * data_identifier: for DVB subtitle streams shall be coded with the value 0x20
1150  * subtitle_stream_id: for DVB subtitle stream shall be identified by the value 0x00 */
1151  *q++ = 0x20;
1152  *q++ = 0x00;
1153  }
1154  if (is_dvb_teletext) {
1155  memset(q, 0xff, pes_header_stuffing_bytes);
1156  q += pes_header_stuffing_bytes;
1157  }
1158  is_start = 0;
1159  }
1160  /* header size */
1161  header_len = q - buf;
1162  /* data len */
1163  len = TS_PACKET_SIZE - header_len;
1164  if (len > payload_size)
1165  len = payload_size;
1166  stuffing_len = TS_PACKET_SIZE - header_len - len;
1167  if (stuffing_len > 0) {
1168  /* add stuffing with AFC */
1169  if (buf[3] & 0x20) {
1170  /* stuffing already present: increase its size */
1171  afc_len = buf[4] + 1;
1172  memmove(buf + 4 + afc_len + stuffing_len,
1173  buf + 4 + afc_len,
1174  header_len - (4 + afc_len));
1175  buf[4] += stuffing_len;
1176  memset(buf + 4 + afc_len, 0xff, stuffing_len);
1177  } else {
1178  /* add stuffing */
1179  memmove(buf + 4 + stuffing_len, buf + 4, header_len - 4);
1180  buf[3] |= 0x20;
1181  buf[4] = stuffing_len - 1;
1182  if (stuffing_len >= 2) {
1183  buf[5] = 0x00;
1184  memset(buf + 6, 0xff, stuffing_len - 2);
1185  }
1186  }
1187  }
1188 
1189  if (is_dvb_subtitle && payload_size == len) {
1190  memcpy(buf + TS_PACKET_SIZE - len, payload, len - 1);
1191  buf[TS_PACKET_SIZE - 1] = 0xff; /* end_of_PES_data_field_marker: an 8-bit field with fixed contents 0xff for DVB subtitle */
1192  } else {
1193  memcpy(buf + TS_PACKET_SIZE - len, payload, len);
1194  }
1195 
1196  payload += len;
1197  payload_size -= len;
1199  avio_write(s->pb, buf, TS_PACKET_SIZE);
1200  }
1201  ts_st->prev_payload_key = key;
1202 }
1203 
1205 {
1206  if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001 && AV_RB24(pkt->data) != 0x000001) {
1207  if (!st->nb_frames) {
1208  av_log(s, AV_LOG_ERROR, "H.264 bitstream malformed, "
1209  "no startcode found, use the video bitstream filter 'h264_mp4toannexb' to fix it "
1210  "('-bsf:v h264_mp4toannexb' option with ffmpeg)\n");
1211  return AVERROR_INVALIDDATA;
1212  }
1213  av_log(s, AV_LOG_WARNING, "H.264 bitstream error, startcode missing, size %d", pkt->size);
1214  if (pkt->size) av_log(s, AV_LOG_WARNING, " data %08X", AV_RB32(pkt->data));
1215  av_log(s, AV_LOG_WARNING, "\n");
1216  }
1217  return 0;
1218 }
1219 
1221 {
1222  if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001) {
1223  if (!st->nb_frames) {
1224  av_log(s, AV_LOG_ERROR, "HEVC bitstream malformed, no startcode found\n");
1225  return AVERROR_PATCHWELCOME;
1226  }
1227  av_log(s, AV_LOG_WARNING, "HEVC bitstream error, startcode missing, size %d", pkt->size);
1228  if (pkt->size) av_log(s, AV_LOG_WARNING, " data %08X", AV_RB32(pkt->data));
1229  av_log(s, AV_LOG_WARNING, "\n");
1230  }
1231  return 0;
1232 }
1233 
1235 {
1236  AVStream *st = s->streams[pkt->stream_index];
1237  int size = pkt->size;
1238  uint8_t *buf = pkt->data;
1239  uint8_t *data = NULL;
1240  MpegTSWrite *ts = s->priv_data;
1241  MpegTSWriteStream *ts_st = st->priv_data;
1242  const int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE) * 2;
1243  int64_t dts = pkt->dts, pts = pkt->pts;
1244 
1245  if (ts->reemit_pat_pmt) {
1247  "resend_headers option is deprecated, use -mpegts_flags resend_headers\n");
1248  ts->reemit_pat_pmt = 0;
1250  }
1251 
1252  if (ts->flags & MPEGTS_FLAG_REEMIT_PAT_PMT) {
1253  ts->pat_packet_count = ts->pat_packet_period - 1;
1254  ts->sdt_packet_count = ts->sdt_packet_period - 1;
1256  }
1257 
1258  if (ts->copyts < 1) {
1259  if (pts != AV_NOPTS_VALUE)
1260  pts += delay;
1261  if (dts != AV_NOPTS_VALUE)
1262  dts += delay;
1263  }
1264 
1265  if (ts_st->first_pts_check && pts == AV_NOPTS_VALUE) {
1266  av_log(s, AV_LOG_ERROR, "first pts value must be set\n");
1267  return AVERROR_INVALIDDATA;
1268  }
1269  ts_st->first_pts_check = 0;
1270 
1271  if (st->codec->codec_id == AV_CODEC_ID_H264) {
1272  const uint8_t *p = buf, *buf_end = p + size;
1273  uint32_t state = -1;
1274  int extradd = (pkt->flags & AV_PKT_FLAG_KEY) ? st->codec->extradata_size : 0;
1275  int ret = ff_check_h264_startcode(s, st, pkt);
1276  if (ret < 0)
1277  return ret;
1278 
1279  if (extradd && AV_RB24(st->codec->extradata) > 1)
1280  extradd = 0;
1281 
1282  do {
1283  p = avpriv_find_start_code(p, buf_end, &state);
1284  av_dlog(s, "nal %d\n", state & 0x1f);
1285  if ((state & 0x1f) == 7)
1286  extradd = 0;
1287  } while (p < buf_end && (state & 0x1f) != 9 &&
1288  (state & 0x1f) != 5 && (state & 0x1f) != 1);
1289 
1290  if ((state & 0x1f) != 5)
1291  extradd = 0;
1292  if ((state & 0x1f) != 9) { // AUD NAL
1293  data = av_malloc(pkt->size + 6 + extradd);
1294  if (!data)
1295  return AVERROR(ENOMEM);
1296  memcpy(data + 6, st->codec->extradata, extradd);
1297  memcpy(data + 6 + extradd, pkt->data, pkt->size);
1298  AV_WB32(data, 0x00000001);
1299  data[4] = 0x09;
1300  data[5] = 0xf0; // any slice type (0xe) + rbsp stop one bit
1301  buf = data;
1302  size = pkt->size + 6 + extradd;
1303  }
1304  } else if (st->codec->codec_id == AV_CODEC_ID_AAC) {
1305  if (pkt->size < 2) {
1306  av_log(s, AV_LOG_ERROR, "AAC packet too short\n");
1307  return AVERROR_INVALIDDATA;
1308  }
1309  if ((AV_RB16(pkt->data) & 0xfff0) != 0xfff0) {
1310  int ret;
1311  AVPacket pkt2;
1312 
1313  if (!ts_st->amux) {
1314  av_log(s, AV_LOG_ERROR, "AAC bitstream not in ADTS format "
1315  "and extradata missing\n");
1316  return AVERROR_INVALIDDATA;
1317  }
1318 
1319  av_init_packet(&pkt2);
1320  pkt2.data = pkt->data;
1321  pkt2.size = pkt->size;
1322  av_assert0(pkt->dts != AV_NOPTS_VALUE);
1323  pkt2.dts = av_rescale_q(pkt->dts, st->time_base, ts_st->amux->streams[0]->time_base);
1324 
1325  ret = avio_open_dyn_buf(&ts_st->amux->pb);
1326  if (ret < 0)
1327  return AVERROR(ENOMEM);
1328 
1329  ret = av_write_frame(ts_st->amux, &pkt2);
1330  if (ret < 0) {
1331  ffio_free_dyn_buf(&ts_st->amux->pb);
1332  return ret;
1333  }
1334  size = avio_close_dyn_buf(ts_st->amux->pb, &data);
1335  ts_st->amux->pb = NULL;
1336  buf = data;
1337  }
1338  } else if (st->codec->codec_id == AV_CODEC_ID_HEVC) {
1339  int ret = check_hevc_startcode(s, st, pkt);
1340  if (ret < 0)
1341  return ret;
1342  }
1343 
1344  if (pkt->dts != AV_NOPTS_VALUE) {
1345  int i;
1346  for(i=0; i<s->nb_streams; i++) {
1347  AVStream *st2 = s->streams[i];
1348  MpegTSWriteStream *ts_st2 = st2->priv_data;
1349  if ( ts_st2->payload_size
1350  && (ts_st2->payload_dts == AV_NOPTS_VALUE || dts - ts_st2->payload_dts > delay/2)) {
1351  mpegts_write_pes(s, st2, ts_st2->payload, ts_st2->payload_size,
1352  ts_st2->payload_pts, ts_st2->payload_dts,
1353  ts_st2->payload_flags & AV_PKT_FLAG_KEY);
1354  ts_st2->payload_size = 0;
1355  }
1356  }
1357  }
1358 
1359  if (ts_st->payload_size && ts_st->payload_size + size > ts->pes_payload_size) {
1360  mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_size,
1361  ts_st->payload_pts, ts_st->payload_dts,
1362  ts_st->payload_flags & AV_PKT_FLAG_KEY);
1363  ts_st->payload_size = 0;
1364  }
1365 
1366  if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO || size > ts->pes_payload_size) {
1367  av_assert0(!ts_st->payload_size);
1368  // for video and subtitle, write a single pes packet
1369  mpegts_write_pes(s, st, buf, size, pts, dts,
1370  pkt->flags & AV_PKT_FLAG_KEY);
1371  av_free(data);
1372  return 0;
1373  }
1374 
1375  if (!ts_st->payload_size) {
1376  ts_st->payload_pts = pts;
1377  ts_st->payload_dts = dts;
1378  ts_st->payload_flags = pkt->flags;
1379  }
1380 
1381  memcpy(ts_st->payload + ts_st->payload_size, buf, size);
1382  ts_st->payload_size += size;
1383 
1384  av_free(data);
1385 
1386  return 0;
1387 }
1388 
1390 {
1391  int i;
1392 
1393  /* flush current packets */
1394  for (i = 0; i < s->nb_streams; i++) {
1395  AVStream *st = s->streams[i];
1396  MpegTSWriteStream *ts_st = st->priv_data;
1397  if (ts_st->payload_size > 0) {
1398  mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_size,
1399  ts_st->payload_pts, ts_st->payload_dts,
1400  ts_st->payload_flags & AV_PKT_FLAG_KEY);
1401  ts_st->payload_size = 0;
1402  }
1403  }
1404 }
1405 
1407 {
1408  if (!pkt) {
1409  mpegts_write_flush(s);
1410  return 1;
1411  } else {
1412  return mpegts_write_packet_internal(s, pkt);
1413  }
1414 }
1415 
1417 {
1418  MpegTSWrite *ts = s->priv_data;
1419  MpegTSService *service;
1420  int i;
1421 
1422  if (s->pb)
1423  mpegts_write_flush(s);
1424 
1425  for (i = 0; i < s->nb_streams; i++) {
1426  AVStream *st = s->streams[i];
1427  MpegTSWriteStream *ts_st = st->priv_data;
1428  av_freep(&ts_st->payload);
1429  if (ts_st->amux) {
1430  avformat_free_context(ts_st->amux);
1431  ts_st->amux = NULL;
1432  }
1433  }
1434 
1435  for (i = 0; i < ts->nb_services; i++) {
1436  service = ts->services[i];
1437  av_freep(&service->provider_name);
1438  av_freep(&service->name);
1439  av_freep(&service);
1440  }
1441  av_freep(&ts->services);
1442 
1443  return 0;
1444 }
1445 
1446 static const AVOption options[] = {
1447  { "mpegts_transport_stream_id", "Set transport_stream_id field.",
1448  offsetof(MpegTSWrite, transport_stream_id), AV_OPT_TYPE_INT,
1449  { .i64 = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM },
1450  { "mpegts_original_network_id", "Set original_network_id field.",
1451  offsetof(MpegTSWrite, original_network_id), AV_OPT_TYPE_INT,
1452  { .i64 = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM },
1453  { "mpegts_service_id", "Set service_id field.",
1454  offsetof(MpegTSWrite, service_id), AV_OPT_TYPE_INT,
1455  { .i64 = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM },
1456  { "mpegts_service_type", "Set service_type field.",
1457  offsetof(MpegTSWrite, service_type), AV_OPT_TYPE_INT,
1458  { .i64 = 0x01 }, 0x01, 0xff, AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1459  { "digital_tv", "Digital Television.",
1460  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_DIGITAL_TV }, 0x01, 0xff,
1461  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1462  { "digital_radio", "Digital Radio.",
1463  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_DIGITAL_RADIO }, 0x01, 0xff,
1464  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1465  { "teletext", "Teletext.",
1466  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_TELETEXT }, 0x01, 0xff,
1467  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1468  { "advanced_codec_digital_radio", "Advanced Codec Digital Radio.",
1470  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1471  { "mpeg2_digital_hdtv", "MPEG2 Digital HDTV.",
1472  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_SERVICE_TYPE_MPEG2_DIGITAL_HDTV }, 0x01, 0xff,
1473  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1474  { "advanced_codec_digital_sdtv", "Advanced Codec Digital SDTV.",
1476  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1477  { "advanced_codec_digital_hdtv", "Advanced Codec Digital HDTV.",
1479  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_service_type" },
1480  { "mpegts_pmt_start_pid", "Set the first pid of the PMT.",
1481  offsetof(MpegTSWrite, pmt_start_pid), AV_OPT_TYPE_INT,
1482  { .i64 = 0x1000 }, 0x0010, 0x1f00, AV_OPT_FLAG_ENCODING_PARAM },
1483  { "mpegts_start_pid", "Set the first pid.",
1484  offsetof(MpegTSWrite, start_pid), AV_OPT_TYPE_INT,
1485  { .i64 = 0x0100 }, 0x0020, 0x0f00, AV_OPT_FLAG_ENCODING_PARAM },
1486  { "mpegts_m2ts_mode", "Enable m2ts mode.",
1487  offsetof(MpegTSWrite, m2ts_mode), AV_OPT_TYPE_INT,
1488  { .i64 = -1 }, -1, 1, AV_OPT_FLAG_ENCODING_PARAM },
1489  { "muxrate", NULL,
1490  offsetof(MpegTSWrite, mux_rate), AV_OPT_TYPE_INT,
1491  { .i64 = 1 }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
1492  { "pes_payload_size", "Minimum PES packet payload in bytes",
1493  offsetof(MpegTSWrite, pes_payload_size), AV_OPT_TYPE_INT,
1494  { .i64 = DEFAULT_PES_PAYLOAD_SIZE }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
1495  { "mpegts_flags", "MPEG-TS muxing flags",
1496  offsetof(MpegTSWrite, flags), AV_OPT_TYPE_FLAGS, { .i64 = 0 }, 0, INT_MAX,
1497  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags" },
1498  { "resend_headers", "Reemit PAT/PMT before writing the next packet",
1499  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_FLAG_REEMIT_PAT_PMT }, 0, INT_MAX,
1500  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags" },
1501  { "latm", "Use LATM packetization for AAC",
1502  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_FLAG_AAC_LATM }, 0, INT_MAX,
1503  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags" },
1504  // backward compatibility
1505  { "resend_headers", "Reemit PAT/PMT before writing the next packet",
1506  offsetof(MpegTSWrite, reemit_pat_pmt), AV_OPT_TYPE_INT,
1507  { .i64 = 0 }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
1508  { "mpegts_copyts", "don't offset dts/pts",
1509  offsetof(MpegTSWrite, copyts), AV_OPT_TYPE_INT,
1510  { .i64 = -1 }, -1, 1, AV_OPT_FLAG_ENCODING_PARAM },
1511  { "tables_version", "set PAT, PMT and SDT version",
1512  offsetof(MpegTSWrite, tables_version), AV_OPT_TYPE_INT,
1513  { .i64 = 0 }, 0, 31, AV_OPT_FLAG_ENCODING_PARAM },
1514  { "omit_video_pes_length", "Omit the PES packet length for video packets",
1515  offsetof(MpegTSWrite, omit_video_pes_length), AV_OPT_TYPE_INT,
1516  { .i64 = 1 }, 0, 1, AV_OPT_FLAG_ENCODING_PARAM },
1517  { "pcr_period", "PCR retransmission time",
1518  offsetof(MpegTSWrite, pcr_period), AV_OPT_TYPE_INT,
1519  { .i64 = PCR_RETRANS_TIME }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
1520  { NULL },
1521 };
1522 
1523 static const AVClass mpegts_muxer_class = {
1524  .class_name = "MPEGTS muxer",
1525  .item_name = av_default_item_name,
1526  .option = options,
1527  .version = LIBAVUTIL_VERSION_INT,
1528 };
1529 
1531  .name = "mpegts",
1532  .long_name = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
1533  .mime_type = "video/MP2T",
1534  .extensions = "ts,m2t,m2ts,mts",
1535  .priv_data_size = sizeof(MpegTSWrite),
1536  .audio_codec = AV_CODEC_ID_MP2,
1537  .video_codec = AV_CODEC_ID_MPEG2VIDEO,
1542  .priv_class = &mpegts_muxer_class,
1543 };