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