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