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