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