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