Libav
mpegts.c
Go to the documentation of this file.
1 /*
2  * MPEG-2 transport stream (aka DVB) demuxer
3  * Copyright (c) 2002-2003 Fabrice Bellard
4  *
5  * This file is part of Libav.
6  *
7  * Libav 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  * Libav 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 Libav; 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/buffer.h"
23 #include "libavutil/crc.h"
24 #include "libavutil/intreadwrite.h"
25 #include "libavutil/log.h"
26 #include "libavutil/dict.h"
27 #include "libavutil/mathematics.h"
28 #include "libavutil/opt.h"
29 #include "libavcodec/bytestream.h"
30 #include "libavcodec/get_bits.h"
31 #include "libavcodec/opus.h"
32 #include "avformat.h"
33 #include "mpegts.h"
34 #include "internal.h"
35 #include "avio_internal.h"
36 #include "mpeg.h"
37 #include "isom.h"
38 
39 /* maximum size in which we look for synchronization if
40  * synchronization is lost */
41 #define MAX_RESYNC_SIZE 65536
42 
43 #define MAX_PES_PAYLOAD 200 * 1024
44 
45 #define MAX_MP4_DESCR_COUNT 16
46 
47 #define MOD_UNLIKELY(modulus, dividend, divisor, prev_dividend) \
48  do { \
49  if ((prev_dividend) == 0 || (dividend) - (prev_dividend) != (divisor)) \
50  (modulus) = (dividend) % (divisor); \
51  (prev_dividend) = (dividend); \
52  } while (0)
53 
57 };
58 
59 typedef struct MpegTSFilter MpegTSFilter;
60 
61 typedef int PESCallback (MpegTSFilter *f, const uint8_t *buf, int len,
62  int is_start, int64_t pos);
63 
64 typedef struct MpegTSPESFilter {
66  void *opaque;
68 
69 typedef void SectionCallback (MpegTSFilter *f, const uint8_t *buf, int len);
70 
71 typedef void SetServiceCallback (void *opaque, int ret);
72 
73 typedef struct MpegTSSectionFilter {
76  int last_ver;
78  unsigned int check_crc : 1;
79  unsigned int end_of_section_reached : 1;
81  void *opaque;
83 
84 struct MpegTSFilter {
85  int pid;
86  int es_id;
87  int last_cc; /* last cc code (-1 if first packet) */
88  enum MpegTSFilterType type;
89  union {
92  } u;
93 };
94 
95 #define MAX_PIDS_PER_PROGRAM 64
96 struct Program {
97  unsigned int id; // program id/service id
98  unsigned int nb_pids;
99  unsigned int pids[MAX_PIDS_PER_PROGRAM];
100 };
101 
103  const AVClass *class;
104  /* user data */
108 
109  int pos47;
111  int64_t pos;
112 
115 
118 
119  int64_t cur_pcr;
120  int pcr_incr;
122  /* data needed to handle file based ts */
128  int64_t last_pos;
129 
131 
132  /******************************************/
133  /* private mpegts data */
134  /* scan context */
136  unsigned int nb_prg;
137  struct Program *prg;
138 
141 };
142 
143 #define MPEGTS_OPTIONS \
144  { "resync_size", "Size limit for looking up a new synchronization.", offsetof(MpegTSContext, resync_size), AV_OPT_TYPE_INT, { .i64 = MAX_RESYNC_SIZE}, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM }
145 
146 static const AVOption options[] = {
148  { NULL },
149 };
150 
151 static const AVClass mpegts_class = {
152  .class_name = "mpegts demuxer",
153  .item_name = av_default_item_name,
154  .option = options,
155  .version = LIBAVUTIL_VERSION_INT,
156 };
157 
158 static const AVOption raw_options[] = {
160  { "compute_pcr", "Compute exact PCR for each transport stream packet.",
161  offsetof(MpegTSContext, mpeg2ts_compute_pcr), AV_OPT_TYPE_INT,
162  { .i64 = 0 }, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
163  { "ts_packetsize", "Output option carrying the raw packet size.",
164  offsetof(MpegTSContext, raw_packet_size), AV_OPT_TYPE_INT,
165  { .i64 = 0 }, 0, 0,
167  { NULL },
168 };
169 
170 static const AVClass mpegtsraw_class = {
171  .class_name = "mpegtsraw demuxer",
172  .item_name = av_default_item_name,
173  .option = raw_options,
174  .version = LIBAVUTIL_VERSION_INT,
175 };
176 
177 /* TS stream handling */
178 
185 };
186 
187 /* enough for PES header + length */
188 #define PES_START_SIZE 6
189 #define PES_HEADER_SIZE 9
190 #define MAX_PES_HEADER_SIZE (9 + 255)
191 
192 typedef struct PESContext {
193  int pid;
194  int pcr_pid;
201  /* used to get the format */
203  int flags;
207  int64_t pts, dts;
208  int64_t ts_packet_pos;
212 } PESContext;
213 
215 
216 static void clear_program(MpegTSContext *ts, unsigned int programid)
217 {
218  int i;
219 
220  for (i = 0; i < ts->nb_prg; i++)
221  if (ts->prg[i].id == programid)
222  ts->prg[i].nb_pids = 0;
223 }
224 
226 {
227  av_freep(&ts->prg);
228  ts->nb_prg = 0;
229 }
230 
231 static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
232 {
233  struct Program *p;
234  if (av_reallocp_array(&ts->prg, ts->nb_prg + 1, sizeof(*ts->prg)) < 0) {
235  ts->nb_prg = 0;
236  return;
237  }
238  p = &ts->prg[ts->nb_prg];
239  p->id = programid;
240  p->nb_pids = 0;
241  ts->nb_prg++;
242 }
243 
244 static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid,
245  unsigned int pid)
246 {
247  int i;
248  struct Program *p = NULL;
249  for (i = 0; i < ts->nb_prg; i++) {
250  if (ts->prg[i].id == programid) {
251  p = &ts->prg[i];
252  break;
253  }
254  }
255  if (!p)
256  return;
257 
258  if (p->nb_pids >= MAX_PIDS_PER_PROGRAM)
259  return;
260  p->pids[p->nb_pids++] = pid;
261 }
262 
271 static int discard_pid(MpegTSContext *ts, unsigned int pid)
272 {
273  int i, j, k;
274  int used = 0, discarded = 0;
275  struct Program *p;
276 
277  /* If none of the programs have .discard=AVDISCARD_ALL then there's
278  * no way we have to discard this packet */
279  for (k = 0; k < ts->stream->nb_programs; k++)
280  if (ts->stream->programs[k]->discard == AVDISCARD_ALL)
281  break;
282  if (k == ts->stream->nb_programs)
283  return 0;
284 
285  for (i = 0; i < ts->nb_prg; i++) {
286  p = &ts->prg[i];
287  for (j = 0; j < p->nb_pids; j++) {
288  if (p->pids[j] != pid)
289  continue;
290  // is program with id p->id set to be discarded?
291  for (k = 0; k < ts->stream->nb_programs; k++) {
292  if (ts->stream->programs[k]->id == p->id) {
293  if (ts->stream->programs[k]->discard == AVDISCARD_ALL)
294  discarded++;
295  else
296  used++;
297  }
298  }
299  }
300  }
301 
302  return !used && discarded;
303 }
304 
310  const uint8_t *buf, int buf_size, int is_start)
311 {
312  MpegTSSectionFilter *tss = &tss1->u.section_filter;
313  int len;
314 
315  if (is_start) {
316  memcpy(tss->section_buf, buf, buf_size);
317  tss->section_index = buf_size;
318  tss->section_h_size = -1;
319  tss->end_of_section_reached = 0;
320  } else {
321  if (tss->end_of_section_reached)
322  return;
323  len = 4096 - tss->section_index;
324  if (buf_size < len)
325  len = buf_size;
326  memcpy(tss->section_buf + tss->section_index, buf, len);
327  tss->section_index += len;
328  }
329 
330  /* compute section length if possible */
331  if (tss->section_h_size == -1 && tss->section_index >= 3) {
332  len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
333  if (len > 4096)
334  return;
335  tss->section_h_size = len;
336  }
337 
338  if (tss->section_h_size != -1 &&
339  tss->section_index >= tss->section_h_size) {
340  tss->end_of_section_reached = 1;
341  if (!tss->check_crc ||
343  tss->section_buf, tss->section_h_size) == 0)
344  tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
345  }
346 }
347 
349  unsigned int pid,
350  SectionCallback *section_cb,
351  void *opaque,
352  int check_crc)
353 {
355  MpegTSSectionFilter *sec;
356 
357  av_log(ts->stream, AV_LOG_TRACE, "Filter: pid=0x%x\n", pid);
358 
359  if (pid >= NB_PID_MAX || ts->pids[pid])
360  return NULL;
361  filter = av_mallocz(sizeof(MpegTSFilter));
362  if (!filter)
363  return NULL;
364  ts->pids[pid] = filter;
365 
366  filter->type = MPEGTS_SECTION;
367  filter->pid = pid;
368  filter->es_id = -1;
369  filter->last_cc = -1;
370 
371  sec = &filter->u.section_filter;
372  sec->section_cb = section_cb;
373  sec->opaque = opaque;
375  sec->check_crc = check_crc;
376  sec->last_ver = -1;
377 
378  if (!sec->section_buf) {
379  av_free(filter);
380  return NULL;
381  }
382  return filter;
383 }
384 
385 static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
387  void *opaque)
388 {
390  MpegTSPESFilter *pes;
391 
392  if (pid >= NB_PID_MAX || ts->pids[pid])
393  return NULL;
394  filter = av_mallocz(sizeof(MpegTSFilter));
395  if (!filter)
396  return NULL;
397 
398  ts->pids[pid] = filter;
399  filter->type = MPEGTS_PES;
400  filter->pid = pid;
401  filter->es_id = -1;
402  filter->last_cc = -1;
403 
404  pes = &filter->u.pes_filter;
405  pes->pes_cb = pes_cb;
406  pes->opaque = opaque;
407  return filter;
408 }
409 
411 {
412  int pid;
413 
414  pid = filter->pid;
415  if (filter->type == MPEGTS_SECTION)
417  else if (filter->type == MPEGTS_PES) {
418  PESContext *pes = filter->u.pes_filter.opaque;
419  av_buffer_unref(&pes->buffer);
420  /* referenced private data will be freed later in
421  * avformat_close_input */
422  if (!((PESContext *)filter->u.pes_filter.opaque)->st) {
423  av_freep(&filter->u.pes_filter.opaque);
424  }
425  }
426 
427  av_free(filter);
428  ts->pids[pid] = NULL;
429 }
430 
431 static int analyze(const uint8_t *buf, int size, int packet_size, int *index,
432  int probe)
433 {
434  int stat[TS_MAX_PACKET_SIZE];
435  int i;
436  int x = 0;
437  int best_score = 0;
438 
439  memset(stat, 0, packet_size * sizeof(int));
440 
441  for (x = i = 0; i < size - 3; i++) {
442  if (buf[i] == 0x47 &&
443  (!probe || (!(buf[i + 1] & 0x80) && (buf[i + 3] & 0x30)))) {
444  stat[x]++;
445  if (stat[x] > best_score) {
446  best_score = stat[x];
447  if (index)
448  *index = x;
449  }
450  }
451 
452  x++;
453  if (x == packet_size)
454  x = 0;
455  }
456 
457  return best_score;
458 }
459 
460 /* autodetect fec presence. Must have at least 1024 bytes */
461 static int get_packet_size(const uint8_t *buf, int size)
462 {
463  int score, fec_score, dvhs_score;
464 
465  if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
466  return AVERROR_INVALIDDATA;
467 
468  score = analyze(buf, size, TS_PACKET_SIZE, NULL, 0);
469  dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL, 0);
470  fec_score = analyze(buf, size, TS_FEC_PACKET_SIZE, NULL, 0);
471  av_log(NULL, AV_LOG_TRACE, "score: %d, dvhs_score: %d, fec_score: %d \n",
472  score, dvhs_score, fec_score);
473 
474  if (score > fec_score && score > dvhs_score)
475  return TS_PACKET_SIZE;
476  else if (dvhs_score > score && dvhs_score > fec_score)
477  return TS_DVHS_PACKET_SIZE;
478  else if (score < fec_score && dvhs_score < fec_score)
479  return TS_FEC_PACKET_SIZE;
480  else
481  return AVERROR_INVALIDDATA;
482 }
483 
484 typedef struct SectionHeader {
486  uint16_t id;
490 } SectionHeader;
491 
492 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
493 {
494  const uint8_t *p;
495  int c;
496 
497  p = *pp;
498  if (p >= p_end)
499  return AVERROR_INVALIDDATA;
500  c = *p++;
501  *pp = p;
502  return c;
503 }
504 
505 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
506 {
507  const uint8_t *p;
508  int c;
509 
510  p = *pp;
511  if ((p + 1) >= p_end)
512  return AVERROR_INVALIDDATA;
513  c = AV_RB16(p);
514  p += 2;
515  *pp = p;
516  return c;
517 }
518 
519 /* read and allocate a DVB string preceded by its length */
520 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
521 {
522  int len;
523  const uint8_t *p;
524  char *str;
525 
526  p = *pp;
527  len = get8(&p, p_end);
528  if (len < 0)
529  return NULL;
530  if ((p + len) > p_end)
531  return NULL;
532  str = av_malloc(len + 1);
533  if (!str)
534  return NULL;
535  memcpy(str, p, len);
536  str[len] = '\0';
537  p += len;
538  *pp = p;
539  return str;
540 }
541 
543  const uint8_t **pp, const uint8_t *p_end)
544 {
545  int val;
546 
547  val = get8(pp, p_end);
548  if (val < 0)
549  return val;
550  h->tid = val;
551  *pp += 2;
552  val = get16(pp, p_end);
553  if (val < 0)
554  return val;
555  h->id = val;
556  val = get8(pp, p_end);
557  if (val < 0)
558  return val;
559  h->version = (val >> 1) & 0x1f;
560  val = get8(pp, p_end);
561  if (val < 0)
562  return val;
563  h->sec_num = val;
564  val = get8(pp, p_end);
565  if (val < 0)
566  return val;
567  h->last_sec_num = val;
568  return 0;
569 }
570 
571 typedef struct StreamType {
572  uint32_t stream_type;
575 } StreamType;
576 
577 static const StreamType ISO_types[] = {
579  { 0x02, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
581  { 0x04, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_MP3 },
584  { 0x11, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC_LATM }, /* LATM syntax */
591  { 0 },
592 };
593 
594 static const StreamType HDMV_types[] = {
600  { 0x85, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD */
601  { 0x86, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD MASTER*/
603  { 0 },
604 };
605 
606 /* ATSC ? */
607 static const StreamType MISC_types[] = {
610  { 0 },
611 };
612 
613 static const StreamType REGD_types[] = {
614  { MKTAG('d', 'r', 'a', 'c'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC },
615  { MKTAG('A', 'C', '-', '3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
616  { MKTAG('B', 'S', 'S', 'D'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_S302M },
617  { MKTAG('D', 'T', 'S', '1'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
618  { MKTAG('D', 'T', 'S', '2'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
619  { MKTAG('D', 'T', 'S', '3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
620  { MKTAG('H', 'E', 'V', 'C'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_HEVC },
621  { MKTAG('V', 'C', '-', '1'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1 },
622  { MKTAG('O', 'p', 'u', 's'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_OPUS },
623  { 0 },
624 };
625 
626 /* descriptor present */
627 static const StreamType DESC_types[] = {
628  { 0x6a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 }, /* AC-3 descriptor */
629  { 0x7a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 }, /* E-AC-3 descriptor */
632  { 0x59, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
633  { 0 },
634 };
635 
637  uint32_t stream_type,
638  const StreamType *types)
639 {
640  for (; types->stream_type; types++)
641  if (stream_type == types->stream_type) {
642  st->codecpar->codec_type = types->codec_type;
643  st->codecpar->codec_id = types->codec_id;
644  return;
645  }
646 }
647 
649  uint32_t stream_type, uint32_t prog_reg_desc)
650 {
651  avpriv_set_pts_info(st, 33, 1, 90000);
652  st->priv_data = pes;
656  pes->st = st;
657  pes->stream_type = stream_type;
658 
659  av_log(pes->stream, AV_LOG_DEBUG,
660  "stream=%d stream_type=%x pid=%x prog_reg_desc=%.4s\n",
661  st->index, pes->stream_type, pes->pid, (char *)&prog_reg_desc);
662 
663  st->codecpar->codec_tag = pes->stream_type;
664 
665  mpegts_find_stream_type(st, pes->stream_type, ISO_types);
666  if (prog_reg_desc == AV_RL32("HDMV") &&
668  mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
669  if (pes->stream_type == 0x83) {
670  // HDMV TrueHD streams also contain an AC3 coded version of the
671  // audio track - add a second stream for this
672  AVStream *sub_st;
673  // priv_data cannot be shared between streams
674  PESContext *sub_pes = av_malloc(sizeof(*sub_pes));
675  if (!sub_pes)
676  return AVERROR(ENOMEM);
677  memcpy(sub_pes, pes, sizeof(*sub_pes));
678 
679  sub_st = avformat_new_stream(pes->stream, NULL);
680  if (!sub_st) {
681  av_free(sub_pes);
682  return AVERROR(ENOMEM);
683  }
684 
685  sub_st->id = pes->pid;
686  avpriv_set_pts_info(sub_st, 33, 1, 90000);
687  sub_st->priv_data = sub_pes;
689  sub_st->codecpar->codec_id = AV_CODEC_ID_AC3;
691  sub_pes->sub_st = pes->sub_st = sub_st;
692  }
693  }
694  if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
695  mpegts_find_stream_type(st, pes->stream_type, MISC_types);
696 
697  return 0;
698 }
699 
700 static void new_pes_packet(PESContext *pes, AVPacket *pkt)
701 {
702  av_init_packet(pkt);
703 
704  pkt->buf = pes->buffer;
705  pkt->data = pes->buffer->data;
706  pkt->size = pes->data_index;
707 
708  if (pes->total_size != MAX_PES_PAYLOAD &&
709  pes->pes_header_size + pes->data_index != pes->total_size +
710  PES_START_SIZE) {
711  av_log(pes->stream, AV_LOG_WARNING, "PES packet size mismatch\n");
712  pes->flags |= AV_PKT_FLAG_CORRUPT;
713  }
714  memset(pkt->data + pkt->size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
715 
716  // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID
717  if (pes->sub_st && pes->stream_type == 0x83 && pes->extended_stream_id == 0x76)
718  pkt->stream_index = pes->sub_st->index;
719  else
720  pkt->stream_index = pes->st->index;
721  pkt->pts = pes->pts;
722  pkt->dts = pes->dts;
723  /* store position of first TS packet of this PES packet */
724  pkt->pos = pes->ts_packet_pos;
725  pkt->flags = pes->flags;
726 
727  /* reset pts values */
728  pes->pts = AV_NOPTS_VALUE;
729  pes->dts = AV_NOPTS_VALUE;
730  pes->buffer = NULL;
731  pes->data_index = 0;
732  pes->flags = 0;
733 }
734 
736  const uint8_t *buf, int buf_size)
737 {
738  GetBitContext gb;
739  int au_start_flag = 0, au_end_flag = 0, ocr_flag = 0, idle_flag = 0;
740  int padding_flag = 0, padding_bits = 0, inst_bitrate_flag = 0;
741  int dts_flag = -1, cts_flag = -1;
742  int64_t dts = AV_NOPTS_VALUE, cts = AV_NOPTS_VALUE;
743  init_get_bits(&gb, buf, buf_size * 8);
744 
745  if (sl->use_au_start)
746  au_start_flag = get_bits1(&gb);
747  if (sl->use_au_end)
748  au_end_flag = get_bits1(&gb);
749  if (!sl->use_au_start && !sl->use_au_end)
750  au_start_flag = au_end_flag = 1;
751  if (sl->ocr_len > 0)
752  ocr_flag = get_bits1(&gb);
753  if (sl->use_idle)
754  idle_flag = get_bits1(&gb);
755  if (sl->use_padding)
756  padding_flag = get_bits1(&gb);
757  if (padding_flag)
758  padding_bits = get_bits(&gb, 3);
759 
760  if (!idle_flag && (!padding_flag || padding_bits != 0)) {
761  if (sl->packet_seq_num_len)
763  if (sl->degr_prior_len)
764  if (get_bits1(&gb))
765  skip_bits(&gb, sl->degr_prior_len);
766  if (ocr_flag)
767  skip_bits_long(&gb, sl->ocr_len);
768  if (au_start_flag) {
769  if (sl->use_rand_acc_pt)
770  get_bits1(&gb);
771  if (sl->au_seq_num_len > 0)
772  skip_bits_long(&gb, sl->au_seq_num_len);
773  if (sl->use_timestamps) {
774  dts_flag = get_bits1(&gb);
775  cts_flag = get_bits1(&gb);
776  }
777  }
778  if (sl->inst_bitrate_len)
779  inst_bitrate_flag = get_bits1(&gb);
780  if (dts_flag == 1)
781  dts = get_bits64(&gb, sl->timestamp_len);
782  if (cts_flag == 1)
783  cts = get_bits64(&gb, sl->timestamp_len);
784  if (sl->au_len > 0)
785  skip_bits_long(&gb, sl->au_len);
786  if (inst_bitrate_flag)
788  }
789 
790  if (dts != AV_NOPTS_VALUE)
791  pes->dts = dts;
792  if (cts != AV_NOPTS_VALUE)
793  pes->pts = cts;
794 
795  if (sl->timestamp_len && sl->timestamp_res)
797 
798  return (get_bits_count(&gb) + 7) >> 3;
799 }
800 
801 /* return non zero if a packet could be constructed */
803  const uint8_t *buf, int buf_size, int is_start,
804  int64_t pos)
805 {
806  PESContext *pes = filter->u.pes_filter.opaque;
807  MpegTSContext *ts = pes->ts;
808  const uint8_t *p;
809  int len, code;
810 
811  if (!ts->pkt)
812  return 0;
813 
814  if (is_start) {
815  if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
816  new_pes_packet(pes, ts->pkt);
817  ts->stop_parse = 1;
818  }
819  pes->state = MPEGTS_HEADER;
820  pes->data_index = 0;
821  pes->ts_packet_pos = pos;
822  }
823  p = buf;
824  while (buf_size > 0) {
825  switch (pes->state) {
826  case MPEGTS_HEADER:
827  len = PES_START_SIZE - pes->data_index;
828  if (len > buf_size)
829  len = buf_size;
830  memcpy(pes->header + pes->data_index, p, len);
831  pes->data_index += len;
832  p += len;
833  buf_size -= len;
834  if (pes->data_index == PES_START_SIZE) {
835  /* we got all the PES or section header. We can now
836  * decide */
837  if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
838  pes->header[2] == 0x01) {
839  /* it must be an MPEG-2 PES stream */
840  code = pes->header[3] | 0x100;
841  av_log(pes->stream, AV_LOG_TRACE, "pid=%x pes_code=%#x\n", pes->pid,
842  code);
843 
844  if ((pes->st && pes->st->discard == AVDISCARD_ALL &&
845  (!pes->sub_st ||
846  pes->sub_st->discard == AVDISCARD_ALL)) ||
847  code == 0x1be) /* padding_stream */
848  goto skip;
849 
850  /* stream not present in PMT */
851  if (!pes->st) {
852  pes->st = avformat_new_stream(ts->stream, NULL);
853  if (!pes->st)
854  return AVERROR(ENOMEM);
855  pes->st->id = pes->pid;
856  mpegts_set_stream_info(pes->st, pes, 0, 0);
857  }
858 
859  pes->total_size = AV_RB16(pes->header + 4);
860  /* NOTE: a zero total size means the PES size is
861  * unbounded */
862  if (!pes->total_size)
864 
865  /* allocate pes buffer */
866  pes->buffer = av_buffer_alloc(pes->total_size +
868  if (!pes->buffer)
869  return AVERROR(ENOMEM);
870 
871  if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
872  code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
873  code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
874  code != 0x1f8) { /* ITU-T Rec. H.222.1 type E stream */
875  pes->state = MPEGTS_PESHEADER;
876  if (pes->st->codecpar->codec_id == AV_CODEC_ID_NONE) {
877  av_log(pes->stream, AV_LOG_TRACE,
878  "pid=%x stream_type=%x probing\n",
879  pes->pid,
880  pes->stream_type);
882  }
883  } else {
884  pes->state = MPEGTS_PAYLOAD;
885  pes->data_index = 0;
886  }
887  } else {
888  /* otherwise, it should be a table */
889  /* skip packet */
890 skip:
891  pes->state = MPEGTS_SKIP;
892  continue;
893  }
894  }
895  break;
896  /**********************************************/
897  /* PES packing parsing */
898  case MPEGTS_PESHEADER:
899  len = PES_HEADER_SIZE - pes->data_index;
900  if (len < 0)
901  return AVERROR_INVALIDDATA;
902  if (len > buf_size)
903  len = buf_size;
904  memcpy(pes->header + pes->data_index, p, len);
905  pes->data_index += len;
906  p += len;
907  buf_size -= len;
908  if (pes->data_index == PES_HEADER_SIZE) {
909  pes->pes_header_size = pes->header[8] + 9;
911  }
912  break;
914  len = pes->pes_header_size - pes->data_index;
915  if (len < 0)
916  return AVERROR_INVALIDDATA;
917  if (len > buf_size)
918  len = buf_size;
919  memcpy(pes->header + pes->data_index, p, len);
920  pes->data_index += len;
921  p += len;
922  buf_size -= len;
923  if (pes->data_index == pes->pes_header_size) {
924  const uint8_t *r;
925  unsigned int flags, pes_ext, skip;
926 
927  flags = pes->header[7];
928  r = pes->header + 9;
929  pes->pts = AV_NOPTS_VALUE;
930  pes->dts = AV_NOPTS_VALUE;
931  if ((flags & 0xc0) == 0x80) {
932  pes->dts = pes->pts = ff_parse_pes_pts(r);
933  r += 5;
934  } else if ((flags & 0xc0) == 0xc0) {
935  pes->pts = ff_parse_pes_pts(r);
936  r += 5;
937  pes->dts = ff_parse_pes_pts(r);
938  r += 5;
939  }
940  pes->extended_stream_id = -1;
941  if (flags & 0x01) { /* PES extension */
942  pes_ext = *r++;
943  /* Skip PES private data, program packet sequence counter and P-STD buffer */
944  skip = (pes_ext >> 4) & 0xb;
945  skip += skip & 0x9;
946  r += skip;
947  if ((pes_ext & 0x41) == 0x01 &&
948  (r + 2) <= (pes->header + pes->pes_header_size)) {
949  /* PES extension 2 */
950  if ((r[0] & 0x7f) > 0 && (r[1] & 0x80) == 0)
951  pes->extended_stream_id = r[1];
952  }
953  }
954 
955  /* we got the full header. We parse it and get the payload */
956  pes->state = MPEGTS_PAYLOAD;
957  pes->data_index = 0;
958  if (pes->stream_type == 0x12 && buf_size > 0) {
959  int sl_header_bytes = read_sl_header(pes, &pes->sl, p,
960  buf_size);
961  pes->pes_header_size += sl_header_bytes;
962  p += sl_header_bytes;
963  buf_size -= sl_header_bytes;
964  }
965  }
966  break;
967  case MPEGTS_PAYLOAD:
968  if (buf_size > 0 && pes->buffer) {
969  if (pes->data_index > 0 &&
970  pes->data_index + buf_size > pes->total_size) {
971  new_pes_packet(pes, ts->pkt);
973  pes->buffer = av_buffer_alloc(pes->total_size +
975  if (!pes->buffer)
976  return AVERROR(ENOMEM);
977  ts->stop_parse = 1;
978  } else if (pes->data_index == 0 &&
979  buf_size > pes->total_size) {
980  // pes packet size is < ts size packet and pes data is padded with 0xff
981  // not sure if this is legal in ts but see issue #2392
982  buf_size = pes->total_size;
983  }
984  memcpy(pes->buffer->data + pes->data_index, p, buf_size);
985  pes->data_index += buf_size;
986  }
987  buf_size = 0;
988  /* emit complete packets with known packet size
989  * decreases demuxer delay for infrequent packets like subtitles from
990  * a couple of seconds to milliseconds for properly muxed files.
991  * total_size is the number of bytes following pes_packet_length
992  * in the pes header, i.e. not counting the first PES_START_SIZE bytes */
993  if (!ts->stop_parse && pes->total_size < MAX_PES_PAYLOAD &&
994  pes->pes_header_size + pes->data_index == pes->total_size + PES_START_SIZE) {
995  ts->stop_parse = 1;
996  new_pes_packet(pes, ts->pkt);
997  }
998  break;
999  case MPEGTS_SKIP:
1000  buf_size = 0;
1001  break;
1002  }
1003  }
1004 
1005  return 0;
1006 }
1007 
1008 static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
1009 {
1010  MpegTSFilter *tss;
1011  PESContext *pes;
1012 
1013  /* if no pid found, then add a pid context */
1014  pes = av_mallocz(sizeof(PESContext));
1015  if (!pes)
1016  return 0;
1017  pes->ts = ts;
1018  pes->stream = ts->stream;
1019  pes->pid = pid;
1020  pes->pcr_pid = pcr_pid;
1021  pes->state = MPEGTS_SKIP;
1022  pes->pts = AV_NOPTS_VALUE;
1023  pes->dts = AV_NOPTS_VALUE;
1024  tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
1025  if (!tss) {
1026  av_free(pes);
1027  return 0;
1028  }
1029  return pes;
1030 }
1031 
1032 #define MAX_LEVEL 4
1033 typedef struct MP4DescrParseContext {
1040  int level;
1042 
1044  const uint8_t *buf, unsigned size,
1045  Mp4Descr *descr, int max_descr_count)
1046 {
1047  int ret;
1048  if (size > (1 << 30))
1049  return AVERROR_INVALIDDATA;
1050 
1051  if ((ret = ffio_init_context(&d->pb, (unsigned char *)buf, size, 0,
1052  NULL, NULL, NULL, NULL)) < 0)
1053  return ret;
1054 
1055  d->s = s;
1056  d->level = 0;
1057  d->descr_count = 0;
1058  d->descr = descr;
1059  d->active_descr = NULL;
1060  d->max_descr_count = max_descr_count;
1061 
1062  return 0;
1063 }
1064 
1065 static void update_offsets(AVIOContext *pb, int64_t *off, int *len)
1066 {
1067  int64_t new_off = avio_tell(pb);
1068  (*len) -= new_off - *off;
1069  *off = new_off;
1070 }
1071 
1072 static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
1073  int target_tag);
1074 
1075 static int parse_mp4_descr_arr(MP4DescrParseContext *d, int64_t off, int len)
1076 {
1077  while (len > 0) {
1078  int ret = parse_mp4_descr(d, off, len, 0);
1079  if (ret < 0)
1080  return ret;
1081  update_offsets(&d->pb, &off, &len);
1082  }
1083  return 0;
1084 }
1085 
1086 static int parse_MP4IODescrTag(MP4DescrParseContext *d, int64_t off, int len)
1087 {
1088  avio_rb16(&d->pb); // ID
1089  avio_r8(&d->pb);
1090  avio_r8(&d->pb);
1091  avio_r8(&d->pb);
1092  avio_r8(&d->pb);
1093  avio_r8(&d->pb);
1094  update_offsets(&d->pb, &off, &len);
1095  return parse_mp4_descr_arr(d, off, len);
1096 }
1097 
1098 static int parse_MP4ODescrTag(MP4DescrParseContext *d, int64_t off, int len)
1099 {
1100  int id_flags;
1101  if (len < 2)
1102  return 0;
1103  id_flags = avio_rb16(&d->pb);
1104  if (!(id_flags & 0x0020)) { // URL_Flag
1105  update_offsets(&d->pb, &off, &len);
1106  return parse_mp4_descr_arr(d, off, len); // ES_Descriptor[]
1107  } else {
1108  return 0;
1109  }
1110 }
1111 
1112 static int parse_MP4ESDescrTag(MP4DescrParseContext *d, int64_t off, int len)
1113 {
1114  int es_id = 0;
1115  int ret = 0;
1116 
1117  if (d->descr_count >= d->max_descr_count)
1118  return AVERROR_INVALIDDATA;
1119  ff_mp4_parse_es_descr(&d->pb, &es_id);
1120  d->active_descr = d->descr + (d->descr_count++);
1121 
1122  d->active_descr->es_id = es_id;
1123  update_offsets(&d->pb, &off, &len);
1124  if ((ret = parse_mp4_descr(d, off, len, MP4DecConfigDescrTag)) < 0)
1125  return ret;
1126  update_offsets(&d->pb, &off, &len);
1127  if (len > 0)
1128  ret = parse_mp4_descr(d, off, len, MP4SLDescrTag);
1129  d->active_descr = NULL;
1130  return ret;
1131 }
1132 
1134  int len)
1135 {
1136  Mp4Descr *descr = d->active_descr;
1137  if (!descr)
1138  return AVERROR_INVALIDDATA;
1140  if (!descr->dec_config_descr)
1141  return AVERROR(ENOMEM);
1142  descr->dec_config_descr_len = len;
1143  avio_read(&d->pb, descr->dec_config_descr, len);
1144  return 0;
1145 }
1146 
1147 static int parse_MP4SLDescrTag(MP4DescrParseContext *d, int64_t off, int len)
1148 {
1149  Mp4Descr *descr = d->active_descr;
1150  int predefined;
1151  if (!descr)
1152  return AVERROR_INVALIDDATA;
1153 
1154  predefined = avio_r8(&d->pb);
1155  if (!predefined) {
1156  int lengths;
1157  int flags = avio_r8(&d->pb);
1158  descr->sl.use_au_start = !!(flags & 0x80);
1159  descr->sl.use_au_end = !!(flags & 0x40);
1160  descr->sl.use_rand_acc_pt = !!(flags & 0x20);
1161  descr->sl.use_padding = !!(flags & 0x08);
1162  descr->sl.use_timestamps = !!(flags & 0x04);
1163  descr->sl.use_idle = !!(flags & 0x02);
1164  descr->sl.timestamp_res = avio_rb32(&d->pb);
1165  avio_rb32(&d->pb);
1166  descr->sl.timestamp_len = avio_r8(&d->pb);
1167  descr->sl.ocr_len = avio_r8(&d->pb);
1168  descr->sl.au_len = avio_r8(&d->pb);
1169  descr->sl.inst_bitrate_len = avio_r8(&d->pb);
1170  lengths = avio_rb16(&d->pb);
1171  descr->sl.degr_prior_len = lengths >> 12;
1172  descr->sl.au_seq_num_len = (lengths >> 7) & 0x1f;
1173  descr->sl.packet_seq_num_len = (lengths >> 2) & 0x1f;
1174  if (descr->sl.timestamp_len >= 64 ||
1175  descr->sl.ocr_len >= 64 ||
1176  descr->sl.au_len >= 32) {
1177  return AVERROR_INVALIDDATA;
1178  }
1179  } else {
1180  avpriv_report_missing_feature(d->s, "Predefined SLConfigDescriptor");
1181  }
1182  return 0;
1183 }
1184 
1185 static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
1186  int target_tag)
1187 {
1188  int tag;
1189  int len1 = ff_mp4_read_descr(d->s, &d->pb, &tag);
1190  int ret = 0;
1191 
1192  update_offsets(&d->pb, &off, &len);
1193  if (len < 0 || len1 > len || len1 <= 0) {
1194  av_log(d->s, AV_LOG_ERROR,
1195  "Tag %x length violation new length %d bytes remaining %d\n",
1196  tag, len1, len);
1197  return AVERROR_INVALIDDATA;
1198  }
1199 
1200  if (d->level++ >= MAX_LEVEL) {
1201  av_log(d->s, AV_LOG_ERROR, "Maximum MP4 descriptor level exceeded\n");
1202  ret = AVERROR_INVALIDDATA;
1203  goto done;
1204  }
1205 
1206  if (target_tag && tag != target_tag) {
1207  av_log(d->s, AV_LOG_ERROR, "Found tag %x expected %x\n", tag,
1208  target_tag);
1209  ret = AVERROR_INVALIDDATA;
1210  goto done;
1211  }
1212 
1213  switch (tag) {
1214  case MP4IODescrTag:
1215  ret = parse_MP4IODescrTag(d, off, len1);
1216  break;
1217  case MP4ODescrTag:
1218  ret = parse_MP4ODescrTag(d, off, len1);
1219  break;
1220  case MP4ESDescrTag:
1221  ret = parse_MP4ESDescrTag(d, off, len1);
1222  break;
1223  case MP4DecConfigDescrTag:
1224  ret = parse_MP4DecConfigDescrTag(d, off, len1);
1225  break;
1226  case MP4SLDescrTag:
1227  ret = parse_MP4SLDescrTag(d, off, len1);
1228  break;
1229  }
1230 
1231 
1232 done:
1233  d->level--;
1234  avio_seek(&d->pb, off + len1, SEEK_SET);
1235  return ret;
1236 }
1237 
1238 static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size,
1239  Mp4Descr *descr, int *descr_count, int max_descr_count)
1240 {
1242  int ret;
1243 
1244  ret = init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count);
1245  if (ret < 0)
1246  return ret;
1247 
1248  ret = parse_mp4_descr(&d, avio_tell(&d.pb), size, MP4IODescrTag);
1249 
1250  *descr_count = d.descr_count;
1251  return ret;
1252 }
1253 
1254 static int mp4_read_od(AVFormatContext *s, const uint8_t *buf, unsigned size,
1255  Mp4Descr *descr, int *descr_count, int max_descr_count)
1256 {
1258  int ret;
1259 
1260  ret = init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count);
1261  if (ret < 0)
1262  return ret;
1263 
1264  ret = parse_mp4_descr_arr(&d, avio_tell(&d.pb), size);
1265 
1266  *descr_count = d.descr_count;
1267  return ret;
1268 }
1269 
1270 static void m4sl_cb(MpegTSFilter *filter, const uint8_t *section,
1271  int section_len)
1272 {
1273  MpegTSContext *ts = filter->u.section_filter.opaque;
1274  MpegTSSectionFilter *tssf = &filter->u.section_filter;
1275  SectionHeader h;
1276  const uint8_t *p, *p_end;
1277  AVIOContext pb;
1278  int mp4_descr_count = 0;
1279  Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = { { 0 } };
1280  int i, pid;
1281  AVFormatContext *s = ts->stream;
1282 
1283  p_end = section + section_len - 4;
1284  p = section;
1285  if (parse_section_header(&h, &p, p_end) < 0)
1286  return;
1287  if (h.tid != M4OD_TID)
1288  return;
1289  if (h.version == tssf->last_ver)
1290  return;
1291  tssf->last_ver = h.version;
1292 
1293  mp4_read_od(s, p, (unsigned) (p_end - p), mp4_descr, &mp4_descr_count,
1295 
1296  for (pid = 0; pid < NB_PID_MAX; pid++) {
1297  if (!ts->pids[pid])
1298  continue;
1299  for (i = 0; i < mp4_descr_count; i++) {
1300  PESContext *pes;
1301  AVStream *st;
1302  if (ts->pids[pid]->es_id != mp4_descr[i].es_id)
1303  continue;
1304  if (!(ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES)) {
1305  av_log(s, AV_LOG_ERROR, "pid %x is not PES\n", pid);
1306  continue;
1307  }
1308  pes = ts->pids[pid]->u.pes_filter.opaque;
1309  st = pes->st;
1310  if (!st)
1311  continue;
1312 
1313  pes->sl = mp4_descr[i].sl;
1314 
1315  ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
1316  mp4_descr[i].dec_config_descr_len, 0,
1317  NULL, NULL, NULL, NULL);
1318  ff_mp4_read_dec_config_descr(s, st, &pb);
1319  if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
1320  st->codecpar->extradata_size > 0)
1321  st->need_parsing = 0;
1322  if (st->codecpar->codec_id == AV_CODEC_ID_H264 &&
1323  st->codecpar->extradata_size > 0)
1324  st->need_parsing = 0;
1325 
1327  }
1328  }
1329  for (i = 0; i < mp4_descr_count; i++)
1330  av_free(mp4_descr[i].dec_config_descr);
1331 }
1332 
1334  1, 0, 1, 1, 2, 2, 2, 3, 3
1335 };
1336 
1337 static const uint8_t opus_stream_cnt[9] = {
1338  1, 1, 1, 2, 2, 3, 4, 4, 5,
1339 };
1340 
1341 static const uint8_t opus_channel_map[8][8] = {
1342  { 0 },
1343  { 0,1 },
1344  { 0,2,1 },
1345  { 0,1,2,3 },
1346  { 0,4,1,2,3 },
1347  { 0,4,1,2,3,5 },
1348  { 0,4,1,2,3,5,6 },
1349  { 0,6,1,2,3,4,5,7 },
1350 };
1351 
1353  const uint8_t **pp, const uint8_t *desc_list_end,
1354  Mp4Descr *mp4_descr, int mp4_descr_count, int pid,
1355  MpegTSContext *ts)
1356 {
1357  const uint8_t *desc_end;
1358  int desc_len, desc_tag, desc_es_id, ext_desc_tag, channels, channel_config_code;
1359  char language[252];
1360  int i;
1361 
1362  desc_tag = get8(pp, desc_list_end);
1363  if (desc_tag < 0)
1364  return AVERROR_INVALIDDATA;
1365  desc_len = get8(pp, desc_list_end);
1366  if (desc_len < 0)
1367  return AVERROR_INVALIDDATA;
1368  desc_end = *pp + desc_len;
1369  if (desc_end > desc_list_end)
1370  return AVERROR_INVALIDDATA;
1371 
1372  av_log(fc, AV_LOG_TRACE, "tag: 0x%02x len=%d\n", desc_tag, desc_len);
1373 
1374  if (st->codecpar->codec_id == AV_CODEC_ID_NONE &&
1375  stream_type == STREAM_TYPE_PRIVATE_DATA)
1376  mpegts_find_stream_type(st, desc_tag, DESC_types);
1377 
1378  switch (desc_tag) {
1379  case 0x1E: /* SL descriptor */
1380  desc_es_id = get16(pp, desc_end);
1381  if (desc_es_id < 0)
1382  break;
1383  if (ts && ts->pids[pid])
1384  ts->pids[pid]->es_id = desc_es_id;
1385  for (i = 0; i < mp4_descr_count; i++)
1386  if (mp4_descr[i].dec_config_descr_len &&
1387  mp4_descr[i].es_id == desc_es_id) {
1388  AVIOContext pb;
1389  ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
1390  mp4_descr[i].dec_config_descr_len, 0,
1391  NULL, NULL, NULL, NULL);
1392  ff_mp4_read_dec_config_descr(fc, st, &pb);
1393  if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
1394  st->codecpar->extradata_size > 0)
1395  st->need_parsing = 0;
1397  mpegts_open_section_filter(ts, pid, m4sl_cb, ts, 1);
1398  }
1399  break;
1400  case 0x1F: /* FMC descriptor */
1401  if (get16(pp, desc_end) < 0)
1402  break;
1403  if (mp4_descr_count > 0 &&
1405  mp4_descr->dec_config_descr_len && mp4_descr->es_id == pid) {
1406  AVIOContext pb;
1407  ffio_init_context(&pb, mp4_descr->dec_config_descr,
1408  mp4_descr->dec_config_descr_len, 0,
1409  NULL, NULL, NULL, NULL);
1410  ff_mp4_read_dec_config_descr(fc, st, &pb);
1411  if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
1412  st->codecpar->extradata_size > 0)
1413  st->need_parsing = 0;
1414  }
1415  break;
1416  case 0x56: /* DVB teletext descriptor */
1417  language[0] = get8(pp, desc_end);
1418  language[1] = get8(pp, desc_end);
1419  language[2] = get8(pp, desc_end);
1420  language[3] = 0;
1421  av_dict_set(&st->metadata, "language", language, 0);
1422  break;
1423  case 0x59: /* subtitling descriptor */
1424  language[0] = get8(pp, desc_end);
1425  language[1] = get8(pp, desc_end);
1426  language[2] = get8(pp, desc_end);
1427  language[3] = 0;
1428  /* hearing impaired subtitles detection */
1429  switch (get8(pp, desc_end)) {
1430  case 0x20: /* DVB subtitles (for the hard of hearing) with no monitor aspect ratio criticality */
1431  case 0x21: /* DVB subtitles (for the hard of hearing) for display on 4:3 aspect ratio monitor */
1432  case 0x22: /* DVB subtitles (for the hard of hearing) for display on 16:9 aspect ratio monitor */
1433  case 0x23: /* DVB subtitles (for the hard of hearing) for display on 2.21:1 aspect ratio monitor */
1434  case 0x24: /* DVB subtitles (for the hard of hearing) for display on a high definition monitor */
1435  case 0x25: /* DVB subtitles (for the hard of hearing) with plano-stereoscopic disparity for display on a high definition monitor */
1437  break;
1438  }
1439  if (st->codecpar->extradata) {
1440  if (st->codecpar->extradata_size == 4 &&
1441  memcmp(st->codecpar->extradata, *pp, 4))
1442  avpriv_request_sample(fc, "DVB sub with multiple IDs");
1443  } else {
1445  if (st->codecpar->extradata) {
1446  st->codecpar->extradata_size = 4;
1447  memcpy(st->codecpar->extradata, *pp, 4);
1448  }
1449  }
1450  *pp += 4;
1451  av_dict_set(&st->metadata, "language", language, 0);
1452  break;
1453  case 0x0a: /* ISO 639 language descriptor */
1454  for (i = 0; i + 4 <= desc_len; i += 4) {
1455  language[i + 0] = get8(pp, desc_end);
1456  language[i + 1] = get8(pp, desc_end);
1457  language[i + 2] = get8(pp, desc_end);
1458  language[i + 3] = ',';
1459  switch (get8(pp, desc_end)) {
1460  case 0x01:
1462  break;
1463  case 0x02:
1465  break;
1466  case 0x03:
1468  break;
1469  }
1470  }
1471  if (i && language[0]) {
1472  language[i - 1] = 0;
1473  av_dict_set(&st->metadata, "language", language, 0);
1474  }
1475  break;
1476  case 0x05: /* registration descriptor */
1477  st->codecpar->codec_tag = bytestream_get_le32(pp);
1478  av_log(fc, AV_LOG_TRACE, "reg_desc=%.4s\n", (char *)&st->codecpar->codec_tag);
1479  if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
1480  mpegts_find_stream_type(st, st->codecpar->codec_tag, REGD_types);
1481  break;
1482  case 0x7f: /* DVB extension descriptor */
1483  ext_desc_tag = get8(pp, desc_end);
1484  if (ext_desc_tag < 0)
1485  return AVERROR_INVALIDDATA;
1486  if (st->codecpar->codec_id == AV_CODEC_ID_OPUS &&
1487  ext_desc_tag == 0x80) { /* User defined (provisional Opus) */
1488  if (!st->codecpar->extradata) {
1491  if (!st->codecpar->extradata)
1492  return AVERROR(ENOMEM);
1493 
1496 
1497  channel_config_code = get8(pp, desc_end);
1498  if (channel_config_code < 0)
1499  return AVERROR_INVALIDDATA;
1500  if (channel_config_code <= 0x8) {
1501  st->codecpar->extradata[9] = channels = channel_config_code ? channel_config_code : 2;
1502  st->codecpar->extradata[18] = channel_config_code ? (channels > 2) : 255;
1503  st->codecpar->extradata[19] = opus_stream_cnt[channel_config_code];
1504  st->codecpar->extradata[20] = opus_coupled_stream_cnt[channel_config_code];
1505  memcpy(&st->codecpar->extradata[21], opus_channel_map[channels - 1], channels);
1506  } else {
1507  avpriv_request_sample(fc, "Opus in MPEG-TS - channel_config_code > 0x8");
1508  }
1510  }
1511  }
1512  break;
1513  default:
1514  break;
1515  }
1516  *pp = desc_end;
1517  return 0;
1518 }
1519 
1520 static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1521 {
1522  MpegTSContext *ts = filter->u.section_filter.opaque;
1523  MpegTSSectionFilter *tssf = &filter->u.section_filter;
1524  SectionHeader h1, *h = &h1;
1525  PESContext *pes;
1526  AVStream *st;
1527  const uint8_t *p, *p_end, *desc_list_end;
1528  int program_info_length, pcr_pid, pid, stream_type;
1529  int desc_list_len;
1530  uint32_t prog_reg_desc = 0; /* registration descriptor */
1531 
1532  int mp4_descr_count = 0;
1533  Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = { { 0 } };
1534  int i;
1535 
1536  av_log(ts->stream, AV_LOG_TRACE, "PMT: len %i\n", section_len);
1537  hex_dump_debug(ts->stream, section, section_len);
1538 
1539  p_end = section + section_len - 4;
1540  p = section;
1541  if (parse_section_header(h, &p, p_end) < 0)
1542  return;
1543  if (h->version == tssf->last_ver)
1544  return;
1545  tssf->last_ver = h->version;
1546 
1547  av_log(ts->stream, AV_LOG_TRACE, "sid=0x%x sec_num=%d/%d\n",
1548  h->id, h->sec_num, h->last_sec_num);
1549 
1550  if (h->tid != PMT_TID)
1551  return;
1552 
1553  clear_program(ts, h->id);
1554  pcr_pid = get16(&p, p_end);
1555  if (pcr_pid < 0)
1556  return;
1557  pcr_pid &= 0x1fff;
1558  add_pid_to_pmt(ts, h->id, pcr_pid);
1559 
1560  av_log(ts->stream, AV_LOG_TRACE, "pcr_pid=0x%x\n", pcr_pid);
1561 
1562  program_info_length = get16(&p, p_end);
1563  if (program_info_length < 0)
1564  return;
1565  program_info_length &= 0xfff;
1566  while (program_info_length >= 2) {
1567  uint8_t tag, len;
1568  tag = get8(&p, p_end);
1569  len = get8(&p, p_end);
1570 
1571  av_log(ts->stream, AV_LOG_TRACE, "program tag: 0x%02x len=%d\n", tag, len);
1572 
1573  if (len > program_info_length - 2)
1574  // something else is broken, exit the program_descriptors_loop
1575  break;
1576  program_info_length -= len + 2;
1577  if (tag == 0x1d) { // IOD descriptor
1578  get8(&p, p_end); // scope
1579  get8(&p, p_end); // label
1580  len -= 2;
1581  mp4_read_iods(ts->stream, p, len, mp4_descr + mp4_descr_count,
1582  &mp4_descr_count, MAX_MP4_DESCR_COUNT);
1583  } else if (tag == 0x05 && len >= 4) { // registration descriptor
1584  prog_reg_desc = bytestream_get_le32(&p);
1585  len -= 4;
1586  }
1587  p += len;
1588  }
1589  p += program_info_length;
1590  if (p >= p_end)
1591  goto out;
1592 
1593  // stop parsing after pmt, we found header
1594  if (!ts->stream->nb_streams)
1595  ts->stop_parse = 1;
1596 
1597 
1598  for (;;) {
1599  st = 0;
1600  pes = NULL;
1601  stream_type = get8(&p, p_end);
1602  if (stream_type < 0)
1603  break;
1604  pid = get16(&p, p_end);
1605  if (pid < 0)
1606  break;
1607  pid &= 0x1fff;
1608 
1609  /* now create stream */
1610  if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
1611  pes = ts->pids[pid]->u.pes_filter.opaque;
1612  if (!pes->st) {
1613  pes->st = avformat_new_stream(pes->stream, NULL);
1614  pes->st->id = pes->pid;
1615  }
1616  st = pes->st;
1617  } else if (stream_type != 0x13) {
1618  if (ts->pids[pid])
1619  mpegts_close_filter(ts, ts->pids[pid]); // wrongly added sdt filter probably
1620  pes = add_pes_stream(ts, pid, pcr_pid);
1621  if (pes) {
1622  st = avformat_new_stream(pes->stream, NULL);
1623  st->id = pes->pid;
1624  }
1625  } else {
1626  int idx = ff_find_stream_index(ts->stream, pid);
1627  if (idx >= 0) {
1628  st = ts->stream->streams[idx];
1629  } else {
1630  st = avformat_new_stream(ts->stream, NULL);
1631  st->id = pid;
1633  }
1634  }
1635 
1636  if (!st)
1637  goto out;
1638 
1639  if (pes && !pes->stream_type)
1640  mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
1641 
1642  add_pid_to_pmt(ts, h->id, pid);
1643 
1645 
1646  desc_list_len = get16(&p, p_end);
1647  if (desc_list_len < 0)
1648  break;
1649  desc_list_len &= 0xfff;
1650  desc_list_end = p + desc_list_len;
1651  if (desc_list_end > p_end)
1652  break;
1653  for (;;) {
1654  if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p,
1655  desc_list_end, mp4_descr,
1656  mp4_descr_count, pid, ts) < 0)
1657  break;
1658 
1659  if (pes && prog_reg_desc == AV_RL32("HDMV") &&
1660  stream_type == 0x83 && pes->sub_st) {
1662  pes->sub_st->index);
1663  pes->sub_st->codecpar->codec_tag = st->codecpar->codec_tag;
1664  }
1665  }
1666  p = desc_list_end;
1667  }
1668 
1669 out:
1670  for (i = 0; i < mp4_descr_count; i++)
1671  av_free(mp4_descr[i].dec_config_descr);
1672 }
1673 
1674 static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1675 {
1676  MpegTSContext *ts = filter->u.section_filter.opaque;
1677  MpegTSSectionFilter *tssf = &filter->u.section_filter;
1678  SectionHeader h1, *h = &h1;
1679  const uint8_t *p, *p_end;
1680  int sid, pmt_pid;
1681 
1682  av_log(ts->stream, AV_LOG_TRACE, "PAT:\n");
1683  hex_dump_debug(ts->stream, section, section_len);
1684 
1685  p_end = section + section_len - 4;
1686  p = section;
1687  if (parse_section_header(h, &p, p_end) < 0)
1688  return;
1689  if (h->tid != PAT_TID)
1690  return;
1691  if (h->version == tssf->last_ver)
1692  return;
1693  tssf->last_ver = h->version;
1694 
1695  clear_programs(ts);
1696  for (;;) {
1697  sid = get16(&p, p_end);
1698  if (sid < 0)
1699  break;
1700  pmt_pid = get16(&p, p_end);
1701  if (pmt_pid < 0)
1702  break;
1703  pmt_pid &= 0x1fff;
1704 
1705  av_log(ts->stream, AV_LOG_TRACE, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
1706 
1707  if (sid == 0x0000) {
1708  /* NIT info */
1709  } else {
1710  av_new_program(ts->stream, sid);
1711  if (ts->pids[pmt_pid])
1712  mpegts_close_filter(ts, ts->pids[pmt_pid]);
1713  mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
1714  add_pat_entry(ts, sid);
1715  add_pid_to_pmt(ts, sid, 0); // add pat pid to program
1716  add_pid_to_pmt(ts, sid, pmt_pid);
1717  }
1718  }
1719 }
1720 
1721 static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1722 {
1723  MpegTSContext *ts = filter->u.section_filter.opaque;
1724  MpegTSSectionFilter *tssf = &filter->u.section_filter;
1725  SectionHeader h1, *h = &h1;
1726  const uint8_t *p, *p_end, *desc_list_end, *desc_end;
1727  int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
1728  char *name, *provider_name;
1729 
1730  av_log(ts->stream, AV_LOG_TRACE, "SDT:\n");
1731  hex_dump_debug(ts->stream, section, section_len);
1732 
1733  p_end = section + section_len - 4;
1734  p = section;
1735  if (parse_section_header(h, &p, p_end) < 0)
1736  return;
1737  if (h->tid != SDT_TID)
1738  return;
1739  if (h->version == tssf->last_ver)
1740  return;
1741  tssf->last_ver = h->version;
1742 
1743  onid = get16(&p, p_end);
1744  if (onid < 0)
1745  return;
1746  val = get8(&p, p_end);
1747  if (val < 0)
1748  return;
1749  for (;;) {
1750  sid = get16(&p, p_end);
1751  if (sid < 0)
1752  break;
1753  val = get8(&p, p_end);
1754  if (val < 0)
1755  break;
1756  desc_list_len = get16(&p, p_end);
1757  if (desc_list_len < 0)
1758  break;
1759  desc_list_len &= 0xfff;
1760  desc_list_end = p + desc_list_len;
1761  if (desc_list_end > p_end)
1762  break;
1763  for (;;) {
1764  desc_tag = get8(&p, desc_list_end);
1765  if (desc_tag < 0)
1766  break;
1767  desc_len = get8(&p, desc_list_end);
1768  desc_end = p + desc_len;
1769  if (desc_end > desc_list_end)
1770  break;
1771 
1772  av_log(ts->stream, AV_LOG_TRACE, "tag: 0x%02x len=%d\n",
1773  desc_tag, desc_len);
1774 
1775  switch (desc_tag) {
1776  case 0x48:
1777  service_type = get8(&p, p_end);
1778  if (service_type < 0)
1779  break;
1780  provider_name = getstr8(&p, p_end);
1781  if (!provider_name)
1782  break;
1783  name = getstr8(&p, p_end);
1784  if (name) {
1785  AVProgram *program = av_new_program(ts->stream, sid);
1786  if (program) {
1787  av_dict_set(&program->metadata, "service_name", name, 0);
1788  av_dict_set(&program->metadata, "service_provider",
1789  provider_name, 0);
1790  }
1791  }
1792  av_free(name);
1793  av_free(provider_name);
1794  break;
1795  default:
1796  break;
1797  }
1798  p = desc_end;
1799  }
1800  p = desc_list_end;
1801  }
1802 }
1803 
1804 /* handle one TS packet */
1805 static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
1806 {
1807  MpegTSFilter *tss;
1808  int len, pid, cc, expected_cc, cc_ok, afc, is_start, is_discontinuity,
1809  has_adaptation, has_payload;
1810  const uint8_t *p, *p_end;
1811  int64_t pos;
1812 
1813  pid = AV_RB16(packet + 1) & 0x1fff;
1814  if (pid && discard_pid(ts, pid))
1815  return 0;
1816  is_start = packet[1] & 0x40;
1817  tss = ts->pids[pid];
1818  if (ts->auto_guess && !tss && is_start) {
1819  add_pes_stream(ts, pid, -1);
1820  tss = ts->pids[pid];
1821  }
1822  if (!tss)
1823  return 0;
1824 
1825  afc = (packet[3] >> 4) & 3;
1826  if (afc == 0) /* reserved value */
1827  return 0;
1828  has_adaptation = afc & 2;
1829  has_payload = afc & 1;
1830  is_discontinuity = has_adaptation &&
1831  packet[4] != 0 && /* with length > 0 */
1832  (packet[5] & 0x80); /* and discontinuity indicated */
1833 
1834  /* continuity check (currently not used) */
1835  cc = (packet[3] & 0xf);
1836  expected_cc = has_payload ? (tss->last_cc + 1) & 0x0f : tss->last_cc;
1837  cc_ok = pid == 0x1FFF || // null packet PID
1838  is_discontinuity ||
1839  tss->last_cc < 0 ||
1840  expected_cc == cc;
1841 
1842  tss->last_cc = cc;
1843  if (!cc_ok) {
1845  "Continuity check failed for pid %d expected %d got %d\n",
1846  pid, expected_cc, cc);
1847  if (tss->type == MPEGTS_PES) {
1848  PESContext *pc = tss->u.pes_filter.opaque;
1849  pc->flags |= AV_PKT_FLAG_CORRUPT;
1850  }
1851  }
1852 
1853  if (!has_payload)
1854  return 0;
1855  p = packet + 4;
1856  if (has_adaptation) {
1857  /* skip adaptation field */
1858  p += p[0] + 1;
1859  }
1860  /* if past the end of packet, ignore */
1861  p_end = packet + TS_PACKET_SIZE;
1862  if (p >= p_end)
1863  return 0;
1864 
1865  pos = avio_tell(ts->stream->pb);
1866  MOD_UNLIKELY(ts->pos47, pos, ts->raw_packet_size, ts->pos);
1867 
1868  if (tss->type == MPEGTS_SECTION) {
1869  if (is_start) {
1870  /* pointer field present */
1871  len = *p++;
1872  if (p + len > p_end)
1873  return 0;
1874  if (len && cc_ok) {
1875  /* write remaining section bytes */
1876  write_section_data(ts, tss,
1877  p, len, 0);
1878  /* check whether filter has been closed */
1879  if (!ts->pids[pid])
1880  return 0;
1881  }
1882  p += len;
1883  if (p < p_end) {
1884  write_section_data(ts, tss,
1885  p, p_end - p, 1);
1886  }
1887  } else {
1888  if (cc_ok) {
1889  write_section_data(ts, tss,
1890  p, p_end - p, 0);
1891  }
1892  }
1893  } else {
1894  int ret;
1895  // Note: The position here points actually behind the current packet.
1896  if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
1897  pos - ts->raw_packet_size)) < 0)
1898  return ret;
1899  }
1900 
1901  return 0;
1902 }
1903 
1904 /* XXX: try to find a better synchro over several packets (use
1905  * get_packet_size() ?) */
1907 {
1908  MpegTSContext *ts = s->priv_data;
1909  AVIOContext *pb = s->pb;
1910  int c, i;
1911 
1912  for (i = 0; i < ts->resync_size; i++) {
1913  c = avio_r8(pb);
1914  if (pb->eof_reached)
1915  return AVERROR_EOF;
1916  if (c == 0x47) {
1917  avio_seek(pb, -1, SEEK_CUR);
1918  return 0;
1919  }
1920  }
1921  av_log(s, AV_LOG_ERROR,
1922  "max resync size reached, could not find sync byte\n");
1923  /* no sync found */
1924  return AVERROR_INVALIDDATA;
1925 }
1926 
1927 /* return AVERROR_something if error or EOF. Return 0 if OK. */
1928 static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size,
1929  const uint8_t **data)
1930 {
1931  AVIOContext *pb = s->pb;
1932  int len;
1933 
1934  for (;;) {
1935  len = ffio_read_indirect(pb, buf, TS_PACKET_SIZE, data);
1936  if (len != TS_PACKET_SIZE)
1937  return len < 0 ? len : AVERROR_EOF;
1938  /* check packet sync byte */
1939  if ((*data)[0] != 0x47) {
1940  /* find a new packet start */
1941  avio_seek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1942  if (mpegts_resync(s) < 0)
1943  return AVERROR(EAGAIN);
1944  else
1945  continue;
1946  } else {
1947  break;
1948  }
1949  }
1950  return 0;
1951 }
1952 
1953 static void finished_reading_packet(AVFormatContext *s, int raw_packet_size)
1954 {
1955  AVIOContext *pb = s->pb;
1956  int skip = raw_packet_size - TS_PACKET_SIZE;
1957  if (skip > 0)
1958  avio_skip(pb, skip);
1959 }
1960 
1961 static int handle_packets(MpegTSContext *ts, int nb_packets)
1962 {
1963  AVFormatContext *s = ts->stream;
1965  const uint8_t *data;
1966  int packet_num, ret = 0;
1967 
1968  if (avio_tell(s->pb) != ts->last_pos) {
1969  int i;
1970  av_log(ts->stream, AV_LOG_TRACE, "Skipping after seek\n");
1971  /* seek detected, flush pes buffer */
1972  for (i = 0; i < NB_PID_MAX; i++) {
1973  if (ts->pids[i]) {
1974  if (ts->pids[i]->type == MPEGTS_PES) {
1975  PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
1976  av_buffer_unref(&pes->buffer);
1977  pes->data_index = 0;
1978  pes->state = MPEGTS_SKIP; /* skip until pes header */
1979  }
1980  ts->pids[i]->last_cc = -1;
1981  }
1982  }
1983  }
1984 
1985  ts->stop_parse = 0;
1986  packet_num = 0;
1987  memset(packet + TS_PACKET_SIZE, 0, AV_INPUT_BUFFER_PADDING_SIZE);
1988  for (;;) {
1989  if (ts->stop_parse > 0)
1990  break;
1991  packet_num++;
1992  if (nb_packets != 0 && packet_num >= nb_packets)
1993  break;
1994  ret = read_packet(s, packet, ts->raw_packet_size, &data);
1995  if (ret != 0)
1996  break;
1997  ret = handle_packet(ts, data);
1999  if (ret != 0)
2000  break;
2001  }
2002  ts->last_pos = avio_tell(s->pb);
2003  return ret;
2004 }
2005 
2007 {
2008  const int size = p->buf_size;
2009  int score, fec_score, dvhs_score;
2010  int check_count = size / TS_FEC_PACKET_SIZE;
2011 #define CHECK_COUNT 10
2012 
2013  if (check_count < CHECK_COUNT)
2014  return AVERROR_INVALIDDATA;
2015 
2016  score = analyze(p->buf, TS_PACKET_SIZE * check_count,
2017  TS_PACKET_SIZE, NULL, 1) * CHECK_COUNT / check_count;
2018  dvhs_score = analyze(p->buf, TS_DVHS_PACKET_SIZE * check_count,
2019  TS_DVHS_PACKET_SIZE, NULL, 1) * CHECK_COUNT / check_count;
2020  fec_score = analyze(p->buf, TS_FEC_PACKET_SIZE * check_count,
2021  TS_FEC_PACKET_SIZE, NULL, 1) * CHECK_COUNT / check_count;
2022  av_log(NULL, AV_LOG_TRACE, "score: %d, dvhs_score: %d, fec_score: %d \n",
2023  score, dvhs_score, fec_score);
2024 
2025  /* we need a clear definition for the returned score otherwise
2026  * things will become messy sooner or later */
2027  if (score > fec_score && score > dvhs_score && score > 6)
2028  return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
2029  else if (dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6)
2030  return AVPROBE_SCORE_MAX + dvhs_score - CHECK_COUNT;
2031  else if (fec_score > 6)
2032  return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
2033  else
2034  return AVERROR_INVALIDDATA;
2035 }
2036 
2037 /* return the 90kHz PCR and the extension for the 27MHz PCR. return
2038  * (-1) if not available */
2039 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low, const uint8_t *packet)
2040 {
2041  int afc, len, flags;
2042  const uint8_t *p;
2043  unsigned int v;
2044 
2045  afc = (packet[3] >> 4) & 3;
2046  if (afc <= 1)
2047  return AVERROR_INVALIDDATA;
2048  p = packet + 4;
2049  len = p[0];
2050  p++;
2051  if (len == 0)
2052  return AVERROR_INVALIDDATA;
2053  flags = *p++;
2054  len--;
2055  if (!(flags & 0x10))
2056  return AVERROR_INVALIDDATA;
2057  if (len < 6)
2058  return AVERROR_INVALIDDATA;
2059  v = AV_RB32(p);
2060  *ppcr_high = ((int64_t) v << 1) | (p[4] >> 7);
2061  *ppcr_low = ((p[4] & 1) << 8) | p[5];
2062  return 0;
2063 }
2064 
2066 {
2067  MpegTSContext *ts = s->priv_data;
2068  AVIOContext *pb = s->pb;
2069  uint8_t buf[5 * 1024];
2070  int len;
2071  int64_t pos;
2072 
2073  /* read the first 1024 bytes to get packet size */
2074  pos = avio_tell(pb);
2075  len = avio_read(pb, buf, sizeof(buf));
2076  if (len < 0)
2077  return len;
2078  if (len != sizeof(buf))
2079  return AVERROR_BUG;
2080  ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
2081  if (ts->raw_packet_size <= 0)
2082  return AVERROR_INVALIDDATA;
2083  ts->stream = s;
2084  ts->auto_guess = 0;
2085 
2086  if (s->iformat == &ff_mpegts_demuxer) {
2087  /* normal demux */
2088 
2089  /* first do a scan to get all the services */
2090  if (avio_seek(pb, pos, SEEK_SET) < 0 && pb->seekable)
2091  av_log(s, AV_LOG_ERROR, "Unable to seek back to the start\n");
2092 
2094 
2096 
2098  /* if could not find service, enable auto_guess */
2099 
2100  ts->auto_guess = 1;
2101 
2102  av_log(ts->stream, AV_LOG_TRACE, "tuning done\n");
2103 
2105  } else {
2106  AVStream *st;
2107  int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
2108  int64_t pcrs[2], pcr_h;
2109  int packet_count[2];
2110  uint8_t packet[TS_PACKET_SIZE];
2111  const uint8_t *data;
2112 
2113  /* only read packets */
2114 
2115  st = avformat_new_stream(s, NULL);
2116  if (!st)
2117  return AVERROR(ENOMEM);
2118  avpriv_set_pts_info(st, 60, 1, 27000000);
2121 
2122  /* we iterate until we find two PCRs to estimate the bitrate */
2123  pcr_pid = -1;
2124  nb_pcrs = 0;
2125  nb_packets = 0;
2126  for (;;) {
2127  ret = read_packet(s, packet, ts->raw_packet_size, &data);
2128  if (ret < 0)
2129  return ret;
2130  pid = AV_RB16(data + 1) & 0x1fff;
2131  if ((pcr_pid == -1 || pcr_pid == pid) &&
2132  parse_pcr(&pcr_h, &pcr_l, data) == 0) {
2134  pcr_pid = pid;
2135  packet_count[nb_pcrs] = nb_packets;
2136  pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
2137  nb_pcrs++;
2138  if (nb_pcrs >= 2)
2139  break;
2140  } else {
2142  }
2143  nb_packets++;
2144  }
2145 
2146  /* NOTE1: the bitrate is computed without the FEC */
2147  /* NOTE2: it is only the bitrate of the start of the stream */
2148  ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
2149  ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
2150  s->bit_rate = TS_PACKET_SIZE * 8 * 27e6 / ts->pcr_incr;
2151  st->codecpar->bit_rate = s->bit_rate;
2152  st->start_time = ts->cur_pcr;
2153  av_log(ts->stream, AV_LOG_TRACE, "start=%0.3f pcr=%0.3f incr=%d\n",
2154  st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
2155  }
2156 
2157  avio_seek(pb, pos, SEEK_SET);
2158  return 0;
2159 }
2160 
2161 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
2162 
2164 {
2165  MpegTSContext *ts = s->priv_data;
2166  int ret, i;
2167  int64_t pcr_h, next_pcr_h, pos;
2168  int pcr_l, next_pcr_l;
2169  uint8_t pcr_buf[12];
2170  const uint8_t *data;
2171 
2172  if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
2173  return AVERROR(ENOMEM);
2174  ret = read_packet(s, pkt->data, ts->raw_packet_size, &data);
2175  pkt->pos = avio_tell(s->pb);
2176  if (ret < 0) {
2177  av_packet_unref(pkt);
2178  return ret;
2179  }
2180  if (data != pkt->data)
2181  memcpy(pkt->data, data, ts->raw_packet_size);
2183  if (ts->mpeg2ts_compute_pcr) {
2184  /* compute exact PCR for each packet */
2185  if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
2186  /* we read the next PCR (XXX: optimize it by using a bigger buffer */
2187  pos = avio_tell(s->pb);
2188  for (i = 0; i < MAX_PACKET_READAHEAD; i++) {
2189  avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
2190  avio_read(s->pb, pcr_buf, 12);
2191  if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
2192  /* XXX: not precise enough */
2193  ts->pcr_incr =
2194  ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
2195  (i + 1);
2196  break;
2197  }
2198  }
2199  avio_seek(s->pb, pos, SEEK_SET);
2200  /* no next PCR found: we use previous increment */
2201  ts->cur_pcr = pcr_h * 300 + pcr_l;
2202  }
2203  pkt->pts = ts->cur_pcr;
2204  pkt->duration = ts->pcr_incr;
2205  ts->cur_pcr += ts->pcr_incr;
2206  }
2207  pkt->stream_index = 0;
2208  return 0;
2209 }
2210 
2212 {
2213  MpegTSContext *ts = s->priv_data;
2214  int ret, i;
2215 
2216  pkt->size = -1;
2217  ts->pkt = pkt;
2218  ret = handle_packets(ts, 0);
2219  if (ret < 0) {
2220  /* flush pes data left */
2221  for (i = 0; i < NB_PID_MAX; i++)
2222  if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
2223  PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
2224  if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
2225  new_pes_packet(pes, pkt);
2226  pes->state = MPEGTS_SKIP;
2227  ret = 0;
2228  break;
2229  }
2230  }
2231  }
2232 
2233  if (!ret && pkt->size < 0)
2234  ret = AVERROR(EINTR);
2235  return ret;
2236 }
2237 
2238 static void mpegts_free(MpegTSContext *ts)
2239 {
2240  int i;
2241 
2242  clear_programs(ts);
2243 
2244  for (i = 0; i < NB_PID_MAX; i++)
2245  if (ts->pids[i])
2246  mpegts_close_filter(ts, ts->pids[i]);
2247 }
2248 
2250 {
2251  MpegTSContext *ts = s->priv_data;
2252  mpegts_free(ts);
2253  return 0;
2254 }
2255 
2256 static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
2257  int64_t *ppos, int64_t pos_limit)
2258 {
2259  MpegTSContext *ts = s->priv_data;
2260  int64_t pos, timestamp;
2261  uint8_t buf[TS_PACKET_SIZE];
2262  int pcr_l, pcr_pid =
2263  ((PESContext *)s->streams[stream_index]->priv_data)->pcr_pid;
2264  const int find_next = 1;
2265  pos =
2266  ((*ppos + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) *
2267  ts->raw_packet_size + ts->pos47;
2268  if (find_next) {
2269  for (;;) {
2270  avio_seek(s->pb, pos, SEEK_SET);
2271  if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
2272  return AV_NOPTS_VALUE;
2273  if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
2274  parse_pcr(&timestamp, &pcr_l, buf) == 0) {
2275  break;
2276  }
2277  pos += ts->raw_packet_size;
2278  }
2279  } else {
2280  for (;;) {
2281  pos -= ts->raw_packet_size;
2282  if (pos < 0)
2283  return AV_NOPTS_VALUE;
2284  avio_seek(s->pb, pos, SEEK_SET);
2285  if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
2286  return AV_NOPTS_VALUE;
2287  if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
2288  parse_pcr(&timestamp, &pcr_l, buf) == 0) {
2289  break;
2290  }
2291  }
2292  }
2293  *ppos = pos;
2294 
2295  return timestamp;
2296 }
2297 
2298 static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags)
2299 {
2300  MpegTSContext *ts = s->priv_data;
2301  uint8_t buf[TS_PACKET_SIZE];
2302  int64_t pos;
2303  int ret;
2304 
2305  ret = ff_seek_frame_binary(s, stream_index, target_ts, flags);
2306  if (ret < 0)
2307  return ret;
2308 
2309  pos = avio_tell(s->pb);
2310 
2311  for (;;) {
2312  avio_seek(s->pb, pos, SEEK_SET);
2313  ret = avio_read(s->pb, buf, TS_PACKET_SIZE);
2314  if (ret < 0)
2315  return ret;
2316  if (ret != TS_PACKET_SIZE)
2317  return AVERROR_EOF;
2318  // pid = AV_RB16(buf + 1) & 0x1fff;
2319  if (buf[1] & 0x40)
2320  break;
2321  pos += ts->raw_packet_size;
2322  }
2323  avio_seek(s->pb, pos, SEEK_SET);
2324 
2325  return 0;
2326 }
2327 
2328 /**************************************************************/
2329 /* parsing functions - called from other demuxers such as RTP */
2330 
2332 {
2333  MpegTSContext *ts;
2334 
2335  ts = av_mallocz(sizeof(MpegTSContext));
2336  if (!ts)
2337  return NULL;
2338  /* no stream case, currently used by RTP */
2340  ts->stream = s;
2341  ts->auto_guess = 1;
2342  return ts;
2343 }
2344 
2345 /* return the consumed length if a packet was output, or -1 if no
2346  * packet is output */
2348  const uint8_t *buf, int len)
2349 {
2350  int len1;
2351 
2352  len1 = len;
2353  ts->pkt = pkt;
2354  ts->stop_parse = 0;
2355  for (;;) {
2356  if (ts->stop_parse > 0)
2357  break;
2358  if (len < TS_PACKET_SIZE)
2359  return AVERROR_INVALIDDATA;
2360  if (buf[0] != 0x47) {
2361  buf++;
2362  len--;
2363  } else {
2364  handle_packet(ts, buf);
2365  buf += TS_PACKET_SIZE;
2366  len -= TS_PACKET_SIZE;
2367  }
2368  }
2369  return len1 - len;
2370 }
2371 
2373 {
2374  mpegts_free(ts);
2375  av_free(ts);
2376 }
2377 
2378 AVInputFormat ff_mpegts_demuxer = {
2379  .name = "mpegts",
2380  .long_name = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
2381  .priv_data_size = sizeof(MpegTSContext),
2386  .read_seek = read_seek,
2387  .read_timestamp = mpegts_get_pcr,
2389  .priv_class = &mpegts_class,
2390 };
2391 
2393  .name = "mpegtsraw",
2394  .long_name = NULL_IF_CONFIG_SMALL("raw MPEG-TS (MPEG-2 Transport Stream)"),
2395  .priv_data_size = sizeof(MpegTSContext),
2399  .read_seek = read_seek,
2400  .read_timestamp = mpegts_get_pcr,
2402  .priv_class = &mpegtsraw_class,
2403 };
static void mpegts_free(MpegTSContext *ts)
Definition: mpegts.c:2238
codec_id is not known (like AV_CODEC_ID_NONE) but lavf should attempt to identify it ...
Definition: avcodec.h:565
uint8_t last_sec_num
Definition: mpegts.c:489
#define SDT_PID
Definition: mpegts.h:37
void * av_malloc(size_t size)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
Definition: mem.c:62
Bytestream IO Context.
Definition: avio.h:104
int es_id
Definition: mpegts.c:86
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:54
#define PES_START_SIZE
Definition: mpegts.c:188
#define PMT_TID
Definition: mpegts.h:41
void av_buffer_unref(AVBufferRef **buf)
Free a given reference and automatically free the buffer if there are no more references to it...
Definition: buffer.c:106
int size
#define MP4ESDescrTag
Definition: isom.h:179
int total_size
Definition: mpegts.c:204
static int mpegts_resync(AVFormatContext *s)
Definition: mpegts.c:1906
void ff_mp4_parse_es_descr(AVIOContext *pb, int *es_id)
Definition: isom.c:426
static void finished_reading_packet(AVFormatContext *s, int raw_packet_size)
Definition: mpegts.c:1953
uint32_t av_crc(const AVCRC *ctx, uint32_t crc, const uint8_t *buffer, size_t length)
Calculate the CRC of a block.
Definition: crc.c:312
AVOption.
Definition: opt.h:234
int64_t cur_pcr
used to estimate the exact PCR
Definition: mpegts.c:119
#define AV_OPT_FLAG_EXPORT
The option is intended for exporting values to the caller.
Definition: opt.h:275
#define MAX_PACKET_READAHEAD
Definition: mpegts.c:2161
enum AVMediaType codec_type
Definition: mpegts.c:573
int64_t dts
Definition: mpegts.c:207
static int parse_MP4ODescrTag(MP4DescrParseContext *d, int64_t off, int len)
Definition: mpegts.c:1098
static unsigned int get_bits(GetBitContext *s, int n)
Read 1-25 bits.
Definition: get_bits.h:228
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:130
static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
Definition: mpegts.c:1805
int64_t pos
byte position in stream, -1 if unknown
Definition: avcodec.h:1366
static void clear_program(MpegTSContext *ts, unsigned int programid)
Definition: mpegts.c:216
void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den)
Set the time base and wrapping info for a given stream.
Definition: utils.c:2986
static void skip_bits_long(GetBitContext *s, int n)
Definition: get_bits.h:187
static int mpegts_probe(AVProbeData *p)
Definition: mpegts.c:2006
#define MP4ODescrTag
Definition: isom.h:177
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition: avcodec.h:3483
int index
stream index in AVFormatContext
Definition: avformat.h:706
int size
Definition: avcodec.h:1347
MpegTSPESFilter pes_filter
Definition: mpegts.c:90
av_log(ac->avr, AV_LOG_TRACE, "%d samples - audio_convert: %s to %s (%s)\, len, av_get_sample_fmt_name(ac->in_fmt), av_get_sample_fmt_name(ac->out_fmt), use_generic ? ac->func_descr_generic :ac->func_descr)
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition: aviobuf.c:242
uint8_t version
Definition: mpegts.c:487
enum AVMediaType codec_type
Definition: rtp.c:36
#define AV_DISPOSITION_HEARING_IMPAIRED
stream for hearing impaired audiences
Definition: avformat.h:685
AVInputFormat ff_mpegts_demuxer
Definition: mpegts.c:2378
static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
Definition: mpegts.c:1721
void * priv_data
Definition: avformat.h:720
#define AV_DISPOSITION_CLEAN_EFFECTS
stream without voice
Definition: avformat.h:687
#define M4OD_TID
Definition: mpegts.h:42
static int parse_section_header(SectionHeader *h, const uint8_t **pp, const uint8_t *p_end)
Definition: mpegts.c:542
discard all
Definition: avcodec.h:689
enum MpegTSFilterType type
Definition: mpegts.c:88
int pid
Definition: mpegts.c:193
struct Program * prg
Definition: mpegts.c:137
static int mpegts_read_packet(AVFormatContext *s, AVPacket *pkt)
Definition: mpegts.c:2211
unsigned int avio_rb16(AVIOContext *s)
Definition: aviobuf.c:681
int ctx_flags
Flags signalling stream properties.
Definition: avformat.h:989
int pcr_pid
if -1 then all packets containing PCR are considered
Definition: mpegts.c:194
int id
Definition: avformat.h:911
SLConfigDescr sl
Definition: mpegts.h:91
int packet_seq_num_len
Definition: mpegts.h:84
int es_id
Definition: mpegts.h:88
int inst_bitrate_len
Definition: mpegts.h:81
unsigned int nb_prg
structure to keep track of Program->pids mapping
Definition: mpegts.c:136
void av_freep(void *arg)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc() and set the pointer ...
Definition: mem.c:202
#define AVFMT_SHOW_IDS
Show format stream IDs numbers.
Definition: avformat.h:414
int last_cc
Definition: mpegts.c:87
Format I/O context.
Definition: avformat.h:940
static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size, const uint8_t **data)
Definition: mpegts.c:1928
const char * class_name
The name of the class; usually it is the same name as the context structure type to which the AVClass...
Definition: log.h:39
unsigned int pids[MAX_PIDS_PER_PROGRAM]
Definition: mpegts.c:99
Definition: mpegts.c:96
Public dictionary API.
static int read_sl_header(PESContext *pes, SLConfigDescr *sl, const uint8_t *buf, int buf_size)
Definition: mpegts.c:735
void void avpriv_request_sample(void *avc, const char *msg,...) av_printf_format(2
Log a generic warning message about a missing feature.
MpegTSFilter * pids[NB_PID_MAX]
filters for various streams specified by PMT + for the PAT and PMT
Definition: mpegts.c:140
static int mpegts_read_header(AVFormatContext *s)
Definition: mpegts.c:2065
AVFormatContext * s
Definition: mpegts.c:1034
uint8_t
Opaque data information usually continuous.
Definition: avutil.h:196
enum MpegTSState state
Definition: mpegts.c:200
#define AVFMTCTX_NOHEADER
signal that no header is present (streams are added dynamically)
Definition: avformat.h:919
AVOptions.
const AVCRC * av_crc_get_table(AVCRCId crc_id)
Get an initialized standard CRC table.
Definition: crc.c:298
int au_seq_num_len
Definition: mpegts.h:83
#define AV_LOG_TRACE
Extremely verbose debugging, useful for libav* development.
Definition: log.h:150
unsigned int avio_rb32(AVIOContext *s)
Definition: aviobuf.c:696
int stop_parse
stop parsing loop
Definition: mpegts.c:124
static int parse_MP4ESDescrTag(MP4DescrParseContext *d, int64_t off, int len)
Definition: mpegts.c:1112
static int discard_pid(MpegTSContext *ts, unsigned int pid)
discard_pid() decides if the pid is to be discarded according to caller&#39;s programs selection ...
Definition: mpegts.c:271
#define AV_RB32
Definition: intreadwrite.h:130
int64_t duration
Duration of this packet in AVStream->time_base units, 0 if unknown.
Definition: avcodec.h:1364
static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
Definition: mpegts.c:231
static int mpegts_push_data(MpegTSFilter *filter, const uint8_t *buf, int buf_size, int is_start, int64_t pos)
Definition: mpegts.c:802
int id
Format-specific stream ID.
Definition: avformat.h:712
enum AVStreamParseType need_parsing
Definition: avformat.h:879
int use_au_start
Definition: mpegts.h:71
static const AVOption raw_options[]
Definition: mpegts.c:158
AVStream * avformat_new_stream(AVFormatContext *s, const AVCodec *c)
Add a new stream to a media file.
Definition: utils.c:2648
static const uint8_t opus_channel_map[8][8]
Definition: mpegts.c:1341
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:1008
#define TS_PACKET_SIZE
Definition: mpegts.h:29
Mp4Descr * descr
Definition: mpegts.c:1036
const char data[16]
Definition: mxf.c:70
int ffio_read_indirect(AVIOContext *s, unsigned char *buf, int size, const unsigned char **data)
Read size bytes from AVIOContext, returning a pointer.
Definition: aviobuf.c:600
static void update_offsets(AVIOContext *pb, int64_t *off, int *len)
Definition: mpegts.c:1065
uint8_t * data
Definition: avcodec.h:1346
AVProgram * av_new_program(AVFormatContext *s, int id)
Definition: utils.c:2735
static int get_bits_count(const GetBitContext *s)
Definition: get_bits.h:182
MpegTSState
Definition: mpegts.c:179
static int flags
Definition: log.c:50
uint32_t tag
Definition: movenc.c:854
#define AVERROR_EOF
End of file.
Definition: error.h:51
bitstream reader API header.
static av_cold int read_close(AVFormatContext *ctx)
Definition: libcdio.c:145
union MpegTSFilter::@144 u
int pid
Definition: mpegts.c:85
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition: avio.h:295
enum AVDiscard discard
selects which program to discard and which to feed to the caller
Definition: avformat.h:913
static PESContext * add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
Definition: mpegts.c:1008
#define PAT_TID
Definition: mpegts.h:40
int avio_read(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition: aviobuf.c:545
#define r
Definition: input.c:51
static MpegTSFilter * mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid, PESCallback *pes_cb, void *opaque)
Definition: mpegts.c:385
AVInputFormat ff_mpegtsraw_demuxer
Definition: mpegts.c:2392
static int init_MP4DescrParseContext(MP4DescrParseContext *d, AVFormatContext *s, const uint8_t *buf, unsigned size, Mp4Descr *descr, int max_descr_count)
Definition: mpegts.c:1043
int av_new_packet(AVPacket *pkt, int size)
Allocate the payload of a packet and initialize its fields with default values.
Definition: avpacket.c:84
static uint64_t get_bits64(GetBitContext *s, int n)
Definition: get_bits.h:318
enum AVCodecID codec_id
Definition: mpegts.c:574
AVBufferRef * buffer
Definition: mpegts.c:210
static const uint8_t opus_default_extradata[30]
Definition: opus.h:67
int ff_mp4_read_dec_config_descr(AVFormatContext *fc, AVStream *st, AVIOContext *pb)
Definition: isom.c:451
int av_reallocp_array(void *ptr, size_t nmemb, size_t size)
Definition: mem.c:168
AVCodecID
Identify the syntax and semantics of the bitstream.
Definition: avcodec.h:193
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:124
void av_free(void *ptr)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc(). ...
Definition: mem.c:190
static const StreamType HDMV_types[]
Definition: mpegts.c:594
#define AVFMT_TS_DISCONT
Format allows timestamp discontinuities.
Definition: avformat.h:422
#define AV_RB16
Definition: intreadwrite.h:53
#define AVERROR(e)
Definition: error.h:43
static int mpegts_read_close(AVFormatContext *s)
Definition: mpegts.c:2249
unsigned int check_crc
Definition: mpegts.c:78
static int mpegts_raw_read_packet(AVFormatContext *s, AVPacket *pkt)
Definition: mpegts.c:2163
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:148
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:145
unsigned int nb_programs
Definition: avformat.h:1087
preferred ID for decoding MPEG audio layer 1, 2 or 3
Definition: avcodec.h:479
enum AVMediaType codec_type
General type of the encoded data.
Definition: avcodec.h:3479
AVBufferRef * buf
A reference to the reference-counted buffer where the packet data is stored.
Definition: avcodec.h:1329
int pes_header_size
Definition: mpegts.c:205
void ff_program_add_stream_index(AVFormatContext *ac, int progid, unsigned int idx)
enum AVMediaType avcodec_get_type(enum AVCodecID codec_id)
Get the type of the given codec.
Definition: codec_desc.c:2491
#define TS_FEC_PACKET_SIZE
Definition: mpegts.h:27
New fields can be added to the end with minor version bumps.
Definition: avformat.h:910
static int64_t ff_parse_pes_pts(const uint8_t *buf)
Parse MPEG-PES five-byte timestamp.
Definition: mpeg.h:68
int timestamp_len
Definition: mpegts.h:78
static int parse_MP4DecConfigDescrTag(MP4DescrParseContext *d, int64_t off, int len)
Definition: mpegts.c:1133
int flags
copied to the AVPacket flags
Definition: mpegts.c:203
#define MAX_SECTION_SIZE
Definition: mpegts.h:33
int pcr_incr
used to estimate the exact PCR
Definition: mpegts.c:120
int flags
A combination of AV_PKT_FLAG values.
Definition: avcodec.h:1352
int extradata_size
Size of the extradata content in bytes.
Definition: avcodec.h:3501
int avio_r8(AVIOContext *s)
Definition: aviobuf.c:536
static int probe(AVProbeData *p)
Definition: anm.c:50
MpegTSContext * ff_mpegts_parse_open(AVFormatContext *s)
Definition: mpegts.c:2331
int bit_rate
The average bitrate of the encoded data (in bits per second).
Definition: avcodec.h:3512
int buf_size
Size of buf except extra allocated bytes.
Definition: avformat.h:401
unsigned char * buf
Buffer must have AVPROBE_PADDING_SIZE of extra allocated bytes filled with zero.
Definition: avformat.h:400
static void filter(MpegAudioContext *s, int ch, const short *samples, int incr)
Definition: mpegaudioenc.c:307
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
Definition: avformat.h:996
const char * name
Definition: qsvenc.c:44
int ff_find_stream_index(AVFormatContext *s, int id)
Find stream index based on format-specific stream ID.
Definition: utils.c:3063
int seekable
A combination of AVIO_SEEKABLE_ flags or 0 when the stream is not seekable.
Definition: avio.h:153
int64_t ts_packet_pos
position of first TS packet of this PES packet
Definition: mpegts.c:208
SectionCallback * section_cb
Definition: mpegts.c:80
static const StreamType REGD_types[]
Definition: mpegts.c:613
int PESCallback(MpegTSFilter *f, const uint8_t *buf, int len, int is_start, int64_t pos)
Definition: mpegts.c:61
static const StreamType MISC_types[]
Definition: mpegts.c:607
uint16_t id
Definition: mpegts.c:486
static int mp4_read_od(AVFormatContext *s, const uint8_t *buf, unsigned size, Mp4Descr *descr, int *descr_count, int max_descr_count)
Definition: mpegts.c:1254
#define TS_DVHS_PACKET_SIZE
Definition: mpegts.h:28
static int read_probe(AVProbeData *pd)
Definition: jvdec.c:55
enum AVCodecID codec_id
Definition: avconv_vaapi.c:149
AVStream * st
Definition: mpegts.c:198
#define MP4IODescrTag
Definition: isom.h:178
AVFormatContext * stream
Definition: mpegts.c:105
static av_always_inline int64_t avio_skip(AVIOContext *s, int64_t offset)
Skip given number of bytes forward.
Definition: avio.h:286
int ocr_len
Definition: mpegts.h:79
static int handle_packets(MpegTSContext *ts, int nb_packets)
Definition: mpegts.c:1961
static int mpegts_set_stream_info(AVStream *st, PESContext *pes, uint32_t stream_type, uint32_t prog_reg_desc)
Definition: mpegts.c:648
#define AV_RL32
Definition: intreadwrite.h:146
AVDictionary * metadata
Definition: avformat.h:772
static const uint8_t opus_stream_cnt[9]
Definition: mpegts.c:1337
static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len, int target_tag)
Definition: mpegts.c:1185
#define CHECK_COUNT
static int parse_MP4SLDescrTag(MP4DescrParseContext *d, int64_t off, int len)
Definition: mpegts.c:1147
int mpeg2ts_compute_pcr
compute exact PCR for each transport stream packet
Definition: mpegts.c:117
static const AVClass mpegtsraw_class
Definition: mpegts.c:170
MpegTSSectionFilter section_filter
Definition: mpegts.c:91
static const uint8_t opus_coupled_stream_cnt[9]
Definition: mpegts.c:1333
unsigned int probesize
Maximum size of the data read from input for determining the input container format.
Definition: avformat.h:1075
int ff_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt, const uint8_t *buf, int len)
Definition: mpegts.c:2347
uint8_t sec_num
Definition: mpegts.c:488
int extended_stream_id
Definition: mpegts.c:206
preferred ID for MPEG-1/2 video decoding
Definition: avcodec.h:198
LIBAVUTIL_VERSION_INT
Definition: eval.c:55
int stream_type
Definition: mpegts.c:195
int auto_guess
if true, all pids are analyzed to find streams
Definition: mpegts.c:114
int raw_packet_size
raw packet size, including FEC if present
Definition: mpegts.c:107
static const StreamType ISO_types[]
Definition: mpegts.c:577
static int read_header(FFV1Context *f)
Definition: ffv1dec.c:546
if(ac->has_optimized_func)
#define AV_DISPOSITION_VISUAL_IMPAIRED
stream for visual impaired audiences
Definition: avformat.h:686
Stream structure.
Definition: avformat.h:705
FAKE codec to indicate a MPEG-4 Systems stream (only used by libavformat)
Definition: avcodec.h:569
NULL
Definition: eval.c:55
#define TS_MAX_PACKET_SIZE
Definition: mpegts.h:30
uint8_t * dec_config_descr
Definition: mpegts.h:90
unsigned int id
Definition: mpegts.c:97
#define MP4DecConfigDescrTag
Definition: isom.h:180
static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags)
Definition: mpegts.c:2298
AVBufferRef * av_buffer_alloc(int size)
Allocate an AVBuffer of the given size using av_malloc().
Definition: buffer.c:66
#define hex_dump_debug(class, buf, size)
Definition: internal.h:33
AVIOContext * pb
I/O context.
Definition: avformat.h:982
av_default_item_name
Definition: dnxhdenc.c:55
int use_au_end
Definition: mpegts.h:72
static int parse_mp4_descr_arr(MP4DescrParseContext *d, int64_t off, int len)
Definition: mpegts.c:1075
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition: avpacket.c:347
int resync_size
Definition: mpegts.c:130
uint8_t * data
The data buffer.
Definition: buffer.h:89
static void new_pes_packet(PESContext *pes, AVPacket *pkt)
Definition: mpegts.c:700
static int get_packet_size(const uint8_t *buf, int size)
Definition: mpegts.c:461
#define STREAM_TYPE_PRIVATE_DATA
Definition: mpeg.h:54
static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index, int64_t *ppos, int64_t pos_limit)
Definition: mpegts.c:2256
#define MAX_PES_HEADER_SIZE
Definition: mpegts.c:190
static int get8(const uint8_t **pp, const uint8_t *p_end)
Definition: mpegts.c:492
#define MOD_UNLIKELY(modulus, dividend, divisor, prev_dividend)
Definition: mpegts.c:47
#define MAX_LEVEL
Definition: mpegts.c:1032
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition: dict.c:68
#define AVERROR_BUG
Bug detected, please report the issue.
Definition: error.h:60
#define MAX_PIDS_PER_PROGRAM
Definition: mpegts.c:95
static unsigned int get_bits1(GetBitContext *s)
Definition: get_bits.h:267
static int parse_pcr(int64_t *ppcr_high, int *ppcr_low, const uint8_t *packet)
Definition: mpegts.c:2039
int use_timestamps
Definition: mpegts.h:75
Describe the class of an AVClass context structure.
Definition: log.h:34
static void skip_bits(GetBitContext *s, int n)
Definition: get_bits.h:259
int index
Definition: gxfenc.c:72
static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
Definition: mpegts.c:1520
#define AV_OPT_FLAG_DECODING_PARAM
a generic parameter which can be set by the user for demuxing or decoding
Definition: opt.h:265
static int init_get_bits(GetBitContext *s, const uint8_t *buffer, int bit_size)
Initialize GetBitContext.
Definition: get_bits.h:362
static int analyze(const uint8_t *buf, int size, int packet_size, int *index, int probe)
Definition: mpegts.c:431
AVMediaType
Definition: avutil.h:192
refcounted data buffer API
static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
Definition: mpegts.c:410
static const StreamType DESC_types[]
Definition: mpegts.c:627
#define u(width,...)
This structure contains the data a format has to probe a file.
Definition: avformat.h:398
int use_idle
Definition: mpegts.h:76
SLConfigDescr sl
Definition: mpegts.c:211
int dec_config_descr_len
Definition: mpegts.h:89
uint8_t * section_buf
Definition: mpegts.c:77
uint8_t tid
Definition: mpegts.c:485
AVDictionary * metadata
Definition: avformat.h:916
void avpriv_report_missing_feature(void *avc, const char *msg,...) av_printf_format(2
Log a generic warning message about a missing feature.
#define MPEGTS_OPTIONS
Definition: mpegts.c:143
unsigned int end_of_section_reached
Definition: mpegts.c:79
static void write_section_data(MpegTSContext *ts, MpegTSFilter *tss1, const uint8_t *buf, int buf_size, int is_start)
Assemble PES packets out of TS packets, and then call the "section_cb" function when they are complet...
Definition: mpegts.c:309
int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type, const uint8_t **pp, const uint8_t *desc_list_end, Mp4Descr *mp4_descr, int mp4_descr_count, int pid, MpegTSContext *ts)
Parse an MPEG-2 descriptor.
Definition: mpegts.c:1352
static void clear_programs(MpegTSContext *ts)
Definition: mpegts.c:225
#define AVPROBE_SCORE_MAX
maximum score
Definition: avformat.h:407
A reference to a data buffer.
Definition: buffer.h:81
static const AVOption options[]
Definition: mpegts.c:146
full parsing and repack
Definition: avformat.h:657
AVFormatContext * stream
Definition: mpegts.c:197
Main libavformat public API header.
static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
Definition: mpegts.c:1674
static struct @174 state
int ff_mp4_read_descr(AVFormatContext *fc, AVIOContext *pb, int *tag)
Definition: isom.c:417
void ff_mpegts_parse_close(MpegTSContext *ts)
Definition: mpegts.c:2372
static const AVClass mpegts_class
Definition: mpegts.c:151
int use_rand_acc_pt
Definition: mpegts.h:73
int data_index
Definition: mpegts.c:202
int ffio_init_context(AVIOContext *s, unsigned char *buffer, int buffer_size, int write_flag, void *opaque, int(*read_packet)(void *opaque, uint8_t *buf, int buf_size), int(*write_packet)(void *opaque, uint8_t *buf, int buf_size), int64_t(*seek)(void *opaque, int64_t offset, int whence))
Definition: aviobuf.c:109
int64_t start_time
Decoding: pts of the first frame of the stream, in stream time base.
Definition: avformat.h:750
int disposition
AV_DISPOSITION_* bit field.
Definition: avformat.h:761
int64_t pos
position corresponding to pos47, or 0 if pos47 invalid
Definition: mpegts.c:111
uint8_t header[MAX_PES_HEADER_SIZE]
Definition: mpegts.c:209
#define MAX_PES_PAYLOAD
Definition: mpegts.c:43
void av_init_packet(AVPacket *pkt)
Initialize optional fields of a packet with default values.
Definition: avpacket.c:31
#define AV_PKT_FLAG_CORRUPT
The packet content is corrupted.
Definition: avcodec.h:1379
struct AVInputFormat * iformat
The input container format.
Definition: avformat.h:952
PESCallback * pes_cb
Definition: mpegts.c:65
#define AV_INPUT_BUFFER_PADDING_SIZE
Required number of additionally allocated bytes at the end of the input bitstream for decoding...
Definition: avcodec.h:638
static MpegTSFilter * mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid, SectionCallback *section_cb, void *opaque, int check_crc)
Definition: mpegts.c:348
FAKE codec to indicate a raw MPEG-2 TS stream (only used by libavformat)
Definition: avcodec.h:567
unsigned int nb_pids
Definition: mpegts.c:98
void * opaque
Definition: mpegts.c:66
static int get16(const uint8_t **pp, const uint8_t *p_end)
Definition: mpegts.c:505
int eof_reached
true if eof reached
Definition: avio.h:132
Mp4Descr * active_descr
Definition: mpegts.c:1037
AVPacket * pkt
packet containing Audio/Video data
Definition: mpegts.c:126
int len
#define PAT_PID
Definition: mpegts.h:36
void * priv_data
Format private data.
Definition: avformat.h:968
int64_t last_pos
to detect seek
Definition: mpegts.c:128
int timestamp_res
Definition: mpegts.h:77
#define AV_OPT_FLAG_READONLY
The option may not be set through the AVOptions API, only read.
Definition: opt.h:280
#define PES_HEADER_SIZE
Definition: mpegts.c:189
static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid, unsigned int pid)
Definition: mpegts.c:244
int64_t pts
Definition: mpegts.c:207
uint8_t * extradata
Extra binary data needed for initializing the decoder, codec-dependent.
Definition: avcodec.h:3497
int use_padding
Definition: mpegts.h:74
void SetServiceCallback(void *opaque, int ret)
Definition: mpegts.c:71
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed...
Definition: avcodec.h:1345
int bit_rate
Total stream bitrate in bit/s, 0 if not available.
Definition: avformat.h:1042
FILE * out
Definition: movenc.c:54
const char * name
A comma separated list of short names for the format.
Definition: avformat.h:529
AVCodecParameters * codecpar
Definition: avformat.h:831
uint32_t codec_tag
Additional information about the codec (corresponds to the AVI FOURCC).
Definition: avcodec.h:3487
int degr_prior_len
Definition: mpegts.h:82
static int parse_MP4IODescrTag(MP4DescrParseContext *d, int64_t off, int len)
Definition: mpegts.c:1086
static void m4sl_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
Definition: mpegts.c:1270
AVIOContext pb
Definition: mpegts.c:1035
int stream_index
Definition: avcodec.h:1348
MpegTSFilterType
Definition: mpegts.c:54
#define MAX_MP4_DESCR_COUNT
Definition: mpegts.c:45
#define MKTAG(a, b, c, d)
Definition: common.h:256
enum AVDiscard discard
Selects which packets can be discarded at will and do not need to be demuxed.
Definition: avformat.h:763
static void mpegts_find_stream_type(AVStream *st, uint32_t stream_type, const StreamType *types)
Definition: mpegts.c:636
int au_len
Definition: mpegts.h:80
This structure stores compressed data.
Definition: avcodec.h:1323
void * av_mallocz(size_t size)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
Definition: mem.c:211
uint32_t stream_type
Definition: mpegts.c:572
static char * getstr8(const uint8_t **pp, const uint8_t *p_end)
Definition: mpegts.c:520
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: avcodec.h:1339
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:235
int ff_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags)
Perform a binary search using av_index_search_timestamp() and AVInputFormat.read_timestamp().
Definition: utils.c:1261
AVProgram ** programs
Definition: avformat.h:1088
#define MP4SLDescrTag
Definition: isom.h:182
#define NB_PID_MAX
Definition: mpegts.h:32
#define SDT_TID
Definition: mpegts.h:43
void SectionCallback(MpegTSFilter *f, const uint8_t *buf, int len)
Definition: mpegts.c:69
AVStream * sub_st
stream for the embedded AC3 stream in HDMV TrueHD
Definition: mpegts.c:199
MpegTSContext * ts
Definition: mpegts.c:196
static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size, Mp4Descr *descr, int *descr_count, int max_descr_count)
Definition: mpegts.c:1238