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