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