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