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