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