]> rtime.felk.cvut.cz Git - frescor/ffmpeg.git/blob - libavformat/mpegts.c
frsh: Export information about the last RTP contract and VRES
[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
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     dprintf(ts->stream, "Filter: pid=0x%x\n", pid);
287
288     if (pid >= NB_PID_MAX || ts->pids[pid])
289         return NULL;
290     filter = av_mallocz(sizeof(MpegTSFilter));
291     if (!filter)
292         return NULL;
293     ts->pids[pid] = filter;
294     filter->type = MPEGTS_SECTION;
295     filter->pid = pid;
296     filter->last_cc = -1;
297     sec = &filter->u.section_filter;
298     sec->section_cb = section_cb;
299     sec->opaque = opaque;
300     sec->section_buf = av_malloc(MAX_SECTION_SIZE);
301     sec->check_crc = check_crc;
302     if (!sec->section_buf) {
303         av_free(filter);
304         return NULL;
305     }
306     return filter;
307 }
308
309 static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
310                                      PESCallback *pes_cb,
311                                      void *opaque)
312 {
313     MpegTSFilter *filter;
314     MpegTSPESFilter *pes;
315
316     if (pid >= NB_PID_MAX || ts->pids[pid])
317         return NULL;
318     filter = av_mallocz(sizeof(MpegTSFilter));
319     if (!filter)
320         return NULL;
321     ts->pids[pid] = filter;
322     filter->type = MPEGTS_PES;
323     filter->pid = pid;
324     filter->last_cc = -1;
325     pes = &filter->u.pes_filter;
326     pes->pes_cb = pes_cb;
327     pes->opaque = opaque;
328     return filter;
329 }
330
331 static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
332 {
333     int pid;
334
335     pid = filter->pid;
336     if (filter->type == MPEGTS_SECTION)
337         av_freep(&filter->u.section_filter.section_buf);
338     else if (filter->type == MPEGTS_PES) {
339         /* referenced private data will be freed later in
340          * av_close_input_stream */
341         if (!((PESContext *)filter->u.pes_filter.opaque)->st) {
342             av_freep(&filter->u.pes_filter.opaque);
343         }
344     }
345
346     av_free(filter);
347     ts->pids[pid] = NULL;
348 }
349
350 static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
351     int stat[packet_size];
352     int i;
353     int x=0;
354     int best_score=0;
355
356     memset(stat, 0, packet_size*sizeof(int));
357
358     for(x=i=0; i<size-3; i++){
359         if(buf[i] == 0x47 && !(buf[i+1] & 0x80) && (buf[i+3] & 0x30)){
360             stat[x]++;
361             if(stat[x] > best_score){
362                 best_score= stat[x];
363                 if(index) *index= x;
364             }
365         }
366
367         x++;
368         if(x == packet_size) x= 0;
369     }
370
371     return best_score;
372 }
373
374 /* autodetect fec presence. Must have at least 1024 bytes  */
375 static int get_packet_size(const uint8_t *buf, int size)
376 {
377     int score, fec_score, dvhs_score;
378
379     if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
380         return -1;
381
382     score    = analyze(buf, size, TS_PACKET_SIZE, NULL);
383     dvhs_score    = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
384     fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
385 //    av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
386
387     if     (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
388     else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
389     else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
390     else                       return -1;
391 }
392
393 typedef struct SectionHeader {
394     uint8_t tid;
395     uint16_t id;
396     uint8_t version;
397     uint8_t sec_num;
398     uint8_t last_sec_num;
399 } SectionHeader;
400
401 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
402 {
403     const uint8_t *p;
404     int c;
405
406     p = *pp;
407     if (p >= p_end)
408         return -1;
409     c = *p++;
410     *pp = p;
411     return c;
412 }
413
414 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
415 {
416     const uint8_t *p;
417     int c;
418
419     p = *pp;
420     if ((p + 1) >= p_end)
421         return -1;
422     c = AV_RB16(p);
423     p += 2;
424     *pp = p;
425     return c;
426 }
427
428 /* read and allocate a DVB string preceeded by its length */
429 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
430 {
431     int len;
432     const uint8_t *p;
433     char *str;
434
435     p = *pp;
436     len = get8(&p, p_end);
437     if (len < 0)
438         return NULL;
439     if ((p + len) > p_end)
440         return NULL;
441     str = av_malloc(len + 1);
442     if (!str)
443         return NULL;
444     memcpy(str, p, len);
445     str[len] = '\0';
446     p += len;
447     *pp = p;
448     return str;
449 }
450
451 static int parse_section_header(SectionHeader *h,
452                                 const uint8_t **pp, const uint8_t *p_end)
453 {
454     int val;
455
456     val = get8(pp, p_end);
457     if (val < 0)
458         return -1;
459     h->tid = val;
460     *pp += 2;
461     val = get16(pp, p_end);
462     if (val < 0)
463         return -1;
464     h->id = val;
465     val = get8(pp, p_end);
466     if (val < 0)
467         return -1;
468     h->version = (val >> 1) & 0x1f;
469     val = get8(pp, p_end);
470     if (val < 0)
471         return -1;
472     h->sec_num = val;
473     val = get8(pp, p_end);
474     if (val < 0)
475         return -1;
476     h->last_sec_num = val;
477     return 0;
478 }
479
480
481 static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
482 {
483     MpegTSContext *ts = filter->u.section_filter.opaque;
484     SectionHeader h1, *h = &h1;
485     PESContext *pes;
486     AVStream *st;
487     const uint8_t *p, *p_end, *desc_list_end, *desc_end;
488     int program_info_length, pcr_pid, pid, stream_type;
489     int desc_list_len, desc_len, desc_tag;
490     int comp_page = 0, anc_page = 0; /* initialize to kill warnings */
491     char language[4] = {0}; /* initialize to kill warnings */
492     int has_hdmv_descr = 0;
493     int has_dirac_descr = 0;
494     uint32_t reg_desc = 0; /* registration descriptor */
495
496 #ifdef DEBUG
497     dprintf(ts->stream, "PMT: len %i\n", section_len);
498     av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
499 #endif
500
501     p_end = section + section_len - 4;
502     p = section;
503     if (parse_section_header(h, &p, p_end) < 0)
504         return;
505
506     dprintf(ts->stream, "sid=0x%x sec_num=%d/%d\n",
507            h->id, h->sec_num, h->last_sec_num);
508
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
518     dprintf(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
519
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
577             dprintf(ts->stream, "tag: 0x%02x len=%d\n",
578                    desc_tag, desc_len);
579
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         dprintf(ts->stream, "stream_type=%x pid=0x%x\n",
615                stream_type, pid);
616
617         /* now create ffmpeg stream */
618         switch(stream_type) {
619         case STREAM_TYPE_AUDIO_MPEG1:
620         case STREAM_TYPE_AUDIO_MPEG2:
621         case STREAM_TYPE_VIDEO_MPEG1:
622         case STREAM_TYPE_VIDEO_MPEG2:
623         case STREAM_TYPE_VIDEO_MPEG4:
624         case STREAM_TYPE_VIDEO_H264:
625         case STREAM_TYPE_VIDEO_VC1:
626         case STREAM_TYPE_VIDEO_DIRAC:
627         case STREAM_TYPE_AUDIO_AAC:
628         case STREAM_TYPE_AUDIO_AC3:
629         case STREAM_TYPE_AUDIO_DTS:
630         case STREAM_TYPE_AUDIO_HDMV_DTS:
631         case STREAM_TYPE_SUBTITLE_DVB:
632             if((stream_type == STREAM_TYPE_AUDIO_HDMV_DTS && !has_hdmv_descr)
633             || (stream_type == STREAM_TYPE_VIDEO_DIRAC    && !has_dirac_descr))
634                 break;
635             if(ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES){
636                 pes= ts->pids[pid]->u.pes_filter.opaque;
637                 st= pes->st;
638             }else{
639                 if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
640                 pes = add_pes_stream(ts, pid, pcr_pid, stream_type);
641                 if (pes)
642                     st = new_pes_av_stream(pes, 0);
643             }
644             add_pid_to_pmt(ts, h->id, pid);
645             if(st)
646                 av_program_add_stream_index(ts->stream, h->id, st->index);
647             break;
648         default:
649             /* we ignore the other streams */
650             break;
651         }
652
653         if (st) {
654             if (language[0] != 0) {
655                 av_metadata_set(&st->metadata, "language", language);
656             }
657
658             if (stream_type == STREAM_TYPE_SUBTITLE_DVB) {
659                 st->codec->sub_id = (anc_page << 16) | comp_page;
660             }
661         }
662     }
663     /* all parameters are there */
664     ts->stop_parse++;
665     mpegts_close_filter(ts, filter);
666 }
667
668 static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
669 {
670     MpegTSContext *ts = filter->u.section_filter.opaque;
671     SectionHeader h1, *h = &h1;
672     const uint8_t *p, *p_end;
673     int sid, pmt_pid;
674
675 #ifdef DEBUG
676     dprintf(ts->stream, "PAT:\n");
677     av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
678 #endif
679     p_end = section + section_len - 4;
680     p = section;
681     if (parse_section_header(h, &p, p_end) < 0)
682         return;
683     if (h->tid != PAT_TID)
684         return;
685
686     clear_programs(ts);
687     for(;;) {
688         sid = get16(&p, p_end);
689         if (sid < 0)
690             break;
691         pmt_pid = get16(&p, p_end) & 0x1fff;
692         if (pmt_pid < 0)
693             break;
694
695         dprintf(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
696
697         if (sid == 0x0000) {
698             /* NIT info */
699         } else {
700             av_new_program(ts->stream, sid);
701             ts->stop_parse--;
702             mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
703             add_pat_entry(ts, sid);
704             add_pid_to_pmt(ts, sid, 0); //add pat pid to program
705             add_pid_to_pmt(ts, sid, pmt_pid);
706         }
707     }
708     /* not found */
709     ts->stop_parse++;
710
711     mpegts_close_filter(ts, filter);
712 }
713
714 static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
715 {
716     MpegTSContext *ts = filter->u.section_filter.opaque;
717     SectionHeader h1, *h = &h1;
718     const uint8_t *p, *p_end, *desc_list_end, *desc_end;
719     int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
720     char *name, *provider_name;
721
722 #ifdef DEBUG
723     dprintf(ts->stream, "SDT:\n");
724     av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
725 #endif
726
727     p_end = section + section_len - 4;
728     p = section;
729     if (parse_section_header(h, &p, p_end) < 0)
730         return;
731     if (h->tid != SDT_TID)
732         return;
733     onid = get16(&p, p_end);
734     if (onid < 0)
735         return;
736     val = get8(&p, p_end);
737     if (val < 0)
738         return;
739     for(;;) {
740         sid = get16(&p, p_end);
741         if (sid < 0)
742             break;
743         val = get8(&p, p_end);
744         if (val < 0)
745             break;
746         desc_list_len = get16(&p, p_end) & 0xfff;
747         if (desc_list_len < 0)
748             break;
749         desc_list_end = p + desc_list_len;
750         if (desc_list_end > p_end)
751             break;
752         for(;;) {
753             desc_tag = get8(&p, desc_list_end);
754             if (desc_tag < 0)
755                 break;
756             desc_len = get8(&p, desc_list_end);
757             desc_end = p + desc_len;
758             if (desc_end > desc_list_end)
759                 break;
760
761             dprintf(ts->stream, "tag: 0x%02x len=%d\n",
762                    desc_tag, desc_len);
763
764             switch(desc_tag) {
765             case 0x48:
766                 service_type = get8(&p, p_end);
767                 if (service_type < 0)
768                     break;
769                 provider_name = getstr8(&p, p_end);
770                 if (!provider_name)
771                     break;
772                 name = getstr8(&p, p_end);
773                 if (name) {
774                     AVProgram *program = av_new_program(ts->stream, sid);
775                     if(program) {
776                         av_metadata_set(&program->metadata, "name", name);
777                         av_metadata_set(&program->metadata, "provider_name", provider_name);
778                     }
779                 }
780                 av_free(name);
781                 av_free(provider_name);
782                 break;
783             default:
784                 break;
785             }
786             p = desc_end;
787         }
788         p = desc_list_end;
789     }
790 }
791
792 static int64_t get_pts(const uint8_t *p)
793 {
794     int64_t pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
795     pts |= (AV_RB16(p + 1) >> 1) << 15;
796     pts |=  AV_RB16(p + 3) >> 1;
797     return pts;
798 }
799
800 /* return non zero if a packet could be constructed */
801 static void mpegts_push_data(MpegTSFilter *filter,
802                              const uint8_t *buf, int buf_size, int is_start,
803                              int64_t pos)
804 {
805     PESContext *pes = filter->u.pes_filter.opaque;
806     MpegTSContext *ts = pes->ts;
807     const uint8_t *p;
808     int len, code;
809
810     if(!ts->pkt)
811         return;
812
813     if (is_start) {
814         pes->state = MPEGTS_HEADER;
815         pes->data_index = 0;
816         pes->ts_packet_pos = pos;
817     }
818     p = buf;
819     while (buf_size > 0) {
820         switch(pes->state) {
821         case MPEGTS_HEADER:
822             len = PES_START_SIZE - pes->data_index;
823             if (len > buf_size)
824                 len = buf_size;
825             memcpy(pes->header + pes->data_index, p, len);
826             pes->data_index += len;
827             p += len;
828             buf_size -= len;
829             if (pes->data_index == PES_START_SIZE) {
830                 /* we got all the PES or section header. We can now
831                    decide */
832 #if 0
833                 av_hex_dump_log(pes->stream, AV_LOG_DEBUG, pes->header, pes->data_index);
834 #endif
835                 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
836                     pes->header[2] == 0x01) {
837                     /* it must be an mpeg2 PES stream */
838                     code = pes->header[3] | 0x100;
839                     if (!pes->st ||
840                         !((code >= 0x1c0 && code <= 0x1df) ||
841                           (code >= 0x1e0 && code <= 0x1ef) ||
842                           (code == 0x1bd) || (code == 0x1fd)))
843                         goto skip;
844                     pes->state = MPEGTS_PESHEADER_FILL;
845                     pes->total_size = AV_RB16(pes->header + 4);
846                     /* NOTE: a zero total size means the PES size is
847                        unbounded */
848                     if (pes->total_size)
849                         pes->total_size += 6;
850                     pes->pes_header_size = pes->header[8] + 9;
851                 } else {
852                     /* otherwise, it should be a table */
853                     /* skip packet */
854                 skip:
855                     pes->state = MPEGTS_SKIP;
856                     continue;
857                 }
858             }
859             break;
860             /**********************************************/
861             /* PES packing parsing */
862         case MPEGTS_PESHEADER_FILL:
863             len = pes->pes_header_size - pes->data_index;
864             if (len > buf_size)
865                 len = buf_size;
866             memcpy(pes->header + pes->data_index, p, len);
867             pes->data_index += len;
868             p += len;
869             buf_size -= len;
870             if (pes->data_index == pes->pes_header_size) {
871                 const uint8_t *r;
872                 unsigned int flags;
873
874                 flags = pes->header[7];
875                 r = pes->header + 9;
876                 pes->pts = AV_NOPTS_VALUE;
877                 pes->dts = AV_NOPTS_VALUE;
878                 if ((flags & 0xc0) == 0x80) {
879                     pes->dts = pes->pts = get_pts(r);
880                     r += 5;
881                 } else if ((flags & 0xc0) == 0xc0) {
882                     pes->pts = get_pts(r);
883                     r += 5;
884                     pes->dts = get_pts(r);
885                     r += 5;
886                 }
887                 /* we got the full header. We parse it and get the payload */
888                 pes->state = MPEGTS_PAYLOAD;
889             }
890             break;
891         case MPEGTS_PAYLOAD:
892             if (pes->total_size) {
893                 len = pes->total_size - pes->data_index;
894                 if (len > buf_size)
895                     len = buf_size;
896             } else {
897                 len = buf_size;
898             }
899             if (len > 0) {
900                 AVPacket *pkt = ts->pkt;
901                 if (pes->st && av_new_packet(pkt, len) == 0) {
902                     memcpy(pkt->data, p, len);
903                     pkt->stream_index = pes->st->index;
904                     pkt->pts = pes->pts;
905                     pkt->dts = pes->dts;
906                     /* store position of first TS packet of this PES packet */
907                     pkt->pos = pes->ts_packet_pos;
908                     /* reset pts values */
909                     pes->pts = AV_NOPTS_VALUE;
910                     pes->dts = AV_NOPTS_VALUE;
911                     ts->stop_parse = 1;
912                     return;
913                 }
914             }
915             buf_size = 0;
916             break;
917         case MPEGTS_SKIP:
918             buf_size = 0;
919             break;
920         }
921     }
922 }
923
924 static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code)
925 {
926     AVStream *st;
927     enum CodecID codec_id;
928     enum CodecType codec_type;
929
930     switch(pes->stream_type){
931     case STREAM_TYPE_AUDIO_MPEG1:
932     case STREAM_TYPE_AUDIO_MPEG2:
933         codec_type = CODEC_TYPE_AUDIO;
934         codec_id = CODEC_ID_MP3;
935         break;
936     case STREAM_TYPE_VIDEO_MPEG1:
937     case STREAM_TYPE_VIDEO_MPEG2:
938         codec_type = CODEC_TYPE_VIDEO;
939         codec_id = CODEC_ID_MPEG2VIDEO;
940         break;
941     case STREAM_TYPE_VIDEO_MPEG4:
942         codec_type = CODEC_TYPE_VIDEO;
943         codec_id = CODEC_ID_MPEG4;
944         break;
945     case STREAM_TYPE_VIDEO_H264:
946         codec_type = CODEC_TYPE_VIDEO;
947         codec_id = CODEC_ID_H264;
948         break;
949     case STREAM_TYPE_VIDEO_VC1:
950         codec_type = CODEC_TYPE_VIDEO;
951         codec_id = CODEC_ID_VC1;
952         break;
953     case STREAM_TYPE_VIDEO_DIRAC:
954         codec_type = CODEC_TYPE_VIDEO;
955         codec_id = CODEC_ID_DIRAC;
956         break;
957     case STREAM_TYPE_AUDIO_AAC:
958         codec_type = CODEC_TYPE_AUDIO;
959         codec_id = CODEC_ID_AAC;
960         break;
961     case STREAM_TYPE_AUDIO_AC3:
962         codec_type = CODEC_TYPE_AUDIO;
963         codec_id = CODEC_ID_AC3;
964         break;
965     case STREAM_TYPE_AUDIO_DTS:
966     case STREAM_TYPE_AUDIO_HDMV_DTS:
967         codec_type = CODEC_TYPE_AUDIO;
968         codec_id = CODEC_ID_DTS;
969         break;
970     case STREAM_TYPE_SUBTITLE_DVB:
971         codec_type = CODEC_TYPE_SUBTITLE;
972         codec_id = CODEC_ID_DVB_SUBTITLE;
973         break;
974     default:
975         if (code >= 0x1c0 && code <= 0x1df) {
976             codec_type = CODEC_TYPE_AUDIO;
977             codec_id = CODEC_ID_MP2;
978         } else if (code == 0x1bd) {
979             codec_type = CODEC_TYPE_AUDIO;
980             codec_id = CODEC_ID_AC3;
981         } else {
982             codec_type = CODEC_TYPE_VIDEO;
983             codec_id = CODEC_ID_PROBE;
984         }
985         break;
986     }
987     st = av_new_stream(pes->stream, pes->pid);
988     if (st) {
989         av_set_pts_info(st, 33, 1, 90000);
990         st->priv_data = pes;
991         st->codec->codec_type = codec_type;
992         st->codec->codec_id = codec_id;
993         st->need_parsing = AVSTREAM_PARSE_FULL;
994         pes->st = st;
995     }
996     return st;
997 }
998
999
1000 static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid, int stream_type)
1001 {
1002     MpegTSFilter *tss;
1003     PESContext *pes;
1004
1005     /* if no pid found, then add a pid context */
1006     pes = av_mallocz(sizeof(PESContext));
1007     if (!pes)
1008         return 0;
1009     pes->ts = ts;
1010     pes->stream = ts->stream;
1011     pes->pid = pid;
1012     pes->pcr_pid = pcr_pid;
1013     pes->stream_type = stream_type;
1014     tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
1015     if (!tss) {
1016         av_free(pes);
1017         return 0;
1018     }
1019     return pes;
1020 }
1021
1022 /* handle one TS packet */
1023 static void handle_packet(MpegTSContext *ts, const uint8_t *packet)
1024 {
1025     AVFormatContext *s = ts->stream;
1026     MpegTSFilter *tss;
1027     int len, pid, cc, cc_ok, afc, is_start;
1028     const uint8_t *p, *p_end;
1029     int64_t pos;
1030
1031     pid = AV_RB16(packet + 1) & 0x1fff;
1032     if(pid && discard_pid(ts, pid))
1033         return;
1034     is_start = packet[1] & 0x40;
1035     tss = ts->pids[pid];
1036     if (ts->auto_guess && tss == NULL && is_start) {
1037         add_pes_stream(ts, pid, -1, 0);
1038         tss = ts->pids[pid];
1039     }
1040     if (!tss)
1041         return;
1042
1043     /* continuity check (currently not used) */
1044     cc = (packet[3] & 0xf);
1045     cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
1046     tss->last_cc = cc;
1047
1048     /* skip adaptation field */
1049     afc = (packet[3] >> 4) & 3;
1050     p = packet + 4;
1051     if (afc == 0) /* reserved value */
1052         return;
1053     if (afc == 2) /* adaptation field only */
1054         return;
1055     if (afc == 3) {
1056         /* skip adapation field */
1057         p += p[0] + 1;
1058     }
1059     /* if past the end of packet, ignore */
1060     p_end = packet + TS_PACKET_SIZE;
1061     if (p >= p_end)
1062         return;
1063
1064     pos = url_ftell(ts->stream->pb);
1065     ts->pos47= pos % ts->raw_packet_size;
1066
1067     if (tss->type == MPEGTS_SECTION) {
1068         if (is_start) {
1069             /* pointer field present */
1070             len = *p++;
1071             if (p + len > p_end)
1072                 return;
1073             if (len && cc_ok) {
1074                 /* write remaining section bytes */
1075                 write_section_data(s, tss,
1076                                    p, len, 0);
1077                 /* check whether filter has been closed */
1078                 if (!ts->pids[pid])
1079                     return;
1080             }
1081             p += len;
1082             if (p < p_end) {
1083                 write_section_data(s, tss,
1084                                    p, p_end - p, 1);
1085             }
1086         } else {
1087             if (cc_ok) {
1088                 write_section_data(s, tss,
1089                                    p, p_end - p, 0);
1090             }
1091         }
1092     } else {
1093         // Note: The position here points actually behind the current packet.
1094         tss->u.pes_filter.pes_cb(tss,
1095                                  p, p_end - p, is_start, pos - ts->raw_packet_size);
1096     }
1097 }
1098
1099 /* XXX: try to find a better synchro over several packets (use
1100    get_packet_size() ?) */
1101 static int mpegts_resync(ByteIOContext *pb)
1102 {
1103     int c, i;
1104
1105     for(i = 0;i < MAX_RESYNC_SIZE; i++) {
1106         c = url_fgetc(pb);
1107         if (c < 0)
1108             return -1;
1109         if (c == 0x47) {
1110             url_fseek(pb, -1, SEEK_CUR);
1111             return 0;
1112         }
1113     }
1114     /* no sync found */
1115     return -1;
1116 }
1117
1118 /* return -1 if error or EOF. Return 0 if OK. */
1119 static int read_packet(ByteIOContext *pb, uint8_t *buf, int raw_packet_size)
1120 {
1121     int skip, len;
1122
1123     for(;;) {
1124         len = get_buffer(pb, buf, TS_PACKET_SIZE);
1125         if (len != TS_PACKET_SIZE)
1126             return AVERROR(EIO);
1127         /* check paquet sync byte */
1128         if (buf[0] != 0x47) {
1129             /* find a new packet start */
1130             url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1131             if (mpegts_resync(pb) < 0)
1132                 return AVERROR_INVALIDDATA;
1133             else
1134                 continue;
1135         } else {
1136             skip = raw_packet_size - TS_PACKET_SIZE;
1137             if (skip > 0)
1138                 url_fskip(pb, skip);
1139             break;
1140         }
1141     }
1142     return 0;
1143 }
1144
1145 static int handle_packets(MpegTSContext *ts, int nb_packets)
1146 {
1147     AVFormatContext *s = ts->stream;
1148     ByteIOContext *pb = s->pb;
1149     uint8_t packet[TS_PACKET_SIZE];
1150     int packet_num, ret;
1151
1152     ts->stop_parse = 0;
1153     packet_num = 0;
1154     for(;;) {
1155         if (ts->stop_parse>0)
1156             break;
1157         packet_num++;
1158         if (nb_packets != 0 && packet_num >= nb_packets)
1159             break;
1160         ret = read_packet(pb, packet, ts->raw_packet_size);
1161         if (ret != 0)
1162             return ret;
1163         handle_packet(ts, packet);
1164     }
1165     return 0;
1166 }
1167
1168 static int mpegts_probe(AVProbeData *p)
1169 {
1170 #if 1
1171     const int size= p->buf_size;
1172     int score, fec_score, dvhs_score;
1173     int check_count= size / TS_FEC_PACKET_SIZE;
1174 #define CHECK_COUNT 10
1175
1176     if (check_count < CHECK_COUNT)
1177         return -1;
1178
1179     score     = analyze(p->buf, TS_PACKET_SIZE     *check_count, TS_PACKET_SIZE     , NULL)*CHECK_COUNT/check_count;
1180     dvhs_score= analyze(p->buf, TS_DVHS_PACKET_SIZE*check_count, TS_DVHS_PACKET_SIZE, NULL)*CHECK_COUNT/check_count;
1181     fec_score = analyze(p->buf, TS_FEC_PACKET_SIZE *check_count, TS_FEC_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
1182 //    av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
1183
1184 // we need a clear definition for the returned score otherwise things will become messy sooner or later
1185     if     (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score     - CHECK_COUNT;
1186     else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score  - CHECK_COUNT;
1187     else if(                 fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
1188     else                                    return -1;
1189 #else
1190     /* only use the extension for safer guess */
1191     if (match_ext(p->filename, "ts"))
1192         return AVPROBE_SCORE_MAX;
1193     else
1194         return 0;
1195 #endif
1196 }
1197
1198 /* return the 90kHz PCR and the extension for the 27MHz PCR. return
1199    (-1) if not available */
1200 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1201                      const uint8_t *packet)
1202 {
1203     int afc, len, flags;
1204     const uint8_t *p;
1205     unsigned int v;
1206
1207     afc = (packet[3] >> 4) & 3;
1208     if (afc <= 1)
1209         return -1;
1210     p = packet + 4;
1211     len = p[0];
1212     p++;
1213     if (len == 0)
1214         return -1;
1215     flags = *p++;
1216     len--;
1217     if (!(flags & 0x10))
1218         return -1;
1219     if (len < 6)
1220         return -1;
1221     v = AV_RB32(p);
1222     *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1223     *ppcr_low = ((p[4] & 1) << 8) | p[5];
1224     return 0;
1225 }
1226
1227 static int mpegts_read_header(AVFormatContext *s,
1228                               AVFormatParameters *ap)
1229 {
1230     MpegTSContext *ts = s->priv_data;
1231     ByteIOContext *pb = s->pb;
1232     uint8_t buf[5*1024];
1233     int len;
1234     int64_t pos;
1235
1236     if (ap) {
1237         ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
1238         if(ap->mpeg2ts_raw){
1239             av_log(s, AV_LOG_ERROR, "use mpegtsraw_demuxer!\n");
1240             return -1;
1241         }
1242     }
1243
1244     /* read the first 1024 bytes to get packet size */
1245     pos = url_ftell(pb);
1246     len = get_buffer(pb, buf, sizeof(buf));
1247     if (len != sizeof(buf))
1248         goto fail;
1249     ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1250     if (ts->raw_packet_size <= 0)
1251         goto fail;
1252     ts->stream = s;
1253     ts->auto_guess = 0;
1254
1255     if (s->iformat == &mpegts_demuxer) {
1256         /* normal demux */
1257
1258         /* first do a scaning to get all the services */
1259         url_fseek(pb, pos, SEEK_SET);
1260
1261         mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
1262
1263         mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
1264
1265         handle_packets(ts, s->probesize);
1266         /* if could not find service, enable auto_guess */
1267
1268         ts->auto_guess = 1;
1269
1270         dprintf(ts->stream, "tuning done\n");
1271
1272         s->ctx_flags |= AVFMTCTX_NOHEADER;
1273     } else {
1274         AVStream *st;
1275         int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1276         int64_t pcrs[2], pcr_h;
1277         int packet_count[2];
1278         uint8_t packet[TS_PACKET_SIZE];
1279
1280         /* only read packets */
1281
1282         st = av_new_stream(s, 0);
1283         if (!st)
1284             goto fail;
1285         av_set_pts_info(st, 60, 1, 27000000);
1286         st->codec->codec_type = CODEC_TYPE_DATA;
1287         st->codec->codec_id = CODEC_ID_MPEG2TS;
1288
1289         /* we iterate until we find two PCRs to estimate the bitrate */
1290         pcr_pid = -1;
1291         nb_pcrs = 0;
1292         nb_packets = 0;
1293         for(;;) {
1294             ret = read_packet(s->pb, packet, ts->raw_packet_size);
1295             if (ret < 0)
1296                 return -1;
1297             pid = AV_RB16(packet + 1) & 0x1fff;
1298             if ((pcr_pid == -1 || pcr_pid == pid) &&
1299                 parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
1300                 pcr_pid = pid;
1301                 packet_count[nb_pcrs] = nb_packets;
1302                 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
1303                 nb_pcrs++;
1304                 if (nb_pcrs >= 2)
1305                     break;
1306             }
1307             nb_packets++;
1308         }
1309
1310         /* NOTE1: the bitrate is computed without the FEC */
1311         /* NOTE2: it is only the bitrate of the start of the stream */
1312         ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
1313         ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
1314         s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
1315         st->codec->bit_rate = s->bit_rate;
1316         st->start_time = ts->cur_pcr;
1317 #if 0
1318         av_log(ts->stream, AV_LOG_DEBUG, "start=%0.3f pcr=%0.3f incr=%d\n",
1319                st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
1320 #endif
1321     }
1322
1323     url_fseek(pb, pos, SEEK_SET);
1324     return 0;
1325  fail:
1326     return -1;
1327 }
1328
1329 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1330
1331 static int mpegts_raw_read_packet(AVFormatContext *s,
1332                                   AVPacket *pkt)
1333 {
1334     MpegTSContext *ts = s->priv_data;
1335     int ret, i;
1336     int64_t pcr_h, next_pcr_h, pos;
1337     int pcr_l, next_pcr_l;
1338     uint8_t pcr_buf[12];
1339
1340     if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
1341         return AVERROR(ENOMEM);
1342     pkt->pos= url_ftell(s->pb);
1343     ret = read_packet(s->pb, pkt->data, ts->raw_packet_size);
1344     if (ret < 0) {
1345         av_free_packet(pkt);
1346         return ret;
1347     }
1348     if (ts->mpeg2ts_compute_pcr) {
1349         /* compute exact PCR for each packet */
1350         if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
1351             /* we read the next PCR (XXX: optimize it by using a bigger buffer */
1352             pos = url_ftell(s->pb);
1353             for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
1354                 url_fseek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
1355                 get_buffer(s->pb, pcr_buf, 12);
1356                 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
1357                     /* XXX: not precise enough */
1358                     ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
1359                         (i + 1);
1360                     break;
1361                 }
1362             }
1363             url_fseek(s->pb, pos, SEEK_SET);
1364             /* no next PCR found: we use previous increment */
1365             ts->cur_pcr = pcr_h * 300 + pcr_l;
1366         }
1367         pkt->pts = ts->cur_pcr;
1368         pkt->duration = ts->pcr_incr;
1369         ts->cur_pcr += ts->pcr_incr;
1370     }
1371     pkt->stream_index = 0;
1372     return 0;
1373 }
1374
1375 static int mpegts_read_packet(AVFormatContext *s,
1376                               AVPacket *pkt)
1377 {
1378     MpegTSContext *ts = s->priv_data;
1379
1380     ts->pkt = pkt;
1381     return handle_packets(ts, 0);
1382 }
1383
1384 static int mpegts_read_close(AVFormatContext *s)
1385 {
1386     MpegTSContext *ts = s->priv_data;
1387     int i;
1388
1389     clear_programs(ts);
1390
1391     for(i=0;i<NB_PID_MAX;i++)
1392         if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
1393
1394     return 0;
1395 }
1396
1397 static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
1398                               int64_t *ppos, int64_t pos_limit)
1399 {
1400     MpegTSContext *ts = s->priv_data;
1401     int64_t pos, timestamp;
1402     uint8_t buf[TS_PACKET_SIZE];
1403     int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
1404     const int find_next= 1;
1405     pos = ((*ppos  + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
1406     if (find_next) {
1407         for(;;) {
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             if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1412                 parse_pcr(&timestamp, &pcr_l, buf) == 0) {
1413                 break;
1414             }
1415             pos += ts->raw_packet_size;
1416         }
1417     } else {
1418         for(;;) {
1419             pos -= ts->raw_packet_size;
1420             if (pos < 0)
1421                 return AV_NOPTS_VALUE;
1422             url_fseek(s->pb, pos, SEEK_SET);
1423             if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1424                 return AV_NOPTS_VALUE;
1425             if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1426                 parse_pcr(&timestamp, &pcr_l, buf) == 0) {
1427                 break;
1428             }
1429         }
1430     }
1431     *ppos = pos;
1432
1433     return timestamp;
1434 }
1435
1436 static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1437     MpegTSContext *ts = s->priv_data;
1438     uint8_t buf[TS_PACKET_SIZE];
1439     int64_t pos;
1440
1441     if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
1442         return -1;
1443
1444     pos= url_ftell(s->pb);
1445
1446     for(;;) {
1447         url_fseek(s->pb, pos, SEEK_SET);
1448         if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1449             return -1;
1450 //        pid = AV_RB16(buf + 1) & 0x1fff;
1451         if(buf[1] & 0x40) break;
1452         pos += ts->raw_packet_size;
1453     }
1454     url_fseek(s->pb, pos, SEEK_SET);
1455
1456     return 0;
1457 }
1458
1459 /**************************************************************/
1460 /* parsing functions - called from other demuxers such as RTP */
1461
1462 MpegTSContext *mpegts_parse_open(AVFormatContext *s)
1463 {
1464     MpegTSContext *ts;
1465
1466     ts = av_mallocz(sizeof(MpegTSContext));
1467     if (!ts)
1468         return NULL;
1469     /* no stream case, currently used by RTP */
1470     ts->raw_packet_size = TS_PACKET_SIZE;
1471     ts->stream = s;
1472     ts->auto_guess = 1;
1473     return ts;
1474 }
1475
1476 /* return the consumed length if a packet was output, or -1 if no
1477    packet is output */
1478 int mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
1479                         const uint8_t *buf, int len)
1480 {
1481     int len1;
1482
1483     len1 = len;
1484     ts->pkt = pkt;
1485     ts->stop_parse = 0;
1486     for(;;) {
1487         if (ts->stop_parse>0)
1488             break;
1489         if (len < TS_PACKET_SIZE)
1490             return -1;
1491         if (buf[0] != 0x47) {
1492             buf++;
1493             len--;
1494         } else {
1495             handle_packet(ts, buf);
1496             buf += TS_PACKET_SIZE;
1497             len -= TS_PACKET_SIZE;
1498         }
1499     }
1500     return len1 - len;
1501 }
1502
1503 void mpegts_parse_close(MpegTSContext *ts)
1504 {
1505     int i;
1506
1507     for(i=0;i<NB_PID_MAX;i++)
1508         av_free(ts->pids[i]);
1509     av_free(ts);
1510 }
1511
1512 AVInputFormat mpegts_demuxer = {
1513     "mpegts",
1514     NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
1515     sizeof(MpegTSContext),
1516     mpegts_probe,
1517     mpegts_read_header,
1518     mpegts_read_packet,
1519     mpegts_read_close,
1520     read_seek,
1521     mpegts_get_pcr,
1522     .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
1523 };
1524
1525 AVInputFormat mpegtsraw_demuxer = {
1526     "mpegtsraw",
1527     NULL_IF_CONFIG_SMALL("MPEG-2 raw transport stream format"),
1528     sizeof(MpegTSContext),
1529     NULL,
1530     mpegts_read_header,
1531     mpegts_raw_read_packet,
1532     mpegts_read_close,
1533     read_seek,
1534     mpegts_get_pcr,
1535     .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
1536 };