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