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