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