12 // work arounds (centos)
15 #define INT64_MAX 9223372036854775807LL
17 #define MAX_RETRY 1000
18 // max pts/curr_pos drift allowed before correction (in seconds)
19 #define AUDIO_PTS_TOLERANCE 0.04
22 #include "bccmodels.h"
25 #include "edlsession.h"
27 #include "fileffmpeg.h"
28 #include "filesystem.h"
30 #include "indexfile.h"
31 #include "interlacemodes.h"
34 #include "mainerror.h"
36 #include "preferences.h"
42 #define av_register_all(s)
43 #define avfilter_register_all(s)
46 #define VIDEO_INBUF_SIZE 0x10000
47 #define AUDIO_INBUF_SIZE 0x10000
48 #define VIDEO_REFILL_THRESH 0
49 #define AUDIO_REFILL_THRESH 0x1000
50 #define AUDIO_MIN_FRAME_SZ 128
52 #define FF_ESTM_TIMES 0x0001
53 #define FF_BAD_TIMES 0x0002
55 Mutex FFMPEG::fflock("FFMPEG::fflock");
57 static void ff_err(int ret, const char *fmt, ...)
62 vsnprintf(msg, sizeof(msg), fmt, ap);
64 char errmsg[BCSTRLEN];
65 av_strerror(ret, errmsg, sizeof(errmsg));
66 fprintf(stderr,_("%s err: %s\n"),msg, errmsg);
72 pkt.data = 0; pkt.size = 0;
74 void FFPacket::finit()
76 av_packet_unref(&pkt);
79 FFrame::FFrame(FFStream *fst)
82 frm = av_frame_alloc();
83 init = fst->init_frame(frm);
91 void FFrame::queue(int64_t pos)
97 void FFrame::dequeue()
102 void FFrame::set_hw_frame(AVFrame *frame)
108 int FFAudioStream::read(float *fp, long len)
116 while( --k >= 0 ) *fp++ = *op++;
117 if( op >= lmt ) op = bfr;
122 void FFAudioStream::realloc(long nsz, int nch, long len)
124 long bsz = nsz * nch;
125 float *np = new float[bsz];
126 inp = np + read(np, len) * nch;
131 delete [] bfr; bfr = np;
134 void FFAudioStream::realloc(long nsz, int nch)
136 if( nsz > sz || this->nch != nch ) {
137 long len = this->nch != nch ? 0 : hpos;
138 if( len > sz ) len = sz;
140 realloc(nsz, nch, len);
144 void FFAudioStream::reserve(long nsz, int nch)
146 long len = (inp - outp) / nch;
148 if( nsz > sz || this->nch != nch ) {
149 if( this->nch != nch ) len = 0;
150 realloc(nsz, nch, len);
153 if( (len*=nch) > 0 && bfr != outp )
154 memmove(bfr, outp, len*sizeof(*bfr));
159 long FFAudioStream::used()
161 long len = inp>=outp ? inp-outp : inp-bfr + lmt-outp;
164 long FFAudioStream::avail()
167 if( in1 >= lmt ) in1 = bfr;
168 long len = outp >= in1 ? outp-in1 : outp-bfr + lmt-in1;
171 void FFAudioStream::reset_history()
175 memset(bfr, 0, lmt-bfr);
178 void FFAudioStream::iseek(int64_t ofs)
180 if( ofs > hpos ) ofs = hpos;
181 if( ofs > sz ) ofs = sz;
182 outp = inp - ofs*nch;
183 if( outp < bfr ) outp += sz*nch;
186 float *FFAudioStream::get_outp(int ofs)
193 int64_t FFAudioStream::put_inp(int ofs)
196 return (inp-outp) / nch;
199 int FFAudioStream::write(const float *fp, long len)
207 while( --k >= 0 ) *ip++ = *fp++;
208 if( ip >= lmt ) ip = bfr;
215 int FFAudioStream::zero(long len)
223 while( --k >= 0 ) *ip++ = 0;
224 if( ip >= lmt ) ip = bfr;
231 // does not advance outp
232 int FFAudioStream::read(double *dp, long len, int ch)
235 float *op = outp + ch;
236 float *lmt1 = lmt + nch-1;
238 int k = (lmt1 - op) / nch;
241 while( --k >= 0 ) { *dp++ = *op; op += nch; }
242 if( op >= lmt ) op -= sz*nch;
247 // load linear buffer, no wrapping allowed, does not advance inp
248 int FFAudioStream::write(const double *dp, long len, int ch)
251 float *ip = inp + ch;
252 while( --n >= 0 ) { *ip = *dp++; ip += nch; }
257 FFStream::FFStream(FFMPEG *ffmpeg, AVStream *st, int fidx)
259 this->ffmpeg = ffmpeg;
262 frm_lock = new Mutex("FFStream::frm_lock");
269 nudge = AV_NOPTS_VALUE;
270 seek_pos = curr_pos = 0;
272 reading = writing = 0;
273 hw_pixfmt = AV_PIX_FMT_NONE;
285 FFStream::~FFStream()
287 if( reading > 0 || writing > 0 ) avcodec_close(avctx);
288 if( avctx ) avcodec_free_context(&avctx);
289 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
290 if( hw_device_ctx ) av_buffer_unref(&hw_device_ctx);
291 if( bsfc ) av_bsf_free(&bsfc);
292 while( frms.first ) frms.remove(frms.first);
293 if( filter_graph ) avfilter_graph_free(&filter_graph);
294 if( frame ) av_frame_free(&frame);
295 if( fframe ) av_frame_free(&fframe);
297 if( stats_fp ) fclose(stats_fp);
298 if( stats_in ) av_freep(&stats_in);
299 delete [] stats_filename;
302 void FFStream::ff_lock(const char *cp)
304 FFMPEG::fflock.lock(cp);
307 void FFStream::ff_unlock()
309 FFMPEG::fflock.unlock();
312 void FFStream::queue(FFrame *frm)
314 frm_lock->lock("FFStream::queue");
318 ffmpeg->mux_lock->unlock();
321 void FFStream::dequeue(FFrame *frm)
323 frm_lock->lock("FFStream::dequeue");
325 frms.remove_pointer(frm);
329 int FFStream::encode_activate()
332 writing = ffmpeg->encode_activate();
336 static AVPixelFormat hw_pix_fmt = AV_PIX_FMT_NONE; // protected by ff_lock
337 static enum AVPixelFormat get_hw_format(AVCodecContext *ctx,
338 const enum AVPixelFormat *pix_fmts)
340 for( const enum AVPixelFormat *p=pix_fmts; *p!=AV_PIX_FMT_NONE; ++p )
341 if( *p == hw_pix_fmt ) return *p;
342 fprintf(stderr, "Failed to get HW surface format.\n");
343 return hw_pix_fmt = AV_PIX_FMT_NONE;
347 AVHWDeviceType FFStream::decode_hw_activate()
349 return AV_HWDEVICE_TYPE_NONE;
352 int FFStream::decode_hw_format(AVCodec *decoder, AVHWDeviceType type)
357 int FFStream::decode_activate()
359 if( reading < 0 && (reading=ffmpeg->decode_activate()) > 0 ) {
360 ff_lock("FFStream::decode_activate");
362 AVDictionary *copts = 0;
363 av_dict_copy(&copts, ffmpeg->opts, 0);
365 AVHWDeviceType hw_type = decode_hw_activate();
367 // this should be avformat_copy_context(), but no copy avail
368 ret = avformat_open_input(&fmt_ctx,
369 ffmpeg->fmt_ctx->url, ffmpeg->fmt_ctx->iformat, &copts);
371 ret = avformat_find_stream_info(fmt_ctx, 0);
372 st = fmt_ctx->streams[fidx];
375 while( ret >= 0 && st != 0 && !reading ) {
376 AVCodecID codec_id = st->codecpar->codec_id;
377 AVCodec *decoder = avcodec_find_decoder(codec_id);
378 avctx = avcodec_alloc_context3(decoder);
380 eprintf(_("cant allocate codec context\n"));
381 ret = AVERROR(ENOMEM);
383 if( ret >= 0 && hw_type != AV_HWDEVICE_TYPE_NONE ) {
384 ret = decode_hw_format(decoder, hw_type);
385 if( !ret ) hw_type = AV_HWDEVICE_TYPE_NONE;
388 avcodec_parameters_to_context(avctx, st->codecpar);
389 if( !av_dict_get(copts, "threads", NULL, 0) )
390 avctx->thread_count = ffmpeg->ff_cpus();
391 ret = avcodec_open2(avctx, decoder, &copts);
393 if( ret >= 0 && hw_type != AV_HWDEVICE_TYPE_NONE ) {
399 AVPacket *pkt = (AVPacket*)ipkt;
400 ret = avcodec_send_packet(avctx, pkt);
401 if( ret < 0 || hw_pix_fmt == AV_PIX_FMT_NONE ) {
402 ff_err(ret, "HW device init failed, using SW decode.\nfile:%s\n",
403 ffmpeg->fmt_ctx->url);
404 avcodec_close(avctx);
405 avcodec_free_context(&avctx);
406 av_buffer_unref(&hw_device_ctx);
408 hw_type = AV_HWDEVICE_TYPE_NONE;
409 int flags = AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_ANY;
411 av_seek_frame(fmt_ctx, idx, INT64_MIN, flags);
412 need_packet = 1; flushed = 0;
413 seeked = 1; st_eof(0);
423 eprintf(_("open decoder failed\n"));
426 eprintf(_("can't open input file: %s\n"), ffmpeg->fmt_ctx->url);
427 av_dict_free(&copts);
433 int FFStream::read_packet()
435 av_packet_unref(ipkt);
436 int ret = av_read_frame(fmt_ctx, ipkt);
439 if( ret == AVERROR_EOF ) return 0;
440 ff_err(ret, "FFStream::read_packet: av_read_frame failed\n");
447 int FFStream::decode(AVFrame *frame)
450 int retries = MAX_RETRY;
452 while( ret >= 0 && !flushed && --retries >= 0 ) {
454 if( (ret=read_packet()) < 0 ) break;
455 AVPacket *pkt = ret > 0 ? (AVPacket*)ipkt : 0;
457 if( pkt->stream_index != st->index ) continue;
458 if( !pkt->data | !pkt->size ) continue;
460 if( (ret=avcodec_send_packet(avctx, pkt)) < 0 ) {
461 ff_err(ret, "FFStream::decode: avcodec_send_packet failed.\nfile:%s\n",
462 ffmpeg->fmt_ctx->url);
468 if( (ret=decode_frame(frame)) > 0 ) break;
476 fprintf(stderr, "FFStream::decode: Retry limit\n");
480 fprintf(stderr, "FFStream::decode: failed\n");
484 int FFStream::load_filter(AVFrame *frame)
486 int ret = av_buffersrc_add_frame_flags(buffersrc_ctx, frame, 0);
488 eprintf(_("av_buffersrc_add_frame_flags failed\n"));
492 int FFStream::read_filter(AVFrame *frame)
494 int ret = av_buffersink_get_frame(buffersink_ctx, frame);
496 if( ret == AVERROR(EAGAIN) ) return 0;
497 if( ret == AVERROR_EOF ) { st_eof(1); return -1; }
498 ff_err(ret, "FFStream::read_filter: av_buffersink_get_frame failed\n");
504 int FFStream::read_frame(AVFrame *frame)
506 av_frame_unref(frame);
507 if( !filter_graph || !buffersrc_ctx || !buffersink_ctx )
508 return decode(frame);
509 if( !fframe && !(fframe=av_frame_alloc()) ) {
510 fprintf(stderr, "FFStream::read_frame: av_frame_alloc failed\n");
514 while( !flushed && !(ret=read_filter(frame)) ) {
515 if( (ret=decode(fframe)) < 0 ) break;
516 if( ret > 0 && (ret=load_filter(fframe)) < 0 ) break;
521 int FFStream::write_packet(FFPacket &pkt)
525 av_packet_rescale_ts(pkt, avctx->time_base, st->time_base);
526 pkt->stream_index = st->index;
527 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, pkt);
530 ret = av_bsf_send_packet(bsfc, pkt);
533 if( (ret=av_bsf_receive_packet(bsfc, bs)) < 0 ) {
534 if( ret == AVERROR(EAGAIN) ) return 0;
535 if( ret == AVERROR_EOF ) return -1;
538 av_packet_rescale_ts(bs, avctx->time_base, st->time_base);
539 bs->stream_index = st->index;
540 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, bs);
544 ff_err(ret, "FFStream::write_packet: write packet failed.\nfile:%s\n",
545 ffmpeg->fmt_ctx->url);
549 int FFStream::encode_frame(AVFrame *frame)
551 int pkts = 0, ret = 0;
552 for( int retry=MAX_RETRY; --retry>=0; ) {
554 ret = avcodec_send_frame(avctx, frame);
555 if( !ret && frame ) return pkts;
556 if( ret < 0 && ret != AVERROR(EAGAIN) ) break;
558 ret = avcodec_receive_packet(avctx, opkt);
559 if( !frame && ret == AVERROR_EOF ) return pkts;
561 ret = write_packet(opkt);
564 if( frame && stats_fp ) {
565 ret = write_stats_file();
569 ff_err(ret, "FFStream::encode_frame: encode failed.\nfile: %s\n",
570 ffmpeg->fmt_ctx->url);
574 int FFStream::flush()
578 int ret = encode_frame(0);
579 if( ret >= 0 && stats_fp ) {
580 ret = write_stats_file();
584 ff_err(ret, "FFStream::flush failed\n:file:%s\n",
585 ffmpeg->fmt_ctx->url);
586 return ret >= 0 ? 0 : 1;
590 int FFStream::open_stats_file()
592 stats_fp = fopen(stats_filename,"w");
593 return stats_fp ? 0 : AVERROR(errno);
596 int FFStream::close_stats_file()
599 fclose(stats_fp); stats_fp = 0;
604 int FFStream::read_stats_file()
606 int64_t len = 0; struct stat stats_st;
607 int fd = open(stats_filename, O_RDONLY);
608 int ret = fd >= 0 ? 0: ENOENT;
609 if( !ret && fstat(fd, &stats_st) )
612 len = stats_st.st_size;
613 stats_in = (char *)av_malloc(len+1);
617 if( !ret && read(fd, stats_in, len+1) != len )
621 avctx->stats_in = stats_in;
625 return !ret ? 0 : AVERROR(ret);
628 int FFStream::write_stats_file()
631 if( avctx->stats_out && (ret=strlen(avctx->stats_out)) > 0 ) {
632 int len = fwrite(avctx->stats_out, 1, ret, stats_fp);
634 ff_err(ret = AVERROR(errno), "FFStream::write_stats_file.\n%file:%s\n",
635 ffmpeg->fmt_ctx->url);
640 int FFStream::init_stats_file()
643 if( (pass & 2) && (ret = read_stats_file()) < 0 )
644 ff_err(ret, "stat file read: %s", stats_filename);
645 if( (pass & 1) && (ret=open_stats_file()) < 0 )
646 ff_err(ret, "stat file open: %s", stats_filename);
647 return ret >= 0 ? 0 : ret;
650 int FFStream::seek(int64_t no, double rate)
652 // default ffmpeg native seek
654 int64_t pos = no, pkt_pos = -1;
655 IndexMarks *index_markers = get_markers();
656 if( index_markers && index_markers->size() > 1 ) {
657 IndexMarks &marks = *index_markers;
658 int i = marks.find(pos);
659 int64_t n = i < 0 ? (i=0) : marks[i].no;
660 // if indexed seek point not too far away (<30 secs), use index
661 if( no-n < 30*rate ) {
664 if( i < marks.size() ) pkt_pos = marks[i].pos;
668 if( pos == curr_pos ) return 0;
669 double secs = pos < 0 ? 0. : pos / rate;
670 AVRational time_base = st->time_base;
671 int64_t tstmp = time_base.num > 0 ? secs * time_base.den/time_base.num : 0;
673 if( st->nb_index_entries > 0 ) tstmp = st->index_entries[0].timestamp;
674 else if( st->start_time != AV_NOPTS_VALUE ) tstmp = st->start_time;
675 else if( st->first_dts != AV_NOPTS_VALUE ) tstmp = st->first_dts;
676 else tstmp = INT64_MIN+1;
678 else if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
681 // seek all streams using the default timebase.
682 // this is how ffmpeg and ffplay work. stream seeks are less tested.
683 tstmp = av_rescale_q(tstmp, time_base, AV_TIME_BASE_Q);
687 avcodec_flush_buffers(avctx);
688 avformat_flush(fmt_ctx);
690 int64_t seek = tstmp;
691 int flags = AVSEEK_FLAG_ANY;
692 if( !(fmt_ctx->iformat->flags & AVFMT_NO_BYTE_SEEK) && pkt_pos >= 0 ) {
694 flags = AVSEEK_FLAG_BYTE;
696 int ret = avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, seek, INT64_MAX, flags);
698 // finds the first index frame below the target time
699 int flags = AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_ANY;
700 int ret = av_seek_frame(fmt_ctx, idx, tstmp, flags);
702 int retry = MAX_RETRY;
704 need_packet = 0; flushed = 0;
705 seeked = 1; st_eof(0);
706 // read up to retry packets, limited to npkts in stream, and not pkt.pos past pkt_pos
707 while( --retry >= 0 ) {
708 if( read_packet() <= 0 ) { ret = -1; break; }
709 if( ipkt->stream_index != st->index ) continue;
710 if( !ipkt->data || !ipkt->size ) continue;
711 if( pkt_pos >= 0 && ipkt->pos >= pkt_pos ) break;
712 if( --npkts <= 0 ) break;
713 int64_t pkt_ts = ipkt->dts != AV_NOPTS_VALUE ? ipkt->dts : ipkt->pts;
714 if( pkt_ts == AV_NOPTS_VALUE ) continue;
715 if( pkt_ts >= tstmp ) break;
718 fprintf(stderr,"FFStream::seek: retry limit, pos=%jd tstmp=%jd\n",pos,tstmp);
722 ret = avcodec_send_packet(avctx, ipkt);
724 //some codecs need more than one pkt to resync
725 if( ret == AVERROR_INVALIDDATA ) ret = 0;
727 ff_err(ret, "FFStream::avcodec_send_packet failed.\nseek:%s\n",
728 ffmpeg->fmt_ctx->url);
733 printf("** seek fail %jd, %jd\n", pos, tstmp);
734 seeked = need_packet = 0;
738 //printf("seeked pos = %ld, %ld\n", pos, tstmp);
739 seek_pos = curr_pos = pos;
743 FFAudioStream::FFAudioStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
744 : FFStream(ffmpeg, strm, fidx)
747 channel0 = channels = 0;
750 frame_sz = AUDIO_MIN_FRAME_SZ;
752 resample_context = 0;
753 swr_ichs = swr_ifmt = swr_irate = 0;
762 bfr = new float[bsz];
767 FFAudioStream::~FFAudioStream()
769 if( resample_context ) swr_free(&resample_context);
774 void FFAudioStream::init_swr(int ichs, int ifmt, int irate)
776 if( resample_context ) {
777 if( swr_ichs == ichs && swr_ifmt == ifmt && swr_irate == irate )
779 swr_free(&resample_context);
781 swr_ichs = ichs; swr_ifmt = ifmt; swr_irate = irate;
782 if( ichs == channels && ifmt == AV_SAMPLE_FMT_FLT && irate == sample_rate )
784 uint64_t ilayout = av_get_default_channel_layout(ichs);
785 if( !ilayout ) ilayout = ((uint64_t)1<<ichs) - 1;
786 uint64_t olayout = av_get_default_channel_layout(channels);
787 if( !olayout ) olayout = ((uint64_t)1<<channels) - 1;
788 resample_context = swr_alloc_set_opts(NULL,
789 olayout, AV_SAMPLE_FMT_FLT, sample_rate,
790 ilayout, (AVSampleFormat)ifmt, irate,
792 if( resample_context )
793 swr_init(resample_context);
796 int FFAudioStream::get_samples(float *&samples, uint8_t **data, int len)
798 samples = *(float **)data;
799 if( resample_context ) {
800 if( len > aud_bfr_sz ) {
806 aud_bfr = new float[aud_bfr_sz*channels];
808 int ret = swr_convert(resample_context,
809 (uint8_t**)&aud_bfr, aud_bfr_sz, (const uint8_t**)data, len);
811 ff_err(ret, "FFAudioStream::get_samples: swr_convert failed\n");
820 int FFAudioStream::load_history(uint8_t **data, int len)
823 len = get_samples(samples, data, len);
825 // biggest user bfr since seek + frame
826 realloc(mbsz + len + 1, channels);
832 int FFAudioStream::decode_frame(AVFrame *frame)
834 int first_frame = seeked; seeked = 0;
835 frame->best_effort_timestamp = AV_NOPTS_VALUE;
836 int ret = avcodec_receive_frame(avctx, frame);
838 if( first_frame || ret == AVERROR(EAGAIN) ) return 0;
839 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
840 ff_err(ret, "FFAudioStream::decode_frame: Could not read audio frame.\nfile:%s\n",
841 ffmpeg->fmt_ctx->url);
844 int64_t pkt_ts = frame->best_effort_timestamp;
845 if( pkt_ts != AV_NOPTS_VALUE ) {
846 double ts = ffmpeg->to_secs(pkt_ts - nudge, st->time_base);
847 double t = (double)curr_pos / sample_rate;
848 // some time_base clocks are very grainy, too grainy for audio (clicks, pops)
849 if( fabs(ts - t) > AUDIO_PTS_TOLERANCE )
850 curr_pos = ts * sample_rate + 0.5;
855 int FFAudioStream::encode_activate()
857 if( writing >= 0 ) return writing;
858 if( !avctx->codec ) return writing = 0;
859 frame_sz = avctx->codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE ?
860 10000 : avctx->frame_size;
861 return FFStream::encode_activate();
864 int64_t FFAudioStream::load_buffer(double ** const sp, int len)
866 reserve(len+1, st->codecpar->channels);
867 for( int ch=0; ch<nch; ++ch )
868 write(sp[ch], len, ch);
872 int FFAudioStream::in_history(int64_t pos)
874 if( pos > curr_pos ) return 0;
876 if( len > sz ) len = sz;
877 if( pos < curr_pos - len ) return 0;
882 int FFAudioStream::init_frame(AVFrame *frame)
884 frame->nb_samples = frame_sz;
885 frame->format = avctx->sample_fmt;
886 frame->channel_layout = avctx->channel_layout;
887 frame->sample_rate = avctx->sample_rate;
888 int ret = av_frame_get_buffer(frame, 0);
890 ff_err(ret, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
894 int FFAudioStream::load(int64_t pos, int len)
896 if( audio_seek(pos) < 0 ) return -1;
897 if( !frame && !(frame=av_frame_alloc()) ) {
898 fprintf(stderr, "FFAudioStream::load: av_frame_alloc failed\n");
901 if( mbsz < len ) mbsz = len;
902 int64_t end_pos = pos + len;
903 int ret = 0, i = len / frame_sz + MAX_RETRY;
904 while( ret>=0 && !flushed && curr_pos<end_pos && --i>=0 ) {
905 ret = read_frame(frame);
906 if( ret > 0 && frame->nb_samples > 0 ) {
907 init_swr(frame->channels, frame->format, frame->sample_rate);
908 load_history(&frame->extended_data[0], frame->nb_samples);
909 curr_pos += frame->nb_samples;
912 if( end_pos > curr_pos ) {
913 zero(end_pos - curr_pos);
916 len = curr_pos - pos;
921 int FFAudioStream::audio_seek(int64_t pos)
923 if( decode_activate() <= 0 ) return -1;
924 if( !st->codecpar ) return -1;
925 if( in_history(pos) ) return 0;
926 if( pos == curr_pos ) return 0;
927 reset_history(); mbsz = 0;
928 // guarentee preload > 1sec samples
929 if( (pos-=sample_rate) < 0 ) pos = 0;
930 if( seek(pos, sample_rate) < 0 ) return -1;
934 int FFAudioStream::encode(double **samples, int len)
936 if( encode_activate() <= 0 ) return -1;
939 int64_t count = samples ? load_buffer(samples, len) : used();
940 int frame_sz1 = samples ? frame_sz-1 : 0;
943 while( ret >= 0 && count > frame_sz1 ) {
944 frm = new FFrame(this);
945 if( (ret=frm->initted()) < 0 ) break;
946 AVFrame *frame = *frm;
947 len = count >= frame_sz ? frame_sz : count;
948 float *bfrp = get_outp(len);
949 ret = swr_convert(resample_context,
950 (uint8_t **)frame->extended_data, len,
951 (const uint8_t **)&bfrp, len);
953 ff_err(ret, "FFAudioStream::encode: swr_convert failed\n");
956 frame->nb_samples = len;
957 frm->queue(curr_pos);
964 return ret >= 0 ? 0 : 1;
967 int FFAudioStream::drain()
972 int FFAudioStream::encode_frame(AVFrame *frame)
974 return FFStream::encode_frame(frame);
977 int FFAudioStream::write_packet(FFPacket &pkt)
979 return FFStream::write_packet(pkt);
982 void FFAudioStream::load_markers()
984 IndexState *index_state = ffmpeg->file_base->asset->index_state;
985 if( !index_state || idx >= index_state->audio_markers.size() ) return;
986 if( index_state->marker_status == MARKERS_NOTTESTED ) return;
987 FFStream::load_markers(*index_state->audio_markers[idx], sample_rate);
990 IndexMarks *FFAudioStream::get_markers()
992 IndexState *index_state = ffmpeg->file_base->asset->index_state;
993 if( !index_state || idx >= index_state->audio_markers.size() ) return 0;
994 return index_state->audio_markers[idx];
997 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
998 : FFStream(ffmpeg, strm, fidx)
1006 top_field_first = 0;
1009 FFVideoStream::~FFVideoStream()
1013 AVHWDeviceType FFVideoStream::decode_hw_activate()
1015 AVHWDeviceType type = AV_HWDEVICE_TYPE_NONE;
1016 const char *hw_dev = ffmpeg->opt_hw_dev;
1017 if( !hw_dev ) hw_dev = getenv("CIN_HW_DEV");
1018 if( !hw_dev ) hw_dev = ffmpeg->ff_hw_dev();
1019 if( hw_dev && *hw_dev && strcmp(_("none"), hw_dev) ) {
1020 type = av_hwdevice_find_type_by_name(hw_dev);
1021 if( type == AV_HWDEVICE_TYPE_NONE ) {
1022 fprintf(stderr, "Device type %s is not supported.\n", hw_dev);
1023 fprintf(stderr, "Available device types:");
1024 while( (type = av_hwdevice_iterate_types(type)) != AV_HWDEVICE_TYPE_NONE )
1025 fprintf(stderr, " %s", av_hwdevice_get_type_name(type));
1026 fprintf(stderr, "\n");
1032 int FFVideoStream::decode_hw_format(AVCodec *decoder, AVHWDeviceType type)
1035 hw_pix_fmt = AV_PIX_FMT_NONE;
1036 for( int i=0; ; ++i ) {
1037 const AVCodecHWConfig *config = avcodec_get_hw_config(decoder, i);
1039 fprintf(stderr, "Decoder %s does not support device type %s.\n",
1040 decoder->name, av_hwdevice_get_type_name(type));
1043 if( (config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX) != 0 &&
1044 config->device_type == type ) {
1045 hw_pix_fmt = config->pix_fmt;
1049 if( hw_pix_fmt >= 0 ) {
1050 hw_pixfmt = hw_pix_fmt;
1051 avctx->get_format = get_hw_format;
1052 ret = av_hwdevice_ctx_create(&hw_device_ctx, type, 0, 0, 0);
1054 avctx->hw_device_ctx = av_buffer_ref(hw_device_ctx);
1058 ff_err(ret, "Failed HW device create.\ndev:%s\n",
1059 av_hwdevice_get_type_name(type));
1064 AVHWDeviceType FFVideoStream::encode_hw_activate(const char *hw_dev)
1066 AVBufferRef *hw_device_ctx = 0;
1067 AVBufferRef *hw_frames_ref = 0;
1068 AVHWDeviceType type = AV_HWDEVICE_TYPE_NONE;
1069 if( strcmp(_("none"), hw_dev) ) {
1070 type = av_hwdevice_find_type_by_name(hw_dev);
1071 if( type != AV_HWDEVICE_TYPE_VAAPI ) {
1072 fprintf(stderr, "currently, only vaapi hw encode is supported\n");
1073 type = AV_HWDEVICE_TYPE_NONE;
1076 if( type != AV_HWDEVICE_TYPE_NONE ) {
1077 int ret = av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_VAAPI, 0, 0, 0);
1079 ff_err(ret, "Failed to create a HW device.\n");
1080 type = AV_HWDEVICE_TYPE_NONE;
1083 if( type != AV_HWDEVICE_TYPE_NONE ) {
1084 hw_frames_ref = av_hwframe_ctx_alloc(hw_device_ctx);
1085 if( !hw_frames_ref ) {
1086 fprintf(stderr, "Failed to create HW frame context.\n");
1087 type = AV_HWDEVICE_TYPE_NONE;
1090 if( type != AV_HWDEVICE_TYPE_NONE ) {
1091 AVHWFramesContext *frames_ctx = (AVHWFramesContext *)(hw_frames_ref->data);
1092 frames_ctx->format = AV_PIX_FMT_VAAPI;
1093 frames_ctx->sw_format = AV_PIX_FMT_NV12;
1094 frames_ctx->width = width;
1095 frames_ctx->height = height;
1096 frames_ctx->initial_pool_size = 0; // 200;
1097 int ret = av_hwframe_ctx_init(hw_frames_ref);
1099 avctx->hw_frames_ctx = av_buffer_ref(hw_frames_ref);
1100 if( !avctx->hw_frames_ctx ) ret = AVERROR(ENOMEM);
1103 ff_err(ret, "Failed to initialize HW frame context.\n");
1104 type = AV_HWDEVICE_TYPE_NONE;
1106 av_buffer_unref(&hw_frames_ref);
1111 int FFVideoStream::encode_hw_write(FFrame *picture)
1114 AVFrame *hw_frm = 0;
1115 switch( avctx->pix_fmt ) {
1116 case AV_PIX_FMT_VAAPI:
1117 hw_frm = av_frame_alloc();
1118 if( !hw_frm ) { ret = AVERROR(ENOMEM); break; }
1119 ret = av_hwframe_get_buffer(avctx->hw_frames_ctx, hw_frm, 0);
1120 if( ret < 0 ) break;
1121 ret = av_hwframe_transfer_data(hw_frm, *picture, 0);
1122 if( ret < 0 ) break;
1123 picture->set_hw_frame(hw_frm);
1128 av_frame_free(&hw_frm);
1129 ff_err(ret, "Error while transferring frame data to GPU.\n");
1133 int FFVideoStream::decode_frame(AVFrame *frame)
1135 int first_frame = seeked; seeked = 0;
1136 int ret = avcodec_receive_frame(avctx, frame);
1138 if( first_frame || ret == AVERROR(EAGAIN) ) return 0;
1139 if( ret == AVERROR(EAGAIN) ) return 0;
1140 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
1141 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame.\nfile:%s\n,",
1142 ffmpeg->fmt_ctx->url);
1145 int64_t pkt_ts = frame->best_effort_timestamp;
1146 if( pkt_ts != AV_NOPTS_VALUE )
1147 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * frame_rate + 0.5;
1151 int FFVideoStream::load(VFrame *vframe, int64_t pos)
1153 int ret = video_seek(pos);
1154 if( ret < 0 ) return -1;
1155 if( !frame && !(frame=av_frame_alloc()) ) {
1156 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
1159 int i = MAX_RETRY + pos - curr_pos;
1160 while( ret>=0 && !flushed && curr_pos<=pos && --i>=0 ) {
1161 ret = read_frame(frame);
1162 if( ret > 0 ) ++curr_pos;
1164 if( frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0 )
1167 ret = convert_cmodel(vframe, frame);
1169 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
1173 int FFVideoStream::video_seek(int64_t pos)
1175 if( decode_activate() <= 0 ) return -1;
1176 if( !st->codecpar ) return -1;
1177 if( pos == curr_pos-1 && !seeked ) return 0;
1178 // if close enough, just read up to current
1179 int gop = avctx->gop_size;
1180 if( gop < 4 ) gop = 4;
1181 if( gop > 64 ) gop = 64;
1182 int read_limit = curr_pos + 3*gop;
1183 if( pos >= curr_pos && pos <= read_limit ) return 0;
1184 // guarentee preload more than 2*gop frames
1185 if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
1189 int FFVideoStream::init_frame(AVFrame *picture)
1191 switch( avctx->pix_fmt ) {
1192 case AV_PIX_FMT_VAAPI:
1193 picture->format = AV_PIX_FMT_NV12;
1196 picture->format = avctx->pix_fmt;
1199 picture->width = avctx->width;
1200 picture->height = avctx->height;
1201 int ret = av_frame_get_buffer(picture, 32);
1205 int FFVideoStream::encode(VFrame *vframe)
1207 if( encode_activate() <= 0 ) return -1;
1209 FFrame *picture = new FFrame(this);
1210 int ret = picture->initted();
1212 AVFrame *frame = *picture;
1213 frame->pts = curr_pos;
1214 ret = convert_pixfmt(vframe, frame);
1216 if( ret >= 0 && avctx->hw_frames_ctx )
1217 encode_hw_write(picture);
1219 picture->queue(curr_pos);
1223 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
1226 return ret >= 0 ? 0 : 1;
1229 int FFVideoStream::drain()
1234 int FFVideoStream::encode_frame(AVFrame *frame)
1237 frame->interlaced_frame = interlaced;
1238 frame->top_field_first = top_field_first;
1240 return FFStream::encode_frame(frame);
1243 int FFVideoStream::write_packet(FFPacket &pkt)
1245 if( !(ffmpeg->fmt_ctx->oformat->flags & AVFMT_VARIABLE_FPS) )
1247 return FFStream::write_packet(pkt);
1250 AVPixelFormat FFVideoConvert::color_model_to_pix_fmt(int color_model)
1252 switch( color_model ) {
1253 case BC_YUV422: return AV_PIX_FMT_YUYV422;
1254 case BC_RGB888: return AV_PIX_FMT_RGB24;
1255 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
1256 case BC_BGR8888: return AV_PIX_FMT_BGR0;
1257 case BC_BGR888: return AV_PIX_FMT_BGR24;
1258 case BC_ARGB8888: return AV_PIX_FMT_ARGB;
1259 case BC_ABGR8888: return AV_PIX_FMT_ABGR;
1260 case BC_RGB8: return AV_PIX_FMT_RGB8;
1261 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
1262 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
1263 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
1264 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
1265 case BC_RGB565: return AV_PIX_FMT_RGB565;
1266 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
1267 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
1268 case BC_AYUV16161616: return AV_PIX_FMT_AYUV64LE;
1269 case BC_GBRP: return AV_PIX_FMT_GBRP;
1273 return AV_PIX_FMT_NB;
1276 int FFVideoConvert::pix_fmt_to_color_model(AVPixelFormat pix_fmt)
1279 case AV_PIX_FMT_YUYV422: return BC_YUV422;
1280 case AV_PIX_FMT_RGB24: return BC_RGB888;
1281 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
1282 case AV_PIX_FMT_BGR0: return BC_BGR8888;
1283 case AV_PIX_FMT_BGR24: return BC_BGR888;
1284 case AV_PIX_FMT_ARGB: return BC_ARGB8888;
1285 case AV_PIX_FMT_ABGR: return BC_ABGR8888;
1286 case AV_PIX_FMT_RGB8: return BC_RGB8;
1287 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
1288 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
1289 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
1290 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
1291 case AV_PIX_FMT_RGB565: return BC_RGB565;
1292 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
1293 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
1294 case AV_PIX_FMT_AYUV64LE: return BC_AYUV16161616;
1295 case AV_PIX_FMT_GBRP: return BC_GBRP;
1302 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip)
1304 AVFrame *ipic = av_frame_alloc();
1305 int ret = convert_picture_vframe(frame, ip, ipic);
1306 av_frame_free(&ipic);
1310 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip, AVFrame *ipic)
1312 int cmodel = frame->get_color_model();
1313 AVPixelFormat ofmt = color_model_to_pix_fmt(cmodel);
1314 if( ofmt == AV_PIX_FMT_NB ) return -1;
1315 int size = av_image_fill_arrays(ipic->data, ipic->linesize,
1316 frame->get_data(), ofmt, frame->get_w(), frame->get_h(), 1);
1317 if( size < 0 ) return -1;
1319 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1320 int ysz = bpp * frame->get_w(), usz = ysz;
1330 // override av_image_fill_arrays() for planar types
1331 ipic->data[0] = frame->get_y(); ipic->linesize[0] = ysz;
1332 ipic->data[1] = frame->get_u(); ipic->linesize[1] = usz;
1333 ipic->data[2] = frame->get_v(); ipic->linesize[2] = usz;
1336 ipic->data[0] = frame->get_data();
1337 ipic->linesize[0] = frame->get_bytes_per_line();
1341 AVPixelFormat pix_fmt = (AVPixelFormat)ip->format;
1342 FFVideoStream *vid =(FFVideoStream *)this;
1343 if( pix_fmt == vid->hw_pixfmt ) {
1345 if( !sw_frame && !(sw_frame=av_frame_alloc()) )
1346 ret = AVERROR(ENOMEM);
1348 ret = av_hwframe_transfer_data(sw_frame, ip, 0);
1350 pix_fmt = (AVPixelFormat)ip->format;
1353 eprintf(_("Error retrieving data from GPU to CPU\nfile: %s\n"),
1354 vid->ffmpeg->fmt_ctx->url);
1358 convert_ctx = sws_getCachedContext(convert_ctx, ip->width, ip->height, pix_fmt,
1359 frame->get_w(), frame->get_h(), ofmt, SWS_POINT, NULL, NULL, NULL);
1360 if( !convert_ctx ) {
1361 fprintf(stderr, "FFVideoConvert::convert_picture_frame:"
1362 " sws_getCachedContext() failed\n");
1365 int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ip->height,
1366 ipic->data, ipic->linesize);
1368 ff_err(ret, "FFVideoConvert::convert_picture_frame: sws_scale() failed\nfile: %s\n",
1369 vid->ffmpeg->fmt_ctx->url);
1375 int FFVideoConvert::convert_cmodel(VFrame *frame, AVFrame *ip)
1377 // try direct transfer
1378 if( !convert_picture_vframe(frame, ip) ) return 1;
1379 // use indirect transfer
1380 AVPixelFormat ifmt = (AVPixelFormat)ip->format;
1381 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
1383 for( int i = 0; i <desc->nb_components; ++i ) {
1384 int bits = desc->comp[i].depth;
1385 if( bits > max_bits ) max_bits = bits;
1387 int imodel = pix_fmt_to_color_model(ifmt);
1388 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1389 int cmodel = frame->get_color_model();
1390 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1391 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1392 imodel = cmodel_is_yuv ?
1393 (BC_CModels::has_alpha(cmodel) ?
1395 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1396 (BC_CModels::has_alpha(cmodel) ?
1397 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1398 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1400 VFrame vframe(ip->width, ip->height, imodel);
1401 if( convert_picture_vframe(&vframe, ip) ) return -1;
1402 frame->transfer_from(&vframe);
1406 int FFVideoConvert::transfer_cmodel(VFrame *frame, AVFrame *ifp)
1408 int ret = convert_cmodel(frame, ifp);
1410 const AVDictionary *src = ifp->metadata;
1411 AVDictionaryEntry *t = NULL;
1412 BC_Hash *hp = frame->get_params();
1414 while( (t=av_dict_get(src, "", t, AV_DICT_IGNORE_SUFFIX)) )
1415 hp->update(t->key, t->value);
1420 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op)
1422 AVFrame *opic = av_frame_alloc();
1423 int ret = convert_vframe_picture(frame, op, opic);
1424 av_frame_free(&opic);
1428 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op, AVFrame *opic)
1430 int cmodel = frame->get_color_model();
1431 AVPixelFormat ifmt = color_model_to_pix_fmt(cmodel);
1432 if( ifmt == AV_PIX_FMT_NB ) return -1;
1433 int size = av_image_fill_arrays(opic->data, opic->linesize,
1434 frame->get_data(), ifmt, frame->get_w(), frame->get_h(), 1);
1435 if( size < 0 ) return -1;
1437 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1438 int ysz = bpp * frame->get_w(), usz = ysz;
1448 // override av_image_fill_arrays() for planar types
1449 opic->data[0] = frame->get_y(); opic->linesize[0] = ysz;
1450 opic->data[1] = frame->get_u(); opic->linesize[1] = usz;
1451 opic->data[2] = frame->get_v(); opic->linesize[2] = usz;
1454 opic->data[0] = frame->get_data();
1455 opic->linesize[0] = frame->get_bytes_per_line();
1459 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1460 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(),
1461 ifmt, op->width, op->height, ofmt, SWS_POINT, NULL, NULL, NULL);
1462 if( !convert_ctx ) {
1463 fprintf(stderr, "FFVideoConvert::convert_frame_picture:"
1464 " sws_getCachedContext() failed\n");
1467 int ret = sws_scale(convert_ctx, opic->data, opic->linesize, 0, frame->get_h(),
1468 op->data, op->linesize);
1470 ff_err(ret, "FFVideoConvert::convert_frame_picture: sws_scale() failed\n");
1476 int FFVideoConvert::convert_pixfmt(VFrame *frame, AVFrame *op)
1478 // try direct transfer
1479 if( !convert_vframe_picture(frame, op) ) return 1;
1480 // use indirect transfer
1481 int cmodel = frame->get_color_model();
1482 int max_bits = BC_CModels::calculate_pixelsize(cmodel) * 8;
1483 max_bits /= BC_CModels::components(cmodel);
1484 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1485 int imodel = pix_fmt_to_color_model(ofmt);
1486 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1487 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1488 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1489 imodel = cmodel_is_yuv ?
1490 (BC_CModels::has_alpha(cmodel) ?
1492 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1493 (BC_CModels::has_alpha(cmodel) ?
1494 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1495 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1497 VFrame vframe(frame->get_w(), frame->get_h(), imodel);
1498 vframe.transfer_from(frame);
1499 if( !convert_vframe_picture(&vframe, op) ) return 1;
1503 int FFVideoConvert::transfer_pixfmt(VFrame *frame, AVFrame *ofp)
1505 int ret = convert_pixfmt(frame, ofp);
1507 BC_Hash *hp = frame->get_params();
1508 AVDictionary **dict = &ofp->metadata;
1509 //av_dict_free(dict);
1510 for( int i=0; i<hp->size(); ++i ) {
1511 char *key = hp->get_key(i), *val = hp->get_value(i);
1512 av_dict_set(dict, key, val, 0);
1518 void FFVideoStream::load_markers()
1520 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1521 if( !index_state || idx >= index_state->video_markers.size() ) return;
1522 FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
1525 IndexMarks *FFVideoStream::get_markers()
1527 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1528 if( !index_state || idx >= index_state->video_markers.size() ) return 0;
1529 return !index_state ? 0 : index_state->video_markers[idx];
1533 FFMPEG::FFMPEG(FileBase *file_base)
1536 this->file_base = file_base;
1537 memset(file_format,0,sizeof(file_format));
1538 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
1539 flow_lock = new Condition(1,"FFStream::flow_lock",0);
1542 decoding = encoding = 0;
1543 has_audio = has_video = 0;
1546 opt_video_filter = 0;
1547 opt_audio_filter = 0;
1550 char option_path[BCTEXTLEN];
1551 set_option_path(option_path, "%s", "ffmpeg.opts");
1552 read_options(option_path, opts);
1557 ff_lock("FFMPEG::~FFMPEG()");
1559 ffaudio.remove_all_objects();
1560 ffvideo.remove_all_objects();
1561 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1565 av_dict_free(&opts);
1566 delete [] opt_video_filter;
1567 delete [] opt_audio_filter;
1568 delete [] opt_hw_dev;
1571 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1573 const int *p = codec->supported_samplerates;
1574 if( !p ) return sample_rate;
1576 if( *p == sample_rate ) return *p;
1582 static inline AVRational std_frame_rate(int i)
1584 static const int m1 = 1001*12, m2 = 1000*12;
1585 static const int freqs[] = {
1586 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1587 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
1589 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1590 return (AVRational) { freq, 1001*12 };
1593 AVRational FFMPEG::check_frame_rate(AVCodec *codec, double frame_rate)
1595 const AVRational *p = codec->supported_framerates;
1596 AVRational rate, best_rate = (AVRational) { 0, 0 };
1597 double max_err = 1.; int i = 0;
1598 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1599 double framerate = (double) rate.num / rate.den;
1600 double err = fabs(frame_rate/framerate - 1.);
1601 if( err >= max_err ) continue;
1605 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1608 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1611 double display_aspect = asset->width / (double)asset->height;
1612 double sample_aspect = display_aspect / asset->aspect_ratio;
1613 int width = 1000000, height = width * sample_aspect + 0.5;
1615 MWindow::create_aspect_ratio(w, h, width, height);
1616 return (AVRational){(int)w, (int)h};
1619 return (AVRational){1, 1};
1623 AVRational FFMPEG::to_time_base(int sample_rate)
1625 return (AVRational){1, sample_rate};
1628 int FFMPEG::get_fmt_score(AVSampleFormat dst_fmt, AVSampleFormat src_fmt)
1631 int dst_planar = av_sample_fmt_is_planar(dst_fmt);
1632 int src_planar = av_sample_fmt_is_planar(src_fmt);
1633 if( dst_planar != src_planar ) ++score;
1634 int dst_bytes = av_get_bytes_per_sample(dst_fmt);
1635 int src_bytes = av_get_bytes_per_sample(src_fmt);
1636 score += (src_bytes > dst_bytes ? 100 : -10) * (src_bytes - dst_bytes);
1637 int src_packed = av_get_packed_sample_fmt(src_fmt);
1638 int dst_packed = av_get_packed_sample_fmt(dst_fmt);
1639 if( dst_packed == AV_SAMPLE_FMT_S32 && src_packed == AV_SAMPLE_FMT_FLT ) score += 20;
1640 if( dst_packed == AV_SAMPLE_FMT_FLT && src_packed == AV_SAMPLE_FMT_S32 ) score += 2;
1644 AVSampleFormat FFMPEG::find_best_sample_fmt_of_list(
1645 const AVSampleFormat *sample_fmts, AVSampleFormat src_fmt)
1647 AVSampleFormat best = AV_SAMPLE_FMT_NONE;
1648 int best_score = get_fmt_score(best, src_fmt);
1649 for( int i=0; sample_fmts[i] >= 0; ++i ) {
1650 AVSampleFormat sample_fmt = sample_fmts[i];
1651 int score = get_fmt_score(sample_fmt, src_fmt);
1652 if( score >= best_score ) continue;
1653 best = sample_fmt; best_score = score;
1659 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
1661 char *ep = path + BCTEXTLEN-1;
1662 strncpy(path, File::get_cindat_path(), ep-path);
1663 strncat(path, "/ffmpeg/", ep-path);
1664 path += strlen(path);
1667 path += vsnprintf(path, ep-path, fmt, ap);
1672 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
1677 set_option_path(path, "%s/%s", type, spec);
1680 int FFMPEG::get_format(char *format, const char *path, const char *spec)
1682 char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
1683 get_option_path(option_path, path, spec);
1684 FILE *fp = fopen(option_path,"r");
1687 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1689 line[sizeof(line)-1] = 0;
1690 ret = scan_option_line(line, format, codec);
1696 int FFMPEG::get_codec(char *codec, const char *path, const char *spec)
1698 char option_path[BCTEXTLEN], line[BCTEXTLEN], format[BCTEXTLEN];
1699 get_option_path(option_path, path, spec);
1700 FILE *fp = fopen(option_path,"r");
1703 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1706 line[sizeof(line)-1] = 0;
1707 ret = scan_option_line(line, format, codec);
1710 char *vp = codec, *ep = vp+BCTEXTLEN-1;
1711 while( vp < ep && *vp && *vp != '|' ) ++vp;
1712 if( *vp == '|' ) --vp;
1713 while( vp > codec && (*vp==' ' || *vp=='\t') ) *vp-- = 0;
1718 int FFMPEG::get_file_format()
1720 char audio_muxer[BCSTRLEN], video_muxer[BCSTRLEN];
1721 char audio_format[BCSTRLEN], video_format[BCSTRLEN];
1722 audio_muxer[0] = audio_format[0] = 0;
1723 video_muxer[0] = video_format[0] = 0;
1724 Asset *asset = file_base->asset;
1725 int ret = asset ? 0 : 1;
1726 if( !ret && asset->audio_data ) {
1727 if( !(ret=get_format(audio_format, "audio", asset->acodec)) ) {
1728 if( get_format(audio_muxer, "format", audio_format) ) {
1729 strcpy(audio_muxer, audio_format);
1730 audio_format[0] = 0;
1734 if( !ret && asset->video_data ) {
1735 if( !(ret=get_format(video_format, "video", asset->vcodec)) ) {
1736 if( get_format(video_muxer, "format", video_format) ) {
1737 strcpy(video_muxer, video_format);
1738 video_format[0] = 0;
1742 if( !ret && !audio_muxer[0] && !video_muxer[0] )
1744 if( !ret && audio_muxer[0] && video_muxer[0] &&
1745 strcmp(audio_muxer, video_muxer) ) ret = -1;
1746 if( !ret && audio_format[0] && video_format[0] &&
1747 strcmp(audio_format, video_format) ) ret = -1;
1749 strcpy(file_format, !audio_format[0] && !video_format[0] ?
1750 (audio_muxer[0] ? audio_muxer : video_muxer) :
1751 (audio_format[0] ? audio_format : video_format));
1755 int FFMPEG::scan_option_line(const char *cp, char *tag, char *val)
1757 while( *cp == ' ' || *cp == '\t' ) ++cp;
1758 const char *bp = cp;
1759 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' && *cp != '\n' ) ++cp;
1761 if( !len || len > BCSTRLEN-1 ) return 1;
1762 while( bp < cp ) *tag++ = *bp++;
1764 while( *cp == ' ' || *cp == '\t' ) ++cp;
1765 if( *cp == '=' ) ++cp;
1766 while( *cp == ' ' || *cp == '\t' ) ++cp;
1768 while( *cp && *cp != '\n' ) ++cp;
1770 if( len > BCTEXTLEN-1 ) return 1;
1771 while( bp < cp ) *val++ = *bp++;
1776 int FFMPEG::can_render(const char *fformat, const char *type)
1779 char option_path[BCTEXTLEN];
1780 FFMPEG::set_option_path(option_path, type);
1781 fs.update(option_path);
1782 int total_files = fs.total_files();
1783 for( int i=0; i<total_files; ++i ) {
1784 const char *name = fs.get_entry(i)->get_name();
1785 const char *ext = strrchr(name,'.');
1786 if( !ext ) continue;
1787 if( !strcmp(fformat, ++ext) ) return 1;
1792 int FFMPEG::get_ff_option(const char *nm, const char *options, char *value)
1794 for( const char *cp=options; *cp!=0; ) {
1795 char line[BCTEXTLEN], *bp = line, *ep = bp+sizeof(line)-1;
1796 while( bp < ep && *cp && *cp!='\n' ) *bp++ = *cp++;
1799 if( !line[0] || line[0] == '#' || line[0] == ';' ) continue;
1800 char key[BCSTRLEN], val[BCTEXTLEN];
1801 if( FFMPEG::scan_option_line(line, key, val) ) continue;
1802 if( !strcmp(key, nm) ) {
1803 strncpy(value, val, BCSTRLEN);
1810 void FFMPEG::scan_audio_options(Asset *asset, EDL *edl)
1812 char cin_sample_fmt[BCSTRLEN];
1813 int cin_fmt = AV_SAMPLE_FMT_NONE;
1814 const char *options = asset->ff_audio_options;
1815 if( !get_ff_option("cin_sample_fmt", options, cin_sample_fmt) )
1816 cin_fmt = (int)av_get_sample_fmt(cin_sample_fmt);
1818 char audio_codec[BCSTRLEN]; audio_codec[0] = 0;
1819 AVCodec *av_codec = !FFMPEG::get_codec(audio_codec, "audio", asset->acodec) ?
1820 avcodec_find_encoder_by_name(audio_codec) : 0;
1821 if( av_codec && av_codec->sample_fmts )
1822 cin_fmt = find_best_sample_fmt_of_list(av_codec->sample_fmts, AV_SAMPLE_FMT_FLT);
1824 if( cin_fmt < 0 ) cin_fmt = AV_SAMPLE_FMT_S16;
1825 const char *name = av_get_sample_fmt_name((AVSampleFormat)cin_fmt);
1826 if( !name ) name = _("None");
1827 strcpy(asset->ff_sample_format, name);
1829 char value[BCSTRLEN];
1830 if( !get_ff_option("cin_bitrate", options, value) )
1831 asset->ff_audio_bitrate = atoi(value);
1832 if( !get_ff_option("cin_quality", options, value) )
1833 asset->ff_audio_quality = atoi(value);
1836 void FFMPEG::load_audio_options(Asset *asset, EDL *edl)
1838 char options_path[BCTEXTLEN];
1839 set_option_path(options_path, "audio/%s", asset->acodec);
1840 if( !load_options(options_path,
1841 asset->ff_audio_options,
1842 sizeof(asset->ff_audio_options)) )
1843 scan_audio_options(asset, edl);
1846 void FFMPEG::scan_video_options(Asset *asset, EDL *edl)
1848 char cin_pix_fmt[BCSTRLEN];
1849 int cin_fmt = AV_PIX_FMT_NONE;
1850 const char *options = asset->ff_video_options;
1851 if( !get_ff_option("cin_pix_fmt", options, cin_pix_fmt) )
1852 cin_fmt = (int)av_get_pix_fmt(cin_pix_fmt);
1854 char video_codec[BCSTRLEN]; video_codec[0] = 0;
1855 AVCodec *av_codec = !get_codec(video_codec, "video", asset->vcodec) ?
1856 avcodec_find_encoder_by_name(video_codec) : 0;
1857 if( av_codec && av_codec->pix_fmts ) {
1858 if( 0 && edl ) { // frequently picks a bad answer
1859 int color_model = edl->session->color_model;
1860 int max_bits = BC_CModels::calculate_pixelsize(color_model) * 8;
1861 max_bits /= BC_CModels::components(color_model);
1862 cin_fmt = avcodec_find_best_pix_fmt_of_list(av_codec->pix_fmts,
1863 (BC_CModels::is_yuv(color_model) ?
1864 (max_bits > 8 ? AV_PIX_FMT_AYUV64LE : AV_PIX_FMT_YUV444P) :
1865 (max_bits > 8 ? AV_PIX_FMT_RGB48LE : AV_PIX_FMT_RGB24)), 0, 0);
1868 cin_fmt = av_codec->pix_fmts[0];
1871 if( cin_fmt < 0 ) cin_fmt = AV_PIX_FMT_YUV420P;
1872 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get((AVPixelFormat)cin_fmt);
1873 const char *name = desc ? desc->name : _("None");
1874 strcpy(asset->ff_pixel_format, name);
1876 char value[BCSTRLEN];
1877 if( !get_ff_option("cin_bitrate", options, value) )
1878 asset->ff_video_bitrate = atoi(value);
1879 if( !get_ff_option("cin_quality", options, value) )
1880 asset->ff_video_quality = atoi(value);
1883 void FFMPEG::load_video_options(Asset *asset, EDL *edl)
1885 char options_path[BCTEXTLEN];
1886 set_option_path(options_path, "video/%s", asset->vcodec);
1887 if( !load_options(options_path,
1888 asset->ff_video_options,
1889 sizeof(asset->ff_video_options)) )
1890 scan_video_options(asset, edl);
1893 int FFMPEG::load_defaults(const char *path, const char *type,
1894 char *codec, char *codec_options, int len)
1896 char default_file[BCTEXTLEN];
1897 set_option_path(default_file, "%s/%s.dfl", path, type);
1898 FILE *fp = fopen(default_file,"r");
1900 fgets(codec, BCSTRLEN, fp);
1902 while( *cp && *cp!='\n' ) ++cp;
1904 while( len > 0 && fgets(codec_options, len, fp) ) {
1905 int n = strlen(codec_options);
1906 codec_options += n; len -= n;
1909 set_option_path(default_file, "%s/%s", path, codec);
1910 return load_options(default_file, codec_options, len);
1913 void FFMPEG::set_asset_format(Asset *asset, EDL *edl, const char *text)
1915 if( asset->format != FILE_FFMPEG ) return;
1916 if( text != asset->fformat )
1917 strcpy(asset->fformat, text);
1918 if( asset->audio_data && !asset->ff_audio_options[0] ) {
1919 if( !load_defaults("audio", text, asset->acodec,
1920 asset->ff_audio_options, sizeof(asset->ff_audio_options)) )
1921 scan_audio_options(asset, edl);
1923 asset->audio_data = 0;
1925 if( asset->video_data && !asset->ff_video_options[0] ) {
1926 if( !load_defaults("video", text, asset->vcodec,
1927 asset->ff_video_options, sizeof(asset->ff_video_options)) )
1928 scan_video_options(asset, edl);
1930 asset->video_data = 0;
1934 int FFMPEG::get_encoder(const char *options,
1935 char *format, char *codec, char *bsfilter)
1937 FILE *fp = fopen(options,"r");
1939 eprintf(_("options open failed %s\n"),options);
1942 char line[BCTEXTLEN];
1943 if( !fgets(line, sizeof(line), fp) ||
1944 scan_encoder(line, format, codec, bsfilter) )
1945 eprintf(_("format/codec not found %s\n"), options);
1950 int FFMPEG::scan_encoder(const char *line,
1951 char *format, char *codec, char *bsfilter)
1953 format[0] = codec[0] = bsfilter[0] = 0;
1954 if( scan_option_line(line, format, codec) ) return 1;
1956 while( *cp && *cp != '|' ) ++cp;
1957 if( !*cp ) return 0;
1959 do { *bp-- = 0; } while( bp>=codec && (*bp==' ' || *bp == '\t' ) );
1960 while( *++cp && (*cp==' ' || *cp == '\t') );
1962 for( int i=BCTEXTLEN; --i>0 && *cp; ) *bp++ = *cp++;
1967 int FFMPEG::read_options(const char *options, AVDictionary *&opts, int skip)
1969 FILE *fp = fopen(options,"r");
1972 while( !ret && --skip >= 0 ) {
1974 while( ch >= 0 && ch != '\n' ) ch = getc(fp);
1975 if( ch < 0 ) ret = 1;
1978 ret = read_options(fp, options, opts);
1983 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
1985 FILE *fp = fmemopen((void *)options,strlen(options),"r");
1987 int ret = read_options(fp, options, opts);
1989 AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
1990 if( tag ) st->id = strtol(tag->value,0,0);
1994 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
1996 int ret = 0, no = 0;
1997 char line[BCTEXTLEN];
1998 while( !ret && fgets(line, sizeof(line), fp) ) {
1999 line[sizeof(line)-1] = 0;
2000 if( line[0] == '#' ) continue;
2001 if( line[0] == '\n' ) continue;
2002 char key[BCSTRLEN], val[BCTEXTLEN];
2003 if( scan_option_line(line, key, val) ) {
2004 eprintf(_("err reading %s: line %d\n"), options, no);
2008 if( !strcmp(key, "duration") )
2009 opt_duration = strtod(val, 0);
2010 else if( !strcmp(key, "video_filter") )
2011 opt_video_filter = cstrdup(val);
2012 else if( !strcmp(key, "audio_filter") )
2013 opt_audio_filter = cstrdup(val);
2014 else if( !strcmp(key, "cin_hw_dev") )
2015 opt_hw_dev = cstrdup(val);
2016 else if( !strcmp(key, "loglevel") )
2019 av_dict_set(&opts, key, val, 0);
2025 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
2027 char option_path[BCTEXTLEN];
2028 set_option_path(option_path, "%s", options);
2029 return read_options(option_path, opts);
2032 int FFMPEG::load_options(const char *path, char *bfr, int len)
2035 FILE *fp = fopen(path, "r");
2037 fgets(bfr, len, fp); // skip hdr
2038 len = fread(bfr, 1, len-1, fp);
2039 if( len < 0 ) len = 0;
2045 void FFMPEG::set_loglevel(const char *ap)
2047 if( !ap || !*ap ) return;
2052 { "quiet" , AV_LOG_QUIET },
2053 { "panic" , AV_LOG_PANIC },
2054 { "fatal" , AV_LOG_FATAL },
2055 { "error" , AV_LOG_ERROR },
2056 { "warning", AV_LOG_WARNING },
2057 { "info" , AV_LOG_INFO },
2058 { "verbose", AV_LOG_VERBOSE },
2059 { "debug" , AV_LOG_DEBUG },
2061 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
2062 if( !strcmp(log_levels[i].name, ap) ) {
2063 av_log_set_level(log_levels[i].level);
2067 av_log_set_level(atoi(ap));
2070 double FFMPEG::to_secs(int64_t time, AVRational time_base)
2072 double base_time = time == AV_NOPTS_VALUE ? 0 :
2073 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
2074 return base_time / AV_TIME_BASE;
2077 int FFMPEG::info(char *text, int len)
2079 if( len <= 0 ) return 0;
2081 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
2083 report("format: %s\n",fmt_ctx->iformat->name);
2084 if( ffvideo.size() > 0 )
2085 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
2086 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
2087 FFVideoStream *vid = ffvideo[vidx];
2088 AVStream *st = vid->st;
2089 AVCodecID codec_id = st->codecpar->codec_id;
2090 report(_("vid%d (%d), id 0x%06x:\n"), vid->idx, vid->fidx, codec_id);
2091 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
2092 report(" video%d %s", vidx+1, desc ? desc->name : " (unkn)");
2093 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
2094 AVPixelFormat pix_fmt = (AVPixelFormat)st->codecpar->format;
2095 const char *pfn = av_get_pix_fmt_name(pix_fmt);
2096 report(" pix %s\n", pfn ? pfn : "(unkn)");
2097 double secs = to_secs(st->duration, st->time_base);
2098 int64_t length = secs * vid->frame_rate + 0.5;
2099 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
2100 int64_t nudge = ofs * vid->frame_rate;
2101 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
2102 report(" %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
2103 int hrs = secs/3600; secs -= hrs*3600;
2104 int mins = secs/60; secs -= mins*60;
2105 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
2107 if( ffaudio.size() > 0 )
2108 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
2109 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2110 FFAudioStream *aud = ffaudio[aidx];
2111 AVStream *st = aud->st;
2112 AVCodecID codec_id = st->codecpar->codec_id;
2113 report(_("aud%d (%d), id 0x%06x:\n"), aud->idx, aud->fidx, codec_id);
2114 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
2115 int nch = aud->channels, ch0 = aud->channel0+1;
2116 report(" audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
2117 AVSampleFormat sample_fmt = (AVSampleFormat)st->codecpar->format;
2118 const char *fmt = av_get_sample_fmt_name(sample_fmt);
2119 report(" %s %d", fmt, aud->sample_rate);
2120 int sample_bits = av_get_bits_per_sample(codec_id);
2121 report(" %dbits\n", sample_bits);
2122 double secs = to_secs(st->duration, st->time_base);
2123 int64_t length = secs * aud->sample_rate + 0.5;
2124 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
2125 int64_t nudge = ofs * aud->sample_rate;
2126 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
2127 report(" %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
2128 int hrs = secs/3600; secs -= hrs*3600;
2129 int mins = secs/60; secs -= mins*60;
2130 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
2132 if( fmt_ctx->nb_programs > 0 )
2133 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
2134 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
2135 report("program %d", i+1);
2136 AVProgram *pgrm = fmt_ctx->programs[i];
2137 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2138 int idx = pgrm->stream_index[j];
2139 int vidx = ffvideo.size();
2140 while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
2142 report(", vid%d", vidx);
2145 int aidx = ffaudio.size();
2146 while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
2148 report(", aud%d", aidx);
2151 report(", (%d)", pgrm->stream_index[j]);
2156 AVDictionaryEntry *tag = 0;
2157 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
2158 report("%s=%s\n", tag->key, tag->value);
2167 int FFMPEG::init_decoder(const char *filename)
2169 ff_lock("FFMPEG::init_decoder");
2171 char file_opts[BCTEXTLEN];
2172 strcpy(file_opts, filename);
2173 char *bp = strrchr(file_opts, '/');
2174 if( !bp ) bp = file_opts;
2175 char *sp = strrchr(bp, '.');
2176 if( !sp ) sp = bp + strlen(bp);
2178 AVInputFormat *ifmt = 0;
2180 strcpy(sp, ".opts");
2181 fp = fopen(file_opts, "r");
2184 read_options(fp, file_opts, opts);
2186 AVDictionaryEntry *tag;
2187 if( (tag=av_dict_get(opts, "format", NULL, 0)) != 0 ) {
2188 ifmt = av_find_input_format(tag->value);
2192 load_options("decode.opts", opts);
2193 AVDictionary *fopts = 0;
2194 av_dict_copy(&fopts, opts, 0);
2195 int ret = avformat_open_input(&fmt_ctx, filename, ifmt, &fopts);
2196 av_dict_free(&fopts);
2198 ret = avformat_find_stream_info(fmt_ctx, NULL);
2203 return !ret ? 0 : 1;
2206 int FFMPEG::open_decoder()
2209 if( stat(fmt_ctx->url, &st) < 0 ) {
2210 eprintf(_("can't stat file: %s\n"), fmt_ctx->url);
2214 int64_t file_bits = 8 * st.st_size;
2215 if( !fmt_ctx->bit_rate && opt_duration > 0 )
2216 fmt_ctx->bit_rate = file_bits / opt_duration;
2219 if( fmt_ctx->bit_rate > 0 ) {
2220 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2221 AVStream *st = fmt_ctx->streams[i];
2222 if( st->duration != AV_NOPTS_VALUE ) continue;
2223 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
2224 st->duration = av_rescale(file_bits, st->time_base.den,
2225 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
2229 if( estimated && !(fflags & FF_ESTM_TIMES) ) {
2230 fflags |= FF_ESTM_TIMES;
2231 printf("FFMPEG::open_decoder: some stream times estimated: %s\n",
2235 ff_lock("FFMPEG::open_decoder");
2236 int ret = 0, bad_time = 0;
2237 for( int i=0; !ret && i<(int)fmt_ctx->nb_streams; ++i ) {
2238 AVStream *st = fmt_ctx->streams[i];
2239 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
2240 AVCodecParameters *avpar = st->codecpar;
2241 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avpar->codec_id);
2242 if( !codec_desc ) continue;
2243 switch( avpar->codec_type ) {
2244 case AVMEDIA_TYPE_VIDEO: {
2245 if( avpar->width < 1 ) continue;
2246 if( avpar->height < 1 ) continue;
2247 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
2248 if( framerate.num < 1 ) continue;
2250 int vidx = ffvideo.size();
2251 FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
2252 vstrm_index.append(ffidx(vidx, 0));
2253 ffvideo.append(vid);
2254 vid->width = avpar->width;
2255 vid->height = avpar->height;
2256 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
2257 double secs = to_secs(st->duration, st->time_base);
2258 vid->length = secs * vid->frame_rate;
2259 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
2260 vid->nudge = st->start_time;
2262 if( opt_video_filter )
2263 ret = vid->create_filter(opt_video_filter, avpar);
2265 case AVMEDIA_TYPE_AUDIO: {
2266 if( avpar->channels < 1 ) continue;
2267 if( avpar->sample_rate < 1 ) continue;
2269 int aidx = ffaudio.size();
2270 FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
2271 ffaudio.append(aud);
2272 aud->channel0 = astrm_index.size();
2273 aud->channels = avpar->channels;
2274 for( int ch=0; ch<aud->channels; ++ch )
2275 astrm_index.append(ffidx(aidx, ch));
2276 aud->sample_rate = avpar->sample_rate;
2277 double secs = to_secs(st->duration, st->time_base);
2278 aud->length = secs * aud->sample_rate;
2279 aud->init_swr(aud->channels, avpar->format, aud->sample_rate);
2280 aud->nudge = st->start_time;
2282 if( opt_audio_filter )
2283 ret = aud->create_filter(opt_audio_filter, avpar);
2288 if( bad_time && !(fflags & FF_BAD_TIMES) ) {
2289 fflags |= FF_BAD_TIMES;
2290 printf("FFMPEG::open_decoder: some stream have bad times: %s\n",
2294 return ret < 0 ? -1 : 0;
2298 int FFMPEG::init_encoder(const char *filename)
2300 // try access first for named pipes
2301 int ret = access(filename, W_OK);
2303 int fd = ::open(filename,O_WRONLY);
2304 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
2305 if( fd >= 0 ) { close(fd); ret = 0; }
2308 eprintf(_("bad file path: %s\n"), filename);
2311 ret = get_file_format();
2313 eprintf(_("bad file format: %s\n"), filename);
2317 eprintf(_("mismatch audio/video file format: %s\n"), filename);
2320 ff_lock("FFMPEG::init_encoder");
2322 char format[BCSTRLEN];
2323 if( get_format(format, "format", file_format) )
2324 strcpy(format, file_format);
2325 avformat_alloc_output_context2(&fmt_ctx, 0, format, filename);
2327 eprintf(_("failed: %s\n"), filename);
2332 load_options("encode.opts", opts);
2338 int FFMPEG::open_encoder(const char *type, const char *spec)
2341 Asset *asset = file_base->asset;
2342 char *filename = asset->path;
2343 AVDictionary *sopts = 0;
2344 av_dict_copy(&sopts, opts, 0);
2345 char option_path[BCTEXTLEN];
2346 set_option_path(option_path, "%s/%s.opts", type, type);
2347 read_options(option_path, sopts);
2348 get_option_path(option_path, type, spec);
2349 char format_name[BCSTRLEN], codec_name[BCTEXTLEN], bsfilter[BCTEXTLEN];
2350 if( get_encoder(option_path, format_name, codec_name, bsfilter) ) {
2351 eprintf(_("get_encoder failed %s:%s\n"), option_path, filename);
2356 if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
2358 else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
2359 else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
2362 ff_lock("FFMPEG::open_encoder");
2365 AVCodecContext *ctx = 0;
2367 const AVCodecDescriptor *codec_desc = 0;
2368 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
2370 eprintf(_("cant find codec %s:%s\n"), codec_name, filename);
2374 codec_desc = avcodec_descriptor_get(codec->id);
2376 eprintf(_("unknown codec %s:%s\n"), codec_name, filename);
2381 st = avformat_new_stream(fmt_ctx, 0);
2383 eprintf(_("cant create stream %s:%s\n"), codec_name, filename);
2388 switch( codec_desc->type ) {
2389 case AVMEDIA_TYPE_AUDIO: {
2391 eprintf(_("duplicate audio %s:%s\n"), codec_name, filename);
2395 if( scan_options(asset->ff_audio_options, sopts, st) ) {
2396 eprintf(_("bad audio options %s:%s\n"), codec_name, filename);
2401 ctx = avcodec_alloc_context3(codec);
2402 if( asset->ff_audio_bitrate > 0 ) {
2403 ctx->bit_rate = asset->ff_audio_bitrate;
2405 sprintf(arg, "%d", asset->ff_audio_bitrate);
2406 av_dict_set(&sopts, "b", arg, 0);
2408 else if( asset->ff_audio_quality >= 0 ) {
2409 ctx->global_quality = asset->ff_audio_quality * FF_QP2LAMBDA;
2410 ctx->qmin = ctx->qmax = asset->ff_audio_quality;
2411 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2412 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2413 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2415 av_dict_set(&sopts, "flags", "+qscale", 0);
2416 sprintf(arg, "%d", asset->ff_audio_quality);
2417 av_dict_set(&sopts, "qscale", arg, 0);
2418 sprintf(arg, "%d", ctx->global_quality);
2419 av_dict_set(&sopts, "global_quality", arg, 0);
2421 int aidx = ffaudio.size();
2422 int fidx = aidx + ffvideo.size();
2423 FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
2424 aud->avctx = ctx; ffaudio.append(aud); fst = aud;
2425 aud->sample_rate = asset->sample_rate;
2426 ctx->channels = aud->channels = asset->channels;
2427 for( int ch=0; ch<aud->channels; ++ch )
2428 astrm_index.append(ffidx(aidx, ch));
2429 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
2430 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
2431 if( !ctx->sample_rate ) {
2432 eprintf(_("check_sample_rate failed %s\n"), filename);
2436 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
2437 AVSampleFormat sample_fmt = av_get_sample_fmt(asset->ff_sample_format);
2438 if( sample_fmt == AV_SAMPLE_FMT_NONE )
2439 sample_fmt = codec->sample_fmts ? codec->sample_fmts[0] : AV_SAMPLE_FMT_S16;
2440 ctx->sample_fmt = sample_fmt;
2441 uint64_t layout = av_get_default_channel_layout(ctx->channels);
2442 aud->resample_context = swr_alloc_set_opts(NULL,
2443 layout, ctx->sample_fmt, aud->sample_rate,
2444 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
2446 swr_init(aud->resample_context);
2449 case AVMEDIA_TYPE_VIDEO: {
2451 eprintf(_("duplicate video %s:%s\n"), codec_name, filename);
2455 if( scan_options(asset->ff_video_options, sopts, st) ) {
2456 eprintf(_("bad video options %s:%s\n"), codec_name, filename);
2461 ctx = avcodec_alloc_context3(codec);
2462 if( asset->ff_video_bitrate > 0 ) {
2463 ctx->bit_rate = asset->ff_video_bitrate;
2465 sprintf(arg, "%d", asset->ff_video_bitrate);
2466 av_dict_set(&sopts, "b", arg, 0);
2468 else if( asset->ff_video_quality >= 0 ) {
2469 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
2470 ctx->qmin = ctx->qmax = asset->ff_video_quality;
2471 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2472 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2473 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2475 av_dict_set(&sopts, "flags", "+qscale", 0);
2476 sprintf(arg, "%d", asset->ff_video_quality);
2477 av_dict_set(&sopts, "qscale", arg, 0);
2478 sprintf(arg, "%d", ctx->global_quality);
2479 av_dict_set(&sopts, "global_quality", arg, 0);
2481 int vidx = ffvideo.size();
2482 int fidx = vidx + ffaudio.size();
2483 FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
2484 vstrm_index.append(ffidx(vidx, 0));
2485 vid->avctx = ctx; ffvideo.append(vid); fst = vid;
2486 vid->width = asset->width;
2487 vid->height = asset->height;
2488 vid->frame_rate = asset->frame_rate;
2490 AVPixelFormat pix_fmt = av_get_pix_fmt(asset->ff_pixel_format);
2491 if( opt_hw_dev != 0 ) {
2492 AVHWDeviceType hw_type = vid->encode_hw_activate(opt_hw_dev);
2494 case AV_HWDEVICE_TYPE_VAAPI:
2495 pix_fmt = AV_PIX_FMT_VAAPI;
2497 case AV_HWDEVICE_TYPE_NONE:
2501 if( pix_fmt == AV_PIX_FMT_NONE )
2502 pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
2503 ctx->pix_fmt = pix_fmt;
2505 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
2506 int mask_w = (1<<desc->log2_chroma_w)-1;
2507 ctx->width = (vid->width+mask_w) & ~mask_w;
2508 int mask_h = (1<<desc->log2_chroma_h)-1;
2509 ctx->height = (vid->height+mask_h) & ~mask_h;
2510 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
2511 AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
2512 if( !frame_rate.num || !frame_rate.den ) {
2513 eprintf(_("check_frame_rate failed %s\n"), filename);
2517 av_reduce(&frame_rate.num, &frame_rate.den,
2518 frame_rate.num, frame_rate.den, INT_MAX);
2519 ctx->framerate = (AVRational) { frame_rate.num, frame_rate.den };
2520 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
2521 st->avg_frame_rate = frame_rate;
2522 st->time_base = ctx->time_base;
2524 vid->interlaced = asset->interlace_mode == ILACE_MODE_TOP_FIRST ||
2525 asset->interlace_mode == ILACE_MODE_BOTTOM_FIRST ? 1 : 0;
2526 vid->top_field_first = asset->interlace_mode == ILACE_MODE_TOP_FIRST ? 1 : 0;
2529 eprintf(_("not audio/video, %s:%s\n"), codec_name, filename);
2534 AVDictionaryEntry *tag;
2535 if( (tag=av_dict_get(sopts, "cin_stats_filename", NULL, 0)) != 0 ) {
2536 char suffix[BCSTRLEN]; sprintf(suffix,"-%d.log",fst->fidx);
2537 fst->stats_filename = cstrcat(2, tag->value, suffix);
2539 if( (tag=av_dict_get(sopts, "flags", NULL, 0)) != 0 ) {
2540 int pass = fst->pass;
2541 char *cp = tag->value;
2543 int ch = *cp++, pfx = ch=='-' ? -1 : ch=='+' ? 1 : 0;
2544 if( !isalnum(!pfx ? ch : (ch=*cp++)) ) continue;
2545 char id[BCSTRLEN], *bp = id, *ep = bp+sizeof(id)-1;
2546 for( *bp++=ch; isalnum(ch=*cp); ++cp )
2547 if( bp < ep ) *bp++ = ch;
2549 if( !strcmp(id, "pass1") ) {
2550 pass = pfx<0 ? (pass&~1) : pfx>0 ? (pass|1) : 1;
2552 else if( !strcmp(id, "pass2") ) {
2553 pass = pfx<0 ? (pass&~2) : pfx>0 ? (pass|2) : 2;
2556 if( (fst->pass=pass) ) {
2557 if( pass & 1 ) ctx->flags |= AV_CODEC_FLAG_PASS1;
2558 if( pass & 2 ) ctx->flags |= AV_CODEC_FLAG_PASS2;
2564 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
2565 ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
2566 if( fst->stats_filename && (ret=fst->init_stats_file()) )
2567 eprintf(_("error: stats file = %s\n"), fst->stats_filename);
2570 av_dict_set(&sopts, "cin_bitrate", 0, 0);
2571 av_dict_set(&sopts, "cin_quality", 0, 0);
2573 if( !av_dict_get(sopts, "threads", NULL, 0) )
2574 ctx->thread_count = ff_cpus();
2575 ret = avcodec_open2(ctx, codec, &sopts);
2577 ret = avcodec_parameters_from_context(st->codecpar, ctx);
2579 fprintf(stderr, "Could not copy the stream parameters\n");
2582 _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
2583 ret = avcodec_copy_context(st->codec, ctx);
2584 _Pragma("GCC diagnostic warning \"-Wdeprecated-declarations\"")
2586 fprintf(stderr, "Could not copy the stream context\n");
2589 ff_err(ret,"FFMPEG::open_encoder");
2590 eprintf(_("open failed %s:%s\n"), codec_name, filename);
2596 if( !ret && fst && bsfilter[0] ) {
2597 ret = av_bsf_list_parse_str(bsfilter, &fst->bsfc);
2599 ff_err(ret,"FFMPEG::open_encoder");
2600 eprintf(_("bitstream filter failed %s:\n%s\n"), filename, bsfilter);
2611 av_dict_free(&sopts);
2615 int FFMPEG::close_encoder()
2618 if( encoding > 0 ) {
2619 av_write_trailer(fmt_ctx);
2620 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
2621 avio_closep(&fmt_ctx->pb);
2627 int FFMPEG::decode_activate()
2629 if( decoding < 0 ) {
2631 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
2632 ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
2633 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
2634 ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
2635 // set nudges for each program stream set
2636 const int64_t min_nudge = INT64_MIN+1;
2637 int npgrms = fmt_ctx->nb_programs;
2638 for( int i=0; i<npgrms; ++i ) {
2639 AVProgram *pgrm = fmt_ctx->programs[i];
2640 // first start time video stream
2641 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2642 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2643 int fidx = pgrm->stream_index[j];
2644 AVStream *st = fmt_ctx->streams[fidx];
2645 AVCodecParameters *avpar = st->codecpar;
2646 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2647 if( st->start_time == AV_NOPTS_VALUE ) continue;
2648 if( vstart_time < st->start_time )
2649 vstart_time = st->start_time;
2652 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2653 if( st->start_time == AV_NOPTS_VALUE ) continue;
2654 if( astart_time < st->start_time )
2655 astart_time = st->start_time;
2659 //since frame rate is much more grainy than sample rate, it is better to
2660 // align using video, so that total absolute error is minimized.
2661 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2662 astart_time > min_nudge ? astart_time : AV_NOPTS_VALUE;
2663 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2664 int fidx = pgrm->stream_index[j];
2665 AVStream *st = fmt_ctx->streams[fidx];
2666 AVCodecParameters *avpar = st->codecpar;
2667 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2668 for( int k=0; k<ffvideo.size(); ++k ) {
2669 if( ffvideo[k]->fidx != fidx ) continue;
2670 ffvideo[k]->nudge = nudge;
2674 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2675 for( int k=0; k<ffaudio.size(); ++k ) {
2676 if( ffaudio[k]->fidx != fidx ) continue;
2677 ffaudio[k]->nudge = nudge;
2683 // set nudges for any streams not yet set
2684 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2685 int nstreams = fmt_ctx->nb_streams;
2686 for( int i=0; i<nstreams; ++i ) {
2687 AVStream *st = fmt_ctx->streams[i];
2688 AVCodecParameters *avpar = st->codecpar;
2689 switch( avpar->codec_type ) {
2690 case AVMEDIA_TYPE_VIDEO: {
2691 if( st->start_time == AV_NOPTS_VALUE ) continue;
2692 int vidx = ffvideo.size();
2693 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
2694 if( vidx < 0 ) continue;
2695 if( ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
2696 if( vstart_time < st->start_time )
2697 vstart_time = st->start_time;
2699 case AVMEDIA_TYPE_AUDIO: {
2700 if( st->start_time == AV_NOPTS_VALUE ) continue;
2701 int aidx = ffaudio.size();
2702 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
2703 if( aidx < 0 ) continue;
2704 if( ffaudio[aidx]->frame_sz < avpar->frame_size )
2705 ffaudio[aidx]->frame_sz = avpar->frame_size;
2706 if( ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
2707 if( astart_time < st->start_time )
2708 astart_time = st->start_time;
2713 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2714 astart_time > min_nudge ? astart_time : 0;
2715 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
2716 if( ffvideo[vidx]->nudge == AV_NOPTS_VALUE )
2717 ffvideo[vidx]->nudge = nudge;
2719 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2720 if( ffaudio[aidx]->nudge == AV_NOPTS_VALUE )
2721 ffaudio[aidx]->nudge = nudge;
2728 int FFMPEG::encode_activate()
2731 if( encoding < 0 ) {
2733 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
2734 (ret=avio_open(&fmt_ctx->pb, fmt_ctx->url, AVIO_FLAG_WRITE)) < 0 ) {
2735 ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
2741 AVProgram *prog = av_new_program(fmt_ctx, prog_id);
2742 for( int i=0; i< ffvideo.size(); ++i )
2743 av_program_add_stream_index(fmt_ctx, prog_id, ffvideo[i]->fidx);
2744 for( int i=0; i< ffaudio.size(); ++i )
2745 av_program_add_stream_index(fmt_ctx, prog_id, ffaudio[i]->fidx);
2746 int pi = fmt_ctx->nb_programs;
2747 while( --pi >= 0 && fmt_ctx->programs[pi]->id != prog_id );
2748 AVDictionary **meta = &prog->metadata;
2749 av_dict_set(meta, "service_provider", "cin5", 0);
2750 const char *path = fmt_ctx->url, *bp = strrchr(path,'/');
2751 if( bp ) path = bp + 1;
2752 av_dict_set(meta, "title", path, 0);
2754 if( ffaudio.size() ) {
2755 const char *ep = getenv("CIN_AUDIO_LANG"), *lp = 0;
2756 if( !ep && (lp=getenv("LANG")) ) { // some are guesses
2757 static struct { const char lc[3], lng[4]; } lcode[] = {
2758 { "en", "eng" }, { "de", "ger" }, { "es", "spa" },
2759 { "eu", "bas" }, { "fr", "fre" }, { "el", "gre" },
2760 { "hi", "hin" }, { "it", "ita" }, { "ja", "jap" },
2761 { "ko", "kor" }, { "du", "dut" }, { "pl", "pol" },
2762 { "pt", "por" }, { "ru", "rus" }, { "sl", "slv" },
2763 { "uk", "ukr" }, { "vi", "vie" }, { "zh", "chi" },
2765 for( int i=sizeof(lcode)/sizeof(lcode[0]); --i>=0 && !ep; )
2766 if( !strncmp(lcode[i].lc,lp,2) ) ep = lcode[i].lng;
2768 if( !ep ) ep = "und";
2770 strncpy(lang,ep,3); lang[3] = 0;
2771 AVStream *st = ffaudio[0]->st;
2772 av_dict_set(&st->metadata,"language",lang,0);
2775 AVDictionary *fopts = 0;
2776 char option_path[BCTEXTLEN];
2777 set_option_path(option_path, "format/%s", file_format);
2778 read_options(option_path, fopts, 1);
2779 ret = avformat_write_header(fmt_ctx, &fopts);
2781 ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
2785 av_dict_free(&fopts);
2792 int FFMPEG::audio_seek(int stream, int64_t pos)
2794 int aidx = astrm_index[stream].st_idx;
2795 FFAudioStream *aud = ffaudio[aidx];
2796 aud->audio_seek(pos);
2800 int FFMPEG::video_seek(int stream, int64_t pos)
2802 int vidx = vstrm_index[stream].st_idx;
2803 FFVideoStream *vid = ffvideo[vidx];
2804 vid->video_seek(pos);
2809 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
2811 if( !has_audio || chn >= astrm_index.size() ) return -1;
2812 int aidx = astrm_index[chn].st_idx;
2813 FFAudioStream *aud = ffaudio[aidx];
2814 if( aud->load(pos, len) < len ) return -1;
2815 int ch = astrm_index[chn].st_ch;
2816 int ret = aud->read(samples,len,ch);
2820 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
2822 if( !has_video || layer >= vstrm_index.size() ) return -1;
2823 int vidx = vstrm_index[layer].st_idx;
2824 FFVideoStream *vid = ffvideo[vidx];
2825 return vid->load(vframe, pos);
2829 int FFMPEG::encode(int stream, double **samples, int len)
2831 FFAudioStream *aud = ffaudio[stream];
2832 return aud->encode(samples, len);
2836 int FFMPEG::encode(int stream, VFrame *frame)
2838 FFVideoStream *vid = ffvideo[stream];
2839 return vid->encode(frame);
2842 void FFMPEG::start_muxer()
2850 void FFMPEG::stop_muxer()
2859 void FFMPEG::flow_off()
2862 flow_lock->lock("FFMPEG::flow_off");
2866 void FFMPEG::flow_on()
2870 flow_lock->unlock();
2873 void FFMPEG::flow_ctl()
2876 flow_lock->lock("FFMPEG::flow_ctl");
2877 flow_lock->unlock();
2881 int FFMPEG::mux_audio(FFrame *frm)
2883 FFStream *fst = frm->fst;
2884 AVCodecContext *ctx = fst->avctx;
2885 AVFrame *frame = *frm;
2886 AVRational tick_rate = {1, ctx->sample_rate};
2887 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
2888 int ret = fst->encode_frame(frame);
2890 ff_err(ret, "FFMPEG::mux_audio");
2891 return ret >= 0 ? 0 : 1;
2894 int FFMPEG::mux_video(FFrame *frm)
2896 FFStream *fst = frm->fst;
2897 AVFrame *frame = *frm;
2898 frame->pts = frm->position;
2899 int ret = fst->encode_frame(frame);
2901 ff_err(ret, "FFMPEG::mux_video");
2902 return ret >= 0 ? 0 : 1;
2908 double atm = -1, vtm = -1;
2909 FFrame *afrm = 0, *vfrm = 0;
2911 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
2912 FFStream *fst = ffaudio[i];
2913 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
2914 FFrame *frm = fst->frms.first;
2915 if( !frm ) { if( !done ) return; continue; }
2916 double tm = to_secs(frm->position, fst->avctx->time_base);
2917 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
2919 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
2920 FFStream *fst = ffvideo[i];
2921 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
2922 FFrame *frm = fst->frms.first;
2923 if( !frm ) { if( !done ) return; continue; }
2924 double tm = to_secs(frm->position, fst->avctx->time_base);
2925 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
2927 if( !demand ) flow_off();
2928 if( !afrm && !vfrm ) break;
2929 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
2930 vfrm->position, vfrm->fst->avctx->time_base,
2931 afrm->position, afrm->fst->avctx->time_base);
2932 FFrame *frm = v <= 0 ? vfrm : afrm;
2933 if( frm == afrm ) mux_audio(frm);
2934 if( frm == vfrm ) mux_video(frm);
2943 mux_lock->lock("FFMPEG::run");
2946 for( int i=0; i<ffaudio.size(); ++i )
2947 ffaudio[i]->drain();
2948 for( int i=0; i<ffvideo.size(); ++i )
2949 ffvideo[i]->drain();
2951 for( int i=0; i<ffaudio.size(); ++i )
2952 ffaudio[i]->flush();
2953 for( int i=0; i<ffvideo.size(); ++i )
2954 ffvideo[i]->flush();
2958 int FFMPEG::ff_total_audio_channels()
2960 return astrm_index.size();
2963 int FFMPEG::ff_total_astreams()
2965 return ffaudio.size();
2968 int FFMPEG::ff_audio_channels(int stream)
2970 return ffaudio[stream]->channels;
2973 int FFMPEG::ff_sample_rate(int stream)
2975 return ffaudio[stream]->sample_rate;
2978 const char* FFMPEG::ff_audio_format(int stream)
2980 AVStream *st = ffaudio[stream]->st;
2981 AVCodecID id = st->codecpar->codec_id;
2982 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2983 return desc ? desc->name : _("Unknown");
2986 int FFMPEG::ff_audio_pid(int stream)
2988 return ffaudio[stream]->st->id;
2991 int64_t FFMPEG::ff_audio_samples(int stream)
2993 return ffaudio[stream]->length;
2996 // find audio astream/channels with this program,
2997 // or all program audio channels (astream=-1)
2998 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
3002 int vidx = ffvideo[vstream]->fidx;
3003 // find first program with this video stream
3004 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
3005 AVProgram *pgrm = fmt_ctx->programs[i];
3006 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
3007 int st_idx = pgrm->stream_index[j];
3008 AVStream *st = fmt_ctx->streams[st_idx];
3009 if( st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
3010 if( st_idx == vidx ) pidx = i;
3013 if( pidx < 0 ) return -1;
3015 int64_t channels = 0;
3016 AVProgram *pgrm = fmt_ctx->programs[pidx];
3017 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
3018 int aidx = pgrm->stream_index[j];
3019 AVStream *st = fmt_ctx->streams[aidx];
3020 if( st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
3021 if( astream > 0 ) { --astream; continue; }
3023 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
3024 if( ffaudio[i]->fidx == aidx ) astrm = i;
3026 if( ret < 0 ) ret = astrm;
3027 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
3028 channels |= mask << ffaudio[astrm]->channel0;
3030 if( !astream ) break;
3032 channel_mask = channels;
3037 int FFMPEG::ff_total_video_layers()
3039 return vstrm_index.size();
3042 int FFMPEG::ff_total_vstreams()
3044 return ffvideo.size();
3047 int FFMPEG::ff_video_width(int stream)
3049 return ffvideo[stream]->width;
3052 int FFMPEG::ff_video_height(int stream)
3054 return ffvideo[stream]->height;
3057 int FFMPEG::ff_set_video_width(int stream, int width)
3059 int w = ffvideo[stream]->width;
3060 ffvideo[stream]->width = width;
3064 int FFMPEG::ff_set_video_height(int stream, int height)
3066 int h = ffvideo[stream]->height;
3067 ffvideo[stream]->height = height;
3071 int FFMPEG::ff_coded_width(int stream)
3073 return ffvideo[stream]->avctx->coded_width;
3076 int FFMPEG::ff_coded_height(int stream)
3078 return ffvideo[stream]->avctx->coded_height;
3081 float FFMPEG::ff_aspect_ratio(int stream)
3083 return ffvideo[stream]->aspect_ratio;
3086 const char* FFMPEG::ff_video_format(int stream)
3088 AVStream *st = ffvideo[stream]->st;
3089 AVCodecID id = st->codecpar->codec_id;
3090 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
3091 return desc ? desc->name : _("Unknown");
3094 double FFMPEG::ff_frame_rate(int stream)
3096 return ffvideo[stream]->frame_rate;
3099 int64_t FFMPEG::ff_video_frames(int stream)
3101 return ffvideo[stream]->length;
3104 int FFMPEG::ff_video_pid(int stream)
3106 return ffvideo[stream]->st->id;
3109 int FFMPEG::ff_video_mpeg_color_range(int stream)
3111 return ffvideo[stream]->st->codecpar->color_range == AVCOL_RANGE_MPEG ? 1 : 0;
3114 int FFMPEG::ff_cpus()
3116 return file_base->file->cpus;
3119 const char *FFMPEG::ff_hw_dev()
3121 return &file_base->file->preferences->use_hw_dev[0];
3124 int FFVideoStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
3126 avfilter_register_all();
3127 const char *sp = filter_spec;
3128 char filter_name[BCSTRLEN], *np = filter_name;
3129 int i = sizeof(filter_name);
3130 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
3132 const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
3133 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_VIDEO ) {
3134 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
3137 filter_graph = avfilter_graph_alloc();
3138 const AVFilter *buffersrc = avfilter_get_by_name("buffer");
3139 const AVFilter *buffersink = avfilter_get_by_name("buffersink");
3141 int ret = 0; char args[BCTEXTLEN];
3142 AVPixelFormat pix_fmt = (AVPixelFormat)avpar->format;
3143 snprintf(args, sizeof(args),
3144 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
3145 avpar->width, avpar->height, (int)pix_fmt,
3146 st->time_base.num, st->time_base.den,
3147 avpar->sample_aspect_ratio.num, avpar->sample_aspect_ratio.den);
3149 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
3150 args, NULL, filter_graph);
3152 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
3153 NULL, NULL, filter_graph);
3155 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
3156 (uint8_t*)&pix_fmt, sizeof(pix_fmt),
3157 AV_OPT_SEARCH_CHILDREN);
3159 ff_err(ret, "FFVideoStream::create_filter");
3161 ret = FFStream::create_filter(filter_spec);
3162 return ret >= 0 ? 0 : -1;
3165 int FFAudioStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
3167 avfilter_register_all();
3168 const char *sp = filter_spec;
3169 char filter_name[BCSTRLEN], *np = filter_name;
3170 int i = sizeof(filter_name);
3171 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
3173 const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
3174 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_AUDIO ) {
3175 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
3178 filter_graph = avfilter_graph_alloc();
3179 const AVFilter *buffersrc = avfilter_get_by_name("abuffer");
3180 const AVFilter *buffersink = avfilter_get_by_name("abuffersink");
3181 int ret = 0; char args[BCTEXTLEN];
3182 AVSampleFormat sample_fmt = (AVSampleFormat)avpar->format;
3183 snprintf(args, sizeof(args),
3184 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
3185 st->time_base.num, st->time_base.den, avpar->sample_rate,
3186 av_get_sample_fmt_name(sample_fmt), avpar->channel_layout);
3188 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
3189 args, NULL, filter_graph);
3191 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
3192 NULL, NULL, filter_graph);
3194 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
3195 (uint8_t*)&sample_fmt, sizeof(sample_fmt),
3196 AV_OPT_SEARCH_CHILDREN);
3198 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
3199 (uint8_t*)&avpar->channel_layout,
3200 sizeof(avpar->channel_layout), AV_OPT_SEARCH_CHILDREN);
3202 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
3203 (uint8_t*)&sample_rate, sizeof(sample_rate),
3204 AV_OPT_SEARCH_CHILDREN);
3206 ff_err(ret, "FFAudioStream::create_filter");
3208 ret = FFStream::create_filter(filter_spec);
3209 return ret >= 0 ? 0 : -1;
3212 int FFStream::create_filter(const char *filter_spec)
3214 /* Endpoints for the filter graph. */
3215 AVFilterInOut *outputs = avfilter_inout_alloc();
3216 outputs->name = av_strdup("in");
3217 outputs->filter_ctx = buffersrc_ctx;
3218 outputs->pad_idx = 0;
3221 AVFilterInOut *inputs = avfilter_inout_alloc();
3222 inputs->name = av_strdup("out");
3223 inputs->filter_ctx = buffersink_ctx;
3224 inputs->pad_idx = 0;
3227 int ret = !outputs->name || !inputs->name ? -1 : 0;
3229 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
3230 &inputs, &outputs, NULL);
3232 ret = avfilter_graph_config(filter_graph, NULL);
3235 ff_err(ret, "FFStream::create_filter");
3236 avfilter_graph_free(&filter_graph);
3239 avfilter_inout_free(&inputs);
3240 avfilter_inout_free(&outputs);
3244 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
3247 av_init_packet(&pkt);
3248 AVFrame *frame = av_frame_alloc();
3250 fprintf(stderr,"FFMPEG::scan: ");
3251 fprintf(stderr,_("av_frame_alloc failed\n"));
3252 fprintf(stderr,"FFMPEG::scan:file=%s\n", file_base->asset->path);
3256 index_state->add_video_markers(ffvideo.size());
3257 index_state->add_audio_markers(ffaudio.size());
3259 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
3261 AVDictionary *copts = 0;
3262 av_dict_copy(&copts, opts, 0);
3263 AVStream *st = fmt_ctx->streams[i];
3264 AVCodecID codec_id = st->codecpar->codec_id;
3265 AVCodec *decoder = avcodec_find_decoder(codec_id);
3266 AVCodecContext *avctx = avcodec_alloc_context3(decoder);
3268 eprintf(_("cant allocate codec context\n"));
3269 ret = AVERROR(ENOMEM);
3272 avcodec_parameters_to_context(avctx, st->codecpar);
3273 if( !av_dict_get(copts, "threads", NULL, 0) )
3274 avctx->thread_count = ff_cpus();
3275 ret = avcodec_open2(avctx, decoder, &copts);
3277 av_dict_free(&copts);
3279 AVCodecParameters *avpar = st->codecpar;
3280 switch( avpar->codec_type ) {
3281 case AVMEDIA_TYPE_VIDEO: {
3282 int vidx = ffvideo.size();
3283 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
3284 if( vidx < 0 ) break;
3285 ffvideo[vidx]->avctx = avctx;
3287 case AVMEDIA_TYPE_AUDIO: {
3288 int aidx = ffaudio.size();
3289 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3290 if( aidx < 0 ) break;
3291 ffaudio[aidx]->avctx = avctx;
3296 fprintf(stderr,"FFMPEG::scan: ");
3297 fprintf(stderr,_("codec open failed\n"));
3298 fprintf(stderr,"FFMPEG::scan:file=%s\n", file_base->asset->path);
3299 avcodec_free_context(&avctx);
3303 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
3304 AVStream *st = fmt_ctx->streams[i];
3305 AVCodecParameters *avpar = st->codecpar;
3306 if( avpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
3307 int64_t tstmp = st->start_time;
3308 if( tstmp == AV_NOPTS_VALUE ) continue;
3309 int aidx = ffaudio.size();
3310 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3311 if( aidx < 0 ) continue;
3312 FFAudioStream *aud = ffaudio[aidx];
3313 tstmp -= aud->nudge;
3314 double secs = to_secs(tstmp, st->time_base);
3315 aud->curr_pos = secs * aud->sample_rate + 0.5;
3319 for( int64_t count=0; !*canceled; ++count ) {
3320 av_packet_unref(&pkt);
3321 pkt.data = 0; pkt.size = 0;
3323 int ret = av_read_frame(fmt_ctx, &pkt);
3325 if( ret == AVERROR_EOF ) break;
3326 if( ++errs > 100 ) {
3327 ff_err(ret,_("over 100 read_frame errs\n"));
3332 if( !pkt.data ) continue;
3333 int i = pkt.stream_index;
3334 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
3335 AVStream *st = fmt_ctx->streams[i];
3336 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
3338 AVCodecParameters *avpar = st->codecpar;
3339 switch( avpar->codec_type ) {
3340 case AVMEDIA_TYPE_VIDEO: {
3341 int vidx = ffvideo.size();
3342 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
3343 if( vidx < 0 ) break;
3344 FFVideoStream *vid = ffvideo[vidx];
3345 if( !vid->avctx ) break;
3346 int64_t tstmp = pkt.dts;
3347 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.pts;
3348 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
3349 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
3350 double secs = to_secs(tstmp, st->time_base);
3351 int64_t frm = secs * vid->frame_rate + 0.5;
3352 if( frm < 0 ) frm = 0;
3353 index_state->put_video_mark(vidx, frm, pkt.pos);
3356 ret = avcodec_send_packet(vid->avctx, pkt);
3357 if( ret < 0 ) break;
3358 while( (ret=vid->decode_frame(frame)) > 0 ) {}
3361 case AVMEDIA_TYPE_AUDIO: {
3362 int aidx = ffaudio.size();
3363 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3364 if( aidx < 0 ) break;
3365 FFAudioStream *aud = ffaudio[aidx];
3366 if( !aud->avctx ) break;
3367 int64_t tstmp = pkt.pts;
3368 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
3369 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
3370 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
3371 double secs = to_secs(tstmp, st->time_base);
3372 int64_t sample = secs * aud->sample_rate + 0.5;
3374 index_state->put_audio_mark(aidx, sample, pkt.pos);
3376 ret = avcodec_send_packet(aud->avctx, &pkt);
3377 if( ret < 0 ) break;
3378 int ch = aud->channel0, nch = aud->channels;
3379 int64_t pos = index_state->pos(ch);
3380 if( pos != aud->curr_pos ) {
3381 if( abs(pos-aud->curr_pos) > 1 )
3382 printf("audio%d pad %jd %jd (%jd)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
3383 index_state->pad_data(ch, nch, aud->curr_pos);
3385 while( (ret=aud->decode_frame(frame)) > 0 ) {
3386 //if( frame->channels != nch ) break;
3387 aud->init_swr(frame->channels, frame->format, frame->sample_rate);
3389 int len = aud->get_samples(samples,
3390 &frame->extended_data[0], frame->nb_samples);
3391 pos = aud->curr_pos;
3392 if( (aud->curr_pos += len) >= 0 ) {
3394 samples += -pos * nch;
3395 len = aud->curr_pos;
3397 for( int i=0; i<nch; ++i )
3398 index_state->put_data(ch+i,nch,samples+i,len);
3405 av_frame_free(&frame);
3409 void FFStream::load_markers(IndexMarks &marks, double rate)
3412 int64_t sz = marks.size();
3413 int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
3414 int nb_ent = st->nb_index_entries;
3415 // some formats already have an index
3417 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
3418 int64_t tstmp = ep->timestamp;
3419 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
3420 double secs = ffmpeg->to_secs(tstmp, st->time_base);
3421 int64_t no = secs * rate;
3422 while( in < sz && marks[in].no <= no ) ++in;
3424 int64_t len = sz - in;
3425 int64_t count = max_entries - nb_ent;
3426 if( count > len ) count = len;
3427 for( int i=0; i<count; ++i ) {
3428 int k = in + i * len / count;
3429 int64_t no = marks[k].no, pos = marks[k].pos;
3430 double secs = (double)no / rate;
3431 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
3432 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
3433 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);