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