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