add ffmpeg dvd render option, fix undo deadlock, fix a few plugin interface gaffs
[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         avcodec_flush_buffers(st->codec);
552         double secs = (double)pos / sample_rate;
553         int64_t tstmp = secs * st->time_base.den / st->time_base.num;
554         if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
555         avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, tstmp, INT64_MAX, 0);
556         seek_pos = curr_pos = pos;
557         reset();  st_eof(0);
558         mbsz = 0; flushed = 0;  need_packet = 1;
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         avcodec_flush_buffers(st->codec);
650 // back up a few frames to read up to current to help repair damages
651         if( (pos-=gop) < 0 ) pos = 0;
652         double secs = (double)pos / frame_rate;
653         int64_t tstmp = secs * st->time_base.den / st->time_base.num;
654         if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
655         avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, tstmp, INT64_MAX, 0);
656         seek_pos = curr_pos = pos;
657         st_eof(0);
658         flushed = 0;  need_packet = 1;
659         return 1;
660 }
661
662 int FFVideoStream::init_frame(AVFrame *picture)
663 {
664         AVCodecContext *ctx = st->codec;
665         picture->format = ctx->pix_fmt;
666         picture->width  = ctx->width;
667         picture->height = ctx->height;
668         int ret = av_frame_get_buffer(picture, 32);
669         return ret;
670 }
671
672 int FFVideoStream::encode(VFrame *vframe)
673 {
674         if( encode_activate() <= 0 ) return -1;
675         ffmpeg->flow_ctl();
676         FFrame *picture = new FFrame(this);
677         int ret = picture->initted();
678         if( ret >= 0 ) {
679                 AVFrame *frame = *picture;
680                 frame->pts = curr_pos;
681                 AVCodecContext *ctx = st->codec;
682                 ret = convert_pixfmt(vframe, (AVPicture*)frame,
683                         ctx->pix_fmt, ctx->width, ctx->height);
684         }
685         if( ret >= 0 ) {
686                 picture->queue(curr_pos);
687                 ++curr_pos;
688         }
689         else {
690                 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
691                 delete picture;
692         }
693         return ret >= 0 ? 0 : 1;
694 }
695
696
697 PixelFormat FFVideoStream::color_model_to_pix_fmt(int color_model)
698 {
699         switch( color_model ) { 
700         case BC_YUV422:         return AV_PIX_FMT_YUYV422;
701         case BC_RGB888:         return AV_PIX_FMT_RGB24;
702         case BC_RGBA8888:       return AV_PIX_FMT_RGBA;
703         case BC_BGR8888:        return AV_PIX_FMT_BGR0;
704         case BC_BGR888:         return AV_PIX_FMT_BGR24;
705         case BC_YUV420P:        return AV_PIX_FMT_YUV420P;
706         case BC_YUV422P:        return AV_PIX_FMT_YUV422P;
707         case BC_YUV444P:        return AV_PIX_FMT_YUV444P;
708         case BC_YUV411P:        return AV_PIX_FMT_YUV411P;
709         case BC_RGB565:         return AV_PIX_FMT_RGB565;
710         case BC_RGB161616:      return AV_PIX_FMT_RGB48LE;
711         case BC_RGBA16161616:   return AV_PIX_FMT_RGBA64LE;
712         default: break;
713         }
714
715         return AV_PIX_FMT_NB;
716 }
717
718 int FFVideoStream::pix_fmt_to_color_model(PixelFormat pix_fmt)
719 {
720         switch (pix_fmt) { 
721         case AV_PIX_FMT_YUYV422:        return BC_YUV422;
722         case AV_PIX_FMT_RGB24:          return BC_RGB888;
723         case AV_PIX_FMT_RGBA:           return BC_RGBA8888;
724         case AV_PIX_FMT_BGR0:           return BC_BGR8888;
725         case AV_PIX_FMT_BGR24:          return BC_BGR888;
726         case AV_PIX_FMT_YUV420P:        return BC_YUV420P;
727         case AV_PIX_FMT_YUV422P:        return BC_YUV422P;
728         case AV_PIX_FMT_YUV444P:        return BC_YUV444P;
729         case AV_PIX_FMT_YUV411P:        return BC_YUV411P;
730         case AV_PIX_FMT_RGB565:         return BC_RGB565;
731         case AV_PIX_FMT_RGB48LE:        return BC_RGB161616;
732         case AV_PIX_FMT_RGBA64LE:       return BC_RGBA16161616;
733         default: break;
734         }
735
736         return BC_TRANSPARENCY;
737 }
738
739 int FFVideoStream::convert_picture_vframe(VFrame *frame,
740                 AVPicture *ip, PixelFormat ifmt, int iw, int ih)
741 {
742         AVPicture opic;
743         int cmodel = frame->get_color_model();
744         PixelFormat ofmt = color_model_to_pix_fmt(cmodel);
745         if( ofmt == AV_PIX_FMT_NB ) return -1;
746         int size = avpicture_fill(&opic, frame->get_data(), ofmt, 
747                                   frame->get_w(), frame->get_h());
748         if( size < 0 ) return -1;
749
750         // transfer line sizes must match also
751         int planar = BC_CModels::is_planar(cmodel);
752         int packed_width = !planar ? frame->get_bytes_per_line() :
753                  BC_CModels::calculate_pixelsize(cmodel) * frame->get_w();
754         if( packed_width != opic.linesize[0] )  return -1;
755
756         if( planar ) {
757                 // override avpicture_fill() for planar types
758                 opic.data[0] = frame->get_y();
759                 opic.data[1] = frame->get_u();
760                 opic.data[2] = frame->get_v();
761         }
762
763         convert_ctx = sws_getCachedContext(convert_ctx, iw, ih, ifmt,
764                 frame->get_w(), frame->get_h(), ofmt, SWS_BICUBIC, NULL, NULL, NULL);
765         if( !convert_ctx ) {
766                 fprintf(stderr, "FFVideoStream::convert_picture_frame:"
767                                 " sws_getCachedContext() failed\n");
768                 return 1;
769         }
770         if( sws_scale(convert_ctx, ip->data, ip->linesize, 0, ih,
771             opic.data, opic.linesize) < 0 ) {
772                 fprintf(stderr, "FFVideoStream::convert_picture_frame: sws_scale() failed\n");
773                 return 1;
774         }
775         return 0;
776 }
777
778 int FFVideoStream::convert_cmodel(VFrame *frame,
779                  AVPicture *ip, PixelFormat ifmt, int iw, int ih)
780 {
781         // try direct transfer
782         if( !convert_picture_vframe(frame, ip, ifmt, iw, ih) ) return 1;
783         // use indirect transfer
784         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
785         int max_bits = 0;
786         for( int i = 0; i <desc->nb_components; ++i ) {
787                 int bits = desc->comp[i].depth_minus1 + 1;
788                 if( bits > max_bits ) max_bits = bits;
789         }
790 // from libavcodec/pixdesc.c
791 #define pixdesc_has_alpha(pixdesc) ((pixdesc)->nb_components == 2 || \
792  (pixdesc)->nb_components == 4 || (pixdesc)->flags & AV_PIX_FMT_FLAG_PAL)
793         int icolor_model = pixdesc_has_alpha(desc) ?
794                 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
795                 (max_bits > 8 ? BC_RGB161616 : BC_RGB888) ;
796         VFrame vframe(iw, ih, icolor_model);
797         if( convert_picture_vframe(&vframe, ip, ifmt, iw, ih) ) return -1;
798         frame->transfer_from(&vframe);
799         return 1;
800 }
801
802 int FFVideoStream::convert_vframe_picture(VFrame *frame,
803                 AVPicture *op, PixelFormat ofmt, int ow, int oh)
804 {
805         AVPicture opic;
806         int cmodel = frame->get_color_model();
807         PixelFormat ifmt = color_model_to_pix_fmt(cmodel);
808         if( ifmt == AV_PIX_FMT_NB ) return -1;
809         int size = avpicture_fill(&opic, frame->get_data(), ifmt, 
810                                   frame->get_w(), frame->get_h());
811         if( size < 0 ) return -1;
812
813         // transfer line sizes must match also
814         int planar = BC_CModels::is_planar(cmodel);
815         int packed_width = !planar ? frame->get_bytes_per_line() :
816                  BC_CModels::calculate_pixelsize(cmodel) * frame->get_w();
817         if( packed_width != opic.linesize[0] )  return -1;
818
819         if( planar ) {
820                 // override avpicture_fill() for planar types
821                 opic.data[0] = frame->get_y();
822                 opic.data[1] = frame->get_u();
823                 opic.data[2] = frame->get_v();
824         }
825
826         convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(), ifmt,
827                 ow, oh, ofmt, SWS_BICUBIC, NULL, NULL, NULL);
828         if( !convert_ctx ) {
829                 fprintf(stderr, "FFVideoStream::convert_frame_picture:"
830                                 " sws_getCachedContext() failed\n");
831                 return 1;
832         }
833         if( sws_scale(convert_ctx, opic.data, opic.linesize, 0, frame->get_h(),
834                         op->data, op->linesize) < 0 ) {
835                 fprintf(stderr, "FFVideoStream::convert_frame_picture: sws_scale() failed\n");
836                 return 1;
837         }
838         return 0;
839 }
840
841 int FFVideoStream::convert_pixfmt(VFrame *frame,
842                  AVPicture *op, PixelFormat ofmt, int ow, int oh)
843 {
844         // try direct transfer
845         if( !convert_vframe_picture(frame, op, ofmt, ow, oh) ) return 0;
846         // use indirect transfer
847         int colormodel = frame->get_color_model();
848         int bits = BC_CModels::calculate_pixelsize(colormodel) * 8;
849         bits /= BC_CModels::components(colormodel);
850         int icolor_model =  BC_CModels::has_alpha(colormodel) ?
851                 (bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
852                 (bits > 8 ? BC_RGB161616: BC_RGB888) ;
853         VFrame vframe(frame->get_w(), frame->get_h(), icolor_model);
854         vframe.transfer_from(frame);
855         if( convert_vframe_picture(&vframe, op, ofmt, ow, oh) ) return 1;
856         return 0;
857 }
858
859
860 FFMPEG::FFMPEG(FileBase *file_base)
861 {
862         fmt_ctx = 0;
863         this->file_base = file_base;
864         memset(file_format,0,sizeof(file_format));
865         mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
866         flow_lock = new Condition(1,"FFStream::flow_lock",0);
867         done = -1;
868         flow = 1;
869         decoding = encoding = 0;
870         has_audio = has_video = 0;
871         opts = 0;
872         opt_duration = -1;
873         opt_video_filter = 0;
874         opt_audio_filter = 0;
875         char option_path[BCTEXTLEN];
876         set_option_path(option_path, "%s", "ffmpeg.opts");
877         read_options(option_path, opts);
878 }
879
880 FFMPEG::~FFMPEG()
881 {
882         ff_lock("FFMPEG::~FFMPEG()");
883         close_encoder();
884         ffaudio.remove_all_objects();
885         ffvideo.remove_all_objects();
886         if( encoding ) avformat_free_context(fmt_ctx);
887         ff_unlock();
888         delete flow_lock;
889         delete mux_lock;
890         av_dict_free(&opts);
891         delete opt_video_filter;
892         delete opt_audio_filter;
893 }
894
895 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
896 {
897         const int *p = codec->supported_samplerates;
898         if( !p ) return sample_rate;
899         while( *p != 0 ) {
900                 if( *p == sample_rate ) return *p;
901                 ++p;
902         }
903         return 0;
904 }
905
906 static inline AVRational std_frame_rate(int i)
907 {
908         static const int m1 = 1001*12, m2 = 1000*12;
909         static const int freqs[] = {
910                 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
911                 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
912         };
913         int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
914         return (AVRational) { freq, 1001*12 };
915 }
916
917 AVRational FFMPEG::check_frame_rate(AVCodec *codec, double frame_rate)
918 {
919         const AVRational *p = codec->supported_framerates;
920         AVRational rate, best_rate = (AVRational) { 0, 0 };
921         double max_err = 1.;  int i = 0;
922         while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
923                 double framerate = (double) rate.num / rate.den;
924                 double err = fabs(frame_rate/framerate - 1.);
925                 if( err >= max_err ) continue;
926                 max_err = err;
927                 best_rate = rate;
928         }
929         return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
930 }
931
932 AVRational FFMPEG::to_sample_aspect_ratio(double aspect_ratio)
933 {
934 #if 1
935         int height = 1000000, width = height * aspect_ratio;
936         float w, h;
937         MWindow::create_aspect_ratio(w, h, width, height);
938         return (AVRational){(int)w, (int)h};
939 #else
940 // square pixels
941         return (AVRational){1, 1};
942 #endif
943 }
944
945 AVRational FFMPEG::to_time_base(int sample_rate)
946 {
947         return (AVRational){1, sample_rate};
948 }
949
950 extern void get_exe_path(char *result); // from main.C
951
952 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
953 {
954         get_exe_path(path);
955         strcat(path, "/ffmpeg/");
956         path += strlen(path);
957         va_list ap;
958         va_start(ap, fmt);
959         vsprintf(path, fmt, ap);
960         va_end(ap);
961 }
962
963 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
964 {
965         if( *spec == '/' )
966                 strcpy(path, spec);
967         else
968                 set_option_path(path, "%s/%s", type, spec);
969 }
970
971 int FFMPEG::get_format(char *format, const char *path, char *spec)
972 {
973         char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
974         get_option_path(option_path, path, spec);
975         FILE *fp = fopen(option_path,"r");
976         if( !fp ) return 1;
977         int ret = 0;
978         if( !fgets(line, sizeof(line), fp) ) ret = 1;
979         if( !ret ) {
980                 line[sizeof(line)-1] = 0;
981                 ret = scan_option_line(line, format, codec);
982         }
983         fclose(fp);
984         return ret;
985 }
986
987 int FFMPEG::get_file_format()
988 {
989         int ret = 0;
990         char audio_format[BCSTRLEN], video_format[BCSTRLEN];
991         file_format[0] = audio_format[0] = video_format[0] = 0;
992         Asset *asset = file_base->asset;
993         if( !ret && asset->audio_data )
994                 ret = get_format(audio_format, "audio", asset->acodec);
995         if( !ret && asset->video_data )
996                 ret = get_format(video_format, "video", asset->vcodec);
997         if( !ret && !audio_format[0] && !video_format[0] )
998                 ret = 1;
999         if( !ret && audio_format[0] && video_format[0] &&
1000             strcmp(audio_format, video_format) ) ret = -1;
1001         if( !ret )
1002                 strcpy(file_format, audio_format[0] ? audio_format : video_format);
1003         return ret;
1004 }
1005
1006 int FFMPEG::scan_option_line(char *cp, char *tag, char *val)
1007 {
1008         while( *cp == ' ' || *cp == '\t' ) ++cp;
1009         char *bp = cp;
1010         while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' ) ++cp;
1011         int len = cp - bp;
1012         if( !len || len > BCSTRLEN-1 ) return 1;
1013         while( bp < cp ) *tag++ = *bp++;
1014         *tag = 0;
1015         while( *cp == ' ' || *cp == '\t' ) ++cp;
1016         if( *cp == '=' ) ++cp;
1017         while( *cp == ' ' || *cp == '\t' ) ++cp;
1018         bp = cp;
1019         while( *cp && *cp != '\n' ) ++cp;
1020         len = cp - bp;
1021         if( len > BCTEXTLEN-1 ) return 1;
1022         while( bp < cp ) *val++ = *bp++;
1023         *val = 0;
1024         return 0;
1025 }
1026
1027 int FFMPEG::get_encoder(const char *options,
1028                 char *format, char *codec, char *bsfilter, char *bsargs)
1029 {
1030         FILE *fp = fopen(options,"r");
1031         if( !fp ) {
1032                 eprintf("FFMPEG::get_encoder: options open failed %s\n",options);
1033                 return 1;
1034         }
1035         if( get_encoder(fp, format, codec, bsfilter, bsargs) )
1036                 eprintf("FFMPEG::get_encoder:"
1037                         " err: format/codec not found %s\n", options);
1038         fclose(fp);
1039         return 0;
1040 }
1041
1042 int FFMPEG::get_encoder(FILE *fp,
1043                 char *format, char *codec, char *bsfilter, char *bsargs)
1044 {
1045         format[0] = codec[0] = bsfilter[0] = bsargs[0] = 0;
1046         char line[BCTEXTLEN];
1047         if( !fgets(line, sizeof(line), fp) ) return 1;
1048         line[sizeof(line)-1] = 0;
1049         if( scan_option_line(line, format, codec) ) return 1;
1050         char *cp = codec;
1051         while( *cp && *cp != '|' ) ++cp;
1052         if( !*cp ) return 0;
1053         if( scan_option_line(cp+1, bsfilter, bsargs) ) return 1;
1054         do { *cp-- = 0; } while( cp>=codec && (*cp==' ' || *cp == '\t' ) );
1055         return 0;
1056 }
1057
1058 int FFMPEG::read_options(const char *options, AVDictionary *&opts)
1059 {
1060         FILE *fp = fopen(options,"r");
1061         if( !fp ) return 1;
1062         int ret = read_options(fp, options, opts);
1063         fclose(fp);
1064         return ret;
1065 }
1066
1067 int FFMPEG::scan_options(const char *options, AVDictionary *&opts)
1068 {
1069         FILE *fp = fmemopen((void *)options,strlen(options),"r");
1070         if( !fp ) return 0;
1071         int ret = read_options(fp, options, opts);
1072         fclose(fp);
1073         return ret;
1074 }
1075
1076 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
1077 {
1078         int ret = 0, no = 0;
1079         char line[BCTEXTLEN];
1080         while( !ret && fgets(line, sizeof(line), fp) ) {
1081                 line[sizeof(line)-1] = 0;
1082                 ++no;
1083                 if( line[0] == '#' ) continue;
1084                 if( line[0] == '\n' ) continue;
1085                 char key[BCSTRLEN], val[BCTEXTLEN];
1086                 if( scan_option_line(line, key, val) ) {
1087                         eprintf("FFMPEG::read_options:"
1088                                 " err reading %s: line %d\n", options, no);
1089                         ret = 1;
1090                 }
1091                 if( !ret ) {
1092                         if( !strcmp(key, "duration") )
1093                                 opt_duration = strtod(val, 0);
1094                         if( !strcmp(key, "video_filter") )
1095                                 opt_video_filter = cstrdup(val);
1096                         if( !strcmp(key, "audio_filter") )
1097                                 opt_audio_filter = cstrdup(val);
1098                         else if( !strcmp(key, "loglevel") )
1099                                 set_loglevel(val);
1100                         else
1101                                 av_dict_set(&opts, key, val, 0);
1102                 }
1103         }
1104         return ret;
1105 }
1106
1107 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
1108 {
1109         char option_path[BCTEXTLEN];
1110         set_option_path(option_path, "%s", options);
1111         return read_options(option_path, opts);
1112 }
1113
1114 int FFMPEG::load_options(const char *path, char *bfr, int len)
1115 {
1116         *bfr = 0;
1117         FILE *fp = fopen(path, "r");
1118         if( !fp ) return 1;
1119         fgets(bfr, len, fp); // skip hdr
1120         len = fread(bfr, 1, len-1, fp);
1121         if( len < 0 ) len = 0;
1122         bfr[len] = 0;
1123         fclose(fp);
1124         return 0;
1125 }
1126
1127 void FFMPEG::set_loglevel(const char *ap)
1128 {
1129         if( !ap || !*ap ) return;
1130         const struct {
1131                 const char *name;
1132                 int level;
1133         } log_levels[] = {
1134                 { "quiet"  , AV_LOG_QUIET   },
1135                 { "panic"  , AV_LOG_PANIC   },
1136                 { "fatal"  , AV_LOG_FATAL   },
1137                 { "error"  , AV_LOG_ERROR   },
1138                 { "warning", AV_LOG_WARNING },
1139                 { "info"   , AV_LOG_INFO    },
1140                 { "verbose", AV_LOG_VERBOSE },
1141                 { "debug"  , AV_LOG_DEBUG   },
1142         };
1143         for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
1144                 if( !strcmp(log_levels[i].name, ap) ) {
1145                         av_log_set_level(log_levels[i].level);
1146                         return;
1147                 }
1148         }
1149         av_log_set_level(atoi(ap));
1150 }
1151
1152 double FFMPEG::to_secs(int64_t time, AVRational time_base)
1153 {
1154         double base_time = time == AV_NOPTS_VALUE ? 0 :
1155                 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
1156         return base_time / AV_TIME_BASE; 
1157 }
1158
1159 int FFMPEG::info(char *text, int len)
1160 {
1161         if( len <= 0 ) return 0;
1162 #define report(s...) do { int n = snprintf(cp,len,s); cp += n;  len -= n; } while(0)
1163         char *cp = text;
1164         for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1165                 AVStream *st = fmt_ctx->streams[i];
1166                 AVCodecContext *avctx = st->codec;
1167                 report("stream %d,  id 0x%06x:\n", i, avctx->codec_id);
1168                 const AVCodecDescriptor *desc = avcodec_descriptor_get(avctx->codec_id);
1169                 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1170                         AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
1171                         double frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
1172                         report("  video %s",desc ? desc->name : " (unkn)");
1173                         report(" %dx%d %5.2f", avctx->width, avctx->height, frame_rate);
1174                         const char *pfn = av_get_pix_fmt_name(avctx->pix_fmt);
1175                         report(" pix %s\n", pfn ? pfn : "(unkn)");
1176                         double secs = to_secs(st->duration, st->time_base);
1177                         int64_t length = secs * frame_rate + 0.5;
1178                         report("    %jd frms %0.2f secs", length, secs);
1179                         int hrs = secs/3600;  secs -= hrs*3600;
1180                         int mins = secs/60;  secs -= mins*60;
1181                         report("  %d:%02d:%05.2f\n", hrs, mins, secs);
1182
1183                 }
1184                 else if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1185                         int sample_rate = avctx->sample_rate;
1186                         const char *fmt = av_get_sample_fmt_name(avctx->sample_fmt);
1187                         report("  audio %s",desc ? desc->name : " (unkn)");
1188                         report(" %dch %s %d",avctx->channels, fmt, sample_rate);
1189                         int sample_bits = av_get_bits_per_sample(avctx->codec_id);
1190                         report(" %dbits\n", sample_bits);
1191                         double secs = to_secs(st->duration, st->time_base);
1192                         int64_t length = secs * sample_rate + 0.5;
1193                         report("    %jd smpl %0.2f secs", length, secs);
1194                         int hrs = secs/3600;  secs -= hrs*3600;
1195                         int mins = secs/60;  secs -= mins*60;
1196                         report("  %d:%02d:%05.2f\n", hrs, mins, secs);
1197                 }
1198                 else
1199                         report("  codec_type unknown\n");
1200         }
1201         report("\n");
1202         for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
1203                 report("program %d", i+1);
1204                 AVProgram *pgrm = fmt_ctx->programs[i];
1205                 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j )
1206                         report(", %d", pgrm->stream_index[j]);
1207                 report("\n");
1208         }
1209         report("\n");
1210         AVDictionaryEntry *tag = 0;
1211         while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
1212                 report("%s=%s\n", tag->key, tag->value);
1213
1214         if( !len ) --cp;
1215         *cp = 0;
1216         return cp - text;
1217 #undef report
1218 }
1219
1220
1221 int FFMPEG::init_decoder(const char *filename)
1222 {
1223         ff_lock("FFMPEG::init_decoder");
1224         av_register_all();
1225         char file_opts[BCTEXTLEN];
1226         char *bp = strrchr(strcpy(file_opts, filename), '/');
1227         char *sp = strrchr(!bp ? file_opts : bp, '.');
1228         FILE *fp = 0;
1229         if( sp ) {
1230                 strcpy(sp, ".opts");
1231                 fp = fopen(file_opts, "r");
1232         }
1233         if( fp ) {
1234                 read_options(fp, file_opts, opts);
1235                 fclose(fp);
1236         }
1237         else
1238                 load_options("decode.opts", opts);
1239         AVDictionary *fopts = 0;
1240         av_dict_copy(&fopts, opts, 0);
1241         int ret = avformat_open_input(&fmt_ctx, filename, NULL, &fopts);
1242         av_dict_free(&fopts);
1243         if( ret >= 0 )
1244                 ret = avformat_find_stream_info(fmt_ctx, NULL);
1245         if( !ret ) {
1246                 decoding = -1;
1247         }
1248         ff_unlock();
1249         return !ret ? 0 : 1;
1250 }
1251
1252 int FFMPEG::open_decoder()
1253 {
1254         struct stat st;
1255         if( stat(fmt_ctx->filename, &st) < 0 ) {
1256                 eprintf("FFMPEG::open_decoder: can't stat file: %s\n",
1257                         fmt_ctx->filename);
1258                 return 1;
1259         }
1260
1261         int64_t file_bits = 8 * st.st_size;
1262         if( !fmt_ctx->bit_rate && opt_duration > 0 )
1263                 fmt_ctx->bit_rate = file_bits / opt_duration;
1264
1265         int estimated = 0;
1266         if( fmt_ctx->bit_rate > 0 ) {
1267                 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1268                         AVStream *st = fmt_ctx->streams[i];
1269                         if( st->duration != AV_NOPTS_VALUE ) continue;
1270                         if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
1271                         st->duration = av_rescale(file_bits, st->time_base.den,
1272                                 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
1273                         estimated = 1;
1274                 }
1275         }
1276         if( estimated )
1277                 printf("FFMPEG::open_decoder: some stream times estimated\n");
1278
1279         ff_lock("FFMPEG::open_decoder");
1280         int bad_time = 0;
1281         for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1282                 AVStream *st = fmt_ctx->streams[i];
1283                 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
1284                 AVCodecContext *avctx = st->codec;
1285                 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1286                         has_video = 1;
1287                         FFVideoStream *vid = new FFVideoStream(this, st, i);
1288                         int vidx = ffvideo.size();
1289                         vstrm_index.append(ffidx(vidx, 0));
1290                         ffvideo.append(vid);
1291                         vid->width = avctx->width;
1292                         vid->height = avctx->height;
1293                         AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
1294                         vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
1295                         double secs = to_secs(st->duration, st->time_base);
1296                         vid->length = secs * vid->frame_rate;
1297                         vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
1298                         vid->nudge = st->start_time;
1299                         vid->reading = -1;
1300                         if( opt_video_filter )
1301                                 vid->create_filter(opt_video_filter, avctx,avctx);
1302                 }
1303                 else if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1304                         has_audio = 1;
1305                         FFAudioStream *aud = new FFAudioStream(this, st, i);
1306                         int aidx = ffaudio.size();
1307                         ffaudio.append(aud);
1308                         aud->channel0 = astrm_index.size();
1309                         aud->channels = avctx->channels;
1310                         for( int ch=0; ch<aud->channels; ++ch )
1311                                 astrm_index.append(ffidx(aidx, ch));
1312                         aud->sample_rate = avctx->sample_rate;
1313                         double secs = to_secs(st->duration, st->time_base);
1314                         aud->length = secs * aud->sample_rate;
1315                         if( avctx->sample_fmt != AV_SAMPLE_FMT_FLT ) {
1316                                 uint64_t layout = av_get_default_channel_layout(avctx->channels);
1317                                 if( !layout ) layout = ((uint64_t)1<<aud->channels) - 1;
1318                                 aud->resample_context = swr_alloc_set_opts(NULL,
1319                                         layout, AV_SAMPLE_FMT_FLT, avctx->sample_rate,
1320                                         layout, avctx->sample_fmt, avctx->sample_rate,
1321                                         0, NULL);
1322                                 swr_init(aud->resample_context);
1323                         }
1324                         aud->nudge = st->start_time;
1325                         aud->reading = -1;
1326                         if( opt_audio_filter )
1327                                 aud->create_filter(opt_audio_filter, avctx,avctx);
1328                 }
1329         }
1330         if( bad_time )
1331                 printf("FFMPEG::open_decoder: some stream have bad times\n");
1332         ff_unlock();
1333         return 0;
1334 }
1335
1336
1337 int FFMPEG::init_encoder(const char *filename)
1338 {
1339         int fd = ::open(filename,O_WRONLY);
1340         if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
1341         if( fd < 0 ) {
1342                 eprintf("FFMPEG::init_encoder: bad file path: %s\n", filename);
1343                 return 1;
1344         }
1345         ::close(fd);
1346         int ret = get_file_format();
1347         if( ret > 0 ) {
1348                 eprintf("FFMPEG::init_encoder: bad file format: %s\n", filename);
1349                 return 1;
1350         }
1351         if( ret < 0 ) {
1352                 eprintf("FFMPEG::init_encoder: mismatch audio/video file format: %s\n", filename);
1353                 return 1;
1354         }
1355         ff_lock("FFMPEG::init_encoder");
1356         av_register_all();
1357         avformat_alloc_output_context2(&fmt_ctx, 0, file_format, filename);
1358         if( !fmt_ctx ) {
1359                 eprintf("FFMPEG::init_encoder: failed: %s\n", filename);
1360                 ret = 1;
1361         }
1362         if( !ret ) {
1363                 encoding = -1;
1364                 load_options("encode.opts", opts);
1365         }
1366         ff_unlock();
1367         start_muxer();
1368         return ret;
1369 }
1370
1371 int FFMPEG::open_encoder(const char *type, const char *spec)
1372 {
1373
1374         Asset *asset = file_base->asset;
1375         char *filename = asset->path;
1376         AVDictionary *sopts = 0;
1377         av_dict_copy(&sopts, opts, 0);
1378         char option_path[BCTEXTLEN];
1379         set_option_path(option_path, "%s/%s.opts", type, type);
1380         read_options(option_path, sopts);
1381         get_option_path(option_path, type, spec);
1382         char format_name[BCSTRLEN], codec_name[BCTEXTLEN];
1383         char bsfilter[BCSTRLEN], bsargs[BCTEXTLEN];
1384         if( get_encoder(option_path, format_name, codec_name, bsfilter, bsargs) ) {
1385                 eprintf("FFMPEG::open_encoder: get_encoder failed %s:%s\n",
1386                         option_path, filename);
1387                 return 1;
1388         }
1389
1390         int ret = 0;
1391         ff_lock("FFMPEG::open_encoder");
1392         FFStream *fst = 0;
1393         AVStream *st = 0;
1394
1395         const AVCodecDescriptor *codec_desc = 0;
1396         AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
1397         if( !codec ) {
1398                 eprintf("FFMPEG::open_encoder: cant find codec %s:%s\n",
1399                         codec_name, filename);
1400                 ret = 1;
1401         }
1402         if( !ret ) {
1403                 codec_desc = avcodec_descriptor_get(codec->id);
1404                 if( !codec_desc ) {
1405                         eprintf("FFMPEG::open_encoder: unknown codec %s:%s\n",
1406                                 codec_name, filename);
1407                         ret = 1;
1408                 }
1409         }
1410         if( !ret ) {
1411                 st = avformat_new_stream(fmt_ctx, 0);
1412                 if( !st ) {
1413                         eprintf("FFMPEG::open_encoder: cant create stream %s:%s\n",
1414                                 codec_name, filename);
1415                         ret = 1;
1416                 }
1417         } 
1418         if( !ret ) {
1419                 AVCodecContext *ctx = st->codec;
1420                 switch( codec_desc->type ) {
1421                 case AVMEDIA_TYPE_AUDIO: {
1422                         if( has_audio ) {
1423                                 eprintf("FFMPEG::open_encoder: duplicate audio %s:%s\n",
1424                                         codec_name, filename);
1425                                 ret = 1;
1426                                 break;
1427                         }
1428                         has_audio = 1;
1429                         if( scan_options(asset->ff_audio_options, sopts) ) {
1430                                 eprintf("FFMPEG::open_encoder: bad audio options %s:%s\n",
1431                                         codec_name, filename);
1432                                 ret = 1;
1433                                 break;
1434                         }
1435                         if( asset->ff_audio_bitrate > 0 ) {
1436                                 ctx->bit_rate = asset->ff_audio_bitrate;
1437                                 char arg[BCSTRLEN];
1438                                 sprintf(arg, "%d", asset->ff_audio_bitrate);
1439                                 av_dict_set(&sopts, "b", arg, 0);
1440                         }
1441                         int aidx = ffaudio.size();
1442                         int idx = aidx + ffvideo.size();
1443                         FFAudioStream *aud = new FFAudioStream(this, st, idx);
1444                         ffaudio.append(aud);  fst = aud;
1445                         aud->sample_rate = asset->sample_rate;
1446                         ctx->channels = aud->channels = asset->channels;
1447                         for( int ch=0; ch<aud->channels; ++ch )
1448                                 astrm_index.append(ffidx(aidx, ch));
1449                         ctx->channel_layout =  av_get_default_channel_layout(ctx->channels);
1450                         ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
1451                         if( !ctx->sample_rate ) {
1452                                 eprintf("FFMPEG::open_audio_encode:"
1453                                         " check_sample_rate failed %s\n", filename);
1454                                 ret = 1;
1455                                 break;
1456                         }
1457                         ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
1458                         ctx->sample_fmt = codec->sample_fmts[0];
1459                         uint64_t layout = av_get_default_channel_layout(ctx->channels);
1460                         aud->resample_context = swr_alloc_set_opts(NULL,
1461                                 layout, ctx->sample_fmt, aud->sample_rate,
1462                                 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
1463                                 0, NULL);
1464                         swr_init(aud->resample_context);
1465                         aud->writing = -1;
1466                         break; }
1467                 case AVMEDIA_TYPE_VIDEO: {
1468                         if( has_video ) {
1469                                 eprintf("FFMPEG::open_encoder: duplicate video %s:%s\n",
1470                                         codec_name, filename);
1471                                 ret = 1;
1472                                 break;
1473                         }
1474                         has_video = 1;
1475                         if( scan_options(asset->ff_video_options, sopts) ) {
1476                                 eprintf("FFMPEG::open_encoder: bad video options %s:%s\n",
1477                                         codec_name, filename);
1478                                 ret = 1;
1479                                 break;
1480                         }
1481                         if( asset->ff_video_bitrate > 0 ) {
1482                                 ctx->bit_rate = asset->ff_video_bitrate;
1483                                 char arg[BCSTRLEN];
1484                                 sprintf(arg, "%d", asset->ff_video_bitrate);
1485                                 av_dict_set(&sopts, "b", arg, 0);
1486                         }
1487                         else if( asset->ff_video_quality > 0 ) {
1488                                 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
1489                                 ctx->qmin    = ctx->qmax =  asset->ff_video_quality;
1490                                 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
1491                                 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
1492                                 ctx->flags |= CODEC_FLAG_QSCALE;
1493                                 char arg[BCSTRLEN];
1494                                 av_dict_set(&sopts, "flags", "+qscale", 0);
1495                                 sprintf(arg, "%d", asset->ff_video_quality);
1496                                 av_dict_set(&sopts, "qscale", arg, 0);
1497                                 sprintf(arg, "%d", ctx->global_quality);
1498                                 av_dict_set(&sopts, "global_quality", arg, 0);
1499                         }
1500                         int vidx = ffvideo.size();
1501                         int idx = vidx + ffaudio.size();
1502                         FFVideoStream *vid = new FFVideoStream(this, st, idx);
1503                         vstrm_index.append(ffidx(vidx, 0));
1504                         ffvideo.append(vid);  fst = vid;
1505                         vid->width = asset->width;
1506                         ctx->width = (vid->width+3) & ~3;
1507                         vid->height = asset->height;
1508                         ctx->height = (vid->height+3) & ~3;
1509                         vid->frame_rate = asset->frame_rate;
1510                         ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset->aspect_ratio);
1511                         ctx->pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
1512                         AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
1513                         if( !frame_rate.num || !frame_rate.den ) {
1514                                 eprintf("FFMPEG::open_audio_encode:"
1515                                         " check_frame_rate failed %s\n", filename);
1516                                 ret = 1;
1517                                 break;
1518                         }
1519                         ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
1520                         st->time_base = ctx->time_base;
1521                         vid->writing = -1;
1522                         break; }
1523                 default:
1524                         eprintf("FFMPEG::open_encoder: not audio/video, %s:%s\n",
1525                                 codec_name, filename);
1526                         ret = 1;
1527                 }
1528         }
1529         if( !ret ) {
1530                 ret = avcodec_open2(st->codec, codec, &sopts);
1531                 if( ret < 0 ) {
1532                         ff_err(ret,"FFMPEG::open_encoder");
1533                         eprintf("FFMPEG::open_encoder: open failed %s:%s\n",
1534                                 codec_name, filename);
1535                         ret = 1;
1536                 }
1537                 else
1538                         ret = 0;
1539         }
1540         if( !ret ) {
1541                 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
1542                         st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
1543                 if( fst && bsfilter[0] )
1544                         fst->add_bsfilter(bsfilter, !bsargs[0] ? 0 : bsargs);
1545         }
1546
1547         ff_unlock();
1548         av_dict_free(&sopts);
1549         return ret;
1550 }
1551
1552 int FFMPEG::close_encoder()
1553 {
1554         stop_muxer();
1555         if( encoding > 0 ) {
1556                 av_write_trailer(fmt_ctx);
1557                 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
1558                         avio_closep(&fmt_ctx->pb);
1559         }
1560         encoding = 0;
1561         return 0;
1562 }
1563
1564 int FFMPEG::decode_activate()
1565 {
1566         if( decoding < 0 ) {
1567                 decoding = 0;
1568                 int npgrms = fmt_ctx->nb_programs;
1569                 for( int i=0; i<npgrms; ++i ) {
1570                         AVProgram *pgrm = fmt_ctx->programs[i];
1571                         // first start time video stream
1572                         int64_t vstart_time = -1;
1573                         for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1574                                 int st_idx = pgrm->stream_index[j];
1575                                 AVStream *st = fmt_ctx->streams[st_idx];
1576                                 AVCodecContext *avctx = st->codec;
1577                                 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1578                                         if( st->start_time == AV_NOPTS_VALUE ) continue;
1579                                         vstart_time = st->start_time;
1580                                         break;
1581                                 }
1582                         }
1583                         // max start time audio stream
1584                         int64_t astart_time = -1;
1585                         for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1586                                 int st_idx = pgrm->stream_index[j];
1587                                 AVStream *st = fmt_ctx->streams[st_idx];
1588                                 AVCodecContext *avctx = st->codec;
1589                                 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1590                                         if( st->start_time == AV_NOPTS_VALUE ) continue;
1591                                         if( astart_time > st->start_time ) continue;
1592                                         astart_time = st->start_time;
1593                                 }
1594                         }
1595                         if( astart_time < 0 || vstart_time < 0 ) continue;
1596                         // match program streams to max start_time
1597                         int64_t nudge = vstart_time > astart_time ? vstart_time : astart_time;
1598                         for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1599                                 int st_idx = pgrm->stream_index[j];
1600                                 AVStream *st = fmt_ctx->streams[st_idx];
1601                                 AVCodecContext *avctx = st->codec;
1602                                 if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1603                                         for( int k=0; k<ffaudio.size(); ++k ) {
1604                                                 if( ffaudio[k]->idx == st_idx )
1605                                                         ffaudio[k]->nudge = nudge;
1606                                         }
1607                                 }
1608                                 else if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1609                                         for( int k=0; k<ffvideo.size(); ++k ) {
1610                                                 if( ffvideo[k]->idx == st_idx )
1611                                                         ffvideo[k]->nudge = nudge;
1612                                         }
1613                                 }
1614                         }
1615                 }
1616                 int64_t vstart_time = 0, astart_time = 0;
1617                 int nstreams = fmt_ctx->nb_streams;
1618                 for( int i=0; i<nstreams; ++i ) {
1619                         AVStream *st = fmt_ctx->streams[i];
1620                         AVCodecContext *avctx = st->codec;
1621                         switch( avctx->codec_type ) {
1622                         case AVMEDIA_TYPE_VIDEO:
1623                                 if( st->start_time == AV_NOPTS_VALUE ) continue;
1624                                 if( vstart_time >= st->start_time ) continue;
1625                                 vstart_time = st->start_time;
1626                                 break;
1627                         case AVMEDIA_TYPE_AUDIO:
1628                                 if( st->start_time == AV_NOPTS_VALUE ) continue;
1629                                 if( astart_time >= st->start_time ) continue;
1630                                 astart_time = st->start_time;
1631                         default: break;
1632                         }
1633                 }
1634                 int64_t nudge = vstart_time > astart_time ? vstart_time : astart_time;
1635                 for( int k=0; k<ffvideo.size(); ++k ) {
1636                         if( ffvideo[k]->nudge != AV_NOPTS_VALUE ) continue;
1637                         ffvideo[k]->nudge = nudge;
1638                 }
1639                 for( int k=0; k<ffaudio.size(); ++k ) {
1640                         if( ffaudio[k]->nudge != AV_NOPTS_VALUE ) continue;
1641                         ffaudio[k]->nudge = nudge;
1642                 }
1643                 decoding = 1;
1644         }
1645         return decoding;
1646 }
1647
1648 int FFMPEG::encode_activate()
1649 {
1650         if( encoding < 0 ) {
1651                 encoding = 0;
1652                 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
1653                     avio_open(&fmt_ctx->pb, fmt_ctx->filename, AVIO_FLAG_WRITE) < 0 ) {
1654                         fprintf(stderr, "FFMPEG::encode_activate: err opening : %s\n",
1655                                 fmt_ctx->filename);
1656                         return 1;
1657                 }
1658
1659                 AVDictionary *fopts = 0;
1660                 char option_path[BCTEXTLEN];
1661                 set_option_path(option_path, "format/%s", file_format);
1662                 read_options(option_path, fopts);
1663                 int ret = avformat_write_header(fmt_ctx, &fopts);
1664                 av_dict_free(&fopts);
1665                 if( ret < 0 ) {
1666                         fprintf(stderr, "FFMPEG::encode_activate: write header failed %s\n",
1667                                 fmt_ctx->filename);
1668                         return 1;
1669                 }
1670                 encoding = 1;
1671         }
1672         return encoding;
1673 }
1674
1675 int FFMPEG::audio_seek(int stream, int64_t pos)
1676 {
1677         int aidx = astrm_index[stream].st_idx;
1678         FFAudioStream *aud = ffaudio[aidx];
1679         aud->audio_seek(pos);
1680         aud->seek_pos = aud->curr_pos = pos;
1681         return 0;
1682 }
1683
1684 int FFMPEG::video_seek(int stream, int64_t pos)
1685 {
1686         int vidx = vstrm_index[stream].st_idx;
1687         FFVideoStream *vid = ffvideo[vidx];
1688         vid->video_seek(pos);
1689         vid->seek_pos = vid->curr_pos = pos;
1690         return 0;
1691 }
1692
1693
1694 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
1695 {
1696         if( !has_audio || chn >= astrm_index.size() ) return -1;
1697         int aidx = astrm_index[chn].st_idx;
1698         FFAudioStream *aud = ffaudio[aidx];
1699         if( aud->load(pos, len) < len ) return -1;
1700         int ch = astrm_index[chn].st_ch;
1701         return aud->read(samples,len,ch);
1702 }
1703
1704 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
1705 {
1706         if( !has_video || layer >= vstrm_index.size() ) return -1;
1707         int vidx = vstrm_index[layer].st_idx;
1708         FFVideoStream *vid = ffvideo[vidx];
1709         return vid->load(vframe, pos);
1710 }
1711
1712 int FFMPEG::encode(int stream, double **samples, int len)
1713 {
1714         FFAudioStream *aud = ffaudio[stream];
1715         return aud->encode(samples, len);
1716 }
1717
1718
1719 int FFMPEG::encode(int stream, VFrame *frame)
1720 {
1721         FFVideoStream *vid = ffvideo[stream];
1722         return vid->encode(frame);
1723 }
1724
1725 void FFMPEG::start_muxer()
1726 {
1727         if( !running() ) {
1728                 done = 0;
1729                 start();
1730         }
1731 }
1732
1733 void FFMPEG::stop_muxer()
1734 {
1735         if( running() ) {
1736                 done = 1;
1737                 mux_lock->unlock();
1738                 join();
1739         }
1740 }
1741
1742 void FFMPEG::flow_off()
1743 {
1744         if( !flow ) return;
1745         flow_lock->lock("FFMPEG::flow_off");
1746         flow = 0;
1747 }
1748
1749 void FFMPEG::flow_on()
1750 {
1751         if( flow ) return;
1752         flow = 1;
1753         flow_lock->unlock();
1754 }
1755
1756 void FFMPEG::flow_ctl()
1757 {
1758         while( !flow ) {
1759                 flow_lock->lock("FFMPEG::flow_ctl");
1760                 flow_lock->unlock();
1761         }
1762 }
1763
1764 int FFMPEG::mux_audio(FFrame *frm)
1765 {
1766         FFPacket pkt;
1767         AVStream *st = frm->fst->st;
1768         AVCodecContext *ctx = st->codec;
1769         AVFrame *frame = *frm;
1770         AVRational tick_rate = {1, ctx->sample_rate};
1771         frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
1772         int got_packet = 0;
1773         int ret = avcodec_encode_audio2(ctx, pkt, frame, &got_packet);
1774         if( ret >= 0 && got_packet ) {
1775                 frm->fst->bs_filter(pkt);
1776                 av_packet_rescale_ts(pkt, ctx->time_base, st->time_base);
1777                 pkt->stream_index = st->index;
1778                 ret = av_interleaved_write_frame(fmt_ctx, pkt);
1779         }
1780         if( ret < 0 )
1781                 ff_err(ret, "FFMPEG::mux_audio");
1782         return ret >= 0 ? 0 : 1;
1783 }
1784
1785 int FFMPEG::mux_video(FFrame *frm)
1786 {
1787         FFPacket pkt;
1788         AVStream *st = frm->fst->st;
1789         AVFrame *frame = *frm;
1790         frame->pts = frm->position;
1791         int ret = 1, got_packet = 0;
1792         if( fmt_ctx->oformat->flags & AVFMT_RAWPICTURE ) {
1793                 /* a hack to avoid data copy with some raw video muxers */
1794                 pkt->flags |= AV_PKT_FLAG_KEY;
1795                 pkt->stream_index  = st->index;
1796                 AVPicture *picture = (AVPicture *)frame;
1797                 pkt->data = (uint8_t *)picture;
1798                 pkt->size = sizeof(AVPicture);
1799                 pkt->pts = pkt->dts = frame->pts;
1800                 got_packet = 1;
1801         }
1802         else
1803                 ret = avcodec_encode_video2(st->codec, pkt, frame, &got_packet);
1804         if( ret >= 0 && got_packet ) {
1805                 frm->fst->bs_filter(pkt);
1806                 av_packet_rescale_ts(pkt, st->codec->time_base, st->time_base);
1807                 pkt->stream_index = st->index;
1808                 ret = av_interleaved_write_frame(fmt_ctx, pkt);
1809         }
1810         if( ret < 0 )
1811                 ff_err(ret, "FFMPEG::mux_video");
1812         return ret >= 0 ? 0 : 1;
1813 }
1814
1815 void FFMPEG::mux()
1816 {
1817         for(;;) {
1818                 double atm = -1, vtm = -1;
1819                 FFrame *afrm = 0, *vfrm = 0;
1820                 int demand = 0;
1821                 for( int i=0; i<ffaudio.size(); ++i ) {  // earliest audio
1822                         FFStream *fst = ffaudio[i];
1823                         if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
1824                         FFrame *frm = fst->frms.first;
1825                         if( !frm ) { if( !done ) return; continue; }
1826                         double tm = to_secs(frm->position, fst->st->codec->time_base);
1827                         if( atm < 0 || tm < atm ) { atm = tm;  afrm = frm; }
1828                 }
1829                 for( int i=0; i<ffvideo.size(); ++i ) {  // earliest video
1830                         FFStream *fst = ffvideo[i];
1831                         if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
1832                         FFrame *frm = fst->frms.first;
1833                         if( !frm ) { if( !done ) return; continue; }
1834                         double tm = to_secs(frm->position, fst->st->codec->time_base);
1835                         if( vtm < 0 || tm < vtm ) { vtm = tm;  vfrm = frm; }
1836                 }
1837                 if( !demand ) flow_off();
1838                 if( !afrm && !vfrm ) break;
1839                 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
1840                         vfrm->position, vfrm->fst->st->codec->time_base,
1841                         afrm->position, afrm->fst->st->codec->time_base);
1842                 FFrame *frm = v <= 0 ? vfrm : afrm;
1843                 if( frm == afrm ) mux_audio(frm);
1844                 if( frm == vfrm ) mux_video(frm);
1845                 frm->dequeue();
1846                 delete frm;
1847         }
1848 }
1849
1850 void FFMPEG::run()
1851 {
1852         while( !done ) {
1853                 mux_lock->lock("FFMPEG::run");
1854                 if( !done ) mux();
1855         }
1856         mux();
1857 }
1858
1859
1860 int FFMPEG::ff_total_audio_channels()
1861 {
1862         return astrm_index.size();
1863 }
1864
1865 int FFMPEG::ff_total_astreams()
1866 {
1867         return ffaudio.size();
1868 }
1869
1870 int FFMPEG::ff_audio_channels(int stream)
1871 {
1872         return ffaudio[stream]->channels;
1873 }
1874
1875 int FFMPEG::ff_sample_rate(int stream)
1876 {
1877         return ffaudio[stream]->sample_rate;
1878 }
1879
1880 const char* FFMPEG::ff_audio_format(int stream)
1881 {
1882         AVStream *st = ffaudio[stream]->st;
1883         AVCodecID id = st->codec->codec_id;
1884         const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
1885         return desc ? desc->name : "Unknown";
1886 }
1887
1888 int FFMPEG::ff_audio_pid(int stream)
1889 {
1890         return ffaudio[stream]->st->id;
1891 }
1892
1893 int64_t FFMPEG::ff_audio_samples(int stream)
1894 {
1895         return ffaudio[stream]->length;
1896 }
1897
1898 // find audio astream/channels with this program,
1899 //   or all program audio channels (astream=-1)
1900 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
1901 {
1902         channel_mask = 0;
1903         int pidx = -1;
1904         int vidx = ffvideo[vstream]->idx;
1905         // find first program with this video stream
1906         for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
1907                 AVProgram *pgrm = fmt_ctx->programs[i];
1908                 for( int j=0;  pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
1909                         int st_idx = pgrm->stream_index[j];
1910                         AVStream *st = fmt_ctx->streams[st_idx];
1911                         if( st->codec->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
1912                         if( st_idx == vidx ) pidx = i;
1913                 }
1914         }
1915         if( pidx < 0 ) return -1;
1916         int ret = -1;
1917         int64_t channels = 0;
1918         AVProgram *pgrm = fmt_ctx->programs[pidx];
1919         for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1920                 int aidx = pgrm->stream_index[j];
1921                 AVStream *st = fmt_ctx->streams[aidx];
1922                 if( st->codec->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
1923                 if( astream > 0 ) { --astream;  continue; }
1924                 int astrm = -1;
1925                 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
1926                         if( ffaudio[i]->idx == aidx ) astrm = i;
1927                 if( astrm >= 0 ) {
1928                         if( ret < 0 ) ret = astrm;
1929                         int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
1930                         channels |= mask << ffaudio[astrm]->channel0;
1931                 }
1932                 if( !astream ) break;
1933         }
1934         channel_mask = channels;
1935         return ret;
1936 }
1937
1938
1939 int FFMPEG::ff_total_video_layers()
1940 {
1941         return vstrm_index.size();
1942 }
1943
1944 int FFMPEG::ff_total_vstreams()
1945 {
1946         return ffvideo.size();
1947 }
1948
1949 int FFMPEG::ff_video_width(int stream)
1950 {
1951         return ffvideo[stream]->width;
1952 }
1953
1954 int FFMPEG::ff_video_height(int stream)
1955 {
1956         return ffvideo[stream]->height;
1957 }
1958
1959 int FFMPEG::ff_set_video_width(int stream, int width)
1960 {
1961         int w = ffvideo[stream]->width;
1962         ffvideo[stream]->width = width;
1963         return w;
1964 }
1965
1966 int FFMPEG::ff_set_video_height(int stream, int height)
1967 {
1968         int h = ffvideo[stream]->height;
1969         ffvideo[stream]->height = height;
1970         return h;
1971 }
1972
1973 int FFMPEG::ff_coded_width(int stream)
1974 {
1975         AVStream *st = ffvideo[stream]->st;
1976         return st->codec->coded_width;
1977 }
1978
1979 int FFMPEG::ff_coded_height(int stream)
1980 {
1981         AVStream *st = ffvideo[stream]->st;
1982         return st->codec->coded_height;
1983 }
1984
1985 float FFMPEG::ff_aspect_ratio(int stream)
1986 {
1987         return ffvideo[stream]->aspect_ratio;
1988 }
1989
1990 const char* FFMPEG::ff_video_format(int stream)
1991 {
1992         AVStream *st = ffvideo[stream]->st;
1993         AVCodecID id = st->codec->codec_id;
1994         const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
1995         return desc ? desc->name : "Unknown";
1996 }
1997
1998 double FFMPEG::ff_frame_rate(int stream)
1999 {
2000         return ffvideo[stream]->frame_rate;
2001 }
2002
2003 int64_t FFMPEG::ff_video_frames(int stream)
2004 {
2005         return ffvideo[stream]->length;
2006 }
2007
2008 int FFMPEG::ff_video_pid(int stream)
2009 {
2010         return ffvideo[stream]->st->id;
2011 }
2012
2013
2014 int FFMPEG::ff_cpus()
2015 {
2016         return file_base->file->cpus;
2017 }
2018
2019 int FFVideoStream::create_filter(const char *filter_spec,
2020                 AVCodecContext *src_ctx, AVCodecContext *sink_ctx)
2021 {
2022         avfilter_register_all();
2023         filter_graph = avfilter_graph_alloc();
2024         AVFilter *buffersrc = avfilter_get_by_name("buffer");
2025         AVFilter *buffersink = avfilter_get_by_name("buffersink");
2026
2027         int ret = 0;  char args[BCTEXTLEN];
2028         snprintf(args, sizeof(args),
2029                 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
2030                 src_ctx->width, src_ctx->height, src_ctx->pix_fmt,
2031                 st->time_base.num, st->time_base.den,
2032                 src_ctx->sample_aspect_ratio.num, src_ctx->sample_aspect_ratio.den);
2033         if( ret >= 0 )
2034                 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2035                         args, NULL, filter_graph);
2036         if( ret >= 0 )
2037                 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2038                         NULL, NULL, filter_graph);
2039         if( ret >= 0 )
2040                 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
2041                         (uint8_t*)&sink_ctx->pix_fmt, sizeof(sink_ctx->pix_fmt),
2042                         AV_OPT_SEARCH_CHILDREN);
2043         if( ret < 0 )
2044                 ff_err(ret, "FFVideoStream::create_filter");
2045         else
2046                 ret = FFStream::create_filter(filter_spec);
2047         return ret >= 0 ? 0 : 1;
2048 }
2049
2050 int FFAudioStream::create_filter(const char *filter_spec,
2051                 AVCodecContext *src_ctx, AVCodecContext *sink_ctx)
2052 {
2053         avfilter_register_all();
2054         filter_graph = avfilter_graph_alloc();
2055         AVFilter *buffersrc = avfilter_get_by_name("abuffer");
2056         AVFilter *buffersink = avfilter_get_by_name("abuffersink");
2057         int ret = 0;  char args[BCTEXTLEN];
2058         snprintf(args, sizeof(args),
2059                 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
2060                 st->time_base.num, st->time_base.den, src_ctx->sample_rate,
2061                 av_get_sample_fmt_name(src_ctx->sample_fmt), src_ctx->channel_layout);
2062         if( ret >= 0 )
2063                 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2064                         args, NULL, filter_graph);
2065         if( ret >= 0 )
2066                 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2067                         NULL, NULL, filter_graph);
2068         if( ret >= 0 )
2069                 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
2070                         (uint8_t*)&sink_ctx->sample_fmt, sizeof(sink_ctx->sample_fmt),
2071                         AV_OPT_SEARCH_CHILDREN);
2072         if( ret >= 0 )
2073                 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
2074                         (uint8_t*)&sink_ctx->channel_layout,
2075                         sizeof(sink_ctx->channel_layout), AV_OPT_SEARCH_CHILDREN);
2076         if( ret >= 0 )
2077                 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
2078                         (uint8_t*)&sink_ctx->sample_rate, sizeof(sink_ctx->sample_rate),
2079                         AV_OPT_SEARCH_CHILDREN);
2080         if( ret < 0 )
2081                 ff_err(ret, "FFAudioStream::create_filter");
2082         else
2083                 ret = FFStream::create_filter(filter_spec);
2084         return ret >= 0 ? 0 : 1;
2085 }
2086
2087 int FFStream::create_filter(const char *filter_spec)
2088 {
2089         /* Endpoints for the filter graph. */
2090         AVFilterInOut *outputs = avfilter_inout_alloc();
2091         outputs->name = av_strdup("in");
2092         outputs->filter_ctx = buffersrc_ctx;
2093         outputs->pad_idx = 0;
2094         outputs->next = 0;
2095
2096         AVFilterInOut *inputs  = avfilter_inout_alloc();
2097         inputs->name = av_strdup("out");
2098         inputs->filter_ctx = buffersink_ctx;
2099         inputs->pad_idx = 0;
2100         inputs->next = 0;
2101
2102         int ret = !outputs->name || !inputs->name ? -1 : 0;
2103         if( ret >= 0 )
2104                 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
2105                         &inputs, &outputs, NULL);
2106         if( ret >= 0 )
2107                 ret = avfilter_graph_config(filter_graph, NULL);
2108
2109         if( ret < 0 )
2110                 ff_err(ret, "FFStream::create_filter");
2111         avfilter_inout_free(&inputs);
2112         avfilter_inout_free(&outputs);
2113         return ret;
2114 }
2115
2116 void FFStream::add_bsfilter(const char *bsf, const char *ap)
2117 {
2118         bsfilter.append(new BSFilter(bsf,ap));
2119 }
2120
2121 int FFStream::bs_filter(AVPacket *pkt)
2122 {
2123         if( !bsfilter.size() ) return 0;
2124         av_packet_split_side_data(pkt);
2125
2126         int ret = 0;
2127         for( int i=0; i<bsfilter.size(); ++i ) {
2128                 AVPacket bspkt = *pkt;
2129                 ret = av_bitstream_filter_filter(bsfilter[i]->bsfc,
2130                          st->codec, bsfilter[i]->args, &bspkt.data, &bspkt.size,
2131                          pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY);
2132                 if( ret < 0 ) break;
2133                 int size = bspkt.size;
2134                 uint8_t *data = bspkt.data;
2135                 if( !ret && bspkt.data != pkt->data ) {
2136                         size = bspkt.size;
2137                         data = (uint8_t *)av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
2138                         if( !data ) { ret = AVERROR(ENOMEM);  break; }
2139                         memcpy(data, bspkt.data, size);
2140                         memset(data+size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2141                         ret = 1;
2142                 }
2143                 if( ret > 0 ) {
2144                         pkt->side_data = 0;  pkt->side_data_elems = 0;
2145                         av_free_packet(pkt);
2146                         ret = av_packet_from_data(&bspkt, data, size);
2147                         if( ret < 0 ) break;
2148                 }
2149                 *pkt = bspkt;
2150         }
2151         if( ret < 0 )
2152                 ff_err(ret,"FFStream::bs_filter");
2153         return ret;
2154 }
2155