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