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