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