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