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