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