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