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