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