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