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