• Main Page
  • Related Pages
  • Modules
  • Data Structures
  • Files
  • Examples
  • File List
  • Globals

libavformat/mpegts.c

Go to the documentation of this file.
00001 /*
00002  * MPEG2 transport stream (aka DVB) demuxer
00003  * Copyright (c) 2002-2003 Fabrice Bellard
00004  *
00005  * This file is part of Libav.
00006  *
00007  * Libav is free software; you can redistribute it and/or
00008  * modify it under the terms of the GNU Lesser General Public
00009  * License as published by the Free Software Foundation; either
00010  * version 2.1 of the License, or (at your option) any later version.
00011  *
00012  * Libav is distributed in the hope that it will be useful,
00013  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00014  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00015  * Lesser General Public License for more details.
00016  *
00017  * You should have received a copy of the GNU Lesser General Public
00018  * License along with Libav; if not, write to the Free Software
00019  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00020  */
00021 
00022 //#define USE_SYNCPOINT_SEARCH
00023 
00024 #include "libavutil/crc.h"
00025 #include "libavutil/intreadwrite.h"
00026 #include "libavutil/log.h"
00027 #include "libavutil/dict.h"
00028 #include "libavutil/mathematics.h"
00029 #include "libavutil/opt.h"
00030 #include "libavcodec/bytestream.h"
00031 #include "libavcodec/get_bits.h"
00032 #include "avformat.h"
00033 #include "mpegts.h"
00034 #include "internal.h"
00035 #include "avio_internal.h"
00036 #include "seek.h"
00037 #include "mpeg.h"
00038 #include "isom.h"
00039 
00040 /* maximum size in which we look for synchronisation if
00041    synchronisation is lost */
00042 #define MAX_RESYNC_SIZE 65536
00043 
00044 #define MAX_PES_PAYLOAD 200*1024
00045 
00046 #define MAX_MP4_DESCR_COUNT 16
00047 
00048 enum MpegTSFilterType {
00049     MPEGTS_PES,
00050     MPEGTS_SECTION,
00051 };
00052 
00053 typedef struct MpegTSFilter MpegTSFilter;
00054 
00055 typedef int PESCallback(MpegTSFilter *f, const uint8_t *buf, int len, int is_start, int64_t pos);
00056 
00057 typedef struct MpegTSPESFilter {
00058     PESCallback *pes_cb;
00059     void *opaque;
00060 } MpegTSPESFilter;
00061 
00062 typedef void SectionCallback(MpegTSFilter *f, const uint8_t *buf, int len);
00063 
00064 typedef void SetServiceCallback(void *opaque, int ret);
00065 
00066 typedef struct MpegTSSectionFilter {
00067     int section_index;
00068     int section_h_size;
00069     uint8_t *section_buf;
00070     unsigned int check_crc:1;
00071     unsigned int end_of_section_reached:1;
00072     SectionCallback *section_cb;
00073     void *opaque;
00074 } MpegTSSectionFilter;
00075 
00076 struct MpegTSFilter {
00077     int pid;
00078     int es_id;
00079     int last_cc; /* last cc code (-1 if first packet) */
00080     enum MpegTSFilterType type;
00081     union {
00082         MpegTSPESFilter pes_filter;
00083         MpegTSSectionFilter section_filter;
00084     } u;
00085 };
00086 
00087 #define MAX_PIDS_PER_PROGRAM 64
00088 struct Program {
00089     unsigned int id; //program id/service id
00090     unsigned int nb_pids;
00091     unsigned int pids[MAX_PIDS_PER_PROGRAM];
00092 };
00093 
00094 struct MpegTSContext {
00095     const AVClass *class;
00096     /* user data */
00097     AVFormatContext *stream;
00099     int raw_packet_size;
00100 
00101     int pos47;
00102 
00104     int auto_guess;
00105 
00107     int mpeg2ts_compute_pcr;
00108 
00109     int64_t cur_pcr;    
00110     int pcr_incr;       
00112     /* data needed to handle file based ts */
00114     int stop_parse;
00116     AVPacket *pkt;
00118     int64_t last_pos;
00119 
00120     /******************************************/
00121     /* private mpegts data */
00122     /* scan context */
00124     unsigned int nb_prg;
00125     struct Program *prg;
00126 
00127 
00129     MpegTSFilter *pids[NB_PID_MAX];
00130 };
00131 
00132 static const AVOption options[] = {
00133     {"compute_pcr", "Compute exact PCR for each transport stream packet.", offsetof(MpegTSContext, mpeg2ts_compute_pcr), AV_OPT_TYPE_INT,
00134      {.dbl = 0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
00135     { NULL },
00136 };
00137 
00138 static const AVClass mpegtsraw_class = {
00139     .class_name = "mpegtsraw demuxer",
00140     .item_name  = av_default_item_name,
00141     .option     = options,
00142     .version    = LIBAVUTIL_VERSION_INT,
00143 };
00144 
00145 /* TS stream handling */
00146 
00147 enum MpegTSState {
00148     MPEGTS_HEADER = 0,
00149     MPEGTS_PESHEADER,
00150     MPEGTS_PESHEADER_FILL,
00151     MPEGTS_PAYLOAD,
00152     MPEGTS_SKIP,
00153 };
00154 
00155 /* enough for PES header + length */
00156 #define PES_START_SIZE  6
00157 #define PES_HEADER_SIZE 9
00158 #define MAX_PES_HEADER_SIZE (9 + 255)
00159 
00160 typedef struct PESContext {
00161     int pid;
00162     int pcr_pid; 
00163     int stream_type;
00164     MpegTSContext *ts;
00165     AVFormatContext *stream;
00166     AVStream *st;
00167     AVStream *sub_st; 
00168     enum MpegTSState state;
00169     /* used to get the format */
00170     int data_index;
00171     int flags; 
00172     int total_size;
00173     int pes_header_size;
00174     int extended_stream_id;
00175     int64_t pts, dts;
00176     int64_t ts_packet_pos; 
00177     uint8_t header[MAX_PES_HEADER_SIZE];
00178     uint8_t *buffer;
00179     SLConfigDescr sl;
00180 } PESContext;
00181 
00182 extern AVInputFormat ff_mpegts_demuxer;
00183 
00184 static void clear_program(MpegTSContext *ts, unsigned int programid)
00185 {
00186     int i;
00187 
00188     for(i=0; i<ts->nb_prg; i++)
00189         if(ts->prg[i].id == programid)
00190             ts->prg[i].nb_pids = 0;
00191 }
00192 
00193 static void clear_programs(MpegTSContext *ts)
00194 {
00195     av_freep(&ts->prg);
00196     ts->nb_prg=0;
00197 }
00198 
00199 static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
00200 {
00201     struct Program *p;
00202     void *tmp = av_realloc(ts->prg, (ts->nb_prg+1)*sizeof(struct Program));
00203     if(!tmp)
00204         return;
00205     ts->prg = tmp;
00206     p = &ts->prg[ts->nb_prg];
00207     p->id = programid;
00208     p->nb_pids = 0;
00209     ts->nb_prg++;
00210 }
00211 
00212 static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid, unsigned int pid)
00213 {
00214     int i;
00215     struct Program *p = NULL;
00216     for(i=0; i<ts->nb_prg; i++) {
00217         if(ts->prg[i].id == programid) {
00218             p = &ts->prg[i];
00219             break;
00220         }
00221     }
00222     if(!p)
00223         return;
00224 
00225     if(p->nb_pids >= MAX_PIDS_PER_PROGRAM)
00226         return;
00227     p->pids[p->nb_pids++] = pid;
00228 }
00229 
00238 static int discard_pid(MpegTSContext *ts, unsigned int pid)
00239 {
00240     int i, j, k;
00241     int used = 0, discarded = 0;
00242     struct Program *p;
00243     for(i=0; i<ts->nb_prg; i++) {
00244         p = &ts->prg[i];
00245         for(j=0; j<p->nb_pids; j++) {
00246             if(p->pids[j] != pid)
00247                 continue;
00248             //is program with id p->id set to be discarded?
00249             for(k=0; k<ts->stream->nb_programs; k++) {
00250                 if(ts->stream->programs[k]->id == p->id) {
00251                     if(ts->stream->programs[k]->discard == AVDISCARD_ALL)
00252                         discarded++;
00253                     else
00254                         used++;
00255                 }
00256             }
00257         }
00258     }
00259 
00260     return !used && discarded;
00261 }
00262 
00267 static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
00268                                const uint8_t *buf, int buf_size, int is_start)
00269 {
00270     MpegTSSectionFilter *tss = &tss1->u.section_filter;
00271     int len;
00272 
00273     if (is_start) {
00274         memcpy(tss->section_buf, buf, buf_size);
00275         tss->section_index = buf_size;
00276         tss->section_h_size = -1;
00277         tss->end_of_section_reached = 0;
00278     } else {
00279         if (tss->end_of_section_reached)
00280             return;
00281         len = 4096 - tss->section_index;
00282         if (buf_size < len)
00283             len = buf_size;
00284         memcpy(tss->section_buf + tss->section_index, buf, len);
00285         tss->section_index += len;
00286     }
00287 
00288     /* compute section length if possible */
00289     if (tss->section_h_size == -1 && tss->section_index >= 3) {
00290         len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
00291         if (len > 4096)
00292             return;
00293         tss->section_h_size = len;
00294     }
00295 
00296     if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
00297         tss->end_of_section_reached = 1;
00298         if (!tss->check_crc ||
00299             av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1,
00300                    tss->section_buf, tss->section_h_size) == 0)
00301             tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
00302     }
00303 }
00304 
00305 static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
00306                                          SectionCallback *section_cb, void *opaque,
00307                                          int check_crc)
00308 
00309 {
00310     MpegTSFilter *filter;
00311     MpegTSSectionFilter *sec;
00312 
00313     av_dlog(ts->stream, "Filter: pid=0x%x\n", pid);
00314 
00315     if (pid >= NB_PID_MAX || ts->pids[pid])
00316         return NULL;
00317     filter = av_mallocz(sizeof(MpegTSFilter));
00318     if (!filter)
00319         return NULL;
00320     ts->pids[pid] = filter;
00321     filter->type = MPEGTS_SECTION;
00322     filter->pid = pid;
00323     filter->es_id = -1;
00324     filter->last_cc = -1;
00325     sec = &filter->u.section_filter;
00326     sec->section_cb = section_cb;
00327     sec->opaque = opaque;
00328     sec->section_buf = av_malloc(MAX_SECTION_SIZE);
00329     sec->check_crc = check_crc;
00330     if (!sec->section_buf) {
00331         av_free(filter);
00332         return NULL;
00333     }
00334     return filter;
00335 }
00336 
00337 static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
00338                                      PESCallback *pes_cb,
00339                                      void *opaque)
00340 {
00341     MpegTSFilter *filter;
00342     MpegTSPESFilter *pes;
00343 
00344     if (pid >= NB_PID_MAX || ts->pids[pid])
00345         return NULL;
00346     filter = av_mallocz(sizeof(MpegTSFilter));
00347     if (!filter)
00348         return NULL;
00349     ts->pids[pid] = filter;
00350     filter->type = MPEGTS_PES;
00351     filter->pid = pid;
00352     filter->es_id = -1;
00353     filter->last_cc = -1;
00354     pes = &filter->u.pes_filter;
00355     pes->pes_cb = pes_cb;
00356     pes->opaque = opaque;
00357     return filter;
00358 }
00359 
00360 static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
00361 {
00362     int pid;
00363 
00364     pid = filter->pid;
00365     if (filter->type == MPEGTS_SECTION)
00366         av_freep(&filter->u.section_filter.section_buf);
00367     else if (filter->type == MPEGTS_PES) {
00368         PESContext *pes = filter->u.pes_filter.opaque;
00369         av_freep(&pes->buffer);
00370         /* referenced private data will be freed later in
00371          * avformat_close_input */
00372         if (!((PESContext *)filter->u.pes_filter.opaque)->st) {
00373             av_freep(&filter->u.pes_filter.opaque);
00374         }
00375     }
00376 
00377     av_free(filter);
00378     ts->pids[pid] = NULL;
00379 }
00380 
00381 static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
00382     int stat[TS_MAX_PACKET_SIZE];
00383     int i;
00384     int x=0;
00385     int best_score=0;
00386 
00387     memset(stat, 0, packet_size*sizeof(int));
00388 
00389     for(x=i=0; i<size-3; i++){
00390         if(buf[i] == 0x47 && !(buf[i+1] & 0x80) && (buf[i+3] & 0x30)){
00391             stat[x]++;
00392             if(stat[x] > best_score){
00393                 best_score= stat[x];
00394                 if(index) *index= x;
00395             }
00396         }
00397 
00398         x++;
00399         if(x == packet_size) x= 0;
00400     }
00401 
00402     return best_score;
00403 }
00404 
00405 /* autodetect fec presence. Must have at least 1024 bytes  */
00406 static int get_packet_size(const uint8_t *buf, int size)
00407 {
00408     int score, fec_score, dvhs_score;
00409 
00410     if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
00411         return -1;
00412 
00413     score    = analyze(buf, size, TS_PACKET_SIZE, NULL);
00414     dvhs_score    = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
00415     fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
00416 //    av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
00417 
00418     if     (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
00419     else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
00420     else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
00421     else                       return -1;
00422 }
00423 
00424 typedef struct SectionHeader {
00425     uint8_t tid;
00426     uint16_t id;
00427     uint8_t version;
00428     uint8_t sec_num;
00429     uint8_t last_sec_num;
00430 } SectionHeader;
00431 
00432 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
00433 {
00434     const uint8_t *p;
00435     int c;
00436 
00437     p = *pp;
00438     if (p >= p_end)
00439         return -1;
00440     c = *p++;
00441     *pp = p;
00442     return c;
00443 }
00444 
00445 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
00446 {
00447     const uint8_t *p;
00448     int c;
00449 
00450     p = *pp;
00451     if ((p + 1) >= p_end)
00452         return -1;
00453     c = AV_RB16(p);
00454     p += 2;
00455     *pp = p;
00456     return c;
00457 }
00458 
00459 /* read and allocate a DVB string preceded by its length */
00460 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
00461 {
00462     int len;
00463     const uint8_t *p;
00464     char *str;
00465 
00466     p = *pp;
00467     len = get8(&p, p_end);
00468     if (len < 0)
00469         return NULL;
00470     if ((p + len) > p_end)
00471         return NULL;
00472     str = av_malloc(len + 1);
00473     if (!str)
00474         return NULL;
00475     memcpy(str, p, len);
00476     str[len] = '\0';
00477     p += len;
00478     *pp = p;
00479     return str;
00480 }
00481 
00482 static int parse_section_header(SectionHeader *h,
00483                                 const uint8_t **pp, const uint8_t *p_end)
00484 {
00485     int val;
00486 
00487     val = get8(pp, p_end);
00488     if (val < 0)
00489         return -1;
00490     h->tid = val;
00491     *pp += 2;
00492     val = get16(pp, p_end);
00493     if (val < 0)
00494         return -1;
00495     h->id = val;
00496     val = get8(pp, p_end);
00497     if (val < 0)
00498         return -1;
00499     h->version = (val >> 1) & 0x1f;
00500     val = get8(pp, p_end);
00501     if (val < 0)
00502         return -1;
00503     h->sec_num = val;
00504     val = get8(pp, p_end);
00505     if (val < 0)
00506         return -1;
00507     h->last_sec_num = val;
00508     return 0;
00509 }
00510 
00511 typedef struct {
00512     uint32_t stream_type;
00513     enum AVMediaType codec_type;
00514     enum CodecID codec_id;
00515 } StreamType;
00516 
00517 static const StreamType ISO_types[] = {
00518     { 0x01, AVMEDIA_TYPE_VIDEO, CODEC_ID_MPEG2VIDEO },
00519     { 0x02, AVMEDIA_TYPE_VIDEO, CODEC_ID_MPEG2VIDEO },
00520     { 0x03, AVMEDIA_TYPE_AUDIO,        CODEC_ID_MP3 },
00521     { 0x04, AVMEDIA_TYPE_AUDIO,        CODEC_ID_MP3 },
00522     { 0x0f, AVMEDIA_TYPE_AUDIO,        CODEC_ID_AAC },
00523     { 0x10, AVMEDIA_TYPE_VIDEO,      CODEC_ID_MPEG4 },
00524     { 0x11, AVMEDIA_TYPE_AUDIO,   CODEC_ID_AAC_LATM }, /* LATM syntax */
00525     { 0x1b, AVMEDIA_TYPE_VIDEO,       CODEC_ID_H264 },
00526     { 0xd1, AVMEDIA_TYPE_VIDEO,      CODEC_ID_DIRAC },
00527     { 0xea, AVMEDIA_TYPE_VIDEO,        CODEC_ID_VC1 },
00528     { 0 },
00529 };
00530 
00531 static const StreamType HDMV_types[] = {
00532     { 0x80, AVMEDIA_TYPE_AUDIO, CODEC_ID_PCM_BLURAY },
00533     { 0x81, AVMEDIA_TYPE_AUDIO, CODEC_ID_AC3 },
00534     { 0x82, AVMEDIA_TYPE_AUDIO, CODEC_ID_DTS },
00535     { 0x83, AVMEDIA_TYPE_AUDIO, CODEC_ID_TRUEHD },
00536     { 0x84, AVMEDIA_TYPE_AUDIO, CODEC_ID_EAC3 },
00537     { 0x90, AVMEDIA_TYPE_SUBTITLE, CODEC_ID_HDMV_PGS_SUBTITLE },
00538     { 0 },
00539 };
00540 
00541 /* ATSC ? */
00542 static const StreamType MISC_types[] = {
00543     { 0x81, AVMEDIA_TYPE_AUDIO,   CODEC_ID_AC3 },
00544     { 0x8a, AVMEDIA_TYPE_AUDIO,   CODEC_ID_DTS },
00545     { 0 },
00546 };
00547 
00548 static const StreamType REGD_types[] = {
00549     { MKTAG('d','r','a','c'), AVMEDIA_TYPE_VIDEO, CODEC_ID_DIRAC },
00550     { MKTAG('A','C','-','3'), AVMEDIA_TYPE_AUDIO,   CODEC_ID_AC3 },
00551     { MKTAG('B','S','S','D'), AVMEDIA_TYPE_AUDIO, CODEC_ID_S302M },
00552     { 0 },
00553 };
00554 
00555 /* descriptor present */
00556 static const StreamType DESC_types[] = {
00557     { 0x6a, AVMEDIA_TYPE_AUDIO,             CODEC_ID_AC3 }, /* AC-3 descriptor */
00558     { 0x7a, AVMEDIA_TYPE_AUDIO,            CODEC_ID_EAC3 }, /* E-AC-3 descriptor */
00559     { 0x7b, AVMEDIA_TYPE_AUDIO,             CODEC_ID_DTS },
00560     { 0x56, AVMEDIA_TYPE_SUBTITLE, CODEC_ID_DVB_TELETEXT },
00561     { 0x59, AVMEDIA_TYPE_SUBTITLE, CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
00562     { 0 },
00563 };
00564 
00565 static void mpegts_find_stream_type(AVStream *st,
00566                                     uint32_t stream_type, const StreamType *types)
00567 {
00568     for (; types->stream_type; types++) {
00569         if (stream_type == types->stream_type) {
00570             st->codec->codec_type = types->codec_type;
00571             st->codec->codec_id   = types->codec_id;
00572             return;
00573         }
00574     }
00575 }
00576 
00577 static int mpegts_set_stream_info(AVStream *st, PESContext *pes,
00578                                   uint32_t stream_type, uint32_t prog_reg_desc)
00579 {
00580     avpriv_set_pts_info(st, 33, 1, 90000);
00581     st->priv_data = pes;
00582     st->codec->codec_type = AVMEDIA_TYPE_DATA;
00583     st->codec->codec_id   = CODEC_ID_NONE;
00584     st->need_parsing = AVSTREAM_PARSE_FULL;
00585     pes->st = st;
00586     pes->stream_type = stream_type;
00587 
00588     av_log(pes->stream, AV_LOG_DEBUG,
00589            "stream=%d stream_type=%x pid=%x prog_reg_desc=%.4s\n",
00590            st->index, pes->stream_type, pes->pid, (char*)&prog_reg_desc);
00591 
00592     st->codec->codec_tag = pes->stream_type;
00593 
00594     mpegts_find_stream_type(st, pes->stream_type, ISO_types);
00595     if (prog_reg_desc == AV_RL32("HDMV") &&
00596         st->codec->codec_id == CODEC_ID_NONE) {
00597         mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
00598         if (pes->stream_type == 0x83) {
00599             // HDMV TrueHD streams also contain an AC3 coded version of the
00600             // audio track - add a second stream for this
00601             AVStream *sub_st;
00602             // priv_data cannot be shared between streams
00603             PESContext *sub_pes = av_malloc(sizeof(*sub_pes));
00604             if (!sub_pes)
00605                 return AVERROR(ENOMEM);
00606             memcpy(sub_pes, pes, sizeof(*sub_pes));
00607 
00608             sub_st = avformat_new_stream(pes->stream, NULL);
00609             if (!sub_st) {
00610                 av_free(sub_pes);
00611                 return AVERROR(ENOMEM);
00612             }
00613 
00614             sub_st->id = pes->pid;
00615             avpriv_set_pts_info(sub_st, 33, 1, 90000);
00616             sub_st->priv_data = sub_pes;
00617             sub_st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
00618             sub_st->codec->codec_id   = CODEC_ID_AC3;
00619             sub_st->need_parsing = AVSTREAM_PARSE_FULL;
00620             sub_pes->sub_st = pes->sub_st = sub_st;
00621         }
00622     }
00623     if (st->codec->codec_id == CODEC_ID_NONE)
00624         mpegts_find_stream_type(st, pes->stream_type, MISC_types);
00625 
00626     return 0;
00627 }
00628 
00629 static void new_pes_packet(PESContext *pes, AVPacket *pkt)
00630 {
00631     av_init_packet(pkt);
00632 
00633     pkt->destruct = av_destruct_packet;
00634     pkt->data = pes->buffer;
00635     pkt->size = pes->data_index;
00636 
00637     if(pes->total_size != MAX_PES_PAYLOAD &&
00638        pes->pes_header_size + pes->data_index != pes->total_size + PES_START_SIZE) {
00639         av_log(pes->stream, AV_LOG_WARNING, "PES packet size mismatch\n");
00640         pes->flags |= AV_PKT_FLAG_CORRUPT;
00641     }
00642     memset(pkt->data+pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
00643 
00644     // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID
00645     if (pes->sub_st && pes->stream_type == 0x83 && pes->extended_stream_id == 0x76)
00646         pkt->stream_index = pes->sub_st->index;
00647     else
00648         pkt->stream_index = pes->st->index;
00649     pkt->pts = pes->pts;
00650     pkt->dts = pes->dts;
00651     /* store position of first TS packet of this PES packet */
00652     pkt->pos = pes->ts_packet_pos;
00653     pkt->flags = pes->flags;
00654 
00655     /* reset pts values */
00656     pes->pts = AV_NOPTS_VALUE;
00657     pes->dts = AV_NOPTS_VALUE;
00658     pes->buffer = NULL;
00659     pes->data_index = 0;
00660     pes->flags = 0;
00661 }
00662 
00663 static uint64_t get_bits64(GetBitContext *gb, int bits)
00664 {
00665     uint64_t ret = 0;
00666     while (bits > 17) {
00667         ret <<= 17;
00668         ret |= get_bits(gb, 17);
00669         bits -= 17;
00670     }
00671     ret <<= bits;
00672     ret |= get_bits(gb, bits);
00673     return ret;
00674 }
00675 
00676 static int read_sl_header(PESContext *pes, SLConfigDescr *sl, const uint8_t *buf, int buf_size)
00677 {
00678     GetBitContext gb;
00679     int au_start_flag = 0, au_end_flag = 0, ocr_flag = 0, idle_flag = 0;
00680     int padding_flag = 0, padding_bits = 0, inst_bitrate_flag = 0;
00681     int dts_flag = -1, cts_flag = -1;
00682     int64_t dts = AV_NOPTS_VALUE, cts = AV_NOPTS_VALUE;
00683     init_get_bits(&gb, buf, buf_size*8);
00684 
00685     if (sl->use_au_start)
00686         au_start_flag = get_bits1(&gb);
00687     if (sl->use_au_end)
00688         au_end_flag = get_bits1(&gb);
00689     if (!sl->use_au_start && !sl->use_au_end)
00690         au_start_flag = au_end_flag = 1;
00691     if (sl->ocr_len > 0)
00692         ocr_flag = get_bits1(&gb);
00693     if (sl->use_idle)
00694         idle_flag = get_bits1(&gb);
00695     if (sl->use_padding)
00696         padding_flag = get_bits1(&gb);
00697     if (padding_flag)
00698         padding_bits = get_bits(&gb, 3);
00699 
00700     if (!idle_flag && (!padding_flag || padding_bits != 0)) {
00701         if (sl->packet_seq_num_len)
00702             skip_bits_long(&gb, sl->packet_seq_num_len);
00703         if (sl->degr_prior_len)
00704             if (get_bits1(&gb))
00705                 skip_bits(&gb, sl->degr_prior_len);
00706         if (ocr_flag)
00707             skip_bits_long(&gb, sl->ocr_len);
00708         if (au_start_flag) {
00709             if (sl->use_rand_acc_pt)
00710                 get_bits1(&gb);
00711             if (sl->au_seq_num_len > 0)
00712                 skip_bits_long(&gb, sl->au_seq_num_len);
00713             if (sl->use_timestamps) {
00714                 dts_flag = get_bits1(&gb);
00715                 cts_flag = get_bits1(&gb);
00716             }
00717         }
00718         if (sl->inst_bitrate_len)
00719             inst_bitrate_flag = get_bits1(&gb);
00720         if (dts_flag == 1)
00721             dts = get_bits64(&gb, sl->timestamp_len);
00722         if (cts_flag == 1)
00723             cts = get_bits64(&gb, sl->timestamp_len);
00724         if (sl->au_len > 0)
00725             skip_bits_long(&gb, sl->au_len);
00726         if (inst_bitrate_flag)
00727             skip_bits_long(&gb, sl->inst_bitrate_len);
00728     }
00729 
00730     if (dts != AV_NOPTS_VALUE)
00731         pes->dts = dts;
00732     if (cts != AV_NOPTS_VALUE)
00733         pes->pts = cts;
00734 
00735     if (sl->timestamp_len && sl->timestamp_res)
00736         avpriv_set_pts_info(pes->st, sl->timestamp_len, 1, sl->timestamp_res);
00737 
00738     return (get_bits_count(&gb) + 7) >> 3;
00739 }
00740 
00741 /* return non zero if a packet could be constructed */
00742 static int mpegts_push_data(MpegTSFilter *filter,
00743                             const uint8_t *buf, int buf_size, int is_start,
00744                             int64_t pos)
00745 {
00746     PESContext *pes = filter->u.pes_filter.opaque;
00747     MpegTSContext *ts = pes->ts;
00748     const uint8_t *p;
00749     int len, code;
00750 
00751     if(!ts->pkt)
00752         return 0;
00753 
00754     if (is_start) {
00755         if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
00756             new_pes_packet(pes, ts->pkt);
00757             ts->stop_parse = 1;
00758         }
00759         pes->state = MPEGTS_HEADER;
00760         pes->data_index = 0;
00761         pes->ts_packet_pos = pos;
00762     }
00763     p = buf;
00764     while (buf_size > 0) {
00765         switch(pes->state) {
00766         case MPEGTS_HEADER:
00767             len = PES_START_SIZE - pes->data_index;
00768             if (len > buf_size)
00769                 len = buf_size;
00770             memcpy(pes->header + pes->data_index, p, len);
00771             pes->data_index += len;
00772             p += len;
00773             buf_size -= len;
00774             if (pes->data_index == PES_START_SIZE) {
00775                 /* we got all the PES or section header. We can now
00776                    decide */
00777                 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
00778                     pes->header[2] == 0x01) {
00779                     /* it must be an mpeg2 PES stream */
00780                     code = pes->header[3] | 0x100;
00781                     av_dlog(pes->stream, "pid=%x pes_code=%#x\n", pes->pid, code);
00782 
00783                     if ((pes->st && pes->st->discard == AVDISCARD_ALL) ||
00784                         code == 0x1be) /* padding_stream */
00785                         goto skip;
00786 
00787                     /* stream not present in PMT */
00788                     if (!pes->st) {
00789                         pes->st = avformat_new_stream(ts->stream, NULL);
00790                         if (!pes->st)
00791                             return AVERROR(ENOMEM);
00792                         pes->st->id = pes->pid;
00793                         mpegts_set_stream_info(pes->st, pes, 0, 0);
00794                     }
00795 
00796                     pes->total_size = AV_RB16(pes->header + 4);
00797                     /* NOTE: a zero total size means the PES size is
00798                        unbounded */
00799                     if (!pes->total_size)
00800                         pes->total_size = MAX_PES_PAYLOAD;
00801 
00802                     /* allocate pes buffer */
00803                     pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
00804                     if (!pes->buffer)
00805                         return AVERROR(ENOMEM);
00806 
00807                     if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
00808                         code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
00809                         code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
00810                         code != 0x1f8) {                  /* ITU-T Rec. H.222.1 type E stream */
00811                         pes->state = MPEGTS_PESHEADER;
00812                         if (pes->st->codec->codec_id == CODEC_ID_NONE) {
00813                             av_dlog(pes->stream, "pid=%x stream_type=%x probing\n",
00814                                     pes->pid, pes->stream_type);
00815                             pes->st->codec->codec_id = CODEC_ID_PROBE;
00816                         }
00817                     } else {
00818                         pes->state = MPEGTS_PAYLOAD;
00819                         pes->data_index = 0;
00820                     }
00821                 } else {
00822                     /* otherwise, it should be a table */
00823                     /* skip packet */
00824                 skip:
00825                     pes->state = MPEGTS_SKIP;
00826                     continue;
00827                 }
00828             }
00829             break;
00830             /**********************************************/
00831             /* PES packing parsing */
00832         case MPEGTS_PESHEADER:
00833             len = PES_HEADER_SIZE - pes->data_index;
00834             if (len < 0)
00835                 return -1;
00836             if (len > buf_size)
00837                 len = buf_size;
00838             memcpy(pes->header + pes->data_index, p, len);
00839             pes->data_index += len;
00840             p += len;
00841             buf_size -= len;
00842             if (pes->data_index == PES_HEADER_SIZE) {
00843                 pes->pes_header_size = pes->header[8] + 9;
00844                 pes->state = MPEGTS_PESHEADER_FILL;
00845             }
00846             break;
00847         case MPEGTS_PESHEADER_FILL:
00848             len = pes->pes_header_size - pes->data_index;
00849             if (len < 0)
00850                 return -1;
00851             if (len > buf_size)
00852                 len = buf_size;
00853             memcpy(pes->header + pes->data_index, p, len);
00854             pes->data_index += len;
00855             p += len;
00856             buf_size -= len;
00857             if (pes->data_index == pes->pes_header_size) {
00858                 const uint8_t *r;
00859                 unsigned int flags, pes_ext, skip;
00860 
00861                 flags = pes->header[7];
00862                 r = pes->header + 9;
00863                 pes->pts = AV_NOPTS_VALUE;
00864                 pes->dts = AV_NOPTS_VALUE;
00865                 if ((flags & 0xc0) == 0x80) {
00866                     pes->dts = pes->pts = ff_parse_pes_pts(r);
00867                     r += 5;
00868                 } else if ((flags & 0xc0) == 0xc0) {
00869                     pes->pts = ff_parse_pes_pts(r);
00870                     r += 5;
00871                     pes->dts = ff_parse_pes_pts(r);
00872                     r += 5;
00873                 }
00874                 pes->extended_stream_id = -1;
00875                 if (flags & 0x01) { /* PES extension */
00876                     pes_ext = *r++;
00877                     /* Skip PES private data, program packet sequence counter and P-STD buffer */
00878                     skip = (pes_ext >> 4) & 0xb;
00879                     skip += skip & 0x9;
00880                     r += skip;
00881                     if ((pes_ext & 0x41) == 0x01 &&
00882                         (r + 2) <= (pes->header + pes->pes_header_size)) {
00883                         /* PES extension 2 */
00884                         if ((r[0] & 0x7f) > 0 && (r[1] & 0x80) == 0)
00885                             pes->extended_stream_id = r[1];
00886                     }
00887                 }
00888 
00889                 /* we got the full header. We parse it and get the payload */
00890                 pes->state = MPEGTS_PAYLOAD;
00891                 pes->data_index = 0;
00892                 if (pes->stream_type == 0x12 && buf_size > 0) {
00893                     int sl_header_bytes = read_sl_header(pes, &pes->sl, p, buf_size);
00894                     pes->pes_header_size += sl_header_bytes;
00895                     p += sl_header_bytes;
00896                     buf_size -= sl_header_bytes;
00897                 }
00898             }
00899             break;
00900         case MPEGTS_PAYLOAD:
00901             if (buf_size > 0 && pes->buffer) {
00902                 if (pes->data_index > 0 && pes->data_index+buf_size > pes->total_size) {
00903                     new_pes_packet(pes, ts->pkt);
00904                     pes->total_size = MAX_PES_PAYLOAD;
00905                     pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
00906                     if (!pes->buffer)
00907                         return AVERROR(ENOMEM);
00908                     ts->stop_parse = 1;
00909                 } else if (pes->data_index == 0 && buf_size > pes->total_size) {
00910                     // pes packet size is < ts size packet and pes data is padded with 0xff
00911                     // not sure if this is legal in ts but see issue #2392
00912                     buf_size = pes->total_size;
00913                 }
00914                 memcpy(pes->buffer+pes->data_index, p, buf_size);
00915                 pes->data_index += buf_size;
00916             }
00917             buf_size = 0;
00918             /* emit complete packets with known packet size
00919              * decreases demuxer delay for infrequent packets like subtitles from
00920              * a couple of seconds to milliseconds for properly muxed files.
00921              * total_size is the number of bytes following pes_packet_length
00922              * in the pes header, i.e. not counting the first PES_START_SIZE bytes */
00923             if (!ts->stop_parse && pes->total_size < MAX_PES_PAYLOAD &&
00924                 pes->pes_header_size + pes->data_index == pes->total_size + PES_START_SIZE) {
00925                 ts->stop_parse = 1;
00926                 new_pes_packet(pes, ts->pkt);
00927             }
00928             break;
00929         case MPEGTS_SKIP:
00930             buf_size = 0;
00931             break;
00932         }
00933     }
00934 
00935     return 0;
00936 }
00937 
00938 static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
00939 {
00940     MpegTSFilter *tss;
00941     PESContext *pes;
00942 
00943     /* if no pid found, then add a pid context */
00944     pes = av_mallocz(sizeof(PESContext));
00945     if (!pes)
00946         return 0;
00947     pes->ts = ts;
00948     pes->stream = ts->stream;
00949     pes->pid = pid;
00950     pes->pcr_pid = pcr_pid;
00951     pes->state = MPEGTS_SKIP;
00952     pes->pts = AV_NOPTS_VALUE;
00953     pes->dts = AV_NOPTS_VALUE;
00954     tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
00955     if (!tss) {
00956         av_free(pes);
00957         return 0;
00958     }
00959     return pes;
00960 }
00961 
00962 #define MAX_LEVEL 4
00963 typedef struct {
00964     AVFormatContext *s;
00965     AVIOContext pb;
00966     Mp4Descr *descr;
00967     Mp4Descr *active_descr;
00968     int descr_count;
00969     int max_descr_count;
00970     int level;
00971 } MP4DescrParseContext;
00972 
00973 static int init_MP4DescrParseContext(
00974     MP4DescrParseContext *d, AVFormatContext *s, const uint8_t *buf,
00975     unsigned size, Mp4Descr *descr, int max_descr_count)
00976 {
00977     int ret;
00978     if (size > (1<<30))
00979         return AVERROR_INVALIDDATA;
00980 
00981     if ((ret = ffio_init_context(&d->pb, (unsigned char*)buf, size, 0,
00982                           NULL, NULL, NULL, NULL)) < 0)
00983         return ret;
00984 
00985     d->s = s;
00986     d->level = 0;
00987     d->descr_count = 0;
00988     d->descr = descr;
00989     d->active_descr = NULL;
00990     d->max_descr_count = max_descr_count;
00991 
00992     return 0;
00993 }
00994 
00995 static void update_offsets(AVIOContext *pb, int64_t *off, int *len) {
00996     int64_t new_off = avio_tell(pb);
00997     (*len) -= new_off - *off;
00998     *off = new_off;
00999 }
01000 
01001 static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
01002                            int target_tag);
01003 
01004 static int parse_mp4_descr_arr(MP4DescrParseContext *d, int64_t off, int len)
01005 {
01006     while (len > 0) {
01007         if (parse_mp4_descr(d, off, len, 0) < 0)
01008             return -1;
01009         update_offsets(&d->pb, &off, &len);
01010     }
01011     return 0;
01012 }
01013 
01014 static int parse_MP4IODescrTag(MP4DescrParseContext *d, int64_t off, int len)
01015 {
01016     avio_rb16(&d->pb); // ID
01017     avio_r8(&d->pb);
01018     avio_r8(&d->pb);
01019     avio_r8(&d->pb);
01020     avio_r8(&d->pb);
01021     avio_r8(&d->pb);
01022     update_offsets(&d->pb, &off, &len);
01023     return parse_mp4_descr_arr(d, off, len);
01024 }
01025 
01026 static int parse_MP4ODescrTag(MP4DescrParseContext *d, int64_t off, int len)
01027 {
01028     int id_flags;
01029     if (len < 2)
01030         return 0;
01031     id_flags = avio_rb16(&d->pb);
01032     if (!(id_flags & 0x0020)) { //URL_Flag
01033         update_offsets(&d->pb, &off, &len);
01034         return parse_mp4_descr_arr(d, off, len); //ES_Descriptor[]
01035     } else {
01036         return 0;
01037     }
01038 }
01039 
01040 static int parse_MP4ESDescrTag(MP4DescrParseContext *d, int64_t off, int len)
01041 {
01042     int es_id = 0;
01043     if (d->descr_count >= d->max_descr_count)
01044         return -1;
01045     ff_mp4_parse_es_descr(&d->pb, &es_id);
01046     d->active_descr = d->descr + (d->descr_count++);
01047 
01048     d->active_descr->es_id = es_id;
01049     update_offsets(&d->pb, &off, &len);
01050     parse_mp4_descr(d, off, len, MP4DecConfigDescrTag);
01051     update_offsets(&d->pb, &off, &len);
01052     if (len > 0)
01053         parse_mp4_descr(d, off, len, MP4SLDescrTag);
01054     d->active_descr = NULL;
01055     return 0;
01056 }
01057 
01058 static int parse_MP4DecConfigDescrTag(MP4DescrParseContext *d, int64_t off, int len)
01059 {
01060     Mp4Descr *descr = d->active_descr;
01061     if (!descr)
01062         return -1;
01063     d->active_descr->dec_config_descr = av_malloc(len);
01064     if (!descr->dec_config_descr)
01065         return AVERROR(ENOMEM);
01066     descr->dec_config_descr_len = len;
01067     avio_read(&d->pb, descr->dec_config_descr, len);
01068     return 0;
01069 }
01070 
01071 static int parse_MP4SLDescrTag(MP4DescrParseContext *d, int64_t off, int len)
01072 {
01073     Mp4Descr *descr = d->active_descr;
01074     int predefined;
01075     if (!descr)
01076         return -1;
01077 
01078     predefined = avio_r8(&d->pb);
01079     if (!predefined) {
01080         int lengths;
01081         int flags = avio_r8(&d->pb);
01082         descr->sl.use_au_start       = !!(flags & 0x80);
01083         descr->sl.use_au_end         = !!(flags & 0x40);
01084         descr->sl.use_rand_acc_pt    = !!(flags & 0x20);
01085         descr->sl.use_padding        = !!(flags & 0x08);
01086         descr->sl.use_timestamps     = !!(flags & 0x04);
01087         descr->sl.use_idle           = !!(flags & 0x02);
01088         descr->sl.timestamp_res      = avio_rb32(&d->pb);
01089                                        avio_rb32(&d->pb);
01090         descr->sl.timestamp_len      = avio_r8(&d->pb);
01091         descr->sl.ocr_len            = avio_r8(&d->pb);
01092         descr->sl.au_len             = avio_r8(&d->pb);
01093         descr->sl.inst_bitrate_len   = avio_r8(&d->pb);
01094         lengths                      = avio_rb16(&d->pb);
01095         descr->sl.degr_prior_len     = lengths >> 12;
01096         descr->sl.au_seq_num_len     = (lengths >> 7) & 0x1f;
01097         descr->sl.packet_seq_num_len = (lengths >> 2) & 0x1f;
01098     } else {
01099         av_log_missing_feature(d->s, "Predefined SLConfigDescriptor\n", 0);
01100     }
01101     return 0;
01102 }
01103 
01104 static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
01105                            int target_tag) {
01106     int tag;
01107     int len1 = ff_mp4_read_descr(d->s, &d->pb, &tag);
01108     update_offsets(&d->pb, &off, &len);
01109     if (len < 0 || len1 > len || len1 <= 0) {
01110         av_log(d->s, AV_LOG_ERROR, "Tag %x length violation new length %d bytes remaining %d\n", tag, len1, len);
01111         return -1;
01112     }
01113 
01114     if (d->level++ >= MAX_LEVEL) {
01115         av_log(d->s, AV_LOG_ERROR, "Maximum MP4 descriptor level exceeded\n");
01116         goto done;
01117     }
01118 
01119     if (target_tag && tag != target_tag) {
01120         av_log(d->s, AV_LOG_ERROR, "Found tag %x expected %x\n", tag, target_tag);
01121         goto done;
01122     }
01123 
01124     switch (tag) {
01125     case MP4IODescrTag:
01126         parse_MP4IODescrTag(d, off, len1);
01127         break;
01128     case MP4ODescrTag:
01129         parse_MP4ODescrTag(d, off, len1);
01130         break;
01131     case MP4ESDescrTag:
01132         parse_MP4ESDescrTag(d, off, len1);
01133         break;
01134     case MP4DecConfigDescrTag:
01135         parse_MP4DecConfigDescrTag(d, off, len1);
01136         break;
01137     case MP4SLDescrTag:
01138         parse_MP4SLDescrTag(d, off, len1);
01139         break;
01140     }
01141 
01142 done:
01143     d->level--;
01144     avio_seek(&d->pb, off + len1, SEEK_SET);
01145     return 0;
01146 }
01147 
01148 static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size,
01149                          Mp4Descr *descr, int *descr_count, int max_descr_count)
01150 {
01151     MP4DescrParseContext d;
01152     if (init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count) < 0)
01153         return -1;
01154 
01155     parse_mp4_descr(&d, avio_tell(&d.pb), size, MP4IODescrTag);
01156 
01157     *descr_count = d.descr_count;
01158     return 0;
01159 }
01160 
01161 static int mp4_read_od(AVFormatContext *s, const uint8_t *buf, unsigned size,
01162                        Mp4Descr *descr, int *descr_count, int max_descr_count)
01163 {
01164     MP4DescrParseContext d;
01165     if (init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count) < 0)
01166         return -1;
01167 
01168     parse_mp4_descr_arr(&d, avio_tell(&d.pb), size);
01169 
01170     *descr_count = d.descr_count;
01171     return 0;
01172 }
01173 
01174 static void m4sl_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
01175 {
01176     MpegTSContext *ts = filter->u.section_filter.opaque;
01177     SectionHeader h;
01178     const uint8_t *p, *p_end;
01179     AVIOContext pb;
01180     Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = {{ 0 }};
01181     int mp4_descr_count = 0;
01182     int i, pid;
01183     AVFormatContext *s = ts->stream;
01184 
01185     p_end = section + section_len - 4;
01186     p = section;
01187     if (parse_section_header(&h, &p, p_end) < 0)
01188         return;
01189     if (h.tid != M4OD_TID)
01190         return;
01191 
01192     mp4_read_od(s, p, (unsigned)(p_end - p), mp4_descr, &mp4_descr_count, MAX_MP4_DESCR_COUNT);
01193 
01194     for (pid = 0; pid < NB_PID_MAX; pid++) {
01195         if (!ts->pids[pid])
01196              continue;
01197         for (i = 0; i < mp4_descr_count; i++) {
01198             PESContext *pes;
01199             AVStream *st;
01200             if (ts->pids[pid]->es_id != mp4_descr[i].es_id)
01201                 continue;
01202             if (!(ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES)) {
01203                 av_log(s, AV_LOG_ERROR, "pid %x is not PES\n", pid);
01204                 continue;
01205             }
01206             pes = ts->pids[pid]->u.pes_filter.opaque;
01207             st = pes->st;
01208             if (!st) {
01209                 continue;
01210             }
01211 
01212             pes->sl = mp4_descr[i].sl;
01213 
01214             ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
01215                               mp4_descr[i].dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
01216             ff_mp4_read_dec_config_descr(s, st, &pb);
01217             if (st->codec->codec_id == CODEC_ID_AAC &&
01218                 st->codec->extradata_size > 0)
01219                 st->need_parsing = 0;
01220             if (st->codec->codec_id == CODEC_ID_H264 &&
01221                 st->codec->extradata_size > 0)
01222                 st->need_parsing = 0;
01223 
01224             if (st->codec->codec_id <= CODEC_ID_NONE) {
01225             } else if (st->codec->codec_id < CODEC_ID_FIRST_AUDIO) {
01226                 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
01227             } else if (st->codec->codec_id < CODEC_ID_FIRST_SUBTITLE) {
01228                 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
01229             } else if (st->codec->codec_id < CODEC_ID_FIRST_UNKNOWN) {
01230                 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
01231             }
01232         }
01233     }
01234     for (i = 0; i < mp4_descr_count; i++)
01235         av_free(mp4_descr[i].dec_config_descr);
01236 }
01237 
01238 int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,
01239                               const uint8_t **pp, const uint8_t *desc_list_end,
01240                               Mp4Descr *mp4_descr, int mp4_descr_count, int pid,
01241                               MpegTSContext *ts)
01242 {
01243     const uint8_t *desc_end;
01244     int desc_len, desc_tag, desc_es_id;
01245     char language[252];
01246     int i;
01247 
01248     desc_tag = get8(pp, desc_list_end);
01249     if (desc_tag < 0)
01250         return -1;
01251     desc_len = get8(pp, desc_list_end);
01252     if (desc_len < 0)
01253         return -1;
01254     desc_end = *pp + desc_len;
01255     if (desc_end > desc_list_end)
01256         return -1;
01257 
01258     av_dlog(fc, "tag: 0x%02x len=%d\n", desc_tag, desc_len);
01259 
01260     if (st->codec->codec_id == CODEC_ID_NONE &&
01261         stream_type == STREAM_TYPE_PRIVATE_DATA)
01262         mpegts_find_stream_type(st, desc_tag, DESC_types);
01263 
01264     switch(desc_tag) {
01265     case 0x1E: /* SL descriptor */
01266         desc_es_id = get16(pp, desc_end);
01267         if (ts && ts->pids[pid])
01268             ts->pids[pid]->es_id = desc_es_id;
01269         for (i = 0; i < mp4_descr_count; i++)
01270         if (mp4_descr[i].dec_config_descr_len &&
01271             mp4_descr[i].es_id == desc_es_id) {
01272             AVIOContext pb;
01273             ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
01274                           mp4_descr[i].dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
01275             ff_mp4_read_dec_config_descr(fc, st, &pb);
01276             if (st->codec->codec_id == CODEC_ID_AAC &&
01277                 st->codec->extradata_size > 0)
01278                 st->need_parsing = 0;
01279             if (st->codec->codec_id == CODEC_ID_MPEG4SYSTEMS)
01280                 mpegts_open_section_filter(ts, pid, m4sl_cb, ts, 1);
01281         }
01282         break;
01283     case 0x1F: /* FMC descriptor */
01284         get16(pp, desc_end);
01285         if (mp4_descr_count > 0 && st->codec->codec_id == CODEC_ID_AAC_LATM &&
01286             mp4_descr->dec_config_descr_len && mp4_descr->es_id == pid) {
01287             AVIOContext pb;
01288             ffio_init_context(&pb, mp4_descr->dec_config_descr,
01289                           mp4_descr->dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
01290             ff_mp4_read_dec_config_descr(fc, st, &pb);
01291             if (st->codec->codec_id == CODEC_ID_AAC &&
01292                 st->codec->extradata_size > 0)
01293                 st->need_parsing = 0;
01294         }
01295         break;
01296     case 0x56: /* DVB teletext descriptor */
01297         language[0] = get8(pp, desc_end);
01298         language[1] = get8(pp, desc_end);
01299         language[2] = get8(pp, desc_end);
01300         language[3] = 0;
01301         av_dict_set(&st->metadata, "language", language, 0);
01302         break;
01303     case 0x59: /* subtitling descriptor */
01304         language[0] = get8(pp, desc_end);
01305         language[1] = get8(pp, desc_end);
01306         language[2] = get8(pp, desc_end);
01307         language[3] = 0;
01308         /* hearing impaired subtitles detection */
01309         switch(get8(pp, desc_end)) {
01310         case 0x20: /* DVB subtitles (for the hard of hearing) with no monitor aspect ratio criticality */
01311         case 0x21: /* DVB subtitles (for the hard of hearing) for display on 4:3 aspect ratio monitor */
01312         case 0x22: /* DVB subtitles (for the hard of hearing) for display on 16:9 aspect ratio monitor */
01313         case 0x23: /* DVB subtitles (for the hard of hearing) for display on 2.21:1 aspect ratio monitor */
01314         case 0x24: /* DVB subtitles (for the hard of hearing) for display on a high definition monitor */
01315         case 0x25: /* DVB subtitles (for the hard of hearing) with plano-stereoscopic disparity for display on a high definition monitor */
01316             st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
01317             break;
01318         }
01319         if (st->codec->extradata) {
01320             if (st->codec->extradata_size == 4 && memcmp(st->codec->extradata, *pp, 4))
01321                 av_log_ask_for_sample(fc, "DVB sub with multiple IDs\n");
01322         } else {
01323             st->codec->extradata = av_malloc(4 + FF_INPUT_BUFFER_PADDING_SIZE);
01324             if (st->codec->extradata) {
01325                 st->codec->extradata_size = 4;
01326                 memcpy(st->codec->extradata, *pp, 4);
01327             }
01328         }
01329         *pp += 4;
01330         av_dict_set(&st->metadata, "language", language, 0);
01331         break;
01332     case 0x0a: /* ISO 639 language descriptor */
01333         for (i = 0; i + 4 <= desc_len; i += 4) {
01334             language[i + 0] = get8(pp, desc_end);
01335             language[i + 1] = get8(pp, desc_end);
01336             language[i + 2] = get8(pp, desc_end);
01337             language[i + 3] = ',';
01338         switch (get8(pp, desc_end)) {
01339             case 0x01: st->disposition |= AV_DISPOSITION_CLEAN_EFFECTS; break;
01340             case 0x02: st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED; break;
01341             case 0x03: st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED; break;
01342         }
01343         }
01344         if (i) {
01345             language[i - 1] = 0;
01346             av_dict_set(&st->metadata, "language", language, 0);
01347         }
01348         break;
01349     case 0x05: /* registration descriptor */
01350         st->codec->codec_tag = bytestream_get_le32(pp);
01351         av_dlog(fc, "reg_desc=%.4s\n", (char*)&st->codec->codec_tag);
01352         if (st->codec->codec_id == CODEC_ID_NONE &&
01353             stream_type == STREAM_TYPE_PRIVATE_DATA)
01354             mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
01355         break;
01356     default:
01357         break;
01358     }
01359     *pp = desc_end;
01360     return 0;
01361 }
01362 
01363 static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
01364 {
01365     MpegTSContext *ts = filter->u.section_filter.opaque;
01366     SectionHeader h1, *h = &h1;
01367     PESContext *pes;
01368     AVStream *st;
01369     const uint8_t *p, *p_end, *desc_list_end;
01370     int program_info_length, pcr_pid, pid, stream_type;
01371     int desc_list_len;
01372     uint32_t prog_reg_desc = 0; /* registration descriptor */
01373 
01374     Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = {{ 0 }};
01375     int mp4_descr_count = 0;
01376     int i;
01377 
01378     av_dlog(ts->stream, "PMT: len %i\n", section_len);
01379     hex_dump_debug(ts->stream, (uint8_t *)section, section_len);
01380 
01381     p_end = section + section_len - 4;
01382     p = section;
01383     if (parse_section_header(h, &p, p_end) < 0)
01384         return;
01385 
01386     av_dlog(ts->stream, "sid=0x%x sec_num=%d/%d\n",
01387            h->id, h->sec_num, h->last_sec_num);
01388 
01389     if (h->tid != PMT_TID)
01390         return;
01391 
01392     clear_program(ts, h->id);
01393     pcr_pid = get16(&p, p_end) & 0x1fff;
01394     if (pcr_pid < 0)
01395         return;
01396     add_pid_to_pmt(ts, h->id, pcr_pid);
01397 
01398     av_dlog(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
01399 
01400     program_info_length = get16(&p, p_end) & 0xfff;
01401     if (program_info_length < 0)
01402         return;
01403     while(program_info_length >= 2) {
01404         uint8_t tag, len;
01405         tag = get8(&p, p_end);
01406         len = get8(&p, p_end);
01407 
01408         av_dlog(ts->stream, "program tag: 0x%02x len=%d\n", tag, len);
01409 
01410         if(len > program_info_length - 2)
01411             //something else is broken, exit the program_descriptors_loop
01412             break;
01413         program_info_length -= len + 2;
01414         if (tag == 0x1d) { // IOD descriptor
01415             get8(&p, p_end); // scope
01416             get8(&p, p_end); // label
01417             len -= 2;
01418             mp4_read_iods(ts->stream, p, len, mp4_descr + mp4_descr_count,
01419                           &mp4_descr_count, MAX_MP4_DESCR_COUNT);
01420         } else if (tag == 0x05 && len >= 4) { // registration descriptor
01421             prog_reg_desc = bytestream_get_le32(&p);
01422             len -= 4;
01423         }
01424         p += len;
01425     }
01426     p += program_info_length;
01427     if (p >= p_end)
01428         goto out;
01429 
01430     // stop parsing after pmt, we found header
01431     if (!ts->stream->nb_streams)
01432         ts->stop_parse = 1;
01433 
01434     for(;;) {
01435         st = 0;
01436         pes = NULL;
01437         stream_type = get8(&p, p_end);
01438         if (stream_type < 0)
01439             break;
01440         pid = get16(&p, p_end) & 0x1fff;
01441         if (pid < 0)
01442             break;
01443 
01444         /* now create stream */
01445         if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
01446             pes = ts->pids[pid]->u.pes_filter.opaque;
01447             if (!pes->st) {
01448                 pes->st = avformat_new_stream(pes->stream, NULL);
01449                 pes->st->id = pes->pid;
01450             }
01451             st = pes->st;
01452         } else if (stream_type != 0x13) {
01453             if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
01454             pes = add_pes_stream(ts, pid, pcr_pid);
01455             if (pes) {
01456                 st = avformat_new_stream(pes->stream, NULL);
01457                 st->id = pes->pid;
01458             }
01459         } else {
01460             int idx = ff_find_stream_index(ts->stream, pid);
01461             if (idx >= 0) {
01462                 st = ts->stream->streams[idx];
01463             } else {
01464                 st = avformat_new_stream(ts->stream, NULL);
01465                 st->id = pid;
01466                 st->codec->codec_type = AVMEDIA_TYPE_DATA;
01467             }
01468         }
01469 
01470         if (!st)
01471             goto out;
01472 
01473         if (pes && !pes->stream_type)
01474             mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
01475 
01476         add_pid_to_pmt(ts, h->id, pid);
01477 
01478         ff_program_add_stream_index(ts->stream, h->id, st->index);
01479 
01480         desc_list_len = get16(&p, p_end) & 0xfff;
01481         if (desc_list_len < 0)
01482             break;
01483         desc_list_end = p + desc_list_len;
01484         if (desc_list_end > p_end)
01485             break;
01486         for(;;) {
01487             if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p, desc_list_end,
01488                 mp4_descr, mp4_descr_count, pid, ts) < 0)
01489                 break;
01490 
01491             if (pes && prog_reg_desc == AV_RL32("HDMV") && stream_type == 0x83 && pes->sub_st) {
01492                 ff_program_add_stream_index(ts->stream, h->id, pes->sub_st->index);
01493                 pes->sub_st->codec->codec_tag = st->codec->codec_tag;
01494             }
01495         }
01496         p = desc_list_end;
01497     }
01498 
01499  out:
01500     for (i = 0; i < mp4_descr_count; i++)
01501         av_free(mp4_descr[i].dec_config_descr);
01502 }
01503 
01504 static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
01505 {
01506     MpegTSContext *ts = filter->u.section_filter.opaque;
01507     SectionHeader h1, *h = &h1;
01508     const uint8_t *p, *p_end;
01509     int sid, pmt_pid;
01510 
01511     av_dlog(ts->stream, "PAT:\n");
01512     hex_dump_debug(ts->stream, (uint8_t *)section, section_len);
01513 
01514     p_end = section + section_len - 4;
01515     p = section;
01516     if (parse_section_header(h, &p, p_end) < 0)
01517         return;
01518     if (h->tid != PAT_TID)
01519         return;
01520 
01521     clear_programs(ts);
01522     for(;;) {
01523         sid = get16(&p, p_end);
01524         if (sid < 0)
01525             break;
01526         pmt_pid = get16(&p, p_end) & 0x1fff;
01527         if (pmt_pid < 0)
01528             break;
01529 
01530         av_dlog(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
01531 
01532         if (sid == 0x0000) {
01533             /* NIT info */
01534         } else {
01535             av_new_program(ts->stream, sid);
01536             if (ts->pids[pmt_pid])
01537                 mpegts_close_filter(ts, ts->pids[pmt_pid]);
01538             mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
01539             add_pat_entry(ts, sid);
01540             add_pid_to_pmt(ts, sid, 0); //add pat pid to program
01541             add_pid_to_pmt(ts, sid, pmt_pid);
01542         }
01543     }
01544 }
01545 
01546 static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
01547 {
01548     MpegTSContext *ts = filter->u.section_filter.opaque;
01549     SectionHeader h1, *h = &h1;
01550     const uint8_t *p, *p_end, *desc_list_end, *desc_end;
01551     int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
01552     char *name, *provider_name;
01553 
01554     av_dlog(ts->stream, "SDT:\n");
01555     hex_dump_debug(ts->stream, (uint8_t *)section, section_len);
01556 
01557     p_end = section + section_len - 4;
01558     p = section;
01559     if (parse_section_header(h, &p, p_end) < 0)
01560         return;
01561     if (h->tid != SDT_TID)
01562         return;
01563     onid = get16(&p, p_end);
01564     if (onid < 0)
01565         return;
01566     val = get8(&p, p_end);
01567     if (val < 0)
01568         return;
01569     for(;;) {
01570         sid = get16(&p, p_end);
01571         if (sid < 0)
01572             break;
01573         val = get8(&p, p_end);
01574         if (val < 0)
01575             break;
01576         desc_list_len = get16(&p, p_end) & 0xfff;
01577         if (desc_list_len < 0)
01578             break;
01579         desc_list_end = p + desc_list_len;
01580         if (desc_list_end > p_end)
01581             break;
01582         for(;;) {
01583             desc_tag = get8(&p, desc_list_end);
01584             if (desc_tag < 0)
01585                 break;
01586             desc_len = get8(&p, desc_list_end);
01587             desc_end = p + desc_len;
01588             if (desc_end > desc_list_end)
01589                 break;
01590 
01591             av_dlog(ts->stream, "tag: 0x%02x len=%d\n",
01592                    desc_tag, desc_len);
01593 
01594             switch(desc_tag) {
01595             case 0x48:
01596                 service_type = get8(&p, p_end);
01597                 if (service_type < 0)
01598                     break;
01599                 provider_name = getstr8(&p, p_end);
01600                 if (!provider_name)
01601                     break;
01602                 name = getstr8(&p, p_end);
01603                 if (name) {
01604                     AVProgram *program = av_new_program(ts->stream, sid);
01605                     if(program) {
01606                         av_dict_set(&program->metadata, "service_name", name, 0);
01607                         av_dict_set(&program->metadata, "service_provider", provider_name, 0);
01608                     }
01609                 }
01610                 av_free(name);
01611                 av_free(provider_name);
01612                 break;
01613             default:
01614                 break;
01615             }
01616             p = desc_end;
01617         }
01618         p = desc_list_end;
01619     }
01620 }
01621 
01622 /* handle one TS packet */
01623 static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
01624 {
01625     AVFormatContext *s = ts->stream;
01626     MpegTSFilter *tss;
01627     int len, pid, cc, expected_cc, cc_ok, afc, is_start, is_discontinuity,
01628         has_adaptation, has_payload;
01629     const uint8_t *p, *p_end;
01630     int64_t pos;
01631 
01632     pid = AV_RB16(packet + 1) & 0x1fff;
01633     if(pid && discard_pid(ts, pid))
01634         return 0;
01635     is_start = packet[1] & 0x40;
01636     tss = ts->pids[pid];
01637     if (ts->auto_guess && tss == NULL && is_start) {
01638         add_pes_stream(ts, pid, -1);
01639         tss = ts->pids[pid];
01640     }
01641     if (!tss)
01642         return 0;
01643 
01644     afc = (packet[3] >> 4) & 3;
01645     if (afc == 0) /* reserved value */
01646         return 0;
01647     has_adaptation = afc & 2;
01648     has_payload = afc & 1;
01649     is_discontinuity = has_adaptation
01650                 && packet[4] != 0 /* with length > 0 */
01651                 && (packet[5] & 0x80); /* and discontinuity indicated */
01652 
01653     /* continuity check (currently not used) */
01654     cc = (packet[3] & 0xf);
01655     expected_cc = has_payload ? (tss->last_cc + 1) & 0x0f : tss->last_cc;
01656     cc_ok = pid == 0x1FFF // null packet PID
01657             || is_discontinuity
01658             || tss->last_cc < 0
01659             || expected_cc == cc;
01660 
01661     tss->last_cc = cc;
01662     if (!cc_ok) {
01663         av_log(ts->stream, AV_LOG_WARNING,
01664                "Continuity check failed for pid %d expected %d got %d\n",
01665                pid, expected_cc, cc);
01666         if(tss->type == MPEGTS_PES) {
01667             PESContext *pc = tss->u.pes_filter.opaque;
01668             pc->flags |= AV_PKT_FLAG_CORRUPT;
01669         }
01670     }
01671 
01672     if (!has_payload)
01673         return 0;
01674     p = packet + 4;
01675     if (has_adaptation) {
01676         /* skip adaptation field */
01677         p += p[0] + 1;
01678     }
01679     /* if past the end of packet, ignore */
01680     p_end = packet + TS_PACKET_SIZE;
01681     if (p >= p_end)
01682         return 0;
01683 
01684     pos = avio_tell(ts->stream->pb);
01685     ts->pos47= pos % ts->raw_packet_size;
01686 
01687     if (tss->type == MPEGTS_SECTION) {
01688         if (is_start) {
01689             /* pointer field present */
01690             len = *p++;
01691             if (p + len > p_end)
01692                 return 0;
01693             if (len && cc_ok) {
01694                 /* write remaining section bytes */
01695                 write_section_data(s, tss,
01696                                    p, len, 0);
01697                 /* check whether filter has been closed */
01698                 if (!ts->pids[pid])
01699                     return 0;
01700             }
01701             p += len;
01702             if (p < p_end) {
01703                 write_section_data(s, tss,
01704                                    p, p_end - p, 1);
01705             }
01706         } else {
01707             if (cc_ok) {
01708                 write_section_data(s, tss,
01709                                    p, p_end - p, 0);
01710             }
01711         }
01712     } else {
01713         int ret;
01714         // Note: The position here points actually behind the current packet.
01715         if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
01716                                             pos - ts->raw_packet_size)) < 0)
01717             return ret;
01718     }
01719 
01720     return 0;
01721 }
01722 
01723 /* XXX: try to find a better synchro over several packets (use
01724    get_packet_size() ?) */
01725 static int mpegts_resync(AVFormatContext *s)
01726 {
01727     AVIOContext *pb = s->pb;
01728     int c, i;
01729 
01730     for(i = 0;i < MAX_RESYNC_SIZE; i++) {
01731         c = avio_r8(pb);
01732         if (pb->eof_reached)
01733             return -1;
01734         if (c == 0x47) {
01735             avio_seek(pb, -1, SEEK_CUR);
01736             return 0;
01737         }
01738     }
01739     av_log(s, AV_LOG_ERROR, "max resync size reached, could not find sync byte\n");
01740     /* no sync found */
01741     return -1;
01742 }
01743 
01744 /* return -1 if error or EOF. Return 0 if OK. */
01745 static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size)
01746 {
01747     AVIOContext *pb = s->pb;
01748     int skip, len;
01749 
01750     for(;;) {
01751         len = avio_read(pb, buf, TS_PACKET_SIZE);
01752         if (len != TS_PACKET_SIZE)
01753             return len < 0 ? len : AVERROR_EOF;
01754         /* check packet sync byte */
01755         if (buf[0] != 0x47) {
01756             /* find a new packet start */
01757             avio_seek(pb, -TS_PACKET_SIZE, SEEK_CUR);
01758             if (mpegts_resync(s) < 0)
01759                 return AVERROR(EAGAIN);
01760             else
01761                 continue;
01762         } else {
01763             skip = raw_packet_size - TS_PACKET_SIZE;
01764             if (skip > 0)
01765                 avio_skip(pb, skip);
01766             break;
01767         }
01768     }
01769     return 0;
01770 }
01771 
01772 static int handle_packets(MpegTSContext *ts, int nb_packets)
01773 {
01774     AVFormatContext *s = ts->stream;
01775     uint8_t packet[TS_PACKET_SIZE+FF_INPUT_BUFFER_PADDING_SIZE];
01776     int packet_num, ret = 0;
01777 
01778     if (avio_tell(s->pb) != ts->last_pos) {
01779         int i;
01780         av_dlog(ts->stream, "Skipping after seek\n");
01781         /* seek detected, flush pes buffer */
01782         for (i = 0; i < NB_PID_MAX; i++) {
01783             if (ts->pids[i]) {
01784                 if (ts->pids[i]->type == MPEGTS_PES) {
01785                    PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
01786                    av_freep(&pes->buffer);
01787                    pes->data_index = 0;
01788                    pes->state = MPEGTS_SKIP; /* skip until pes header */
01789                 }
01790                 ts->pids[i]->last_cc = -1;
01791             }
01792         }
01793     }
01794 
01795     ts->stop_parse = 0;
01796     packet_num = 0;
01797     memset(packet + TS_PACKET_SIZE, 0, FF_INPUT_BUFFER_PADDING_SIZE);
01798     for(;;) {
01799         if (ts->stop_parse>0)
01800             break;
01801         packet_num++;
01802         if (nb_packets != 0 && packet_num >= nb_packets)
01803             break;
01804         ret = read_packet(s, packet, ts->raw_packet_size);
01805         if (ret != 0)
01806             break;
01807         ret = handle_packet(ts, packet);
01808         if (ret != 0)
01809             break;
01810     }
01811     ts->last_pos = avio_tell(s->pb);
01812     return ret;
01813 }
01814 
01815 static int mpegts_probe(AVProbeData *p)
01816 {
01817 #if 1
01818     const int size= p->buf_size;
01819     int score, fec_score, dvhs_score;
01820     int check_count= size / TS_FEC_PACKET_SIZE;
01821 #define CHECK_COUNT 10
01822 
01823     if (check_count < CHECK_COUNT)
01824         return -1;
01825 
01826     score     = analyze(p->buf, TS_PACKET_SIZE     *check_count, TS_PACKET_SIZE     , NULL)*CHECK_COUNT/check_count;
01827     dvhs_score= analyze(p->buf, TS_DVHS_PACKET_SIZE*check_count, TS_DVHS_PACKET_SIZE, NULL)*CHECK_COUNT/check_count;
01828     fec_score = analyze(p->buf, TS_FEC_PACKET_SIZE *check_count, TS_FEC_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
01829 //    av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
01830 
01831 // we need a clear definition for the returned score otherwise things will become messy sooner or later
01832     if     (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score     - CHECK_COUNT;
01833     else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score  - CHECK_COUNT;
01834     else if(                 fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
01835     else                                    return -1;
01836 #else
01837     /* only use the extension for safer guess */
01838     if (av_match_ext(p->filename, "ts"))
01839         return AVPROBE_SCORE_MAX;
01840     else
01841         return 0;
01842 #endif
01843 }
01844 
01845 /* return the 90kHz PCR and the extension for the 27MHz PCR. return
01846    (-1) if not available */
01847 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
01848                      const uint8_t *packet)
01849 {
01850     int afc, len, flags;
01851     const uint8_t *p;
01852     unsigned int v;
01853 
01854     afc = (packet[3] >> 4) & 3;
01855     if (afc <= 1)
01856         return -1;
01857     p = packet + 4;
01858     len = p[0];
01859     p++;
01860     if (len == 0)
01861         return -1;
01862     flags = *p++;
01863     len--;
01864     if (!(flags & 0x10))
01865         return -1;
01866     if (len < 6)
01867         return -1;
01868     v = AV_RB32(p);
01869     *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
01870     *ppcr_low = ((p[4] & 1) << 8) | p[5];
01871     return 0;
01872 }
01873 
01874 static int mpegts_read_header(AVFormatContext *s,
01875                               AVFormatParameters *ap)
01876 {
01877     MpegTSContext *ts = s->priv_data;
01878     AVIOContext *pb = s->pb;
01879     uint8_t buf[5*1024];
01880     int len;
01881     int64_t pos;
01882 
01883     /* read the first 1024 bytes to get packet size */
01884     pos = avio_tell(pb);
01885     len = avio_read(pb, buf, sizeof(buf));
01886     if (len != sizeof(buf))
01887         goto fail;
01888     ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
01889     if (ts->raw_packet_size <= 0)
01890         goto fail;
01891     ts->stream = s;
01892     ts->auto_guess = 0;
01893 
01894     if (s->iformat == &ff_mpegts_demuxer) {
01895         /* normal demux */
01896 
01897         /* first do a scan to get all the services */
01898         if (pb->seekable && avio_seek(pb, pos, SEEK_SET) < 0)
01899             av_log(s, AV_LOG_ERROR, "Unable to seek back to the start\n");
01900 
01901         mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
01902 
01903         mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
01904 
01905         handle_packets(ts, s->probesize / ts->raw_packet_size);
01906         /* if could not find service, enable auto_guess */
01907 
01908         ts->auto_guess = 1;
01909 
01910         av_dlog(ts->stream, "tuning done\n");
01911 
01912         s->ctx_flags |= AVFMTCTX_NOHEADER;
01913     } else {
01914         AVStream *st;
01915         int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
01916         int64_t pcrs[2], pcr_h;
01917         int packet_count[2];
01918         uint8_t packet[TS_PACKET_SIZE];
01919 
01920         /* only read packets */
01921 
01922         st = avformat_new_stream(s, NULL);
01923         if (!st)
01924             goto fail;
01925         avpriv_set_pts_info(st, 60, 1, 27000000);
01926         st->codec->codec_type = AVMEDIA_TYPE_DATA;
01927         st->codec->codec_id = CODEC_ID_MPEG2TS;
01928 
01929         /* we iterate until we find two PCRs to estimate the bitrate */
01930         pcr_pid = -1;
01931         nb_pcrs = 0;
01932         nb_packets = 0;
01933         for(;;) {
01934             ret = read_packet(s, packet, ts->raw_packet_size);
01935             if (ret < 0)
01936                 return -1;
01937             pid = AV_RB16(packet + 1) & 0x1fff;
01938             if ((pcr_pid == -1 || pcr_pid == pid) &&
01939                 parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
01940                 pcr_pid = pid;
01941                 packet_count[nb_pcrs] = nb_packets;
01942                 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
01943                 nb_pcrs++;
01944                 if (nb_pcrs >= 2)
01945                     break;
01946             }
01947             nb_packets++;
01948         }
01949 
01950         /* NOTE1: the bitrate is computed without the FEC */
01951         /* NOTE2: it is only the bitrate of the start of the stream */
01952         ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
01953         ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
01954         s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
01955         st->codec->bit_rate = s->bit_rate;
01956         st->start_time = ts->cur_pcr;
01957         av_dlog(ts->stream, "start=%0.3f pcr=%0.3f incr=%d\n",
01958                 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
01959     }
01960 
01961     avio_seek(pb, pos, SEEK_SET);
01962     return 0;
01963  fail:
01964     return -1;
01965 }
01966 
01967 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
01968 
01969 static int mpegts_raw_read_packet(AVFormatContext *s,
01970                                   AVPacket *pkt)
01971 {
01972     MpegTSContext *ts = s->priv_data;
01973     int ret, i;
01974     int64_t pcr_h, next_pcr_h, pos;
01975     int pcr_l, next_pcr_l;
01976     uint8_t pcr_buf[12];
01977 
01978     if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
01979         return AVERROR(ENOMEM);
01980     pkt->pos= avio_tell(s->pb);
01981     ret = read_packet(s, pkt->data, ts->raw_packet_size);
01982     if (ret < 0) {
01983         av_free_packet(pkt);
01984         return ret;
01985     }
01986     if (ts->mpeg2ts_compute_pcr) {
01987         /* compute exact PCR for each packet */
01988         if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
01989             /* we read the next PCR (XXX: optimize it by using a bigger buffer */
01990             pos = avio_tell(s->pb);
01991             for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
01992                 avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
01993                 avio_read(s->pb, pcr_buf, 12);
01994                 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
01995                     /* XXX: not precise enough */
01996                     ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
01997                         (i + 1);
01998                     break;
01999                 }
02000             }
02001             avio_seek(s->pb, pos, SEEK_SET);
02002             /* no next PCR found: we use previous increment */
02003             ts->cur_pcr = pcr_h * 300 + pcr_l;
02004         }
02005         pkt->pts = ts->cur_pcr;
02006         pkt->duration = ts->pcr_incr;
02007         ts->cur_pcr += ts->pcr_incr;
02008     }
02009     pkt->stream_index = 0;
02010     return 0;
02011 }
02012 
02013 static int mpegts_read_packet(AVFormatContext *s,
02014                               AVPacket *pkt)
02015 {
02016     MpegTSContext *ts = s->priv_data;
02017     int ret, i;
02018 
02019     ts->pkt = pkt;
02020     ret = handle_packets(ts, 0);
02021     if (ret < 0) {
02022         /* flush pes data left */
02023         for (i = 0; i < NB_PID_MAX; i++) {
02024             if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
02025                 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
02026                 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
02027                     new_pes_packet(pes, pkt);
02028                     pes->state = MPEGTS_SKIP;
02029                     ret = 0;
02030                     break;
02031                 }
02032             }
02033         }
02034     }
02035 
02036     return ret;
02037 }
02038 
02039 static int mpegts_read_close(AVFormatContext *s)
02040 {
02041     MpegTSContext *ts = s->priv_data;
02042     int i;
02043 
02044     clear_programs(ts);
02045 
02046     for(i=0;i<NB_PID_MAX;i++)
02047         if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
02048 
02049     return 0;
02050 }
02051 
02052 static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
02053                               int64_t *ppos, int64_t pos_limit)
02054 {
02055     MpegTSContext *ts = s->priv_data;
02056     int64_t pos, timestamp;
02057     uint8_t buf[TS_PACKET_SIZE];
02058     int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
02059     const int find_next= 1;
02060     pos = ((*ppos  + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
02061     if (find_next) {
02062         for(;;) {
02063             avio_seek(s->pb, pos, SEEK_SET);
02064             if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
02065                 return AV_NOPTS_VALUE;
02066             if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
02067                 parse_pcr(&timestamp, &pcr_l, buf) == 0) {
02068                 break;
02069             }
02070             pos += ts->raw_packet_size;
02071         }
02072     } else {
02073         for(;;) {
02074             pos -= ts->raw_packet_size;
02075             if (pos < 0)
02076                 return AV_NOPTS_VALUE;
02077             avio_seek(s->pb, pos, SEEK_SET);
02078             if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
02079                 return AV_NOPTS_VALUE;
02080             if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
02081                 parse_pcr(&timestamp, &pcr_l, buf) == 0) {
02082                 break;
02083             }
02084         }
02085     }
02086     *ppos = pos;
02087 
02088     return timestamp;
02089 }
02090 
02091 #ifdef USE_SYNCPOINT_SEARCH
02092 
02093 static int read_seek2(AVFormatContext *s,
02094                       int stream_index,
02095                       int64_t min_ts,
02096                       int64_t target_ts,
02097                       int64_t max_ts,
02098                       int flags)
02099 {
02100     int64_t pos;
02101 
02102     int64_t ts_ret, ts_adj;
02103     int stream_index_gen_search;
02104     AVStream *st;
02105     AVParserState *backup;
02106 
02107     backup = ff_store_parser_state(s);
02108 
02109     // detect direction of seeking for search purposes
02110     flags |= (target_ts - min_ts > (uint64_t)(max_ts - target_ts)) ?
02111              AVSEEK_FLAG_BACKWARD : 0;
02112 
02113     if (flags & AVSEEK_FLAG_BYTE) {
02114         // use position directly, we will search starting from it
02115         pos = target_ts;
02116     } else {
02117         // search for some position with good timestamp match
02118         if (stream_index < 0) {
02119             stream_index_gen_search = av_find_default_stream_index(s);
02120             if (stream_index_gen_search < 0) {
02121                 ff_restore_parser_state(s, backup);
02122                 return -1;
02123             }
02124 
02125             st = s->streams[stream_index_gen_search];
02126             // timestamp for default must be expressed in AV_TIME_BASE units
02127             ts_adj = av_rescale(target_ts,
02128                                 st->time_base.den,
02129                                 AV_TIME_BASE * (int64_t)st->time_base.num);
02130         } else {
02131             ts_adj = target_ts;
02132             stream_index_gen_search = stream_index;
02133         }
02134         pos = ff_gen_search(s, stream_index_gen_search, ts_adj,
02135                             0, INT64_MAX, -1,
02136                             AV_NOPTS_VALUE,
02137                             AV_NOPTS_VALUE,
02138                             flags, &ts_ret, mpegts_get_pcr);
02139         if (pos < 0) {
02140             ff_restore_parser_state(s, backup);
02141             return -1;
02142         }
02143     }
02144 
02145     // search for actual matching keyframe/starting position for all streams
02146     if (ff_gen_syncpoint_search(s, stream_index, pos,
02147                                 min_ts, target_ts, max_ts,
02148                                 flags) < 0) {
02149         ff_restore_parser_state(s, backup);
02150         return -1;
02151     }
02152 
02153     ff_free_parser_state(s, backup);
02154     return 0;
02155 }
02156 
02157 static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags)
02158 {
02159     int ret;
02160     if (flags & AVSEEK_FLAG_BACKWARD) {
02161         flags &= ~AVSEEK_FLAG_BACKWARD;
02162         ret = read_seek2(s, stream_index, INT64_MIN, target_ts, target_ts, flags);
02163         if (ret < 0)
02164             // for compatibility reasons, seek to the best-fitting timestamp
02165             ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags);
02166     } else {
02167         ret = read_seek2(s, stream_index, target_ts, target_ts, INT64_MAX, flags);
02168         if (ret < 0)
02169             // for compatibility reasons, seek to the best-fitting timestamp
02170             ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags);
02171     }
02172     return ret;
02173 }
02174 
02175 #else
02176 
02177 static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
02178     MpegTSContext *ts = s->priv_data;
02179     uint8_t buf[TS_PACKET_SIZE];
02180     int64_t pos;
02181 
02182     if (ff_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
02183         return -1;
02184 
02185     pos= avio_tell(s->pb);
02186 
02187     for(;;) {
02188         avio_seek(s->pb, pos, SEEK_SET);
02189         if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
02190             return -1;
02191 //        pid = AV_RB16(buf + 1) & 0x1fff;
02192         if(buf[1] & 0x40) break;
02193         pos += ts->raw_packet_size;
02194     }
02195     avio_seek(s->pb, pos, SEEK_SET);
02196 
02197     return 0;
02198 }
02199 
02200 #endif
02201 
02202 /**************************************************************/
02203 /* parsing functions - called from other demuxers such as RTP */
02204 
02205 MpegTSContext *ff_mpegts_parse_open(AVFormatContext *s)
02206 {
02207     MpegTSContext *ts;
02208 
02209     ts = av_mallocz(sizeof(MpegTSContext));
02210     if (!ts)
02211         return NULL;
02212     /* no stream case, currently used by RTP */
02213     ts->raw_packet_size = TS_PACKET_SIZE;
02214     ts->stream = s;
02215     ts->auto_guess = 1;
02216     return ts;
02217 }
02218 
02219 /* return the consumed length if a packet was output, or -1 if no
02220    packet is output */
02221 int ff_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
02222                         const uint8_t *buf, int len)
02223 {
02224     int len1;
02225 
02226     len1 = len;
02227     ts->pkt = pkt;
02228     ts->stop_parse = 0;
02229     for(;;) {
02230         if (ts->stop_parse>0)
02231             break;
02232         if (len < TS_PACKET_SIZE)
02233             return -1;
02234         if (buf[0] != 0x47) {
02235             buf++;
02236             len--;
02237         } else {
02238             handle_packet(ts, buf);
02239             buf += TS_PACKET_SIZE;
02240             len -= TS_PACKET_SIZE;
02241         }
02242     }
02243     return len1 - len;
02244 }
02245 
02246 void ff_mpegts_parse_close(MpegTSContext *ts)
02247 {
02248     int i;
02249 
02250     for(i=0;i<NB_PID_MAX;i++)
02251         av_free(ts->pids[i]);
02252     av_free(ts);
02253 }
02254 
02255 AVInputFormat ff_mpegts_demuxer = {
02256     .name           = "mpegts",
02257     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
02258     .priv_data_size = sizeof(MpegTSContext),
02259     .read_probe     = mpegts_probe,
02260     .read_header    = mpegts_read_header,
02261     .read_packet    = mpegts_read_packet,
02262     .read_close     = mpegts_read_close,
02263     .read_seek      = read_seek,
02264     .read_timestamp = mpegts_get_pcr,
02265     .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
02266 #ifdef USE_SYNCPOINT_SEARCH
02267     .read_seek2 = read_seek2,
02268 #endif
02269 };
02270 
02271 AVInputFormat ff_mpegtsraw_demuxer = {
02272     .name           = "mpegtsraw",
02273     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-2 raw transport stream format"),
02274     .priv_data_size = sizeof(MpegTSContext),
02275     .read_header    = mpegts_read_header,
02276     .read_packet    = mpegts_raw_read_packet,
02277     .read_close     = mpegts_read_close,
02278     .read_seek      = read_seek,
02279     .read_timestamp = mpegts_get_pcr,
02280     .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
02281 #ifdef USE_SYNCPOINT_SEARCH
02282     .read_seek2 = read_seek2,
02283 #endif
02284     .priv_class = &mpegtsraw_class,
02285 };
Generated on Sat Mar 17 2012 12:57:54 for Libav by doxygen 1.7.1