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