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