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