]> git.sesse.net Git - ffmpeg/blob - libavformat/mpegts.c
a97fd7a62d63d1da41e63aee35ddc463fdb58763
[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
22 //#define DEBUG
23 //#define DEBUG_SEEK
24 //#define USE_SYNCPOINT_SEARCH
25
26 #include "libavutil/crc.h"
27 #include "libavutil/intreadwrite.h"
28 #include "libavcodec/bytestream.h"
29 #include "avformat.h"
30 #include "mpegts.h"
31 #include "internal.h"
32 #include "seek.h"
33 #include "mpeg.h"
34 #include "isom.h"
35
36 /* maximum size in which we look for synchronisation if
37    synchronisation is lost */
38 #define MAX_RESYNC_SIZE 65536
39
40 #define MAX_PES_PAYLOAD 200*1024
41
42 enum MpegTSFilterType {
43     MPEGTS_PES,
44     MPEGTS_SECTION,
45 };
46
47 typedef struct MpegTSFilter MpegTSFilter;
48
49 typedef int PESCallback(MpegTSFilter *f, const uint8_t *buf, int len, int is_start, int64_t pos);
50
51 typedef struct MpegTSPESFilter {
52     PESCallback *pes_cb;
53     void *opaque;
54 } MpegTSPESFilter;
55
56 typedef void SectionCallback(MpegTSFilter *f, const uint8_t *buf, int len);
57
58 typedef void SetServiceCallback(void *opaque, int ret);
59
60 typedef struct MpegTSSectionFilter {
61     int section_index;
62     int section_h_size;
63     uint8_t *section_buf;
64     unsigned int check_crc:1;
65     unsigned int end_of_section_reached:1;
66     SectionCallback *section_cb;
67     void *opaque;
68 } MpegTSSectionFilter;
69
70 struct MpegTSFilter {
71     int pid;
72     int last_cc; /* last cc code (-1 if first packet) */
73     enum MpegTSFilterType type;
74     union {
75         MpegTSPESFilter pes_filter;
76         MpegTSSectionFilter section_filter;
77     } u;
78 };
79
80 #define MAX_PIDS_PER_PROGRAM 64
81 struct Program {
82     unsigned int id; //program id/service id
83     unsigned int nb_pids;
84     unsigned int pids[MAX_PIDS_PER_PROGRAM];
85 };
86
87 struct MpegTSContext {
88     /* user data */
89     AVFormatContext *stream;
90     /** raw packet size, including FEC if present            */
91     int raw_packet_size;
92
93     int pos47;
94
95     /** if true, all pids are analyzed to find streams       */
96     int auto_guess;
97
98     /** compute exact PCR for each transport stream packet   */
99     int mpeg2ts_compute_pcr;
100
101     int64_t cur_pcr;    /**< used to estimate the exact PCR  */
102     int pcr_incr;       /**< used to estimate the exact PCR  */
103
104     /* data needed to handle file based ts */
105     /** stop parsing loop                                    */
106     int stop_parse;
107     /** packet containing Audio/Video data                   */
108     AVPacket *pkt;
109     /** to detect seek                                       */
110     int64_t last_pos;
111
112     /******************************************/
113     /* private mpegts data */
114     /* scan context */
115     /** structure to keep track of Program->pids mapping     */
116     unsigned int nb_prg;
117     struct Program *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,
129     MPEGTS_PESHEADER_FILL,
130     MPEGTS_PAYLOAD,
131     MPEGTS_SKIP,
132 };
133
134 /* enough for PES header + length */
135 #define PES_START_SIZE  6
136 #define PES_HEADER_SIZE 9
137 #define MAX_PES_HEADER_SIZE (9 + 255)
138
139 typedef struct PESContext {
140     int pid;
141     int pcr_pid; /**< if -1 then all packets containing PCR are considered */
142     int stream_type;
143     MpegTSContext *ts;
144     AVFormatContext *stream;
145     AVStream *st;
146     AVStream *sub_st; /**< stream for the embedded AC3 stream in HDMV TrueHD */
147     enum MpegTSState state;
148     /* used to get the format */
149     int data_index;
150     int total_size;
151     int pes_header_size;
152     int extended_stream_id;
153     int64_t pts, dts;
154     int64_t ts_packet_pos; /**< position of first TS packet of this PES packet */
155     uint8_t header[MAX_PES_HEADER_SIZE];
156     uint8_t *buffer;
157 } PESContext;
158
159 extern AVInputFormat ff_mpegts_demuxer;
160
161 static void clear_program(MpegTSContext *ts, unsigned int programid)
162 {
163     int i;
164
165     for(i=0; i<ts->nb_prg; i++)
166         if(ts->prg[i].id == programid)
167             ts->prg[i].nb_pids = 0;
168 }
169
170 static void clear_programs(MpegTSContext *ts)
171 {
172     av_freep(&ts->prg);
173     ts->nb_prg=0;
174 }
175
176 static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
177 {
178     struct Program *p;
179     void *tmp = av_realloc(ts->prg, (ts->nb_prg+1)*sizeof(struct Program));
180     if(!tmp)
181         return;
182     ts->prg = tmp;
183     p = &ts->prg[ts->nb_prg];
184     p->id = programid;
185     p->nb_pids = 0;
186     ts->nb_prg++;
187 }
188
189 static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid, unsigned int pid)
190 {
191     int i;
192     struct Program *p = NULL;
193     for(i=0; i<ts->nb_prg; i++) {
194         if(ts->prg[i].id == programid) {
195             p = &ts->prg[i];
196             break;
197         }
198     }
199     if(!p)
200         return;
201
202     if(p->nb_pids >= MAX_PIDS_PER_PROGRAM)
203         return;
204     p->pids[p->nb_pids++] = pid;
205 }
206
207 /**
208  * \brief discard_pid() decides if the pid is to be discarded according
209  *                      to caller's programs selection
210  * \param ts    : - TS context
211  * \param pid   : - pid
212  * \return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
213  *         0 otherwise
214  */
215 static int discard_pid(MpegTSContext *ts, unsigned int pid)
216 {
217     int i, j, k;
218     int used = 0, discarded = 0;
219     struct Program *p;
220     for(i=0; i<ts->nb_prg; i++) {
221         p = &ts->prg[i];
222         for(j=0; j<p->nb_pids; j++) {
223             if(p->pids[j] != pid)
224                 continue;
225             //is program with id p->id set to be discarded?
226             for(k=0; k<ts->stream->nb_programs; k++) {
227                 if(ts->stream->programs[k]->id == p->id) {
228                     if(ts->stream->programs[k]->discard == AVDISCARD_ALL)
229                         discarded++;
230                     else
231                         used++;
232                 }
233             }
234         }
235     }
236
237     return !used && discarded;
238 }
239
240 /**
241  *  Assemble PES packets out of TS packets, and then call the "section_cb"
242  *  function when they are complete.
243  */
244 static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
245                                const uint8_t *buf, int buf_size, int is_start)
246 {
247     MpegTSSectionFilter *tss = &tss1->u.section_filter;
248     int len;
249
250     if (is_start) {
251         memcpy(tss->section_buf, buf, buf_size);
252         tss->section_index = buf_size;
253         tss->section_h_size = -1;
254         tss->end_of_section_reached = 0;
255     } else {
256         if (tss->end_of_section_reached)
257             return;
258         len = 4096 - tss->section_index;
259         if (buf_size < len)
260             len = buf_size;
261         memcpy(tss->section_buf + tss->section_index, buf, len);
262         tss->section_index += len;
263     }
264
265     /* compute section length if possible */
266     if (tss->section_h_size == -1 && tss->section_index >= 3) {
267         len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
268         if (len > 4096)
269             return;
270         tss->section_h_size = len;
271     }
272
273     if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
274         tss->end_of_section_reached = 1;
275         if (!tss->check_crc ||
276             av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1,
277                    tss->section_buf, tss->section_h_size) == 0)
278             tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
279     }
280 }
281
282 static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
283                                          SectionCallback *section_cb, void *opaque,
284                                          int check_crc)
285
286 {
287     MpegTSFilter *filter;
288     MpegTSSectionFilter *sec;
289
290     av_dlog(ts->stream, "Filter: pid=0x%x\n", pid);
291
292     if (pid >= NB_PID_MAX || ts->pids[pid])
293         return NULL;
294     filter = av_mallocz(sizeof(MpegTSFilter));
295     if (!filter)
296         return NULL;
297     ts->pids[pid] = filter;
298     filter->type = MPEGTS_SECTION;
299     filter->pid = pid;
300     filter->last_cc = -1;
301     sec = &filter->u.section_filter;
302     sec->section_cb = section_cb;
303     sec->opaque = opaque;
304     sec->section_buf = av_malloc(MAX_SECTION_SIZE);
305     sec->check_crc = check_crc;
306     if (!sec->section_buf) {
307         av_free(filter);
308         return NULL;
309     }
310     return filter;
311 }
312
313 static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
314                                      PESCallback *pes_cb,
315                                      void *opaque)
316 {
317     MpegTSFilter *filter;
318     MpegTSPESFilter *pes;
319
320     if (pid >= NB_PID_MAX || ts->pids[pid])
321         return NULL;
322     filter = av_mallocz(sizeof(MpegTSFilter));
323     if (!filter)
324         return NULL;
325     ts->pids[pid] = filter;
326     filter->type = MPEGTS_PES;
327     filter->pid = pid;
328     filter->last_cc = -1;
329     pes = &filter->u.pes_filter;
330     pes->pes_cb = pes_cb;
331     pes->opaque = opaque;
332     return filter;
333 }
334
335 static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
336 {
337     int pid;
338
339     pid = filter->pid;
340     if (filter->type == MPEGTS_SECTION)
341         av_freep(&filter->u.section_filter.section_buf);
342     else if (filter->type == MPEGTS_PES) {
343         PESContext *pes = filter->u.pes_filter.opaque;
344         av_freep(&pes->buffer);
345         /* referenced private data will be freed later in
346          * av_close_input_stream */
347         if (!((PESContext *)filter->u.pes_filter.opaque)->st) {
348             av_freep(&filter->u.pes_filter.opaque);
349         }
350     }
351
352     av_free(filter);
353     ts->pids[pid] = NULL;
354 }
355
356 static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
357     int stat[TS_MAX_PACKET_SIZE];
358     int i;
359     int x=0;
360     int best_score=0;
361
362     memset(stat, 0, packet_size*sizeof(int));
363
364     for(x=i=0; i<size-3; i++){
365         if(buf[i] == 0x47 && !(buf[i+1] & 0x80) && (buf[i+3] & 0x30)){
366             stat[x]++;
367             if(stat[x] > best_score){
368                 best_score= stat[x];
369                 if(index) *index= x;
370             }
371         }
372
373         x++;
374         if(x == packet_size) x= 0;
375     }
376
377     return best_score;
378 }
379
380 /* autodetect fec presence. Must have at least 1024 bytes  */
381 static int get_packet_size(const uint8_t *buf, int size)
382 {
383     int score, fec_score, dvhs_score;
384
385     if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
386         return -1;
387
388     score    = analyze(buf, size, TS_PACKET_SIZE, NULL);
389     dvhs_score    = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
390     fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
391 //    av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
392
393     if     (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
394     else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
395     else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
396     else                       return -1;
397 }
398
399 typedef struct SectionHeader {
400     uint8_t tid;
401     uint16_t id;
402     uint8_t version;
403     uint8_t sec_num;
404     uint8_t last_sec_num;
405 } SectionHeader;
406
407 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
408 {
409     const uint8_t *p;
410     int c;
411
412     p = *pp;
413     if (p >= p_end)
414         return -1;
415     c = *p++;
416     *pp = p;
417     return c;
418 }
419
420 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
421 {
422     const uint8_t *p;
423     int c;
424
425     p = *pp;
426     if ((p + 1) >= p_end)
427         return -1;
428     c = AV_RB16(p);
429     p += 2;
430     *pp = p;
431     return c;
432 }
433
434 /* read and allocate a DVB string preceeded by its length */
435 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
436 {
437     int len;
438     const uint8_t *p;
439     char *str;
440
441     p = *pp;
442     len = get8(&p, p_end);
443     if (len < 0)
444         return NULL;
445     if ((p + len) > p_end)
446         return NULL;
447     str = av_malloc(len + 1);
448     if (!str)
449         return NULL;
450     memcpy(str, p, len);
451     str[len] = '\0';
452     p += len;
453     *pp = p;
454     return str;
455 }
456
457 static int parse_section_header(SectionHeader *h,
458                                 const uint8_t **pp, const uint8_t *p_end)
459 {
460     int val;
461
462     val = get8(pp, p_end);
463     if (val < 0)
464         return -1;
465     h->tid = val;
466     *pp += 2;
467     val = get16(pp, p_end);
468     if (val < 0)
469         return -1;
470     h->id = val;
471     val = get8(pp, p_end);
472     if (val < 0)
473         return -1;
474     h->version = (val >> 1) & 0x1f;
475     val = get8(pp, p_end);
476     if (val < 0)
477         return -1;
478     h->sec_num = val;
479     val = get8(pp, p_end);
480     if (val < 0)
481         return -1;
482     h->last_sec_num = val;
483     return 0;
484 }
485
486 typedef struct {
487     uint32_t stream_type;
488     enum AVMediaType codec_type;
489     enum CodecID codec_id;
490 } StreamType;
491
492 static const StreamType ISO_types[] = {
493     { 0x01, AVMEDIA_TYPE_VIDEO, CODEC_ID_MPEG2VIDEO },
494     { 0x02, AVMEDIA_TYPE_VIDEO, CODEC_ID_MPEG2VIDEO },
495     { 0x03, AVMEDIA_TYPE_AUDIO,        CODEC_ID_MP3 },
496     { 0x04, AVMEDIA_TYPE_AUDIO,        CODEC_ID_MP3 },
497     { 0x0f, AVMEDIA_TYPE_AUDIO,        CODEC_ID_AAC },
498     { 0x10, AVMEDIA_TYPE_VIDEO,      CODEC_ID_MPEG4 },
499     { 0x11, AVMEDIA_TYPE_AUDIO,   CODEC_ID_AAC_LATM }, /* LATM syntax */
500     { 0x1b, AVMEDIA_TYPE_VIDEO,       CODEC_ID_H264 },
501     { 0xd1, AVMEDIA_TYPE_VIDEO,      CODEC_ID_DIRAC },
502     { 0xea, AVMEDIA_TYPE_VIDEO,        CODEC_ID_VC1 },
503     { 0 },
504 };
505
506 static const StreamType HDMV_types[] = {
507     { 0x80, AVMEDIA_TYPE_AUDIO, CODEC_ID_PCM_BLURAY },
508     { 0x81, AVMEDIA_TYPE_AUDIO, CODEC_ID_AC3 },
509     { 0x82, AVMEDIA_TYPE_AUDIO, CODEC_ID_DTS },
510     { 0x83, AVMEDIA_TYPE_AUDIO, CODEC_ID_TRUEHD },
511     { 0x84, AVMEDIA_TYPE_AUDIO, CODEC_ID_EAC3 },
512     { 0x90, AVMEDIA_TYPE_SUBTITLE, CODEC_ID_HDMV_PGS_SUBTITLE },
513     { 0 },
514 };
515
516 /* ATSC ? */
517 static const StreamType MISC_types[] = {
518     { 0x81, AVMEDIA_TYPE_AUDIO,   CODEC_ID_AC3 },
519     { 0x8a, AVMEDIA_TYPE_AUDIO,   CODEC_ID_DTS },
520     { 0 },
521 };
522
523 static const StreamType REGD_types[] = {
524     { MKTAG('d','r','a','c'), AVMEDIA_TYPE_VIDEO, CODEC_ID_DIRAC },
525     { MKTAG('A','C','-','3'), AVMEDIA_TYPE_AUDIO,   CODEC_ID_AC3 },
526     { 0 },
527 };
528
529 /* descriptor present */
530 static const StreamType DESC_types[] = {
531     { 0x6a, AVMEDIA_TYPE_AUDIO,             CODEC_ID_AC3 }, /* AC-3 descriptor */
532     { 0x7a, AVMEDIA_TYPE_AUDIO,            CODEC_ID_EAC3 }, /* E-AC-3 descriptor */
533     { 0x7b, AVMEDIA_TYPE_AUDIO,             CODEC_ID_DTS },
534     { 0x56, AVMEDIA_TYPE_SUBTITLE, CODEC_ID_DVB_TELETEXT },
535     { 0x59, AVMEDIA_TYPE_SUBTITLE, CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
536     { 0 },
537 };
538
539 static void mpegts_find_stream_type(AVStream *st,
540                                     uint32_t stream_type, const StreamType *types)
541 {
542     for (; types->stream_type; types++) {
543         if (stream_type == types->stream_type) {
544             st->codec->codec_type = types->codec_type;
545             st->codec->codec_id   = types->codec_id;
546             return;
547         }
548     }
549 }
550
551 static int mpegts_set_stream_info(AVStream *st, PESContext *pes,
552                                   uint32_t stream_type, uint32_t prog_reg_desc)
553 {
554     av_set_pts_info(st, 33, 1, 90000);
555     st->priv_data = pes;
556     st->codec->codec_type = AVMEDIA_TYPE_DATA;
557     st->codec->codec_id   = CODEC_ID_NONE;
558     st->need_parsing = AVSTREAM_PARSE_FULL;
559     pes->st = st;
560     pes->stream_type = stream_type;
561
562     av_log(pes->stream, AV_LOG_DEBUG,
563            "stream=%d stream_type=%x pid=%x prog_reg_desc=%.4s\n",
564            st->index, pes->stream_type, pes->pid, (char*)&prog_reg_desc);
565
566     st->codec->codec_tag = pes->stream_type;
567
568     mpegts_find_stream_type(st, pes->stream_type, ISO_types);
569     if (prog_reg_desc == AV_RL32("HDMV") &&
570         st->codec->codec_id == CODEC_ID_NONE) {
571         mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
572         if (pes->stream_type == 0x83) {
573             // HDMV TrueHD streams also contain an AC3 coded version of the
574             // audio track - add a second stream for this
575             AVStream *sub_st;
576             // priv_data cannot be shared between streams
577             PESContext *sub_pes = av_malloc(sizeof(*sub_pes));
578             if (!sub_pes)
579                 return AVERROR(ENOMEM);
580             memcpy(sub_pes, pes, sizeof(*sub_pes));
581
582             sub_st = av_new_stream(pes->stream, pes->pid);
583             if (!sub_st) {
584                 av_free(sub_pes);
585                 return AVERROR(ENOMEM);
586             }
587
588             av_set_pts_info(sub_st, 33, 1, 90000);
589             sub_st->priv_data = sub_pes;
590             sub_st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
591             sub_st->codec->codec_id   = CODEC_ID_AC3;
592             sub_st->need_parsing = AVSTREAM_PARSE_FULL;
593             sub_pes->sub_st = pes->sub_st = sub_st;
594         }
595     }
596     if (st->codec->codec_id == CODEC_ID_NONE)
597         mpegts_find_stream_type(st, pes->stream_type, MISC_types);
598
599     return 0;
600 }
601
602 static void new_pes_packet(PESContext *pes, AVPacket *pkt)
603 {
604     av_init_packet(pkt);
605
606     pkt->destruct = av_destruct_packet;
607     pkt->data = pes->buffer;
608     pkt->size = pes->data_index;
609     memset(pkt->data+pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
610
611     // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID
612     if (pes->sub_st && pes->stream_type == 0x83 && pes->extended_stream_id == 0x76)
613         pkt->stream_index = pes->sub_st->index;
614     else
615         pkt->stream_index = pes->st->index;
616     pkt->pts = pes->pts;
617     pkt->dts = pes->dts;
618     /* store position of first TS packet of this PES packet */
619     pkt->pos = pes->ts_packet_pos;
620
621     /* reset pts values */
622     pes->pts = AV_NOPTS_VALUE;
623     pes->dts = AV_NOPTS_VALUE;
624     pes->buffer = NULL;
625     pes->data_index = 0;
626 }
627
628 /* return non zero if a packet could be constructed */
629 static int mpegts_push_data(MpegTSFilter *filter,
630                             const uint8_t *buf, int buf_size, int is_start,
631                             int64_t pos)
632 {
633     PESContext *pes = filter->u.pes_filter.opaque;
634     MpegTSContext *ts = pes->ts;
635     const uint8_t *p;
636     int len, code;
637
638     if(!ts->pkt)
639         return 0;
640
641     if (is_start) {
642         if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
643             new_pes_packet(pes, ts->pkt);
644             ts->stop_parse = 1;
645         }
646         pes->state = MPEGTS_HEADER;
647         pes->data_index = 0;
648         pes->ts_packet_pos = pos;
649     }
650     p = buf;
651     while (buf_size > 0) {
652         switch(pes->state) {
653         case MPEGTS_HEADER:
654             len = PES_START_SIZE - pes->data_index;
655             if (len > buf_size)
656                 len = buf_size;
657             memcpy(pes->header + pes->data_index, p, len);
658             pes->data_index += len;
659             p += len;
660             buf_size -= len;
661             if (pes->data_index == PES_START_SIZE) {
662                 /* we got all the PES or section header. We can now
663                    decide */
664 #if 0
665                 av_hex_dump_log(pes->stream, AV_LOG_DEBUG, pes->header, pes->data_index);
666 #endif
667                 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
668                     pes->header[2] == 0x01) {
669                     /* it must be an mpeg2 PES stream */
670                     code = pes->header[3] | 0x100;
671                     av_dlog(pes->stream, "pid=%x pes_code=%#x\n", pes->pid, code);
672
673                     if ((pes->st && pes->st->discard == AVDISCARD_ALL) ||
674                         code == 0x1be) /* padding_stream */
675                         goto skip;
676
677 #if FF_API_MAX_STREAMS
678                     if (!pes->st && pes->stream->nb_streams == MAX_STREAMS)
679                         goto skip;
680 #endif
681
682                     /* stream not present in PMT */
683                     if (!pes->st) {
684                         pes->st = av_new_stream(ts->stream, pes->pid);
685                         if (!pes->st)
686                             return AVERROR(ENOMEM);
687                         mpegts_set_stream_info(pes->st, pes, 0, 0);
688                     }
689
690                     pes->total_size = AV_RB16(pes->header + 4);
691                     /* NOTE: a zero total size means the PES size is
692                        unbounded */
693                     if (!pes->total_size)
694                         pes->total_size = MAX_PES_PAYLOAD;
695
696                     /* allocate pes buffer */
697                     pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
698                     if (!pes->buffer)
699                         return AVERROR(ENOMEM);
700
701                     if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
702                         code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
703                         code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
704                         code != 0x1f8) {                  /* ITU-T Rec. H.222.1 type E stream */
705                         pes->state = MPEGTS_PESHEADER;
706                         if (pes->st->codec->codec_id == CODEC_ID_NONE) {
707                             av_dlog(pes->stream, "pid=%x stream_type=%x probing\n",
708                                     pes->pid, pes->stream_type);
709                             pes->st->codec->codec_id = CODEC_ID_PROBE;
710                         }
711                     } else {
712                         pes->state = MPEGTS_PAYLOAD;
713                         pes->data_index = 0;
714                     }
715                 } else {
716                     /* otherwise, it should be a table */
717                     /* skip packet */
718                 skip:
719                     pes->state = MPEGTS_SKIP;
720                     continue;
721                 }
722             }
723             break;
724             /**********************************************/
725             /* PES packing parsing */
726         case MPEGTS_PESHEADER:
727             len = PES_HEADER_SIZE - pes->data_index;
728             if (len < 0)
729                 return -1;
730             if (len > buf_size)
731                 len = buf_size;
732             memcpy(pes->header + pes->data_index, p, len);
733             pes->data_index += len;
734             p += len;
735             buf_size -= len;
736             if (pes->data_index == PES_HEADER_SIZE) {
737                 pes->pes_header_size = pes->header[8] + 9;
738                 pes->state = MPEGTS_PESHEADER_FILL;
739             }
740             break;
741         case MPEGTS_PESHEADER_FILL:
742             len = pes->pes_header_size - pes->data_index;
743             if (len < 0)
744                 return -1;
745             if (len > buf_size)
746                 len = buf_size;
747             memcpy(pes->header + pes->data_index, p, len);
748             pes->data_index += len;
749             p += len;
750             buf_size -= len;
751             if (pes->data_index == pes->pes_header_size) {
752                 const uint8_t *r;
753                 unsigned int flags, pes_ext, skip;
754
755                 flags = pes->header[7];
756                 r = pes->header + 9;
757                 pes->pts = AV_NOPTS_VALUE;
758                 pes->dts = AV_NOPTS_VALUE;
759                 if ((flags & 0xc0) == 0x80) {
760                     pes->dts = pes->pts = ff_parse_pes_pts(r);
761                     r += 5;
762                 } else if ((flags & 0xc0) == 0xc0) {
763                     pes->pts = ff_parse_pes_pts(r);
764                     r += 5;
765                     pes->dts = ff_parse_pes_pts(r);
766                     r += 5;
767                 }
768                 pes->extended_stream_id = -1;
769                 if (flags & 0x01) { /* PES extension */
770                     pes_ext = *r++;
771                     /* Skip PES private data, program packet sequence counter and P-STD buffer */
772                     skip = (pes_ext >> 4) & 0xb;
773                     skip += skip & 0x9;
774                     r += skip;
775                     if ((pes_ext & 0x41) == 0x01 &&
776                         (r + 2) <= (pes->header + pes->pes_header_size)) {
777                         /* PES extension 2 */
778                         if ((r[0] & 0x7f) > 0 && (r[1] & 0x80) == 0)
779                             pes->extended_stream_id = r[1];
780                     }
781                 }
782
783                 /* we got the full header. We parse it and get the payload */
784                 pes->state = MPEGTS_PAYLOAD;
785                 pes->data_index = 0;
786             }
787             break;
788         case MPEGTS_PAYLOAD:
789             if (buf_size > 0 && pes->buffer) {
790                 if (pes->data_index > 0 && pes->data_index+buf_size > pes->total_size) {
791                     new_pes_packet(pes, ts->pkt);
792                     pes->total_size = MAX_PES_PAYLOAD;
793                     pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
794                     if (!pes->buffer)
795                         return AVERROR(ENOMEM);
796                     ts->stop_parse = 1;
797                 } else if (pes->data_index == 0 && buf_size > pes->total_size) {
798                     // pes packet size is < ts size packet and pes data is padded with 0xff
799                     // not sure if this is legal in ts but see issue #2392
800                     buf_size = pes->total_size;
801                 }
802                 memcpy(pes->buffer+pes->data_index, p, buf_size);
803                 pes->data_index += buf_size;
804             }
805             buf_size = 0;
806             /* emit complete packets with known packet size
807              * decreases demuxer delay for infrequent packets like subtitles from
808              * a couple of seconds to milliseconds for properly muxed files.
809              * total_size is the number of bytes following pes_packet_length
810              * in the pes header, i.e. not counting the first 6 bytes */
811             if (pes->total_size < MAX_PES_PAYLOAD &&
812                 pes->pes_header_size + pes->data_index == pes->total_size + 6) {
813                 ts->stop_parse = 1;
814                 new_pes_packet(pes, ts->pkt);
815             }
816             break;
817         case MPEGTS_SKIP:
818             buf_size = 0;
819             break;
820         }
821     }
822
823     return 0;
824 }
825
826 static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
827 {
828     MpegTSFilter *tss;
829     PESContext *pes;
830
831     /* if no pid found, then add a pid context */
832     pes = av_mallocz(sizeof(PESContext));
833     if (!pes)
834         return 0;
835     pes->ts = ts;
836     pes->stream = ts->stream;
837     pes->pid = pid;
838     pes->pcr_pid = pcr_pid;
839     pes->state = MPEGTS_SKIP;
840     pes->pts = AV_NOPTS_VALUE;
841     pes->dts = AV_NOPTS_VALUE;
842     tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
843     if (!tss) {
844         av_free(pes);
845         return 0;
846     }
847     return pes;
848 }
849
850 static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size,
851                          int *es_id, uint8_t **dec_config_descr,
852                          int *dec_config_descr_size)
853 {
854     AVIOContext pb;
855     int tag;
856     unsigned len;
857
858     init_put_byte(&pb, buf, size, 0, NULL, NULL, NULL, NULL);
859
860     len = ff_mp4_read_descr(s, &pb, &tag);
861     if (tag == MP4IODescrTag) {
862         get_be16(&pb); // ID
863         get_byte(&pb);
864         get_byte(&pb);
865         get_byte(&pb);
866         get_byte(&pb);
867         get_byte(&pb);
868         len = ff_mp4_read_descr(s, &pb, &tag);
869         if (tag == MP4ESDescrTag) {
870             *es_id = get_be16(&pb); /* ES_ID */
871             av_dlog(s, "ES_ID %#x\n", *es_id);
872             get_byte(&pb); /* priority */
873             len = ff_mp4_read_descr(s, &pb, &tag);
874             if (tag == MP4DecConfigDescrTag) {
875                 *dec_config_descr = av_malloc(len);
876                 if (!*dec_config_descr)
877                     return AVERROR(ENOMEM);
878                 *dec_config_descr_size = len;
879                 get_buffer(&pb, *dec_config_descr, len);
880             }
881         }
882     }
883     return 0;
884 }
885
886 int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,
887                               const uint8_t **pp, const uint8_t *desc_list_end,
888                               int mp4_dec_config_descr_len, int mp4_es_id, int pid,
889                               uint8_t *mp4_dec_config_descr)
890 {
891     const uint8_t *desc_end;
892     int desc_len, desc_tag;
893     char language[4];
894
895     desc_tag = get8(pp, desc_list_end);
896     if (desc_tag < 0)
897         return -1;
898     desc_len = get8(pp, desc_list_end);
899     if (desc_len < 0)
900         return -1;
901     desc_end = *pp + desc_len;
902     if (desc_end > desc_list_end)
903         return -1;
904
905     av_dlog(fc, "tag: 0x%02x len=%d\n", desc_tag, desc_len);
906
907     if (st->codec->codec_id == CODEC_ID_NONE &&
908         stream_type == STREAM_TYPE_PRIVATE_DATA)
909         mpegts_find_stream_type(st, desc_tag, DESC_types);
910
911     switch(desc_tag) {
912     case 0x1F: /* FMC descriptor */
913         get16(pp, desc_end);
914         if (st->codec->codec_id == CODEC_ID_AAC_LATM &&
915             mp4_dec_config_descr_len && mp4_es_id == pid) {
916             AVIOContext pb;
917             init_put_byte(&pb, mp4_dec_config_descr,
918                           mp4_dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
919             ff_mp4_read_dec_config_descr(fc, st, &pb);
920             if (st->codec->codec_id == CODEC_ID_AAC &&
921                 st->codec->extradata_size > 0)
922                 st->need_parsing = 0;
923         }
924         break;
925     case 0x56: /* DVB teletext descriptor */
926         language[0] = get8(pp, desc_end);
927         language[1] = get8(pp, desc_end);
928         language[2] = get8(pp, desc_end);
929         language[3] = 0;
930         av_metadata_set2(&st->metadata, "language", language, 0);
931         break;
932     case 0x59: /* subtitling descriptor */
933         language[0] = get8(pp, desc_end);
934         language[1] = get8(pp, desc_end);
935         language[2] = get8(pp, desc_end);
936         language[3] = 0;
937         get8(pp, desc_end);
938         if (st->codec->extradata) {
939             if (st->codec->extradata_size == 4 && memcmp(st->codec->extradata, *pp, 4))
940                 av_log_ask_for_sample(fc, "DVB sub with multiple IDs\n");
941         } else {
942             st->codec->extradata = av_malloc(4 + FF_INPUT_BUFFER_PADDING_SIZE);
943             if (st->codec->extradata) {
944                 st->codec->extradata_size = 4;
945                 memcpy(st->codec->extradata, *pp, 4);
946             }
947         }
948         *pp += 4;
949         av_metadata_set2(&st->metadata, "language", language, 0);
950         break;
951     case 0x0a: /* ISO 639 language descriptor */
952         language[0] = get8(pp, desc_end);
953         language[1] = get8(pp, desc_end);
954         language[2] = get8(pp, desc_end);
955         language[3] = 0;
956         av_metadata_set2(&st->metadata, "language", language, 0);
957         switch (get8(pp, desc_end)) {
958             case 0x01: st->disposition |= AV_DISPOSITION_CLEAN_EFFECTS; break;
959             case 0x02: st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED; break;
960             case 0x03: st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED; break;
961         }
962         break;
963     case 0x05: /* registration descriptor */
964         st->codec->codec_tag = bytestream_get_le32(pp);
965         av_dlog(fc, "reg_desc=%.4s\n", (char*)&st->codec->codec_tag);
966         if (st->codec->codec_id == CODEC_ID_NONE &&
967             stream_type == STREAM_TYPE_PRIVATE_DATA)
968             mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
969         break;
970     default:
971         break;
972     }
973     *pp = desc_end;
974     return 0;
975 }
976
977 static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
978 {
979     MpegTSContext *ts = filter->u.section_filter.opaque;
980     SectionHeader h1, *h = &h1;
981     PESContext *pes;
982     AVStream *st;
983     const uint8_t *p, *p_end, *desc_list_end;
984     int program_info_length, pcr_pid, pid, stream_type;
985     int desc_list_len;
986     uint32_t prog_reg_desc = 0; /* registration descriptor */
987     uint8_t *mp4_dec_config_descr = NULL;
988     int mp4_dec_config_descr_len = 0;
989     int mp4_es_id = 0;
990
991 #ifdef DEBUG
992     av_dlog(ts->stream, "PMT: len %i\n", section_len);
993     av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
994 #endif
995
996     p_end = section + section_len - 4;
997     p = section;
998     if (parse_section_header(h, &p, p_end) < 0)
999         return;
1000
1001     av_dlog(ts->stream, "sid=0x%x sec_num=%d/%d\n",
1002            h->id, h->sec_num, h->last_sec_num);
1003
1004     if (h->tid != PMT_TID)
1005         return;
1006
1007     clear_program(ts, h->id);
1008     pcr_pid = get16(&p, p_end) & 0x1fff;
1009     if (pcr_pid < 0)
1010         return;
1011     add_pid_to_pmt(ts, h->id, pcr_pid);
1012
1013     av_dlog(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
1014
1015     program_info_length = get16(&p, p_end) & 0xfff;
1016     if (program_info_length < 0)
1017         return;
1018     while(program_info_length >= 2) {
1019         uint8_t tag, len;
1020         tag = get8(&p, p_end);
1021         len = get8(&p, p_end);
1022
1023         av_dlog(ts->stream, "program tag: 0x%02x len=%d\n", tag, len);
1024
1025         if(len > program_info_length - 2)
1026             //something else is broken, exit the program_descriptors_loop
1027             break;
1028         program_info_length -= len + 2;
1029         if (tag == 0x1d) { // IOD descriptor
1030             get8(&p, p_end); // scope
1031             get8(&p, p_end); // label
1032             len -= 2;
1033             mp4_read_iods(ts->stream, p, len, &mp4_es_id,
1034                           &mp4_dec_config_descr, &mp4_dec_config_descr_len);
1035         } else if (tag == 0x05 && len >= 4) { // registration descriptor
1036             prog_reg_desc = bytestream_get_le32(&p);
1037             len -= 4;
1038         }
1039         p += len;
1040     }
1041     p += program_info_length;
1042     if (p >= p_end)
1043         goto out;
1044
1045     // stop parsing after pmt, we found header
1046     if (!ts->stream->nb_streams)
1047         ts->stop_parse = 1;
1048
1049     for(;;) {
1050         st = 0;
1051         stream_type = get8(&p, p_end);
1052         if (stream_type < 0)
1053             break;
1054         pid = get16(&p, p_end) & 0x1fff;
1055         if (pid < 0)
1056             break;
1057
1058         /* now create ffmpeg stream */
1059         if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
1060             pes = ts->pids[pid]->u.pes_filter.opaque;
1061             if (!pes->st)
1062                 pes->st = av_new_stream(pes->stream, pes->pid);
1063             st = pes->st;
1064         } else {
1065             if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
1066             pes = add_pes_stream(ts, pid, pcr_pid);
1067             if (pes)
1068                 st = av_new_stream(pes->stream, pes->pid);
1069         }
1070
1071         if (!st)
1072             goto out;
1073
1074         if (!pes->stream_type)
1075             mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
1076
1077         add_pid_to_pmt(ts, h->id, pid);
1078
1079         ff_program_add_stream_index(ts->stream, h->id, st->index);
1080
1081         desc_list_len = get16(&p, p_end) & 0xfff;
1082         if (desc_list_len < 0)
1083             break;
1084         desc_list_end = p + desc_list_len;
1085         if (desc_list_end > p_end)
1086             break;
1087         for(;;) {
1088             if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p, desc_list_end,
1089                 mp4_dec_config_descr_len, mp4_es_id, pid, mp4_dec_config_descr) < 0)
1090                 break;
1091
1092             if (prog_reg_desc == AV_RL32("HDMV") && stream_type == 0x83 && pes->sub_st) {
1093                 ff_program_add_stream_index(ts->stream, h->id, pes->sub_st->index);
1094                 pes->sub_st->codec->codec_tag = st->codec->codec_tag;
1095             }
1096         }
1097         p = desc_list_end;
1098     }
1099
1100  out:
1101     av_free(mp4_dec_config_descr);
1102 }
1103
1104 static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1105 {
1106     MpegTSContext *ts = filter->u.section_filter.opaque;
1107     SectionHeader h1, *h = &h1;
1108     const uint8_t *p, *p_end;
1109     int sid, pmt_pid;
1110
1111 #ifdef DEBUG
1112     av_dlog(ts->stream, "PAT:\n");
1113     av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
1114 #endif
1115     p_end = section + section_len - 4;
1116     p = section;
1117     if (parse_section_header(h, &p, p_end) < 0)
1118         return;
1119     if (h->tid != PAT_TID)
1120         return;
1121
1122     clear_programs(ts);
1123     for(;;) {
1124         sid = get16(&p, p_end);
1125         if (sid < 0)
1126             break;
1127         pmt_pid = get16(&p, p_end) & 0x1fff;
1128         if (pmt_pid < 0)
1129             break;
1130
1131         av_dlog(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
1132
1133         if (sid == 0x0000) {
1134             /* NIT info */
1135         } else {
1136             av_new_program(ts->stream, sid);
1137             if (ts->pids[pmt_pid])
1138                 mpegts_close_filter(ts, ts->pids[pmt_pid]);
1139             mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
1140             add_pat_entry(ts, sid);
1141             add_pid_to_pmt(ts, sid, 0); //add pat pid to program
1142             add_pid_to_pmt(ts, sid, pmt_pid);
1143         }
1144     }
1145 }
1146
1147 static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1148 {
1149     MpegTSContext *ts = filter->u.section_filter.opaque;
1150     SectionHeader h1, *h = &h1;
1151     const uint8_t *p, *p_end, *desc_list_end, *desc_end;
1152     int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
1153     char *name, *provider_name;
1154
1155 #ifdef DEBUG
1156     av_dlog(ts->stream, "SDT:\n");
1157     av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
1158 #endif
1159
1160     p_end = section + section_len - 4;
1161     p = section;
1162     if (parse_section_header(h, &p, p_end) < 0)
1163         return;
1164     if (h->tid != SDT_TID)
1165         return;
1166     onid = get16(&p, p_end);
1167     if (onid < 0)
1168         return;
1169     val = get8(&p, p_end);
1170     if (val < 0)
1171         return;
1172     for(;;) {
1173         sid = get16(&p, p_end);
1174         if (sid < 0)
1175             break;
1176         val = get8(&p, p_end);
1177         if (val < 0)
1178             break;
1179         desc_list_len = get16(&p, p_end) & 0xfff;
1180         if (desc_list_len < 0)
1181             break;
1182         desc_list_end = p + desc_list_len;
1183         if (desc_list_end > p_end)
1184             break;
1185         for(;;) {
1186             desc_tag = get8(&p, desc_list_end);
1187             if (desc_tag < 0)
1188                 break;
1189             desc_len = get8(&p, desc_list_end);
1190             desc_end = p + desc_len;
1191             if (desc_end > desc_list_end)
1192                 break;
1193
1194             av_dlog(ts->stream, "tag: 0x%02x len=%d\n",
1195                    desc_tag, desc_len);
1196
1197             switch(desc_tag) {
1198             case 0x48:
1199                 service_type = get8(&p, p_end);
1200                 if (service_type < 0)
1201                     break;
1202                 provider_name = getstr8(&p, p_end);
1203                 if (!provider_name)
1204                     break;
1205                 name = getstr8(&p, p_end);
1206                 if (name) {
1207                     AVProgram *program = av_new_program(ts->stream, sid);
1208                     if(program) {
1209                         av_metadata_set2(&program->metadata, "service_name", name, 0);
1210                         av_metadata_set2(&program->metadata, "service_provider", provider_name, 0);
1211                     }
1212                 }
1213                 av_free(name);
1214                 av_free(provider_name);
1215                 break;
1216             default:
1217                 break;
1218             }
1219             p = desc_end;
1220         }
1221         p = desc_list_end;
1222     }
1223 }
1224
1225 /* handle one TS packet */
1226 static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
1227 {
1228     AVFormatContext *s = ts->stream;
1229     MpegTSFilter *tss;
1230     int len, pid, cc, cc_ok, afc, is_start;
1231     const uint8_t *p, *p_end;
1232     int64_t pos;
1233
1234     pid = AV_RB16(packet + 1) & 0x1fff;
1235     if(pid && discard_pid(ts, pid))
1236         return 0;
1237     is_start = packet[1] & 0x40;
1238     tss = ts->pids[pid];
1239     if (ts->auto_guess && tss == NULL && is_start) {
1240         add_pes_stream(ts, pid, -1);
1241         tss = ts->pids[pid];
1242     }
1243     if (!tss)
1244         return 0;
1245
1246     /* continuity check (currently not used) */
1247     cc = (packet[3] & 0xf);
1248     cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
1249     tss->last_cc = cc;
1250
1251     /* skip adaptation field */
1252     afc = (packet[3] >> 4) & 3;
1253     p = packet + 4;
1254     if (afc == 0) /* reserved value */
1255         return 0;
1256     if (afc == 2) /* adaptation field only */
1257         return 0;
1258     if (afc == 3) {
1259         /* skip adapation field */
1260         p += p[0] + 1;
1261     }
1262     /* if past the end of packet, ignore */
1263     p_end = packet + TS_PACKET_SIZE;
1264     if (p >= p_end)
1265         return 0;
1266
1267     pos = url_ftell(ts->stream->pb);
1268     ts->pos47= pos % ts->raw_packet_size;
1269
1270     if (tss->type == MPEGTS_SECTION) {
1271         if (is_start) {
1272             /* pointer field present */
1273             len = *p++;
1274             if (p + len > p_end)
1275                 return 0;
1276             if (len && cc_ok) {
1277                 /* write remaining section bytes */
1278                 write_section_data(s, tss,
1279                                    p, len, 0);
1280                 /* check whether filter has been closed */
1281                 if (!ts->pids[pid])
1282                     return 0;
1283             }
1284             p += len;
1285             if (p < p_end) {
1286                 write_section_data(s, tss,
1287                                    p, p_end - p, 1);
1288             }
1289         } else {
1290             if (cc_ok) {
1291                 write_section_data(s, tss,
1292                                    p, p_end - p, 0);
1293             }
1294         }
1295     } else {
1296         int ret;
1297         // Note: The position here points actually behind the current packet.
1298         if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
1299                                             pos - ts->raw_packet_size)) < 0)
1300             return ret;
1301     }
1302
1303     return 0;
1304 }
1305
1306 /* XXX: try to find a better synchro over several packets (use
1307    get_packet_size() ?) */
1308 static int mpegts_resync(AVFormatContext *s)
1309 {
1310     AVIOContext *pb = s->pb;
1311     int c, i;
1312
1313     for(i = 0;i < MAX_RESYNC_SIZE; i++) {
1314         c = url_fgetc(pb);
1315         if (c < 0)
1316             return -1;
1317         if (c == 0x47) {
1318             url_fseek(pb, -1, SEEK_CUR);
1319             return 0;
1320         }
1321     }
1322     av_log(s, AV_LOG_ERROR, "max resync size reached, could not find sync byte\n");
1323     /* no sync found */
1324     return -1;
1325 }
1326
1327 /* return -1 if error or EOF. Return 0 if OK. */
1328 static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size)
1329 {
1330     AVIOContext *pb = s->pb;
1331     int skip, len;
1332
1333     for(;;) {
1334         len = get_buffer(pb, buf, TS_PACKET_SIZE);
1335         if (len != TS_PACKET_SIZE)
1336             return AVERROR(EIO);
1337         /* check paquet sync byte */
1338         if (buf[0] != 0x47) {
1339             /* find a new packet start */
1340             url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1341             if (mpegts_resync(s) < 0)
1342                 return AVERROR(EAGAIN);
1343             else
1344                 continue;
1345         } else {
1346             skip = raw_packet_size - TS_PACKET_SIZE;
1347             if (skip > 0)
1348                 url_fskip(pb, skip);
1349             break;
1350         }
1351     }
1352     return 0;
1353 }
1354
1355 static int handle_packets(MpegTSContext *ts, int nb_packets)
1356 {
1357     AVFormatContext *s = ts->stream;
1358     uint8_t packet[TS_PACKET_SIZE];
1359     int packet_num, ret;
1360
1361     ts->stop_parse = 0;
1362     packet_num = 0;
1363     for(;;) {
1364         if (ts->stop_parse>0)
1365             break;
1366         packet_num++;
1367         if (nb_packets != 0 && packet_num >= nb_packets)
1368             break;
1369         ret = read_packet(s, packet, ts->raw_packet_size);
1370         if (ret != 0)
1371             return ret;
1372         ret = handle_packet(ts, packet);
1373         if (ret != 0)
1374             return ret;
1375     }
1376     return 0;
1377 }
1378
1379 static int mpegts_probe(AVProbeData *p)
1380 {
1381 #if 1
1382     const int size= p->buf_size;
1383     int score, fec_score, dvhs_score;
1384     int check_count= size / TS_FEC_PACKET_SIZE;
1385 #define CHECK_COUNT 10
1386
1387     if (check_count < CHECK_COUNT)
1388         return -1;
1389
1390     score     = analyze(p->buf, TS_PACKET_SIZE     *check_count, TS_PACKET_SIZE     , NULL)*CHECK_COUNT/check_count;
1391     dvhs_score= analyze(p->buf, TS_DVHS_PACKET_SIZE*check_count, TS_DVHS_PACKET_SIZE, NULL)*CHECK_COUNT/check_count;
1392     fec_score = analyze(p->buf, TS_FEC_PACKET_SIZE *check_count, TS_FEC_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
1393 //    av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
1394
1395 // we need a clear definition for the returned score otherwise things will become messy sooner or later
1396     if     (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score     - CHECK_COUNT;
1397     else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score  - CHECK_COUNT;
1398     else if(                 fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
1399     else                                    return -1;
1400 #else
1401     /* only use the extension for safer guess */
1402     if (av_match_ext(p->filename, "ts"))
1403         return AVPROBE_SCORE_MAX;
1404     else
1405         return 0;
1406 #endif
1407 }
1408
1409 /* return the 90kHz PCR and the extension for the 27MHz PCR. return
1410    (-1) if not available */
1411 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1412                      const uint8_t *packet)
1413 {
1414     int afc, len, flags;
1415     const uint8_t *p;
1416     unsigned int v;
1417
1418     afc = (packet[3] >> 4) & 3;
1419     if (afc <= 1)
1420         return -1;
1421     p = packet + 4;
1422     len = p[0];
1423     p++;
1424     if (len == 0)
1425         return -1;
1426     flags = *p++;
1427     len--;
1428     if (!(flags & 0x10))
1429         return -1;
1430     if (len < 6)
1431         return -1;
1432     v = AV_RB32(p);
1433     *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1434     *ppcr_low = ((p[4] & 1) << 8) | p[5];
1435     return 0;
1436 }
1437
1438 static int mpegts_read_header(AVFormatContext *s,
1439                               AVFormatParameters *ap)
1440 {
1441     MpegTSContext *ts = s->priv_data;
1442     AVIOContext *pb = s->pb;
1443     uint8_t buf[5*1024];
1444     int len;
1445     int64_t pos;
1446
1447     if (ap) {
1448         ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
1449         if(ap->mpeg2ts_raw){
1450             av_log(s, AV_LOG_ERROR, "use mpegtsraw_demuxer!\n");
1451             return -1;
1452         }
1453     }
1454
1455     /* read the first 1024 bytes to get packet size */
1456     pos = url_ftell(pb);
1457     len = get_buffer(pb, buf, sizeof(buf));
1458     if (len != sizeof(buf))
1459         goto fail;
1460     ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1461     if (ts->raw_packet_size <= 0)
1462         goto fail;
1463     ts->stream = s;
1464     ts->auto_guess = 0;
1465
1466     if (s->iformat == &ff_mpegts_demuxer) {
1467         /* normal demux */
1468
1469         /* first do a scaning to get all the services */
1470         if (url_fseek(pb, pos, SEEK_SET) < 0)
1471             av_log(s, AV_LOG_ERROR, "Unable to seek back to the start\n");
1472
1473         mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
1474
1475         mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
1476
1477         handle_packets(ts, s->probesize / ts->raw_packet_size);
1478         /* if could not find service, enable auto_guess */
1479
1480         ts->auto_guess = 1;
1481
1482         av_dlog(ts->stream, "tuning done\n");
1483
1484         s->ctx_flags |= AVFMTCTX_NOHEADER;
1485     } else {
1486         AVStream *st;
1487         int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1488         int64_t pcrs[2], pcr_h;
1489         int packet_count[2];
1490         uint8_t packet[TS_PACKET_SIZE];
1491
1492         /* only read packets */
1493
1494         st = av_new_stream(s, 0);
1495         if (!st)
1496             goto fail;
1497         av_set_pts_info(st, 60, 1, 27000000);
1498         st->codec->codec_type = AVMEDIA_TYPE_DATA;
1499         st->codec->codec_id = CODEC_ID_MPEG2TS;
1500
1501         /* we iterate until we find two PCRs to estimate the bitrate */
1502         pcr_pid = -1;
1503         nb_pcrs = 0;
1504         nb_packets = 0;
1505         for(;;) {
1506             ret = read_packet(s, packet, ts->raw_packet_size);
1507             if (ret < 0)
1508                 return -1;
1509             pid = AV_RB16(packet + 1) & 0x1fff;
1510             if ((pcr_pid == -1 || pcr_pid == pid) &&
1511                 parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
1512                 pcr_pid = pid;
1513                 packet_count[nb_pcrs] = nb_packets;
1514                 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
1515                 nb_pcrs++;
1516                 if (nb_pcrs >= 2)
1517                     break;
1518             }
1519             nb_packets++;
1520         }
1521
1522         /* NOTE1: the bitrate is computed without the FEC */
1523         /* NOTE2: it is only the bitrate of the start of the stream */
1524         ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
1525         ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
1526         s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
1527         st->codec->bit_rate = s->bit_rate;
1528         st->start_time = ts->cur_pcr;
1529 #if 0
1530         av_log(ts->stream, AV_LOG_DEBUG, "start=%0.3f pcr=%0.3f incr=%d\n",
1531                st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
1532 #endif
1533     }
1534
1535     url_fseek(pb, pos, SEEK_SET);
1536     return 0;
1537  fail:
1538     return -1;
1539 }
1540
1541 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1542
1543 static int mpegts_raw_read_packet(AVFormatContext *s,
1544                                   AVPacket *pkt)
1545 {
1546     MpegTSContext *ts = s->priv_data;
1547     int ret, i;
1548     int64_t pcr_h, next_pcr_h, pos;
1549     int pcr_l, next_pcr_l;
1550     uint8_t pcr_buf[12];
1551
1552     if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
1553         return AVERROR(ENOMEM);
1554     pkt->pos= url_ftell(s->pb);
1555     ret = read_packet(s, pkt->data, ts->raw_packet_size);
1556     if (ret < 0) {
1557         av_free_packet(pkt);
1558         return ret;
1559     }
1560     if (ts->mpeg2ts_compute_pcr) {
1561         /* compute exact PCR for each packet */
1562         if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
1563             /* we read the next PCR (XXX: optimize it by using a bigger buffer */
1564             pos = url_ftell(s->pb);
1565             for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
1566                 url_fseek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
1567                 get_buffer(s->pb, pcr_buf, 12);
1568                 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
1569                     /* XXX: not precise enough */
1570                     ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
1571                         (i + 1);
1572                     break;
1573                 }
1574             }
1575             url_fseek(s->pb, pos, SEEK_SET);
1576             /* no next PCR found: we use previous increment */
1577             ts->cur_pcr = pcr_h * 300 + pcr_l;
1578         }
1579         pkt->pts = ts->cur_pcr;
1580         pkt->duration = ts->pcr_incr;
1581         ts->cur_pcr += ts->pcr_incr;
1582     }
1583     pkt->stream_index = 0;
1584     return 0;
1585 }
1586
1587 static int mpegts_read_packet(AVFormatContext *s,
1588                               AVPacket *pkt)
1589 {
1590     MpegTSContext *ts = s->priv_data;
1591     int ret, i;
1592
1593     if (url_ftell(s->pb) != ts->last_pos) {
1594         /* seek detected, flush pes buffer */
1595         for (i = 0; i < NB_PID_MAX; i++) {
1596             if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
1597                 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
1598                 av_freep(&pes->buffer);
1599                 pes->data_index = 0;
1600                 pes->state = MPEGTS_SKIP; /* skip until pes header */
1601             }
1602         }
1603     }
1604
1605     ts->pkt = pkt;
1606     ret = handle_packets(ts, 0);
1607     if (ret < 0) {
1608         /* flush pes data left */
1609         for (i = 0; i < NB_PID_MAX; i++) {
1610             if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
1611                 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
1612                 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
1613                     new_pes_packet(pes, pkt);
1614                     pes->state = MPEGTS_SKIP;
1615                     ret = 0;
1616                     break;
1617                 }
1618             }
1619         }
1620     }
1621
1622     ts->last_pos = url_ftell(s->pb);
1623
1624     return ret;
1625 }
1626
1627 static int mpegts_read_close(AVFormatContext *s)
1628 {
1629     MpegTSContext *ts = s->priv_data;
1630     int i;
1631
1632     clear_programs(ts);
1633
1634     for(i=0;i<NB_PID_MAX;i++)
1635         if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
1636
1637     return 0;
1638 }
1639
1640 static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
1641                               int64_t *ppos, int64_t pos_limit)
1642 {
1643     MpegTSContext *ts = s->priv_data;
1644     int64_t pos, timestamp;
1645     uint8_t buf[TS_PACKET_SIZE];
1646     int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
1647     const int find_next= 1;
1648     pos = ((*ppos  + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
1649     if (find_next) {
1650         for(;;) {
1651             url_fseek(s->pb, pos, SEEK_SET);
1652             if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1653                 return AV_NOPTS_VALUE;
1654             if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1655                 parse_pcr(&timestamp, &pcr_l, buf) == 0) {
1656                 break;
1657             }
1658             pos += ts->raw_packet_size;
1659         }
1660     } else {
1661         for(;;) {
1662             pos -= ts->raw_packet_size;
1663             if (pos < 0)
1664                 return AV_NOPTS_VALUE;
1665             url_fseek(s->pb, pos, SEEK_SET);
1666             if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1667                 return AV_NOPTS_VALUE;
1668             if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1669                 parse_pcr(&timestamp, &pcr_l, buf) == 0) {
1670                 break;
1671             }
1672         }
1673     }
1674     *ppos = pos;
1675
1676     return timestamp;
1677 }
1678
1679 #ifdef USE_SYNCPOINT_SEARCH
1680
1681 static int read_seek2(AVFormatContext *s,
1682                       int stream_index,
1683                       int64_t min_ts,
1684                       int64_t target_ts,
1685                       int64_t max_ts,
1686                       int flags)
1687 {
1688     int64_t pos;
1689
1690     int64_t ts_ret, ts_adj;
1691     int stream_index_gen_search;
1692     AVStream *st;
1693     AVParserState *backup;
1694
1695     backup = ff_store_parser_state(s);
1696
1697     // detect direction of seeking for search purposes
1698     flags |= (target_ts - min_ts > (uint64_t)(max_ts - target_ts)) ?
1699              AVSEEK_FLAG_BACKWARD : 0;
1700
1701     if (flags & AVSEEK_FLAG_BYTE) {
1702         // use position directly, we will search starting from it
1703         pos = target_ts;
1704     } else {
1705         // search for some position with good timestamp match
1706         if (stream_index < 0) {
1707             stream_index_gen_search = av_find_default_stream_index(s);
1708             if (stream_index_gen_search < 0) {
1709                 ff_restore_parser_state(s, backup);
1710                 return -1;
1711             }
1712
1713             st = s->streams[stream_index_gen_search];
1714             // timestamp for default must be expressed in AV_TIME_BASE units
1715             ts_adj = av_rescale(target_ts,
1716                                 st->time_base.den,
1717                                 AV_TIME_BASE * (int64_t)st->time_base.num);
1718         } else {
1719             ts_adj = target_ts;
1720             stream_index_gen_search = stream_index;
1721         }
1722         pos = av_gen_search(s, stream_index_gen_search, ts_adj,
1723                             0, INT64_MAX, -1,
1724                             AV_NOPTS_VALUE,
1725                             AV_NOPTS_VALUE,
1726                             flags, &ts_ret, mpegts_get_pcr);
1727         if (pos < 0) {
1728             ff_restore_parser_state(s, backup);
1729             return -1;
1730         }
1731     }
1732
1733     // search for actual matching keyframe/starting position for all streams
1734     if (ff_gen_syncpoint_search(s, stream_index, pos,
1735                                 min_ts, target_ts, max_ts,
1736                                 flags) < 0) {
1737         ff_restore_parser_state(s, backup);
1738         return -1;
1739     }
1740
1741     ff_free_parser_state(s, backup);
1742     return 0;
1743 }
1744
1745 static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags)
1746 {
1747     int ret;
1748     if (flags & AVSEEK_FLAG_BACKWARD) {
1749         flags &= ~AVSEEK_FLAG_BACKWARD;
1750         ret = read_seek2(s, stream_index, INT64_MIN, target_ts, target_ts, flags);
1751         if (ret < 0)
1752             // for compatibility reasons, seek to the best-fitting timestamp
1753             ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags);
1754     } else {
1755         ret = read_seek2(s, stream_index, target_ts, target_ts, INT64_MAX, flags);
1756         if (ret < 0)
1757             // for compatibility reasons, seek to the best-fitting timestamp
1758             ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags);
1759     }
1760     return ret;
1761 }
1762
1763 #else
1764
1765 static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1766     MpegTSContext *ts = s->priv_data;
1767     uint8_t buf[TS_PACKET_SIZE];
1768     int64_t pos;
1769
1770     if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
1771         return -1;
1772
1773     pos= url_ftell(s->pb);
1774
1775     for(;;) {
1776         url_fseek(s->pb, pos, SEEK_SET);
1777         if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1778             return -1;
1779 //        pid = AV_RB16(buf + 1) & 0x1fff;
1780         if(buf[1] & 0x40) break;
1781         pos += ts->raw_packet_size;
1782     }
1783     url_fseek(s->pb, pos, SEEK_SET);
1784
1785     return 0;
1786 }
1787
1788 #endif
1789
1790 /**************************************************************/
1791 /* parsing functions - called from other demuxers such as RTP */
1792
1793 MpegTSContext *ff_mpegts_parse_open(AVFormatContext *s)
1794 {
1795     MpegTSContext *ts;
1796
1797     ts = av_mallocz(sizeof(MpegTSContext));
1798     if (!ts)
1799         return NULL;
1800     /* no stream case, currently used by RTP */
1801     ts->raw_packet_size = TS_PACKET_SIZE;
1802     ts->stream = s;
1803     ts->auto_guess = 1;
1804     return ts;
1805 }
1806
1807 /* return the consumed length if a packet was output, or -1 if no
1808    packet is output */
1809 int ff_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
1810                         const uint8_t *buf, int len)
1811 {
1812     int len1;
1813
1814     len1 = len;
1815     ts->pkt = pkt;
1816     ts->stop_parse = 0;
1817     for(;;) {
1818         if (ts->stop_parse>0)
1819             break;
1820         if (len < TS_PACKET_SIZE)
1821             return -1;
1822         if (buf[0] != 0x47) {
1823             buf++;
1824             len--;
1825         } else {
1826             handle_packet(ts, buf);
1827             buf += TS_PACKET_SIZE;
1828             len -= TS_PACKET_SIZE;
1829         }
1830     }
1831     return len1 - len;
1832 }
1833
1834 void ff_mpegts_parse_close(MpegTSContext *ts)
1835 {
1836     int i;
1837
1838     for(i=0;i<NB_PID_MAX;i++)
1839         av_free(ts->pids[i]);
1840     av_free(ts);
1841 }
1842
1843 AVInputFormat ff_mpegts_demuxer = {
1844     "mpegts",
1845     NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
1846     sizeof(MpegTSContext),
1847     mpegts_probe,
1848     mpegts_read_header,
1849     mpegts_read_packet,
1850     mpegts_read_close,
1851     read_seek,
1852     mpegts_get_pcr,
1853     .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
1854 #ifdef USE_SYNCPOINT_SEARCH
1855     .read_seek2 = read_seek2,
1856 #endif
1857 };
1858
1859 AVInputFormat ff_mpegtsraw_demuxer = {
1860     "mpegtsraw",
1861     NULL_IF_CONFIG_SMALL("MPEG-2 raw transport stream format"),
1862     sizeof(MpegTSContext),
1863     NULL,
1864     mpegts_read_header,
1865     mpegts_raw_read_packet,
1866     mpegts_read_close,
1867     read_seek,
1868     mpegts_get_pcr,
1869     .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
1870 #ifdef USE_SYNCPOINT_SEARCH
1871     .read_seek2 = read_seek2,
1872 #endif
1873 };