no /. in ffmpeg init_decode segv, build index fix audio wave, stop playback state...
[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         strcpy(file_opts, filename);
1952         char *bp = strrchr(file_opts, '/');
1953         if( !bp ) bp = file_opts;
1954         char *sp = strrchr(bp, '.');
1955         if( !sp ) sp = bp + strlen(bp);
1956         FILE *fp = 0;
1957         AVInputFormat *ifmt = 0;
1958         if( sp ) {
1959                 strcpy(sp, ".opts");
1960                 fp = fopen(file_opts, "r");
1961         }
1962         if( fp ) {
1963                 read_options(fp, file_opts, opts);
1964                 fclose(fp);
1965                 AVDictionaryEntry *tag;
1966                 if( (tag=av_dict_get(opts, "format", NULL, 0)) != 0 ) {
1967                         ifmt = av_find_input_format(tag->value);
1968                 }
1969         }
1970         else
1971                 load_options("decode.opts", opts);
1972         AVDictionary *fopts = 0;
1973         av_dict_copy(&fopts, opts, 0);
1974         int ret = avformat_open_input(&fmt_ctx, filename, ifmt, &fopts);
1975         av_dict_free(&fopts);
1976         if( ret >= 0 )
1977                 ret = avformat_find_stream_info(fmt_ctx, NULL);
1978         if( !ret ) {
1979                 decoding = -1;
1980         }
1981         ff_unlock();
1982         return !ret ? 0 : 1;
1983 }
1984
1985 int FFMPEG::open_decoder()
1986 {
1987         struct stat st;
1988         if( stat(fmt_ctx->url, &st) < 0 ) {
1989                 eprintf(_("can't stat file: %s\n"), fmt_ctx->url);
1990                 return 1;
1991         }
1992
1993         int64_t file_bits = 8 * st.st_size;
1994         if( !fmt_ctx->bit_rate && opt_duration > 0 )
1995                 fmt_ctx->bit_rate = file_bits / opt_duration;
1996
1997         int estimated = 0;
1998         if( fmt_ctx->bit_rate > 0 ) {
1999                 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2000                         AVStream *st = fmt_ctx->streams[i];
2001                         if( st->duration != AV_NOPTS_VALUE ) continue;
2002                         if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
2003                         st->duration = av_rescale(file_bits, st->time_base.den,
2004                                 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
2005                         estimated = 1;
2006                 }
2007         }
2008         if( estimated && !(fflags & FF_ESTM_TIMES) ) {
2009                 fflags |= FF_ESTM_TIMES;
2010                 printf("FFMPEG::open_decoder: some stream times estimated: %s\n",
2011                         fmt_ctx->url);
2012         }
2013
2014         ff_lock("FFMPEG::open_decoder");
2015         int ret = 0, bad_time = 0;
2016         for( int i=0; !ret && i<(int)fmt_ctx->nb_streams; ++i ) {
2017                 AVStream *st = fmt_ctx->streams[i];
2018                 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
2019                 AVCodecParameters *avpar = st->codecpar;
2020                 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avpar->codec_id);
2021                 if( !codec_desc ) continue;
2022                 switch( avpar->codec_type ) {
2023                 case AVMEDIA_TYPE_VIDEO: {
2024                         if( avpar->width < 1 ) continue;
2025                         if( avpar->height < 1 ) continue;
2026                         AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
2027                         if( framerate.num < 1 ) continue;
2028                         has_video = 1;
2029                         int vidx = ffvideo.size();
2030                         FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
2031                         vstrm_index.append(ffidx(vidx, 0));
2032                         ffvideo.append(vid);
2033                         vid->width = avpar->width;
2034                         vid->height = avpar->height;
2035                         vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
2036                         double secs = to_secs(st->duration, st->time_base);
2037                         vid->length = secs * vid->frame_rate;
2038                         vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
2039                         vid->nudge = st->start_time;
2040                         vid->reading = -1;
2041                         if( opt_video_filter )
2042                                 ret = vid->create_filter(opt_video_filter, avpar);
2043                         break; }
2044                 case AVMEDIA_TYPE_AUDIO: {
2045                         if( avpar->channels < 1 ) continue;
2046                         if( avpar->sample_rate < 1 ) continue;
2047                         has_audio = 1;
2048                         int aidx = ffaudio.size();
2049                         FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
2050                         ffaudio.append(aud);
2051                         aud->channel0 = astrm_index.size();
2052                         aud->channels = avpar->channels;
2053                         for( int ch=0; ch<aud->channels; ++ch )
2054                                 astrm_index.append(ffidx(aidx, ch));
2055                         aud->sample_rate = avpar->sample_rate;
2056                         double secs = to_secs(st->duration, st->time_base);
2057                         aud->length = secs * aud->sample_rate;
2058                         aud->init_swr(aud->channels, avpar->format, aud->sample_rate);
2059                         aud->nudge = st->start_time;
2060                         aud->reading = -1;
2061                         if( opt_audio_filter )
2062                                 ret = aud->create_filter(opt_audio_filter, avpar);
2063                         break; }
2064                 default: break;
2065                 }
2066         }
2067         if( bad_time && !(fflags & FF_BAD_TIMES) ) {
2068                 fflags |= FF_BAD_TIMES;
2069                 printf("FFMPEG::open_decoder: some stream have bad times: %s\n",
2070                         fmt_ctx->url);
2071         }
2072         ff_unlock();
2073         return ret < 0 ? -1 : 0;
2074 }
2075
2076
2077 int FFMPEG::init_encoder(const char *filename)
2078 {
2079 // try access first for named pipes
2080         int ret = access(filename, W_OK);
2081         if( ret ) {
2082                 int fd = ::open(filename,O_WRONLY);
2083                 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
2084                 if( fd >= 0 ) { close(fd);  ret = 0; }
2085         }
2086         if( ret ) {
2087                 eprintf(_("bad file path: %s\n"), filename);
2088                 return 1;
2089         }
2090         ret = get_file_format();
2091         if( ret > 0 ) {
2092                 eprintf(_("bad file format: %s\n"), filename);
2093                 return 1;
2094         }
2095         if( ret < 0 ) {
2096                 eprintf(_("mismatch audio/video file format: %s\n"), filename);
2097                 return 1;
2098         }
2099         ff_lock("FFMPEG::init_encoder");
2100         av_register_all();
2101         char format[BCSTRLEN];
2102         if( get_format(format, "format", file_format) )
2103                 strcpy(format, file_format);
2104         avformat_alloc_output_context2(&fmt_ctx, 0, format, filename);
2105         if( !fmt_ctx ) {
2106                 eprintf(_("failed: %s\n"), filename);
2107                 ret = 1;
2108         }
2109         if( !ret ) {
2110                 encoding = -1;
2111                 load_options("encode.opts", opts);
2112         }
2113         ff_unlock();
2114         return ret;
2115 }
2116
2117 int FFMPEG::open_encoder(const char *type, const char *spec)
2118 {
2119
2120         Asset *asset = file_base->asset;
2121         char *filename = asset->path;
2122         AVDictionary *sopts = 0;
2123         av_dict_copy(&sopts, opts, 0);
2124         char option_path[BCTEXTLEN];
2125         set_option_path(option_path, "%s/%s.opts", type, type);
2126         read_options(option_path, sopts);
2127         get_option_path(option_path, type, spec);
2128         char format_name[BCSTRLEN], codec_name[BCTEXTLEN], bsfilter[BCTEXTLEN];
2129         if( get_encoder(option_path, format_name, codec_name, bsfilter) ) {
2130                 eprintf(_("get_encoder failed %s:%s\n"), option_path, filename);
2131                 return 1;
2132         }
2133
2134 #ifdef HAVE_DV
2135         if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
2136 #endif
2137         else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
2138         else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
2139
2140         int ret = 0;
2141         ff_lock("FFMPEG::open_encoder");
2142         FFStream *fst = 0;
2143         AVStream *st = 0;
2144         AVCodecContext *ctx = 0;
2145
2146         const AVCodecDescriptor *codec_desc = 0;
2147         AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
2148         if( !codec ) {
2149                 eprintf(_("cant find codec %s:%s\n"), codec_name, filename);
2150                 ret = 1;
2151         }
2152         if( !ret ) {
2153                 codec_desc = avcodec_descriptor_get(codec->id);
2154                 if( !codec_desc ) {
2155                         eprintf(_("unknown codec %s:%s\n"), codec_name, filename);
2156                         ret = 1;
2157                 }
2158         }
2159         if( !ret ) {
2160                 st = avformat_new_stream(fmt_ctx, 0);
2161                 if( !st ) {
2162                         eprintf(_("cant create stream %s:%s\n"), codec_name, filename);
2163                         ret = 1;
2164                 }
2165         }
2166         if( !ret ) {
2167                 switch( codec_desc->type ) {
2168                 case AVMEDIA_TYPE_AUDIO: {
2169                         if( has_audio ) {
2170                                 eprintf(_("duplicate audio %s:%s\n"), codec_name, filename);
2171                                 ret = 1;
2172                                 break;
2173                         }
2174                         if( scan_options(asset->ff_audio_options, sopts, st) ) {
2175                                 eprintf(_("bad audio options %s:%s\n"), codec_name, filename);
2176                                 ret = 1;
2177                                 break;
2178                         }
2179                         has_audio = 1;
2180                         ctx = avcodec_alloc_context3(codec);
2181                         if( asset->ff_audio_bitrate > 0 ) {
2182                                 ctx->bit_rate = asset->ff_audio_bitrate;
2183                                 char arg[BCSTRLEN];
2184                                 sprintf(arg, "%d", asset->ff_audio_bitrate);
2185                                 av_dict_set(&sopts, "b", arg, 0);
2186                         }
2187                         else if( asset->ff_audio_quality >= 0 ) {
2188                                 ctx->global_quality = asset->ff_audio_quality * FF_QP2LAMBDA;
2189                                 ctx->qmin    = ctx->qmax =  asset->ff_audio_quality;
2190                                 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2191                                 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2192                                 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2193                                 char arg[BCSTRLEN];
2194                                 av_dict_set(&sopts, "flags", "+qscale", 0);
2195                                 sprintf(arg, "%d", asset->ff_audio_quality);
2196                                 av_dict_set(&sopts, "qscale", arg, 0);
2197                                 sprintf(arg, "%d", ctx->global_quality);
2198                                 av_dict_set(&sopts, "global_quality", arg, 0);
2199                         }
2200                         int aidx = ffaudio.size();
2201                         int fidx = aidx + ffvideo.size();
2202                         FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
2203                         aud->avctx = ctx;  ffaudio.append(aud);  fst = aud;
2204                         aud->sample_rate = asset->sample_rate;
2205                         ctx->channels = aud->channels = asset->channels;
2206                         for( int ch=0; ch<aud->channels; ++ch )
2207                                 astrm_index.append(ffidx(aidx, ch));
2208                         ctx->channel_layout =  av_get_default_channel_layout(ctx->channels);
2209                         ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
2210                         if( !ctx->sample_rate ) {
2211                                 eprintf(_("check_sample_rate failed %s\n"), filename);
2212                                 ret = 1;
2213                                 break;
2214                         }
2215                         ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
2216                         AVSampleFormat sample_fmt = av_get_sample_fmt(asset->ff_sample_format);
2217                         if( sample_fmt == AV_SAMPLE_FMT_NONE )
2218                                 sample_fmt = codec->sample_fmts ? codec->sample_fmts[0] : AV_SAMPLE_FMT_S16;
2219                         ctx->sample_fmt = sample_fmt;
2220                         uint64_t layout = av_get_default_channel_layout(ctx->channels);
2221                         aud->resample_context = swr_alloc_set_opts(NULL,
2222                                 layout, ctx->sample_fmt, aud->sample_rate,
2223                                 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
2224                                 0, NULL);
2225                         swr_init(aud->resample_context);
2226                         aud->writing = -1;
2227                         break; }
2228                 case AVMEDIA_TYPE_VIDEO: {
2229                         if( has_video ) {
2230                                 eprintf(_("duplicate video %s:%s\n"), codec_name, filename);
2231                                 ret = 1;
2232                                 break;
2233                         }
2234                         if( scan_options(asset->ff_video_options, sopts, st) ) {
2235                                 eprintf(_("bad video options %s:%s\n"), codec_name, filename);
2236                                 ret = 1;
2237                                 break;
2238                         }
2239                         has_video = 1;
2240                         ctx = avcodec_alloc_context3(codec);
2241                         if( asset->ff_video_bitrate > 0 ) {
2242                                 ctx->bit_rate = asset->ff_video_bitrate;
2243                                 char arg[BCSTRLEN];
2244                                 sprintf(arg, "%d", asset->ff_video_bitrate);
2245                                 av_dict_set(&sopts, "b", arg, 0);
2246                         }
2247                         else if( asset->ff_video_quality >= 0 ) {
2248                                 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
2249                                 ctx->qmin    = ctx->qmax =  asset->ff_video_quality;
2250                                 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2251                                 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2252                                 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2253                                 char arg[BCSTRLEN];
2254                                 av_dict_set(&sopts, "flags", "+qscale", 0);
2255                                 sprintf(arg, "%d", asset->ff_video_quality);
2256                                 av_dict_set(&sopts, "qscale", arg, 0);
2257                                 sprintf(arg, "%d", ctx->global_quality);
2258                                 av_dict_set(&sopts, "global_quality", arg, 0);
2259                         }
2260                         int vidx = ffvideo.size();
2261                         int fidx = vidx + ffaudio.size();
2262                         FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
2263                         vstrm_index.append(ffidx(vidx, 0));
2264                         vid->avctx = ctx;  ffvideo.append(vid);  fst = vid;
2265                         vid->width = asset->width;
2266                         vid->height = asset->height;
2267                         vid->frame_rate = asset->frame_rate;
2268
2269                         AVPixelFormat pix_fmt = av_get_pix_fmt(asset->ff_pixel_format);
2270                         if( pix_fmt == AV_PIX_FMT_NONE )
2271                                 pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
2272                         ctx->pix_fmt = pix_fmt;
2273                         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
2274                         int mask_w = (1<<desc->log2_chroma_w)-1;
2275                         ctx->width = (vid->width+mask_w) & ~mask_w;
2276                         int mask_h = (1<<desc->log2_chroma_h)-1;
2277                         ctx->height = (vid->height+mask_h) & ~mask_h;
2278                         ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
2279                         AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
2280                         if( !frame_rate.num || !frame_rate.den ) {
2281                                 eprintf(_("check_frame_rate failed %s\n"), filename);
2282                                 ret = 1;
2283                                 break;
2284                         }
2285                         av_reduce(&frame_rate.num, &frame_rate.den,
2286                                 frame_rate.num, frame_rate.den, INT_MAX);
2287                         ctx->framerate = (AVRational) { frame_rate.num, frame_rate.den };
2288                         ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
2289                         st->avg_frame_rate = frame_rate;
2290                         st->time_base = ctx->time_base;
2291                         vid->writing = -1;
2292                         vid->interlaced = asset->interlace_mode == ILACE_MODE_TOP_FIRST ||
2293                                 asset->interlace_mode == ILACE_MODE_BOTTOM_FIRST ? 1 : 0;
2294                         vid->top_field_first = asset->interlace_mode == ILACE_MODE_TOP_FIRST ? 1 : 0;
2295                         break; }
2296                 default:
2297                         eprintf(_("not audio/video, %s:%s\n"), codec_name, filename);
2298                         ret = 1;
2299                 }
2300
2301                 if( ctx ) {
2302                         AVDictionaryEntry *tag;
2303                         if( (tag=av_dict_get(sopts, "cin_stats_filename", NULL, 0)) != 0 ) {
2304                                 char suffix[BCSTRLEN];  sprintf(suffix,"-%d.log",fst->fidx);
2305                                 fst->stats_filename = cstrcat(2, tag->value, suffix);
2306                         }
2307                         if( (tag=av_dict_get(sopts, "flags", NULL, 0)) != 0 ) {
2308                                 int pass = fst->pass;
2309                                 char *cp = tag->value;
2310                                 while( *cp ) {
2311                                         int ch = *cp++, pfx = ch=='-' ? -1 : ch=='+' ? 1 : 0;
2312                                         if( !isalnum(!pfx ? ch : (ch=*cp++)) ) continue;
2313                                         char id[BCSTRLEN], *bp = id, *ep = bp+sizeof(id)-1;
2314                                         for( *bp++=ch; isalnum(ch=*cp); ++cp )
2315                                                 if( bp < ep ) *bp++ = ch;
2316                                         *bp = 0;
2317                                         if( !strcmp(id, "pass1") ) {
2318                                                 pass = pfx<0 ? (pass&~1) : pfx>0 ? (pass|1) : 1;
2319                                         }
2320                                         else if( !strcmp(id, "pass2") ) {
2321                                                 pass = pfx<0 ? (pass&~2) : pfx>0 ? (pass|2) : 2;
2322                                         }
2323                                 }
2324                                 if( (fst->pass=pass) ) {
2325                                         if( pass & 1 ) ctx->flags |= AV_CODEC_FLAG_PASS1;
2326                                         if( pass & 2 ) ctx->flags |= AV_CODEC_FLAG_PASS2;
2327                                 }
2328                         }
2329                 }
2330         }
2331         if( !ret ) {
2332                 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
2333                         ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
2334                 if( fst->stats_filename && (ret=fst->init_stats_file()) )
2335                         eprintf(_("error: stats file = %s\n"), fst->stats_filename);
2336         }
2337         if( !ret ) {
2338                 av_dict_set(&sopts, "cin_bitrate", 0, 0);
2339                 av_dict_set(&sopts, "cin_quality", 0, 0);
2340
2341                 if( !av_dict_get(sopts, "threads", NULL, 0) )
2342                         ctx->thread_count = ff_cpus();
2343                 ret = avcodec_open2(ctx, codec, &sopts);
2344                 if( ret >= 0 ) {
2345                         ret = avcodec_parameters_from_context(st->codecpar, ctx);
2346                         if( ret < 0 )
2347                                 fprintf(stderr, "Could not copy the stream parameters\n");
2348                 }
2349                 if( ret >= 0 ) {
2350 _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
2351                         ret = avcodec_copy_context(st->codec, ctx);
2352 _Pragma("GCC diagnostic warning \"-Wdeprecated-declarations\"")
2353                         if( ret < 0 )
2354                                 fprintf(stderr, "Could not copy the stream context\n");
2355                 }
2356                 if( ret < 0 ) {
2357                         ff_err(ret,"FFMPEG::open_encoder");
2358                         eprintf(_("open failed %s:%s\n"), codec_name, filename);
2359                         ret = 1;
2360                 }
2361                 else
2362                         ret = 0;
2363         }
2364         if( !ret && fst && bsfilter[0] ) {
2365                 ret = av_bsf_list_parse_str(bsfilter, &fst->bsfc);
2366                 if( ret < 0 ) {
2367                         ff_err(ret,"FFMPEG::open_encoder");
2368                         eprintf(_("bitstream filter failed %s:\n%s\n"), filename, bsfilter);
2369                         ret = 1;
2370                 }
2371                 else
2372                         ret = 0;
2373         }
2374
2375         if( !ret )
2376                 start_muxer();
2377
2378         ff_unlock();
2379         av_dict_free(&sopts);
2380         return ret;
2381 }
2382
2383 int FFMPEG::close_encoder()
2384 {
2385         stop_muxer();
2386         if( encoding > 0 ) {
2387                 av_write_trailer(fmt_ctx);
2388                 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
2389                         avio_closep(&fmt_ctx->pb);
2390         }
2391         encoding = 0;
2392         return 0;
2393 }
2394
2395 int FFMPEG::decode_activate()
2396 {
2397         if( decoding < 0 ) {
2398                 decoding = 0;
2399                 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
2400                         ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
2401                 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
2402                         ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
2403                 // set nudges for each program stream set
2404                 const int64_t min_nudge = INT64_MIN+1;
2405                 int npgrms = fmt_ctx->nb_programs;
2406                 for( int i=0; i<npgrms; ++i ) {
2407                         AVProgram *pgrm = fmt_ctx->programs[i];
2408                         // first start time video stream
2409                         int64_t vstart_time = min_nudge, astart_time = min_nudge;
2410                         for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2411                                 int fidx = pgrm->stream_index[j];
2412                                 AVStream *st = fmt_ctx->streams[fidx];
2413                                 AVCodecParameters *avpar = st->codecpar;
2414                                 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2415                                         if( st->start_time == AV_NOPTS_VALUE ) continue;
2416                                         if( vstart_time < st->start_time )
2417                                                 vstart_time = st->start_time;
2418                                         continue;
2419                                 }
2420                                 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2421                                         if( st->start_time == AV_NOPTS_VALUE ) continue;
2422                                         if( astart_time < st->start_time )
2423                                                 astart_time = st->start_time;
2424                                         continue;
2425                                 }
2426                         }
2427                         //since frame rate is much more grainy than sample rate, it is better to
2428                         // align using video, so that total absolute error is minimized.
2429                         int64_t nudge = vstart_time > min_nudge ? vstart_time :
2430                                 astart_time > min_nudge ? astart_time : AV_NOPTS_VALUE;
2431                         for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2432                                 int fidx = pgrm->stream_index[j];
2433                                 AVStream *st = fmt_ctx->streams[fidx];
2434                                 AVCodecParameters *avpar = st->codecpar;
2435                                 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2436                                         for( int k=0; k<ffvideo.size(); ++k ) {
2437                                                 if( ffvideo[k]->fidx != fidx ) continue;
2438                                                 ffvideo[k]->nudge = nudge;
2439                                         }
2440                                         continue;
2441                                 }
2442                                 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2443                                         for( int k=0; k<ffaudio.size(); ++k ) {
2444                                                 if( ffaudio[k]->fidx != fidx ) continue;
2445                                                 ffaudio[k]->nudge = nudge;
2446                                         }
2447                                         continue;
2448                                 }
2449                         }
2450                 }
2451                 // set nudges for any streams not yet set
2452                 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2453                 int nstreams = fmt_ctx->nb_streams;
2454                 for( int i=0; i<nstreams; ++i ) {
2455                         AVStream *st = fmt_ctx->streams[i];
2456                         AVCodecParameters *avpar = st->codecpar;
2457                         switch( avpar->codec_type ) {
2458                         case AVMEDIA_TYPE_VIDEO: {
2459                                 if( st->start_time == AV_NOPTS_VALUE ) continue;
2460                                 int vidx = ffvideo.size();
2461                                 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
2462                                 if( vidx < 0 ) continue;
2463                                 if( ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
2464                                 if( vstart_time < st->start_time )
2465                                         vstart_time = st->start_time;
2466                                 break; }
2467                         case AVMEDIA_TYPE_AUDIO: {
2468                                 if( st->start_time == AV_NOPTS_VALUE ) continue;
2469                                 int aidx = ffaudio.size();
2470                                 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
2471                                 if( aidx < 0 ) continue;
2472                                 if( ffaudio[aidx]->frame_sz < avpar->frame_size )
2473                                         ffaudio[aidx]->frame_sz = avpar->frame_size;
2474                                 if( ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
2475                                 if( astart_time < st->start_time )
2476                                         astart_time = st->start_time;
2477                                 break; }
2478                         default: break;
2479                         }
2480                 }
2481                 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2482                         astart_time > min_nudge ? astart_time : 0;
2483                 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
2484                         if( ffvideo[vidx]->nudge == AV_NOPTS_VALUE )
2485                                 ffvideo[vidx]->nudge = nudge;
2486                 }
2487                 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2488                         if( ffaudio[aidx]->nudge == AV_NOPTS_VALUE )
2489                                 ffaudio[aidx]->nudge = nudge;
2490                 }
2491                 decoding = 1;
2492         }
2493         return decoding;
2494 }
2495
2496 int FFMPEG::encode_activate()
2497 {
2498         int ret = 0;
2499         if( encoding < 0 ) {
2500                 encoding = 0;
2501                 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
2502                     (ret=avio_open(&fmt_ctx->pb, fmt_ctx->url, AVIO_FLAG_WRITE)) < 0 ) {
2503                         ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
2504                                 fmt_ctx->url);
2505                         return -1;
2506                 }
2507
2508                 int prog_id = 1;
2509                 AVProgram *prog = av_new_program(fmt_ctx, prog_id);
2510                 for( int i=0; i< ffvideo.size(); ++i )
2511                         av_program_add_stream_index(fmt_ctx, prog_id, ffvideo[i]->fidx);
2512                 for( int i=0; i< ffaudio.size(); ++i )
2513                         av_program_add_stream_index(fmt_ctx, prog_id, ffaudio[i]->fidx);
2514                 int pi = fmt_ctx->nb_programs;
2515                 while(  --pi >= 0 && fmt_ctx->programs[pi]->id != prog_id );
2516                 AVDictionary **meta = &prog->metadata;
2517                 av_dict_set(meta, "service_provider", "cin5", 0);
2518                 const char *path = fmt_ctx->url, *bp = strrchr(path,'/');
2519                 if( bp ) path = bp + 1;
2520                 av_dict_set(meta, "title", path, 0);
2521
2522                 if( ffaudio.size() ) {
2523                         const char *ep = getenv("CIN_AUDIO_LANG"), *lp = 0;
2524                         if( !ep && (lp=getenv("LANG")) ) { // some are guesses
2525                                 static struct { const char lc[3], lng[4]; } lcode[] = {
2526                                         { "en", "eng" }, { "de", "ger" }, { "es", "spa" },
2527                                         { "eu", "bas" }, { "fr", "fre" }, { "el", "gre" },
2528                                         { "hi", "hin" }, { "it", "ita" }, { "ja", "jap" },
2529                                         { "ko", "kor" }, { "du", "dut" }, { "pl", "pol" },
2530                                         { "pt", "por" }, { "ru", "rus" }, { "sl", "slv" },
2531                                         { "uk", "ukr" }, { "vi", "vie" }, { "zh", "chi" },
2532                                 };
2533                                 for( int i=sizeof(lcode)/sizeof(lcode[0]); --i>=0 && !ep; )
2534                                         if( !strncmp(lcode[i].lc,lp,2) ) ep = lcode[i].lng;
2535                         }
2536                         if( !ep ) ep = "und";
2537                         char lang[5];
2538                         strncpy(lang,ep,3);  lang[3] = 0;
2539                         AVStream *st = ffaudio[0]->st;
2540                         av_dict_set(&st->metadata,"language",lang,0);
2541                 }
2542
2543                 AVDictionary *fopts = 0;
2544                 char option_path[BCTEXTLEN];
2545                 set_option_path(option_path, "format/%s", file_format);
2546                 read_options(option_path, fopts, 1);
2547                 ret = avformat_write_header(fmt_ctx, &fopts);
2548                 if( ret < 0 ) {
2549                         ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
2550                                 fmt_ctx->url);
2551                         return -1;
2552                 }
2553                 av_dict_free(&fopts);
2554                 encoding = 1;
2555         }
2556         return encoding;
2557 }
2558
2559
2560 int FFMPEG::audio_seek(int stream, int64_t pos)
2561 {
2562         int aidx = astrm_index[stream].st_idx;
2563         FFAudioStream *aud = ffaudio[aidx];
2564         aud->audio_seek(pos);
2565         return 0;
2566 }
2567
2568 int FFMPEG::video_seek(int stream, int64_t pos)
2569 {
2570         int vidx = vstrm_index[stream].st_idx;
2571         FFVideoStream *vid = ffvideo[vidx];
2572         vid->video_seek(pos);
2573         return 0;
2574 }
2575
2576
2577 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
2578 {
2579         if( !has_audio || chn >= astrm_index.size() ) return -1;
2580         int aidx = astrm_index[chn].st_idx;
2581         FFAudioStream *aud = ffaudio[aidx];
2582         if( aud->load(pos, len) < len ) return -1;
2583         int ch = astrm_index[chn].st_ch;
2584         int ret = aud->read(samples,len,ch);
2585         return ret;
2586 }
2587
2588 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
2589 {
2590         if( !has_video || layer >= vstrm_index.size() ) return -1;
2591         int vidx = vstrm_index[layer].st_idx;
2592         FFVideoStream *vid = ffvideo[vidx];
2593         return vid->load(vframe, pos);
2594 }
2595
2596
2597 int FFMPEG::encode(int stream, double **samples, int len)
2598 {
2599         FFAudioStream *aud = ffaudio[stream];
2600         return aud->encode(samples, len);
2601 }
2602
2603
2604 int FFMPEG::encode(int stream, VFrame *frame)
2605 {
2606         FFVideoStream *vid = ffvideo[stream];
2607         return vid->encode(frame);
2608 }
2609
2610 void FFMPEG::start_muxer()
2611 {
2612         if( !running() ) {
2613                 done = 0;
2614                 start();
2615         }
2616 }
2617
2618 void FFMPEG::stop_muxer()
2619 {
2620         if( running() ) {
2621                 done = 1;
2622                 mux_lock->unlock();
2623         }
2624         join();
2625 }
2626
2627 void FFMPEG::flow_off()
2628 {
2629         if( !flow ) return;
2630         flow_lock->lock("FFMPEG::flow_off");
2631         flow = 0;
2632 }
2633
2634 void FFMPEG::flow_on()
2635 {
2636         if( flow ) return;
2637         flow = 1;
2638         flow_lock->unlock();
2639 }
2640
2641 void FFMPEG::flow_ctl()
2642 {
2643         while( !flow ) {
2644                 flow_lock->lock("FFMPEG::flow_ctl");
2645                 flow_lock->unlock();
2646         }
2647 }
2648
2649 int FFMPEG::mux_audio(FFrame *frm)
2650 {
2651         FFStream *fst = frm->fst;
2652         AVCodecContext *ctx = fst->avctx;
2653         AVFrame *frame = *frm;
2654         AVRational tick_rate = {1, ctx->sample_rate};
2655         frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
2656         int ret = fst->encode_frame(frame);
2657         if( ret < 0 )
2658                 ff_err(ret, "FFMPEG::mux_audio");
2659         return ret >= 0 ? 0 : 1;
2660 }
2661
2662 int FFMPEG::mux_video(FFrame *frm)
2663 {
2664         FFStream *fst = frm->fst;
2665         AVFrame *frame = *frm;
2666         frame->pts = frm->position;
2667         int ret = fst->encode_frame(frame);
2668         if( ret < 0 )
2669                 ff_err(ret, "FFMPEG::mux_video");
2670         return ret >= 0 ? 0 : 1;
2671 }
2672
2673 void FFMPEG::mux()
2674 {
2675         for(;;) {
2676                 double atm = -1, vtm = -1;
2677                 FFrame *afrm = 0, *vfrm = 0;
2678                 int demand = 0;
2679                 for( int i=0; i<ffaudio.size(); ++i ) {  // earliest audio
2680                         FFStream *fst = ffaudio[i];
2681                         if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
2682                         FFrame *frm = fst->frms.first;
2683                         if( !frm ) { if( !done ) return; continue; }
2684                         double tm = to_secs(frm->position, fst->avctx->time_base);
2685                         if( atm < 0 || tm < atm ) { atm = tm;  afrm = frm; }
2686                 }
2687                 for( int i=0; i<ffvideo.size(); ++i ) {  // earliest video
2688                         FFStream *fst = ffvideo[i];
2689                         if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
2690                         FFrame *frm = fst->frms.first;
2691                         if( !frm ) { if( !done ) return; continue; }
2692                         double tm = to_secs(frm->position, fst->avctx->time_base);
2693                         if( vtm < 0 || tm < vtm ) { vtm = tm;  vfrm = frm; }
2694                 }
2695                 if( !demand ) flow_off();
2696                 if( !afrm && !vfrm ) break;
2697                 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
2698                         vfrm->position, vfrm->fst->avctx->time_base,
2699                         afrm->position, afrm->fst->avctx->time_base);
2700                 FFrame *frm = v <= 0 ? vfrm : afrm;
2701                 if( frm == afrm ) mux_audio(frm);
2702                 if( frm == vfrm ) mux_video(frm);
2703                 frm->dequeue();
2704                 delete frm;
2705         }
2706 }
2707
2708 void FFMPEG::run()
2709 {
2710         while( !done ) {
2711                 mux_lock->lock("FFMPEG::run");
2712                 if( !done ) mux();
2713         }
2714         for( int i=0; i<ffaudio.size(); ++i )
2715                 ffaudio[i]->drain();
2716         for( int i=0; i<ffvideo.size(); ++i )
2717                 ffvideo[i]->drain();
2718         mux();
2719         for( int i=0; i<ffaudio.size(); ++i )
2720                 ffaudio[i]->flush();
2721         for( int i=0; i<ffvideo.size(); ++i )
2722                 ffvideo[i]->flush();
2723 }
2724
2725
2726 int FFMPEG::ff_total_audio_channels()
2727 {
2728         return astrm_index.size();
2729 }
2730
2731 int FFMPEG::ff_total_astreams()
2732 {
2733         return ffaudio.size();
2734 }
2735
2736 int FFMPEG::ff_audio_channels(int stream)
2737 {
2738         return ffaudio[stream]->channels;
2739 }
2740
2741 int FFMPEG::ff_sample_rate(int stream)
2742 {
2743         return ffaudio[stream]->sample_rate;
2744 }
2745
2746 const char* FFMPEG::ff_audio_format(int stream)
2747 {
2748         AVStream *st = ffaudio[stream]->st;
2749         AVCodecID id = st->codecpar->codec_id;
2750         const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2751         return desc ? desc->name : _("Unknown");
2752 }
2753
2754 int FFMPEG::ff_audio_pid(int stream)
2755 {
2756         return ffaudio[stream]->st->id;
2757 }
2758
2759 int64_t FFMPEG::ff_audio_samples(int stream)
2760 {
2761         return ffaudio[stream]->length;
2762 }
2763
2764 // find audio astream/channels with this program,
2765 //   or all program audio channels (astream=-1)
2766 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
2767 {
2768         channel_mask = 0;
2769         int pidx = -1;
2770         int vidx = ffvideo[vstream]->fidx;
2771         // find first program with this video stream
2772         for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
2773                 AVProgram *pgrm = fmt_ctx->programs[i];
2774                 for( int j=0;  pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
2775                         int st_idx = pgrm->stream_index[j];
2776                         AVStream *st = fmt_ctx->streams[st_idx];
2777                         if( st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
2778                         if( st_idx == vidx ) pidx = i;
2779                 }
2780         }
2781         if( pidx < 0 ) return -1;
2782         int ret = -1;
2783         int64_t channels = 0;
2784         AVProgram *pgrm = fmt_ctx->programs[pidx];
2785         for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2786                 int aidx = pgrm->stream_index[j];
2787                 AVStream *st = fmt_ctx->streams[aidx];
2788                 if( st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
2789                 if( astream > 0 ) { --astream;  continue; }
2790                 int astrm = -1;
2791                 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
2792                         if( ffaudio[i]->fidx == aidx ) astrm = i;
2793                 if( astrm >= 0 ) {
2794                         if( ret < 0 ) ret = astrm;
2795                         int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
2796                         channels |= mask << ffaudio[astrm]->channel0;
2797                 }
2798                 if( !astream ) break;
2799         }
2800         channel_mask = channels;
2801         return ret;
2802 }
2803
2804
2805 int FFMPEG::ff_total_video_layers()
2806 {
2807         return vstrm_index.size();
2808 }
2809
2810 int FFMPEG::ff_total_vstreams()
2811 {
2812         return ffvideo.size();
2813 }
2814
2815 int FFMPEG::ff_video_width(int stream)
2816 {
2817         return ffvideo[stream]->width;
2818 }
2819
2820 int FFMPEG::ff_video_height(int stream)
2821 {
2822         return ffvideo[stream]->height;
2823 }
2824
2825 int FFMPEG::ff_set_video_width(int stream, int width)
2826 {
2827         int w = ffvideo[stream]->width;
2828         ffvideo[stream]->width = width;
2829         return w;
2830 }
2831
2832 int FFMPEG::ff_set_video_height(int stream, int height)
2833 {
2834         int h = ffvideo[stream]->height;
2835         ffvideo[stream]->height = height;
2836         return h;
2837 }
2838
2839 int FFMPEG::ff_coded_width(int stream)
2840 {
2841         return ffvideo[stream]->avctx->coded_width;
2842 }
2843
2844 int FFMPEG::ff_coded_height(int stream)
2845 {
2846         return ffvideo[stream]->avctx->coded_height;
2847 }
2848
2849 float FFMPEG::ff_aspect_ratio(int stream)
2850 {
2851         return ffvideo[stream]->aspect_ratio;
2852 }
2853
2854 const char* FFMPEG::ff_video_format(int stream)
2855 {
2856         AVStream *st = ffvideo[stream]->st;
2857         AVCodecID id = st->codecpar->codec_id;
2858         const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2859         return desc ? desc->name : _("Unknown");
2860 }
2861
2862 double FFMPEG::ff_frame_rate(int stream)
2863 {
2864         return ffvideo[stream]->frame_rate;
2865 }
2866
2867 int64_t FFMPEG::ff_video_frames(int stream)
2868 {
2869         return ffvideo[stream]->length;
2870 }
2871
2872 int FFMPEG::ff_video_pid(int stream)
2873 {
2874         return ffvideo[stream]->st->id;
2875 }
2876
2877 int FFMPEG::ff_video_mpeg_color_range(int stream)
2878 {
2879         return ffvideo[stream]->st->codecpar->color_range == AVCOL_RANGE_MPEG ? 1 : 0;
2880 }
2881
2882 int FFMPEG::ff_cpus()
2883 {
2884         return file_base->file->cpus;
2885 }
2886
2887 int FFVideoStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
2888 {
2889         avfilter_register_all();
2890         const char *sp = filter_spec;
2891         char filter_name[BCSTRLEN], *np = filter_name;
2892         int i = sizeof(filter_name);
2893         while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
2894         *np = 0;
2895         const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
2896         if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_VIDEO ) {
2897                 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
2898                 return -1;
2899         }
2900         filter_graph = avfilter_graph_alloc();
2901         const AVFilter *buffersrc = avfilter_get_by_name("buffer");
2902         const AVFilter *buffersink = avfilter_get_by_name("buffersink");
2903
2904         int ret = 0;  char args[BCTEXTLEN];
2905         AVPixelFormat pix_fmt = (AVPixelFormat)avpar->format;
2906         snprintf(args, sizeof(args),
2907                 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
2908                 avpar->width, avpar->height, (int)pix_fmt,
2909                 st->time_base.num, st->time_base.den,
2910                 avpar->sample_aspect_ratio.num, avpar->sample_aspect_ratio.den);
2911         if( ret >= 0 )
2912                 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2913                         args, NULL, filter_graph);
2914         if( ret >= 0 )
2915                 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2916                         NULL, NULL, filter_graph);
2917         if( ret >= 0 )
2918                 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
2919                         (uint8_t*)&pix_fmt, sizeof(pix_fmt),
2920                         AV_OPT_SEARCH_CHILDREN);
2921         if( ret < 0 )
2922                 ff_err(ret, "FFVideoStream::create_filter");
2923         else
2924                 ret = FFStream::create_filter(filter_spec);
2925         return ret >= 0 ? 0 : -1;
2926 }
2927
2928 int FFAudioStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
2929 {
2930         avfilter_register_all();
2931         const char *sp = filter_spec;
2932         char filter_name[BCSTRLEN], *np = filter_name;
2933         int i = sizeof(filter_name);
2934         while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
2935         *np = 0;
2936         const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
2937         if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_AUDIO ) {
2938                 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
2939                 return -1;
2940         }
2941         filter_graph = avfilter_graph_alloc();
2942         const AVFilter *buffersrc = avfilter_get_by_name("abuffer");
2943         const AVFilter *buffersink = avfilter_get_by_name("abuffersink");
2944         int ret = 0;  char args[BCTEXTLEN];
2945         AVSampleFormat sample_fmt = (AVSampleFormat)avpar->format;
2946         snprintf(args, sizeof(args),
2947                 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
2948                 st->time_base.num, st->time_base.den, avpar->sample_rate,
2949                 av_get_sample_fmt_name(sample_fmt), avpar->channel_layout);
2950         if( ret >= 0 )
2951                 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2952                         args, NULL, filter_graph);
2953         if( ret >= 0 )
2954                 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2955                         NULL, NULL, filter_graph);
2956         if( ret >= 0 )
2957                 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
2958                         (uint8_t*)&sample_fmt, sizeof(sample_fmt),
2959                         AV_OPT_SEARCH_CHILDREN);
2960         if( ret >= 0 )
2961                 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
2962                         (uint8_t*)&avpar->channel_layout,
2963                         sizeof(avpar->channel_layout), AV_OPT_SEARCH_CHILDREN);
2964         if( ret >= 0 )
2965                 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
2966                         (uint8_t*)&sample_rate, sizeof(sample_rate),
2967                         AV_OPT_SEARCH_CHILDREN);
2968         if( ret < 0 )
2969                 ff_err(ret, "FFAudioStream::create_filter");
2970         else
2971                 ret = FFStream::create_filter(filter_spec);
2972         return ret >= 0 ? 0 : -1;
2973 }
2974
2975 int FFStream::create_filter(const char *filter_spec)
2976 {
2977         /* Endpoints for the filter graph. */
2978         AVFilterInOut *outputs = avfilter_inout_alloc();
2979         outputs->name = av_strdup("in");
2980         outputs->filter_ctx = buffersrc_ctx;
2981         outputs->pad_idx = 0;
2982         outputs->next = 0;
2983
2984         AVFilterInOut *inputs  = avfilter_inout_alloc();
2985         inputs->name = av_strdup("out");
2986         inputs->filter_ctx = buffersink_ctx;
2987         inputs->pad_idx = 0;
2988         inputs->next = 0;
2989
2990         int ret = !outputs->name || !inputs->name ? -1 : 0;
2991         if( ret >= 0 )
2992                 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
2993                         &inputs, &outputs, NULL);
2994         if( ret >= 0 )
2995                 ret = avfilter_graph_config(filter_graph, NULL);
2996
2997         if( ret < 0 ) {
2998                 ff_err(ret, "FFStream::create_filter");
2999                 avfilter_graph_free(&filter_graph);
3000                 filter_graph = 0;
3001         }
3002         avfilter_inout_free(&inputs);
3003         avfilter_inout_free(&outputs);
3004         return ret;
3005 }
3006
3007 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
3008 {
3009         AVPacket pkt;
3010         av_init_packet(&pkt);
3011         AVFrame *frame = av_frame_alloc();
3012         if( !frame ) {
3013                 fprintf(stderr,"FFMPEG::scan: ");
3014                 fprintf(stderr,_("av_frame_alloc failed\n"));
3015                 fprintf(stderr,"FFMPEG::scan:file=%s\n", file_base->asset->path);
3016                 return -1;
3017         }
3018
3019         index_state->add_video_markers(ffvideo.size());
3020         index_state->add_audio_markers(ffaudio.size());
3021
3022         for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
3023                 int ret = 0;
3024                 AVDictionary *copts = 0;
3025                 av_dict_copy(&copts, opts, 0);
3026                 AVStream *st = fmt_ctx->streams[i];
3027                 AVCodecID codec_id = st->codecpar->codec_id;
3028                 AVCodec *decoder = avcodec_find_decoder(codec_id);
3029                 AVCodecContext *avctx = avcodec_alloc_context3(decoder);
3030                 if( !avctx ) {
3031                         eprintf(_("cant allocate codec context\n"));
3032                         ret = AVERROR(ENOMEM);
3033                 }
3034                 if( ret >= 0 ) {
3035                         avcodec_parameters_to_context(avctx, st->codecpar);
3036                         if( !av_dict_get(copts, "threads", NULL, 0) )
3037                                 avctx->thread_count = ff_cpus();
3038                         ret = avcodec_open2(avctx, decoder, &copts);
3039                 }
3040                 av_dict_free(&copts);
3041                 if( ret >= 0 ) {
3042                         AVCodecParameters *avpar = st->codecpar;
3043                         switch( avpar->codec_type ) {
3044                         case AVMEDIA_TYPE_VIDEO: {
3045                                 int vidx = ffvideo.size();
3046                                 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
3047                                 if( vidx < 0 ) break;
3048                                 ffvideo[vidx]->avctx = avctx;
3049                                 continue; }
3050                         case AVMEDIA_TYPE_AUDIO: {
3051                                 int aidx = ffaudio.size();
3052                                 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3053                                 if( aidx < 0 ) break;
3054                                 ffaudio[aidx]->avctx = avctx;
3055                                 continue; }
3056                         default: break;
3057                         }
3058                 }