mpegts: do not set pts for missing dts in video streams
[vuplus_xbmc] / lib / 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 #include "libavutil/crc.h"
23 #include "libavutil/intreadwrite.h"
24 #include "libavutil/log.h"
25 #include "libavutil/dict.h"
26 #include "libavutil/mathematics.h"
27 #include "libavutil/opt.h"
28 #include "libavutil/avassert.h"
29 #include "libavcodec/bytestream.h"
30 #include "libavcodec/get_bits.h"
31 #include "libavcodec/mathops.h"
32 #include "avformat.h"
33 #include "mpegts.h"
34 #include "internal.h"
35 #include "avio_internal.h"
36 #include "seek.h"
37 #include "mpeg.h"
38 #include "isom.h"
39
40 /* maximum size in which we look for synchronisation if
41    synchronisation is lost */
42 #define MAX_RESYNC_SIZE 65536
43
44 #define MAX_PES_PAYLOAD 200*1024
45
46 #define MAX_MP4_DESCR_COUNT 16
47
48 enum MpegTSFilterType {
49     MPEGTS_PES,
50     MPEGTS_SECTION,
51 };
52
53 typedef struct MpegTSFilter MpegTSFilter;
54
55 typedef int PESCallback(MpegTSFilter *f, const uint8_t *buf, int len, int is_start, int64_t pos);
56
57 typedef struct MpegTSPESFilter {
58     PESCallback *pes_cb;
59     void *opaque;
60 } MpegTSPESFilter;
61
62 typedef void SectionCallback(MpegTSFilter *f, const uint8_t *buf, int len);
63
64 typedef void SetServiceCallback(void *opaque, int ret);
65
66 typedef struct MpegTSSectionFilter {
67     int section_index;
68     int section_h_size;
69     uint8_t *section_buf;
70     unsigned int check_crc:1;
71     unsigned int end_of_section_reached:1;
72     SectionCallback *section_cb;
73     void *opaque;
74 } MpegTSSectionFilter;
75
76 struct MpegTSFilter {
77     int pid;
78     int es_id;
79     int last_cc; /* last cc code (-1 if first packet) */
80     int last_version; /* last version of data on this pid */
81     enum MpegTSFilterType type;
82     union {
83         MpegTSPESFilter pes_filter;
84         MpegTSSectionFilter section_filter;
85     } u;
86 };
87
88 #define MAX_PIDS_PER_PROGRAM 64
89 struct Program {
90     unsigned int id; //program id/service id
91     unsigned int nb_pids;
92     unsigned int pids[MAX_PIDS_PER_PROGRAM];
93 };
94
95 struct MpegTSContext {
96     const AVClass *class;
97     /* user data */
98     AVFormatContext *stream;
99     /** raw packet size, including FEC if present            */
100     int raw_packet_size;
101
102     int pos47;
103     /** position corresponding to pos47, or 0 if pos47 invalid */
104     int64_t pos;
105
106     /** if true, all pids are analyzed to find streams       */
107     int auto_guess;
108
109     /** compute exact PCR for each transport stream packet   */
110     int mpeg2ts_compute_pcr;
111
112     int64_t cur_pcr;    /**< used to estimate the exact PCR  */
113     int pcr_incr;       /**< used to estimate the exact PCR  */
114
115     /* data needed to handle file based ts */
116     /** stop parsing loop                                    */
117     int stop_parse;
118     /** packet containing Audio/Video data                   */
119     AVPacket *pkt;
120     /** to detect seek                                       */
121     int64_t last_pos;
122
123     /******************************************/
124     /* private mpegts data */
125     /* scan context */
126     /** structure to keep track of Program->pids mapping     */
127     unsigned int nb_prg;
128     struct Program *prg;
129
130     int8_t crc_validity[NB_PID_MAX];
131
132     /** filters for various streams specified by PMT + for the PAT and PMT */
133     MpegTSFilter *pids[NB_PID_MAX];
134     int current_pid;
135 };
136
137 static const AVOption options[] = {
138     {"compute_pcr", "Compute exact PCR for each transport stream packet.", offsetof(MpegTSContext, mpeg2ts_compute_pcr), AV_OPT_TYPE_INT,
139      {.i64 = 0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
140     { NULL },
141 };
142
143 static const AVClass mpegtsraw_class = {
144     .class_name = "mpegtsraw demuxer",
145     .item_name  = av_default_item_name,
146     .option     = options,
147     .version    = LIBAVUTIL_VERSION_INT,
148 };
149
150 /* TS stream handling */
151
152 enum MpegTSState {
153     MPEGTS_HEADER = 0,
154     MPEGTS_PESHEADER,
155     MPEGTS_PESHEADER_FILL,
156     MPEGTS_PAYLOAD,
157     MPEGTS_SKIP,
158 };
159
160 /* enough for PES header + length */
161 #define PES_START_SIZE  6
162 #define PES_HEADER_SIZE 9
163 #define MAX_PES_HEADER_SIZE (9 + 255)
164
165 typedef struct PESContext {
166     int pid;
167     int pcr_pid; /**< if -1 then all packets containing PCR are considered */
168     int stream_type;
169     MpegTSContext *ts;
170     AVFormatContext *stream;
171     AVStream *st;
172     AVStream *sub_st; /**< stream for the embedded AC3 stream in HDMV TrueHD */
173     enum MpegTSState state;
174     /* used to get the format */
175     int data_index;
176     int flags; /**< copied to the AVPacket flags */
177     int total_size;
178     int pes_header_size;
179     int extended_stream_id;
180     int64_t pts, dts;
181     int64_t ts_packet_pos; /**< position of first TS packet of this PES packet */
182     uint8_t header[MAX_PES_HEADER_SIZE];
183     uint8_t *buffer;
184     SLConfigDescr sl;
185 } PESContext;
186
187 extern AVInputFormat ff_mpegts_demuxer;
188
189 static void clear_avprogram(MpegTSContext *ts, unsigned int programid)
190 {
191     AVProgram *prg = NULL;
192     int i;
193     for(i=0; i<ts->stream->nb_programs; i++)
194         if(ts->stream->programs[i]->id == programid){
195             prg = ts->stream->programs[i];
196             break;
197         }
198     if (!prg)
199         return;
200     prg->nb_stream_indexes = 0;
201 }
202
203 static void clear_program(MpegTSContext *ts, unsigned int programid)
204 {
205     int i;
206
207     clear_avprogram(ts, programid);
208     for(i=0; i<ts->nb_prg; i++)
209         if(ts->prg[i].id == programid)
210             ts->prg[i].nb_pids = 0;
211 }
212
213 static void clear_programs(MpegTSContext *ts)
214 {
215     av_freep(&ts->prg);
216     ts->nb_prg=0;
217 }
218
219 static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
220 {
221     struct Program *p;
222     void *tmp = av_realloc(ts->prg, (ts->nb_prg+1)*sizeof(struct Program));
223     if(!tmp)
224         return;
225     ts->prg = tmp;
226     p = &ts->prg[ts->nb_prg];
227     p->id = programid;
228     p->nb_pids = 0;
229     ts->nb_prg++;
230 }
231
232 static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid, unsigned int pid)
233 {
234     int i;
235     struct Program *p = NULL;
236     for(i=0; i<ts->nb_prg; i++) {
237         if(ts->prg[i].id == programid) {
238             p = &ts->prg[i];
239             break;
240         }
241     }
242     if(!p)
243         return;
244
245     if(p->nb_pids >= MAX_PIDS_PER_PROGRAM)
246         return;
247     p->pids[p->nb_pids++] = pid;
248 }
249
250 static void set_pcr_pid(AVFormatContext *s, unsigned int programid, unsigned int pid)
251 {
252     int i;
253     for(i=0; i<s->nb_programs; i++) {
254         if(s->programs[i]->id == programid) {
255             s->programs[i]->pcr_pid = pid;
256             break;
257         }
258     }
259 }
260
261 /**
262  * @brief discard_pid() decides if the pid is to be discarded according
263  *                      to caller's programs selection
264  * @param ts    : - TS context
265  * @param pid   : - pid
266  * @return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
267  *         0 otherwise
268  */
269 static int discard_pid(MpegTSContext *ts, unsigned int pid)
270 {
271     int i, j, k;
272     int used = 0, discarded = 0;
273     struct Program *p;
274
275     /* If none of the programs have .discard=AVDISCARD_ALL then there's
276      * no way we have to discard this packet
277      */
278     for (k = 0; k < ts->stream->nb_programs; k++) {
279         if (ts->stream->programs[k]->discard == AVDISCARD_ALL)
280             break;
281     }
282     if (k == ts->stream->nb_programs)
283         return 0;
284
285     for(i=0; i<ts->nb_prg; i++) {
286         p = &ts->prg[i];
287         for(j=0; j<p->nb_pids; j++) {
288             if(p->pids[j] != pid)
289                 continue;
290             //is program with id p->id set to be discarded?
291             for(k=0; k<ts->stream->nb_programs; k++) {
292                 if(ts->stream->programs[k]->id == p->id) {
293                     if(ts->stream->programs[k]->discard == AVDISCARD_ALL)
294                         discarded++;
295                     else
296                         used++;
297                 }
298             }
299         }
300     }
301
302     return !used && discarded;
303 }
304
305 /**
306  *  Assemble PES packets out of TS packets, and then call the "section_cb"
307  *  function when they are complete.
308  */
309 static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
310                                const uint8_t *buf, int buf_size, int is_start)
311 {
312     MpegTSContext *ts = s->priv_data;
313     MpegTSSectionFilter *tss = &tss1->u.section_filter;
314     int len;
315
316     if (is_start) {
317         memcpy(tss->section_buf, buf, buf_size);
318         tss->section_index = buf_size;
319         tss->section_h_size = -1;
320         tss->end_of_section_reached = 0;
321     } else {
322         if (tss->end_of_section_reached)
323             return;
324         len = 4096 - tss->section_index;
325         if (buf_size < len)
326             len = buf_size;
327         memcpy(tss->section_buf + tss->section_index, buf, len);
328         tss->section_index += len;
329     }
330
331     /* compute section length if possible */
332     if (tss->section_h_size == -1 && tss->section_index >= 3) {
333         len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
334         if (len > 4096)
335             return;
336         tss->section_h_size = len;
337     }
338
339     if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
340         int crc_valid = 1;
341         tss->end_of_section_reached = 1;
342
343         if (tss->check_crc){
344             crc_valid = !av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1, tss->section_buf, tss->section_h_size);
345             if (crc_valid){
346                 ts->crc_validity[ tss1->pid ] = 100;
347             }else if(ts->crc_validity[ tss1->pid ] > -10){
348                 ts->crc_validity[ tss1->pid ]--;
349             }else
350                 crc_valid = 2;
351         }
352         if (crc_valid)
353             tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
354     }
355 }
356
357 static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
358                                          SectionCallback *section_cb, void *opaque,
359                                          int check_crc)
360
361 {
362     MpegTSFilter *filter;
363     MpegTSSectionFilter *sec;
364
365     av_dlog(ts->stream, "Filter: pid=0x%x\n", pid);
366
367     if (pid >= NB_PID_MAX || ts->pids[pid])
368         return NULL;
369     filter = av_mallocz(sizeof(MpegTSFilter));
370     if (!filter)
371         return NULL;
372     ts->pids[pid] = filter;
373     filter->type = MPEGTS_SECTION;
374     filter->pid = pid;
375     filter->es_id = -1;
376     filter->last_cc = -1;
377     filter->last_version = -1;
378     sec = &filter->u.section_filter;
379     sec->section_cb = section_cb;
380     sec->opaque = opaque;
381     sec->section_buf = av_malloc(MAX_SECTION_SIZE);
382     sec->check_crc = check_crc;
383     if (!sec->section_buf) {
384         av_free(filter);
385         return NULL;
386     }
387     return filter;
388 }
389
390 static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
391                                      PESCallback *pes_cb,
392                                      void *opaque)
393 {
394     MpegTSFilter *filter;
395     MpegTSPESFilter *pes;
396
397     if (pid >= NB_PID_MAX || ts->pids[pid])
398         return NULL;
399     filter = av_mallocz(sizeof(MpegTSFilter));
400     if (!filter)
401         return NULL;
402     ts->pids[pid] = filter;
403     filter->type = MPEGTS_PES;
404     filter->pid = pid;
405     filter->es_id = -1;
406     filter->last_cc = -1;
407     pes = &filter->u.pes_filter;
408     pes->pes_cb = pes_cb;
409     pes->opaque = opaque;
410     return filter;
411 }
412
413 static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
414 {
415     int pid;
416
417     pid = filter->pid;
418     if (filter->type == MPEGTS_SECTION)
419         av_freep(&filter->u.section_filter.section_buf);
420     else if (filter->type == MPEGTS_PES) {
421         PESContext *pes = filter->u.pes_filter.opaque;
422         av_freep(&pes->buffer);
423         /* referenced private data will be freed later in
424          * avformat_close_input */
425         if (!((PESContext *)filter->u.pes_filter.opaque)->st) {
426             av_freep(&filter->u.pes_filter.opaque);
427         }
428     }
429
430     av_free(filter);
431     ts->pids[pid] = NULL;
432 }
433
434 static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
435     int stat[TS_MAX_PACKET_SIZE];
436     int i;
437     int x=0;
438     int best_score=0;
439
440     memset(stat, 0, packet_size*sizeof(int));
441
442     for(x=i=0; i<size-3; i++){
443         if(buf[i] == 0x47 && !(buf[i+1] & 0x80) && buf[i+3] != 0x47){
444             stat[x]++;
445             if(stat[x] > best_score){
446                 best_score= stat[x];
447                 if(index) *index= x;
448             }
449         }
450
451         x++;
452         if(x == packet_size) x= 0;
453     }
454
455     return best_score;
456 }
457
458 /* autodetect fec presence. Must have at least 1024 bytes  */
459 static int get_packet_size(const uint8_t *buf, int size)
460 {
461     int score, fec_score, dvhs_score;
462
463     if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
464         return -1;
465
466     score    = analyze(buf, size, TS_PACKET_SIZE, NULL);
467     dvhs_score    = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
468     fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
469     av_dlog(NULL, "score: %d, dvhs_score: %d, fec_score: %d \n",
470             score, dvhs_score, fec_score);
471
472     if     (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
473     else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
474     else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
475     else                       return -1;
476 }
477
478 typedef struct SectionHeader {
479     uint8_t tid;
480     uint16_t id;
481     uint8_t version;
482     uint8_t current;
483     uint8_t sec_num;
484     uint8_t last_sec_num;
485 } SectionHeader;
486
487 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
488 {
489     const uint8_t *p;
490     int c;
491
492     p = *pp;
493     if (p >= p_end)
494         return -1;
495     c = *p++;
496     *pp = p;
497     return c;
498 }
499
500 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
501 {
502     const uint8_t *p;
503     int c;
504
505     p = *pp;
506     if ((p + 1) >= p_end)
507         return -1;
508     c = AV_RB16(p);
509     p += 2;
510     *pp = p;
511     return c;
512 }
513
514 /* read and allocate a DVB string preceded by its length */
515 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
516 {
517     int len;
518     const uint8_t *p;
519     char *str;
520
521     p = *pp;
522     len = get8(&p, p_end);
523     if (len < 0)
524         return NULL;
525     if ((p + len) > p_end)
526         return NULL;
527     str = av_malloc(len + 1);
528     if (!str)
529         return NULL;
530     memcpy(str, p, len);
531     str[len] = '\0';
532     p += len;
533     *pp = p;
534     return str;
535 }
536
537 static int parse_section_header(SectionHeader *h,
538                                 const uint8_t **pp, const uint8_t *p_end)
539 {
540     int val;
541
542     val = get8(pp, p_end);
543     if (val < 0)
544         return -1;
545     h->tid = val;
546     *pp += 2;
547     val = get16(pp, p_end);
548     if (val < 0)
549         return -1;
550     h->id = val;
551     val = get8(pp, p_end);
552     if (val < 0)
553         return -1;
554     h->current = val & 0x1;
555     h->version = (val >> 1) & 0x1f;
556     val = get8(pp, p_end);
557     if (val < 0)
558         return -1;
559     h->sec_num = val;
560     val = get8(pp, p_end);
561     if (val < 0)
562         return -1;
563     h->last_sec_num = val;
564     return 0;
565 }
566
567 typedef struct {
568     uint32_t stream_type;
569     enum AVMediaType codec_type;
570     enum AVCodecID codec_id;
571 } StreamType;
572
573 static const StreamType ISO_types[] = {
574     { 0x01, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
575     { 0x02, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
576     { 0x03, AVMEDIA_TYPE_AUDIO,        AV_CODEC_ID_MP3 },
577     { 0x04, AVMEDIA_TYPE_AUDIO,        AV_CODEC_ID_MP3 },
578     { 0x0f, AVMEDIA_TYPE_AUDIO,        AV_CODEC_ID_AAC },
579     { 0x10, AVMEDIA_TYPE_VIDEO,      AV_CODEC_ID_MPEG4 },
580     /* Makito encoder sets stream type 0x11 for AAC,
581      * so auto-detect LOAS/LATM instead of hardcoding it. */
582 #if !CONFIG_LOAS_DEMUXER
583     { 0x11, AVMEDIA_TYPE_AUDIO,   AV_CODEC_ID_AAC_LATM }, /* LATM syntax */
584 #endif
585     { 0x1b, AVMEDIA_TYPE_VIDEO,       AV_CODEC_ID_H264 },
586     { 0xd1, AVMEDIA_TYPE_VIDEO,      AV_CODEC_ID_DIRAC },
587     { 0xea, AVMEDIA_TYPE_VIDEO,        AV_CODEC_ID_VC1 },
588     { 0 },
589 };
590
591 static const StreamType HDMV_types[] = {
592     { 0x80, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_PCM_BLURAY },
593     { 0x81, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
594     { 0x82, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
595     { 0x83, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_TRUEHD },
596     { 0x84, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 },
597     { 0x85, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD */
598     { 0x86, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD MASTER*/
599     { 0xa1, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 }, /* E-AC3 Secondary Audio */
600     { 0xa2, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },  /* DTS Express Secondary Audio */
601     { 0x90, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_HDMV_PGS_SUBTITLE },
602     { 0 },
603 };
604
605 /* ATSC ? */
606 static const StreamType MISC_types[] = {
607     { 0x81, AVMEDIA_TYPE_AUDIO,   AV_CODEC_ID_AC3 },
608     { 0x8a, AVMEDIA_TYPE_AUDIO,   AV_CODEC_ID_DTS },
609     { 0 },
610 };
611
612 static const StreamType REGD_types[] = {
613     { MKTAG('d','r','a','c'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC },
614     { MKTAG('A','C','-','3'), AVMEDIA_TYPE_AUDIO,   AV_CODEC_ID_AC3 },
615     { MKTAG('B','S','S','D'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_S302M },
616     { MKTAG('D','T','S','1'), AVMEDIA_TYPE_AUDIO,   AV_CODEC_ID_DTS },
617     { MKTAG('D','T','S','2'), AVMEDIA_TYPE_AUDIO,   AV_CODEC_ID_DTS },
618     { MKTAG('D','T','S','3'), AVMEDIA_TYPE_AUDIO,   AV_CODEC_ID_DTS },
619     { MKTAG('K','L','V','A'), AVMEDIA_TYPE_DATA,    AV_CODEC_ID_SMPTE_KLV },
620     { MKTAG('V','C','-','1'), AVMEDIA_TYPE_VIDEO,   AV_CODEC_ID_VC1 },
621     { 0 },
622 };
623
624 /* descriptor present */
625 static const StreamType DESC_types[] = {
626     { 0x6a, AVMEDIA_TYPE_AUDIO,             AV_CODEC_ID_AC3 }, /* AC-3 descriptor */
627     { 0x7a, AVMEDIA_TYPE_AUDIO,            AV_CODEC_ID_EAC3 }, /* E-AC-3 descriptor */
628     { 0x7b, AVMEDIA_TYPE_AUDIO,             AV_CODEC_ID_DTS },
629     { 0x56, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_TELETEXT },
630     { 0x59, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
631     { 0x45, AVMEDIA_TYPE_DATA,         AV_CODEC_ID_VBI_DATA }, /* VBI Data descriptor */
632     { 0x46, AVMEDIA_TYPE_DATA,     AV_CODEC_ID_VBI_TELETEXT }, /* VBI Teletext descriptor */
633     { 0 },
634 };
635
636 static void mpegts_find_stream_type(AVStream *st,
637                                     uint32_t stream_type, const StreamType *types)
638 {
639     if (avcodec_is_open(st->codec)) {
640         av_log(NULL, AV_LOG_DEBUG, "cannot set stream info, codec is open\n");
641         return;
642     }
643
644     for (; types->stream_type; types++) {
645         if (stream_type == types->stream_type) {
646             st->codec->codec_type = types->codec_type;
647             st->codec->codec_id   = types->codec_id;
648             st->request_probe     = 0;
649             return;
650         }
651     }
652 }
653
654 static int mpegts_set_stream_info(AVStream *st, PESContext *pes,
655                                   uint32_t stream_type, uint32_t prog_reg_desc)
656 {
657     int old_codec_type= st->codec->codec_type;
658     int old_codec_id  = st->codec->codec_id;
659
660     if (avcodec_is_open(st->codec)) {
661         av_log(pes->stream, AV_LOG_DEBUG, "cannot set stream info, codec is open\n");
662         return 0;
663     }
664
665     avpriv_set_pts_info(st, 33, 1, 90000);
666     st->priv_data = pes;
667     st->codec->codec_type = AVMEDIA_TYPE_DATA;
668     st->codec->codec_id   = AV_CODEC_ID_NONE;
669     st->need_parsing = AVSTREAM_PARSE_FULL;
670     pes->st = st;
671     pes->stream_type = stream_type;
672
673     av_log(pes->stream, AV_LOG_DEBUG,
674            "stream=%d stream_type=%x pid=%x prog_reg_desc=%.4s\n",
675            st->index, pes->stream_type, pes->pid, (char*)&prog_reg_desc);
676
677     st->codec->codec_tag = pes->stream_type;
678
679     mpegts_find_stream_type(st, pes->stream_type, ISO_types);
680     if ((prog_reg_desc == AV_RL32("HDMV") ||
681          prog_reg_desc == AV_RL32("HDPR")) &&
682         st->codec->codec_id == AV_CODEC_ID_NONE) {
683         mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
684         if (pes->stream_type == 0x83) {
685             // HDMV TrueHD streams also contain an AC3 coded version of the
686             // audio track - add a second stream for this
687             AVStream *sub_st;
688             // priv_data cannot be shared between streams
689             PESContext *sub_pes = av_malloc(sizeof(*sub_pes));
690             if (!sub_pes)
691                 return AVERROR(ENOMEM);
692             memcpy(sub_pes, pes, sizeof(*sub_pes));
693
694             sub_st = avformat_new_stream(pes->stream, NULL);
695             if (!sub_st) {
696                 av_free(sub_pes);
697                 return AVERROR(ENOMEM);
698             }
699
700             sub_st->id = pes->pid;
701             avpriv_set_pts_info(sub_st, 33, 1, 90000);
702             sub_st->priv_data = sub_pes;
703             sub_st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
704             sub_st->codec->codec_id   = AV_CODEC_ID_AC3;
705             sub_st->need_parsing = AVSTREAM_PARSE_FULL;
706             sub_pes->sub_st = pes->sub_st = sub_st;
707         }
708     }
709     if (st->codec->codec_id == AV_CODEC_ID_NONE)
710         mpegts_find_stream_type(st, pes->stream_type, MISC_types);
711     if (st->codec->codec_id == AV_CODEC_ID_NONE){
712         st->codec->codec_id  = old_codec_id;
713         st->codec->codec_type= old_codec_type;
714     }
715
716     return 0;
717 }
718
719 static void new_pes_packet(PESContext *pes, AVPacket *pkt)
720 {
721     if(pkt->data) {
722       av_log(pes->stream, AV_LOG_ERROR, "ignoring previously allocated packet on stream %d\n", pkt->stream_index);
723       av_free_packet(pkt);
724     }
725     av_init_packet(pkt);
726
727     pkt->destruct = av_destruct_packet;
728     pkt->data = pes->buffer;
729     pkt->size = pes->data_index;
730
731     if(pes->total_size != MAX_PES_PAYLOAD &&
732        pes->pes_header_size + pes->data_index != pes->total_size + PES_START_SIZE) {
733         av_log(pes->stream, AV_LOG_WARNING, "PES packet size mismatch\n");
734         pes->flags |= AV_PKT_FLAG_CORRUPT;
735     }
736     memset(pkt->data+pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
737
738     // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID
739     if (pes->sub_st && pes->stream_type == 0x83 && pes->extended_stream_id == 0x76)
740         pkt->stream_index = pes->sub_st->index;
741     else
742         pkt->stream_index = pes->st->index;
743     pkt->pts = pes->pts;
744     pkt->dts = pes->dts;
745     /* store position of first TS packet of this PES packet */
746     pkt->pos = pes->ts_packet_pos;
747     pkt->flags = pes->flags;
748
749     /* reset pts values */
750     pes->pts = AV_NOPTS_VALUE;
751     pes->dts = AV_NOPTS_VALUE;
752     pes->buffer = NULL;
753     pes->data_index = 0;
754     pes->flags = 0;
755 }
756
757 static uint64_t get_ts64(GetBitContext *gb, int bits)
758 {
759     if (get_bits_left(gb) < bits)
760         return AV_NOPTS_VALUE;
761     return get_bits64(gb, bits);
762 }
763
764 static int read_sl_header(PESContext *pes, SLConfigDescr *sl, const uint8_t *buf, int buf_size)
765 {
766     GetBitContext gb;
767     int au_start_flag = 0, au_end_flag = 0, ocr_flag = 0, idle_flag = 0;
768     int padding_flag = 0, padding_bits = 0, inst_bitrate_flag = 0;
769     int dts_flag = -1, cts_flag = -1;
770     int64_t dts = AV_NOPTS_VALUE, cts = AV_NOPTS_VALUE;
771
772     init_get_bits(&gb, buf, buf_size*8);
773
774     if (sl->use_au_start)
775         au_start_flag = get_bits1(&gb);
776     if (sl->use_au_end)
777         au_end_flag = get_bits1(&gb);
778     if (!sl->use_au_start && !sl->use_au_end)
779         au_start_flag = au_end_flag = 1;
780     if (sl->ocr_len > 0)
781         ocr_flag = get_bits1(&gb);
782     if (sl->use_idle)
783         idle_flag = get_bits1(&gb);
784     if (sl->use_padding)
785         padding_flag = get_bits1(&gb);
786     if (padding_flag)
787         padding_bits = get_bits(&gb, 3);
788
789     if (!idle_flag && (!padding_flag || padding_bits != 0)) {
790         if (sl->packet_seq_num_len)
791             skip_bits_long(&gb, sl->packet_seq_num_len);
792         if (sl->degr_prior_len)
793             if (get_bits1(&gb))
794                 skip_bits(&gb, sl->degr_prior_len);
795         if (ocr_flag)
796             skip_bits_long(&gb, sl->ocr_len);
797         if (au_start_flag) {
798             if (sl->use_rand_acc_pt)
799                 get_bits1(&gb);
800             if (sl->au_seq_num_len > 0)
801                 skip_bits_long(&gb, sl->au_seq_num_len);
802             if (sl->use_timestamps) {
803                 dts_flag = get_bits1(&gb);
804                 cts_flag = get_bits1(&gb);
805             }
806         }
807         if (sl->inst_bitrate_len)
808             inst_bitrate_flag = get_bits1(&gb);
809         if (dts_flag == 1)
810             dts = get_ts64(&gb, sl->timestamp_len);
811         if (cts_flag == 1)
812             cts = get_ts64(&gb, sl->timestamp_len);
813         if (sl->au_len > 0)
814             skip_bits_long(&gb, sl->au_len);
815         if (inst_bitrate_flag)
816             skip_bits_long(&gb, sl->inst_bitrate_len);
817     }
818
819     if (dts != AV_NOPTS_VALUE)
820         pes->dts = dts;
821     if (cts != AV_NOPTS_VALUE)
822         pes->pts = cts;
823
824     if (sl->timestamp_len && sl->timestamp_res)
825         avpriv_set_pts_info(pes->st, sl->timestamp_len, 1, sl->timestamp_res);
826
827     return (get_bits_count(&gb) + 7) >> 3;
828 }
829
830 /* return non zero if a packet could be constructed */
831 static int mpegts_push_data(MpegTSFilter *filter,
832                             const uint8_t *buf, int buf_size, int is_start,
833                             int64_t pos)
834 {
835     PESContext *pes = filter->u.pes_filter.opaque;
836     MpegTSContext *ts = pes->ts;
837     const uint8_t *p;
838     int len, code;
839
840     if(!ts->pkt)
841         return 0;
842
843     if (is_start) {
844         if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
845             new_pes_packet(pes, ts->pkt);
846             ts->stop_parse = 1;
847         }
848         pes->state = MPEGTS_HEADER;
849         pes->data_index = 0;
850         pes->ts_packet_pos = pos;
851     }
852     p = buf;
853     while (buf_size > 0) {
854         switch(pes->state) {
855         case MPEGTS_HEADER:
856             len = PES_START_SIZE - pes->data_index;
857             if (len > buf_size)
858                 len = buf_size;
859             memcpy(pes->header + pes->data_index, p, len);
860             pes->data_index += len;
861             p += len;
862             buf_size -= len;
863             if (pes->data_index == PES_START_SIZE) {
864                 /* we got all the PES or section header. We can now
865                    decide */
866                 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
867                     pes->header[2] == 0x01) {
868                     /* it must be an mpeg2 PES stream */
869                     code = pes->header[3] | 0x100;
870                     av_dlog(pes->stream, "pid=%x pes_code=%#x\n", pes->pid, code);
871
872                     if ((pes->st && pes->st->discard == AVDISCARD_ALL &&
873                          (!pes->sub_st || pes->sub_st->discard == AVDISCARD_ALL)) ||
874                         code == 0x1be) /* padding_stream */
875                         goto skip;
876
877                     /* stream not present in PMT */
878                     if (ts->auto_guess && !pes->st) {
879                         pes->st = avformat_new_stream(ts->stream, NULL);
880                         if (!pes->st)
881                             return AVERROR(ENOMEM);
882                         pes->st->id = pes->pid;
883                         mpegts_set_stream_info(pes->st, pes, 0, 0);
884                     }
885
886                     pes->total_size = AV_RB16(pes->header + 4);
887                     /* NOTE: a zero total size means the PES size is
888                        unbounded */
889                     if (!pes->total_size)
890                         pes->total_size = MAX_PES_PAYLOAD;
891
892                     /* allocate pes buffer */
893                     pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
894                     if (!pes->buffer)
895                         return AVERROR(ENOMEM);
896
897                     if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
898                         code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
899                         code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
900                         code != 0x1f8) {                  /* ITU-T Rec. H.222.1 type E stream */
901                         pes->state = MPEGTS_PESHEADER;
902                         if (pes->st->codec->codec_id == AV_CODEC_ID_NONE && !pes->st->request_probe) {
903                             av_dlog(pes->stream, "pid=%x stream_type=%x probing\n",
904                                     pes->pid, pes->stream_type);
905                             pes->st->request_probe= 1;
906                         }
907                     } else {
908                         pes->state = MPEGTS_PAYLOAD;
909                         pes->data_index = 0;
910                     }
911                 } else {
912                     /* otherwise, it should be a table */
913                     /* skip packet */
914                 skip:
915                     pes->state = MPEGTS_SKIP;
916                     continue;
917                 }
918             }
919             break;
920             /**********************************************/
921             /* PES packing parsing */
922         case MPEGTS_PESHEADER:
923             len = PES_HEADER_SIZE - pes->data_index;
924             if (len < 0)
925                 return -1;
926             if (len > buf_size)
927                 len = buf_size;
928             memcpy(pes->header + pes->data_index, p, len);
929             pes->data_index += len;
930             p += len;
931             buf_size -= len;
932             if (pes->data_index == PES_HEADER_SIZE) {
933                 pes->pes_header_size = pes->header[8] + 9;
934                 pes->state = MPEGTS_PESHEADER_FILL;
935             }
936             break;
937         case MPEGTS_PESHEADER_FILL:
938             len = pes->pes_header_size - pes->data_index;
939             if (len < 0)
940                 return -1;
941             if (len > buf_size)
942                 len = buf_size;
943             memcpy(pes->header + pes->data_index, p, len);
944             pes->data_index += len;
945             p += len;
946             buf_size -= len;
947             if (pes->data_index == pes->pes_header_size) {
948                 const uint8_t *r;
949                 unsigned int flags, pes_ext, skip;
950
951                 flags = pes->header[7];
952                 r = pes->header + 9;
953                 pes->pts = AV_NOPTS_VALUE;
954                 pes->dts = AV_NOPTS_VALUE;
955                 if ((flags & 0xc0) == 0x80) {
956                     pes->pts = ff_parse_pes_pts(r);
957                     /* video pts is not monotonic, can't be used for dts */
958                     if (pes->st->codec->codec_type != AVMEDIA_TYPE_VIDEO)
959                         pes->dts = pes->pts;
960                     r += 5;
961                 } else if ((flags & 0xc0) == 0xc0) {
962                     pes->pts = ff_parse_pes_pts(r);
963                     r += 5;
964                     pes->dts = ff_parse_pes_pts(r);
965                     r += 5;
966                 }
967                 pes->extended_stream_id = -1;
968                 if (flags & 0x01) { /* PES extension */
969                     pes_ext = *r++;
970                     /* Skip PES private data, program packet sequence counter and P-STD buffer */
971                     skip = (pes_ext >> 4) & 0xb;
972                     skip += skip & 0x9;
973                     r += skip;
974                     if ((pes_ext & 0x41) == 0x01 &&
975                         (r + 2) <= (pes->header + pes->pes_header_size)) {
976                         /* PES extension 2 */
977                         if ((r[0] & 0x7f) > 0 && (r[1] & 0x80) == 0)
978                             pes->extended_stream_id = r[1];
979                     }
980                 }
981
982                 /* we got the full header. We parse it and get the payload */
983                 pes->state = MPEGTS_PAYLOAD;
984                 pes->data_index = 0;
985                 if (pes->stream_type == 0x12 && buf_size > 0) {
986                     int sl_header_bytes = read_sl_header(pes, &pes->sl, p, buf_size);
987                     pes->pes_header_size += sl_header_bytes;
988                     p += sl_header_bytes;
989                     buf_size -= sl_header_bytes;
990                 }
991             }
992             break;
993         case MPEGTS_PAYLOAD:
994             if (buf_size > 0 && pes->buffer) {
995                 if (pes->data_index > 0 && pes->data_index+buf_size > pes->total_size) {
996                     new_pes_packet(pes, ts->pkt);
997                     pes->total_size = MAX_PES_PAYLOAD;
998                     pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
999                     if (!pes->buffer)
1000                         return AVERROR(ENOMEM);
1001                     ts->stop_parse = 1;
1002                 } else if (pes->data_index == 0 && buf_size > pes->total_size) {
1003                     // pes packet size is < ts size packet and pes data is padded with 0xff
1004                     // not sure if this is legal in ts but see issue #2392
1005                     buf_size = pes->total_size;
1006                 }
1007                 memcpy(pes->buffer+pes->data_index, p, buf_size);
1008                 pes->data_index += buf_size;
1009             }
1010             buf_size = 0;
1011             /* emit complete packets with known packet size
1012              * decreases demuxer delay for infrequent packets like subtitles from
1013              * a couple of seconds to milliseconds for properly muxed files.
1014              * total_size is the number of bytes following pes_packet_length
1015              * in the pes header, i.e. not counting the first PES_START_SIZE bytes */
1016             if (!ts->stop_parse && pes->total_size < MAX_PES_PAYLOAD &&
1017                 pes->pes_header_size + pes->data_index == pes->total_size + PES_START_SIZE) {
1018                 ts->stop_parse = 1;
1019                 new_pes_packet(pes, ts->pkt);
1020             }
1021             break;
1022         case MPEGTS_SKIP:
1023             buf_size = 0;
1024             break;
1025         }
1026     }
1027
1028     return 0;
1029 }
1030
1031 static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
1032 {
1033     MpegTSFilter *tss;
1034     PESContext *pes;
1035
1036     /* if no pid found, then add a pid context */
1037     pes = av_mallocz(sizeof(PESContext));
1038     if (!pes)
1039         return 0;
1040     pes->ts = ts;
1041     pes->stream = ts->stream;
1042     pes->pid = pid;
1043     pes->pcr_pid = pcr_pid;
1044     pes->state = MPEGTS_SKIP;
1045     pes->pts = AV_NOPTS_VALUE;
1046     pes->dts = AV_NOPTS_VALUE;
1047     tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
1048     if (!tss) {
1049         av_free(pes);
1050         return 0;
1051     }
1052     return pes;
1053 }
1054
1055 #define MAX_LEVEL 4
1056 typedef struct {
1057     AVFormatContext *s;
1058     AVIOContext pb;
1059     Mp4Descr *descr;
1060     Mp4Descr *active_descr;
1061     int descr_count;
1062     int max_descr_count;
1063     int level;
1064 } MP4DescrParseContext;
1065
1066 static int init_MP4DescrParseContext(
1067     MP4DescrParseContext *d, AVFormatContext *s, const uint8_t *buf,
1068     unsigned size, Mp4Descr *descr, int max_descr_count)
1069 {
1070     int ret;
1071     if (size > (1<<30))
1072         return AVERROR_INVALIDDATA;
1073
1074     if ((ret = ffio_init_context(&d->pb, (unsigned char*)buf, size, 0,
1075                           NULL, NULL, NULL, NULL)) < 0)
1076         return ret;
1077
1078     d->s = s;
1079     d->level = 0;
1080     d->descr_count = 0;
1081     d->descr = descr;
1082     d->active_descr = NULL;
1083     d->max_descr_count = max_descr_count;
1084
1085     return 0;
1086 }
1087
1088 static void update_offsets(AVIOContext *pb, int64_t *off, int *len) {
1089     int64_t new_off = avio_tell(pb);
1090     (*len) -= new_off - *off;
1091     *off = new_off;
1092 }
1093
1094 static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
1095                            int target_tag);
1096
1097 static int parse_mp4_descr_arr(MP4DescrParseContext *d, int64_t off, int len)
1098 {
1099     while (len > 0) {
1100         if (parse_mp4_descr(d, off, len, 0) < 0)
1101             return -1;
1102         update_offsets(&d->pb, &off, &len);
1103     }
1104     return 0;
1105 }
1106
1107 static int parse_MP4IODescrTag(MP4DescrParseContext *d, int64_t off, int len)
1108 {
1109     avio_rb16(&d->pb); // ID
1110     avio_r8(&d->pb);
1111     avio_r8(&d->pb);
1112     avio_r8(&d->pb);
1113     avio_r8(&d->pb);
1114     avio_r8(&d->pb);
1115     update_offsets(&d->pb, &off, &len);
1116     return parse_mp4_descr_arr(d, off, len);
1117 }
1118
1119 static int parse_MP4ODescrTag(MP4DescrParseContext *d, int64_t off, int len)
1120 {
1121     int id_flags;
1122     if (len < 2)
1123         return 0;
1124     id_flags = avio_rb16(&d->pb);
1125     if (!(id_flags & 0x0020)) { //URL_Flag
1126         update_offsets(&d->pb, &off, &len);
1127         return parse_mp4_descr_arr(d, off, len); //ES_Descriptor[]
1128     } else {
1129         return 0;
1130     }
1131 }
1132
1133 static int parse_MP4ESDescrTag(MP4DescrParseContext *d, int64_t off, int len)
1134 {
1135     int es_id = 0;
1136     if (d->descr_count >= d->max_descr_count)
1137         return -1;
1138     ff_mp4_parse_es_descr(&d->pb, &es_id);
1139     d->active_descr = d->descr + (d->descr_count++);
1140
1141     d->active_descr->es_id = es_id;
1142     update_offsets(&d->pb, &off, &len);
1143     parse_mp4_descr(d, off, len, MP4DecConfigDescrTag);
1144     update_offsets(&d->pb, &off, &len);
1145     if (len > 0)
1146         parse_mp4_descr(d, off, len, MP4SLDescrTag);
1147     d->active_descr = NULL;
1148     return 0;
1149 }
1150
1151 static int parse_MP4DecConfigDescrTag(MP4DescrParseContext *d, int64_t off, int len)
1152 {
1153     Mp4Descr *descr = d->active_descr;
1154     if (!descr)
1155         return -1;
1156     d->active_descr->dec_config_descr = av_malloc(len);
1157     if (!descr->dec_config_descr)
1158         return AVERROR(ENOMEM);
1159     descr->dec_config_descr_len = len;
1160     avio_read(&d->pb, descr->dec_config_descr, len);
1161     return 0;
1162 }
1163
1164 static int parse_MP4SLDescrTag(MP4DescrParseContext *d, int64_t off, int len)
1165 {
1166     Mp4Descr *descr = d->active_descr;
1167     int predefined;
1168     if (!descr)
1169         return -1;
1170
1171     predefined = avio_r8(&d->pb);
1172     if (!predefined) {
1173         int lengths;
1174         int flags = avio_r8(&d->pb);
1175         descr->sl.use_au_start       = !!(flags & 0x80);
1176         descr->sl.use_au_end         = !!(flags & 0x40);
1177         descr->sl.use_rand_acc_pt    = !!(flags & 0x20);
1178         descr->sl.use_padding        = !!(flags & 0x08);
1179         descr->sl.use_timestamps     = !!(flags & 0x04);
1180         descr->sl.use_idle           = !!(flags & 0x02);
1181         descr->sl.timestamp_res      = avio_rb32(&d->pb);
1182                                        avio_rb32(&d->pb);
1183         descr->sl.timestamp_len      = avio_r8(&d->pb);
1184         descr->sl.ocr_len            = avio_r8(&d->pb);
1185         descr->sl.au_len             = avio_r8(&d->pb);
1186         descr->sl.inst_bitrate_len   = avio_r8(&d->pb);
1187         lengths                      = avio_rb16(&d->pb);
1188         descr->sl.degr_prior_len     = lengths >> 12;
1189         descr->sl.au_seq_num_len     = (lengths >> 7) & 0x1f;
1190         descr->sl.packet_seq_num_len = (lengths >> 2) & 0x1f;
1191     } else {
1192         av_log_missing_feature(d->s, "Predefined SLConfigDescriptor", 0);
1193     }
1194     return 0;
1195 }
1196
1197 static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
1198                            int target_tag) {
1199     int tag;
1200     int len1 = ff_mp4_read_descr(d->s, &d->pb, &tag);
1201     update_offsets(&d->pb, &off, &len);
1202     if (len < 0 || len1 > len || len1 <= 0) {
1203         av_log(d->s, AV_LOG_ERROR, "Tag %x length violation new length %d bytes remaining %d\n", tag, len1, len);
1204         return -1;
1205     }
1206
1207     if (d->level++ >= MAX_LEVEL) {
1208         av_log(d->s, AV_LOG_ERROR, "Maximum MP4 descriptor level exceeded\n");
1209         goto done;
1210     }
1211
1212     if (target_tag && tag != target_tag) {
1213         av_log(d->s, AV_LOG_ERROR, "Found tag %x expected %x\n", tag, target_tag);
1214         goto done;
1215     }
1216
1217     switch (tag) {
1218     case MP4IODescrTag:
1219         parse_MP4IODescrTag(d, off, len1);
1220         break;
1221     case MP4ODescrTag:
1222         parse_MP4ODescrTag(d, off, len1);
1223         break;
1224     case MP4ESDescrTag:
1225         parse_MP4ESDescrTag(d, off, len1);
1226         break;
1227     case MP4DecConfigDescrTag:
1228         parse_MP4DecConfigDescrTag(d, off, len1);
1229         break;
1230     case MP4SLDescrTag:
1231         parse_MP4SLDescrTag(d, off, len1);
1232         break;
1233     }
1234
1235 done:
1236     d->level--;
1237     avio_seek(&d->pb, off + len1, SEEK_SET);
1238     return 0;
1239 }
1240
1241 static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size,
1242                          Mp4Descr *descr, int *descr_count, int max_descr_count)
1243 {
1244     MP4DescrParseContext d;
1245     if (init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count) < 0)
1246         return -1;
1247
1248     parse_mp4_descr(&d, avio_tell(&d.pb), size, MP4IODescrTag);
1249
1250     *descr_count = d.descr_count;
1251     return 0;
1252 }
1253
1254 static int mp4_read_od(AVFormatContext *s, const uint8_t *buf, unsigned size,
1255                        Mp4Descr *descr, int *descr_count, int max_descr_count)
1256 {
1257     MP4DescrParseContext d;
1258     if (init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count) < 0)
1259         return -1;
1260
1261     parse_mp4_descr_arr(&d, avio_tell(&d.pb), size);
1262
1263     *descr_count = d.descr_count;
1264     return 0;
1265 }
1266
1267 static void m4sl_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1268 {
1269     MpegTSContext *ts = filter->u.section_filter.opaque;
1270     SectionHeader h;
1271     const uint8_t *p, *p_end;
1272     AVIOContext pb;
1273     Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = {{ 0 }};
1274     int mp4_descr_count = 0;
1275     int i, pid;
1276     AVFormatContext *s = ts->stream;
1277
1278     p_end = section + section_len - 4;
1279     p = section;
1280     if (parse_section_header(&h, &p, p_end) < 0)
1281         return;
1282     if (h.tid != M4OD_TID)
1283         return;
1284
1285     mp4_read_od(s, p, (unsigned)(p_end - p), mp4_descr, &mp4_descr_count, MAX_MP4_DESCR_COUNT);
1286
1287     for (pid = 0; pid < NB_PID_MAX; pid++) {
1288         if (!ts->pids[pid])
1289              continue;
1290         for (i = 0; i < mp4_descr_count; i++) {
1291             PESContext *pes;
1292             AVStream *st;
1293             if (ts->pids[pid]->es_id != mp4_descr[i].es_id)
1294                 continue;
1295             if (!(ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES)) {
1296                 av_log(s, AV_LOG_ERROR, "pid %x is not PES\n", pid);
1297                 continue;
1298             }
1299             pes = ts->pids[pid]->u.pes_filter.opaque;
1300             st = pes->st;
1301             if (!st) {
1302                 continue;
1303             }
1304
1305             pes->sl = mp4_descr[i].sl;
1306
1307             ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
1308                               mp4_descr[i].dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
1309             ff_mp4_read_dec_config_descr(s, st, &pb);
1310             if (st->codec->codec_id == AV_CODEC_ID_AAC &&
1311                 st->codec->extradata_size > 0)
1312                 st->need_parsing = 0;
1313             if (st->codec->codec_id == AV_CODEC_ID_H264 &&
1314                 st->codec->extradata_size > 0)
1315                 st->need_parsing = 0;
1316
1317             if (st->codec->codec_id <= AV_CODEC_ID_NONE) {
1318             } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_AUDIO) {
1319                 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1320             } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_SUBTITLE) {
1321                 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1322             } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_UNKNOWN) {
1323                 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1324             }
1325         }
1326     }
1327     for (i = 0; i < mp4_descr_count; i++)
1328         av_free(mp4_descr[i].dec_config_descr);
1329 }
1330
1331 int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,
1332                               const uint8_t **pp, const uint8_t *desc_list_end,
1333                               Mp4Descr *mp4_descr, int mp4_descr_count, int pid,
1334                               MpegTSContext *ts)
1335 {
1336     const uint8_t *desc_end;
1337     int desc_len, desc_tag, desc_es_id;
1338     char language[252];
1339     int i;
1340
1341     desc_tag = get8(pp, desc_list_end);
1342     if (desc_tag < 0)
1343         return -1;
1344     desc_len = get8(pp, desc_list_end);
1345     if (desc_len < 0)
1346         return -1;
1347     desc_end = *pp + desc_len;
1348     if (desc_end > desc_list_end)
1349         return -1;
1350
1351     av_dlog(fc, "tag: 0x%02x len=%d\n", desc_tag, desc_len);
1352
1353     if (st->codec->codec_id == AV_CODEC_ID_NONE &&
1354         stream_type == STREAM_TYPE_PRIVATE_DATA)
1355         mpegts_find_stream_type(st, desc_tag, DESC_types);
1356
1357     switch(desc_tag) {
1358     case 0x1E: /* SL descriptor */
1359         desc_es_id = get16(pp, desc_end);
1360         if (ts && ts->pids[pid])
1361             ts->pids[pid]->es_id = desc_es_id;
1362         for (i = 0; i < mp4_descr_count; i++)
1363         if (mp4_descr[i].dec_config_descr_len &&
1364             mp4_descr[i].es_id == desc_es_id) {
1365             AVIOContext pb;
1366             ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
1367                           mp4_descr[i].dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
1368             ff_mp4_read_dec_config_descr(fc, st, &pb);
1369             if (st->codec->codec_id == AV_CODEC_ID_AAC &&
1370                 st->codec->extradata_size > 0)
1371                 st->need_parsing = 0;
1372             if (st->codec->codec_id == AV_CODEC_ID_MPEG4SYSTEMS)
1373                 mpegts_open_section_filter(ts, pid, m4sl_cb, ts, 1);
1374         }
1375         break;
1376     case 0x1F: /* FMC descriptor */
1377         get16(pp, desc_end);
1378         if (mp4_descr_count > 0 && (st->codec->codec_id == AV_CODEC_ID_AAC_LATM || st->request_probe>0) &&
1379             mp4_descr->dec_config_descr_len && mp4_descr->es_id == pid) {
1380             AVIOContext pb;
1381             ffio_init_context(&pb, mp4_descr->dec_config_descr,
1382                           mp4_descr->dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
1383             ff_mp4_read_dec_config_descr(fc, st, &pb);
1384             if (st->codec->codec_id == AV_CODEC_ID_AAC &&
1385                 st->codec->extradata_size > 0){
1386                 st->request_probe= st->need_parsing = 0;
1387                 st->codec->codec_type= AVMEDIA_TYPE_AUDIO;
1388             }
1389         }
1390         break;
1391     case 0x56: /* DVB teletext descriptor */
1392         language[0] = get8(pp, desc_end);
1393         language[1] = get8(pp, desc_end);
1394         language[2] = get8(pp, desc_end);
1395         language[3] = 0;
1396         av_dict_set(&st->metadata, "language", language, 0);
1397         break;
1398     case 0x59: /* subtitling descriptor */
1399         language[0] = get8(pp, desc_end);
1400         language[1] = get8(pp, desc_end);
1401         language[2] = get8(pp, desc_end);
1402         language[3] = 0;
1403         /* hearing impaired subtitles detection */
1404         switch(get8(pp, desc_end)) {
1405         case 0x20: /* DVB subtitles (for the hard of hearing) with no monitor aspect ratio criticality */
1406         case 0x21: /* DVB subtitles (for the hard of hearing) for display on 4:3 aspect ratio monitor */
1407         case 0x22: /* DVB subtitles (for the hard of hearing) for display on 16:9 aspect ratio monitor */
1408         case 0x23: /* DVB subtitles (for the hard of hearing) for display on 2.21:1 aspect ratio monitor */
1409         case 0x24: /* DVB subtitles (for the hard of hearing) for display on a high definition monitor */
1410         case 0x25: /* DVB subtitles (for the hard of hearing) with plano-stereoscopic disparity for display on a high definition monitor */
1411             st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
1412             break;
1413         }
1414         if (st->codec->extradata) {
1415             if (st->codec->extradata_size == 4 && memcmp(st->codec->extradata, *pp, 4))
1416                 av_log_ask_for_sample(fc, "DVB sub with multiple IDs\n");
1417         } else {
1418             st->codec->extradata = av_malloc(4 + FF_INPUT_BUFFER_PADDING_SIZE);
1419             if (st->codec->extradata) {
1420                 st->codec->extradata_size = 4;
1421                 memcpy(st->codec->extradata, *pp, 4);
1422             }
1423         }
1424         *pp += 4;
1425         av_dict_set(&st->metadata, "language", language, 0);
1426         break;
1427     case 0x0a: /* ISO 639 language descriptor */
1428         for (i = 0; i + 4 <= desc_len; i += 4) {
1429             language[i + 0] = get8(pp, desc_end);
1430             language[i + 1] = get8(pp, desc_end);
1431             language[i + 2] = get8(pp, desc_end);
1432             language[i + 3] = ',';
1433         switch (get8(pp, desc_end)) {
1434             case 0x01: st->disposition |= AV_DISPOSITION_CLEAN_EFFECTS; break;
1435             case 0x02: st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED; break;
1436             case 0x03: st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED; break;
1437         }
1438         }
1439         if (i) {
1440             language[i - 1] = 0;
1441             av_dict_set(&st->metadata, "language", language, 0);
1442         }
1443         break;
1444     case 0x05: /* registration descriptor */
1445         st->codec->codec_tag = bytestream_get_le32(pp);
1446         av_dlog(fc, "reg_desc=%.4s\n", (char*)&st->codec->codec_tag);
1447         if (st->codec->codec_id == AV_CODEC_ID_NONE)
1448             mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
1449         break;
1450     case 0x52: /* stream identifier descriptor */
1451         st->stream_identifier = 1 + get8(pp, desc_end);
1452         break;
1453     default:
1454         break;
1455     }
1456     *pp = desc_end;
1457     return 0;
1458 }
1459
1460 static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1461 {
1462     MpegTSContext *ts = filter->u.section_filter.opaque;
1463     SectionHeader h1, *h = &h1;
1464     PESContext *pes;
1465     AVStream *st;
1466     const uint8_t *p, *p_end, *desc_list_end;
1467     int program_info_length, pcr_pid, pid, stream_type;
1468     int desc_list_len;
1469     uint32_t prog_reg_desc = 0; /* registration descriptor */
1470
1471     Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = {{ 0 }};
1472     int mp4_descr_count = 0;
1473     int i;
1474
1475     av_dlog(ts->stream, "PMT: len %i\n", section_len);
1476     hex_dump_debug(ts->stream, section, section_len);
1477
1478     p_end = section + section_len - 4;
1479     p = section;
1480     if (parse_section_header(h, &p, p_end) < 0)
1481         return;
1482
1483     av_dlog(ts->stream, "sid=0x%x sec_num=%d/%d\n",
1484            h->id, h->sec_num, h->last_sec_num);
1485
1486     if (h->tid != PMT_TID)
1487         return;
1488
1489     clear_program(ts, h->id);
1490     pcr_pid = get16(&p, p_end);
1491     if (pcr_pid < 0)
1492         return;
1493     pcr_pid &= 0x1fff;
1494     add_pid_to_pmt(ts, h->id, pcr_pid);
1495     set_pcr_pid(ts->stream, h->id, pcr_pid);
1496
1497     av_dlog(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
1498
1499     program_info_length = get16(&p, p_end);
1500     if (program_info_length < 0)
1501         return;
1502     program_info_length &= 0xfff;
1503     while(program_info_length >= 2) {
1504         uint8_t tag, len;
1505         tag = get8(&p, p_end);
1506         len = get8(&p, p_end);
1507
1508         av_dlog(ts->stream, "program tag: 0x%02x len=%d\n", tag, len);
1509
1510         if(len > program_info_length - 2)
1511             //something else is broken, exit the program_descriptors_loop
1512             break;
1513         program_info_length -= len + 2;
1514         if (tag == 0x1d) { // IOD descriptor
1515             get8(&p, p_end); // scope
1516             get8(&p, p_end); // label
1517             len -= 2;
1518             mp4_read_iods(ts->stream, p, len, mp4_descr + mp4_descr_count,
1519                           &mp4_descr_count, MAX_MP4_DESCR_COUNT);
1520         } else if (tag == 0x05 && len >= 4) { // registration descriptor
1521             prog_reg_desc = bytestream_get_le32(&p);
1522             len -= 4;
1523         }
1524         p += len;
1525     }
1526     p += program_info_length;
1527     if (p >= p_end)
1528         goto out;
1529
1530     // stop parsing after pmt, we found header
1531     if (!ts->stream->nb_streams)
1532         ts->stop_parse = 2;
1533
1534     for(;;) {
1535         st = 0;
1536         pes = NULL;
1537         stream_type = get8(&p, p_end);
1538         if (stream_type < 0)
1539             break;
1540         pid = get16(&p, p_end);
1541         if (pid < 0)
1542             break;
1543         pid &= 0x1fff;
1544         if (pid == ts->current_pid)
1545             break;
1546
1547         /* now create stream */
1548         if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
1549             pes = ts->pids[pid]->u.pes_filter.opaque;
1550             if (!pes->st) {
1551                 pes->st = avformat_new_stream(pes->stream, NULL);
1552                 if (!pes->st)
1553                     goto out;
1554                 pes->st->id = pes->pid;
1555             }
1556             st = pes->st;
1557         } else if (stream_type != 0x13) {
1558             if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
1559             pes = add_pes_stream(ts, pid, pcr_pid);
1560             if (pes) {
1561                 st = avformat_new_stream(pes->stream, NULL);
1562                 if (!st)
1563                     goto out;
1564                 st->id = pes->pid;
1565             }
1566         } else {
1567             int idx = ff_find_stream_index(ts->stream, pid);
1568             if (idx >= 0) {
1569                 st = ts->stream->streams[idx];
1570             } else {
1571                 st = avformat_new_stream(ts->stream, NULL);
1572                 if (!st)
1573                     goto out;
1574                 st->id = pid;
1575                 st->codec->codec_type = AVMEDIA_TYPE_DATA;
1576             }
1577         }
1578
1579         if (!st)
1580             goto out;
1581
1582         if (pes && !pes->stream_type)
1583             mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
1584
1585         add_pid_to_pmt(ts, h->id, pid);
1586
1587         ff_program_add_stream_index(ts->stream, h->id, st->index);
1588
1589         desc_list_len = get16(&p, p_end);
1590         if (desc_list_len < 0)
1591             break;
1592         desc_list_len &= 0xfff;
1593         desc_list_end = p + desc_list_len;
1594         if (desc_list_end > p_end)
1595             break;
1596         for(;;) {
1597             if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p, desc_list_end,
1598                 mp4_descr, mp4_descr_count, pid, ts) < 0)
1599                 break;
1600
1601             if (pes && prog_reg_desc == AV_RL32("HDMV") && stream_type == 0x83 && pes->sub_st) {
1602                 ff_program_add_stream_index(ts->stream, h->id, pes->sub_st->index);
1603                 pes->sub_st->codec->codec_tag = st->codec->codec_tag;
1604             }
1605         }
1606         p = desc_list_end;
1607     }
1608
1609  out:
1610     for (i = 0; i < mp4_descr_count; i++)
1611         av_free(mp4_descr[i].dec_config_descr);
1612 }
1613
1614 static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1615 {
1616     MpegTSContext *ts = filter->u.section_filter.opaque;
1617     SectionHeader h1, *h = &h1;
1618     const uint8_t *p, *p_end;
1619     int sid, pmt_pid;
1620     AVProgram *program;
1621
1622     av_dlog(ts->stream, "PAT:\n");
1623     hex_dump_debug(ts->stream, section, section_len);
1624
1625     p_end = section + section_len - 4;
1626     p = section;
1627     if (parse_section_header(h, &p, p_end) < 0)
1628         return;
1629     if (h->tid != PAT_TID)
1630         return;
1631     if (!h->current)
1632         return;
1633     if (h->version == filter->last_version)
1634         return;
1635     filter->last_version = h->version;
1636     av_dlog(ts->stream, "version=%d\n", filter->last_version);
1637
1638     ts->stream->ts_id = h->id;
1639
1640     clear_programs(ts);
1641     for(;;) {
1642         sid = get16(&p, p_end);
1643         if (sid < 0)
1644             break;
1645         pmt_pid = get16(&p, p_end);
1646         if (pmt_pid < 0)
1647             break;
1648         pmt_pid &= 0x1fff;
1649
1650         if (pmt_pid == ts->current_pid)
1651             break;
1652
1653         av_dlog(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
1654
1655         if (sid == 0x0000) {
1656             /* NIT info */
1657         } else {
1658             program = av_new_program(ts->stream, sid);
1659             program->program_num = sid;
1660             program->pmt_pid = pmt_pid;
1661             if (ts->pids[pmt_pid])
1662                 mpegts_close_filter(ts, ts->pids[pmt_pid]);
1663             mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
1664             add_pat_entry(ts, sid);
1665             add_pid_to_pmt(ts, sid, 0); //add pat pid to program
1666             add_pid_to_pmt(ts, sid, pmt_pid);
1667         }
1668     }
1669
1670     if (sid < 0) {
1671         int i,j;
1672         for (j=0; j<ts->stream->nb_programs; j++) {
1673             for (i=0; i<ts->nb_prg; i++)
1674                 if (ts->prg[i].id == ts->stream->programs[j]->id)
1675                     break;
1676             if (i==ts->nb_prg)
1677                 clear_avprogram(ts, ts->stream->programs[j]->id);
1678         }
1679     }
1680 }
1681
1682 static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1683 {
1684     MpegTSContext *ts = filter->u.section_filter.opaque;
1685     SectionHeader h1, *h = &h1;
1686     const uint8_t *p, *p_end, *desc_list_end, *desc_end;
1687     int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
1688     char *name, *provider_name;
1689
1690     av_dlog(ts->stream, "SDT:\n");
1691     hex_dump_debug(ts->stream, section, section_len);
1692
1693     p_end = section + section_len - 4;
1694     p = section;
1695     if (parse_section_header(h, &p, p_end) < 0)
1696         return;
1697     if (h->tid != SDT_TID)
1698         return;
1699     onid = get16(&p, p_end);
1700     if (onid < 0)
1701         return;
1702     val = get8(&p, p_end);
1703     if (val < 0)
1704         return;
1705     for(;;) {
1706         sid = get16(&p, p_end);
1707         if (sid < 0)
1708             break;
1709         val = get8(&p, p_end);
1710         if (val < 0)
1711             break;
1712         desc_list_len = get16(&p, p_end);
1713         if (desc_list_len < 0)
1714             break;
1715         desc_list_len &= 0xfff;
1716         desc_list_end = p + desc_list_len;
1717         if (desc_list_end > p_end)
1718             break;
1719         for(;;) {
1720             desc_tag = get8(&p, desc_list_end);
1721             if (desc_tag < 0)
1722                 break;
1723             desc_len = get8(&p, desc_list_end);
1724             desc_end = p + desc_len;
1725             if (desc_end > desc_list_end)
1726                 break;
1727
1728             av_dlog(ts->stream, "tag: 0x%02x len=%d\n",
1729                    desc_tag, desc_len);
1730
1731             switch(desc_tag) {
1732             case 0x48:
1733                 service_type = get8(&p, p_end);
1734                 if (service_type < 0)
1735                     break;
1736                 provider_name = getstr8(&p, p_end);
1737                 if (!provider_name)
1738                     break;
1739                 name = getstr8(&p, p_end);
1740                 if (name) {
1741                     AVProgram *program = av_new_program(ts->stream, sid);
1742                     if(program) {
1743                         av_dict_set(&program->metadata, "service_name", name, 0);
1744                         av_dict_set(&program->metadata, "service_provider", provider_name, 0);
1745                     }
1746                 }
1747                 av_free(name);
1748                 av_free(provider_name);
1749                 break;
1750             default:
1751                 break;
1752             }
1753             p = desc_end;
1754         }
1755         p = desc_list_end;
1756     }
1757 }
1758
1759 /* handle one TS packet */
1760 static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
1761 {
1762     AVFormatContext *s = ts->stream;
1763     MpegTSFilter *tss;
1764     int len, pid, cc, expected_cc, cc_ok, afc, is_start, is_discontinuity,
1765         has_adaptation, has_payload;
1766     const uint8_t *p, *p_end;
1767     int64_t pos;
1768
1769     pid = AV_RB16(packet + 1) & 0x1fff;
1770     if(pid && discard_pid(ts, pid))
1771         return 0;
1772     is_start = packet[1] & 0x40;
1773     tss = ts->pids[pid];
1774     if (ts->auto_guess && tss == NULL && is_start) {
1775         add_pes_stream(ts, pid, -1);
1776         tss = ts->pids[pid];
1777     }
1778     if (!tss)
1779         return 0;
1780     ts->current_pid = pid;
1781
1782     afc = (packet[3] >> 4) & 3;
1783     if (afc == 0) /* reserved value */
1784         return 0;
1785     has_adaptation = afc & 2;
1786     has_payload = afc & 1;
1787     is_discontinuity = has_adaptation
1788                 && packet[4] != 0 /* with length > 0 */
1789                 && (packet[5] & 0x80); /* and discontinuity indicated */
1790
1791     /* continuity check (currently not used) */
1792     cc = (packet[3] & 0xf);
1793     expected_cc = has_payload ? (tss->last_cc + 1) & 0x0f : tss->last_cc;
1794     cc_ok = pid == 0x1FFF // null packet PID
1795             || is_discontinuity
1796             || tss->last_cc < 0
1797             || expected_cc == cc;
1798
1799     tss->last_cc = cc;
1800     if (!cc_ok) {
1801         av_log(ts->stream, AV_LOG_DEBUG,
1802                "Continuity check failed for pid %d expected %d got %d\n",
1803                pid, expected_cc, cc);
1804         if(tss->type == MPEGTS_PES) {
1805             PESContext *pc = tss->u.pes_filter.opaque;
1806             pc->flags |= AV_PKT_FLAG_CORRUPT;
1807         }
1808     }
1809
1810     if (!has_payload)
1811         return 0;
1812     p = packet + 4;
1813     if (has_adaptation) {
1814         /* skip adaptation field */
1815         p += p[0] + 1;
1816     }
1817     /* if past the end of packet, ignore */
1818     p_end = packet + TS_PACKET_SIZE;
1819     if (p >= p_end)
1820         return 0;
1821
1822     pos = avio_tell(ts->stream->pb);
1823     MOD_UNLIKELY(ts->pos47, pos, ts->raw_packet_size, ts->pos);
1824
1825     if (tss->type == MPEGTS_SECTION) {
1826         if (is_start) {
1827             /* pointer field present */
1828             len = *p++;
1829             if (p + len > p_end)
1830                 return 0;
1831             if (len && cc_ok) {
1832                 /* write remaining section bytes */
1833                 write_section_data(s, tss,
1834                                    p, len, 0);
1835                 /* check whether filter has been closed */
1836                 if (!ts->pids[pid])
1837                     return 0;
1838             }
1839             p += len;
1840             if (p < p_end) {
1841                 write_section_data(s, tss,
1842                                    p, p_end - p, 1);
1843             }
1844         } else {
1845             if (cc_ok) {
1846                 write_section_data(s, tss,
1847                                    p, p_end - p, 0);
1848             }
1849         }
1850     } else {
1851         int ret;
1852         // Note: The position here points actually behind the current packet.
1853         if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
1854                                             pos - ts->raw_packet_size)) < 0)
1855             return ret;
1856     }
1857
1858     return 0;
1859 }
1860
1861 /* XXX: try to find a better synchro over several packets (use
1862    get_packet_size() ?) */
1863 static int mpegts_resync(AVFormatContext *s)
1864 {
1865     AVIOContext *pb = s->pb;
1866     int c, i;
1867
1868     for(i = 0;i < MAX_RESYNC_SIZE; i++) {
1869         c = avio_r8(pb);
1870         if (url_feof(pb))
1871             return -1;
1872         if (c == 0x47) {
1873             avio_seek(pb, -1, SEEK_CUR);
1874             return 0;
1875         }
1876     }
1877     av_log(s, AV_LOG_ERROR, "max resync size reached, could not find sync byte\n");
1878     /* no sync found */
1879     return -1;
1880 }
1881
1882 /* return -1 if error or EOF. Return 0 if OK. */
1883 static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size, uint8_t **data)
1884 {
1885     AVIOContext *pb = s->pb;
1886     int len;
1887
1888     for(;;) {
1889         len = ffio_read_indirect(pb, buf, TS_PACKET_SIZE, data);
1890         if (len != TS_PACKET_SIZE)
1891             return len < 0 ? len : AVERROR_EOF;
1892         /* check packet sync byte */
1893         if ((*data)[0] != 0x47) {
1894             /* find a new packet start */
1895             avio_seek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1896             if (mpegts_resync(s) < 0)
1897                 return AVERROR(EAGAIN);
1898             else
1899                 continue;
1900         } else {
1901             break;
1902         }
1903     }
1904     return 0;
1905 }
1906
1907 static void finished_reading_packet(AVFormatContext *s, int raw_packet_size)
1908 {
1909     AVIOContext *pb = s->pb;
1910     int skip = raw_packet_size - TS_PACKET_SIZE;
1911     if (skip > 0)
1912         avio_skip(pb, skip);
1913 }
1914
1915 static int handle_packets(MpegTSContext *ts, int nb_packets)
1916 {
1917     AVFormatContext *s = ts->stream;
1918     uint8_t packet[TS_PACKET_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
1919     uint8_t *data;
1920     int packet_num, ret = 0;
1921
1922     if (avio_tell(s->pb) != ts->last_pos) {
1923         int i;
1924         av_dlog(ts->stream, "Skipping after seek\n");
1925         /* seek detected, flush pes buffer */
1926         for (i = 0; i < NB_PID_MAX; i++) {
1927             if (ts->pids[i]) {
1928                 if (ts->pids[i]->type == MPEGTS_PES) {
1929                    PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
1930                    av_freep(&pes->buffer);
1931                    pes->data_index = 0;
1932                    pes->state = MPEGTS_SKIP; /* skip until pes header */
1933                 }
1934                 ts->pids[i]->last_cc = -1;
1935             }
1936         }
1937     }
1938
1939     ts->stop_parse = 0;
1940     packet_num = 0;
1941     memset(packet + TS_PACKET_SIZE, 0, FF_INPUT_BUFFER_PADDING_SIZE);
1942     for(;;) {
1943         packet_num++;
1944         if (nb_packets != 0 && packet_num >= nb_packets ||
1945             ts->stop_parse > 1) {
1946             ret = AVERROR(EAGAIN);
1947             break;
1948         }
1949         if (ts->stop_parse > 0)
1950             break;
1951
1952         ret = read_packet(s, packet, ts->raw_packet_size, &data);
1953         if (ret != 0)
1954             break;
1955         ret = handle_packet(ts, data);
1956         finished_reading_packet(s, ts->raw_packet_size);
1957         if (ret != 0)
1958             break;
1959     }
1960     ts->last_pos = avio_tell(s->pb);
1961     return ret;
1962 }
1963
1964 static int mpegts_probe(AVProbeData *p)
1965 {
1966     const int size= p->buf_size;
1967     int maxscore=0;
1968     int sumscore=0;
1969     int i;
1970     int check_count= size / TS_FEC_PACKET_SIZE;
1971 #define CHECK_COUNT 10
1972 #define CHECK_BLOCK 100
1973
1974     if (check_count < CHECK_COUNT)
1975         return -1;
1976
1977     for (i=0; i<check_count; i+=CHECK_BLOCK){
1978         int left = FFMIN(check_count - i, CHECK_BLOCK);
1979         int score     = analyze(p->buf + TS_PACKET_SIZE     *i, TS_PACKET_SIZE     *left, TS_PACKET_SIZE     , NULL);
1980         int dvhs_score= analyze(p->buf + TS_DVHS_PACKET_SIZE*i, TS_DVHS_PACKET_SIZE*left, TS_DVHS_PACKET_SIZE, NULL);
1981         int fec_score = analyze(p->buf + TS_FEC_PACKET_SIZE *i, TS_FEC_PACKET_SIZE *left, TS_FEC_PACKET_SIZE , NULL);
1982         score = FFMAX3(score, dvhs_score, fec_score);
1983         sumscore += score;
1984         maxscore = FFMAX(maxscore, score);
1985     }
1986
1987     sumscore = sumscore*CHECK_COUNT/check_count;
1988     maxscore = maxscore*CHECK_COUNT/CHECK_BLOCK;
1989
1990     av_dlog(0, "TS score: %d %d\n", sumscore, maxscore);
1991
1992     if (sumscore > 6)           return AVPROBE_SCORE_MAX + sumscore - CHECK_COUNT;
1993     else if (maxscore > 6)      return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;
1994     else                        return -1;
1995 }
1996
1997 /* return the 90kHz PCR and the extension for the 27MHz PCR. return
1998    (-1) if not available */
1999 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
2000                      const uint8_t *packet)
2001 {
2002     int afc, len, flags;
2003     const uint8_t *p;
2004     unsigned int v;
2005
2006     afc = (packet[3] >> 4) & 3;
2007     if (afc <= 1)
2008         return -1;
2009     p = packet + 4;
2010     len = p[0];
2011     p++;
2012     if (len == 0)
2013         return -1;
2014     flags = *p++;
2015     len--;
2016     if (!(flags & 0x10))
2017         return -1;
2018     if (len < 6)
2019         return -1;
2020     v = AV_RB32(p);
2021     *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
2022     *ppcr_low = ((p[4] & 1) << 8) | p[5];
2023     return 0;
2024 }
2025
2026 static int parse_timestamp(int64_t *ts, const uint8_t *buf)
2027 {
2028     int afc, flags;
2029     const uint8_t *p;
2030
2031     if(!(buf[1] & 0x40)) /* must be a start packet */
2032         return -1;
2033
2034     afc = (buf[3] >> 4) & 3;
2035     p = buf + 4;
2036     if (afc == 0 || afc == 2) /* invalid or only adaption field */
2037         return -1;
2038     if (afc == 3)
2039         p += p[0] + 1;
2040     if (p >= buf + TS_PACKET_SIZE)
2041         return -1;
2042
2043     if (p[0] != 0x00 || p[1] != 0x00 || p[2] != 0x01)  /* packet_start_code_prefix */
2044         return -1;
2045
2046     flags = p[3] | 0x100; /* stream type */
2047     if (!((flags >= 0x1c0 && flags <= 0x1df) ||
2048           (flags >= 0x1e0 && flags <= 0x1ef) ||
2049           (flags == 0x1bd) || (flags == 0x1fd)))
2050         return -1;
2051
2052     flags = p[7];
2053     if ((flags & 0xc0) == 0x80) {
2054         *ts = ff_parse_pes_pts(p+9);
2055         return 0;
2056     } else if ((flags & 0xc0) == 0xc0) {
2057         *ts = ff_parse_pes_pts(p+9+5);
2058         return 0;
2059     }
2060     return -1;
2061 }
2062
2063
2064 static int mpegts_read_header(AVFormatContext *s)
2065 {
2066     MpegTSContext *ts = s->priv_data;
2067     AVIOContext *pb = s->pb;
2068     uint8_t buf[8*1024]={0};
2069     int len;
2070     int64_t pos;
2071
2072     /* read the first 8192 bytes to get packet size */
2073     pos = avio_tell(pb);
2074     len = avio_read(pb, buf, sizeof(buf));
2075     ts->raw_packet_size = get_packet_size(buf, len);
2076     if (ts->raw_packet_size <= 0) {
2077         av_log(s, AV_LOG_WARNING, "Could not detect TS packet size, defaulting to non-FEC/DVHS\n");
2078         ts->raw_packet_size = TS_PACKET_SIZE;
2079     }
2080     ts->stream = s;
2081     ts->auto_guess = 0;
2082
2083     if (s->iformat == &ff_mpegts_demuxer) {
2084         /* normal demux */
2085
2086         /* first do a scan to get all the services */
2087         /* NOTE: We attempt to seek on non-seekable files as well, as the
2088          * probe buffer usually is big enough. Only warn if the seek failed
2089          * on files where the seek should work. */
2090         if (avio_seek(pb, pos, SEEK_SET) < 0)
2091             av_log(s, pb->seekable ? AV_LOG_ERROR : AV_LOG_INFO, "Unable to seek back to the start\n");
2092
2093         mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
2094
2095         mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
2096
2097         handle_packets(ts, s->probesize / ts->raw_packet_size);
2098         /* if could not find service, enable auto_guess */
2099
2100         ts->auto_guess = 1;
2101
2102         av_dlog(ts->stream, "tuning done\n");
2103
2104         /* only flag NOHEADER if we are in file mode,
2105            in streaming mode scanning may take too long for users */
2106         if (pb->seekable)
2107             s->ctx_flags |= AVFMTCTX_NOHEADER;
2108     } else {
2109         AVStream *st;
2110         int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
2111         int64_t pcrs[2], pcr_h;
2112         int packet_count[2];
2113         uint8_t packet[TS_PACKET_SIZE];
2114         uint8_t *data;
2115
2116         /* only read packets */
2117
2118         st = avformat_new_stream(s, NULL);
2119         if (!st)
2120             goto fail;
2121         avpriv_set_pts_info(st, 60, 1, 27000000);
2122         st->codec->codec_type = AVMEDIA_TYPE_DATA;
2123         st->codec->codec_id = AV_CODEC_ID_MPEG2TS;
2124
2125         /* we iterate until we find two PCRs to estimate the bitrate */
2126         pcr_pid = -1;
2127         nb_pcrs = 0;
2128         nb_packets = 0;
2129         for(;;) {
2130             ret = read_packet(s, packet, ts->raw_packet_size, &data);
2131             if (ret < 0)
2132                 return -1;
2133             pid = AV_RB16(data + 1) & 0x1fff;
2134             if ((pcr_pid == -1 || pcr_pid == pid) &&
2135                 parse_pcr(&pcr_h, &pcr_l, data) == 0) {
2136                 finished_reading_packet(s, ts->raw_packet_size);
2137                 pcr_pid = pid;
2138                 packet_count[nb_pcrs] = nb_packets;
2139                 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
2140                 nb_pcrs++;
2141                 if (nb_pcrs >= 2)
2142                     break;
2143             } else {
2144                 finished_reading_packet(s, ts->raw_packet_size);
2145             }
2146             nb_packets++;
2147         }
2148
2149         /* NOTE1: the bitrate is computed without the FEC */
2150         /* NOTE2: it is only the bitrate of the start of the stream */
2151         ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
2152         ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
2153         s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
2154         st->codec->bit_rate = s->bit_rate;
2155         st->start_time = ts->cur_pcr;
2156         av_dlog(ts->stream, "start=%0.3f pcr=%0.3f incr=%d\n",
2157                 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
2158     }
2159
2160     avio_seek(pb, pos, SEEK_SET);
2161     return 0;
2162  fail:
2163     return -1;
2164 }
2165
2166 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
2167
2168 static int mpegts_raw_read_packet(AVFormatContext *s,
2169                                   AVPacket *pkt)
2170 {
2171     MpegTSContext *ts = s->priv_data;
2172     int ret, i;
2173     int64_t pcr_h, next_pcr_h, pos;
2174     int pcr_l, next_pcr_l;
2175     uint8_t pcr_buf[12];
2176     uint8_t *data;
2177
2178     if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
2179         return AVERROR(ENOMEM);
2180     pkt->pos= avio_tell(s->pb);
2181     ret = read_packet(s, pkt->data, ts->raw_packet_size, &data);
2182     if (ret < 0) {
2183         av_free_packet(pkt);
2184         return ret;
2185     }
2186     if (data != pkt->data)
2187         memcpy(pkt->data, data, ts->raw_packet_size);
2188     finished_reading_packet(s, ts->raw_packet_size);
2189     if (ts->mpeg2ts_compute_pcr) {
2190         /* compute exact PCR for each packet */
2191         if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
2192             /* we read the next PCR (XXX: optimize it by using a bigger buffer */
2193             pos = avio_tell(s->pb);
2194             for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
2195                 avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
2196                 avio_read(s->pb, pcr_buf, 12);
2197                 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
2198                     /* XXX: not precise enough */
2199                     ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
2200                         (i + 1);
2201                     break;
2202                 }
2203             }
2204             avio_seek(s->pb, pos, SEEK_SET);
2205             /* no next PCR found: we use previous increment */
2206             ts->cur_pcr = pcr_h * 300 + pcr_l;
2207         }
2208         pkt->pts = ts->cur_pcr;
2209         pkt->duration = ts->pcr_incr;
2210         ts->cur_pcr += ts->pcr_incr;
2211     }
2212     pkt->stream_index = 0;
2213     return 0;
2214 }
2215
2216 static int mpegts_read_packet(AVFormatContext *s,
2217                               AVPacket *pkt)
2218 {
2219     MpegTSContext *ts = s->priv_data;
2220     int ret, i;
2221
2222     pkt->size = -1;
2223     ts->pkt = pkt;
2224     ts->pkt->data = NULL;
2225
2226     ret = handle_packets(ts, 0);
2227     if (ret < 0) {
2228         av_free_packet(ts->pkt);
2229         /* flush pes data left */
2230         for (i = 0; i < NB_PID_MAX; i++) {
2231             if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
2232                 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
2233                 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
2234                     new_pes_packet(pes, pkt);
2235                     pes->state = MPEGTS_SKIP;
2236                     ret = 0;
2237                     break;
2238                 }
2239             }
2240         }
2241     }
2242
2243     if (!ret && pkt->size < 0)
2244         ret = AVERROR(EINTR);
2245     return ret;
2246 }
2247
2248 static void mpegts_free(MpegTSContext *ts)
2249 {
2250     int i;
2251
2252     clear_programs(ts);
2253
2254     for(i=0;i<NB_PID_MAX;i++)
2255         if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
2256 }
2257
2258 static int mpegts_read_close(AVFormatContext *s)
2259 {
2260     MpegTSContext *ts = s->priv_data;
2261     mpegts_free(ts);
2262     return 0;
2263 }
2264
2265 static av_unused int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
2266                               int64_t *ppos, int64_t pos_limit)
2267 {
2268     MpegTSContext *ts = s->priv_data;
2269     int64_t pos, timestamp;
2270     uint8_t buf[TS_PACKET_SIZE];
2271     int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
2272     int pid = ((PESContext*)s->streams[stream_index]->priv_data)->pid;
2273     pos = ((*ppos  + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
2274     while(pos < pos_limit) {
2275         if (avio_seek(s->pb, pos, SEEK_SET) < 0)
2276             return AV_NOPTS_VALUE;
2277         if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
2278             return AV_NOPTS_VALUE;
2279         if (buf[0] != 0x47) {
2280             if (mpegts_resync(s) < 0)
2281                 return AV_NOPTS_VALUE;
2282             pos = avio_tell(s->pb);
2283             continue;
2284         }
2285         if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
2286             parse_pcr(&timestamp, &pcr_l, buf) == 0) {
2287             *ppos = pos;
2288             return timestamp;
2289         }
2290         if ((pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pid) &&
2291             parse_timestamp(&timestamp, buf) == 0) {
2292             *ppos = pos;
2293             return timestamp;
2294         }
2295         pos += ts->raw_packet_size;
2296     }
2297
2298     return AV_NOPTS_VALUE;
2299 }
2300
2301 static int64_t mpegts_get_dts(AVFormatContext *s, int stream_index,
2302                               int64_t *ppos, int64_t pos_limit)
2303 {
2304     MpegTSContext *ts = s->priv_data;
2305     int64_t pos;
2306     pos = ((*ppos  + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
2307     ff_read_frame_flush(s);
2308     if (avio_seek(s->pb, pos, SEEK_SET) < 0)
2309         return AV_NOPTS_VALUE;
2310     while(pos < pos_limit) {
2311         int ret;
2312         AVPacket pkt;
2313         av_init_packet(&pkt);
2314         ret= av_read_frame(s, &pkt);
2315         if(ret < 0)
2316             return AV_NOPTS_VALUE;
2317         av_free_packet(&pkt);
2318         if(pkt.dts != AV_NOPTS_VALUE && pkt.pos >= 0){
2319             ff_reduce_index(s, pkt.stream_index);
2320             av_add_index_entry(s->streams[pkt.stream_index], pkt.pos, pkt.dts, 0, 0, AVINDEX_KEYFRAME /* FIXME keyframe? */);
2321             if(pkt.stream_index == stream_index){
2322                 *ppos= pkt.pos;
2323                 return pkt.dts;
2324             }
2325         }
2326         pos = pkt.pos;
2327     }
2328
2329     return AV_NOPTS_VALUE;
2330 }
2331
2332 /**************************************************************/
2333 /* parsing functions - called from other demuxers such as RTP */
2334
2335 MpegTSContext *ff_mpegts_parse_open(AVFormatContext *s)
2336 {
2337     MpegTSContext *ts;
2338
2339     ts = av_mallocz(sizeof(MpegTSContext));
2340     if (!ts)
2341         return NULL;
2342     /* no stream case, currently used by RTP */
2343     ts->raw_packet_size = TS_PACKET_SIZE;
2344     ts->stream = s;
2345     ts->auto_guess = 1;
2346     mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
2347     mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
2348
2349     return ts;
2350 }
2351
2352 /* return the consumed length if a packet was output, or -1 if no
2353    packet is output */
2354 int ff_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
2355                         const uint8_t *buf, int len)
2356 {
2357     int len1;
2358
2359     len1 = len;
2360     ts->pkt = pkt;
2361     for(;;) {
2362         ts->stop_parse = 0;
2363         if (len < TS_PACKET_SIZE)
2364             return -1;
2365         if (buf[0] != 0x47) {
2366             buf++;
2367             len--;
2368         } else {
2369             handle_packet(ts, buf);
2370             buf += TS_PACKET_SIZE;
2371             len -= TS_PACKET_SIZE;
2372             if (ts->stop_parse == 1)
2373                 break;
2374         }
2375     }
2376     return len1 - len;
2377 }
2378
2379 void ff_mpegts_parse_close(MpegTSContext *ts)
2380 {
2381     mpegts_free(ts);
2382     av_free(ts);
2383 }
2384
2385 AVInputFormat ff_mpegts_demuxer = {
2386     .name           = "mpegts",
2387     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
2388     .priv_data_size = sizeof(MpegTSContext),
2389     .read_probe     = mpegts_probe,
2390     .read_header    = mpegts_read_header,
2391     .read_packet    = mpegts_read_packet,
2392     .read_close     = mpegts_read_close,
2393     .read_timestamp = mpegts_get_pcr,
2394     .flags          = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
2395 };
2396
2397 AVInputFormat ff_mpegtsraw_demuxer = {
2398     .name           = "mpegtsraw",
2399     .long_name      = NULL_IF_CONFIG_SMALL("raw MPEG-TS (MPEG-2 Transport Stream)"),
2400     .priv_data_size = sizeof(MpegTSContext),
2401     .read_header    = mpegts_read_header,
2402     .read_packet    = mpegts_raw_read_packet,
2403     .read_close     = mpegts_read_close,
2404     .read_timestamp = mpegts_get_pcr,
2405     .flags          = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
2406     .priv_class     = &mpegtsraw_class,
2407 };