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 
319  if (q - data > sizeof(data) - 32)
320  return AVERROR(EINVAL);
321 
322  *q++ = stream_type;
323  put16(&q, 0xe000 | ts_st->pid);
324  desc_length_ptr = q;
325  q += 2; /* patched after */
326 
327  /* write optional descriptors here */
328  switch(st->codec->codec_type) {
329  case AVMEDIA_TYPE_AUDIO:
330  if(st->codec->codec_id==AV_CODEC_ID_EAC3){
331  *q++=0x7a; // EAC3 descriptor see A038 DVB SI
332  *q++=1; // 1 byte, all flags sets to 0
333  *q++=0; // omit all fields...
334  }
335  if(st->codec->codec_id==AV_CODEC_ID_S302M){
336  *q++ = 0x05; /* MPEG-2 registration descriptor*/
337  *q++ = 4;
338  *q++ = 'B';
339  *q++ = 'S';
340  *q++ = 'S';
341  *q++ = 'D';
342  }
343 
344  if (lang) {
345  char *p;
346  char *next = lang->value;
347  uint8_t *len_ptr;
348 
349  *q++ = 0x0a; /* ISO 639 language descriptor */
350  len_ptr = q++;
351  *len_ptr = 0;
352 
353  for (p = lang->value; next && *len_ptr < 255 / 4 * 4 && q - data < sizeof(data) - 4; p = next + 1) {
354  next = strchr(p, ',');
355  if (strlen(p) != 3 && (!next || next != p + 3))
356  continue; /* not a 3-letter code */
357 
358  *q++ = *p++;
359  *q++ = *p++;
360  *q++ = *p++;
361 
363  *q++ = 0x01;
365  *q++ = 0x02;
367  *q++ = 0x03;
368  else
369  *q++ = 0; /* undefined type */
370 
371  *len_ptr += 4;
372  }
373 
374  if (*len_ptr == 0)
375  q -= 2; /* no language codes were written */
376  }
377  break;
379  {
380  const char default_language[] = "und";
381  const char *language = lang && strlen(lang->value) >= 3 ? lang->value : default_language;
382 
384  uint8_t *len_ptr;
385  int extradata_copied = 0;
386 
387  *q++ = 0x59; /* subtitling_descriptor */
388  len_ptr = q++;
389 
390  while (strlen(language) >= 3 && (sizeof(data) - (q - data)) >= 8) { /* 8 bytes per DVB subtitle substream data */
391  *q++ = *language++;
392  *q++ = *language++;
393  *q++ = *language++;
394  /* Skip comma */
395  if (*language != '\0')
396  language++;
397 
398  if (st->codec->extradata_size - extradata_copied >= 5) {
399  *q++ = st->codec->extradata[extradata_copied + 4]; /* subtitling_type */
400  memcpy(q, st->codec->extradata + extradata_copied, 4); /* composition_page_id and ancillary_page_id */
401  extradata_copied += 5;
402  q += 4;
403  } else {
404  /* subtitling_type:
405  * 0x10 - normal with no monitor aspect ratio criticality
406  * 0x20 - for the hard of hearing with no monitor aspect ratio criticality */
407  *q++ = (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED) ? 0x20 : 0x10;
408  if ((st->codec->extradata_size == 4) && (extradata_copied == 0)) {
409  /* support of old 4-byte extradata format */
410  memcpy(q, st->codec->extradata, 4); /* composition_page_id and ancillary_page_id */
411  extradata_copied += 4;
412  q += 4;
413  } else {
414  put16(&q, 1); /* composition_page_id */
415  put16(&q, 1); /* ancillary_page_id */
416  }
417  }
418  }
419 
420  *len_ptr = q - len_ptr - 1;
421  } else if (st->codec->codec_id == AV_CODEC_ID_DVB_TELETEXT) {
422  uint8_t *len_ptr = NULL;
423  int extradata_copied = 0;
424 
425  /* The descriptor tag. teletext_descriptor */
426  *q++ = 0x56;
427  len_ptr = q++;
428 
429  while (strlen(language) >= 3 && q - data < sizeof(data) - 6) {
430  *q++ = *language++;
431  *q++ = *language++;
432  *q++ = *language++;
433  /* Skip comma */
434  if (*language != '\0')
435  language++;
436 
437  if (st->codec->extradata_size - 1 > extradata_copied) {
438  memcpy(q, st->codec->extradata + extradata_copied, 2);
439  extradata_copied += 2;
440  q += 2;
441  } else {
442  /* The Teletext descriptor:
443  * teletext_type: This 5-bit field indicates the type of Teletext page indicated. (0x01 Initial Teletext page)
444  * teletext_magazine_number: This is a 3-bit field which identifies the magazine number.
445  * teletext_page_number: This is an 8-bit field giving two 4-bit hex digits identifying the page number. */
446  *q++ = 0x08;
447  *q++ = 0x00;
448  }
449  }
450 
451  *len_ptr = q - len_ptr - 1;
452  }
453  }
454  break;
455  case AVMEDIA_TYPE_VIDEO:
456  if (stream_type == STREAM_TYPE_VIDEO_DIRAC) {
457  *q++ = 0x05; /*MPEG-2 registration descriptor*/
458  *q++ = 4;
459  *q++ = 'd';
460  *q++ = 'r';
461  *q++ = 'a';
462  *q++ = 'c';
463  }
464  break;
465  case AVMEDIA_TYPE_DATA:
466  if (st->codec->codec_id == AV_CODEC_ID_SMPTE_KLV) {
467  *q++ = 0x05; /* MPEG-2 registration descriptor */
468  *q++ = 4;
469  *q++ = 'K';
470  *q++ = 'L';
471  *q++ = 'V';
472  *q++ = 'A';
473  }
474  break;
475  }
476 
477  val = 0xf000 | (q - desc_length_ptr - 2);
478  desc_length_ptr[0] = val >> 8;
479  desc_length_ptr[1] = val;
480  }
481  mpegts_write_section1(&service->pmt, PMT_TID, service->sid, ts->tables_version, 0, 0,
482  data, q - data);
483  return 0;
484 }
485 
486 /* NOTE: str == NULL is accepted for an empty string */
487 static void putstr8(uint8_t **q_ptr, const char *str)
488 {
489  uint8_t *q;
490  int len;
491 
492  q = *q_ptr;
493  if (!str)
494  len = 0;
495  else
496  len = strlen(str);
497  *q++ = len;
498  memcpy(q, str, len);
499  q += len;
500  *q_ptr = q;
501 }
502 
504 {
505  MpegTSWrite *ts = s->priv_data;
506  MpegTSService *service;
507  uint8_t data[1012], *q, *desc_list_len_ptr, *desc_len_ptr;
508  int i, running_status, free_ca_mode, val;
509 
510  q = data;
511  put16(&q, ts->onid);
512  *q++ = 0xff;
513  for(i = 0; i < ts->nb_services; i++) {
514  service = ts->services[i];
515  put16(&q, service->sid);
516  *q++ = 0xfc | 0x00; /* currently no EIT info */
517  desc_list_len_ptr = q;
518  q += 2;
519  running_status = 4; /* running */
520  free_ca_mode = 0;
521 
522  /* write only one descriptor for the service name and provider */
523  *q++ = 0x48;
524  desc_len_ptr = q;
525  q++;
526  *q++ = 0x01; /* digital television service */
527  putstr8(&q, service->provider_name);
528  putstr8(&q, service->name);
529  desc_len_ptr[0] = q - desc_len_ptr - 1;
530 
531  /* fill descriptor length */
532  val = (running_status << 13) | (free_ca_mode << 12) |
533  (q - desc_list_len_ptr - 2);
534  desc_list_len_ptr[0] = val >> 8;
535  desc_list_len_ptr[1] = val;
536  }
537  mpegts_write_section1(&ts->sdt, SDT_TID, ts->tsid, ts->tables_version, 0, 0,
538  data, q - data);
539 }
540 
542  int sid,
543  const char *provider_name,
544  const char *name)
545 {
546  MpegTSService *service;
547 
548  service = av_mallocz(sizeof(MpegTSService));
549  if (!service)
550  return NULL;
551  service->pmt.pid = ts->pmt_start_pid + ts->nb_services;
552  service->sid = sid;
553  service->provider_name = av_strdup(provider_name);
554  service->name = av_strdup(name);
555  service->pcr_pid = 0x1fff;
556  dynarray_add(&ts->services, &ts->nb_services, service);
557  return service;
558 }
559 
560 static int64_t get_pcr(const MpegTSWrite *ts, AVIOContext *pb)
561 {
562  return av_rescale(avio_tell(pb) + 11, 8 * PCR_TIME_BASE, ts->mux_rate) +
563  ts->first_pcr;
564 }
565 
567 {
568  MpegTSWrite *ts = s->priv_data;
569  if (ts->m2ts_mode) {
570  int64_t pcr = get_pcr(s->priv_data, s->pb);
571  uint32_t tp_extra_header = pcr % 0x3fffffff;
572  tp_extra_header = AV_RB32(&tp_extra_header);
573  avio_write(s->pb, (unsigned char *) &tp_extra_header,
574  sizeof(tp_extra_header));
575  }
576 }
577 
578 static void section_write_packet(MpegTSSection *s, const uint8_t *packet)
579 {
580  AVFormatContext *ctx = s->opaque;
582  avio_write(ctx->pb, packet, TS_PACKET_SIZE);
583 }
584 
586 {
587  MpegTSWrite *ts = s->priv_data;
588  MpegTSWriteStream *ts_st;
589  MpegTSService *service;
590  AVStream *st, *pcr_st = NULL;
591  AVDictionaryEntry *title, *provider;
592  int i, j;
593  const char *service_name;
594  const char *provider_name;
595  int *pids;
596  int ret;
597 
598  if (s->max_delay < 0) /* Not set by the caller */
599  s->max_delay = 0;
600 
601  // round up to a whole number of TS packets
602  ts->pes_payload_size = (ts->pes_payload_size + 14 + 183) / 184 * 184 - 14;
603 
604  ts->tsid = ts->transport_stream_id;
605  ts->onid = ts->original_network_id;
606  /* allocate a single DVB service */
607  title = av_dict_get(s->metadata, "service_name", NULL, 0);
608  if (!title)
609  title = av_dict_get(s->metadata, "title", NULL, 0);
610  service_name = title ? title->value : DEFAULT_SERVICE_NAME;
611  provider = av_dict_get(s->metadata, "service_provider", NULL, 0);
612  provider_name = provider ? provider->value : DEFAULT_PROVIDER_NAME;
613  service = mpegts_add_service(ts, ts->service_id, provider_name, service_name);
615  service->pmt.opaque = s;
616  service->pmt.cc = 15;
617 
618  ts->pat.pid = PAT_PID;
619  ts->pat.cc = 15; // Initialize at 15 so that it wraps and be equal to 0 for the first packet we write
621  ts->pat.opaque = s;
622 
623  ts->sdt.pid = SDT_PID;
624  ts->sdt.cc = 15;
626  ts->sdt.opaque = s;
627 
628  pids = av_malloc(s->nb_streams * sizeof(*pids));
629  if (!pids)
630  return AVERROR(ENOMEM);
631 
632  /* assign pids to each stream */
633  for(i = 0;i < s->nb_streams; i++) {
634  st = s->streams[i];
635  avpriv_set_pts_info(st, 33, 1, 90000);
636  ts_st = av_mallocz(sizeof(MpegTSWriteStream));
637  if (!ts_st) {
638  ret = AVERROR(ENOMEM);
639  goto fail;
640  }
641  st->priv_data = ts_st;
642  ts_st->payload = av_mallocz(ts->pes_payload_size);
643  if (!ts_st->payload) {
644  ret = AVERROR(ENOMEM);
645  goto fail;
646  }
647  ts_st->service = service;
648  /* MPEG pid values < 16 are reserved. Applications which set st->id in
649  * this range are assigned a calculated pid. */
650  if (st->id < 16) {
651  ts_st->pid = ts->start_pid + i;
652  } else if (st->id < 0x1FFF) {
653  ts_st->pid = st->id;
654  } else {
655  av_log(s, AV_LOG_ERROR, "Invalid stream id %d, must be less than 8191\n", st->id);
656  ret = AVERROR(EINVAL);
657  goto fail;
658  }
659  if (ts_st->pid == service->pmt.pid) {
660  av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
661  ret = AVERROR(EINVAL);
662  goto fail;
663  }
664  for (j = 0; j < i; j++)
665  if (pids[j] == ts_st->pid) {
666  av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
667  ret = AVERROR(EINVAL);
668  goto fail;
669  }
670  pids[i] = ts_st->pid;
671  ts_st->payload_pts = AV_NOPTS_VALUE;
672  ts_st->payload_dts = AV_NOPTS_VALUE;
673  ts_st->first_pts_check = 1;
674  ts_st->cc = 15;
675  /* update PCR pid by using the first video stream */
676  if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
677  service->pcr_pid == 0x1fff) {
678  service->pcr_pid = ts_st->pid;
679  pcr_st = st;
680  }
681  if (st->codec->codec_id == AV_CODEC_ID_AAC &&
682  st->codec->extradata_size > 0)
683  {
684  AVStream *ast;
685  ts_st->amux = avformat_alloc_context();
686  if (!ts_st->amux) {
687  ret = AVERROR(ENOMEM);
688  goto fail;
689  }
690  ts_st->amux->oformat = av_guess_format((ts->flags & MPEGTS_FLAG_AAC_LATM) ? "latm" : "adts", NULL, NULL);
691  if (!ts_st->amux->oformat) {
692  ret = AVERROR(EINVAL);
693  goto fail;
694  }
695  ast = avformat_new_stream(ts_st->amux, NULL);
696  ret = avcodec_copy_context(ast->codec, st->codec);
697  if (ret != 0)
698  goto fail;
699  ret = avformat_write_header(ts_st->amux, NULL);
700  if (ret < 0)
701  goto fail;
702  }
703  }
704 
705  av_free(pids);
706 
707  /* if no video stream, use the first stream as PCR */
708  if (service->pcr_pid == 0x1fff && s->nb_streams > 0) {
709  pcr_st = s->streams[0];
710  ts_st = pcr_st->priv_data;
711  service->pcr_pid = ts_st->pid;
712  }
713 
714  if (ts->mux_rate > 1) {
715  service->pcr_packet_period = (ts->mux_rate * PCR_RETRANS_TIME) /
716  (TS_PACKET_SIZE * 8 * 1000);
718  (TS_PACKET_SIZE * 8 * 1000);
720  (TS_PACKET_SIZE * 8 * 1000);
721 
722  if(ts->copyts < 1)
724  } else {
725  /* Arbitrary values, PAT/PMT will also be written on video key frames */
726  ts->sdt_packet_period = 200;
727  ts->pat_packet_period = 40;
728  if (pcr_st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
729  if (!pcr_st->codec->frame_size) {
730  av_log(s, AV_LOG_WARNING, "frame size not set\n");
731  service->pcr_packet_period =
732  pcr_st->codec->sample_rate/(10*512);
733  } else {
734  service->pcr_packet_period =
735  pcr_st->codec->sample_rate/(10*pcr_st->codec->frame_size);
736  }
737  } else {
738  // max delta PCR 0.1s
739  service->pcr_packet_period =
740  pcr_st->codec->time_base.den/(10*pcr_st->codec->time_base.num);
741  }
742  if(!service->pcr_packet_period)
743  service->pcr_packet_period = 1;
744  }
745 
746  // output a PCR as soon as possible
747  service->pcr_packet_count = service->pcr_packet_period;
750 
751  if (ts->mux_rate == 1)
752  av_log(s, AV_LOG_VERBOSE, "muxrate VBR, ");
753  else
754  av_log(s, AV_LOG_VERBOSE, "muxrate %d, ", ts->mux_rate);
755  av_log(s, AV_LOG_VERBOSE, "pcr every %d pkts, "
756  "sdt every %d, pat/pmt every %d pkts\n",
757  service->pcr_packet_period,
759 
760  if (ts->m2ts_mode == -1) {
761  if (av_match_ext(s->filename, "m2ts")) {
762  ts->m2ts_mode = 1;
763  } else {
764  ts->m2ts_mode = 0;
765  }
766  }
767 
768  avio_flush(s->pb);
769 
770  return 0;
771 
772  fail:
773  av_free(pids);
774  for(i = 0;i < s->nb_streams; i++) {
775  MpegTSWriteStream *ts_st;
776  st = s->streams[i];
777  ts_st = st->priv_data;
778  if (ts_st) {
779  av_freep(&ts_st->payload);
780  if (ts_st->amux) {
781  avformat_free_context(ts_st->amux);
782  ts_st->amux = NULL;
783  }
784  }
785  av_freep(&st->priv_data);
786  }
787  return ret;
788 }
789 
790 /* send SDT, PAT and PMT tables regulary */
791 static void retransmit_si_info(AVFormatContext *s, int force_pat)
792 {
793  MpegTSWrite *ts = s->priv_data;
794  int i;
795 
796  if (++ts->sdt_packet_count == ts->sdt_packet_period) {
797  ts->sdt_packet_count = 0;
798  mpegts_write_sdt(s);
799  }
800  if (++ts->pat_packet_count == ts->pat_packet_period || force_pat) {
801  ts->pat_packet_count = 0;
802  mpegts_write_pat(s);
803  for(i = 0; i < ts->nb_services; i++) {
804  mpegts_write_pmt(s, ts->services[i]);
805  }
806  }
807 }
808 
809 static int write_pcr_bits(uint8_t *buf, int64_t pcr)
810 {
811  int64_t pcr_low = pcr % 300, pcr_high = pcr / 300;
812 
813  *buf++ = pcr_high >> 25;
814  *buf++ = pcr_high >> 17;
815  *buf++ = pcr_high >> 9;
816  *buf++ = pcr_high >> 1;
817  *buf++ = pcr_high << 7 | pcr_low >> 8 | 0x7e;
818  *buf++ = pcr_low;
819 
820  return 6;
821 }
822 
823 /* Write a single null transport stream packet */
825 {
826  uint8_t *q;
828 
829  q = buf;
830  *q++ = 0x47;
831  *q++ = 0x00 | 0x1f;
832  *q++ = 0xff;
833  *q++ = 0x10;
834  memset(q, 0x0FF, TS_PACKET_SIZE - (q - buf));
836  avio_write(s->pb, buf, TS_PACKET_SIZE);
837 }
838 
839 /* Write a single transport stream packet with a PCR and no payload */
841 {
842  MpegTSWrite *ts = s->priv_data;
843  MpegTSWriteStream *ts_st = st->priv_data;
844  uint8_t *q;
846 
847  q = buf;
848  *q++ = 0x47;
849  *q++ = ts_st->pid >> 8;
850  *q++ = ts_st->pid;
851  *q++ = 0x20 | ts_st->cc; /* Adaptation only */
852  /* Continuity Count field does not increment (see 13818-1 section 2.4.3.3) */
853  *q++ = TS_PACKET_SIZE - 5; /* Adaptation Field Length */
854  *q++ = 0x10; /* Adaptation flags: PCR present */
855 
856  /* PCR coded into 6 bytes */
857  q += write_pcr_bits(q, get_pcr(ts, s->pb));
858 
859  /* stuffing bytes */
860  memset(q, 0xFF, TS_PACKET_SIZE - (q - buf));
862  avio_write(s->pb, buf, TS_PACKET_SIZE);
863 }
864 
865 static void write_pts(uint8_t *q, int fourbits, int64_t pts)
866 {
867  int val;
868 
869  val = fourbits << 4 | (((pts >> 30) & 0x07) << 1) | 1;
870  *q++ = val;
871  val = (((pts >> 15) & 0x7fff) << 1) | 1;
872  *q++ = val >> 8;
873  *q++ = val;
874  val = (((pts) & 0x7fff) << 1) | 1;
875  *q++ = val >> 8;
876  *q++ = val;
877 }
878 
879 /* Set an adaptation field flag in an MPEG-TS packet*/
880 static void set_af_flag(uint8_t *pkt, int flag)
881 {
882  // expect at least one flag to set
883  av_assert0(flag);
884 
885  if ((pkt[3] & 0x20) == 0) {
886  // no AF yet, set adaptation field flag
887  pkt[3] |= 0x20;
888  // 1 byte length, no flags
889  pkt[4] = 1;
890  pkt[5] = 0;
891  }
892  pkt[5] |= flag;
893 }
894 
895 /* Extend the adaptation field by size bytes */
896 static void extend_af(uint8_t *pkt, int size)
897 {
898  // expect already existing adaptation field
899  av_assert0(pkt[3] & 0x20);
900  pkt[4] += size;
901 }
902 
903 /* Get a pointer to MPEG-TS payload (right after TS packet header) */
905 {
906  if (pkt[3] & 0x20)
907  return pkt + 5 + pkt[4];
908  else
909  return pkt + 4;
910 }
911 
912 /* Add a pes header to the front of payload, and segment into an integer number of
913  * ts packets. The final ts packet is padded using an over-sized adaptation header
914  * to exactly fill the last ts packet.
915  * NOTE: 'payload' contains a complete PES payload.
916  */
918  const uint8_t *payload, int payload_size,
919  int64_t pts, int64_t dts, int key)
920 {
921  MpegTSWriteStream *ts_st = st->priv_data;
922  MpegTSWrite *ts = s->priv_data;
924  uint8_t *q;
925  int val, is_start, len, header_len, write_pcr, is_dvb_subtitle, is_dvb_teletext, flags;
926  int afc_len, stuffing_len;
927  int64_t pcr = -1; /* avoid warning */
928  int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE);
929  int force_pat = st->codec->codec_type == AVMEDIA_TYPE_VIDEO && key && !ts_st->prev_payload_key;
930 
931  is_start = 1;
932  while (payload_size > 0) {
933  retransmit_si_info(s, force_pat);
934  force_pat = 0;
935 
936  write_pcr = 0;
937  if (ts_st->pid == ts_st->service->pcr_pid) {
938  if (ts->mux_rate > 1 || is_start) // VBR pcr period is based on frames
939  ts_st->service->pcr_packet_count++;
940  if (ts_st->service->pcr_packet_count >=
941  ts_st->service->pcr_packet_period) {
942  ts_st->service->pcr_packet_count = 0;
943  write_pcr = 1;
944  }
945  }
946 
947  if (ts->mux_rate > 1 && dts != AV_NOPTS_VALUE &&
948  (dts - get_pcr(ts, s->pb)/300) > delay) {
949  /* pcr insert gets priority over null packet insert */
950  if (write_pcr)
951  mpegts_insert_pcr_only(s, st);
952  else
954  continue; /* recalculate write_pcr and possibly retransmit si_info */
955  }
956 
957  /* prepare packet header */
958  q = buf;
959  *q++ = 0x47;
960  val = (ts_st->pid >> 8);
961  if (is_start)
962  val |= 0x40;
963  *q++ = val;
964  *q++ = ts_st->pid;
965  ts_st->cc = (ts_st->cc + 1) & 0xf;
966  *q++ = 0x10 | ts_st->cc; // payload indicator + CC
967  if (key && is_start && pts != AV_NOPTS_VALUE) {
968  // set Random Access for key frames
969  if (ts_st->pid == ts_st->service->pcr_pid)
970  write_pcr = 1;
971  set_af_flag(buf, 0x40);
972  q = get_ts_payload_start(buf);
973  }
974  if (write_pcr) {
975  set_af_flag(buf, 0x10);
976  q = get_ts_payload_start(buf);
977  // add 11, pcr references the last byte of program clock reference base
978  if (ts->mux_rate > 1)
979  pcr = get_pcr(ts, s->pb);
980  else
981  pcr = (dts - delay)*300;
982  if (dts != AV_NOPTS_VALUE && dts < pcr / 300)
983  av_log(s, AV_LOG_WARNING, "dts < pcr, TS is invalid\n");
984  extend_af(buf, write_pcr_bits(q, pcr));
985  q = get_ts_payload_start(buf);
986  }
987  if (is_start) {
988  int pes_extension = 0;
989  int pes_header_stuffing_bytes = 0;
990  /* write PES header */
991  *q++ = 0x00;
992  *q++ = 0x00;
993  *q++ = 0x01;
994  is_dvb_subtitle = 0;
995  is_dvb_teletext = 0;
996  if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
997  if (st->codec->codec_id == AV_CODEC_ID_DIRAC) {
998  *q++ = 0xfd;
999  } else
1000  *q++ = 0xe0;
1001  } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1002  (st->codec->codec_id == AV_CODEC_ID_MP2 ||
1003  st->codec->codec_id == AV_CODEC_ID_MP3 ||
1004  st->codec->codec_id == AV_CODEC_ID_AAC)) {
1005  *q++ = 0xc0;
1006  } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1007  st->codec->codec_id == AV_CODEC_ID_AC3 &&
1008  ts->m2ts_mode) {
1009  *q++ = 0xfd;
1010  } else {
1011  *q++ = 0xbd;
1012  if(st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1013  if (st->codec->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
1014  is_dvb_subtitle = 1;
1015  } else if (st->codec->codec_id == AV_CODEC_ID_DVB_TELETEXT) {
1016  is_dvb_teletext = 1;
1017  }
1018  }
1019  }
1020  header_len = 0;
1021  flags = 0;
1022  if (pts != AV_NOPTS_VALUE) {
1023  header_len += 5;
1024  flags |= 0x80;
1025  }
1026  if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
1027  header_len += 5;
1028  flags |= 0x40;
1029  }
1030  if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
1031  st->codec->codec_id == AV_CODEC_ID_DIRAC) {
1032  /* set PES_extension_flag */
1033  pes_extension = 1;
1034  flags |= 0x01;
1035 
1036  /*
1037  * One byte for PES2 extension flag +
1038  * one byte for extension length +
1039  * one byte for extension id
1040  */
1041  header_len += 3;
1042  }
1043  /* for Blu-ray AC3 Audio the PES Extension flag should be as follow
1044  * otherwise it will not play sound on blu-ray
1045  */
1046  if (ts->m2ts_mode &&
1048  st->codec->codec_id == AV_CODEC_ID_AC3) {
1049  /* set PES_extension_flag */
1050  pes_extension = 1;
1051  flags |= 0x01;
1052  header_len += 3;
1053  }
1054  if (is_dvb_teletext) {
1055  pes_header_stuffing_bytes = 0x24 - header_len;
1056  header_len = 0x24;
1057  }
1058  len = payload_size + header_len + 3;
1059  /* 3 extra bytes should be added to DVB subtitle payload: 0x20 0x00 at the beginning and trailing 0xff */
1060  if (is_dvb_subtitle) {
1061  len += 3;
1062  payload_size++;
1063  }
1064  if (len > 0xffff)
1065  len = 0;
1066  *q++ = len >> 8;
1067  *q++ = len;
1068  val = 0x80;
1069  /* data alignment indicator is required for subtitle and data streams */
1071  val |= 0x04;
1072  *q++ = val;
1073  *q++ = flags;
1074  *q++ = header_len;
1075  if (pts != AV_NOPTS_VALUE) {
1076  write_pts(q, flags >> 6, pts);
1077  q += 5;
1078  }
1079  if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
1080  write_pts(q, 1, dts);
1081  q += 5;
1082  }
1083  if (pes_extension && st->codec->codec_id == AV_CODEC_ID_DIRAC) {
1084  flags = 0x01; /* set PES_extension_flag_2 */
1085  *q++ = flags;
1086  *q++ = 0x80 | 0x01; /* marker bit + extension length */
1087  /*
1088  * Set the stream id extension flag bit to 0 and
1089  * write the extended stream id
1090  */
1091  *q++ = 0x00 | 0x60;
1092  }
1093  /* For Blu-ray AC3 Audio Setting extended flags */
1094  if (ts->m2ts_mode &&
1095  pes_extension &&
1096  st->codec->codec_id == AV_CODEC_ID_AC3) {
1097  flags = 0x01; /* set PES_extension_flag_2 */
1098  *q++ = flags;
1099  *q++ = 0x80 | 0x01; /* marker bit + extension length */
1100  *q++ = 0x00 | 0x71; /* for AC3 Audio (specifically on blue-rays) */
1101  }
1102 
1103 
1104  if (is_dvb_subtitle) {
1105  /* First two fields of DVB subtitles PES data:
1106  * data_identifier: for DVB subtitle streams shall be coded with the value 0x20
1107  * subtitle_stream_id: for DVB subtitle stream shall be identified by the value 0x00 */
1108  *q++ = 0x20;
1109  *q++ = 0x00;
1110  }
1111  if (is_dvb_teletext) {
1112  memset(q, 0xff, pes_header_stuffing_bytes);
1113  q += pes_header_stuffing_bytes;
1114  }
1115  is_start = 0;
1116  }
1117  /* header size */
1118  header_len = q - buf;
1119  /* data len */
1120  len = TS_PACKET_SIZE - header_len;
1121  if (len > payload_size)
1122  len = payload_size;
1123  stuffing_len = TS_PACKET_SIZE - header_len - len;
1124  if (stuffing_len > 0) {
1125  /* add stuffing with AFC */
1126  if (buf[3] & 0x20) {
1127  /* stuffing already present: increase its size */
1128  afc_len = buf[4] + 1;
1129  memmove(buf + 4 + afc_len + stuffing_len,
1130  buf + 4 + afc_len,
1131  header_len - (4 + afc_len));
1132  buf[4] += stuffing_len;
1133  memset(buf + 4 + afc_len, 0xff, stuffing_len);
1134  } else {
1135  /* add stuffing */
1136  memmove(buf + 4 + stuffing_len, buf + 4, header_len - 4);
1137  buf[3] |= 0x20;
1138  buf[4] = stuffing_len - 1;
1139  if (stuffing_len >= 2) {
1140  buf[5] = 0x00;
1141  memset(buf + 6, 0xff, stuffing_len - 2);
1142  }
1143  }
1144  }
1145 
1146  if (is_dvb_subtitle && payload_size == len) {
1147  memcpy(buf + TS_PACKET_SIZE - len, payload, len - 1);
1148  buf[TS_PACKET_SIZE - 1] = 0xff; /* end_of_PES_data_field_marker: an 8-bit field with fixed contents 0xff for DVB subtitle */
1149  } else {
1150  memcpy(buf + TS_PACKET_SIZE - len, payload, len);
1151  }
1152 
1153  payload += len;
1154  payload_size -= len;
1156  avio_write(s->pb, buf, TS_PACKET_SIZE);
1157  }
1158  avio_flush(s->pb);
1159  ts_st->prev_payload_key = key;
1160 }
1161 
1163 {
1164  AVStream *st = s->streams[pkt->stream_index];
1165  int size = pkt->size;
1166  uint8_t *buf= pkt->data;
1167  uint8_t *data= NULL;
1168  MpegTSWrite *ts = s->priv_data;
1169  MpegTSWriteStream *ts_st = st->priv_data;
1170  const int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE)*2;
1171  int64_t dts = pkt->dts, pts = pkt->pts;
1172 
1173  if (ts->reemit_pat_pmt) {
1174  av_log(s, AV_LOG_WARNING, "resend_headers option is deprecated, use -mpegts_flags resend_headers\n");
1175  ts->reemit_pat_pmt = 0;
1177  }
1178 
1179  if (ts->flags & MPEGTS_FLAG_REEMIT_PAT_PMT) {
1180  ts->pat_packet_count = ts->pat_packet_period - 1;
1181  ts->sdt_packet_count = ts->sdt_packet_period - 1;
1183  }
1184 
1185  if(ts->copyts < 1){
1186  if (pts != AV_NOPTS_VALUE)
1187  pts += delay;
1188  if (dts != AV_NOPTS_VALUE)
1189  dts += delay;
1190  }
1191 
1192  if (ts_st->first_pts_check && pts == AV_NOPTS_VALUE) {
1193  av_log(s, AV_LOG_ERROR, "first pts value must be set\n");
1194  return AVERROR_INVALIDDATA;
1195  }
1196  ts_st->first_pts_check = 0;
1197 
1198  if (st->codec->codec_id == AV_CODEC_ID_H264) {
1199  const uint8_t *p = buf, *buf_end = p+size;
1200  uint32_t state = -1;
1201 
1202  if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001) {
1203  if (!st->nb_frames) {
1204  av_log(s, AV_LOG_ERROR, "H.264 bitstream malformed, "
1205  "no startcode found, use the h264_mp4toannexb bitstream filter (-bsf h264_mp4toannexb)\n");
1206  return AVERROR(EINVAL);
1207  }
1208  av_log(s, AV_LOG_WARNING, "H.264 bitstream error, startcode missing\n");
1209  }
1210 
1211  do {
1212  p = avpriv_find_start_code(p, buf_end, &state);
1213  av_dlog(s, "nal %d\n", state & 0x1f);
1214  } while (p < buf_end && (state & 0x1f) != 9 &&
1215  (state & 0x1f) != 5 && (state & 0x1f) != 1);
1216 
1217  if ((state & 0x1f) != 9) { // AUD NAL
1218  data = av_malloc(pkt->size+6);
1219  if (!data)
1220  return AVERROR(ENOMEM);
1221  memcpy(data+6, pkt->data, pkt->size);
1222  AV_WB32(data, 0x00000001);
1223  data[4] = 0x09;
1224  data[5] = 0xf0; // any slice type (0xe) + rbsp stop one bit
1225  buf = data;
1226  size = pkt->size+6;
1227  }
1228  } else if (st->codec->codec_id == AV_CODEC_ID_AAC) {
1229  if (pkt->size < 2) {
1230  av_log(s, AV_LOG_ERROR, "AAC packet too short\n");
1231  return AVERROR_INVALIDDATA;
1232  }
1233  if ((AV_RB16(pkt->data) & 0xfff0) != 0xfff0) {
1234  int ret;
1235  AVPacket pkt2;
1236 
1237  if (!ts_st->amux) {
1238  av_log(s, AV_LOG_ERROR, "AAC bitstream not in ADTS format "
1239  "and extradata missing\n");
1240  return AVERROR_INVALIDDATA;
1241  }
1242 
1243  av_init_packet(&pkt2);
1244  pkt2.data = pkt->data;
1245  pkt2.size = pkt->size;
1246  ret = avio_open_dyn_buf(&ts_st->amux->pb);
1247  if (ret < 0)
1248  return AVERROR(ENOMEM);
1249 
1250  ret = av_write_frame(ts_st->amux, &pkt2);
1251  if (ret < 0) {
1252  avio_close_dyn_buf(ts_st->amux->pb, &data);
1253  ts_st->amux->pb = NULL;
1254  av_free(data);
1255  return ret;
1256  }
1257  size = avio_close_dyn_buf(ts_st->amux->pb, &data);
1258  ts_st->amux->pb = NULL;
1259  buf = data;
1260  }
1261  }
1262 
1263  if (pkt->dts != AV_NOPTS_VALUE) {
1264  int i;
1265  for(i=0; i<s->nb_streams; i++){
1266  AVStream *st2 = s->streams[i];
1267  MpegTSWriteStream *ts_st2 = st2->priv_data;
1268  if( ts_st2->payload_size
1269  && (ts_st2->payload_dts == AV_NOPTS_VALUE || dts - ts_st2->payload_dts > delay/2)){
1270  mpegts_write_pes(s, st2, ts_st2->payload, ts_st2->payload_size,
1271  ts_st2->payload_pts, ts_st2->payload_dts,
1272  ts_st2->payload_flags & AV_PKT_FLAG_KEY);
1273  ts_st2->payload_size = 0;
1274  }
1275  }
1276  }
1277 
1278  if (ts_st->payload_size && ts_st->payload_size + size > ts->pes_payload_size) {
1279  mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_size,
1280  ts_st->payload_pts, ts_st->payload_dts,
1281  ts_st->payload_flags & AV_PKT_FLAG_KEY);
1282  ts_st->payload_size = 0;
1283  }
1284 
1285  if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO || size > ts->pes_payload_size) {
1286  av_assert0(!ts_st->payload_size);
1287  // for video and subtitle, write a single pes packet
1288  mpegts_write_pes(s, st, buf, size, pts, dts, pkt->flags & AV_PKT_FLAG_KEY);
1289  av_free(data);
1290  return 0;
1291  }
1292 
1293  if (!ts_st->payload_size) {
1294  ts_st->payload_pts = pts;
1295  ts_st->payload_dts = dts;
1296  ts_st->payload_flags = pkt->flags;
1297  }
1298 
1299  memcpy(ts_st->payload + ts_st->payload_size, buf, size);
1300  ts_st->payload_size += size;
1301 
1302  av_free(data);
1303 
1304  return 0;
1305 }
1306 
1308 {
1309  int i;
1310 
1311  /* flush current packets */
1312  for(i = 0; i < s->nb_streams; i++) {
1313  AVStream *st = s->streams[i];
1314  MpegTSWriteStream *ts_st = st->priv_data;
1315  if (ts_st->payload_size > 0) {
1316  mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_size,
1317  ts_st->payload_pts, ts_st->payload_dts,
1318  ts_st->payload_flags & AV_PKT_FLAG_KEY);
1319  ts_st->payload_size = 0;
1320  }
1321  }
1322  avio_flush(s->pb);
1323 }
1324 
1326 {
1327  if (!pkt) {
1328  mpegts_write_flush(s);
1329  return 1;
1330  } else {
1331  return mpegts_write_packet_internal(s, pkt);
1332  }
1333 }
1334 
1336 {
1337  MpegTSWrite *ts = s->priv_data;
1338  MpegTSService *service;
1339  int i;
1340 
1341  mpegts_write_flush(s);
1342 
1343  for(i = 0; i < s->nb_streams; i++) {
1344  AVStream *st = s->streams[i];
1345  MpegTSWriteStream *ts_st = st->priv_data;
1346  av_freep(&ts_st->payload);
1347  if (ts_st->amux) {
1348  avformat_free_context(ts_st->amux);
1349  ts_st->amux = NULL;
1350  }
1351  }
1352 
1353  for(i = 0; i < ts->nb_services; i++) {
1354  service = ts->services[i];
1355  av_freep(&service->provider_name);
1356  av_freep(&service->name);
1357  av_free(service);
1358  }
1359  av_free(ts->services);
1360 
1361  return 0;
1362 }
1363 
1365  .name = "mpegts",
1366  .long_name = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
1367  .mime_type = "video/x-mpegts",
1368  .extensions = "ts,m2t,m2ts,mts",
1369  .priv_data_size = sizeof(MpegTSWrite),
1370  .audio_codec = AV_CODEC_ID_MP2,
1371  .video_codec = AV_CODEC_ID_MPEG2VIDEO,
1376  .priv_class = &mpegts_muxer_class,
1377 };