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