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