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