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