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