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