fix prob in last checkin with seek read limit
[goodguy/history.git] / cinelerra-5.0 / cinelerra / ffmpeg.C
index 48a8bf40099abc85932c1f266be1e84d0d9ebfb8..b149a30cd183c262558c6604f2316b4f21113476 100644 (file)
@@ -5,18 +5,25 @@
 #include <unistd.h>
 #include <string.h>
 #include <stdarg.h>
+#include <fcntl.h>
 #include <limits.h>
 // work arounds (centos)
 #include <lzma.h>
 #ifndef INT64_MAX
 #define INT64_MAX 9223372036854775807LL
 #endif
+#define MAX_RETRY 1000
 
 #include "asset.h"
 #include "bccmodels.h"
+#include "bchash.h"
 #include "fileffmpeg.h"
 #include "file.h"
 #include "ffmpeg.h"
+#include "indexfile.h"
+#include "libdv.h"
+#include "libmjpeg.h"
+#include "mainerror.h"
 #include "mwindow.h"
 #include "vframe.h"
 
 
 Mutex FFMPEG::fflock("FFMPEG::fflock");
 
-static void ff_err(int ret, const char *msg)
+static void ff_err(int ret, const char *fmt, ...)
 {
-       char errmsg[BCSTRLEN];  av_strerror(ret, errmsg, sizeof(errmsg));
-       fprintf(stderr,"%s: %s\n",msg, errmsg);
+       char msg[BCTEXTLEN];
+       va_list ap;
+       va_start(ap, fmt);
+       vsnprintf(msg, sizeof(msg), fmt, ap);
+       va_end(ap);
+       char errmsg[BCSTRLEN];
+       av_strerror(ret, errmsg, sizeof(errmsg));
+       fprintf(stderr,_("%s  err: %s\n"),msg, errmsg);
 }
 
 FFPacket::FFPacket()
@@ -73,149 +86,145 @@ void FFrame::dequeue()
        fst->dequeue(this);
 }
 
-FFAudioHistory::FFAudioHistory()
+int FFAudioStream::read(float *fp, long len)
 {
-       this->nch = 1;
-       this->sz = 0x1000;
-       bsz = sz * nch;
-       bfr = new float[bsz];
-       inp = outp = bfr;
-       lmt = bfr + bsz;
+       long n = len * nch;
+       float *op = outp;
+       while( n > 0 ) {
+               int k = lmt - op;
+               if( k > n ) k = n;
+               n -= k;
+               while( --k >= 0 ) *fp++ = *op++;
+               if( op >= lmt ) op = bfr;
+       }
+       return len;
 }
 
-FFAudioHistory::~FFAudioHistory()
+void FFAudioStream::realloc(long nsz, int nch, long len)
 {
-       delete [] bfr;
+       long bsz = nsz * nch;
+       float *np = new float[bsz];
+       inp = np + read(np, len) * nch;
+       outp = np;
+       lmt = np + bsz;
+       this->nch = nch;
+       sz = nsz;
+       delete [] bfr;  bfr = np;
 }
 
-
-void FFAudioHistory::reserve(long sz, int nch)
+void FFAudioStream::realloc(long nsz, int nch)
 {
-       long isz = inp - outp;
-       sz += isz / nch;
-       if( this->sz < sz || this->nch != nch ) {
-               realloc(sz, nch);
-               return;
+       if( nsz > sz || this->nch != nch ) {
+               long len = this->nch != nch ? 0 : hpos;
+               if( len > sz ) len = sz;
+               iseek(len);
+               realloc(nsz, nch, len);
        }
-       if( isz > 0 )
-               memmove(bfr, outp, isz*sizeof(*bfr));
-       outp = bfr;
-       inp = bfr + isz;
 }
 
-void FFAudioHistory::realloc(long sz, int nch)
+void FFAudioStream::reserve(long nsz, int nch)
 {
-       if( this->sz >= sz && this->nch == nch ) return;
-       long isz = used() * nch;
-       this->nch = nch;
-       this->sz = sz;
-       bsz = sz * nch;
-       float *np = new float[bsz];
-       if( isz > 0 ) copy(np, isz);
-       inp = np + isz;
-       outp = np;
-       lmt = np + bsz;
-       delete [] bfr;  bfr = np;
+       long len = (inp - outp) / nch;
+       nsz += len;
+       if( nsz > sz || this->nch != nch ) {
+               if( this->nch != nch ) len = 0;
+               realloc(nsz, nch, len);
+               return;
+       }
+       if( (len*=nch) > 0 && bfr != outp )
+               memmove(bfr, outp, len*sizeof(*bfr));
+       outp = bfr;
+       inp = bfr + len;
 }
 
-long FFAudioHistory::used()
+long FFAudioStream::used()
 {
        long len = inp>=outp ? inp-outp : inp-bfr + lmt-outp;
        return len / nch;
 }
-long FFAudioHistory::avail()
+long FFAudioStream::avail()
 {
        float *in1 = inp+1;
        if( in1 >= lmt ) in1 = bfr;
        long len = outp >= in1 ? outp-in1 : outp-bfr + lmt-in1;
        return len / nch;
 }
-void FFAudioHistory::reset() // clear bfr
+void FFAudioStream::reset_history()
 {
        inp = outp = bfr;
+       hpos = 0;
 }
 
-void FFAudioHistory::iseek(int64_t ofs)
+void FFAudioStream::iseek(int64_t ofs)
 {
        outp = inp - ofs*nch;
-       if( outp < bfr ) outp += bsz;
+       if( outp < bfr ) outp += sz*nch;
 }
 
-float *FFAudioHistory::get_outp(int ofs)
+float *FFAudioStream::get_outp(int ofs)
 {
        float *ret = outp;
        outp += ofs*nch;
        return ret;
 }
 
-int64_t FFAudioHistory::get_inp(int ofs)
+int64_t FFAudioStream::put_inp(int ofs)
 {
        inp += ofs*nch;
-       return (inp-bfr) / nch;
+       return (inp-outp) / nch;
 }
 
-int FFAudioHistory::write(const float *fp, long len)
+int FFAudioStream::write(const float *fp, long len)
 {
        long n = len * nch;
+       float *ip = inp;
        while( n > 0 ) {
-               int k = lmt - inp;
+               int k = lmt - ip;
                if( k > n ) k = n;
                n -= k;
-               while( --k >= 0 ) *inp++ = *fp++;
-               if( inp >= lmt ) inp -= bsz;
+               while( --k >= 0 ) *ip++ = *fp++;
+               if( ip >= lmt ) ip = bfr;
        }
+       inp = ip;
+       hpos += len;
        return len;
 }
 
-int FFAudioHistory::copy(float *fp, long len)
-{
-       long n = len;
-       while( n > 0 ) {
-               int k = lmt - outp;
-               if( k > n ) k = n;
-               n -= k;
-               while( --k >= 0 ) *fp++ = *outp++;
-               if( outp >= lmt ) outp -= bsz;
-       }
-       return len;
-}
-
-int FFAudioHistory::zero(long len)
+int FFAudioStream::zero(long len)
 {
        long n = len * nch;
+       float *ip = inp;
        while( n > 0 ) {
-               int k = lmt - inp;
+               int k = lmt - ip;
                if( k > n ) k = n;
                n -= k;
-               while( --k >= 0 ) *inp++ = 0;
-               if( inp >= lmt ) inp -= bsz;
+               while( --k >= 0 ) *ip++ = 0;
+               if( ip >= lmt ) ip = bfr;
        }
+       inp = ip;
+       hpos += len;
        return len;
 }
 
-int FFAudioHistory::read(double *dp, long len, int ch)
+// does not advance outp
+int FFAudioStream::read(double *dp, long len, int ch)
 {
-       long sz = used();
-       if( !sz ) return 0;
-       if( len > sz ) len = sz;
        long n = len;
        float *op = outp + ch;
+       float *lmt1 = lmt + nch-1;
        while( n > 0 ) {
-               int k = (lmt - outp) / nch;
+               int k = (lmt1 - op) / nch;
                if( k > n ) k = n;
                n -= k;
                while( --k >= 0 ) { *dp++ = *op;  op += nch; }
-               if( op >= lmt ) op -= bsz;
+               if( op >= lmt ) op -= sz*nch;
        }
        return len;
 }
 
 // load linear buffer, no wrapping allowed, does not advance inp
-int FFAudioHistory::write(const double *dp, long len, int ch)
+int FFAudioStream::write(const double *dp, long len, int ch)
 {
-       long osz = avail();
-       if( !osz || !len ) return 0;
-       if( len > osz ) len = osz;
        long n = len;
        float *ip = inp + ch;
        while( --n >= 0 ) { *ip = *dp++;  ip += nch; }
@@ -223,11 +232,11 @@ int FFAudioHistory::write(const double *dp, long len, int ch)
 }
 
 
-FFStream::FFStream(FFMPEG *ffmpeg, AVStream *st, int idx)
+FFStream::FFStream(FFMPEG *ffmpeg, AVStream *st, int fidx)
 {
        this->ffmpeg = ffmpeg;
        this->st = st;
-       this->idx = idx;
+       this->fidx = fidx;
        frm_lock = new Mutex("FFStream::frm_lock");
        fmt_ctx = 0;
        filter_graph = 0;
@@ -235,10 +244,12 @@ FFStream::FFStream(FFMPEG *ffmpeg, AVStream *st, int idx)
        buffersink_ctx = 0;
        frm_count = 0;
        nudge = AV_NOPTS_VALUE;
-       eof = 0;
+       seek_pos = curr_pos = 0;
+       seeked = 1;  eof = 0;
+       index_markers = 0;
        reading = writing = 0;
-       need_packet = 1;
        flushed = 0;
+       need_packet = 1;
        frame = fframe = 0;
 }
 
@@ -300,7 +311,8 @@ int FFStream::decode_activate()
                ret = avformat_open_input(&fmt_ctx, ffmpeg->fmt_ctx->filename, NULL, &copts);
                if( ret >= 0 ) {
                        ret = avformat_find_stream_info(fmt_ctx, 0);
-                       st = fmt_ctx->streams[idx];
+                       st = fmt_ctx->streams[fidx];
+                       load_markers();
                }
                if( ret >= 0 ) {
                        AVCodecID codec_id = st->codec->codec_id;
@@ -309,10 +321,10 @@ int FFStream::decode_activate()
                        if( ret >= 0 )
                                reading = 1;
                        else
-                               fprintf(stderr, "FFStream::decode_activate: open decoder failed\n");
+                               eprintf("FFStream::decode_activate: open decoder failed\n");
                }
                else
-                       fprintf(stderr, "FFStream::decode_activate: can't clone input file\n");
+                       eprintf("FFStream::decode_activate: can't clone input file\n");
                av_dict_free(&copts);
                ff_unlock();
        }
@@ -323,35 +335,38 @@ int FFStream::read_packet()
 {
        av_packet_unref(ipkt);
        int ret = av_read_frame(fmt_ctx, ipkt);
-       if( ret >= 0 ) return 1;
-       st_eof(1);
-       if( ret == AVERROR_EOF ) return 0;
-       fprintf(stderr, "FFStream::read_packet: av_read_frame failed\n");
-       flushed = 1;
-       return -1;
+       if( ret < 0 ) {
+               st_eof(1);
+               if( ret == AVERROR_EOF ) {
+                       ipkt->stream_index = st->index;
+                       return 0;
+               }
+               ff_err(ret, "FFStream::read_packet: av_read_frame failed\n");
+               flushed = 1;
+               return -1;
+       }
+       return 1;
 }
 
 int FFStream::decode(AVFrame *frame)
 {
        int ret = 0;
-       int retries = 100;
+       int retries = MAX_RETRY;
        int got_frame = 0;
 
        while( ret >= 0 && !flushed && --retries >= 0 && !got_frame ) {
                if( need_packet ) {
                        need_packet = 0;
-                       ret = read_packet();
-                       if( ret < 0 ) break;
-                       if( !ret ) ipkt->stream_index = st->index;
+                       if( (ret=read_packet()) < 0 ) break;
                }
                if( ipkt->stream_index == st->index ) {
-                       while( ipkt->size > 0 && !got_frame ) {
-                               ret = decode_frame(frame, got_frame);
-                               if( ret < 0 ) break;
+                       while( (ipkt->size > 0 || !ipkt->data) && !got_frame ) {
+                               ret = decode_frame(ipkt, frame, got_frame);
+                               if( ret <= 0 || !ipkt->data ) break;
                                ipkt->data += ret;
                                ipkt->size -= ret;
                        }
-                       retries = 100;
+                       retries = MAX_RETRY;
                }
                if( !got_frame ) {
                        need_packet = 1;
@@ -375,7 +390,7 @@ int FFStream::load_filter(AVFrame *frame)
                        frame, AV_BUFFERSRC_FLAG_KEEP_REF);
        if( ret < 0 ) {
                av_frame_unref(frame);
-               fprintf(stderr, "FFStream::load_filter: av_buffersrc_add_frame_flags failed\n");
+               eprintf("FFStream::load_filter: av_buffersrc_add_frame_flags failed\n");
        }
        return ret;
 }
@@ -386,7 +401,7 @@ int FFStream::read_filter(AVFrame *frame)
        if( ret < 0 ) {
                if( ret == AVERROR(EAGAIN) ) return 0;
                if( ret == AVERROR_EOF ) { st_eof(1); return -1; }
-               fprintf(stderr, "FFStream::read_filter: av_buffersink_get_frame failed\n");
+               ff_err(ret, "FFStream::read_filter: av_buffersink_get_frame failed\n");
                return ret;
        }
        return 1;
@@ -408,28 +423,110 @@ int FFStream::read_frame(AVFrame *frame)
        return ret;
 }
 
-FFAudioStream::FFAudioStream(FFMPEG *ffmpeg, AVStream *strm, int idx)
- : FFStream(ffmpeg, strm, idx)
+int FFStream::write_packet(FFPacket &pkt)
+{
+       bs_filter(pkt);
+       av_packet_rescale_ts(pkt, st->codec->time_base, st->time_base);
+       pkt->stream_index = st->index;
+       return av_interleaved_write_frame(ffmpeg->fmt_ctx, pkt);
+}
+
+int FFStream::flush()
+{
+       int ret = 0;
+       while( ret >= 0 ) {
+               FFPacket pkt;
+               int got_packet = 0;
+               ret = encode_frame(pkt, 0, got_packet);
+               if( ret < 0 || !got_packet ) break;
+               ret = write_packet(pkt);
+       }
+       if( ret < 0 )
+               ff_err(ret, "FFStream::flush");
+       return ret >= 0 ? 0 : 1;
+}
+
+int FFStream::seek(int64_t no, double rate)
+{
+       if( no < 0 ) no = 0;
+// default ffmpeg native seek
+       int npkts = 1;
+       int64_t pos = no, plmt = -1;
+       if( index_markers && index_markers->size() > 1 ) {
+               IndexMarks &marks = *index_markers;
+               int i = marks.find(pos);
+               int64_t n = i < 0 ? (i=0) : marks[i].no;
+// if indexed seek point not too far away (<30 secs), use index
+               if( no-n < 30*rate ) {
+                       if( n < 0 ) n = 0;
+                       pos = n;
+                       if( ++i < marks.size() ) plmt = marks[i].pos;
+                       npkts = MAX_RETRY;
+               }
+       }
+       double secs = pos / rate;
+       int64_t pkt_ts, tstmp = secs * st->time_base.den / st->time_base.num;
+       if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
+       int ret = avformat_seek_file(fmt_ctx, st->index,
+               -INT64_MAX, tstmp, INT64_MAX, AVSEEK_FLAG_ANY);
+       if( ret >= 0 ) {
+               avcodec_flush_buffers(st->codec);
+               need_packet = 0;  flushed = 0;
+               seeked = 1;  st_eof(0);
+// read up to retry packets, limited to npkts in stream, and not past pkt.pos plmt
+               for( int retry=MAX_RETRY; ret>=0 && --retry>=0; ) {
+                       if( read_packet() <= 0 ) { ret = -1;  break; }
+                       if( plmt >= 0 && ipkt->pos >= plmt ) break;
+                       if( ipkt->stream_index != st->index ) continue;
+                       if( --npkts <= 0 ) break;
+                       if( (pkt_ts=ipkt->dts) == AV_NOPTS_VALUE &&
+                           (pkt_ts=ipkt->pts) == AV_NOPTS_VALUE ) continue;
+                       if( pkt_ts >= tstmp ) break;
+               }
+       }
+       if( ret < 0 ) {
+//printf("** seek fail %ld, %ld\n", pos, tstmp);
+               seeked = need_packet = 0;
+               st_eof(flushed=1);
+               return -1;
+       }
+//printf("seeked pos = %ld, %ld\n", pos, tstmp);
+       seek_pos = curr_pos = pos;
+       return 0;
+}
+
+FFAudioStream::FFAudioStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
+ : FFStream(ffmpeg, strm, fidx)
 {
+       this->idx = idx;
        channel0 = channels = 0;
        sample_rate = 0;
        mbsz = 0;
-       seek_pos = curr_pos = 0;
        length = 0;
        resample_context = 0;
 
        aud_bfr_sz = 0;
        aud_bfr = 0;
+
+// history buffer
+       nch = 2;
+       sz = 0x10000;
+       long bsz = sz * nch;
+       bfr = new float[bsz];
+       lmt = bfr + bsz;
+       reset_history();
 }
 
 FFAudioStream::~FFAudioStream()
 {
        if( resample_context ) swr_free(&resample_context);
        delete [] aud_bfr;
+       delete [] bfr;
 }
 
-int FFAudioStream::load_history(float *&bfr, int len)
+int FFAudioStream::get_samples(float *&samples, uint8_t **data, int len)
 {
+       samples = *(float **)data;
        if( resample_context ) {
                if( len > aud_bfr_sz ) {        
                        delete [] aud_bfr;
@@ -440,26 +537,43 @@ int FFAudioStream::load_history(float *&bfr, int len)
                        aud_bfr = new float[aud_bfr_sz*channels];
                }
                int ret = swr_convert(resample_context,
-                       (uint8_t**)&aud_bfr, aud_bfr_sz,
-                       (const uint8_t**)&bfr, len);
+                       (uint8_t**)&aud_bfr, aud_bfr_sz, (const uint8_t**)data, len);
                if( ret < 0 ) {
-                       fprintf(stderr, "FFAudioStream::load_history: swr_convert failed\n");
+                       ff_err(ret, "FFAudioStream::get_samples: swr_convert failed\n");
                        return -1;
                }
-               bfr = aud_bfr;
+               samples = aud_bfr;
                len = ret;
        }
-       append_history(bfr, len);
        return len;
 }
 
-int FFAudioStream::decode_frame(AVFrame *frame, int &got_frame)
+int FFAudioStream::load_history(uint8_t **data, int len)
+{
+       float *samples;
+       len = get_samples(samples, data, len);
+       if( len > 0 ) {
+               // biggest user bfr since seek + frame
+               realloc(mbsz + len + 1, channels);
+               write(samples, len);
+       }
+       return len;
+}
+
+int FFAudioStream::decode_frame(AVPacket *pkt, AVFrame *frame, int &got_frame)
 {
-       int ret = avcodec_decode_audio4(st->codec, frame, &got_frame, ipkt);
+       int first_frame = seeked;  seeked = 0;
+       int ret = avcodec_decode_audio4(st->codec, frame, &got_frame, pkt);
        if( ret < 0 ) {
-               fprintf(stderr, "FFAudioStream::decode_frame: Could not read audio frame\n");
+               if( first_frame ) return 0;
+               ff_err(ret, "FFAudioStream::decode_frame: Could not read audio frame\n");
                return -1;
        }
+       if( got_frame ) {
+               int64_t pkt_ts = av_frame_get_best_effort_timestamp(frame);
+               if( pkt_ts != AV_NOPTS_VALUE )
+                       curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * sample_rate + 0.5;
+       }
        return ret;
 }
 
@@ -476,51 +590,22 @@ int FFAudioStream::nb_samples()
 {
        AVCodecContext *ctx = st->codec;
        return ctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE ?
-                10000 : ctx->frame_size;
-}
-
-void FFAudioStream::alloc_history(int len)
-{
-       history.realloc(len+1, channels);
-}
-
-void FFAudioStream::reserve_history(int len)
-{
-       history.reserve(len+1, st->codec->channels);
-}
-
-void FFAudioStream::append_history(const float *fp, int len)
-{
-       // biggest user bfr since seek + length this frame
-       int hsz = mbsz + len;
-       alloc_history(hsz);
-       history.write(fp, len);
+               10000 : ctx->frame_size;
 }
 
 int64_t FFAudioStream::load_buffer(double ** const sp, int len)
 {
-       reserve_history(len);
-       int nch = st->codec->channels;
+       reserve(len+1, st->codec->channels);
        for( int ch=0; ch<nch; ++ch )
-               history.write(sp[ch], len, ch);
-       return history.get_inp(len);
-}
-
-void FFAudioStream::zero_history(int len)
-{
-       history.zero(len);
-}
-
-float* FFAudioStream::get_history(int len)
-{
-       return history.get_outp(len);
+               write(sp[ch], len, ch);
+       return put_inp(len);
 }
 
 int FFAudioStream::in_history(int64_t pos)
 {
        if( pos > curr_pos ) return 0;
-       int64_t len = curr_pos - seek_pos;
-       if( len > history.sz ) len = history.sz;
+       int64_t len = hpos;
+       if( len > sz ) len = sz;
        if( pos < curr_pos - len ) return 0;
        return 1;
 }
@@ -535,50 +620,45 @@ int FFAudioStream::init_frame(AVFrame *frame)
        frame->sample_rate = ctx->sample_rate;
        int ret = av_frame_get_buffer(frame, 0);
        if (ret < 0)
-               fprintf(stderr, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
+               ff_err(ret, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
        return ret;
 }
 
 int FFAudioStream::load(int64_t pos, int len)
 {
        if( audio_seek(pos) < 0 ) return -1;
-       if( mbsz < len ) mbsz = len;
-       int ret = 0;
-       int64_t end_pos = pos + len;
        if( !frame && !(frame=av_frame_alloc()) ) {
                fprintf(stderr, "FFAudioStream::load: av_frame_alloc failed\n");
                return -1;
        }
-       for( int i=0; ret>=0 && !flushed && curr_pos<end_pos && i<1000; ++i ) {
+       if( mbsz < len ) mbsz = len;
+       int64_t end_pos = pos + len;
+       int ret = 0;
+       for( int i=0; ret>=0 && !flushed && curr_pos<end_pos && i<MAX_RETRY; ++i ) {
                ret = read_frame(frame);
                if( ret > 0 ) {
-                       load_history((float *&)frame->extended_data[0], frame->nb_samples);
+                       load_history(&frame->extended_data[0], frame->nb_samples);
                        curr_pos += frame->nb_samples;
                }
        }
-       if( flushed && end_pos > curr_pos ) {
-               zero_history(end_pos - curr_pos);
+       if( end_pos > curr_pos ) {
+               zero(end_pos - curr_pos);
                curr_pos = end_pos;
        }
-       return curr_pos - pos;
+       len = curr_pos - pos;
+       iseek(len);
+       return len;
 }
 
 int FFAudioStream::audio_seek(int64_t pos)
 {
        if( decode_activate() < 0 ) return -1;
-       if( in_history(pos) ) {
-               history.iseek(curr_pos - pos);
-               return 0;
-       }
+       if( !st->codec || !st->codec->codec ) return -1;
+       if( in_history(pos) ) return 0;
        if( pos == curr_pos ) return 0;
-       double secs = (double)pos / sample_rate;
-       int64_t tstmp = secs * st->time_base.den / st->time_base.num;
-       if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
-       avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, tstmp, INT64_MAX, 0);
-       seek_pos = curr_pos = pos;
-       mbsz = 0;
-       history.reset();
-       st_eof(0);
+       reset_history();  mbsz = 0;
+// guarentee preload > 1sec samples
+       if( seek(pos-sample_rate, sample_rate) < 0 ) return -1;
        return 1;
 }
 
@@ -594,12 +674,12 @@ int FFAudioStream::encode(double **samples, int len)
                frm = new FFrame(this);
                if( (ret=frm->initted()) < 0 ) break;
                AVFrame *frame = *frm;
-               float *bfrp = get_history(frame_sz);
+               float *bfrp = get_outp(frame_sz);
                ret =  swr_convert(resample_context,
                        (uint8_t **)frame->extended_data, frame_sz,
                        (const uint8_t **)&bfrp, frame_sz);
                if( ret < 0 ) {
-                       fprintf(stderr, "FFAudioStream::encode: swr_convert failed\n");
+                       ff_err(ret, "FFAudioStream::encode: swr_convert failed\n");
                        break;
                }
                frm->queue(curr_pos);
@@ -612,46 +692,67 @@ int FFAudioStream::encode(double **samples, int len)
        return ret >= 0 ? 0 : 1;
 }
 
-FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx)
- : FFStream(ffmpeg, strm, idx)
+int FFAudioStream::encode_frame(AVPacket *pkt, AVFrame *frame, int &got_packet)
 {
+       int ret = avcodec_encode_audio2(st->codec, pkt, frame, &got_packet);
+       if( ret < 0 ) {
+               ff_err(ret, "FFAudioStream::encode_frame: encode audio failed\n");
+               return -1;
+       }
+       return ret;
+}
+
+void FFAudioStream::load_markers()
+{
+       IndexState *index_state = ffmpeg->file_base->asset->index_state;
+       if( !index_state || idx >= index_state->audio_markers.size() ) return;
+       FFStream::load_markers(*index_state->audio_markers[idx], sample_rate);
+}
+
+FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
+ : FFStream(ffmpeg, strm, fidx)
+{
+       this->idx = idx;
        width = height = 0;
        frame_rate = 0;
        aspect_ratio = 0;
-       seek_pos = curr_pos = 0;
        length = 0;
-       convert_ctx = 0;
 }
 
 FFVideoStream::~FFVideoStream()
 {
-       if( convert_ctx ) sws_freeContext(convert_ctx);
 }
 
-int FFVideoStream::decode_frame(AVFrame *frame, int &got_frame)
+int FFVideoStream::decode_frame(AVPacket *pkt, AVFrame *frame, int &got_frame)
 {
-       int ret = avcodec_decode_video2(st->codec, frame, &got_frame, ipkt);
+       int first_frame = seeked;  seeked = 0;
+       int ret = avcodec_decode_video2(st->codec, frame, &got_frame, pkt);
        if( ret < 0 ) {
-               fprintf(stderr, "FFVideoStream::decode_frame: Could not read video frame\n");
+               if( first_frame ) return 0;
+               ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame\n");
                return -1;
        }
-       if( got_frame )
-               ++curr_pos;
+       if( got_frame ) {
+               int64_t pkt_ts = av_frame_get_best_effort_timestamp(frame);
+               if( pkt_ts != AV_NOPTS_VALUE )
+                       curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * frame_rate + 0.5;
+       }
        return ret;
 }
 
 int FFVideoStream::load(VFrame *vframe, int64_t pos)
 {
-       if( video_seek(pos) < 0 ) return -1;
+       int ret = video_seek(pos);
+       if( ret < 0 ) return -1;
        if( !frame && !(frame=av_frame_alloc()) ) {
                fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
                return -1;
        }
-       int ret = 0;
-       for( int i=0; ret>=0 && !flushed && curr_pos<=pos && i<1000; ++i ) {
+       for( int i=0; ret>=0 && !flushed && curr_pos<=pos && i<MAX_RETRY; ++i ) {
                ret = read_frame(frame);
+               if( ret > 0 ) ++curr_pos;
        }
-       if( ret > 0 ) {
+       if( ret >= 0 ) {
                AVCodecContext *ctx = st->codec;
                ret = convert_cmodel(vframe, (AVPicture *)frame,
                        ctx->pix_fmt, ctx->width, ctx->height);
@@ -663,20 +764,16 @@ int FFVideoStream::load(VFrame *vframe, int64_t pos)
 int FFVideoStream::video_seek(int64_t pos)
 {
        if( decode_activate() < 0 ) return -1;
+       if( !st->codec || !st->codec->codec ) return -1;
+       if( pos == curr_pos-1 && !seeked ) return 0;
 // if close enough, just read up to current
-//   3*gop_size seems excessive, but less causes tears
-       int gop = 3*st->codec->gop_size;
+       int gop = st->codec->gop_size;
        if( gop < 4 ) gop = 4;
        if( gop > 64 ) gop = 64;
-       if( pos >= curr_pos && pos <= curr_pos + gop ) return 0;
-// back up a few frames to read up to current to help repair damages
-       if( (pos-=gop) < 0 ) pos = 0;
-       double secs = (double)pos / frame_rate;
-       int64_t tstmp = secs * st->time_base.den / st->time_base.num;
-       if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
-       avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, tstmp, INT64_MAX, 0);
-       seek_pos = curr_pos = pos;
-       st_eof(0);
+       int read_limit = curr_pos + 3*gop;
+       if( pos >= curr_pos && pos <= read_limit ) return 0;
+// guarentee preload more than 2*gop frames
+       if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
        return 1;
 }
 
@@ -714,8 +811,17 @@ int FFVideoStream::encode(VFrame *vframe)
        return ret >= 0 ? 0 : 1;
 }
 
+int FFVideoStream::encode_frame(AVPacket *pkt, AVFrame *frame, int &got_packet)
+{
+       int ret = avcodec_encode_video2(st->codec, pkt, frame, &got_packet);
+       if( ret < 0 ) {
+               ff_err(ret, "FFVideoStream::encode_frame: encode video failed\n");
+               return -1;
+       }
+       return ret;
+}
 
-PixelFormat FFVideoStream::color_model_to_pix_fmt(int color_model)
+PixelFormat FFVideoConvert::color_model_to_pix_fmt(int color_model)
 {
        switch( color_model ) { 
        case BC_YUV422:         return AV_PIX_FMT_YUYV422;
@@ -736,7 +842,7 @@ PixelFormat FFVideoStream::color_model_to_pix_fmt(int color_model)
        return AV_PIX_FMT_NB;
 }
 
-int FFVideoStream::pix_fmt_to_color_model(PixelFormat pix_fmt)
+int FFVideoConvert::pix_fmt_to_color_model(PixelFormat pix_fmt)
 {
        switch (pix_fmt) { 
        case AV_PIX_FMT_YUYV422:        return BC_YUV422;
@@ -757,7 +863,7 @@ int FFVideoStream::pix_fmt_to_color_model(PixelFormat pix_fmt)
        return BC_TRANSPARENCY;
 }
 
-int FFVideoStream::convert_picture_vframe(VFrame *frame,
+int FFVideoConvert::convert_picture_vframe(VFrame *frame,
                AVPicture *ip, PixelFormat ifmt, int iw, int ih)
 {
        AVPicture opic;
@@ -784,19 +890,20 @@ int FFVideoStream::convert_picture_vframe(VFrame *frame,
        convert_ctx = sws_getCachedContext(convert_ctx, iw, ih, ifmt,
                frame->get_w(), frame->get_h(), ofmt, SWS_BICUBIC, NULL, NULL, NULL);
        if( !convert_ctx ) {
-               fprintf(stderr, "FFVideoStream::convert_picture_frame:"
+               fprintf(stderr, "FFVideoConvert::convert_picture_frame:"
                                " sws_getCachedContext() failed\n");
-               return 1;
+               return -1;
        }
-       if( sws_scale(convert_ctx, ip->data, ip->linesize, 0, ih,
-           opic.data, opic.linesize) < 0 ) {
-               fprintf(stderr, "FFVideoStream::convert_picture_frame: sws_scale() failed\n");
-               return 1;
+       int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ih,
+           opic.data, opic.linesize);
+       if( ret < 0 ) {
+               ff_err(ret, "FFVideoConvert::convert_picture_frame: sws_scale() failed\n");
+               return -1;
        }
        return 0;
 }
 
-int FFVideoStream::convert_cmodel(VFrame *frame,
+int FFVideoConvert::convert_cmodel(VFrame *frame,
                 AVPicture *ip, PixelFormat ifmt, int iw, int ih)
 {
        // try direct transfer
@@ -820,7 +927,22 @@ int FFVideoStream::convert_cmodel(VFrame *frame,
        return 1;
 }
 
-int FFVideoStream::convert_vframe_picture(VFrame *frame,
+int FFVideoConvert::transfer_cmodel(VFrame *frame,
+                AVFrame *ifp, PixelFormat ifmt, int iw, int ih)
+{
+       int ret = convert_cmodel(frame, (AVPicture *)ifp, ifmt, iw, ih);
+       if( ret > 0 ) {
+               const AVDictionary *src = av_frame_get_metadata(ifp);
+               AVDictionaryEntry *t = NULL;
+               BC_Hash *hp = frame->get_params();
+               //hp->clear();
+               while( (t=av_dict_get(src, "", t, AV_DICT_IGNORE_SUFFIX)) )
+                       hp->update(t->key, t->value);
+       }
+       return ret;
+}
+
+int FFVideoConvert::convert_vframe_picture(VFrame *frame,
                AVPicture *op, PixelFormat ofmt, int ow, int oh)
 {
        AVPicture opic;
@@ -847,23 +969,24 @@ int FFVideoStream::convert_vframe_picture(VFrame *frame,
        convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(), ifmt,
                ow, oh, ofmt, SWS_BICUBIC, NULL, NULL, NULL);
        if( !convert_ctx ) {
-               fprintf(stderr, "FFVideoStream::convert_frame_picture:"
+               fprintf(stderr, "FFVideoConvert::convert_frame_picture:"
                                " sws_getCachedContext() failed\n");
-               return 1;
+               return -1;
        }
-       if( sws_scale(convert_ctx, opic.data, opic.linesize, 0, frame->get_h(),
-                       op->data, op->linesize) < 0 ) {
-               fprintf(stderr, "FFVideoStream::convert_frame_picture: sws_scale() failed\n");
-               return 1;
+       int ret = sws_scale(convert_ctx, opic.data, opic.linesize, 0, frame->get_h(),
+                       op->data, op->linesize);
+       if( ret < 0 ) {
+               ff_err(ret, "FFVideoConvert::convert_frame_picture: sws_scale() failed\n");
+               return -1;
        }
        return 0;
 }
 
-int FFVideoStream::convert_pixfmt(VFrame *frame,
+int FFVideoConvert::convert_pixfmt(VFrame *frame,
                 AVPicture *op, PixelFormat ofmt, int ow, int oh)
 {
        // try direct transfer
-       if( !convert_vframe_picture(frame, op, ofmt, ow, oh) ) return 0;
+       if( !convert_vframe_picture(frame, op, ofmt, ow, oh) ) return 1;
        // use indirect transfer
        int colormodel = frame->get_color_model();
        int bits = BC_CModels::calculate_pixelsize(colormodel) * 8;
@@ -873,8 +996,31 @@ int FFVideoStream::convert_pixfmt(VFrame *frame,
                (bits > 8 ? BC_RGB161616: BC_RGB888) ;
        VFrame vframe(frame->get_w(), frame->get_h(), icolor_model);
        vframe.transfer_from(frame);
-       if( convert_vframe_picture(&vframe, op, ofmt, ow, oh) ) return 1;
-       return 0;
+       if( !convert_vframe_picture(&vframe, op, ofmt, ow, oh) ) return 1;
+       return -1;
+}
+
+int FFVideoConvert::transfer_pixfmt(VFrame *frame,
+                AVFrame *ofp, PixelFormat ofmt, int ow, int oh)
+{
+       int ret = convert_pixfmt(frame, (AVPicture *)ofp, ofmt, ow, oh);
+       if( ret > 0 ) {
+               BC_Hash *hp = frame->get_params();
+               AVDictionary **dict = avpriv_frame_get_metadatap(ofp);
+               //av_dict_free(dict);
+               for( int i=0; i<hp->size(); ++i ) {
+                       char *key = hp->get_key(i), *val = hp->get_value(i);
+                       av_dict_set(dict, key, val, 0);
+               }
+       }
+       return ret;
+}
+
+void FFVideoStream::load_markers()
+{
+       IndexState *index_state = ffmpeg->file_base->asset->index_state;
+       if( idx >= index_state->video_markers.size() ) return;
+       FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
 }
 
 
@@ -904,13 +1050,13 @@ FFMPEG::~FFMPEG()
        close_encoder();
        ffaudio.remove_all_objects();
        ffvideo.remove_all_objects();
-       if( encoding ) avformat_free_context(fmt_ctx);
+       if( fmt_ctx ) avformat_close_input(&fmt_ctx);
        ff_unlock();
        delete flow_lock;
        delete mux_lock;
        av_dict_free(&opts);
-       delete opt_video_filter;
-       delete opt_audio_filter;
+       delete [] opt_video_filter;
+       delete [] opt_audio_filter;
 }
 
 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
@@ -950,12 +1096,19 @@ AVRational FFMPEG::check_frame_rate(AVCodec *codec, double frame_rate)
        return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
 }
 
-AVRational FFMPEG::to_sample_aspect_ratio(double aspect_ratio)
+AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
 {
-       int height = 1000000, width = height * aspect_ratio;
+#if 1
+       double display_aspect = asset->width / (double)asset->height;
+       double sample_aspect = asset->aspect_ratio / display_aspect;
+       int width = 1000000, height = width * sample_aspect + 0.5;
        float w, h;
        MWindow::create_aspect_ratio(w, h, width, height);
-       return (AVRational){(int)w, (int)h};
+       return (AVRational){(int)h, (int)w};
+#else
+// square pixels
+       return (AVRational){1, 1};
+#endif
 }
 
 AVRational FFMPEG::to_time_base(int sample_rate)
@@ -963,8 +1116,6 @@ AVRational FFMPEG::to_time_base(int sample_rate)
        return (AVRational){1, sample_rate};
 }
 
-extern void get_exe_path(char *result); // from main.C
-
 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
 {
        get_exe_path(path);
@@ -984,10 +1135,9 @@ void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
                set_option_path(path, "%s/%s", type, spec);
 }
 
-int FFMPEG::check_option(const char *path, char *spec)
+int FFMPEG::get_format(char *format, const char *path, char *spec)
 {
-       char option_path[BCTEXTLEN], line[BCTEXTLEN];
-       char format[BCSTRLEN], codec[BCSTRLEN];
+       char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
        get_option_path(option_path, path, spec);
        FILE *fp = fopen(option_path,"r");
        if( !fp ) return 1;
@@ -997,25 +1147,27 @@ int FFMPEG::check_option(const char *path, char *spec)
                line[sizeof(line)-1] = 0;
                ret = scan_option_line(line, format, codec);
        }
-       if( !ret ) {
-               if( !file_format[0] ) strcpy(file_format, format);
-               else if( strcmp(file_format, format) ) ret = 1;
-       }
        fclose(fp);
        return ret;
 }
 
-const char *FFMPEG::get_file_format()
+int FFMPEG::get_file_format()
 {
-       file_format[0] = 0;
        int ret = 0;
+       char audio_format[BCSTRLEN], video_format[BCSTRLEN];
+       file_format[0] = audio_format[0] = video_format[0] = 0;
        Asset *asset = file_base->asset;
        if( !ret && asset->audio_data )
-               ret = check_option("audio", asset->acodec);
+               ret = get_format(audio_format, "audio", asset->acodec);
        if( !ret && asset->video_data )
-               ret = check_option("video", asset->vcodec);
-       if( !ret && !file_format[0] ) ret = 1;
-       return !ret ? file_format : 0;
+               ret = get_format(video_format, "video", asset->vcodec);
+       if( !ret && !audio_format[0] && !video_format[0] )
+               ret = 1;
+       if( !ret && audio_format[0] && video_format[0] &&
+           strcmp(audio_format, video_format) ) ret = -1;
+       if( !ret )
+               strcpy(file_format, audio_format[0] ? audio_format : video_format);
+       return ret;
 }
 
 int FFMPEG::scan_option_line(char *cp, char *tag, char *val)
@@ -1039,42 +1191,35 @@ int FFMPEG::scan_option_line(char *cp, char *tag, char *val)
        return 0;
 }
 
-int FFMPEG::read_options(const char *options, char *format, char *codec,
-               char *bsfilter, char *bsargs, AVDictionary *&opts)
+int FFMPEG::get_encoder(const char *options,
+               char *format, char *codec, char *bsfilter, char *bsargs)
 {
        FILE *fp = fopen(options,"r");
        if( !fp ) {
-               fprintf(stderr, "FFMPEG::read_options: options open failed %s\n",options);
+               eprintf("FFMPEG::get_encoder: options open failed %s\n",options);
                return 1;
        }
-       int ret = read_options(fp, options, format, codec, opts);
-       char *cp = codec;
-       while( *cp && *cp != '|' ) ++cp;
-       if( *cp == '|' && !scan_option_line(cp+1, bsfilter, bsargs) ) {
-               do { *cp-- = 0; } while( cp>=codec && (*cp==' ' || *cp == '\t' ) );
-       }
-       else
-               bsfilter[0] = bsargs[0] = 0;
+       if( get_encoder(fp, format, codec, bsfilter, bsargs) )
+               eprintf(_("FFMPEG::get_encoder:"
+                         " err: format/codec not found %s\n"), options);
        fclose(fp);
-       return ret;
+       return 0;
 }
 
-int FFMPEG::read_options(FILE *fp, const char *options,
-                char *format, char *codec, AVDictionary *&opts)
+int FFMPEG::get_encoder(FILE *fp,
+               char *format, char *codec, char *bsfilter, char *bsargs)
 {
+       format[0] = codec[0] = bsfilter[0] = bsargs[0] = 0;
        char line[BCTEXTLEN];
-       if( !fgets(line, sizeof(line), fp) ) {
-               fprintf(stderr, "FFMPEG::read_options:"
-                       " options file empty %s\n",options);
-               return 1;
-       }
+       if( !fgets(line, sizeof(line), fp) ) return 1;
        line[sizeof(line)-1] = 0;
-       if( scan_option_line(line, format, codec) ) {
-               fprintf(stderr, "FFMPEG::read_options:"
-                       " err: format/codec not found %s\n", options);
-               return 1;
-       }
-       return read_options(fp, options, opts, 1);
+       if( scan_option_line(line, format, codec) ) return 1;
+       char *cp = codec;
+       while( *cp && *cp != '|' ) ++cp;
+       if( !*cp ) return 0;
+       if( scan_option_line(cp+1, bsfilter, bsargs) ) return 1;
+       do { *cp-- = 0; } while( cp>=codec && (*cp==' ' || *cp == '\t' ) );
+       return 0;
 }
 
 int FFMPEG::read_options(const char *options, AVDictionary *&opts)
@@ -1086,26 +1231,38 @@ int FFMPEG::read_options(const char *options, AVDictionary *&opts)
        return ret;
 }
 
-int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts, int no)
+int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
 {
-       int ret = 0;
+       FILE *fp = fmemopen((void *)options,strlen(options),"r");
+       if( !fp ) return 0;
+       int ret = read_options(fp, options, opts);
+       fclose(fp);
+       AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
+       if( tag ) st->id = strtol(tag->value,0,0);
+       return ret;
+}
+
+int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
+{
+       int ret = 0, no = 0;
        char line[BCTEXTLEN];
        while( !ret && fgets(line, sizeof(line), fp) ) {
                line[sizeof(line)-1] = 0;
                ++no;
                if( line[0] == '#' ) continue;
+               if( line[0] == '\n' ) continue;
                char key[BCSTRLEN], val[BCTEXTLEN];
                if( scan_option_line(line, key, val) ) {
-                       fprintf(stderr, "FFMPEG::read_options:"
-                               " err reading %s: line %d\n", options, no);
+                       eprintf(_("FFMPEG::read_options:"
+                                 " err reading %s: line %d\n"), options, no);
                        ret = 1;
                }
                if( !ret ) {
                        if( !strcmp(key, "duration") )
                                opt_duration = strtod(val, 0);
-                       if( !strcmp(key, "video_filter") )
+                       else if( !strcmp(key, "video_filter") )
                                opt_video_filter = cstrdup(val);
-                       if( !strcmp(key, "audio_filter") )
+                       else if( !strcmp(key, "audio_filter") )
                                opt_audio_filter = cstrdup(val);
                        else if( !strcmp(key, "loglevel") )
                                set_loglevel(val);
@@ -1123,6 +1280,19 @@ int FFMPEG::load_options(const char *options, AVDictionary *&opts)
        return read_options(option_path, opts);
 }
 
+int FFMPEG::load_options(const char *path, char *bfr, int len)
+{
+       *bfr = 0;
+       FILE *fp = fopen(path, "r");
+       if( !fp ) return 1;
+       fgets(bfr, len, fp); // skip hdr
+       len = fread(bfr, 1, len-1, fp);
+       if( len < 0 ) len = 0;
+       bfr[len] = 0;
+       fclose(fp);
+       return 0;
+}
+
 void FFMPEG::set_loglevel(const char *ap)
 {
        if( !ap || !*ap ) return;
@@ -1158,51 +1328,76 @@ double FFMPEG::to_secs(int64_t time, AVRational time_base)
 int FFMPEG::info(char *text, int len)
 {
        if( len <= 0 ) return 0;
+       decode_activate();
 #define report(s...) do { int n = snprintf(cp,len,s); cp += n;  len -= n; } while(0)
        char *cp = text;
-       for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
-               AVStream *st = fmt_ctx->streams[i];
+       if( ffvideo.size() > 0 )
+               report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
+       for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
+               FFVideoStream *vid = ffvideo[vidx];
+               AVStream *st = vid->st;
                AVCodecContext *avctx = st->codec;
-               report("stream %d,  id 0x%06x:\n", i, avctx->codec_id);
+               report(_("vid%d (%d),  id 0x%06x:\n"), vid->idx, vid->fidx, avctx->codec_id);
                const AVCodecDescriptor *desc = avcodec_descriptor_get(avctx->codec_id);
-               if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
-                       AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
-                       double frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
-                       report("  video %s",desc ? desc->name : " (unkn)");
-                       report(" %dx%d %5.2f", avctx->width, avctx->height, frame_rate);
-                       const char *pfn = av_get_pix_fmt_name(avctx->pix_fmt);
-                       report(" pix %s\n", pfn ? pfn : "(unkn)");
-                       double secs = to_secs(st->duration, st->time_base);
-                       int64_t length = secs * frame_rate + 0.5;
-                       report("    %jd frms %0.2f secs", length, secs);
-                       int hrs = secs/3600;  secs -= hrs*3600;
-                       int mins = secs/60;  secs -= mins*60;
-                       report("  %d:%02d:%05.2f\n", hrs, mins, secs);
-
-               }
-               else if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
-                       int sample_rate = avctx->sample_rate;
-                       const char *fmt = av_get_sample_fmt_name(avctx->sample_fmt);
-                       report("  audio %s",desc ? desc->name : " (unkn)");
-                       report(" %dch %s %d",avctx->channels, fmt, sample_rate);
-                       int sample_bits = av_get_bits_per_sample(avctx->codec_id);
-                       report(" %dbits\n", sample_bits);
-                       double secs = to_secs(st->duration, st->time_base);
-                       int64_t length = secs * sample_rate + 0.5;
-                       report("    %jd smpl %0.2f secs", length, secs);
-                       int hrs = secs/3600;  secs -= hrs*3600;
-                       int mins = secs/60;  secs -= mins*60;
-                       report("  %d:%02d:%05.2f\n", hrs, mins, secs);
-               }
-               else
-                       report("  codec_type unknown\n");
-       }
-       report("\n");
+               report("  video%d %s", vidx+1, desc ? desc->name : " (unkn)");
+               report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
+               const char *pfn = av_get_pix_fmt_name(avctx->pix_fmt);
+               report(" pix %s\n", pfn ? pfn : "(unkn)");
+               double secs = to_secs(st->duration, st->time_base);
+               int64_t length = secs * vid->frame_rate + 0.5;
+               double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
+               int64_t nudge = ofs * vid->frame_rate;
+               int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
+               report("    %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
+               int hrs = secs/3600;  secs -= hrs*3600;
+               int mins = secs/60;  secs -= mins*60;
+               report("  %d:%02d:%05.2f\n", hrs, mins, secs);
+       }
+       if( ffaudio.size() > 0 )
+               report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
+       for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
+               FFAudioStream *aud = ffaudio[aidx];
+               AVStream *st = aud->st;
+               AVCodecContext *avctx = st->codec;
+               report(_("aud%d (%d),  id 0x%06x:\n"), aud->idx, aud->fidx, avctx->codec_id);
+               const AVCodecDescriptor *desc = avcodec_descriptor_get(avctx->codec_id);
+               int nch = aud->channels, ch0 = aud->channel0+1;
+               report("  audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
+               const char *fmt = av_get_sample_fmt_name(avctx->sample_fmt);
+               report(" %s %d", fmt, aud->sample_rate);
+               int sample_bits = av_get_bits_per_sample(avctx->codec_id);
+               report(" %dbits\n", sample_bits);
+               double secs = to_secs(st->duration, st->time_base);
+               int64_t length = secs * aud->sample_rate + 0.5;
+               double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
+               int64_t nudge = ofs * aud->sample_rate;
+               int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
+               report("    %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
+               int hrs = secs/3600;  secs -= hrs*3600;
+               int mins = secs/60;  secs -= mins*60;
+               report("  %d:%02d:%05.2f\n", hrs, mins, secs);
+       }
+       if( fmt_ctx->nb_programs > 0 )
+               report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
        for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
                report("program %d", i+1);
                AVProgram *pgrm = fmt_ctx->programs[i];
-               for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j )
-                       report(", %d", pgrm->stream_index[j]);
+               for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
+                       int idx = pgrm->stream_index[j];
+                       int vidx = ffvideo.size();
+                       while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
+                       if( vidx >= 0 ) {
+                               report(", vid%d", vidx);
+                               continue;
+                       }
+                       int aidx = ffaudio.size();
+                       while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
+                       if( aidx >= 0 ) {
+                               report(", aud%d", aidx);
+                               continue;
+                       }
+                       report(", (%d)", pgrm->stream_index[j]);
+               }
                report("\n");
        }
        report("\n");
@@ -1230,7 +1425,7 @@ int FFMPEG::init_decoder(const char *filename)
                fp = fopen(file_opts, "r");
        }
        if( fp ) {
-               read_options(fp, file_opts, opts, 0);
+               read_options(fp, file_opts, opts);
                fclose(fp);
        }
        else
@@ -1252,7 +1447,7 @@ int FFMPEG::open_decoder()
 {
        struct stat st;
        if( stat(fmt_ctx->filename, &st) < 0 ) {
-               fprintf(stderr,"FFMPEG::open_decoder: can't stat file: %s\n",
+               eprintf("FFMPEG::open_decoder: can't stat file: %s\n",
                        fmt_ctx->filename);
                return 1;
        }
@@ -1281,15 +1476,20 @@ int FFMPEG::open_decoder()
                AVStream *st = fmt_ctx->streams[i];
                if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
                AVCodecContext *avctx = st->codec;
+               const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avctx->codec_id);
+               if( !codec_desc ) continue;
                if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
+                       if( avctx->width < 1 ) continue;
+                       if( avctx->height < 1 ) continue;
+                       AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
+                       if( framerate.num < 1 ) continue;
                        has_video = 1;
-                       FFVideoStream *vid = new FFVideoStream(this, st, i);
                        int vidx = ffvideo.size();
+                       FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
                        vstrm_index.append(ffidx(vidx, 0));
                        ffvideo.append(vid);
                        vid->width = avctx->width;
                        vid->height = avctx->height;
-                       AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
                        vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
                        double secs = to_secs(st->duration, st->time_base);
                        vid->length = secs * vid->frame_rate;
@@ -1300,9 +1500,11 @@ int FFMPEG::open_decoder()
                                vid->create_filter(opt_video_filter, avctx,avctx);
                }
                else if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
+                       if( avctx->channels < 1 ) continue;
+                       if( avctx->sample_rate < 1 ) continue;
                        has_audio = 1;
-                       FFAudioStream *aud = new FFAudioStream(this, st, i);
                        int aidx = ffaudio.size();
+                       FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
                        ffaudio.append(aud);
                        aud->channel0 = astrm_index.size();
                        aud->channels = avctx->channels;
@@ -1335,17 +1537,27 @@ int FFMPEG::open_decoder()
 
 int FFMPEG::init_encoder(const char *filename)
 {
-       const char *format = get_file_format();
-       if( !format ) {
-               fprintf(stderr, "FFMPEG::init_encoder: invalid file format for %s\n", filename);
+       int fd = ::open(filename,O_WRONLY);
+       if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
+       if( fd < 0 ) {
+               eprintf("FFMPEG::init_encoder: bad file path: %s\n", filename);
+               return 1;
+       }
+       ::close(fd);
+       int ret = get_file_format();
+       if( ret > 0 ) {
+               eprintf("FFMPEG::init_encoder: bad file format: %s\n", filename);
+               return 1;
+       }
+       if( ret < 0 ) {
+               eprintf("FFMPEG::init_encoder: mismatch audio/video file format: %s\n", filename);
                return 1;
        }
-       int ret = 0;
        ff_lock("FFMPEG::init_encoder");
        av_register_all();
-       avformat_alloc_output_context2(&fmt_ctx, 0, format, filename);
+       avformat_alloc_output_context2(&fmt_ctx, 0, file_format, filename);
        if( !fmt_ctx ) {
-               fprintf(stderr, "FFMPEG::init_encoder: failed: %s\n", filename);
+               eprintf("FFMPEG::init_encoder: failed: %s\n", filename);
                ret = 1;
        }
        if( !ret ) {
@@ -1357,7 +1569,7 @@ int FFMPEG::init_encoder(const char *filename)
        return ret;
 }
 
-int FFMPEG::open_encoder(const char *path, const char *spec)
+int FFMPEG::open_encoder(const char *type, const char *spec)
 {
 
        Asset *asset = file_base->asset;
@@ -1365,17 +1577,21 @@ int FFMPEG::open_encoder(const char *path, const char *spec)
        AVDictionary *sopts = 0;
        av_dict_copy(&sopts, opts, 0);
        char option_path[BCTEXTLEN];
-       set_option_path(option_path, "%s/%s.opts", path, path);
+       set_option_path(option_path, "%s/%s.opts", type, type);
        read_options(option_path, sopts);
-       get_option_path(option_path, path, spec);
+       get_option_path(option_path, type, spec);
        char format_name[BCSTRLEN], codec_name[BCTEXTLEN];
        char bsfilter[BCSTRLEN], bsargs[BCTEXTLEN];
-       if( read_options(option_path, format_name, codec_name, bsfilter, bsargs, sopts) ) {
-               fprintf(stderr, "FFMPEG::open_encoder: read options failed %s:%s\n",
+       if( get_encoder(option_path, format_name, codec_name, bsfilter, bsargs) ) {
+               eprintf("FFMPEG::open_encoder: get_encoder failed %s:%s\n",
                        option_path, filename);
                return 1;
        }
 
+       if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
+       else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
+       else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
+
        int ret = 0;
        ff_lock("FFMPEG::open_encoder");
        FFStream *fst = 0;
@@ -1384,14 +1600,14 @@ int FFMPEG::open_encoder(const char *path, const char *spec)
        const AVCodecDescriptor *codec_desc = 0;
        AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
        if( !codec ) {
-               fprintf(stderr, "FFMPEG::open_encoder: cant find codec %s:%s\n",
+               eprintf("FFMPEG::open_encoder: cant find codec %s:%s\n",
                        codec_name, filename);
                ret = 1;
        }
        if( !ret ) {
                codec_desc = avcodec_descriptor_get(codec->id);
                if( !codec_desc ) {
-                       fprintf(stderr, "FFMPEG::open_encoder: unknown codec %s:%s\n",
+                       eprintf("FFMPEG::open_encoder: unknown codec %s:%s\n",
                                codec_name, filename);
                        ret = 1;
                }
@@ -1399,7 +1615,7 @@ int FFMPEG::open_encoder(const char *path, const char *spec)
        if( !ret ) {
                st = avformat_new_stream(fmt_ctx, 0);
                if( !st ) {
-                       fprintf(stderr, "FFMPEG::open_encoder: cant create stream %s:%s\n",
+                       eprintf("FFMPEG::open_encoder: cant create stream %s:%s\n",
                                codec_name, filename);
                        ret = 1;
                }
@@ -1409,15 +1625,27 @@ int FFMPEG::open_encoder(const char *path, const char *spec)
                switch( codec_desc->type ) {
                case AVMEDIA_TYPE_AUDIO: {
                        if( has_audio ) {
-                               fprintf(stderr, "FFMPEG::open_encoder: duplicate audio %s:%s\n",
+                               eprintf("FFMPEG::open_encoder: duplicate audio %s:%s\n",
                                        codec_name, filename);
                                ret = 1;
                                break;
                        }
                        has_audio = 1;
+                       if( scan_options(asset->ff_audio_options, sopts, st) ) {
+                               eprintf("FFMPEG::open_encoder: bad audio options %s:%s\n",
+                                       codec_name, filename);
+                               ret = 1;
+                               break;
+                       }
+                       if( asset->ff_audio_bitrate > 0 ) {
+                               ctx->bit_rate = asset->ff_audio_bitrate;
+                               char arg[BCSTRLEN];
+                               sprintf(arg, "%d", asset->ff_audio_bitrate);
+                               av_dict_set(&sopts, "b", arg, 0);
+                       }
                        int aidx = ffaudio.size();
-                       int idx = aidx + ffvideo.size();
-                       FFAudioStream *aud = new FFAudioStream(this, st, idx);
+                       int fidx = aidx + ffvideo.size();
+                       FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
                        ffaudio.append(aud);  fst = aud;
                        aud->sample_rate = asset->sample_rate;
                        ctx->channels = aud->channels = asset->channels;
@@ -1426,7 +1654,7 @@ int FFMPEG::open_encoder(const char *path, const char *spec)
                        ctx->channel_layout =  av_get_default_channel_layout(ctx->channels);
                        ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
                        if( !ctx->sample_rate ) {
-                               fprintf(stderr, "FFMPEG::open_audio_encode:"
+                               eprintf("FFMPEG::open_audio_encode:"
                                        " check_sample_rate failed %s\n", filename);
                                ret = 1;
                                break;
@@ -1443,15 +1671,40 @@ int FFMPEG::open_encoder(const char *path, const char *spec)
                        break; }
                case AVMEDIA_TYPE_VIDEO: {
                        if( has_video ) {
-                               fprintf(stderr, "FFMPEG::open_encoder: duplicate video %s:%s\n",
+                               eprintf("FFMPEG::open_encoder: duplicate video %s:%s\n",
                                        codec_name, filename);
                                ret = 1;
                                break;
                        }
                        has_video = 1;
+                       if( scan_options(asset->ff_video_options, sopts, st) ) {
+                               eprintf("FFMPEG::open_encoder: bad video options %s:%s\n",
+                                       codec_name, filename);
+                               ret = 1;
+                               break;
+                       }
+                       if( asset->ff_video_bitrate > 0 ) {
+                               ctx->bit_rate = asset->ff_video_bitrate;
+                               char arg[BCSTRLEN];
+                               sprintf(arg, "%d", asset->ff_video_bitrate);
+                               av_dict_set(&sopts, "b", arg, 0);
+                       }
+                       else if( asset->ff_video_quality > 0 ) {
+                               ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
+                               ctx->qmin    = ctx->qmax =  asset->ff_video_quality;
+                               ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
+                               ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
+                               ctx->flags |= CODEC_FLAG_QSCALE;
+                               char arg[BCSTRLEN];
+                               av_dict_set(&sopts, "flags", "+qscale", 0);
+                               sprintf(arg, "%d", asset->ff_video_quality);
+                               av_dict_set(&sopts, "qscale", arg, 0);
+                               sprintf(arg, "%d", ctx->global_quality);
+                               av_dict_set(&sopts, "global_quality", arg, 0);
+                       }
                        int vidx = ffvideo.size();
-                       int idx = vidx + ffaudio.size();
-                       FFVideoStream *vid = new FFVideoStream(this, st, idx);
+                       int fidx = vidx + ffaudio.size();
+                       FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
                        vstrm_index.append(ffidx(vidx, 0));
                        ffvideo.append(vid);  fst = vid;
                        vid->width = asset->width;
@@ -1459,11 +1712,11 @@ int FFMPEG::open_encoder(const char *path, const char *spec)
                        vid->height = asset->height;
                        ctx->height = (vid->height+3) & ~3;
                        vid->frame_rate = asset->frame_rate;
-                       ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset->aspect_ratio);
+                       ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
                        ctx->pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
                        AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
                        if( !frame_rate.num || !frame_rate.den ) {
-                               fprintf(stderr, "FFMPEG::open_audio_encode:"
+                               eprintf("FFMPEG::open_audio_encode:"
                                        " check_frame_rate failed %s\n", filename);
                                ret = 1;
                                break;
@@ -1473,16 +1726,19 @@ int FFMPEG::open_encoder(const char *path, const char *spec)
                        vid->writing = -1;
                        break; }
                default:
-                       fprintf(stderr, "FFMPEG::open_encoder: not audio/video, %s:%s\n",
+                       eprintf("FFMPEG::open_encoder: not audio/video, %s:%s\n",
                                codec_name, filename);
                        ret = 1;
                }
        }
        if( !ret ) {
+               if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
+                       st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
+
                ret = avcodec_open2(st->codec, codec, &sopts);
                if( ret < 0 ) {
                        ff_err(ret,"FFMPEG::open_encoder");
-                       fprintf(stderr, "FFMPEG::open_encoder: open failed %s:%s\n",
+                       eprintf("FFMPEG::open_encoder: open failed %s:%s\n",
                                codec_name, filename);
                        ret = 1;
                }
@@ -1490,8 +1746,6 @@ int FFMPEG::open_encoder(const char *path, const char *spec)
                        ret = 0;
        }
        if( !ret ) {
-               if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
-                       st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
                if( fst && bsfilter[0] )
                        fst->add_bsfilter(bsfilter, !bsargs[0] ? 0 : bsargs);
        }
@@ -1517,80 +1771,89 @@ int FFMPEG::decode_activate()
 {
        if( decoding < 0 ) {
                decoding = 0;
+               for( int vidx=0; vidx<ffvideo.size(); ++vidx )
+                       ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
+               for( int aidx=0; aidx<ffaudio.size(); ++aidx )
+                       ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
+               // set nudges for each program stream set
                int npgrms = fmt_ctx->nb_programs;
                for( int i=0; i<npgrms; ++i ) {
                        AVProgram *pgrm = fmt_ctx->programs[i];
                        // first start time video stream
-                       int64_t vstart_time = -1;
+                       int64_t vstart_time = -1, astart_time = -1;
                        for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
-                               int st_idx = pgrm->stream_index[j];
-                               AVStream *st = fmt_ctx->streams[st_idx];
+                               int fidx = pgrm->stream_index[j];
+                               AVStream *st = fmt_ctx->streams[fidx];
                                AVCodecContext *avctx = st->codec;
                                if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
                                        if( st->start_time == AV_NOPTS_VALUE ) continue;
+                                       if( vstart_time > st->start_time ) continue;
                                        vstart_time = st->start_time;
-                                       break;
+                                       continue;
                                }
-                       }
-                       // max start time audio stream
-                       int64_t astart_time = -1;
-                       for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
-                               int st_idx = pgrm->stream_index[j];
-                               AVStream *st = fmt_ctx->streams[st_idx];
-                               AVCodecContext *avctx = st->codec;
                                if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
                                        if( st->start_time == AV_NOPTS_VALUE ) continue;
                                        if( astart_time > st->start_time ) continue;
                                        astart_time = st->start_time;
+                                       continue;
                                }
                        }
-                       if( astart_time < 0 || vstart_time < 0 ) continue;
                        // match program streams to max start_time
                        int64_t nudge = vstart_time > astart_time ? vstart_time : astart_time;
                        for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
-                               int st_idx = pgrm->stream_index[j];
-                               AVStream *st = fmt_ctx->streams[st_idx];
+                               int fidx = pgrm->stream_index[j];
+                               AVStream *st = fmt_ctx->streams[fidx];
                                AVCodecContext *avctx = st->codec;
-                               if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
-                                       for( int k=0; k<ffaudio.size(); ++k ) {
-                                               if( ffaudio[k]->idx == st_idx )
-                                                       ffaudio[k]->nudge = nudge;
+                               if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
+                                       for( int k=0; k<ffvideo.size(); ++k ) {
+                                               if( ffvideo[k]->fidx != fidx ) continue;
+                                               ffvideo[k]->nudge = nudge;
                                        }
+                                       continue;
                                }
-                               else if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
-                                       for( int k=0; k<ffvideo.size(); ++k ) {
-                                               if( ffvideo[k]->idx == st_idx )
-                                                       ffvideo[k]->nudge = nudge;
+                               if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
+                                       for( int k=0; k<ffaudio.size(); ++k ) {
+                                               if( ffaudio[k]->fidx != fidx ) continue;
+                                               ffaudio[k]->nudge = nudge;
                                        }
+                                       continue;
                                }
                        }
                }
+               // set nudges for any streams not yet set
                int64_t vstart_time = 0, astart_time = 0;
                int nstreams = fmt_ctx->nb_streams;
                for( int i=0; i<nstreams; ++i ) {
                        AVStream *st = fmt_ctx->streams[i];
                        AVCodecContext *avctx = st->codec;
                        switch( avctx->codec_type ) {
-                       case AVMEDIA_TYPE_VIDEO:
+                       case AVMEDIA_TYPE_VIDEO: {
                                if( st->start_time == AV_NOPTS_VALUE ) continue;
+                               int vidx = ffvideo.size();
+                               while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
+                               if( vidx >= 0 && ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
                                if( vstart_time >= st->start_time ) continue;
                                vstart_time = st->start_time;
-                               break;
-                       case AVMEDIA_TYPE_AUDIO:
+                               break; }
+                       case AVMEDIA_TYPE_AUDIO: {
                                if( st->start_time == AV_NOPTS_VALUE ) continue;
+                               int aidx = ffaudio.size();
+                               while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
+                               if( aidx >= 0 && ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
                                if( astart_time >= st->start_time ) continue;
                                astart_time = st->start_time;
+                               break; }
                        default: break;
                        }
                }
                int64_t nudge = vstart_time > astart_time ? vstart_time : astart_time;
-               for( int k=0; k<ffvideo.size(); ++k ) {
-                       if( ffvideo[k]->nudge != AV_NOPTS_VALUE ) continue;
-                       ffvideo[k]->nudge = nudge;
+               for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
+                       if( ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
+                       ffvideo[vidx]->nudge = nudge;
                }
-               for( int k=0; k<ffaudio.size(); ++k ) {
-                       if( ffaudio[k]->nudge != AV_NOPTS_VALUE ) continue;
-                       ffaudio[k]->nudge = nudge;
+               for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
+                       if( ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
+                       ffaudio[aidx]->nudge = nudge;
                }
                decoding = 1;
        }
@@ -1599,11 +1862,12 @@ int FFMPEG::decode_activate()
 
 int FFMPEG::encode_activate()
 {
+       int ret = 0;
        if( encoding < 0 ) {
                encoding = 0;
                if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
-                   avio_open(&fmt_ctx->pb, fmt_ctx->filename, AVIO_FLAG_WRITE) < 0 ) {
-                       fprintf(stderr, "FFMPEG::encode_activate: err opening : %s\n",
+                   (ret=avio_open(&fmt_ctx->pb, fmt_ctx->filename, AVIO_FLAG_WRITE)) < 0 ) {
+                       ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
                                fmt_ctx->filename);
                        return 1;
                }
@@ -1612,10 +1876,10 @@ int FFMPEG::encode_activate()
                char option_path[BCTEXTLEN];
                set_option_path(option_path, "format/%s", file_format);
                read_options(option_path, fopts);
-               int ret = avformat_write_header(fmt_ctx, &fopts);
+               ret = avformat_write_header(fmt_ctx, &fopts);
                av_dict_free(&fopts);
                if( ret < 0 ) {
-                       fprintf(stderr, "FFMPEG::encode_activate: write header failed %s\n",
+                       ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
                                fmt_ctx->filename);
                        return 1;
                }
@@ -1624,12 +1888,12 @@ int FFMPEG::encode_activate()
        return encoding;
 }
 
+
 int FFMPEG::audio_seek(int stream, int64_t pos)
 {
        int aidx = astrm_index[stream].st_idx;
        FFAudioStream *aud = ffaudio[aidx];
        aud->audio_seek(pos);
-       aud->seek_pos = aud->curr_pos = pos;
        return 0;
 }
 
@@ -1638,7 +1902,6 @@ int FFMPEG::video_seek(int stream, int64_t pos)
        int vidx = vstrm_index[stream].st_idx;
        FFVideoStream *vid = ffvideo[vidx];
        vid->video_seek(pos);
-       vid->seek_pos = vid->curr_pos = pos;
        return 0;
 }
 
@@ -1650,7 +1913,8 @@ int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
        FFAudioStream *aud = ffaudio[aidx];
        if( aud->load(pos, len) < len ) return -1;
        int ch = astrm_index[chn].st_ch;
-       return aud->history.read(samples,len,ch);
+       int ret = aud->read(samples,len,ch);
+       return ret;
 }
 
 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
@@ -1661,6 +1925,7 @@ int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
        return vid->load(vframe, pos);
 }
 
+
 int FFMPEG::encode(int stream, double **samples, int len)
 {
        FFAudioStream *aud = ffaudio[stream];
@@ -1716,19 +1981,15 @@ void FFMPEG::flow_ctl()
 int FFMPEG::mux_audio(FFrame *frm)
 {
        FFPacket pkt;
-       AVStream *st = frm->fst->st;
-       AVCodecContext *ctx = st->codec;
+       FFStream *fst = frm->fst;
+       AVCodecContext *ctx = fst->st->codec;
        AVFrame *frame = *frm;
        AVRational tick_rate = {1, ctx->sample_rate};
        frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
        int got_packet = 0;
-       int ret = avcodec_encode_audio2(ctx, pkt, frame, &got_packet);
-       if( ret >= 0 && got_packet ) {
-               frm->fst->bs_filter(pkt);
-               av_packet_rescale_ts(pkt, ctx->time_base, st->time_base);
-               pkt->stream_index = st->index;
-               ret = av_interleaved_write_frame(fmt_ctx, pkt);
-       }
+       int ret = fst->encode_frame(pkt, frame, got_packet);
+       if( ret >= 0 && got_packet )
+               ret = fst->write_packet(pkt);
        if( ret < 0 )
                ff_err(ret, "FFMPEG::mux_audio");
        return ret >= 0 ? 0 : 1;
@@ -1737,14 +1998,14 @@ int FFMPEG::mux_audio(FFrame *frm)
 int FFMPEG::mux_video(FFrame *frm)
 {
        FFPacket pkt;
-       AVStream *st = frm->fst->st;
+       FFStream *fst = frm->fst;
        AVFrame *frame = *frm;
        frame->pts = frm->position;
        int ret = 1, got_packet = 0;
        if( fmt_ctx->oformat->flags & AVFMT_RAWPICTURE ) {
                /* a hack to avoid data copy with some raw video muxers */
                pkt->flags |= AV_PKT_FLAG_KEY;
-               pkt->stream_index  = st->index;
+               pkt->stream_index  = fst->st->index;
                AVPicture *picture = (AVPicture *)frame;
                pkt->data = (uint8_t *)picture;
                pkt->size = sizeof(AVPicture);
@@ -1752,13 +2013,9 @@ int FFMPEG::mux_video(FFrame *frm)
                got_packet = 1;
        }
        else
-               ret = avcodec_encode_video2(st->codec, pkt, frame, &got_packet);
-       if( ret >= 0 && got_packet ) {
-               frm->fst->bs_filter(pkt);
-               av_packet_rescale_ts(pkt, st->codec->time_base, st->time_base);
-               pkt->stream_index = st->index;
-               ret = av_interleaved_write_frame(fmt_ctx, pkt);
-       }
+               ret = fst->encode_frame(pkt, frame, got_packet);
+       if( ret >= 0 && got_packet )
+               ret = fst->write_packet(pkt);
        if( ret < 0 )
                ff_err(ret, "FFMPEG::mux_video");
        return ret >= 0 ? 0 : 1;
@@ -1806,6 +2063,10 @@ void FFMPEG::run()
                if( !done ) mux();
        }
        mux();
+       for( int i=0; i<ffaudio.size(); ++i )
+               ffaudio[i]->flush();
+       for( int i=0; i<ffvideo.size(); ++i )
+               ffvideo[i]->flush();
 }
 
 
@@ -1853,7 +2114,7 @@ int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
 {
        channel_mask = 0;
        int pidx = -1;
-       int vidx = ffvideo[vstream]->idx;
+       int vidx = ffvideo[vstream]->fidx;
        // find first program with this video stream
        for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
                AVProgram *pgrm = fmt_ctx->programs[i];
@@ -1875,7 +2136,7 @@ int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
                if( astream > 0 ) { --astream;  continue; }
                int astrm = -1;
                for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
-                       if( ffaudio[i]->idx == aidx ) astrm = i;
+                       if( ffaudio[i]->fidx == aidx ) astrm = i;
                if( astrm >= 0 ) {
                        if( ret < 0 ) ret = astrm;
                        int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
@@ -1972,6 +2233,11 @@ int FFVideoStream::create_filter(const char *filter_spec,
                AVCodecContext *src_ctx, AVCodecContext *sink_ctx)
 {
        avfilter_register_all();
+       AVFilter *filter = avfilter_get_by_name(filter_spec);
+       if( !filter || filter->inputs->type != AVMEDIA_TYPE_VIDEO ) {
+               ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
+               return -1;
+       }
        filter_graph = avfilter_graph_alloc();
        AVFilter *buffersrc = avfilter_get_by_name("buffer");
        AVFilter *buffersink = avfilter_get_by_name("buffersink");
@@ -1980,7 +2246,7 @@ int FFVideoStream::create_filter(const char *filter_spec,
        snprintf(args, sizeof(args),
                "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
                src_ctx->width, src_ctx->height, src_ctx->pix_fmt,
-               st->time_base.num, st->time_base.den,
+               src_ctx->time_base.num, src_ctx->time_base.den,
                src_ctx->sample_aspect_ratio.num, src_ctx->sample_aspect_ratio.den);
        if( ret >= 0 )
                ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
@@ -2003,13 +2269,18 @@ int FFAudioStream::create_filter(const char *filter_spec,
                AVCodecContext *src_ctx, AVCodecContext *sink_ctx)
 {
        avfilter_register_all();
+       AVFilter *filter = avfilter_get_by_name(filter_spec);
+       if( !filter || filter->inputs->type != AVMEDIA_TYPE_AUDIO ) {
+               ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
+               return -1;
+       }
        filter_graph = avfilter_graph_alloc();
        AVFilter *buffersrc = avfilter_get_by_name("abuffer");
        AVFilter *buffersink = avfilter_get_by_name("abuffersink");
        int ret = 0;  char args[BCTEXTLEN];
        snprintf(args, sizeof(args),
                "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
-               st->time_base.num, st->time_base.den, src_ctx->sample_rate,
+               src_ctx->time_base.num, src_ctx->time_base.den, src_ctx->sample_rate,
                av_get_sample_fmt_name(src_ctx->sample_fmt), src_ctx->channel_layout);
        if( ret >= 0 )
                ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
@@ -2105,3 +2376,148 @@ int FFStream::bs_filter(AVPacket *pkt)
        return ret;
 }
 
+int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
+{
+       AVPacket pkt;
+       av_init_packet(&pkt);
+       AVFrame *frame = av_frame_alloc();
+       if( !frame ) {
+               fprintf(stderr, "FFMPEG::scan: av_frame_alloc failed\n");
+               return -1;
+       }
+
+       index_state->add_video_markers(ffvideo.size());
+       index_state->add_audio_markers(ffaudio.size());
+
+       for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
+               AVDictionary *copts = 0;
+               av_dict_copy(&copts, opts, 0);
+               AVStream *st = fmt_ctx->streams[i];
+               AVCodecID codec_id = st->codec->codec_id;
+               AVCodec *decoder = avcodec_find_decoder(codec_id);
+               if( avcodec_open2(st->codec, decoder, &copts) < 0 )
+                       fprintf(stderr, "FFMPEG::scan: codec open failed\n");
+               av_dict_free(&copts);
+       }
+       int errs = 0;
+       for( int64_t count=0; !*canceled; ++count ) {
+               av_packet_unref(&pkt);
+               pkt.data = 0; pkt.size = 0;
+
+               int ret = av_read_frame(fmt_ctx, &pkt);
+               if( ret < 0 ) {
+                       if( ret == AVERROR_EOF ) break;
+                       if( ++errs > 100 ) {
+                               ff_err(ret, "over 100 read_frame errs\n");
+                               break;
+                       }
+                       continue;
+               }
+               if( !pkt.data ) continue;
+               int i = pkt.stream_index;
+               if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
+               AVStream *st = fmt_ctx->streams[i];
+               AVCodecContext *avctx = st->codec;
+               if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
+
+               switch( avctx->codec_type ) {
+               case AVMEDIA_TYPE_VIDEO: {
+                       int vidx = ffvideo.size();
+                       while( --vidx>=0 && ffvideo[vidx]->fidx != i );
+                       if( vidx < 0 ) break;
+                       FFVideoStream *vid = ffvideo[vidx];
+                       int64_t tstmp = pkt.dts;
+                       if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.pts;
+                       if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
+                               if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
+                               double secs = to_secs(tstmp, st->time_base);
+                               int64_t frm = secs * vid->frame_rate + 0.5;
+                               if( frm < 0 ) frm = 0;
+                               index_state->put_video_mark(vidx, frm, pkt.pos);
+                       }
+#if 0
+                       while( pkt.size > 0 ) {
+                               av_frame_unref(frame);
+                               int got_frame = 0;
+                               int ret = vid->decode_frame(&pkt, frame, got_frame);
+                               if( ret <= 0 ) break;
+//                             if( got_frame ) {}
+                               pkt.data += ret;
+                               pkt.size -= ret;
+                       }
+#endif
+                       break; }
+               case AVMEDIA_TYPE_AUDIO: {
+                       int aidx = ffaudio.size();
+                       while( --aidx>=0 && ffaudio[aidx]->fidx != i );
+                       if( aidx < 0 ) break;
+                       FFAudioStream *aud = ffaudio[aidx];
+                       int64_t tstmp = pkt.pts;
+                       if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
+                       if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
+                               if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
+                               double secs = to_secs(tstmp, st->time_base);
+                               int64_t sample = secs * aud->sample_rate + 0.5;
+                               if( sample < 0 ) sample = 0;
+                               index_state->put_audio_mark(aidx, sample, pkt.pos);
+                       }
+                       while( pkt.size > 0 ) {
+                               int ch = aud->channel0,  nch = aud->channels;
+                               int64_t pos = index_state->pos(ch);
+                               if( pos != aud->curr_pos ) {
+if( abs(pos-aud->curr_pos) > 1 )
+printf("audio%d pad %ld %ld (%ld)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
+                                       index_state->pad_data(ch, nch, aud->curr_pos);
+                               }
+                               av_frame_unref(frame);
+                               int got_frame = 0;
+                               int ret = aud->decode_frame(&pkt, frame, got_frame);
+                               if( ret <= 0 ) break;
+                               if( got_frame ) {
+                                       float *samples;
+                                       int len = aud->get_samples(samples,
+                                                &frame->extended_data[0], frame->nb_samples);
+                                       for( int i=0; i<nch; ++i )
+                                               index_state->put_data(ch+i,nch,samples+i,len);
+                                       aud->curr_pos += len;
+                               }
+                               pkt.data += ret;
+                               pkt.size -= ret;
+                       }
+                       break; }
+               default: break;
+               }
+       }
+       av_frame_free(&frame);
+       return 0;
+}
+
+void FFStream::load_markers(IndexMarks &marks, double rate)
+{
+       index_markers = &marks;
+       int in = 0;
+       int64_t sz = marks.size();
+       int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
+       int nb_ent = st->nb_index_entries;
+// some formats already have an index
+       if( nb_ent > 0 ) {
+               AVIndexEntry *ep = &st->index_entries[nb_ent-1];
+               int64_t tstmp = ep->timestamp;
+               if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
+               double secs = ffmpeg->to_secs(tstmp, st->time_base);
+               int64_t no = secs * rate;
+               while( in < sz && marks[in].no <= no ) ++in;
+       }
+       int64_t len = sz - in;
+       int64_t count = max_entries - nb_ent;
+       if( count > len ) count = len;
+       for( int i=0; i<count; ++i ) {
+               int k = in + i * len / count;
+               int64_t no = marks[k].no, pos = marks[k].pos;
+               double secs = (double)no / rate;
+               int64_t tstmp = secs * st->time_base.den / st->time_base.num;
+               if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
+               av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);
+       }
+}
+