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