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