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