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