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