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