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