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