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