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