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