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