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