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