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