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