add hw_dev preference, opts file var, tweak hw GPU xfer err msg
[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 "preferences.h"
37 #include "vframe.h"
38
39 #ifdef FFMPEG3
40 #define url filename
41 #else
42 #define av_register_all(s)
43 #define avfilter_register_all(s)
44 #endif
45
46 #define VIDEO_INBUF_SIZE 0x10000
47 #define AUDIO_INBUF_SIZE 0x10000
48 #define VIDEO_REFILL_THRESH 0
49 #define AUDIO_REFILL_THRESH 0x1000
50 #define AUDIO_MIN_FRAME_SZ 128
51
52 #define FF_ESTM_TIMES 0x0001
53 #define FF_BAD_TIMES  0x0002
54
55 Mutex FFMPEG::fflock("FFMPEG::fflock");
56
57 static void ff_err(int ret, const char *fmt, ...)
58 {
59         char msg[BCTEXTLEN];
60         va_list ap;
61         va_start(ap, fmt);
62         vsnprintf(msg, sizeof(msg), fmt, ap);
63         va_end(ap);
64         char errmsg[BCSTRLEN];
65         av_strerror(ret, errmsg, sizeof(errmsg));
66         fprintf(stderr,_("%s  err: %s\n"),msg, errmsg);
67 }
68
69 void FFPacket::init()
70 {
71         av_init_packet(&pkt);
72         pkt.data = 0; pkt.size = 0;
73 }
74 void FFPacket::finit()
75 {
76         av_packet_unref(&pkt);
77 }
78
79 FFrame::FFrame(FFStream *fst)
80 {
81         this->fst = fst;
82         frm = av_frame_alloc();
83         init = fst->init_frame(frm);
84 }
85
86 FFrame::~FFrame()
87 {
88         av_frame_free(&frm);
89 }
90
91 void FFrame::queue(int64_t pos)
92 {
93         position = pos;
94         fst->queue(this);
95 }
96
97 void FFrame::dequeue()
98 {
99         fst->dequeue(this);
100 }
101
102 int FFAudioStream::read(float *fp, long len)
103 {
104         long n = len * nch;
105         float *op = outp;
106         while( n > 0 ) {
107                 int k = lmt - op;
108                 if( k > n ) k = n;
109                 n -= k;
110                 while( --k >= 0 ) *fp++ = *op++;
111                 if( op >= lmt ) op = bfr;
112         }
113         return len;
114 }
115
116 void FFAudioStream::realloc(long nsz, int nch, long len)
117 {
118         long bsz = nsz * nch;
119         float *np = new float[bsz];
120         inp = np + read(np, len) * nch;
121         outp = np;
122         lmt = np + bsz;
123         this->nch = nch;
124         sz = nsz;
125         delete [] bfr;  bfr = np;
126 }
127
128 void FFAudioStream::realloc(long nsz, int nch)
129 {
130         if( nsz > sz || this->nch != nch ) {
131                 long len = this->nch != nch ? 0 : hpos;
132                 if( len > sz ) len = sz;
133                 iseek(len);
134                 realloc(nsz, nch, len);
135         }
136 }
137
138 void FFAudioStream::reserve(long nsz, int nch)
139 {
140         long len = (inp - outp) / nch;
141         nsz += len;
142         if( nsz > sz || this->nch != nch ) {
143                 if( this->nch != nch ) len = 0;
144                 realloc(nsz, nch, len);
145                 return;
146         }
147         if( (len*=nch) > 0 && bfr != outp )
148                 memmove(bfr, outp, len*sizeof(*bfr));
149         outp = bfr;
150         inp = bfr + len;
151 }
152
153 long FFAudioStream::used()
154 {
155         long len = inp>=outp ? inp-outp : inp-bfr + lmt-outp;
156         return len / nch;
157 }
158 long FFAudioStream::avail()
159 {
160         float *in1 = inp+1;
161         if( in1 >= lmt ) in1 = bfr;
162         long len = outp >= in1 ? outp-in1 : outp-bfr + lmt-in1;
163         return len / nch;
164 }
165 void FFAudioStream::reset_history()
166 {
167         inp = outp = bfr;
168         hpos = 0;
169         memset(bfr, 0, lmt-bfr);
170 }
171
172 void FFAudioStream::iseek(int64_t ofs)
173 {
174         if( ofs > hpos ) ofs = hpos;
175         if( ofs > sz ) ofs = sz;
176         outp = inp - ofs*nch;
177         if( outp < bfr ) outp += sz*nch;
178 }
179
180 float *FFAudioStream::get_outp(int ofs)
181 {
182         float *ret = outp;
183         outp += ofs*nch;
184         return ret;
185 }
186
187 int64_t FFAudioStream::put_inp(int ofs)
188 {
189         inp += ofs*nch;
190         return (inp-outp) / nch;
191 }
192
193 int FFAudioStream::write(const float *fp, long len)
194 {
195         long n = len * nch;
196         float *ip = inp;
197         while( n > 0 ) {
198                 int k = lmt - ip;
199                 if( k > n ) k = n;
200                 n -= k;
201                 while( --k >= 0 ) *ip++ = *fp++;
202                 if( ip >= lmt ) ip = bfr;
203         }
204         inp = ip;
205         hpos += len;
206         return len;
207 }
208
209 int FFAudioStream::zero(long len)
210 {
211         long n = len * nch;
212         float *ip = inp;
213         while( n > 0 ) {
214                 int k = lmt - ip;
215                 if( k > n ) k = n;
216                 n -= k;
217                 while( --k >= 0 ) *ip++ = 0;
218                 if( ip >= lmt ) ip = bfr;
219         }
220         inp = ip;
221         hpos += len;
222         return len;
223 }
224
225 // does not advance outp
226 int FFAudioStream::read(double *dp, long len, int ch)
227 {
228         long n = len;
229         float *op = outp + ch;
230         float *lmt1 = lmt + nch-1;
231         while( n > 0 ) {
232                 int k = (lmt1 - op) / nch;
233                 if( k > n ) k = n;
234                 n -= k;
235                 while( --k >= 0 ) { *dp++ = *op;  op += nch; }
236                 if( op >= lmt ) op -= sz*nch;
237         }
238         return len;
239 }
240
241 // load linear buffer, no wrapping allowed, does not advance inp
242 int FFAudioStream::write(const double *dp, long len, int ch)
243 {
244         long n = len;
245         float *ip = inp + ch;
246         while( --n >= 0 ) { *ip = *dp++;  ip += nch; }
247         return len;
248 }
249
250
251 FFStream::FFStream(FFMPEG *ffmpeg, AVStream *st, int fidx)
252 {
253         this->ffmpeg = ffmpeg;
254         this->st = st;
255         this->fidx = fidx;
256         frm_lock = new Mutex("FFStream::frm_lock");
257         fmt_ctx = 0;
258         avctx = 0;
259         filter_graph = 0;
260         buffersrc_ctx = 0;
261         buffersink_ctx = 0;
262         frm_count = 0;
263         nudge = AV_NOPTS_VALUE;
264         seek_pos = curr_pos = 0;
265         seeked = 1;  eof = 0;
266         reading = writing = 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 = ffmpeg->opt_hw_dev;
1005         if( !hw_dev ) hw_dev = getenv("CIN_HW_DEV");
1006         if( !hw_dev ) hw_dev = ffmpeg->ff_hw_dev();
1007         if( hw_dev && *hw_dev && strcmp(_("none"), hw_dev) ) {
1008                 type = av_hwdevice_find_type_by_name(hw_dev);
1009                 if( type == AV_HWDEVICE_TYPE_NONE ) {
1010                         fprintf(stderr, "Device type %s is not supported.\n", hw_dev);
1011                         fprintf(stderr, "Available device types:");
1012                         while( (type = av_hwdevice_iterate_types(type)) != AV_HWDEVICE_TYPE_NONE )
1013                                 fprintf(stderr, " %s", av_hwdevice_get_type_name(type));
1014                         fprintf(stderr, "\n");
1015                 }
1016         }
1017         return type;
1018 }
1019
1020 void FFVideoStream::decode_hw_format(AVCodec *decoder, AVHWDeviceType type)
1021 {
1022         hw_pix_fmt = AV_PIX_FMT_NONE;
1023         for( int i=0; ; ++i ) {
1024                 const AVCodecHWConfig *config = avcodec_get_hw_config(decoder, i);
1025                 if( !config ) {
1026                         fprintf(stderr, "Decoder %s does not support device type %s.\n",
1027                                 decoder->name, av_hwdevice_get_type_name(type));
1028                         break;
1029                 }
1030                 if( (config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX) != 0 &&
1031                     config->device_type == type ) {
1032                         hw_pix_fmt = config->pix_fmt;
1033                         break;
1034                 }
1035         }
1036         if( hw_pix_fmt >= 0 ) {
1037                 hw_pixfmt = hw_pix_fmt;
1038                 avctx->get_format  = get_hw_format;
1039                 int ret = av_hwdevice_ctx_create(&hw_device_ctx, type, 0, 0, 0);
1040                 if( ret >= 0 )
1041                         avctx->hw_device_ctx = av_buffer_ref(hw_device_ctx);
1042                 else
1043                         ff_err(ret, "Failed HW device create.\ndev:%s\n",
1044                                 av_hwdevice_get_type_name(type));
1045         }
1046 }
1047
1048 int FFVideoStream::decode_frame(AVFrame *frame)
1049 {
1050         int first_frame = seeked;  seeked = 0;
1051         int ret = avcodec_receive_frame(avctx, frame);
1052         if( ret < 0 ) {
1053                 if( first_frame || ret == AVERROR(EAGAIN) ) return 0;
1054                 if( ret == AVERROR(EAGAIN) ) return 0;
1055                 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
1056                 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame.\nfile:%s\n,",
1057                                 ffmpeg->fmt_ctx->url);
1058                 return -1;
1059         }
1060         int64_t pkt_ts = frame->best_effort_timestamp;
1061         if( pkt_ts != AV_NOPTS_VALUE )
1062                 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * frame_rate + 0.5;
1063         return 1;
1064 }
1065
1066 int FFVideoStream::load(VFrame *vframe, int64_t pos)
1067 {
1068         int ret = video_seek(pos);
1069         if( ret < 0 ) return -1;
1070         if( !frame && !(frame=av_frame_alloc()) ) {
1071                 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
1072                 return -1;
1073         }
1074         int i = MAX_RETRY + pos - curr_pos;
1075         while( ret>=0 && !flushed && curr_pos<=pos && --i>=0 ) {
1076                 ret = read_frame(frame);
1077                 if( ret > 0 ) ++curr_pos;
1078         }
1079         if( frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0 )
1080                 ret = -1;
1081         if( ret >= 0 ) {
1082                 ret = convert_cmodel(vframe, frame);
1083         }
1084         ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
1085         return ret;
1086 }
1087
1088 int FFVideoStream::video_seek(int64_t pos)
1089 {
1090         if( decode_activate() <= 0 ) return -1;
1091         if( !st->codecpar ) return -1;
1092         if( pos == curr_pos-1 && !seeked ) return 0;
1093 // if close enough, just read up to current
1094         int gop = avctx->gop_size;
1095         if( gop < 4 ) gop = 4;
1096         if( gop > 64 ) gop = 64;
1097         int read_limit = curr_pos + 3*gop;
1098         if( pos >= curr_pos && pos <= read_limit ) return 0;
1099 // guarentee preload more than 2*gop frames
1100         if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
1101         return 1;
1102 }
1103
1104 int FFVideoStream::init_frame(AVFrame *picture)
1105 {
1106         picture->format = avctx->pix_fmt;
1107         picture->width  = avctx->width;
1108         picture->height = avctx->height;
1109         int ret = av_frame_get_buffer(picture, 32);
1110         return ret;
1111 }
1112
1113 int FFVideoStream::encode(VFrame *vframe)
1114 {
1115         if( encode_activate() <= 0 ) return -1;
1116         ffmpeg->flow_ctl();
1117         FFrame *picture = new FFrame(this);
1118         int ret = picture->initted();
1119         if( ret >= 0 ) {
1120                 AVFrame *frame = *picture;
1121                 frame->pts = curr_pos;
1122                 ret = convert_pixfmt(vframe, frame);
1123         }
1124         if( ret >= 0 ) {
1125                 picture->queue(curr_pos);
1126                 ++curr_pos;
1127         }
1128         else {
1129                 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
1130                 delete picture;
1131         }
1132         return ret >= 0 ? 0 : 1;
1133 }
1134
1135 int FFVideoStream::drain()
1136 {
1137         return 0;
1138 }
1139
1140 int FFVideoStream::encode_frame(AVFrame *frame)
1141 {
1142         if( frame ) {
1143                 frame->interlaced_frame = interlaced;
1144                 frame->top_field_first = top_field_first;
1145         }
1146         return FFStream::encode_frame(frame);
1147 }
1148
1149 int FFVideoStream::write_packet(FFPacket &pkt)
1150 {
1151         if( !(ffmpeg->fmt_ctx->oformat->flags & AVFMT_VARIABLE_FPS) )
1152                 pkt->duration = 1;
1153         return FFStream::write_packet(pkt);
1154 }
1155
1156 AVPixelFormat FFVideoConvert::color_model_to_pix_fmt(int color_model)
1157 {
1158         switch( color_model ) {
1159         case BC_YUV422:         return AV_PIX_FMT_YUYV422;
1160         case BC_RGB888:         return AV_PIX_FMT_RGB24;
1161         case BC_RGBA8888:       return AV_PIX_FMT_RGBA;
1162         case BC_BGR8888:        return AV_PIX_FMT_BGR0;
1163         case BC_BGR888:         return AV_PIX_FMT_BGR24;
1164         case BC_ARGB8888:       return AV_PIX_FMT_ARGB;
1165         case BC_ABGR8888:       return AV_PIX_FMT_ABGR;
1166         case BC_RGB8:           return AV_PIX_FMT_RGB8;
1167         case BC_YUV420P:        return AV_PIX_FMT_YUV420P;
1168         case BC_YUV422P:        return AV_PIX_FMT_YUV422P;
1169         case BC_YUV444P:        return AV_PIX_FMT_YUV444P;
1170         case BC_YUV411P:        return AV_PIX_FMT_YUV411P;
1171         case BC_RGB565:         return AV_PIX_FMT_RGB565;
1172         case BC_RGB161616:      return AV_PIX_FMT_RGB48LE;
1173         case BC_RGBA16161616:   return AV_PIX_FMT_RGBA64LE;
1174         case BC_AYUV16161616:   return AV_PIX_FMT_AYUV64LE;
1175         case BC_GBRP:           return AV_PIX_FMT_GBRP;
1176         default: break;
1177         }
1178
1179         return AV_PIX_FMT_NB;
1180 }
1181
1182 int FFVideoConvert::pix_fmt_to_color_model(AVPixelFormat pix_fmt)
1183 {
1184         switch (pix_fmt) {
1185         case AV_PIX_FMT_YUYV422:        return BC_YUV422;
1186         case AV_PIX_FMT_RGB24:          return BC_RGB888;
1187         case AV_PIX_FMT_RGBA:           return BC_RGBA8888;
1188         case AV_PIX_FMT_BGR0:           return BC_BGR8888;
1189         case AV_PIX_FMT_BGR24:          return BC_BGR888;
1190         case AV_PIX_FMT_ARGB:           return BC_ARGB8888;
1191         case AV_PIX_FMT_ABGR:           return BC_ABGR8888;
1192         case AV_PIX_FMT_RGB8:           return BC_RGB8;
1193         case AV_PIX_FMT_YUV420P:        return BC_YUV420P;
1194         case AV_PIX_FMT_YUV422P:        return BC_YUV422P;
1195         case AV_PIX_FMT_YUV444P:        return BC_YUV444P;
1196         case AV_PIX_FMT_YUV411P:        return BC_YUV411P;
1197         case AV_PIX_FMT_RGB565:         return BC_RGB565;
1198         case AV_PIX_FMT_RGB48LE:        return BC_RGB161616;
1199         case AV_PIX_FMT_RGBA64LE:       return BC_RGBA16161616;
1200         case AV_PIX_FMT_AYUV64LE:       return BC_AYUV16161616;
1201         case AV_PIX_FMT_GBRP:           return BC_GBRP;
1202         default: break;
1203         }
1204
1205         return -1;
1206 }
1207
1208 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip)
1209 {
1210         AVFrame *ipic = av_frame_alloc();
1211         int ret = convert_picture_vframe(frame, ip, ipic);
1212         av_frame_free(&ipic);
1213         return ret;
1214 }
1215
1216 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip, AVFrame *ipic)
1217 {
1218         int cmodel = frame->get_color_model();
1219         AVPixelFormat ofmt = color_model_to_pix_fmt(cmodel);
1220         if( ofmt == AV_PIX_FMT_NB ) return -1;
1221         int size = av_image_fill_arrays(ipic->data, ipic->linesize,
1222                 frame->get_data(), ofmt, frame->get_w(), frame->get_h(), 1);
1223         if( size < 0 ) return -1;
1224
1225         int bpp = BC_CModels::calculate_pixelsize(cmodel);
1226         int ysz = bpp * frame->get_w(), usz = ysz;
1227         switch( cmodel ) {
1228         case BC_YUV410P:
1229         case BC_YUV411P:
1230                 usz /= 2;
1231         case BC_YUV420P:
1232         case BC_YUV422P:
1233                 usz /= 2;
1234         case BC_YUV444P:
1235         case BC_GBRP:
1236                 // override av_image_fill_arrays() for planar types
1237                 ipic->data[0] = frame->get_y();  ipic->linesize[0] = ysz;
1238                 ipic->data[1] = frame->get_u();  ipic->linesize[1] = usz;
1239                 ipic->data[2] = frame->get_v();  ipic->linesize[2] = usz;
1240                 break;
1241         default:
1242                 ipic->data[0] = frame->get_data();
1243                 ipic->linesize[0] = frame->get_bytes_per_line();
1244                 break;
1245         }
1246
1247         AVPixelFormat pix_fmt = (AVPixelFormat)ip->format;
1248         FFVideoStream *vid =(FFVideoStream *)this;
1249         if( pix_fmt == vid->hw_pixfmt ) {
1250                 int ret = 0;
1251                 if( !sw_frame && !(sw_frame=av_frame_alloc()) )
1252                         ret = AVERROR(ENOMEM);
1253                 if( !ret ) {
1254                         ret = av_hwframe_transfer_data(sw_frame, ip, 0);
1255                         ip = sw_frame;
1256                         pix_fmt = (AVPixelFormat)ip->format;
1257                 }
1258                 if( ret < 0 ) {
1259                         eprintf(_("Error retrieving data from GPU to CPU\nfile: %s\n"),
1260                                 vid->ffmpeg->fmt_ctx->url);
1261                         return -1;
1262                 }
1263         }
1264         convert_ctx = sws_getCachedContext(convert_ctx, ip->width, ip->height, pix_fmt,
1265                 frame->get_w(), frame->get_h(), ofmt, SWS_POINT, NULL, NULL, NULL);
1266         if( !convert_ctx ) {
1267                 fprintf(stderr, "FFVideoConvert::convert_picture_frame:"
1268                                 " sws_getCachedContext() failed\n");
1269                 return -1;
1270         }
1271         int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ip->height,
1272             ipic->data, ipic->linesize);
1273         if( ret < 0 ) {
1274                 ff_err(ret, "FFVideoConvert::convert_picture_frame: sws_scale() failed\nfile: %s\n",
1275                         vid->ffmpeg->fmt_ctx->url);
1276                 return -1;
1277         }
1278         return 0;
1279 }
1280
1281 int FFVideoConvert::convert_cmodel(VFrame *frame, AVFrame *ip)
1282 {
1283         // try direct transfer
1284         if( !convert_picture_vframe(frame, ip) ) return 1;
1285         // use indirect transfer
1286         AVPixelFormat ifmt = (AVPixelFormat)ip->format;
1287         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
1288         int max_bits = 0;
1289         for( int i = 0; i <desc->nb_components; ++i ) {
1290                 int bits = desc->comp[i].depth;
1291                 if( bits > max_bits ) max_bits = bits;
1292         }
1293         int imodel = pix_fmt_to_color_model(ifmt);
1294         int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1295         int cmodel = frame->get_color_model();
1296         int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1297         if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1298                 imodel = cmodel_is_yuv ?
1299                     (BC_CModels::has_alpha(cmodel) ?
1300                         BC_AYUV16161616 :
1301                         (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1302                     (BC_CModels::has_alpha(cmodel) ?
1303                         (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1304                         (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1305         }
1306         VFrame vframe(ip->width, ip->height, imodel);
1307         if( convert_picture_vframe(&vframe, ip) ) return -1;
1308         frame->transfer_from(&vframe);
1309         return 1;
1310 }
1311
1312 int FFVideoConvert::transfer_cmodel(VFrame *frame, AVFrame *ifp)
1313 {
1314         int ret = convert_cmodel(frame, ifp);
1315         if( ret > 0 ) {
1316                 const AVDictionary *src = ifp->metadata;
1317                 AVDictionaryEntry *t = NULL;
1318                 BC_Hash *hp = frame->get_params();
1319                 //hp->clear();
1320                 while( (t=av_dict_get(src, "", t, AV_DICT_IGNORE_SUFFIX)) )
1321                         hp->update(t->key, t->value);
1322         }
1323         return ret;
1324 }
1325
1326 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op)
1327 {
1328         AVFrame *opic = av_frame_alloc();
1329         int ret = convert_vframe_picture(frame, op, opic);
1330         av_frame_free(&opic);
1331         return ret;
1332 }
1333
1334 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op, AVFrame *opic)
1335 {
1336         int cmodel = frame->get_color_model();
1337         AVPixelFormat ifmt = color_model_to_pix_fmt(cmodel);
1338         if( ifmt == AV_PIX_FMT_NB ) return -1;
1339         int size = av_image_fill_arrays(opic->data, opic->linesize,
1340                  frame->get_data(), ifmt, frame->get_w(), frame->get_h(), 1);
1341         if( size < 0 ) return -1;
1342
1343         int bpp = BC_CModels::calculate_pixelsize(cmodel);
1344         int ysz = bpp * frame->get_w(), usz = ysz;
1345         switch( cmodel ) {
1346         case BC_YUV410P:
1347         case BC_YUV411P:
1348                 usz /= 2;
1349         case BC_YUV420P:
1350         case BC_YUV422P:
1351                 usz /= 2;
1352         case BC_YUV444P:
1353         case BC_GBRP:
1354                 // override av_image_fill_arrays() for planar types
1355                 opic->data[0] = frame->get_y();  opic->linesize[0] = ysz;
1356                 opic->data[1] = frame->get_u();  opic->linesize[1] = usz;
1357                 opic->data[2] = frame->get_v();  opic->linesize[2] = usz;
1358                 break;
1359         default:
1360                 opic->data[0] = frame->get_data();
1361                 opic->linesize[0] = frame->get_bytes_per_line();
1362                 break;
1363         }
1364
1365         AVPixelFormat ofmt = (AVPixelFormat)op->format;
1366         convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(),
1367                 ifmt, op->width, op->height, ofmt, SWS_POINT, NULL, NULL, NULL);
1368         if( !convert_ctx ) {
1369                 fprintf(stderr, "FFVideoConvert::convert_frame_picture:"
1370                                 " sws_getCachedContext() failed\n");
1371                 return -1;
1372         }
1373         int ret = sws_scale(convert_ctx, opic->data, opic->linesize, 0, frame->get_h(),
1374                         op->data, op->linesize);
1375         if( ret < 0 ) {
1376                 ff_err(ret, "FFVideoConvert::convert_frame_picture: sws_scale() failed\n");
1377                 return -1;
1378         }
1379         return 0;
1380 }
1381
1382 int FFVideoConvert::convert_pixfmt(VFrame *frame, AVFrame *op)
1383 {
1384         // try direct transfer
1385         if( !convert_vframe_picture(frame, op) ) return 1;
1386         // use indirect transfer
1387         int cmodel = frame->get_color_model();
1388         int max_bits = BC_CModels::calculate_pixelsize(cmodel) * 8;
1389         max_bits /= BC_CModels::components(cmodel);
1390         AVPixelFormat ofmt = (AVPixelFormat)op->format;
1391         int imodel = pix_fmt_to_color_model(ofmt);
1392         int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1393         int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1394         if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1395                 imodel = cmodel_is_yuv ?
1396                     (BC_CModels::has_alpha(cmodel) ?
1397                         BC_AYUV16161616 :
1398                         (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1399                     (BC_CModels::has_alpha(cmodel) ?
1400                         (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1401                         (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1402         }
1403         VFrame vframe(frame->get_w(), frame->get_h(), imodel);
1404         vframe.transfer_from(frame);
1405         if( !convert_vframe_picture(&vframe, op) ) return 1;
1406         return -1;
1407 }
1408
1409 int FFVideoConvert::transfer_pixfmt(VFrame *frame, AVFrame *ofp)
1410 {
1411         int ret = convert_pixfmt(frame, ofp);
1412         if( ret > 0 ) {
1413                 BC_Hash *hp = frame->get_params();
1414                 AVDictionary **dict = &ofp->metadata;
1415                 //av_dict_free(dict);
1416                 for( int i=0; i<hp->size(); ++i ) {
1417                         char *key = hp->get_key(i), *val = hp->get_value(i);
1418                         av_dict_set(dict, key, val, 0);
1419                 }
1420         }
1421         return ret;
1422 }
1423
1424 void FFVideoStream::load_markers()
1425 {
1426         IndexState *index_state = ffmpeg->file_base->asset->index_state;
1427         if( !index_state || idx >= index_state->video_markers.size() ) return;
1428         FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
1429 }
1430
1431 IndexMarks *FFVideoStream::get_markers()
1432 {
1433         IndexState *index_state = ffmpeg->file_base->asset->index_state;
1434         if( !index_state || idx >= index_state->video_markers.size() ) return 0;
1435         return !index_state ? 0 : index_state->video_markers[idx];
1436 }
1437
1438
1439 FFMPEG::FFMPEG(FileBase *file_base)
1440 {
1441         fmt_ctx = 0;
1442         this->file_base = file_base;
1443         memset(file_format,0,sizeof(file_format));
1444         mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
1445         flow_lock = new Condition(1,"FFStream::flow_lock",0);
1446         done = -1;
1447         flow = 1;
1448         decoding = encoding = 0;
1449         has_audio = has_video = 0;
1450         opts = 0;
1451         opt_duration = -1;
1452         opt_video_filter = 0;
1453         opt_audio_filter = 0;
1454         opt_hw_dev = 0;
1455         fflags = 0;
1456         char option_path[BCTEXTLEN];
1457         set_option_path(option_path, "%s", "ffmpeg.opts");
1458         read_options(option_path, opts);
1459 }
1460
1461 FFMPEG::~FFMPEG()
1462 {
1463         ff_lock("FFMPEG::~FFMPEG()");
1464         close_encoder();
1465         ffaudio.remove_all_objects();
1466         ffvideo.remove_all_objects();
1467         if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1468         ff_unlock();
1469         delete flow_lock;
1470         delete mux_lock;
1471         av_dict_free(&opts);
1472         delete [] opt_video_filter;
1473         delete [] opt_audio_filter;
1474         delete [] opt_hw_dev;
1475 }
1476
1477 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1478 {
1479         const int *p = codec->supported_samplerates;
1480         if( !p ) return sample_rate;
1481         while( *p != 0 ) {
1482                 if( *p == sample_rate ) return *p;
1483                 ++p;
1484         }
1485         return 0;
1486 }
1487
1488 static inline AVRational std_frame_rate(int i)
1489 {
1490         static const int m1 = 1001*12, m2 = 1000*12;
1491         static const int freqs[] = {
1492                 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1493                 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
1494         };
1495         int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1496         return (AVRational) { freq, 1001*12 };
1497 }
1498
1499 AVRational FFMPEG::check_frame_rate(AVCodec *codec, double frame_rate)
1500 {
1501         const AVRational *p = codec->supported_framerates;
1502         AVRational rate, best_rate = (AVRational) { 0, 0 };
1503         double max_err = 1.;  int i = 0;
1504         while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1505                 double framerate = (double) rate.num / rate.den;
1506                 double err = fabs(frame_rate/framerate - 1.);
1507                 if( err >= max_err ) continue;
1508                 max_err = err;
1509                 best_rate = rate;
1510         }
1511         return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1512 }
1513
1514 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1515 {
1516 #if 1
1517         double display_aspect = asset->width / (double)asset->height;
1518         double sample_aspect = display_aspect / asset->aspect_ratio;
1519         int width = 1000000, height = width * sample_aspect + 0.5;
1520         float w, h;
1521         MWindow::create_aspect_ratio(w, h, width, height);
1522         return (AVRational){(int)w, (int)h};
1523 #else
1524 // square pixels
1525         return (AVRational){1, 1};
1526 #endif
1527 }
1528
1529 AVRational FFMPEG::to_time_base(int sample_rate)
1530 {
1531         return (AVRational){1, sample_rate};
1532 }
1533
1534 int FFMPEG::get_fmt_score(AVSampleFormat dst_fmt, AVSampleFormat src_fmt)
1535 {
1536         int score = 0;
1537         int dst_planar = av_sample_fmt_is_planar(dst_fmt);
1538         int src_planar = av_sample_fmt_is_planar(src_fmt);
1539         if( dst_planar != src_planar ) ++score;
1540         int dst_bytes = av_get_bytes_per_sample(dst_fmt);
1541         int src_bytes = av_get_bytes_per_sample(src_fmt);
1542         score += (src_bytes > dst_bytes ? 100 : -10) * (src_bytes - dst_bytes);
1543         int src_packed = av_get_packed_sample_fmt(src_fmt);
1544         int dst_packed = av_get_packed_sample_fmt(dst_fmt);
1545         if( dst_packed == AV_SAMPLE_FMT_S32 && src_packed == AV_SAMPLE_FMT_FLT ) score += 20;
1546         if( dst_packed == AV_SAMPLE_FMT_FLT && src_packed == AV_SAMPLE_FMT_S32 ) score += 2;
1547         return score;
1548 }
1549
1550 AVSampleFormat FFMPEG::find_best_sample_fmt_of_list(
1551                 const AVSampleFormat *sample_fmts, AVSampleFormat src_fmt)
1552 {
1553         AVSampleFormat best = AV_SAMPLE_FMT_NONE;
1554         int best_score = get_fmt_score(best, src_fmt);
1555         for( int i=0; sample_fmts[i] >= 0; ++i ) {
1556                 AVSampleFormat sample_fmt = sample_fmts[i];
1557                 int score = get_fmt_score(sample_fmt, src_fmt);
1558                 if( score >= best_score ) continue;
1559                 best = sample_fmt;  best_score = score;
1560         }
1561         return best;
1562 }
1563
1564
1565 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
1566 {
1567         char *ep = path + BCTEXTLEN-1;
1568         strncpy(path, File::get_cindat_path(), ep-path);
1569         strncat(path, "/ffmpeg/", ep-path);
1570         path += strlen(path);
1571         va_list ap;
1572         va_start(ap, fmt);
1573         path += vsnprintf(path, ep-path, fmt, ap);
1574         va_end(ap);
1575         *path = 0;
1576 }
1577
1578 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
1579 {
1580         if( *spec == '/' )
1581                 strcpy(path, spec);
1582         else
1583                 set_option_path(path, "%s/%s", type, spec);
1584 }
1585
1586 int FFMPEG::get_format(char *format, const char *path, const char *spec)
1587 {
1588         char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
1589         get_option_path(option_path, path, spec);
1590         FILE *fp = fopen(option_path,"r");
1591         if( !fp ) return 1;
1592         int ret = 0;
1593         if( !fgets(line, sizeof(line), fp) ) ret = 1;
1594         if( !ret ) {
1595                 line[sizeof(line)-1] = 0;
1596                 ret = scan_option_line(line, format, codec);
1597         }
1598         fclose(fp);
1599         return ret;
1600 }
1601
1602 int FFMPEG::get_codec(char *codec, const char *path, const char *spec)
1603 {
1604         char option_path[BCTEXTLEN], line[BCTEXTLEN], format[BCTEXTLEN];
1605         get_option_path(option_path, path, spec);
1606         FILE *fp = fopen(option_path,"r");
1607         if( !fp ) return 1;
1608         int ret = 0;
1609         if( !fgets(line, sizeof(line), fp) ) ret = 1;
1610         fclose(fp);
1611         if( !ret ) {
1612                 line[sizeof(line)-1] = 0;
1613                 ret = scan_option_line(line, format, codec);
1614         }
1615         if( !ret ) {
1616                 char *vp = codec, *ep = vp+BCTEXTLEN-1;
1617                 while( vp < ep && *vp && *vp != '|' ) ++vp;
1618                 if( *vp == '|' ) --vp;
1619                 while( vp > codec && (*vp==' ' || *vp=='\t') ) *vp-- = 0;
1620         }
1621         return ret;
1622 }
1623
1624 int FFMPEG::get_file_format()
1625 {
1626         char audio_muxer[BCSTRLEN], video_muxer[BCSTRLEN];
1627         char audio_format[BCSTRLEN], video_format[BCSTRLEN];
1628         audio_muxer[0] = audio_format[0] = 0;
1629         video_muxer[0] = video_format[0] = 0;
1630         Asset *asset = file_base->asset;
1631         int ret = asset ? 0 : 1;
1632         if( !ret && asset->audio_data ) {
1633                 if( !(ret=get_format(audio_format, "audio", asset->acodec)) ) {
1634                         if( get_format(audio_muxer, "format", audio_format) ) {
1635                                 strcpy(audio_muxer, audio_format);
1636                                 audio_format[0] = 0;
1637                         }
1638                 }
1639         }
1640         if( !ret && asset->video_data ) {
1641                 if( !(ret=get_format(video_format, "video", asset->vcodec)) ) {
1642                         if( get_format(video_muxer, "format", video_format) ) {
1643                                 strcpy(video_muxer, video_format);
1644                                 video_format[0] = 0;
1645                         }
1646                 }
1647         }
1648         if( !ret && !audio_muxer[0] && !video_muxer[0] )
1649                 ret = 1;
1650         if( !ret && audio_muxer[0] && video_muxer[0] &&
1651             strcmp(audio_muxer, video_muxer) ) ret = -1;
1652         if( !ret && audio_format[0] && video_format[0] &&
1653             strcmp(audio_format, video_format) ) ret = -1;
1654         if( !ret )
1655                 strcpy(file_format, !audio_format[0] && !video_format[0] ?
1656                         (audio_muxer[0] ? audio_muxer : video_muxer) :
1657                         (audio_format[0] ? audio_format : video_format));
1658         return ret;
1659 }
1660
1661 int FFMPEG::scan_option_line(const char *cp, char *tag, char *val)
1662 {
1663         while( *cp == ' ' || *cp == '\t' ) ++cp;
1664         const char *bp = cp;
1665         while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' && *cp != '\n' ) ++cp;
1666         int len = cp - bp;
1667         if( !len || len > BCSTRLEN-1 ) return 1;
1668         while( bp < cp ) *tag++ = *bp++;
1669         *tag = 0;
1670         while( *cp == ' ' || *cp == '\t' ) ++cp;
1671         if( *cp == '=' ) ++cp;
1672         while( *cp == ' ' || *cp == '\t' ) ++cp;
1673         bp = cp;
1674         while( *cp && *cp != '\n' ) ++cp;
1675         len = cp - bp;
1676         if( len > BCTEXTLEN-1 ) return 1;
1677         while( bp < cp ) *val++ = *bp++;
1678         *val = 0;
1679         return 0;
1680 }
1681
1682 int FFMPEG::can_render(const char *fformat, const char *type)
1683 {
1684         FileSystem fs;
1685         char option_path[BCTEXTLEN];
1686         FFMPEG::set_option_path(option_path, type);
1687         fs.update(option_path);
1688         int total_files = fs.total_files();
1689         for( int i=0; i<total_files; ++i ) {
1690                 const char *name = fs.get_entry(i)->get_name();
1691                 const char *ext = strrchr(name,'.');
1692                 if( !ext ) continue;
1693                 if( !strcmp(fformat, ++ext) ) return 1;
1694         }
1695         return 0;
1696 }
1697
1698 int FFMPEG::get_ff_option(const char *nm, const char *options, char *value)
1699 {
1700         for( const char *cp=options; *cp!=0; ) {
1701                 char line[BCTEXTLEN], *bp = line, *ep = bp+sizeof(line)-1;
1702                 while( bp < ep && *cp && *cp!='\n' ) *bp++ = *cp++;
1703                 if( *cp ) ++cp;
1704                 *bp = 0;
1705                 if( !line[0] || line[0] == '#' || line[0] == ';' ) continue;
1706                 char key[BCSTRLEN], val[BCTEXTLEN];
1707                 if( FFMPEG::scan_option_line(line, key, val) ) continue;
1708                 if( !strcmp(key, nm) ) {
1709                         strncpy(value, val, BCSTRLEN);
1710                         return 0;
1711                 }
1712         }
1713         return 1;
1714 }
1715
1716 void FFMPEG::scan_audio_options(Asset *asset, EDL *edl)
1717 {
1718         char cin_sample_fmt[BCSTRLEN];
1719         int cin_fmt = AV_SAMPLE_FMT_NONE;
1720         const char *options = asset->ff_audio_options;
1721         if( !get_ff_option("cin_sample_fmt", options, cin_sample_fmt) )
1722                 cin_fmt = (int)av_get_sample_fmt(cin_sample_fmt);
1723         if( cin_fmt < 0 ) {
1724                 char audio_codec[BCSTRLEN]; audio_codec[0] = 0;
1725                 AVCodec *av_codec = !FFMPEG::get_codec(audio_codec, "audio", asset->acodec) ?
1726                         avcodec_find_encoder_by_name(audio_codec) : 0;
1727                 if( av_codec && av_codec->sample_fmts )
1728                         cin_fmt = find_best_sample_fmt_of_list(av_codec->sample_fmts, AV_SAMPLE_FMT_FLT);
1729         }
1730         if( cin_fmt < 0 ) cin_fmt = AV_SAMPLE_FMT_S16;
1731         const char *name = av_get_sample_fmt_name((AVSampleFormat)cin_fmt);
1732         if( !name ) name = _("None");
1733         strcpy(asset->ff_sample_format, name);
1734
1735         char value[BCSTRLEN];
1736         if( !get_ff_option("cin_bitrate", options, value) )
1737                 asset->ff_audio_bitrate = atoi(value);
1738         if( !get_ff_option("cin_quality", options, value) )
1739                 asset->ff_audio_quality = atoi(value);
1740 }
1741
1742 void FFMPEG::load_audio_options(Asset *asset, EDL *edl)
1743 {
1744         char options_path[BCTEXTLEN];
1745         set_option_path(options_path, "audio/%s", asset->acodec);
1746         if( !load_options(options_path,
1747                         asset->ff_audio_options,
1748                         sizeof(asset->ff_audio_options)) )
1749                 scan_audio_options(asset, edl);
1750 }
1751
1752 void FFMPEG::scan_video_options(Asset *asset, EDL *edl)
1753 {
1754         char cin_pix_fmt[BCSTRLEN];
1755         int cin_fmt = AV_PIX_FMT_NONE;
1756         const char *options = asset->ff_video_options;
1757         if( !get_ff_option("cin_pix_fmt", options, cin_pix_fmt) )
1758                         cin_fmt = (int)av_get_pix_fmt(cin_pix_fmt);
1759         if( cin_fmt < 0 ) {
1760                 char video_codec[BCSTRLEN];  video_codec[0] = 0;
1761                 AVCodec *av_codec = !get_codec(video_codec, "video", asset->vcodec) ?
1762                         avcodec_find_encoder_by_name(video_codec) : 0;
1763                 if( av_codec && av_codec->pix_fmts ) {
1764                         if( 0 && edl ) { // frequently picks a bad answer
1765                                 int color_model = edl->session->color_model;
1766                                 int max_bits = BC_CModels::calculate_pixelsize(color_model) * 8;
1767                                 max_bits /= BC_CModels::components(color_model);
1768                                 cin_fmt = avcodec_find_best_pix_fmt_of_list(av_codec->pix_fmts,
1769                                         (BC_CModels::is_yuv(color_model) ?
1770                                                 (max_bits > 8 ? AV_PIX_FMT_AYUV64LE : AV_PIX_FMT_YUV444P) :
1771                                                 (max_bits > 8 ? AV_PIX_FMT_RGB48LE : AV_PIX_FMT_RGB24)), 0, 0);
1772                         }
1773                         else
1774                                 cin_fmt = av_codec->pix_fmts[0];
1775                 }
1776         }
1777         if( cin_fmt < 0 ) cin_fmt = AV_PIX_FMT_YUV420P;
1778         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get((AVPixelFormat)cin_fmt);
1779         const char *name = desc ? desc->name : _("None");
1780         strcpy(asset->ff_pixel_format, name);
1781
1782         char value[BCSTRLEN];
1783         if( !get_ff_option("cin_bitrate", options, value) )
1784                 asset->ff_video_bitrate = atoi(value);
1785         if( !get_ff_option("cin_quality", options, value) )
1786                 asset->ff_video_quality = atoi(value);
1787 }
1788
1789 void FFMPEG::load_video_options(Asset *asset, EDL *edl)
1790 {
1791         char options_path[BCTEXTLEN];
1792         set_option_path(options_path, "video/%s", asset->vcodec);
1793         if( !load_options(options_path,
1794                         asset->ff_video_options,
1795                         sizeof(asset->ff_video_options)) )
1796                 scan_video_options(asset, edl);
1797 }
1798
1799 int FFMPEG::load_defaults(const char *path, const char *type,
1800                  char *codec, char *codec_options, int len)
1801 {
1802         char default_file[BCTEXTLEN];
1803         set_option_path(default_file, "%s/%s.dfl", path, type);
1804         FILE *fp = fopen(default_file,"r");
1805         if( !fp ) return 1;
1806         fgets(codec, BCSTRLEN, fp);
1807         char *cp = codec;
1808         while( *cp && *cp!='\n' ) ++cp;
1809         *cp = 0;
1810         while( len > 0 && fgets(codec_options, len, fp) ) {
1811                 int n = strlen(codec_options);
1812                 codec_options += n;  len -= n;
1813         }
1814         fclose(fp);
1815         set_option_path(default_file, "%s/%s", path, codec);
1816         return load_options(default_file, codec_options, len);
1817 }
1818
1819 void FFMPEG::set_asset_format(Asset *asset, EDL *edl, const char *text)
1820 {
1821         if( asset->format != FILE_FFMPEG ) return;
1822         if( text != asset->fformat )
1823                 strcpy(asset->fformat, text);
1824         if( asset->audio_data && !asset->ff_audio_options[0] ) {
1825                 if( !load_defaults("audio", text, asset->acodec,
1826                                 asset->ff_audio_options, sizeof(asset->ff_audio_options)) )
1827                         scan_audio_options(asset, edl);
1828                 else
1829                         asset->audio_data = 0;
1830         }
1831         if( asset->video_data && !asset->ff_video_options[0] ) {
1832                 if( !load_defaults("video", text, asset->vcodec,
1833                                 asset->ff_video_options, sizeof(asset->ff_video_options)) )
1834                         scan_video_options(asset, edl);
1835                 else
1836                         asset->video_data = 0;
1837         }
1838 }
1839
1840 int FFMPEG::get_encoder(const char *options,
1841                 char *format, char *codec, char *bsfilter)
1842 {
1843         FILE *fp = fopen(options,"r");
1844         if( !fp ) {
1845                 eprintf(_("options open failed %s\n"),options);
1846                 return 1;
1847         }
1848         char line[BCTEXTLEN];
1849         if( !fgets(line, sizeof(line), fp) ||
1850             scan_encoder(line, format, codec, bsfilter) )
1851                 eprintf(_("format/codec not found %s\n"), options);
1852         fclose(fp);
1853         return 0;
1854 }
1855
1856 int FFMPEG::scan_encoder(const char *line,
1857                 char *format, char *codec, char *bsfilter)
1858 {
1859         format[0] = codec[0] = bsfilter[0] = 0;
1860         if( scan_option_line(line, format, codec) ) return 1;
1861         char *cp = codec;
1862         while( *cp && *cp != '|' ) ++cp;
1863         if( !*cp ) return 0;
1864         char *bp = cp;
1865         do { *bp-- = 0; } while( bp>=codec && (*bp==' ' || *bp == '\t' ) );
1866         while( *++cp && (*cp==' ' || *cp == '\t') );
1867         bp = bsfilter;
1868         for( int i=BCTEXTLEN; --i>0 && *cp; ) *bp++ = *cp++;
1869         *bp = 0;
1870         return 0;
1871 }
1872
1873 int FFMPEG::read_options(const char *options, AVDictionary *&opts, int skip)
1874 {
1875         FILE *fp = fopen(options,"r");
1876         if( !fp ) return 1;
1877         int ret = 0;
1878         while( !ret && --skip >= 0 ) {
1879                 int ch = getc(fp);
1880                 while( ch >= 0 && ch != '\n' ) ch = getc(fp);
1881                 if( ch < 0 ) ret = 1;
1882         }
1883         if( !ret )
1884                 ret = read_options(fp, options, opts);
1885         fclose(fp);
1886         return ret;
1887 }
1888
1889 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
1890 {
1891         FILE *fp = fmemopen((void *)options,strlen(options),"r");
1892         if( !fp ) return 0;
1893         int ret = read_options(fp, options, opts);
1894         fclose(fp);
1895         AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
1896         if( tag ) st->id = strtol(tag->value,0,0);
1897         return ret;
1898 }
1899
1900 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
1901 {
1902         int ret = 0, no = 0;
1903         char line[BCTEXTLEN];
1904         while( !ret && fgets(line, sizeof(line), fp) ) {
1905                 line[sizeof(line)-1] = 0;
1906                 if( line[0] == '#' ) continue;
1907                 if( line[0] == '\n' ) continue;
1908                 char key[BCSTRLEN], val[BCTEXTLEN];
1909                 if( scan_option_line(line, key, val) ) {
1910                         eprintf(_("err reading %s: line %d\n"), options, no);
1911                         ret = 1;
1912                 }
1913                 if( !ret ) {
1914                         if( !strcmp(key, "duration") )
1915                                 opt_duration = strtod(val, 0);
1916                         else if( !strcmp(key, "video_filter") )
1917                                 opt_video_filter = cstrdup(val);
1918                         else if( !strcmp(key, "audio_filter") )
1919                                 opt_audio_filter = cstrdup(val);
1920                         else if( !strcmp(key, "cin_hw_dev") )
1921                                 opt_hw_dev = cstrdup(val);
1922                         else if( !strcmp(key, "loglevel") )
1923                                 set_loglevel(val);
1924                         else
1925                                 av_dict_set(&opts, key, val, 0);
1926                 }
1927         }
1928         return ret;
1929 }
1930
1931 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
1932 {
1933         char option_path[BCTEXTLEN];
1934         set_option_path(option_path, "%s", options);
1935         return read_options(option_path, opts);
1936 }
1937
1938 int FFMPEG::load_options(const char *path, char *bfr, int len)
1939 {
1940         *bfr = 0;
1941         FILE *fp = fopen(path, "r");
1942         if( !fp ) return 1;
1943         fgets(bfr, len, fp); // skip hdr
1944         len = fread(bfr, 1, len-1, fp);
1945         if( len < 0 ) len = 0;
1946         bfr[len] = 0;
1947         fclose(fp);
1948         return 0;
1949 }
1950
1951 void FFMPEG::set_loglevel(const char *ap)
1952 {
1953         if( !ap || !*ap ) return;
1954         const struct {
1955                 const char *name;
1956                 int level;
1957         } log_levels[] = {
1958                 { "quiet"  , AV_LOG_QUIET   },
1959                 { "panic"  , AV_LOG_PANIC   },
1960                 { "fatal"  , AV_LOG_FATAL   },
1961                 { "error"  , AV_LOG_ERROR   },
1962                 { "warning", AV_LOG_WARNING },
1963                 { "info"   , AV_LOG_INFO    },
1964                 { "verbose", AV_LOG_VERBOSE },
1965                 { "debug"  , AV_LOG_DEBUG   },
1966         };
1967         for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
1968                 if( !strcmp(log_levels[i].name, ap) ) {
1969                         av_log_set_level(log_levels[i].level);
1970                         return;
1971                 }
1972         }
1973         av_log_set_level(atoi(ap));
1974 }
1975
1976 double FFMPEG::to_secs(int64_t time, AVRational time_base)
1977 {
1978         double base_time = time == AV_NOPTS_VALUE ? 0 :
1979                 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
1980         return base_time / AV_TIME_BASE;
1981 }
1982
1983 int FFMPEG::info(char *text, int len)
1984 {
1985         if( len <= 0 ) return 0;
1986         decode_activate();
1987 #define report(s...) do { int n = snprintf(cp,len,s); cp += n;  len -= n; } while(0)
1988         char *cp = text;
1989         report("format: %s\n",fmt_ctx->iformat->name);
1990         if( ffvideo.size() > 0 )
1991                 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
1992         for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
1993                 FFVideoStream *vid = ffvideo[vidx];
1994                 AVStream *st = vid->st;
1995                 AVCodecID codec_id = st->codecpar->codec_id;
1996                 report(_("vid%d (%d),  id 0x%06x:\n"), vid->idx, vid->fidx, codec_id);
1997                 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
1998                 report("  video%d %s", vidx+1, desc ? desc->name : " (unkn)");
1999                 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
2000                 AVPixelFormat pix_fmt = (AVPixelFormat)st->codecpar->format;
2001                 const char *pfn = av_get_pix_fmt_name(pix_fmt);
2002                 report(" pix %s\n", pfn ? pfn : "(unkn)");
2003                 double secs = to_secs(st->duration, st->time_base);
2004                 int64_t length = secs * vid->frame_rate + 0.5;
2005                 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
2006                 int64_t nudge = ofs * vid->frame_rate;
2007                 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
2008                 report("    %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
2009                 int hrs = secs/3600;  secs -= hrs*3600;
2010                 int mins = secs/60;  secs -= mins*60;
2011                 report("  %d:%02d:%05.2f\n", hrs, mins, secs);
2012         }
2013         if( ffaudio.size() > 0 )
2014                 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
2015         for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2016                 FFAudioStream *aud = ffaudio[aidx];
2017                 AVStream *st = aud->st;
2018                 AVCodecID codec_id = st->codecpar->codec_id;
2019                 report(_("aud%d (%d),  id 0x%06x:\n"), aud->idx, aud->fidx, codec_id);
2020                 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
2021                 int nch = aud->channels, ch0 = aud->channel0+1;
2022                 report("  audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
2023                 AVSampleFormat sample_fmt = (AVSampleFormat)st->codecpar->format;
2024                 const char *fmt = av_get_sample_fmt_name(sample_fmt);
2025                 report(" %s %d", fmt, aud->sample_rate);
2026                 int sample_bits = av_get_bits_per_sample(codec_id);
2027                 report(" %dbits\n", sample_bits);
2028                 double secs = to_secs(st->duration, st->time_base);
2029                 int64_t length = secs * aud->sample_rate + 0.5;
2030                 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
2031                 int64_t nudge = ofs * aud->sample_rate;
2032                 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
2033                 report("    %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
2034                 int hrs = secs/3600;  secs -= hrs*3600;
2035                 int mins = secs/60;  secs -= mins*60;
2036                 report("  %d:%02d:%05.2f\n", hrs, mins, secs);
2037         }
2038         if( fmt_ctx->nb_programs > 0 )
2039                 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
2040         for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
2041                 report("program %d", i+1);
2042                 AVProgram *pgrm = fmt_ctx->programs[i];
2043                 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2044                         int idx = pgrm->stream_index[j];
2045                         int vidx = ffvideo.size();
2046                         while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
2047                         if( vidx >= 0 ) {
2048                                 report(", vid%d", vidx);
2049                                 continue;
2050                         }
2051                         int aidx = ffaudio.size();
2052                         while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
2053                         if( aidx >= 0 ) {
2054                                 report(", aud%d", aidx);
2055                                 continue;
2056                         }
2057                         report(", (%d)", pgrm->stream_index[j]);
2058                 }
2059                 report("\n");
2060         }
2061         report("\n");
2062         AVDictionaryEntry *tag = 0;
2063         while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
2064                 report("%s=%s\n", tag->key, tag->value);
2065
2066         if( !len ) --cp;
2067         *cp = 0;
2068         return cp - text;
2069 #undef report
2070 }
2071
2072
2073 int FFMPEG::init_decoder(const char *filename)
2074 {
2075         ff_lock("FFMPEG::init_decoder");
2076         av_register_all();
2077         char file_opts[BCTEXTLEN];
2078         strcpy(file_opts, filename);
2079         char *bp = strrchr(file_opts, '/');
2080         if( !bp ) bp = file_opts;
2081         char *sp = strrchr(bp, '.');
2082         if( !sp ) sp = bp + strlen(bp);
2083         FILE *fp = 0;
2084         AVInputFormat *ifmt = 0;
2085         if( sp ) {
2086                 strcpy(sp, ".opts");
2087                 fp = fopen(file_opts, "r");
2088         }
2089         if( fp ) {
2090                 read_options(fp, file_opts, opts);
2091                 fclose(fp);
2092                 AVDictionaryEntry *tag;
2093                 if( (tag=av_dict_get(opts, "format", NULL, 0)) != 0 ) {
2094                         ifmt = av_find_input_format(tag->value);
2095                 }
2096         }
2097         else
2098                 load_options("decode.opts", opts);
2099         AVDictionary *fopts = 0;
2100         av_dict_copy(&fopts, opts, 0);
2101         int ret = avformat_open_input(&fmt_ctx, filename, ifmt, &fopts);
2102         av_dict_free(&fopts);
2103         if( ret >= 0 )
2104                 ret = avformat_find_stream_info(fmt_ctx, NULL);
2105         if( !ret ) {
2106                 decoding = -1;
2107         }
2108         ff_unlock();
2109         return !ret ? 0 : 1;
2110 }
2111
2112 int FFMPEG::open_decoder()
2113 {
2114         struct stat st;
2115         if( stat(fmt_ctx->url, &st) < 0 ) {
2116                 eprintf(_("can't stat file: %s\n"), fmt_ctx->url);
2117                 return 1;
2118         }
2119
2120         int64_t file_bits = 8 * st.st_size;
2121         if( !fmt_ctx->bit_rate && opt_duration > 0 )
2122                 fmt_ctx->bit_rate = file_bits / opt_duration;
2123
2124         int estimated = 0;
2125         if( fmt_ctx->bit_rate > 0 ) {
2126                 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2127                         AVStream *st = fmt_ctx->streams[i];
2128                         if( st->duration != AV_NOPTS_VALUE ) continue;
2129                         if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
2130                         st->duration = av_rescale(file_bits, st->time_base.den,
2131                                 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
2132                         estimated = 1;
2133                 }
2134         }
2135         if( estimated && !(fflags & FF_ESTM_TIMES) ) {
2136                 fflags |= FF_ESTM_TIMES;
2137                 printf("FFMPEG::open_decoder: some stream times estimated: %s\n",
2138                         fmt_ctx->url);
2139         }
2140
2141         ff_lock("FFMPEG::open_decoder");
2142         int ret = 0, bad_time = 0;
2143         for( int i=0; !ret && i<(int)fmt_ctx->nb_streams; ++i ) {
2144                 AVStream *st = fmt_ctx->streams[i];
2145                 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
2146                 AVCodecParameters *avpar = st->codecpar;
2147                 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avpar->codec_id);
2148                 if( !codec_desc ) continue;
2149                 switch( avpar->codec_type ) {
2150                 case AVMEDIA_TYPE_VIDEO: {
2151                         if( avpar->width < 1 ) continue;
2152                         if( avpar->height < 1 ) continue;
2153                         AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
2154                         if( framerate.num < 1 ) continue;
2155                         has_video = 1;
2156                         int vidx = ffvideo.size();
2157                         FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
2158                         vstrm_index.append(ffidx(vidx, 0));
2159                         ffvideo.append(vid);
2160                         vid->width = avpar->width;
2161                         vid->height = avpar->height;
2162                         vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
2163                         double secs = to_secs(st->duration, st->time_base);
2164                         vid->length = secs * vid->frame_rate;
2165                         vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
2166                         vid->nudge = st->start_time;
2167                         vid->reading = -1;
2168                         if( opt_video_filter )
2169                                 ret = vid->create_filter(opt_video_filter, avpar);
2170                         break; }
2171                 case AVMEDIA_TYPE_AUDIO: {
2172                         if( avpar->channels < 1 ) continue;
2173                         if( avpar->sample_rate < 1 ) continue;
2174                         has_audio = 1;
2175                         int aidx = ffaudio.size();
2176                         FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
2177                         ffaudio.append(aud);
2178                         aud->channel0 = astrm_index.size();
2179                         aud->channels = avpar->channels;
2180                         for( int ch=0; ch<aud->channels; ++ch )
2181                                 astrm_index.append(ffidx(aidx, ch));
2182                         aud->sample_rate = avpar->sample_rate;
2183                         double secs = to_secs(st->duration, st->time_base);
2184                         aud->length = secs * aud->sample_rate;
2185                         aud->init_swr(aud->channels, avpar->format, aud->sample_rate);
2186                         aud->nudge = st->start_time;
2187                         aud->reading = -1;
2188                         if( opt_audio_filter )
2189                                 ret = aud->create_filter(opt_audio_filter, avpar);
2190                         break; }
2191                 default: break;
2192                 }
2193         }
2194         if( bad_time && !(fflags & FF_BAD_TIMES) ) {
2195                 fflags |= FF_BAD_TIMES;
2196                 printf("FFMPEG::open_decoder: some stream have bad times: %s\n",
2197                         fmt_ctx->url);
2198         }
2199         ff_unlock();
2200         return ret < 0 ? -1 : 0;
2201 }
2202
2203
2204 int FFMPEG::init_encoder(const char *filename)
2205 {
2206 // try access first for named pipes
2207         int ret = access(filename, W_OK);
2208         if( ret ) {
2209                 int fd = ::open(filename,O_WRONLY);
2210                 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
2211                 if( fd >= 0 ) { close(fd);  ret = 0; }
2212         }
2213         if( ret ) {
2214                 eprintf(_("bad file path: %s\n"), filename);
2215                 return 1;
2216         }
2217         ret = get_file_format();
2218         if( ret > 0 ) {
2219                 eprintf(_("bad file format: %s\n"), filename);
2220                 return 1;
2221         }
2222         if( ret < 0 ) {
2223                 eprintf(_("mismatch audio/video file format: %s\n"), filename);
2224                 return 1;
2225         }
2226         ff_lock("FFMPEG::init_encoder");
2227         av_register_all();
2228         char format[BCSTRLEN];
2229         if( get_format(format, "format", file_format) )
2230                 strcpy(format, file_format);
2231         avformat_alloc_output_context2(&fmt_ctx, 0, format, filename);
2232         if( !fmt_ctx ) {
2233                 eprintf(_("failed: %s\n"), filename);
2234                 ret = 1;
2235         }
2236         if( !ret ) {
2237                 encoding = -1;
2238                 load_options("encode.opts", opts);
2239         }
2240         ff_unlock();
2241         return ret;
2242 }
2243
2244 int FFMPEG::open_encoder(const char *type, const char *spec)
2245 {
2246
2247         Asset *asset = file_base->asset;
2248         char *filename = asset->path;
2249         AVDictionary *sopts = 0;
2250         av_dict_copy(&sopts, opts, 0);
2251         char option_path[BCTEXTLEN];
2252         set_option_path(option_path, "%s/%s.opts", type, type);
2253         read_options(option_path, sopts);
2254         get_option_path(option_path, type, spec);
2255         char format_name[BCSTRLEN], codec_name[BCTEXTLEN], bsfilter[BCTEXTLEN];
2256         if( get_encoder(option_path, format_name, codec_name, bsfilter) ) {
2257                 eprintf(_("get_encoder failed %s:%s\n"), option_path, filename);
2258                 return 1;
2259         }
2260
2261 #ifdef HAVE_DV
2262         if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
2263 #endif
2264         else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
2265         else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
2266
2267         int ret = 0;
2268         ff_lock("FFMPEG::open_encoder");
2269         FFStream *fst = 0;
2270         AVStream *st = 0;
2271         AVCodecContext *ctx = 0;
2272
2273         const AVCodecDescriptor *codec_desc = 0;
2274         AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
2275         if( !codec ) {
2276                 eprintf(_("cant find codec %s:%s\n"), codec_name, filename);
2277                 ret = 1;
2278         }
2279         if( !ret ) {
2280                 codec_desc = avcodec_descriptor_get(codec->id);
2281                 if( !codec_desc ) {
2282                         eprintf(_("unknown codec %s:%s\n"), codec_name, filename);
2283                         ret = 1;
2284                 }
2285         }
2286         if( !ret ) {
2287                 st = avformat_new_stream(fmt_ctx, 0);
2288                 if( !st ) {
2289                         eprintf(_("cant create stream %s:%s\n"), codec_name, filename);
2290                         ret = 1;
2291                 }
2292         }
2293         if( !ret ) {
2294                 switch( codec_desc->type ) {
2295                 case AVMEDIA_TYPE_AUDIO: {
2296                         if( has_audio ) {
2297                                 eprintf(_("duplicate audio %s:%s\n"), codec_name, filename);
2298                                 ret = 1;
2299                                 break;
2300                         }
2301                         if( scan_options(asset->ff_audio_options, sopts, st) ) {
2302                                 eprintf(_("bad audio options %s:%s\n"), codec_name, filename);
2303                                 ret = 1;
2304                                 break;
2305                         }
2306                         has_audio = 1;
2307                         ctx = avcodec_alloc_context3(codec);
2308                         if( asset->ff_audio_bitrate > 0 ) {
2309                                 ctx->bit_rate = asset->ff_audio_bitrate;
2310                                 char arg[BCSTRLEN];
2311                                 sprintf(arg, "%d", asset->ff_audio_bitrate);
2312                                 av_dict_set(&sopts, "b", arg, 0);
2313                         }
2314                         else if( asset->ff_audio_quality >= 0 ) {
2315                                 ctx->global_quality = asset->ff_audio_quality * FF_QP2LAMBDA;
2316                                 ctx->qmin    = ctx->qmax =  asset->ff_audio_quality;
2317                                 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2318                                 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2319                                 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2320                                 char arg[BCSTRLEN];
2321                                 av_dict_set(&sopts, "flags", "+qscale", 0);
2322                                 sprintf(arg, "%d", asset->ff_audio_quality);
2323                                 av_dict_set(&sopts, "qscale", arg, 0);
2324                                 sprintf(arg, "%d", ctx->global_quality);
2325                                 av_dict_set(&sopts, "global_quality", arg, 0);
2326                         }
2327                         int aidx = ffaudio.size();
2328                         int fidx = aidx + ffvideo.size();
2329                         FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
2330                         aud->avctx = ctx;  ffaudio.append(aud);  fst = aud;
2331                         aud->sample_rate = asset->sample_rate;
2332                         ctx->channels = aud->channels = asset->channels;
2333                         for( int ch=0; ch<aud->channels; ++ch )
2334                                 astrm_index.append(ffidx(aidx, ch));
2335                         ctx->channel_layout =  av_get_default_channel_layout(ctx->channels);
2336                         ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
2337                         if( !ctx->sample_rate ) {
2338                                 eprintf(_("check_sample_rate failed %s\n"), filename);
2339                                 ret = 1;
2340                                 break;
2341                         }
2342                         ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
2343                         AVSampleFormat sample_fmt = av_get_sample_fmt(asset->ff_sample_format);
2344                         if( sample_fmt == AV_SAMPLE_FMT_NONE )
2345                                 sample_fmt = codec->sample_fmts ? codec->sample_fmts[0] : AV_SAMPLE_FMT_S16;
2346                         ctx->sample_fmt = sample_fmt;
2347                         uint64_t layout = av_get_default_channel_layout(ctx->channels);
2348                         aud->resample_context = swr_alloc_set_opts(NULL,
2349                                 layout, ctx->sample_fmt, aud->sample_rate,
2350                                 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
2351                                 0, NULL);
2352                         swr_init(aud->resample_context);
2353                         aud->writing = -1;
2354                         break; }
2355                 case AVMEDIA_TYPE_VIDEO: {
2356                         if( has_video ) {
2357                                 eprintf(_("duplicate video %s:%s\n"), codec_name, filename);
2358                                 ret = 1;
2359                                 break;
2360                         }
2361                         if( scan_options(asset->ff_video_options, sopts, st) ) {
2362                                 eprintf(_("bad video options %s:%s\n"), codec_name, filename);
2363                                 ret = 1;
2364                                 break;
2365                         }
2366                         has_video = 1;
2367                         ctx = avcodec_alloc_context3(codec);
2368                         if( asset->ff_video_bitrate > 0 ) {
2369                                 ctx->bit_rate = asset->ff_video_bitrate;
2370                                 char arg[BCSTRLEN];
2371                                 sprintf(arg, "%d", asset->ff_video_bitrate);
2372                                 av_dict_set(&sopts, "b", arg, 0);
2373                         }
2374                         else if( asset->ff_video_quality >= 0 ) {
2375                                 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
2376                                 ctx->qmin    = ctx->qmax =  asset->ff_video_quality;
2377                                 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2378                                 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2379                                 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2380                                 char arg[BCSTRLEN];
2381                                 av_dict_set(&sopts, "flags", "+qscale", 0);
2382                                 sprintf(arg, "%d", asset->ff_video_quality);
2383                                 av_dict_set(&sopts, "qscale", arg, 0);
2384                                 sprintf(arg, "%d", ctx->global_quality);
2385                                 av_dict_set(&sopts, "global_quality", arg, 0);
2386                         }
2387                         int vidx = ffvideo.size();
2388                         int fidx = vidx + ffaudio.size();
2389                         FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
2390                         vstrm_index.append(ffidx(vidx, 0));
2391                         vid->avctx = ctx;  ffvideo.append(vid);  fst = vid;
2392                         vid->width = asset->width;
2393                         vid->height = asset->height;
2394                         vid->frame_rate = asset->frame_rate;
2395
2396                         AVPixelFormat pix_fmt = av_get_pix_fmt(asset->ff_pixel_format);
2397                         if( pix_fmt == AV_PIX_FMT_NONE )
2398                                 pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
2399                         ctx->pix_fmt = pix_fmt;
2400                         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
2401                         int mask_w = (1<<desc->log2_chroma_w)-1;
2402                         ctx->width = (vid->width+mask_w) & ~mask_w;
2403                         int mask_h = (1<<desc->log2_chroma_h)-1;
2404                         ctx->height = (vid->height+mask_h) & ~mask_h;
2405                         ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
2406                         AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
2407                         if( !frame_rate.num || !frame_rate.den ) {
2408                                 eprintf(_("check_frame_rate failed %s\n"), filename);
2409                                 ret = 1;
2410                                 break;
2411                         }
2412                         av_reduce(&frame_rate.num, &frame_rate.den,
2413                                 frame_rate.num, frame_rate.den, INT_MAX);
2414                         ctx->framerate = (AVRational) { frame_rate.num, frame_rate.den };
2415                         ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
2416                         st->avg_frame_rate = frame_rate;
2417                         st->time_base = ctx->time_base;
2418                         vid->writing = -1;
2419                         vid->interlaced = asset->interlace_mode == ILACE_MODE_TOP_FIRST ||
2420                                 asset->interlace_mode == ILACE_MODE_BOTTOM_FIRST ? 1 : 0;
2421                         vid->top_field_first = asset->interlace_mode == ILACE_MODE_TOP_FIRST ? 1 : 0;
2422                         break; }
2423                 default:
2424                         eprintf(_("not audio/video, %s:%s\n"), codec_name, filename);
2425                         ret = 1;
2426                 }
2427
2428                 if( ctx ) {
2429                         AVDictionaryEntry *tag;
2430                         if( (tag=av_dict_get(sopts, "cin_stats_filename", NULL, 0)) != 0 ) {
2431                                 char suffix[BCSTRLEN];  sprintf(suffix,"-%d.log",fst->fidx);
2432                                 fst->stats_filename = cstrcat(2, tag->value, suffix);
2433                         }
2434                         if( (tag=av_dict_get(sopts, "flags", NULL, 0)) != 0 ) {
2435                                 int pass = fst->pass;
2436                                 char *cp = tag->value;
2437                                 while( *cp ) {
2438                                         int ch = *cp++, pfx = ch=='-' ? -1 : ch=='+' ? 1 : 0;
2439                                         if( !isalnum(!pfx ? ch : (ch=*cp++)) ) continue;
2440                                         char id[BCSTRLEN], *bp = id, *ep = bp+sizeof(id)-1;
2441                                         for( *bp++=ch; isalnum(ch=*cp); ++cp )
2442                                                 if( bp < ep ) *bp++ = ch;
2443                                         *bp = 0;
2444                                         if( !strcmp(id, "pass1") ) {
2445                                                 pass = pfx<0 ? (pass&~1) : pfx>0 ? (pass|1) : 1;
2446                                         }
2447                                         else if( !strcmp(id, "pass2") ) {
2448                                                 pass = pfx<0 ? (pass&~2) : pfx>0 ? (pass|2) : 2;
2449                                         }
2450                                 }
2451                                 if( (fst->pass=pass) ) {
2452                                         if( pass & 1 ) ctx->flags |= AV_CODEC_FLAG_PASS1;
2453                                         if( pass & 2 ) ctx->flags |= AV_CODEC_FLAG_PASS2;
2454                                 }
2455                         }
2456                 }
2457         }
2458         if( !ret ) {
2459                 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
2460                         ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
2461                 if( fst->stats_filename && (ret=fst->init_stats_file()) )
2462                         eprintf(_("error: stats file = %s\n"), fst->stats_filename);
2463         }
2464         if( !ret ) {
2465                 av_dict_set(&sopts, "cin_bitrate", 0, 0);
2466                 av_dict_set(&sopts, "cin_quality", 0, 0);
2467
2468                 if( !av_dict_get(sopts, "threads", NULL, 0) )
2469                         ctx->thread_count = ff_cpus();
2470                 ret = avcodec_open2(ctx, codec, &sopts);
2471                 if( ret >= 0 ) {
2472                         ret = avcodec_parameters_from_context(st->codecpar, ctx);
2473                         if( ret < 0 )
2474                                 fprintf(stderr, "Could not copy the stream parameters\n");
2475                 }
2476                 if( ret >= 0 ) {
2477 _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
2478                         ret = avcodec_copy_context(st->codec, ctx);
2479 _Pragma("GCC diagnostic warning \"-Wdeprecated-declarations\"")
2480                         if( ret < 0 )
2481                                 fprintf(stderr, "Could not copy the stream context\n");
2482                 }
2483                 if( ret < 0 ) {
2484                         ff_err(ret,"FFMPEG::open_encoder");
2485                         eprintf(_("open failed %s:%s\n"), codec_name, filename);
2486                         ret = 1;
2487                 }
2488                 else
2489                         ret = 0;
2490         }
2491         if( !ret && fst && bsfilter[0] ) {
2492                 ret = av_bsf_list_parse_str(bsfilter, &fst->bsfc);
2493                 if( ret < 0 ) {
2494                         ff_err(ret,"FFMPEG::open_encoder");
2495                         eprintf(_("bitstream filter failed %s:\n%s\n"), filename, bsfilter);
2496                         ret = 1;
2497                 }
2498                 else
2499                         ret = 0;
2500         }
2501
2502         if( !ret )
2503                 start_muxer();
2504
2505         ff_unlock();
2506         av_dict_free(&sopts);
2507         return ret;
2508 }
2509
2510 int FFMPEG::close_encoder()
2511 {
2512         stop_muxer();
2513         if( encoding > 0 ) {
2514                 av_write_trailer(fmt_ctx);
2515                 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
2516                         avio_closep(&fmt_ctx->pb);
2517         }
2518         encoding = 0;
2519         return 0;
2520 }
2521
2522 int FFMPEG::decode_activate()
2523 {
2524         if( decoding < 0 ) {
2525                 decoding = 0;
2526                 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
2527                         ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
2528                 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
2529                         ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
2530                 // set nudges for each program stream set
2531                 const int64_t min_nudge = INT64_MIN+1;
2532                 int npgrms = fmt_ctx->nb_programs;
2533                 for( int i=0; i<npgrms; ++i ) {
2534                         AVProgram *pgrm = fmt_ctx->programs[i];
2535                         // first start time video stream
2536                         int64_t vstart_time = min_nudge, astart_time = min_nudge;
2537                         for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2538                                 int fidx = pgrm->stream_index[j];
2539                                 AVStream *st = fmt_ctx->streams[fidx];
2540                                 AVCodecParameters *avpar = st->codecpar;
2541                                 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2542                                         if( st->start_time == AV_NOPTS_VALUE ) continue;
2543                                         if( vstart_time < st->start_time )
2544                                                 vstart_time = st->start_time;
2545                                         continue;
2546                                 }
2547                                 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2548                                         if( st->start_time == AV_NOPTS_VALUE ) continue;
2549                                         if( astart_time < st->start_time )
2550                                                 astart_time = st->start_time;
2551                                         continue;
2552                                 }
2553                         }
2554                         //since frame rate is much more grainy than sample rate, it is better to
2555                         // align using video, so that total absolute error is minimized.
2556                         int64_t nudge = vstart_time > min_nudge ? vstart_time :
2557                                 astart_time > min_nudge ? astart_time : AV_NOPTS_VALUE;
2558                         for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2559                                 int fidx = pgrm->stream_index[j];
2560                                 AVStream *st = fmt_ctx->streams[fidx];
2561                                 AVCodecParameters *avpar = st->codecpar;
2562                                 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2563                                         for( int k=0; k<ffvideo.size(); ++k ) {
2564                                                 if( ffvideo[k]->fidx != fidx ) continue;
2565                                                 ffvideo[k]->nudge = nudge;
2566                                         }
2567                                         continue;
2568                                 }
2569                                 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2570                                         for( int k=0; k<ffaudio.size(); ++k ) {
2571                                                 if( ffaudio[k]->fidx != fidx ) continue;
2572                                                 ffaudio[k]->nudge = nudge;
2573                                         }
2574                                         continue;
2575                                 }
2576                         }
2577                 }
2578                 // set nudges for any streams not yet set
2579                 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2580                 int nstreams = fmt_ctx->nb_streams;
2581                 for( int i=0; i<nstreams; ++i ) {
2582                         AVStream *st = fmt_ctx->streams[i];
2583                         AVCodecParameters *avpar = st->codecpar;
2584                         switch( avpar->codec_type ) {
2585                         case AVMEDIA_TYPE_VIDEO: {
2586                                 if( st->start_time == AV_NOPTS_VALUE ) continue;
2587                                 int vidx = ffvideo.size();
2588                                 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
2589                                 if( vidx < 0 ) continue;
2590                                 if( ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
2591                                 if( vstart_time < st->start_time )
2592                                         vstart_time = st->start_time;
2593                                 break; }
2594                         case AVMEDIA_TYPE_AUDIO: {
2595                                 if( st->start_time == AV_NOPTS_VALUE ) continue;
2596                                 int aidx = ffaudio.size();
2597                                 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
2598                                 if( aidx < 0 ) continue;
2599                                 if( ffaudio[aidx]->frame_sz < avpar->frame_size )
2600                                         ffaudio[aidx]->frame_sz = avpar->frame_size;
2601                                 if( ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
2602                                 if( astart_time < st->start_time )
2603                                         astart_time = st->start_time;
2604                                 break; }
2605                         default: break;
2606                         }
2607                 }
2608                 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2609                         astart_time > min_nudge ? astart_time : 0;
2610                 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
2611                         if( ffvideo[vidx]->nudge == AV_NOPTS_VALUE )
2612                                 ffvideo[vidx]->nudge = nudge;
2613                 }
2614                 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2615                         if( ffaudio[aidx]->nudge == AV_NOPTS_VALUE )
2616                                 ffaudio[aidx]->nudge = nudge;
2617                 }
2618                 decoding = 1;
2619         }
2620         return decoding;
2621 }
2622
2623 int FFMPEG::encode_activate()
2624 {
2625         int ret = 0;
2626         if( encoding < 0 ) {
2627                 encoding = 0;
2628                 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
2629                     (ret=avio_open(&fmt_ctx->pb, fmt_ctx->url, AVIO_FLAG_WRITE)) < 0 ) {
2630                         ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
2631                                 fmt_ctx->url);
2632                         return -1;
2633                 }
2634
2635                 int prog_id = 1;
2636                 AVProgram *prog = av_new_program(fmt_ctx, prog_id);
2637                 for( int i=0; i< ffvideo.size(); ++i )
2638                         av_program_add_stream_index(fmt_ctx, prog_id, ffvideo[i]->fidx);
2639                 for( int i=0; i< ffaudio.size(); ++i )
2640                         av_program_add_stream_index(fmt_ctx, prog_id, ffaudio[i]->fidx);
2641                 int pi = fmt_ctx->nb_programs;
2642                 while(  --pi >= 0 && fmt_ctx->programs[pi]->id != prog_id );
2643                 AVDictionary **meta = &prog->metadata;
2644                 av_dict_set(meta, "service_provider", "cin5", 0);
2645                 const char *path = fmt_ctx->url, *bp = strrchr(path,'/');
2646                 if( bp ) path = bp + 1;
2647                 av_dict_set(meta, "title", path, 0);
2648
2649                 if( ffaudio.size() ) {
2650                         const char *ep = getenv("CIN_AUDIO_LANG"), *lp = 0;
2651                         if( !ep && (lp=getenv("LANG")) ) { // some are guesses
2652                                 static struct { const char lc[3], lng[4]; } lcode[] = {
2653                                         { "en", "eng" }, { "de", "ger" }, { "es", "spa" },
2654                                         { "eu", "bas" }, { "fr", "fre" }, { "el", "gre" },
2655                                         { "hi", "hin" }, { "it", "ita" }, { "ja", "jap" },
2656                                         { "ko", "kor" }, { "du", "dut" }, { "pl", "pol" },
2657                                         { "pt", "por" }, { "ru", "rus" }, { "sl", "slv" },
2658                                         { "uk", "ukr" }, { "vi", "vie" }, { "zh", "chi" },
2659                                 };
2660                                 for( int i=sizeof(lcode)/sizeof(lcode[0]); --i>=0 && !ep; )
2661                                         if( !strncmp(lcode[i].lc,lp,2) ) ep = lcode[i].lng;
2662                         }
2663                         if( !ep ) ep = "und";
2664                         char lang[5];
2665                         strncpy(lang,ep,3);  lang[3] = 0;
2666                         AVStream *st = ffaudio[0]->st;
2667                         av_dict_set(&st->metadata,"language",lang,0);
2668                 }
2669
2670                 AVDictionary *fopts = 0;
2671                 char option_path[BCTEXTLEN];
2672                 set_option_path(option_path, "format/%s", file_format);
2673                 read_options(option_path, fopts, 1);
2674                 ret = avformat_write_header(fmt_ctx, &fopts);
2675                 if( ret < 0 ) {
2676                         ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
2677                                 fmt_ctx->url);
2678                         return -1;
2679                 }
2680                 av_dict_free(&fopts);
2681                 encoding = 1;
2682         }
2683         return encoding;
2684 }
2685
2686
2687 int FFMPEG::audio_seek(int stream, int64_t pos)
2688 {
2689         int aidx = astrm_index[stream].st_idx;
2690         FFAudioStream *aud = ffaudio[aidx];
2691         aud->audio_seek(pos);
2692         return 0;
2693 }
2694
2695 int FFMPEG::video_seek(int stream, int64_t pos)
2696 {
2697         int vidx = vstrm_index[stream].st_idx;
2698         FFVideoStream *vid = ffvideo[vidx];
2699         vid->video_seek(pos);
2700         return 0;
2701 }
2702
2703
2704 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
2705 {
2706         if( !has_audio || chn >= astrm_index.size() ) return -1;
2707         int aidx = astrm_index[chn].st_idx;
2708         FFAudioStream *aud = ffaudio[aidx];
2709         if( aud->load(pos, len) < len ) return -1;
2710         int ch = astrm_index[chn].st_ch;
2711         int ret = aud->read(samples,len,ch);
2712         return ret;
2713 }
2714
2715 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
2716 {
2717         if( !has_video || layer >= vstrm_index.size() ) return -1;
2718         int vidx = vstrm_index[layer].st_idx;
2719         FFVideoStream *vid = ffvideo[vidx];
2720         return vid->load(vframe, pos);
2721 }
2722
2723
2724 int FFMPEG::encode(int stream, double **samples, int len)
2725 {
2726         FFAudioStream *aud = ffaudio[stream];
2727         return aud->encode(samples, len);
2728 }
2729
2730
2731 int FFMPEG::encode(int stream, VFrame *frame)
2732 {
2733         FFVideoStream *vid = ffvideo[stream];
2734         return vid->encode(frame);
2735 }
2736
2737 void FFMPEG::start_muxer()
2738 {
2739         if( !running() ) {
2740                 done = 0;
2741                 start();
2742         }
2743 }
2744
2745 void FFMPEG::stop_muxer()
2746 {
2747         if( running() ) {
2748                 done = 1;
2749                 mux_lock->unlock();
2750         }
2751         join();
2752 }
2753
2754 void FFMPEG::flow_off()
2755 {
2756         if( !flow ) return;
2757         flow_lock->lock("FFMPEG::flow_off");
2758         flow = 0;
2759 }
2760
2761 void FFMPEG::flow_on()
2762 {
2763         if( flow ) return;
2764         flow = 1;
2765         flow_lock->unlock();
2766 }
2767
2768 void FFMPEG::flow_ctl()
2769 {
2770         while( !flow ) {
2771                 flow_lock->lock("FFMPEG::flow_ctl");
2772                 flow_lock->unlock();
2773         }
2774 }
2775
2776 int FFMPEG::mux_audio(FFrame *frm)
2777 {
2778         FFStream *fst = frm->fst;
2779         AVCodecContext *ctx = fst->avctx;
2780         AVFrame *frame = *frm;
2781         AVRational tick_rate = {1, ctx->sample_rate};
2782         frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
2783         int ret = fst->encode_frame(frame);
2784         if( ret < 0 )
2785                 ff_err(ret, "FFMPEG::mux_audio");
2786         return ret >= 0 ? 0 : 1;
2787 }
2788
2789 int FFMPEG::mux_video(FFrame *frm)
2790 {
2791         FFStream *fst = frm->fst;
2792         AVFrame *frame = *frm;
2793         frame->pts = frm->position;
2794         int ret = fst->encode_frame(frame);
2795         if( ret < 0 )
2796                 ff_err(ret, "FFMPEG::mux_video");
2797         return ret >= 0 ? 0 : 1;
2798 }
2799
2800 void FFMPEG::mux()
2801 {
2802         for(;;) {
2803                 double atm = -1, vtm = -1;
2804                 FFrame *afrm = 0, *vfrm = 0;
2805                 int demand = 0;
2806                 for( int i=0; i<ffaudio.size(); ++i ) {  // earliest audio
2807                         FFStream *fst = ffaudio[i];
2808                         if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
2809                         FFrame *frm = fst->frms.first;
2810                         if( !frm ) { if( !done ) return; continue; }
2811                         double tm = to_secs(frm->position, fst->avctx->time_base);
2812                         if( atm < 0 || tm < atm ) { atm = tm;  afrm = frm; }
2813                 }
2814                 for( int i=0; i<ffvideo.size(); ++i ) {  // earliest video
2815                         FFStream *fst = ffvideo[i];
2816                         if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
2817                         FFrame *frm = fst->frms.first;
2818                         if( !frm ) { if( !done ) return; continue; }
2819                         double tm = to_secs(frm->position, fst->avctx->time_base);
2820                         if( vtm < 0 || tm < vtm ) { vtm = tm;  vfrm = frm; }
2821                 }
2822                 if( !demand ) flow_off();
2823                 if( !afrm && !vfrm ) break;
2824                 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
2825                         vfrm->position, vfrm->fst->avctx->time_base,
2826                         afrm->position, afrm->fst->avctx->time_base);
2827                 FFrame *frm = v <= 0 ? vfrm : afrm;
2828                 if( frm == afrm ) mux_audio(frm);
2829                 if( frm == vfrm ) mux_video(frm);
2830                 frm->dequeue();
2831                 delete frm;
2832         }
2833 }
2834
2835 void FFMPEG::run()
2836 {
2837         while( !done ) {
2838                 mux_lock->lock("FFMPEG::run");
2839                 if( !done ) mux();
2840         }
2841         for( int i=0; i<ffaudio.size(); ++i )
2842                 ffaudio[i]->drain();
2843         for( int i=0; i<ffvideo.size(); ++i )
2844                 ffvideo[i]->drain();
2845         mux();
2846         for( int i=0; i<ffaudio.size(); ++i )
2847                 ffaudio[i]->flush();
2848         for( int i=0; i<ffvideo.size(); ++i )
2849                 ffvideo[i]->flush();
2850 }
2851
2852
2853 int FFMPEG::ff_total_audio_channels()
2854 {
2855         return astrm_index.size();
2856 }
2857
2858 int FFMPEG::ff_total_astreams()
2859 {
2860         return ffaudio.size();
2861 }
2862
2863 int FFMPEG::ff_audio_channels(int stream)
2864 {
2865         return ffaudio[stream]->channels;
2866 }
2867
2868 int FFMPEG::ff_sample_rate(int stream)
2869 {
2870         return ffaudio[stream]->sample_rate;
2871 }
2872
2873 const char* FFMPEG::ff_audio_format(int stream)
2874 {
2875         AVStream *st = ffaudio[stream]->st;
2876         AVCodecID id = st->codecpar->codec_id;
2877         const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2878         return desc ? desc->name : _("Unknown");
2879 }
2880
2881 int FFMPEG::ff_audio_pid(int stream)
2882 {
2883         return ffaudio[stream]->st->id;
2884 }
2885
2886 int64_t FFMPEG::ff_audio_samples(int stream)
2887 {
2888         return ffaudio[stream]->length;
2889 }
2890
2891 // find audio astream/channels with this program,
2892 //   or all program audio channels (astream=-1)
2893 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
2894 {
2895         channel_mask = 0;
2896         int pidx = -1;
2897         int vidx = ffvideo[vstream]->fidx;
2898         // find first program with this video stream
2899         for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
2900                 AVProgram *pgrm = fmt_ctx->programs[i];
2901                 for( int j=0;  pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
2902                         int st_idx = pgrm->stream_index[j];
2903                         AVStream *st = fmt_ctx->streams[st_idx];
2904                         if( st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
2905                         if( st_idx == vidx ) pidx = i;
2906                 }
2907         }
2908         if( pidx < 0 ) return -1;
2909         int ret = -1;
2910         int64_t channels = 0;
2911         AVProgram *pgrm = fmt_ctx->programs[pidx];
2912         for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2913                 int aidx = pgrm->stream_index[j];
2914                 AVStream *st = fmt_ctx->streams[aidx];
2915                 if( st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
2916                 if( astream > 0 ) { --astream;  continue; }
2917                 int astrm = -1;
2918                 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
2919                         if( ffaudio[i]->fidx == aidx ) astrm = i;
2920                 if( astrm >= 0 ) {
2921                         if( ret < 0 ) ret = astrm;
2922                         int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
2923                         channels |= mask << ffaudio[astrm]->channel0;
2924                 }
2925                 if( !astream ) break;
2926         }
2927         channel_mask = channels;
2928         return ret;
2929 }
2930
2931
2932 int FFMPEG::ff_total_video_layers()
2933 {
2934         return vstrm_index.size();
2935 }
2936
2937 int FFMPEG::ff_total_vstreams()
2938 {
2939         return ffvideo.size();
2940 }
2941
2942 int FFMPEG::ff_video_width(int stream)
2943 {
2944         return ffvideo[stream]->width;
2945 }
2946
2947 int FFMPEG::ff_video_height(int stream)
2948 {
2949         return ffvideo[stream]->height;
2950 }
2951
2952 int FFMPEG::ff_set_video_width(int stream, int width)
2953 {
2954         int w = ffvideo[stream]->width;
2955         ffvideo[stream]->width = width;
2956         return w;
2957 }
2958
2959 int FFMPEG::ff_set_video_height(int stream, int height)
2960 {
2961         int h = ffvideo[stream]->height;
2962         ffvideo[stream]->height = height;
2963         return h;
2964 }
2965
2966 int FFMPEG::ff_coded_width(int stream)
2967 {
2968         return ffvideo[stream]->avctx->coded_width;
2969 }
2970
2971 int FFMPEG::ff_coded_height(int stream)
2972 {
2973         return ffvideo[stream]->avctx->coded_height;
2974 }
2975
2976 float FFMPEG::ff_aspect_ratio(int stream)
2977 {
2978         return ffvideo[stream]->aspect_ratio;
2979 }
2980
2981 const char* FFMPEG::ff_video_format(int stream)
2982 {
2983         AVStream *st = ffvideo[stream]->st;
2984         AVCodecID id = st->codecpar->codec_id;
2985         const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2986         return desc ? desc->name : _("Unknown");
2987 }
2988
2989 double FFMPEG::ff_frame_rate(int stream)
2990 {
2991         return ffvideo[stream]->frame_rate;
2992 }
2993
2994 int64_t FFMPEG::ff_video_frames(int stream)
2995 {
2996         return ffvideo[stream]->length;
2997 }
2998
2999 int FFMPEG::ff_video_pid(int stream)
3000 {
3001         return ffvideo[stream]->st->id;
3002 }
3003
3004 int FFMPEG::ff_video_mpeg_color_range(int stream)
3005 {
3006         return ffvideo[stream]->st->codecpar->color_range == AVCOL_RANGE_MPEG ? 1 : 0;
3007 }
3008
3009 int FFMPEG::ff_cpus()
3010 {
3011         return file_base->file->cpus;
3012 }
3013
3014 const char *FFMPEG::ff_hw_dev()
3015 {
3016         return &file_base->file->preferences->use_hw_dev[0];
3017 }
3018
3019 int FFVideoStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
3020 {
3021         avfilter_register_all();
3022         const char *sp = filter_spec;
3023         char filter_name[BCSTRLEN], *np = filter_name;
3024         int i = sizeof(filter_name);
3025         while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
3026         *np = 0;
3027         const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
3028         if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_VIDEO ) {
3029                 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
3030                 return -1;
3031         }
3032         filter_graph = avfilter_graph_alloc();
3033         const AVFilter *buffersrc = avfilter_get_by_name("buffer");
3034         const AVFilter *buffersink = avfilter_get_by_name("buffersink");
3035
3036         int ret = 0;  char args[BCTEXTLEN];
3037         AVPixelFormat pix_fmt = (AVPixelFormat)avpar->format;
3038         snprintf(args, sizeof(args),
3039                 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
3040                 avpar->width, avpar->height, (int)pix_fmt,
3041                 st->time_base.num, st->time_base.den,
3042                 avpar->sample_aspect_ratio.num, avpar->sample_aspect_ratio.den);
3043         if( ret >= 0 )
3044                 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
3045                         args, NULL, filter_graph);
3046         if( ret >= 0 )
3047                 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
3048                         NULL, NULL, filter_graph);
3049         if( ret >= 0 )