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