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