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