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