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