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