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