add buffer flush to ffmpeg seek, clear loop_session on load replace mode
[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         int height = 1000000, width = height * aspect_ratio;
935         float w, h;
936         MWindow::create_aspect_ratio(w, h, width, height);
937         return (AVRational){(int)w, (int)h};
938 }
939
940 AVRational FFMPEG::to_time_base(int sample_rate)
941 {
942         return (AVRational){1, sample_rate};
943 }
944
945 extern void get_exe_path(char *result); // from main.C
946
947 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
948 {
949         get_exe_path(path);
950         strcat(path, "/ffmpeg/");
951         path += strlen(path);
952         va_list ap;
953         va_start(ap, fmt);
954         vsprintf(path, fmt, ap);
955         va_end(ap);
956 }
957
958 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
959 {
960         if( *spec == '/' )
961                 strcpy(path, spec);
962         else
963                 set_option_path(path, "%s/%s", type, spec);
964 }
965
966 int FFMPEG::get_format(char *format, const char *path, char *spec)
967 {
968         char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
969         get_option_path(option_path, path, spec);
970         FILE *fp = fopen(option_path,"r");
971         if( !fp ) return 1;
972         int ret = 0;
973         if( !fgets(line, sizeof(line), fp) ) ret = 1;
974         if( !ret ) {
975                 line[sizeof(line)-1] = 0;
976                 ret = scan_option_line(line, format, codec);
977         }
978         fclose(fp);
979         return ret;
980 }
981
982 int FFMPEG::get_file_format()
983 {
984         int ret = 0;
985         char audio_format[BCSTRLEN], video_format[BCSTRLEN];
986         file_format[0] = audio_format[0] = video_format[0] = 0;
987         Asset *asset = file_base->asset;
988         if( !ret && asset->audio_data )
989                 ret = get_format(audio_format, "audio", asset->acodec);
990         if( !ret && asset->video_data )
991                 ret = get_format(video_format, "video", asset->vcodec);
992         if( !ret && !audio_format[0] && !video_format[0] )
993                 ret = 1;
994         if( !ret && audio_format[0] && video_format[0] &&
995             strcmp(audio_format, video_format) ) ret = -1;
996         if( !ret )
997                 strcpy(file_format, audio_format[0] ? audio_format : video_format);
998         return ret;
999 }
1000
1001 int FFMPEG::scan_option_line(char *cp, char *tag, char *val)
1002 {
1003         while( *cp == ' ' || *cp == '\t' ) ++cp;
1004         char *bp = cp;
1005         while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' ) ++cp;
1006         int len = cp - bp;
1007         if( !len || len > BCSTRLEN-1 ) return 1;
1008         while( bp < cp ) *tag++ = *bp++;
1009         *tag = 0;
1010         while( *cp == ' ' || *cp == '\t' ) ++cp;
1011         if( *cp == '=' ) ++cp;
1012         while( *cp == ' ' || *cp == '\t' ) ++cp;
1013         bp = cp;
1014         while( *cp && *cp != '\n' ) ++cp;
1015         len = cp - bp;
1016         if( len > BCTEXTLEN-1 ) return 1;
1017         while( bp < cp ) *val++ = *bp++;
1018         *val = 0;
1019         return 0;
1020 }
1021
1022 int FFMPEG::get_encoder(const char *options,
1023                 char *format, char *codec, char *bsfilter, char *bsargs)
1024 {
1025         FILE *fp = fopen(options,"r");
1026         if( !fp ) {
1027                 eprintf("FFMPEG::get_encoder: options open failed %s\n",options);
1028                 return 1;
1029         }
1030         if( get_encoder(fp, format, codec, bsfilter, bsargs) )
1031                 eprintf("FFMPEG::get_encoder:"
1032                         " err: format/codec not found %s\n", options);
1033         fclose(fp);
1034         return 0;
1035 }
1036
1037 int FFMPEG::get_encoder(FILE *fp,
1038                 char *format, char *codec, char *bsfilter, char *bsargs)
1039 {
1040         format[0] = codec[0] = bsfilter[0] = bsargs[0] = 0;
1041         char line[BCTEXTLEN];
1042         if( !fgets(line, sizeof(line), fp) ) return 1;
1043         line[sizeof(line)-1] = 0;
1044         if( scan_option_line(line, format, codec) ) return 1;
1045         char *cp = codec;
1046         while( *cp && *cp != '|' ) ++cp;
1047         if( !*cp ) return 0;
1048         if( scan_option_line(cp+1, bsfilter, bsargs) ) return 1;
1049         do { *cp-- = 0; } while( cp>=codec && (*cp==' ' || *cp == '\t' ) );
1050         return 0;
1051 }
1052
1053 int FFMPEG::read_options(const char *options, AVDictionary *&opts)
1054 {
1055         FILE *fp = fopen(options,"r");
1056         if( !fp ) return 1;
1057         int ret = read_options(fp, options, opts);
1058         fclose(fp);
1059         return ret;
1060 }
1061
1062 int FFMPEG::scan_options(const char *options, AVDictionary *&opts)
1063 {
1064         FILE *fp = fmemopen((void *)options,strlen(options),"r");
1065         if( !fp ) return 0;
1066         int ret = read_options(fp, options, opts);
1067         fclose(fp);
1068         return ret;
1069 }
1070
1071 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
1072 {
1073         int ret = 0, no = 0;
1074         char line[BCTEXTLEN];
1075         while( !ret && fgets(line, sizeof(line), fp) ) {
1076                 line[sizeof(line)-1] = 0;
1077                 ++no;
1078                 if( line[0] == '#' ) continue;
1079                 if( line[0] == '\n' ) continue;
1080                 char key[BCSTRLEN], val[BCTEXTLEN];
1081                 if( scan_option_line(line, key, val) ) {
1082                         eprintf("FFMPEG::read_options:"
1083                                 " err reading %s: line %d\n", options, no);
1084                         ret = 1;
1085                 }
1086                 if( !ret ) {
1087                         if( !strcmp(key, "duration") )
1088                                 opt_duration = strtod(val, 0);
1089                         if( !strcmp(key, "video_filter") )
1090                                 opt_video_filter = cstrdup(val);
1091                         if( !strcmp(key, "audio_filter") )
1092                                 opt_audio_filter = cstrdup(val);
1093                         else if( !strcmp(key, "loglevel") )
1094                                 set_loglevel(val);
1095                         else
1096                                 av_dict_set(&opts, key, val, 0);
1097                 }
1098         }
1099         return ret;
1100 }
1101
1102 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
1103 {
1104         char option_path[BCTEXTLEN];
1105         set_option_path(option_path, "%s", options);
1106         return read_options(option_path, opts);
1107 }
1108
1109 int FFMPEG::load_options(const char *path, char *bfr, int len)
1110 {
1111         *bfr = 0;
1112         FILE *fp = fopen(path, "r");
1113         if( !fp ) return 1;
1114         fgets(bfr, len, fp); // skip hdr
1115         len = fread(bfr, 1, len-1, fp);
1116         if( len < 0 ) len = 0;
1117         bfr[len] = 0;
1118         fclose(fp);
1119         return 0;
1120 }
1121
1122 void FFMPEG::set_loglevel(const char *ap)
1123 {
1124         if( !ap || !*ap ) return;
1125         const struct {
1126                 const char *name;
1127                 int level;
1128         } log_levels[] = {
1129                 { "quiet"  , AV_LOG_QUIET   },
1130                 { "panic"  , AV_LOG_PANIC   },
1131                 { "fatal"  , AV_LOG_FATAL   },
1132                 { "error"  , AV_LOG_ERROR   },
1133                 { "warning", AV_LOG_WARNING },
1134                 { "info"   , AV_LOG_INFO    },
1135                 { "verbose", AV_LOG_VERBOSE },
1136                 { "debug"  , AV_LOG_DEBUG   },
1137         };
1138         for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
1139                 if( !strcmp(log_levels[i].name, ap) ) {
1140                         av_log_set_level(log_levels[i].level);
1141                         return;
1142                 }
1143         }
1144         av_log_set_level(atoi(ap));
1145 }
1146
1147 double FFMPEG::to_secs(int64_t time, AVRational time_base)
1148 {
1149         double base_time = time == AV_NOPTS_VALUE ? 0 :
1150                 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
1151         return base_time / AV_TIME_BASE; 
1152 }
1153
1154 int FFMPEG::info(char *text, int len)
1155 {
1156         if( len <= 0 ) return 0;
1157 #define report(s...) do { int n = snprintf(cp,len,s); cp += n;  len -= n; } while(0)
1158         char *cp = text;
1159         for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1160                 AVStream *st = fmt_ctx->streams[i];
1161                 AVCodecContext *avctx = st->codec;
1162                 report("stream %d,  id 0x%06x:\n", i, avctx->codec_id);
1163                 const AVCodecDescriptor *desc = avcodec_descriptor_get(avctx->codec_id);
1164                 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1165                         AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
1166                         double frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
1167                         report("  video %s",desc ? desc->name : " (unkn)");
1168                         report(" %dx%d %5.2f", avctx->width, avctx->height, frame_rate);
1169                         const char *pfn = av_get_pix_fmt_name(avctx->pix_fmt);
1170                         report(" pix %s\n", pfn ? pfn : "(unkn)");
1171                         double secs = to_secs(st->duration, st->time_base);
1172                         int64_t length = secs * frame_rate + 0.5;
1173                         report("    %jd frms %0.2f secs", length, secs);
1174                         int hrs = secs/3600;  secs -= hrs*3600;
1175                         int mins = secs/60;  secs -= mins*60;
1176                         report("  %d:%02d:%05.2f\n", hrs, mins, secs);
1177
1178                 }
1179                 else if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1180                         int sample_rate = avctx->sample_rate;
1181                         const char *fmt = av_get_sample_fmt_name(avctx->sample_fmt);
1182                         report("  audio %s",desc ? desc->name : " (unkn)");
1183                         report(" %dch %s %d",avctx->channels, fmt, sample_rate);
1184                         int sample_bits = av_get_bits_per_sample(avctx->codec_id);
1185                         report(" %dbits\n", sample_bits);
1186                         double secs = to_secs(st->duration, st->time_base);
1187                         int64_t length = secs * sample_rate + 0.5;
1188                         report("    %jd smpl %0.2f secs", length, secs);
1189                         int hrs = secs/3600;  secs -= hrs*3600;
1190                         int mins = secs/60;  secs -= mins*60;
1191                         report("  %d:%02d:%05.2f\n", hrs, mins, secs);
1192                 }
1193                 else
1194                         report("  codec_type unknown\n");
1195         }
1196         report("\n");
1197         for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
1198                 report("program %d", i+1);
1199                 AVProgram *pgrm = fmt_ctx->programs[i];
1200                 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j )
1201                         report(", %d", pgrm->stream_index[j]);
1202                 report("\n");
1203         }
1204         report("\n");
1205         AVDictionaryEntry *tag = 0;
1206         while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
1207                 report("%s=%s\n", tag->key, tag->value);
1208
1209         if( !len ) --cp;
1210         *cp = 0;
1211         return cp - text;
1212 #undef report
1213 }
1214
1215
1216 int FFMPEG::init_decoder(const char *filename)
1217 {
1218         ff_lock("FFMPEG::init_decoder");
1219         av_register_all();
1220         char file_opts[BCTEXTLEN];
1221         char *bp = strrchr(strcpy(file_opts, filename), '/');
1222         char *sp = strrchr(!bp ? file_opts : bp, '.');
1223         FILE *fp = 0;
1224         if( sp ) {
1225                 strcpy(sp, ".opts");
1226                 fp = fopen(file_opts, "r");
1227         }
1228         if( fp ) {
1229                 read_options(fp, file_opts, opts);
1230                 fclose(fp);
1231         }
1232         else
1233                 load_options("decode.opts", opts);
1234         AVDictionary *fopts = 0;
1235         av_dict_copy(&fopts, opts, 0);
1236         int ret = avformat_open_input(&fmt_ctx, filename, NULL, &fopts);
1237         av_dict_free(&fopts);
1238         if( ret >= 0 )
1239                 ret = avformat_find_stream_info(fmt_ctx, NULL);
1240         if( !ret ) {
1241                 decoding = -1;
1242         }
1243         ff_unlock();
1244         return !ret ? 0 : 1;
1245 }
1246
1247 int FFMPEG::open_decoder()
1248 {
1249         struct stat st;
1250         if( stat(fmt_ctx->filename, &st) < 0 ) {
1251                 eprintf("FFMPEG::open_decoder: can't stat file: %s\n",
1252                         fmt_ctx->filename);
1253                 return 1;
1254         }
1255
1256         int64_t file_bits = 8 * st.st_size;
1257         if( !fmt_ctx->bit_rate && opt_duration > 0 )
1258                 fmt_ctx->bit_rate = file_bits / opt_duration;
1259
1260         int estimated = 0;
1261         if( fmt_ctx->bit_rate > 0 ) {
1262                 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1263                         AVStream *st = fmt_ctx->streams[i];
1264                         if( st->duration != AV_NOPTS_VALUE ) continue;
1265                         if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
1266                         st->duration = av_rescale(file_bits, st->time_base.den,
1267                                 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
1268                         estimated = 1;
1269                 }
1270         }
1271         if( estimated )
1272                 printf("FFMPEG::open_decoder: some stream times estimated\n");
1273
1274         ff_lock("FFMPEG::open_decoder");
1275         int bad_time = 0;
1276         for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1277                 AVStream *st = fmt_ctx->streams[i];
1278                 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
1279                 AVCodecContext *avctx = st->codec;
1280                 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1281                         has_video = 1;
1282                         FFVideoStream *vid = new FFVideoStream(this, st, i);
1283                         int vidx = ffvideo.size();
1284                         vstrm_index.append(ffidx(vidx, 0));
1285                         ffvideo.append(vid);
1286                         vid->width = avctx->width;
1287                         vid->height = avctx->height;
1288                         AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
1289                         vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
1290                         double secs = to_secs(st->duration, st->time_base);
1291                         vid->length = secs * vid->frame_rate;
1292                         vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
1293                         vid->nudge = st->start_time;
1294                         vid->reading = -1;
1295                         if( opt_video_filter )
1296                                 vid->create_filter(opt_video_filter, avctx,avctx);
1297                 }
1298                 else if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1299                         has_audio = 1;
1300                         FFAudioStream *aud = new FFAudioStream(this, st, i);
1301                         int aidx = ffaudio.size();
1302                         ffaudio.append(aud);
1303                         aud->channel0 = astrm_index.size();
1304                         aud->channels = avctx->channels;
1305                         for( int ch=0; ch<aud->channels; ++ch )
1306                                 astrm_index.append(ffidx(aidx, ch));
1307                         aud->sample_rate = avctx->sample_rate;
1308                         double secs = to_secs(st->duration, st->time_base);
1309                         aud->length = secs * aud->sample_rate;
1310                         if( avctx->sample_fmt != AV_SAMPLE_FMT_FLT ) {
1311                                 uint64_t layout = av_get_default_channel_layout(avctx->channels);
1312                                 if( !layout ) layout = ((uint64_t)1<<aud->channels) - 1;
1313                                 aud->resample_context = swr_alloc_set_opts(NULL,
1314                                         layout, AV_SAMPLE_FMT_FLT, avctx->sample_rate,
1315                                         layout, avctx->sample_fmt, avctx->sample_rate,
1316                                         0, NULL);
1317                                 swr_init(aud->resample_context);
1318                         }
1319                         aud->nudge = st->start_time;
1320                         aud->reading = -1;
1321                         if( opt_audio_filter )
1322                                 aud->create_filter(opt_audio_filter, avctx,avctx);
1323                 }
1324         }
1325         if( bad_time )
1326                 printf("FFMPEG::open_decoder: some stream have bad times\n");
1327         ff_unlock();
1328         return 0;
1329 }
1330
1331
1332 int FFMPEG::init_encoder(const char *filename)
1333 {
1334         int fd = ::open(filename,O_WRONLY);
1335         if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
1336         if( fd < 0 ) {
1337                 eprintf("FFMPEG::init_encoder: bad file path: %s\n", filename);
1338                 return 1;
1339         }
1340         ::close(fd);
1341         int ret = get_file_format();
1342         if( ret > 0 ) {
1343                 eprintf("FFMPEG::init_encoder: bad file format: %s\n", filename);
1344                 return 1;
1345         }
1346         if( ret < 0 ) {
1347                 eprintf("FFMPEG::init_encoder: mismatch audio/video file format: %s\n", filename);
1348                 return 1;
1349         }
1350         ff_lock("FFMPEG::init_encoder");
1351         av_register_all();
1352         avformat_alloc_output_context2(&fmt_ctx, 0, file_format, filename);
1353         if( !fmt_ctx ) {
1354                 eprintf("FFMPEG::init_encoder: failed: %s\n", filename);
1355                 ret = 1;
1356         }
1357         if( !ret ) {
1358                 encoding = -1;
1359                 load_options("encode.opts", opts);
1360         }
1361         ff_unlock();
1362         start_muxer();
1363         return ret;
1364 }
1365
1366 int FFMPEG::open_encoder(const char *type, const char *spec)
1367 {
1368
1369         Asset *asset = file_base->asset;
1370         char *filename = asset->path;
1371         AVDictionary *sopts = 0;
1372         av_dict_copy(&sopts, opts, 0);
1373         char option_path[BCTEXTLEN];
1374         set_option_path(option_path, "%s/%s.opts", type, type);
1375         read_options(option_path, sopts);
1376         get_option_path(option_path, type, spec);
1377         char format_name[BCSTRLEN], codec_name[BCTEXTLEN];
1378         char bsfilter[BCSTRLEN], bsargs[BCTEXTLEN];
1379         if( get_encoder(option_path, format_name, codec_name, bsfilter, bsargs) ) {
1380                 eprintf("FFMPEG::open_encoder: get_encoder failed %s:%s\n",
1381                         option_path, filename);
1382                 return 1;
1383         }
1384
1385         int ret = 0;
1386         ff_lock("FFMPEG::open_encoder");
1387         FFStream *fst = 0;
1388         AVStream *st = 0;
1389
1390         const AVCodecDescriptor *codec_desc = 0;
1391         AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
1392         if( !codec ) {
1393                 eprintf("FFMPEG::open_encoder: cant find codec %s:%s\n",
1394                         codec_name, filename);
1395                 ret = 1;
1396         }
1397         if( !ret ) {
1398                 codec_desc = avcodec_descriptor_get(codec->id);
1399                 if( !codec_desc ) {
1400                         eprintf("FFMPEG::open_encoder: unknown codec %s:%s\n",
1401                                 codec_name, filename);
1402                         ret = 1;
1403                 }
1404         }
1405         if( !ret ) {
1406                 st = avformat_new_stream(fmt_ctx, 0);
1407                 if( !st ) {
1408                         eprintf("FFMPEG::open_encoder: cant create stream %s:%s\n",
1409                                 codec_name, filename);
1410                         ret = 1;
1411                 }
1412         } 
1413         if( !ret ) {
1414                 AVCodecContext *ctx = st->codec;
1415                 switch( codec_desc->type ) {
1416                 case AVMEDIA_TYPE_AUDIO: {
1417                         if( has_audio ) {
1418                                 eprintf("FFMPEG::open_encoder: duplicate audio %s:%s\n",
1419                                         codec_name, filename);
1420                                 ret = 1;
1421                                 break;
1422                         }
1423                         has_audio = 1;
1424                         if( scan_options(asset->ff_audio_options, sopts) ) {
1425                                 eprintf("FFMPEG::open_encoder: bad audio options %s:%s\n",
1426                                         codec_name, filename);
1427                                 ret = 1;
1428                                 break;
1429                         }
1430                         if( asset->ff_audio_bitrate > 0 ) {
1431                                 char arg[BCSTRLEN];
1432                                 sprintf(arg, "%d", asset->ff_audio_bitrate);
1433                                 av_dict_set(&sopts, "b", arg, 0);
1434                         }
1435                         int aidx = ffaudio.size();
1436                         int idx = aidx + ffvideo.size();
1437                         FFAudioStream *aud = new FFAudioStream(this, st, idx);
1438                         ffaudio.append(aud);  fst = aud;
1439                         aud->sample_rate = asset->sample_rate;
1440                         ctx->channels = aud->channels = asset->channels;
1441                         for( int ch=0; ch<aud->channels; ++ch )
1442                                 astrm_index.append(ffidx(aidx, ch));
1443                         ctx->channel_layout =  av_get_default_channel_layout(ctx->channels);
1444                         ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
1445                         if( !ctx->sample_rate ) {
1446                                 eprintf("FFMPEG::open_audio_encode:"
1447                                         " check_sample_rate failed %s\n", filename);
1448                                 ret = 1;
1449                                 break;
1450                         }
1451                         ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
1452                         ctx->sample_fmt = codec->sample_fmts[0];
1453                         uint64_t layout = av_get_default_channel_layout(ctx->channels);
1454                         aud->resample_context = swr_alloc_set_opts(NULL,
1455                                 layout, ctx->sample_fmt, aud->sample_rate,
1456                                 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
1457                                 0, NULL);
1458                         swr_init(aud->resample_context);
1459                         aud->writing = -1;
1460                         break; }
1461                 case AVMEDIA_TYPE_VIDEO: {
1462                         if( has_video ) {
1463                                 eprintf("FFMPEG::open_encoder: duplicate video %s:%s\n",
1464                                         codec_name, filename);
1465                                 ret = 1;
1466                                 break;
1467                         }
1468                         has_video = 1;
1469                         if( scan_options(asset->ff_video_options, sopts) ) {
1470                                 eprintf("FFMPEG::open_encoder: bad video options %s:%s\n",
1471                                         codec_name, filename);
1472                                 ret = 1;
1473                                 break;
1474                         }
1475                         if( asset->ff_video_bitrate > 0 ) {
1476                                 char arg[BCSTRLEN];
1477                                 sprintf(arg, "%d", asset->ff_video_bitrate);
1478                                 av_dict_set(&sopts, "b", arg, 0);
1479                         }
1480                         else if( asset->ff_video_quality > 0 ) {
1481                                 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
1482                                 ctx->qmin    = ctx->qmax =  asset->ff_video_quality;
1483                                 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
1484                                 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
1485                                 ctx->flags |= CODEC_FLAG_QSCALE;
1486                                 char arg[BCSTRLEN];
1487                                 av_dict_set(&sopts, "flags", "+qscale", 0);
1488                                 sprintf(arg, "%d", asset->ff_video_quality);
1489                                 av_dict_set(&sopts, "qscale", arg, 0);
1490                                 sprintf(arg, "%d", ctx->global_quality);
1491                                 av_dict_set(&sopts, "global_quality", arg, 0);
1492                         }
1493                         int vidx = ffvideo.size();
1494                         int idx = vidx + ffaudio.size();
1495                         FFVideoStream *vid = new FFVideoStream(this, st, idx);
1496                         vstrm_index.append(ffidx(vidx, 0));
1497                         ffvideo.append(vid);  fst = vid;
1498                         vid->width = asset->width;
1499                         ctx->width = (vid->width+3) & ~3;
1500                         vid->height = asset->height;
1501                         ctx->height = (vid->height+3) & ~3;
1502                         vid->frame_rate = asset->frame_rate;
1503                         ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset->aspect_ratio);
1504                         ctx->pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
1505                         AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
1506                         if( !frame_rate.num || !frame_rate.den ) {
1507                                 eprintf("FFMPEG::open_audio_encode:"
1508                                         " check_frame_rate failed %s\n", filename);
1509                                 ret = 1;
1510                                 break;
1511                         }
1512                         ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
1513                         st->time_base = ctx->time_base;
1514                         vid->writing = -1;
1515                         break; }
1516                 default:
1517                         eprintf("FFMPEG::open_encoder: not audio/video, %s:%s\n",
1518                                 codec_name, filename);
1519                         ret = 1;
1520                 }
1521         }
1522         if( !ret ) {
1523                 ret = avcodec_open2(st->codec, codec, &sopts);
1524                 if( ret < 0 ) {
1525                         ff_err(ret,"FFMPEG::open_encoder");
1526                         eprintf("FFMPEG::open_encoder: open failed %s:%s\n",
1527                                 codec_name, filename);
1528                         ret = 1;
1529                 }
1530                 else
1531                         ret = 0;
1532         }
1533         if( !ret ) {
1534                 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
1535                         st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
1536                 if( fst && bsfilter[0] )
1537                         fst->add_bsfilter(bsfilter, !bsargs[0] ? 0 : bsargs);
1538         }
1539
1540         ff_unlock();
1541         av_dict_free(&sopts);
1542         return ret;
1543 }
1544
1545 int FFMPEG::close_encoder()
1546 {
1547         stop_muxer();
1548         if( encoding > 0 ) {
1549                 av_write_trailer(fmt_ctx);
1550                 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
1551                         avio_closep(&fmt_ctx->pb);
1552         }
1553         encoding = 0;
1554         return 0;
1555 }
1556
1557 int FFMPEG::decode_activate()
1558 {
1559         if( decoding < 0 ) {
1560                 decoding = 0;
1561                 int npgrms = fmt_ctx->nb_programs;
1562                 for( int i=0; i<npgrms; ++i ) {
1563                         AVProgram *pgrm = fmt_ctx->programs[i];
1564                         // first start time video stream
1565                         int64_t vstart_time = -1;
1566                         for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1567                                 int st_idx = pgrm->stream_index[j];
1568                                 AVStream *st = fmt_ctx->streams[st_idx];
1569                                 AVCodecContext *avctx = st->codec;
1570                                 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1571                                         if( st->start_time == AV_NOPTS_VALUE ) continue;
1572                                         vstart_time = st->start_time;
1573                                         break;
1574                                 }
1575                         }
1576                         // max start time audio stream
1577                         int64_t astart_time = -1;
1578                         for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1579                                 int st_idx = pgrm->stream_index[j];
1580                                 AVStream *st = fmt_ctx->streams[st_idx];
1581                                 AVCodecContext *avctx = st->codec;
1582                                 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1583                                         if( st->start_time == AV_NOPTS_VALUE ) continue;
1584                                         if( astart_time > st->start_time ) continue;
1585                                         astart_time = st->start_time;
1586                                 }
1587                         }
1588                         if( astart_time < 0 || vstart_time < 0 ) continue;
1589                         // match program streams to max start_time
1590                         int64_t nudge = vstart_time > astart_time ? vstart_time : astart_time;
1591                         for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1592                                 int st_idx = pgrm->stream_index[j];
1593                                 AVStream *st = fmt_ctx->streams[st_idx];
1594                                 AVCodecContext *avctx = st->codec;
1595                                 if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1596                                         for( int k=0; k<ffaudio.size(); ++k ) {
1597                                                 if( ffaudio[k]->idx == st_idx )
1598                                                         ffaudio[k]->nudge = nudge;
1599                                         }
1600                                 }
1601                                 else if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1602                                         for( int k=0; k<ffvideo.size(); ++k ) {
1603                                                 if( ffvideo[k]->idx == st_idx )
1604                                                         ffvideo[k]->nudge = nudge;
1605                                         }
1606                                 }
1607                         }
1608                 }
1609                 int64_t vstart_time = 0, astart_time = 0;
1610                 int nstreams = fmt_ctx->nb_streams;
1611                 for( int i=0; i<nstreams; ++i ) {
1612                         AVStream *st = fmt_ctx->streams[i];
1613                         AVCodecContext *avctx = st->codec;
1614                         switch( avctx->codec_type ) {
1615                         case AVMEDIA_TYPE_VIDEO:
1616                                 if( st->start_time == AV_NOPTS_VALUE ) continue;
1617                                 if( vstart_time >= st->start_time ) continue;
1618                                 vstart_time = st->start_time;
1619                                 break;
1620                         case AVMEDIA_TYPE_AUDIO:
1621                                 if( st->start_time == AV_NOPTS_VALUE ) continue;
1622                                 if( astart_time >= st->start_time ) continue;
1623                                 astart_time = st->start_time;
1624                         default: break;
1625                         }
1626                 }
1627                 int64_t nudge = vstart_time > astart_time ? vstart_time : astart_time;
1628                 for( int k=0; k<ffvideo.size(); ++k ) {
1629                         if( ffvideo[k]->nudge != AV_NOPTS_VALUE ) continue;
1630                         ffvideo[k]->nudge = nudge;
1631                 }
1632                 for( int k=0; k<ffaudio.size(); ++k ) {
1633                         if( ffaudio[k]->nudge != AV_NOPTS_VALUE ) continue;
1634                         ffaudio[k]->nudge = nudge;
1635                 }
1636                 decoding = 1;
1637         }
1638         return decoding;
1639 }
1640
1641 int FFMPEG::encode_activate()
1642 {
1643         if( encoding < 0 ) {
1644                 encoding = 0;
1645                 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
1646                     avio_open(&fmt_ctx->pb, fmt_ctx->filename, AVIO_FLAG_WRITE) < 0 ) {
1647                         fprintf(stderr, "FFMPEG::encode_activate: err opening : %s\n",
1648                                 fmt_ctx->filename);
1649                         return 1;
1650                 }
1651
1652                 AVDictionary *fopts = 0;
1653                 char option_path[BCTEXTLEN];
1654                 set_option_path(option_path, "format/%s", file_format);
1655                 read_options(option_path, fopts);
1656                 int ret = avformat_write_header(fmt_ctx, &fopts);
1657                 av_dict_free(&fopts);
1658                 if( ret < 0 ) {
1659                         fprintf(stderr, "FFMPEG::encode_activate: write header failed %s\n",
1660                                 fmt_ctx->filename);
1661                         return 1;
1662                 }
1663                 encoding = 1;
1664         }
1665         return encoding;
1666 }
1667
1668 int FFMPEG::audio_seek(int stream, int64_t pos)
1669 {
1670         int aidx = astrm_index[stream].st_idx;
1671         FFAudioStream *aud = ffaudio[aidx];
1672         aud->audio_seek(pos);
1673         aud->seek_pos = aud->curr_pos = pos;
1674         return 0;
1675 }
1676
1677 int FFMPEG::video_seek(int stream, int64_t pos)
1678 {
1679         int vidx = vstrm_index[stream].st_idx;
1680         FFVideoStream *vid = ffvideo[vidx];
1681         vid->video_seek(pos);
1682         vid->seek_pos = vid->curr_pos = pos;
1683         return 0;
1684 }
1685
1686
1687 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
1688 {
1689         if( !has_audio || chn >= astrm_index.size() ) return -1;
1690         int aidx = astrm_index[chn].st_idx;
1691         FFAudioStream *aud = ffaudio[aidx];
1692         if( aud->load(pos, len) < len ) return -1;
1693         int ch = astrm_index[chn].st_ch;
1694         return aud->read(samples,len,ch);
1695 }
1696
1697 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
1698 {
1699         if( !has_video || layer >= vstrm_index.size() ) return -1;
1700         int vidx = vstrm_index[layer].st_idx;
1701         FFVideoStream *vid = ffvideo[vidx];
1702         return vid->load(vframe, pos);
1703 }
1704
1705 int FFMPEG::encode(int stream, double **samples, int len)
1706 {
1707         FFAudioStream *aud = ffaudio[stream];
1708         return aud->encode(samples, len);
1709 }
1710
1711
1712 int FFMPEG::encode(int stream, VFrame *frame)
1713 {
1714         FFVideoStream *vid = ffvideo[stream];
1715         return vid->encode(frame);
1716 }
1717
1718 void FFMPEG::start_muxer()
1719 {
1720         if( !running() ) {
1721                 done = 0;
1722                 start();
1723         }
1724 }
1725
1726 void FFMPEG::stop_muxer()
1727 {
1728         if( running() ) {
1729                 done = 1;
1730                 mux_lock->unlock();
1731                 join();
1732         }
1733 }
1734
1735 void FFMPEG::flow_off()
1736 {
1737         if( !flow ) return;
1738         flow_lock->lock("FFMPEG::flow_off");
1739         flow = 0;
1740 }
1741
1742 void FFMPEG::flow_on()
1743 {
1744         if( flow ) return;
1745         flow = 1;
1746         flow_lock->unlock();
1747 }
1748
1749 void FFMPEG::flow_ctl()
1750 {
1751         while( !flow ) {
1752                 flow_lock->lock("FFMPEG::flow_ctl");
1753                 flow_lock->unlock();
1754         }
1755 }
1756
1757 int FFMPEG::mux_audio(FFrame *frm)
1758 {
1759         FFPacket pkt;
1760         AVStream *st = frm->fst->st;
1761         AVCodecContext *ctx = st->codec;
1762         AVFrame *frame = *frm;
1763         AVRational tick_rate = {1, ctx->sample_rate};
1764         frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
1765         int got_packet = 0;
1766         int ret = avcodec_encode_audio2(ctx, pkt, frame, &got_packet);
1767         if( ret >= 0 && got_packet ) {
1768                 frm->fst->bs_filter(pkt);
1769                 av_packet_rescale_ts(pkt, ctx->time_base, st->time_base);
1770                 pkt->stream_index = st->index;
1771                 ret = av_interleaved_write_frame(fmt_ctx, pkt);
1772         }
1773         if( ret < 0 )
1774                 ff_err(ret, "FFMPEG::mux_audio");
1775         return ret >= 0 ? 0 : 1;
1776 }
1777
1778 int FFMPEG::mux_video(FFrame *frm)
1779 {
1780         FFPacket pkt;
1781         AVStream *st = frm->fst->st;
1782         AVFrame *frame = *frm;
1783         frame->pts = frm->position;
1784         int ret = 1, got_packet = 0;
1785         if( fmt_ctx->oformat->flags & AVFMT_RAWPICTURE ) {
1786                 /* a hack to avoid data copy with some raw video muxers */
1787                 pkt->flags |= AV_PKT_FLAG_KEY;
1788                 pkt->stream_index  = st->index;
1789                 AVPicture *picture = (AVPicture *)frame;
1790                 pkt->data = (uint8_t *)picture;
1791                 pkt->size = sizeof(AVPicture);
1792                 pkt->pts = pkt->dts = frame->pts;
1793                 got_packet = 1;
1794         }
1795         else
1796                 ret = avcodec_encode_video2(st->codec, pkt, frame, &got_packet);
1797         if( ret >= 0 && got_packet ) {
1798                 frm->fst->bs_filter(pkt);
1799                 av_packet_rescale_ts(pkt, st->codec->time_base, st->time_base);
1800                 pkt->stream_index = st->index;
1801                 ret = av_interleaved_write_frame(fmt_ctx, pkt);
1802         }
1803         if( ret < 0 )
1804                 ff_err(ret, "FFMPEG::mux_video");
1805         return ret >= 0 ? 0 : 1;
1806 }
1807
1808 void FFMPEG::mux()
1809 {
1810         for(;;) {
1811                 double atm = -1, vtm = -1;
1812                 FFrame *afrm = 0, *vfrm = 0;
1813                 int demand = 0;
1814                 for( int i=0; i<ffaudio.size(); ++i ) {  // earliest audio
1815                         FFStream *fst = ffaudio[i];
1816                         if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
1817                         FFrame *frm = fst->frms.first;
1818                         if( !frm ) { if( !done ) return; continue; }
1819                         double tm = to_secs(frm->position, fst->st->codec->time_base);
1820                         if( atm < 0 || tm < atm ) { atm = tm;  afrm = frm; }
1821                 }
1822                 for( int i=0; i<ffvideo.size(); ++i ) {  // earliest video
1823                         FFStream *fst = ffvideo[i];
1824                         if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
1825                         FFrame *frm = fst->frms.first;
1826                         if( !frm ) { if( !done ) return; continue; }
1827                         double tm = to_secs(frm->position, fst->st->codec->time_base);
1828                         if( vtm < 0 || tm < vtm ) { vtm = tm;  vfrm = frm; }
1829                 }
1830                 if( !demand ) flow_off();
1831                 if( !afrm && !vfrm ) break;
1832                 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
1833                         vfrm->position, vfrm->fst->st->codec->time_base,
1834                         afrm->position, afrm->fst->st->codec->time_base);
1835                 FFrame *frm = v <= 0 ? vfrm : afrm;
1836                 if( frm == afrm ) mux_audio(frm);
1837                 if( frm == vfrm ) mux_video(frm);
1838                 frm->dequeue();
1839                 delete frm;
1840         }
1841 }
1842
1843 void FFMPEG::run()
1844 {
1845         while( !done ) {
1846                 mux_lock->lock("FFMPEG::run");
1847                 if( !done ) mux();
1848         }
1849         mux();
1850 }
1851
1852
1853 int FFMPEG::ff_total_audio_channels()
1854 {
1855         return astrm_index.size();
1856 }
1857
1858 int FFMPEG::ff_total_astreams()
1859 {
1860         return ffaudio.size();
1861 }
1862
1863 int FFMPEG::ff_audio_channels(int stream)
1864 {
1865         return ffaudio[stream]->channels;
1866 }
1867
1868 int FFMPEG::ff_sample_rate(int stream)
1869 {
1870         return ffaudio[stream]->sample_rate;
1871 }
1872
1873 const char* FFMPEG::ff_audio_format(int stream)
1874 {
1875         AVStream *st = ffaudio[stream]->st;
1876         AVCodecID id = st->codec->codec_id;
1877         const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
1878         return desc ? desc->name : "Unknown";
1879 }
1880
1881 int FFMPEG::ff_audio_pid(int stream)
1882 {
1883         return ffaudio[stream]->st->id;
1884 }
1885
1886 int64_t FFMPEG::ff_audio_samples(int stream)
1887 {
1888         return ffaudio[stream]->length;
1889 }
1890
1891 // find audio astream/channels with this program,
1892 //   or all program audio channels (astream=-1)
1893 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
1894 {
1895         channel_mask = 0;
1896         int pidx = -1;
1897         int vidx = ffvideo[vstream]->idx;
1898         // find first program with this video stream
1899         for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
1900                 AVProgram *pgrm = fmt_ctx->programs[i];
1901                 for( int j=0;  pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
1902                         int st_idx = pgrm->stream_index[j];
1903                         AVStream *st = fmt_ctx->streams[st_idx];
1904                         if( st->codec->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
1905                         if( st_idx == vidx ) pidx = i;
1906                 }
1907         }
1908         if( pidx < 0 ) return -1;
1909         int ret = -1;
1910         int64_t channels = 0;
1911         AVProgram *pgrm = fmt_ctx->programs[pidx];
1912         for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1913                 int aidx = pgrm->stream_index[j];
1914                 AVStream *st = fmt_ctx->streams[aidx];
1915                 if( st->codec->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
1916                 if( astream > 0 ) { --astream;  continue; }
1917                 int astrm = -1;
1918                 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
1919                         if( ffaudio[i]->idx == aidx ) astrm = i;
1920                 if( astrm >= 0 ) {
1921                         if( ret < 0 ) ret = astrm;
1922                         int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
1923                         channels |= mask << ffaudio[astrm]->channel0;
1924                 }
1925                 if( !astream ) break;
1926         }
1927         channel_mask = channels;
1928         return ret;
1929 }
1930
1931
1932 int FFMPEG::ff_total_video_layers()
1933 {
1934         return vstrm_index.size();
1935 }
1936
1937 int FFMPEG::ff_total_vstreams()
1938 {
1939         return ffvideo.size();
1940 }
1941
1942 int FFMPEG::ff_video_width(int stream)
1943 {
1944         return ffvideo[stream]->width;
1945 }
1946
1947 int FFMPEG::ff_video_height(int stream)
1948 {
1949         return ffvideo[stream]->height;
1950 }
1951
1952 int FFMPEG::ff_set_video_width(int stream, int width)
1953 {
1954         int w = ffvideo[stream]->width;
1955         ffvideo[stream]->width = width;
1956         return w;
1957 }
1958
1959 int FFMPEG::ff_set_video_height(int stream, int height)
1960 {
1961         int h = ffvideo[stream]->height;
1962         ffvideo[stream]->height = height;
1963         return h;
1964 }
1965
1966 int FFMPEG::ff_coded_width(int stream)
1967 {
1968         AVStream *st = ffvideo[stream]->st;
1969         return st->codec->coded_width;
1970 }
1971
1972 int FFMPEG::ff_coded_height(int stream)
1973 {
1974         AVStream *st = ffvideo[stream]->st;
1975         return st->codec->coded_height;
1976 }
1977
1978 float FFMPEG::ff_aspect_ratio(int stream)
1979 {
1980         return ffvideo[stream]->aspect_ratio;
1981 }
1982
1983 const char* FFMPEG::ff_video_format(int stream)
1984 {
1985         AVStream *st = ffvideo[stream]->st;
1986         AVCodecID id = st->codec->codec_id;
1987         const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
1988         return desc ? desc->name : "Unknown";
1989 }
1990
1991 double FFMPEG::ff_frame_rate(int stream)
1992 {
1993         return ffvideo[stream]->frame_rate;
1994 }
1995
1996 int64_t FFMPEG::ff_video_frames(int stream)
1997 {
1998         return ffvideo[stream]->length;
1999 }
2000
2001 int FFMPEG::ff_video_pid(int stream)
2002 {
2003         return ffvideo[stream]->st->id;
2004 }
2005
2006
2007 int FFMPEG::ff_cpus()
2008 {
2009         return file_base->file->cpus;
2010 }
2011
2012 int FFVideoStream::create_filter(const char *filter_spec,
2013                 AVCodecContext *src_ctx, AVCodecContext *sink_ctx)
2014 {
2015         avfilter_register_all();
2016         filter_graph = avfilter_graph_alloc();
2017         AVFilter *buffersrc = avfilter_get_by_name("buffer");
2018         AVFilter *buffersink = avfilter_get_by_name("buffersink");
2019
2020         int ret = 0;  char args[BCTEXTLEN];
2021         snprintf(args, sizeof(args),
2022                 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
2023                 src_ctx->width, src_ctx->height, src_ctx->pix_fmt,
2024                 st->time_base.num, st->time_base.den,
2025                 src_ctx->sample_aspect_ratio.num, src_ctx->sample_aspect_ratio.den);
2026         if( ret >= 0 )
2027                 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2028                         args, NULL, filter_graph);
2029         if( ret >= 0 )
2030                 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2031                         NULL, NULL, filter_graph);
2032         if( ret >= 0 )
2033                 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
2034                         (uint8_t*)&sink_ctx->pix_fmt, sizeof(sink_ctx->pix_fmt),
2035                         AV_OPT_SEARCH_CHILDREN);
2036         if( ret < 0 )
2037                 ff_err(ret, "FFVideoStream::create_filter");
2038         else
2039                 ret = FFStream::create_filter(filter_spec);
2040         return ret >= 0 ? 0 : 1;
2041 }
2042
2043 int FFAudioStream::create_filter(const char *filter_spec,
2044                 AVCodecContext *src_ctx, AVCodecContext *sink_ctx)
2045 {
2046         avfilter_register_all();
2047         filter_graph = avfilter_graph_alloc();
2048         AVFilter *buffersrc = avfilter_get_by_name("abuffer");
2049         AVFilter *buffersink = avfilter_get_by_name("abuffersink");
2050         int ret = 0;  char args[BCTEXTLEN];
2051         snprintf(args, sizeof(args),
2052                 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
2053                 st->time_base.num, st->time_base.den, src_ctx->sample_rate,
2054                 av_get_sample_fmt_name(src_ctx->sample_fmt), src_ctx->channel_layout);
2055         if( ret >= 0 )
2056                 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2057                         args, NULL, filter_graph);
2058         if( ret >= 0 )
2059                 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2060                         NULL, NULL, filter_graph);
2061         if( ret >= 0 )
2062                 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
2063                         (uint8_t*)&sink_ctx->sample_fmt, sizeof(sink_ctx->sample_fmt),
2064                         AV_OPT_SEARCH_CHILDREN);
2065         if( ret >= 0 )
2066                 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
2067                         (uint8_t*)&sink_ctx->channel_layout,
2068                         sizeof(sink_ctx->channel_layout), AV_OPT_SEARCH_CHILDREN);
2069         if( ret >= 0 )
2070                 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
2071                         (uint8_t*)&sink_ctx->sample_rate, sizeof(sink_ctx->sample_rate),
2072                         AV_OPT_SEARCH_CHILDREN);
2073         if( ret < 0 )
2074                 ff_err(ret, "FFAudioStream::create_filter");
2075         else
2076                 ret = FFStream::create_filter(filter_spec);
2077         return ret >= 0 ? 0 : 1;
2078 }
2079
2080 int FFStream::create_filter(const char *filter_spec)
2081 {
2082         /* Endpoints for the filter graph. */
2083         AVFilterInOut *outputs = avfilter_inout_alloc();
2084         outputs->name = av_strdup("in");
2085         outputs->filter_ctx = buffersrc_ctx;
2086         outputs->pad_idx = 0;
2087         outputs->next = 0;
2088
2089         AVFilterInOut *inputs  = avfilter_inout_alloc();
2090         inputs->name = av_strdup("out");
2091         inputs->filter_ctx = buffersink_ctx;
2092         inputs->pad_idx = 0;
2093         inputs->next = 0;
2094
2095         int ret = !outputs->name || !inputs->name ? -1 : 0;
2096         if( ret >= 0 )
2097                 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
2098                         &inputs, &outputs, NULL);
2099         if( ret >= 0 )
2100                 ret = avfilter_graph_config(filter_graph, NULL);
2101
2102         if( ret < 0 )
2103                 ff_err(ret, "FFStream::create_filter");
2104         avfilter_inout_free(&inputs);
2105         avfilter_inout_free(&outputs);
2106         return ret;
2107 }
2108
2109 void FFStream::add_bsfilter(const char *bsf, const char *ap)
2110 {
2111         bsfilter.append(new BSFilter(bsf,ap));
2112 }
2113
2114 int FFStream::bs_filter(AVPacket *pkt)
2115 {
2116         if( !bsfilter.size() ) return 0;
2117         av_packet_split_side_data(pkt);
2118
2119         int ret = 0;
2120         for( int i=0; i<bsfilter.size(); ++i ) {
2121                 AVPacket bspkt = *pkt;
2122                 ret = av_bitstream_filter_filter(bsfilter[i]->bsfc,
2123                          st->codec, bsfilter[i]->args, &bspkt.data, &bspkt.size,
2124                          pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY);
2125                 if( ret < 0 ) break;
2126                 int size = bspkt.size;
2127                 uint8_t *data = bspkt.data;
2128                 if( !ret && bspkt.data != pkt->data ) {
2129                         size = bspkt.size;
2130                         data = (uint8_t *)av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
2131                         if( !data ) { ret = AVERROR(ENOMEM);  break; }
2132                         memcpy(data, bspkt.data, size);
2133                         memset(data+size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2134                         ret = 1;
2135                 }
2136                 if( ret > 0 ) {
2137                         pkt->side_data = 0;  pkt->side_data_elems = 0;
2138                         av_free_packet(pkt);
2139                         ret = av_packet_from_data(&bspkt, data, size);
2140                         if( ret < 0 ) break;
2141                 }
2142                 *pkt = bspkt;
2143         }
2144         if( ret < 0 )
2145                 ff_err(ret,"FFStream::bs_filter");
2146         return ret;
2147 }
2148