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