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