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