FFmpeg
 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
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 */
97  /** raw packet size, including FEC if present */
99 
100  int pos47;
101 
102  /** if true, all pids are analyzed to find streams */
104 
105  /** compute exact PCR for each transport stream packet */
107 
108  int64_t cur_pcr; /**< used to estimate the exact PCR */
109  int pcr_incr; /**< used to estimate the exact PCR */
110 
111  /* data needed to handle file based ts */
112  /** stop parsing loop */
114  /** packet containing Audio/Video data */
116  /** to detect seek */
117  int64_t last_pos;
118 
119  /******************************************/
120  /* private mpegts data */
121  /* scan context */
122  /** structure to keep track of Program->pids mapping */
123  unsigned int nb_prg;
124  struct Program *prg;
125 
127 
128  /** filters for various streams specified by PMT + for the PAT and PMT */
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; /**< if -1 then all packets containing PCR are considered */
168  AVStream *sub_st; /**< stream for the embedded AC3 stream in HDMV TrueHD */
170  /* used to get the format */
172  int flags; /**< copied to the AVPacket flags */
176  int64_t pts, dts;
177  int64_t ts_packet_pos; /**< position of first TS packet of this PES packet */
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 
257 /**
258  * @brief discard_pid() decides if the pid is to be discarded according
259  * to caller's programs selection
260  * @param ts : - TS context
261  * @param pid : - pid
262  * @return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
263  * 0 otherwise
264  */
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 
290 /**
291  * Assemble PES packets out of TS packets, and then call the "section_cb"
292  * function when they are complete.
293  */
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 // { 0x11, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC_LATM }, /* LATM syntax */
568  { 0 },
569 };
570 
571 static const StreamType HDMV_types[] = {
577  { 0x85, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD */
578  { 0x86, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD MASTER*/
579  { 0xa1, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 }, /* E-AC3 Secondary Audio */
580  { 0xa2, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS Express Secondary Audio */
582  { 0 },
583 };
584 
585 /* ATSC ? */
586 static const StreamType MISC_types[] = {
589  { 0 },
590 };
591 
592 static const StreamType REGD_types[] = {
593  { MKTAG('d','r','a','c'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC },
594  { MKTAG('A','C','-','3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
595  { MKTAG('B','S','S','D'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_S302M },
596  { MKTAG('D','T','S','1'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
597  { MKTAG('D','T','S','2'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
598  { MKTAG('D','T','S','3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
599  { MKTAG('K','L','V','A'), AVMEDIA_TYPE_DATA, AV_CODEC_ID_SMPTE_KLV },
600  { MKTAG('V','C','-','1'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1 },
601  { 0 },
602 };
603 
604 /* descriptor present */
605 static const StreamType DESC_types[] = {
606  { 0x6a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 }, /* AC-3 descriptor */
607  { 0x7a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 }, /* E-AC-3 descriptor */
610  { 0x59, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
611  { 0 },
612 };
613 
615  uint32_t stream_type, const StreamType *types)
616 {
617  if (avcodec_is_open(st->codec)) {
618  av_log(NULL, AV_LOG_DEBUG, "cannot set stream info, codec is open\n");
619  return;
620  }
621 
622  for (; types->stream_type; types++) {
623  if (stream_type == types->stream_type) {
624  st->codec->codec_type = types->codec_type;
625  st->codec->codec_id = types->codec_id;
626  st->request_probe = 0;
627  return;
628  }
629  }
630 }
631 
633  uint32_t stream_type, uint32_t prog_reg_desc)
634 {
635  int old_codec_type= st->codec->codec_type;
636  int old_codec_id = st->codec->codec_id;
637 
638  if (avcodec_is_open(st->codec)) {
639  av_log(pes->stream, AV_LOG_DEBUG, "cannot set stream info, codec is open\n");
640  return 0;
641  }
642 
643  avpriv_set_pts_info(st, 33, 1, 90000);
644  st->priv_data = pes;
648  pes->st = st;
649  pes->stream_type = stream_type;
650 
651  av_log(pes->stream, AV_LOG_DEBUG,
652  "stream=%d stream_type=%x pid=%x prog_reg_desc=%.4s\n",
653  st->index, pes->stream_type, pes->pid, (char*)&prog_reg_desc);
654 
655  st->codec->codec_tag = pes->stream_type;
656 
657  mpegts_find_stream_type(st, pes->stream_type, ISO_types);
658  if ((prog_reg_desc == AV_RL32("HDMV") ||
659  prog_reg_desc == AV_RL32("HDPR")) &&
660  st->codec->codec_id == AV_CODEC_ID_NONE) {
661  mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
662  if (pes->stream_type == 0x83) {
663  // HDMV TrueHD streams also contain an AC3 coded version of the
664  // audio track - add a second stream for this
665  AVStream *sub_st;
666  // priv_data cannot be shared between streams
667  PESContext *sub_pes = av_malloc(sizeof(*sub_pes));
668  if (!sub_pes)
669  return AVERROR(ENOMEM);
670  memcpy(sub_pes, pes, sizeof(*sub_pes));
671 
672  sub_st = avformat_new_stream(pes->stream, NULL);
673  if (!sub_st) {
674  av_free(sub_pes);
675  return AVERROR(ENOMEM);
676  }
677 
678  sub_st->id = pes->pid;
679  avpriv_set_pts_info(sub_st, 33, 1, 90000);
680  sub_st->priv_data = sub_pes;
682  sub_st->codec->codec_id = AV_CODEC_ID_AC3;
684  sub_pes->sub_st = pes->sub_st = sub_st;
685  }
686  }
687  if (st->codec->codec_id == AV_CODEC_ID_NONE)
688  mpegts_find_stream_type(st, pes->stream_type, MISC_types);
689  if (st->codec->codec_id == AV_CODEC_ID_NONE){
690  st->codec->codec_id = old_codec_id;
691  st->codec->codec_type= old_codec_type;
692  }
693 
694  return 0;
695 }
696 
698 {
699  av_init_packet(pkt);
700 
702  pkt->data = pes->buffer;
703  pkt->size = pes->data_index;
704 
705  if(pes->total_size != MAX_PES_PAYLOAD &&
706  pes->pes_header_size + pes->data_index != pes->total_size + PES_START_SIZE) {
707  av_log(pes->stream, AV_LOG_WARNING, "PES packet size mismatch\n");
708  pes->flags |= AV_PKT_FLAG_CORRUPT;
709  }
710  memset(pkt->data+pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
711 
712  // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID
713  if (pes->sub_st && pes->stream_type == 0x83 && pes->extended_stream_id == 0x76)
714  pkt->stream_index = pes->sub_st->index;
715  else
716  pkt->stream_index = pes->st->index;
717  pkt->pts = pes->pts;
718  pkt->dts = pes->dts;
719  /* store position of first TS packet of this PES packet */
720  pkt->pos = pes->ts_packet_pos;
721  pkt->flags = pes->flags;
722 
723  /* reset pts values */
724  pes->pts = AV_NOPTS_VALUE;
725  pes->dts = AV_NOPTS_VALUE;
726  pes->buffer = NULL;
727  pes->data_index = 0;
728  pes->flags = 0;
729 }
730 
731 static uint64_t get_ts64(GetBitContext *gb, int bits)
732 {
733  if (get_bits_left(gb) < bits)
734  return AV_NOPTS_VALUE;
735  return get_bits64(gb, bits);
736 }
737 
738 static int read_sl_header(PESContext *pes, SLConfigDescr *sl, const uint8_t *buf, int buf_size)
739 {
740  GetBitContext gb;
741  int au_start_flag = 0, au_end_flag = 0, ocr_flag = 0, idle_flag = 0;
742  int padding_flag = 0, padding_bits = 0, inst_bitrate_flag = 0;
743  int dts_flag = -1, cts_flag = -1;
744  int64_t dts = AV_NOPTS_VALUE, cts = AV_NOPTS_VALUE;
745 
746  init_get_bits(&gb, buf, buf_size*8);
747 
748  if (sl->use_au_start)
749  au_start_flag = get_bits1(&gb);
750  if (sl->use_au_end)
751  au_end_flag = get_bits1(&gb);
752  if (!sl->use_au_start && !sl->use_au_end)
753  au_start_flag = au_end_flag = 1;
754  if (sl->ocr_len > 0)
755  ocr_flag = get_bits1(&gb);
756  if (sl->use_idle)
757  idle_flag = get_bits1(&gb);
758  if (sl->use_padding)
759  padding_flag = get_bits1(&gb);
760  if (padding_flag)
761  padding_bits = get_bits(&gb, 3);
762 
763  if (!idle_flag && (!padding_flag || padding_bits != 0)) {
764  if (sl->packet_seq_num_len)
766  if (sl->degr_prior_len)
767  if (get_bits1(&gb))
768  skip_bits(&gb, sl->degr_prior_len);
769  if (ocr_flag)
770  skip_bits_long(&gb, sl->ocr_len);
771  if (au_start_flag) {
772  if (sl->use_rand_acc_pt)
773  get_bits1(&gb);
774  if (sl->au_seq_num_len > 0)
775  skip_bits_long(&gb, sl->au_seq_num_len);
776  if (sl->use_timestamps) {
777  dts_flag = get_bits1(&gb);
778  cts_flag = get_bits1(&gb);
779  }
780  }
781  if (sl->inst_bitrate_len)
782  inst_bitrate_flag = get_bits1(&gb);
783  if (dts_flag == 1)
784  dts = get_ts64(&gb, sl->timestamp_len);
785  if (cts_flag == 1)
786  cts = get_ts64(&gb, sl->timestamp_len);
787  if (sl->au_len > 0)
788  skip_bits_long(&gb, sl->au_len);
789  if (inst_bitrate_flag)
791  }
792 
793  if (dts != AV_NOPTS_VALUE)
794  pes->dts = dts;
795  if (cts != AV_NOPTS_VALUE)
796  pes->pts = cts;
797 
798  if (sl->timestamp_len && sl->timestamp_res)
800 
801  return (get_bits_count(&gb) + 7) >> 3;
802 }
803 
804 /* return non zero if a packet could be constructed */
806  const uint8_t *buf, int buf_size, int is_start,
807  int64_t pos)
808 {
809  PESContext *pes = filter->u.pes_filter.opaque;
810  MpegTSContext *ts = pes->ts;
811  const uint8_t *p;
812  int len, code;
813 
814  if(!ts->pkt)
815  return 0;
816 
817  if (is_start) {
818  if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
819  new_pes_packet(pes, ts->pkt);
820  ts->stop_parse = 1;
821  }
822  pes->state = MPEGTS_HEADER;
823  pes->data_index = 0;
824  pes->ts_packet_pos = pos;
825  }
826  p = buf;
827  while (buf_size > 0) {
828  switch(pes->state) {
829  case MPEGTS_HEADER:
830  len = PES_START_SIZE - pes->data_index;
831  if (len > buf_size)
832  len = buf_size;
833  memcpy(pes->header + pes->data_index, p, len);
834  pes->data_index += len;
835  p += len;
836  buf_size -= len;
837  if (pes->data_index == PES_START_SIZE) {
838  /* we got all the PES or section header. We can now
839  decide */
840  if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
841  pes->header[2] == 0x01) {
842  /* it must be an mpeg2 PES stream */
843  code = pes->header[3] | 0x100;
844  av_dlog(pes->stream, "pid=%x pes_code=%#x\n", pes->pid, code);
845 
846  if ((pes->st && pes->st->discard == AVDISCARD_ALL &&
847  (!pes->sub_st || pes->sub_st->discard == AVDISCARD_ALL)) ||
848  code == 0x1be) /* padding_stream */
849  goto skip;
850 
851  /* stream not present in PMT */
852  if (!pes->st) {
853  pes->st = avformat_new_stream(ts->stream, NULL);
854  if (!pes->st)
855  return AVERROR(ENOMEM);
856  pes->st->id = pes->pid;
857  mpegts_set_stream_info(pes->st, pes, 0, 0);
858  }
859 
860  pes->total_size = AV_RB16(pes->header + 4);
861  /* NOTE: a zero total size means the PES size is
862  unbounded */
863  if (!pes->total_size)
865 
866  /* allocate pes buffer */
868  if (!pes->buffer)
869  return AVERROR(ENOMEM);
870 
871  if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
872  code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
873  code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
874  code != 0x1f8) { /* ITU-T Rec. H.222.1 type E stream */
875  pes->state = MPEGTS_PESHEADER;
876  if (pes->st->codec->codec_id == AV_CODEC_ID_NONE && !pes->st->request_probe) {
877  av_dlog(pes->stream, "pid=%x stream_type=%x probing\n",
878  pes->pid, pes->stream_type);
879  pes->st->request_probe= 1;
880  }
881  } else {
882  pes->state = MPEGTS_PAYLOAD;
883  pes->data_index = 0;
884  }
885  } else {
886  /* otherwise, it should be a table */
887  /* skip packet */
888  skip:
889  pes->state = MPEGTS_SKIP;
890  continue;
891  }
892  }
893  break;
894  /**********************************************/
895  /* PES packing parsing */
896  case MPEGTS_PESHEADER:
897  len = PES_HEADER_SIZE - pes->data_index;
898  if (len < 0)
899  return -1;
900  if (len > buf_size)
901  len = buf_size;
902  memcpy(pes->header + pes->data_index, p, len);
903  pes->data_index += len;
904  p += len;
905  buf_size -= len;
906  if (pes->data_index == PES_HEADER_SIZE) {
907  pes->pes_header_size = pes->header[8] + 9;
909  }
910  break;
912  len = pes->pes_header_size - pes->data_index;
913  if (len < 0)
914  return -1;
915  if (len > buf_size)
916  len = buf_size;
917  memcpy(pes->header + pes->data_index, p, len);
918  pes->data_index += len;
919  p += len;
920  buf_size -= len;
921  if (pes->data_index == pes->pes_header_size) {
922  const uint8_t *r;
923  unsigned int flags, pes_ext, skip;
924 
925  flags = pes->header[7];
926  r = pes->header + 9;
927  pes->pts = AV_NOPTS_VALUE;
928  pes->dts = AV_NOPTS_VALUE;
929  if ((flags & 0xc0) == 0x80) {
930  pes->dts = pes->pts = ff_parse_pes_pts(r);
931  r += 5;
932  } else if ((flags & 0xc0) == 0xc0) {
933  pes->pts = ff_parse_pes_pts(r);
934  r += 5;
935  pes->dts = ff_parse_pes_pts(r);
936  r += 5;
937  }
938  pes->extended_stream_id = -1;
939  if (flags & 0x01) { /* PES extension */
940  pes_ext = *r++;
941  /* Skip PES private data, program packet sequence counter and P-STD buffer */
942  skip = (pes_ext >> 4) & 0xb;
943  skip += skip & 0x9;
944  r += skip;
945  if ((pes_ext & 0x41) == 0x01 &&
946  (r + 2) <= (pes->header + pes->pes_header_size)) {
947  /* PES extension 2 */
948  if ((r[0] & 0x7f) > 0 && (r[1] & 0x80) == 0)
949  pes->extended_stream_id = r[1];
950  }
951  }
952 
953  /* we got the full header. We parse it and get the payload */
954  pes->state = MPEGTS_PAYLOAD;
955  pes->data_index = 0;
956  if (pes->stream_type == 0x12 && buf_size > 0) {
957  int sl_header_bytes = read_sl_header(pes, &pes->sl, p, buf_size);
958  pes->pes_header_size += sl_header_bytes;
959  p += sl_header_bytes;
960  buf_size -= sl_header_bytes;
961  }
962  }
963  break;
964  case MPEGTS_PAYLOAD:
965  if (buf_size > 0 && pes->buffer) {
966  if (pes->data_index > 0 && pes->data_index+buf_size > pes->total_size) {
967  new_pes_packet(pes, ts->pkt);
970  if (!pes->buffer)
971  return AVERROR(ENOMEM);
972  ts->stop_parse = 1;
973  } else if (pes->data_index == 0 && buf_size > pes->total_size) {
974  // pes packet size is < ts size packet and pes data is padded with 0xff
975  // not sure if this is legal in ts but see issue #2392
976  buf_size = pes->total_size;
977  }
978  memcpy(pes->buffer+pes->data_index, p, buf_size);
979  pes->data_index += buf_size;
980  }
981  buf_size = 0;
982  /* emit complete packets with known packet size
983  * decreases demuxer delay for infrequent packets like subtitles from
984  * a couple of seconds to milliseconds for properly muxed files.
985  * total_size is the number of bytes following pes_packet_length
986  * in the pes header, i.e. not counting the first PES_START_SIZE bytes */
987  if (!ts->stop_parse && pes->total_size < MAX_PES_PAYLOAD &&
988  pes->pes_header_size + pes->data_index == pes->total_size + PES_START_SIZE) {
989  ts->stop_parse = 1;
990  new_pes_packet(pes, ts->pkt);
991  }
992  break;
993  case MPEGTS_SKIP:
994  buf_size = 0;
995  break;
996  }
997  }
998 
999  return 0;
1000 }
1001 
1002 static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
1003 {
1004  MpegTSFilter *tss;
1005  PESContext *pes;
1006 
1007  /* if no pid found, then add a pid context */
1008  pes = av_mallocz(sizeof(PESContext));
1009  if (!pes)
1010  return 0;
1011  pes->ts = ts;
1012  pes->stream = ts->stream;
1013  pes->pid = pid;
1014  pes->pcr_pid = pcr_pid;
1015  pes->state = MPEGTS_SKIP;
1016  pes->pts = AV_NOPTS_VALUE;
1017  pes->dts = AV_NOPTS_VALUE;
1018  tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
1019  if (!tss) {
1020  av_free(pes);
1021  return 0;
1022  }
1023  return pes;
1024 }
1025 
1026 #define MAX_LEVEL 4
1027 typedef struct {
1034  int level;
1036 
1038  MP4DescrParseContext *d, AVFormatContext *s, const uint8_t *buf,
1039  unsigned size, Mp4Descr *descr, int max_descr_count)
1040 {
1041  int ret;
1042  if (size > (1<<30))
1043  return AVERROR_INVALIDDATA;
1044 
1045  if ((ret = ffio_init_context(&d->pb, (unsigned char*)buf, size, 0,
1046  NULL, NULL, NULL, NULL)) < 0)
1047  return ret;
1048 
1049  d->s = s;
1050  d->level = 0;
1051  d->descr_count = 0;
1052  d->descr = descr;
1053  d->active_descr = NULL;
1054  d->max_descr_count = max_descr_count;
1055 
1056  return 0;
1057 }
1058 
1059 static void update_offsets(AVIOContext *pb, int64_t *off, int *len) {
1060  int64_t new_off = avio_tell(pb);
1061  (*len) -= new_off - *off;
1062  *off = new_off;
1063 }
1064 
1065 static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
1066  int target_tag);
1067 
1068 static int parse_mp4_descr_arr(MP4DescrParseContext *d, int64_t off, int len)
1069 {
1070  while (len > 0) {
1071  if (parse_mp4_descr(d, off, len, 0) < 0)
1072  return -1;
1073  update_offsets(&d->pb, &off, &len);
1074  }
1075  return 0;
1076 }
1077 
1078 static int parse_MP4IODescrTag(MP4DescrParseContext *d, int64_t off, int len)
1079 {
1080  avio_rb16(&d->pb); // ID
1081  avio_r8(&d->pb);
1082  avio_r8(&d->pb);
1083  avio_r8(&d->pb);
1084  avio_r8(&d->pb);
1085  avio_r8(&d->pb);
1086  update_offsets(&d->pb, &off, &len);
1087  return parse_mp4_descr_arr(d, off, len);
1088 }
1089 
1090 static int parse_MP4ODescrTag(MP4DescrParseContext *d, int64_t off, int len)
1091 {
1092  int id_flags;
1093  if (len < 2)
1094  return 0;
1095  id_flags = avio_rb16(&d->pb);
1096  if (!(id_flags & 0x0020)) { //URL_Flag
1097  update_offsets(&d->pb, &off, &len);
1098  return parse_mp4_descr_arr(d, off, len); //ES_Descriptor[]
1099  } else {
1100  return 0;
1101  }
1102 }
1103 
1104 static int parse_MP4ESDescrTag(MP4DescrParseContext *d, int64_t off, int len)
1105 {
1106  int es_id = 0;
1107  if (d->descr_count >= d->max_descr_count)
1108  return -1;
1109  ff_mp4_parse_es_descr(&d->pb, &es_id);
1110  d->active_descr = d->descr + (d->descr_count++);
1111 
1112  d->active_descr->es_id = es_id;
1113  update_offsets(&d->pb, &off, &len);
1114  parse_mp4_descr(d, off, len, MP4DecConfigDescrTag);
1115  update_offsets(&d->pb, &off, &len);
1116  if (len > 0)
1117  parse_mp4_descr(d, off, len, MP4SLDescrTag);
1118  d->active_descr = NULL;
1119  return 0;
1120 }
1121 
1123 {
1124  Mp4Descr *descr = d->active_descr;
1125  if (!descr)
1126  return -1;
1128  if (!descr->dec_config_descr)
1129  return AVERROR(ENOMEM);
1130  descr->dec_config_descr_len = len;
1131  avio_read(&d->pb, descr->dec_config_descr, len);
1132  return 0;
1133 }
1134 
1135 static int parse_MP4SLDescrTag(MP4DescrParseContext *d, int64_t off, int len)
1136 {
1137  Mp4Descr *descr = d->active_descr;
1138  int predefined;
1139  if (!descr)
1140  return -1;
1141 
1142  predefined = avio_r8(&d->pb);
1143  if (!predefined) {
1144  int lengths;
1145  int flags = avio_r8(&d->pb);
1146  descr->sl.use_au_start = !!(flags & 0x80);
1147  descr->sl.use_au_end = !!(flags & 0x40);
1148  descr->sl.use_rand_acc_pt = !!(flags & 0x20);
1149  descr->sl.use_padding = !!(flags & 0x08);
1150  descr->sl.use_timestamps = !!(flags & 0x04);
1151  descr->sl.use_idle = !!(flags & 0x02);
1152  descr->sl.timestamp_res = avio_rb32(&d->pb);
1153  avio_rb32(&d->pb);
1154  descr->sl.timestamp_len = avio_r8(&d->pb);
1155  descr->sl.ocr_len = avio_r8(&d->pb);
1156  descr->sl.au_len = avio_r8(&d->pb);
1157  descr->sl.inst_bitrate_len = avio_r8(&d->pb);
1158  lengths = avio_rb16(&d->pb);
1159  descr->sl.degr_prior_len = lengths >> 12;
1160  descr->sl.au_seq_num_len = (lengths >> 7) & 0x1f;
1161  descr->sl.packet_seq_num_len = (lengths >> 2) & 0x1f;
1162  } else {
1163  av_log_missing_feature(d->s, "Predefined SLConfigDescriptor", 0);
1164  }
1165  return 0;
1166 }
1167 
1168 static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
1169  int target_tag) {
1170  int tag;
1171  int len1 = ff_mp4_read_descr(d->s, &d->pb, &tag);
1172  update_offsets(&d->pb, &off, &len);
1173  if (len < 0 || len1 > len || len1 <= 0) {
1174  av_log(d->s, AV_LOG_ERROR, "Tag %x length violation new length %d bytes remaining %d\n", tag, len1, len);
1175  return -1;
1176  }
1177 
1178  if (d->level++ >= MAX_LEVEL) {
1179  av_log(d->s, AV_LOG_ERROR, "Maximum MP4 descriptor level exceeded\n");
1180  goto done;
1181  }
1182 
1183  if (target_tag && tag != target_tag) {
1184  av_log(d->s, AV_LOG_ERROR, "Found tag %x expected %x\n", tag, target_tag);
1185  goto done;
1186  }
1187 
1188  switch (tag) {
1189  case MP4IODescrTag:
1190  parse_MP4IODescrTag(d, off, len1);
1191  break;
1192  case MP4ODescrTag:
1193  parse_MP4ODescrTag(d, off, len1);
1194  break;
1195  case MP4ESDescrTag:
1196  parse_MP4ESDescrTag(d, off, len1);
1197  break;
1198  case MP4DecConfigDescrTag:
1199  parse_MP4DecConfigDescrTag(d, off, len1);
1200  break;
1201  case MP4SLDescrTag:
1202  parse_MP4SLDescrTag(d, off, len1);
1203  break;
1204  }
1205 
1206 done:
1207  d->level--;
1208  avio_seek(&d->pb, off + len1, SEEK_SET);
1209  return 0;
1210 }
1211 
1212 static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size,
1213  Mp4Descr *descr, int *descr_count, int max_descr_count)
1214 {
1216  if (init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count) < 0)
1217  return -1;
1218 
1219  parse_mp4_descr(&d, avio_tell(&d.pb), size, MP4IODescrTag);
1220 
1221  *descr_count = d.descr_count;
1222  return 0;
1223 }
1224 
1225 static int mp4_read_od(AVFormatContext *s, const uint8_t *buf, unsigned size,
1226  Mp4Descr *descr, int *descr_count, int max_descr_count)
1227 {
1229  if (init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count) < 0)
1230  return -1;
1231 
1232  parse_mp4_descr_arr(&d, avio_tell(&d.pb), size);
1233 
1234  *descr_count = d.descr_count;
1235  return 0;
1236 }
1237 
1238 static void m4sl_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1239 {
1240  MpegTSContext *ts = filter->u.section_filter.opaque;
1241  SectionHeader h;
1242  const uint8_t *p, *p_end;
1243  AVIOContext pb;
1244  Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = {{ 0 }};
1245  int mp4_descr_count = 0;
1246  int i, pid;
1247  AVFormatContext *s = ts->stream;
1248 
1249  p_end = section + section_len - 4;
1250  p = section;
1251  if (parse_section_header(&h, &p, p_end) < 0)
1252  return;
1253  if (h.tid != M4OD_TID)
1254  return;
1255 
1256  mp4_read_od(s, p, (unsigned)(p_end - p), mp4_descr, &mp4_descr_count, MAX_MP4_DESCR_COUNT);
1257 
1258  for (pid = 0; pid < NB_PID_MAX; pid++) {
1259  if (!ts->pids[pid])
1260  continue;
1261  for (i = 0; i < mp4_descr_count; i++) {
1262  PESContext *pes;
1263  AVStream *st;
1264  if (ts->pids[pid]->es_id != mp4_descr[i].es_id)
1265  continue;
1266  if (!(ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES)) {
1267  av_log(s, AV_LOG_ERROR, "pid %x is not PES\n", pid);
1268  continue;
1269  }
1270  pes = ts->pids[pid]->u.pes_filter.opaque;
1271  st = pes->st;
1272  if (!st) {
1273  continue;
1274  }
1275 
1276  pes->sl = mp4_descr[i].sl;
1277 
1278  ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
1279  mp4_descr[i].dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
1280  ff_mp4_read_dec_config_descr(s, st, &pb);
1281  if (st->codec->codec_id == AV_CODEC_ID_AAC &&
1282  st->codec->extradata_size > 0)
1283  st->need_parsing = 0;
1284  if (st->codec->codec_id == AV_CODEC_ID_H264 &&
1285  st->codec->extradata_size > 0)
1286  st->need_parsing = 0;
1287 
1288  if (st->codec->codec_id <= AV_CODEC_ID_NONE) {
1289  } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_AUDIO) {
1291  } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_SUBTITLE) {
1293  } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_UNKNOWN) {
1295  }
1296  }
1297  }
1298  for (i = 0; i < mp4_descr_count; i++)
1299  av_free(mp4_descr[i].dec_config_descr);
1300 }
1301 
1303  const uint8_t **pp, const uint8_t *desc_list_end,
1304  Mp4Descr *mp4_descr, int mp4_descr_count, int pid,
1305  MpegTSContext *ts)
1306 {
1307  const uint8_t *desc_end;
1308  int desc_len, desc_tag, desc_es_id;
1309  char language[252];
1310  int i;
1311 
1312  desc_tag = get8(pp, desc_list_end);
1313  if (desc_tag < 0)
1314  return -1;
1315  desc_len = get8(pp, desc_list_end);
1316  if (desc_len < 0)
1317  return -1;
1318  desc_end = *pp + desc_len;
1319  if (desc_end > desc_list_end)
1320  return -1;
1321 
1322  av_dlog(fc, "tag: 0x%02x len=%d\n", desc_tag, desc_len);
1323 
1324  if (st->codec->codec_id == AV_CODEC_ID_NONE &&
1325  stream_type == STREAM_TYPE_PRIVATE_DATA)
1326  mpegts_find_stream_type(st, desc_tag, DESC_types);
1327 
1328  switch(desc_tag) {
1329  case 0x1E: /* SL descriptor */
1330  desc_es_id = get16(pp, desc_end);
1331  if (ts && ts->pids[pid])
1332  ts->pids[pid]->es_id = desc_es_id;
1333  for (i = 0; i < mp4_descr_count; i++)
1334  if (mp4_descr[i].dec_config_descr_len &&
1335  mp4_descr[i].es_id == desc_es_id) {
1336  AVIOContext pb;
1337  ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
1338  mp4_descr[i].dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
1339  ff_mp4_read_dec_config_descr(fc, st, &pb);
1340  if (st->codec->codec_id == AV_CODEC_ID_AAC &&
1341  st->codec->extradata_size > 0)
1342  st->need_parsing = 0;
1344  mpegts_open_section_filter(ts, pid, m4sl_cb, ts, 1);
1345  }
1346  break;
1347  case 0x1F: /* FMC descriptor */
1348  get16(pp, desc_end);
1349  if (mp4_descr_count > 0 && (st->codec->codec_id == AV_CODEC_ID_AAC_LATM || st->request_probe>0) &&
1350  mp4_descr->dec_config_descr_len && mp4_descr->es_id == pid) {
1351  AVIOContext pb;
1352  ffio_init_context(&pb, mp4_descr->dec_config_descr,
1353  mp4_descr->dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
1354  ff_mp4_read_dec_config_descr(fc, st, &pb);
1355  if (st->codec->codec_id == AV_CODEC_ID_AAC &&
1356  st->codec->extradata_size > 0){
1357  st->request_probe= st->need_parsing = 0;
1359  }
1360  }
1361  break;
1362  case 0x56: /* DVB teletext descriptor */
1363  language[0] = get8(pp, desc_end);
1364  language[1] = get8(pp, desc_end);
1365  language[2] = get8(pp, desc_end);
1366  language[3] = 0;
1367  av_dict_set(&st->metadata, "language", language, 0);
1368  break;
1369  case 0x59: /* subtitling descriptor */
1370  language[0] = get8(pp, desc_end);
1371  language[1] = get8(pp, desc_end);
1372  language[2] = get8(pp, desc_end);
1373  language[3] = 0;
1374  /* hearing impaired subtitles detection */
1375  switch(get8(pp, desc_end)) {
1376  case 0x20: /* DVB subtitles (for the hard of hearing) with no monitor aspect ratio criticality */
1377  case 0x21: /* DVB subtitles (for the hard of hearing) for display on 4:3 aspect ratio monitor */
1378  case 0x22: /* DVB subtitles (for the hard of hearing) for display on 16:9 aspect ratio monitor */
1379  case 0x23: /* DVB subtitles (for the hard of hearing) for display on 2.21:1 aspect ratio monitor */
1380  case 0x24: /* DVB subtitles (for the hard of hearing) for display on a high definition monitor */
1381  case 0x25: /* DVB subtitles (for the hard of hearing) with plano-stereoscopic disparity for display on a high definition monitor */
1383  break;
1384  }
1385  if (st->codec->extradata) {
1386  if (st->codec->extradata_size == 4 && memcmp(st->codec->extradata, *pp, 4))
1387  av_log_ask_for_sample(fc, "DVB sub with multiple IDs\n");
1388  } else {
1390  if (st->codec->extradata) {
1391  st->codec->extradata_size = 4;
1392  memcpy(st->codec->extradata, *pp, 4);
1393  }
1394  }
1395  *pp += 4;
1396  av_dict_set(&st->metadata, "language", language, 0);
1397  break;
1398  case 0x0a: /* ISO 639 language descriptor */
1399  for (i = 0; i + 4 <= desc_len; i += 4) {
1400  language[i + 0] = get8(pp, desc_end);
1401  language[i + 1] = get8(pp, desc_end);
1402  language[i + 2] = get8(pp, desc_end);
1403  language[i + 3] = ',';
1404  switch (get8(pp, desc_end)) {
1405  case 0x01: st->disposition |= AV_DISPOSITION_CLEAN_EFFECTS; break;
1406  case 0x02: st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED; break;
1407  case 0x03: st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED; break;
1408  }
1409  }
1410  if (i) {
1411  language[i - 1] = 0;
1412  av_dict_set(&st->metadata, "language", language, 0);
1413  }
1414  break;
1415  case 0x05: /* registration descriptor */
1416  st->codec->codec_tag = bytestream_get_le32(pp);
1417  av_dlog(fc, "reg_desc=%.4s\n", (char*)&st->codec->codec_tag);
1418  if (st->codec->codec_id == AV_CODEC_ID_NONE)
1419  mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
1420  break;
1421  case 0x52: /* stream identifier descriptor */
1422  st->stream_identifier = 1 + get8(pp, desc_end);
1423  break;
1424  default:
1425  break;
1426  }
1427  *pp = desc_end;
1428  return 0;
1429 }
1430 
1431 static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1432 {
1433  MpegTSContext *ts = filter->u.section_filter.opaque;
1434  SectionHeader h1, *h = &h1;
1435  PESContext *pes;
1436  AVStream *st;
1437  const uint8_t *p, *p_end, *desc_list_end;
1438  int program_info_length, pcr_pid, pid, stream_type;
1439  int desc_list_len;
1440  uint32_t prog_reg_desc = 0; /* registration descriptor */
1441 
1442  Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = {{ 0 }};
1443  int mp4_descr_count = 0;
1444  int i;
1445 
1446  av_dlog(ts->stream, "PMT: len %i\n", section_len);
1447  hex_dump_debug(ts->stream, section, section_len);
1448 
1449  p_end = section + section_len - 4;
1450  p = section;
1451  if (parse_section_header(h, &p, p_end) < 0)
1452  return;
1453 
1454  av_dlog(ts->stream, "sid=0x%x sec_num=%d/%d\n",
1455  h->id, h->sec_num, h->last_sec_num);
1456 
1457  if (h->tid != PMT_TID)
1458  return;
1459 
1460  clear_program(ts, h->id);
1461  pcr_pid = get16(&p, p_end);
1462  if (pcr_pid < 0)
1463  return;
1464  pcr_pid &= 0x1fff;
1465  add_pid_to_pmt(ts, h->id, pcr_pid);
1466  set_pcr_pid(ts->stream, h->id, pcr_pid);
1467 
1468  av_dlog(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
1469 
1470  program_info_length = get16(&p, p_end);
1471  if (program_info_length < 0)
1472  return;
1473  program_info_length &= 0xfff;
1474  while(program_info_length >= 2) {
1475  uint8_t tag, len;
1476  tag = get8(&p, p_end);
1477  len = get8(&p, p_end);
1478 
1479  av_dlog(ts->stream, "program tag: 0x%02x len=%d\n", tag, len);
1480 
1481  if(len > program_info_length - 2)
1482  //something else is broken, exit the program_descriptors_loop
1483  break;
1484  program_info_length -= len + 2;
1485  if (tag == 0x1d) { // IOD descriptor
1486  get8(&p, p_end); // scope
1487  get8(&p, p_end); // label
1488  len -= 2;
1489  mp4_read_iods(ts->stream, p, len, mp4_descr + mp4_descr_count,
1490  &mp4_descr_count, MAX_MP4_DESCR_COUNT);
1491  } else if (tag == 0x05 && len >= 4) { // registration descriptor
1492  prog_reg_desc = bytestream_get_le32(&p);
1493  len -= 4;
1494  }
1495  p += len;
1496  }
1497  p += program_info_length;
1498  if (p >= p_end)
1499  goto out;
1500 
1501  // stop parsing after pmt, we found header
1502  if (!ts->stream->nb_streams)
1503  ts->stop_parse = 2;
1504 
1505  for(;;) {
1506  st = 0;
1507  pes = NULL;
1508  stream_type = get8(&p, p_end);
1509  if (stream_type < 0)
1510  break;
1511  pid = get16(&p, p_end);
1512  if (pid < 0)
1513  break;
1514  pid &= 0x1fff;
1515  if (pid == ts->current_pid)
1516  break;
1517 
1518  /* now create stream */
1519  if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
1520  pes = ts->pids[pid]->u.pes_filter.opaque;
1521  if (!pes->st) {
1522  pes->st = avformat_new_stream(pes->stream, NULL);
1523  if (!pes->st)
1524  goto out;
1525  pes->st->id = pes->pid;
1526  }
1527  st = pes->st;
1528  } else if (stream_type != 0x13) {
1529  if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
1530  pes = add_pes_stream(ts, pid, pcr_pid);
1531  if (pes) {
1532  st = avformat_new_stream(pes->stream, NULL);
1533  if (!st)
1534  goto out;
1535  st->id = pes->pid;
1536  }
1537  } else {
1538  int idx = ff_find_stream_index(ts->stream, pid);
1539  if (idx >= 0) {
1540  st = ts->stream->streams[idx];
1541  } else {
1542  st = avformat_new_stream(ts->stream, NULL);
1543  if (!st)
1544  goto out;
1545  st->id = pid;
1547  }
1548  }
1549 
1550  if (!st)
1551  goto out;
1552 
1553  if (pes && !pes->stream_type)
1554  mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
1555 
1556  add_pid_to_pmt(ts, h->id, pid);
1557 
1559 
1560  desc_list_len = get16(&p, p_end);
1561  if (desc_list_len < 0)
1562  break;
1563  desc_list_len &= 0xfff;
1564  desc_list_end = p + desc_list_len;
1565  if (desc_list_end > p_end)
1566  break;
1567  for(;;) {
1568  if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p, desc_list_end,
1569  mp4_descr, mp4_descr_count, pid, ts) < 0)
1570  break;
1571 
1572  if (pes && prog_reg_desc == AV_RL32("HDMV") && stream_type == 0x83 && pes->sub_st) {
1574  pes->sub_st->codec->codec_tag = st->codec->codec_tag;
1575  }
1576  }
1577  p = desc_list_end;
1578  }
1579 
1580  out:
1581  for (i = 0; i < mp4_descr_count; i++)
1582  av_free(mp4_descr[i].dec_config_descr);
1583 }
1584 
1585 static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1586 {
1587  MpegTSContext *ts = filter->u.section_filter.opaque;
1588  SectionHeader h1, *h = &h1;
1589  const uint8_t *p, *p_end;
1590  int sid, pmt_pid;
1591  AVProgram *program;
1592 
1593  av_dlog(ts->stream, "PAT:\n");
1594  hex_dump_debug(ts->stream, section, section_len);
1595 
1596  p_end = section + section_len - 4;
1597  p = section;
1598  if (parse_section_header(h, &p, p_end) < 0)
1599  return;
1600  if (h->tid != PAT_TID)
1601  return;
1602 
1603  ts->stream->ts_id = h->id;
1604 
1605  clear_programs(ts);
1606  for(;;) {
1607  sid = get16(&p, p_end);
1608  if (sid < 0)
1609  break;
1610  pmt_pid = get16(&p, p_end);
1611  if (pmt_pid < 0)
1612  break;
1613  pmt_pid &= 0x1fff;
1614 
1615  if (pmt_pid == ts->current_pid)
1616  break;
1617 
1618  av_dlog(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
1619 
1620  if (sid == 0x0000) {
1621  /* NIT info */
1622  } else {
1623  program = av_new_program(ts->stream, sid);
1624  program->program_num = sid;
1625  program->pmt_pid = pmt_pid;
1626  if (ts->pids[pmt_pid])
1627  mpegts_close_filter(ts, ts->pids[pmt_pid]);
1628  mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
1629  add_pat_entry(ts, sid);
1630  add_pid_to_pmt(ts, sid, 0); //add pat pid to program
1631  add_pid_to_pmt(ts, sid, pmt_pid);
1632  }
1633  }
1634 
1635  if (sid < 0) {
1636  int i,j;
1637  for (j=0; j<ts->stream->nb_programs; j++) {
1638  for (i=0; i<ts->nb_prg; i++)
1639  if (ts->prg[i].id == ts->stream->programs[j]->id)
1640  break;
1641  if (i==ts->nb_prg)
1642  clear_avprogram(ts, ts->stream->programs[j]->id);
1643  }
1644  }
1645 }
1646 
1647 static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1648 {
1649  MpegTSContext *ts = filter->u.section_filter.opaque;
1650  SectionHeader h1, *h = &h1;
1651  const uint8_t *p, *p_end, *desc_list_end, *desc_end;
1652  int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
1653  char *name, *provider_name;
1654 
1655  av_dlog(ts->stream, "SDT:\n");
1656  hex_dump_debug(ts->stream, section, section_len);
1657 
1658  p_end = section + section_len - 4;
1659  p = section;
1660  if (parse_section_header(h, &p, p_end) < 0)
1661  return;
1662  if (h->tid != SDT_TID)
1663  return;
1664  onid = get16(&p, p_end);
1665  if (onid < 0)
1666  return;
1667  val = get8(&p, p_end);
1668  if (val < 0)
1669  return;
1670  for(;;) {
1671  sid = get16(&p, p_end);
1672  if (sid < 0)
1673  break;
1674  val = get8(&p, p_end);
1675  if (val < 0)
1676  break;
1677  desc_list_len = get16(&p, p_end);
1678  if (desc_list_len < 0)
1679  break;
1680  desc_list_len &= 0xfff;
1681  desc_list_end = p + desc_list_len;
1682  if (desc_list_end > p_end)
1683  break;
1684  for(;;) {
1685  desc_tag = get8(&p, desc_list_end);
1686  if (desc_tag < 0)
1687  break;
1688  desc_len = get8(&p, desc_list_end);
1689  desc_end = p + desc_len;
1690  if (desc_end > desc_list_end)
1691  break;
1692 
1693  av_dlog(ts->stream, "tag: 0x%02x len=%d\n",
1694  desc_tag, desc_len);
1695 
1696  switch(desc_tag) {
1697  case 0x48:
1698  service_type = get8(&p, p_end);
1699  if (service_type < 0)
1700  break;
1701  provider_name = getstr8(&p, p_end);
1702  if (!provider_name)
1703  break;
1704  name = getstr8(&p, p_end);
1705  if (name) {
1706  AVProgram *program = av_new_program(ts->stream, sid);
1707  if(program) {
1708  av_dict_set(&program->metadata, "service_name", name, 0);
1709  av_dict_set(&program->metadata, "service_provider", provider_name, 0);
1710  }
1711  }
1712  av_free(name);
1713  av_free(provider_name);
1714  break;
1715  default:
1716  break;
1717  }
1718  p = desc_end;
1719  }
1720  p = desc_list_end;
1721  }
1722 }
1723 
1724 /* handle one TS packet */
1725 static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
1726 {
1727  AVFormatContext *s = ts->stream;
1728  MpegTSFilter *tss;
1729  int len, pid, cc, expected_cc, cc_ok, afc, is_start, is_discontinuity,
1730  has_adaptation, has_payload;
1731  const uint8_t *p, *p_end;
1732  int64_t pos;
1733 
1734  pid = AV_RB16(packet + 1) & 0x1fff;
1735  if(pid && discard_pid(ts, pid))
1736  return 0;
1737  is_start = packet[1] & 0x40;
1738  tss = ts->pids[pid];
1739  if (ts->auto_guess && tss == NULL && is_start) {
1740  add_pes_stream(ts, pid, -1);
1741  tss = ts->pids[pid];
1742  }
1743  if (!tss)
1744  return 0;
1745  ts->current_pid = pid;
1746 
1747  afc = (packet[3] >> 4) & 3;
1748  if (afc == 0) /* reserved value */
1749  return 0;
1750  has_adaptation = afc & 2;
1751  has_payload = afc & 1;
1752  is_discontinuity = has_adaptation
1753  && packet[4] != 0 /* with length > 0 */
1754  && (packet[5] & 0x80); /* and discontinuity indicated */
1755 
1756  /* continuity check (currently not used) */
1757  cc = (packet[3] & 0xf);
1758  expected_cc = has_payload ? (tss->last_cc + 1) & 0x0f : tss->last_cc;
1759  cc_ok = pid == 0x1FFF // null packet PID
1760  || is_discontinuity
1761  || tss->last_cc < 0
1762  || expected_cc == cc;
1763 
1764  tss->last_cc = cc;
1765  if (!cc_ok) {
1766  av_log(ts->stream, AV_LOG_DEBUG,
1767  "Continuity check failed for pid %d expected %d got %d\n",
1768  pid, expected_cc, cc);
1769  if(tss->type == MPEGTS_PES) {
1770  PESContext *pc = tss->u.pes_filter.opaque;
1771  pc->flags |= AV_PKT_FLAG_CORRUPT;
1772  }
1773  }
1774 
1775  if (!has_payload)
1776  return 0;
1777  p = packet + 4;
1778  if (has_adaptation) {
1779  /* skip adaptation field */
1780  p += p[0] + 1;
1781  }
1782  /* if past the end of packet, ignore */
1783  p_end = packet + TS_PACKET_SIZE;
1784  if (p >= p_end)
1785  return 0;
1786 
1787  pos = avio_tell(ts->stream->pb);
1788  ts->pos47= pos % ts->raw_packet_size;
1789 
1790  if (tss->type == MPEGTS_SECTION) {
1791  if (is_start) {
1792  /* pointer field present */
1793  len = *p++;
1794  if (p + len > p_end)
1795  return 0;
1796  if (len && cc_ok) {
1797  /* write remaining section bytes */
1798  write_section_data(s, tss,
1799  p, len, 0);
1800  /* check whether filter has been closed */
1801  if (!ts->pids[pid])
1802  return 0;
1803  }
1804  p += len;
1805  if (p < p_end) {
1806  write_section_data(s, tss,
1807  p, p_end - p, 1);
1808  }
1809  } else {
1810  if (cc_ok) {
1811  write_section_data(s, tss,
1812  p, p_end - p, 0);
1813  }
1814  }
1815  } else {
1816  int ret;
1817  // Note: The position here points actually behind the current packet.
1818  if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
1819  pos - ts->raw_packet_size)) < 0)
1820  return ret;
1821  }
1822 
1823  return 0;
1824 }
1825 
1826 /* XXX: try to find a better synchro over several packets (use
1827  get_packet_size() ?) */
1829 {
1830  AVIOContext *pb = s->pb;
1831  int c, i;
1832 
1833  for(i = 0;i < MAX_RESYNC_SIZE; i++) {
1834  c = avio_r8(pb);
1835  if (url_feof(pb))
1836  return -1;
1837  if (c == 0x47) {
1838  avio_seek(pb, -1, SEEK_CUR);
1839  return 0;
1840  }
1841  }
1842  av_log(s, AV_LOG_ERROR, "max resync size reached, could not find sync byte\n");
1843  /* no sync found */
1844  return -1;
1845 }
1846 
1847 /* return -1 if error or EOF. Return 0 if OK. */
1848 static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size)
1849 {
1850  AVIOContext *pb = s->pb;
1851  int skip, len;
1852 
1853  for(;;) {
1854  len = avio_read(pb, buf, TS_PACKET_SIZE);
1855  if (len != TS_PACKET_SIZE)
1856  return len < 0 ? len : AVERROR_EOF;
1857  /* check packet sync byte */
1858  if (buf[0] != 0x47) {
1859  /* find a new packet start */
1860  avio_seek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1861  if (mpegts_resync(s) < 0)
1862  return AVERROR(EAGAIN);
1863  else
1864  continue;
1865  } else {
1866  skip = raw_packet_size - TS_PACKET_SIZE;
1867  if (skip > 0)
1868  avio_skip(pb, skip);
1869  break;
1870  }
1871  }
1872  return 0;
1873 }
1874 
1875 static int handle_packets(MpegTSContext *ts, int nb_packets)
1876 {
1877  AVFormatContext *s = ts->stream;
1879  int packet_num, ret = 0;
1880 
1881  if (avio_tell(s->pb) != ts->last_pos) {
1882  int i;
1883  av_dlog(ts->stream, "Skipping after seek\n");
1884  /* seek detected, flush pes buffer */
1885  for (i = 0; i < NB_PID_MAX; i++) {
1886  if (ts->pids[i]) {
1887  if (ts->pids[i]->type == MPEGTS_PES) {
1888  PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
1889  av_freep(&pes->buffer);
1890  pes->data_index = 0;
1891  pes->state = MPEGTS_SKIP; /* skip until pes header */
1892  }
1893  ts->pids[i]->last_cc = -1;
1894  }
1895  }
1896  }
1897 
1898  ts->stop_parse = 0;
1899  packet_num = 0;
1900  memset(packet + TS_PACKET_SIZE, 0, FF_INPUT_BUFFER_PADDING_SIZE);
1901  for(;;) {
1902  packet_num++;
1903  if (nb_packets != 0 && packet_num >= nb_packets ||
1904  ts->stop_parse > 1) {
1905  ret = AVERROR(EAGAIN);
1906  break;
1907  }
1908  if (ts->stop_parse > 0)
1909  break;
1910 
1911  ret = read_packet(s, packet, ts->raw_packet_size);
1912  if (ret != 0)
1913  break;
1914  ret = handle_packet(ts, packet);
1915  if (ret != 0)
1916  break;
1917  }
1918  ts->last_pos = avio_tell(s->pb);
1919  return ret;
1920 }
1921 
1923 {
1924  const int size= p->buf_size;
1925  int maxscore=0;
1926  int sumscore=0;
1927  int i;
1928  int check_count= size / TS_FEC_PACKET_SIZE;
1929 #define CHECK_COUNT 10
1930 #define CHECK_BLOCK 100
1931 
1932  if (check_count < CHECK_COUNT)
1933  return -1;
1934 
1935  for (i=0; i<check_count; i+=CHECK_BLOCK){
1936  int left = FFMIN(check_count - i, CHECK_BLOCK);
1937  int score = analyze(p->buf + TS_PACKET_SIZE *i, TS_PACKET_SIZE *left, TS_PACKET_SIZE , NULL);
1939  int fec_score = analyze(p->buf + TS_FEC_PACKET_SIZE *i, TS_FEC_PACKET_SIZE *left, TS_FEC_PACKET_SIZE , NULL);
1940  score = FFMAX3(score, dvhs_score, fec_score);
1941  sumscore += score;
1942  maxscore = FFMAX(maxscore, score);
1943  }
1944 
1945  sumscore = sumscore*CHECK_COUNT/check_count;
1946  maxscore = maxscore*CHECK_COUNT/CHECK_BLOCK;
1947 
1948  av_dlog(0, "TS score: %d %d\n", sumscore, maxscore);
1949 
1950  if (sumscore > 6) return AVPROBE_SCORE_MAX + sumscore - CHECK_COUNT;
1951  else if (maxscore > 6) return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;
1952  else return -1;
1953 }
1954 
1955 /* return the 90kHz PCR and the extension for the 27MHz PCR. return
1956  (-1) if not available */
1957 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1958  const uint8_t *packet)
1959 {
1960  int afc, len, flags;
1961  const uint8_t *p;
1962  unsigned int v;
1963 
1964  afc = (packet[3] >> 4) & 3;
1965  if (afc <= 1)
1966  return -1;
1967  p = packet + 4;
1968  len = p[0];
1969  p++;
1970  if (len == 0)
1971  return -1;
1972  flags = *p++;
1973  len--;
1974  if (!(flags & 0x10))
1975  return -1;
1976  if (len < 6)
1977  return -1;
1978  v = AV_RB32(p);
1979  *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1980  *ppcr_low = ((p[4] & 1) << 8) | p[5];
1981  return 0;
1982 }
1983 
1985 {
1986  MpegTSContext *ts = s->priv_data;
1987  AVIOContext *pb = s->pb;
1988  uint8_t buf[8*1024]={0};
1989  int len;
1990  int64_t pos;
1991 
1992  /* read the first 8192 bytes to get packet size */
1993  pos = avio_tell(pb);
1994  len = avio_read(pb, buf, sizeof(buf));
1995  ts->raw_packet_size = get_packet_size(buf, len);
1996  if (ts->raw_packet_size <= 0) {
1997  av_log(s, AV_LOG_WARNING, "Could not detect TS packet size, defaulting to non-FEC/DVHS\n");
1999  }
2000  ts->stream = s;
2001  ts->auto_guess = 0;
2002 
2003  if (s->iformat == &ff_mpegts_demuxer) {
2004  /* normal demux */
2005 
2006  /* first do a scan to get all the services */
2007  /* NOTE: We attempt to seek on non-seekable files as well, as the
2008  * probe buffer usually is big enough. Only warn if the seek failed
2009  * on files where the seek should work. */
2010  if (avio_seek(pb, pos, SEEK_SET) < 0)
2011  av_log(s, pb->seekable ? AV_LOG_ERROR : AV_LOG_INFO, "Unable to seek back to the start\n");
2012 
2014 
2016 
2018  /* if could not find service, enable auto_guess */
2019 
2020  ts->auto_guess = 1;
2021 
2022  av_dlog(ts->stream, "tuning done\n");
2023 
2025  } else {
2026  AVStream *st;
2027  int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
2028  int64_t pcrs[2], pcr_h;
2029  int packet_count[2];
2030  uint8_t packet[TS_PACKET_SIZE];
2031 
2032  /* only read packets */
2033 
2034  st = avformat_new_stream(s, NULL);
2035  if (!st)
2036  goto fail;
2037  avpriv_set_pts_info(st, 60, 1, 27000000);
2040 
2041  /* we iterate until we find two PCRs to estimate the bitrate */
2042  pcr_pid = -1;
2043  nb_pcrs = 0;
2044  nb_packets = 0;
2045  for(;;) {
2046  ret = read_packet(s, packet, ts->raw_packet_size);
2047  if (ret < 0)
2048  return -1;
2049  pid = AV_RB16(packet + 1) & 0x1fff;
2050  if ((pcr_pid == -1 || pcr_pid == pid) &&
2051  parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
2052  pcr_pid = pid;
2053  packet_count[nb_pcrs] = nb_packets;
2054  pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
2055  nb_pcrs++;
2056  if (nb_pcrs >= 2)
2057  break;
2058  }
2059  nb_packets++;
2060  }
2061 
2062  /* NOTE1: the bitrate is computed without the FEC */
2063  /* NOTE2: it is only the bitrate of the start of the stream */
2064  ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
2065  ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
2066  s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
2067  st->codec->bit_rate = s->bit_rate;
2068  st->start_time = ts->cur_pcr;
2069  av_dlog(ts->stream, "start=%0.3f pcr=%0.3f incr=%d\n",
2070  st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
2071  }
2072 
2073  avio_seek(pb, pos, SEEK_SET);
2074  return 0;
2075  fail:
2076  return -1;
2077 }
2078 
2079 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
2080 
2082  AVPacket *pkt)
2083 {
2084  MpegTSContext *ts = s->priv_data;
2085  int ret, i;
2086  int64_t pcr_h, next_pcr_h, pos;
2087  int pcr_l, next_pcr_l;
2088  uint8_t pcr_buf[12];
2089 
2090  if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
2091  return AVERROR(ENOMEM);
2092  pkt->pos= avio_tell(s->pb);
2093  ret = read_packet(s, pkt->data, ts->raw_packet_size);
2094  if (ret < 0) {
2095  av_free_packet(pkt);
2096  return ret;
2097  }
2098  if (ts->mpeg2ts_compute_pcr) {
2099  /* compute exact PCR for each packet */
2100  if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
2101  /* we read the next PCR (XXX: optimize it by using a bigger buffer */
2102  pos = avio_tell(s->pb);
2103  for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
2104  avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
2105  avio_read(s->pb, pcr_buf, 12);
2106  if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
2107  /* XXX: not precise enough */
2108  ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
2109  (i + 1);
2110  break;
2111  }
2112  }
2113  avio_seek(s->pb, pos, SEEK_SET);
2114  /* no next PCR found: we use previous increment */
2115  ts->cur_pcr = pcr_h * 300 + pcr_l;
2116  }
2117  pkt->pts = ts->cur_pcr;
2118  pkt->duration = ts->pcr_incr;
2119  ts->cur_pcr += ts->pcr_incr;
2120  }
2121  pkt->stream_index = 0;
2122  return 0;
2123 }
2124 
2126  AVPacket *pkt)
2127 {
2128  MpegTSContext *ts = s->priv_data;
2129  int ret, i;
2130 
2131  pkt->size = -1;
2132  ts->pkt = pkt;
2133  ret = handle_packets(ts, 0);
2134  if (ret < 0) {
2135  av_free_packet(ts->pkt);
2136  /* flush pes data left */
2137  for (i = 0; i < NB_PID_MAX; i++) {
2138  if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
2139  PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
2140  if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
2141  new_pes_packet(pes, pkt);
2142  pes->state = MPEGTS_SKIP;
2143  ret = 0;
2144  break;
2145  }
2146  }
2147  }
2148  }
2149 
2150  if (!ret && pkt->size < 0)
2151  ret = AVERROR(EINTR);
2152  return ret;
2153 }
2154 
2156 {
2157  MpegTSContext *ts = s->priv_data;
2158  int i;
2159 
2160  clear_programs(ts);
2161 
2162  for(i=0;i<NB_PID_MAX;i++)
2163  if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
2164 
2165  return 0;
2166 }
2167 
2168 static av_unused int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
2169  int64_t *ppos, int64_t pos_limit)
2170 {
2171  MpegTSContext *ts = s->priv_data;
2172  int64_t pos, timestamp;
2173  uint8_t buf[TS_PACKET_SIZE];
2174  int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
2175  pos = ((*ppos + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
2176  while(pos < pos_limit) {
2177  if (avio_seek(s->pb, pos, SEEK_SET) < 0)
2178  return AV_NOPTS_VALUE;
2179  if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
2180  return AV_NOPTS_VALUE;
2181  if (buf[0] != 0x47) {
2182  if (mpegts_resync(s) < 0)
2183  return AV_NOPTS_VALUE;
2184  pos = avio_tell(s->pb);
2185  continue;
2186  }
2187  if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
2188  parse_pcr(&timestamp, &pcr_l, buf) == 0) {
2189  *ppos = pos;
2190  return timestamp;
2191  }
2192  pos += ts->raw_packet_size;
2193  }
2194 
2195  return AV_NOPTS_VALUE;
2196 }
2197 
2198 static int64_t mpegts_get_dts(AVFormatContext *s, int stream_index,
2199  int64_t *ppos, int64_t pos_limit)
2200 {
2201  MpegTSContext *ts = s->priv_data;
2202  int64_t pos;
2203  pos = ((*ppos + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
2205  if (avio_seek(s->pb, pos, SEEK_SET) < 0)
2206  return AV_NOPTS_VALUE;
2207  while(pos < pos_limit) {
2208  int ret;
2209  AVPacket pkt;
2210  av_init_packet(&pkt);
2211  ret= av_read_frame(s, &pkt);
2212  if(ret < 0)
2213  return AV_NOPTS_VALUE;
2214  av_free_packet(&pkt);
2215  if(pkt.dts != AV_NOPTS_VALUE && pkt.pos >= 0){
2216  ff_reduce_index(s, pkt.stream_index);
2217  av_add_index_entry(s->streams[pkt.stream_index], pkt.pos, pkt.dts, 0, 0, AVINDEX_KEYFRAME /* FIXME keyframe? */);
2218  if(pkt.stream_index == stream_index){
2219  *ppos= pkt.pos;
2220  return pkt.dts;
2221  }
2222  }
2223  pos = pkt.pos;
2224  }
2225 
2226  return AV_NOPTS_VALUE;
2227 }
2228 
2229 /**************************************************************/
2230 /* parsing functions - called from other demuxers such as RTP */
2231 
2233 {
2234  MpegTSContext *ts;
2235 
2236  ts = av_mallocz(sizeof(MpegTSContext));
2237  if (!ts)
2238  return NULL;
2239  /* no stream case, currently used by RTP */
2241  ts->stream = s;
2242  ts->auto_guess = 1;
2245 
2246  return ts;
2247 }
2248 
2249 /* return the consumed length if a packet was output, or -1 if no
2250  packet is output */
2252  const uint8_t *buf, int len)
2253 {
2254  int len1;
2255 
2256  len1 = len;
2257  ts->pkt = pkt;
2258  for(;;) {
2259  ts->stop_parse = 0;
2260  if (len < TS_PACKET_SIZE)
2261  return -1;
2262  if (buf[0] != 0x47) {
2263  buf++;
2264  len--;
2265  } else {
2266  handle_packet(ts, buf);
2267  buf += TS_PACKET_SIZE;
2268  len -= TS_PACKET_SIZE;
2269  if (ts->stop_parse == 1)
2270  break;
2271  }
2272  }
2273  return len1 - len;
2274 }
2275 
2277 {
2278  int i;
2279 
2280  for(i=0;i<NB_PID_MAX;i++)
2281  av_free(ts->pids[i]);
2282  av_free(ts);
2283 }
2284 
2285 AVInputFormat ff_mpegts_demuxer = {
2286  .name = "mpegts",
2287  .long_name = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
2288  .priv_data_size = sizeof(MpegTSContext),
2293  .read_timestamp = mpegts_get_dts,
2295 };
2296 
2298  .name = "mpegtsraw",
2299  .long_name = NULL_IF_CONFIG_SMALL("raw MPEG-TS (MPEG-2 Transport Stream)"),
2300  .priv_data_size = sizeof(MpegTSContext),
2304  .read_timestamp = mpegts_get_dts,
2306  .priv_class = &mpegtsraw_class,
2307 };