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