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