efb11be359a0bc4018000ed7784b3ad1f2bb5385
[goodguy/history.git] / cinelerra-5.0 / cinelerra / ffmpeg.C
1
2 #include <stdio.h>
3 #include <stdint.h>
4 #include <stdlib.h>
5 #include <unistd.h>
6 #include <string.h>
7 #include <stdarg.h>
8 #include <fcntl.h>
9 #include <limits.h>
10 // work arounds (centos)
11 #include <lzma.h>
12 #ifndef INT64_MAX
13 #define INT64_MAX 9223372036854775807LL
14 #endif
15
16 #include "asset.h"
17 #include "bccmodels.h"
18 #include "fileffmpeg.h"
19 #include "file.h"
20 #include "ffmpeg.h"
21 #include "indexfile.h"
22 #include "libdv.h"
23 #include "libmjpeg.h"
24 #include "mainerror.h"
25 #include "mwindow.h"
26 #include "vframe.h"
27
28
29 #define VIDEO_INBUF_SIZE 0x10000
30 #define AUDIO_INBUF_SIZE 0x10000
31 #define VIDEO_REFILL_THRESH 0
32 #define AUDIO_REFILL_THRESH 0x1000
33
34 Mutex FFMPEG::fflock("FFMPEG::fflock");
35
36 static void ff_err(int ret, const char *fmt, ...)
37 {
38         char msg[BCTEXTLEN];
39         va_list ap;
40         va_start(ap, fmt);
41         vsnprintf(msg, sizeof(msg), fmt, ap);
42         va_end(ap);
43         char errmsg[BCSTRLEN];
44         av_strerror(ret, errmsg, sizeof(errmsg));
45         fprintf(stderr,_("%s  err: %s\n"),msg, errmsg);
46 }
47
48 FFPacket::FFPacket()
49 {
50         init();
51 }
52
53 FFPacket::~FFPacket()
54 {
55         av_free_packet(&pkt);
56 }
57
58 void FFPacket::init()
59 {
60         av_init_packet(&pkt);
61         pkt.data = 0; pkt.size = 0;
62 }
63
64 FFrame::FFrame(FFStream *fst)
65 {
66         this->fst = fst;
67         frm = av_frame_alloc();
68         init = fst->init_frame(frm);
69 }
70
71 FFrame::~FFrame()
72 {
73         av_frame_free(&frm);
74 }
75
76 void FFrame::queue(int64_t pos)
77 {
78         position = pos;
79         fst->queue(this);
80 }
81
82 void FFrame::dequeue()
83 {
84         fst->dequeue(this);
85 }
86
87 int FFAudioStream::read(float *fp, long len)
88 {
89         long n = len * nch;
90         float *op = outp;
91         while( n > 0 ) {
92                 int k = lmt - op;
93                 if( k > n ) k = n;
94                 n -= k;
95                 while( --k >= 0 ) *fp++ = *op++;
96                 if( op >= lmt ) op = bfr;
97         }
98         return len;
99 }
100
101 void FFAudioStream::realloc(long nsz, int nch, long len)
102 {
103         long bsz = nsz * nch;
104         float *np = new float[bsz];
105         inp = np + read(np, len) * nch;
106         outp = np;
107         lmt = np + bsz;
108         this->nch = nch;
109         sz = nsz;
110         delete [] bfr;  bfr = np;
111 }
112
113 void FFAudioStream::realloc(long nsz, int nch)
114 {
115         if( nsz > sz || this->nch != nch ) {
116                 long len = this->nch != nch ? 0 : hpos;
117                 if( len > sz ) len = sz;
118                 iseek(len);
119                 realloc(nsz, nch, len);
120         }
121 }
122
123 void FFAudioStream::reserve(long nsz, int nch)
124 {
125         long len = (inp - outp) / nch;
126         nsz += len;
127         if( nsz > sz || this->nch != nch ) {
128                 if( this->nch != nch ) len = 0;
129                 realloc(nsz, nch, len);
130                 return;
131         }
132         if( (len*=nch) > 0 && bfr != outp )
133                 memmove(bfr, outp, len*sizeof(*bfr));
134         outp = bfr;
135         inp = bfr + len;
136 }
137
138 long FFAudioStream::used()
139 {
140         long len = inp>=outp ? inp-outp : inp-bfr + lmt-outp;
141         return len / nch;
142 }
143 long FFAudioStream::avail()
144 {
145         float *in1 = inp+1;
146         if( in1 >= lmt ) in1 = bfr;
147         long len = outp >= in1 ? outp-in1 : outp-bfr + lmt-in1;
148         return len / nch;
149 }
150 void FFAudioStream::reset_history()
151 {
152         inp = outp = bfr;
153         hpos = 0;
154 }
155
156 void FFAudioStream::iseek(int64_t ofs)
157 {
158         outp = inp - ofs*nch;
159         if( outp < bfr ) outp += sz*nch;
160 }
161
162 float *FFAudioStream::get_outp(int ofs)
163 {
164         float *ret = outp;
165         outp += ofs*nch;
166         return ret;
167 }
168
169 int64_t FFAudioStream::put_inp(int ofs)
170 {
171         inp += ofs*nch;
172         return (inp-outp) / nch;
173 }
174
175 int FFAudioStream::write(const float *fp, long len)
176 {
177         long n = len * nch;
178         float *ip = inp;
179         while( n > 0 ) {
180                 int k = lmt - ip;
181                 if( k > n ) k = n;
182                 n -= k;
183                 while( --k >= 0 ) *ip++ = *fp++;
184                 if( ip >= lmt ) ip = bfr;
185         }
186         inp = ip;
187         hpos += len;
188         return len;
189 }
190
191 int FFAudioStream::zero(long len)
192 {
193         long n = len * nch;
194         float *ip = inp;
195         while( n > 0 ) {
196                 int k = lmt - ip;
197                 if( k > n ) k = n;
198                 n -= k;
199                 while( --k >= 0 ) *ip++ = 0;
200                 if( ip >= lmt ) ip = bfr;
201         }
202         inp = ip;
203         hpos += len;
204         return len;
205 }
206
207 // does not advance outp
208 int FFAudioStream::read(double *dp, long len, int ch)
209 {
210         long n = len;
211         float *op = outp + ch;
212         float *lmt1 = lmt + nch-1;
213         while( n > 0 ) {
214                 int k = (lmt1 - op) / nch;
215                 if( k > n ) k = n;
216                 n -= k;
217                 while( --k >= 0 ) { *dp++ = *op;  op += nch; }
218                 if( op >= lmt ) op -= sz*nch;
219         }
220         return len;
221 }
222
223 // load linear buffer, no wrapping allowed, does not advance inp
224 int FFAudioStream::write(const double *dp, long len, int ch)
225 {
226         long n = len;
227         float *ip = inp + ch;
228         while( --n >= 0 ) { *ip = *dp++;  ip += nch; }
229         return len;
230 }
231
232
233 FFStream::FFStream(FFMPEG *ffmpeg, AVStream *st, int fidx)
234 {
235         this->ffmpeg = ffmpeg;
236         this->st = st;
237         this->fidx = fidx;
238         frm_lock = new Mutex("FFStream::frm_lock");
239         fmt_ctx = 0;
240         filter_graph = 0;
241         buffersrc_ctx = 0;
242         buffersink_ctx = 0;
243         frm_count = 0;
244         nudge = AV_NOPTS_VALUE;
245         seek_pos = curr_pos = 0;
246         seeked = 1;  eof = 0;
247         index_markers = 0;
248         reading = writing = 0;
249         flushed = 0;
250         need_packet = 1;
251         frame = fframe = 0;
252 }
253
254 FFStream::~FFStream()
255 {
256         if( reading > 0 || writing > 0 ) avcodec_close(st->codec);
257         if( fmt_ctx ) avformat_close_input(&fmt_ctx);
258         while( frms.first ) frms.remove(frms.first);
259         if( filter_graph ) avfilter_graph_free(&filter_graph);
260         if( frame ) av_frame_free(&frame);
261         if( fframe ) av_frame_free(&fframe);
262         bsfilter.remove_all_objects();
263         delete frm_lock;
264 }
265
266 void FFStream::ff_lock(const char *cp)
267 {
268         FFMPEG::fflock.lock(cp);
269 }
270
271 void FFStream::ff_unlock()
272 {
273         FFMPEG::fflock.unlock();
274 }
275
276 void FFStream::queue(FFrame *frm)
277 {
278         frm_lock->lock("FFStream::queue");
279         frms.append(frm);
280         ++frm_count;
281         frm_lock->unlock();
282         ffmpeg->mux_lock->unlock();
283 }
284
285 void FFStream::dequeue(FFrame *frm)
286 {
287         frm_lock->lock("FFStream::dequeue");
288         --frm_count;
289         frms.remove_pointer(frm);
290         frm_lock->unlock();
291 }
292
293 int FFStream::encode_activate()
294 {
295         if( writing < 0 )
296                 writing = ffmpeg->encode_activate();
297         return writing;
298 }
299
300 int FFStream::decode_activate()
301 {
302         if( reading < 0 && (reading=ffmpeg->decode_activate()) > 0 ) {
303                 ff_lock("FFStream::decode_activate");
304                 reading = 0;
305                 AVDictionary *copts = 0;
306                 av_dict_copy(&copts, ffmpeg->opts, 0);
307                 int ret = 0;
308                 // this should be avformat_copy_context(), but no copy avail
309                 ret = avformat_open_input(&fmt_ctx, ffmpeg->fmt_ctx->filename, NULL, &copts);
310                 if( ret >= 0 ) {
311                         ret = avformat_find_stream_info(fmt_ctx, 0);
312                         st = fmt_ctx->streams[fidx];
313                         load_markers();
314                 }
315                 if( ret >= 0 ) {
316                         AVCodecID codec_id = st->codec->codec_id;
317                         AVCodec *decoder = avcodec_find_decoder(codec_id);
318                         ret = avcodec_open2(st->codec, decoder, &copts);
319                         if( ret >= 0 )
320                                 reading = 1;
321                         else
322                                 eprintf("FFStream::decode_activate: open decoder failed\n");
323                 }
324                 else
325                         eprintf("FFStream::decode_activate: can't clone input file\n");
326                 av_dict_free(&copts);
327                 ff_unlock();
328         }
329         return reading;
330 }
331
332 int FFStream::read_packet()
333 {
334         av_packet_unref(ipkt);
335         int ret = av_read_frame(fmt_ctx, ipkt);
336         if( ret < 0 ) {
337                 st_eof(1);
338                 if( ret == AVERROR_EOF ) {
339                         ipkt->stream_index = st->index;
340                         return 0;
341                 }
342                 ff_err(ret, "FFStream::read_packet: av_read_frame failed\n");
343                 flushed = 1;
344                 return -1;
345         }
346         return 1;
347 }
348
349 int FFStream::decode(AVFrame *frame)
350 {
351         int ret = 0;
352         int retries = 1000;
353         int got_frame = 0;
354
355         while( ret >= 0 && !flushed && --retries >= 0 && !got_frame ) {
356                 if( need_packet ) {
357                         need_packet = 0;
358                         if( (ret=read_packet()) < 0 ) break;
359                 }
360                 if( ipkt->stream_index == st->index ) {
361                         while( (ipkt->size > 0 || !ipkt->data) && !got_frame ) {
362                                 ret = decode_frame(ipkt, frame, got_frame);
363                                 if( ret <= 0 || !ipkt->data ) break;
364                                 ipkt->data += ret;
365                                 ipkt->size -= ret;
366                         }
367                         retries = 1000;
368                 }
369                 if( !got_frame ) {
370                         need_packet = 1;
371                         flushed = st_eof();
372                 }
373         }
374
375         if( retries < 0 )
376                 fprintf(stderr, "FFStream::decode: Retry limit\n");
377         if( ret >= 0 )
378                 ret = got_frame;
379         else
380                 fprintf(stderr, "FFStream::decode: failed\n");
381
382         return ret;
383 }
384
385 int FFStream::load_filter(AVFrame *frame)
386 {
387         int ret = av_buffersrc_add_frame_flags(buffersrc_ctx,
388                         frame, AV_BUFFERSRC_FLAG_KEEP_REF);
389         if( ret < 0 ) {
390                 av_frame_unref(frame);
391                 eprintf("FFStream::load_filter: av_buffersrc_add_frame_flags failed\n");
392         }
393         return ret;
394 }
395
396 int FFStream::read_filter(AVFrame *frame)
397 {
398         int ret = av_buffersink_get_frame(buffersink_ctx, frame);
399         if( ret < 0 ) {
400                 if( ret == AVERROR(EAGAIN) ) return 0;
401                 if( ret == AVERROR_EOF ) { st_eof(1); return -1; }
402                 ff_err(ret, "FFStream::read_filter: av_buffersink_get_frame failed\n");
403                 return ret;
404         }
405         return 1;
406 }
407
408 int FFStream::read_frame(AVFrame *frame)
409 {
410         if( !filter_graph || !buffersrc_ctx || !buffersink_ctx )
411                 return decode(frame);
412         if( !fframe && !(fframe=av_frame_alloc()) ) {
413                 fprintf(stderr, "FFStream::read_frame: av_frame_alloc failed\n");
414                 return -1;
415         }
416         int ret = -1;
417         while( !flushed && !(ret=read_filter(frame)) ) {
418                 if( (ret=decode(fframe)) < 0 ) break;
419                 if( ret > 0 && (ret=load_filter(fframe)) < 0 ) break;
420         }
421         return ret;
422 }
423
424 int FFStream::write_packet(FFPacket &pkt)
425 {
426         bs_filter(pkt);
427         av_packet_rescale_ts(pkt, st->codec->time_base, st->time_base);
428         pkt->stream_index = st->index;
429         return av_interleaved_write_frame(ffmpeg->fmt_ctx, pkt);
430 }
431
432 int FFStream::flush()
433 {
434         int ret = 0;
435         while( ret >= 0 ) {
436                 FFPacket pkt;
437                 int got_packet = 0;
438                 ret = encode_frame(pkt, 0, got_packet);
439                 if( ret < 0 || !got_packet ) break;
440                 ret = write_packet(pkt);
441         }
442         if( ret < 0 )
443                 ff_err(ret, "FFStream::flush");
444         return ret >= 0 ? 0 : 1;
445 }
446
447 int FFStream::seek(int64_t no, double rate)
448 {
449         if( no < 0 ) no = 0;
450 // default ffmpeg native seek
451         int npkts = 1;
452         int64_t pos = no, plmt = -1;
453         if( index_markers && index_markers->size() > 1 ) {
454                 IndexMarks &marks = *index_markers;
455                 int i = marks.find(pos);
456                 int64_t n = i < 0 ? (i=0) : marks[i].no;
457 // if indexed seek point not too far away (<30 secs), use index
458                 if( no-n < 30*rate ) {
459                         if( n < 0 ) n = 0;
460                         pos = n;
461                         plmt = marks[i].pos;
462                         npkts = 1000;
463                 }
464         }
465         double secs = pos / rate;
466         int64_t tstmp = secs * st->time_base.den / st->time_base.num;
467         if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
468         if( avformat_seek_file(fmt_ctx, st->index,
469                 -INT64_MAX, tstmp, INT64_MAX, AVSEEK_FLAG_ANY) < 0 ) return -1;
470         avcodec_flush_buffers(st->codec);
471         need_packet = 0;  flushed = 0;
472         seeked = 1;  st_eof(0);
473         int64_t pkt_ts = AV_NOPTS_VALUE;
474         int ret = 1, retry = 1000;
475
476 // read up to retry packets, limited to npkts in stream, and not past pkt.pos plmt
477         while( ret > 0 && npkts > 0 && --retry >= 0 ) {
478                 if( (ret=read_packet()) <= 0 ) break;
479                 if( ipkt->stream_index != st->index ) continue;
480                 if( (pkt_ts=ipkt->dts) == AV_NOPTS_VALUE ) pkt_ts = ipkt->pts;
481                 if( pkt_ts != AV_NOPTS_VALUE && pkt_ts >= tstmp ) break;
482                 if( plmt >= 0 && ipkt->pos >= plmt ) break;
483                 --npkts;
484         }
485
486         if( ret <= 0 || retry < 0 ) return -1;
487         seek_pos = curr_pos = pos;
488         return npkts > 0 ? 1 : 0;
489 }
490
491 FFAudioStream::FFAudioStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
492  : FFStream(ffmpeg, strm, fidx)
493 {
494         this->idx = idx;
495         channel0 = channels = 0;
496         sample_rate = 0;
497         mbsz = 0;
498         length = 0;
499         resample_context = 0;
500
501         aud_bfr_sz = 0;
502         aud_bfr = 0;
503
504 // history buffer
505         nch = 2;
506         sz = 0x10000;
507         long bsz = sz * nch;
508         bfr = new float[bsz];
509         lmt = bfr + bsz;
510         reset_history();
511 }
512
513 FFAudioStream::~FFAudioStream()
514 {
515         if( resample_context ) swr_free(&resample_context);
516         delete [] aud_bfr;
517         delete [] bfr;
518 }
519
520 int FFAudioStream::get_samples(float *&samples, uint8_t **data, int len)
521 {
522         samples = *(float **)data;
523         if( resample_context ) {
524                 if( len > aud_bfr_sz ) {        
525                         delete [] aud_bfr;
526                         aud_bfr = 0;
527                 }
528                 if( !aud_bfr ) {
529                         aud_bfr_sz = len;
530                         aud_bfr = new float[aud_bfr_sz*channels];
531                 }
532                 int ret = swr_convert(resample_context,
533                         (uint8_t**)&aud_bfr, aud_bfr_sz, (const uint8_t**)data, len);
534                 if( ret < 0 ) {
535                         ff_err(ret, "FFAudioStream::get_samples: swr_convert failed\n");
536                         return -1;
537                 }
538                 samples = aud_bfr;
539                 len = ret;
540         }
541         return len;
542 }
543
544 int FFAudioStream::load_history(uint8_t **data, int len)
545 {
546         float *samples;
547         len = get_samples(samples, data, len);
548         if( len > 0 ) {
549                 // biggest user bfr since seek + frame
550                 realloc(mbsz + len + 1, channels);
551                 write(samples, len);
552         }
553         return len;
554 }
555
556 int FFAudioStream::decode_frame(AVPacket *pkt, AVFrame *frame, int &got_frame)
557 {
558         int first_frame = seeked;  seeked = 0;
559         int ret = avcodec_decode_audio4(st->codec, frame, &got_frame, pkt);
560         if( ret < 0 ) {
561                 if( first_frame ) return 0;
562                 ff_err(ret, "FFAudioStream::decode_frame: Could not read audio frame\n");
563                 return -1;
564         }
565         if( got_frame ) {
566                 int64_t pkt_ts = av_frame_get_best_effort_timestamp(frame);
567                 if( pkt_ts != AV_NOPTS_VALUE )
568                         curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * sample_rate + 0.5;
569         }
570         return ret;
571 }
572
573 int FFAudioStream::encode_activate()
574 {
575         if( writing >= 0 ) return writing;
576         AVCodecContext *ctx = st->codec;
577         frame_sz = ctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE ?
578                 10000 : ctx->frame_size;
579         return FFStream::encode_activate();
580 }
581
582 int FFAudioStream::nb_samples()
583 {
584         AVCodecContext *ctx = st->codec;
585         return ctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE ?
586                 10000 : ctx->frame_size;
587 }
588
589 int64_t FFAudioStream::load_buffer(double ** const sp, int len)
590 {
591         reserve(len+1, st->codec->channels);
592         for( int ch=0; ch<nch; ++ch )
593                 write(sp[ch], len, ch);
594         return put_inp(len);
595 }
596
597 int FFAudioStream::in_history(int64_t pos)
598 {
599         if( pos > curr_pos ) return 0;
600         int64_t len = hpos;
601         if( len > sz ) len = sz;
602         if( pos < curr_pos - len ) return 0;
603         return 1;
604 }
605
606
607 int FFAudioStream::init_frame(AVFrame *frame)
608 {
609         AVCodecContext *ctx = st->codec;
610         frame->nb_samples = frame_sz;
611         frame->format = ctx->sample_fmt;
612         frame->channel_layout = ctx->channel_layout;
613         frame->sample_rate = ctx->sample_rate;
614         int ret = av_frame_get_buffer(frame, 0);
615         if (ret < 0)
616                 ff_err(ret, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
617         return ret;
618 }
619
620 int FFAudioStream::load(int64_t pos, int len)
621 {
622         if( audio_seek(pos) < 0 ) return -1;
623         if( !frame && !(frame=av_frame_alloc()) ) {
624                 fprintf(stderr, "FFAudioStream::load: av_frame_alloc failed\n");
625                 return -1;
626         }
627         if( mbsz < len ) mbsz = len;
628         int64_t end_pos = pos + len;
629         int ret = 0;
630         for( int i=0; ret>=0 && !flushed && curr_pos<end_pos && i<1000; ++i ) {
631                 ret = read_frame(frame);
632                 if( ret > 0 ) {
633                         load_history(&frame->extended_data[0], frame->nb_samples);
634                         curr_pos += frame->nb_samples;
635                 }
636         }
637         if( end_pos > curr_pos ) {
638                 zero(end_pos - curr_pos);
639                 curr_pos = end_pos;
640         }
641         len = curr_pos - pos;
642         iseek(len);
643         return len;
644 }
645
646 int FFAudioStream::audio_seek(int64_t pos)
647 {
648         if( decode_activate() < 0 ) return -1;
649         if( !st->codec || !st->codec->codec ) return -1;
650         if( in_history(pos) ) return 0;
651         if( pos == curr_pos ) return 0;
652         reset_history();  mbsz = 0;
653 // guarentee preload > 1sec samples
654         if( seek(pos-sample_rate, sample_rate) < 0 ) return -1;
655         return 1;
656 }
657
658 int FFAudioStream::encode(double **samples, int len)
659 {
660         if( encode_activate() <= 0 ) return -1;
661         ffmpeg->flow_ctl();
662         int ret = 0;
663         int64_t count = load_buffer(samples, len);
664         FFrame *frm = 0;
665
666         while( ret >= 0 && count >= frame_sz ) {
667                 frm = new FFrame(this);
668                 if( (ret=frm->initted()) < 0 ) break;
669                 AVFrame *frame = *frm;
670                 float *bfrp = get_outp(frame_sz);
671                 ret =  swr_convert(resample_context,
672                         (uint8_t **)frame->extended_data, frame_sz,
673                         (const uint8_t **)&bfrp, frame_sz);
674                 if( ret < 0 ) {
675                         ff_err(ret, "FFAudioStream::encode: swr_convert failed\n");
676                         break;
677                 }
678                 frm->queue(curr_pos);
679                 frm = 0;
680                 curr_pos += frame_sz;
681                 count -= frame_sz;
682         }
683
684         delete frm;
685         return ret >= 0 ? 0 : 1;
686 }
687
688 int FFAudioStream::encode_frame(AVPacket *pkt, AVFrame *frame, int &got_packet)
689 {
690         int ret = avcodec_encode_audio2(st->codec, pkt, frame, &got_packet);
691         if( ret < 0 ) {
692                 ff_err(ret, "FFAudioStream::encode_frame: encode audio failed\n");
693                 return -1;
694         }
695         return ret;
696 }
697
698 void FFAudioStream::load_markers()
699 {
700         IndexState *index_state = ffmpeg->file_base->asset->index_state;
701         if( !index_state || idx >= index_state->audio_markers.size() ) return;
702         FFStream::load_markers(*index_state->audio_markers[idx], sample_rate);
703 }
704
705 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
706  : FFStream(ffmpeg, strm, fidx)
707 {
708         this->idx = idx;
709         width = height = 0;
710         frame_rate = 0;
711         aspect_ratio = 0;
712         length = 0;
713         convert_ctx = 0;
714 }
715
716 FFVideoStream::~FFVideoStream()
717 {
718         if( convert_ctx ) sws_freeContext(convert_ctx);
719 }
720
721 int FFVideoStream::decode_frame(AVPacket *pkt, AVFrame *frame, int &got_frame)
722 {
723         int first_frame = seeked;  seeked = 0;
724         int ret = avcodec_decode_video2(st->codec, frame, &got_frame, pkt);
725         if( ret < 0 ) {
726                 if( first_frame ) return 0;
727                 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame\n");
728                 return -1;
729         }
730         if( got_frame ) {
731                 int64_t pkt_ts = av_frame_get_best_effort_timestamp(frame);
732                 if( pkt_ts != AV_NOPTS_VALUE )
733                         curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * frame_rate + 0.5;
734         }
735         return ret;
736 }
737
738 int FFVideoStream::load(VFrame *vframe, int64_t pos)
739 {
740         int ret = video_seek(pos);
741         if( ret < 0 ) return -1;
742         if( !frame && !(frame=av_frame_alloc()) ) {
743                 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
744                 return -1;
745         }
746         for( int i=0; ret>=0 && !flushed && curr_pos<=pos && i<1000; ++i ) {
747                 ret = read_frame(frame);
748                 if( ret > 0 ) ++curr_pos;
749         }
750         if( ret > 0 ) {
751                 AVCodecContext *ctx = st->codec;
752                 ret = convert_cmodel(vframe, (AVPicture *)frame,
753                         ctx->pix_fmt, ctx->width, ctx->height);
754         }
755         ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
756         return ret;
757 }
758
759 int FFVideoStream::video_seek(int64_t pos)
760 {
761         if( decode_activate() < 0 ) return -1;
762         if( !st->codec || !st->codec->codec ) return -1;
763         if( pos == curr_pos-1 && !seeked ) return 0;
764 // if close enough, just read up to current
765         int gop = st->codec->gop_size;
766         if( gop < 4 ) gop = 4;
767         if( gop > 64 ) gop = 64;
768         int read_limit = curr_pos + 3*gop;
769         if( pos >= curr_pos && pos <= read_limit ) return 0;
770 // guarentee preload more than 2*gop frames
771         if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
772         return 1;
773 }
774
775 int FFVideoStream::init_frame(AVFrame *picture)
776 {
777         AVCodecContext *ctx = st->codec;
778         picture->format = ctx->pix_fmt;
779         picture->width  = ctx->width;
780         picture->height = ctx->height;
781         int ret = av_frame_get_buffer(picture, 32);
782         return ret;
783 }
784
785 int FFVideoStream::encode(VFrame *vframe)
786 {
787         if( encode_activate() <= 0 ) return -1;
788         ffmpeg->flow_ctl();
789         FFrame *picture = new FFrame(this);
790         int ret = picture->initted();
791         if( ret >= 0 ) {
792                 AVFrame *frame = *picture;
793                 frame->pts = curr_pos;
794                 AVCodecContext *ctx = st->codec;
795                 ret = convert_pixfmt(vframe, (AVPicture*)frame,
796                         ctx->pix_fmt, ctx->width, ctx->height);
797         }
798         if( ret >= 0 ) {
799                 picture->queue(curr_pos);
800                 ++curr_pos;
801         }
802         else {
803                 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
804                 delete picture;
805         }
806         return ret >= 0 ? 0 : 1;
807 }
808
809 int FFVideoStream::encode_frame(AVPacket *pkt, AVFrame *frame, int &got_packet)
810 {
811         int ret = avcodec_encode_video2(st->codec, pkt, frame, &got_packet);
812         if( ret < 0 ) {
813                 ff_err(ret, "FFVideoStream::encode_frame: encode video failed\n");
814                 return -1;
815         }
816         return ret;
817 }
818
819 PixelFormat FFVideoStream::color_model_to_pix_fmt(int color_model)
820 {
821         switch( color_model ) { 
822         case BC_YUV422:         return AV_PIX_FMT_YUYV422;
823         case BC_RGB888:         return AV_PIX_FMT_RGB24;
824         case BC_RGBA8888:       return AV_PIX_FMT_RGBA;
825         case BC_BGR8888:        return AV_PIX_FMT_BGR0;
826         case BC_BGR888:         return AV_PIX_FMT_BGR24;
827         case BC_YUV420P:        return AV_PIX_FMT_YUV420P;
828         case BC_YUV422P:        return AV_PIX_FMT_YUV422P;
829         case BC_YUV444P:        return AV_PIX_FMT_YUV444P;
830         case BC_YUV411P:        return AV_PIX_FMT_YUV411P;
831         case BC_RGB565:         return AV_PIX_FMT_RGB565;
832         case BC_RGB161616:      return AV_PIX_FMT_RGB48LE;
833         case BC_RGBA16161616:   return AV_PIX_FMT_RGBA64LE;
834         default: break;
835         }
836
837         return AV_PIX_FMT_NB;
838 }
839
840 int FFVideoStream::pix_fmt_to_color_model(PixelFormat pix_fmt)
841 {
842         switch (pix_fmt) { 
843         case AV_PIX_FMT_YUYV422:        return BC_YUV422;
844         case AV_PIX_FMT_RGB24:          return BC_RGB888;
845         case AV_PIX_FMT_RGBA:           return BC_RGBA8888;
846         case AV_PIX_FMT_BGR0:           return BC_BGR8888;
847         case AV_PIX_FMT_BGR24:          return BC_BGR888;
848         case AV_PIX_FMT_YUV420P:        return BC_YUV420P;
849         case AV_PIX_FMT_YUV422P:        return BC_YUV422P;
850         case AV_PIX_FMT_YUV444P:        return BC_YUV444P;
851         case AV_PIX_FMT_YUV411P:        return BC_YUV411P;
852         case AV_PIX_FMT_RGB565:         return BC_RGB565;
853         case AV_PIX_FMT_RGB48LE:        return BC_RGB161616;
854         case AV_PIX_FMT_RGBA64LE:       return BC_RGBA16161616;
855         default: break;
856         }
857
858         return BC_TRANSPARENCY;
859 }
860
861 int FFVideoStream::convert_picture_vframe(VFrame *frame,
862                 AVPicture *ip, PixelFormat ifmt, int iw, int ih)
863 {
864         AVPicture opic;
865         int cmodel = frame->get_color_model();
866         PixelFormat ofmt = color_model_to_pix_fmt(cmodel);
867         if( ofmt == AV_PIX_FMT_NB ) return -1;
868         int size = avpicture_fill(&opic, frame->get_data(), ofmt, 
869                                   frame->get_w(), frame->get_h());
870         if( size < 0 ) return -1;
871
872         // transfer line sizes must match also
873         int planar = BC_CModels::is_planar(cmodel);
874         int packed_width = !planar ? frame->get_bytes_per_line() :
875                  BC_CModels::calculate_pixelsize(cmodel) * frame->get_w();
876         if( packed_width != opic.linesize[0] )  return -1;
877
878         if( planar ) {
879                 // override avpicture_fill() for planar types
880                 opic.data[0] = frame->get_y();
881                 opic.data[1] = frame->get_u();
882                 opic.data[2] = frame->get_v();
883         }
884
885         convert_ctx = sws_getCachedContext(convert_ctx, iw, ih, ifmt,
886                 frame->get_w(), frame->get_h(), ofmt, SWS_BICUBIC, NULL, NULL, NULL);
887         if( !convert_ctx ) {
888                 fprintf(stderr, "FFVideoStream::convert_picture_frame:"
889                                 " sws_getCachedContext() failed\n");
890                 return 1;
891         }
892         int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ih,
893             opic.data, opic.linesize);
894         if( ret < 0 ) {
895                 ff_err(ret, "FFVideoStream::convert_picture_frame: sws_scale() failed\n");
896                 return 1;
897         }
898         return 0;
899 }
900
901 int FFVideoStream::convert_cmodel(VFrame *frame,
902                  AVPicture *ip, PixelFormat ifmt, int iw, int ih)
903 {
904         // try direct transfer
905         if( !convert_picture_vframe(frame, ip, ifmt, iw, ih) ) return 1;
906         // use indirect transfer
907         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
908         int max_bits = 0;
909         for( int i = 0; i <desc->nb_components; ++i ) {
910                 int bits = desc->comp[i].depth_minus1 + 1;
911                 if( bits > max_bits ) max_bits = bits;
912         }
913 // from libavcodec/pixdesc.c
914 #define pixdesc_has_alpha(pixdesc) ((pixdesc)->nb_components == 2 || \
915  (pixdesc)->nb_components == 4 || (pixdesc)->flags & AV_PIX_FMT_FLAG_PAL)
916         int icolor_model = pixdesc_has_alpha(desc) ?
917                 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
918                 (max_bits > 8 ? BC_RGB161616 : BC_RGB888) ;
919         VFrame vframe(iw, ih, icolor_model);
920         if( convert_picture_vframe(&vframe, ip, ifmt, iw, ih) ) return -1;
921         frame->transfer_from(&vframe);
922         return 1;
923 }
924
925 int FFVideoStream::convert_vframe_picture(VFrame *frame,
926                 AVPicture *op, PixelFormat ofmt, int ow, int oh)
927 {
928         AVPicture opic;
929         int cmodel = frame->get_color_model();
930         PixelFormat ifmt = color_model_to_pix_fmt(cmodel);
931         if( ifmt == AV_PIX_FMT_NB ) return -1;
932         int size = avpicture_fill(&opic, frame->get_data(), ifmt, 
933                                   frame->get_w(), frame->get_h());
934         if( size < 0 ) return -1;
935
936         // transfer line sizes must match also
937         int planar = BC_CModels::is_planar(cmodel);
938         int packed_width = !planar ? frame->get_bytes_per_line() :
939                  BC_CModels::calculate_pixelsize(cmodel) * frame->get_w();
940         if( packed_width != opic.linesize[0] )  return -1;
941
942         if( planar ) {
943                 // override avpicture_fill() for planar types
944                 opic.data[0] = frame->get_y();
945                 opic.data[1] = frame->get_u();
946                 opic.data[2] = frame->get_v();
947         }
948
949         convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(), ifmt,
950                 ow, oh, ofmt, SWS_BICUBIC, NULL, NULL, NULL);
951         if( !convert_ctx ) {
952                 fprintf(stderr, "FFVideoStream::convert_frame_picture:"
953                                 " sws_getCachedContext() failed\n");
954                 return 1;
955         }
956         int ret = sws_scale(convert_ctx, opic.data, opic.linesize, 0, frame->get_h(),
957                         op->data, op->linesize);
958         if( ret < 0 ) {
959                 ff_err(ret, "FFVideoStream::convert_frame_picture: sws_scale() failed\n");
960                 return 1;
961         }
962         return 0;
963 }
964
965 int FFVideoStream::convert_pixfmt(VFrame *frame,
966                  AVPicture *op, PixelFormat ofmt, int ow, int oh)
967 {
968         // try direct transfer
969         if( !convert_vframe_picture(frame, op, ofmt, ow, oh) ) return 0;
970         // use indirect transfer
971         int colormodel = frame->get_color_model();
972         int bits = BC_CModels::calculate_pixelsize(colormodel) * 8;
973         bits /= BC_CModels::components(colormodel);
974         int icolor_model =  BC_CModels::has_alpha(colormodel) ?
975                 (bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
976                 (bits > 8 ? BC_RGB161616: BC_RGB888) ;
977         VFrame vframe(frame->get_w(), frame->get_h(), icolor_model);
978         vframe.transfer_from(frame);
979         if( convert_vframe_picture(&vframe, op, ofmt, ow, oh) ) return 1;
980         return 0;
981 }
982
983 void FFVideoStream::load_markers()
984 {
985         IndexState *index_state = ffmpeg->file_base->asset->index_state;
986         if( idx >= index_state->video_markers.size() ) return;
987         FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
988 }
989
990
991 FFMPEG::FFMPEG(FileBase *file_base)
992 {
993         fmt_ctx = 0;
994         this->file_base = file_base;
995         memset(file_format,0,sizeof(file_format));
996         mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
997         flow_lock = new Condition(1,"FFStream::flow_lock",0);
998         done = -1;
999         flow = 1;
1000         decoding = encoding = 0;
1001         has_audio = has_video = 0;
1002         opts = 0;
1003         opt_duration = -1;
1004         opt_video_filter = 0;
1005         opt_audio_filter = 0;
1006         char option_path[BCTEXTLEN];
1007         set_option_path(option_path, "%s", "ffmpeg.opts");
1008         read_options(option_path, opts);
1009 }
1010
1011 FFMPEG::~FFMPEG()
1012 {
1013         ff_lock("FFMPEG::~FFMPEG()");
1014         close_encoder();
1015         ffaudio.remove_all_objects();
1016         ffvideo.remove_all_objects();
1017         if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1018         ff_unlock();
1019         delete flow_lock;
1020         delete mux_lock;
1021         av_dict_free(&opts);
1022         delete [] opt_video_filter;
1023         delete [] opt_audio_filter;
1024 }
1025
1026 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1027 {
1028         const int *p = codec->supported_samplerates;
1029         if( !p ) return sample_rate;
1030         while( *p != 0 ) {
1031                 if( *p == sample_rate ) return *p;
1032                 ++p;
1033         }
1034         return 0;
1035 }
1036
1037 static inline AVRational std_frame_rate(int i)
1038 {
1039         static const int m1 = 1001*12, m2 = 1000*12;
1040         static const int freqs[] = {
1041                 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1042                 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
1043         };
1044         int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1045         return (AVRational) { freq, 1001*12 };
1046 }
1047
1048 AVRational FFMPEG::check_frame_rate(AVCodec *codec, double frame_rate)
1049 {
1050         const AVRational *p = codec->supported_framerates;
1051         AVRational rate, best_rate = (AVRational) { 0, 0 };
1052         double max_err = 1.;  int i = 0;
1053         while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1054                 double framerate = (double) rate.num / rate.den;
1055                 double err = fabs(frame_rate/framerate - 1.);
1056                 if( err >= max_err ) continue;
1057                 max_err = err;
1058                 best_rate = rate;
1059         }
1060         return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1061 }
1062
1063 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1064 {
1065 #if 1
1066         double display_aspect = asset->width / (double)asset->height;
1067         double sample_aspect = asset->aspect_ratio / display_aspect;
1068         int width = 1000000, height = width * sample_aspect + 0.5;
1069         float w, h;
1070         MWindow::create_aspect_ratio(w, h, width, height);
1071         return (AVRational){(int)h, (int)w};
1072 #else
1073 // square pixels
1074         return (AVRational){1, 1};
1075 #endif
1076 }
1077
1078 AVRational FFMPEG::to_time_base(int sample_rate)
1079 {
1080         return (AVRational){1, sample_rate};
1081 }
1082
1083 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
1084 {
1085         get_exe_path(path);
1086         strcat(path, "/ffmpeg/");
1087         path += strlen(path);
1088         va_list ap;
1089         va_start(ap, fmt);
1090         vsprintf(path, fmt, ap);
1091         va_end(ap);
1092 }
1093
1094 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
1095 {
1096         if( *spec == '/' )
1097                 strcpy(path, spec);
1098         else
1099                 set_option_path(path, "%s/%s", type, spec);
1100 }
1101
1102 int FFMPEG::get_format(char *format, const char *path, char *spec)
1103 {
1104         char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
1105         get_option_path(option_path, path, spec);
1106         FILE *fp = fopen(option_path,"r");
1107         if( !fp ) return 1;
1108         int ret = 0;
1109         if( !fgets(line, sizeof(line), fp) ) ret = 1;
1110         if( !ret ) {
1111                 line[sizeof(line)-1] = 0;
1112                 ret = scan_option_line(line, format, codec);
1113         }
1114         fclose(fp);
1115         return ret;
1116 }
1117
1118 int FFMPEG::get_file_format()
1119 {
1120         int ret = 0;
1121         char audio_format[BCSTRLEN], video_format[BCSTRLEN];
1122         file_format[0] = audio_format[0] = video_format[0] = 0;
1123         Asset *asset = file_base->asset;
1124         if( !ret && asset->audio_data )
1125                 ret = get_format(audio_format, "audio", asset->acodec);
1126         if( !ret && asset->video_data )
1127                 ret = get_format(video_format, "video", asset->vcodec);
1128         if( !ret && !audio_format[0] && !video_format[0] )
1129                 ret = 1;
1130         if( !ret && audio_format[0] && video_format[0] &&
1131             strcmp(audio_format, video_format) ) ret = -1;
1132         if( !ret )
1133                 strcpy(file_format, audio_format[0] ? audio_format : video_format);
1134         return ret;
1135 }
1136
1137 int FFMPEG::scan_option_line(char *cp, char *tag, char *val)
1138 {
1139         while( *cp == ' ' || *cp == '\t' ) ++cp;
1140         char *bp = cp;
1141         while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' ) ++cp;
1142         int len = cp - bp;
1143         if( !len || len > BCSTRLEN-1 ) return 1;
1144         while( bp < cp ) *tag++ = *bp++;
1145         *tag = 0;
1146         while( *cp == ' ' || *cp == '\t' ) ++cp;
1147         if( *cp == '=' ) ++cp;
1148         while( *cp == ' ' || *cp == '\t' ) ++cp;
1149         bp = cp;
1150         while( *cp && *cp != '\n' ) ++cp;
1151         len = cp - bp;
1152         if( len > BCTEXTLEN-1 ) return 1;
1153         while( bp < cp ) *val++ = *bp++;
1154         *val = 0;
1155         return 0;
1156 }
1157
1158 int FFMPEG::get_encoder(const char *options,
1159                 char *format, char *codec, char *bsfilter, char *bsargs)
1160 {
1161         FILE *fp = fopen(options,"r");
1162         if( !fp ) {
1163                 eprintf("FFMPEG::get_encoder: options open failed %s\n",options);
1164                 return 1;
1165         }
1166         if( get_encoder(fp, format, codec, bsfilter, bsargs) )
1167                 eprintf(_("FFMPEG::get_encoder:"
1168                           " err: format/codec not found %s\n"), options);
1169         fclose(fp);
1170         return 0;
1171 }
1172
1173 int FFMPEG::get_encoder(FILE *fp,
1174                 char *format, char *codec, char *bsfilter, char *bsargs)
1175 {
1176         format[0] = codec[0] = bsfilter[0] = bsargs[0] = 0;
1177         char line[BCTEXTLEN];
1178         if( !fgets(line, sizeof(line), fp) ) return 1;
1179         line[sizeof(line)-1] = 0;
1180         if( scan_option_line(line, format, codec) ) return 1;
1181         char *cp = codec;
1182         while( *cp && *cp != '|' ) ++cp;
1183         if( !*cp ) return 0;
1184         if( scan_option_line(cp+1, bsfilter, bsargs) ) return 1;
1185         do { *cp-- = 0; } while( cp>=codec && (*cp==' ' || *cp == '\t' ) );
1186         return 0;
1187 }
1188
1189 int FFMPEG::read_options(const char *options, AVDictionary *&opts)
1190 {
1191         FILE *fp = fopen(options,"r");
1192         if( !fp ) return 1;
1193         int ret = read_options(fp, options, opts);
1194         fclose(fp);
1195         return ret;
1196 }
1197
1198 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
1199 {
1200         FILE *fp = fmemopen((void *)options,strlen(options),"r");
1201         if( !fp ) return 0;
1202         int ret = read_options(fp, options, opts);
1203         fclose(fp);
1204         AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
1205         if( tag ) st->id = strtol(tag->value,0,0);
1206         return ret;
1207 }
1208
1209 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
1210 {
1211         int ret = 0, no = 0;
1212         char line[BCTEXTLEN];
1213         while( !ret && fgets(line, sizeof(line), fp) ) {
1214                 line[sizeof(line)-1] = 0;
1215                 ++no;
1216                 if( line[0] == '#' ) continue;
1217                 if( line[0] == '\n' ) continue;
1218                 char key[BCSTRLEN], val[BCTEXTLEN];
1219                 if( scan_option_line(line, key, val) ) {
1220                         eprintf(_("FFMPEG::read_options:"
1221                                   " err reading %s: line %d\n"), options, no);
1222                         ret = 1;
1223                 }
1224                 if( !ret ) {
1225                         if( !strcmp(key, "duration") )
1226                                 opt_duration = strtod(val, 0);
1227                         if( !strcmp(key, "video_filter") )
1228                                 opt_video_filter = cstrdup(val);
1229                         if( !strcmp(key, "audio_filter") )
1230                                 opt_audio_filter = cstrdup(val);
1231                         else if( !strcmp(key, "loglevel") )
1232                                 set_loglevel(val);
1233                         else
1234                                 av_dict_set(&opts, key, val, 0);
1235                 }
1236         }
1237         return ret;
1238 }
1239
1240 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
1241 {
1242         char option_path[BCTEXTLEN];
1243         set_option_path(option_path, "%s", options);
1244         return read_options(option_path, opts);
1245 }
1246
1247 int FFMPEG::load_options(const char *path, char *bfr, int len)
1248 {
1249         *bfr = 0;
1250         FILE *fp = fopen(path, "r");
1251         if( !fp ) return 1;
1252         fgets(bfr, len, fp); // skip hdr
1253         len = fread(bfr, 1, len-1, fp);
1254         if( len < 0 ) len = 0;
1255         bfr[len] = 0;
1256         fclose(fp);
1257         return 0;
1258 }
1259
1260 void FFMPEG::set_loglevel(const char *ap)
1261 {
1262         if( !ap || !*ap ) return;
1263         const struct {
1264                 const char *name;
1265                 int level;
1266         } log_levels[] = {
1267                 { "quiet"  , AV_LOG_QUIET   },
1268                 { "panic"  , AV_LOG_PANIC   },
1269                 { "fatal"  , AV_LOG_FATAL   },
1270                 { "error"  , AV_LOG_ERROR   },
1271                 { "warning", AV_LOG_WARNING },
1272                 { "info"   , AV_LOG_INFO    },
1273                 { "verbose", AV_LOG_VERBOSE },
1274                 { "debug"  , AV_LOG_DEBUG   },
1275         };
1276         for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
1277                 if( !strcmp(log_levels[i].name, ap) ) {
1278                         av_log_set_level(log_levels[i].level);
1279                         return;
1280                 }
1281         }
1282         av_log_set_level(atoi(ap));
1283 }
1284
1285 double FFMPEG::to_secs(int64_t time, AVRational time_base)
1286 {
1287         double base_time = time == AV_NOPTS_VALUE ? 0 :
1288                 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
1289         return base_time / AV_TIME_BASE; 
1290 }
1291
1292 int FFMPEG::info(char *text, int len)
1293 {
1294         if( len <= 0 ) return 0;
1295         decode_activate();
1296 #define report(s...) do { int n = snprintf(cp,len,s); cp += n;  len -= n; } while(0)
1297         char *cp = text;
1298         if( ffvideo.size() > 0 )
1299                 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
1300         for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
1301                 FFVideoStream *vid = ffvideo[vidx];
1302                 AVStream *st = vid->st;
1303                 AVCodecContext *avctx = st->codec;
1304                 report(_("vid%d (%d),  id 0x%06x:\n"), vid->idx, vid->fidx, avctx->codec_id);
1305                 const AVCodecDescriptor *desc = avcodec_descriptor_get(avctx->codec_id);
1306                 report("  video%d %s", vidx+1, desc ? desc->name : " (unkn)");
1307                 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
1308                 const char *pfn = av_get_pix_fmt_name(avctx->pix_fmt);
1309                 report(" pix %s\n", pfn ? pfn : "(unkn)");
1310                 double secs = to_secs(st->duration, st->time_base);
1311                 int64_t length = secs * vid->frame_rate + 0.5;
1312                 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
1313                 int64_t nudge = ofs * vid->frame_rate;
1314                 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1315                 report("    %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
1316                 int hrs = secs/3600;  secs -= hrs*3600;
1317                 int mins = secs/60;  secs -= mins*60;
1318                 report("  %d:%02d:%05.2f\n", hrs, mins, secs);
1319         }
1320         if( ffaudio.size() > 0 )
1321                 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
1322         for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
1323                 FFAudioStream *aud = ffaudio[aidx];
1324                 AVStream *st = aud->st;
1325                 AVCodecContext *avctx = st->codec;
1326                 report(_("aud%d (%d),  id 0x%06x:\n"), aud->idx, aud->fidx, avctx->codec_id);
1327                 const AVCodecDescriptor *desc = avcodec_descriptor_get(avctx->codec_id);
1328                 int nch = aud->channels, ch0 = aud->channel0+1;
1329                 report("  audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
1330                 const char *fmt = av_get_sample_fmt_name(avctx->sample_fmt);
1331                 report(" %s %d", fmt, aud->sample_rate);
1332                 int sample_bits = av_get_bits_per_sample(avctx->codec_id);
1333                 report(" %dbits\n", sample_bits);
1334                 double secs = to_secs(st->duration, st->time_base);
1335                 int64_t length = secs * aud->sample_rate + 0.5;
1336                 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
1337                 int64_t nudge = ofs * aud->sample_rate;
1338                 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1339                 report("    %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
1340                 int hrs = secs/3600;  secs -= hrs*3600;
1341                 int mins = secs/60;  secs -= mins*60;
1342                 report("  %d:%02d:%05.2f\n", hrs, mins, secs);
1343         }
1344         if( fmt_ctx->nb_programs > 0 )
1345                 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
1346         for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
1347                 report("program %d", i+1);
1348                 AVProgram *pgrm = fmt_ctx->programs[i];
1349                 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1350                         int idx = pgrm->stream_index[j];
1351                         int vidx = ffvideo.size();
1352                         while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
1353                         if( vidx >= 0 ) {
1354                                 report(", vid%d", vidx);
1355                                 continue;
1356                         }
1357                         int aidx = ffaudio.size();
1358                         while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
1359                         if( aidx >= 0 ) {
1360                                 report(", aud%d", aidx);
1361                                 continue;
1362                         }
1363                         report(", (%d)", pgrm->stream_index[j]);
1364                 }
1365                 report("\n");
1366         }
1367         report("\n");
1368         AVDictionaryEntry *tag = 0;
1369         while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
1370                 report("%s=%s\n", tag->key, tag->value);
1371
1372         if( !len ) --cp;
1373         *cp = 0;
1374         return cp - text;
1375 #undef report
1376 }
1377
1378
1379 int FFMPEG::init_decoder(const char *filename)
1380 {
1381         ff_lock("FFMPEG::init_decoder");
1382         av_register_all();
1383         char file_opts[BCTEXTLEN];
1384         char *bp = strrchr(strcpy(file_opts, filename), '/');
1385         char *sp = strrchr(!bp ? file_opts : bp, '.');
1386         FILE *fp = 0;
1387         if( sp ) {
1388                 strcpy(sp, ".opts");
1389                 fp = fopen(file_opts, "r");
1390         }
1391         if( fp ) {
1392                 read_options(fp, file_opts, opts);
1393                 fclose(fp);
1394         }
1395         else
1396                 load_options("decode.opts", opts);
1397         AVDictionary *fopts = 0;
1398         av_dict_copy(&fopts, opts, 0);
1399         int ret = avformat_open_input(&fmt_ctx, filename, NULL, &fopts);
1400         av_dict_free(&fopts);
1401         if( ret >= 0 )
1402                 ret = avformat_find_stream_info(fmt_ctx, NULL);
1403         if( !ret ) {
1404                 decoding = -1;
1405         }
1406         ff_unlock();
1407         return !ret ? 0 : 1;
1408 }
1409
1410 int FFMPEG::open_decoder()
1411 {
1412         struct stat st;
1413         if( stat(fmt_ctx->filename, &st) < 0 ) {
1414                 eprintf("FFMPEG::open_decoder: can't stat file: %s\n",
1415                         fmt_ctx->filename);
1416                 return 1;
1417         }
1418
1419         int64_t file_bits = 8 * st.st_size;
1420         if( !fmt_ctx->bit_rate && opt_duration > 0 )
1421                 fmt_ctx->bit_rate = file_bits / opt_duration;
1422
1423         int estimated = 0;
1424         if( fmt_ctx->bit_rate > 0 ) {
1425                 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1426                         AVStream *st = fmt_ctx->streams[i];
1427                         if( st->duration != AV_NOPTS_VALUE ) continue;
1428                         if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
1429                         st->duration = av_rescale(file_bits, st->time_base.den,
1430                                 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
1431                         estimated = 1;
1432                 }
1433         }
1434         if( estimated )
1435                 printf("FFMPEG::open_decoder: some stream times estimated\n");
1436
1437         ff_lock("FFMPEG::open_decoder");
1438         int bad_time = 0;
1439         for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1440                 AVStream *st = fmt_ctx->streams[i];
1441                 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
1442                 AVCodecContext *avctx = st->codec;
1443                 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avctx->codec_id);
1444                 if( !codec_desc ) continue;
1445                 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1446                         if( avctx->width < 1 ) continue;
1447                         if( avctx->height < 1 ) continue;
1448                         AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
1449                         if( framerate.num < 1 ) continue;
1450                         has_video = 1;
1451                         int vidx = ffvideo.size();
1452                         FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
1453                         vstrm_index.append(ffidx(vidx, 0));
1454                         ffvideo.append(vid);
1455                         vid->width = avctx->width;
1456                         vid->height = avctx->height;
1457                         vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
1458                         double secs = to_secs(st->duration, st->time_base);
1459                         vid->length = secs * vid->frame_rate;
1460                         vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
1461                         vid->nudge = st->start_time;
1462                         vid->reading = -1;
1463                         if( opt_video_filter )
1464                                 vid->create_filter(opt_video_filter, avctx,avctx);
1465                 }
1466                 else if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1467                         if( avctx->channels < 1 ) continue;
1468                         if( avctx->sample_rate < 1 ) continue;
1469                         has_audio = 1;
1470                         int aidx = ffaudio.size();
1471                         FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
1472                         ffaudio.append(aud);
1473                         aud->channel0 = astrm_index.size();
1474                         aud->channels = avctx->channels;
1475                         for( int ch=0; ch<aud->channels; ++ch )
1476                                 astrm_index.append(ffidx(aidx, ch));
1477                         aud->sample_rate = avctx->sample_rate;
1478                         double secs = to_secs(st->duration, st->time_base);
1479                         aud->length = secs * aud->sample_rate;
1480                         if( avctx->sample_fmt != AV_SAMPLE_FMT_FLT ) {
1481                                 uint64_t layout = av_get_default_channel_layout(avctx->channels);
1482                                 if( !layout ) layout = ((uint64_t)1<<aud->channels) - 1;
1483                                 aud->resample_context = swr_alloc_set_opts(NULL,
1484                                         layout, AV_SAMPLE_FMT_FLT, avctx->sample_rate,
1485                                         layout, avctx->sample_fmt, avctx->sample_rate,
1486                                         0, NULL);
1487                                 swr_init(aud->resample_context);
1488                         }
1489                         aud->nudge = st->start_time;
1490                         aud->reading = -1;
1491                         if( opt_audio_filter )
1492                                 aud->create_filter(opt_audio_filter, avctx,avctx);
1493                 }
1494         }
1495         if( bad_time )
1496                 printf("FFMPEG::open_decoder: some stream have bad times\n");
1497         ff_unlock();
1498         return 0;
1499 }
1500
1501
1502 int FFMPEG::init_encoder(const char *filename)
1503 {
1504         int fd = ::open(filename,O_WRONLY);
1505         if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
1506         if( fd < 0 ) {
1507                 eprintf("FFMPEG::init_encoder: bad file path: %s\n", filename);
1508                 return 1;
1509         }
1510         ::close(fd);
1511         int ret = get_file_format();
1512         if( ret > 0 ) {
1513                 eprintf("FFMPEG::init_encoder: bad file format: %s\n", filename);
1514                 return 1;
1515         }
1516         if( ret < 0 ) {
1517                 eprintf("FFMPEG::init_encoder: mismatch audio/video file format: %s\n", filename);
1518                 return 1;
1519         }
1520         ff_lock("FFMPEG::init_encoder");
1521         av_register_all();
1522         avformat_alloc_output_context2(&fmt_ctx, 0, file_format, filename);
1523         if( !fmt_ctx ) {
1524                 eprintf("FFMPEG::init_encoder: failed: %s\n", filename);
1525                 ret = 1;
1526         }
1527         if( !ret ) {
1528                 encoding = -1;
1529                 load_options("encode.opts", opts);
1530         }
1531         ff_unlock();
1532         start_muxer();
1533         return ret;
1534 }
1535
1536 int FFMPEG::open_encoder(const char *type, const char *spec)
1537 {
1538
1539         Asset *asset = file_base->asset;
1540         char *filename = asset->path;
1541         AVDictionary *sopts = 0;
1542         av_dict_copy(&sopts, opts, 0);
1543         char option_path[BCTEXTLEN];
1544         set_option_path(option_path, "%s/%s.opts", type, type);
1545         read_options(option_path, sopts);
1546         get_option_path(option_path, type, spec);
1547         char format_name[BCSTRLEN], codec_name[BCTEXTLEN];
1548         char bsfilter[BCSTRLEN], bsargs[BCTEXTLEN];
1549         if( get_encoder(option_path, format_name, codec_name, bsfilter, bsargs) ) {
1550                 eprintf("FFMPEG::open_encoder: get_encoder failed %s:%s\n",
1551                         option_path, filename);
1552                 return 1;
1553         }
1554
1555         if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
1556         else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
1557         else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
1558
1559         int ret = 0;
1560         ff_lock("FFMPEG::open_encoder");
1561         FFStream *fst = 0;
1562         AVStream *st = 0;
1563
1564         const AVCodecDescriptor *codec_desc = 0;
1565         AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
1566         if( !codec ) {
1567                 eprintf("FFMPEG::open_encoder: cant find codec %s:%s\n",
1568                         codec_name, filename);
1569                 ret = 1;
1570         }
1571         if( !ret ) {
1572                 codec_desc = avcodec_descriptor_get(codec->id);
1573                 if( !codec_desc ) {
1574                         eprintf("FFMPEG::open_encoder: unknown codec %s:%s\n",
1575                                 codec_name, filename);
1576                         ret = 1;
1577                 }
1578         }
1579         if( !ret ) {
1580                 st = avformat_new_stream(fmt_ctx, 0);
1581                 if( !st ) {
1582                         eprintf("FFMPEG::open_encoder: cant create stream %s:%s\n",
1583                                 codec_name, filename);
1584                         ret = 1;
1585                 }
1586         } 
1587         if( !ret ) {
1588                 AVCodecContext *ctx = st->codec;
1589                 switch( codec_desc->type ) {
1590                 case AVMEDIA_TYPE_AUDIO: {
1591                         if( has_audio ) {
1592                                 eprintf("FFMPEG::open_encoder: duplicate audio %s:%s\n",
1593                                         codec_name, filename);
1594                                 ret = 1;
1595                                 break;
1596                         }
1597                         has_audio = 1;
1598                         if( scan_options(asset->ff_audio_options, sopts, st) ) {
1599                                 eprintf("FFMPEG::open_encoder: bad audio options %s:%s\n",
1600                                         codec_name, filename);
1601                                 ret = 1;
1602                                 break;
1603                         }
1604                         if( asset->ff_audio_bitrate > 0 ) {
1605                                 ctx->bit_rate = asset->ff_audio_bitrate;
1606                                 char arg[BCSTRLEN];
1607                                 sprintf(arg, "%d", asset->ff_audio_bitrate);
1608                                 av_dict_set(&sopts, "b", arg, 0);
1609                         }
1610                         int aidx = ffaudio.size();
1611                         int fidx = aidx + ffvideo.size();
1612                         FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
1613                         ffaudio.append(aud);  fst = aud;
1614                         aud->sample_rate = asset->sample_rate;
1615                         ctx->channels = aud->channels = asset->channels;
1616                         for( int ch=0; ch<aud->channels; ++ch )
1617                                 astrm_index.append(ffidx(aidx, ch));
1618                         ctx->channel_layout =  av_get_default_channel_layout(ctx->channels);
1619                         ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
1620                         if( !ctx->sample_rate ) {
1621                                 eprintf("FFMPEG::open_audio_encode:"
1622                                         " check_sample_rate failed %s\n", filename);
1623                                 ret = 1;
1624                                 break;
1625                         }
1626                         ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
1627                         ctx->sample_fmt = codec->sample_fmts[0];
1628                         uint64_t layout = av_get_default_channel_layout(ctx->channels);
1629                         aud->resample_context = swr_alloc_set_opts(NULL,
1630                                 layout, ctx->sample_fmt, aud->sample_rate,
1631                                 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
1632                                 0, NULL);
1633                         swr_init(aud->resample_context);
1634                         aud->writing = -1;
1635                         break; }
1636                 case AVMEDIA_TYPE_VIDEO: {
1637                         if( has_video ) {
1638                                 eprintf("FFMPEG::open_encoder: duplicate video %s:%s\n",
1639                                         codec_name, filename);
1640                                 ret = 1;
1641                                 break;
1642                         }
1643                         has_video = 1;
1644                         if( scan_options(asset->ff_video_options, sopts, st) ) {
1645                                 eprintf("FFMPEG::open_encoder: bad video options %s:%s\n",
1646                                         codec_name, filename);
1647                                 ret = 1;
1648                                 break;
1649                         }
1650                         if( asset->ff_video_bitrate > 0 ) {
1651                                 ctx->bit_rate = asset->ff_video_bitrate;
1652                                 char arg[BCSTRLEN];
1653                                 sprintf(arg, "%d", asset->ff_video_bitrate);
1654                                 av_dict_set(&sopts, "b", arg, 0);
1655                         }
1656                         else if( asset->ff_video_quality > 0 ) {
1657                                 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
1658                                 ctx->qmin    = ctx->qmax =  asset->ff_video_quality;
1659                                 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
1660                                 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
1661                                 ctx->flags |= CODEC_FLAG_QSCALE;
1662                                 char arg[BCSTRLEN];
1663                                 av_dict_set(&sopts, "flags", "+qscale", 0);
1664                                 sprintf(arg, "%d", asset->ff_video_quality);
1665                                 av_dict_set(&sopts, "qscale", arg, 0);
1666                                 sprintf(arg, "%d", ctx->global_quality);
1667                                 av_dict_set(&sopts, "global_quality", arg, 0);
1668                         }
1669                         int vidx = ffvideo.size();
1670                         int fidx = vidx + ffaudio.size();
1671                         FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
1672                         vstrm_index.append(ffidx(vidx, 0));
1673                         ffvideo.append(vid);  fst = vid;
1674                         vid->width = asset->width;
1675                         ctx->width = (vid->width+3) & ~3;
1676                         vid->height = asset->height;
1677                         ctx->height = (vid->height+3) & ~3;
1678                         vid->frame_rate = asset->frame_rate;
1679                         ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
1680                         ctx->pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
1681                         AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
1682                         if( !frame_rate.num || !frame_rate.den ) {
1683                                 eprintf("FFMPEG::open_audio_encode:"
1684                                         " check_frame_rate failed %s\n", filename);
1685                                 ret = 1;
1686                                 break;
1687                         }
1688                         ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
1689                         st->time_base = ctx->time_base;
1690                         vid->writing = -1;
1691                         break; }
1692                 default:
1693                         eprintf("FFMPEG::open_encoder: not audio/video, %s:%s\n",
1694                                 codec_name, filename);
1695                         ret = 1;
1696                 }
1697         }
1698         if( !ret ) {
1699                 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
1700                         st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
1701
1702                 ret = avcodec_open2(st->codec, codec, &sopts);
1703                 if( ret < 0 ) {
1704                         ff_err(ret,"FFMPEG::open_encoder");
1705                         eprintf("FFMPEG::open_encoder: open failed %s:%s\n",
1706                                 codec_name, filename);
1707                         ret = 1;
1708                 }
1709                 else
1710                         ret = 0;
1711         }
1712         if( !ret ) {
1713                 if( fst && bsfilter[0] )
1714                         fst->add_bsfilter(bsfilter, !bsargs[0] ? 0 : bsargs);
1715         }
1716
1717         ff_unlock();
1718         av_dict_free(&sopts);
1719         return ret;
1720 }
1721
1722 int FFMPEG::close_encoder()
1723 {
1724         stop_muxer();
1725         if( encoding > 0 ) {
1726                 av_write_trailer(fmt_ctx);
1727                 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
1728                         avio_closep(&fmt_ctx->pb);
1729         }
1730         encoding = 0;
1731         return 0;
1732 }
1733
1734 int FFMPEG::decode_activate()
1735 {
1736         if( decoding < 0 ) {
1737                 decoding = 0;
1738                 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
1739                         ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
1740                 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
1741                         ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
1742                 // set nudges for each program stream set
1743                 int npgrms = fmt_ctx->nb_programs;
1744                 for( int i=0; i<npgrms; ++i ) {
1745                         AVProgram *pgrm = fmt_ctx->programs[i];
1746                         // first start time video stream
1747                         int64_t vstart_time = -1, astart_time = -1;
1748                         for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1749                                 int fidx = pgrm->stream_index[j];
1750                                 AVStream *st = fmt_ctx->streams[fidx];
1751                                 AVCodecContext *avctx = st->codec;
1752                                 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1753                                         if( st->start_time == AV_NOPTS_VALUE ) continue;
1754                                         if( vstart_time > st->start_time ) continue;
1755                                         vstart_time = st->start_time;
1756                                         continue;
1757                                 }
1758                                 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1759                                         if( st->start_time == AV_NOPTS_VALUE ) continue;
1760                                         if( astart_time > st->start_time ) continue;
1761                                         astart_time = st->start_time;
1762                                         continue;
1763                                 }
1764                         }
1765                         // match program streams to max start_time
1766                         int64_t nudge = vstart_time > astart_time ? vstart_time : astart_time;
1767                         for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1768                                 int fidx = pgrm->stream_index[j];
1769                                 AVStream *st = fmt_ctx->streams[fidx];
1770                                 AVCodecContext *avctx = st->codec;
1771                                 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1772                                         for( int k=0; k<ffvideo.size(); ++k ) {
1773                                                 if( ffvideo[k]->fidx != fidx ) continue;
1774                                                 ffvideo[k]->nudge = nudge;
1775                                         }
1776                                         continue;
1777                                 }
1778                                 if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1779                                         for( int k=0; k<ffaudio.size(); ++k ) {
1780                                                 if( ffaudio[k]->fidx != fidx ) continue;
1781                                                 ffaudio[k]->nudge = nudge;
1782                                         }
1783                                         continue;
1784                                 }
1785                         }
1786                 }
1787                 // set nudges for any streams not yet set
1788                 int64_t vstart_time = 0, astart_time = 0;
1789                 int nstreams = fmt_ctx->nb_streams;
1790                 for( int i=0; i<nstreams; ++i ) {
1791                         AVStream *st = fmt_ctx->streams[i];
1792                         AVCodecContext *avctx = st->codec;
1793                         switch( avctx->codec_type ) {
1794                         case AVMEDIA_TYPE_VIDEO: {
1795                                 if( st->start_time == AV_NOPTS_VALUE ) continue;
1796                                 int vidx = ffvideo.size();
1797                                 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
1798                                 if( vidx >= 0 && ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
1799                                 if( vstart_time >= st->start_time ) continue;
1800                                 vstart_time = st->start_time;
1801                                 break; }
1802                         case AVMEDIA_TYPE_AUDIO: {
1803                                 if( st->start_time == AV_NOPTS_VALUE ) continue;
1804                                 int aidx = ffaudio.size();
1805                                 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
1806                                 if( aidx >= 0 && ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
1807                                 if( astart_time >= st->start_time ) continue;
1808                                 astart_time = st->start_time;
1809                                 break; }
1810                         default: break;
1811                         }
1812                 }
1813                 int64_t nudge = vstart_time > astart_time ? vstart_time : astart_time;
1814                 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
1815                         if( ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
1816                         ffvideo[vidx]->nudge = nudge;
1817                 }
1818                 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
1819                         if( ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
1820                         ffaudio[aidx]->nudge = nudge;
1821                 }
1822                 decoding = 1;
1823         }
1824         return decoding;
1825 }
1826
1827 int FFMPEG::encode_activate()
1828 {
1829         int ret = 0;
1830         if( encoding < 0 ) {
1831                 encoding = 0;
1832                 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
1833                     (ret=avio_open(&fmt_ctx->pb, fmt_ctx->filename, AVIO_FLAG_WRITE)) < 0 ) {
1834                         ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
1835                                 fmt_ctx->filename);
1836                         return 1;
1837                 }
1838
1839                 AVDictionary *fopts = 0;
1840                 char option_path[BCTEXTLEN];
1841                 set_option_path(option_path, "format/%s", file_format);
1842                 read_options(option_path, fopts);
1843                 ret = avformat_write_header(fmt_ctx, &fopts);
1844                 av_dict_free(&fopts);
1845                 if( ret < 0 ) {
1846                         ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
1847                                 fmt_ctx->filename);
1848                         return 1;
1849                 }
1850                 encoding = 1;
1851         }
1852         return encoding;
1853 }
1854
1855
1856 int FFMPEG::audio_seek(int stream, int64_t pos)
1857 {
1858         int aidx = astrm_index[stream].st_idx;
1859         FFAudioStream *aud = ffaudio[aidx];
1860         pos = pos * aud->sample_rate / file_base->asset->sample_rate + 0.5;
1861         aud->audio_seek(pos);
1862         return 0;
1863 }
1864
1865 int FFMPEG::video_seek(int stream, int64_t pos)
1866 {
1867         int vidx = vstrm_index[stream].st_idx;
1868         FFVideoStream *vid = ffvideo[vidx];
1869         pos = pos * vid->frame_rate / file_base->asset->frame_rate + 0.5;
1870         vid->video_seek(pos);
1871         return 0;
1872 }
1873
1874
1875 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
1876 {
1877         if( !has_audio || chn >= astrm_index.size() ) return -1;
1878         int aidx = astrm_index[chn].st_idx;
1879         FFAudioStream *aud = ffaudio[aidx];
1880         pos = pos * aud->sample_rate / file_base->asset->sample_rate + 0.5;
1881         if( aud->load(pos, len) < len ) return -1;
1882         int ch = astrm_index[chn].st_ch;
1883         int ret = aud->read(samples,len,ch);
1884         return ret;
1885 }
1886
1887 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
1888 {
1889         if( !has_video || layer >= vstrm_index.size() ) return -1;
1890         int vidx = vstrm_index[layer].st_idx;
1891         FFVideoStream *vid = ffvideo[vidx];
1892         pos = pos * vid->frame_rate / file_base->asset->frame_rate + 0.5;
1893         return vid->load(vframe, pos);
1894 }
1895
1896
1897 int FFMPEG::encode(int stream, double **samples, int len)
1898 {
1899         FFAudioStream *aud = ffaudio[stream];
1900         return aud->encode(samples, len);
1901 }
1902
1903
1904 int FFMPEG::encode(int stream, VFrame *frame)
1905 {
1906         FFVideoStream *vid = ffvideo[stream];
1907         return vid->encode(frame);
1908 }
1909
1910 void FFMPEG::start_muxer()
1911 {
1912         if( !running() ) {
1913                 done = 0;
1914                 start();
1915         }
1916 }
1917
1918 void FFMPEG::stop_muxer()
1919 {
1920         if( running() ) {
1921                 done = 1;
1922                 mux_lock->unlock();
1923                 join();
1924         }
1925 }
1926
1927 void FFMPEG::flow_off()
1928 {
1929         if( !flow ) return;
1930         flow_lock->lock("FFMPEG::flow_off");
1931         flow = 0;
1932 }
1933
1934 void FFMPEG::flow_on()
1935 {
1936         if( flow ) return;
1937         flow = 1;
1938         flow_lock->unlock();
1939 }
1940
1941 void FFMPEG::flow_ctl()
1942 {
1943         while( !flow ) {
1944                 flow_lock->lock("FFMPEG::flow_ctl");
1945                 flow_lock->unlock();
1946         }
1947 }
1948
1949 int FFMPEG::mux_audio(FFrame *frm)
1950 {
1951         FFPacket pkt;
1952         FFStream *fst = frm->fst;
1953         AVCodecContext *ctx = fst->st->codec;
1954         AVFrame *frame = *frm;
1955         AVRational tick_rate = {1, ctx->sample_rate};
1956         frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
1957         int got_packet = 0;
1958         int ret = fst->encode_frame(pkt, frame, got_packet);
1959         if( ret >= 0 && got_packet )
1960                 ret = fst->write_packet(pkt);
1961         if( ret < 0 )
1962                 ff_err(ret, "FFMPEG::mux_audio");
1963         return ret >= 0 ? 0 : 1;
1964 }
1965
1966 int FFMPEG::mux_video(FFrame *frm)
1967 {
1968         FFPacket pkt;
1969         FFStream *fst = frm->fst;
1970         AVFrame *frame = *frm;
1971         frame->pts = frm->position;
1972         int ret = 1, got_packet = 0;
1973         if( fmt_ctx->oformat->flags & AVFMT_RAWPICTURE ) {
1974                 /* a hack to avoid data copy with some raw video muxers */
1975                 pkt->flags |= AV_PKT_FLAG_KEY;
1976                 pkt->stream_index  = fst->st->index;
1977                 AVPicture *picture = (AVPicture *)frame;
1978                 pkt->data = (uint8_t *)picture;
1979                 pkt->size = sizeof(AVPicture);
1980                 pkt->pts = pkt->dts = frame->pts;
1981                 got_packet = 1;
1982         }
1983         else
1984                 ret = fst->encode_frame(pkt, frame, got_packet);
1985         if( ret >= 0 && got_packet )
1986                 ret = fst->write_packet(pkt);
1987         if( ret < 0 )
1988                 ff_err(ret, "FFMPEG::mux_video");
1989         return ret >= 0 ? 0 : 1;
1990 }
1991
1992 void FFMPEG::mux()
1993 {
1994         for(;;) {
1995                 double atm = -1, vtm = -1;
1996                 FFrame *afrm = 0, *vfrm = 0;
1997                 int demand = 0;
1998                 for( int i=0; i<ffaudio.size(); ++i ) {  // earliest audio
1999                         FFStream *fst = ffaudio[i];
2000                         if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
2001                         FFrame *frm = fst->frms.first;
2002                         if( !frm ) { if( !done ) return; continue; }
2003                         double tm = to_secs(frm->position, fst->st->codec->time_base);
2004                         if( atm < 0 || tm < atm ) { atm = tm;  afrm = frm; }
2005                 }
2006                 for( int i=0; i<ffvideo.size(); ++i ) {  // earliest video
2007                         FFStream *fst = ffvideo[i];
2008                         if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
2009                         FFrame *frm = fst->frms.first;
2010                         if( !frm ) { if( !done ) return; continue; }
2011                         double tm = to_secs(frm->position, fst->st->codec->time_base);
2012                         if( vtm < 0 || tm < vtm ) { vtm = tm;  vfrm = frm; }
2013                 }
2014                 if( !demand ) flow_off();
2015                 if( !afrm && !vfrm ) break;
2016                 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
2017                         vfrm->position, vfrm->fst->st->codec->time_base,
2018                         afrm->position, afrm->fst->st->codec->time_base);
2019                 FFrame *frm = v <= 0 ? vfrm : afrm;
2020                 if( frm == afrm ) mux_audio(frm);
2021                 if( frm == vfrm ) mux_video(frm);
2022                 frm->dequeue();
2023                 delete frm;
2024         }
2025 }
2026
2027 void FFMPEG::run()
2028 {
2029         while( !done ) {
2030                 mux_lock->lock("FFMPEG::run");
2031                 if( !done ) mux();
2032         }
2033         mux();
2034         for( int i=0; i<ffaudio.size(); ++i )
2035                 ffaudio[i]->flush();
2036         for( int i=0; i<ffvideo.size(); ++i )
2037                 ffvideo[i]->flush();
2038 }
2039
2040
2041 int FFMPEG::ff_total_audio_channels()
2042 {
2043         return astrm_index.size();
2044 }
2045
2046 int FFMPEG::ff_total_astreams()
2047 {
2048         return ffaudio.size();
2049 }
2050
2051 int FFMPEG::ff_audio_channels(int stream)
2052 {
2053         return ffaudio[stream]->channels;
2054 }
2055
2056 int FFMPEG::ff_sample_rate(int stream)
2057 {
2058         return ffaudio[stream]->sample_rate;
2059 }
2060
2061 const char* FFMPEG::ff_audio_format(int stream)
2062 {
2063         AVStream *st = ffaudio[stream]->st;
2064         AVCodecID id = st->codec->codec_id;
2065         const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2066         return desc ? desc->name : "Unknown";
2067 }
2068
2069 int FFMPEG::ff_audio_pid(int stream)
2070 {
2071         return ffaudio[stream]->st->id;
2072 }
2073
2074 int64_t FFMPEG::ff_audio_samples(int stream)
2075 {
2076         return ffaudio[stream]->length;
2077 }
2078
2079 // find audio astream/channels with this program,
2080 //   or all program audio channels (astream=-1)
2081 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
2082 {
2083         channel_mask = 0;
2084         int pidx = -1;
2085         int vidx = ffvideo[vstream]->fidx;
2086         // find first program with this video stream
2087         for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
2088                 AVProgram *pgrm = fmt_ctx->programs[i];
2089                 for( int j=0;  pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
2090                         int st_idx = pgrm->stream_index[j];
2091                         AVStream *st = fmt_ctx->streams[st_idx];
2092                         if( st->codec->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
2093                         if( st_idx == vidx ) pidx = i;
2094                 }
2095         }
2096         if( pidx < 0 ) return -1;
2097         int ret = -1;
2098         int64_t channels = 0;
2099         AVProgram *pgrm = fmt_ctx->programs[pidx];
2100         for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2101                 int aidx = pgrm->stream_index[j];
2102                 AVStream *st = fmt_ctx->streams[aidx];
2103                 if( st->codec->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
2104                 if( astream > 0 ) { --astream;  continue; }
2105                 int astrm = -1;
2106                 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
2107                         if( ffaudio[i]->fidx == aidx ) astrm = i;
2108                 if( astrm >= 0 ) {
2109                         if( ret < 0 ) ret = astrm;
2110                         int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
2111                         channels |= mask << ffaudio[astrm]->channel0;
2112                 }
2113                 if( !astream ) break;
2114         }
2115         channel_mask = channels;
2116         return ret;
2117 }
2118
2119
2120 int FFMPEG::ff_total_video_layers()
2121 {
2122         return vstrm_index.size();
2123 }
2124
2125 int FFMPEG::ff_total_vstreams()
2126 {
2127         return ffvideo.size();
2128 }
2129
2130 int FFMPEG::ff_video_width(int stream)
2131 {
2132         return ffvideo[stream]->width;
2133 }
2134
2135 int FFMPEG::ff_video_height(int stream)
2136 {
2137         return ffvideo[stream]->height;
2138 }
2139
2140 int FFMPEG::ff_set_video_width(int stream, int width)
2141 {
2142         int w = ffvideo[stream]->width;
2143         ffvideo[stream]->width = width;
2144         return w;
2145 }
2146
2147 int FFMPEG::ff_set_video_height(int stream, int height)
2148 {
2149         int h = ffvideo[stream]->height;
2150         ffvideo[stream]->height = height;
2151         return h;
2152 }
2153
2154 int FFMPEG::ff_coded_width(int stream)
2155 {
2156         AVStream *st = ffvideo[stream]->st;
2157         return st->codec->coded_width;
2158 }
2159
2160 int FFMPEG::ff_coded_height(int stream)
2161 {
2162         AVStream *st = ffvideo[stream]->st;
2163         return st->codec->coded_height;
2164 }
2165
2166 float FFMPEG::ff_aspect_ratio(int stream)
2167 {
2168         return ffvideo[stream]->aspect_ratio;
2169 }
2170
2171 const char* FFMPEG::ff_video_format(int stream)
2172 {
2173         AVStream *st = ffvideo[stream]->st;
2174         AVCodecID id = st->codec->codec_id;
2175         const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2176         return desc ? desc->name : "Unknown";
2177 }
2178
2179 double FFMPEG::ff_frame_rate(int stream)
2180 {
2181         return ffvideo[stream]->frame_rate;
2182 }
2183
2184 int64_t FFMPEG::ff_video_frames(int stream)
2185 {
2186         return ffvideo[stream]->length;
2187 }
2188
2189 int FFMPEG::ff_video_pid(int stream)
2190 {
2191         return ffvideo[stream]->st->id;
2192 }
2193
2194
2195 int FFMPEG::ff_cpus()
2196 {
2197         return file_base->file->cpus;
2198 }
2199
2200 int FFVideoStream::create_filter(const char *filter_spec,
2201                 AVCodecContext *src_ctx, AVCodecContext *sink_ctx)
2202 {
2203         avfilter_register_all();
2204         AVFilter *filter = avfilter_get_by_name(filter_spec);
2205         if( !filter || filter->inputs->type != AVMEDIA_TYPE_VIDEO ) {
2206                 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
2207                 return -1;
2208         }
2209         filter_graph = avfilter_graph_alloc();
2210         AVFilter *buffersrc = avfilter_get_by_name("buffer");
2211         AVFilter *buffersink = avfilter_get_by_name("buffersink");
2212
2213         int ret = 0;  char args[BCTEXTLEN];
2214         snprintf(args, sizeof(args),
2215                 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
2216                 src_ctx->width, src_ctx->height, src_ctx->pix_fmt,
2217                 st->time_base.num, st->time_base.den,
2218                 src_ctx->sample_aspect_ratio.num, src_ctx->sample_aspect_ratio.den);
2219         if( ret >= 0 )
2220                 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2221                         args, NULL, filter_graph);
2222         if( ret >= 0 )
2223                 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2224                         NULL, NULL, filter_graph);
2225         if( ret >= 0 )
2226                 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
2227                         (uint8_t*)&sink_ctx->pix_fmt, sizeof(sink_ctx->pix_fmt),
2228                         AV_OPT_SEARCH_CHILDREN);
2229         if( ret < 0 )
2230                 ff_err(ret, "FFVideoStream::create_filter");
2231         else
2232                 ret = FFStream::create_filter(filter_spec);
2233         return ret >= 0 ? 0 : 1;
2234 }
2235
2236 int FFAudioStream::create_filter(const char *filter_spec,
2237                 AVCodecContext *src_ctx, AVCodecContext *sink_ctx)
2238 {
2239         avfilter_register_all();
2240         AVFilter *filter = avfilter_get_by_name(filter_spec);
2241         if( !filter || filter->inputs->type != AVMEDIA_TYPE_AUDIO ) {
2242                 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
2243                 return -1;
2244         }
2245         filter_graph = avfilter_graph_alloc();
2246         AVFilter *buffersrc = avfilter_get_by_name("abuffer");
2247         AVFilter *buffersink = avfilter_get_by_name("abuffersink");
2248         int ret = 0;  char args[BCTEXTLEN];
2249         snprintf(args, sizeof(args),
2250                 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
2251                 st->time_base.num, st->time_base.den, src_ctx->sample_rate,
2252                 av_get_sample_fmt_name(src_ctx->sample_fmt), src_ctx->channel_layout);
2253         if( ret >= 0 )
2254                 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2255                         args, NULL, filter_graph);
2256         if( ret >= 0 )
2257                 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2258                         NULL, NULL, filter_graph);
2259         if( ret >= 0 )
2260                 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
2261                         (uint8_t*)&sink_ctx->sample_fmt, sizeof(sink_ctx->sample_fmt),
2262                         AV_OPT_SEARCH_CHILDREN);
2263         if( ret >= 0 )
2264                 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
2265                         (uint8_t*)&sink_ctx->channel_layout,
2266                         sizeof(sink_ctx->channel_layout), AV_OPT_SEARCH_CHILDREN);
2267         if( ret >= 0 )
2268                 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
2269                         (uint8_t*)&sink_ctx->sample_rate, sizeof(sink_ctx->sample_rate),
2270                         AV_OPT_SEARCH_CHILDREN);
2271         if( ret < 0 )
2272                 ff_err(ret, "FFAudioStream::create_filter");
2273         else
2274                 ret = FFStream::create_filter(filter_spec);
2275         return ret >= 0 ? 0 : 1;
2276 }
2277
2278 int FFStream::create_filter(const char *filter_spec)
2279 {
2280         /* Endpoints for the filter graph. */
2281         AVFilterInOut *outputs = avfilter_inout_alloc();
2282         outputs->name = av_strdup("in");
2283         outputs->filter_ctx = buffersrc_ctx;
2284         outputs->pad_idx = 0;
2285         outputs->next = 0;
2286
2287         AVFilterInOut *inputs  = avfilter_inout_alloc();
2288         inputs->name = av_strdup("out");
2289         inputs->filter_ctx = buffersink_ctx;
2290         inputs->pad_idx = 0;
2291         inputs->next = 0;
2292
2293         int ret = !outputs->name || !inputs->name ? -1 : 0;
2294         if( ret >= 0 )
2295                 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
2296                         &inputs, &outputs, NULL);
2297         if( ret >= 0 )
2298                 ret = avfilter_graph_config(filter_graph, NULL);
2299
2300         if( ret < 0 )
2301                 ff_err(ret, "FFStream::create_filter");
2302         avfilter_inout_free(&inputs);
2303         avfilter_inout_free(&outputs);
2304         return ret;
2305 }
2306
2307 void FFStream::add_bsfilter(const char *bsf, const char *ap)
2308 {
2309         bsfilter.append(new BSFilter(bsf,ap));
2310 }
2311
2312 int FFStream::bs_filter(AVPacket *pkt)
2313 {
2314         if( !bsfilter.size() ) return 0;
2315         av_packet_split_side_data(pkt);
2316
2317         int ret = 0;
2318         for( int i=0; i<bsfilter.size(); ++i ) {
2319                 AVPacket bspkt = *pkt;
2320                 ret = av_bitstream_filter_filter(bsfilter[i]->bsfc,
2321                          st->codec, bsfilter[i]->args, &bspkt.data, &bspkt.size,
2322                          pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY);
2323                 if( ret < 0 ) break;
2324                 int size = bspkt.size;
2325                 uint8_t *data = bspkt.data;
2326                 if( !ret && bspkt.data != pkt->data ) {
2327                         size = bspkt.size;
2328                         data = (uint8_t *)av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
2329                         if( !data ) { ret = AVERROR(ENOMEM);  break; }
2330                         memcpy(data, bspkt.data, size);
2331                         memset(data+size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2332                         ret = 1;
2333                 }
2334                 if( ret > 0 ) {
2335                         pkt->side_data = 0;  pkt->side_data_elems = 0;
2336                         av_free_packet(pkt);
2337                         ret = av_packet_from_data(&bspkt, data, size);
2338                         if( ret < 0 ) break;
2339                 }
2340                 *pkt = bspkt;
2341         }
2342         if( ret < 0 )
2343                 ff_err(ret,"FFStream::bs_filter");
2344         return ret;
2345 }
2346
2347 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
2348 {
2349         AVPacket pkt;
2350         av_init_packet(&pkt);
2351         AVFrame *frame = av_frame_alloc();
2352         if( !frame ) {
2353                 fprintf(stderr, "FFMPEG::scan: av_frame_alloc failed\n");
2354                 return -1;
2355         }
2356
2357         index_state->add_video_markers(ffvideo.size());
2358         index_state->add_audio_markers(ffaudio.size());
2359
2360         for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2361                 AVDictionary *copts = 0;
2362                 av_dict_copy(&copts, opts, 0);
2363                 AVStream *st = fmt_ctx->streams[i];
2364                 AVCodecID codec_id = st->codec->codec_id;
2365                 AVCodec *decoder = avcodec_find_decoder(codec_id);
2366                 if( avcodec_open2(st->codec, decoder, &copts) < 0 )
2367                         fprintf(stderr, "FFMPEG::scan: codec open failed\n");
2368                 av_dict_free(&copts);
2369         }
2370         int errs = 0;
2371         for( int64_t count=0; !*canceled; ++count ) {
2372                 av_packet_unref(&pkt);
2373                 pkt.data = 0; pkt.size = 0;
2374
2375                 int ret = av_read_frame(fmt_ctx, &pkt);
2376                 if( ret < 0 ) {
2377                         if( ret == AVERROR_EOF ) break;
2378                         if( ++errs > 100 ) {
2379                                 ff_err(ret, "over 100 read_frame errs\n");
2380                                 break;
2381                         }
2382                         continue;
2383                 }
2384                 if( !pkt.data ) continue;
2385                 int i = pkt.stream_index;
2386                 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
2387                 AVStream *st = fmt_ctx->streams[i];
2388                 AVCodecContext *avctx = st->codec;
2389                 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
2390
2391                 switch( avctx->codec_type ) {
2392                 case AVMEDIA_TYPE_VIDEO: {
2393                         int vidx = ffvideo.size();
2394                         while( --vidx>=0 && ffvideo[vidx]->fidx != i );
2395                         if( vidx < 0 ) break;
2396                         FFVideoStream *vid = ffvideo[vidx];
2397                         int64_t tstmp = pkt.dts;
2398                         if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.pts;
2399                         if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
2400                                 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
2401                                 double secs = to_secs(tstmp, st->time_base);
2402                                 int64_t frm = secs * vid->frame_rate + 0.5;
2403                                 if( frm < 0 ) frm = 0;
2404                                 index_state->put_video_mark(vidx, frm, pkt.pos);
2405                         }
2406 #if 0
2407                         while( pkt.size > 0 ) {
2408                                 av_frame_unref(frame);
2409                                 int got_frame = 0;
2410                                 int ret = vid->decode_frame(&pkt, frame, got_frame);
2411                                 if( ret <= 0 ) break;
2412 //                              if( got_frame ) {}
2413                                 pkt.data += ret;
2414                                 pkt.size -= ret;
2415                         }
2416 #endif
2417                         break; }
2418                 case AVMEDIA_TYPE_AUDIO: {
2419                         int aidx = ffaudio.size();
2420                         while( --aidx>=0 && ffaudio[aidx]->fidx != i );
2421                         if( aidx < 0 ) break;
2422                         FFAudioStream *aud = ffaudio[aidx];
2423                         int64_t tstmp = pkt.pts;
2424                         if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
2425                         if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
2426                                 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
2427                                 double secs = to_secs(tstmp, st->time_base);
2428                                 int64_t sample = secs * aud->sample_rate + 0.5;
2429                                 if( sample < 0 ) sample = 0;
2430                                 index_state->put_audio_mark(aidx, sample, pkt.pos);
2431                         }
2432                         while( pkt.size > 0 ) {
2433                                 int ch = aud->channel0,  nch = aud->channels;
2434                                 int64_t pos = index_state->pos(ch);
2435                                 if( pos != aud->curr_pos ) {
2436 if( abs(pos-aud->curr_pos) > 1 )
2437 printf("audio%d pad %ld %ld (%ld)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
2438                                         index_state->pad_data(ch, nch, aud->curr_pos);
2439                                 }
2440                                 av_frame_unref(frame);
2441                                 int got_frame = 0;
2442                                 int ret = aud->decode_frame(&pkt, frame, got_frame);
2443                                 if( ret <= 0 ) break;
2444                                 if( got_frame ) {
2445                                         float *samples;
2446                                         int len = aud->get_samples(samples,
2447                                                  &frame->extended_data[0], frame->nb_samples);
2448                                         for( int i=0; i<nch; ++i )
2449                                                 index_state->put_data(ch+i,nch,samples+i,len);
2450                                         aud->curr_pos += len;
2451                                 }
2452                                 pkt.data += ret;
2453                                 pkt.size -= ret;
2454                         }
2455                         break; }
2456                 default: break;
2457                 }
2458         }
2459         av_frame_free(&frame);
2460         return 0;
2461 }
2462
2463 void FFStream::load_markers(IndexMarks &marks, double rate)
2464 {
2465         index_markers = &marks;
2466         int in = 0;
2467         int64_t sz = marks.size();
2468         int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
2469         int nb_ent = st->nb_index_entries;
2470 // some formats already have an index
2471         if( nb_ent > 0 ) {
2472                 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
2473                 int64_t tstmp = ep->timestamp;
2474                 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
2475                 double secs = ffmpeg->to_secs(tstmp, st->time_base);
2476                 int64_t no = secs * rate;
2477                 while( in < sz && marks[in].no <= no ) ++in;
2478         }
2479         int64_t len = sz - in;
2480         int64_t count = max_entries - nb_ent;
2481         if( count > len ) count = len;
2482         for( int i=0; i<count; ++i ) {
2483                 int k = in + i * len / count;
2484                 int64_t no = marks[k].no, pos = marks[k].pos;
2485                 double secs = (double)no / rate;
2486                 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
2487                 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
2488                 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);
2489         }
2490 }
2491