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