add binfolder path relative filters, fix gbrp color model, vwdw timebar tweaks, title...
[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 #include <ctype.h>
11
12 // work arounds (centos)
13 #include <lzma.h>
14 #ifndef INT64_MAX
15 #define INT64_MAX 9223372036854775807LL
16 #endif
17 #define MAX_RETRY 1000
18
19 #include "asset.h"
20 #include "bccmodels.h"
21 #include "bchash.h"
22 #include "edl.h"
23 #include "edlsession.h"
24 #include "file.h"
25 #include "fileffmpeg.h"
26 #include "filesystem.h"
27 #include "ffmpeg.h"
28 #include "indexfile.h"
29 #include "interlacemodes.h"
30 #include "libdv.h"
31 #include "libmjpeg.h"
32 #include "mainerror.h"
33 #include "mwindow.h"
34 #include "vframe.h"
35
36 #ifdef FFMPEG3
37 #define url filename
38 #else
39 #define av_register_all(s)
40 #define avfilter_register_all(s)
41 #endif
42
43 #define VIDEO_INBUF_SIZE 0x10000
44 #define AUDIO_INBUF_SIZE 0x10000
45 #define VIDEO_REFILL_THRESH 0
46 #define AUDIO_REFILL_THRESH 0x1000
47 #define AUDIO_MIN_FRAME_SZ 128
48
49 Mutex FFMPEG::fflock("FFMPEG::fflock");
50
51 static void ff_err(int ret, const char *fmt, ...)
52 {
53         char msg[BCTEXTLEN];
54         va_list ap;
55         va_start(ap, fmt);
56         vsnprintf(msg, sizeof(msg), fmt, ap);
57         va_end(ap);
58         char errmsg[BCSTRLEN];
59         av_strerror(ret, errmsg, sizeof(errmsg));
60         fprintf(stderr,_("%s  err: %s\n"),msg, errmsg);
61 }
62
63 void FFPacket::init()
64 {
65         av_init_packet(&pkt);
66         pkt.data = 0; pkt.size = 0;
67 }
68 void FFPacket::finit()
69 {
70         av_packet_unref(&pkt);
71 }
72
73 FFrame::FFrame(FFStream *fst)
74 {
75         this->fst = fst;
76         frm = av_frame_alloc();
77         init = fst->init_frame(frm);
78 }
79
80 FFrame::~FFrame()
81 {
82         av_frame_free(&frm);
83 }
84
85 void FFrame::queue(int64_t pos)
86 {
87         position = pos;
88         fst->queue(this);
89 }
90
91 void FFrame::dequeue()
92 {
93         fst->dequeue(this);
94 }
95
96 int FFAudioStream::read(float *fp, long len)
97 {
98         long n = len * nch;
99         float *op = outp;
100         while( n > 0 ) {
101                 int k = lmt - op;
102                 if( k > n ) k = n;
103                 n -= k;
104                 while( --k >= 0 ) *fp++ = *op++;
105                 if( op >= lmt ) op = bfr;
106         }
107         return len;
108 }
109
110 void FFAudioStream::realloc(long nsz, int nch, long len)
111 {
112         long bsz = nsz * nch;
113         float *np = new float[bsz];
114         inp = np + read(np, len) * nch;
115         outp = np;
116         lmt = np + bsz;
117         this->nch = nch;
118         sz = nsz;
119         delete [] bfr;  bfr = np;
120 }
121
122 void FFAudioStream::realloc(long nsz, int nch)
123 {
124         if( nsz > sz || this->nch != nch ) {
125                 long len = this->nch != nch ? 0 : hpos;
126                 if( len > sz ) len = sz;
127                 iseek(len);
128                 realloc(nsz, nch, len);
129         }
130 }
131
132 void FFAudioStream::reserve(long nsz, int nch)
133 {
134         long len = (inp - outp) / nch;
135         nsz += len;
136         if( nsz > sz || this->nch != nch ) {
137                 if( this->nch != nch ) len = 0;
138                 realloc(nsz, nch, len);
139                 return;
140         }
141         if( (len*=nch) > 0 && bfr != outp )
142                 memmove(bfr, outp, len*sizeof(*bfr));
143         outp = bfr;
144         inp = bfr + len;
145 }
146
147 long FFAudioStream::used()
148 {
149         long len = inp>=outp ? inp-outp : inp-bfr + lmt-outp;
150         return len / nch;
151 }
152 long FFAudioStream::avail()
153 {
154         float *in1 = inp+1;
155         if( in1 >= lmt ) in1 = bfr;
156         long len = outp >= in1 ? outp-in1 : outp-bfr + lmt-in1;
157         return len / nch;
158 }
159 void FFAudioStream::reset_history()
160 {
161         inp = outp = bfr;
162         hpos = 0;
163         memset(bfr, 0, lmt-bfr);
164 }
165
166 void FFAudioStream::iseek(int64_t ofs)
167 {
168         if( ofs > hpos ) ofs = hpos;
169         if( ofs > sz ) ofs = sz;
170         outp = inp - ofs*nch;
171         if( outp < bfr ) outp += sz*nch;
172 }
173
174 float *FFAudioStream::get_outp(int ofs)
175 {
176         float *ret = outp;
177         outp += ofs*nch;
178         return ret;
179 }
180
181 int64_t FFAudioStream::put_inp(int ofs)
182 {
183         inp += ofs*nch;
184         return (inp-outp) / nch;
185 }
186
187 int FFAudioStream::write(const float *fp, 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++ = *fp++;
196                 if( ip >= lmt ) ip = bfr;
197         }
198         inp = ip;
199         hpos += len;
200         return len;
201 }
202
203 int FFAudioStream::zero(long len)
204 {
205         long n = len * nch;
206         float *ip = inp;
207         while( n > 0 ) {
208                 int k = lmt - ip;
209                 if( k > n ) k = n;
210                 n -= k;
211                 while( --k >= 0 ) *ip++ = 0;
212                 if( ip >= lmt ) ip = bfr;
213         }
214         inp = ip;
215         hpos += len;
216         return len;
217 }
218
219 // does not advance outp
220 int FFAudioStream::read(double *dp, long len, int ch)
221 {
222         long n = len;
223         float *op = outp + ch;
224         float *lmt1 = lmt + nch-1;
225         while( n > 0 ) {
226                 int k = (lmt1 - op) / nch;
227                 if( k > n ) k = n;
228                 n -= k;
229                 while( --k >= 0 ) { *dp++ = *op;  op += nch; }
230                 if( op >= lmt ) op -= sz*nch;
231         }
232         return len;
233 }
234
235 // load linear buffer, no wrapping allowed, does not advance inp
236 int FFAudioStream::write(const double *dp, long len, int ch)
237 {
238         long n = len;
239         float *ip = inp + ch;
240         while( --n >= 0 ) { *ip = *dp++;  ip += nch; }
241         return len;
242 }
243
244
245 FFStream::FFStream(FFMPEG *ffmpeg, AVStream *st, int fidx)
246 {
247         this->ffmpeg = ffmpeg;
248         this->st = st;
249         this->fidx = fidx;
250         frm_lock = new Mutex("FFStream::frm_lock");
251         fmt_ctx = 0;
252         avctx = 0;
253         filter_graph = 0;
254         buffersrc_ctx = 0;
255         buffersink_ctx = 0;
256         frm_count = 0;
257         nudge = AV_NOPTS_VALUE;
258         seek_pos = curr_pos = 0;
259         seeked = 1;  eof = 0;
260         reading = writing = 0;
261         flushed = 0;
262         need_packet = 1;
263         frame = fframe = 0;
264         bsfc = 0;
265         stats_fp = 0;
266         stats_filename = 0;
267         stats_in = 0;
268         pass = 0;
269 }
270
271 FFStream::~FFStream()
272 {
273         if( reading > 0 || writing > 0 ) avcodec_close(avctx);
274         if( avctx ) avcodec_free_context(&avctx);
275         if( fmt_ctx ) avformat_close_input(&fmt_ctx);
276         if( bsfc ) av_bsf_free(&bsfc);
277         while( frms.first ) frms.remove(frms.first);
278         if( filter_graph ) avfilter_graph_free(&filter_graph);
279         if( frame ) av_frame_free(&frame);
280         if( fframe ) av_frame_free(&fframe);
281         delete frm_lock;
282         if( stats_fp ) fclose(stats_fp);
283         if( stats_in ) av_freep(&stats_in);
284         delete [] stats_filename;
285 }
286
287 void FFStream::ff_lock(const char *cp)
288 {
289         FFMPEG::fflock.lock(cp);
290 }
291
292 void FFStream::ff_unlock()
293 {
294         FFMPEG::fflock.unlock();
295 }
296
297 void FFStream::queue(FFrame *frm)
298 {
299         frm_lock->lock("FFStream::queue");
300         frms.append(frm);
301         ++frm_count;
302         frm_lock->unlock();
303         ffmpeg->mux_lock->unlock();
304 }
305
306 void FFStream::dequeue(FFrame *frm)
307 {
308         frm_lock->lock("FFStream::dequeue");
309         --frm_count;
310         frms.remove_pointer(frm);
311         frm_lock->unlock();
312 }
313
314 int FFStream::encode_activate()
315 {
316         if( writing < 0 )
317                 writing = ffmpeg->encode_activate();
318         return writing;
319 }
320
321 int FFStream::decode_activate()
322 {
323         if( reading < 0 && (reading=ffmpeg->decode_activate()) > 0 ) {
324                 ff_lock("FFStream::decode_activate");
325                 reading = 0;
326                 AVDictionary *copts = 0;
327                 av_dict_copy(&copts, ffmpeg->opts, 0);
328                 int ret = 0;
329                 // this should be avformat_copy_context(), but no copy avail
330                 ret = avformat_open_input(&fmt_ctx,
331                         ffmpeg->fmt_ctx->url, ffmpeg->fmt_ctx->iformat, &copts);
332                 if( ret >= 0 ) {
333                         ret = avformat_find_stream_info(fmt_ctx, 0);
334                         st = fmt_ctx->streams[fidx];
335                         load_markers();
336                 }
337                 if( ret >= 0 && st != 0 ) {
338                         AVCodecID codec_id = st->codecpar->codec_id;
339                         AVCodec *decoder = avcodec_find_decoder(codec_id);
340                         avctx = avcodec_alloc_context3(decoder);
341                         if( !avctx ) {
342                                 eprintf(_("cant allocate codec context\n"));
343                                 ret = AVERROR(ENOMEM);
344                         }
345                         if( ret >= 0 ) {
346                                 avcodec_parameters_to_context(avctx, st->codecpar);
347                                 if( !av_dict_get(copts, "threads", NULL, 0) )
348                                         avctx->thread_count = ffmpeg->ff_cpus();
349                                 ret = avcodec_open2(avctx, decoder, &copts);
350                         }
351                         if( ret >= 0 ) {
352                                 reading = 1;
353                         }
354                         else
355                                 eprintf(_("open decoder failed\n"));
356                 }
357                 else
358                         eprintf(_("can't clone input file\n"));
359                 av_dict_free(&copts);
360                 ff_unlock();
361         }
362         return reading;
363 }
364
365 int FFStream::read_packet()
366 {
367         av_packet_unref(ipkt);
368         int ret = av_read_frame(fmt_ctx, ipkt);
369         if( ret < 0 ) {
370                 st_eof(1);
371                 if( ret == AVERROR_EOF ) return 0;
372                 ff_err(ret, "FFStream::read_packet: av_read_frame failed\n");
373                 flushed = 1;
374                 return -1;
375         }
376         return 1;
377 }
378
379 int FFStream::decode(AVFrame *frame)
380 {
381         int ret = 0;
382         int retries = MAX_RETRY;
383
384         while( ret >= 0 && !flushed && --retries >= 0 ) {
385                 if( need_packet ) {
386                         if( (ret=read_packet()) < 0 ) break;
387                         AVPacket *pkt = ret > 0 ? (AVPacket*)ipkt : 0;
388                         if( pkt ) {
389                                 if( pkt->stream_index != st->index ) continue;
390                                 if( !pkt->data | !pkt->size ) continue;
391                         }
392                         if( (ret=avcodec_send_packet(avctx, pkt)) < 0 ) {
393                                 ff_err(ret, "FFStream::decode: avcodec_send_packet failed\n");
394                                 break;
395                         }
396                         need_packet = 0;
397                         retries = MAX_RETRY;
398                 }
399                 if( (ret=decode_frame(frame)) > 0 ) break;
400                 if( !ret ) {
401                         need_packet = 1;
402                         flushed = st_eof();
403                 }
404         }
405
406         if( retries < 0 ) {
407                 fprintf(stderr, "FFStream::decode: Retry limit\n");
408                 ret = 0;
409         }
410         if( ret < 0 )
411                 fprintf(stderr, "FFStream::decode: failed\n");
412         return ret;
413 }
414
415 int FFStream::load_filter(AVFrame *frame)
416 {
417         int ret = av_buffersrc_add_frame_flags(buffersrc_ctx, frame, 0);
418         if( ret < 0 )
419                 eprintf(_("av_buffersrc_add_frame_flags failed\n"));
420         return ret;
421 }
422
423 int FFStream::read_filter(AVFrame *frame)
424 {
425         int ret = av_buffersink_get_frame(buffersink_ctx, frame);
426         if( ret < 0 ) {
427                 if( ret == AVERROR(EAGAIN) ) return 0;
428                 if( ret == AVERROR_EOF ) { st_eof(1); return -1; }
429                 ff_err(ret, "FFStream::read_filter: av_buffersink_get_frame failed\n");
430                 return ret;
431         }
432         return 1;
433 }
434
435 int FFStream::read_frame(AVFrame *frame)
436 {
437         av_frame_unref(frame);
438         if( !filter_graph || !buffersrc_ctx || !buffersink_ctx )
439                 return decode(frame);
440         if( !fframe && !(fframe=av_frame_alloc()) ) {
441                 fprintf(stderr, "FFStream::read_frame: av_frame_alloc failed\n");
442                 return -1;
443         }
444         int ret = -1;
445         while( !flushed && !(ret=read_filter(frame)) ) {
446                 if( (ret=decode(fframe)) < 0 ) break;
447                 if( ret > 0 && (ret=load_filter(fframe)) < 0 ) break;
448         }
449         return ret;
450 }
451
452 int FFStream::write_packet(FFPacket &pkt)
453 {
454         int ret = 0;
455         if( !bsfc ) {
456                 av_packet_rescale_ts(pkt, avctx->time_base, st->time_base);
457                 pkt->stream_index = st->index;
458                 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, pkt);
459         }
460         else {
461                 ret = av_bsf_send_packet(bsfc, pkt);
462                 while( ret >= 0 ) {
463                         FFPacket bs;
464                         if( (ret=av_bsf_receive_packet(bsfc, bs)) < 0 ) {
465                                 if( ret == AVERROR(EAGAIN) ) return 0;
466                                 if( ret == AVERROR_EOF ) return -1;
467                                 break;
468                         }
469                         av_packet_rescale_ts(bs, avctx->time_base, st->time_base);
470                         bs->stream_index = st->index;
471                         ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, bs);
472                 }
473         }
474         if( ret < 0 )
475                 ff_err(ret, "FFStream::write_packet: write packet failed\n");
476         return ret;
477 }
478
479 int FFStream::encode_frame(AVFrame *frame)
480 {
481         int pkts = 0, ret = 0;
482         for( int retry=100; --retry>=0; ) {
483                 if( frame || !pkts )
484                         ret = avcodec_send_frame(avctx, frame);
485                 if( !ret && frame ) return pkts;
486                 if( ret < 0 && ret != AVERROR(EAGAIN) ) break;
487                 FFPacket opkt;
488                 ret = avcodec_receive_packet(avctx, opkt);
489                 if( !frame && ret == AVERROR_EOF ) return pkts;
490                 if( ret < 0 ) break;
491                 ret = write_packet(opkt);
492                 if( ret < 0 ) break;
493                 ++pkts;
494                 if( frame && stats_fp ) {
495                         ret = write_stats_file();
496                         if( ret < 0 ) break;
497                 }
498         }
499         ff_err(ret, "FFStream::encode_frame: encode failed\n");
500         return -1;
501 }
502
503 int FFStream::flush()
504 {
505         if( writing < 0 )
506                 return -1;
507         int ret = encode_frame(0);
508         if( ret >= 0 && stats_fp ) {
509                 ret = write_stats_file();
510                 close_stats_file();
511         }
512         if( ret < 0 )
513                 ff_err(ret, "FFStream::flush");
514         return ret >= 0 ? 0 : 1;
515 }
516
517
518 int FFStream::open_stats_file()
519 {
520         stats_fp = fopen(stats_filename,"w");
521         return stats_fp ? 0 : AVERROR(errno);
522 }
523
524 int FFStream::close_stats_file()
525 {
526         if( stats_fp ) {
527                 fclose(stats_fp);  stats_fp = 0;
528         }
529         return 0;
530 }
531
532 int FFStream::read_stats_file()
533 {
534         int64_t len = 0;  struct stat stats_st;
535         int fd = open(stats_filename, O_RDONLY);
536         int ret = fd >= 0 ? 0: ENOENT;
537         if( !ret && fstat(fd, &stats_st) )
538                 ret = EINVAL;
539         if( !ret ) {
540                 len = stats_st.st_size;
541                 stats_in = (char *)av_malloc(len+1);
542                 if( !stats_in )
543                         ret = ENOMEM;
544         }
545         if( !ret && read(fd, stats_in, len+1) != len )
546                 ret = EIO;
547         if( !ret ) {
548                 stats_in[len] = 0;
549                 avctx->stats_in = stats_in;
550         }
551         if( fd >= 0 )
552                 close(fd);
553         return !ret ? 0 : AVERROR(ret);
554 }
555
556 int FFStream::write_stats_file()
557 {
558         int ret = 0;
559         if( avctx->stats_out && (ret=strlen(avctx->stats_out)) > 0 ) {
560                 int len = fwrite(avctx->stats_out, 1, ret, stats_fp);
561                 if( ret != len )
562                         ff_err(ret = AVERROR(errno), "FFStream::write_stats_file");
563         }
564         return ret;
565 }
566
567 int FFStream::init_stats_file()
568 {
569         int ret = 0;
570         if( (pass & 2) && (ret = read_stats_file()) < 0 )
571                 ff_err(ret, "stat file read: %s", stats_filename);
572         if( (pass & 1) && (ret=open_stats_file()) < 0 )
573                 ff_err(ret, "stat file open: %s", stats_filename);
574         return ret >= 0 ? 0 : ret;
575 }
576
577 int FFStream::seek(int64_t no, double rate)
578 {
579 // default ffmpeg native seek
580         int npkts = 1;
581         int64_t pos = no, pkt_pos = -1;
582         IndexMarks *index_markers = get_markers();
583         if( index_markers && index_markers->size() > 1 ) {
584                 IndexMarks &marks = *index_markers;
585                 int i = marks.find(pos);
586                 int64_t n = i < 0 ? (i=0) : marks[i].no;
587 // if indexed seek point not too far away (<30 secs), use index
588                 if( no-n < 30*rate ) {
589                         if( n < 0 ) n = 0;
590                         pos = n;
591                         if( i < marks.size() ) pkt_pos = marks[i].pos;
592                         npkts = MAX_RETRY;
593                 }
594         }
595         if( pos == curr_pos ) return 0;
596         double secs = pos < 0 ? 0. : pos / rate;
597         AVRational time_base = st->time_base;
598         int64_t tstmp = time_base.num > 0 ? secs * time_base.den/time_base.num : 0;
599         if( !tstmp ) {
600                 if( st->nb_index_entries > 0 ) tstmp = st->index_entries[0].timestamp;
601                 else if( st->start_time != AV_NOPTS_VALUE ) tstmp = st->start_time;
602                 else if( st->first_dts != AV_NOPTS_VALUE ) tstmp = st->first_dts;
603                 else tstmp = INT64_MIN+1;
604         }
605         else if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
606         int idx = st->index;
607 #if 0
608 // seek all streams using the default timebase.
609 //   this is how ffmpeg and ffplay work.  stream seeks are less tested.
610         tstmp = av_rescale_q(tstmp, time_base, AV_TIME_BASE_Q);
611         idx = -1;
612 #endif
613
614         avcodec_flush_buffers(avctx);
615         avformat_flush(fmt_ctx);
616 #if 0
617         int64_t seek = tstmp;
618         int flags = AVSEEK_FLAG_ANY;
619         if( !(fmt_ctx->iformat->flags & AVFMT_NO_BYTE_SEEK) && pkt_pos >= 0 ) {
620                 seek = pkt_pos;
621                 flags = AVSEEK_FLAG_BYTE;
622         }
623         int ret = avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, seek, INT64_MAX, flags);
624 #else
625 // finds the first index frame below the target time
626         int flags = AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_ANY;
627         int ret = av_seek_frame(fmt_ctx, idx, tstmp, flags);
628 #endif
629         int retry = MAX_RETRY;
630         while( ret >= 0 ) {
631                 need_packet = 0;  flushed = 0;
632                 seeked = 1;  st_eof(0);
633 // read up to retry packets, limited to npkts in stream, and not pkt.pos past pkt_pos
634                 while( --retry >= 0 ) {
635                         if( read_packet() <= 0 ) { ret = -1;  break; }
636                         if( ipkt->stream_index != st->index ) continue;
637                         if( !ipkt->data || !ipkt->size ) continue;
638                         if( pkt_pos >= 0 && ipkt->pos >= pkt_pos ) break;
639                         if( --npkts <= 0 ) break;
640                         int64_t pkt_ts = ipkt->dts != AV_NOPTS_VALUE ? ipkt->dts : ipkt->pts;
641                         if( pkt_ts == AV_NOPTS_VALUE ) continue;
642                         if( pkt_ts >= tstmp ) break;
643                 }
644                 if( retry < 0 ) {
645                         fprintf(stderr,"FFStream::seek: retry limit, pos=%jd tstmp=%jd\n",pos,tstmp);
646                         ret = -1;
647                 }
648                 if( ret < 0 ) break;
649                 ret = avcodec_send_packet(avctx, ipkt);
650                 if( !ret ) break;
651 //some codecs need more than one pkt to resync
652                 if( ret == AVERROR_INVALIDDATA ) ret = 0;
653                 if( ret < 0 ) {
654                         ff_err(ret, "FFStream::avcodec_send_packet failed\n");
655                         break;
656                 }
657         }
658         if( ret < 0 ) {
659 printf("** seek fail %jd, %jd\n", pos, tstmp);
660                 seeked = need_packet = 0;
661                 st_eof(flushed=1);
662                 return -1;
663         }
664 //printf("seeked pos = %ld, %ld\n", pos, tstmp);
665         seek_pos = curr_pos = pos;
666         return 0;
667 }
668
669 FFAudioStream::FFAudioStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
670  : FFStream(ffmpeg, strm, fidx)
671 {
672         this->idx = idx;
673         channel0 = channels = 0;
674         sample_rate = 0;
675         mbsz = 0;
676         frame_sz = AUDIO_MIN_FRAME_SZ;
677         length = 0;
678         resample_context = 0;
679         swr_ichs = swr_ifmt = swr_irate = 0;
680
681         aud_bfr_sz = 0;
682         aud_bfr = 0;
683
684 // history buffer
685         nch = 2;
686         sz = 0x10000;
687         long bsz = sz * nch;
688         bfr = new float[bsz];
689         lmt = bfr + bsz;
690         reset_history();
691 }
692
693 FFAudioStream::~FFAudioStream()
694 {
695         if( resample_context ) swr_free(&resample_context);
696         delete [] aud_bfr;
697         delete [] bfr;
698 }
699
700 void FFAudioStream::init_swr(int ichs, int ifmt, int irate)
701 {
702         if( resample_context ) {
703                 if( swr_ichs == ichs && swr_ifmt == ifmt && swr_irate == irate )
704                         return;
705                 swr_free(&resample_context);
706         }
707         swr_ichs = ichs;  swr_ifmt = ifmt;  swr_irate = irate;
708         if( ichs == channels && ifmt == AV_SAMPLE_FMT_FLT && irate == sample_rate )
709                 return;
710         uint64_t ilayout = av_get_default_channel_layout(ichs);
711         if( !ilayout ) ilayout = ((uint64_t)1<<ichs) - 1;
712         uint64_t olayout = av_get_default_channel_layout(channels);
713         if( !olayout ) olayout = ((uint64_t)1<<channels) - 1;
714         resample_context = swr_alloc_set_opts(NULL,
715                 olayout, AV_SAMPLE_FMT_FLT, sample_rate,
716                 ilayout, (AVSampleFormat)ifmt, irate,
717                 0, NULL);
718         if( resample_context )
719                 swr_init(resample_context);
720 }
721
722 int FFAudioStream::get_samples(float *&samples, uint8_t **data, int len)
723 {
724         samples = *(float **)data;
725         if( resample_context ) {
726                 if( len > aud_bfr_sz ) {
727                         delete [] aud_bfr;
728                         aud_bfr = 0;
729                 }
730                 if( !aud_bfr ) {
731                         aud_bfr_sz = len;
732                         aud_bfr = new float[aud_bfr_sz*channels];
733                 }
734                 int ret = swr_convert(resample_context,
735                         (uint8_t**)&aud_bfr, aud_bfr_sz, (const uint8_t**)data, len);
736                 if( ret < 0 ) {
737                         ff_err(ret, "FFAudioStream::get_samples: swr_convert failed\n");
738                         return -1;
739                 }
740                 samples = aud_bfr;
741                 len = ret;
742         }
743         return len;
744 }
745
746 int FFAudioStream::load_history(uint8_t **data, int len)
747 {
748         float *samples;
749         len = get_samples(samples, data, len);
750         if( len > 0 ) {
751                 // biggest user bfr since seek + frame
752                 realloc(mbsz + len + 1, channels);
753                 write(samples, len);
754         }
755         return len;
756 }
757
758 int FFAudioStream::decode_frame(AVFrame *frame)
759 {
760         int first_frame = seeked;  seeked = 0;
761         int ret = avcodec_receive_frame(avctx, frame);
762         if( ret < 0 ) {
763                 if( first_frame || ret == AVERROR(EAGAIN) ) return 0;
764                 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
765                 ff_err(ret, "FFAudioStream::decode_frame: Could not read audio frame\n");
766                 return -1;
767         }
768         int64_t pkt_ts = frame->best_effort_timestamp;
769         if( pkt_ts != AV_NOPTS_VALUE )
770                 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * sample_rate + 0.5;
771         return 1;
772 }
773
774 int FFAudioStream::encode_activate()
775 {
776         if( writing >= 0 ) return writing;
777         if( !avctx->codec ) return writing = 0;
778         frame_sz = avctx->codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE ?
779                 10000 : avctx->frame_size;
780         return FFStream::encode_activate();
781 }
782
783 int64_t FFAudioStream::load_buffer(double ** const sp, int len)
784 {
785         reserve(len+1, st->codecpar->channels);
786         for( int ch=0; ch<nch; ++ch )
787                 write(sp[ch], len, ch);
788         return put_inp(len);
789 }
790
791 int FFAudioStream::in_history(int64_t pos)
792 {
793         if( pos > curr_pos ) return 0;
794         int64_t len = hpos;
795         if( len > sz ) len = sz;
796         if( pos < curr_pos - len ) return 0;
797         return 1;
798 }
799
800
801 int FFAudioStream::init_frame(AVFrame *frame)
802 {
803         frame->nb_samples = frame_sz;
804         frame->format = avctx->sample_fmt;
805         frame->channel_layout = avctx->channel_layout;
806         frame->sample_rate = avctx->sample_rate;
807         int ret = av_frame_get_buffer(frame, 0);
808         if (ret < 0)
809                 ff_err(ret, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
810         return ret;
811 }
812
813 int FFAudioStream::load(int64_t pos, int len)
814 {
815         if( audio_seek(pos) < 0 ) return -1;
816         if( !frame && !(frame=av_frame_alloc()) ) {
817                 fprintf(stderr, "FFAudioStream::load: av_frame_alloc failed\n");
818                 return -1;
819         }
820         if( mbsz < len ) mbsz = len;
821         int64_t end_pos = pos + len;
822         int ret = 0, i = len / frame_sz + MAX_RETRY;
823         while( ret>=0 && !flushed && curr_pos<end_pos && --i>=0 ) {
824                 ret = read_frame(frame);
825                 if( ret > 0 && frame->nb_samples > 0 ) {
826                         init_swr(frame->channels, frame->format, frame->sample_rate);
827                         load_history(&frame->extended_data[0], frame->nb_samples);
828                         curr_pos += frame->nb_samples;
829                 }
830         }
831         if( end_pos > curr_pos ) {
832                 zero(end_pos - curr_pos);
833                 curr_pos = end_pos;
834         }
835         len = curr_pos - pos;
836         iseek(len);
837         return len;
838 }
839
840 int FFAudioStream::audio_seek(int64_t pos)
841 {
842         if( decode_activate() <= 0 ) return -1;
843         if( !st->codecpar ) return -1;
844         if( in_history(pos) ) return 0;
845         if( pos == curr_pos ) return 0;
846         reset_history();  mbsz = 0;
847 // guarentee preload > 1sec samples
848         if( seek(pos-sample_rate, sample_rate) < 0 ) return -1;
849         return 1;
850 }
851
852 int FFAudioStream::encode(double **samples, int len)
853 {
854         if( encode_activate() <= 0 ) return -1;
855         ffmpeg->flow_ctl();
856         int ret = 0;
857         int64_t count = samples ? load_buffer(samples, len) : used();
858         int frame_sz1 = samples ? frame_sz-1 : 0;
859         FFrame *frm = 0;
860
861         while( ret >= 0 && count > frame_sz1 ) {
862                 frm = new FFrame(this);
863                 if( (ret=frm->initted()) < 0 ) break;
864                 AVFrame *frame = *frm;
865                 len = count >= frame_sz ? frame_sz : count;
866                 float *bfrp = get_outp(len);
867                 ret =  swr_convert(resample_context,
868                         (uint8_t **)frame->extended_data, len,
869                         (const uint8_t **)&bfrp, len);
870                 if( ret < 0 ) {
871                         ff_err(ret, "FFAudioStream::encode: swr_convert failed\n");
872                         break;
873                 }
874                 frame->nb_samples = len;
875                 frm->queue(curr_pos);
876                 frm = 0;
877                 curr_pos += len;
878                 count -= len;
879         }
880
881         delete frm;
882         return ret >= 0 ? 0 : 1;
883 }
884
885 int FFAudioStream::drain()
886 {
887         return encode(0,0);
888 }
889
890 int FFAudioStream::encode_frame(AVFrame *frame)
891 {
892         return FFStream::encode_frame(frame);
893 }
894
895 int FFAudioStream::write_packet(FFPacket &pkt)
896 {
897         return FFStream::write_packet(pkt);
898 }
899
900 void FFAudioStream::load_markers()
901 {
902         IndexState *index_state = ffmpeg->file_base->asset->index_state;
903         if( !index_state || idx >= index_state->audio_markers.size() ) return;
904         if( index_state->marker_status == MARKERS_NOTTESTED ) return;
905         FFStream::load_markers(*index_state->audio_markers[idx], sample_rate);
906 }
907
908 IndexMarks *FFAudioStream::get_markers()
909 {
910         IndexState *index_state = ffmpeg->file_base->asset->index_state;
911         if( !index_state || idx >= index_state->audio_markers.size() ) return 0;
912         return index_state->audio_markers[idx];
913 }
914
915 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
916  : FFStream(ffmpeg, strm, fidx)
917 {
918         this->idx = idx;
919         width = height = 0;
920         frame_rate = 0;
921         aspect_ratio = 0;
922         length = 0;
923         interlaced = 0;
924         top_field_first = 0;
925 }
926
927 FFVideoStream::~FFVideoStream()
928 {
929 }
930
931 int FFVideoStream::decode_frame(AVFrame *frame)
932 {
933         int first_frame = seeked;  seeked = 0;
934         int ret = avcodec_receive_frame(avctx, frame);
935         if( ret < 0 ) {
936                 if( first_frame || ret == AVERROR(EAGAIN) ) return 0;
937                 if( ret == AVERROR(EAGAIN) ) return 0;
938                 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
939                 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame\n");
940                 return -1;
941         }
942         int64_t pkt_ts = frame->best_effort_timestamp;
943         if( pkt_ts != AV_NOPTS_VALUE )
944                 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * frame_rate + 0.5;
945         return 1;
946 }
947
948 int FFVideoStream::load(VFrame *vframe, int64_t pos)
949 {
950         int ret = video_seek(pos);
951         if( ret < 0 ) return -1;
952         if( !frame && !(frame=av_frame_alloc()) ) {
953                 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
954                 return -1;
955         }
956         int i = MAX_RETRY + pos - curr_pos;
957         while( ret>=0 && !flushed && curr_pos<=pos && --i>=0 ) {
958                 ret = read_frame(frame);
959                 if( ret > 0 ) ++curr_pos;
960         }
961         if( frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0 )
962                 ret = -1;
963         if( ret >= 0 ) {
964                 ret = convert_cmodel(vframe, frame);
965         }
966         ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
967         return ret;
968 }
969
970 int FFVideoStream::video_seek(int64_t pos)
971 {
972         if( decode_activate() <= 0 ) return -1;
973         if( !st->codecpar ) return -1;
974         if( pos == curr_pos-1 && !seeked ) return 0;
975 // if close enough, just read up to current
976         int gop = avctx->gop_size;
977         if( gop < 4 ) gop = 4;
978         if( gop > 64 ) gop = 64;
979         int read_limit = curr_pos + 3*gop;
980         if( pos >= curr_pos && pos <= read_limit ) return 0;
981 // guarentee preload more than 2*gop frames
982         if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
983         return 1;
984 }
985
986 int FFVideoStream::init_frame(AVFrame *picture)
987 {
988         picture->format = avctx->pix_fmt;
989         picture->width  = avctx->width;
990         picture->height = avctx->height;
991         int ret = av_frame_get_buffer(picture, 32);
992         return ret;
993 }
994
995 int FFVideoStream::encode(VFrame *vframe)
996 {
997         if( encode_activate() <= 0 ) return -1;
998         ffmpeg->flow_ctl();
999         FFrame *picture = new FFrame(this);
1000         int ret = picture->initted();
1001         if( ret >= 0 ) {
1002                 AVFrame *frame = *picture;
1003                 frame->pts = curr_pos;
1004                 ret = convert_pixfmt(vframe, frame);
1005         }
1006         if( ret >= 0 ) {
1007                 picture->queue(curr_pos);
1008                 ++curr_pos;
1009         }
1010         else {
1011                 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
1012                 delete picture;
1013         }
1014         return ret >= 0 ? 0 : 1;
1015 }
1016
1017 int FFVideoStream::drain()
1018 {
1019         return 0;
1020 }
1021
1022 int FFVideoStream::encode_frame(AVFrame *frame)
1023 {
1024         if( frame ) {
1025                 frame->interlaced_frame = interlaced;
1026                 frame->top_field_first = top_field_first;
1027         }
1028         return FFStream::encode_frame(frame);
1029 }
1030
1031 int FFVideoStream::write_packet(FFPacket &pkt)
1032 {
1033         if( !(ffmpeg->fmt_ctx->oformat->flags & AVFMT_VARIABLE_FPS) )
1034                 pkt->duration = 1;
1035         return FFStream::write_packet(pkt);
1036 }
1037
1038 AVPixelFormat FFVideoConvert::color_model_to_pix_fmt(int color_model)
1039 {
1040         switch( color_model ) {
1041         case BC_YUV422:         return AV_PIX_FMT_YUYV422;
1042         case BC_RGB888:         return AV_PIX_FMT_RGB24;
1043         case BC_RGBA8888:       return AV_PIX_FMT_RGBA;
1044         case BC_BGR8888:        return AV_PIX_FMT_BGR0;
1045         case BC_BGR888:         return AV_PIX_FMT_BGR24;
1046         case BC_ARGB8888:       return AV_PIX_FMT_ARGB;
1047         case BC_ABGR8888:       return AV_PIX_FMT_ABGR;
1048         case BC_RGB8:           return AV_PIX_FMT_RGB8;
1049         case BC_YUV420P:        return AV_PIX_FMT_YUV420P;
1050         case BC_YUV422P:        return AV_PIX_FMT_YUV422P;
1051         case BC_YUV444P:        return AV_PIX_FMT_YUV444P;
1052         case BC_YUV411P:        return AV_PIX_FMT_YUV411P;
1053         case BC_RGB565:         return AV_PIX_FMT_RGB565;
1054         case BC_RGB161616:      return AV_PIX_FMT_RGB48LE;
1055         case BC_RGBA16161616:   return AV_PIX_FMT_RGBA64LE;
1056         case BC_AYUV16161616:   return AV_PIX_FMT_AYUV64LE;
1057         case BC_GBRP:           return AV_PIX_FMT_GBRP;
1058         default: break;
1059         }
1060
1061         return AV_PIX_FMT_NB;
1062 }
1063
1064 int FFVideoConvert::pix_fmt_to_color_model(AVPixelFormat pix_fmt)
1065 {
1066         switch (pix_fmt) {
1067         case AV_PIX_FMT_YUYV422:        return BC_YUV422;
1068         case AV_PIX_FMT_RGB24:          return BC_RGB888;
1069         case AV_PIX_FMT_RGBA:           return BC_RGBA8888;
1070         case AV_PIX_FMT_BGR0:           return BC_BGR8888;
1071         case AV_PIX_FMT_BGR24:          return BC_BGR888;
1072         case AV_PIX_FMT_ARGB:           return BC_ARGB8888;
1073         case AV_PIX_FMT_ABGR:           return BC_ABGR8888;
1074         case AV_PIX_FMT_RGB8:           return BC_RGB8;
1075         case AV_PIX_FMT_YUV420P:        return BC_YUV420P;
1076         case AV_PIX_FMT_YUV422P:        return BC_YUV422P;
1077         case AV_PIX_FMT_YUV444P:        return BC_YUV444P;
1078         case AV_PIX_FMT_YUV411P:        return BC_YUV411P;
1079         case AV_PIX_FMT_RGB565:         return BC_RGB565;
1080         case AV_PIX_FMT_RGB48LE:        return BC_RGB161616;
1081         case AV_PIX_FMT_RGBA64LE:       return BC_RGBA16161616;
1082         case AV_PIX_FMT_AYUV64LE:       return BC_AYUV16161616;
1083         case AV_PIX_FMT_GBRP:           return BC_GBRP;
1084         default: break;
1085         }
1086
1087         return -1;
1088 }
1089
1090 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip)
1091 {
1092         AVFrame *ipic = av_frame_alloc();
1093         int ret = convert_picture_vframe(frame, ip, ipic);
1094         av_frame_free(&ipic);
1095         return ret;
1096 }
1097
1098 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip, AVFrame *ipic)
1099 {
1100         int cmodel = frame->get_color_model();
1101         AVPixelFormat ofmt = color_model_to_pix_fmt(cmodel);
1102         if( ofmt == AV_PIX_FMT_NB ) return -1;
1103         int size = av_image_fill_arrays(ipic->data, ipic->linesize,
1104                 frame->get_data(), ofmt, frame->get_w(), frame->get_h(), 1);
1105         if( size < 0 ) return -1;
1106
1107         int bpp = BC_CModels::calculate_pixelsize(cmodel);
1108         int ysz = bpp * frame->get_w(), usz = ysz;
1109         switch( cmodel ) {
1110         case BC_YUV410P:
1111         case BC_YUV411P:
1112                 usz /= 2;
1113         case BC_YUV420P:
1114         case BC_YUV422P:
1115                 usz /= 2;
1116         case BC_YUV444P:
1117         case BC_GBRP:
1118                 // override av_image_fill_arrays() for planar types
1119                 ipic->data[0] = frame->get_y();  ipic->linesize[0] = ysz;
1120                 ipic->data[1] = frame->get_u();  ipic->linesize[1] = usz;
1121                 ipic->data[2] = frame->get_v();  ipic->linesize[2] = usz;
1122                 break;
1123         default:
1124                 ipic->data[0] = frame->get_data();
1125                 ipic->linesize[0] = frame->get_bytes_per_line();
1126                 break;
1127         }
1128
1129         AVPixelFormat pix_fmt = (AVPixelFormat)ip->format;
1130         convert_ctx = sws_getCachedContext(convert_ctx, ip->width, ip->height, pix_fmt,
1131                 frame->get_w(), frame->get_h(), ofmt, SWS_POINT, NULL, NULL, NULL);
1132         if( !convert_ctx ) {
1133                 fprintf(stderr, "FFVideoConvert::convert_picture_frame:"
1134                                 " sws_getCachedContext() failed\n");
1135                 return -1;
1136         }
1137         int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ip->height,
1138             ipic->data, ipic->linesize);
1139         if( ret < 0 ) {
1140                 ff_err(ret, "FFVideoConvert::convert_picture_frame: sws_scale() failed\n");
1141                 return -1;
1142         }
1143         return 0;
1144 }
1145
1146 int FFVideoConvert::convert_cmodel(VFrame *frame, AVFrame *ip)
1147 {
1148         // try direct transfer
1149         if( !convert_picture_vframe(frame, ip) ) return 1;
1150         // use indirect transfer
1151         AVPixelFormat ifmt = (AVPixelFormat)ip->format;
1152         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
1153         int max_bits = 0;
1154         for( int i = 0; i <desc->nb_components; ++i ) {
1155                 int bits = desc->comp[i].depth;
1156                 if( bits > max_bits ) max_bits = bits;
1157         }
1158         int imodel = pix_fmt_to_color_model(ifmt);
1159         int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1160         int cmodel = frame->get_color_model();
1161         int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1162         if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1163                 imodel = cmodel_is_yuv ?
1164                     (BC_CModels::has_alpha(cmodel) ?
1165                         BC_AYUV16161616 :
1166                         (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1167                     (BC_CModels::has_alpha(cmodel) ?
1168                         (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1169                         (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1170         }
1171         VFrame vframe(ip->width, ip->height, imodel);
1172         if( convert_picture_vframe(&vframe, ip) ) return -1;
1173         frame->transfer_from(&vframe);
1174         return 1;
1175 }
1176
1177 int FFVideoConvert::transfer_cmodel(VFrame *frame, AVFrame *ifp)
1178 {
1179         int ret = convert_cmodel(frame, ifp);
1180         if( ret > 0 ) {
1181                 const AVDictionary *src = ifp->metadata;
1182                 AVDictionaryEntry *t = NULL;
1183                 BC_Hash *hp = frame->get_params();
1184                 //hp->clear();
1185                 while( (t=av_dict_get(src, "", t, AV_DICT_IGNORE_SUFFIX)) )
1186                         hp->update(t->key, t->value);
1187         }
1188         return ret;
1189 }
1190
1191 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op)
1192 {
1193         AVFrame *opic = av_frame_alloc();
1194         int ret = convert_vframe_picture(frame, op, opic);
1195         av_frame_free(&opic);
1196         return ret;
1197 }
1198
1199 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op, AVFrame *opic)
1200 {
1201         int cmodel = frame->get_color_model();
1202         AVPixelFormat ifmt = color_model_to_pix_fmt(cmodel);
1203         if( ifmt == AV_PIX_FMT_NB ) return -1;
1204         int size = av_image_fill_arrays(opic->data, opic->linesize,
1205                  frame->get_data(), ifmt, frame->get_w(), frame->get_h(), 1);
1206         if( size < 0 ) return -1;
1207
1208         int bpp = BC_CModels::calculate_pixelsize(cmodel);
1209         int ysz = bpp * frame->get_w(), usz = ysz;
1210         switch( cmodel ) {
1211         case BC_YUV410P:
1212         case BC_YUV411P:
1213                 usz /= 2;
1214         case BC_YUV420P:
1215         case BC_YUV422P:
1216                 usz /= 2;
1217         case BC_YUV444P:
1218         case BC_GBRP:
1219                 // override av_image_fill_arrays() for planar types
1220                 opic->data[0] = frame->get_y();  opic->linesize[0] = ysz;
1221                 opic->data[1] = frame->get_u();  opic->linesize[1] = usz;
1222                 opic->data[2] = frame->get_v();  opic->linesize[2] = usz;
1223                 break;
1224         default:
1225                 opic->data[0] = frame->get_data();
1226                 opic->linesize[0] = frame->get_bytes_per_line();
1227                 break;
1228         }
1229
1230         AVPixelFormat ofmt = (AVPixelFormat)op->format;
1231         convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(),
1232                 ifmt, op->width, op->height, ofmt, SWS_POINT, NULL, NULL, NULL);
1233         if( !convert_ctx ) {
1234                 fprintf(stderr, "FFVideoConvert::convert_frame_picture:"
1235                                 " sws_getCachedContext() failed\n");
1236                 return -1;
1237         }
1238         int ret = sws_scale(convert_ctx, opic->data, opic->linesize, 0, frame->get_h(),
1239                         op->data, op->linesize);
1240         if( ret < 0 ) {
1241                 ff_err(ret, "FFVideoConvert::convert_frame_picture: sws_scale() failed\n");
1242                 return -1;
1243         }
1244         return 0;
1245 }
1246
1247 int FFVideoConvert::convert_pixfmt(VFrame *frame, AVFrame *op)
1248 {
1249         // try direct transfer
1250         if( !convert_vframe_picture(frame, op) ) return 1;
1251         // use indirect transfer
1252         int cmodel = frame->get_color_model();
1253         int max_bits = BC_CModels::calculate_pixelsize(cmodel) * 8;
1254         max_bits /= BC_CModels::components(cmodel);
1255         AVPixelFormat ofmt = (AVPixelFormat)op->format;
1256         int imodel = pix_fmt_to_color_model(ofmt);
1257         int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1258         int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1259         if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1260                 imodel = cmodel_is_yuv ?
1261                     (BC_CModels::has_alpha(cmodel) ?
1262                         BC_AYUV16161616 :
1263                         (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1264                     (BC_CModels::has_alpha(cmodel) ?
1265                         (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1266                         (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1267         }
1268         VFrame vframe(frame->get_w(), frame->get_h(), imodel);
1269         vframe.transfer_from(frame);
1270         if( !convert_vframe_picture(&vframe, op) ) return 1;
1271         return -1;
1272 }
1273
1274 int FFVideoConvert::transfer_pixfmt(VFrame *frame, AVFrame *ofp)
1275 {
1276         int ret = convert_pixfmt(frame, ofp);
1277         if( ret > 0 ) {
1278                 BC_Hash *hp = frame->get_params();
1279                 AVDictionary **dict = &ofp->metadata;
1280                 //av_dict_free(dict);
1281                 for( int i=0; i<hp->size(); ++i ) {
1282                         char *key = hp->get_key(i), *val = hp->get_value(i);
1283                         av_dict_set(dict, key, val, 0);
1284                 }
1285         }
1286         return ret;
1287 }
1288
1289 void FFVideoStream::load_markers()
1290 {
1291         IndexState *index_state = ffmpeg->file_base->asset->index_state;
1292         if( !index_state || idx >= index_state->video_markers.size() ) return;
1293         FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
1294 }
1295
1296 IndexMarks *FFVideoStream::get_markers()
1297 {
1298         IndexState *index_state = ffmpeg->file_base->asset->index_state;
1299         if( !index_state || idx >= index_state->video_markers.size() ) return 0;
1300         return !index_state ? 0 : index_state->video_markers[idx];
1301 }
1302
1303
1304 FFMPEG::FFMPEG(FileBase *file_base)
1305 {
1306         fmt_ctx = 0;
1307         this->file_base = file_base;
1308         memset(file_format,0,sizeof(file_format));
1309         mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
1310         flow_lock = new Condition(1,"FFStream::flow_lock",0);
1311         done = -1;
1312         flow = 1;
1313         decoding = encoding = 0;
1314         has_audio = has_video = 0;
1315         opts = 0;
1316         opt_duration = -1;
1317         opt_video_filter = 0;
1318         opt_audio_filter = 0;
1319         char option_path[BCTEXTLEN];
1320         set_option_path(option_path, "%s", "ffmpeg.opts");
1321         read_options(option_path, opts);
1322 }
1323
1324 FFMPEG::~FFMPEG()
1325 {
1326         ff_lock("FFMPEG::~FFMPEG()");
1327         close_encoder();
1328         ffaudio.remove_all_objects();
1329         ffvideo.remove_all_objects();
1330         if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1331         ff_unlock();
1332         delete flow_lock;
1333         delete mux_lock;
1334         av_dict_free(&opts);
1335         delete [] opt_video_filter;
1336         delete [] opt_audio_filter;
1337 }
1338
1339 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1340 {
1341         const int *p = codec->supported_samplerates;
1342         if( !p ) return sample_rate;
1343         while( *p != 0 ) {
1344                 if( *p == sample_rate ) return *p;
1345                 ++p;
1346         }
1347         return 0;
1348 }
1349
1350 static inline AVRational std_frame_rate(int i)
1351 {
1352         static const int m1 = 1001*12, m2 = 1000*12;
1353         static const int freqs[] = {
1354                 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1355                 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
1356         };
1357         int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1358         return (AVRational) { freq, 1001*12 };
1359 }
1360
1361 AVRational FFMPEG::check_frame_rate(AVCodec *codec, double frame_rate)
1362 {
1363         const AVRational *p = codec->supported_framerates;
1364         AVRational rate, best_rate = (AVRational) { 0, 0 };
1365         double max_err = 1.;  int i = 0;
1366         while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1367                 double framerate = (double) rate.num / rate.den;
1368                 double err = fabs(frame_rate/framerate - 1.);
1369                 if( err >= max_err ) continue;
1370                 max_err = err;
1371                 best_rate = rate;
1372         }
1373         return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1374 }
1375
1376 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1377 {
1378 #if 1
1379         double display_aspect = asset->width / (double)asset->height;
1380         double sample_aspect = display_aspect / asset->aspect_ratio;
1381         int width = 1000000, height = width * sample_aspect + 0.5;
1382         float w, h;
1383         MWindow::create_aspect_ratio(w, h, width, height);
1384         return (AVRational){(int)w, (int)h};
1385 #else
1386 // square pixels
1387         return (AVRational){1, 1};
1388 #endif
1389 }
1390
1391 AVRational FFMPEG::to_time_base(int sample_rate)
1392 {
1393         return (AVRational){1, sample_rate};
1394 }
1395
1396 int FFMPEG::get_fmt_score(AVSampleFormat dst_fmt, AVSampleFormat src_fmt)
1397 {
1398         int score = 0;
1399         int dst_planar = av_sample_fmt_is_planar(dst_fmt);
1400         int src_planar = av_sample_fmt_is_planar(src_fmt);
1401         if( dst_planar != src_planar ) ++score;
1402         int dst_bytes = av_get_bytes_per_sample(dst_fmt);
1403         int src_bytes = av_get_bytes_per_sample(src_fmt);
1404         score += (src_bytes > dst_bytes ? 100 : -10) * (src_bytes - dst_bytes);
1405         int src_packed = av_get_packed_sample_fmt(src_fmt);
1406         int dst_packed = av_get_packed_sample_fmt(dst_fmt);
1407         if( dst_packed == AV_SAMPLE_FMT_S32 && src_packed == AV_SAMPLE_FMT_FLT ) score += 20;
1408         if( dst_packed == AV_SAMPLE_FMT_FLT && src_packed == AV_SAMPLE_FMT_S32 ) score += 2;
1409         return score;
1410 }
1411
1412 AVSampleFormat FFMPEG::find_best_sample_fmt_of_list(
1413                 const AVSampleFormat *sample_fmts, AVSampleFormat src_fmt)
1414 {
1415         AVSampleFormat best = AV_SAMPLE_FMT_NONE;
1416         int best_score = get_fmt_score(best, src_fmt);
1417         for( int i=0; sample_fmts[i] >= 0; ++i ) {
1418                 AVSampleFormat sample_fmt = sample_fmts[i];
1419                 int score = get_fmt_score(sample_fmt, src_fmt);
1420                 if( score >= best_score ) continue;
1421                 best = sample_fmt;  best_score = score;
1422         }
1423         return best;
1424 }
1425
1426
1427 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
1428 {
1429         char *ep = path + BCTEXTLEN-1;
1430         strncpy(path, File::get_cindat_path(), ep-path);
1431         strncat(path, "/ffmpeg/", ep-path);
1432         path += strlen(path);
1433         va_list ap;
1434         va_start(ap, fmt);
1435         path += vsnprintf(path, ep-path, fmt, ap);
1436         va_end(ap);
1437         *path = 0;
1438 }
1439
1440 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
1441 {
1442         if( *spec == '/' )
1443                 strcpy(path, spec);
1444         else
1445                 set_option_path(path, "%s/%s", type, spec);
1446 }
1447
1448 int FFMPEG::get_format(char *format, const char *path, const char *spec)
1449 {
1450         char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
1451         get_option_path(option_path, path, spec);
1452         FILE *fp = fopen(option_path,"r");
1453         if( !fp ) return 1;
1454         int ret = 0;
1455         if( !fgets(line, sizeof(line), fp) ) ret = 1;
1456         if( !ret ) {
1457                 line[sizeof(line)-1] = 0;
1458                 ret = scan_option_line(line, format, codec);
1459         }
1460         fclose(fp);
1461         return ret;
1462 }
1463
1464 int FFMPEG::get_codec(char *codec, const char *path, const char *spec)
1465 {
1466         char option_path[BCTEXTLEN], line[BCTEXTLEN], format[BCTEXTLEN];
1467         get_option_path(option_path, path, spec);
1468         FILE *fp = fopen(option_path,"r");
1469         if( !fp ) return 1;
1470         int ret = 0;
1471         if( !fgets(line, sizeof(line), fp) ) ret = 1;
1472         fclose(fp);
1473         if( !ret ) {
1474                 line[sizeof(line)-1] = 0;
1475                 ret = scan_option_line(line, format, codec);
1476         }
1477         if( !ret ) {
1478                 char *vp = codec, *ep = vp+BCTEXTLEN-1;
1479                 while( vp < ep && *vp && *vp != '|' ) ++vp;
1480                 if( *vp == '|' ) --vp;
1481                 while( vp > codec && (*vp==' ' || *vp=='\t') ) *vp-- = 0;
1482         }
1483         return ret;
1484 }
1485
1486 int FFMPEG::get_file_format()
1487 {
1488         char audio_muxer[BCSTRLEN], video_muxer[BCSTRLEN];
1489         char audio_format[BCSTRLEN], video_format[BCSTRLEN];
1490         audio_muxer[0] = audio_format[0] = 0;
1491         video_muxer[0] = video_format[0] = 0;
1492         Asset *asset = file_base->asset;
1493         int ret = asset ? 0 : 1;
1494         if( !ret && asset->audio_data ) {
1495                 if( !(ret=get_format(audio_format, "audio", asset->acodec)) ) {
1496                         if( get_format(audio_muxer, "format", audio_format) ) {
1497                                 strcpy(audio_muxer, audio_format);
1498                                 audio_format[0] = 0;
1499                         }
1500                 }
1501         }
1502         if( !ret && asset->video_data ) {
1503                 if( !(ret=get_format(video_format, "video", asset->vcodec)) ) {
1504                         if( get_format(video_muxer, "format", video_format) ) {
1505                                 strcpy(video_muxer, video_format);
1506                                 video_format[0] = 0;
1507                         }
1508                 }
1509         }
1510         if( !ret && !audio_muxer[0] && !video_muxer[0] )
1511                 ret = 1;
1512         if( !ret && audio_muxer[0] && video_muxer[0] &&
1513             strcmp(audio_muxer, video_muxer) ) ret = -1;
1514         if( !ret && audio_format[0] && video_format[0] &&
1515             strcmp(audio_format, video_format) ) ret = -1;
1516         if( !ret )
1517                 strcpy(file_format, !audio_format[0] && !video_format[0] ?
1518                         (audio_muxer[0] ? audio_muxer : video_muxer) :
1519                         (audio_format[0] ? audio_format : video_format));
1520         return ret;
1521 }
1522
1523 int FFMPEG::scan_option_line(const char *cp, char *tag, char *val)
1524 {
1525         while( *cp == ' ' || *cp == '\t' ) ++cp;
1526         const char *bp = cp;
1527         while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' && *cp != '\n' ) ++cp;
1528         int len = cp - bp;
1529         if( !len || len > BCSTRLEN-1 ) return 1;
1530         while( bp < cp ) *tag++ = *bp++;
1531         *tag = 0;
1532         while( *cp == ' ' || *cp == '\t' ) ++cp;
1533         if( *cp == '=' ) ++cp;
1534         while( *cp == ' ' || *cp == '\t' ) ++cp;
1535         bp = cp;
1536         while( *cp && *cp != '\n' ) ++cp;
1537         len = cp - bp;
1538         if( len > BCTEXTLEN-1 ) return 1;
1539         while( bp < cp ) *val++ = *bp++;
1540         *val = 0;
1541         return 0;
1542 }
1543
1544 int FFMPEG::can_render(const char *fformat, const char *type)
1545 {
1546         FileSystem fs;
1547         char option_path[BCTEXTLEN];
1548         FFMPEG::set_option_path(option_path, type);
1549         fs.update(option_path);
1550         int total_files = fs.total_files();
1551         for( int i=0; i<total_files; ++i ) {
1552                 const char *name = fs.get_entry(i)->get_name();
1553                 const char *ext = strrchr(name,'.');
1554                 if( !ext ) continue;
1555                 if( !strcmp(fformat, ++ext) ) return 1;
1556         }
1557         return 0;
1558 }
1559
1560 int FFMPEG::get_ff_option(const char *nm, const char *options, char *value)
1561 {
1562         for( const char *cp=options; *cp!=0; ) {
1563                 char line[BCTEXTLEN], *bp = line, *ep = bp+sizeof(line)-1;
1564                 while( bp < ep && *cp && *cp!='\n' ) *bp++ = *cp++;
1565                 if( *cp ) ++cp;
1566                 *bp = 0;
1567                 if( !line[0] || line[0] == '#' || line[0] == ';' ) continue;
1568                 char key[BCSTRLEN], val[BCTEXTLEN];
1569                 if( FFMPEG::scan_option_line(line, key, val) ) continue;
1570                 if( !strcmp(key, nm) ) {
1571                         strncpy(value, val, BCSTRLEN);
1572                         return 0;
1573                 }
1574         }
1575         return 1;
1576 }
1577
1578 void FFMPEG::scan_audio_options(Asset *asset, EDL *edl)
1579 {
1580         char cin_sample_fmt[BCSTRLEN];
1581         int cin_fmt = AV_SAMPLE_FMT_NONE;
1582         const char *options = asset->ff_audio_options;
1583         if( !get_ff_option("cin_sample_fmt", options, cin_sample_fmt) )
1584                 cin_fmt = (int)av_get_sample_fmt(cin_sample_fmt);
1585         if( cin_fmt < 0 ) {
1586                 char audio_codec[BCSTRLEN]; audio_codec[0] = 0;
1587                 AVCodec *av_codec = !FFMPEG::get_codec(audio_codec, "audio", asset->acodec) ?
1588                         avcodec_find_encoder_by_name(audio_codec) : 0;
1589                 if( av_codec && av_codec->sample_fmts )
1590                         cin_fmt = find_best_sample_fmt_of_list(av_codec->sample_fmts, AV_SAMPLE_FMT_FLT);
1591         }
1592         if( cin_fmt < 0 ) cin_fmt = AV_SAMPLE_FMT_S16;
1593         const char *name = av_get_sample_fmt_name((AVSampleFormat)cin_fmt);
1594         if( !name ) name = _("None");
1595         strcpy(asset->ff_sample_format, name);
1596
1597         char value[BCSTRLEN];
1598         if( !get_ff_option("cin_bitrate", options, value) )
1599                 asset->ff_audio_bitrate = atoi(value);
1600         if( !get_ff_option("cin_quality", options, value) )
1601                 asset->ff_audio_quality = atoi(value);
1602 }
1603
1604 void FFMPEG::load_audio_options(Asset *asset, EDL *edl)
1605 {
1606         char options_path[BCTEXTLEN];
1607         set_option_path(options_path, "audio/%s", asset->acodec);
1608         if( !load_options(options_path,
1609                         asset->ff_audio_options,
1610                         sizeof(asset->ff_audio_options)) )
1611                 scan_audio_options(asset, edl);
1612 }
1613
1614 void FFMPEG::scan_video_options(Asset *asset, EDL *edl)
1615 {
1616         char cin_pix_fmt[BCSTRLEN];
1617         int cin_fmt = AV_PIX_FMT_NONE;
1618         const char *options = asset->ff_video_options;
1619         if( !get_ff_option("cin_pix_fmt", options, cin_pix_fmt) )
1620                         cin_fmt = (int)av_get_pix_fmt(cin_pix_fmt);
1621         if( cin_fmt < 0 ) {
1622                 char video_codec[BCSTRLEN];  video_codec[0] = 0;
1623                 AVCodec *av_codec = !get_codec(video_codec, "video", asset->vcodec) ?
1624                         avcodec_find_encoder_by_name(video_codec) : 0;
1625                 if( av_codec && av_codec->pix_fmts ) {
1626                         if( 0 && edl ) { // frequently picks a bad answer
1627                                 int color_model = edl->session->color_model;
1628                                 int max_bits = BC_CModels::calculate_pixelsize(color_model) * 8;
1629                                 max_bits /= BC_CModels::components(color_model);
1630                                 cin_fmt = avcodec_find_best_pix_fmt_of_list(av_codec->pix_fmts,
1631                                         (BC_CModels::is_yuv(color_model) ?
1632                                                 (max_bits > 8 ? AV_PIX_FMT_AYUV64LE : AV_PIX_FMT_YUV444P) :
1633                                                 (max_bits > 8 ? AV_PIX_FMT_RGB48LE : AV_PIX_FMT_RGB24)), 0, 0);
1634                         }
1635                         else
1636                                 cin_fmt = av_codec->pix_fmts[0];
1637                 }
1638         }
1639         if( cin_fmt < 0 ) cin_fmt = AV_PIX_FMT_YUV420P;
1640         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get((AVPixelFormat)cin_fmt);
1641         const char *name = desc ? desc->name : _("None");
1642         strcpy(asset->ff_pixel_format, name);
1643
1644         char value[BCSTRLEN];
1645         if( !get_ff_option("cin_bitrate", options, value) )
1646                 asset->ff_video_bitrate = atoi(value);
1647         if( !get_ff_option("cin_quality", options, value) )
1648                 asset->ff_video_quality = atoi(value);
1649 }
1650
1651 void FFMPEG::load_video_options(Asset *asset, EDL *edl)
1652 {
1653         char options_path[BCTEXTLEN];
1654         set_option_path(options_path, "video/%s", asset->vcodec);
1655         if( !load_options(options_path,
1656                         asset->ff_video_options,
1657                         sizeof(asset->ff_video_options)) )
1658                 scan_video_options(asset, edl);
1659 }
1660
1661 int FFMPEG::load_defaults(const char *path, const char *type,
1662                  char *codec, char *codec_options, int len)
1663 {
1664         char default_file[BCTEXTLEN];
1665         set_option_path(default_file, "%s/%s.dfl", path, type);
1666         FILE *fp = fopen(default_file,"r");
1667         if( !fp ) return 1;
1668         fgets(codec, BCSTRLEN, fp);
1669         char *cp = codec;
1670         while( *cp && *cp!='\n' ) ++cp;
1671         *cp = 0;
1672         while( len > 0 && fgets(codec_options, len, fp) ) {
1673                 int n = strlen(codec_options);
1674                 codec_options += n;  len -= n;
1675         }
1676         fclose(fp);
1677         set_option_path(default_file, "%s/%s", path, codec);
1678         return load_options(default_file, codec_options, len);
1679 }
1680
1681 void FFMPEG::set_asset_format(Asset *asset, EDL *edl, const char *text)
1682 {
1683         if( asset->format != FILE_FFMPEG ) return;
1684         if( text != asset->fformat )
1685                 strcpy(asset->fformat, text);
1686         if( asset->audio_data && !asset->ff_audio_options[0] ) {
1687                 if( !load_defaults("audio", text, asset->acodec,
1688                                 asset->ff_audio_options, sizeof(asset->ff_audio_options)) )
1689                         scan_audio_options(asset, edl);
1690                 else
1691                         asset->audio_data = 0;
1692         }
1693         if( asset->video_data && !asset->ff_video_options[0] ) {
1694                 if( !load_defaults("video", text, asset->vcodec,
1695                                 asset->ff_video_options, sizeof(asset->ff_video_options)) )
1696                         scan_video_options(asset, edl);
1697                 else
1698                         asset->video_data = 0;
1699         }
1700 }
1701
1702 int FFMPEG::get_encoder(const char *options,
1703                 char *format, char *codec, char *bsfilter)
1704 {
1705         FILE *fp = fopen(options,"r");
1706         if( !fp ) {
1707                 eprintf(_("options open failed %s\n"),options);
1708                 return 1;
1709         }
1710         char line[BCTEXTLEN];
1711         if( !fgets(line, sizeof(line), fp) ||
1712             scan_encoder(line, format, codec, bsfilter) )
1713                 eprintf(_("format/codec not found %s\n"), options);
1714         fclose(fp);
1715         return 0;
1716 }
1717
1718 int FFMPEG::scan_encoder(const char *line,
1719                 char *format, char *codec, char *bsfilter)
1720 {
1721         format[0] = codec[0] = bsfilter[0] = 0;
1722         if( scan_option_line(line, format, codec) ) return 1;
1723         char *cp = codec;
1724         while( *cp && *cp != '|' ) ++cp;
1725         if( !*cp ) return 0;
1726         char *bp = cp;
1727         do { *bp-- = 0; } while( bp>=codec && (*bp==' ' || *bp == '\t' ) );
1728         while( *++cp && (*cp==' ' || *cp == '\t') );
1729         bp = bsfilter;
1730         for( int i=BCTEXTLEN; --i>0 && *cp; ) *bp++ = *cp++;
1731         *bp = 0;
1732         return 0;
1733 }
1734
1735 int FFMPEG::read_options(const char *options, AVDictionary *&opts, int skip)
1736 {
1737         FILE *fp = fopen(options,"r");
1738         if( !fp ) return 1;
1739         int ret = 0;
1740         while( !ret && --skip >= 0 ) {
1741                 int ch = getc(fp);
1742                 while( ch >= 0 && ch != '\n' ) ch = getc(fp);
1743                 if( ch < 0 ) ret = 1;
1744         }
1745         if( !ret )
1746                 ret = read_options(fp, options, opts);
1747         fclose(fp);
1748         return ret;
1749 }
1750
1751 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
1752 {
1753         FILE *fp = fmemopen((void *)options,strlen(options),"r");
1754         if( !fp ) return 0;
1755         int ret = read_options(fp, options, opts);
1756         fclose(fp);
1757         AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
1758         if( tag ) st->id = strtol(tag->value,0,0);
1759         return ret;
1760 }
1761
1762 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
1763 {
1764         int ret = 0, no = 0;
1765         char line[BCTEXTLEN];
1766         while( !ret && fgets(line, sizeof(line), fp) ) {
1767                 line[sizeof(line)-1] = 0;
1768                 if( line[0] == '#' ) continue;
1769                 if( line[0] == '\n' ) continue;
1770                 char key[BCSTRLEN], val[BCTEXTLEN];
1771                 if( scan_option_line(line, key, val) ) {
1772                         eprintf(_("err reading %s: line %d\n"), options, no);
1773                         ret = 1;
1774                 }
1775                 if( !ret ) {
1776                         if( !strcmp(key, "duration") )
1777                                 opt_duration = strtod(val, 0);
1778                         else if( !strcmp(key, "video_filter") )
1779                                 opt_video_filter = cstrdup(val);
1780                         else if( !strcmp(key, "audio_filter") )
1781                                 opt_audio_filter = cstrdup(val);
1782                         else if( !strcmp(key, "loglevel") )
1783                                 set_loglevel(val);
1784                         else
1785                                 av_dict_set(&opts, key, val, 0);
1786                 }
1787         }
1788         return ret;
1789 }
1790
1791 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
1792 {
1793         char option_path[BCTEXTLEN];
1794         set_option_path(option_path, "%s", options);
1795         return read_options(option_path, opts);
1796 }
1797
1798 int FFMPEG::load_options(const char *path, char *bfr, int len)
1799 {
1800         *bfr = 0;
1801         FILE *fp = fopen(path, "r");
1802         if( !fp ) return 1;
1803         fgets(bfr, len, fp); // skip hdr
1804         len = fread(bfr, 1, len-1, fp);
1805         if( len < 0 ) len = 0;
1806         bfr[len] = 0;
1807         fclose(fp);
1808         return 0;
1809 }
1810
1811 void FFMPEG::set_loglevel(const char *ap)
1812 {
1813         if( !ap || !*ap ) return;
1814         const struct {
1815                 const char *name;
1816                 int level;
1817         } log_levels[] = {
1818                 { "quiet"  , AV_LOG_QUIET   },
1819                 { "panic"  , AV_LOG_PANIC   },
1820                 { "fatal"  , AV_LOG_FATAL   },
1821                 { "error"  , AV_LOG_ERROR   },
1822                 { "warning", AV_LOG_WARNING },
1823                 { "info"   , AV_LOG_INFO    },
1824                 { "verbose", AV_LOG_VERBOSE },
1825                 { "debug"  , AV_LOG_DEBUG   },
1826         };
1827         for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
1828                 if( !strcmp(log_levels[i].name, ap) ) {
1829                         av_log_set_level(log_levels[i].level);
1830                         return;
1831                 }
1832         }
1833         av_log_set_level(atoi(ap));
1834 }
1835
1836 double FFMPEG::to_secs(int64_t time, AVRational time_base)
1837 {
1838         double base_time = time == AV_NOPTS_VALUE ? 0 :
1839                 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
1840         return base_time / AV_TIME_BASE;
1841 }
1842
1843 int FFMPEG::info(char *text, int len)
1844 {
1845         if( len <= 0 ) return 0;
1846         decode_activate();
1847 #define report(s...) do { int n = snprintf(cp,len,s); cp += n;  len -= n; } while(0)
1848         char *cp = text;
1849         report("format: %s\n",fmt_ctx->iformat->name);
1850         if( ffvideo.size() > 0 )
1851                 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
1852         for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
1853                 FFVideoStream *vid = ffvideo[vidx];
1854                 AVStream *st = vid->st;
1855                 AVCodecID codec_id = st->codecpar->codec_id;
1856                 report(_("vid%d (%d),  id 0x%06x:\n"), vid->idx, vid->fidx, codec_id);
1857                 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
1858                 report("  video%d %s", vidx+1, desc ? desc->name : " (unkn)");
1859                 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
1860                 AVPixelFormat pix_fmt = (AVPixelFormat)st->codecpar->format;
1861                 const char *pfn = av_get_pix_fmt_name(pix_fmt);
1862                 report(" pix %s\n", pfn ? pfn : "(unkn)");
1863                 double secs = to_secs(st->duration, st->time_base);
1864                 int64_t length = secs * vid->frame_rate + 0.5;
1865                 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
1866                 int64_t nudge = ofs * vid->frame_rate;
1867                 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1868                 report("    %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
1869                 int hrs = secs/3600;  secs -= hrs*3600;
1870                 int mins = secs/60;  secs -= mins*60;
1871                 report("  %d:%02d:%05.2f\n", hrs, mins, secs);
1872         }
1873         if( ffaudio.size() > 0 )
1874                 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
1875         for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
1876                 FFAudioStream *aud = ffaudio[aidx];
1877                 AVStream *st = aud->st;
1878                 AVCodecID codec_id = st->codecpar->codec_id;
1879                 report(_("aud%d (%d),  id 0x%06x:\n"), aud->idx, aud->fidx, codec_id);
1880                 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
1881                 int nch = aud->channels, ch0 = aud->channel0+1;
1882                 report("  audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
1883                 AVSampleFormat sample_fmt = (AVSampleFormat)st->codecpar->format;
1884                 const char *fmt = av_get_sample_fmt_name(sample_fmt);
1885                 report(" %s %d", fmt, aud->sample_rate);
1886                 int sample_bits = av_get_bits_per_sample(codec_id);
1887                 report(" %dbits\n", sample_bits);
1888                 double secs = to_secs(st->duration, st->time_base);
1889                 int64_t length = secs * aud->sample_rate + 0.5;
1890                 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
1891                 int64_t nudge = ofs * aud->sample_rate;
1892                 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1893                 report("    %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
1894                 int hrs = secs/3600;  secs -= hrs*3600;
1895                 int mins = secs/60;  secs -= mins*60;
1896                 report("  %d:%02d:%05.2f\n", hrs, mins, secs);
1897         }
1898         if( fmt_ctx->nb_programs > 0 )
1899                 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
1900         for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
1901                 report("program %d", i+1);
1902                 AVProgram *pgrm = fmt_ctx->programs[i];
1903                 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1904                         int idx = pgrm->stream_index[j];
1905                         int vidx = ffvideo.size();
1906                         while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
1907                         if( vidx >= 0 ) {
1908                                 report(", vid%d", vidx);
1909                                 continue;
1910                         }
1911                         int aidx = ffaudio.size();
1912                         while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
1913                         if( aidx >= 0 ) {
1914                                 report(", aud%d", aidx);
1915                                 continue;
1916                         }
1917                         report(", (%d)", pgrm->stream_index[j]);
1918                 }
1919                 report("\n");
1920         }
1921         report("\n");
1922         AVDictionaryEntry *tag = 0;
1923         while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
1924                 report("%s=%s\n", tag->key, tag->value);
1925
1926         if( !len ) --cp;
1927         *cp = 0;
1928         return cp - text;
1929 #undef report
1930 }
1931
1932
1933 int FFMPEG::init_decoder(const char *filename)
1934 {
1935         ff_lock("FFMPEG::init_decoder");
1936         av_register_all();
1937         char file_opts[BCTEXTLEN];
1938         char *bp = strrchr(strcpy(file_opts, filename), '/');
1939         char *sp = strrchr(!bp ? file_opts : bp, '.');
1940         if( !sp ) sp = bp + strlen(bp);
1941         FILE *fp = 0;
1942         AVInputFormat *ifmt = 0;
1943         if( sp ) {
1944                 strcpy(sp, ".opts");
1945                 fp = fopen(file_opts, "r");
1946         }
1947         if( fp ) {
1948                 read_options(fp, file_opts, opts);
1949                 fclose(fp);
1950                 AVDictionaryEntry *tag;
1951                 if( (tag=av_dict_get(opts, "format", NULL, 0)) != 0 ) {
1952                         ifmt = av_find_input_format(tag->value);
1953                 }
1954         }
1955         else
1956                 load_options("decode.opts", opts);
1957         AVDictionary *fopts = 0;
1958         av_dict_copy(&fopts, opts, 0);
1959         int ret = avformat_open_input(&fmt_ctx, filename, ifmt, &fopts);
1960         av_dict_free(&fopts);
1961         if( ret >= 0 )
1962                 ret = avformat_find_stream_info(fmt_ctx, NULL);
1963         if( !ret ) {
1964                 decoding = -1;
1965         }
1966         ff_unlock();
1967         return !ret ? 0 : 1;
1968 }
1969
1970 int FFMPEG::open_decoder()
1971 {
1972         struct stat st;
1973         if( stat(fmt_ctx->url, &st) < 0 ) {
1974                 eprintf(_("can't stat file: %s\n"), fmt_ctx->url);
1975                 return 1;
1976         }
1977
1978         int64_t file_bits = 8 * st.st_size;
1979         if( !fmt_ctx->bit_rate && opt_duration > 0 )
1980                 fmt_ctx->bit_rate = file_bits / opt_duration;
1981
1982         int estimated = 0;
1983         if( fmt_ctx->bit_rate > 0 ) {
1984                 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1985                         AVStream *st = fmt_ctx->streams[i];
1986                         if( st->duration != AV_NOPTS_VALUE ) continue;
1987                         if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
1988                         st->duration = av_rescale(file_bits, st->time_base.den,
1989                                 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
1990                         estimated = 1;
1991                 }
1992         }
1993         static int notified = 0;
1994         if( !notified && estimated ) {
1995                 notified = 1;
1996                 printf("FFMPEG::open_decoder: some stream times estimated\n");
1997         }
1998
1999         ff_lock("FFMPEG::open_decoder");
2000         int ret = 0, bad_time = 0;
2001         for( int i=0; !ret && i<(int)fmt_ctx->nb_streams; ++i ) {
2002                 AVStream *st = fmt_ctx->streams[i];
2003                 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
2004                 AVCodecParameters *avpar = st->codecpar;
2005                 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avpar->codec_id);
2006                 if( !codec_desc ) continue;
2007                 switch( avpar->codec_type ) {
2008                 case AVMEDIA_TYPE_VIDEO: {
2009                         if( avpar->width < 1 ) continue;
2010                         if( avpar->height < 1 ) continue;
2011                         AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
2012                         if( framerate.num < 1 ) continue;
2013                         has_video = 1;
2014                         int vidx = ffvideo.size();
2015                         FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
2016                         vstrm_index.append(ffidx(vidx, 0));
2017                         ffvideo.append(vid);
2018                         vid->width = avpar->width;
2019                         vid->height = avpar->height;
2020                         vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
2021                         double secs = to_secs(st->duration, st->time_base);
2022                         vid->length = secs * vid->frame_rate;
2023                         vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
2024                         vid->nudge = st->start_time;
2025                         vid->reading = -1;
2026                         if( opt_video_filter )
2027                                 ret = vid->create_filter(opt_video_filter, avpar);
2028                         break; }
2029                 case AVMEDIA_TYPE_AUDIO: {
2030                         if( avpar->channels < 1 ) continue;
2031                         if( avpar->sample_rate < 1 ) continue;
2032                         has_audio = 1;
2033                         int aidx = ffaudio.size();
2034                         FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
2035                         ffaudio.append(aud);
2036                         aud->channel0 = astrm_index.size();
2037                         aud->channels = avpar->channels;
2038                         for( int ch=0; ch<aud->channels; ++ch )
2039                                 astrm_index.append(ffidx(aidx, ch));
2040                         aud->sample_rate = avpar->sample_rate;
2041                         double secs = to_secs(st->duration, st->time_base);
2042                         aud->length = secs * aud->sample_rate;
2043                         aud->init_swr(aud->channels, avpar->format, aud->sample_rate);
2044                         aud->nudge = st->start_time;
2045                         aud->reading = -1;
2046                         if( opt_audio_filter )
2047                                 ret = aud->create_filter(opt_audio_filter, avpar);
2048                         break; }
2049                 default: break;
2050                 }
2051         }
2052         if( bad_time )
2053                 printf("FFMPEG::open_decoder: some stream have bad times\n");
2054         ff_unlock();
2055         return ret < 0 ? -1 : 0;
2056 }
2057
2058
2059 int FFMPEG::init_encoder(const char *filename)
2060 {
2061 // try access first for named pipes
2062         int ret = access(filename, W_OK);
2063         if( ret ) {
2064                 int fd = ::open(filename,O_WRONLY);
2065                 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
2066                 if( fd >= 0 ) { close(fd);  ret = 0; }
2067         }
2068         if( ret ) {
2069                 eprintf(_("bad file path: %s\n"), filename);
2070                 return 1;
2071         }
2072         ret = get_file_format();
2073         if( ret > 0 ) {
2074                 eprintf(_("bad file format: %s\n"), filename);
2075                 return 1;
2076         }
2077         if( ret < 0 ) {
2078                 eprintf(_("mismatch audio/video file format: %s\n"), filename);
2079                 return 1;
2080         }
2081         ff_lock("FFMPEG::init_encoder");
2082         av_register_all();
2083         char format[BCSTRLEN];
2084         if( get_format(format, "format", file_format) )
2085                 strcpy(format, file_format);
2086         avformat_alloc_output_context2(&fmt_ctx, 0, format, filename);
2087         if( !fmt_ctx ) {
2088                 eprintf(_("failed: %s\n"), filename);
2089                 ret = 1;
2090         }
2091         if( !ret ) {
2092                 encoding = -1;
2093                 load_options("encode.opts", opts);
2094         }
2095         ff_unlock();
2096         return ret;
2097 }
2098
2099 int FFMPEG::open_encoder(const char *type, const char *spec)
2100 {
2101
2102         Asset *asset = file_base->asset;
2103         char *filename = asset->path;
2104         AVDictionary *sopts = 0;
2105         av_dict_copy(&sopts, opts, 0);
2106         char option_path[BCTEXTLEN];
2107         set_option_path(option_path, "%s/%s.opts", type, type);
2108         read_options(option_path, sopts);
2109         get_option_path(option_path, type, spec);
2110         char format_name[BCSTRLEN], codec_name[BCTEXTLEN], bsfilter[BCTEXTLEN];
2111         if( get_encoder(option_path, format_name, codec_name, bsfilter) ) {
2112                 eprintf(_("get_encoder failed %s:%s\n"), option_path, filename);
2113                 return 1;
2114         }
2115
2116 #ifdef HAVE_DV
2117         if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
2118 #endif
2119         else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
2120         else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
2121
2122         int ret = 0;
2123         ff_lock("FFMPEG::open_encoder");
2124         FFStream *fst = 0;
2125         AVStream *st = 0;
2126         AVCodecContext *ctx = 0;
2127
2128         const AVCodecDescriptor *codec_desc = 0;
2129         AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
2130         if( !codec ) {
2131                 eprintf(_("cant find codec %s:%s\n"), codec_name, filename);
2132                 ret = 1;
2133         }
2134         if( !ret ) {
2135                 codec_desc = avcodec_descriptor_get(codec->id);
2136                 if( !codec_desc ) {
2137                         eprintf(_("unknown codec %s:%s\n"), codec_name, filename);
2138                         ret = 1;
2139                 }
2140         }
2141         if( !ret ) {
2142                 st = avformat_new_stream(fmt_ctx, 0);
2143                 if( !st ) {
2144                         eprintf(_("cant create stream %s:%s\n"), codec_name, filename);
2145                         ret = 1;
2146                 }
2147         }
2148         if( !ret ) {
2149                 switch( codec_desc->type ) {
2150                 case AVMEDIA_TYPE_AUDIO: {
2151                         if( has_audio ) {
2152                                 eprintf(_("duplicate audio %s:%s\n"), codec_name, filename);
2153                                 ret = 1;
2154                                 break;
2155                         }
2156                         if( scan_options(asset->ff_audio_options, sopts, st) ) {
2157                                 eprintf(_("bad audio options %s:%s\n"), codec_name, filename);
2158                                 ret = 1;
2159                                 break;
2160                         }
2161                         has_audio = 1;
2162                         ctx = avcodec_alloc_context3(codec);
2163                         if( asset->ff_audio_bitrate > 0 ) {
2164                                 ctx->bit_rate = asset->ff_audio_bitrate;
2165                                 char arg[BCSTRLEN];
2166                                 sprintf(arg, "%d", asset->ff_audio_bitrate);
2167                                 av_dict_set(&sopts, "b", arg, 0);
2168                         }
2169                         else if( asset->ff_audio_quality >= 0 ) {
2170                                 ctx->global_quality = asset->ff_audio_quality * FF_QP2LAMBDA;
2171                                 ctx->qmin    = ctx->qmax =  asset->ff_audio_quality;
2172                                 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2173                                 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2174                                 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2175                                 char arg[BCSTRLEN];
2176                                 av_dict_set(&sopts, "flags", "+qscale", 0);
2177                                 sprintf(arg, "%d", asset->ff_audio_quality);
2178                                 av_dict_set(&sopts, "qscale", arg, 0);
2179                                 sprintf(arg, "%d", ctx->global_quality);
2180                                 av_dict_set(&sopts, "global_quality", arg, 0);
2181                         }
2182                         int aidx = ffaudio.size();
2183                         int fidx = aidx + ffvideo.size();
2184                         FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
2185                         aud->avctx = ctx;  ffaudio.append(aud);  fst = aud;
2186                         aud->sample_rate = asset->sample_rate;
2187                         ctx->channels = aud->channels = asset->channels;
2188                         for( int ch=0; ch<aud->channels; ++ch )
2189                                 astrm_index.append(ffidx(aidx, ch));
2190                         ctx->channel_layout =  av_get_default_channel_layout(ctx->channels);
2191                         ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
2192                         if( !ctx->sample_rate ) {
2193                                 eprintf(_("check_sample_rate failed %s\n"), filename);
2194                                 ret = 1;
2195                                 break;
2196                         }
2197                         ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
2198                         AVSampleFormat sample_fmt = av_get_sample_fmt(asset->ff_sample_format);
2199                         if( sample_fmt == AV_SAMPLE_FMT_NONE )
2200                                 sample_fmt = codec->sample_fmts ? codec->sample_fmts[0] : AV_SAMPLE_FMT_S16;
2201                         ctx->sample_fmt = sample_fmt;
2202                         uint64_t layout = av_get_default_channel_layout(ctx->channels);
2203                         aud->resample_context = swr_alloc_set_opts(NULL,
2204                                 layout, ctx->sample_fmt, aud->sample_rate,
2205                                 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
2206                                 0, NULL);
2207                         swr_init(aud->resample_context);
2208                         aud->writing = -1;
2209                         break; }
2210                 case AVMEDIA_TYPE_VIDEO: {
2211                         if( has_video ) {
2212                                 eprintf(_("duplicate video %s:%s\n"), codec_name, filename);
2213                                 ret = 1;
2214                                 break;
2215                         }
2216                         if( scan_options(asset->ff_video_options, sopts, st) ) {
2217                                 eprintf(_("bad video options %s:%s\n"), codec_name, filename);
2218                                 ret = 1;
2219                                 break;
2220                         }
2221                         has_video = 1;
2222                         ctx = avcodec_alloc_context3(codec);
2223                         if( asset->ff_video_bitrate > 0 ) {
2224                                 ctx->bit_rate = asset->ff_video_bitrate;
2225                                 char arg[BCSTRLEN];
2226                                 sprintf(arg, "%d", asset->ff_video_bitrate);
2227                                 av_dict_set(&sopts, "b", arg, 0);
2228                         }
2229                         else if( asset->ff_video_quality >= 0 ) {
2230                                 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
2231                                 ctx->qmin    = ctx->qmax =  asset->ff_video_quality;
2232                                 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2233                                 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2234                                 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2235                                 char arg[BCSTRLEN];
2236                                 av_dict_set(&sopts, "flags", "+qscale", 0);
2237                                 sprintf(arg, "%d", asset->ff_video_quality);
2238                                 av_dict_set(&sopts, "qscale", arg, 0);
2239                                 sprintf(arg, "%d", ctx->global_quality);
2240                                 av_dict_set(&sopts, "global_quality", arg, 0);
2241                         }
2242                         int vidx = ffvideo.size();
2243                         int fidx = vidx + ffaudio.size();
2244                         FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
2245                         vstrm_index.append(ffidx(vidx, 0));
2246                         vid->avctx = ctx;  ffvideo.append(vid);  fst = vid;
2247                         vid->width = asset->width;
2248                         vid->height = asset->height;
2249                         vid->frame_rate = asset->frame_rate;
2250
2251                         AVPixelFormat pix_fmt = av_get_pix_fmt(asset->ff_pixel_format);
2252                         if( pix_fmt == AV_PIX_FMT_NONE )
2253                                 pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
2254                         ctx->pix_fmt = pix_fmt;
2255                         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
2256                         int mask_w = (1<<desc->log2_chroma_w)-1;
2257                         ctx->width = (vid->width+mask_w) & ~mask_w;
2258                         int mask_h = (1<<desc->log2_chroma_h)-1;
2259                         ctx->height = (vid->height+mask_h) & ~mask_h;
2260                         ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
2261                         AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
2262                         if( !frame_rate.num || !frame_rate.den ) {
2263                                 eprintf(_("check_frame_rate failed %s\n"), filename);
2264                                 ret = 1;
2265                                 break;
2266                         }
2267                         av_reduce(&frame_rate.num, &frame_rate.den,
2268                                 frame_rate.num, frame_rate.den, INT_MAX);
2269                         ctx->framerate = (AVRational) { frame_rate.num, frame_rate.den };
2270                         ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
2271                         st->avg_frame_rate = frame_rate;
2272                         st->time_base = ctx->time_base;
2273                         vid->writing = -1;
2274                         vid->interlaced = asset->interlace_mode == ILACE_MODE_TOP_FIRST ||
2275                                 asset->interlace_mode == ILACE_MODE_BOTTOM_FIRST ? 1 : 0;
2276                         vid->top_field_first = asset->interlace_mode == ILACE_MODE_TOP_FIRST ? 1 : 0;
2277                         break; }
2278                 default:
2279                         eprintf(_("not audio/video, %s:%s\n"), codec_name, filename);
2280                         ret = 1;
2281                 }
2282
2283                 if( ctx ) {
2284                         AVDictionaryEntry *tag;
2285                         if( (tag=av_dict_get(sopts, "cin_stats_filename", NULL, 0)) != 0 ) {
2286                                 char suffix[BCSTRLEN];  sprintf(suffix,"-%d.log",fst->fidx);
2287                                 fst->stats_filename = cstrcat(2, tag->value, suffix);
2288                         }
2289                         if( (tag=av_dict_get(sopts, "flags", NULL, 0)) != 0 ) {
2290                                 int pass = fst->pass;
2291                                 char *cp = tag->value;
2292                                 while( *cp ) {
2293                                         int ch = *cp++, pfx = ch=='-' ? -1 : ch=='+' ? 1 : 0;
2294                                         if( !isalnum(!pfx ? ch : (ch=*cp++)) ) continue;
2295                                         char id[BCSTRLEN], *bp = id, *ep = bp+sizeof(id)-1;
2296                                         for( *bp++=ch; isalnum(ch=*cp); ++cp )
2297                                                 if( bp < ep ) *bp++ = ch;
2298                                         *bp = 0;
2299                                         if( !strcmp(id, "pass1") ) {
2300                                                 pass = pfx<0 ? (pass&~1) : pfx>0 ? (pass|1) : 1;
2301                                         }
2302                                         else if( !strcmp(id, "pass2") ) {
2303                                                 pass = pfx<0 ? (pass&~2) : pfx>0 ? (pass|2) : 2;
2304                                         }
2305                                 }
2306                                 if( (fst->pass=pass) ) {
2307                                         if( pass & 1 ) ctx->flags |= AV_CODEC_FLAG_PASS1;
2308                                         if( pass & 2 ) ctx->flags |= AV_CODEC_FLAG_PASS2;
2309                                 }
2310                         }
2311                 }
2312         }
2313         if( !ret ) {
2314                 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
2315                         ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
2316                 if( fst->stats_filename && (ret=fst->init_stats_file()) )
2317                         eprintf(_("error: stats file = %s\n"), fst->stats_filename);
2318         }
2319         if( !ret ) {
2320                 av_dict_set(&sopts, "cin_bitrate", 0, 0);
2321                 av_dict_set(&sopts, "cin_quality", 0, 0);
2322
2323                 if( !av_dict_get(sopts, "threads", NULL, 0) )
2324                         ctx->thread_count = ff_cpus();
2325                 ret = avcodec_open2(ctx, codec, &sopts);
2326                 if( ret >= 0 ) {
2327                         ret = avcodec_parameters_from_context(st->codecpar, ctx);
2328                         if( ret < 0 )
2329                                 fprintf(stderr, "Could not copy the stream parameters\n");
2330                 }
2331                 if( ret >= 0 ) {
2332 _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
2333                         ret = avcodec_copy_context(st->codec, ctx);
2334 _Pragma("GCC diagnostic warning \"-Wdeprecated-declarations\"")
2335                         if( ret < 0 )
2336                                 fprintf(stderr, "Could not copy the stream context\n");
2337                 }
2338                 if( ret < 0 ) {
2339                         ff_err(ret,"FFMPEG::open_encoder");
2340                         eprintf(_("open failed %s:%s\n"), codec_name, filename);
2341                         ret = 1;
2342                 }
2343                 else
2344                         ret = 0;
2345         }
2346         if( !ret && fst && bsfilter[0] ) {
2347                 ret = av_bsf_list_parse_str(bsfilter, &fst->bsfc);
2348                 if( ret < 0 ) {
2349                         ff_err(ret,"FFMPEG::open_encoder");
2350                         eprintf(_("bitstream filter failed %s:\n%s\n"), filename, bsfilter);
2351                         ret = 1;
2352                 }
2353                 else
2354                         ret = 0;
2355         }
2356
2357         if( !ret )
2358                 start_muxer();
2359
2360         ff_unlock();
2361         av_dict_free(&sopts);
2362         return ret;
2363 }
2364
2365 int FFMPEG::close_encoder()
2366 {
2367         stop_muxer();
2368         if( encoding > 0 ) {
2369                 av_write_trailer(fmt_ctx);
2370                 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
2371                         avio_closep(&fmt_ctx->pb);
2372         }
2373         encoding = 0;
2374         return 0;
2375 }
2376
2377 int FFMPEG::decode_activate()
2378 {
2379         if( decoding < 0 ) {
2380                 decoding = 0;
2381                 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
2382                         ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
2383                 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
2384                         ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
2385                 // set nudges for each program stream set
2386                 const int64_t min_nudge = INT64_MIN+1;
2387                 int npgrms = fmt_ctx->nb_programs;
2388                 for( int i=0; i<npgrms; ++i ) {
2389                         AVProgram *pgrm = fmt_ctx->programs[i];
2390                         // first start time video stream
2391                         int64_t vstart_time = min_nudge, astart_time = min_nudge;
2392                         for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2393                                 int fidx = pgrm->stream_index[j];
2394                                 AVStream *st = fmt_ctx->streams[fidx];
2395                                 AVCodecParameters *avpar = st->codecpar;
2396                                 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2397                                         if( st->start_time == AV_NOPTS_VALUE ) continue;
2398                                         if( vstart_time < st->start_time )
2399                                                 vstart_time = st->start_time;
2400                                         continue;
2401                                 }
2402                                 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2403                                         if( st->start_time == AV_NOPTS_VALUE ) continue;
2404                                         if( astart_time < st->start_time )
2405                                                 astart_time = st->start_time;
2406                                         continue;
2407                                 }
2408                         }
2409                         //since frame rate is much more grainy than sample rate, it is better to
2410                         // align using video, so that total absolute error is minimized.
2411                         int64_t nudge = vstart_time > min_nudge ? vstart_time :
2412                                 astart_time > min_nudge ? astart_time : AV_NOPTS_VALUE;
2413                         for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2414                                 int fidx = pgrm->stream_index[j];
2415                                 AVStream *st = fmt_ctx->streams[fidx];
2416                                 AVCodecParameters *avpar = st->codecpar;
2417                                 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2418                                         for( int k=0; k<ffvideo.size(); ++k ) {
2419                                                 if( ffvideo[k]->fidx != fidx ) continue;
2420                                                 ffvideo[k]->nudge = nudge;
2421                                         }
2422                                         continue;
2423                                 }
2424                                 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2425                                         for( int k=0; k<ffaudio.size(); ++k ) {
2426                                                 if( ffaudio[k]->fidx != fidx ) continue;
2427                                                 ffaudio[k]->nudge = nudge;
2428                                         }
2429                                         continue;
2430                                 }
2431                         }
2432                 }
2433                 // set nudges for any streams not yet set
2434                 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2435                 int nstreams = fmt_ctx->nb_streams;
2436                 for( int i=0; i<nstreams; ++i ) {
2437                         AVStream *st = fmt_ctx->streams[i];
2438                         AVCodecParameters *avpar = st->codecpar;
2439                         switch( avpar->codec_type ) {
2440                         case AVMEDIA_TYPE_VIDEO: {
2441                                 if( st->start_time == AV_NOPTS_VALUE ) continue;
2442                                 int vidx = ffvideo.size();
2443                                 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
2444                                 if( vidx < 0 ) continue;
2445                                 if( ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
2446                                 if( vstart_time < st->start_time )
2447                                         vstart_time = st->start_time;
2448                                 break; }
2449                         case AVMEDIA_TYPE_AUDIO: {
2450                                 if( st->start_time == AV_NOPTS_VALUE ) continue;
2451                                 int aidx = ffaudio.size();
2452                                 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
2453                                 if( aidx < 0 ) continue;
2454                                 if( ffaudio[aidx]->frame_sz < avpar->frame_size )
2455                                         ffaudio[aidx]->frame_sz = avpar->frame_size;
2456                                 if( ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
2457                                 if( astart_time < st->start_time )
2458                                         astart_time = st->start_time;
2459                                 break; }
2460                         default: break;
2461                         }
2462                 }
2463                 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2464                         astart_time > min_nudge ? astart_time : 0;
2465                 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
2466                         if( ffvideo[vidx]->nudge == AV_NOPTS_VALUE )
2467                                 ffvideo[vidx]->nudge = nudge;
2468                 }
2469                 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2470                         if( ffaudio[aidx]->nudge == AV_NOPTS_VALUE )
2471                                 ffaudio[aidx]->nudge = nudge;
2472                 }
2473                 decoding = 1;
2474         }
2475         return decoding;
2476 }
2477
2478 int FFMPEG::encode_activate()
2479 {
2480         int ret = 0;
2481         if( encoding < 0 ) {
2482                 encoding = 0;
2483                 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
2484                     (ret=avio_open(&fmt_ctx->pb, fmt_ctx->url, AVIO_FLAG_WRITE)) < 0 ) {
2485                         ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
2486                                 fmt_ctx->url);
2487                         return -1;
2488                 }
2489
2490                 int prog_id = 1;
2491                 AVProgram *prog = av_new_program(fmt_ctx, prog_id);
2492                 for( int i=0; i< ffvideo.size(); ++i )
2493                         av_program_add_stream_index(fmt_ctx, prog_id, ffvideo[i]->fidx);
2494                 for( int i=0; i< ffaudio.size(); ++i )
2495                         av_program_add_stream_index(fmt_ctx, prog_id, ffaudio[i]->fidx);
2496                 int pi = fmt_ctx->nb_programs;
2497                 while(  --pi >= 0 && fmt_ctx->programs[pi]->id != prog_id );
2498                 AVDictionary **meta = &prog->metadata;
2499                 av_dict_set(meta, "service_provider", "cin5", 0);
2500                 const char *path = fmt_ctx->url, *bp = strrchr(path,'/');
2501                 if( bp ) path = bp + 1;
2502                 av_dict_set(meta, "title", path, 0);
2503
2504                 if( ffaudio.size() ) {
2505                         const char *ep = getenv("CIN_AUDIO_LANG"), *lp = 0;
2506                         if( !ep && (lp=getenv("LANG")) ) { // some are guesses
2507                                 static struct { const char lc[3], lng[4]; } lcode[] = {
2508                                         { "en", "eng" }, { "de", "ger" }, { "es", "spa" },
2509                                         { "eu", "bas" }, { "fr", "fre" }, { "el", "gre" },
2510                                         { "hi", "hin" }, { "it", "ita" }, { "ja", "jap" },
2511                                         { "ko", "kor" }, { "du", "dut" }, { "pl", "pol" },
2512                                         { "pt", "por" }, { "ru", "rus" }, { "sl", "slv" },
2513                                         { "uk", "ukr" }, { "vi", "vie" }, { "zh", "chi" },
2514                                 };
2515                                 for( int i=sizeof(lcode)/sizeof(lcode[0]); --i>=0 && !ep; )
2516                                         if( !strncmp(lcode[i].lc,lp,2) ) ep = lcode[i].lng;
2517                         }
2518                         if( !ep ) ep = "und";
2519                         char lang[5];
2520                         strncpy(lang,ep,3);  lang[3] = 0;
2521                         AVStream *st = ffaudio[0]->st;
2522                         av_dict_set(&st->metadata,"language",lang,0);
2523                 }
2524
2525                 AVDictionary *fopts = 0;
2526                 char option_path[BCTEXTLEN];
2527                 set_option_path(option_path, "format/%s", file_format);
2528                 read_options(option_path, fopts, 1);
2529                 ret = avformat_write_header(fmt_ctx, &fopts);
2530                 if( ret < 0 ) {
2531                         ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
2532                                 fmt_ctx->url);
2533                         return -1;
2534                 }
2535                 av_dict_free(&fopts);
2536                 encoding = 1;
2537         }
2538         return encoding;
2539 }
2540
2541
2542 int FFMPEG::audio_seek(int stream, int64_t pos)
2543 {
2544         int aidx = astrm_index[stream].st_idx;
2545         FFAudioStream *aud = ffaudio[aidx];
2546         aud->audio_seek(pos);
2547         return 0;
2548 }
2549
2550 int FFMPEG::video_seek(int stream, int64_t pos)
2551 {
2552         int vidx = vstrm_index[stream].st_idx;
2553         FFVideoStream *vid = ffvideo[vidx];
2554         vid->video_seek(pos);
2555         return 0;
2556 }
2557
2558
2559 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
2560 {
2561         if( !has_audio || chn >= astrm_index.size() ) return -1;
2562         int aidx = astrm_index[chn].st_idx;
2563         FFAudioStream *aud = ffaudio[aidx];
2564         if( aud->load(pos, len) < len ) return -1;
2565         int ch = astrm_index[chn].st_ch;
2566         int ret = aud->read(samples,len,ch);
2567         return ret;
2568 }
2569
2570 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
2571 {
2572         if( !has_video || layer >= vstrm_index.size() ) return -1;
2573         int vidx = vstrm_index[layer].st_idx;
2574         FFVideoStream *vid = ffvideo[vidx];
2575         return vid->load(vframe, pos);
2576 }
2577
2578
2579 int FFMPEG::encode(int stream, double **samples, int len)
2580 {
2581         FFAudioStream *aud = ffaudio[stream];
2582         return aud->encode(samples, len);
2583 }
2584
2585
2586 int FFMPEG::encode(int stream, VFrame *frame)
2587 {
2588         FFVideoStream *vid = ffvideo[stream];
2589         return vid->encode(frame);
2590 }
2591
2592 void FFMPEG::start_muxer()
2593 {
2594         if( !running() ) {
2595                 done = 0;
2596                 start();
2597         }
2598 }
2599
2600 void FFMPEG::stop_muxer()
2601 {
2602         if( running() ) {
2603                 done = 1;
2604                 mux_lock->unlock();
2605         }
2606         join();
2607 }
2608
2609 void FFMPEG::flow_off()
2610 {
2611         if( !flow ) return;
2612         flow_lock->lock("FFMPEG::flow_off");
2613         flow = 0;
2614 }
2615
2616 void FFMPEG::flow_on()
2617 {
2618         if( flow ) return;
2619         flow = 1;
2620         flow_lock->unlock();
2621 }
2622
2623 void FFMPEG::flow_ctl()
2624 {
2625         while( !flow ) {
2626                 flow_lock->lock("FFMPEG::flow_ctl");
2627                 flow_lock->unlock();
2628         }
2629 }
2630
2631 int FFMPEG::mux_audio(FFrame *frm)
2632 {
2633         FFStream *fst = frm->fst;
2634         AVCodecContext *ctx = fst->avctx;
2635         AVFrame *frame = *frm;
2636         AVRational tick_rate = {1, ctx->sample_rate};
2637         frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
2638         int ret = fst->encode_frame(frame);
2639         if( ret < 0 )
2640                 ff_err(ret, "FFMPEG::mux_audio");
2641         return ret >= 0 ? 0 : 1;
2642 }
2643
2644 int FFMPEG::mux_video(FFrame *frm)
2645 {
2646         FFStream *fst = frm->fst;
2647         AVFrame *frame = *frm;
2648         frame->pts = frm->position;
2649         int ret = fst->encode_frame(frame);
2650         if( ret < 0 )
2651                 ff_err(ret, "FFMPEG::mux_video");
2652         return ret >= 0 ? 0 : 1;
2653 }
2654
2655 void FFMPEG::mux()
2656 {
2657         for(;;) {
2658                 double atm = -1, vtm = -1;
2659                 FFrame *afrm = 0, *vfrm = 0;
2660                 int demand = 0;
2661                 for( int i=0; i<ffaudio.size(); ++i ) {  // earliest audio
2662                         FFStream *fst = ffaudio[i];
2663                         if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
2664                         FFrame *frm = fst->frms.first;
2665                         if( !frm ) { if( !done ) return; continue; }
2666                         double tm = to_secs(frm->position, fst->avctx->time_base);
2667                         if( atm < 0 || tm < atm ) { atm = tm;  afrm = frm; }
2668                 }
2669                 for( int i=0; i<ffvideo.size(); ++i ) {  // earliest video
2670                         FFStream *fst = ffvideo[i];
2671                         if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
2672                         FFrame *frm = fst->frms.first;
2673                         if( !frm ) { if( !done ) return; continue; }
2674                         double tm = to_secs(frm->position, fst->avctx->time_base);
2675                         if( vtm < 0 || tm < vtm ) { vtm = tm;  vfrm = frm; }
2676                 }
2677                 if( !demand ) flow_off();
2678                 if( !afrm && !vfrm ) break;
2679                 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
2680                         vfrm->position, vfrm->fst->avctx->time_base,
2681                         afrm->position, afrm->fst->avctx->time_base);
2682                 FFrame *frm = v <= 0 ? vfrm : afrm;
2683                 if( frm == afrm ) mux_audio(frm);
2684                 if( frm == vfrm ) mux_video(frm);
2685                 frm->dequeue();
2686                 delete frm;
2687         }
2688 }
2689
2690 void FFMPEG::run()
2691 {
2692         while( !done ) {
2693                 mux_lock->lock("FFMPEG::run");
2694                 if( !done ) mux();
2695         }
2696         for( int i=0; i<ffaudio.size(); ++i )
2697                 ffaudio[i]->drain();
2698         for( int i=0; i<ffvideo.size(); ++i )
2699                 ffvideo[i]->drain();
2700         mux();
2701         for( int i=0; i<ffaudio.size(); ++i )
2702                 ffaudio[i]->flush();
2703         for( int i=0; i<ffvideo.size(); ++i )
2704                 ffvideo[i]->flush();
2705 }
2706
2707
2708 int FFMPEG::ff_total_audio_channels()
2709 {
2710         return astrm_index.size();
2711 }
2712
2713 int FFMPEG::ff_total_astreams()
2714 {
2715         return ffaudio.size();
2716 }
2717
2718 int FFMPEG::ff_audio_channels(int stream)
2719 {
2720         return ffaudio[stream]->channels;
2721 }
2722
2723 int FFMPEG::ff_sample_rate(int stream)
2724 {
2725         return ffaudio[stream]->sample_rate;
2726 }
2727
2728 const char* FFMPEG::ff_audio_format(int stream)
2729 {
2730         AVStream *st = ffaudio[stream]->st;
2731         AVCodecID id = st->codecpar->codec_id;
2732         const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2733         return desc ? desc->name : _("Unknown");
2734 }
2735
2736 int FFMPEG::ff_audio_pid(int stream)
2737 {
2738         return ffaudio[stream]->st->id;
2739 }
2740
2741 int64_t FFMPEG::ff_audio_samples(int stream)
2742 {
2743         return ffaudio[stream]->length;
2744 }
2745
2746 // find audio astream/channels with this program,
2747 //   or all program audio channels (astream=-1)
2748 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
2749 {
2750         channel_mask = 0;
2751         int pidx = -1;
2752         int vidx = ffvideo[vstream]->fidx;
2753         // find first program with this video stream
2754         for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
2755                 AVProgram *pgrm = fmt_ctx->programs[i];
2756                 for( int j=0;  pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
2757                         int st_idx = pgrm->stream_index[j];
2758                         AVStream *st = fmt_ctx->streams[st_idx];
2759                         if( st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
2760                         if( st_idx == vidx ) pidx = i;
2761                 }
2762         }
2763         if( pidx < 0 ) return -1;
2764         int ret = -1;
2765         int64_t channels = 0;
2766         AVProgram *pgrm = fmt_ctx->programs[pidx];
2767         for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2768                 int aidx = pgrm->stream_index[j];
2769                 AVStream *st = fmt_ctx->streams[aidx];
2770                 if( st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
2771                 if( astream > 0 ) { --astream;  continue; }
2772                 int astrm = -1;
2773                 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
2774                         if( ffaudio[i]->fidx == aidx ) astrm = i;
2775                 if( astrm >= 0 ) {
2776                         if( ret < 0 ) ret = astrm;
2777                         int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
2778                         channels |= mask << ffaudio[astrm]->channel0;
2779                 }
2780                 if( !astream ) break;
2781         }
2782         channel_mask = channels;
2783         return ret;
2784 }
2785
2786
2787 int FFMPEG::ff_total_video_layers()
2788 {
2789         return vstrm_index.size();
2790 }
2791
2792 int FFMPEG::ff_total_vstreams()
2793 {
2794         return ffvideo.size();
2795 }
2796
2797 int FFMPEG::ff_video_width(int stream)
2798 {
2799         return ffvideo[stream]->width;
2800 }
2801
2802 int FFMPEG::ff_video_height(int stream)
2803 {
2804         return ffvideo[stream]->height;
2805 }
2806
2807 int FFMPEG::ff_set_video_width(int stream, int width)
2808 {
2809         int w = ffvideo[stream]->width;
2810         ffvideo[stream]->width = width;
2811         return w;
2812 }
2813
2814 int FFMPEG::ff_set_video_height(int stream, int height)
2815 {
2816         int h = ffvideo[stream]->height;
2817         ffvideo[stream]->height = height;
2818         return h;
2819 }
2820
2821 int FFMPEG::ff_coded_width(int stream)
2822 {
2823         return ffvideo[stream]->avctx->coded_width;
2824 }
2825
2826 int FFMPEG::ff_coded_height(int stream)
2827 {
2828         return ffvideo[stream]->avctx->coded_height;
2829 }
2830
2831 float FFMPEG::ff_aspect_ratio(int stream)
2832 {
2833         return ffvideo[stream]->aspect_ratio;
2834 }
2835
2836 const char* FFMPEG::ff_video_format(int stream)
2837 {
2838         AVStream *st = ffvideo[stream]->st;
2839         AVCodecID id = st->codecpar->codec_id;
2840         const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2841         return desc ? desc->name : _("Unknown");
2842 }
2843
2844 double FFMPEG::ff_frame_rate(int stream)
2845 {
2846         return ffvideo[stream]->frame_rate;
2847 }
2848
2849 int64_t FFMPEG::ff_video_frames(int stream)
2850 {
2851         return ffvideo[stream]->length;
2852 }
2853
2854 int FFMPEG::ff_video_pid(int stream)
2855 {
2856         return ffvideo[stream]->st->id;
2857 }
2858
2859 int FFMPEG::ff_video_mpeg_color_range(int stream)
2860 {
2861         return ffvideo[stream]->st->codecpar->color_range == AVCOL_RANGE_MPEG ? 1 : 0;
2862 }
2863
2864 int FFMPEG::ff_cpus()
2865 {
2866         return file_base->file->cpus;
2867 }
2868
2869 int FFVideoStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
2870 {
2871         avfilter_register_all();
2872         const char *sp = filter_spec;
2873         char filter_name[BCSTRLEN], *np = filter_name;
2874         int i = sizeof(filter_name);
2875         while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
2876         *np = 0;
2877         const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
2878         if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_VIDEO ) {
2879                 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
2880                 return -1;
2881         }
2882         filter_graph = avfilter_graph_alloc();
2883         const AVFilter *buffersrc = avfilter_get_by_name("buffer");
2884         const AVFilter *buffersink = avfilter_get_by_name("buffersink");
2885
2886         int ret = 0;  char args[BCTEXTLEN];
2887         AVPixelFormat pix_fmt = (AVPixelFormat)avpar->format;
2888         snprintf(args, sizeof(args),
2889                 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
2890                 avpar->width, avpar->height, (int)pix_fmt,
2891                 st->time_base.num, st->time_base.den,
2892                 avpar->sample_aspect_ratio.num, avpar->sample_aspect_ratio.den);
2893         if( ret >= 0 )
2894                 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2895                         args, NULL, filter_graph);
2896         if( ret >= 0 )
2897                 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2898                         NULL, NULL, filter_graph);
2899         if( ret >= 0 )
2900                 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
2901                         (uint8_t*)&pix_fmt, sizeof(pix_fmt),
2902                         AV_OPT_SEARCH_CHILDREN);
2903         if( ret < 0 )
2904                 ff_err(ret, "FFVideoStream::create_filter");
2905         else
2906                 ret = FFStream::create_filter(filter_spec);
2907         return ret >= 0 ? 0 : -1;
2908 }
2909
2910 int FFAudioStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
2911 {
2912         avfilter_register_all();
2913         const char *sp = filter_spec;
2914         char filter_name[BCSTRLEN], *np = filter_name;
2915         int i = sizeof(filter_name);
2916         while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
2917         *np = 0;
2918         const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
2919         if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_AUDIO ) {
2920                 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
2921                 return -1;
2922         }
2923         filter_graph = avfilter_graph_alloc();
2924         const AVFilter *buffersrc = avfilter_get_by_name("abuffer");
2925         const AVFilter *buffersink = avfilter_get_by_name("abuffersink");
2926         int ret = 0;  char args[BCTEXTLEN];
2927         AVSampleFormat sample_fmt = (AVSampleFormat)avpar->format;
2928         snprintf(args, sizeof(args),
2929                 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
2930                 st->time_base.num, st->time_base.den, avpar->sample_rate,
2931                 av_get_sample_fmt_name(sample_fmt), avpar->channel_layout);
2932         if( ret >= 0 )
2933                 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2934                         args, NULL, filter_graph);
2935         if( ret >= 0 )
2936                 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2937                         NULL, NULL, filter_graph);
2938         if( ret >= 0 )
2939                 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
2940                         (uint8_t*)&sample_fmt, sizeof(sample_fmt),
2941                         AV_OPT_SEARCH_CHILDREN);
2942         if( ret >= 0 )
2943                 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
2944                         (uint8_t*)&avpar->channel_layout,
2945                         sizeof(avpar->channel_layout), AV_OPT_SEARCH_CHILDREN);
2946         if( ret >= 0 )
2947                 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
2948                         (uint8_t*)&sample_rate, sizeof(sample_rate),
2949                         AV_OPT_SEARCH_CHILDREN);
2950         if( ret < 0 )
2951                 ff_err(ret, "FFAudioStream::create_filter");
2952         else
2953                 ret = FFStream::create_filter(filter_spec);
2954         return ret >= 0 ? 0 : -1;
2955 }
2956
2957 int FFStream::create_filter(const char *filter_spec)
2958 {
2959         /* Endpoints for the filter graph. */
2960         AVFilterInOut *outputs = avfilter_inout_alloc();
2961         outputs->name = av_strdup("in");
2962         outputs->filter_ctx = buffersrc_ctx;
2963         outputs->pad_idx = 0;
2964         outputs->next = 0;
2965
2966         AVFilterInOut *inputs  = avfilter_inout_alloc();
2967         inputs->name = av_strdup("out");
2968         inputs->filter_ctx = buffersink_ctx;
2969         inputs->pad_idx = 0;
2970         inputs->next = 0;
2971
2972         int ret = !outputs->name || !inputs->name ? -1 : 0;
2973         if( ret >= 0 )
2974                 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
2975                         &inputs, &outputs, NULL);
2976         if( ret >= 0 )
2977                 ret = avfilter_graph_config(filter_graph, NULL);
2978
2979         if( ret < 0 ) {
2980                 ff_err(ret, "FFStream::create_filter");
2981                 avfilter_graph_free(&filter_graph);
2982                 filter_graph = 0;
2983         }
2984         avfilter_inout_free(&inputs);
2985         avfilter_inout_free(&outputs);
2986         return ret;
2987 }
2988
2989 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
2990 {
2991         AVPacket pkt;
2992         av_init_packet(&pkt);
2993         AVFrame *frame = av_frame_alloc();
2994         if( !frame ) {
2995                 fprintf(stderr,"FFMPEG::scan: ");
2996                 fprintf(stderr,_("av_frame_alloc failed\n"));
2997                 fprintf(stderr,"FFMPEG::scan:file=%s\n", file_base->asset->path);
2998                 return -1;
2999         }
3000
3001         index_state->add_video_markers(ffvideo.size());
3002         index_state->add_audio_markers(ffaudio.size());
3003
3004         for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
3005                 int ret = 0;
3006                 AVDictionary *copts = 0;
3007                 av_dict_copy(&copts, opts, 0);
3008                 AVStream *st = fmt_ctx->streams[i];
3009                 AVCodecID codec_id = st->codecpar->codec_id;
3010                 AVCodec *decoder = avcodec_find_decoder(codec_id);
3011                 AVCodecContext *avctx = avcodec_alloc_context3(decoder);
3012                 if( !avctx ) {
3013                         eprintf(_("cant allocate codec context\n"));
3014                         ret = AVERROR(ENOMEM);
3015                 }
3016                 if( ret >= 0 ) {
3017                         avcodec_parameters_to_context(avctx, st->codecpar);
3018                         if( !av_dict_get(copts, "threads", NULL, 0) )
3019                                 avctx->thread_count = ff_cpus();
3020                         ret = avcodec_open2(avctx, decoder, &copts);
3021                 }
3022                 av_dict_free(&copts);
3023                 if( ret >= 0 ) {
3024                         AVCodecParameters *avpar = st->codecpar;
3025                         switch( avpar->codec_type ) {
3026                         case AVMEDIA_TYPE_VIDEO: {
3027                                 int vidx = ffvideo.size();
3028                                 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
3029                                 if( vidx < 0 ) break;
3030                                 ffvideo[vidx]->avctx = avctx;
3031                                 continue; }
3032                         case AVMEDIA_TYPE_AUDIO: {
3033                                 int aidx = ffaudio.size();
3034                                 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3035                                 if( aidx < 0 ) break;
3036                                 ffaudio[aidx]->avctx = avctx;
3037                                 continue; }
3038                         default: break;
3039                         }
3040                 }
3041                 fprintf(stderr,"FFMPEG::scan: ");
3042                 fprintf(stderr,_("codec open failed\n"));
3043                 fprintf(stderr,"FFMPEG::scan:file=%s\n", file_base->asset->path);
3044                 avcodec_free_context(&avctx);
3045         }
3046
3047         decode_activate();
3048         for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
3049                 AVStream *st = fmt_ctx->streams[i];
3050                 AVCodecParameters *avpar = st->codecpar;
3051                 if( avpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
3052                 int64_t tstmp = st->start_time;
3053                 if( tstmp == AV_NOPTS_VALUE ) continue;
3054                 int aidx = ffaudio.size();
3055                 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3056                 if( aidx < 0 ) continue;
3057                 FFAudioStream *aud = ffaudio[aidx];
3058                 tstmp -= aud->nudge;
3059                 double secs = to_secs(tstmp, st->time_base);
3060                 aud->curr_pos = secs * aud->sample_rate + 0.5;
3061         }
3062
3063         int errs = 0;
3064         for( int64_t count=0; !*canceled; ++count ) {
3065                 av_packet_unref(&pkt);
3066                 pkt.data = 0; pkt.size = 0;
3067
3068                 int ret = av_read_frame(fmt_ctx, &pkt);
3069                 if( ret < 0 ) {
3070                         if( ret == AVERROR_EOF ) break;
3071                         if( ++errs > 100 ) {
3072                                 ff_err(ret,_("over 100 read_frame errs\n"));
3073                                 break;
3074                         }
3075                         continue;
3076                 }
3077                 if( !pkt.data ) continue;
3078                 int i = pkt.stream_index;
3079                 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
3080                 AVStream *st = fmt_ctx->streams[i];
3081                 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
3082
3083                 AVCodecParameters *avpar = st->codecpar;
3084                 switch( avpar->codec_type ) {
3085                 case AVMEDIA_TYPE_VIDEO: {
3086                         int vidx = ffvideo.size();
3087                         while( --vidx>=0 && ffvideo[vidx]->fidx != i );
3088                         if( vidx < 0 ) break;
3089                         FFVideoStream *vid = ffvideo[vidx];
3090                         if( !vid->avctx ) break;
3091                         int64_t tstmp = pkt.dts;
3092                         if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.pts;
3093                         if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
3094                                 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
3095                                 double secs = to_secs(tstmp, st->time_base);
3096                                 int64_t frm = secs * vid->frame_rate + 0.5;
3097                                 if( frm < 0 ) frm = 0;
3098                                 index_state->put_video_mark(vidx, frm, pkt.pos);
3099                         }
3100 #if 0
3101                         ret = avcodec_send_packet(vid->avctx, pkt);
3102                         if( ret < 0 ) break;
3103                         while( (ret=vid->decode_frame(frame)) > 0 ) {}
3104 #endif
3105                         break; }
3106                 case AVMEDIA_TYPE_AUDIO: {
3107                         int aidx = ffaudio.size();
3108                         while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3109                         if( aidx < 0 ) break;
3110                         FFAudioStream *aud = ffaudio[aidx];
3111                         if( !aud->avctx ) break;
3112                         int64_t tstmp = pkt.pts;
3113                         if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
3114                         if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
3115                                 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
3116                                 double secs = to_secs(tstmp, st->time_base);
3117                                 int64_t sample = secs * aud->sample_rate + 0.5;
3118                                 if( sample >= 0 )
3119                                         index_state->put_audio_mark(aidx, sample, pkt.pos);
3120                         }
3121                         ret = avcodec_send_packet(aud->avctx, &pkt);
3122                         if( ret < 0 ) break;
3123                         int ch = aud->channel0,  nch = aud->channels;
3124                         int64_t pos = index_state->pos(ch);
3125                         if( pos != aud->curr_pos ) {
3126 if( abs(pos-aud->curr_pos) > 1 )
3127 printf("audio%d pad %jd %jd (%jd)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
3128                                 index_state->pad_data(ch, nch, aud->curr_pos);
3129                         }
3130                         while( (ret=aud->decode_frame(frame)) > 0 ) {
3131                                 //if( frame->channels != nch ) break;
3132                                 aud->init_swr(frame->channels, frame->format, frame->sample_rate);
3133                                 float *samples;
3134                                 int len = aud->get_samples(samples,
3135                                          &frame->extended_data[0], frame->nb_samples);
3136                                 pos = aud->curr_pos;
3137                                 if( (aud->curr_pos += len) >= 0 ) {
3138                                         if( pos < 0 ) {
3139                                                 samples += -pos * nch;
3140                                                 len = aud->curr_pos;
3141                                         }
3142                                         for( int i=0; i<nch; ++i )
3143                                                 index_state->put_data(ch+i,nch,samples+i,len);
3144                                 }
3145                         }
3146                         break; }
3147                 default: break;
3148                 }
3149         }
3150         av_frame_free(&frame);
3151         return 0;
3152 }
3153
3154 void FFStream::load_markers(IndexMarks &marks, double rate)
3155 {
3156         int in = 0;
3157         int64_t sz = marks.size();
3158         int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
3159         int nb_ent = st->nb_index_entries;
3160 // some formats already have an index
3161         if( nb_ent > 0 ) {
3162                 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
3163                 int64_t tstmp = ep->timestamp;
3164                 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
3165                 double secs = ffmpeg->to_secs(tstmp, st->time_base);
3166                 int64_t no = secs * rate;
3167                 while( in < sz && marks[in].no <= no ) ++in;
3168         }
3169         int64_t len = sz - in;
3170         int64_t count = max_entries - nb_ent;
3171         if( count > len ) count = len;
3172         for( int i=0; i<count; ++i ) {
3173                 int k = in + i * len / count;
3174                 int64_t no = marks[k].no, pos = marks[k].pos;
3175                 double secs = (double)no / rate;
3176                 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
3177                 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
3178                 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);
3179         }
3180 }
3181