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