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