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