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