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