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