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\n");
1201  }
1202  return 0;
1203 }
1204 
1206 {
1207  if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001) {
1208  if (!st->nb_frames) {
1209  av_log(s, AV_LOG_ERROR, "HEVC bitstream malformed, no startcode found\n");
1210  return AVERROR_PATCHWELCOME;
1211  }
1212  av_log(s, AV_LOG_WARNING, "HEVC bitstream error, startcode missing\n");
1213  }
1214  return 0;
1215 }
1216 
1218 {
1219  AVStream *st = s->streams[pkt->stream_index];
1220  int size = pkt->size;
1221  uint8_t *buf = pkt->data;
1222  uint8_t *data = NULL;
1223  MpegTSWrite *ts = s->priv_data;
1224  MpegTSWriteStream *ts_st = st->priv_data;
1225  const int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE) * 2;
1226  int64_t dts = pkt->dts, pts = pkt->pts;
1227 
1228  if (ts->reemit_pat_pmt) {
1230  "resend_headers option is deprecated, use -mpegts_flags resend_headers\n");
1231  ts->reemit_pat_pmt = 0;
1233  }
1234 
1235  if (ts->flags & MPEGTS_FLAG_REEMIT_PAT_PMT) {
1236  ts->pat_packet_count = ts->pat_packet_period - 1;
1237  ts->sdt_packet_count = ts->sdt_packet_period - 1;
1239  }
1240 
1241  if (ts->copyts < 1) {
1242  if (pts != AV_NOPTS_VALUE)
1243  pts += delay;
1244  if (dts != AV_NOPTS_VALUE)
1245  dts += delay;
1246  }
1247 
1248  if (ts_st->first_pts_check && pts == AV_NOPTS_VALUE) {
1249  av_log(s, AV_LOG_ERROR, "first pts value must be set\n");
1250  return AVERROR_INVALIDDATA;
1251  }
1252  ts_st->first_pts_check = 0;
1253 
1254  if (st->codec->codec_id == AV_CODEC_ID_H264) {
1255  const uint8_t *p = buf, *buf_end = p + size;
1256  uint32_t state = -1;
1257  int ret = ff_check_h264_startcode(s, st, pkt);
1258  if (ret < 0)
1259  return ret;
1260 
1261  do {
1262  p = avpriv_find_start_code(p, buf_end, &state);
1263  av_dlog(s, "nal %d\n", state & 0x1f);
1264  } while (p < buf_end && (state & 0x1f) != 9 &&
1265  (state & 0x1f) != 5 && (state & 0x1f) != 1);
1266 
1267  if ((state & 0x1f) != 9) { // AUD NAL
1268  data = av_malloc(pkt->size + 6);
1269  if (!data)
1270  return AVERROR(ENOMEM);
1271  memcpy(data + 6, pkt->data, pkt->size);
1272  AV_WB32(data, 0x00000001);
1273  data[4] = 0x09;
1274  data[5] = 0xf0; // any slice type (0xe) + rbsp stop one bit
1275  buf = data;
1276  size = pkt->size + 6;
1277  }
1278  } else if (st->codec->codec_id == AV_CODEC_ID_AAC) {
1279  if (pkt->size < 2) {
1280  av_log(s, AV_LOG_ERROR, "AAC packet too short\n");
1281  return AVERROR_INVALIDDATA;
1282  }
1283  if ((AV_RB16(pkt->data) & 0xfff0) != 0xfff0) {
1284  int ret;
1285  AVPacket pkt2;
1286 
1287  if (!ts_st->amux) {
1288  av_log(s, AV_LOG_ERROR, "AAC bitstream not in ADTS format "
1289  "and extradata missing\n");
1290  return AVERROR_INVALIDDATA;
1291  }
1292 
1293  av_init_packet(&pkt2);
1294  pkt2.data = pkt->data;
1295  pkt2.size = pkt->size;
1296  av_assert0(pkt->dts != AV_NOPTS_VALUE);
1297  pkt2.dts = av_rescale_q(pkt->dts, st->time_base, ts_st->amux->streams[0]->time_base);
1298 
1299  ret = avio_open_dyn_buf(&ts_st->amux->pb);
1300  if (ret < 0)
1301  return AVERROR(ENOMEM);
1302 
1303  ret = av_write_frame(ts_st->amux, &pkt2);
1304  if (ret < 0) {
1305  avio_close_dyn_buf(ts_st->amux->pb, &data);
1306  ts_st->amux->pb = NULL;
1307  av_free(data);
1308  return ret;
1309  }
1310  size = avio_close_dyn_buf(ts_st->amux->pb, &data);
1311  ts_st->amux->pb = NULL;
1312  buf = data;
1313  }
1314  } else if (st->codec->codec_id == AV_CODEC_ID_HEVC) {
1315  int ret = check_hevc_startcode(s, st, pkt);
1316  if (ret < 0)
1317  return ret;
1318  }
1319 
1320  if (pkt->dts != AV_NOPTS_VALUE) {
1321  int i;
1322  for(i=0; i<s->nb_streams; i++) {
1323  AVStream *st2 = s->streams[i];
1324  MpegTSWriteStream *ts_st2 = st2->priv_data;
1325  if ( ts_st2->payload_size
1326  && (ts_st2->payload_dts == AV_NOPTS_VALUE || dts - ts_st2->payload_dts > delay/2)) {
1327  mpegts_write_pes(s, st2, ts_st2->payload, ts_st2->payload_size,
1328  ts_st2->payload_pts, ts_st2->payload_dts,
1329  ts_st2->payload_flags & AV_PKT_FLAG_KEY);
1330  ts_st2->payload_size = 0;
1331  }
1332  }
1333  }
1334 
1335  if (ts_st->payload_size && ts_st->payload_size + size > ts->pes_payload_size) {
1336  mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_size,
1337  ts_st->payload_pts, ts_st->payload_dts,
1338  ts_st->payload_flags & AV_PKT_FLAG_KEY);
1339  ts_st->payload_size = 0;
1340  }
1341 
1342  if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO || size > ts->pes_payload_size) {
1343  av_assert0(!ts_st->payload_size);
1344  // for video and subtitle, write a single pes packet
1345  mpegts_write_pes(s, st, buf, size, pts, dts,
1346  pkt->flags & AV_PKT_FLAG_KEY);
1347  av_free(data);
1348  return 0;
1349  }
1350 
1351  if (!ts_st->payload_size) {
1352  ts_st->payload_pts = pts;
1353  ts_st->payload_dts = dts;
1354  ts_st->payload_flags = pkt->flags;
1355  }
1356 
1357  memcpy(ts_st->payload + ts_st->payload_size, buf, size);
1358  ts_st->payload_size += size;
1359 
1360  av_free(data);
1361 
1362  return 0;
1363 }
1364 
1366 {
1367  int i;
1368 
1369  /* flush current packets */
1370  for (i = 0; i < s->nb_streams; i++) {
1371  AVStream *st = s->streams[i];
1372  MpegTSWriteStream *ts_st = st->priv_data;
1373  if (ts_st->payload_size > 0) {
1374  mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_size,
1375  ts_st->payload_pts, ts_st->payload_dts,
1376  ts_st->payload_flags & AV_PKT_FLAG_KEY);
1377  ts_st->payload_size = 0;
1378  }
1379  }
1380 }
1381 
1383 {
1384  if (!pkt) {
1385  mpegts_write_flush(s);
1386  return 1;
1387  } else {
1388  return mpegts_write_packet_internal(s, pkt);
1389  }
1390 }
1391 
1393 {
1394  MpegTSWrite *ts = s->priv_data;
1395  MpegTSService *service;
1396  int i;
1397 
1398  mpegts_write_flush(s);
1399 
1400  for (i = 0; i < s->nb_streams; i++) {
1401  AVStream *st = s->streams[i];
1402  MpegTSWriteStream *ts_st = st->priv_data;
1403  av_freep(&ts_st->payload);
1404  if (ts_st->amux) {
1405  avformat_free_context(ts_st->amux);
1406  ts_st->amux = NULL;
1407  }
1408  }
1409 
1410  for (i = 0; i < ts->nb_services; i++) {
1411  service = ts->services[i];
1412  av_freep(&service->provider_name);
1413  av_freep(&service->name);
1414  av_free(service);
1415  }
1416  av_free(ts->services);
1417 
1418  return 0;
1419 }
1420 
1421 static const AVOption options[] = {
1422  { "mpegts_transport_stream_id", "Set transport_stream_id field.",
1423  offsetof(MpegTSWrite, transport_stream_id), AV_OPT_TYPE_INT,
1424  { .i64 = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM },
1425  { "mpegts_original_network_id", "Set original_network_id field.",
1426  offsetof(MpegTSWrite, original_network_id), AV_OPT_TYPE_INT,
1427  { .i64 = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM },
1428  { "mpegts_service_id", "Set service_id field.",
1429  offsetof(MpegTSWrite, service_id), AV_OPT_TYPE_INT,
1430  { .i64 = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM },
1431  { "mpegts_pmt_start_pid", "Set the first pid of the PMT.",
1432  offsetof(MpegTSWrite, pmt_start_pid), AV_OPT_TYPE_INT,
1433  { .i64 = 0x1000 }, 0x0010, 0x1f00, AV_OPT_FLAG_ENCODING_PARAM },
1434  { "mpegts_start_pid", "Set the first pid.",
1435  offsetof(MpegTSWrite, start_pid), AV_OPT_TYPE_INT,
1436  { .i64 = 0x0100 }, 0x0100, 0x0f00, AV_OPT_FLAG_ENCODING_PARAM },
1437  { "mpegts_m2ts_mode", "Enable m2ts mode.",
1438  offsetof(MpegTSWrite, m2ts_mode), AV_OPT_TYPE_INT,
1439  { .i64 = -1 }, -1, 1, AV_OPT_FLAG_ENCODING_PARAM },
1440  { "muxrate", NULL,
1441  offsetof(MpegTSWrite, mux_rate), AV_OPT_TYPE_INT,
1442  { .i64 = 1 }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
1443  { "pes_payload_size", "Minimum PES packet payload in bytes",
1444  offsetof(MpegTSWrite, pes_payload_size), AV_OPT_TYPE_INT,
1445  { .i64 = DEFAULT_PES_PAYLOAD_SIZE }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
1446  { "mpegts_flags", "MPEG-TS muxing flags",
1447  offsetof(MpegTSWrite, flags), AV_OPT_TYPE_FLAGS, { .i64 = 0 }, 0, INT_MAX,
1448  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags" },
1449  { "resend_headers", "Reemit PAT/PMT before writing the next packet",
1450  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_FLAG_REEMIT_PAT_PMT }, 0, INT_MAX,
1451  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags" },
1452  { "latm", "Use LATM packetization for AAC",
1453  0, AV_OPT_TYPE_CONST, { .i64 = MPEGTS_FLAG_AAC_LATM }, 0, INT_MAX,
1454  AV_OPT_FLAG_ENCODING_PARAM, "mpegts_flags" },
1455  // backward compatibility
1456  { "resend_headers", "Reemit PAT/PMT before writing the next packet",
1457  offsetof(MpegTSWrite, reemit_pat_pmt), AV_OPT_TYPE_INT,
1458  { .i64 = 0 }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
1459  { "mpegts_copyts", "don't offset dts/pts",
1460  offsetof(MpegTSWrite, copyts), AV_OPT_TYPE_INT,
1461  { .i64 = -1 }, -1, 1, AV_OPT_FLAG_ENCODING_PARAM },
1462  { "tables_version", "set PAT, PMT and SDT version",
1463  offsetof(MpegTSWrite, tables_version), AV_OPT_TYPE_INT,
1464  { .i64 = 0 }, 0, 31, AV_OPT_FLAG_ENCODING_PARAM },
1465  { "omit_video_pes_length", "Omit the PES packet length for video packets",
1466  offsetof(MpegTSWrite, omit_video_pes_length), AV_OPT_TYPE_INT,
1467  { .i64 = 1 }, 0, 1, AV_OPT_FLAG_ENCODING_PARAM },
1468  { "pcr_period", "PCR retransmission time",
1469  offsetof(MpegTSWrite, pcr_period), AV_OPT_TYPE_INT,
1470  { .i64 = PCR_RETRANS_TIME }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
1471  { NULL },
1472 };
1473 
1474 static const AVClass mpegts_muxer_class = {
1475  .class_name = "MPEGTS muxer",
1476  .item_name = av_default_item_name,
1477  .option = options,
1478  .version = LIBAVUTIL_VERSION_INT,
1479 };
1480 
1482  .name = "mpegts",
1483  .long_name = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
1484  .mime_type = "video/MP2T",
1485  .extensions = "ts,m2t,m2ts,mts",
1486  .priv_data_size = sizeof(MpegTSWrite),
1487  .audio_codec = AV_CODEC_ID_MP2,
1488  .video_codec = AV_CODEC_ID_MPEG2VIDEO,
1493  .priv_class = &mpegts_muxer_class,
1494 };