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