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