Credit Andrew DVD improvement and if def 0 save
[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                 ret = av_hwdevice_ctx_create(&hw_device_ctx, type, 0, 0, 0);
1164                 if( ret >= 0 ) {
1165                         avctx->hw_device_ctx = av_buffer_ref(hw_device_ctx);
1166                         ret = 1;
1167                 }
1168                 else {
1169                         ff_err(ret, "Failed HW device create.\ndev:%s\n",
1170                                 av_hwdevice_get_type_name(type));
1171                         ret = -1;
1172                 }
1173         }
1174         return ret;
1175 }
1176
1177 AVHWDeviceType FFVideoStream::encode_hw_activate(const char *hw_dev)
1178 {
1179         AVBufferRef *hw_device_ctx = 0;
1180         AVBufferRef *hw_frames_ref = 0;
1181         AVHWDeviceType type = AV_HWDEVICE_TYPE_NONE;
1182         if( strcmp(_("none"), hw_dev) ) {
1183                 type = av_hwdevice_find_type_by_name(hw_dev);
1184                 if( type != AV_HWDEVICE_TYPE_VAAPI ) {
1185                         fprintf(stderr, "currently, only vaapi hw encode is supported\n");
1186                         type = AV_HWDEVICE_TYPE_NONE;
1187                 }
1188         }
1189         if( type != AV_HWDEVICE_TYPE_NONE ) {
1190                 int ret = av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_VAAPI, 0, 0, 0);
1191                 if( ret < 0 ) {
1192                         ff_err(ret, "Failed to create a HW device.\n");
1193                         type = AV_HWDEVICE_TYPE_NONE;
1194                 }
1195         }
1196         if( type != AV_HWDEVICE_TYPE_NONE ) {
1197                 hw_frames_ref = av_hwframe_ctx_alloc(hw_device_ctx);
1198                 if( !hw_frames_ref ) {
1199                         fprintf(stderr, "Failed to create HW frame context.\n");
1200                         type = AV_HWDEVICE_TYPE_NONE;
1201                 }
1202         }
1203         if( type != AV_HWDEVICE_TYPE_NONE ) {
1204                 AVHWFramesContext *frames_ctx = (AVHWFramesContext *)(hw_frames_ref->data);
1205                 frames_ctx->format = AV_PIX_FMT_VAAPI;
1206                 frames_ctx->sw_format = AV_PIX_FMT_NV12;
1207                 frames_ctx->width = width;
1208                 frames_ctx->height = height;
1209                 frames_ctx->initial_pool_size = 0; // 200;
1210                 int ret = av_hwframe_ctx_init(hw_frames_ref);
1211                 if( ret >= 0 ) {
1212                         avctx->hw_frames_ctx = av_buffer_ref(hw_frames_ref);
1213                         if( !avctx->hw_frames_ctx ) ret = AVERROR(ENOMEM);
1214                 }
1215                 if( ret < 0 ) {
1216                         ff_err(ret, "Failed to initialize HW frame context.\n");
1217                         type = AV_HWDEVICE_TYPE_NONE;
1218                 }
1219                 av_buffer_unref(&hw_frames_ref);
1220         }
1221         return type;
1222 }
1223
1224 int FFVideoStream::encode_hw_write(FFrame *picture)
1225 {
1226         int ret = 0;
1227         AVFrame *hw_frm = 0;
1228         switch( avctx->pix_fmt ) {
1229         case AV_PIX_FMT_VAAPI:
1230                 hw_frm = av_frame_alloc();
1231                 if( !hw_frm ) { ret = AVERROR(ENOMEM);  break; }
1232                 ret = av_hwframe_get_buffer(avctx->hw_frames_ctx, hw_frm, 0);
1233                 if( ret < 0 ) break;
1234                 ret = av_hwframe_transfer_data(hw_frm, *picture, 0);
1235                 if( ret < 0 ) break;
1236                 picture->set_hw_frame(hw_frm);
1237                 return 0;
1238         default:
1239                 return 0;
1240         }
1241         av_frame_free(&hw_frm);
1242         ff_err(ret, "Error while transferring frame data to GPU.\n");
1243         return ret;
1244 }
1245
1246 int FFVideoStream::decode_frame(AVFrame *frame)
1247 {
1248         int first_frame = seeked;  seeked = 0;
1249         int ret = avcodec_receive_frame(avctx, frame);
1250         if( ret < 0 ) {
1251                 if( first_frame ) return 0;
1252                 if( ret == AVERROR(EAGAIN) ) return 0;
1253                 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
1254                 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame.\nfile:%s\n,",
1255                                 ffmpeg->fmt_ctx->url);
1256                 return -1;
1257         }
1258         int64_t pkt_ts = frame->best_effort_timestamp;
1259         if( pkt_ts != AV_NOPTS_VALUE )
1260                 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * frame_rate + 0.5;
1261         return 1;
1262 }
1263
1264 int FFVideoStream::probe(int64_t pos)
1265 {
1266         int ret = video_seek(pos);
1267         if( ret < 0 ) return -1;
1268         if( !frame && !(frame=av_frame_alloc()) ) {
1269                 fprintf(stderr, "FFVideoStream::probe: av_frame_alloc failed\n");
1270                 return -1;
1271         }
1272                 
1273         if (ffmpeg->interlace_from_codec) return 1;
1274
1275                 ret = read_frame(frame);
1276                 if( ret > 0 ) {
1277                         //printf("codec interlace: %i \n",frame->interlaced_frame);
1278                         //printf("codec tff: %i \n",frame->top_field_first);
1279
1280                         if (!frame->interlaced_frame)
1281                                 ffmpeg->interlace_from_codec = AV_FIELD_PROGRESSIVE;
1282                         if ((frame->interlaced_frame) && (frame->top_field_first))
1283                                 ffmpeg->interlace_from_codec = AV_FIELD_TT;
1284                         if ((frame->interlaced_frame) && (!frame->top_field_first))
1285                                 ffmpeg->interlace_from_codec = AV_FIELD_BB;
1286                         //printf("Interlace mode from codec: %i\n", ffmpeg->interlace_from_codec);
1287
1288         }
1289
1290         if( frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0 )
1291                 ret = -1;
1292
1293         ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
1294         av_frame_free(&frame);
1295         return ret;
1296 }
1297
1298 int FFVideoStream::load(VFrame *vframe, int64_t pos)
1299 {
1300         int ret = video_seek(pos);
1301         if( ret < 0 ) return -1;
1302         if( !frame && !(frame=av_frame_alloc()) ) {
1303                 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
1304                 return -1;
1305         }
1306         
1307
1308         int i = MAX_RETRY + pos - curr_pos;
1309         int64_t cache_start = 0;
1310         while( ret>=0 && !flushed && curr_pos<=pos && --i>=0 ) {
1311                 ret = read_frame(frame);
1312                 if( ret > 0 ) {
1313                         if( frame->key_frame && seeking < 0 ) {
1314                                 int use_cache = ffmpeg->get_use_cache();
1315                                 if( use_cache < 0 ) {
1316 // for reverse read, reload file frame_cache from keyframe to pos
1317                                         ffmpeg->purge_cache();
1318                                         int count = preferences->cache_size /
1319                                                 vframe->get_data_size() / 2;  // try to burn only 1/2 of cache
1320                                         cache_start = pos - count + 1;
1321                                         seeking = 1;
1322                                 }
1323                                 else
1324                                         seeking = 0;
1325                         }
1326                         if( seeking > 0 && curr_pos >= cache_start && curr_pos < pos ) {
1327                                 int vw =vframe->get_w(), vh = vframe->get_h();
1328                                 int vcolor_model = vframe->get_color_model();
1329 // do not use shm here, puts too much pressure on 32bit systems
1330                                 VFrame *cache_frame = new VFrame(vw, vh, vcolor_model, 0);
1331                                 ret = convert_cmodel(cache_frame, frame);
1332                                 if( ret > 0 )
1333                                         ffmpeg->put_cache_frame(cache_frame, curr_pos);
1334                         }
1335                         ++curr_pos;
1336                 }
1337         }
1338         seeking = 0;
1339         if( frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0 )
1340                 ret = -1;
1341         if( ret >= 0 ) {
1342                 ret = convert_cmodel(vframe, frame);
1343         }
1344         ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
1345         return ret;
1346 }
1347
1348 int FFVideoStream::video_seek(int64_t pos)
1349 {
1350         if( decode_activate() <= 0 ) return -1;
1351         if( !st->codecpar ) return -1;
1352         if( pos == curr_pos-1 && !seeked ) return 0;
1353 // if close enough, just read up to current
1354         int gop = avctx->gop_size;
1355         if( gop < 4 ) gop = 4;
1356         if( gop > 64 ) gop = 64;
1357         int read_limit = curr_pos + 3*gop;
1358         if( pos >= curr_pos && pos <= read_limit ) return 0;
1359 // guarentee preload more than 2*gop frames
1360         if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
1361         return 1;
1362 }
1363
1364 int FFVideoStream::init_frame(AVFrame *picture)
1365 {
1366         switch( avctx->pix_fmt ) {
1367         case AV_PIX_FMT_VAAPI:
1368                 picture->format = AV_PIX_FMT_NV12;
1369                 break;
1370         default:
1371                 picture->format = avctx->pix_fmt;
1372                 break;
1373         }
1374         picture->width  = avctx->width;
1375         picture->height = avctx->height;
1376         int ret = av_frame_get_buffer(picture, 32);
1377         return ret;
1378 }
1379
1380 int FFVideoStream::convert_hw_frame(AVFrame *ifrm, AVFrame *ofrm)
1381 {
1382         AVPixelFormat ifmt = (AVPixelFormat)ifrm->format;
1383         AVPixelFormat ofmt = (AVPixelFormat)st->codecpar->format;
1384         ofrm->width  = ifrm->width;
1385         ofrm->height = ifrm->height;
1386         ofrm->format = ofmt;
1387         int ret = av_frame_get_buffer(ofrm, 32);
1388         if( ret < 0 ) {
1389                 ff_err(ret, "FFVideoStream::convert_hw_frame:"
1390                                 " av_frame_get_buffer failed\n");
1391                 return -1;
1392         }
1393         fconvert_ctx = sws_getCachedContext(fconvert_ctx,
1394                 ifrm->width, ifrm->height, ifmt,
1395                 ofrm->width, ofrm->height, ofmt,
1396                 SWS_POINT, NULL, NULL, NULL);
1397         if( !fconvert_ctx ) {
1398                 ff_err(AVERROR(EINVAL), "FFVideoStream::convert_hw_frame:"
1399                                 " sws_getCachedContext() failed\n");
1400                 return -1;
1401         }
1402         int codec_range = st->codecpar->color_range;
1403         int codec_space = st->codecpar->color_space;
1404         const int *codec_table = sws_getCoefficients(codec_space);
1405         int *inv_table, *table, src_range, dst_range;
1406         int brightness, contrast, saturation;
1407         if( !sws_getColorspaceDetails(fconvert_ctx,
1408                         &inv_table, &src_range, &table, &dst_range,
1409                         &brightness, &contrast, &saturation) ) {
1410                 if( src_range != codec_range || dst_range != codec_range ||
1411                     inv_table != codec_table || table != codec_table )
1412                         sws_setColorspaceDetails(fconvert_ctx,
1413                                         codec_table, codec_range, codec_table, codec_range,
1414                                         brightness, contrast, saturation);
1415         }
1416         ret = sws_scale(fconvert_ctx,
1417                 ifrm->data, ifrm->linesize, 0, ifrm->height,
1418                 ofrm->data, ofrm->linesize);
1419         if( ret < 0 ) {
1420                 ff_err(ret, "FFVideoStream::convert_hw_frame:"
1421                                 " sws_scale() failed\nfile: %s\n",
1422                                 ffmpeg->fmt_ctx->url);
1423                 return -1;
1424         }
1425         return 0;
1426 }
1427
1428 int FFVideoStream::load_filter(AVFrame *frame)
1429 {
1430         AVPixelFormat pix_fmt = (AVPixelFormat)frame->format;
1431         if( pix_fmt == hw_pixfmt ) {
1432                 AVFrame *hw_frame = this->frame;
1433                 av_frame_unref(hw_frame);
1434                 int ret = av_hwframe_transfer_data(hw_frame, frame, 0);
1435                 if( ret < 0 ) {
1436                         eprintf(_("Error retrieving data from GPU to CPU\nfile: %s\n"),
1437                                 ffmpeg->fmt_ctx->url);
1438                         return -1;
1439                 }
1440                 av_frame_unref(frame);
1441                 ret = convert_hw_frame(hw_frame, frame);
1442                 if( ret < 0 ) {
1443                         eprintf(_("Error converting data from GPU to CPU\nfile: %s\n"),
1444                                 ffmpeg->fmt_ctx->url);
1445                         return -1;
1446                 }
1447                 av_frame_unref(hw_frame);
1448         }
1449         return FFStream::load_filter(frame);
1450 }
1451
1452 int FFVideoStream::encode(VFrame *vframe)
1453 {
1454         if( encode_activate() <= 0 ) return -1;
1455         ffmpeg->flow_ctl();
1456         FFrame *picture = new FFrame(this);
1457         int ret = picture->initted();
1458         if( ret >= 0 ) {
1459                 AVFrame *frame = *picture;
1460                 frame->pts = curr_pos;
1461                 ret = convert_pixfmt(vframe, frame);
1462         }
1463         if( ret >= 0 && avctx->hw_frames_ctx )
1464                 encode_hw_write(picture);
1465         if( ret >= 0 ) {
1466                 picture->queue(curr_pos);
1467                 ++curr_pos;
1468         }
1469         else {
1470                 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
1471                 delete picture;
1472         }
1473         return ret >= 0 ? 0 : 1;
1474 }
1475
1476 int FFVideoStream::drain()
1477 {
1478
1479         return 0;
1480 }
1481
1482 int FFVideoStream::encode_frame(AVFrame *frame)
1483 {
1484         if( frame ) {
1485                 frame->interlaced_frame = interlaced;
1486                 frame->top_field_first = top_field_first;
1487         }
1488         if( frame && frame->format == AV_PIX_FMT_VAAPI ) { // ugly
1489                 int ret = avcodec_send_frame(avctx, frame);
1490                 for( int retry=MAX_RETRY; !ret && --retry>=0; ) {
1491                         FFPacket pkt;  av_init_packet(pkt);
1492                         pkt->data = NULL;  pkt->size = 0;
1493                         if( (ret=avcodec_receive_packet(avctx, pkt)) < 0 ) {
1494                                 if( ret == AVERROR(EAGAIN) ) ret = 0; // weird
1495                                 break;
1496                         }
1497                         ret = write_packet(pkt);
1498                         pkt->stream_index = 0;
1499                         av_packet_unref(pkt);
1500                 }
1501                 if( ret < 0 ) {
1502                         ff_err(ret, "FFStream::encode_frame: vaapi encode failed.\nfile: %s\n",
1503                                 ffmpeg->fmt_ctx->url);
1504                         return -1;
1505                 }
1506                 return 0;
1507         }
1508         return FFStream::encode_frame(frame);
1509 }
1510
1511 int FFVideoStream::write_packet(FFPacket &pkt)
1512 {
1513         if( !(ffmpeg->fmt_ctx->oformat->flags & AVFMT_VARIABLE_FPS) )
1514                 pkt->duration = 1;
1515         return FFStream::write_packet(pkt);
1516 }
1517
1518 AVPixelFormat FFVideoConvert::color_model_to_pix_fmt(int color_model)
1519 {
1520         switch( color_model ) {
1521         case BC_YUV422:         return AV_PIX_FMT_YUYV422;
1522         case BC_RGB888:         return AV_PIX_FMT_RGB24;
1523         case BC_RGBA8888:       return AV_PIX_FMT_RGBA;
1524         case BC_BGR8888:        return AV_PIX_FMT_BGR0;
1525         case BC_BGR888:         return AV_PIX_FMT_BGR24;
1526         case BC_ARGB8888:       return AV_PIX_FMT_ARGB;
1527         case BC_ABGR8888:       return AV_PIX_FMT_ABGR;
1528         case BC_RGB8:           return AV_PIX_FMT_RGB8;
1529         case BC_YUV420P:        return AV_PIX_FMT_YUV420P;
1530         case BC_YUV422P:        return AV_PIX_FMT_YUV422P;
1531         case BC_YUV444P:        return AV_PIX_FMT_YUV444P;
1532         case BC_YUV411P:        return AV_PIX_FMT_YUV411P;
1533         case BC_RGB565:         return AV_PIX_FMT_RGB565;
1534         case BC_RGB161616:      return AV_PIX_FMT_RGB48LE;
1535         case BC_RGBA16161616:   return AV_PIX_FMT_RGBA64LE;
1536         case BC_AYUV16161616:   return AV_PIX_FMT_AYUV64LE;
1537         case BC_GBRP:           return AV_PIX_FMT_GBRP;
1538         default: break;
1539         }
1540
1541         return AV_PIX_FMT_NB;
1542 }
1543
1544 int FFVideoConvert::pix_fmt_to_color_model(AVPixelFormat pix_fmt)
1545 {
1546         switch (pix_fmt) {
1547         case AV_PIX_FMT_YUYV422:        return BC_YUV422;
1548         case AV_PIX_FMT_RGB24:          return BC_RGB888;
1549         case AV_PIX_FMT_RGBA:           return BC_RGBA8888;
1550         case AV_PIX_FMT_BGR0:           return BC_BGR8888;
1551         case AV_PIX_FMT_BGR24:          return BC_BGR888;
1552         case AV_PIX_FMT_ARGB:           return BC_ARGB8888;
1553         case AV_PIX_FMT_ABGR:           return BC_ABGR8888;
1554         case AV_PIX_FMT_RGB8:           return BC_RGB8;
1555         case AV_PIX_FMT_YUV420P:        return BC_YUV420P;
1556         case AV_PIX_FMT_YUV422P:        return BC_YUV422P;
1557         case AV_PIX_FMT_YUV444P:        return BC_YUV444P;
1558         case AV_PIX_FMT_YUV411P:        return BC_YUV411P;
1559         case AV_PIX_FMT_RGB565:         return BC_RGB565;
1560         case AV_PIX_FMT_RGB48LE:        return BC_RGB161616;
1561         case AV_PIX_FMT_RGBA64LE:       return BC_RGBA16161616;
1562         case AV_PIX_FMT_AYUV64LE:       return BC_AYUV16161616;
1563         case AV_PIX_FMT_GBRP:           return BC_GBRP;
1564         default: break;
1565         }
1566
1567         return -1;
1568 }
1569
1570 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip)
1571 {
1572         AVFrame *ipic = av_frame_alloc();
1573         int ret = convert_picture_vframe(frame, ip, ipic);
1574         av_frame_free(&ipic);
1575         return ret;
1576 }
1577
1578 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip, AVFrame *ipic)
1579 { // picture = vframe
1580         int cmodel = frame->get_color_model();
1581         AVPixelFormat ofmt = color_model_to_pix_fmt(cmodel);
1582         if( ofmt == AV_PIX_FMT_NB ) return -1;
1583         int size = av_image_fill_arrays(ipic->data, ipic->linesize,
1584                 frame->get_data(), ofmt, frame->get_w(), frame->get_h(), 1);
1585         if( size < 0 ) return -1;
1586
1587         int bpp = BC_CModels::calculate_pixelsize(cmodel);
1588         int ysz = bpp * frame->get_w(), usz = ysz;
1589         switch( cmodel ) {
1590         case BC_YUV410P:
1591         case BC_YUV411P:
1592                 usz /= 2;
1593         case BC_YUV420P:
1594         case BC_YUV422P:
1595                 usz /= 2;
1596         case BC_YUV444P:
1597         case BC_GBRP:
1598                 // override av_image_fill_arrays() for planar types
1599                 ipic->data[0] = frame->get_y();  ipic->linesize[0] = ysz;
1600                 ipic->data[1] = frame->get_u();  ipic->linesize[1] = usz;
1601                 ipic->data[2] = frame->get_v();  ipic->linesize[2] = usz;
1602                 break;
1603         default:
1604                 ipic->data[0] = frame->get_data();
1605                 ipic->linesize[0] = frame->get_bytes_per_line();
1606                 break;
1607         }
1608
1609         AVPixelFormat pix_fmt = (AVPixelFormat)ip->format;
1610         FFVideoStream *vid =(FFVideoStream *)this;
1611         if( pix_fmt == vid->hw_pixfmt ) {
1612                 int ret = 0;
1613                 if( !sw_frame && !(sw_frame=av_frame_alloc()) )
1614                         ret = AVERROR(ENOMEM);
1615                 if( !ret ) {
1616                         ret = av_hwframe_transfer_data(sw_frame, ip, 0);
1617                         ip = sw_frame;
1618                         pix_fmt = (AVPixelFormat)ip->format;
1619                 }
1620                 if( ret < 0 ) {
1621                         eprintf(_("Error retrieving data from GPU to CPU\nfile: %s\n"),
1622                                 vid->ffmpeg->fmt_ctx->url);
1623                         return -1;
1624                 }
1625         }
1626         convert_ctx = sws_getCachedContext(convert_ctx, ip->width, ip->height, pix_fmt,
1627                 frame->get_w(), frame->get_h(), ofmt, SWS_POINT, NULL, NULL, NULL);
1628         if( !convert_ctx ) {
1629                 fprintf(stderr, "FFVideoConvert::convert_picture_frame:"
1630                                 " sws_getCachedContext() failed\n");
1631                 return -1;
1632         }
1633
1634         int color_range = 0;
1635         switch( preferences->yuv_color_range ) {
1636         case BC_COLORS_JPEG:  color_range = 1;  break;
1637         case BC_COLORS_MPEG:  color_range = 0;  break;
1638         }
1639         int color_space = SWS_CS_ITU601;
1640         switch( preferences->yuv_color_space ) {
1641         case BC_COLORS_BT601_PAL:  color_space = SWS_CS_ITU601;  break;
1642         case BC_COLORS_BT601_NTSC: color_space = SWS_CS_SMPTE170M; break;
1643         case BC_COLORS_BT709:  color_space = SWS_CS_ITU709;  break;
1644         case BC_COLORS_BT2020_NCL: 
1645         case BC_COLORS_BT2020_CL: color_space = SWS_CS_BT2020;  break;
1646         }
1647         const int *color_table = sws_getCoefficients(color_space);
1648
1649         int *inv_table, *table, src_range, dst_range;
1650         int brightness, contrast, saturation;
1651         if( !sws_getColorspaceDetails(convert_ctx,
1652                         &inv_table, &src_range, &table, &dst_range,
1653                         &brightness, &contrast, &saturation) ) {
1654                 if( src_range != color_range || dst_range != color_range ||
1655                     inv_table != color_table || table != color_table )
1656                         sws_setColorspaceDetails(convert_ctx,
1657                                         color_table, color_range, color_table, color_range,
1658                                         brightness, contrast, saturation);
1659         }
1660
1661         int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ip->height,
1662             ipic->data, ipic->linesize);
1663         if( ret < 0 ) {
1664                 ff_err(ret, "FFVideoConvert::convert_picture_frame: sws_scale() failed\nfile: %s\n",
1665                         vid->ffmpeg->fmt_ctx->url);
1666                 return -1;
1667         }
1668         return 0;
1669 }
1670
1671 int FFVideoConvert::convert_cmodel(VFrame *frame, AVFrame *ip)
1672 {
1673         // try direct transfer
1674         if( !convert_picture_vframe(frame, ip) ) return 1;
1675         // use indirect transfer
1676         AVPixelFormat ifmt = (AVPixelFormat)ip->format;
1677         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
1678         int max_bits = 0;
1679         for( int i = 0; i <desc->nb_components; ++i ) {
1680                 int bits = desc->comp[i].depth;
1681                 if( bits > max_bits ) max_bits = bits;
1682         }
1683         int imodel = pix_fmt_to_color_model(ifmt);
1684         int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1685         int cmodel = frame->get_color_model();
1686         int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1687         if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1688                 imodel = cmodel_is_yuv ?
1689                     (BC_CModels::has_alpha(cmodel) ?
1690                         BC_AYUV16161616 :
1691                         (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1692                     (BC_CModels::has_alpha(cmodel) ?
1693                         (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1694                         (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1695         }
1696         VFrame vframe(ip->width, ip->height, imodel);
1697         if( convert_picture_vframe(&vframe, ip) ) return -1;
1698         frame->transfer_from(&vframe);
1699         return 1;
1700 }
1701
1702 int FFVideoConvert::transfer_cmodel(VFrame *frame, AVFrame *ifp)
1703 {
1704         int ret = convert_cmodel(frame, ifp);
1705         if( ret > 0 ) {
1706                 const AVDictionary *src = ifp->metadata;
1707                 AVDictionaryEntry *t = NULL;
1708                 BC_Hash *hp = frame->get_params();
1709                 //hp->clear();
1710                 while( (t=av_dict_get(src, "", t, AV_DICT_IGNORE_SUFFIX)) )
1711                         hp->update(t->key, t->value);
1712         }
1713         return ret;
1714 }
1715
1716 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op)
1717 {
1718         AVFrame *opic = av_frame_alloc();
1719         int ret = convert_vframe_picture(frame, op, opic);
1720         av_frame_free(&opic);
1721         return ret;
1722 }
1723
1724 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op, AVFrame *opic)
1725 { // vframe = picture
1726         int cmodel = frame->get_color_model();
1727         AVPixelFormat ifmt = color_model_to_pix_fmt(cmodel);
1728         if( ifmt == AV_PIX_FMT_NB ) return -1;
1729         int size = av_image_fill_arrays(opic->data, opic->linesize,
1730                  frame->get_data(), ifmt, frame->get_w(), frame->get_h(), 1);
1731         if( size < 0 ) return -1;
1732
1733         int bpp = BC_CModels::calculate_pixelsize(cmodel);
1734         int ysz = bpp * frame->get_w(), usz = ysz;
1735         switch( cmodel ) {
1736         case BC_YUV410P:
1737         case BC_YUV411P:
1738                 usz /= 2;
1739         case BC_YUV420P:
1740         case BC_YUV422P:
1741                 usz /= 2;
1742         case BC_YUV444P:
1743         case BC_GBRP:
1744                 // override av_image_fill_arrays() for planar types
1745                 opic->data[0] = frame->get_y();  opic->linesize[0] = ysz;
1746                 opic->data[1] = frame->get_u();  opic->linesize[1] = usz;
1747                 opic->data[2] = frame->get_v();  opic->linesize[2] = usz;
1748                 break;
1749         default:
1750                 opic->data[0] = frame->get_data();
1751                 opic->linesize[0] = frame->get_bytes_per_line();
1752                 break;
1753         }
1754
1755         AVPixelFormat ofmt = (AVPixelFormat)op->format;
1756         convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(),
1757                 ifmt, op->width, op->height, ofmt, SWS_POINT, NULL, NULL, NULL);
1758         if( !convert_ctx ) {
1759                 fprintf(stderr, "FFVideoConvert::convert_frame_picture:"
1760                                 " sws_getCachedContext() failed\n");
1761                 return -1;
1762         }
1763
1764
1765         int color_range = 0;
1766         switch( preferences->yuv_color_range ) {
1767         case BC_COLORS_JPEG:  color_range = 1;  break;
1768         case BC_COLORS_MPEG:  color_range = 0;  break;
1769         }
1770         int color_space = SWS_CS_ITU601;
1771         switch( preferences->yuv_color_space ) {
1772         case BC_COLORS_BT601_PAL:  color_space = SWS_CS_ITU601;  break;
1773         case BC_COLORS_BT601_NTSC: color_space = SWS_CS_SMPTE170M; break;
1774         case BC_COLORS_BT709:  color_space = SWS_CS_ITU709;  break;
1775         case BC_COLORS_BT2020_NCL:
1776         case BC_COLORS_BT2020_CL: color_space = SWS_CS_BT2020;  break;
1777         }
1778         const int *color_table = sws_getCoefficients(color_space);
1779
1780         int *inv_table, *table, src_range, dst_range;
1781         int brightness, contrast, saturation;
1782         if( !sws_getColorspaceDetails(convert_ctx,
1783                         &inv_table, &src_range, &table, &dst_range,
1784                         &brightness, &contrast, &saturation) ) {
1785                 if( dst_range != color_range || table != color_table )
1786                         sws_setColorspaceDetails(convert_ctx,
1787                                         inv_table, src_range, color_table, color_range,
1788                                         brightness, contrast, saturation);
1789         }
1790
1791         int ret = sws_scale(convert_ctx, opic->data, opic->linesize, 0, frame->get_h(),
1792                         op->data, op->linesize);
1793         if( ret < 0 ) {
1794                 ff_err(ret, "FFVideoConvert::convert_frame_picture: sws_scale() failed\n");
1795                 return -1;
1796         }
1797         return 0;
1798 }
1799
1800 int FFVideoConvert::convert_pixfmt(VFrame *frame, AVFrame *op)
1801 {
1802         // try direct transfer
1803         if( !convert_vframe_picture(frame, op) ) return 1;
1804         // use indirect transfer
1805         int cmodel = frame->get_color_model();
1806         int max_bits = BC_CModels::calculate_pixelsize(cmodel) * 8;
1807         max_bits /= BC_CModels::components(cmodel);
1808         AVPixelFormat ofmt = (AVPixelFormat)op->format;
1809         int imodel = pix_fmt_to_color_model(ofmt);
1810         int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1811         int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1812         if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1813                 imodel = cmodel_is_yuv ?
1814                     (BC_CModels::has_alpha(cmodel) ?
1815                         BC_AYUV16161616 :
1816                         (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1817                     (BC_CModels::has_alpha(cmodel) ?
1818                         (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1819                         (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1820         }
1821         VFrame vframe(frame->get_w(), frame->get_h(), imodel);
1822         vframe.transfer_from(frame);
1823         if( !convert_vframe_picture(&vframe, op) ) return 1;
1824         return -1;
1825 }
1826
1827 int FFVideoConvert::transfer_pixfmt(VFrame *frame, AVFrame *ofp)
1828 {
1829         int ret = convert_pixfmt(frame, ofp);
1830         if( ret > 0 ) {
1831                 BC_Hash *hp = frame->get_params();
1832                 AVDictionary **dict = &ofp->metadata;
1833                 //av_dict_free(dict);
1834                 for( int i=0; i<hp->size(); ++i ) {
1835                         char *key = hp->get_key(i), *val = hp->get_value(i);
1836                         av_dict_set(dict, key, val, 0);
1837                 }
1838         }
1839         return ret;
1840 }
1841
1842 void FFVideoStream::load_markers()
1843 {
1844         IndexState *index_state = ffmpeg->file_base->asset->index_state;
1845         if( !index_state || idx >= index_state->video_markers.size() ) return;
1846         FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
1847 }
1848
1849 IndexMarks *FFVideoStream::get_markers()
1850 {
1851         IndexState *index_state = ffmpeg->file_base->asset->index_state;
1852         if( !index_state || idx >= index_state->video_markers.size() ) return 0;
1853         return !index_state ? 0 : index_state->video_markers[idx];
1854 }
1855
1856
1857 FFMPEG::FFMPEG(FileBase *file_base)
1858 {
1859         fmt_ctx = 0;
1860         this->file_base = file_base;
1861         memset(file_format,0,sizeof(file_format));
1862         mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
1863         flow_lock = new Condition(1,"FFStream::flow_lock",0);
1864         done = -1;
1865         flow = 1;
1866         decoding = encoding = 0;
1867         has_audio = has_video = 0;
1868         interlace_from_codec = 0;
1869         opts = 0;
1870         opt_duration = -1;
1871         opt_video_filter = 0;
1872         opt_audio_filter = 0;
1873         opt_hw_dev = 0;
1874         opt_video_decoder = 0;
1875         opt_audio_decoder = 0;
1876         fflags = 0;
1877         char option_path[BCTEXTLEN];
1878         set_option_path(option_path, "%s", "ffmpeg.opts");
1879         read_options(option_path, opts);
1880 }
1881
1882 FFMPEG::~FFMPEG()
1883 {
1884         ff_lock("FFMPEG::~FFMPEG()");
1885         close_encoder();
1886         ffaudio.remove_all_objects();
1887         ffvideo.remove_all_objects();
1888         if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1889         ff_unlock();
1890         delete flow_lock;
1891         delete mux_lock;
1892         av_dict_free(&opts);
1893         delete [] opt_video_filter;
1894         delete [] opt_audio_filter;
1895         delete [] opt_hw_dev;
1896 }
1897
1898 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
1899 int FFMPEG::check_sample_rate(const AVCodec *codec, int sample_rate)
1900 #else
1901 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1902 #endif
1903 {
1904         const int *p = codec->supported_samplerates;
1905         if( !p ) return sample_rate;
1906         while( *p != 0 ) {
1907                 if( *p == sample_rate ) return *p;
1908                 ++p;
1909         }
1910         return 0;
1911 }
1912
1913 // check_frame_rate and std_frame_rate needed for 23.976
1914 // and 59.94 fps mpeg2
1915 static inline AVRational std_frame_rate(int i)
1916 {
1917         static const int m1 = 1001*12, m2 = 1000*12;
1918         static const int freqs[] = {
1919                 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1920                 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 90*m2,
1921                 100*m2, 120*m2, 144*m2, 72*m2, 0,
1922         };
1923         int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1924         return (AVRational) { freq, 1001*12 };
1925 }
1926
1927 AVRational FFMPEG::check_frame_rate(const AVRational *p, double frame_rate)
1928 {
1929         AVRational rate, best_rate = (AVRational) { 0, 0 };
1930         double max_err = 1.;  int i = 0;
1931         while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1932                 double framerate = (double) rate.num / rate.den;
1933                 double err = fabs(frame_rate/framerate - 1.);
1934                 if( err >= max_err ) continue;
1935                 max_err = err;
1936                 best_rate = rate;
1937         }
1938         return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1939 }
1940
1941 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1942 {
1943 #if 1
1944         double display_aspect = asset->width / (double)asset->height;
1945         double sample_aspect = display_aspect / asset->aspect_ratio;
1946         int width = 1000000, height = width * sample_aspect + 0.5;
1947         float w, h;
1948         MWindow::create_aspect_ratio(w, h, width, height);
1949         return (AVRational){(int)w, (int)h};
1950 #else
1951 // square pixels
1952         return (AVRational){1, 1};
1953 #endif
1954 }
1955
1956 AVRational FFMPEG::to_time_base(int sample_rate)
1957 {
1958         return (AVRational){1, sample_rate};
1959 }
1960
1961 int FFMPEG::get_fmt_score(AVSampleFormat dst_fmt, AVSampleFormat src_fmt)
1962 {
1963         int score = 0;
1964         int dst_planar = av_sample_fmt_is_planar(dst_fmt);
1965         int src_planar = av_sample_fmt_is_planar(src_fmt);
1966         if( dst_planar != src_planar ) ++score;
1967         int dst_bytes = av_get_bytes_per_sample(dst_fmt);
1968         int src_bytes = av_get_bytes_per_sample(src_fmt);
1969         score += (src_bytes > dst_bytes ? 100 : -10) * (src_bytes - dst_bytes);
1970         int src_packed = av_get_packed_sample_fmt(src_fmt);
1971         int dst_packed = av_get_packed_sample_fmt(dst_fmt);
1972         if( dst_packed == AV_SAMPLE_FMT_S32 && src_packed == AV_SAMPLE_FMT_FLT ) score += 20;
1973         if( dst_packed == AV_SAMPLE_FMT_FLT && src_packed == AV_SAMPLE_FMT_S32 ) score += 2;
1974         return score;
1975 }
1976
1977 AVSampleFormat FFMPEG::find_best_sample_fmt_of_list(
1978                 const AVSampleFormat *sample_fmts, AVSampleFormat src_fmt)
1979 {
1980         AVSampleFormat best = AV_SAMPLE_FMT_NONE;
1981         int best_score = get_fmt_score(best, src_fmt);
1982         for( int i=0; sample_fmts[i] >= 0; ++i ) {
1983                 AVSampleFormat sample_fmt = sample_fmts[i];
1984                 int score = get_fmt_score(sample_fmt, src_fmt);
1985                 if( score >= best_score ) continue;
1986                 best = sample_fmt;  best_score = score;
1987         }
1988         return best;
1989 }
1990
1991
1992 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
1993 {
1994         char *ep = path + BCTEXTLEN-1;
1995         strncpy(path, File::get_cindat_path(), ep-path);
1996         strncat(path, "/ffmpeg/", ep-path);
1997         path += strlen(path);
1998         va_list ap;
1999         va_start(ap, fmt);
2000         path += vsnprintf(path, ep-path, fmt, ap);
2001         va_end(ap);
2002         *path = 0;
2003 }
2004
2005 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
2006 {
2007         if( *spec == '/' )
2008                 strcpy(path, spec);
2009         else
2010                 set_option_path(path, "%s/%s", type, spec);
2011 }
2012
2013 int FFMPEG::get_format(char *format, const char *path, const char *spec)
2014 {
2015         char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
2016         get_option_path(option_path, path, spec);
2017         FILE *fp = fopen(option_path,"r");
2018         if( !fp ) return 1;
2019         int ret = 0;
2020         if( !fgets(line, sizeof(line), fp) ) ret = 1;
2021         if( !ret ) {
2022                 line[sizeof(line)-1] = 0;
2023                 ret = scan_option_line(line, format, codec);
2024         }
2025         fclose(fp);
2026         return ret;
2027 }
2028
2029 int FFMPEG::get_codec(char *codec, const char *path, const char *spec)
2030 {
2031         char option_path[BCTEXTLEN], line[BCTEXTLEN], format[BCTEXTLEN];
2032         get_option_path(option_path, path, spec);
2033         FILE *fp = fopen(option_path,"r");
2034         if( !fp ) return 1;
2035         int ret = 0;
2036         if( !fgets(line, sizeof(line), fp) ) ret = 1;
2037         fclose(fp);
2038         if( !ret ) {
2039                 line[sizeof(line)-1] = 0;
2040                 ret = scan_option_line(line, format, codec);
2041         }
2042         if( !ret ) {
2043                 char *vp = codec, *ep = vp+BCTEXTLEN-1;
2044                 while( vp < ep && *vp && *vp != '|' ) ++vp;
2045                 if( *vp == '|' ) --vp;
2046                 while( vp > codec && (*vp==' ' || *vp=='\t') ) *vp-- = 0;
2047         }
2048         return ret;
2049 }
2050
2051 int FFMPEG::get_file_format()
2052 {
2053         char audio_muxer[BCSTRLEN], video_muxer[BCSTRLEN];
2054         char audio_format[BCSTRLEN], video_format[BCSTRLEN];
2055         audio_muxer[0] = audio_format[0] = 0;
2056         video_muxer[0] = video_format[0] = 0;
2057         Asset *asset = file_base->asset;
2058         int ret = asset ? 0 : 1;
2059         if( !ret && asset->audio_data ) {
2060                 if( !(ret=get_format(audio_format, "audio", asset->acodec)) ) {
2061                         if( get_format(audio_muxer, "format", audio_format) ) {
2062                                 strcpy(audio_muxer, audio_format);
2063                                 audio_format[0] = 0;
2064                         }
2065                 }
2066         }
2067         if( !ret && asset->video_data ) {
2068                 if( !(ret=get_format(video_format, "video", asset->vcodec)) ) {
2069                         if( get_format(video_muxer, "format", video_format) ) {
2070                                 strcpy(video_muxer, video_format);
2071                                 video_format[0] = 0;
2072                         }
2073                 }
2074         }
2075         if( !ret && !audio_muxer[0] && !video_muxer[0] )
2076                 ret = 1;
2077         if( !ret && audio_muxer[0] && video_muxer[0] &&
2078             strcmp(audio_muxer, video_muxer) ) ret = -1;
2079         if( !ret && audio_format[0] && video_format[0] &&
2080             strcmp(audio_format, video_format) ) ret = -1;
2081         if( !ret )
2082                 strcpy(file_format, !audio_format[0] && !video_format[0] ?
2083                         (audio_muxer[0] ? audio_muxer : video_muxer) :
2084                         (audio_format[0] ? audio_format : video_format));
2085         return ret;
2086 }
2087
2088 int FFMPEG::scan_option_line(const char *cp, char *tag, char *val)
2089 {
2090         while( *cp == ' ' || *cp == '\t' ) ++cp;
2091         const char *bp = cp;
2092         while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' && *cp != '\n' ) ++cp;
2093         int len = cp - bp;
2094         if( !len || len > BCSTRLEN-1 ) return 1;
2095         while( bp < cp ) *tag++ = *bp++;
2096         *tag = 0;
2097         while( *cp == ' ' || *cp == '\t' ) ++cp;
2098         if( *cp == '=' ) ++cp;
2099         while( *cp == ' ' || *cp == '\t' ) ++cp;
2100         bp = cp;
2101         while( *cp && *cp != '\n' ) ++cp;
2102         len = cp - bp;
2103         if( len > BCTEXTLEN-1 ) return 1;
2104         while( bp < cp ) *val++ = *bp++;
2105         *val = 0;
2106         return 0;
2107 }
2108
2109 int FFMPEG::can_render(const char *fformat, const char *type)
2110 {
2111         FileSystem fs;
2112         char option_path[BCTEXTLEN];
2113         FFMPEG::set_option_path(option_path, type);
2114         fs.update(option_path);
2115         int total_files = fs.total_files();
2116         for( int i=0; i<total_files; ++i ) {
2117                 const char *name = fs.get_entry(i)->get_name();
2118                 const char *ext = strrchr(name,'.');
2119                 if( !ext ) continue;
2120                 if( !strcmp(fformat, ++ext) ) return 1;
2121         }
2122         return 0;
2123 }
2124
2125 int FFMPEG::get_ff_option(const char *nm, const char *options, char *value)
2126 {
2127         for( const char *cp=options; *cp!=0; ) {
2128                 char line[BCTEXTLEN], *bp = line, *ep = bp+sizeof(line)-1;
2129                 while( bp < ep && *cp && *cp!='\n' ) *bp++ = *cp++;
2130                 if( *cp ) ++cp;
2131                 *bp = 0;
2132                 if( !line[0] || line[0] == '#' || line[0] == ';' ) continue;
2133                 char key[BCSTRLEN], val[BCTEXTLEN];
2134                 if( FFMPEG::scan_option_line(line, key, val) ) continue;
2135                 if( !strcmp(key, nm) ) {
2136                         strncpy(value, val, BCSTRLEN);
2137                         return 0;
2138                 }
2139         }
2140         return 1;
2141 }
2142
2143 void FFMPEG::scan_audio_options(Asset *asset, EDL *edl)
2144 {
2145         char cin_sample_fmt[BCSTRLEN];
2146         int cin_fmt = AV_SAMPLE_FMT_NONE;
2147         const char *options = asset->ff_audio_options;
2148         if( !get_ff_option("cin_sample_fmt", options, cin_sample_fmt) )
2149                 cin_fmt = (int)av_get_sample_fmt(cin_sample_fmt);
2150         if( cin_fmt < 0 ) {
2151                 char audio_codec[BCSTRLEN]; audio_codec[0] = 0;
2152 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,18,100)
2153                 const AVCodec *av_codec = !FFMPEG::get_codec(audio_codec, "audio", asset->acodec) ?
2154 #else
2155                 AVCodec *av_codec = !FFMPEG::get_codec(audio_codec, "audio", asset->acodec) ?
2156 #endif
2157                         avcodec_find_encoder_by_name(audio_codec) : 0;
2158                 if( av_codec && av_codec->sample_fmts )
2159                         cin_fmt = find_best_sample_fmt_of_list(av_codec->sample_fmts, AV_SAMPLE_FMT_FLT);
2160         }
2161         if( cin_fmt < 0 ) cin_fmt = AV_SAMPLE_FMT_S16;
2162         const char *name = av_get_sample_fmt_name((AVSampleFormat)cin_fmt);
2163         if( !name ) name = _("None");
2164         strcpy(asset->ff_sample_format, name);
2165
2166         char value[BCSTRLEN];
2167         if( !get_ff_option("cin_bitrate", options, value) )
2168                 asset->ff_audio_bitrate = atoi(value);
2169         if( !get_ff_option("cin_quality", options, value) )
2170                 asset->ff_audio_quality = atoi(value);
2171 }
2172
2173 void FFMPEG::load_audio_options(Asset *asset, EDL *edl)
2174 {
2175         char options_path[BCTEXTLEN];
2176         set_option_path(options_path, "audio/%s", asset->acodec);
2177         if( !load_options(options_path,
2178                         asset->ff_audio_options,
2179                         sizeof(asset->ff_audio_options)) )
2180                 scan_audio_options(asset, edl);
2181 }
2182
2183 void FFMPEG::scan_video_options(Asset *asset, EDL *edl)
2184 {
2185         char cin_pix_fmt[BCSTRLEN];
2186         int cin_fmt = AV_PIX_FMT_NONE;
2187         const char *options = asset->ff_video_options;
2188         if( !get_ff_option("cin_pix_fmt", options, cin_pix_fmt) )
2189                         cin_fmt = (int)av_get_pix_fmt(cin_pix_fmt);
2190         if( cin_fmt < 0 ) {
2191                 char video_codec[BCSTRLEN];  video_codec[0] = 0;
2192 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,18,100)
2193                 const AVCodec *av_codec = !get_codec(video_codec, "video", asset->vcodec) ?
2194 #else
2195                 AVCodec *av_codec = !get_codec(video_codec, "video", asset->vcodec) ?
2196 #endif
2197                         avcodec_find_encoder_by_name(video_codec) : 0;
2198                 if( av_codec && av_codec->pix_fmts ) {
2199                         if( 0 && edl ) { // frequently picks a bad answer
2200                                 int color_model = edl->session->color_model;
2201                                 int max_bits = BC_CModels::calculate_pixelsize(color_model) * 8;
2202                                 max_bits /= BC_CModels::components(color_model);
2203                                 cin_fmt = avcodec_find_best_pix_fmt_of_list(av_codec->pix_fmts,
2204                                         (BC_CModels::is_yuv(color_model) ?
2205                                                 (max_bits > 8 ? AV_PIX_FMT_AYUV64LE : AV_PIX_FMT_YUV444P) :
2206                                                 (max_bits > 8 ? AV_PIX_FMT_RGB48LE : AV_PIX_FMT_RGB24)), 0, 0);
2207                         }
2208                         else
2209                                 cin_fmt = av_codec->pix_fmts[0];
2210                 }
2211         }
2212         if( cin_fmt < 0 ) cin_fmt = AV_PIX_FMT_YUV420P;
2213         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get((AVPixelFormat)cin_fmt);
2214         const char *name = desc ? desc->name : _("None");
2215         strcpy(asset->ff_pixel_format, name);
2216
2217         char value[BCSTRLEN];
2218         if( !get_ff_option("cin_bitrate", options, value) )
2219                 asset->ff_video_bitrate = atoi(value);
2220         if( !get_ff_option("cin_quality", options, value) )
2221                 asset->ff_video_quality = atoi(value);
2222 }
2223
2224 void FFMPEG::load_video_options(Asset *asset, EDL *edl)
2225 {
2226         char options_path[BCTEXTLEN];
2227         set_option_path(options_path, "video/%s", asset->vcodec);
2228         if( !load_options(options_path,
2229                         asset->ff_video_options,
2230                         sizeof(asset->ff_video_options)) )
2231                 scan_video_options(asset, edl);
2232 }
2233
2234 void FFMPEG::scan_format_options(Asset *asset, EDL *edl)
2235 {
2236 }
2237
2238 void FFMPEG::load_format_options(Asset *asset, EDL *edl)
2239 {
2240         char options_path[BCTEXTLEN];
2241         set_option_path(options_path, "format/%s", asset->fformat);
2242         if( !load_options(options_path,
2243                         asset->ff_format_options,
2244                         sizeof(asset->ff_format_options)) )
2245                 scan_format_options(asset, edl);
2246 }
2247
2248 int FFMPEG::load_defaults(const char *path, const char *type,
2249                  char *codec, char *codec_options, int len)
2250 {
2251         char default_file[BCTEXTLEN];
2252         set_option_path(default_file, "%s/%s.dfl", path, type);
2253         FILE *fp = fopen(default_file,"r");
2254         if( !fp ) return 1;
2255         fgets(codec, BCSTRLEN, fp);
2256         char *cp = codec;
2257         while( *cp && *cp!='\n' ) ++cp;
2258         *cp = 0;
2259         while( len > 0 && fgets(codec_options, len, fp) ) {
2260                 int n = strlen(codec_options);
2261                 codec_options += n;  len -= n;
2262         }
2263         fclose(fp);
2264         set_option_path(default_file, "%s/%s", path, codec);
2265         return load_options(default_file, codec_options, len);
2266 }
2267
2268 void FFMPEG::set_asset_format(Asset *asset, EDL *edl, const char *text)
2269 {
2270         if( asset->format != FILE_FFMPEG ) return;
2271         if( text != asset->fformat )
2272                 strcpy(asset->fformat, text);
2273         if( !asset->ff_format_options[0] )
2274                 load_format_options(asset, edl);
2275         if( asset->audio_data && !asset->ff_audio_options[0] ) {
2276                 if( !load_defaults("audio", text, asset->acodec,
2277                                 asset->ff_audio_options, sizeof(asset->ff_audio_options)) )
2278                         scan_audio_options(asset, edl);
2279                 else
2280                         asset->audio_data = 0;
2281         }
2282         if( asset->video_data && !asset->ff_video_options[0] ) {
2283                 if( !load_defaults("video", text, asset->vcodec,
2284                                 asset->ff_video_options, sizeof(asset->ff_video_options)) )
2285                         scan_video_options(asset, edl);
2286                 else
2287                         asset->video_data = 0;
2288         }
2289 }
2290
2291 int FFMPEG::get_encoder(const char *options,
2292                 char *format, char *codec, char *bsfilter)
2293 {
2294         FILE *fp = fopen(options,"r");
2295         if( !fp ) {
2296                 eprintf(_("options open failed %s\n"),options);
2297                 return 1;
2298         }
2299         char line[BCTEXTLEN];
2300         if( !fgets(line, sizeof(line), fp) ||
2301             scan_encoder(line, format, codec, bsfilter) )
2302                 eprintf(_("format/codec not found %s\n"), options);
2303         fclose(fp);
2304         return 0;
2305 }
2306
2307 int FFMPEG::scan_encoder(const char *line,
2308                 char *format, char *codec, char *bsfilter)
2309 {
2310         format[0] = codec[0] = bsfilter[0] = 0;
2311         if( scan_option_line(line, format, codec) ) return 1;
2312         char *cp = codec;
2313         while( *cp && *cp != '|' ) ++cp;
2314         if( !*cp ) return 0;
2315         char *bp = cp;
2316         do { *bp-- = 0; } while( bp>=codec && (*bp==' ' || *bp == '\t' ) );
2317         while( *++cp && (*cp==' ' || *cp == '\t') );
2318         bp = bsfilter;
2319         for( int i=BCTEXTLEN; --i>0 && *cp; ) *bp++ = *cp++;
2320         *bp = 0;
2321         return 0;
2322 }
2323
2324 int FFMPEG::read_options(const char *options, AVDictionary *&opts, int skip)
2325 {
2326         FILE *fp = fopen(options,"r");
2327         if( !fp ) return 1;
2328         int ret = 0;
2329         while( !ret && --skip >= 0 ) {
2330                 int ch = getc(fp);
2331                 while( ch >= 0 && ch != '\n' ) ch = getc(fp);
2332                 if( ch < 0 ) ret = 1;
2333         }
2334         if( !ret )
2335                 ret = read_options(fp, options, opts);
2336         fclose(fp);
2337         return ret;
2338 }
2339
2340 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
2341 {
2342         FILE *fp = fmemopen((void *)options,strlen(options),"r");
2343         if( !fp ) return 0;
2344         int ret = read_options(fp, options, opts);
2345         fclose(fp);
2346         if( !ret && st ) {
2347                 AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
2348                 if( tag ) st->id = strtol(tag->value,0,0);
2349         }
2350         return ret;
2351 }
2352
2353 void FFMPEG::put_cache_frame(VFrame *frame, int64_t position)
2354 {
2355         file_base->file->put_cache_frame(frame, position, 0);
2356 }
2357
2358 int FFMPEG::get_use_cache()
2359 {
2360         return file_base->file->get_use_cache();
2361 }
2362
2363 void FFMPEG::purge_cache()
2364 {
2365         file_base->file->purge_cache();
2366 }
2367
2368 FFCodecRemap::FFCodecRemap()
2369 {
2370         old_codec = 0;
2371         new_codec = 0;
2372 }
2373 FFCodecRemap::~FFCodecRemap()
2374 {
2375         delete [] old_codec;
2376         delete [] new_codec;
2377 }
2378
2379 int FFCodecRemaps::add(const char *val)
2380 {
2381         char old_codec[BCSTRLEN], new_codec[BCSTRLEN];
2382         if( sscanf(val, " %63[a-zA-z0-9_-] = %63[a-z0-9_-]",
2383                 &old_codec[0], &new_codec[0]) != 2 ) return 1;
2384         FFCodecRemap &remap = append();
2385         remap.old_codec = cstrdup(old_codec);
2386         remap.new_codec = cstrdup(new_codec);
2387         return 0;
2388 }
2389
2390 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
2391 int FFCodecRemaps::update(AVCodecID &codec_id, const AVCodec *&decoder)
2392 {
2393         const AVCodec *codec = avcodec_find_decoder(codec_id);
2394 #else
2395 int FFCodecRemaps::update(AVCodecID &codec_id, AVCodec *&decoder)
2396 {
2397         AVCodec *codec = avcodec_find_decoder(codec_id);
2398 #endif
2399         if( !codec ) return -1;
2400         const char *name = codec->name;
2401         FFCodecRemaps &map = *this;
2402         int k = map.size();
2403         while( --k >= 0 && strcmp(map[k].old_codec, name) );
2404         if( k < 0 ) return 1;
2405         const char *new_codec = map[k].new_codec;
2406         codec = avcodec_find_decoder_by_name(new_codec);
2407         if( !codec ) return -1;
2408         decoder = codec;
2409         return 0;
2410 }
2411
2412 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
2413 {
2414         int ret = 0, no = 0;
2415         char line[BCTEXTLEN];
2416         while( !ret && fgets(line, sizeof(line), fp) ) {
2417                 line[sizeof(line)-1] = 0;
2418                 if( line[0] == '#' ) continue;
2419                 if( line[0] == '\n' ) continue;
2420                 char key[BCSTRLEN], val[BCTEXTLEN];
2421                 if( scan_option_line(line, key, val) ) {
2422                         eprintf(_("err reading %s: line %d\n"), options, no);
2423                         ret = 1;
2424                 }
2425                 if( !ret ) {
2426                         if( !strcmp(key, "duration") )
2427                                 opt_duration = strtod(val, 0);
2428                         else if( !strcmp(key, "video_decoder") )
2429                                 opt_video_decoder = cstrdup(val);
2430                         else if( !strcmp(key, "audio_decoder") )
2431                                 opt_audio_decoder = cstrdup(val);
2432                         else if( !strcmp(key, "remap_video_decoder") )
2433                                 video_codec_remaps.add(val);
2434                         else if( !strcmp(key, "remap_audio_decoder") )
2435                                 audio_codec_remaps.add(val);
2436                         else if( !strcmp(key, "video_filter") )
2437                                 opt_video_filter = cstrdup(val);
2438                         else if( !strcmp(key, "audio_filter") )
2439                                 opt_audio_filter = cstrdup(val);
2440                         else if( !strcmp(key, "cin_hw_dev") )
2441                                 opt_hw_dev = cstrdup(val);
2442                         else if( !strcmp(key, "loglevel") )
2443                                 set_loglevel(val);
2444                         else
2445                                 av_dict_set(&opts, key, val, 0);
2446                 }
2447         }
2448         return ret;
2449 }
2450
2451 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
2452 {
2453         char option_path[BCTEXTLEN];
2454         set_option_path(option_path, "%s", options);
2455         return read_options(option_path, opts);
2456 }
2457
2458 int FFMPEG::load_options(const char *path, char *bfr, int len)
2459 {
2460         *bfr = 0;
2461         FILE *fp = fopen(path, "r");
2462         if( !fp ) return 1;
2463         fgets(bfr, len, fp); // skip hdr
2464         len = fread(bfr, 1, len-1, fp);
2465         if( len < 0 ) len = 0;
2466         bfr[len] = 0;
2467         fclose(fp);
2468         return 0;
2469 }
2470
2471 void FFMPEG::set_loglevel(const char *ap)
2472 {
2473         if( !ap || !*ap ) return;
2474         const struct {
2475                 const char *name;
2476                 int level;
2477         } log_levels[] = {
2478                 { "quiet"  , AV_LOG_QUIET   },
2479                 { "panic"  , AV_LOG_PANIC   },
2480                 { "fatal"  , AV_LOG_FATAL   },
2481                 { "error"  , AV_LOG_ERROR   },
2482                 { "warning", AV_LOG_WARNING },
2483                 { "info"   , AV_LOG_INFO    },
2484                 { "verbose", AV_LOG_VERBOSE },
2485                 { "debug"  , AV_LOG_DEBUG   },
2486         };
2487         for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
2488                 if( !strcmp(log_levels[i].name, ap) ) {
2489                         av_log_set_level(log_levels[i].level);
2490                         return;
2491                 }
2492         }
2493         av_log_set_level(atoi(ap));
2494 }
2495
2496 double FFMPEG::to_secs(int64_t time, AVRational time_base)
2497 {
2498         double base_time = time == AV_NOPTS_VALUE ? 0 :
2499                 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
2500         return base_time / AV_TIME_BASE;
2501 }
2502
2503 int FFMPEG::info(char *text, int len)
2504 {
2505         if( len <= 0 ) return 0;
2506         decode_activate();
2507 #define report(s...) do { int n = snprintf(cp,len,s); cp += n;  len -= n; } while(0)
2508         char *cp = text;
2509         report("format: %s\n",fmt_ctx->iformat->name);
2510         if( ffvideo.size() > 0 )
2511                 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
2512         for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
2513                 const char *unkn = _("(unkn)");
2514                 FFVideoStream *vid = ffvideo[vidx];
2515                 AVStream *st = vid->st;
2516                 AVCodecID codec_id = st->codecpar->codec_id;
2517                 report(_("vid%d (%d),  id 0x%06x:\n"), vid->idx, vid->fidx, codec_id);
2518                 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
2519                 report("  video%d %s ", vidx+1, desc ? desc->name : unkn);
2520                 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
2521                 AVPixelFormat pix_fmt = (AVPixelFormat)st->codecpar->format;
2522                 const char *pfn = av_get_pix_fmt_name(pix_fmt);
2523                 report(" pix %s\n", pfn ? pfn : unkn);
2524                 int interlace = st->codecpar->field_order;
2525                 report("  interlace (container level): %i\n", interlace ? interlace : -1);
2526                 int interlace_codec = interlace_from_codec;
2527                 report("  interlace (codec level): %i\n", interlace_codec ? interlace_codec : -1);
2528                 enum AVColorSpace space = st->codecpar->color_space;
2529                 const char *nm = av_color_space_name(space);
2530                 report("    color space:%s", nm ? nm : unkn);
2531                 enum AVColorRange range = st->codecpar->color_range;
2532                 const char *rg = av_color_range_name(range);
2533                 report("/ range:%s\n", rg ? rg : unkn);
2534                 double secs = to_secs(st->duration, st->time_base);
2535                 int64_t length = secs * vid->frame_rate + 0.5;
2536                 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
2537                 int64_t nudge = ofs * vid->frame_rate;
2538                 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
2539                 report("    %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
2540                 int hrs = secs/3600;  secs -= hrs*3600;
2541                 int mins = secs/60;  secs -= mins*60;
2542                 report("  %d:%02d:%05.2f\n", hrs, mins, secs);
2543                 double theta = vid->get_rotation_angle();
2544                 if( fabs(theta) > 1 ) 
2545                         report("    rotation angle: %0.1f\n", theta);
2546         }
2547         if( ffaudio.size() > 0 )
2548                 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
2549         for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2550                 FFAudioStream *aud = ffaudio[aidx];
2551                 AVStream *st = aud->st;
2552                 AVCodecID codec_id = st->codecpar->codec_id;
2553                 report(_("aud%d (%d),  id 0x%06x:\n"), aud->idx, aud->fidx, codec_id);
2554                 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
2555                 int nch = aud->channels, ch0 = aud->channel0+1;
2556                 report("  audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
2557                 AVSampleFormat sample_fmt = (AVSampleFormat)st->codecpar->format;
2558                 const char *fmt = av_get_sample_fmt_name(sample_fmt);
2559                 report(" %s %d", fmt, aud->sample_rate);
2560                 int sample_bits = av_get_bits_per_sample(codec_id);
2561                 report(" %dbits\n", sample_bits);
2562                 double secs = to_secs(st->duration, st->time_base);
2563                 int64_t length = secs * aud->sample_rate + 0.5;
2564                 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
2565                 int64_t nudge = ofs * aud->sample_rate;
2566                 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
2567                 report("    %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
2568                 int hrs = secs/3600;  secs -= hrs*3600;
2569                 int mins = secs/60;  secs -= mins*60;
2570                 report("  %d:%02d:%05.2f\n", hrs, mins, secs);
2571         }
2572         if( fmt_ctx->nb_programs > 0 )
2573                 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
2574         for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
2575                 report("program %d", i+1);
2576                 AVProgram *pgrm = fmt_ctx->programs[i];
2577                 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2578                         int idx = pgrm->stream_index[j];
2579                         int vidx = ffvideo.size();
2580                         while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
2581                         if( vidx >= 0 ) {
2582                                 report(", vid%d", vidx);
2583                                 continue;
2584                         }
2585                         int aidx = ffaudio.size();
2586                         while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
2587                         if( aidx >= 0 ) {
2588                                 report(", aud%d", aidx);
2589                                 continue;
2590                         }
2591                         report(", (%d)", pgrm->stream_index[j]);
2592                 }
2593                 report("\n");
2594         }
2595         report("\n");
2596         AVDictionaryEntry *tag = 0;
2597         while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
2598                 report("%s=%s\n", tag->key, tag->value);
2599
2600         if( !len ) --cp;
2601         *cp = 0;
2602         return cp - text;
2603 #undef report
2604 }
2605
2606
2607 int FFMPEG::init_decoder(const char *filename)
2608 {
2609         ff_lock("FFMPEG::init_decoder");
2610         av_register_all();
2611         char file_opts[BCTEXTLEN];
2612         strcpy(file_opts, filename);
2613         char *bp = strrchr(file_opts, '/');
2614         if( !bp ) bp = file_opts;
2615         char *sp = strrchr(bp, '.');
2616         if( !sp ) sp = bp + strlen(bp);
2617         FILE *fp = 0;
2618 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,18,100)
2619         const AVInputFormat *ifmt = 0;
2620 #else
2621         AVInputFormat *ifmt = 0;
2622 #endif
2623         if( sp ) {
2624                 strcpy(sp, ".opts");
2625                 fp = fopen(file_opts, "r");
2626         }
2627         if( fp ) {
2628                 read_options(fp, file_opts, opts);
2629                 fclose(fp);
2630                 AVDictionaryEntry *tag;
2631                 if( (tag=av_dict_get(opts, "format", NULL, 0)) != 0 ) {
2632                         ifmt = av_find_input_format(tag->value);
2633                 }
2634         }
2635         else
2636                 load_options("decode.opts", opts);
2637         AVDictionary *fopts = 0;
2638         av_dict_copy(&fopts, opts, 0);
2639         int ret = avformat_open_input(&fmt_ctx, filename, ifmt, &fopts);
2640         av_dict_free(&fopts);
2641         if( ret >= 0 )
2642                 ret = avformat_find_stream_info(fmt_ctx, NULL);
2643         if( !ret ) {
2644                 decoding = -1;
2645         }
2646         ff_unlock();
2647         return !ret ? 0 : 1;
2648 }
2649
2650 int FFMPEG::open_decoder()
2651 {
2652         struct stat st;
2653         if( stat(fmt_ctx->url, &st) < 0 ) {
2654                 eprintf(_("can't stat file: %s\n"), fmt_ctx->url);
2655                 return 1;
2656         }
2657
2658         int64_t file_bits = 8 * st.st_size;
2659         if( !fmt_ctx->bit_rate && opt_duration > 0 )
2660                 fmt_ctx->bit_rate = file_bits / opt_duration;
2661
2662         int estimated = 0;
2663         if( fmt_ctx->bit_rate > 0 ) {
2664                 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2665                         AVStream *st = fmt_ctx->streams[i];
2666                         if( st->duration != AV_NOPTS_VALUE ) continue;
2667                         if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
2668                         st->duration = av_rescale(file_bits, st->time_base.den,
2669                                 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
2670                         estimated = 1;
2671                 }
2672         }
2673         if( estimated && !(fflags & FF_ESTM_TIMES) ) {
2674                 fflags |= FF_ESTM_TIMES;
2675                 printf("FFMPEG::open_decoder: some stream times estimated: %s\n",
2676                         fmt_ctx->url);
2677         }
2678
2679         ff_lock("FFMPEG::open_decoder");
2680         int ret = 0, bad_time = 0;
2681         for( int i=0; !ret && i<(int)fmt_ctx->nb_streams; ++i ) {
2682                 AVStream *st = fmt_ctx->streams[i];
2683                 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
2684                 AVCodecParameters *avpar = st->codecpar;
2685                 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avpar->codec_id);
2686                 if( !codec_desc ) continue;
2687                 switch( avpar->codec_type ) {
2688                 case AVMEDIA_TYPE_VIDEO: {
2689                         if( avpar->width < 1 ) continue;
2690                         if( avpar->height < 1 ) continue;
2691                         AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
2692                         if( framerate.num < 1 ) continue;
2693                         has_video = 1;
2694                         int vidx = ffvideo.size();
2695                         FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
2696                         vstrm_index.append(ffidx(vidx, 0));
2697                         ffvideo.append(vid);
2698                         vid->width = avpar->width;
2699                         vid->height = avpar->height;
2700                         vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
2701                         switch( avpar->color_range ) {
2702                         case AVCOL_RANGE_MPEG:
2703                                 vid->color_range = BC_COLORS_MPEG;
2704                                 break;
2705                         case AVCOL_RANGE_JPEG:
2706                                 vid->color_range = BC_COLORS_JPEG;
2707                                 break;
2708                         default:
2709                                 vid->color_range = !file_base ? BC_COLORS_JPEG :
2710                                         file_base->file->preferences->yuv_color_range;
2711                                 break;
2712                         }
2713                         switch( avpar->color_space ) {
2714                         case AVCOL_SPC_BT470BG:
2715                                 vid->color_space = BC_COLORS_BT601_PAL;
2716                                 break;
2717                         case AVCOL_SPC_SMPTE170M:
2718                                 vid->color_space = BC_COLORS_BT601_NTSC;
2719                                 break;
2720                         case AVCOL_SPC_BT709:
2721                                 vid->color_space = BC_COLORS_BT709;
2722                                 break;
2723                         case AVCOL_SPC_BT2020_NCL:
2724                                 vid->color_space = BC_COLORS_BT2020_NCL;
2725                                 break;
2726                         case AVCOL_SPC_BT2020_CL:
2727                                 vid->color_space = BC_COLORS_BT2020_CL;
2728                                 break;
2729                         default:
2730                                 vid->color_space = !file_base ? BC_COLORS_BT601_NTSC :
2731                                         file_base->file->preferences->yuv_color_space;
2732                                 break;
2733                         }
2734                         double secs = to_secs(st->duration, st->time_base);
2735                         vid->length = secs * vid->frame_rate;
2736                         vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
2737                         vid->nudge = st->start_time;
2738                         vid->reading = -1;
2739                         ret = vid->create_filter(opt_video_filter);
2740                         break; }
2741                 case AVMEDIA_TYPE_AUDIO: {
2742                         if( avpar->channels < 1 ) continue;
2743                         if( avpar->sample_rate < 1 ) continue;
2744                         has_audio = 1;
2745                         int aidx = ffaudio.size();
2746                         FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
2747                         ffaudio.append(aud);
2748                         aud->channel0 = astrm_index.size();
2749                         aud->channels = avpar->channels;
2750                         for( int ch=0; ch<aud->channels; ++ch )
2751                                 astrm_index.append(ffidx(aidx, ch));
2752                         aud->sample_rate = avpar->sample_rate;
2753                         double secs = to_secs(st->duration, st->time_base);
2754                         aud->length = secs * aud->sample_rate;
2755                         aud->init_swr(aud->channels, avpar->format, aud->sample_rate);
2756                         aud->nudge = st->start_time;
2757                         aud->reading = -1;
2758                         ret = aud->create_filter(opt_audio_filter);
2759                         break; }
2760                 default: break;
2761                 }
2762         }
2763         if( bad_time && !(fflags & FF_BAD_TIMES) ) {
2764                 fflags |= FF_BAD_TIMES;
2765                 printf(_("FFMPEG::open_decoder: some stream have bad times: %s\n"),
2766                         fmt_ctx->url);
2767         }
2768         ff_unlock();
2769         return ret < 0 ? -1 : 0;
2770 }
2771
2772
2773 int FFMPEG::init_encoder(const char *filename)
2774 {
2775 // try access first for named pipes
2776         int ret = access(filename, W_OK);
2777         if( ret ) {
2778                 int fd = ::open(filename,O_WRONLY);
2779                 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
2780                 if( fd >= 0 ) { close(fd);  ret = 0; }
2781         }
2782         if( ret ) {
2783                 eprintf(_("bad file path: %s\n"), filename);
2784                 return 1;
2785         }
2786         ret = get_file_format();
2787         if( ret > 0 ) {
2788                 eprintf(_("bad file format: %s\n"), filename);
2789                 return 1;
2790         }
2791         if( ret < 0 ) {
2792                 eprintf(_("mismatch audio/video file format: %s\n"), filename);
2793                 return 1;
2794         }
2795         ff_lock("FFMPEG::init_encoder");
2796         av_register_all();
2797         char format[BCSTRLEN];
2798         if( get_format(format, "format", file_format) )
2799                 strcpy(format, file_format);
2800         avformat_alloc_output_context2(&fmt_ctx, 0, format, filename);
2801         if( !fmt_ctx ) {
2802                 eprintf(_("failed: %s\n"), filename);
2803                 ret = 1;
2804         }
2805         if( !ret ) {
2806                 encoding = -1;
2807                 load_options("encode.opts", opts);
2808         }
2809         ff_unlock();
2810         return ret;
2811 }
2812
2813 int FFMPEG::open_encoder(const char *type, const char *spec)
2814 {
2815
2816         Asset *asset = file_base->asset;
2817         char *filename = asset->path;
2818         AVDictionary *sopts = 0;
2819         av_dict_copy(&sopts, opts, 0);
2820         char option_path[BCTEXTLEN];
2821         set_option_path(option_path, "%s/%s.opts", type, type);
2822         read_options(option_path, sopts);
2823         get_option_path(option_path, type, spec);
2824         char format_name[BCSTRLEN], codec_name[BCTEXTLEN], bsfilter[BCTEXTLEN];
2825         if( get_encoder(option_path, format_name, codec_name, bsfilter) ) {
2826                 eprintf(_("get_encoder failed %s:%s\n"), option_path, filename);
2827                 return 1;
2828         }
2829
2830 #ifdef HAVE_DV
2831         if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
2832 #endif
2833         else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
2834         else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
2835
2836         int ret = 0;
2837         ff_lock("FFMPEG::open_encoder");
2838         FFStream *fst = 0;
2839         AVStream *st = 0;
2840         AVCodecContext *ctx = 0;
2841
2842         const AVCodecDescriptor *codec_desc = 0;
2843 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
2844         const AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
2845 #else
2846         AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
2847 #endif
2848         if( !codec ) {
2849                 eprintf(_("cant find codec %s:%s\n"), codec_name, filename);
2850                 ret = 1;
2851         }
2852         if( !ret ) {
2853                 codec_desc = avcodec_descriptor_get(codec->id);
2854                 if( !codec_desc ) {
2855                         eprintf(_("unknown codec %s:%s\n"), codec_name, filename);
2856                         ret = 1;
2857                 }
2858         }
2859         if( !ret ) {
2860                 st = avformat_new_stream(fmt_ctx, 0);
2861                 if( !st ) {
2862                         eprintf(_("cant create stream %s:%s\n"), codec_name, filename);
2863                         ret = 1;
2864                 }
2865         }
2866         if( !ret ) {
2867                 switch( codec_desc->type ) {
2868                 case AVMEDIA_TYPE_AUDIO: {
2869                         if( has_audio ) {
2870                                 eprintf(_("duplicate audio %s:%s\n"), codec_name, filename);
2871                                 ret = 1;
2872                                 break;
2873                         }
2874                         if( scan_options(asset->ff_audio_options, sopts, st) ) {
2875                                 eprintf(_("bad audio options %s:%s\n"), codec_name, filename);
2876                                 ret = 1;
2877                                 break;
2878                         }
2879                         has_audio = 1;
2880                         ctx = avcodec_alloc_context3(codec);
2881                         if( asset->ff_audio_bitrate > 0 ) {
2882                                 ctx->bit_rate = asset->ff_audio_bitrate;
2883                                 char arg[BCSTRLEN];
2884                                 sprintf(arg, "%d", asset->ff_audio_bitrate);
2885                                 av_dict_set(&sopts, "b", arg, 0);
2886                         }
2887                         else if( asset->ff_audio_quality >= 0 ) {
2888                                 ctx->global_quality = asset->ff_audio_quality * FF_QP2LAMBDA;
2889                                 ctx->qmin    = ctx->qmax =  asset->ff_audio_quality;
2890                                 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2891                                 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2892                                 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2893                                 char arg[BCSTRLEN];
2894                                 av_dict_set(&sopts, "flags", "+qscale", 0);
2895                                 sprintf(arg, "%d", asset->ff_audio_quality);
2896                                 av_dict_set(&sopts, "qscale", arg, 0);
2897                                 sprintf(arg, "%d", ctx->global_quality);
2898                                 av_dict_set(&sopts, "global_quality", arg, 0);
2899                         }
2900                         int aidx = ffaudio.size();
2901                         int fidx = aidx + ffvideo.size();
2902                         FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
2903                         aud->avctx = ctx;  ffaudio.append(aud);  fst = aud;
2904                         aud->sample_rate = asset->sample_rate;
2905                         ctx->channels = aud->channels = asset->channels;
2906                         for( int ch=0; ch<aud->channels; ++ch )
2907                                 astrm_index.append(ffidx(aidx, ch));
2908                         ctx->channel_layout =  av_get_default_channel_layout(ctx->channels);
2909                         ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
2910                         if( !ctx->sample_rate ) {
2911                                 eprintf(_("check_sample_rate failed %s\n"), filename);
2912                                 ret = 1;
2913                                 break;
2914                         }
2915                         ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
2916                         AVSampleFormat sample_fmt = av_get_sample_fmt(asset->ff_sample_format);
2917                         if( sample_fmt == AV_SAMPLE_FMT_NONE )
2918                                 sample_fmt = codec->sample_fmts ? codec->sample_fmts[0] : AV_SAMPLE_FMT_S16;
2919                         ctx->sample_fmt = sample_fmt;
2920                         uint64_t layout = av_get_default_channel_layout(ctx->channels);
2921                         aud->resample_context = swr_alloc_set_opts(NULL,
2922                                 layout, ctx->sample_fmt, aud->sample_rate,
2923                                 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
2924                                 0, NULL);
2925                         swr_init(aud->resample_context);
2926                         aud->writing = -1;
2927                         break; }
2928                 case AVMEDIA_TYPE_VIDEO: {
2929                         if( has_video ) {
2930                                 eprintf(_("duplicate video %s:%s\n"), codec_name, filename);
2931                                 ret = 1;
2932                                 break;
2933                         }
2934                         if( scan_options(asset->ff_video_options, sopts, st) ) {
2935                                 eprintf(_("bad video options %s:%s\n"), codec_name, filename);
2936                                 ret = 1;
2937                                 break;
2938                         }
2939                         has_video = 1;
2940                         ctx = avcodec_alloc_context3(codec);
2941                         if( asset->ff_video_bitrate > 0 ) {
2942                                 ctx->bit_rate = asset->ff_video_bitrate;
2943                                 char arg[BCSTRLEN];
2944                                 sprintf(arg, "%d", asset->ff_video_bitrate);
2945                                 av_dict_set(&sopts, "b", arg, 0);
2946                         }
2947                         else if( asset->ff_video_quality >= 0 ) {
2948                                 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
2949                                 ctx->qmin    = ctx->qmax =  asset->ff_video_quality;
2950                                 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2951                                 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2952                                 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2953                                 char arg[BCSTRLEN];
2954                                 av_dict_set(&sopts, "flags", "+qscale", 0);
2955                                 sprintf(arg, "%d", asset->ff_video_quality);
2956                                 av_dict_set(&sopts, "qscale", arg, 0);
2957                                 sprintf(arg, "%d", ctx->global_quality);
2958                                 av_dict_set(&sopts, "global_quality", arg, 0);
2959                         }
2960                         int vidx = ffvideo.size();
2961                         int fidx = vidx + ffaudio.size();
2962                         FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
2963                         vstrm_index.append(ffidx(vidx, 0));
2964                         vid->avctx = ctx;  ffvideo.append(vid);  fst = vid;
2965                         vid->width = asset->width;
2966                         vid->height = asset->height;
2967                         vid->frame_rate = asset->frame_rate;
2968 #if 0
2969                         char tc_str[20] = "00:00:00:00";
2970                         double tc_offset;
2971                         if(asset->timecode > 0)
2972                         Units::totext(tc_str, asset->timecode, TIME_HMSF, 0, asset->frame_rate, 0);
2973                         //printf("tc: %s \n", tc_str);
2974                         av_dict_set(&st->metadata, "timecode", tc_str, 0);
2975 #endif
2976                         if( (vid->color_range = asset->ff_color_range) < 0 )
2977                                 vid->color_range = file_base->file->preferences->yuv_color_range;
2978                         switch( vid->color_range ) {
2979                         case BC_COLORS_MPEG:  ctx->color_range = AVCOL_RANGE_MPEG;  break;
2980                         case BC_COLORS_JPEG:  ctx->color_range = AVCOL_RANGE_JPEG;  break;
2981                         }
2982                         if( (vid->color_space = asset->ff_color_space) < 0 )
2983                                 vid->color_space = file_base->file->preferences->yuv_color_space;
2984                         switch( vid->color_space ) {
2985                         case BC_COLORS_BT601_NTSC:  ctx->colorspace = AVCOL_SPC_SMPTE170M;  break;
2986                         case BC_COLORS_BT601_PAL: ctx->colorspace = AVCOL_SPC_BT470BG; break;
2987                         case BC_COLORS_BT709:  ctx->colorspace = AVCOL_SPC_BT709;      break;
2988                         case BC_COLORS_BT2020_NCL: ctx->colorspace = AVCOL_SPC_BT2020_NCL; break;
2989                         case BC_COLORS_BT2020_CL: ctx->colorspace = AVCOL_SPC_BT2020_CL; break;
2990                         }
2991                         AVPixelFormat pix_fmt = av_get_pix_fmt(asset->ff_pixel_format);
2992                         if( opt_hw_dev != 0 ) {
2993                                 AVHWDeviceType hw_type = vid->encode_hw_activate(opt_hw_dev);
2994                                 switch( hw_type ) {
2995                                 case AV_HWDEVICE_TYPE_VAAPI:
2996                                         pix_fmt = AV_PIX_FMT_VAAPI;
2997                                         break;
2998                                 case AV_HWDEVICE_TYPE_NONE:
2999                                 default: break;
3000                                 }
3001                         }
3002                         if( pix_fmt == AV_PIX_FMT_NONE )
3003                                 pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
3004                         ctx->pix_fmt = pix_fmt;
3005
3006                         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
3007                         int mask_w = (1<<desc->log2_chroma_w)-1;
3008                         ctx->width = (vid->width+mask_w) & ~mask_w;
3009                         int mask_h = (1<<desc->log2_chroma_h)-1;
3010                         ctx->height = (vid->height+mask_h) & ~mask_h;
3011                         ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
3012                         AVRational frame_rate;
3013                         if (ctx->codec->id == AV_CODEC_ID_MPEG1VIDEO ||
3014                             ctx->codec->id == AV_CODEC_ID_MPEG2VIDEO)
3015                         frame_rate = check_frame_rate(codec->supported_framerates, vid->frame_rate);
3016                         else
3017                         frame_rate = av_d2q(vid->frame_rate, INT_MAX);
3018                         if( !frame_rate.num || !frame_rate.den ) {
3019                                 eprintf(_("check_frame_rate failed %s\n"), filename);
3020                                 ret = 1;
3021                                 break;
3022                         }
3023                         av_reduce(&frame_rate.num, &frame_rate.den,
3024                                 frame_rate.num, frame_rate.den, INT_MAX);
3025                         ctx->framerate = (AVRational) { frame_rate.num, frame_rate.den };
3026                         ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
3027                         st->avg_frame_rate = frame_rate;
3028                         st->time_base = ctx->time_base;
3029                         vid->writing = -1;
3030                         vid->interlaced = asset->interlace_mode == ILACE_MODE_TOP_FIRST ||
3031                                 asset->interlace_mode == ILACE_MODE_BOTTOM_FIRST ? 1 : 0;
3032                         vid->top_field_first = asset->interlace_mode == ILACE_MODE_TOP_FIRST ? 1 : 0;
3033                         switch (asset->interlace_mode)  {               
3034                         case ILACE_MODE_TOP_FIRST: 
3035                         if (ctx->codec->id == AV_CODEC_ID_MJPEG)
3036                         av_dict_set(&sopts, "field_order", "tt", 0); 
3037                         else
3038                         av_dict_set(&sopts, "field_order", "tb", 0); 
3039                         if (ctx->codec_id != AV_CODEC_ID_MJPEG) 
3040                         av_dict_set(&sopts, "flags", "+ilme+ildct", 0);
3041                         break;
3042                         case ILACE_MODE_BOTTOM_FIRST: 
3043                         if (ctx->codec->id == AV_CODEC_ID_MJPEG)
3044                         av_dict_set(&sopts, "field_order", "bb", 0); 
3045                         else
3046                         av_dict_set(&sopts, "field_order", "bt", 0); 
3047                         if (ctx->codec_id != AV_CODEC_ID_MJPEG)
3048                         av_dict_set(&sopts, "flags", "+ilme+ildct", 0);
3049                         break;
3050                         case ILACE_MODE_NOTINTERLACED: av_dict_set(&sopts, "field_order", "progressive", 0); break;
3051                         }
3052                         break; }
3053                 default:
3054                         eprintf(_("not audio/video, %s:%s\n"), codec_name, filename);
3055                         ret = 1;
3056                 }
3057
3058                 if( ctx ) {
3059                         AVDictionaryEntry *tag;
3060                         if( (tag=av_dict_get(sopts, "cin_stats_filename", NULL, 0)) != 0 ) {
3061                                 char suffix[BCSTRLEN];  sprintf(suffix,"-%d.log",fst->fidx);
3062                                 fst->stats_filename = cstrcat(2, tag->value, suffix);
3063                         }
3064                         if( (tag=av_dict_get(sopts, "flags", NULL, 0)) != 0 ) {
3065                                 int pass = fst->pass;
3066                                 char *cp = tag->value;
3067                                 while( *cp ) {
3068                                         int ch = *cp++, pfx = ch=='-' ? -1 : ch=='+' ? 1 : 0;
3069                                         if( !isalnum(!pfx ? ch : (ch=*cp++)) ) continue;
3070                                         char id[BCSTRLEN], *bp = id, *ep = bp+sizeof(id)-1;
3071                                         for( *bp++=ch; isalnum(ch=*cp); ++cp )
3072                                                 if( bp < ep ) *bp++ = ch;
3073                                         *bp = 0;
3074                                         if( !strcmp(id, "pass1") ) {
3075                                                 pass = pfx<0 ? (pass&~1) : pfx>0 ? (pass|1) : 1;
3076                                         }
3077                                         else if( !strcmp(id, "pass2") ) {
3078                                                 pass = pfx<0 ? (pass&~2) : pfx>0 ? (pass|2) : 2;
3079                                         }
3080                                 }
3081                                 if( (fst->pass=pass) ) {
3082                                         if( pass & 1 ) ctx->flags |= AV_CODEC_FLAG_PASS1;
3083                                         if( pass & 2 ) ctx->flags |= AV_CODEC_FLAG_PASS2;
3084                                 }
3085                         }
3086                 }
3087         }
3088         if( !ret ) {
3089                 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
3090                         ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
3091                 if( fst->stats_filename && (ret=fst->init_stats_file()) )
3092                         eprintf(_("error: stats file = %s\n"), fst->stats_filename);
3093         }
3094         if( !ret ) {
3095                 av_dict_set(&sopts, "cin_bitrate", 0, 0);
3096                 av_dict_set(&sopts, "cin_quality", 0, 0);
3097
3098                 if( !av_dict_get(sopts, "threads", NULL, 0) )
3099                         ctx->thread_count = ff_cpus();
3100                 ret = avcodec_open2(ctx, codec, &sopts);
3101                 if( ret >= 0 ) {
3102                         ret = avcodec_parameters_from_context(st->codecpar, ctx);
3103                         if( ret < 0 )
3104                                 fprintf(stderr, "Could not copy the stream parameters\n");
3105                 }
3106                 if( ret >= 0 ) {
3107 _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
3108 #if LIBAVCODEC_VERSION_INT <= AV_VERSION_INT(58,134,100)
3109                         ret = avcodec_copy_context(st->codec, ctx);
3110 #else
3111                         ret = avcodec_parameters_to_context(ctx, st->codecpar);
3112 #endif
3113 _Pragma("GCC diagnostic warning \"-Wdeprecated-declarations\"")
3114                         if( ret < 0 )
3115                                 fprintf(stderr, "Could not copy the stream context\n");
3116                 }
3117                 if( ret < 0 ) {
3118                         ff_err(ret,"FFMPEG::open_encoder");
3119                         eprintf(_("open failed %s:%s\n"), codec_name, filename);
3120                         ret = 1;
3121                 }
3122                 else
3123                         ret = 0;
3124         }
3125         if( !ret && fst && bsfilter[0] ) {
3126                 ret = av_bsf_list_parse_str(bsfilter, &fst->bsfc);
3127                 if( ret < 0 ) {
3128                         ff_err(ret,"FFMPEG::open_encoder");
3129                         eprintf(_("bitstream filter failed %s:\n%s\n"), filename, bsfilter);
3130                         ret = 1;
3131                 }
3132                 else
3133                         ret = 0;
3134         }
3135
3136         if( !ret )
3137                 start_muxer();
3138
3139         ff_unlock();
3140         av_dict_free(&sopts);
3141         return ret;
3142 }
3143
3144 int FFMPEG::close_encoder()
3145 {
3146         stop_muxer();
3147         if( encoding > 0 ) {
3148                 av_write_trailer(fmt_ctx);
3149                 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
3150                         avio_closep(&fmt_ctx->pb);
3151         }
3152         encoding = 0;
3153         return 0;
3154 }
3155
3156 int FFMPEG::decode_activate()
3157 {
3158         if( decoding < 0 ) {
3159                 decoding = 0;
3160                 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
3161                         ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
3162                 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
3163                         ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
3164                 // set nudges for each program stream set
3165                 const int64_t min_nudge = INT64_MIN+1;
3166                 int npgrms = fmt_ctx->nb_programs;
3167                 for( int i=0; i<npgrms; ++i ) {
3168                         AVProgram *pgrm = fmt_ctx->programs[i];
3169                         // first start time video stream
3170                         int64_t vstart_time = min_nudge, astart_time = min_nudge;
3171                         for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
3172                                 int fidx = pgrm->stream_index[j];
3173                                 AVStream *st = fmt_ctx->streams[fidx];
3174                                 AVCodecParameters *avpar = st->codecpar;
3175                                 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
3176                                         if( st->start_time == AV_NOPTS_VALUE ) continue;
3177                                         if( vstart_time < st->start_time )
3178                                                 vstart_time = st->start_time;
3179                                         continue;
3180                                 }
3181                                 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
3182                                         if( st->start_time == AV_NOPTS_VALUE ) continue;
3183                                         if( astart_time < st->start_time )
3184                                                 astart_time = st->start_time;
3185                                         continue;
3186                                 }
3187                         }
3188                         //since frame rate is much more grainy than sample rate, it is better to
3189                         // align using video, so that total absolute error is minimized.
3190                         int64_t nudge = vstart_time > min_nudge ? vstart_time :
3191                                 astart_time > min_nudge ? astart_time : AV_NOPTS_VALUE;
3192                         for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
3193                                 int fidx = pgrm->stream_index[j];
3194                                 AVStream *st = fmt_ctx->streams[fidx];
3195                                 AVCodecParameters *avpar = st->codecpar;
3196                                 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
3197                                         for( int k=0; k<ffvideo.size(); ++k ) {
3198                                                 if( ffvideo[k]->fidx != fidx ) continue;
3199                                                 ffvideo[k]->nudge = nudge;
3200                                         }
3201                                         continue;
3202                                 }
3203                                 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
3204                                         for( int k=0; k<ffaudio.size(); ++k ) {
3205                                                 if( ffaudio[k]->fidx != fidx ) continue;
3206                                                 ffaudio[k]->nudge = nudge;
3207                                         }
3208                                         continue;
3209                                 }
3210                         }
3211                 }
3212                 // set nudges for any streams not yet set
3213                 int64_t vstart_time = min_nudge, astart_time = min_nudge;
3214                 int nstreams = fmt_ctx->nb_streams;
3215                 for( int i=0; i<nstreams; ++i ) {
3216                         AVStream *st = fmt_ctx->streams[i];
3217                         AVCodecParameters *avpar = st->codecpar;
3218                         switch( avpar->codec_type ) {
3219                         case AVMEDIA_TYPE_VIDEO: {
3220                                 if( st->start_time == AV_NOPTS_VALUE ) continue;
3221                                 int vidx = ffvideo.size();
3222                                 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
3223                                 if( vidx < 0 ) continue;
3224                                 if( ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
3225                                 if( vstart_time < st->start_time )
3226                                         vstart_time = st->start_time;
3227                                 break; }
3228                         case AVMEDIA_TYPE_AUDIO: {
3229                                 if( st->start_time == AV_NOPTS_VALUE ) continue;
3230                                 int aidx = ffaudio.size();
3231                                 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
3232                                 if( aidx < 0 ) continue;
3233                                 if( ffaudio[aidx]->frame_sz < avpar->frame_size )
3234                                         ffaudio[aidx]->frame_sz = avpar->frame_size;
3235                                 if( ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
3236                                 if( astart_time < st->start_time )
3237                                         astart_time = st->start_time;
3238                                 break; }
3239                         default: break;
3240                         }
3241                 }
3242                 int64_t nudge = vstart_time > min_nudge ? vstart_time :
3243                         astart_time > min_nudge ? astart_time : 0;
3244                 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
3245                         if( ffvideo[vidx]->nudge == AV_NOPTS_VALUE )
3246                                 ffvideo[vidx]->nudge = nudge;
3247                 }
3248                 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
3249                         if( ffaudio[aidx]->nudge == AV_NOPTS_VALUE )
3250                                 ffaudio[aidx]->nudge = nudge;
3251                 }
3252                 decoding = 1;
3253         }
3254         return decoding;
3255 }
3256
3257 int FFMPEG::encode_activate()
3258 {
3259         int ret = 0;
3260         if( encoding < 0 ) {
3261                 encoding = 0;
3262                 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
3263                     (ret=avio_open(&fmt_ctx->pb, fmt_ctx->url, AVIO_FLAG_WRITE)) < 0 ) {
3264                         ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
3265                                 fmt_ctx->url);
3266                         return -1;
3267                 }
3268                 if( !strcmp(file_format, "image2") ) {
3269                         Asset *asset = file_base->asset;
3270                         const char *filename = asset->path;
3271                         FILE *fp = fopen(filename,"w");
3272                         if( !fp ) {
3273                                 eprintf(_("Cant write image2 header file: %s\n  %m"), filename);
3274                                 return 1;
3275                         }
3276                         fprintf(fp, "IMAGE2\n");
3277                         fprintf(fp, "# Frame rate: %f\n", asset->frame_rate);
3278                         fprintf(fp, "# Width: %d\n", asset->width);
3279                         fprintf(fp, "# Height: %d\n", asset->height);
3280                         fclose(fp);
3281                 }
3282                 int prog_id = 1;
3283                 AVProgram *prog = av_new_program(fmt_ctx, prog_id);
3284                 for( int i=0; i< ffvideo.size(); ++i )
3285                         av_program_add_stream_index(fmt_ctx, prog_id, ffvideo[i]->fidx);
3286                 for( int i=0; i< ffaudio.size(); ++i )
3287                         av_program_add_stream_index(fmt_ctx, prog_id, ffaudio[i]->fidx);
3288                 int pi = fmt_ctx->nb_programs;
3289                 while(  --pi >= 0 && fmt_ctx->programs[pi]->id != prog_id );
3290                 AVDictionary **meta = &prog->metadata;
3291                 av_dict_set(meta, "service_provider", "cin5", 0);
3292                 const char *path = fmt_ctx->url, *bp = strrchr(path,'/');
3293                 if( bp ) path = bp + 1;
3294                 av_dict_set(meta, "title", path, 0);
3295
3296                 if( ffaudio.size() ) {
3297                         const char *ep = getenv("CIN_AUDIO_LANG"), *lp = 0;
3298                         if( !ep && (lp=getenv("LANG")) ) { // some are guesses
3299                                 static struct { const char lc[3], lng[4]; } lcode[] = {
3300                                         { "en", "eng" }, { "de", "ger" }, { "es", "spa" },
3301                                         { "eu", "bas" }, { "fr", "fre" }, { "el", "gre" },
3302                                         { "hi", "hin" }, { "it", "ita" }, { "ja", "jap" },
3303                                         { "ko", "kor" }, { "du", "dut" }, { "pl", "pol" },
3304                                         { "pt", "por" }, { "ru", "rus" }, { "sl", "slv" },
3305                                         { "uk", "ukr" }, { "vi", "vie" }, { "zh", "chi" },
3306                                 };
3307                                 for( int i=sizeof(lcode)/sizeof(lcode[0]); --i>=0 && !ep; )
3308                                         if( !strncmp(lcode[i].lc,lp,2) ) ep = lcode[i].lng;
3309                         }
3310                         if( !ep ) ep = "und";
3311                         char lang[5];
3312                         strncpy(lang,ep,3);  lang[3] = 0;
3313                         AVStream *st = ffaudio[0]->st;
3314                         av_dict_set(&st->metadata,"language",lang,0);
3315                 }
3316
3317                 AVDictionary *fopts = 0;
3318                 char option_path[BCTEXTLEN];
3319                 set_option_path(option_path, "format/%s", file_format);
3320                 read_options(option_path, fopts, 1);
3321                 av_dict_copy(&fopts, opts, 0);
3322                 if( scan_options(file_base->asset->ff_format_options, fopts, 0) ) {
3323                         eprintf(_("bad format options %s\n"), file_base->asset->path);
3324                         ret = -1;
3325                 }
3326                 if( ret >= 0 )
3327                         ret = avformat_write_header(fmt_ctx, &fopts);
3328                 if( ret < 0 ) {
3329                         ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
3330                                 fmt_ctx->url);
3331                         return -1;
3332                 }
3333                 av_dict_free(&fopts);
3334                 encoding = 1;
3335         }
3336         return encoding;
3337 }
3338
3339
3340 int FFMPEG::audio_seek(int stream, int64_t pos)
3341 {
3342         int aidx = astrm_index[stream].st_idx;
3343         FFAudioStream *aud = ffaudio[aidx];
3344         aud->audio_seek(pos);
3345         return 0;
3346 }
3347
3348 int FFMPEG::video_probe(int64_t pos)
3349 {
3350         int vidx = vstrm_index[0].st_idx;
3351         FFVideoStream *vid = ffvideo[vidx];
3352         vid->probe(pos);
3353         
3354         int interlace1 = interlace_from_codec;
3355         //printf("interlace from codec: %i\n", interlace1);
3356
3357         switch (interlace1)
3358         {
3359         case AV_FIELD_TT:
3360         case AV_FIELD_TB:
3361             return ILACE_MODE_TOP_FIRST;
3362         case AV_FIELD_BB:
3363         case AV_FIELD_BT:
3364             return ILACE_MODE_BOTTOM_FIRST;
3365         case AV_FIELD_PROGRESSIVE:
3366             return ILACE_MODE_NOTINTERLACED;
3367         default:
3368             return ILACE_MODE_UNDETECTED;
3369         }
3370
3371 }
3372
3373
3374
3375 int FFMPEG::video_seek(int stream, int64_t pos)
3376 {
3377         int vidx = vstrm_index[stream].st_idx;
3378         FFVideoStream *vid = ffvideo[vidx];
3379         vid->video_seek(pos);
3380         return 0;
3381 }
3382
3383
3384 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
3385 {
3386         if( !has_audio || chn >= astrm_index.size() ) return -1;
3387         int aidx = astrm_index[chn].st_idx;
3388         FFAudioStream *aud = ffaudio[aidx];
3389         if( aud->load(pos, len) < len ) return -1;
3390         int ch = astrm_index[chn].st_ch;
3391         int ret = aud->read(samples,len,ch);
3392         return ret;
3393 }
3394
3395 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
3396 {
3397         if( !has_video || layer >= vstrm_index.size() ) return -1;
3398         int vidx = vstrm_index[layer].st_idx;
3399         FFVideoStream *vid = ffvideo[vidx];
3400         return vid->load(vframe, pos);
3401 }
3402
3403
3404 int FFMPEG::encode(int stream, double **samples, int len)
3405 {
3406         FFAudioStream *aud = ffaudio[stream];
3407         return aud->encode(samples, len);
3408 }
3409
3410
3411 int FFMPEG::encode(int stream, VFrame *frame)
3412 {
3413         FFVideoStream *vid = ffvideo[stream];
3414         return vid->encode(frame);
3415 }
3416
3417 void FFMPEG::start_muxer()
3418 {
3419         if( !running() ) {
3420                 done = 0;
3421                 start();
3422         }
3423 }
3424
3425 void FFMPEG::stop_muxer()
3426 {
3427         if( running() ) {
3428                 done = 1;
3429                 mux_lock->unlock();
3430         }
3431         join();
3432 }
3433
3434 void FFMPEG::flow_off()
3435 {
3436         if( !flow ) return;
3437         flow_lock->lock("FFMPEG::flow_off");
3438         flow = 0;
3439 }
3440
3441 void FFMPEG::flow_on()
3442 {
3443         if( flow ) return;
3444         flow = 1;
3445         flow_lock->unlock();
3446 }
3447
3448 void FFMPEG::flow_ctl()
3449 {
3450         while( !flow ) {
3451                 flow_lock->lock("FFMPEG::flow_ctl");
3452                 flow_lock->unlock();
3453         }
3454 }
3455
3456 int FFMPEG::mux_audio(FFrame *frm)
3457 {
3458         FFStream *fst = frm->fst;
3459         AVCodecContext *ctx = fst->avctx;
3460         AVFrame *frame = *frm;
3461         AVRational tick_rate = {1, ctx->sample_rate};
3462         frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
3463         int ret = fst->encode_frame(frame);
3464         if( ret < 0 )
3465                 ff_err(ret, "FFMPEG::mux_audio");
3466         return ret >= 0 ? 0 : 1;
3467 }
3468
3469 int FFMPEG::mux_video(FFrame *frm)
3470 {
3471         FFStream *fst = frm->fst;
3472         AVFrame *frame = *frm;
3473         frame->pts = frm->position;
3474         int ret = fst->encode_frame(frame);
3475         if( ret < 0 )
3476                 ff_err(ret, "FFMPEG::mux_video");
3477         return ret >= 0 ? 0 : 1;
3478 }
3479
3480 void FFMPEG::mux()
3481 {
3482         for(;;) {
3483                 double atm = -1, vtm = -1;
3484                 FFrame *afrm = 0, *vfrm = 0;
3485                 int demand = 0;
3486                 for( int i=0; i<ffaudio.size(); ++i ) {  // earliest audio
3487                         FFStream *fst = ffaudio[i];
3488                         if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
3489                         FFrame *frm = fst->frms.first;
3490                         if( !frm ) { if( !done ) return; continue; }
3491                         double tm = to_secs(frm->position, fst->avctx->time_base);
3492                         if( atm < 0 || tm < atm ) { atm = tm;  afrm = frm; }
3493                 }
3494                 for( int i=0; i<ffvideo.size(); ++i ) {  // earliest video
3495                         FFStream *fst = ffvideo[i];
3496                         if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
3497                         FFrame *frm = fst->frms.first;
3498                         if( !frm ) { if( !done ) return; continue; }
3499                         double tm = to_secs(frm->position, fst->avctx->time_base);
3500                         if( vtm < 0 || tm < vtm ) { vtm = tm;  vfrm = frm; }
3501                 }
3502                 if( !demand ) flow_off();
3503                 if( !afrm && !vfrm ) break;
3504                 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
3505                         vfrm->position, vfrm->fst->avctx->time_base,
3506                         afrm->position, afrm->fst->avctx->time_base);
3507                 FFrame *frm = v <= 0 ? vfrm : afrm;
3508                 if( frm == afrm ) mux_audio(frm);
3509                 if( frm == vfrm ) mux_video(frm);
3510                 frm->dequeue();
3511                 delete frm;
3512         }
3513 }
3514
3515 void FFMPEG::run()
3516 {
3517         while( !done ) {
3518                 mux_lock->lock("FFMPEG::run");
3519                 if( !done ) mux();
3520         }
3521         for( int i=0; i<ffaudio.size(); ++i )
3522                 ffaudio[i]->drain();
3523         for( int i=0; i<ffvideo.size(); ++i )
3524                 ffvideo[i]->drain();
3525         mux();
3526         for( int i=0; i<ffaudio.size(); ++i )
3527                 ffaudio[i]->flush();
3528         for( int i=0; i<ffvideo.size(); ++i )
3529                 ffvideo[i]->flush();
3530 }
3531
3532
3533 int FFMPEG::ff_total_audio_channels()
3534 {
3535         return astrm_index.size();
3536 }
3537
3538 int FFMPEG::ff_total_astreams()
3539 {
3540         return ffaudio.size();
3541 }
3542
3543 int FFMPEG::ff_audio_channels(int stream)
3544 {
3545         return ffaudio[stream]->channels;
3546 }
3547
3548 int FFMPEG::ff_sample_rate(int stream)
3549 {
3550         return ffaudio[stream]->sample_rate;
3551 }
3552
3553 const char* FFMPEG::ff_audio_format(int stream)
3554 {
3555         AVStream *st = ffaudio[stream]->st;
3556         AVCodecID id = st->codecpar->codec_id;
3557         const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
3558         return desc ? desc->name : _("Unknown");
3559 }
3560
3561 int FFMPEG::ff_audio_pid(int stream)
3562 {
3563         return ffaudio[stream]->st->id;
3564 }
3565
3566 int64_t FFMPEG::ff_audio_samples(int stream)
3567 {
3568         return ffaudio[stream]->length;
3569 }
3570
3571 // find audio astream/channels with this program,
3572 //   or all program audio channels (astream=-1)
3573 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
3574 {
3575         channel_mask = 0;
3576         int pidx = -1;
3577         int vidx = ffvideo[vstream]->fidx;
3578         // find first program with this video stream
3579         for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
3580                 AVProgram *pgrm = fmt_ctx->programs[i];
3581                 for( int j=0;  pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
3582                         int st_idx = pgrm->stream_index[j];
3583                         AVStream *st = fmt_ctx->streams[st_idx];
3584                         if( st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
3585                         if( st_idx == vidx ) pidx = i;
3586                 }
3587         }
3588         if( pidx < 0 ) return -1;
3589         int ret = -1;
3590         int64_t channels = 0;
3591         AVProgram *pgrm = fmt_ctx->programs[pidx];
3592         for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
3593                 int aidx = pgrm->stream_index[j];
3594                 AVStream *st = fmt_ctx->streams[aidx];
3595                 if( st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
3596                 if( astream > 0 ) { --astream;  continue; }
3597                 int astrm = -1;
3598                 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
3599                         if( ffaudio[i]->fidx == aidx ) astrm = i;
3600                 if( astrm >= 0 ) {
3601                         if( ret < 0 ) ret = astrm;
3602                         int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
3603                         channels |= mask << ffaudio[astrm]->channel0;
3604                 }
3605                 if( !astream ) break;
3606         }
3607         channel_mask = channels;
3608         return ret;
3609 }
3610
3611
3612 int FFMPEG::ff_total_video_layers()
3613 {
3614         return vstrm_index.size();
3615 }
3616
3617 int FFMPEG::ff_total_vstreams()
3618 {
3619         return ffvideo.size();
3620 }
3621
3622 int FFMPEG::ff_video_width(int stream)
3623 {
3624         FFVideoStream *vst = ffvideo[stream];
3625         return !vst->transpose ? vst->width : vst->height;
3626 }
3627
3628 int FFMPEG::ff_video_height(int stream)
3629 {
3630         FFVideoStream *vst = ffvideo[stream];
3631         return !vst->transpose ? vst->height : vst->width;
3632 }
3633
3634 int FFMPEG::ff_set_video_width(int stream, int width)
3635 {
3636         FFVideoStream *vst = ffvideo[stream];
3637         int *vw = !vst->transpose ? &vst->width : &vst->height, w = *vw;
3638         *vw = width;
3639         return w;
3640 }
3641
3642 int FFMPEG::ff_set_video_height(int stream, int height)
3643 {
3644         FFVideoStream *vst = ffvideo[stream];
3645         int *vh = !vst->transpose ? &vst->height : &vst->width, h = *vh;
3646         *vh = height;
3647         return h;
3648 }
3649
3650 int FFMPEG::ff_coded_width(int stream)
3651 {
3652         return ffvideo[stream]->avctx->coded_width;
3653 }
3654
3655 int FFMPEG::ff_coded_height(int stream)
3656 {
3657         return ffvideo[stream]->avctx->coded_height;
3658 }
3659
3660 float FFMPEG::ff_aspect_ratio(int stream)
3661 {
3662         //return ffvideo[stream]->aspect_ratio;
3663         AVFormatContext *fmt_ctx = ffvideo[stream]->fmt_ctx;
3664         AVStream *strm = ffvideo[stream]->st;
3665         AVCodecParameters *par = ffvideo[stream]->st->codecpar;
3666         AVRational dar;
3667         AVRational sar = av_guess_sample_aspect_ratio(fmt_ctx, strm, NULL);
3668         if (sar.num && ffvideo[stream]->get_rotation_angle() == 0) {
3669             av_reduce(&dar.num, &dar.den,
3670                       par->width  * sar.num,
3671                       par->height * sar.den,
3672                       1024*1024);
3673                       return av_q2d(dar);
3674                       }
3675         return ffvideo[stream]->aspect_ratio;
3676 }
3677
3678 const char* FFMPEG::ff_video_codec(int stream)
3679 {
3680         AVStream *st = ffvideo[stream]->st;
3681         AVCodecID id = st->codecpar->codec_id;
3682         const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
3683         return desc ? desc->name : _("Unknown");
3684 }
3685
3686 int FFMPEG::ff_color_range(int stream)
3687 {
3688         return ffvideo[stream]->color_range;
3689 }
3690
3691 int FFMPEG::ff_color_space(int stream)
3692 {
3693         return ffvideo[stream]->color_space;
3694 }
3695
3696 double FFMPEG::ff_frame_rate(int stream)
3697 {
3698         return ffvideo[stream]->frame_rate;
3699 }
3700
3701 int64_t FFMPEG::ff_video_frames(int stream)
3702 {
3703         return ffvideo[stream]->length;
3704 }
3705
3706 int FFMPEG::ff_video_pid(int stream)
3707 {
3708         return ffvideo[stream]->st->id;
3709 }
3710
3711 int FFMPEG::ff_video_mpeg_color_range(int stream)
3712 {
3713         return ffvideo[stream]->st->codecpar->color_range == AVCOL_RANGE_MPEG ? 1 : 0;
3714 }
3715
3716 int FFMPEG::ff_interlace(int stream)
3717 {
3718 // https://ffmpeg.org/doxygen/trunk/structAVCodecParserContext.html
3719 /* reads from demuxer because codec frame not ready */
3720         int interlace0 = ffvideo[stream]->st->codecpar->field_order;
3721
3722         switch (interlace0)
3723         {
3724         case AV_FIELD_TT:
3725         case AV_FIELD_TB:
3726             return ILACE_MODE_TOP_FIRST;
3727         case AV_FIELD_BB:
3728         case AV_FIELD_BT:
3729             return ILACE_MODE_BOTTOM_FIRST;
3730         case AV_FIELD_PROGRESSIVE:
3731             return ILACE_MODE_NOTINTERLACED;
3732         default:
3733             return ILACE_MODE_UNDETECTED;
3734         }
3735         
3736 }
3737
3738
3739
3740 int FFMPEG::ff_cpus()
3741 {
3742         return !file_base ? 1 : file_base->file->cpus;
3743 }
3744
3745 const char *FFMPEG::ff_hw_dev()
3746 {
3747         return &file_base->file->preferences->use_hw_dev[0];
3748 }
3749
3750 Preferences *FFMPEG::ff_prefs()
3751 {
3752         return !file_base ? 0 : file_base->file->preferences;
3753 }
3754
3755 double FFVideoStream::get_rotation_angle()
3756 {
3757 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
3758         size_t size = 0;
3759 #else
3760         int size = 0;
3761 #endif
3762         int *matrix = (int*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX, &size);
3763         int len = size/sizeof(*matrix);
3764         if( !matrix || len < 5 ) return 0;
3765         const double s = 1/65536.;
3766         double theta = (!matrix[0] && !matrix[3]) || (!matrix[1] && !matrix[4]) ? 0 :
3767                  atan2( s*matrix[1] / hypot(s*matrix[1], s*matrix[4]),
3768                         s*matrix[0] / hypot(s*matrix[0], s*matrix[3])) * 180/M_PI;
3769         return theta;
3770 }
3771
3772 int FFVideoStream::flip(double theta)
3773 {
3774         int ret = 0;
3775         transpose = 0;
3776         Preferences *preferences = ffmpeg->ff_prefs();
3777         if( !preferences || !preferences->auto_rotate ) return ret;
3778         double tolerance = 1;
3779         if( fabs(theta-0) < tolerance ) return  ret;
3780         if( (theta=fmod(theta, 360)) < 0 ) theta += 360;
3781         if( fabs(theta-90) < tolerance ) {
3782                 if( (ret = insert_filter("transpose", "clock")) < 0 )
3783                         return ret;
3784                 transpose = 1;
3785         }
3786         else if( fabs(theta-180) < tolerance ) {
3787                 if( (ret=insert_filter("hflip", 0)) < 0 )
3788                         return ret;
3789                 if( (ret=insert_filter("vflip", 0)) < 0 )
3790                         return ret;
3791         }
3792         else if (fabs(theta-270) < tolerance ) {
3793                 if( (ret=insert_filter("transpose", "cclock")) < 0 )
3794                         return ret;
3795                 transpose = 1;
3796         }
3797         else {
3798                 char angle[BCSTRLEN];
3799                 sprintf(angle, "%f", theta*M_PI/180.);
3800                 if( (ret=insert_filter("rotate", angle)) < 0 )
3801                         return ret;
3802         }
3803         return 1;
3804 }
3805
3806 int FFVideoStream::create_filter(const char *filter_spec)
3807 {
3808         double theta = get_rotation_angle();
3809         if( !theta && !filter_spec )
3810                 return 0;
3811         avfilter_register_all();
3812         if( filter_spec ) {
3813                 const char *sp = filter_spec;
3814                 char filter_name[BCSTRLEN], *np = filter_name;
3815                 int i = sizeof(filter_name);
3816                 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
3817                 *np = 0;
3818                 const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
3819                 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_VIDEO ) {
3820                         ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
3821                         return -1;
3822                 }
3823         }
3824         AVCodecParameters *avpar = st->codecpar;
3825         int sa_num = avpar->sample_aspect_ratio.num;
3826         if( !sa_num ) sa_num = 1;
3827         int sa_den = avpar->sample_aspect_ratio.den;
3828         if( !sa_den ) sa_num = 1;
3829
3830         int ret = 0;  char args[BCTEXTLEN];
3831         AVPixelFormat pix_fmt = (AVPixelFormat)avpar->format;
3832         snprintf(args, sizeof(args),
3833                 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
3834                 avpar->width, avpar->height, (int)pix_fmt,
3835                 st->time_base.num, st->time_base.den, sa_num, sa_den);
3836         if( ret >= 0 ) {
3837                 filt_ctx = 0;
3838                 ret = insert_filter("buffer", args, "in");
3839                 buffersrc_ctx = filt_ctx;
3840         }
3841         if( ret >= 0 )
3842                 ret = flip(theta);
3843         AVFilterContext *fsrc = filt_ctx;
3844         if( ret >= 0 ) {
3845                 filt_ctx = 0;
3846                 ret = insert_filter("buffersink", 0, "out");
3847                 buffersink_ctx = filt_ctx;
3848         }
3849         if( ret >= 0 ) {
3850                 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
3851                         (uint8_t*)&pix_fmt, sizeof(pix_fmt),
3852                         AV_OPT_SEARCH_CHILDREN);
3853         }
3854         if( ret >= 0 )
3855                 ret = config_filters(filter_spec, fsrc);
3856         else
3857                 ff_err(ret, "FFVideoStream::create_filter");
3858         return ret >= 0 ? 0 : -1;
3859 }
3860
3861 int FFAudioStream::create_filter(const char *filter_spec)
3862 {
3863         if( !filter_spec )
3864                 return 0;
3865         avfilter_register_all();
3866         if( filter_spec ) {
3867                 const char *sp = filter_spec;
3868                 char filter_name[BCSTRLEN], *np = filter_name;
3869                 int i = sizeof(filter_name);
3870                 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
3871                 *np = 0;
3872                 const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
3873                 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_AUDIO ) {
3874                         ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
3875                         return -1;
3876                 }
3877         }
3878         int ret = 0;  char args[BCTEXTLEN];
3879         AVCodecParameters *avpar = st->codecpar;
3880         AVSampleFormat sample_fmt = (AVSampleFormat)avpar->format;
3881         snprintf(args, sizeof(args),
3882                 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
3883                 st->time_base.num, st->time_base.den, avpar->sample_rate,
3884                 av_get_sample_fmt_name(sample_fmt), avpar->channel_layout);
3885         if( ret >= 0 ) {
3886                 filt_ctx = 0;
3887                 ret = insert_filter("abuffer", args, "in");
3888                 buffersrc_ctx = filt_ctx;
3889         }
3890         AVFilterContext *fsrc = filt_ctx;
3891         if( ret >= 0 ) {
3892                 filt_ctx = 0;
3893                 ret = insert_filter("abuffersink", 0, "out");
3894                 buffersink_ctx = filt_ctx;
3895         }
3896         if( ret >= 0 )
3897                 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
3898                         (uint8_t*)&sample_fmt, sizeof(sample_fmt),
3899                         AV_OPT_SEARCH_CHILDREN);
3900         if( ret >= 0 )
3901                 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
3902                         (uint8_t*)&avpar->channel_layout,
3903                         sizeof(avpar->channel_layout), AV_OPT_SEARCH_CHILDREN);
3904         if( ret >= 0 )
3905                 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
3906                         (uint8_t*)&sample_rate, sizeof(sample_rate),
3907                         AV_OPT_SEARCH_CHILDREN);
3908         if( ret >= 0 )
3909                 ret = config_filters(filter_spec, fsrc);
3910         else
3911                 ff_err(ret, "FFAudioStream::create_filter");
3912         return ret >= 0 ? 0 : -1;
3913 }
3914
3915 int FFStream::insert_filter(const char *name, const char *arg, const char *inst_name)
3916 {
3917         const AVFilter *filter = avfilter_get_by_name(name);
3918         if( !filter ) return -1;
3919         char filt_inst[BCSTRLEN];
3920         if( !inst_name ) {
3921                 snprintf(filt_inst, sizeof(filt_inst), "%s_%d", name, ++filt_id);
3922                 inst_name = filt_inst;
3923         }
3924         if( !filter_graph )
3925                 filter_graph = avfilter_graph_alloc();
3926         AVFilterContext *fctx = 0;
3927         int ret = avfilter_graph_create_filter(&fctx,
3928                 filter, inst_name, arg, NULL, filter_graph);
3929         if( ret >= 0 && filt_ctx )
3930                 ret = avfilter_link(filt_ctx, 0, fctx, 0);
3931         if( ret >= 0 )
3932                 filt_ctx = fctx;
3933         else
3934                 avfilter_free(fctx);
3935         return ret;
3936 }
3937
3938 int FFStream::config_filters(const char *filter_spec, AVFilterContext *fsrc)
3939 {
3940         int ret = 0;
3941         AVFilterContext *fsink = buffersink_ctx;
3942         if( filter_spec ) {
3943                 /* Endpoints for the filter graph. */
3944                 AVFilterInOut *outputs = avfilter_inout_alloc();
3945                 AVFilterInOut *inputs = avfilter_inout_alloc();
3946                 if( !inputs || !outputs ) ret = -1;
3947                 if( ret >= 0 ) {
3948                         outputs->filter_ctx = fsrc;
3949                         outputs->pad_idx = 0;
3950                         outputs->next = 0;
3951                         if( !(outputs->name = av_strdup(fsrc->name)) ) ret = -1;
3952                 }
3953                 if( ret >= 0 ) {
3954                         inputs->filter_ctx = fsink;
3955                         inputs->pad_idx = 0;
3956                         inputs->next = 0;
3957                         if( !(inputs->name = av_strdup(fsink->name)) ) ret = -1;
3958                 }
3959                 if( ret >= 0 ) {
3960                         int len = strlen(fsrc->name)+2 + strlen(filter_spec) + 1;
3961                         char spec[len];  sprintf(spec, "[%s]%s", fsrc->name, filter_spec);
3962                         ret = avfilter_graph_parse_ptr(filter_graph, spec,
3963                                 &inputs, &outputs, NULL);
3964                 }
3965                 avfilter_inout_free(&inputs);
3966                 avfilter_inout_free(&outputs);
3967         }
3968         else
3969                 ret = avfilter_link(fsrc, 0, fsink, 0);
3970         if( ret >= 0 )
3971                 ret = avfilter_graph_config(filter_graph, NULL);
3972         if( ret < 0 ) {
3973                 ff_err(ret, "FFStream::create_filter");
3974                 avfilter_graph_free(&filter_graph);
3975                 filter_graph = 0;
3976         }
3977         return ret;
3978 }
3979
3980
3981 AVCodecContext *FFMPEG::activate_decoder(AVStream *st)
3982 {
3983         AVDictionary *copts = 0;
3984         av_dict_copy(&copts, opts, 0);
3985         AVCodecID codec_id = st->codecpar->codec_id;
3986 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
3987         const AVCodec *decoder = 0;
3988 #else
3989         AVCodec *decoder = 0;
3990 #endif
3991         switch( st->codecpar->codec_type ) {
3992         case AVMEDIA_TYPE_VIDEO:
3993                 if( opt_video_decoder )
3994                         decoder = avcodec_find_decoder_by_name(opt_video_decoder);
3995                 else
3996                         video_codec_remaps.update(codec_id, decoder);
3997                 break;
3998         case AVMEDIA_TYPE_AUDIO:
3999                 if( opt_audio_decoder )
4000                         decoder = avcodec_find_decoder_by_name(opt_audio_decoder);
4001                 else
4002                         audio_codec_remaps.update(codec_id, decoder);
4003                 break;
4004         default:
4005                 return 0;
4006         }
4007         if( !decoder && !(decoder = avcodec_find_decoder(codec_id)) ) {
4008                 eprintf(_("cant find decoder codec %d\n"), (int)codec_id);
4009                 return 0;
4010         }
4011         AVCodecContext *avctx = avcodec_alloc_context3(decoder);
4012         if( !avctx ) {
4013                 eprintf(_("cant allocate codec context\n"));
4014                 return 0;
4015         }
4016         avcodec_parameters_to_context(avctx, st->codecpar);
4017         if( !av_dict_get(copts, "threads", NULL, 0) )
4018                 avctx->thread_count = ff_cpus();
4019         int ret = avcodec_open2(avctx, decoder, &copts);
4020         av_dict_free(&copts);
4021         if( ret < 0 ) {
4022                 avcodec_free_context(&avctx);
4023                 avctx = 0;
4024         }
4025         return avctx;
4026 }
4027
4028 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
4029 {
4030         AVPacket pkt;
4031         av_init_packet(&pkt);
4032         AVFrame *frame = av_frame_alloc();
4033         if( !frame ) {
4034                 fprintf(stderr,"FFMPEG::scan: ");
4035                 fprintf(stderr,_("av_frame_alloc failed\n"));
4036                 fprintf(stderr,"FFMPEG::scan:file=%s\n", file_base->asset->path);
4037                 return -1;
4038         }
4039
4040         index_state->add_video_markers(ffvideo.size());
4041         index_state->add_audio_markers(ffaudio.size());
4042
4043         for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
4044                 AVStream *st = fmt_ctx->streams[i];
4045                 AVCodecContext *avctx = activate_decoder(st);
4046                 if( avctx ) {
4047                         AVCodecParameters *avpar = st->codecpar;
4048                         switch( avpar->codec_type ) {
4049                         case AVMEDIA_TYPE_VIDEO: {
4050                                 int vidx = ffvideo.size();
4051                                 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
4052                                 if( vidx < 0 ) break;
4053                                 ffvideo[vidx]->avctx = avctx;
4054                                 continue; }
4055                         case AVMEDIA_TYPE_AUDIO: {
4056                                 int aidx = ffaudio.size();
4057                                 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
4058                                 if( aidx < 0 ) break;
4059                                 ffaudio[aidx]->avctx = avctx;
4060                                 continue; }
4061                         default: break;
4062                         }
4063                 }
4064                 fprintf(stderr,"FFMPEG::scan: ");
4065                 fprintf(stderr,_("codec open failed\n"));
4066                 fprintf(stderr,"FFMPEG::scan:file=%s\n", file_base->asset->path);
4067                 avcodec_free_context(&avctx);
4068         }
4069
4070         decode_activate();
4071         for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
4072                 AVStream *st = fmt_ctx->streams[i];
4073                 AVCodecParameters *avpar = st->codecpar;
4074                 if( avpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
4075                 int64_t tstmp = st->start_time;
4076                 if( tstmp == AV_NOPTS_VALUE ) continue;
4077                 int aidx = ffaudio.size();
4078                 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
4079                 if( aidx < 0 ) continue;
4080                 FFAudioStream *aud = ffaudio[aidx];
4081                 tstmp -= aud->nudge;
4082                 double secs = to_secs(tstmp, st->time_base);
4083                 aud->curr_pos = secs * aud->sample_rate + 0.5;
4084         }
4085
4086         int errs = 0;
4087         for( int64_t count=0; !*canceled; ++count ) {
4088                 av_packet_unref(&pkt);
4089                 pkt.data = 0; pkt.size = 0;
4090
4091                 int ret = av_read_frame(fmt_ctx, &pkt);
4092                 if( ret < 0 ) {
4093                         if( ret == AVERROR_EOF ) break;
4094                         if( ++errs > 100 ) {
4095                                 ff_err(ret,_("over 100 read_frame errs\n"));
4096                                 break;
4097                         }
4098                         continue;
4099                 }
4100                 if( !pkt.data ) continue;
4101                 int i = pkt.stream_index;
4102                 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
4103                 AVStream *st = fmt_ctx->streams[i];
4104                 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
4105
4106                 AVCodecParameters *avpar = st->codecpar;
4107                 switch( avpar->codec_type ) {
4108                 case AVMEDIA_TYPE_VIDEO: {
4109                         int vidx = ffvideo.size();
4110                         while( --vidx>=0 && ffvideo[vidx]->fidx != i );
4111                         if( vidx < 0 ) break;
4112                         FFVideoStream *vid = ffvideo[vidx];
4113                         if( !vid->avctx ) break;
4114                         int64_t tstmp = pkt.pts;
4115                         if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
4116                         if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
4117                                 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
4118                                 double secs = to_secs(tstmp, st->time_base);
4119                                 int64_t frm = secs * vid->frame_rate + 0.5;
4120                                 if( frm < 0 ) frm = 0;
4121                                 index_state->put_video_mark(vidx, frm, pkt.pos);
4122                         }
4123 #if 0
4124                         ret = avcodec_send_packet(vid->avctx, pkt);
4125                         if( ret < 0 ) break;
4126                         while( (ret=vid->decode_frame(frame)) > 0 ) {}
4127 #endif
4128                         break; }
4129                 case AVMEDIA_TYPE_AUDIO: {
4130                         int aidx = ffaudio.size();
4131                         while( --aidx>=0 && ffaudio[aidx]->fidx != i );
4132                         if( aidx < 0 ) break;
4133                         FFAudioStream *aud = ffaudio[aidx];
4134                         if( !aud->avctx ) break;
4135                         int64_t tstmp = pkt.pts;
4136                         if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
4137                         if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
4138                                 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
4139                                 double secs = to_secs(tstmp, st->time_base);
4140                                 int64_t sample = secs * aud->sample_rate + 0.5;
4141                                 if( sample >= 0 )
4142                                         index_state->put_audio_mark(aidx, sample, pkt.pos);
4143                         }
4144                         ret = avcodec_send_packet(aud->avctx, &pkt);
4145                         if( ret < 0 ) break;
4146                         int ch = aud->channel0,  nch = aud->channels;
4147                         int64_t pos = index_state->pos(ch);
4148                         if( pos != aud->curr_pos ) {
4149 if( abs(pos-aud->curr_pos) > 1 )
4150 printf("audio%d pad %jd %jd (%jd)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
4151                                 index_state->pad_data(ch, nch, aud->curr_pos);
4152                         }
4153                         while( (ret=aud->decode_frame(frame)) > 0 ) {
4154                                 //if( frame->channels != nch ) break;
4155                                 aud->init_swr(frame->channels, frame->format, frame->sample_rate);
4156                                 float *samples;
4157                                 int len = aud->get_samples(samples,
4158                                          &frame->extended_data[0], frame->nb_samples);
4159                                 pos = aud->curr_pos;
4160                                 if( (aud->curr_pos += len) >= 0 ) {
4161                                         if( pos < 0 ) {
4162                                                 samples += -pos * nch;
4163                                                 len = aud->curr_pos;
4164                                         }
4165                                         for( int i=0; i<nch; ++i )
4166                                                 index_state->put_data(ch+i,nch,samples+i,len);
4167                                 }
4168                         }
4169                         break; }
4170                 default: break;
4171                 }
4172         }
4173         av_frame_free(&frame);
4174         return 0;
4175 }
4176
4177 void FFStream::load_markers(IndexMarks &marks, double rate)
4178 {
4179         int in = 0;
4180         int64_t sz = marks.size();
4181         int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
4182 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
4183         int nb_ent = avformat_index_get_entries_count(st);
4184 #endif
4185 #if LIBAVCODEC_VERSION_INT <= AV_VERSION_INT(58,134,100)
4186         int nb_ent = st->nb_index_entries;
4187 #endif
4188 // some formats already have an index
4189         if( nb_ent > 0 ) {
4190 #if LIBAVCODEC_VERSION_INT <= AV_VERSION_INT(58,134,100)
4191                 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
4192 #endif
4193 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
4194                 const AVIndexEntry *ep = avformat_index_get_entry(st, nb_ent-1);
4195 #endif
4196                 int64_t tstmp = ep->timestamp;
4197                 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
4198                 double secs = ffmpeg->to_secs(tstmp, st->time_base);
4199                 int64_t no = secs * rate;
4200                 while( in < sz && marks[in].no <= no ) ++in;
4201         }
4202         int64_t len = sz - in;
4203         int64_t count = max_entries - nb_ent;
4204         if( count > len ) count = len;
4205         for( int i=0; i<count; ++i ) {
4206                 int k = in + i * len / count;
4207                 int64_t no = marks[k].no, pos = marks[k].pos;
4208                 double secs = (double)no / rate;
4209                 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
4210                 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
4211                 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);
4212         }
4213 }
4214
4215
4216 /*
4217  * 1) if the format context has a timecode
4218  *   return fmt_ctx->timecode - 0
4219  * 2) if the layer/channel has a timecode
4220  *   return st->timecode - (start_time-nudge)
4221  * 3) find the 1st program with stream, find 1st program video stream,
4222  *   if video stream has a timecode, return st->timecode - (start_time-nudge)
4223  * 4) find timecode in any stream, return st->timecode
4224  * 5) read 100 packets, save ofs=pkt.pts*st->time_base - st->nudge:
4225  *   decode frame for video stream of 1st program
4226  *   if frame->timecode has a timecode, return frame->timecode - ofs
4227  *   if side_data has gop timecode, return gop->timecode - ofs
4228  *   if side_data has smpte timecode, return smpte->timecode - ofs
4229  * 6) if the filename/url scans *date_time.ext, return date_time
4230  * 7) if stat works on the filename/url, return mtime
4231  * 8) return -1 failure
4232 */
4233 double FFMPEG::get_initial_timecode(int data_type, int channel, double frame_rate)
4234 {
4235         AVRational rate = check_frame_rate(0, frame_rate);
4236         if( !rate.num ) return -1;
4237 // format context timecode
4238         AVDictionaryEntry *tc = av_dict_get(fmt_ctx->metadata, "timecode", 0, 0);
4239         if( tc ) return ff_get_timecode(tc->value, rate, 0);
4240 // stream timecode
4241         if( open_decoder() ) return -1;
4242         AVStream *st = 0;
4243         int64_t nudge = 0;
4244         int codec_type = -1, fidx = -1;
4245         switch( data_type ) {
4246         case TRACK_AUDIO: {
4247                 codec_type = AVMEDIA_TYPE_AUDIO;
4248                 int aidx = astrm_index[channel].st_idx;
4249                 FFAudioStream *aud = ffaudio[aidx];
4250                 fidx = aud->fidx;
4251                 nudge = aud->nudge;
4252                 st = aud->st;
4253                 AVDictionaryEntry *tref = av_dict_get(fmt_ctx->metadata, "time_reference", 0, 0);
4254                 if( tref && aud && aud->sample_rate )
4255                         return strtod(tref->value, 0) / aud->sample_rate;
4256                 break; }
4257         case TRACK_VIDEO: {
4258                 codec_type = AVMEDIA_TYPE_VIDEO;
4259                 int vidx = vstrm_index[channel].st_idx;
4260                 FFVideoStream *vid = ffvideo[vidx];
4261                 fidx = vid->fidx;
4262                 nudge = vid->nudge;
4263                 st = vid->st;
4264                 break; }
4265         }
4266         if( codec_type < 0 ) return -1;
4267         if( st )
4268                 tc = av_dict_get(st->metadata, "timecode", 0, 0);
4269         if( !tc ) {
4270                 st = 0;
4271 // find first program which references this stream
4272                 int pidx = -1;
4273                 for( int i=0, m=fmt_ctx->nb_programs; pidx<0 && i<m; ++i ) {
4274                         AVProgram *pgrm = fmt_ctx->programs[i];
4275                         for( int j=0, n=pgrm->nb_stream_indexes; j<n; ++j ) {
4276                                 int st_idx = pgrm->stream_index[j];
4277                                 if( st_idx == fidx ) { pidx = i;  break; }
4278                         }
4279                 }
4280                 fidx = -1;
4281                 if( pidx >= 0 ) {
4282                         AVProgram *pgrm = fmt_ctx->programs[pidx];
4283                         for( int j=0, n=pgrm->nb_stream_indexes; j<n; ++j ) {
4284                                 int st_idx = pgrm->stream_index[j];
4285                                 AVStream *tst = fmt_ctx->streams[st_idx];
4286                                 if( !tst ) continue;
4287                                 if( tst->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
4288                                         st = tst;  fidx = st_idx;
4289                                         break;
4290                                 }
4291                         }
4292                 }
4293                 else {
4294                         for( int i=0, n=fmt_ctx->nb_streams; i<n; ++i ) {
4295                                 AVStream *tst = fmt_ctx->streams[i];
4296                                 if( !tst ) continue;
4297                                 if( tst->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
4298                                         st = tst;  fidx = i;
4299                                         break;
4300                                 }
4301                         }
4302                 }
4303                 if( st )
4304                         tc = av_dict_get(st->metadata, "timecode", 0, 0);
4305         }
4306
4307         if( !tc ) {
4308                 // any timecode, includes -data- streams
4309                 for( int i=0, n=fmt_ctx->nb_streams; i<n; ++i ) {
4310                         AVStream *tst = fmt_ctx->streams[i];
4311                         if( !tst ) continue;
4312                         if( (tc = av_dict_get(tst->metadata, "timecode", 0, 0)) ) {
4313                                 st = tst;  fidx = i;
4314                                 break;
4315                         }
4316                 }
4317         }
4318
4319         if( st && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
4320                 if( st->r_frame_rate.num && st->r_frame_rate.den )
4321                         rate = st->r_frame_rate;
4322                 nudge = st->start_time;
4323                 for( int i=0; i<ffvideo.size(); ++i ) {
4324                         if( ffvideo[i]->st == st ) {
4325                                 nudge = ffvideo[i]->nudge;
4326                                 break;
4327                         }
4328                 }
4329         }
4330
4331         if( tc ) { // return timecode
4332                 double secs = st->start_time == AV_NOPTS_VALUE ? 0 :
4333                         to_secs(st->start_time - nudge, st->time_base);
4334                 return ff_get_timecode(tc->value, rate, secs);
4335         }
4336         
4337         if( !st || fidx < 0 ) return -1;
4338
4339         decode_activate();
4340         AVCodecContext *av_ctx = activate_decoder(st);
4341         if( !av_ctx ) {
4342                 fprintf(stderr,"activate_decoder failed\n");
4343                 return -1;
4344         }
4345         avCodecContext avctx(av_ctx); // auto deletes
4346         if( avctx->codec_type == AVMEDIA_TYPE_VIDEO &&
4347             avctx->framerate.num && avctx->framerate.den )
4348                 rate = avctx->framerate;
4349
4350         avPacket pkt;   // auto deletes
4351         avFrame frame;  // auto deletes
4352         if( !frame ) {
4353                 fprintf(stderr,"av_frame_alloc failed\n");
4354                 return -1;
4355         }
4356         int errs = 0;
4357         int64_t max_packets = 100;
4358         char tcbuf[AV_TIMECODE_STR_SIZE];
4359
4360         for( int64_t count=0; count<max_packets; ++count ) {
4361                 av_packet_unref(pkt);
4362                 pkt->data = 0; pkt->size = 0;
4363
4364                 int ret = av_read_frame(fmt_ctx, pkt);
4365                 if( ret < 0 ) {
4366                         if( ret == AVERROR_EOF ) break;
4367                         if( ++errs > 100 ) {
4368                                 fprintf(stderr,"over 100 read_frame errs\n");
4369                                 break;
4370                         }
4371                         continue;
4372                 }
4373                 if( !pkt->data ) continue;
4374                 int i = pkt->stream_index;
4375                 if( i != fidx ) continue;
4376                 int64_t tstmp = pkt->pts;
4377                 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt->dts;
4378                 double secs = to_secs(tstmp - nudge, st->time_base);
4379                 ret = avcodec_send_packet(avctx, pkt);
4380                 if( ret < 0 ) return -1;
4381
4382                 while( (ret = avcodec_receive_frame(avctx, frame)) >= 0 ) {
4383                         if( (tc = av_dict_get(frame->metadata, "timecode", 0, 0)) )
4384                                 return ff_get_timecode(tc->value, rate, secs);
4385                         int k = frame->nb_side_data;
4386                         AVFrameSideData *side_data = 0;
4387                         while( --k >= 0 ) {
4388                                 side_data = frame->side_data[k];
4389                                 switch( side_data->type ) {
4390                                 case AV_FRAME_DATA_GOP_TIMECODE: {
4391                                         int64_t data = *(int64_t *)side_data->data;
4392                                         int sz = sizeof(data);
4393                                         if( side_data->size >= sz ) {
4394                                                 av_timecode_make_mpeg_tc_string(tcbuf, data);
4395                                                 return ff_get_timecode(tcbuf, rate, secs);
4396                                         }
4397                                         break; }
4398                                 case AV_FRAME_DATA_S12M_TIMECODE: {
4399                                         uint32_t *data = (uint32_t *)side_data->data;
4400                                         int n = data[0], sz = (n+1)*sizeof(*data);
4401                                         if( side_data->size >= sz ) {
4402                                                 av_timecode_make_smpte_tc_string(tcbuf, data[n], 0);
4403                                                 return ff_get_timecode(tcbuf, rate, secs);
4404                                         }
4405                                         break; }
4406                                 default:
4407                                         break;
4408                                 }
4409                         }
4410                 }
4411         }
4412         char *path = fmt_ctx->url;
4413         char *bp = strrchr(path, '/');
4414         if( !bp ) bp = path; else ++bp;
4415         char *cp = strrchr(bp, '.');
4416         if( cp && (cp-=(8+1+6)) >= bp ) {
4417                 char sep[BCSTRLEN];
4418                 int year,mon,day, hour,min,sec, frm=0;
4419                 if( sscanf(cp,"%4d%2d%2d%[_-]%2d%2d%2d",
4420                                 &year,&mon,&day, sep, &hour,&min,&sec) == 7 ) {
4421                         int ch = sep[0];
4422                         // year>=1970,mon=1..12,day=1..31, hour=0..23,min=0..59,sec=0..60
4423                         if( (ch=='_' || ch=='-' ) &&
4424                             year >= 1970 && mon>=1 && mon<=12 && day>=1 && day<=31 &&
4425                             hour>=0 && hour<24 && min>=0 && min<60 && sec>=0 && sec<=60 ) {
4426                                 sprintf(tcbuf,"%d:%02d:%02d:%02d", hour,min,sec, frm);
4427                                 return ff_get_timecode(tcbuf, rate, 0);
4428                         }
4429                 }
4430         }
4431         struct stat tst;
4432         if( stat(path, &tst) >= 0 ) {
4433                 time_t t = (time_t)tst.st_mtim.tv_sec;
4434                 struct tm tm;
4435                 localtime_r(&t, &tm);
4436                 int64_t us = tst.st_mtim.tv_nsec / 1000;
4437                 int frm = us/1000000. * frame_rate;
4438                 sprintf(tcbuf,"%d:%02d:%02d:%02d", tm.tm_hour, tm.tm_min, tm.tm_sec, frm);
4439                 return ff_get_timecode(tcbuf, rate, 0);
4440         }
4441         return -1;
4442 }
4443
4444 double FFMPEG::ff_get_timecode(char *str, AVRational rate, double pos)
4445 {
4446         AVTimecode tc;
4447         if( av_timecode_init_from_string(&tc, rate, str, fmt_ctx) )
4448                 return -1;
4449         double secs = (double)tc.start / tc.fps - pos;
4450         if( secs < 0 ) secs = 0;
4451         return secs;
4452 }
4453
4454 double FFMPEG::get_timecode(const char *path, int data_type, int channel, double rate)
4455 {
4456         FFMPEG ffmpeg(0);
4457         if( ffmpeg.init_decoder(path) ) return -1;
4458         return ffmpeg.get_initial_timecode(data_type, channel, rate);
4459 }
4460