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