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