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