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