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