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