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 #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] && 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  program = av_new_program(ts->stream, sid);
1626  program->program_num = sid;
1627  program->pmt_pid = pmt_pid;
1628  if (ts->pids[pmt_pid])
1629  mpegts_close_filter(ts, ts->pids[pmt_pid]);
1630  mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
1631  add_pat_entry(ts, sid);
1632  add_pid_to_pmt(ts, sid, 0); //add pat pid to program
1633  add_pid_to_pmt(ts, sid, pmt_pid);
1634  }
1635  }
1636 
1637  if (sid < 0) {
1638  int i,j;
1639  for (j=0; j<ts->stream->nb_programs; j++) {
1640  for (i=0; i<ts->nb_prg; i++)
1641  if (ts->prg[i].id == ts->stream->programs[j]->id)
1642  break;
1643  if (i==ts->nb_prg)
1644  clear_avprogram(ts, ts->stream->programs[j]->id);
1645  }
1646  }
1647 }
1648 
1649 static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1650 {
1651  MpegTSContext *ts = filter->u.section_filter.opaque;
1652  SectionHeader h1, *h = &h1;
1653  const uint8_t *p, *p_end, *desc_list_end, *desc_end;
1654  int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
1655  char *name, *provider_name;
1656 
1657  av_dlog(ts->stream, "SDT:\n");
1658  hex_dump_debug(ts->stream, section, section_len);
1659 
1660  p_end = section + section_len - 4;
1661  p = section;
1662  if (parse_section_header(h, &p, p_end) < 0)
1663  return;
1664  if (h->tid != SDT_TID)
1665  return;
1666  onid = get16(&p, p_end);
1667  if (onid < 0)
1668  return;
1669  val = get8(&p, p_end);
1670  if (val < 0)
1671  return;
1672  for(;;) {
1673  sid = get16(&p, p_end);
1674  if (sid < 0)
1675  break;
1676  val = get8(&p, p_end);
1677  if (val < 0)
1678  break;
1679  desc_list_len = get16(&p, p_end);
1680  if (desc_list_len < 0)
1681  break;
1682  desc_list_len &= 0xfff;
1683  desc_list_end = p + desc_list_len;
1684  if (desc_list_end > p_end)
1685  break;
1686  for(;;) {
1687  desc_tag = get8(&p, desc_list_end);
1688  if (desc_tag < 0)
1689  break;
1690  desc_len = get8(&p, desc_list_end);
1691  desc_end = p + desc_len;
1692  if (desc_end > desc_list_end)
1693  break;
1694 
1695  av_dlog(ts->stream, "tag: 0x%02x len=%d\n",
1696  desc_tag, desc_len);
1697 
1698  switch(desc_tag) {
1699  case 0x48:
1700  service_type = get8(&p, p_end);
1701  if (service_type < 0)
1702  break;
1703  provider_name = getstr8(&p, p_end);
1704  if (!provider_name)
1705  break;
1706  name = getstr8(&p, p_end);
1707  if (name) {
1708  AVProgram *program = av_new_program(ts->stream, sid);
1709  if(program) {
1710  av_dict_set(&program->metadata, "service_name", name, 0);
1711  av_dict_set(&program->metadata, "service_provider", provider_name, 0);
1712  }
1713  }
1714  av_free(name);
1715  av_free(provider_name);
1716  break;
1717  default:
1718  break;
1719  }
1720  p = desc_end;
1721  }
1722  p = desc_list_end;
1723  }
1724 }
1725 
1726 /* handle one TS packet */
1727 static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
1728 {
1729  AVFormatContext *s = ts->stream;
1730  MpegTSFilter *tss;
1731  int len, pid, cc, expected_cc, cc_ok, afc, is_start, is_discontinuity,
1732  has_adaptation, has_payload;
1733  const uint8_t *p, *p_end;
1734  int64_t pos;
1735 
1736  pid = AV_RB16(packet + 1) & 0x1fff;
1737  if(pid && discard_pid(ts, pid))
1738  return 0;
1739  is_start = packet[1] & 0x40;
1740  tss = ts->pids[pid];
1741  if (ts->auto_guess && tss == NULL && is_start) {
1742  add_pes_stream(ts, pid, -1);
1743  tss = ts->pids[pid];
1744  }
1745  if (!tss)
1746  return 0;
1747  ts->current_pid = pid;
1748 
1749  afc = (packet[3] >> 4) & 3;
1750  if (afc == 0) /* reserved value */
1751  return 0;
1752  has_adaptation = afc & 2;
1753  has_payload = afc & 1;
1754  is_discontinuity = has_adaptation
1755  && packet[4] != 0 /* with length > 0 */
1756  && (packet[5] & 0x80); /* and discontinuity indicated */
1757 
1758  /* continuity check (currently not used) */
1759  cc = (packet[3] & 0xf);
1760  expected_cc = has_payload ? (tss->last_cc + 1) & 0x0f : tss->last_cc;
1761  cc_ok = pid == 0x1FFF // null packet PID
1762  || is_discontinuity
1763  || tss->last_cc < 0
1764  || expected_cc == cc;
1765 
1766  tss->last_cc = cc;
1767  if (!cc_ok) {
1768  av_log(ts->stream, AV_LOG_DEBUG,
1769  "Continuity check failed for pid %d expected %d got %d\n",
1770  pid, expected_cc, cc);
1771  if(tss->type == MPEGTS_PES) {
1772  PESContext *pc = tss->u.pes_filter.opaque;
1773  pc->flags |= AV_PKT_FLAG_CORRUPT;
1774  }
1775  }
1776 
1777  if (!has_payload)
1778  return 0;
1779  p = packet + 4;
1780  if (has_adaptation) {
1781  /* skip adaptation field */
1782  p += p[0] + 1;
1783  }
1784  /* if past the end of packet, ignore */
1785  p_end = packet + TS_PACKET_SIZE;
1786  if (p >= p_end)
1787  return 0;
1788 
1789  pos = avio_tell(ts->stream->pb);
1790  ts->pos47= pos % ts->raw_packet_size;
1791 
1792  if (tss->type == MPEGTS_SECTION) {
1793  if (is_start) {
1794  /* pointer field present */
1795  len = *p++;
1796  if (p + len > p_end)
1797  return 0;
1798  if (len && cc_ok) {
1799  /* write remaining section bytes */
1800  write_section_data(s, tss,
1801  p, len, 0);
1802  /* check whether filter has been closed */
1803  if (!ts->pids[pid])
1804  return 0;
1805  }
1806  p += len;
1807  if (p < p_end) {
1808  write_section_data(s, tss,
1809  p, p_end - p, 1);
1810  }
1811  } else {
1812  if (cc_ok) {
1813  write_section_data(s, tss,
1814  p, p_end - p, 0);
1815  }
1816  }
1817  } else {
1818  int ret;
1819  // Note: The position here points actually behind the current packet.
1820  if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
1821  pos - ts->raw_packet_size)) < 0)
1822  return ret;
1823  }
1824 
1825  return 0;
1826 }
1827 
1828 /* XXX: try to find a better synchro over several packets (use
1829  get_packet_size() ?) */
1831 {
1832  AVIOContext *pb = s->pb;
1833  int c, i;
1834 
1835  for(i = 0;i < MAX_RESYNC_SIZE; i++) {
1836  c = avio_r8(pb);
1837  if (url_feof(pb))
1838  return -1;
1839  if (c == 0x47) {
1840  avio_seek(pb, -1, SEEK_CUR);
1841  return 0;
1842  }
1843  }
1844  av_log(s, AV_LOG_ERROR, "max resync size reached, could not find sync byte\n");
1845  /* no sync found */
1846  return -1;
1847 }
1848 
1849 /* return -1 if error or EOF. Return 0 if OK. */
1850 static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size)
1851 {
1852  AVIOContext *pb = s->pb;
1853  int skip, len;
1854 
1855  for(;;) {
1856  len = avio_read(pb, buf, TS_PACKET_SIZE);
1857  if (len != TS_PACKET_SIZE)
1858  return len < 0 ? len : AVERROR_EOF;
1859  /* check packet sync byte */
1860  if (buf[0] != 0x47) {
1861  /* find a new packet start */
1862  avio_seek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1863  if (mpegts_resync(s) < 0)
1864  return AVERROR(EAGAIN);
1865  else
1866  continue;
1867  } else {
1868  skip = raw_packet_size - TS_PACKET_SIZE;
1869  if (skip > 0)
1870  avio_skip(pb, skip);
1871  break;
1872  }
1873  }
1874  return 0;
1875 }
1876 
1877 static int handle_packets(MpegTSContext *ts, int nb_packets)
1878 {
1879  AVFormatContext *s = ts->stream;
1881  int packet_num, ret = 0;
1882 
1883  if (avio_tell(s->pb) != ts->last_pos) {
1884  int i;
1885  av_dlog(ts->stream, "Skipping after seek\n");
1886  /* seek detected, flush pes buffer */
1887  for (i = 0; i < NB_PID_MAX; i++) {
1888  if (ts->pids[i]) {
1889  if (ts->pids[i]->type == MPEGTS_PES) {
1890  PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
1891  av_freep(&pes->buffer);
1892  pes->data_index = 0;
1893  pes->state = MPEGTS_SKIP; /* skip until pes header */
1894  }
1895  ts->pids[i]->last_cc = -1;
1896  }
1897  }
1898  }
1899 
1900  ts->stop_parse = 0;
1901  packet_num = 0;
1902  memset(packet + TS_PACKET_SIZE, 0, FF_INPUT_BUFFER_PADDING_SIZE);
1903  for(;;) {
1904  packet_num++;
1905  if (nb_packets != 0 && packet_num >= nb_packets ||
1906  ts->stop_parse > 1) {
1907  ret = AVERROR(EAGAIN);
1908  break;
1909  }
1910  if (ts->stop_parse > 0)
1911  break;
1912 
1913  ret = read_packet(s, packet, ts->raw_packet_size);
1914  if (ret != 0)
1915  break;
1916  ret = handle_packet(ts, packet);
1917  if (ret != 0)
1918  break;
1919  }
1920  ts->last_pos = avio_tell(s->pb);
1921  return ret;
1922 }
1923 
1925 {
1926  const int size= p->buf_size;
1927  int maxscore=0;
1928  int sumscore=0;
1929  int i;
1930  int check_count= size / TS_FEC_PACKET_SIZE;
1931 #define CHECK_COUNT 10
1932 #define CHECK_BLOCK 100
1933 
1934  if (check_count < CHECK_COUNT)
1935  return -1;
1936 
1937  for (i=0; i<check_count; i+=CHECK_BLOCK){
1938  int left = FFMIN(check_count - i, CHECK_BLOCK);
1939  int score = analyze(p->buf + TS_PACKET_SIZE *i, TS_PACKET_SIZE *left, TS_PACKET_SIZE , NULL);
1941  int fec_score = analyze(p->buf + TS_FEC_PACKET_SIZE *i, TS_FEC_PACKET_SIZE *left, TS_FEC_PACKET_SIZE , NULL);
1942  score = FFMAX3(score, dvhs_score, fec_score);
1943  sumscore += score;
1944  maxscore = FFMAX(maxscore, score);
1945  }
1946 
1947  sumscore = sumscore*CHECK_COUNT/check_count;
1948  maxscore = maxscore*CHECK_COUNT/CHECK_BLOCK;
1949 
1950  av_dlog(0, "TS score: %d %d\n", sumscore, maxscore);
1951 
1952  if (sumscore > 6) return AVPROBE_SCORE_MAX + sumscore - CHECK_COUNT;
1953  else if (maxscore > 6) return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;
1954  else return -1;
1955 }
1956 
1957 /* return the 90kHz PCR and the extension for the 27MHz PCR. return
1958  (-1) if not available */
1959 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1960  const uint8_t *packet)
1961 {
1962  int afc, len, flags;
1963  const uint8_t *p;
1964  unsigned int v;
1965 
1966  afc = (packet[3] >> 4) & 3;
1967  if (afc <= 1)
1968  return -1;
1969  p = packet + 4;
1970  len = p[0];
1971  p++;
1972  if (len == 0)
1973  return -1;
1974  flags = *p++;
1975  len--;
1976  if (!(flags & 0x10))
1977  return -1;
1978  if (len < 6)
1979  return -1;
1980  v = AV_RB32(p);
1981  *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1982  *ppcr_low = ((p[4] & 1) << 8) | p[5];
1983  return 0;
1984 }
1985 
1987 {
1988  MpegTSContext *ts = s->priv_data;
1989  AVIOContext *pb = s->pb;
1990  uint8_t buf[8*1024]={0};
1991  int len;
1992  int64_t pos;
1993 
1994  /* read the first 8192 bytes to get packet size */
1995  pos = avio_tell(pb);
1996  len = avio_read(pb, buf, sizeof(buf));
1997  ts->raw_packet_size = get_packet_size(buf, len);
1998  if (ts->raw_packet_size <= 0) {
1999  av_log(s, AV_LOG_WARNING, "Could not detect TS packet size, defaulting to non-FEC/DVHS\n");
2001  }
2002  ts->stream = s;
2003  ts->auto_guess = 0;
2004 
2005  if (s->iformat == &ff_mpegts_demuxer) {
2006  /* normal demux */
2007 
2008  /* first do a scan to get all the services */
2009  /* NOTE: We attempt to seek on non-seekable files as well, as the
2010  * probe buffer usually is big enough. Only warn if the seek failed
2011  * on files where the seek should work. */
2012  if (avio_seek(pb, pos, SEEK_SET) < 0)
2013  av_log(s, pb->seekable ? AV_LOG_ERROR : AV_LOG_INFO, "Unable to seek back to the start\n");
2014 
2016 
2018 
2020  /* if could not find service, enable auto_guess */
2021 
2022  ts->auto_guess = 1;
2023 
2024  av_dlog(ts->stream, "tuning done\n");
2025 
2027  } else {
2028  AVStream *st;
2029  int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
2030  int64_t pcrs[2], pcr_h;
2031  int packet_count[2];
2032  uint8_t packet[TS_PACKET_SIZE];
2033 
2034  /* only read packets */
2035 
2036  st = avformat_new_stream(s, NULL);
2037  if (!st)
2038  goto fail;
2039  avpriv_set_pts_info(st, 60, 1, 27000000);
2042 
2043  /* we iterate until we find two PCRs to estimate the bitrate */
2044  pcr_pid = -1;
2045  nb_pcrs = 0;
2046  nb_packets = 0;
2047  for(;;) {
2048  ret = read_packet(s, packet, ts->raw_packet_size);
2049  if (ret < 0)
2050  return -1;
2051  pid = AV_RB16(packet + 1) & 0x1fff;
2052  if ((pcr_pid == -1 || pcr_pid == pid) &&
2053  parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
2054  pcr_pid = pid;
2055  packet_count[nb_pcrs] = nb_packets;
2056  pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
2057  nb_pcrs++;
2058  if (nb_pcrs >= 2)
2059  break;
2060  }
2061  nb_packets++;
2062  }
2063 
2064  /* NOTE1: the bitrate is computed without the FEC */
2065  /* NOTE2: it is only the bitrate of the start of the stream */
2066  ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
2067  ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
2068  s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
2069  st->codec->bit_rate = s->bit_rate;
2070  st->start_time = ts->cur_pcr;
2071  av_dlog(ts->stream, "start=%0.3f pcr=%0.3f incr=%d\n",
2072  st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
2073  }
2074 
2075  avio_seek(pb, pos, SEEK_SET);
2076  return 0;
2077  fail:
2078  return -1;
2079 }
2080 
2081 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
2082 
2084  AVPacket *pkt)
2085 {
2086  MpegTSContext *ts = s->priv_data;
2087  int ret, i;
2088  int64_t pcr_h, next_pcr_h, pos;
2089  int pcr_l, next_pcr_l;
2090  uint8_t pcr_buf[12];
2091 
2092  if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
2093  return AVERROR(ENOMEM);
2094  pkt->pos= avio_tell(s->pb);
2095  ret = read_packet(s, pkt->data, ts->raw_packet_size);
2096  if (ret < 0) {
2097  av_free_packet(pkt);
2098  return ret;
2099  }
2100  if (ts->mpeg2ts_compute_pcr) {
2101  /* compute exact PCR for each packet */
2102  if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
2103  /* we read the next PCR (XXX: optimize it by using a bigger buffer */
2104  pos = avio_tell(s->pb);
2105  for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
2106  avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
2107  avio_read(s->pb, pcr_buf, 12);
2108  if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
2109  /* XXX: not precise enough */
2110  ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
2111  (i + 1);
2112  break;
2113  }
2114  }
2115  avio_seek(s->pb, pos, SEEK_SET);
2116  /* no next PCR found: we use previous increment */
2117  ts->cur_pcr = pcr_h * 300 + pcr_l;
2118  }
2119  pkt->pts = ts->cur_pcr;
2120  pkt->duration = ts->pcr_incr;
2121  ts->cur_pcr += ts->pcr_incr;
2122  }
2123  pkt->stream_index = 0;
2124  return 0;
2125 }
2126 
2128  AVPacket *pkt)
2129 {
2130  MpegTSContext *ts = s->priv_data;
2131  int ret, i;
2132 
2133  pkt->size = -1;
2134  ts->pkt = pkt;
2135  ret = handle_packets(ts, 0);
2136  if (ret < 0) {
2137  av_free_packet(ts->pkt);
2138  /* flush pes data left */
2139  for (i = 0; i < NB_PID_MAX; i++) {
2140  if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
2141  PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
2142  if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
2143  new_pes_packet(pes, pkt);
2144  pes->state = MPEGTS_SKIP;
2145  ret = 0;
2146  break;
2147  }
2148  }
2149  }
2150  }
2151 
2152  if (!ret && pkt->size < 0)
2153  ret = AVERROR(EINTR);
2154  return ret;
2155 }
2156 
2157 static void mpegts_free(MpegTSContext *ts)
2158 {
2159  int i;
2160 
2161  clear_programs(ts);
2162 
2163  for(i=0;i<NB_PID_MAX;i++)
2164  if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
2165 }
2166 
2168 {
2169  MpegTSContext *ts = s->priv_data;
2170  mpegts_free(ts);
2171  return 0;
2172 }
2173 
2174 static av_unused int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
2175  int64_t *ppos, int64_t pos_limit)
2176 {
2177  MpegTSContext *ts = s->priv_data;
2178  int64_t pos, timestamp;
2179  uint8_t buf[TS_PACKET_SIZE];
2180  int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
2181  pos = ((*ppos + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
2182  while(pos < pos_limit) {
2183  if (avio_seek(s->pb, pos, SEEK_SET) < 0)
2184  return AV_NOPTS_VALUE;
2185  if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
2186  return AV_NOPTS_VALUE;
2187  if (buf[0] != 0x47) {
2188  if (mpegts_resync(s) < 0)
2189  return AV_NOPTS_VALUE;
2190  pos = avio_tell(s->pb);
2191  continue;
2192  }
2193  if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
2194  parse_pcr(&timestamp, &pcr_l, buf) == 0) {
2195  *ppos = pos;
2196  return timestamp;
2197  }
2198  pos += ts->raw_packet_size;
2199  }
2200 
2201  return AV_NOPTS_VALUE;
2202 }
2203 
2204 static int64_t mpegts_get_dts(AVFormatContext *s, int stream_index,
2205  int64_t *ppos, int64_t pos_limit)
2206 {
2207  MpegTSContext *ts = s->priv_data;
2208  int64_t pos;
2209  pos = ((*ppos + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
2211  if (avio_seek(s->pb, pos, SEEK_SET) < 0)
2212  return AV_NOPTS_VALUE;
2213  while(pos < pos_limit) {
2214  int ret;
2215  AVPacket pkt;
2216  av_init_packet(&pkt);
2217  ret= av_read_frame(s, &pkt);
2218  if(ret < 0)
2219  return AV_NOPTS_VALUE;
2220  av_free_packet(&pkt);
2221  if(pkt.dts != AV_NOPTS_VALUE && pkt.pos >= 0){
2222  ff_reduce_index(s, pkt.stream_index);
2223  av_add_index_entry(s->streams[pkt.stream_index], pkt.pos, pkt.dts, 0, 0, AVINDEX_KEYFRAME /* FIXME keyframe? */);
2224  if(pkt.stream_index == stream_index){
2225  *ppos= pkt.pos;
2226  return pkt.dts;
2227  }
2228  }
2229  pos = pkt.pos;
2230  }
2231 
2232  return AV_NOPTS_VALUE;
2233 }
2234 
2235 /**************************************************************/
2236 /* parsing functions - called from other demuxers such as RTP */
2237 
2239 {
2240  MpegTSContext *ts;
2241 
2242  ts = av_mallocz(sizeof(MpegTSContext));
2243  if (!ts)
2244  return NULL;
2245  /* no stream case, currently used by RTP */
2247  ts->stream = s;
2248  ts->auto_guess = 1;
2251 
2252  return ts;
2253 }
2254 
2255 /* return the consumed length if a packet was output, or -1 if no
2256  packet is output */
2258  const uint8_t *buf, int len)
2259 {
2260  int len1;
2261 
2262  len1 = len;
2263  ts->pkt = pkt;
2264  for(;;) {
2265  ts->stop_parse = 0;
2266  if (len < TS_PACKET_SIZE)
2267  return -1;
2268  if (buf[0] != 0x47) {
2269  buf++;
2270  len--;
2271  } else {
2272  handle_packet(ts, buf);
2273  buf += TS_PACKET_SIZE;
2274  len -= TS_PACKET_SIZE;
2275  if (ts->stop_parse == 1)
2276  break;
2277  }
2278  }
2279  return len1 - len;
2280 }
2281 
2283 {
2284  mpegts_free(ts);
2285  av_free(ts);
2286 }
2287 
2288 AVInputFormat ff_mpegts_demuxer = {
2289  .name = "mpegts",
2290  .long_name = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
2291  .priv_data_size = sizeof(MpegTSContext),
2296  .read_timestamp = mpegts_get_dts,
2298 };
2299 
2301  .name = "mpegtsraw",
2302  .long_name = NULL_IF_CONFIG_SMALL("raw MPEG-TS (MPEG-2 Transport Stream)"),
2303  .priv_data_size = sizeof(MpegTSContext),
2307  .read_timestamp = mpegts_get_dts,
2309  .priv_class = &mpegtsraw_class,
2310 };