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