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