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