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