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