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