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