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