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