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