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