]> git.sesse.net Git - ffmpeg/blob - libavformat/mpegts.c
Merge commit '3ea5f64ffff0a51f62922efd2e2bc231b13b2179'
[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 x=0;
456     int best_score=0;
457
458     memset(stat, 0, packet_size*sizeof(int));
459
460     for(x=i=0; i<size-3; i++){
461         if(buf[i] == 0x47 && !(buf[i+1] & 0x80) && buf[i+3] != 0x47){
462             stat[x]++;
463             if(stat[x] > best_score){
464                 best_score= stat[x];
465                 if(index) *index= x;
466             }
467         }
468
469         x++;
470         if(x == packet_size) x= 0;
471     }
472
473     return best_score;
474 }
475
476 /* autodetect fec presence. Must have at least 1024 bytes  */
477 static int get_packet_size(const uint8_t *buf, int size)
478 {
479     int score, fec_score, dvhs_score;
480
481     if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
482         return -1;
483
484     score    = analyze(buf, size, TS_PACKET_SIZE, NULL);
485     dvhs_score    = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
486     fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
487     av_dlog(NULL, "score: %d, dvhs_score: %d, fec_score: %d \n",
488             score, dvhs_score, fec_score);
489
490     if     (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
491     else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
492     else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
493     else                       return -1;
494 }
495
496 typedef struct SectionHeader {
497     uint8_t tid;
498     uint16_t id;
499     uint8_t version;
500     uint8_t sec_num;
501     uint8_t last_sec_num;
502 } SectionHeader;
503
504 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
505 {
506     const uint8_t *p;
507     int c;
508
509     p = *pp;
510     if (p >= p_end)
511         return -1;
512     c = *p++;
513     *pp = p;
514     return c;
515 }
516
517 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
518 {
519     const uint8_t *p;
520     int c;
521
522     p = *pp;
523     if ((p + 1) >= p_end)
524         return -1;
525     c = AV_RB16(p);
526     p += 2;
527     *pp = p;
528     return c;
529 }
530
531 /* read and allocate a DVB string preceded by its length */
532 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
533 {
534     int len;
535     const uint8_t *p;
536     char *str;
537
538     p = *pp;
539     len = get8(&p, p_end);
540     if (len < 0)
541         return NULL;
542     if ((p + len) > p_end)
543         return NULL;
544     str = av_malloc(len + 1);
545     if (!str)
546         return NULL;
547     memcpy(str, p, len);
548     str[len] = '\0';
549     p += len;
550     *pp = p;
551     return str;
552 }
553
554 static int parse_section_header(SectionHeader *h,
555                                 const uint8_t **pp, const uint8_t *p_end)
556 {
557     int val;
558
559     val = get8(pp, p_end);
560     if (val < 0)
561         return -1;
562     h->tid = val;
563     *pp += 2;
564     val = get16(pp, p_end);
565     if (val < 0)
566         return -1;
567     h->id = val;
568     val = get8(pp, p_end);
569     if (val < 0)
570         return -1;
571     h->version = (val >> 1) & 0x1f;
572     val = get8(pp, p_end);
573     if (val < 0)
574         return -1;
575     h->sec_num = val;
576     val = get8(pp, p_end);
577     if (val < 0)
578         return -1;
579     h->last_sec_num = val;
580     return 0;
581 }
582
583 typedef struct {
584     uint32_t stream_type;
585     enum AVMediaType codec_type;
586     enum AVCodecID codec_id;
587 } StreamType;
588
589 static const StreamType ISO_types[] = {
590     { 0x01, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
591     { 0x02, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
592     { 0x03, AVMEDIA_TYPE_AUDIO,        AV_CODEC_ID_MP3 },
593     { 0x04, AVMEDIA_TYPE_AUDIO,        AV_CODEC_ID_MP3 },
594     { 0x0f, AVMEDIA_TYPE_AUDIO,        AV_CODEC_ID_AAC },
595     { 0x10, AVMEDIA_TYPE_VIDEO,      AV_CODEC_ID_MPEG4 },
596     /* Makito encoder sets stream type 0x11 for AAC,
597      * so auto-detect LOAS/LATM instead of hardcoding it. */
598 #if !CONFIG_LOAS_DEMUXER
599     { 0x11, AVMEDIA_TYPE_AUDIO,   AV_CODEC_ID_AAC_LATM }, /* LATM syntax */
600 #endif
601     { 0x1b, AVMEDIA_TYPE_VIDEO,       AV_CODEC_ID_H264 },
602     { 0x24, AVMEDIA_TYPE_VIDEO,       AV_CODEC_ID_HEVC },
603     { 0x42, AVMEDIA_TYPE_VIDEO,       AV_CODEC_ID_CAVS },
604     { 0xd1, AVMEDIA_TYPE_VIDEO,      AV_CODEC_ID_DIRAC },
605     { 0xea, AVMEDIA_TYPE_VIDEO,        AV_CODEC_ID_VC1 },
606     { 0 },
607 };
608
609 static const StreamType HDMV_types[] = {
610     { 0x80, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_PCM_BLURAY },
611     { 0x81, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
612     { 0x82, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
613     { 0x83, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_TRUEHD },
614     { 0x84, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 },
615     { 0x85, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD */
616     { 0x86, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD MASTER*/
617     { 0xa1, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 }, /* E-AC3 Secondary Audio */
618     { 0xa2, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },  /* DTS Express Secondary Audio */
619     { 0x90, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_HDMV_PGS_SUBTITLE },
620     { 0 },
621 };
622
623 /* ATSC ? */
624 static const StreamType MISC_types[] = {
625     { 0x81, AVMEDIA_TYPE_AUDIO,   AV_CODEC_ID_AC3 },
626     { 0x8a, AVMEDIA_TYPE_AUDIO,   AV_CODEC_ID_DTS },
627     { 0 },
628 };
629
630 static const StreamType REGD_types[] = {
631     { MKTAG('d','r','a','c'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC },
632     { MKTAG('A','C','-','3'), AVMEDIA_TYPE_AUDIO,   AV_CODEC_ID_AC3 },
633     { MKTAG('B','S','S','D'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_S302M },
634     { MKTAG('D','T','S','1'), AVMEDIA_TYPE_AUDIO,   AV_CODEC_ID_DTS },
635     { MKTAG('D','T','S','2'), AVMEDIA_TYPE_AUDIO,   AV_CODEC_ID_DTS },
636     { MKTAG('D','T','S','3'), AVMEDIA_TYPE_AUDIO,   AV_CODEC_ID_DTS },
637     { MKTAG('H','E','V','C'), AVMEDIA_TYPE_VIDEO,  AV_CODEC_ID_HEVC },
638     { MKTAG('K','L','V','A'), AVMEDIA_TYPE_DATA,    AV_CODEC_ID_SMPTE_KLV },
639     { MKTAG('V','C','-','1'), AVMEDIA_TYPE_VIDEO,   AV_CODEC_ID_VC1 },
640     { 0 },
641 };
642
643 static const StreamType METADATA_types[] = {
644     { MKTAG('K','L','V','A'), AVMEDIA_TYPE_DATA, AV_CODEC_ID_SMPTE_KLV },
645     { 0 },
646 };
647
648 /* descriptor present */
649 static const StreamType DESC_types[] = {
650     { 0x6a, AVMEDIA_TYPE_AUDIO,             AV_CODEC_ID_AC3 }, /* AC-3 descriptor */
651     { 0x7a, AVMEDIA_TYPE_AUDIO,            AV_CODEC_ID_EAC3 }, /* E-AC-3 descriptor */
652     { 0x7b, AVMEDIA_TYPE_AUDIO,             AV_CODEC_ID_DTS },
653     { 0x56, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_TELETEXT },
654     { 0x59, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
655     { 0 },
656 };
657
658 static void mpegts_find_stream_type(AVStream *st,
659                                     uint32_t stream_type, const StreamType *types)
660 {
661     if (avcodec_is_open(st->codec)) {
662         av_log(NULL, AV_LOG_DEBUG, "cannot set stream info, codec is open\n");
663         return;
664     }
665
666     for (; types->stream_type; types++) {
667         if (stream_type == types->stream_type) {
668             st->codec->codec_type = types->codec_type;
669             st->codec->codec_id   = types->codec_id;
670             st->request_probe     = 0;
671             return;
672         }
673     }
674 }
675
676 static int mpegts_set_stream_info(AVStream *st, PESContext *pes,
677                                   uint32_t stream_type, uint32_t prog_reg_desc)
678 {
679     int old_codec_type= st->codec->codec_type;
680     int old_codec_id  = st->codec->codec_id;
681
682     if (avcodec_is_open(st->codec)) {
683         av_log(pes->stream, AV_LOG_DEBUG, "cannot set stream info, codec is open\n");
684         return 0;
685     }
686
687     avpriv_set_pts_info(st, 33, 1, 90000);
688     st->priv_data = pes;
689     st->codec->codec_type = AVMEDIA_TYPE_DATA;
690     st->codec->codec_id   = AV_CODEC_ID_NONE;
691     st->need_parsing = AVSTREAM_PARSE_FULL;
692     pes->st = st;
693     pes->stream_type = stream_type;
694
695     av_log(pes->stream, AV_LOG_DEBUG,
696            "stream=%d stream_type=%x pid=%x prog_reg_desc=%.4s\n",
697            st->index, pes->stream_type, pes->pid, (char*)&prog_reg_desc);
698
699     st->codec->codec_tag = pes->stream_type;
700
701     mpegts_find_stream_type(st, pes->stream_type, ISO_types);
702     if ((prog_reg_desc == AV_RL32("HDMV") ||
703          prog_reg_desc == AV_RL32("HDPR")) &&
704         st->codec->codec_id == AV_CODEC_ID_NONE) {
705         mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
706         if (pes->stream_type == 0x83) {
707             // HDMV TrueHD streams also contain an AC3 coded version of the
708             // audio track - add a second stream for this
709             AVStream *sub_st;
710             // priv_data cannot be shared between streams
711             PESContext *sub_pes = av_malloc(sizeof(*sub_pes));
712             if (!sub_pes)
713                 return AVERROR(ENOMEM);
714             memcpy(sub_pes, pes, sizeof(*sub_pes));
715
716             sub_st = avformat_new_stream(pes->stream, NULL);
717             if (!sub_st) {
718                 av_free(sub_pes);
719                 return AVERROR(ENOMEM);
720             }
721
722             sub_st->id = pes->pid;
723             avpriv_set_pts_info(sub_st, 33, 1, 90000);
724             sub_st->priv_data = sub_pes;
725             sub_st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
726             sub_st->codec->codec_id   = AV_CODEC_ID_AC3;
727             sub_st->need_parsing = AVSTREAM_PARSE_FULL;
728             sub_pes->sub_st = pes->sub_st = sub_st;
729         }
730     }
731     if (st->codec->codec_id == AV_CODEC_ID_NONE)
732         mpegts_find_stream_type(st, pes->stream_type, MISC_types);
733     if (st->codec->codec_id == AV_CODEC_ID_NONE){
734         st->codec->codec_id  = old_codec_id;
735         st->codec->codec_type= old_codec_type;
736     }
737
738     return 0;
739 }
740
741 static void new_pes_packet(PESContext *pes, AVPacket *pkt)
742 {
743     av_init_packet(pkt);
744
745     pkt->buf  = pes->buffer;
746     pkt->data = pes->buffer->data;
747     pkt->size = pes->data_index;
748
749     if(pes->total_size != MAX_PES_PAYLOAD &&
750        pes->pes_header_size + pes->data_index != pes->total_size + PES_START_SIZE) {
751         av_log(pes->stream, AV_LOG_WARNING, "PES packet size mismatch\n");
752         pes->flags |= AV_PKT_FLAG_CORRUPT;
753     }
754     memset(pkt->data+pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
755
756     // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID
757     if (pes->sub_st && pes->stream_type == 0x83 && pes->extended_stream_id == 0x76)
758         pkt->stream_index = pes->sub_st->index;
759     else
760         pkt->stream_index = pes->st->index;
761     pkt->pts = pes->pts;
762     pkt->dts = pes->dts;
763     /* store position of first TS packet of this PES packet */
764     pkt->pos = pes->ts_packet_pos;
765     pkt->flags = pes->flags;
766
767     /* reset pts values */
768     pes->pts = AV_NOPTS_VALUE;
769     pes->dts = AV_NOPTS_VALUE;
770     pes->buffer = NULL;
771     pes->data_index = 0;
772     pes->flags = 0;
773 }
774
775 static uint64_t get_ts64(GetBitContext *gb, int bits)
776 {
777     if (get_bits_left(gb) < bits)
778         return AV_NOPTS_VALUE;
779     return get_bits64(gb, bits);
780 }
781
782 static int read_sl_header(PESContext *pes, SLConfigDescr *sl, const uint8_t *buf, int buf_size)
783 {
784     GetBitContext gb;
785     int au_start_flag = 0, au_end_flag = 0, ocr_flag = 0, idle_flag = 0;
786     int padding_flag = 0, padding_bits = 0, inst_bitrate_flag = 0;
787     int dts_flag = -1, cts_flag = -1;
788     int64_t dts = AV_NOPTS_VALUE, cts = AV_NOPTS_VALUE;
789
790     init_get_bits(&gb, buf, buf_size*8);
791
792     if (sl->use_au_start)
793         au_start_flag = get_bits1(&gb);
794     if (sl->use_au_end)
795         au_end_flag = get_bits1(&gb);
796     if (!sl->use_au_start && !sl->use_au_end)
797         au_start_flag = au_end_flag = 1;
798     if (sl->ocr_len > 0)
799         ocr_flag = get_bits1(&gb);
800     if (sl->use_idle)
801         idle_flag = get_bits1(&gb);
802     if (sl->use_padding)
803         padding_flag = get_bits1(&gb);
804     if (padding_flag)
805         padding_bits = get_bits(&gb, 3);
806
807     if (!idle_flag && (!padding_flag || padding_bits != 0)) {
808         if (sl->packet_seq_num_len)
809             skip_bits_long(&gb, sl->packet_seq_num_len);
810         if (sl->degr_prior_len)
811             if (get_bits1(&gb))
812                 skip_bits(&gb, sl->degr_prior_len);
813         if (ocr_flag)
814             skip_bits_long(&gb, sl->ocr_len);
815         if (au_start_flag) {
816             if (sl->use_rand_acc_pt)
817                 get_bits1(&gb);
818             if (sl->au_seq_num_len > 0)
819                 skip_bits_long(&gb, sl->au_seq_num_len);
820             if (sl->use_timestamps) {
821                 dts_flag = get_bits1(&gb);
822                 cts_flag = get_bits1(&gb);
823             }
824         }
825         if (sl->inst_bitrate_len)
826             inst_bitrate_flag = get_bits1(&gb);
827         if (dts_flag == 1)
828             dts = get_ts64(&gb, sl->timestamp_len);
829         if (cts_flag == 1)
830             cts = get_ts64(&gb, sl->timestamp_len);
831         if (sl->au_len > 0)
832             skip_bits_long(&gb, sl->au_len);
833         if (inst_bitrate_flag)
834             skip_bits_long(&gb, sl->inst_bitrate_len);
835     }
836
837     if (dts != AV_NOPTS_VALUE)
838         pes->dts = dts;
839     if (cts != AV_NOPTS_VALUE)
840         pes->pts = cts;
841
842     if (sl->timestamp_len && sl->timestamp_res)
843         avpriv_set_pts_info(pes->st, sl->timestamp_len, 1, sl->timestamp_res);
844
845     return (get_bits_count(&gb) + 7) >> 3;
846 }
847
848 /* return non zero if a packet could be constructed */
849 static int mpegts_push_data(MpegTSFilter *filter,
850                             const uint8_t *buf, int buf_size, int is_start,
851                             int64_t pos, int64_t pcr)
852 {
853     PESContext *pes = filter->u.pes_filter.opaque;
854     MpegTSContext *ts = pes->ts;
855     const uint8_t *p;
856     int len, code;
857
858     if(!ts->pkt)
859         return 0;
860
861     if (pcr != -1)
862         pes->last_pcr = pcr;
863
864     if (is_start) {
865         if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
866             new_pes_packet(pes, ts->pkt);
867             ts->stop_parse = 1;
868         }
869         pes->state = MPEGTS_HEADER;
870         pes->data_index = 0;
871         pes->ts_packet_pos = pos;
872     }
873     p = buf;
874     while (buf_size > 0) {
875         switch(pes->state) {
876         case MPEGTS_HEADER:
877             len = PES_START_SIZE - pes->data_index;
878             if (len > buf_size)
879                 len = buf_size;
880             memcpy(pes->header + pes->data_index, p, len);
881             pes->data_index += len;
882             p += len;
883             buf_size -= len;
884             if (pes->data_index == PES_START_SIZE) {
885                 /* we got all the PES or section header. We can now
886                    decide */
887                 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
888                     pes->header[2] == 0x01) {
889                     /* it must be an mpeg2 PES stream */
890                     code = pes->header[3] | 0x100;
891                     av_dlog(pes->stream, "pid=%x pes_code=%#x\n", pes->pid, code);
892
893                     if ((pes->st && pes->st->discard == AVDISCARD_ALL &&
894                          (!pes->sub_st || pes->sub_st->discard == AVDISCARD_ALL)) ||
895                         code == 0x1be) /* padding_stream */
896                         goto skip;
897
898                     /* stream not present in PMT */
899                     if (!pes->st) {
900                         pes->st = avformat_new_stream(ts->stream, NULL);
901                         if (!pes->st)
902                             return AVERROR(ENOMEM);
903                         pes->st->id = pes->pid;
904                         mpegts_set_stream_info(pes->st, pes, 0, 0);
905                     }
906
907                     pes->total_size = AV_RB16(pes->header + 4);
908                     /* NOTE: a zero total size means the PES size is
909                        unbounded */
910                     if (!pes->total_size)
911                         pes->total_size = MAX_PES_PAYLOAD;
912
913                     /* allocate pes buffer */
914                     pes->buffer = av_buffer_alloc(pes->total_size +
915                                                   FF_INPUT_BUFFER_PADDING_SIZE);
916                     if (!pes->buffer)
917                         return AVERROR(ENOMEM);
918
919                     if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
920                         code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
921                         code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
922                         code != 0x1f8) {                  /* ITU-T Rec. H.222.1 type E stream */
923                         pes->state = MPEGTS_PESHEADER;
924                         if (pes->st->codec->codec_id == AV_CODEC_ID_NONE && !pes->st->request_probe) {
925                             av_dlog(pes->stream, "pid=%x stream_type=%x probing\n",
926                                     pes->pid, pes->stream_type);
927                             pes->st->request_probe= 1;
928                         }
929                     } else {
930                         pes->state = MPEGTS_PAYLOAD;
931                         pes->data_index = 0;
932                     }
933                 } else {
934                     /* otherwise, it should be a table */
935                     /* skip packet */
936                 skip:
937                     pes->state = MPEGTS_SKIP;
938                     continue;
939                 }
940             }
941             break;
942             /**********************************************/
943             /* PES packing parsing */
944         case MPEGTS_PESHEADER:
945             len = PES_HEADER_SIZE - pes->data_index;
946             if (len < 0)
947                 return -1;
948             if (len > buf_size)
949                 len = buf_size;
950             memcpy(pes->header + pes->data_index, p, len);
951             pes->data_index += len;
952             p += len;
953             buf_size -= len;
954             if (pes->data_index == PES_HEADER_SIZE) {
955                 pes->pes_header_size = pes->header[8] + 9;
956                 pes->state = MPEGTS_PESHEADER_FILL;
957             }
958             break;
959         case MPEGTS_PESHEADER_FILL:
960             len = pes->pes_header_size - pes->data_index;
961             if (len < 0)
962                 return -1;
963             if (len > buf_size)
964                 len = buf_size;
965             memcpy(pes->header + pes->data_index, p, len);
966             pes->data_index += len;
967             p += len;
968             buf_size -= len;
969             if (pes->data_index == pes->pes_header_size) {
970                 const uint8_t *r;
971                 unsigned int flags, pes_ext, skip;
972
973                 flags = pes->header[7];
974                 r = pes->header + 9;
975                 pes->pts = AV_NOPTS_VALUE;
976                 pes->dts = AV_NOPTS_VALUE;
977                 if ((flags & 0xc0) == 0x80) {
978                     pes->dts = pes->pts = ff_parse_pes_pts(r);
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             avio_seek(pb, -raw_packet_size, SEEK_CUR);
2000             if (mpegts_resync(s) < 0)
2001                 return AVERROR(EAGAIN);
2002             else
2003                 continue;
2004         } else {
2005             break;
2006         }
2007     }
2008     return 0;
2009 }
2010
2011 static void finished_reading_packet(AVFormatContext *s, int raw_packet_size)
2012 {
2013     AVIOContext *pb = s->pb;
2014     int skip = raw_packet_size - TS_PACKET_SIZE;
2015     if (skip > 0)
2016         avio_skip(pb, skip);
2017 }
2018
2019 static int handle_packets(MpegTSContext *ts, int nb_packets)
2020 {
2021     AVFormatContext *s = ts->stream;
2022     uint8_t packet[TS_PACKET_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
2023     const uint8_t *data;
2024     int packet_num, ret = 0;
2025
2026     if (avio_tell(s->pb) != ts->last_pos) {
2027         int i;
2028         av_dlog(ts->stream, "Skipping after seek\n");
2029         /* seek detected, flush pes buffer */
2030         for (i = 0; i < NB_PID_MAX; i++) {
2031             if (ts->pids[i]) {
2032                 if (ts->pids[i]->type == MPEGTS_PES) {
2033                    PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
2034                    av_buffer_unref(&pes->buffer);
2035                    pes->data_index = 0;
2036                    pes->state = MPEGTS_SKIP; /* skip until pes header */
2037                    pes->last_pcr = -1;
2038                 }
2039                 ts->pids[i]->last_cc = -1;
2040             }
2041         }
2042     }
2043
2044     ts->stop_parse = 0;
2045     packet_num = 0;
2046     memset(packet + TS_PACKET_SIZE, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2047     for(;;) {
2048         packet_num++;
2049         if (nb_packets != 0 && packet_num >= nb_packets ||
2050             ts->stop_parse > 1) {
2051             ret = AVERROR(EAGAIN);
2052             break;
2053         }
2054         if (ts->stop_parse > 0)
2055             break;
2056
2057         ret = read_packet(s, packet, ts->raw_packet_size, &data);
2058         if (ret != 0)
2059             break;
2060         ret = handle_packet(ts, data);
2061         finished_reading_packet(s, ts->raw_packet_size);
2062         if (ret != 0)
2063             break;
2064     }
2065     ts->last_pos = avio_tell(s->pb);
2066     return ret;
2067 }
2068
2069 static int mpegts_probe(AVProbeData *p)
2070 {
2071     const int size= p->buf_size;
2072     int maxscore=0;
2073     int sumscore=0;
2074     int i;
2075     int check_count= size / TS_FEC_PACKET_SIZE;
2076 #define CHECK_COUNT 10
2077 #define CHECK_BLOCK 100
2078
2079     if (check_count < CHECK_COUNT)
2080         return -1;
2081
2082     for (i=0; i<check_count; i+=CHECK_BLOCK){
2083         int left = FFMIN(check_count - i, CHECK_BLOCK);
2084         int score     = analyze(p->buf + TS_PACKET_SIZE     *i, TS_PACKET_SIZE     *left, TS_PACKET_SIZE     , NULL);
2085         int dvhs_score= analyze(p->buf + TS_DVHS_PACKET_SIZE*i, TS_DVHS_PACKET_SIZE*left, TS_DVHS_PACKET_SIZE, NULL);
2086         int fec_score = analyze(p->buf + TS_FEC_PACKET_SIZE *i, TS_FEC_PACKET_SIZE *left, TS_FEC_PACKET_SIZE , NULL);
2087         score = FFMAX3(score, dvhs_score, fec_score);
2088         sumscore += score;
2089         maxscore = FFMAX(maxscore, score);
2090     }
2091
2092     sumscore = sumscore*CHECK_COUNT/check_count;
2093     maxscore = maxscore*CHECK_COUNT/CHECK_BLOCK;
2094
2095     av_dlog(0, "TS score: %d %d\n", sumscore, maxscore);
2096
2097     if (sumscore > 6)           return AVPROBE_SCORE_MAX + sumscore - CHECK_COUNT;
2098     else if (maxscore > 6)      return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;
2099     else                        return -1;
2100 }
2101
2102 /* return the 90kHz PCR and the extension for the 27MHz PCR. return
2103    (-1) if not available */
2104 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
2105                      const uint8_t *packet)
2106 {
2107     int afc, len, flags;
2108     const uint8_t *p;
2109     unsigned int v;
2110
2111     afc = (packet[3] >> 4) & 3;
2112     if (afc <= 1)
2113         return -1;
2114     p = packet + 4;
2115     len = p[0];
2116     p++;
2117     if (len == 0)
2118         return -1;
2119     flags = *p++;
2120     len--;
2121     if (!(flags & 0x10))
2122         return -1;
2123     if (len < 6)
2124         return -1;
2125     v = AV_RB32(p);
2126     *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
2127     *ppcr_low = ((p[4] & 1) << 8) | p[5];
2128     return 0;
2129 }
2130
2131 static void seek_back(AVFormatContext *s, AVIOContext *pb, int64_t pos) {
2132
2133     /* NOTE: We attempt to seek on non-seekable files as well, as the
2134      * probe buffer usually is big enough. Only warn if the seek failed
2135      * on files where the seek should work. */
2136     if (avio_seek(pb, pos, SEEK_SET) < 0)
2137         av_log(s, pb->seekable ? AV_LOG_ERROR : AV_LOG_INFO, "Unable to seek back to the start\n");
2138 }
2139
2140 static int mpegts_read_header(AVFormatContext *s)
2141 {
2142     MpegTSContext *ts = s->priv_data;
2143     AVIOContext *pb = s->pb;
2144     uint8_t buf[8*1024]={0};
2145     int len;
2146     int64_t pos;
2147
2148     ffio_ensure_seekback(pb, s->probesize);
2149
2150     /* read the first 8192 bytes to get packet size */
2151     pos = avio_tell(pb);
2152     len = avio_read(pb, buf, sizeof(buf));
2153     ts->raw_packet_size = get_packet_size(buf, len);
2154     if (ts->raw_packet_size <= 0) {
2155         av_log(s, AV_LOG_WARNING, "Could not detect TS packet size, defaulting to non-FEC/DVHS\n");
2156         ts->raw_packet_size = TS_PACKET_SIZE;
2157     }
2158     ts->stream = s;
2159     ts->auto_guess = 0;
2160
2161     if (s->iformat == &ff_mpegts_demuxer) {
2162         /* normal demux */
2163
2164         /* first do a scan to get all the services */
2165         seek_back(s, pb, pos);
2166
2167         mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
2168
2169         mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
2170
2171         handle_packets(ts, s->probesize / ts->raw_packet_size);
2172         /* if could not find service, enable auto_guess */
2173
2174         ts->auto_guess = 1;
2175
2176         av_dlog(ts->stream, "tuning done\n");
2177
2178         s->ctx_flags |= AVFMTCTX_NOHEADER;
2179     } else {
2180         AVStream *st;
2181         int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
2182         int64_t pcrs[2], pcr_h;
2183         int packet_count[2];
2184         uint8_t packet[TS_PACKET_SIZE];
2185         const uint8_t *data;
2186
2187         /* only read packets */
2188
2189         st = avformat_new_stream(s, NULL);
2190         if (!st)
2191             goto fail;
2192         avpriv_set_pts_info(st, 60, 1, 27000000);
2193         st->codec->codec_type = AVMEDIA_TYPE_DATA;
2194         st->codec->codec_id = AV_CODEC_ID_MPEG2TS;
2195
2196         /* we iterate until we find two PCRs to estimate the bitrate */
2197         pcr_pid = -1;
2198         nb_pcrs = 0;
2199         nb_packets = 0;
2200         for(;;) {
2201             ret = read_packet(s, packet, ts->raw_packet_size, &data);
2202             if (ret < 0)
2203                 goto fail;
2204             pid = AV_RB16(data + 1) & 0x1fff;
2205             if ((pcr_pid == -1 || pcr_pid == pid) &&
2206                 parse_pcr(&pcr_h, &pcr_l, data) == 0) {
2207                 finished_reading_packet(s, ts->raw_packet_size);
2208                 pcr_pid = pid;
2209                 packet_count[nb_pcrs] = nb_packets;
2210                 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
2211                 nb_pcrs++;
2212                 if (nb_pcrs >= 2)
2213                     break;
2214             } else {
2215                 finished_reading_packet(s, ts->raw_packet_size);
2216             }
2217             nb_packets++;
2218         }
2219
2220         /* NOTE1: the bitrate is computed without the FEC */
2221         /* NOTE2: it is only the bitrate of the start of the stream */
2222         ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
2223         ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
2224         s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
2225         st->codec->bit_rate = s->bit_rate;
2226         st->start_time = ts->cur_pcr;
2227         av_dlog(ts->stream, "start=%0.3f pcr=%0.3f incr=%d\n",
2228                 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
2229     }
2230
2231     seek_back(s, pb, pos);
2232     return 0;
2233  fail:
2234     return -1;
2235 }
2236
2237 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
2238
2239 static int mpegts_raw_read_packet(AVFormatContext *s,
2240                                   AVPacket *pkt)
2241 {
2242     MpegTSContext *ts = s->priv_data;
2243     int ret, i;
2244     int64_t pcr_h, next_pcr_h, pos;
2245     int pcr_l, next_pcr_l;
2246     uint8_t pcr_buf[12];
2247     const uint8_t *data;
2248
2249     if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
2250         return AVERROR(ENOMEM);
2251     pkt->pos= avio_tell(s->pb);
2252     ret = read_packet(s, pkt->data, ts->raw_packet_size, &data);
2253     if (ret < 0) {
2254         av_free_packet(pkt);
2255         return ret;
2256     }
2257     if (data != pkt->data)
2258         memcpy(pkt->data, data, ts->raw_packet_size);
2259     finished_reading_packet(s, ts->raw_packet_size);
2260     if (ts->mpeg2ts_compute_pcr) {
2261         /* compute exact PCR for each packet */
2262         if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
2263             /* we read the next PCR (XXX: optimize it by using a bigger buffer */
2264             pos = avio_tell(s->pb);
2265             for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
2266                 avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
2267                 avio_read(s->pb, pcr_buf, 12);
2268                 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
2269                     /* XXX: not precise enough */
2270                     ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
2271                         (i + 1);
2272                     break;
2273                 }
2274             }
2275             avio_seek(s->pb, pos, SEEK_SET);
2276             /* no next PCR found: we use previous increment */
2277             ts->cur_pcr = pcr_h * 300 + pcr_l;
2278         }
2279         pkt->pts = ts->cur_pcr;
2280         pkt->duration = ts->pcr_incr;
2281         ts->cur_pcr += ts->pcr_incr;
2282     }
2283     pkt->stream_index = 0;
2284     return 0;
2285 }
2286
2287 static int mpegts_read_packet(AVFormatContext *s,
2288                               AVPacket *pkt)
2289 {
2290     MpegTSContext *ts = s->priv_data;
2291     int ret, i;
2292
2293     pkt->size = -1;
2294     ts->pkt = pkt;
2295     ret = handle_packets(ts, 0);
2296     if (ret < 0) {
2297         av_free_packet(ts->pkt);
2298         /* flush pes data left */
2299         for (i = 0; i < NB_PID_MAX; i++) {
2300             if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
2301                 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
2302                 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
2303                     new_pes_packet(pes, pkt);
2304                     pes->state = MPEGTS_SKIP;
2305                     ret = 0;
2306                     break;
2307                 }
2308             }
2309         }
2310     }
2311
2312     if (!ret && pkt->size < 0)
2313         ret = AVERROR(EINTR);
2314     return ret;
2315 }
2316
2317 static void mpegts_free(MpegTSContext *ts)
2318 {
2319     int i;
2320
2321     clear_programs(ts);
2322
2323     for(i=0;i<NB_PID_MAX;i++)
2324         if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
2325 }
2326
2327 static int mpegts_read_close(AVFormatContext *s)
2328 {
2329     MpegTSContext *ts = s->priv_data;
2330     mpegts_free(ts);
2331     return 0;
2332 }
2333
2334 static av_unused int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
2335                               int64_t *ppos, int64_t pos_limit)
2336 {
2337     MpegTSContext *ts = s->priv_data;
2338     int64_t pos, timestamp;
2339     uint8_t buf[TS_PACKET_SIZE];
2340     int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
2341     int pos47 = ts->pos47_full % ts->raw_packet_size;
2342     pos = ((*ppos  + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) * ts->raw_packet_size + pos47;
2343     while(pos < pos_limit) {
2344         if (avio_seek(s->pb, pos, SEEK_SET) < 0)
2345             return AV_NOPTS_VALUE;
2346         if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
2347             return AV_NOPTS_VALUE;
2348         if (buf[0] != 0x47) {
2349             avio_seek(s->pb, -TS_PACKET_SIZE, SEEK_CUR);
2350             if (mpegts_resync(s) < 0)
2351                 return AV_NOPTS_VALUE;
2352             pos = avio_tell(s->pb);
2353             continue;
2354         }
2355         if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
2356             parse_pcr(&timestamp, &pcr_l, buf) == 0) {
2357             *ppos = pos;
2358             return timestamp;
2359         }
2360         pos += ts->raw_packet_size;
2361     }
2362
2363     return AV_NOPTS_VALUE;
2364 }
2365
2366 static int64_t mpegts_get_dts(AVFormatContext *s, int stream_index,
2367                               int64_t *ppos, int64_t pos_limit)
2368 {
2369     MpegTSContext *ts = s->priv_data;
2370     int64_t pos;
2371     int pos47 = ts->pos47_full % ts->raw_packet_size;
2372     pos = ((*ppos  + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) * ts->raw_packet_size + pos47;
2373     ff_read_frame_flush(s);
2374     if (avio_seek(s->pb, pos, SEEK_SET) < 0)
2375         return AV_NOPTS_VALUE;
2376     while(pos < pos_limit) {
2377         int ret;
2378         AVPacket pkt;
2379         av_init_packet(&pkt);
2380         ret= av_read_frame(s, &pkt);
2381         if(ret < 0)
2382             return AV_NOPTS_VALUE;
2383         av_free_packet(&pkt);
2384         if(pkt.dts != AV_NOPTS_VALUE && pkt.pos >= 0){
2385             ff_reduce_index(s, pkt.stream_index);
2386             av_add_index_entry(s->streams[pkt.stream_index], pkt.pos, pkt.dts, 0, 0, AVINDEX_KEYFRAME /* FIXME keyframe? */);
2387             if(pkt.stream_index == stream_index && pkt.pos >= *ppos){
2388                 *ppos= pkt.pos;
2389                 return pkt.dts;
2390             }
2391         }
2392         pos = pkt.pos;
2393     }
2394
2395     return AV_NOPTS_VALUE;
2396 }
2397
2398 /**************************************************************/
2399 /* parsing functions - called from other demuxers such as RTP */
2400
2401 MpegTSContext *ff_mpegts_parse_open(AVFormatContext *s)
2402 {
2403     MpegTSContext *ts;
2404
2405     ts = av_mallocz(sizeof(MpegTSContext));
2406     if (!ts)
2407         return NULL;
2408     /* no stream case, currently used by RTP */
2409     ts->raw_packet_size = TS_PACKET_SIZE;
2410     ts->stream = s;
2411     ts->auto_guess = 1;
2412     mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
2413     mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
2414
2415     return ts;
2416 }
2417
2418 /* return the consumed length if a packet was output, or -1 if no
2419    packet is output */
2420 int ff_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
2421                         const uint8_t *buf, int len)
2422 {
2423     int len1;
2424
2425     len1 = len;
2426     ts->pkt = pkt;
2427     for(;;) {
2428         ts->stop_parse = 0;
2429         if (len < TS_PACKET_SIZE)
2430             return -1;
2431         if (buf[0] != 0x47) {
2432             buf++;
2433             len--;
2434         } else {
2435             handle_packet(ts, buf);
2436             buf += TS_PACKET_SIZE;
2437             len -= TS_PACKET_SIZE;
2438             if (ts->stop_parse == 1)
2439                 break;
2440         }
2441     }
2442     return len1 - len;
2443 }
2444
2445 void ff_mpegts_parse_close(MpegTSContext *ts)
2446 {
2447     mpegts_free(ts);
2448     av_free(ts);
2449 }
2450
2451 AVInputFormat ff_mpegts_demuxer = {
2452     .name           = "mpegts",
2453     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
2454     .priv_data_size = sizeof(MpegTSContext),
2455     .read_probe     = mpegts_probe,
2456     .read_header    = mpegts_read_header,
2457     .read_packet    = mpegts_read_packet,
2458     .read_close     = mpegts_read_close,
2459     .read_timestamp = mpegts_get_dts,
2460     .flags          = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
2461     .priv_class     = &mpegts_class,
2462 };
2463
2464 AVInputFormat ff_mpegtsraw_demuxer = {
2465     .name           = "mpegtsraw",
2466     .long_name      = NULL_IF_CONFIG_SMALL("raw MPEG-TS (MPEG-2 Transport Stream)"),
2467     .priv_data_size = sizeof(MpegTSContext),
2468     .read_header    = mpegts_read_header,
2469     .read_packet    = mpegts_raw_read_packet,
2470     .read_close     = mpegts_read_close,
2471     .read_timestamp = mpegts_get_dts,
2472     .flags          = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
2473     .priv_class     = &mpegtsraw_class,
2474 };