libavformat/mpegts.c
fe9cf0d4
 /*
7fbde343
  * MPEG2 transport stream (aka DVB) demuxer
406792e7
  * Copyright (c) 2002-2003 Fabrice Bellard
fe9cf0d4
  *
b78e7197
  * This file is part of FFmpeg.
  *
  * FFmpeg is free software; you can redistribute it and/or
19720f15
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
b78e7197
  * version 2.1 of the License, or (at your option) any later version.
fe9cf0d4
  *
b78e7197
  * FFmpeg is distributed in the hope that it will be useful,
fe9cf0d4
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19720f15
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
fe9cf0d4
  *
19720f15
  * You should have received a copy of the GNU Lesser General Public
b78e7197
  * License along with FFmpeg; if not, write to the Free Software
5509bffa
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
fe9cf0d4
  */
245976da
 
 #include "libavutil/crc.h"
6a5d31ac
 #include "libavutil/intreadwrite.h"
fe9cf0d4
 #include "avformat.h"
5dbafeb7
 #include "mpegts.h"
ecfb51d1
 #include "internal.h"
fe9cf0d4
 
5dbafeb7
 //#define DEBUG_SI
27f388aa
 //#define DEBUG_SEEK
5dbafeb7
 
 /* 1.0 second at 24Mbit/s */
fc48fe84
 #define MAX_SCAN_PACKETS 32000
 
 /* maximum size in which we look for synchronisation if
    synchronisation is lost */
 #define MAX_RESYNC_SIZE 4096
a45b40c4
 #define REGISTRATION_DESCRIPTOR 5
5dbafeb7
 
c6ec28b1
 typedef struct PESContext PESContext;
 
dbf6b678
 static PESContext* add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid, int stream_type);
c6ec28b1
 static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code);
5dbafeb7
 
 enum MpegTSFilterType {
     MPEGTS_PES,
     MPEGTS_SECTION,
fe9cf0d4
 };
 
b474d1f3
 typedef struct MpegTSFilter MpegTSFilter;
 
4c6b49bf
 typedef void PESCallback(MpegTSFilter *f, const uint8_t *buf, int len, int is_start, int64_t pos);
fe9cf0d4
 
5dbafeb7
 typedef struct MpegTSPESFilter {
     PESCallback *pes_cb;
     void *opaque;
 } MpegTSPESFilter;
 
b474d1f3
 typedef void SectionCallback(MpegTSFilter *f, const uint8_t *buf, int len);
5dbafeb7
 
 typedef void SetServiceCallback(void *opaque, int ret);
 
 typedef struct MpegTSSectionFilter {
     int section_index;
     int section_h_size;
     uint8_t *section_buf;
72e043dd
     unsigned int check_crc:1;
     unsigned int end_of_section_reached:1;
5dbafeb7
     SectionCallback *section_cb;
     void *opaque;
 } MpegTSSectionFilter;
 
b474d1f3
 struct MpegTSFilter {
fe9cf0d4
     int pid;
     int last_cc; /* last cc code (-1 if first packet) */
5dbafeb7
     enum MpegTSFilterType type;
     union {
         MpegTSPESFilter pes_filter;
         MpegTSSectionFilter section_filter;
     } u;
b474d1f3
 };
5dbafeb7
 
172d1171
 #define MAX_PIDS_PER_PROGRAM 64
8c39a758
 struct Program {
172d1171
     unsigned int id; //program id/service id
     unsigned int nb_pids;
     unsigned int pids[MAX_PIDS_PER_PROGRAM];
8c39a758
 };
172d1171
 
b45a7a18
 struct MpegTSContext {
5dbafeb7
     /* user data */
     AVFormatContext *stream;
e995cfca
     /** raw packet size, including FEC if present            */
     int raw_packet_size;
5fd63f3c
 
     int pos47;
 
e995cfca
     /** if true, all pids are analyzed to find streams       */
     int auto_guess;
5dbafeb7
 
e995cfca
     /** compute exact PCR for each transport stream packet   */
     int mpeg2ts_compute_pcr;
b45a7a18
 
e995cfca
     int64_t cur_pcr;    /**< used to estimate the exact PCR  */
     int pcr_incr;       /**< used to estimate the exact PCR  */
115329f1
 
5dbafeb7
     /* data needed to handle file based ts */
e995cfca
     /** stop parsing loop                                    */
     int stop_parse;
     /** packet containing Audio/Video data                   */
     AVPacket *pkt;
5dbafeb7
 
     /******************************************/
     /* private mpegts data */
     /* scan context */
172d1171
     /** structure to keep track of Program->pids mapping     */
     unsigned int nb_prg;
8c39a758
     struct Program *prg;
115329f1
 
5dbafeb7
 
e995cfca
     /** filters for various streams specified by PMT + for the PAT and PMT */
5dbafeb7
     MpegTSFilter *pids[NB_PID_MAX];
b45a7a18
 };
fe9cf0d4
 
ecc31d1d
 /* TS stream handling */
 
 enum MpegTSState {
     MPEGTS_HEADER = 0,
     MPEGTS_PESHEADER_FILL,
     MPEGTS_PAYLOAD,
     MPEGTS_SKIP,
 };
 
 /* enough for PES header + length */
 #define PES_START_SIZE 9
 #define MAX_PES_HEADER_SIZE (9 + 255)
 
 struct PESContext {
     int pid;
dbf6b678
     int pcr_pid; /**< if -1 then all packets containing PCR are considered */
ecc31d1d
     int stream_type;
     MpegTSContext *ts;
     AVFormatContext *stream;
     AVStream *st;
     enum MpegTSState state;
     /* used to get the format */
     int data_index;
     int total_size;
     int pes_header_size;
     int64_t pts, dts;
4c6b49bf
     int64_t ts_packet_pos; /**< position of first TS packet of this PES packet */
ecc31d1d
     uint8_t header[MAX_PES_HEADER_SIZE];
 };
 
6369638b
 extern AVInputFormat mpegts_demuxer;
 
172d1171
 static void clear_program(MpegTSContext *ts, unsigned int programid)
 {
     int i;
 
     for(i=0; i<ts->nb_prg; i++)
         if(ts->prg[i].id == programid)
             ts->prg[i].nb_pids = 0;
 }
 
 static void clear_programs(MpegTSContext *ts)
 {
     av_freep(&ts->prg);
     ts->nb_prg=0;
 }
 
 static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
 {
8c39a758
     struct Program *p;
     void *tmp = av_realloc(ts->prg, (ts->nb_prg+1)*sizeof(struct Program));
172d1171
     if(!tmp)
         return;
     ts->prg = tmp;
     p = &ts->prg[ts->nb_prg];
     p->id = programid;
     p->nb_pids = 0;
     ts->nb_prg++;
 }
 
 static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid, unsigned int pid)
 {
     int i;
8c39a758
     struct Program *p = NULL;
172d1171
     for(i=0; i<ts->nb_prg; i++) {
         if(ts->prg[i].id == programid) {
             p = &ts->prg[i];
             break;
         }
     }
     if(!p)
         return;
 
     if(p->nb_pids >= MAX_PIDS_PER_PROGRAM)
         return;
     p->pids[p->nb_pids++] = pid;
 }
 
 /**
  * \brief discard_pid() decides if the pid is to be discarded according
  *                      to caller's programs selection
  * \param ts    : - TS context
  * \param pid   : - pid
  * \return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
  *         0 otherwise
  */
 static int discard_pid(MpegTSContext *ts, unsigned int pid)
 {
     int i, j, k;
     int used = 0, discarded = 0;
8c39a758
     struct Program *p;
172d1171
     for(i=0; i<ts->nb_prg; i++) {
         p = &ts->prg[i];
         for(j=0; j<p->nb_pids; j++) {
             if(p->pids[j] != pid)
                 continue;
             //is program with id p->id set to be discarded?
             for(k=0; k<ts->stream->nb_programs; k++) {
                 if(ts->stream->programs[k]->id == p->id) {
                     if(ts->stream->programs[k]->discard == AVDISCARD_ALL)
                         discarded++;
                     else
                         used++;
                 }
             }
         }
     }
 
ccd425e7
     return !used && discarded;
172d1171
 }
 
e995cfca
 /**
  *  Assembles PES packets out of TS packets, and then calls the "section_cb"
  *  function when they are complete.
  */
5dbafeb7
 static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
                                const uint8_t *buf, int buf_size, int is_start)
 {
     MpegTSSectionFilter *tss = &tss1->u.section_filter;
     int len;
115329f1
 
5dbafeb7
     if (is_start) {
         memcpy(tss->section_buf, buf, buf_size);
         tss->section_index = buf_size;
         tss->section_h_size = -1;
         tss->end_of_section_reached = 0;
     } else {
         if (tss->end_of_section_reached)
             return;
         len = 4096 - tss->section_index;
         if (buf_size < len)
             len = buf_size;
         memcpy(tss->section_buf + tss->section_index, buf, len);
         tss->section_index += len;
     }
 
     /* compute section length if possible */
     if (tss->section_h_size == -1 && tss->section_index >= 3) {
80fb8234
         len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
5dbafeb7
         if (len > 4096)
             return;
         tss->section_h_size = len;
     }
 
     if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
         tss->end_of_section_reached = 1;
27bb1ed3
         if (!tss->check_crc ||
3abe5fbd
             av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1,
                    tss->section_buf, tss->section_h_size) == 0)
4d9a577e
             tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
5dbafeb7
     }
 }
 
7b49ce2e
 static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
5dbafeb7
                                          SectionCallback *section_cb, void *opaque,
                                          int check_crc)
 
 {
     MpegTSFilter *filter;
     MpegTSSectionFilter *sec;
115329f1
 
b45a7a18
 #ifdef DEBUG_SI
f0ee3ea6
     av_log(ts->stream, AV_LOG_DEBUG, "Filter: pid=0x%x\n", pid);
b45a7a18
 #endif
5dbafeb7
     if (pid >= NB_PID_MAX || ts->pids[pid])
         return NULL;
     filter = av_mallocz(sizeof(MpegTSFilter));
115329f1
     if (!filter)
5dbafeb7
         return NULL;
     ts->pids[pid] = filter;
     filter->type = MPEGTS_SECTION;
     filter->pid = pid;
     filter->last_cc = -1;
     sec = &filter->u.section_filter;
     sec->section_cb = section_cb;
     sec->opaque = opaque;
     sec->section_buf = av_malloc(MAX_SECTION_SIZE);
     sec->check_crc = check_crc;
     if (!sec->section_buf) {
         av_free(filter);
         return NULL;
     }
     return filter;
 }
 
7b49ce2e
 static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
5dbafeb7
                                      PESCallback *pes_cb,
                                      void *opaque)
 {
     MpegTSFilter *filter;
     MpegTSPESFilter *pes;
 
     if (pid >= NB_PID_MAX || ts->pids[pid])
         return NULL;
     filter = av_mallocz(sizeof(MpegTSFilter));
115329f1
     if (!filter)
5dbafeb7
         return NULL;
     ts->pids[pid] = filter;
     filter->type = MPEGTS_PES;
     filter->pid = pid;
     filter->last_cc = -1;
     pes = &filter->u.pes_filter;
     pes->pes_cb = pes_cb;
     pes->opaque = opaque;
     return filter;
 }
 
7b49ce2e
 static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
5dbafeb7
 {
     int pid;
 
     pid = filter->pid;
     if (filter->type == MPEGTS_SECTION)
         av_freep(&filter->u.section_filter.section_buf);
dcd913d9
     else if (filter->type == MPEGTS_PES) {
         /* referenced private data will be freed later in
          * av_close_input_stream */
         if (!((PESContext *)filter->u.pes_filter.opaque)->st) {
             av_freep(&filter->u.pes_filter.opaque);
         }
     }
ec7d0d2e
 
5dbafeb7
     av_free(filter);
     ts->pids[pid] = NULL;
 }
 
a0b8f70c
 static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
     int stat[packet_size];
     int i;
     int x=0;
     int best_score=0;
 
     memset(stat, 0, packet_size*sizeof(int));
 
c6002ea1
     for(x=i=0; i<size-3; i++){
         if(buf[i] == 0x47 && !(buf[i+1] & 0x80) && (buf[i+3] & 0x30)){
a0b8f70c
             stat[x]++;
             if(stat[x] > best_score){
                 best_score= stat[x];
                 if(index) *index= x;
             }
         }
 
         x++;
         if(x == packet_size) x= 0;
     }
 
     return best_score;
 }
 
fe9cf0d4
 /* autodetect fec presence. Must have at least 1024 bytes  */
5dbafeb7
 static int get_packet_size(const uint8_t *buf, int size)
fe9cf0d4
 {
5d4d67e0
     int score, fec_score, dvhs_score;
fe9cf0d4
 
     if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
         return -1;
115329f1
 
a0b8f70c
     score    = analyze(buf, size, TS_PACKET_SIZE, NULL);
5d4d67e0
     dvhs_score    = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
a0b8f70c
     fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
5d4d67e0
 //    av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
115329f1
 
5d4d67e0
     if     (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
     else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
     else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
a0b8f70c
     else                       return -1;
fe9cf0d4
 }
 
5dbafeb7
 typedef struct SectionHeader {
     uint8_t tid;
     uint16_t id;
     uint8_t version;
     uint8_t sec_num;
     uint8_t last_sec_num;
 } SectionHeader;
 
 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
fe9cf0d4
 {
5dbafeb7
     const uint8_t *p;
     int c;
 
     p = *pp;
     if (p >= p_end)
         return -1;
     c = *p++;
     *pp = p;
     return c;
fe9cf0d4
 }
 
5dbafeb7
 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
 {
     const uint8_t *p;
     int c;
 
     p = *pp;
     if ((p + 1) >= p_end)
         return -1;
80fb8234
     c = AV_RB16(p);
5dbafeb7
     p += 2;
     *pp = p;
     return c;
 }
 
 /* read and allocate a DVB string preceeded by its length */
 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
fe9cf0d4
 {
     int len;
5dbafeb7
     const uint8_t *p;
     char *str;
fe9cf0d4
 
5dbafeb7
     p = *pp;
     len = get8(&p, p_end);
     if (len < 0)
         return NULL;
     if ((p + len) > p_end)
         return NULL;
     str = av_malloc(len + 1);
     if (!str)
         return NULL;
     memcpy(str, p, len);
     str[len] = '\0';
     p += len;
     *pp = p;
     return str;
 }
 
115329f1
 static int parse_section_header(SectionHeader *h,
5dbafeb7
                                 const uint8_t **pp, const uint8_t *p_end)
 {
     int val;
 
     val = get8(pp, p_end);
     if (val < 0)
         return -1;
     h->tid = val;
     *pp += 2;
     val = get16(pp, p_end);
     if (val < 0)
         return -1;
     h->id = val;
     val = get8(pp, p_end);
     if (val < 0)
         return -1;
     h->version = (val >> 1) & 0x1f;
     val = get8(pp, p_end);
     if (val < 0)
         return -1;
     h->sec_num = val;
     val = get8(pp, p_end);
     if (val < 0)
         return -1;
     h->last_sec_num = val;
fe9cf0d4
     return 0;
5dbafeb7
 }
 
 
4d9a577e
 static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
5dbafeb7
 {
4d9a577e
     MpegTSContext *ts = filter->u.section_filter.opaque;
5dbafeb7
     SectionHeader h1, *h = &h1;
c6ec28b1
     PESContext *pes;
     AVStream *st;
     const uint8_t *p, *p_end, *desc_list_end, *desc_end;
     int program_info_length, pcr_pid, pid, stream_type;
     int desc_list_len, desc_len, desc_tag;
79396ac6
     int comp_page = 0, anc_page = 0; /* initialize to kill warnings */
828bb5f1
     char language[4] = {0}; /* initialize to kill warnings */
a45b40c4
     int has_hdmv_descr = 0;
f4bba201
     int has_dirac_descr = 0;
115329f1
 
5dbafeb7
 #ifdef DEBUG_SI
f0ee3ea6
     av_log(ts->stream, AV_LOG_DEBUG, "PMT: len %i\n", section_len);
750f0e1f
     av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
5dbafeb7
 #endif
     p_end = section + section_len - 4;
     p = section;
     if (parse_section_header(h, &p, p_end) < 0)
         return;
 #ifdef DEBUG_SI
f0ee3ea6
     av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x sec_num=%d/%d\n",
2ddb79be
            h->id, h->sec_num, h->last_sec_num);
5dbafeb7
 #endif
90d13e30
     if (h->tid != PMT_TID)
5dbafeb7
         return;
 
172d1171
     clear_program(ts, h->id);
5dbafeb7
     pcr_pid = get16(&p, p_end) & 0x1fff;
     if (pcr_pid < 0)
         return;
172d1171
     add_pid_to_pmt(ts, h->id, pcr_pid);
5dbafeb7
 #ifdef DEBUG_SI
f0ee3ea6
     av_log(ts->stream, AV_LOG_DEBUG, "pcr_pid=0x%x\n", pcr_pid);
5dbafeb7
 #endif
     program_info_length = get16(&p, p_end) & 0xfff;
     if (program_info_length < 0)
         return;
a45b40c4
     while(program_info_length >= 2) {
         uint8_t tag, len;
         tag = get8(&p, p_end);
         len = get8(&p, p_end);
         if(len > program_info_length - 2)
             //something else is broken, exit the program_descriptors_loop
             break;
         program_info_length -= len + 2;
         if(tag == REGISTRATION_DESCRIPTOR && len >= 4) {
             uint8_t bytes[4];
             bytes[0] = get8(&p, p_end);
             bytes[1] = get8(&p, p_end);
             bytes[2] = get8(&p, p_end);
             bytes[3] = get8(&p, p_end);
             len -= 4;
             if(bytes[0] == 'H' && bytes[1] == 'D' &&
                bytes[2] == 'M' && bytes[3] == 'V')
                 has_hdmv_descr = 1;
         }
         p += len;
     }
5dbafeb7
     p += program_info_length;
     if (p >= p_end)
         return;
     for(;;) {
c6ec28b1
         language[0] = 0;
         st = 0;
5dbafeb7
         stream_type = get8(&p, p_end);
         if (stream_type < 0)
             break;
         pid = get16(&p, p_end) & 0x1fff;
         if (pid < 0)
             break;
c6ec28b1
         desc_list_len = get16(&p, p_end) & 0xfff;
         if (desc_list_len < 0)
             break;
         desc_list_end = p + desc_list_len;
         if (desc_list_end > p_end)
5dbafeb7
             break;
c6ec28b1
         for(;;) {
             desc_tag = get8(&p, desc_list_end);
             if (desc_tag < 0)
                 break;
2eb1a65d
             if (stream_type == STREAM_TYPE_PRIVATE_DATA) {
                 if((desc_tag == 0x6A) || (desc_tag == 0x7A)) {
9d9b432a
                     /*assume DVB AC-3 Audio*/
                     stream_type = STREAM_TYPE_AUDIO_AC3;
2eb1a65d
                 } else if(desc_tag == 0x7B) {
                     /* DVB DTS audio */
                     stream_type = STREAM_TYPE_AUDIO_DTS;
                 }
9d9b432a
             }
c6ec28b1
             desc_len = get8(&p, desc_list_end);
             desc_end = p + desc_len;
             if (desc_end > desc_list_end)
                 break;
 #ifdef DEBUG_SI
f0ee3ea6
             av_log(ts->stream, AV_LOG_DEBUG, "tag: 0x%02x len=%d\n",
2ddb79be
                    desc_tag, desc_len);
c6ec28b1
 #endif
             switch(desc_tag) {
             case DVB_SUBT_DESCID:
                 if (stream_type == STREAM_TYPE_PRIVATE_DATA)
                     stream_type = STREAM_TYPE_SUBTITLE_DVB;
 
                 language[0] = get8(&p, desc_end);
                 language[1] = get8(&p, desc_end);
                 language[2] = get8(&p, desc_end);
                 language[3] = 0;
                 get8(&p, desc_end);
                 comp_page = get16(&p, desc_end);
                 anc_page = get16(&p, desc_end);
 
                 break;
             case 0x0a: /* ISO 639 language descriptor */
                 language[0] = get8(&p, desc_end);
                 language[1] = get8(&p, desc_end);
                 language[2] = get8(&p, desc_end);
                 language[3] = 0;
                 break;
f4bba201
             case REGISTRATION_DESCRIPTOR: /*MPEG-2 Registration descriptor */
                 {
                     uint8_t bytes[4];
                     bytes[0] = get8(&p, desc_end);
                     bytes[1] = get8(&p, desc_end);
                     bytes[2] = get8(&p, desc_end);
                     bytes[3] = get8(&p, desc_end);
                     if(bytes[0] == 'd' && bytes[1] == 'r' &&
                        bytes[2] == 'a' && bytes[3] == 'c')
                         has_dirac_descr = 1;
                     break;
                 }
c6ec28b1
             default:
                 break;
             }
             p = desc_end;
         }
         p = desc_list_end;
5dbafeb7
 
 #ifdef DEBUG_SI
f0ee3ea6
         av_log(ts->stream, AV_LOG_DEBUG, "stream_type=%d pid=0x%x\n",
2ddb79be
                stream_type, pid);
5dbafeb7
 #endif
 
         /* now create ffmpeg stream */
         switch(stream_type) {
ce34182d
         case STREAM_TYPE_AUDIO_MPEG1:
         case STREAM_TYPE_AUDIO_MPEG2:
         case STREAM_TYPE_VIDEO_MPEG1:
         case STREAM_TYPE_VIDEO_MPEG2:
278de475
         case STREAM_TYPE_VIDEO_MPEG4:
         case STREAM_TYPE_VIDEO_H264:
cf10ee18
         case STREAM_TYPE_VIDEO_VC1:
f4bba201
         case STREAM_TYPE_VIDEO_DIRAC:
278de475
         case STREAM_TYPE_AUDIO_AAC:
ec23a472
         case STREAM_TYPE_AUDIO_AC3:
23c99253
         case STREAM_TYPE_AUDIO_DTS:
a45b40c4
         case STREAM_TYPE_AUDIO_HDMV_DTS:
c6ec28b1
         case STREAM_TYPE_SUBTITLE_DVB:
f4bba201
             if((stream_type == STREAM_TYPE_AUDIO_HDMV_DTS && !has_hdmv_descr)
             || (stream_type == STREAM_TYPE_VIDEO_DIRAC    && !has_dirac_descr))
a45b40c4
                 break;
28af284c
             if(ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES){
90d13e30
                 pes= ts->pids[pid]->u.pes_filter.opaque;
                 st= pes->st;
             }else{
28af284c
                 if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
dbf6b678
                 pes = add_pes_stream(ts, pid, pcr_pid, stream_type);
28f03d04
                 if (pes)
                     st = new_pes_av_stream(pes, 0);
90d13e30
             }
172d1171
             add_pid_to_pmt(ts, h->id, pid);
aa237f45
             if(st)
                 av_program_add_stream_index(ts->stream, h->id, st->index);
04ec18b8
             break;
5dbafeb7
         default:
             /* we ignore the other streams */
             break;
         }
c6ec28b1
 
         if (st) {
             if (language[0] != 0) {
08681191
                 av_metadata_set(&st->metadata, "language", language);
c6ec28b1
             }
 
             if (stream_type == STREAM_TYPE_SUBTITLE_DVB) {
01f4895c
                 st->codec->sub_id = (anc_page << 16) | comp_page;
c6ec28b1
             }
         }
5dbafeb7
     }
     /* all parameters are there */
90d13e30
     ts->stop_parse++;
4d9a577e
     mpegts_close_filter(ts, filter);
5dbafeb7
 }
 
4d9a577e
 static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
5dbafeb7
 {
4d9a577e
     MpegTSContext *ts = filter->u.section_filter.opaque;
5dbafeb7
     SectionHeader h1, *h = &h1;
     const uint8_t *p, *p_end;
     int sid, pmt_pid;
 
 #ifdef DEBUG_SI
f0ee3ea6
     av_log(ts->stream, AV_LOG_DEBUG, "PAT:\n");
750f0e1f
     av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
5dbafeb7
 #endif
     p_end = section + section_len - 4;
     p = section;
     if (parse_section_header(h, &p, p_end) < 0)
         return;
     if (h->tid != PAT_TID)
         return;
 
172d1171
     clear_programs(ts);
5dbafeb7
     for(;;) {
         sid = get16(&p, p_end);
         if (sid < 0)
             break;
         pmt_pid = get16(&p, p_end) & 0x1fff;
         if (pmt_pid < 0)
             break;
 #ifdef DEBUG_SI
f0ee3ea6
         av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
5dbafeb7
 #endif
         if (sid == 0x0000) {
             /* NIT info */
         } else {
1d257254
             av_new_program(ts->stream, sid);
90d13e30
             ts->stop_parse--;
28f03d04
             mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
172d1171
             add_pat_entry(ts, sid);
             add_pid_to_pmt(ts, sid, 0); //add pat pid to program
             add_pid_to_pmt(ts, sid, pmt_pid);
5dbafeb7
         }
     }
     /* not found */
90d13e30
     ts->stop_parse++;
5dbafeb7
 
4d9a577e
     mpegts_close_filter(ts, filter);
5dbafeb7
 }
 
90d13e30
 static void mpegts_set_service(MpegTSContext *ts)
5dbafeb7
 {
4d9a577e
     mpegts_open_section_filter(ts, PAT_PID,
5dbafeb7
                                                 pat_cb, ts, 1);
 }
 
4d9a577e
 static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
5dbafeb7
 {
4d9a577e
     MpegTSContext *ts = filter->u.section_filter.opaque;
5dbafeb7
     SectionHeader h1, *h = &h1;
     const uint8_t *p, *p_end, *desc_list_end, *desc_end;
     int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
     char *name, *provider_name;
 
 #ifdef DEBUG_SI
f0ee3ea6
     av_log(ts->stream, AV_LOG_DEBUG, "SDT:\n");
750f0e1f
     av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
5dbafeb7
 #endif
 
     p_end = section + section_len - 4;
     p = section;
     if (parse_section_header(h, &p, p_end) < 0)
         return;
     if (h->tid != SDT_TID)
         return;
     onid = get16(&p, p_end);
     if (onid < 0)
         return;
     val = get8(&p, p_end);
     if (val < 0)
         return;
     for(;;) {
         sid = get16(&p, p_end);
         if (sid < 0)
             break;
         val = get8(&p, p_end);
         if (val < 0)
             break;
         desc_list_len = get16(&p, p_end) & 0xfff;
         if (desc_list_len < 0)
             break;
         desc_list_end = p + desc_list_len;
         if (desc_list_end > p_end)
             break;
         for(;;) {
             desc_tag = get8(&p, desc_list_end);
             if (desc_tag < 0)
                 break;
             desc_len = get8(&p, desc_list_end);
             desc_end = p + desc_len;
             if (desc_end > desc_list_end)
                 break;
 #ifdef DEBUG_SI
f0ee3ea6
             av_log(ts->stream, AV_LOG_DEBUG, "tag: 0x%02x len=%d\n",
2ddb79be
                    desc_tag, desc_len);
5dbafeb7
 #endif
             switch(desc_tag) {
             case 0x48:
                 service_type = get8(&p, p_end);
                 if (service_type < 0)
                     break;
                 provider_name = getstr8(&p, p_end);
                 if (!provider_name)
                     break;
                 name = getstr8(&p, p_end);
1d257254
                 if (name) {
                     AVProgram *program = av_new_program(ts->stream, sid);
08681191
                     if(program) {
                         av_metadata_set(&program->metadata, "name", name);
                         av_metadata_set(&program->metadata, "provider_name", provider_name);
                     }
1d257254
                 }
81d5ae6d
                 av_free(name);
                 av_free(provider_name);
5dbafeb7
                 break;
             default:
                 break;
             }
             p = desc_end;
         }
         p = desc_list_end;
     }
 }
 
fc48fe84
 /* scan services in a transport stream by looking at the SDT */
7b49ce2e
 static void mpegts_scan_sdt(MpegTSContext *ts)
5dbafeb7
 {
37dfd633
     mpegts_open_section_filter(ts, SDT_PID,
5dbafeb7
                                                 sdt_cb, ts, 1);
 }
 
 static int64_t get_pts(const uint8_t *p)
 {
80fb8234
     int64_t pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
     pts |= (AV_RB16(p + 1) >> 1) << 15;
     pts |=  AV_RB16(p + 3) >> 1;
5dbafeb7
     return pts;
fe9cf0d4
 }
 
 /* return non zero if a packet could be constructed */
4d9a577e
 static void mpegts_push_data(MpegTSFilter *filter,
4c6b49bf
                              const uint8_t *buf, int buf_size, int is_start,
                              int64_t pos)
fe9cf0d4
 {
4d9a577e
     PESContext *pes = filter->u.pes_filter.opaque;
b45a7a18
     MpegTSContext *ts = pes->ts;
5dbafeb7
     const uint8_t *p;
c6ec28b1
     int len, code;
115329f1
 
b2292194
     if(!ts->pkt)
         return;
 
fe9cf0d4
     if (is_start) {
5dbafeb7
         pes->state = MPEGTS_HEADER;
         pes->data_index = 0;
4c6b49bf
         pes->ts_packet_pos = pos;
fe9cf0d4
     }
     p = buf;
     while (buf_size > 0) {
5dbafeb7
         switch(pes->state) {
fe9cf0d4
         case MPEGTS_HEADER:
5dbafeb7
             len = PES_START_SIZE - pes->data_index;
             if (len > buf_size)
                 len = buf_size;
             memcpy(pes->header + pes->data_index, p, len);
             pes->data_index += len;
fe9cf0d4
             p += len;
             buf_size -= len;
5dbafeb7
             if (pes->data_index == PES_START_SIZE) {
fe9cf0d4
                 /* we got all the PES or section header. We can now
                    decide */
 #if 0
750f0e1f
                 av_hex_dump_log(pes->stream, AV_LOG_DEBUG, pes->header, pes->data_index);
fe9cf0d4
 #endif
5dbafeb7
                 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
                     pes->header[2] == 0x01) {
fe9cf0d4
                     /* it must be an mpeg2 PES stream */
5dbafeb7
                     code = pes->header[3] | 0x100;
fe9cf0d4
                     if (!((code >= 0x1c0 && code <= 0x1df) ||
ec23a472
                           (code >= 0x1e0 && code <= 0x1ef) ||
cf10ee18
                           (code == 0x1bd) || (code == 0x1fd)))
fe9cf0d4
                         goto skip;
5dbafeb7
                     if (!pes->st) {
fe9cf0d4
                         /* allocate stream */
c6ec28b1
                         new_pes_av_stream(pes, code);
fe9cf0d4
                     }
5dbafeb7
                     pes->state = MPEGTS_PESHEADER_FILL;
80fb8234
                     pes->total_size = AV_RB16(pes->header + 4);
5dbafeb7
                     /* NOTE: a zero total size means the PES size is
                        unbounded */
                     if (pes->total_size)
                         pes->total_size += 6;
                     pes->pes_header_size = pes->header[8] + 9;
fe9cf0d4
                 } else {
                     /* otherwise, it should be a table */
                     /* skip packet */
                 skip:
5dbafeb7
                     pes->state = MPEGTS_SKIP;
fe9cf0d4
                     continue;
                 }
             }
             break;
             /**********************************************/
             /* PES packing parsing */
         case MPEGTS_PESHEADER_FILL:
5dbafeb7
             len = pes->pes_header_size - pes->data_index;
             if (len > buf_size)
                 len = buf_size;
             memcpy(pes->header + pes->data_index, p, len);
             pes->data_index += len;
fe9cf0d4
             p += len;
             buf_size -= len;
5dbafeb7
             if (pes->data_index == pes->pes_header_size) {
                 const uint8_t *r;
                 unsigned int flags;
 
                 flags = pes->header[7];
                 r = pes->header + 9;
                 pes->pts = AV_NOPTS_VALUE;
                 pes->dts = AV_NOPTS_VALUE;
                 if ((flags & 0xc0) == 0x80) {
14120c95
                     pes->dts = pes->pts = get_pts(r);
5dbafeb7
                     r += 5;
                 } else if ((flags & 0xc0) == 0xc0) {
                     pes->pts = get_pts(r);
                     r += 5;
                     pes->dts = get_pts(r);
                     r += 5;
                 }
                 /* we got the full header. We parse it and get the payload */
                 pes->state = MPEGTS_PAYLOAD;
             }
fe9cf0d4
             break;
         case MPEGTS_PAYLOAD:
5dbafeb7
             if (pes->total_size) {
                 len = pes->total_size - pes->data_index;
                 if (len > buf_size)
                     len = buf_size;
             } else {
                 len = buf_size;
             }
fe9cf0d4
             if (len > 0) {
5dbafeb7
                 AVPacket *pkt = ts->pkt;
                 if (pes->st && av_new_packet(pkt, len) == 0) {
                     memcpy(pkt->data, p, len);
                     pkt->stream_index = pes->st->index;
                     pkt->pts = pes->pts;
2092bd75
                     pkt->dts = pes->dts;
4c6b49bf
                     /* store position of first TS packet of this PES packet */
                     pkt->pos = pes->ts_packet_pos;
5dbafeb7
                     /* reset pts values */
                     pes->pts = AV_NOPTS_VALUE;
                     pes->dts = AV_NOPTS_VALUE;
                     ts->stop_parse = 1;
                     return;
fe9cf0d4
                 }
             }
             buf_size = 0;
             break;
         case MPEGTS_SKIP:
             buf_size = 0;
             break;
         }
     }
5dbafeb7
 }
 
c6ec28b1
 static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code)
 {
     AVStream *st;
fb65d2ca
     enum CodecID codec_id;
     enum CodecType codec_type;
c6ec28b1
 
     switch(pes->stream_type){
     case STREAM_TYPE_AUDIO_MPEG1:
     case STREAM_TYPE_AUDIO_MPEG2:
         codec_type = CODEC_TYPE_AUDIO;
         codec_id = CODEC_ID_MP3;
         break;
     case STREAM_TYPE_VIDEO_MPEG1:
     case STREAM_TYPE_VIDEO_MPEG2:
         codec_type = CODEC_TYPE_VIDEO;
         codec_id = CODEC_ID_MPEG2VIDEO;
         break;
     case STREAM_TYPE_VIDEO_MPEG4:
         codec_type = CODEC_TYPE_VIDEO;
         codec_id = CODEC_ID_MPEG4;
         break;
     case STREAM_TYPE_VIDEO_H264:
         codec_type = CODEC_TYPE_VIDEO;
         codec_id = CODEC_ID_H264;
         break;
cf10ee18
     case STREAM_TYPE_VIDEO_VC1:
         codec_type = CODEC_TYPE_VIDEO;
         codec_id = CODEC_ID_VC1;
         break;
f4bba201
     case STREAM_TYPE_VIDEO_DIRAC:
         codec_type = CODEC_TYPE_VIDEO;
         codec_id = CODEC_ID_DIRAC;
         break;
c6ec28b1
     case STREAM_TYPE_AUDIO_AAC:
         codec_type = CODEC_TYPE_AUDIO;
         codec_id = CODEC_ID_AAC;
         break;
     case STREAM_TYPE_AUDIO_AC3:
         codec_type = CODEC_TYPE_AUDIO;
         codec_id = CODEC_ID_AC3;
         break;
     case STREAM_TYPE_AUDIO_DTS:
a45b40c4
     case STREAM_TYPE_AUDIO_HDMV_DTS:
c6ec28b1
         codec_type = CODEC_TYPE_AUDIO;
         codec_id = CODEC_ID_DTS;
         break;
     case STREAM_TYPE_SUBTITLE_DVB:
         codec_type = CODEC_TYPE_SUBTITLE;
         codec_id = CODEC_ID_DVB_SUBTITLE;
         break;
     default:
         if (code >= 0x1c0 && code <= 0x1df) {
             codec_type = CODEC_TYPE_AUDIO;
             codec_id = CODEC_ID_MP2;
         } else if (code == 0x1bd) {
             codec_type = CODEC_TYPE_AUDIO;
             codec_id = CODEC_ID_AC3;
         } else {
             codec_type = CODEC_TYPE_VIDEO;
452a398f
             codec_id = CODEC_ID_PROBE;
c6ec28b1
         }
         break;
     }
     st = av_new_stream(pes->stream, pes->pid);
     if (st) {
         av_set_pts_info(st, 33, 1, 90000);
         st->priv_data = pes;
01f4895c
         st->codec->codec_type = codec_type;
         st->codec->codec_id = codec_id;
57004ff1
         st->need_parsing = AVSTREAM_PARSE_FULL;
c6ec28b1
         pes->st = st;
     }
     return st;
 }
 
 
dbf6b678
 static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid, int stream_type)
5dbafeb7
 {
     MpegTSFilter *tss;
     PESContext *pes;
 
     /* if no pid found, then add a pid context */
     pes = av_mallocz(sizeof(PESContext));
     if (!pes)
c6ec28b1
         return 0;
b45a7a18
     pes->ts = ts;
     pes->stream = ts->stream;
5dbafeb7
     pes->pid = pid;
dbf6b678
     pes->pcr_pid = pcr_pid;
278de475
     pes->stream_type = stream_type;
5dbafeb7
     tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
     if (!tss) {
         av_free(pes);
c6ec28b1
         return 0;
5dbafeb7
     }
c6ec28b1
     return pes;
fe9cf0d4
 }
 
5dbafeb7
 /* handle one TS packet */
b45a7a18
 static void handle_packet(MpegTSContext *ts, const uint8_t *packet)
fe9cf0d4
 {
b45a7a18
     AVFormatContext *s = ts->stream;
5dbafeb7
     MpegTSFilter *tss;
     int len, pid, cc, cc_ok, afc, is_start;
     const uint8_t *p, *p_end;
4c6b49bf
     int64_t pos;
5dbafeb7
 
80fb8234
     pid = AV_RB16(packet + 1) & 0x1fff;
172d1171
     if(pid && discard_pid(ts, pid))
         return;
5dbafeb7
     is_start = packet[1] & 0x40;
     tss = ts->pids[pid];
     if (ts->auto_guess && tss == NULL && is_start) {
dbf6b678
         add_pes_stream(ts, pid, -1, 0);
5dbafeb7
         tss = ts->pids[pid];
     }
     if (!tss)
         return;
 
     /* continuity check (currently not used) */
     cc = (packet[3] & 0xf);
     cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
     tss->last_cc = cc;
115329f1
 
5dbafeb7
     /* skip adaptation field */
     afc = (packet[3] >> 4) & 3;
     p = packet + 4;
     if (afc == 0) /* reserved value */
         return;
     if (afc == 2) /* adaptation field only */
         return;
     if (afc == 3) {
         /* skip adapation field */
         p += p[0] + 1;
     }
     /* if past the end of packet, ignore */
     p_end = packet + TS_PACKET_SIZE;
     if (p >= p_end)
         return;
115329f1
 
4c6b49bf
     pos = url_ftell(ts->stream->pb);
     ts->pos47= pos % ts->raw_packet_size;
5fd63f3c
 
5dbafeb7
     if (tss->type == MPEGTS_SECTION) {
         if (is_start) {
             /* pointer field present */
             len = *p++;
             if (p + len > p_end)
                 return;
             if (len && cc_ok) {
27bb1ed3
                 /* write remaining section bytes */
115329f1
                 write_section_data(s, tss,
5dbafeb7
                                    p, len, 0);
27bb1ed3
                 /* check whether filter has been closed */
                 if (!ts->pids[pid])
                     return;
5dbafeb7
             }
             p += len;
             if (p < p_end) {
115329f1
                 write_section_data(s, tss,
5dbafeb7
                                    p, p_end - p, 1);
             }
         } else {
             if (cc_ok) {
115329f1
                 write_section_data(s, tss,
5dbafeb7
                                    p, p_end - p, 0);
fc48fe84
             }
5dbafeb7
         }
     } else {
4c6b49bf
         // Note: The position here points actually behind the current packet.
4d9a577e
         tss->u.pes_filter.pes_cb(tss,
4c6b49bf
                                  p, p_end - p, is_start, pos - ts->raw_packet_size);
5dbafeb7
     }
 }
 
fc48fe84
 /* XXX: try to find a better synchro over several packets (use
    get_packet_size() ?) */
b45a7a18
 static int mpegts_resync(ByteIOContext *pb)
fc48fe84
 {
     int c, i;
 
     for(i = 0;i < MAX_RESYNC_SIZE; i++) {
         c = url_fgetc(pb);
         if (c < 0)
             return -1;
         if (c == 0x47) {
             url_fseek(pb, -1, SEEK_CUR);
             return 0;
         }
     }
     /* no sync found */
     return -1;
 }
 
b45a7a18
 /* return -1 if error or EOF. Return 0 if OK. */
 static int read_packet(ByteIOContext *pb, uint8_t *buf, int raw_packet_size)
5dbafeb7
 {
b45a7a18
     int skip, len;
 
     for(;;) {
         len = get_buffer(pb, buf, TS_PACKET_SIZE);
         if (len != TS_PACKET_SIZE)
6f3e0b21
             return AVERROR(EIO);
b45a7a18
         /* check paquet sync byte */
         if (buf[0] != 0x47) {
             /* find a new packet start */
             url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
             if (mpegts_resync(pb) < 0)
                 return AVERROR_INVALIDDATA;
             else
                 continue;
         } else {
             skip = raw_packet_size - TS_PACKET_SIZE;
             if (skip > 0)
                 url_fskip(pb, skip);
             break;
         }
     }
     return 0;
 }
 
 static int handle_packets(MpegTSContext *ts, int nb_packets)
 {
     AVFormatContext *s = ts->stream;
899681cd
     ByteIOContext *pb = s->pb;
b45a7a18
     uint8_t packet[TS_PACKET_SIZE];
     int packet_num, ret;
5dbafeb7
 
     ts->stop_parse = 0;
     packet_num = 0;
fe9cf0d4
     for(;;) {
90d13e30
         if (ts->stop_parse>0)
5dbafeb7
             break;
         packet_num++;
         if (nb_packets != 0 && packet_num >= nb_packets)
             break;
b45a7a18
         ret = read_packet(pb, packet, ts->raw_packet_size);
         if (ret != 0)
             return ret;
         handle_packet(ts, packet);
5dbafeb7
     }
     return 0;
 }
fe9cf0d4
 
5dbafeb7
 static int mpegts_probe(AVProbeData *p)
 {
fc48fe84
 #if 1
a0b8f70c
     const int size= p->buf_size;
5d4d67e0
     int score, fec_score, dvhs_score;
1558d0b9
     int check_count= size / TS_FEC_PACKET_SIZE;
a0b8f70c
 #define CHECK_COUNT 10
115329f1
 
1558d0b9
     if (check_count < CHECK_COUNT)
a0b8f70c
         return -1;
115329f1
 
1558d0b9
     score     = analyze(p->buf, TS_PACKET_SIZE     *check_count, TS_PACKET_SIZE     , NULL)*CHECK_COUNT/check_count;
     dvhs_score= analyze(p->buf, TS_DVHS_PACKET_SIZE*check_count, TS_DVHS_PACKET_SIZE, NULL)*CHECK_COUNT/check_count;
     fec_score = analyze(p->buf, TS_FEC_PACKET_SIZE *check_count, TS_FEC_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
5d4d67e0
 //    av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
115329f1
 
a0b8f70c
 // we need a clear definition for the returned score otherwise things will become messy sooner or later
5d4d67e0
     if     (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score     - CHECK_COUNT;
     else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score  - CHECK_COUNT;
a0b8f70c
     else if(                 fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
     else                                    return -1;
fc48fe84
 #else
     /* only use the extension for safer guess */
     if (match_ext(p->filename, "ts"))
         return AVPROBE_SCORE_MAX;
     else
         return 0;
 #endif
5dbafeb7
 }
 
910f02a0
 /* return the 90kHz PCR and the extension for the 27MHz PCR. return
b45a7a18
    (-1) if not available */
115329f1
 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
b45a7a18
                      const uint8_t *packet)
 {
     int afc, len, flags;
     const uint8_t *p;
     unsigned int v;
 
     afc = (packet[3] >> 4) & 3;
     if (afc <= 1)
         return -1;
     p = packet + 4;
     len = p[0];
     p++;
     if (len == 0)
         return -1;
     flags = *p++;
     len--;
     if (!(flags & 0x10))
         return -1;
     if (len < 6)
         return -1;
80fb8234
     v = AV_RB32(p);
b45a7a18
     *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
     *ppcr_low = ((p[4] & 1) << 8) | p[5];
     return 0;
 }
 
5dbafeb7
 static int mpegts_read_header(AVFormatContext *s,
                               AVFormatParameters *ap)
 {
     MpegTSContext *ts = s->priv_data;
899681cd
     ByteIOContext *pb = s->pb;
1558d0b9
     uint8_t buf[5*1024];
4dc8a963
     int len;
5dbafeb7
     int64_t pos;
e05655fb
 
b45a7a18
     if (ap) {
         ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
38c48be2
         if(ap->mpeg2ts_raw){
             av_log(s, AV_LOG_ERROR, "use mpegtsraw_demuxer!\n");
             return -1;
         }
b45a7a18
     }
 
5dbafeb7
     /* read the first 1024 bytes to get packet size */
     pos = url_ftell(pb);
     len = get_buffer(pb, buf, sizeof(buf));
     if (len != sizeof(buf))
         goto fail;
     ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
     if (ts->raw_packet_size <= 0)
         goto fail;
b45a7a18
     ts->stream = s;
5dbafeb7
     ts->auto_guess = 0;
 
38c48be2
     if (s->iformat == &mpegts_demuxer) {
b45a7a18
         /* normal demux */
fc48fe84
 
a45ec414
         /* first do a scaning to get all the services */
         url_fseek(pb, pos, SEEK_SET);
         mpegts_scan_sdt(ts);
115329f1
 
28f03d04
         mpegts_set_service(ts);
115329f1
 
28f03d04
         handle_packets(ts, s->probesize);
a45ec414
         /* if could not find service, enable auto_guess */
115329f1
 
a45ec414
         ts->auto_guess = 1;
115329f1
 
b45a7a18
 #ifdef DEBUG_SI
a45ec414
         av_log(ts->stream, AV_LOG_DEBUG, "tuning done\n");
b45a7a18
 #endif
         s->ctx_flags |= AVFMTCTX_NOHEADER;
     } else {
         AVStream *st;
         int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
         int64_t pcrs[2], pcr_h;
         int packet_count[2];
         uint8_t packet[TS_PACKET_SIZE];
115329f1
 
b45a7a18
         /* only read packets */
115329f1
 
b45a7a18
         st = av_new_stream(s, 0);
         if (!st)
             goto fail;
9ee91c2f
         av_set_pts_info(st, 60, 1, 27000000);
01f4895c
         st->codec->codec_type = CODEC_TYPE_DATA;
         st->codec->codec_id = CODEC_ID_MPEG2TS;
115329f1
 
b45a7a18
         /* we iterate until we find two PCRs to estimate the bitrate */
         pcr_pid = -1;
         nb_pcrs = 0;
         nb_packets = 0;
         for(;;) {
899681cd
             ret = read_packet(s->pb, packet, ts->raw_packet_size);
b45a7a18
             if (ret < 0)
                 return -1;
80fb8234
             pid = AV_RB16(packet + 1) & 0x1fff;
b45a7a18
             if ((pcr_pid == -1 || pcr_pid == pid) &&
                 parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
                 pcr_pid = pid;
                 packet_count[nb_pcrs] = nb_packets;
                 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
                 nb_pcrs++;
                 if (nb_pcrs >= 2)
                     break;
             }
             nb_packets++;
         }
5dbafeb7
 
b45a7a18
         /* NOTE1: the bitrate is computed without the FEC */
         /* NOTE2: it is only the bitrate of the start of the stream */
         ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
         ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
         s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
01f4895c
         st->codec->bit_rate = s->bit_rate;
c0df9d75
         st->start_time = ts->cur_pcr;
b45a7a18
 #if 0
f0ee3ea6
         av_log(ts->stream, AV_LOG_DEBUG, "start=%0.3f pcr=%0.3f incr=%d\n",
b45a7a18
                st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
5dbafeb7
 #endif
fe9cf0d4
     }
5dbafeb7
 
     url_fseek(pb, pos, SEEK_SET);
fe9cf0d4
     return 0;
5dbafeb7
  fail:
     return -1;
 }
 
b45a7a18
 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
 
 static int mpegts_raw_read_packet(AVFormatContext *s,
                                   AVPacket *pkt)
 {
     MpegTSContext *ts = s->priv_data;
     int ret, i;
     int64_t pcr_h, next_pcr_h, pos;
     int pcr_l, next_pcr_l;
     uint8_t pcr_buf[12];
 
     if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
8fa36ae0
         return AVERROR(ENOMEM);
899681cd
     pkt->pos= url_ftell(s->pb);
     ret = read_packet(s->pb, pkt->data, ts->raw_packet_size);
b45a7a18
     if (ret < 0) {
         av_free_packet(pkt);
         return ret;
     }
     if (ts->mpeg2ts_compute_pcr) {
         /* compute exact PCR for each packet */
         if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
             /* we read the next PCR (XXX: optimize it by using a bigger buffer */
899681cd
             pos = url_ftell(s->pb);
b45a7a18
             for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
899681cd
                 url_fseek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
                 get_buffer(s->pb, pcr_buf, 12);
b45a7a18
                 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
                     /* XXX: not precise enough */
115329f1
                     ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
b45a7a18
                         (i + 1);
                     break;
                 }
             }
899681cd
             url_fseek(s->pb, pos, SEEK_SET);
b45a7a18
             /* no next PCR found: we use previous increment */
             ts->cur_pcr = pcr_h * 300 + pcr_l;
         }
         pkt->pts = ts->cur_pcr;
         pkt->duration = ts->pcr_incr;
         ts->cur_pcr += ts->pcr_incr;
     }
     pkt->stream_index = 0;
     return 0;
 }
 
5dbafeb7
 static int mpegts_read_packet(AVFormatContext *s,
                               AVPacket *pkt)
 {
     MpegTSContext *ts = s->priv_data;
b45a7a18
 
38c48be2
     ts->pkt = pkt;
     return handle_packets(ts, 0);
fe9cf0d4
 }
 
 static int mpegts_read_close(AVFormatContext *s)
 {
     MpegTSContext *ts = s->priv_data;
     int i;
81d5ae6d
 
     clear_programs(ts);
 
fe9cf0d4
     for(i=0;i<NB_PID_MAX;i++)
ec7d0d2e
         if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
00a6b92b
 
fe9cf0d4
     return 0;
 }
 
115329f1
 static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
cdd5034f
                               int64_t *ppos, int64_t pos_limit)
27f388aa
 {
     MpegTSContext *ts = s->priv_data;
     int64_t pos, timestamp;
     uint8_t buf[TS_PACKET_SIZE];
dbf6b678
     int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
cdd5034f
     const int find_next= 1;
5fd63f3c
     pos = ((*ppos  + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
27f388aa
     if (find_next) {
         for(;;) {
899681cd
             url_fseek(s->pb, pos, SEEK_SET);
             if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
27f388aa
                 return AV_NOPTS_VALUE;
80fb8234
             if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
27f388aa
                 parse_pcr(&timestamp, &pcr_l, buf) == 0) {
                 break;
             }
             pos += ts->raw_packet_size;
         }
     } else {
         for(;;) {
             pos -= ts->raw_packet_size;
             if (pos < 0)
                 return AV_NOPTS_VALUE;
899681cd
             url_fseek(s->pb, pos, SEEK_SET);
             if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
27f388aa
                 return AV_NOPTS_VALUE;
80fb8234
             if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
27f388aa
                 parse_pcr(&timestamp, &pcr_l, buf) == 0) {
                 break;
             }
         }
     }
     *ppos = pos;
 
cdd5034f
     return timestamp;
27f388aa
 }
 
3ba1438d
 static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
e05655fb
     MpegTSContext *ts = s->priv_data;
     uint8_t buf[TS_PACKET_SIZE];
     int64_t pos;
 
3ba1438d
     if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
e05655fb
         return -1;
 
899681cd
     pos= url_ftell(s->pb);
e05655fb
 
     for(;;) {
899681cd
         url_fseek(s->pb, pos, SEEK_SET);
         if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
e05655fb
             return -1;
80fb8234
 //        pid = AV_RB16(buf + 1) & 0x1fff;
e05655fb
         if(buf[1] & 0x40) break;
         pos += ts->raw_packet_size;
115329f1
     }
899681cd
     url_fseek(s->pb, pos, SEEK_SET);
e05655fb
 
     return 0;
 }
 
b45a7a18
 /**************************************************************/
 /* parsing functions - called from other demuxers such as RTP */
 
 MpegTSContext *mpegts_parse_open(AVFormatContext *s)
 {
     MpegTSContext *ts;
115329f1
 
b45a7a18
     ts = av_mallocz(sizeof(MpegTSContext));
     if (!ts)
         return NULL;
     /* no stream case, currently used by RTP */
     ts->raw_packet_size = TS_PACKET_SIZE;
     ts->stream = s;
     ts->auto_guess = 1;
     return ts;
 }
 
 /* return the consumed length if a packet was output, or -1 if no
    packet is output */
 int mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
                         const uint8_t *buf, int len)
 {
     int len1;
 
     len1 = len;
     ts->pkt = pkt;
     ts->stop_parse = 0;
     for(;;) {
90d13e30
         if (ts->stop_parse>0)
b45a7a18
             break;
         if (len < TS_PACKET_SIZE)
             return -1;
         if (buf[0] != 0x47) {
550f0a9b
             buf++;
b45a7a18
             len--;
         } else {
             handle_packet(ts, buf);
             buf += TS_PACKET_SIZE;
             len -= TS_PACKET_SIZE;
         }
     }
     return len1 - len;
 }
 
 void mpegts_parse_close(MpegTSContext *ts)
 {
     int i;
 
     for(i=0;i<NB_PID_MAX;i++)
         av_free(ts->pids[i]);
     av_free(ts);
 }
 
d2a067d1
 AVInputFormat mpegts_demuxer = {
fe9cf0d4
     "mpegts",
bde15e74
     NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
fe9cf0d4
     sizeof(MpegTSContext),
     mpegts_probe,
     mpegts_read_header,
     mpegts_read_packet,
     mpegts_read_close,
e05655fb
     read_seek,
cdd5034f
     mpegts_get_pcr,
ff9c8d7c
     .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
fe9cf0d4
 };
38c48be2
 
 AVInputFormat mpegtsraw_demuxer = {
     "mpegtsraw",
bde15e74
     NULL_IF_CONFIG_SMALL("MPEG-2 raw transport stream format"),
38c48be2
     sizeof(MpegTSContext),
056f6b8f
     NULL,
38c48be2
     mpegts_read_header,
     mpegts_raw_read_packet,
     mpegts_read_close,
     read_seek,
     mpegts_get_pcr,
ff9c8d7c
     .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
38c48be2
 };