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