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