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  ast->time_base = st->time_base;
725  ret = avformat_write_header(ts_st->amux, NULL);
726  if (ret < 0)
727  goto fail;
728  }
729  }
730 
731  av_freep(&pids);
732 
733  /* if no video stream, use the first stream as PCR */
734  if (service->pcr_pid == 0x1fff && s->nb_streams > 0) {
735  pcr_st = s->streams[0];
736  ts_st = pcr_st->priv_data;
737  service->pcr_pid = ts_st->pid;
738  } else
739  ts_st = pcr_st->priv_data;
740 
741  if (ts->mux_rate > 1) {
742  service->pcr_packet_period = (ts->mux_rate * ts->pcr_period) /
743  (TS_PACKET_SIZE * 8 * 1000);
745  (TS_PACKET_SIZE * 8 * 1000);
747  (TS_PACKET_SIZE * 8 * 1000);
748 
749  if (ts->copyts < 1)
751  } else {
752  /* Arbitrary values, PAT/PMT will also be written on video key frames */
753  ts->sdt_packet_period = 200;
754  ts->pat_packet_period = 40;
755  if (pcr_st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
756  if (!pcr_st->codec->frame_size) {
757  av_log(s, AV_LOG_WARNING, "frame size not set\n");
758  service->pcr_packet_period =
759  pcr_st->codec->sample_rate / (10 * 512);
760  } else {
761  service->pcr_packet_period =
762  pcr_st->codec->sample_rate / (10 * pcr_st->codec->frame_size);
763  }
764  } else {
765  // max delta PCR 0.1s
766  // TODO: should be avg_frame_rate
767  service->pcr_packet_period =
768  ts_st->user_tb.den / (10 * ts_st->user_tb.num);
769  }
770  if (!service->pcr_packet_period)
771  service->pcr_packet_period = 1;
772  }
773 
774  // output a PCR as soon as possible
775  service->pcr_packet_count = service->pcr_packet_period;
776  ts->pat_packet_count = ts->pat_packet_period - 1;
777  ts->sdt_packet_count = ts->sdt_packet_period - 1;
778 
779  if (ts->mux_rate == 1)
780  av_log(s, AV_LOG_VERBOSE, "muxrate VBR, ");
781  else
782  av_log(s, AV_LOG_VERBOSE, "muxrate %d, ", ts->mux_rate);
784  "pcr every %d pkts, sdt every %d, pat/pmt every %d pkts\n",
785  service->pcr_packet_period,
787 
788  if (ts->m2ts_mode == -1) {
789  if (av_match_ext(s->filename, "m2ts")) {
790  ts->m2ts_mode = 1;
791  } else {
792  ts->m2ts_mode = 0;
793  }
794  }
795 
796  return 0;
797 
798 fail:
799  av_freep(&pids);
800  for (i = 0; i < s->nb_streams; i++) {
801  st = s->streams[i];
802  ts_st = st->priv_data;
803  if (ts_st) {
804  av_freep(&ts_st->payload);
805  if (ts_st->amux) {
806  avformat_free_context(ts_st->amux);
807  ts_st->amux = NULL;
808  }
809  }
810  av_freep(&st->priv_data);
811  }
812 
813  for (i = 0; i < ts->nb_services; i++) {
814  service = ts->services[i];
815  av_freep(&service->provider_name);
816  av_freep(&service->name);
817  av_free(service);
818  }
819  av_free(ts->services);
820  return ret;
821 }
822 
823 /* send SDT, PAT and PMT tables regulary */
824 static void retransmit_si_info(AVFormatContext *s, int force_pat)
825 {
826  MpegTSWrite *ts = s->priv_data;
827  int i;
828 
829  if (++ts->sdt_packet_count == ts->sdt_packet_period) {
830  ts->sdt_packet_count = 0;
831  mpegts_write_sdt(s);
832  }
833  if (++ts->pat_packet_count == ts->pat_packet_period || force_pat) {
834  ts->pat_packet_count = 0;
835  mpegts_write_pat(s);
836  for (i = 0; i < ts->nb_services; i++)
837  mpegts_write_pmt(s, ts->services[i]);
838  }
839 }
840 
841 static int write_pcr_bits(uint8_t *buf, int64_t pcr)
842 {
843  int64_t pcr_low = pcr % 300, pcr_high = pcr / 300;
844 
845  *buf++ = pcr_high >> 25;
846  *buf++ = pcr_high >> 17;
847  *buf++ = pcr_high >> 9;
848  *buf++ = pcr_high >> 1;
849  *buf++ = pcr_high << 7 | pcr_low >> 8 | 0x7e;
850  *buf++ = pcr_low;
851 
852  return 6;
853 }
854 
855 /* Write a single null transport stream packet */
857 {
858  uint8_t *q;
860 
861  q = buf;
862  *q++ = 0x47;
863  *q++ = 0x00 | 0x1f;
864  *q++ = 0xff;
865  *q++ = 0x10;
866  memset(q, 0x0FF, TS_PACKET_SIZE - (q - buf));
868  avio_write(s->pb, buf, TS_PACKET_SIZE);
869 }
870 
871 /* Write a single transport stream packet with a PCR and no payload */
873 {
874  MpegTSWrite *ts = s->priv_data;
875  MpegTSWriteStream *ts_st = st->priv_data;
876  uint8_t *q;
878 
879  q = buf;
880  *q++ = 0x47;
881  *q++ = ts_st->pid >> 8;
882  *q++ = ts_st->pid;
883  *q++ = 0x20 | ts_st->cc; /* Adaptation only */
884  /* Continuity Count field does not increment (see 13818-1 section 2.4.3.3) */
885  *q++ = TS_PACKET_SIZE - 5; /* Adaptation Field Length */
886  *q++ = 0x10; /* Adaptation flags: PCR present */
887 
888  /* PCR coded into 6 bytes */
889  q += write_pcr_bits(q, get_pcr(ts, s->pb));
890 
891  /* stuffing bytes */
892  memset(q, 0xFF, TS_PACKET_SIZE - (q - buf));
894  avio_write(s->pb, buf, TS_PACKET_SIZE);
895 }
896 
897 static void write_pts(uint8_t *q, int fourbits, int64_t pts)
898 {
899  int val;
900 
901  val = fourbits << 4 | (((pts >> 30) & 0x07) << 1) | 1;
902  *q++ = val;
903  val = (((pts >> 15) & 0x7fff) << 1) | 1;
904  *q++ = val >> 8;
905  *q++ = val;
906  val = (((pts) & 0x7fff) << 1) | 1;
907  *q++ = val >> 8;
908  *q++ = val;
909 }
910 
911 /* Set an adaptation field flag in an MPEG-TS packet*/
912 static void set_af_flag(uint8_t *pkt, int flag)
913 {
914  // expect at least one flag to set
915  av_assert0(flag);
916 
917  if ((pkt[3] & 0x20) == 0) {
918  // no AF yet, set adaptation field flag
919  pkt[3] |= 0x20;
920  // 1 byte length, no flags
921  pkt[4] = 1;
922  pkt[5] = 0;
923  }
924  pkt[5] |= flag;
925 }
926 
927 /* Extend the adaptation field by size bytes */
928 static void extend_af(uint8_t *pkt, int size)
929 {
930  // expect already existing adaptation field
931  av_assert0(pkt[3] & 0x20);
932  pkt[4] += size;
933 }
934 
935 /* Get a pointer to MPEG-TS payload (right after TS packet header) */
937 {
938  if (pkt[3] & 0x20)
939  return pkt + 5 + pkt[4];
940  else
941  return pkt + 4;
942 }
943 
944 /* Add a PES header to the front of the payload, and segment into an integer
945  * number of TS packets. The final TS packet is padded using an oversized
946  * adaptation header to exactly fill the last TS packet.
947  * NOTE: 'payload' contains a complete PES payload. */
949  const uint8_t *payload, int payload_size,
950  int64_t pts, int64_t dts, int key)
951 {
952  MpegTSWriteStream *ts_st = st->priv_data;
953  MpegTSWrite *ts = s->priv_data;
955  uint8_t *q;
956  int val, is_start, len, header_len, write_pcr, is_dvb_subtitle, is_dvb_teletext, flags;
957  int afc_len, stuffing_len;
958  int64_t pcr = -1; /* avoid warning */
959  int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE);
960  int force_pat = st->codec->codec_type == AVMEDIA_TYPE_VIDEO && key && !ts_st->prev_payload_key;
961 
962  is_start = 1;
963  while (payload_size > 0) {
964  retransmit_si_info(s, force_pat);
965  force_pat = 0;
966 
967  write_pcr = 0;
968  if (ts_st->pid == ts_st->service->pcr_pid) {
969  if (ts->mux_rate > 1 || is_start) // VBR pcr period is based on frames
970  ts_st->service->pcr_packet_count++;
971  if (ts_st->service->pcr_packet_count >=
972  ts_st->service->pcr_packet_period) {
973  ts_st->service->pcr_packet_count = 0;
974  write_pcr = 1;
975  }
976  }
977 
978  if (ts->mux_rate > 1 && dts != AV_NOPTS_VALUE &&
979  (dts - get_pcr(ts, s->pb) / 300) > delay) {
980  /* pcr insert gets priority over null packet insert */
981  if (write_pcr)
982  mpegts_insert_pcr_only(s, st);
983  else
985  /* recalculate write_pcr and possibly retransmit si_info */
986  continue;
987  }
988 
989  /* prepare packet header */
990  q = buf;
991  *q++ = 0x47;
992  val = ts_st->pid >> 8;
993  if (is_start)
994  val |= 0x40;
995  *q++ = val;
996  *q++ = ts_st->pid;
997  ts_st->cc = ts_st->cc + 1 & 0xf;
998  *q++ = 0x10 | ts_st->cc; // payload indicator + CC
999  if (key && is_start && pts != AV_NOPTS_VALUE) {
1000  // set Random Access for key frames
1001  if (ts_st->pid == ts_st->service->pcr_pid)
1002  write_pcr = 1;
1003  set_af_flag(buf, 0x40);
1004  q = get_ts_payload_start(buf);
1005  }
1006  if (write_pcr) {
1007  set_af_flag(buf, 0x10);
1008  q = get_ts_payload_start(buf);
1009  // add 11, pcr references the last byte of program clock reference base
1010  if (ts->mux_rate > 1)
1011  pcr = get_pcr(ts, s->pb);
1012  else
1013  pcr = (dts - delay) * 300;
1014  if (dts != AV_NOPTS_VALUE && dts < pcr / 300)
1015  av_log(s, AV_LOG_WARNING, "dts < pcr, TS is invalid\n");
1016  extend_af(buf, write_pcr_bits(q, pcr));
1017  q = get_ts_payload_start(buf);
1018  }
1019  if (is_start) {
1020  int pes_extension = 0;
1021  int pes_header_stuffing_bytes = 0;
1022  /* write PES header */
1023  *q++ = 0x00;
1024  *q++ = 0x00;
1025  *q++ = 0x01;
1026  is_dvb_subtitle = 0;
1027  is_dvb_teletext = 0;
1028  if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1029  if (st->codec->codec_id == AV_CODEC_ID_DIRAC)
1030  *q++ = 0xfd;
1031  else
1032  *q++ = 0xe0;
1033  } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1034  (st->codec->codec_id == AV_CODEC_ID_MP2 ||
1035  st->codec->codec_id == AV_CODEC_ID_MP3 ||
1036  st->codec->codec_id == AV_CODEC_ID_AAC)) {
1037  *q++ = 0xc0;
1038  } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1039  st->codec->codec_id == AV_CODEC_ID_AC3 &&
1040  ts->m2ts_mode) {
1041  *q++ = 0xfd;
1042  } else {
1043  *q++ = 0xbd;
1044  if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1045  if (st->codec->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
1046  is_dvb_subtitle = 1;
1047  } else if (st->codec->codec_id == AV_CODEC_ID_DVB_TELETEXT) {
1048  is_dvb_teletext = 1;
1049  }
1050  }
1051  }
1052  header_len = 0;
1053  flags = 0;
1054  if (pts != AV_NOPTS_VALUE) {
1055  header_len += 5;
1056  flags |= 0x80;
1057  }
1058  if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
1059  header_len += 5;
1060  flags |= 0x40;
1061  }
1062  if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
1063  st->codec->codec_id == AV_CODEC_ID_DIRAC) {
1064  /* set PES_extension_flag */
1065  pes_extension = 1;
1066  flags |= 0x01;
1067 
1068  /* One byte for PES2 extension flag +
1069  * one byte for extension length +
1070  * one byte for extension id */
1071  header_len += 3;
1072  }
1073  /* for Blu-ray AC3 Audio the PES Extension flag should be as follow
1074  * otherwise it will not play sound on blu-ray
1075  */
1076  if (ts->m2ts_mode &&
1078  st->codec->codec_id == AV_CODEC_ID_AC3) {
1079  /* set PES_extension_flag */
1080  pes_extension = 1;
1081  flags |= 0x01;
1082  header_len += 3;
1083  }
1084  if (is_dvb_teletext) {
1085  pes_header_stuffing_bytes = 0x24 - header_len;
1086  header_len = 0x24;
1087  }
1088  len = payload_size + header_len + 3;
1089  /* 3 extra bytes should be added to DVB subtitle payload: 0x20 0x00 at the beginning and trailing 0xff */
1090  if (is_dvb_subtitle) {
1091  len += 3;
1092  payload_size++;
1093  }
1094  if (len > 0xffff)
1095  len = 0;
1097  len = 0;
1098  }
1099  *q++ = len >> 8;
1100  *q++ = len;
1101  val = 0x80;
1102  /* data alignment indicator is required for subtitle and data streams */
1104  val |= 0x04;
1105  *q++ = val;
1106  *q++ = flags;
1107  *q++ = header_len;
1108  if (pts != AV_NOPTS_VALUE) {
1109  write_pts(q, flags >> 6, pts);
1110  q += 5;
1111  }
1112  if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
1113  write_pts(q, 1, dts);
1114  q += 5;
1115  }
1116  if (pes_extension && st->codec->codec_id == AV_CODEC_ID_DIRAC) {
1117  flags = 0x01; /* set PES_extension_flag_2 */
1118  *q++ = flags;
1119  *q++ = 0x80 | 0x01; /* marker bit + extension length */
1120  /* Set the stream ID extension flag bit to 0 and
1121  * write the extended stream ID. */
1122  *q++ = 0x00 | 0x60;
1123  }
1124  /* For Blu-ray AC3 Audio Setting extended flags */
1125  if (ts->m2ts_mode &&
1126  pes_extension &&
1127  st->codec->codec_id == AV_CODEC_ID_AC3) {
1128  flags = 0x01; /* set PES_extension_flag_2 */
1129  *q++ = flags;
1130  *q++ = 0x80 | 0x01; /* marker bit + extension length */
1131  *q++ = 0x00 | 0x71; /* for AC3 Audio (specifically on blue-rays) */
1132  }
1133 
1134 
1135  if (is_dvb_subtitle) {
1136  /* First two fields of DVB subtitles PES data:
1137  * data_identifier: for DVB subtitle streams shall be coded with the value 0x20
1138  * subtitle_stream_id: for DVB subtitle stream shall be identified by the value 0x00 */
1139  *q++ = 0x20;
1140  *q++ = 0x00;
1141  }
1142  if (is_dvb_teletext) {
1143  memset(q, 0xff, pes_header_stuffing_bytes);
1144  q += pes_header_stuffing_bytes;
1145  }
1146  is_start = 0;
1147  }
1148  /* header size */
1149  header_len = q - buf;
1150  /* data len */
1151  len = TS_PACKET_SIZE - header_len;
1152  if (len > payload_size)
1153  len = payload_size;
1154  stuffing_len = TS_PACKET_SIZE - header_len - len;
1155  if (stuffing_len > 0) {
1156  /* add stuffing with AFC */
1157  if (buf[3] & 0x20) {
1158  /* stuffing already present: increase its size */
1159  afc_len = buf[4] + 1;
1160  memmove(buf + 4 + afc_len + stuffing_len,
1161  buf + 4 + afc_len,
1162  header_len - (4 + afc_len));
1163  buf[4] += stuffing_len;
1164  memset(buf + 4 + afc_len, 0xff, stuffing_len);
1165  } else {
1166  /* add stuffing */
1167  memmove(buf + 4 + stuffing_len, buf + 4, header_len - 4);
1168  buf[3] |= 0x20;
1169  buf[4] = stuffing_len - 1;
1170  if (stuffing_len >= 2) {
1171  buf[5] = 0x00;
1172  memset(buf + 6, 0xff, stuffing_len - 2);
1173  }
1174  }
1175  }
1176 
1177  if (is_dvb_subtitle && payload_size == len) {
1178  memcpy(buf + TS_PACKET_SIZE - len, payload, len - 1);
1179  buf[TS_PACKET_SIZE - 1] = 0xff; /* end_of_PES_data_field_marker: an 8-bit field with fixed contents 0xff for DVB subtitle */
1180  } else {
1181  memcpy(buf + TS_PACKET_SIZE - len, payload, len);
1182  }
1183 
1184  payload += len;
1185  payload_size -= len;
1187  avio_write(s->pb, buf, TS_PACKET_SIZE);
1188  }
1189  ts_st->prev_payload_key = key;
1190 }
1191 
1193 {
1194  if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001) {
1195  if (!st->nb_frames) {
1196  av_log(s, AV_LOG_ERROR, "H.264 bitstream malformed, "
1197  "no startcode found, use the video bitstream filter 'h264_mp4toannexb' to fix it "
1198  "('-bsf:v h264_mp4toannexb' option with ffmpeg)\n");
1199  return AVERROR_INVALIDDATA;
1200  }
1201  av_log(s, AV_LOG_WARNING, "H.264 bitstream error, startcode missing, size %d", pkt->size);
1202  if (pkt->size) av_log(s, AV_LOG_WARNING, " data %08X", AV_RB32(pkt->data));
1203  av_log(s, AV_LOG_WARNING, "\n");
1204  }
1205  return 0;
1206 }
1207 
1209 {
1210  if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001) {
1211  if (!st->nb_frames) {
1212  av_log(s, AV_LOG_ERROR, "HEVC bitstream malformed, no startcode found\n");
1213  return AVERROR_PATCHWELCOME;
1214  }
1215  av_log(s, AV_LOG_WARNING, "HEVC bitstream error, startcode missing, size %d", pkt->size);
1216  if (pkt->size) av_log(s, AV_LOG_WARNING, " data %08X", AV_RB32(pkt->data));
1217  av_log(s, AV_LOG_WARNING, "\n");
1218  }
1219  return 0;
1220 }
1221 
1223 {
1224  AVStream *st = s->streams[pkt->stream_index];
1225  int size = pkt->size;
1226  uint8_t *buf = pkt->data;
1227  uint8_t *data = NULL;
1228  MpegTSWrite *ts = s->priv_data;
1229  MpegTSWriteStream *ts_st = st->priv_data;
1230  const int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE) * 2;
1231  int64_t dts = pkt->dts, pts = pkt->pts;
1232 
1233  if (ts->reemit_pat_pmt) {
1235  "resend_headers option is deprecated, use -mpegts_flags resend_headers\n");
1236  ts->reemit_pat_pmt = 0;
1238  }
1239 
1240  if (ts->flags & MPEGTS_FLAG_REEMIT_PAT_PMT) {
1241  ts->pat_packet_count = ts->pat_packet_period - 1;
1242  ts->sdt_packet_count = ts->sdt_packet_period - 1;
1244  }
1245 
1246  if (ts->copyts < 1) {
1247  if (pts != AV_NOPTS_VALUE)
1248  pts += delay;
1249  if (dts != AV_NOPTS_VALUE)
1250  dts += delay;
1251  }
1252 
1253  if (ts_st->first_pts_check && pts == AV_NOPTS_VALUE) {
1254  av_log(s, AV_LOG_ERROR, "first pts value must be set\n");
1255  return AVERROR_INVALIDDATA;
1256  }
1257  ts_st->first_pts_check = 0;
1258 
1259  if (st->codec->codec_id == AV_CODEC_ID_H264) {
1260  const uint8_t *p = buf, *buf_end = p + size;
1261  uint32_t state = -1;
1262  int ret = ff_check_h264_startcode(s, st, pkt);
1263  if (ret < 0)
1264  return ret;
1265 
1266  do {
1267  p = avpriv_find_start_code(p, buf_end, &state);
1268  av_dlog(s, "nal %d\n", state & 0x1f);
1269  } while (p < buf_end && (state & 0x1f) != 9 &&
1270  (state & 0x1f) != 5 && (state & 0x1f) != 1);
1271 
1272  if ((state & 0x1f) != 9) { // AUD NAL
1273  data = av_malloc(pkt->size + 6);
1274  if (!data)
1275  return AVERROR(ENOMEM);
1276  memcpy(data + 6, pkt->data, pkt->size);
1277  AV_WB32(data, 0x00000001);
1278  data[4] = 0x09;
1279  data[5] = 0xf0; // any slice type (0xe) + rbsp stop one bit
1280  buf = data;
1281  size = pkt->size + 6;
1282  }
1283  } else if (st->codec->codec_id == AV_CODEC_ID_AAC) {
1284  if (pkt->size < 2) {
1285  av_log(s, AV_LOG_ERROR, "AAC packet too short\n");
1286  return AVERROR_INVALIDDATA;
1287  }
1288  if ((AV_RB16(pkt->data) & 0xfff0) != 0xfff0) {
1289  int ret;
1290  AVPacket pkt2;
1291 
1292  if (!ts_st->amux) {
1293  av_log(s, AV_LOG_ERROR, "AAC bitstream not in ADTS format "
1294  "and extradata missing\n");
1295  return AVERROR_INVALIDDATA;
1296  }
1297 
1298  av_init_packet(&pkt2);
1299  pkt2.data = pkt->data;
1300  pkt2.size = pkt->size;
1301  av_assert0(pkt->dts != AV_NOPTS_VALUE);
1302  pkt2.dts = av_rescale_q(pkt->dts, st->time_base, ts_st->amux->streams[0]->time_base);
1303 
1304  ret = avio_open_dyn_buf(&ts_st->amux->pb);
1305  if (ret < 0)
1306  return AVERROR(ENOMEM);
1307 
1308  ret = av_write_frame(ts_st->amux, &pkt2);
1309  if (ret < 0) {
1310  avio_close_dyn_buf(ts_st->amux->pb, &data);
1311  ts_st->amux->pb = NULL;
1312  av_free(data);
1313  return ret;
1314  }
1315  size = avio_close_dyn_buf(ts_st->amux->pb, &data);
1316  ts_st->amux->pb = NULL;
1317  buf = data;
1318  }
1319  } else if (st->codec->codec_id == AV_CODEC_ID_HEVC) {
1320  int ret = check_hevc_startcode(s, st, pkt);
1321  if (ret < 0)
1322  return ret;
1323  }
1324 
1325  if (pkt->dts != AV_NOPTS_VALUE) {
1326  int i;
1327  for(i=0; i<s->nb_streams; i++) {
1328  AVStream *st2 = s->streams[i];
1329  MpegTSWriteStream *ts_st2 = st2->priv_data;
1330  if ( ts_st2->payload_size
1331  && (ts_st2->payload_dts == AV_NOPTS_VALUE || dts - ts_st2->payload_dts > delay/2)) {
1332  mpegts_write_pes(s, st2, ts_st2->payload, ts_st2->payload_size,
1333  ts_st2->payload_pts, ts_st2->payload_dts,
1334  ts_st2->payload_flags & AV_PKT_FLAG_KEY);
1335  ts_st2->payload_size = 0;
1336  }
1337  }
1338  }
1339 
1340  if (ts_st->payload_size && ts_st->payload_size + size > ts->pes_payload_size) {
1341  mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_size,
1342  ts_st->payload_pts, ts_st->payload_dts,
1343  ts_st->payload_flags & AV_PKT_FLAG_KEY);
1344  ts_st->payload_size = 0;
1345  }
1346 
1347  if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO || size > ts->pes_payload_size) {
1348  av_assert0(!ts_st->payload_size);
1349  // for video and subtitle, write a single pes packet
1350  mpegts_write_pes(s, st, buf, size, pts, dts,
1351  pkt->flags & AV_PKT_FLAG_KEY);
1352  av_free(data);
1353  return 0;
1354  }
1355 
1356  if (!ts_st->payload_size) {
1357  ts_st->payload_pts = pts;
1358  ts_st->payload_dts = dts;
1359  ts_st->payload_flags = pkt->flags;
1360  }
1361 
1362  memcpy(ts_st->payload + ts_st->payload_size, buf, size);
1363  ts_st->payload_size += size;
1364 
1365  av_free(data);
1366 
1367  return 0;
1368 }
1369 
1371 {
1372  int i;
1373 
1374  /* flush current packets */
1375  for (i = 0; i < s->nb_streams; i++) {
1376  AVStream *st = s->streams[i];
1377  MpegTSWriteStream *ts_st = st->priv_data;
1378  if (ts_st->payload_size > 0) {
1379  mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_size,
1380  ts_st->payload_pts, ts_st->payload_dts,
1381  ts_st->payload_flags & AV_PKT_FLAG_KEY);
1382  ts_st->payload_size = 0;
1383  }
1384  }
1385 }
1386 
1388 {
1389  if (!pkt) {
1390  mpegts_write_flush(s);
1391  return 1;
1392  } else {
1393  return mpegts_write_packet_internal(s, pkt);
1394  }
1395 }
1396 
1398 {
1399  MpegTSWrite *ts = s->priv_data;
1400  MpegTSService *service;
1401  int i;
1402 
1403  mpegts_write_flush(s);
1404 
1405  for (i = 0; i < s->nb_streams; i++) {
1406  AVStream *st = s->streams[i];
1407  MpegTSWriteStream *ts_st = st->priv_data;
1408  av_freep(&ts_st->payload);
1409  if (ts_st->amux) {
1410  avformat_free_context(ts_st->amux);
1411  ts_st->amux = NULL;
1412  }
1413  }
1414 
1415  for (i = 0; i < ts->nb_services; i++) {
1416  service = ts->services[i];
1417  av_freep(&service->provider_name);
1418  av_freep(&service->name);
1419  av_free(service);
1420  }
1421  av_free(ts->services);
1422 
1423  return 0;
1424 }
1425 
1426 static const AVOption options[] = {
1427  { "mpegts_transport_stream_id", "Set transport_stream_id field.",
1428  offsetof(MpegTSWrite, transport_stream_id), AV_OPT_TYPE_INT,
1429  { .i64 = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM },
1430  { "mpegts_original_network_id", "Set original_network_id field.",
1431  offsetof(MpegTSWrite, original_network_id), AV_OPT_TYPE_INT,
1432  { .i64 = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM },
1433  { "mpegts_service_id", "Set service_id field.",
1434  offsetof(MpegTSWrite, service_id), AV_OPT_TYPE_INT,
1435  { .i64 = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM },
1436  { "mpegts_pmt_start_pid", "Set the first pid of the PMT.",
1437  offsetof(MpegTSWrite, pmt_start_pid), AV_OPT_TYPE_INT,
1438  { .i64 = 0x1000 }, 0x0010, 0x1f00, AV_OPT_FLAG_ENCODING_PARAM },
1439  { "mpegts_start_pid", "Set the first pid.",
1440  offsetof(MpegTSWrite, start_pid), AV_OPT_TYPE_INT,
1441  { .i64 = 0x0100 }, 0x0020, 0x0f00, AV_OPT_FLAG_ENCODING_PARAM },
1442  { "mpegts_m2ts_mode", "Enable m2ts mode.",
1443  offsetof(MpegTSWrite, m2ts_mode), AV_OPT_TYPE_INT,
1444  { .i64 = -1 }, -1, 1, AV_OPT_FLAG_ENCODING_PARAM },
1445  { "muxrate", NULL,
1446  offsetof(MpegTSWrite, mux_rate), AV_OPT_TYPE_INT,
1447  { .i64 = 1 }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
1448  { "pes_payload_size", "Minimum PES packet payload in bytes",
1449  offsetof(MpegTSWrite, pes_payload_size), AV_OPT_TYPE_INT,
1450  { .i64 = DEFAULT_PES_PAYLOAD_SIZE }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
1451  { "mpegts_flags", "MPEG-TS muxing flags",
1452  offsetof(MpegTSWrite, flags), AV_OPT_TYPE_FLAGS, { .i64 = 0 }, 0, INT_MAX,
1453  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags" },
1454  { "resend_headers", "Reemit PAT/PMT before writing the next packet",
1455  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_FLAG_REEMIT_PAT_PMT }, 0, INT_MAX,
1456  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags" },
1457  { "latm", "Use LATM packetization for AAC",
1458  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_FLAG_AAC_LATM }, 0, INT_MAX,
1459  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags" },
1460  // backward compatibility
1461  { "resend_headers", "Reemit PAT/PMT before writing the next packet",
1462  offsetof(MpegTSWrite, reemit_pat_pmt), AV_OPT_TYPE_INT,
1463  { .i64 = 0 }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
1464  { "mpegts_copyts", "don't offset dts/pts",
1465  offsetof(MpegTSWrite, copyts), AV_OPT_TYPE_INT,
1466  { .i64 = -1 }, -1, 1, AV_OPT_FLAG_ENCODING_PARAM },
1467  { "tables_version", "set PAT, PMT and SDT version",
1468  offsetof(MpegTSWrite, tables_version), AV_OPT_TYPE_INT,
1469  { .i64 = 0 }, 0, 31, AV_OPT_FLAG_ENCODING_PARAM },
1470  { "omit_video_pes_length", "Omit the PES packet length for video packets",
1471  offsetof(MpegTSWrite, omit_video_pes_length), AV_OPT_TYPE_INT,
1472  { .i64 = 1 }, 0, 1, AV_OPT_FLAG_ENCODING_PARAM },
1473  { "pcr_period", "PCR retransmission time",
1474  offsetof(MpegTSWrite, pcr_period), AV_OPT_TYPE_INT,
1475  { .i64 = PCR_RETRANS_TIME }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
1476  { NULL },
1477 };
1478 
1479 static const AVClass mpegts_muxer_class = {
1480  .class_name = "MPEGTS muxer",
1481  .item_name = av_default_item_name,
1482  .option = options,
1483  .version = LIBAVUTIL_VERSION_INT,
1484 };
1485 
1487  .name = "mpegts",
1488  .long_name = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
1489  .mime_type = "video/MP2T",
1490  .extensions = "ts,m2t,m2ts,mts",
1491  .priv_data_size = sizeof(MpegTSWrite),
1492  .audio_codec = AV_CODEC_ID_MP2,
1493  .video_codec = AV_CODEC_ID_MPEG2VIDEO,
1498  .priv_class = &mpegts_muxer_class,
1499 };