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