+ for(i=0; i<s->nb_streams; i++){
+ AVStream *st = s->streams[i];
+ AVIStream *ast = st->priv_data;
+ int64_t ts= ast->frame_offset;
+
+ if(ast->sample_size)
+ ts /= ast->sample_size;
+ ts= av_rescale(ts, AV_TIME_BASE * (int64_t)st->time_base.num, st->time_base.den);
+
+// av_log(NULL, AV_LOG_DEBUG, "%Ld %d/%d %Ld\n", ts, st->time_base.num, st->time_base.den, ast->frame_offset);
+ if(ts < best_ts){
+ best_ts= ts;
+ best_st= st;
+ best_stream_index= i;
+ }
+ }
+ best_ast = best_st->priv_data;
+ best_ts= av_rescale(best_ts, best_st->time_base.den, AV_TIME_BASE * (int64_t)best_st->time_base.num); //FIXME a little ugly
+ if(best_ast->remaining)
+ i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD);
+ else
+ i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
+
+// av_log(NULL, AV_LOG_DEBUG, "%d\n", i);
+ if(i>=0){
+ int64_t pos= best_st->index_entries[i].pos;
+ pos += avi->movi_list + best_ast->packet_size - best_ast->remaining;
+ url_fseek(&s->pb, pos, SEEK_SET);
+// av_log(NULL, AV_LOG_DEBUG, "pos=%Ld\n", pos);
+
+ if(best_ast->remaining)
+ avi->stream_index= best_stream_index;
+ else
+ avi->stream_index= -1;
+ }
+ }
+
+resync:
+ if(avi->stream_index >= 0){
+ AVStream *st= s->streams[ avi->stream_index ];
+ AVIStream *ast= st->priv_data;
+ int size;
+
+ if(ast->sample_size == 0)
+ size= INT_MAX;
+ else if(ast->sample_size < 32)
+ size= 64*ast->sample_size;
+ else
+ size= ast->sample_size;
+
+ if(size > ast->remaining)
+ size= ast->remaining;
+ av_get_packet(pb, pkt, size);
+
+ if (avi->dv_demux) {
+ dstr = pkt->destruct;
+ size = dv_produce_packet(avi->dv_demux, pkt,
+ pkt->data, pkt->size);
+ pkt->destruct = dstr;
+ pkt->flags |= PKT_FLAG_KEY;
+ } else {
+ /* XXX: how to handle B frames in avi ? */
+ pkt->dts = ast->frame_offset;
+// pkt->dts += ast->start;
+ if(ast->sample_size)
+ pkt->dts /= ast->sample_size;
+//av_log(NULL, AV_LOG_DEBUG, "dts:%Ld offset:%d %d/%d smpl_siz:%d base:%d st:%d size:%d\n", pkt->dts, ast->frame_offset, ast->scale, ast->rate, ast->sample_size, AV_TIME_BASE, n, size);
+ pkt->stream_index = avi->stream_index;
+
+ if (st->codec.codec_type == CODEC_TYPE_VIDEO) {
+ if(st->index_entries){
+ AVIndexEntry *e;
+ int index;
+
+ index= av_index_search_timestamp(st, pkt->dts, 0);
+ e= &st->index_entries[index];
+
+ if(index >= 0 && e->timestamp == ast->frame_offset){
+ if (e->flags & AVINDEX_KEYFRAME)
+ pkt->flags |= PKT_FLAG_KEY;
+ }
+ } else {
+ /* if no index, better to say that all frames
+ are key frames */
+ pkt->flags |= PKT_FLAG_KEY;
+ }
+ } else {
+ pkt->flags |= PKT_FLAG_KEY;
+ }
+ if(ast->sample_size)
+ ast->frame_offset += pkt->size;
+ else
+ ast->frame_offset++;
+ }
+ ast->remaining -= size;
+ if(!ast->remaining){
+ avi->stream_index= -1;
+ ast->packet_size= 0;
+ if (size & 1) {
+ get_byte(pb);
+ size++;
+ }
+ }
+
+ return size;
+ }
+
+ memset(d, -1, sizeof(int)*8);
+ for(i=sync=url_ftell(pb); !url_feof(pb); i++) {