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