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