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