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