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