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