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");
271 nudge = AV_NOPTS_VALUE;
272 seek_pos = curr_pos = 0;
274 reading = writing = 0;
275 hw_pixfmt = AV_PIX_FMT_NONE;
288 FFStream::~FFStream()
290 frm_lock->lock("FFStream::~FFStream");
291 if( reading > 0 || writing > 0 ) avcodec_close(avctx);
292 if( avctx ) avcodec_free_context(&avctx);
293 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
294 if( hw_device_ctx ) av_buffer_unref(&hw_device_ctx);
295 if( bsfc ) av_bsf_free(&bsfc);
296 while( frms.first ) frms.remove(frms.first);
297 if( filter_graph ) avfilter_graph_free(&filter_graph);
298 if( frame ) av_frame_free(&frame);
299 if( fframe ) av_frame_free(&fframe);
300 if( probe_frame ) av_frame_free(&probe_frame);
303 if( stats_fp ) fclose(stats_fp);
304 if( stats_in ) av_freep(&stats_in);
305 delete [] stats_filename;
308 void FFStream::ff_lock(const char *cp)
310 FFMPEG::fflock.lock(cp);
313 void FFStream::ff_unlock()
315 FFMPEG::fflock.unlock();
318 void FFStream::queue(FFrame *frm)
320 frm_lock->lock("FFStream::queue");
324 ffmpeg->mux_lock->unlock();
327 void FFStream::dequeue(FFrame *frm)
329 frm_lock->lock("FFStream::dequeue");
331 frms.remove_pointer(frm);
335 int FFStream::encode_activate()
338 writing = ffmpeg->encode_activate();
342 // this is a global parameter that really should be in the context
343 static AVPixelFormat hw_pix_fmt = AV_PIX_FMT_NONE; // protected by ff_lock
345 // goofy maneuver to attach a hw_format to an av_context
346 #define GET_HW_PIXFMT(fn, fmt) \
347 static AVPixelFormat get_hw_##fn(AVCodecContext *ctx, const enum AVPixelFormat *pix_fmts) { \
350 GET_HW_PIXFMT(vaapi, AV_PIX_FMT_VAAPI)
351 GET_HW_PIXFMT(vdpau, AV_PIX_FMT_VDPAU)
352 GET_HW_PIXFMT(cuda, AV_PIX_FMT_CUDA)
353 GET_HW_PIXFMT(nv12, AV_PIX_FMT_NV12)
355 static enum AVPixelFormat get_hw_format(AVCodecContext *ctx,
356 const enum AVPixelFormat *pix_fmts)
358 for( const enum AVPixelFormat *p=pix_fmts; *p!=AV_PIX_FMT_NONE; ++p ) {
359 if( *p != hw_pix_fmt ) continue;
361 case AV_PIX_FMT_VAAPI: ctx->get_format = get_hw_vaapi; return *p;
362 case AV_PIX_FMT_VDPAU: ctx->get_format = get_hw_vdpau; return *p;
363 case AV_PIX_FMT_CUDA: ctx->get_format = get_hw_cuda; return *p;
364 case AV_PIX_FMT_NV12: ctx->get_format = get_hw_nv12; return *p;
366 fprintf(stderr, "Unknown HW surface format: %s\n",
367 av_get_pix_fmt_name(*p));
371 fprintf(stderr, "Failed to get HW surface format.\n");
372 return hw_pix_fmt = AV_PIX_FMT_NONE;
376 AVHWDeviceType FFStream::decode_hw_activate()
378 return AV_HWDEVICE_TYPE_NONE;
381 int FFStream::decode_hw_format(AVCodec *decoder, AVHWDeviceType type)
386 int FFStream::decode_activate()
388 if( reading < 0 && (reading=ffmpeg->decode_activate()) > 0 ) {
389 ff_lock("FFStream::decode_activate");
391 AVDictionary *copts = 0;
392 av_dict_copy(&copts, ffmpeg->opts, 0);
394 AVHWDeviceType hw_type = decode_hw_activate();
396 // this should be avformat_copy_context(), but no copy avail
397 ret = avformat_open_input(&fmt_ctx,
398 ffmpeg->fmt_ctx->url, ffmpeg->fmt_ctx->iformat, &copts);
400 ret = avformat_find_stream_info(fmt_ctx, 0);
401 st = fmt_ctx->streams[fidx];
404 while( ret >= 0 && st != 0 && !reading ) {
405 AVCodecID codec_id = st->codecpar->codec_id;
406 AVCodec *decoder = 0;
408 if( ffmpeg->opt_video_decoder )
409 decoder = avcodec_find_decoder_by_name(ffmpeg->opt_video_decoder);
411 ffmpeg->video_codec_remaps.update(codec_id, decoder);
413 else if( is_audio() ) {
414 if( ffmpeg->opt_audio_decoder )
415 decoder = avcodec_find_decoder_by_name(ffmpeg->opt_audio_decoder);
417 ffmpeg->audio_codec_remaps.update(codec_id, decoder);
420 decoder = avcodec_find_decoder(codec_id);
421 avctx = avcodec_alloc_context3(decoder);
423 eprintf(_("cant allocate codec context\n"));
424 ret = AVERROR(ENOMEM);
426 if( ret >= 0 && hw_type != AV_HWDEVICE_TYPE_NONE ) {
427 ret = decode_hw_format(decoder, hw_type);
430 avcodec_parameters_to_context(avctx, st->codecpar);
431 if( !av_dict_get(copts, "threads", NULL, 0) )
432 avctx->thread_count = ffmpeg->ff_cpus();
433 ret = avcodec_open2(avctx, decoder, &copts);
435 AVFrame *hw_frame = 0;
436 if( ret >= 0 && hw_type != AV_HWDEVICE_TYPE_NONE ) {
437 if( !(hw_frame=av_frame_alloc()) ) {
438 fprintf(stderr, "FFStream::decode_activate: av_frame_alloc failed\n");
439 ret = AVERROR(ENOMEM);
442 ret = decode(hw_frame);
444 if( ret < 0 && hw_type != AV_HWDEVICE_TYPE_NONE ) {
445 ff_err(ret, "HW device init failed, using SW decode.\nfile:%s\n",
446 ffmpeg->fmt_ctx->url);
447 avcodec_close(avctx);
448 avcodec_free_context(&avctx);
449 av_buffer_unref(&hw_device_ctx);
451 av_frame_free(&hw_frame);
452 hw_type = AV_HWDEVICE_TYPE_NONE;
453 int flags = AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_ANY;
455 av_seek_frame(fmt_ctx, idx, 0, flags);
456 need_packet = 1; flushed = 0;
457 seeked = 1; st_eof(0);
461 probe_frame = hw_frame;
465 eprintf(_("open decoder failed\n"));
468 eprintf(_("can't open input file: %s\n"), ffmpeg->fmt_ctx->url);
469 av_dict_free(&copts);
475 int FFStream::read_packet()
477 av_packet_unref(ipkt);
478 int ret = av_read_frame(fmt_ctx, ipkt);
481 if( ret == AVERROR_EOF ) return 0;
482 ff_err(ret, "FFStream::read_packet: av_read_frame failed\n");
489 int FFStream::decode(AVFrame *frame)
491 if( probe_frame ) { // hw probe reads first frame
492 av_frame_ref(frame, probe_frame);
493 av_frame_free(&probe_frame);
497 int retries = MAX_RETRY;
498 frm_lock->lock("FFStream::decode");
499 while( ret >= 0 && !flushed && --retries >= 0 ) {
501 if( (ret=read_packet()) < 0 ) break;
502 AVPacket *pkt = ret > 0 ? (AVPacket*)ipkt : 0;
504 if( pkt->stream_index != st->index ) continue;
505 if( !pkt->data || !pkt->size ) continue;
507 if( (ret=avcodec_send_packet(avctx, pkt)) < 0 ) {
508 ff_err(ret, "FFStream::decode: avcodec_send_packet failed.\nfile:%s\n",
509 ffmpeg->fmt_ctx->url);
515 if( (ret=decode_frame(frame)) > 0 ) break;
524 fprintf(stderr, "FFStream::decode: Retry limit\n");
528 fprintf(stderr, "FFStream::decode: failed\n");
532 int FFStream::load_filter(AVFrame *frame)
534 int ret = av_buffersrc_add_frame_flags(buffersrc_ctx, frame, 0);
536 eprintf(_("av_buffersrc_add_frame_flags failed\n"));
540 int FFStream::read_filter(AVFrame *frame)
542 int ret = av_buffersink_get_frame(buffersink_ctx, frame);
544 if( ret == AVERROR(EAGAIN) ) return 0;
545 if( ret == AVERROR_EOF ) { st_eof(1); return -1; }
546 ff_err(ret, "FFStream::read_filter: av_buffersink_get_frame failed\n");
552 int FFStream::read_frame(AVFrame *frame)
554 av_frame_unref(frame);
555 if( !filter_graph || !buffersrc_ctx || !buffersink_ctx )
556 return decode(frame);
557 if( !fframe && !(fframe=av_frame_alloc()) ) {
558 fprintf(stderr, "FFStream::read_frame: av_frame_alloc failed\n");
562 while( !flushed && !(ret=read_filter(frame)) ) {
563 if( (ret=decode(fframe)) < 0 ) break;
564 if( ret > 0 && (ret=load_filter(fframe)) < 0 ) break;
569 int FFStream::write_packet(FFPacket &pkt)
573 av_packet_rescale_ts(pkt, avctx->time_base, st->time_base);
574 pkt->stream_index = st->index;
575 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, pkt);
578 ret = av_bsf_send_packet(bsfc, pkt);
581 if( (ret=av_bsf_receive_packet(bsfc, bs)) < 0 ) {
582 if( ret == AVERROR(EAGAIN) ) return 0;
583 if( ret == AVERROR_EOF ) return -1;
586 av_packet_rescale_ts(bs, avctx->time_base, st->time_base);
587 bs->stream_index = st->index;
588 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, bs);
592 ff_err(ret, "FFStream::write_packet: write packet failed.\nfile:%s\n",
593 ffmpeg->fmt_ctx->url);
597 int FFStream::encode_frame(AVFrame *frame)
599 int pkts = 0, ret = 0;
600 for( int retry=MAX_RETRY; --retry>=0; ) {
602 ret = avcodec_send_frame(avctx, frame);
603 if( !ret && frame ) return pkts;
604 if( ret < 0 && ret != AVERROR(EAGAIN) ) break;
606 ret = avcodec_receive_packet(avctx, opkt);
607 if( !frame && ret == AVERROR_EOF ) return pkts;
609 ret = write_packet(opkt);
612 if( frame && stats_fp ) {
613 ret = write_stats_file();
617 ff_err(ret, "FFStream::encode_frame: encode failed.\nfile: %s\n",
618 ffmpeg->fmt_ctx->url);
622 int FFStream::flush()
626 int ret = encode_frame(0);
627 if( ret >= 0 && stats_fp ) {
628 ret = write_stats_file();
632 ff_err(ret, "FFStream::flush failed\n:file:%s\n",
633 ffmpeg->fmt_ctx->url);
634 return ret >= 0 ? 0 : 1;
638 int FFStream::open_stats_file()
640 stats_fp = fopen(stats_filename,"w");
641 return stats_fp ? 0 : AVERROR(errno);
644 int FFStream::close_stats_file()
647 fclose(stats_fp); stats_fp = 0;
652 int FFStream::read_stats_file()
654 int64_t len = 0; struct stat stats_st;
655 int fd = open(stats_filename, O_RDONLY);
656 int ret = fd >= 0 ? 0: ENOENT;
657 if( !ret && fstat(fd, &stats_st) )
660 len = stats_st.st_size;
661 stats_in = (char *)av_malloc(len+1);
665 if( !ret && read(fd, stats_in, len+1) != len )
669 avctx->stats_in = stats_in;
673 return !ret ? 0 : AVERROR(ret);
676 int FFStream::write_stats_file()
679 if( avctx->stats_out && (ret=strlen(avctx->stats_out)) > 0 ) {
680 int len = fwrite(avctx->stats_out, 1, ret, stats_fp);
682 ff_err(ret = AVERROR(errno), "FFStream::write_stats_file.\n%file:%s\n",
683 ffmpeg->fmt_ctx->url);
688 int FFStream::init_stats_file()
691 if( (pass & 2) && (ret = read_stats_file()) < 0 )
692 ff_err(ret, "stat file read: %s", stats_filename);
693 if( (pass & 1) && (ret=open_stats_file()) < 0 )
694 ff_err(ret, "stat file open: %s", stats_filename);
695 return ret >= 0 ? 0 : ret;
698 int FFStream::seek(int64_t no, double rate)
700 // default ffmpeg native seek
702 int64_t pos = no, pkt_pos = -1;
703 IndexMarks *index_markers = get_markers();
704 if( index_markers && index_markers->size() > 1 ) {
705 IndexMarks &marks = *index_markers;
706 int i = marks.find(pos);
707 int64_t n = i < 0 ? (i=0) : marks[i].no;
708 // if indexed seek point not too far away (<30 secs), use index
709 if( no-n < 30*rate ) {
712 if( i < marks.size() ) pkt_pos = marks[i].pos;
716 if( pos == curr_pos ) return 0;
717 double secs = pos < 0 ? 0. : pos / rate;
718 AVRational time_base = st->time_base;
719 int64_t tstmp = time_base.num > 0 ? secs * time_base.den/time_base.num : 0;
721 if( st->nb_index_entries > 0 ) tstmp = st->index_entries[0].timestamp;
722 else if( st->start_time != AV_NOPTS_VALUE ) tstmp = st->start_time;
723 else if( st->first_dts != AV_NOPTS_VALUE ) tstmp = st->first_dts;
724 else tstmp = INT64_MIN+1;
726 else if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
729 // seek all streams using the default timebase.
730 // this is how ffmpeg and ffplay work. stream seeks are less tested.
731 tstmp = av_rescale_q(tstmp, time_base, AV_TIME_BASE_Q);
734 frm_lock->lock("FFStream::seek");
735 av_frame_free(&probe_frame);
736 avcodec_flush_buffers(avctx);
737 avformat_flush(fmt_ctx);
739 int64_t seek = tstmp;
740 int flags = AVSEEK_FLAG_ANY;
741 if( !(fmt_ctx->iformat->flags & AVFMT_NO_BYTE_SEEK) && pkt_pos >= 0 ) {
743 flags = AVSEEK_FLAG_BYTE;
745 int ret = avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, seek, INT64_MAX, flags);
747 // finds the first index frame below the target time
748 int flags = AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_ANY;
749 int ret = av_seek_frame(fmt_ctx, idx, tstmp, flags);
751 int retry = MAX_RETRY;
753 need_packet = 0; flushed = 0;
754 seeked = 1; st_eof(0);
755 // read up to retry packets, limited to npkts in stream, and not pkt.pos past pkt_pos
756 while( --retry >= 0 ) {
757 if( read_packet() <= 0 ) { ret = -1; break; }
758 if( ipkt->stream_index != st->index ) continue;
759 if( !ipkt->data || !ipkt->size ) continue;
760 if( pkt_pos >= 0 && ipkt->pos >= pkt_pos ) break;
761 if( --npkts <= 0 ) break;
762 int64_t pkt_ts = ipkt->dts != AV_NOPTS_VALUE ? ipkt->dts : ipkt->pts;
763 if( pkt_ts == AV_NOPTS_VALUE ) continue;
764 if( pkt_ts >= tstmp ) break;
767 ff_err(AVERROR(EIO), "FFStream::seek: %s\n"
768 " retry limit, pos=%jd tstmp=%jd, ",
769 ffmpeg->fmt_ctx->url, pos, tstmp);
773 ret = avcodec_send_packet(avctx, ipkt);
775 //some codecs need more than one pkt to resync
776 if( ret == AVERROR_INVALIDDATA ) ret = 0;
778 ff_err(ret, "FFStream::avcodec_send_packet failed.\nseek:%s\n",
779 ffmpeg->fmt_ctx->url);
785 printf("** seek fail %jd, %jd\n", pos, tstmp);
786 seeked = need_packet = 0;
790 //printf("seeked pos = %ld, %ld\n", pos, tstmp);
791 seek_pos = curr_pos = pos;
795 FFAudioStream::FFAudioStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
796 : FFStream(ffmpeg, strm, fidx)
799 channel0 = channels = 0;
802 frame_sz = AUDIO_MIN_FRAME_SZ;
804 resample_context = 0;
805 swr_ichs = swr_ifmt = swr_irate = 0;
814 bfr = new float[bsz];
819 FFAudioStream::~FFAudioStream()
821 if( resample_context ) swr_free(&resample_context);
826 void FFAudioStream::init_swr(int ichs, int ifmt, int irate)
828 if( resample_context ) {
829 if( swr_ichs == ichs && swr_ifmt == ifmt && swr_irate == irate )
831 swr_free(&resample_context);
833 swr_ichs = ichs; swr_ifmt = ifmt; swr_irate = irate;
834 if( ichs == channels && ifmt == AV_SAMPLE_FMT_FLT && irate == sample_rate )
836 uint64_t ilayout = av_get_default_channel_layout(ichs);
837 if( !ilayout ) ilayout = ((uint64_t)1<<ichs) - 1;
838 uint64_t olayout = av_get_default_channel_layout(channels);
839 if( !olayout ) olayout = ((uint64_t)1<<channels) - 1;
840 resample_context = swr_alloc_set_opts(NULL,
841 olayout, AV_SAMPLE_FMT_FLT, sample_rate,
842 ilayout, (AVSampleFormat)ifmt, irate,
844 if( resample_context )
845 swr_init(resample_context);
848 int FFAudioStream::get_samples(float *&samples, uint8_t **data, int len)
850 samples = *(float **)data;
851 if( resample_context ) {
852 if( len > aud_bfr_sz ) {
858 aud_bfr = new float[aud_bfr_sz*channels];
860 int ret = swr_convert(resample_context,
861 (uint8_t**)&aud_bfr, aud_bfr_sz, (const uint8_t**)data, len);
863 ff_err(ret, "FFAudioStream::get_samples: swr_convert failed\n");
872 int FFAudioStream::load_history(uint8_t **data, int len)
875 len = get_samples(samples, data, len);
877 // biggest user bfr since seek + frame
878 realloc(mbsz + len + 1, channels);
884 int FFAudioStream::decode_frame(AVFrame *frame)
886 int first_frame = seeked; seeked = 0;
887 frame->best_effort_timestamp = AV_NOPTS_VALUE;
888 int ret = avcodec_receive_frame(avctx, frame);
890 if( first_frame ) return 0;
891 if( ret == AVERROR(EAGAIN) ) return 0;
892 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
893 ff_err(ret, "FFAudioStream::decode_frame: Could not read audio frame.\nfile:%s\n",
894 ffmpeg->fmt_ctx->url);
897 int64_t pkt_ts = frame->best_effort_timestamp;
898 if( pkt_ts != AV_NOPTS_VALUE ) {
899 double ts = ffmpeg->to_secs(pkt_ts - nudge, st->time_base);
900 double t = (double)curr_pos / sample_rate;
901 // some time_base clocks are very grainy, too grainy for audio (clicks, pops)
902 if( fabs(ts - t) > AUDIO_PTS_TOLERANCE )
903 curr_pos = ts * sample_rate + 0.5;
908 int FFAudioStream::encode_activate()
910 if( writing >= 0 ) return writing;
911 if( !avctx->codec ) return writing = 0;
912 frame_sz = avctx->codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE ?
913 10000 : avctx->frame_size;
914 return FFStream::encode_activate();
917 int64_t FFAudioStream::load_buffer(double ** const sp, int len)
919 reserve(len+1, st->codecpar->channels);
920 for( int ch=0; ch<nch; ++ch )
921 write(sp[ch], len, ch);
925 int FFAudioStream::in_history(int64_t pos)
927 if( pos > curr_pos ) return 0;
929 if( len > sz ) len = sz;
930 if( pos < curr_pos - len ) return 0;
935 int FFAudioStream::init_frame(AVFrame *frame)
937 frame->nb_samples = frame_sz;
938 frame->format = avctx->sample_fmt;
939 frame->channel_layout = avctx->channel_layout;
940 frame->sample_rate = avctx->sample_rate;
941 int ret = av_frame_get_buffer(frame, 0);
943 ff_err(ret, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
947 int FFAudioStream::load(int64_t pos, int len)
949 if( audio_seek(pos) < 0 ) return -1;
950 if( !frame && !(frame=av_frame_alloc()) ) {
951 fprintf(stderr, "FFAudioStream::load: av_frame_alloc failed\n");
954 if( mbsz < len ) mbsz = len;
955 int64_t end_pos = pos + len;
956 int ret = 0, i = len / frame_sz + MAX_RETRY;
957 while( ret>=0 && !flushed && curr_pos<end_pos && --i>=0 ) {
958 ret = read_frame(frame);
959 if( ret > 0 && frame->nb_samples > 0 ) {
960 init_swr(frame->channels, frame->format, frame->sample_rate);
961 load_history(&frame->extended_data[0], frame->nb_samples);
962 curr_pos += frame->nb_samples;
965 if( end_pos > curr_pos ) {
966 zero(end_pos - curr_pos);
969 len = curr_pos - pos;
974 int FFAudioStream::audio_seek(int64_t pos)
976 if( decode_activate() <= 0 ) return -1;
977 if( !st->codecpar ) return -1;
978 if( in_history(pos) ) return 0;
979 if( pos == curr_pos ) return 0;
980 reset_history(); mbsz = 0;
981 // guarentee preload > 1sec samples
982 if( (pos-=sample_rate) < 0 ) pos = 0;
983 if( seek(pos, sample_rate) < 0 ) return -1;
987 int FFAudioStream::encode(double **samples, int len)
989 if( encode_activate() <= 0 ) return -1;
992 int64_t count = samples ? load_buffer(samples, len) : used();
993 int frame_sz1 = samples ? frame_sz-1 : 0;
996 while( ret >= 0 && count > frame_sz1 ) {
997 frm = new FFrame(this);
998 if( (ret=frm->initted()) < 0 ) break;
999 AVFrame *frame = *frm;
1000 len = count >= frame_sz ? frame_sz : count;
1001 float *bfrp = get_outp(len);
1002 ret = swr_convert(resample_context,
1003 (uint8_t **)frame->extended_data, len,
1004 (const uint8_t **)&bfrp, len);
1006 ff_err(ret, "FFAudioStream::encode: swr_convert failed\n");
1009 frame->nb_samples = len;
1010 frm->queue(curr_pos);
1017 return ret >= 0 ? 0 : 1;
1020 int FFAudioStream::drain()
1025 int FFAudioStream::encode_frame(AVFrame *frame)
1027 return FFStream::encode_frame(frame);
1030 int FFAudioStream::write_packet(FFPacket &pkt)
1032 return FFStream::write_packet(pkt);
1035 void FFAudioStream::load_markers()
1037 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1038 if( !index_state || idx >= index_state->audio_markers.size() ) return;
1039 if( index_state->marker_status == MARKERS_NOTTESTED ) return;
1040 FFStream::load_markers(*index_state->audio_markers[idx], sample_rate);
1043 IndexMarks *FFAudioStream::get_markers()
1045 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1046 if( !index_state || idx >= index_state->audio_markers.size() ) return 0;
1047 return index_state->audio_markers[idx];
1050 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
1051 : FFStream(ffmpeg, strm, fidx),
1052 FFVideoConvert(ffmpeg->ff_prefs())
1061 top_field_first = 0;
1067 FFVideoStream::~FFVideoStream()
1069 if( fconvert_ctx ) sws_freeContext(fconvert_ctx);
1072 AVHWDeviceType FFVideoStream::decode_hw_activate()
1074 AVHWDeviceType type = AV_HWDEVICE_TYPE_NONE;
1075 const char *hw_dev = ffmpeg->opt_hw_dev;
1076 if( !hw_dev ) hw_dev = getenv("CIN_HW_DEV");
1077 if( !hw_dev ) hw_dev = ffmpeg->ff_hw_dev();
1078 if( hw_dev && *hw_dev &&
1079 strcmp("none", hw_dev) && strcmp(_("none"), hw_dev) ) {
1080 type = av_hwdevice_find_type_by_name(hw_dev);
1081 if( type == AV_HWDEVICE_TYPE_NONE ) {
1082 fprintf(stderr, "Device type %s is not supported.\n", hw_dev);
1083 fprintf(stderr, "Available device types:");
1084 while( (type = av_hwdevice_iterate_types(type)) != AV_HWDEVICE_TYPE_NONE )
1085 fprintf(stderr, " %s", av_hwdevice_get_type_name(type));
1086 fprintf(stderr, "\n");
1092 int FFVideoStream::decode_hw_format(AVCodec *decoder, AVHWDeviceType type)
1095 hw_pix_fmt = AV_PIX_FMT_NONE;
1096 for( int i=0; ; ++i ) {
1097 const AVCodecHWConfig *config = avcodec_get_hw_config(decoder, i);
1099 fprintf(stderr, "Decoder %s does not support device type %s.\n",
1100 decoder->name, av_hwdevice_get_type_name(type));
1104 if( (config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX) != 0 &&
1105 config->device_type == type ) {
1106 hw_pix_fmt = config->pix_fmt;
1110 if( hw_pix_fmt >= 0 ) {
1111 hw_pixfmt = hw_pix_fmt;
1112 avctx->get_format = get_hw_format;
1113 ret = av_hwdevice_ctx_create(&hw_device_ctx, type, 0, 0, 0);
1115 avctx->hw_device_ctx = av_buffer_ref(hw_device_ctx);
1119 ff_err(ret, "Failed HW device create.\ndev:%s\n",
1120 av_hwdevice_get_type_name(type));
1127 AVHWDeviceType FFVideoStream::encode_hw_activate(const char *hw_dev)
1129 AVBufferRef *hw_device_ctx = 0;
1130 AVBufferRef *hw_frames_ref = 0;
1131 AVHWDeviceType type = AV_HWDEVICE_TYPE_NONE;
1132 if( strcmp(_("none"), hw_dev) ) {
1133 type = av_hwdevice_find_type_by_name(hw_dev);
1134 if( type != AV_HWDEVICE_TYPE_VAAPI ) {
1135 fprintf(stderr, "currently, only vaapi hw encode is supported\n");
1136 type = AV_HWDEVICE_TYPE_NONE;
1139 if( type != AV_HWDEVICE_TYPE_NONE ) {
1140 int ret = av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_VAAPI, 0, 0, 0);
1142 ff_err(ret, "Failed to create a HW device.\n");
1143 type = AV_HWDEVICE_TYPE_NONE;
1146 if( type != AV_HWDEVICE_TYPE_NONE ) {
1147 hw_frames_ref = av_hwframe_ctx_alloc(hw_device_ctx);
1148 if( !hw_frames_ref ) {
1149 fprintf(stderr, "Failed to create HW frame context.\n");
1150 type = AV_HWDEVICE_TYPE_NONE;
1153 if( type != AV_HWDEVICE_TYPE_NONE ) {
1154 AVHWFramesContext *frames_ctx = (AVHWFramesContext *)(hw_frames_ref->data);
1155 frames_ctx->format = AV_PIX_FMT_VAAPI;
1156 frames_ctx->sw_format = AV_PIX_FMT_NV12;
1157 frames_ctx->width = width;
1158 frames_ctx->height = height;
1159 frames_ctx->initial_pool_size = 0; // 200;
1160 int ret = av_hwframe_ctx_init(hw_frames_ref);
1162 avctx->hw_frames_ctx = av_buffer_ref(hw_frames_ref);
1163 if( !avctx->hw_frames_ctx ) ret = AVERROR(ENOMEM);
1166 ff_err(ret, "Failed to initialize HW frame context.\n");
1167 type = AV_HWDEVICE_TYPE_NONE;
1169 av_buffer_unref(&hw_frames_ref);
1174 int FFVideoStream::encode_hw_write(FFrame *picture)
1177 AVFrame *hw_frm = 0;
1178 switch( avctx->pix_fmt ) {
1179 case AV_PIX_FMT_VAAPI:
1180 hw_frm = av_frame_alloc();
1181 if( !hw_frm ) { ret = AVERROR(ENOMEM); break; }
1182 ret = av_hwframe_get_buffer(avctx->hw_frames_ctx, hw_frm, 0);
1183 if( ret < 0 ) break;
1184 ret = av_hwframe_transfer_data(hw_frm, *picture, 0);
1185 if( ret < 0 ) break;
1186 picture->set_hw_frame(hw_frm);
1191 av_frame_free(&hw_frm);
1192 ff_err(ret, "Error while transferring frame data to GPU.\n");
1196 int FFVideoStream::decode_frame(AVFrame *frame)
1198 int first_frame = seeked; seeked = 0;
1199 int ret = avcodec_receive_frame(avctx, frame);
1201 if( first_frame ) return 0;
1202 if( ret == AVERROR(EAGAIN) ) return 0;
1203 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
1204 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame.\nfile:%s\n,",
1205 ffmpeg->fmt_ctx->url);
1208 int64_t pkt_ts = frame->best_effort_timestamp;
1209 if( pkt_ts != AV_NOPTS_VALUE )
1210 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * frame_rate + 0.5;
1214 int FFVideoStream::load(VFrame *vframe, int64_t pos)
1216 int ret = video_seek(pos);
1217 if( ret < 0 ) return -1;
1218 if( !frame && !(frame=av_frame_alloc()) ) {
1219 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
1222 int i = MAX_RETRY + pos - curr_pos;
1223 while( ret>=0 && !flushed && curr_pos<=pos && --i>=0 ) {
1224 ret = read_frame(frame);
1225 if( ret > 0 ) ++curr_pos;
1227 if( frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0 )
1230 ret = convert_cmodel(vframe, frame);
1232 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
1236 int FFVideoStream::video_seek(int64_t pos)
1238 if( decode_activate() <= 0 ) return -1;
1239 if( !st->codecpar ) return -1;
1240 if( pos == curr_pos-1 && !seeked ) return 0;
1241 // if close enough, just read up to current
1242 int gop = avctx->gop_size;
1243 if( gop < 4 ) gop = 4;
1244 if( gop > 64 ) gop = 64;
1245 int read_limit = curr_pos + 3*gop;
1246 if( pos >= curr_pos && pos <= read_limit ) return 0;
1247 // guarentee preload more than 2*gop frames
1248 if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
1252 int FFVideoStream::init_frame(AVFrame *picture)
1254 switch( avctx->pix_fmt ) {
1255 case AV_PIX_FMT_VAAPI:
1256 picture->format = AV_PIX_FMT_NV12;
1259 picture->format = avctx->pix_fmt;
1262 picture->width = avctx->width;
1263 picture->height = avctx->height;
1264 int ret = av_frame_get_buffer(picture, 32);
1268 int FFVideoStream::convert_hw_frame(AVFrame *ifrm, AVFrame *ofrm)
1270 AVPixelFormat ifmt = (AVPixelFormat)ifrm->format;
1271 AVPixelFormat ofmt = (AVPixelFormat)st->codecpar->format;
1272 ofrm->width = ifrm->width;
1273 ofrm->height = ifrm->height;
1274 ofrm->format = ofmt;
1275 int ret = av_frame_get_buffer(ofrm, 32);
1277 ff_err(ret, "FFVideoStream::convert_hw_frame:"
1278 " av_frame_get_buffer failed\n");
1281 fconvert_ctx = sws_getCachedContext(fconvert_ctx,
1282 ifrm->width, ifrm->height, ifmt,
1283 ofrm->width, ofrm->height, ofmt,
1284 SWS_POINT, NULL, NULL, NULL);
1285 if( !fconvert_ctx ) {
1286 ff_err(AVERROR(EINVAL), "FFVideoStream::convert_hw_frame:"
1287 " sws_getCachedContext() failed\n");
1290 int codec_range = st->codecpar->color_range;
1291 int codec_space = st->codecpar->color_space;
1292 const int *codec_table = sws_getCoefficients(codec_space);
1293 int *inv_table, *table, src_range, dst_range;
1294 int brightness, contrast, saturation;
1295 if( !sws_getColorspaceDetails(fconvert_ctx,
1296 &inv_table, &src_range, &table, &dst_range,
1297 &brightness, &contrast, &saturation) ) {
1298 if( src_range != codec_range || dst_range != codec_range ||
1299 inv_table != codec_table || table != codec_table )
1300 sws_setColorspaceDetails(fconvert_ctx,
1301 codec_table, codec_range, codec_table, codec_range,
1302 brightness, contrast, saturation);
1304 ret = sws_scale(fconvert_ctx,
1305 ifrm->data, ifrm->linesize, 0, ifrm->height,
1306 ofrm->data, ofrm->linesize);
1308 ff_err(ret, "FFVideoStream::convert_hw_frame:"
1309 " sws_scale() failed\nfile: %s\n",
1310 ffmpeg->fmt_ctx->url);
1316 int FFVideoStream::load_filter(AVFrame *frame)
1318 AVPixelFormat pix_fmt = (AVPixelFormat)frame->format;
1319 if( pix_fmt == hw_pixfmt ) {
1320 AVFrame *hw_frame = this->frame;
1321 av_frame_unref(hw_frame);
1322 int ret = av_hwframe_transfer_data(hw_frame, frame, 0);
1324 eprintf(_("Error retrieving data from GPU to CPU\nfile: %s\n"),
1325 ffmpeg->fmt_ctx->url);
1328 av_frame_unref(frame);
1329 ret = convert_hw_frame(hw_frame, frame);
1331 eprintf(_("Error converting data from GPU to CPU\nfile: %s\n"),
1332 ffmpeg->fmt_ctx->url);
1335 av_frame_unref(hw_frame);
1337 return FFStream::load_filter(frame);
1340 int FFVideoStream::encode(VFrame *vframe)
1342 if( encode_activate() <= 0 ) return -1;
1344 FFrame *picture = new FFrame(this);
1345 int ret = picture->initted();
1347 AVFrame *frame = *picture;
1348 frame->pts = curr_pos;
1349 ret = convert_pixfmt(vframe, frame);
1351 if( ret >= 0 && avctx->hw_frames_ctx )
1352 encode_hw_write(picture);
1354 picture->queue(curr_pos);
1358 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
1361 return ret >= 0 ? 0 : 1;
1364 int FFVideoStream::drain()
1369 int FFVideoStream::encode_frame(AVFrame *frame)
1372 frame->interlaced_frame = interlaced;
1373 frame->top_field_first = top_field_first;
1375 if( frame && frame->format == AV_PIX_FMT_VAAPI ) { // ugly
1376 int ret = avcodec_send_frame(avctx, frame);
1377 for( int retry=MAX_RETRY; !ret && --retry>=0; ) {
1378 FFPacket pkt; av_init_packet(pkt);
1379 pkt->data = NULL; pkt->size = 0;
1380 if( (ret=avcodec_receive_packet(avctx, pkt)) < 0 ) {
1381 if( ret == AVERROR(EAGAIN) ) ret = 0; // weird
1384 ret = write_packet(pkt);
1385 pkt->stream_index = 0;
1386 av_packet_unref(pkt);
1389 ff_err(ret, "FFStream::encode_frame: vaapi encode failed.\nfile: %s\n",
1390 ffmpeg->fmt_ctx->url);
1395 return FFStream::encode_frame(frame);
1398 int FFVideoStream::write_packet(FFPacket &pkt)
1400 if( !(ffmpeg->fmt_ctx->oformat->flags & AVFMT_VARIABLE_FPS) )
1402 return FFStream::write_packet(pkt);
1405 AVPixelFormat FFVideoConvert::color_model_to_pix_fmt(int color_model)
1407 switch( color_model ) {
1408 case BC_YUV422: return AV_PIX_FMT_YUYV422;
1409 case BC_RGB888: return AV_PIX_FMT_RGB24;
1410 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
1411 case BC_BGR8888: return AV_PIX_FMT_BGR0;
1412 case BC_BGR888: return AV_PIX_FMT_BGR24;
1413 case BC_ARGB8888: return AV_PIX_FMT_ARGB;
1414 case BC_ABGR8888: return AV_PIX_FMT_ABGR;
1415 case BC_RGB8: return AV_PIX_FMT_RGB8;
1416 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
1417 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
1418 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
1419 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
1420 case BC_RGB565: return AV_PIX_FMT_RGB565;
1421 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
1422 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
1423 case BC_AYUV16161616: return AV_PIX_FMT_AYUV64LE;
1424 case BC_GBRP: return AV_PIX_FMT_GBRP;
1428 return AV_PIX_FMT_NB;
1431 int FFVideoConvert::pix_fmt_to_color_model(AVPixelFormat pix_fmt)
1434 case AV_PIX_FMT_YUYV422: return BC_YUV422;
1435 case AV_PIX_FMT_RGB24: return BC_RGB888;
1436 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
1437 case AV_PIX_FMT_BGR0: return BC_BGR8888;
1438 case AV_PIX_FMT_BGR24: return BC_BGR888;
1439 case AV_PIX_FMT_ARGB: return BC_ARGB8888;
1440 case AV_PIX_FMT_ABGR: return BC_ABGR8888;
1441 case AV_PIX_FMT_RGB8: return BC_RGB8;
1442 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
1443 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
1444 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
1445 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
1446 case AV_PIX_FMT_RGB565: return BC_RGB565;
1447 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
1448 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
1449 case AV_PIX_FMT_AYUV64LE: return BC_AYUV16161616;
1450 case AV_PIX_FMT_GBRP: return BC_GBRP;
1457 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip)
1459 AVFrame *ipic = av_frame_alloc();
1460 int ret = convert_picture_vframe(frame, ip, ipic);
1461 av_frame_free(&ipic);
1465 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip, AVFrame *ipic)
1466 { // picture = vframe
1467 int cmodel = frame->get_color_model();
1468 AVPixelFormat ofmt = color_model_to_pix_fmt(cmodel);
1469 if( ofmt == AV_PIX_FMT_NB ) return -1;
1470 int size = av_image_fill_arrays(ipic->data, ipic->linesize,
1471 frame->get_data(), ofmt, frame->get_w(), frame->get_h(), 1);
1472 if( size < 0 ) return -1;
1474 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1475 int ysz = bpp * frame->get_w(), usz = ysz;
1485 // override av_image_fill_arrays() for planar types
1486 ipic->data[0] = frame->get_y(); ipic->linesize[0] = ysz;
1487 ipic->data[1] = frame->get_u(); ipic->linesize[1] = usz;
1488 ipic->data[2] = frame->get_v(); ipic->linesize[2] = usz;
1491 ipic->data[0] = frame->get_data();
1492 ipic->linesize[0] = frame->get_bytes_per_line();
1496 AVPixelFormat pix_fmt = (AVPixelFormat)ip->format;
1497 FFVideoStream *vid =(FFVideoStream *)this;
1498 if( pix_fmt == vid->hw_pixfmt ) {
1500 if( !sw_frame && !(sw_frame=av_frame_alloc()) )
1501 ret = AVERROR(ENOMEM);
1503 ret = av_hwframe_transfer_data(sw_frame, ip, 0);
1505 pix_fmt = (AVPixelFormat)ip->format;
1508 eprintf(_("Error retrieving data from GPU to CPU\nfile: %s\n"),
1509 vid->ffmpeg->fmt_ctx->url);
1513 convert_ctx = sws_getCachedContext(convert_ctx, ip->width, ip->height, pix_fmt,
1514 frame->get_w(), frame->get_h(), ofmt, SWS_POINT, NULL, NULL, NULL);
1515 if( !convert_ctx ) {
1516 fprintf(stderr, "FFVideoConvert::convert_picture_frame:"
1517 " sws_getCachedContext() failed\n");
1521 int color_range = 0;
1522 switch( preferences->yuv_color_range ) {
1523 case BC_COLORS_JPEG: color_range = 1; break;
1524 case BC_COLORS_MPEG: color_range = 0; break;
1526 int color_space = SWS_CS_ITU601;
1527 switch( preferences->yuv_color_space ) {
1528 case BC_COLORS_BT601: color_space = SWS_CS_ITU601; break;
1529 case BC_COLORS_BT709: color_space = SWS_CS_ITU709; break;
1530 case BC_COLORS_BT2020: color_space = SWS_CS_BT2020; break;
1532 const int *color_table = sws_getCoefficients(color_space);
1534 int *inv_table, *table, src_range, dst_range;
1535 int brightness, contrast, saturation;
1536 if( !sws_getColorspaceDetails(convert_ctx,
1537 &inv_table, &src_range, &table, &dst_range,
1538 &brightness, &contrast, &saturation) ) {
1539 if( src_range != color_range || dst_range != color_range ||
1540 inv_table != color_table || table != color_table )
1541 sws_setColorspaceDetails(convert_ctx,
1542 color_table, color_range, color_table, color_range,
1543 brightness, contrast, saturation);
1546 int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ip->height,
1547 ipic->data, ipic->linesize);
1549 ff_err(ret, "FFVideoConvert::convert_picture_frame: sws_scale() failed\nfile: %s\n",
1550 vid->ffmpeg->fmt_ctx->url);
1556 int FFVideoConvert::convert_cmodel(VFrame *frame, AVFrame *ip)
1558 // try direct transfer
1559 if( !convert_picture_vframe(frame, ip) ) return 1;
1560 // use indirect transfer
1561 AVPixelFormat ifmt = (AVPixelFormat)ip->format;
1562 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
1564 for( int i = 0; i <desc->nb_components; ++i ) {
1565 int bits = desc->comp[i].depth;
1566 if( bits > max_bits ) max_bits = bits;
1568 int imodel = pix_fmt_to_color_model(ifmt);
1569 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1570 int cmodel = frame->get_color_model();
1571 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1572 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1573 imodel = cmodel_is_yuv ?
1574 (BC_CModels::has_alpha(cmodel) ?
1576 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1577 (BC_CModels::has_alpha(cmodel) ?
1578 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1579 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1581 VFrame vframe(ip->width, ip->height, imodel);
1582 if( convert_picture_vframe(&vframe, ip) ) return -1;
1583 frame->transfer_from(&vframe);
1587 int FFVideoConvert::transfer_cmodel(VFrame *frame, AVFrame *ifp)
1589 int ret = convert_cmodel(frame, ifp);
1591 const AVDictionary *src = ifp->metadata;
1592 AVDictionaryEntry *t = NULL;
1593 BC_Hash *hp = frame->get_params();
1595 while( (t=av_dict_get(src, "", t, AV_DICT_IGNORE_SUFFIX)) )
1596 hp->update(t->key, t->value);
1601 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op)
1603 AVFrame *opic = av_frame_alloc();
1604 int ret = convert_vframe_picture(frame, op, opic);
1605 av_frame_free(&opic);
1609 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op, AVFrame *opic)
1610 { // vframe = picture
1611 int cmodel = frame->get_color_model();
1612 AVPixelFormat ifmt = color_model_to_pix_fmt(cmodel);
1613 if( ifmt == AV_PIX_FMT_NB ) return -1;
1614 int size = av_image_fill_arrays(opic->data, opic->linesize,
1615 frame->get_data(), ifmt, frame->get_w(), frame->get_h(), 1);
1616 if( size < 0 ) return -1;
1618 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1619 int ysz = bpp * frame->get_w(), usz = ysz;
1629 // override av_image_fill_arrays() for planar types
1630 opic->data[0] = frame->get_y(); opic->linesize[0] = ysz;
1631 opic->data[1] = frame->get_u(); opic->linesize[1] = usz;
1632 opic->data[2] = frame->get_v(); opic->linesize[2] = usz;
1635 opic->data[0] = frame->get_data();
1636 opic->linesize[0] = frame->get_bytes_per_line();
1640 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1641 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(),
1642 ifmt, op->width, op->height, ofmt, SWS_POINT, NULL, NULL, NULL);
1643 if( !convert_ctx ) {
1644 fprintf(stderr, "FFVideoConvert::convert_frame_picture:"
1645 " sws_getCachedContext() failed\n");
1650 int color_range = 0;
1651 switch( preferences->yuv_color_range ) {
1652 case BC_COLORS_JPEG: color_range = 1; break;
1653 case BC_COLORS_MPEG: color_range = 0; break;
1655 int color_space = SWS_CS_ITU601;
1656 switch( preferences->yuv_color_space ) {
1657 case BC_COLORS_BT601: color_space = SWS_CS_ITU601; break;
1658 case BC_COLORS_BT709: color_space = SWS_CS_ITU709; break;
1659 case BC_COLORS_BT2020: color_space = SWS_CS_BT2020; break;
1661 const int *color_table = sws_getCoefficients(color_space);
1663 int *inv_table, *table, src_range, dst_range;
1664 int brightness, contrast, saturation;
1665 if( !sws_getColorspaceDetails(convert_ctx,
1666 &inv_table, &src_range, &table, &dst_range,
1667 &brightness, &contrast, &saturation) ) {
1668 if( dst_range != color_range || table != color_table )
1669 sws_setColorspaceDetails(convert_ctx,
1670 inv_table, src_range, color_table, color_range,
1671 brightness, contrast, saturation);
1674 int ret = sws_scale(convert_ctx, opic->data, opic->linesize, 0, frame->get_h(),
1675 op->data, op->linesize);
1677 ff_err(ret, "FFVideoConvert::convert_frame_picture: sws_scale() failed\n");
1683 int FFVideoConvert::convert_pixfmt(VFrame *frame, AVFrame *op)
1685 // try direct transfer
1686 if( !convert_vframe_picture(frame, op) ) return 1;
1687 // use indirect transfer
1688 int cmodel = frame->get_color_model();
1689 int max_bits = BC_CModels::calculate_pixelsize(cmodel) * 8;
1690 max_bits /= BC_CModels::components(cmodel);
1691 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1692 int imodel = pix_fmt_to_color_model(ofmt);
1693 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1694 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1695 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1696 imodel = cmodel_is_yuv ?
1697 (BC_CModels::has_alpha(cmodel) ?
1699 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1700 (BC_CModels::has_alpha(cmodel) ?
1701 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1702 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1704 VFrame vframe(frame->get_w(), frame->get_h(), imodel);
1705 vframe.transfer_from(frame);
1706 if( !convert_vframe_picture(&vframe, op) ) return 1;
1710 int FFVideoConvert::transfer_pixfmt(VFrame *frame, AVFrame *ofp)
1712 int ret = convert_pixfmt(frame, ofp);
1714 BC_Hash *hp = frame->get_params();
1715 AVDictionary **dict = &ofp->metadata;
1716 //av_dict_free(dict);
1717 for( int i=0; i<hp->size(); ++i ) {
1718 char *key = hp->get_key(i), *val = hp->get_value(i);
1719 av_dict_set(dict, key, val, 0);
1725 void FFVideoStream::load_markers()
1727 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1728 if( !index_state || idx >= index_state->video_markers.size() ) return;
1729 FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
1732 IndexMarks *FFVideoStream::get_markers()
1734 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1735 if( !index_state || idx >= index_state->video_markers.size() ) return 0;
1736 return !index_state ? 0 : index_state->video_markers[idx];
1740 FFMPEG::FFMPEG(FileBase *file_base)
1743 this->file_base = file_base;
1744 memset(file_format,0,sizeof(file_format));
1745 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
1746 flow_lock = new Condition(1,"FFStream::flow_lock",0);
1749 decoding = encoding = 0;
1750 has_audio = has_video = 0;
1753 opt_video_filter = 0;
1754 opt_audio_filter = 0;
1756 opt_video_decoder = 0;
1757 opt_audio_decoder = 0;
1759 char option_path[BCTEXTLEN];
1760 set_option_path(option_path, "%s", "ffmpeg.opts");
1761 read_options(option_path, opts);
1766 ff_lock("FFMPEG::~FFMPEG()");
1768 ffaudio.remove_all_objects();
1769 ffvideo.remove_all_objects();
1770 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1774 av_dict_free(&opts);
1775 delete [] opt_video_filter;
1776 delete [] opt_audio_filter;
1777 delete [] opt_hw_dev;
1780 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1782 const int *p = codec->supported_samplerates;
1783 if( !p ) return sample_rate;
1785 if( *p == sample_rate ) return *p;
1791 static inline AVRational std_frame_rate(int i)
1793 static const int m1 = 1001*12, m2 = 1000*12;
1794 static const int freqs[] = {
1795 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1796 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
1798 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1799 return (AVRational) { freq, 1001*12 };
1802 AVRational FFMPEG::check_frame_rate(const AVRational *p, double frame_rate)
1804 AVRational rate, best_rate = (AVRational) { 0, 0 };
1805 double max_err = 1.; int i = 0;
1806 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1807 double framerate = (double) rate.num / rate.den;
1808 double err = fabs(frame_rate/framerate - 1.);
1809 if( err >= max_err ) continue;
1813 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1816 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1819 double display_aspect = asset->width / (double)asset->height;
1820 double sample_aspect = display_aspect / asset->aspect_ratio;
1821 int width = 1000000, height = width * sample_aspect + 0.5;
1823 MWindow::create_aspect_ratio(w, h, width, height);
1824 return (AVRational){(int)w, (int)h};
1827 return (AVRational){1, 1};
1831 AVRational FFMPEG::to_time_base(int sample_rate)
1833 return (AVRational){1, sample_rate};
1836 int FFMPEG::get_fmt_score(AVSampleFormat dst_fmt, AVSampleFormat src_fmt)
1839 int dst_planar = av_sample_fmt_is_planar(dst_fmt);
1840 int src_planar = av_sample_fmt_is_planar(src_fmt);
1841 if( dst_planar != src_planar ) ++score;
1842 int dst_bytes = av_get_bytes_per_sample(dst_fmt);
1843 int src_bytes = av_get_bytes_per_sample(src_fmt);
1844 score += (src_bytes > dst_bytes ? 100 : -10) * (src_bytes - dst_bytes);
1845 int src_packed = av_get_packed_sample_fmt(src_fmt);
1846 int dst_packed = av_get_packed_sample_fmt(dst_fmt);
1847 if( dst_packed == AV_SAMPLE_FMT_S32 && src_packed == AV_SAMPLE_FMT_FLT ) score += 20;
1848 if( dst_packed == AV_SAMPLE_FMT_FLT && src_packed == AV_SAMPLE_FMT_S32 ) score += 2;
1852 AVSampleFormat FFMPEG::find_best_sample_fmt_of_list(
1853 const AVSampleFormat *sample_fmts, AVSampleFormat src_fmt)
1855 AVSampleFormat best = AV_SAMPLE_FMT_NONE;
1856 int best_score = get_fmt_score(best, src_fmt);
1857 for( int i=0; sample_fmts[i] >= 0; ++i ) {
1858 AVSampleFormat sample_fmt = sample_fmts[i];
1859 int score = get_fmt_score(sample_fmt, src_fmt);
1860 if( score >= best_score ) continue;
1861 best = sample_fmt; best_score = score;
1867 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
1869 char *ep = path + BCTEXTLEN-1;
1870 strncpy(path, File::get_cindat_path(), ep-path);
1871 strncat(path, "/ffmpeg/", ep-path);
1872 path += strlen(path);
1875 path += vsnprintf(path, ep-path, fmt, ap);
1880 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
1885 set_option_path(path, "%s/%s", type, spec);
1888 int FFMPEG::get_format(char *format, const char *path, const char *spec)
1890 char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
1891 get_option_path(option_path, path, spec);
1892 FILE *fp = fopen(option_path,"r");
1895 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1897 line[sizeof(line)-1] = 0;
1898 ret = scan_option_line(line, format, codec);
1904 int FFMPEG::get_codec(char *codec, const char *path, const char *spec)
1906 char option_path[BCTEXTLEN], line[BCTEXTLEN], format[BCTEXTLEN];
1907 get_option_path(option_path, path, spec);
1908 FILE *fp = fopen(option_path,"r");
1911 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1914 line[sizeof(line)-1] = 0;
1915 ret = scan_option_line(line, format, codec);
1918 char *vp = codec, *ep = vp+BCTEXTLEN-1;
1919 while( vp < ep && *vp && *vp != '|' ) ++vp;
1920 if( *vp == '|' ) --vp;
1921 while( vp > codec && (*vp==' ' || *vp=='\t') ) *vp-- = 0;
1926 int FFMPEG::get_file_format()
1928 char audio_muxer[BCSTRLEN], video_muxer[BCSTRLEN];
1929 char audio_format[BCSTRLEN], video_format[BCSTRLEN];
1930 audio_muxer[0] = audio_format[0] = 0;
1931 video_muxer[0] = video_format[0] = 0;
1932 Asset *asset = file_base->asset;
1933 int ret = asset ? 0 : 1;
1934 if( !ret && asset->audio_data ) {
1935 if( !(ret=get_format(audio_format, "audio", asset->acodec)) ) {
1936 if( get_format(audio_muxer, "format", audio_format) ) {
1937 strcpy(audio_muxer, audio_format);
1938 audio_format[0] = 0;
1942 if( !ret && asset->video_data ) {
1943 if( !(ret=get_format(video_format, "video", asset->vcodec)) ) {
1944 if( get_format(video_muxer, "format", video_format) ) {
1945 strcpy(video_muxer, video_format);
1946 video_format[0] = 0;
1950 if( !ret && !audio_muxer[0] && !video_muxer[0] )
1952 if( !ret && audio_muxer[0] && video_muxer[0] &&
1953 strcmp(audio_muxer, video_muxer) ) ret = -1;
1954 if( !ret && audio_format[0] && video_format[0] &&
1955 strcmp(audio_format, video_format) ) ret = -1;
1957 strcpy(file_format, !audio_format[0] && !video_format[0] ?
1958 (audio_muxer[0] ? audio_muxer : video_muxer) :
1959 (audio_format[0] ? audio_format : video_format));
1963 int FFMPEG::scan_option_line(const char *cp, char *tag, char *val)
1965 while( *cp == ' ' || *cp == '\t' ) ++cp;
1966 const char *bp = cp;
1967 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' && *cp != '\n' ) ++cp;
1969 if( !len || len > BCSTRLEN-1 ) return 1;
1970 while( bp < cp ) *tag++ = *bp++;
1972 while( *cp == ' ' || *cp == '\t' ) ++cp;
1973 if( *cp == '=' ) ++cp;
1974 while( *cp == ' ' || *cp == '\t' ) ++cp;
1976 while( *cp && *cp != '\n' ) ++cp;
1978 if( len > BCTEXTLEN-1 ) return 1;
1979 while( bp < cp ) *val++ = *bp++;
1984 int FFMPEG::can_render(const char *fformat, const char *type)
1987 char option_path[BCTEXTLEN];
1988 FFMPEG::set_option_path(option_path, type);
1989 fs.update(option_path);
1990 int total_files = fs.total_files();
1991 for( int i=0; i<total_files; ++i ) {
1992 const char *name = fs.get_entry(i)->get_name();
1993 const char *ext = strrchr(name,'.');
1994 if( !ext ) continue;
1995 if( !strcmp(fformat, ++ext) ) return 1;
2000 int FFMPEG::get_ff_option(const char *nm, const char *options, char *value)
2002 for( const char *cp=options; *cp!=0; ) {
2003 char line[BCTEXTLEN], *bp = line, *ep = bp+sizeof(line)-1;
2004 while( bp < ep && *cp && *cp!='\n' ) *bp++ = *cp++;
2007 if( !line[0] || line[0] == '#' || line[0] == ';' ) continue;
2008 char key[BCSTRLEN], val[BCTEXTLEN];
2009 if( FFMPEG::scan_option_line(line, key, val) ) continue;
2010 if( !strcmp(key, nm) ) {
2011 strncpy(value, val, BCSTRLEN);
2018 void FFMPEG::scan_audio_options(Asset *asset, EDL *edl)
2020 char cin_sample_fmt[BCSTRLEN];
2021 int cin_fmt = AV_SAMPLE_FMT_NONE;
2022 const char *options = asset->ff_audio_options;
2023 if( !get_ff_option("cin_sample_fmt", options, cin_sample_fmt) )
2024 cin_fmt = (int)av_get_sample_fmt(cin_sample_fmt);
2026 char audio_codec[BCSTRLEN]; audio_codec[0] = 0;
2027 AVCodec *av_codec = !FFMPEG::get_codec(audio_codec, "audio", asset->acodec) ?
2028 avcodec_find_encoder_by_name(audio_codec) : 0;
2029 if( av_codec && av_codec->sample_fmts )
2030 cin_fmt = find_best_sample_fmt_of_list(av_codec->sample_fmts, AV_SAMPLE_FMT_FLT);
2032 if( cin_fmt < 0 ) cin_fmt = AV_SAMPLE_FMT_S16;
2033 const char *name = av_get_sample_fmt_name((AVSampleFormat)cin_fmt);
2034 if( !name ) name = _("None");
2035 strcpy(asset->ff_sample_format, name);
2037 char value[BCSTRLEN];
2038 if( !get_ff_option("cin_bitrate", options, value) )
2039 asset->ff_audio_bitrate = atoi(value);
2040 if( !get_ff_option("cin_quality", options, value) )
2041 asset->ff_audio_quality = atoi(value);
2044 void FFMPEG::load_audio_options(Asset *asset, EDL *edl)
2046 char options_path[BCTEXTLEN];
2047 set_option_path(options_path, "audio/%s", asset->acodec);
2048 if( !load_options(options_path,
2049 asset->ff_audio_options,
2050 sizeof(asset->ff_audio_options)) )
2051 scan_audio_options(asset, edl);
2054 void FFMPEG::scan_video_options(Asset *asset, EDL *edl)
2056 char cin_pix_fmt[BCSTRLEN];
2057 int cin_fmt = AV_PIX_FMT_NONE;
2058 const char *options = asset->ff_video_options;
2059 if( !get_ff_option("cin_pix_fmt", options, cin_pix_fmt) )
2060 cin_fmt = (int)av_get_pix_fmt(cin_pix_fmt);
2062 char video_codec[BCSTRLEN]; video_codec[0] = 0;
2063 AVCodec *av_codec = !get_codec(video_codec, "video", asset->vcodec) ?
2064 avcodec_find_encoder_by_name(video_codec) : 0;
2065 if( av_codec && av_codec->pix_fmts ) {
2066 if( 0 && edl ) { // frequently picks a bad answer
2067 int color_model = edl->session->color_model;
2068 int max_bits = BC_CModels::calculate_pixelsize(color_model) * 8;
2069 max_bits /= BC_CModels::components(color_model);
2070 cin_fmt = avcodec_find_best_pix_fmt_of_list(av_codec->pix_fmts,
2071 (BC_CModels::is_yuv(color_model) ?
2072 (max_bits > 8 ? AV_PIX_FMT_AYUV64LE : AV_PIX_FMT_YUV444P) :
2073 (max_bits > 8 ? AV_PIX_FMT_RGB48LE : AV_PIX_FMT_RGB24)), 0, 0);
2076 cin_fmt = av_codec->pix_fmts[0];
2079 if( cin_fmt < 0 ) cin_fmt = AV_PIX_FMT_YUV420P;
2080 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get((AVPixelFormat)cin_fmt);
2081 const char *name = desc ? desc->name : _("None");
2082 strcpy(asset->ff_pixel_format, name);
2084 char value[BCSTRLEN];
2085 if( !get_ff_option("cin_bitrate", options, value) )
2086 asset->ff_video_bitrate = atoi(value);
2087 if( !get_ff_option("cin_quality", options, value) )
2088 asset->ff_video_quality = atoi(value);
2091 void FFMPEG::load_video_options(Asset *asset, EDL *edl)
2093 char options_path[BCTEXTLEN];
2094 set_option_path(options_path, "video/%s", asset->vcodec);
2095 if( !load_options(options_path,
2096 asset->ff_video_options,
2097 sizeof(asset->ff_video_options)) )
2098 scan_video_options(asset, edl);
2101 void FFMPEG::scan_format_options(Asset *asset, EDL *edl)
2105 void FFMPEG::load_format_options(Asset *asset, EDL *edl)
2107 char options_path[BCTEXTLEN];
2108 set_option_path(options_path, "format/%s", asset->fformat);
2109 if( !load_options(options_path,
2110 asset->ff_format_options,
2111 sizeof(asset->ff_format_options)) )
2112 scan_format_options(asset, edl);
2115 int FFMPEG::load_defaults(const char *path, const char *type,
2116 char *codec, char *codec_options, int len)
2118 char default_file[BCTEXTLEN];
2119 set_option_path(default_file, "%s/%s.dfl", path, type);
2120 FILE *fp = fopen(default_file,"r");
2122 fgets(codec, BCSTRLEN, fp);
2124 while( *cp && *cp!='\n' ) ++cp;
2126 while( len > 0 && fgets(codec_options, len, fp) ) {
2127 int n = strlen(codec_options);
2128 codec_options += n; len -= n;
2131 set_option_path(default_file, "%s/%s", path, codec);
2132 return load_options(default_file, codec_options, len);
2135 void FFMPEG::set_asset_format(Asset *asset, EDL *edl, const char *text)
2137 if( asset->format != FILE_FFMPEG ) return;
2138 if( text != asset->fformat )
2139 strcpy(asset->fformat, text);
2140 if( !asset->ff_format_options[0] )
2141 load_format_options(asset, edl);
2142 if( asset->audio_data && !asset->ff_audio_options[0] ) {
2143 if( !load_defaults("audio", text, asset->acodec,
2144 asset->ff_audio_options, sizeof(asset->ff_audio_options)) )
2145 scan_audio_options(asset, edl);
2147 asset->audio_data = 0;
2149 if( asset->video_data && !asset->ff_video_options[0] ) {
2150 if( !load_defaults("video", text, asset->vcodec,
2151 asset->ff_video_options, sizeof(asset->ff_video_options)) )
2152 scan_video_options(asset, edl);
2154 asset->video_data = 0;
2158 int FFMPEG::get_encoder(const char *options,
2159 char *format, char *codec, char *bsfilter)
2161 FILE *fp = fopen(options,"r");
2163 eprintf(_("options open failed %s\n"),options);
2166 char line[BCTEXTLEN];
2167 if( !fgets(line, sizeof(line), fp) ||
2168 scan_encoder(line, format, codec, bsfilter) )
2169 eprintf(_("format/codec not found %s\n"), options);
2174 int FFMPEG::scan_encoder(const char *line,
2175 char *format, char *codec, char *bsfilter)
2177 format[0] = codec[0] = bsfilter[0] = 0;
2178 if( scan_option_line(line, format, codec) ) return 1;
2180 while( *cp && *cp != '|' ) ++cp;
2181 if( !*cp ) return 0;
2183 do { *bp-- = 0; } while( bp>=codec && (*bp==' ' || *bp == '\t' ) );
2184 while( *++cp && (*cp==' ' || *cp == '\t') );
2186 for( int i=BCTEXTLEN; --i>0 && *cp; ) *bp++ = *cp++;
2191 int FFMPEG::read_options(const char *options, AVDictionary *&opts, int skip)
2193 FILE *fp = fopen(options,"r");
2196 while( !ret && --skip >= 0 ) {
2198 while( ch >= 0 && ch != '\n' ) ch = getc(fp);
2199 if( ch < 0 ) ret = 1;
2202 ret = read_options(fp, options, opts);
2207 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
2209 FILE *fp = fmemopen((void *)options,strlen(options),"r");
2211 int ret = read_options(fp, options, opts);
2214 AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
2215 if( tag ) st->id = strtol(tag->value,0,0);
2220 FFCodecRemap::FFCodecRemap()
2225 FFCodecRemap::~FFCodecRemap()
2227 delete [] old_codec;
2228 delete [] new_codec;
2231 int FFCodecRemaps::add(const char *val)
2233 char old_codec[BCSTRLEN], new_codec[BCSTRLEN];
2234 if( sscanf(val, " %63[a-zA-z0-9_-] = %63[a-z0-9_-]",
2235 &old_codec[0], &new_codec[0]) != 2 ) return 1;
2236 FFCodecRemap &remap = append();
2237 remap.old_codec = cstrdup(old_codec);
2238 remap.new_codec = cstrdup(new_codec);
2243 int FFCodecRemaps::update(AVCodecID &codec_id, AVCodec *&decoder)
2245 AVCodec *codec = avcodec_find_decoder(codec_id);
2246 if( !codec ) return -1;
2247 const char *name = codec->name;
2248 FFCodecRemaps &map = *this;
2250 while( --k >= 0 && strcmp(map[k].old_codec, name) );
2251 if( k < 0 ) return 1;
2252 const char *new_codec = map[k].new_codec;
2253 codec = avcodec_find_decoder_by_name(new_codec);
2254 if( !codec ) return -1;
2259 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
2261 int ret = 0, no = 0;
2262 char line[BCTEXTLEN];
2263 while( !ret && fgets(line, sizeof(line), fp) ) {
2264 line[sizeof(line)-1] = 0;
2265 if( line[0] == '#' ) continue;
2266 if( line[0] == '\n' ) continue;
2267 char key[BCSTRLEN], val[BCTEXTLEN];
2268 if( scan_option_line(line, key, val) ) {
2269 eprintf(_("err reading %s: line %d\n"), options, no);
2273 if( !strcmp(key, "duration") )
2274 opt_duration = strtod(val, 0);
2275 else if( !strcmp(key, "video_decoder") )
2276 opt_video_decoder = cstrdup(val);
2277 else if( !strcmp(key, "audio_decoder") )
2278 opt_audio_decoder = cstrdup(val);
2279 else if( !strcmp(key, "remap_video_decoder") )
2280 video_codec_remaps.add(val);
2281 else if( !strcmp(key, "remap_audio_decoder") )
2282 audio_codec_remaps.add(val);
2283 else if( !strcmp(key, "video_filter") )
2284 opt_video_filter = cstrdup(val);
2285 else if( !strcmp(key, "audio_filter") )
2286 opt_audio_filter = cstrdup(val);
2287 else if( !strcmp(key, "cin_hw_dev") )
2288 opt_hw_dev = cstrdup(val);
2289 else if( !strcmp(key, "loglevel") )
2292 av_dict_set(&opts, key, val, 0);
2298 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
2300 char option_path[BCTEXTLEN];
2301 set_option_path(option_path, "%s", options);
2302 return read_options(option_path, opts);
2305 int FFMPEG::load_options(const char *path, char *bfr, int len)
2308 FILE *fp = fopen(path, "r");
2310 fgets(bfr, len, fp); // skip hdr
2311 len = fread(bfr, 1, len-1, fp);
2312 if( len < 0 ) len = 0;
2318 void FFMPEG::set_loglevel(const char *ap)
2320 if( !ap || !*ap ) return;
2325 { "quiet" , AV_LOG_QUIET },
2326 { "panic" , AV_LOG_PANIC },
2327 { "fatal" , AV_LOG_FATAL },
2328 { "error" , AV_LOG_ERROR },
2329 { "warning", AV_LOG_WARNING },
2330 { "info" , AV_LOG_INFO },
2331 { "verbose", AV_LOG_VERBOSE },
2332 { "debug" , AV_LOG_DEBUG },
2334 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
2335 if( !strcmp(log_levels[i].name, ap) ) {
2336 av_log_set_level(log_levels[i].level);
2340 av_log_set_level(atoi(ap));
2343 double FFMPEG::to_secs(int64_t time, AVRational time_base)
2345 double base_time = time == AV_NOPTS_VALUE ? 0 :
2346 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
2347 return base_time / AV_TIME_BASE;
2350 int FFMPEG::info(char *text, int len)
2352 if( len <= 0 ) return 0;
2354 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
2356 report("format: %s\n",fmt_ctx->iformat->name);
2357 if( ffvideo.size() > 0 )
2358 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
2359 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
2360 const char *unkn = _("(unkn)");
2361 FFVideoStream *vid = ffvideo[vidx];
2362 AVStream *st = vid->st;
2363 AVCodecID codec_id = st->codecpar->codec_id;
2364 report(_("vid%d (%d), id 0x%06x:\n"), vid->idx, vid->fidx, codec_id);
2365 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
2366 report(" video%d %s ", vidx+1, desc ? desc->name : unkn);
2367 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
2368 AVPixelFormat pix_fmt = (AVPixelFormat)st->codecpar->format;
2369 const char *pfn = av_get_pix_fmt_name(pix_fmt);
2370 report(" pix %s\n", pfn ? pfn : unkn);
2371 enum AVColorSpace space = st->codecpar->color_space;
2372 const char *nm = av_color_space_name(space);
2373 report(" color space:%s", nm ? nm : unkn);
2374 enum AVColorRange range = st->codecpar->color_range;
2375 const char *rg = av_color_range_name(range);
2376 report("/ range:%s\n", rg ? rg : unkn);
2377 double secs = to_secs(st->duration, st->time_base);
2378 int64_t length = secs * vid->frame_rate + 0.5;
2379 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
2380 int64_t nudge = ofs * vid->frame_rate;
2381 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
2382 report(" %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
2383 int hrs = secs/3600; secs -= hrs*3600;
2384 int mins = secs/60; secs -= mins*60;
2385 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
2386 double theta = vid->get_rotation_angle();
2387 if( fabs(theta) > 1 )
2388 report(" rotation angle: %0.1f\n", theta);
2390 if( ffaudio.size() > 0 )
2391 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
2392 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2393 FFAudioStream *aud = ffaudio[aidx];
2394 AVStream *st = aud->st;
2395 AVCodecID codec_id = st->codecpar->codec_id;
2396 report(_("aud%d (%d), id 0x%06x:\n"), aud->idx, aud->fidx, codec_id);
2397 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
2398 int nch = aud->channels, ch0 = aud->channel0+1;
2399 report(" audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
2400 AVSampleFormat sample_fmt = (AVSampleFormat)st->codecpar->format;
2401 const char *fmt = av_get_sample_fmt_name(sample_fmt);
2402 report(" %s %d", fmt, aud->sample_rate);
2403 int sample_bits = av_get_bits_per_sample(codec_id);
2404 report(" %dbits\n", sample_bits);
2405 double secs = to_secs(st->duration, st->time_base);
2406 int64_t length = secs * aud->sample_rate + 0.5;
2407 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
2408 int64_t nudge = ofs * aud->sample_rate;
2409 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
2410 report(" %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
2411 int hrs = secs/3600; secs -= hrs*3600;
2412 int mins = secs/60; secs -= mins*60;
2413 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
2415 if( fmt_ctx->nb_programs > 0 )
2416 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
2417 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
2418 report("program %d", i+1);
2419 AVProgram *pgrm = fmt_ctx->programs[i];
2420 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2421 int idx = pgrm->stream_index[j];
2422 int vidx = ffvideo.size();
2423 while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
2425 report(", vid%d", vidx);
2428 int aidx = ffaudio.size();
2429 while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
2431 report(", aud%d", aidx);
2434 report(", (%d)", pgrm->stream_index[j]);
2439 AVDictionaryEntry *tag = 0;
2440 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
2441 report("%s=%s\n", tag->key, tag->value);
2450 int FFMPEG::init_decoder(const char *filename)
2452 ff_lock("FFMPEG::init_decoder");
2454 char file_opts[BCTEXTLEN];
2455 strcpy(file_opts, filename);
2456 char *bp = strrchr(file_opts, '/');
2457 if( !bp ) bp = file_opts;
2458 char *sp = strrchr(bp, '.');
2459 if( !sp ) sp = bp + strlen(bp);
2461 AVInputFormat *ifmt = 0;
2463 strcpy(sp, ".opts");
2464 fp = fopen(file_opts, "r");
2467 read_options(fp, file_opts, opts);
2469 AVDictionaryEntry *tag;
2470 if( (tag=av_dict_get(opts, "format", NULL, 0)) != 0 ) {
2471 ifmt = av_find_input_format(tag->value);
2475 load_options("decode.opts", opts);
2476 AVDictionary *fopts = 0;
2477 av_dict_copy(&fopts, opts, 0);
2478 int ret = avformat_open_input(&fmt_ctx, filename, ifmt, &fopts);
2479 av_dict_free(&fopts);
2481 ret = avformat_find_stream_info(fmt_ctx, NULL);
2486 return !ret ? 0 : 1;
2489 int FFMPEG::open_decoder()
2492 if( stat(fmt_ctx->url, &st) < 0 ) {
2493 eprintf(_("can't stat file: %s\n"), fmt_ctx->url);
2497 int64_t file_bits = 8 * st.st_size;
2498 if( !fmt_ctx->bit_rate && opt_duration > 0 )
2499 fmt_ctx->bit_rate = file_bits / opt_duration;
2502 if( fmt_ctx->bit_rate > 0 ) {
2503 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2504 AVStream *st = fmt_ctx->streams[i];
2505 if( st->duration != AV_NOPTS_VALUE ) continue;
2506 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
2507 st->duration = av_rescale(file_bits, st->time_base.den,
2508 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
2512 if( estimated && !(fflags & FF_ESTM_TIMES) ) {
2513 fflags |= FF_ESTM_TIMES;
2514 printf("FFMPEG::open_decoder: some stream times estimated: %s\n",
2518 ff_lock("FFMPEG::open_decoder");
2519 int ret = 0, bad_time = 0;
2520 for( int i=0; !ret && i<(int)fmt_ctx->nb_streams; ++i ) {
2521 AVStream *st = fmt_ctx->streams[i];
2522 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
2523 AVCodecParameters *avpar = st->codecpar;
2524 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avpar->codec_id);
2525 if( !codec_desc ) continue;
2526 switch( avpar->codec_type ) {
2527 case AVMEDIA_TYPE_VIDEO: {
2528 if( avpar->width < 1 ) continue;
2529 if( avpar->height < 1 ) continue;
2530 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
2531 if( framerate.num < 1 ) continue;
2533 int vidx = ffvideo.size();
2534 FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
2535 vstrm_index.append(ffidx(vidx, 0));
2536 ffvideo.append(vid);
2537 vid->width = avpar->width;
2538 vid->height = avpar->height;
2539 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
2540 switch( avpar->color_range ) {
2541 case AVCOL_RANGE_MPEG:
2542 vid->color_range = BC_COLORS_MPEG;
2544 case AVCOL_RANGE_JPEG:
2545 vid->color_range = BC_COLORS_JPEG;
2548 vid->color_range = !file_base ? BC_COLORS_JPEG :
2549 file_base->file->preferences->yuv_color_range;
2552 switch( avpar->color_space ) {
2553 case AVCOL_SPC_BT470BG:
2554 case AVCOL_SPC_SMPTE170M:
2555 vid->color_space = BC_COLORS_BT601;
2557 case AVCOL_SPC_BT709:
2558 vid->color_space = BC_COLORS_BT709;
2560 case AVCOL_SPC_BT2020_NCL:
2561 case AVCOL_SPC_BT2020_CL:
2562 vid->color_space = BC_COLORS_BT2020;
2565 vid->color_space = !file_base ? BC_COLORS_BT601 :
2566 file_base->file->preferences->yuv_color_space;
2569 double secs = to_secs(st->duration, st->time_base);
2570 vid->length = secs * vid->frame_rate;
2571 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
2572 vid->nudge = st->start_time;
2574 ret = vid->create_filter(opt_video_filter);
2576 case AVMEDIA_TYPE_AUDIO: {
2577 if( avpar->channels < 1 ) continue;
2578 if( avpar->sample_rate < 1 ) continue;
2580 int aidx = ffaudio.size();
2581 FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
2582 ffaudio.append(aud);
2583 aud->channel0 = astrm_index.size();
2584 aud->channels = avpar->channels;
2585 for( int ch=0; ch<aud->channels; ++ch )
2586 astrm_index.append(ffidx(aidx, ch));
2587 aud->sample_rate = avpar->sample_rate;
2588 double secs = to_secs(st->duration, st->time_base);
2589 aud->length = secs * aud->sample_rate;
2590 aud->init_swr(aud->channels, avpar->format, aud->sample_rate);
2591 aud->nudge = st->start_time;
2593 ret = aud->create_filter(opt_audio_filter);
2598 if( bad_time && !(fflags & FF_BAD_TIMES) ) {
2599 fflags |= FF_BAD_TIMES;
2600 printf(_("FFMPEG::open_decoder: some stream have bad times: %s\n"),
2604 return ret < 0 ? -1 : 0;
2608 int FFMPEG::init_encoder(const char *filename)
2610 // try access first for named pipes
2611 int ret = access(filename, W_OK);
2613 int fd = ::open(filename,O_WRONLY);
2614 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
2615 if( fd >= 0 ) { close(fd); ret = 0; }
2618 eprintf(_("bad file path: %s\n"), filename);
2621 ret = get_file_format();
2623 eprintf(_("bad file format: %s\n"), filename);
2627 eprintf(_("mismatch audio/video file format: %s\n"), filename);
2630 ff_lock("FFMPEG::init_encoder");
2632 char format[BCSTRLEN];
2633 if( get_format(format, "format", file_format) )
2634 strcpy(format, file_format);
2635 avformat_alloc_output_context2(&fmt_ctx, 0, format, filename);
2637 eprintf(_("failed: %s\n"), filename);
2642 load_options("encode.opts", opts);
2648 int FFMPEG::open_encoder(const char *type, const char *spec)
2651 Asset *asset = file_base->asset;
2652 char *filename = asset->path;
2653 AVDictionary *sopts = 0;
2654 av_dict_copy(&sopts, opts, 0);
2655 char option_path[BCTEXTLEN];
2656 set_option_path(option_path, "%s/%s.opts", type, type);
2657 read_options(option_path, sopts);
2658 get_option_path(option_path, type, spec);
2659 char format_name[BCSTRLEN], codec_name[BCTEXTLEN], bsfilter[BCTEXTLEN];
2660 if( get_encoder(option_path, format_name, codec_name, bsfilter) ) {
2661 eprintf(_("get_encoder failed %s:%s\n"), option_path, filename);
2666 if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
2668 else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
2669 else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
2672 ff_lock("FFMPEG::open_encoder");
2675 AVCodecContext *ctx = 0;
2677 const AVCodecDescriptor *codec_desc = 0;
2678 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
2680 eprintf(_("cant find codec %s:%s\n"), codec_name, filename);
2684 codec_desc = avcodec_descriptor_get(codec->id);
2686 eprintf(_("unknown codec %s:%s\n"), codec_name, filename);
2691 st = avformat_new_stream(fmt_ctx, 0);
2693 eprintf(_("cant create stream %s:%s\n"), codec_name, filename);
2698 switch( codec_desc->type ) {
2699 case AVMEDIA_TYPE_AUDIO: {
2701 eprintf(_("duplicate audio %s:%s\n"), codec_name, filename);
2705 if( scan_options(asset->ff_audio_options, sopts, st) ) {
2706 eprintf(_("bad audio options %s:%s\n"), codec_name, filename);
2711 ctx = avcodec_alloc_context3(codec);
2712 if( asset->ff_audio_bitrate > 0 ) {
2713 ctx->bit_rate = asset->ff_audio_bitrate;
2715 sprintf(arg, "%d", asset->ff_audio_bitrate);
2716 av_dict_set(&sopts, "b", arg, 0);
2718 else if( asset->ff_audio_quality >= 0 ) {
2719 ctx->global_quality = asset->ff_audio_quality * FF_QP2LAMBDA;
2720 ctx->qmin = ctx->qmax = asset->ff_audio_quality;
2721 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2722 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2723 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2725 av_dict_set(&sopts, "flags", "+qscale", 0);
2726 sprintf(arg, "%d", asset->ff_audio_quality);
2727 av_dict_set(&sopts, "qscale", arg, 0);
2728 sprintf(arg, "%d", ctx->global_quality);
2729 av_dict_set(&sopts, "global_quality", arg, 0);
2731 int aidx = ffaudio.size();
2732 int fidx = aidx + ffvideo.size();
2733 FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
2734 aud->avctx = ctx; ffaudio.append(aud); fst = aud;
2735 aud->sample_rate = asset->sample_rate;
2736 ctx->channels = aud->channels = asset->channels;
2737 for( int ch=0; ch<aud->channels; ++ch )
2738 astrm_index.append(ffidx(aidx, ch));
2739 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
2740 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
2741 if( !ctx->sample_rate ) {
2742 eprintf(_("check_sample_rate failed %s\n"), filename);
2746 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
2747 AVSampleFormat sample_fmt = av_get_sample_fmt(asset->ff_sample_format);
2748 if( sample_fmt == AV_SAMPLE_FMT_NONE )
2749 sample_fmt = codec->sample_fmts ? codec->sample_fmts[0] : AV_SAMPLE_FMT_S16;
2750 ctx->sample_fmt = sample_fmt;
2751 uint64_t layout = av_get_default_channel_layout(ctx->channels);
2752 aud->resample_context = swr_alloc_set_opts(NULL,
2753 layout, ctx->sample_fmt, aud->sample_rate,
2754 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
2756 swr_init(aud->resample_context);
2759 case AVMEDIA_TYPE_VIDEO: {
2761 eprintf(_("duplicate video %s:%s\n"), codec_name, filename);
2765 if( scan_options(asset->ff_video_options, sopts, st) ) {
2766 eprintf(_("bad video options %s:%s\n"), codec_name, filename);
2771 ctx = avcodec_alloc_context3(codec);
2772 if( asset->ff_video_bitrate > 0 ) {
2773 ctx->bit_rate = asset->ff_video_bitrate;
2775 sprintf(arg, "%d", asset->ff_video_bitrate);
2776 av_dict_set(&sopts, "b", arg, 0);
2778 else if( asset->ff_video_quality >= 0 ) {
2779 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
2780 ctx->qmin = ctx->qmax = asset->ff_video_quality;
2781 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2782 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2783 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2785 av_dict_set(&sopts, "flags", "+qscale", 0);
2786 sprintf(arg, "%d", asset->ff_video_quality);
2787 av_dict_set(&sopts, "qscale", arg, 0);
2788 sprintf(arg, "%d", ctx->global_quality);
2789 av_dict_set(&sopts, "global_quality", arg, 0);
2791 int vidx = ffvideo.size();
2792 int fidx = vidx + ffaudio.size();
2793 FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
2794 vstrm_index.append(ffidx(vidx, 0));
2795 vid->avctx = ctx; ffvideo.append(vid); fst = vid;
2796 vid->width = asset->width;
2797 vid->height = asset->height;
2798 vid->frame_rate = asset->frame_rate;
2799 if( (vid->color_range = asset->ff_color_range) < 0 )
2800 vid->color_range = file_base->file->preferences->yuv_color_range;
2801 switch( vid->color_range ) {
2802 case BC_COLORS_MPEG: ctx->color_range = AVCOL_RANGE_MPEG; break;
2803 case BC_COLORS_JPEG: ctx->color_range = AVCOL_RANGE_JPEG; break;
2805 if( (vid->color_space = asset->ff_color_space) < 0 )
2806 vid->color_space = file_base->file->preferences->yuv_color_space;
2807 switch( vid->color_space ) {
2808 case BC_COLORS_BT601: ctx->colorspace = AVCOL_SPC_SMPTE170M; break;
2809 case BC_COLORS_BT709: ctx->colorspace = AVCOL_SPC_BT709; break;
2810 case BC_COLORS_BT2020: ctx->colorspace = AVCOL_SPC_BT2020_NCL; break;
2812 AVPixelFormat pix_fmt = av_get_pix_fmt(asset->ff_pixel_format);
2813 if( opt_hw_dev != 0 ) {
2814 AVHWDeviceType hw_type = vid->encode_hw_activate(opt_hw_dev);
2816 case AV_HWDEVICE_TYPE_VAAPI:
2817 pix_fmt = AV_PIX_FMT_VAAPI;
2819 case AV_HWDEVICE_TYPE_NONE:
2823 if( pix_fmt == AV_PIX_FMT_NONE )
2824 pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
2825 ctx->pix_fmt = pix_fmt;
2827 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
2828 int mask_w = (1<<desc->log2_chroma_w)-1;
2829 ctx->width = (vid->width+mask_w) & ~mask_w;
2830 int mask_h = (1<<desc->log2_chroma_h)-1;
2831 ctx->height = (vid->height+mask_h) & ~mask_h;
2832 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
2833 AVRational frame_rate = check_frame_rate(codec->supported_framerates, vid->frame_rate);
2834 if( !frame_rate.num || !frame_rate.den ) {
2835 eprintf(_("check_frame_rate failed %s\n"), filename);
2839 av_reduce(&frame_rate.num, &frame_rate.den,
2840 frame_rate.num, frame_rate.den, INT_MAX);
2841 ctx->framerate = (AVRational) { frame_rate.num, frame_rate.den };
2842 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
2843 st->avg_frame_rate = frame_rate;
2844 st->time_base = ctx->time_base;
2846 vid->interlaced = asset->interlace_mode == ILACE_MODE_TOP_FIRST ||
2847 asset->interlace_mode == ILACE_MODE_BOTTOM_FIRST ? 1 : 0;
2848 vid->top_field_first = asset->interlace_mode == ILACE_MODE_TOP_FIRST ? 1 : 0;
2851 eprintf(_("not audio/video, %s:%s\n"), codec_name, filename);
2856 AVDictionaryEntry *tag;
2857 if( (tag=av_dict_get(sopts, "cin_stats_filename", NULL, 0)) != 0 ) {
2858 char suffix[BCSTRLEN]; sprintf(suffix,"-%d.log",fst->fidx);
2859 fst->stats_filename = cstrcat(2, tag->value, suffix);
2861 if( (tag=av_dict_get(sopts, "flags", NULL, 0)) != 0 ) {
2862 int pass = fst->pass;
2863 char *cp = tag->value;
2865 int ch = *cp++, pfx = ch=='-' ? -1 : ch=='+' ? 1 : 0;
2866 if( !isalnum(!pfx ? ch : (ch=*cp++)) ) continue;
2867 char id[BCSTRLEN], *bp = id, *ep = bp+sizeof(id)-1;
2868 for( *bp++=ch; isalnum(ch=*cp); ++cp )
2869 if( bp < ep ) *bp++ = ch;
2871 if( !strcmp(id, "pass1") ) {
2872 pass = pfx<0 ? (pass&~1) : pfx>0 ? (pass|1) : 1;
2874 else if( !strcmp(id, "pass2") ) {
2875 pass = pfx<0 ? (pass&~2) : pfx>0 ? (pass|2) : 2;
2878 if( (fst->pass=pass) ) {
2879 if( pass & 1 ) ctx->flags |= AV_CODEC_FLAG_PASS1;
2880 if( pass & 2 ) ctx->flags |= AV_CODEC_FLAG_PASS2;
2886 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
2887 ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
2888 if( fst->stats_filename && (ret=fst->init_stats_file()) )
2889 eprintf(_("error: stats file = %s\n"), fst->stats_filename);
2892 av_dict_set(&sopts, "cin_bitrate", 0, 0);
2893 av_dict_set(&sopts, "cin_quality", 0, 0);
2895 if( !av_dict_get(sopts, "threads", NULL, 0) )
2896 ctx->thread_count = ff_cpus();
2897 ret = avcodec_open2(ctx, codec, &sopts);
2899 ret = avcodec_parameters_from_context(st->codecpar, ctx);
2901 fprintf(stderr, "Could not copy the stream parameters\n");
2904 _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
2905 ret = avcodec_copy_context(st->codec, ctx);
2906 _Pragma("GCC diagnostic warning \"-Wdeprecated-declarations\"")
2908 fprintf(stderr, "Could not copy the stream context\n");
2911 ff_err(ret,"FFMPEG::open_encoder");
2912 eprintf(_("open failed %s:%s\n"), codec_name, filename);
2918 if( !ret && fst && bsfilter[0] ) {
2919 ret = av_bsf_list_parse_str(bsfilter, &fst->bsfc);
2921 ff_err(ret,"FFMPEG::open_encoder");
2922 eprintf(_("bitstream filter failed %s:\n%s\n"), filename, bsfilter);
2933 av_dict_free(&sopts);
2937 int FFMPEG::close_encoder()
2940 if( encoding > 0 ) {
2941 av_write_trailer(fmt_ctx);
2942 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
2943 avio_closep(&fmt_ctx->pb);
2949 int FFMPEG::decode_activate()
2951 if( decoding < 0 ) {
2953 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
2954 ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
2955 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
2956 ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
2957 // set nudges for each program stream set
2958 const int64_t min_nudge = INT64_MIN+1;
2959 int npgrms = fmt_ctx->nb_programs;
2960 for( int i=0; i<npgrms; ++i ) {
2961 AVProgram *pgrm = fmt_ctx->programs[i];
2962 // first start time video stream
2963 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2964 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2965 int fidx = pgrm->stream_index[j];
2966 AVStream *st = fmt_ctx->streams[fidx];
2967 AVCodecParameters *avpar = st->codecpar;
2968 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2969 if( st->start_time == AV_NOPTS_VALUE ) continue;
2970 if( vstart_time < st->start_time )
2971 vstart_time = st->start_time;
2974 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2975 if( st->start_time == AV_NOPTS_VALUE ) continue;
2976 if( astart_time < st->start_time )
2977 astart_time = st->start_time;
2981 //since frame rate is much more grainy than sample rate, it is better to
2982 // align using video, so that total absolute error is minimized.
2983 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2984 astart_time > min_nudge ? astart_time : AV_NOPTS_VALUE;
2985 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2986 int fidx = pgrm->stream_index[j];
2987 AVStream *st = fmt_ctx->streams[fidx];
2988 AVCodecParameters *avpar = st->codecpar;
2989 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2990 for( int k=0; k<ffvideo.size(); ++k ) {
2991 if( ffvideo[k]->fidx != fidx ) continue;
2992 ffvideo[k]->nudge = nudge;
2996 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2997 for( int k=0; k<ffaudio.size(); ++k ) {
2998 if( ffaudio[k]->fidx != fidx ) continue;
2999 ffaudio[k]->nudge = nudge;
3005 // set nudges for any streams not yet set
3006 int64_t vstart_time = min_nudge, astart_time = min_nudge;
3007 int nstreams = fmt_ctx->nb_streams;
3008 for( int i=0; i<nstreams; ++i ) {
3009 AVStream *st = fmt_ctx->streams[i];
3010 AVCodecParameters *avpar = st->codecpar;
3011 switch( avpar->codec_type ) {
3012 case AVMEDIA_TYPE_VIDEO: {
3013 if( st->start_time == AV_NOPTS_VALUE ) continue;
3014 int vidx = ffvideo.size();
3015 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
3016 if( vidx < 0 ) continue;
3017 if( ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
3018 if( vstart_time < st->start_time )
3019 vstart_time = st->start_time;
3021 case AVMEDIA_TYPE_AUDIO: {
3022 if( st->start_time == AV_NOPTS_VALUE ) continue;
3023 int aidx = ffaudio.size();
3024 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
3025 if( aidx < 0 ) continue;
3026 if( ffaudio[aidx]->frame_sz < avpar->frame_size )
3027 ffaudio[aidx]->frame_sz = avpar->frame_size;
3028 if( ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
3029 if( astart_time < st->start_time )
3030 astart_time = st->start_time;
3035 int64_t nudge = vstart_time > min_nudge ? vstart_time :
3036 astart_time > min_nudge ? astart_time : 0;
3037 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
3038 if( ffvideo[vidx]->nudge == AV_NOPTS_VALUE )
3039 ffvideo[vidx]->nudge = nudge;
3041 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
3042 if( ffaudio[aidx]->nudge == AV_NOPTS_VALUE )
3043 ffaudio[aidx]->nudge = nudge;
3050 int FFMPEG::encode_activate()
3053 if( encoding < 0 ) {
3055 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
3056 (ret=avio_open(&fmt_ctx->pb, fmt_ctx->url, AVIO_FLAG_WRITE)) < 0 ) {
3057 ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
3061 if( !strcmp(file_format, "image2") ) {
3062 Asset *asset = file_base->asset;
3063 const char *filename = asset->path;
3064 FILE *fp = fopen(filename,"w");
3066 eprintf(_("Cant write image2 header file: %s\n %m"), filename);
3069 fprintf(fp, "IMAGE2\n");
3070 fprintf(fp, "# Frame rate: %f\n", asset->frame_rate);
3071 fprintf(fp, "# Width: %d\n", asset->width);
3072 fprintf(fp, "# Height: %d\n", asset->height);
3076 AVProgram *prog = av_new_program(fmt_ctx, prog_id);
3077 for( int i=0; i< ffvideo.size(); ++i )
3078 av_program_add_stream_index(fmt_ctx, prog_id, ffvideo[i]->fidx);
3079 for( int i=0; i< ffaudio.size(); ++i )
3080 av_program_add_stream_index(fmt_ctx, prog_id, ffaudio[i]->fidx);
3081 int pi = fmt_ctx->nb_programs;
3082 while( --pi >= 0 && fmt_ctx->programs[pi]->id != prog_id );
3083 AVDictionary **meta = &prog->metadata;
3084 av_dict_set(meta, "service_provider", "cin5", 0);
3085 const char *path = fmt_ctx->url, *bp = strrchr(path,'/');
3086 if( bp ) path = bp + 1;
3087 av_dict_set(meta, "title", path, 0);
3089 if( ffaudio.size() ) {
3090 const char *ep = getenv("CIN_AUDIO_LANG"), *lp = 0;
3091 if( !ep && (lp=getenv("LANG")) ) { // some are guesses
3092 static struct { const char lc[3], lng[4]; } lcode[] = {
3093 { "en", "eng" }, { "de", "ger" }, { "es", "spa" },
3094 { "eu", "bas" }, { "fr", "fre" }, { "el", "gre" },
3095 { "hi", "hin" }, { "it", "ita" }, { "ja", "jap" },
3096 { "ko", "kor" }, { "du", "dut" }, { "pl", "pol" },
3097 { "pt", "por" }, { "ru", "rus" }, { "sl", "slv" },
3098 { "uk", "ukr" }, { "vi", "vie" }, { "zh", "chi" },
3100 for( int i=sizeof(lcode)/sizeof(lcode[0]); --i>=0 && !ep; )
3101 if( !strncmp(lcode[i].lc,lp,2) ) ep = lcode[i].lng;
3103 if( !ep ) ep = "und";
3105 strncpy(lang,ep,3); lang[3] = 0;
3106 AVStream *st = ffaudio[0]->st;
3107 av_dict_set(&st->metadata,"language",lang,0);
3110 AVDictionary *fopts = 0;
3111 char option_path[BCTEXTLEN];
3112 set_option_path(option_path, "format/%s", file_format);
3113 read_options(option_path, fopts, 1);
3114 av_dict_copy(&fopts, opts, 0);
3115 if( scan_options(file_base->asset->ff_format_options, fopts, 0) ) {
3116 eprintf(_("bad format options %s\n"), file_base->asset->path);
3120 ret = avformat_write_header(fmt_ctx, &fopts);
3122 ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
3126 av_dict_free(&fopts);
3133 int FFMPEG::audio_seek(int stream, int64_t pos)
3135 int aidx = astrm_index[stream].st_idx;
3136 FFAudioStream *aud = ffaudio[aidx];
3137 aud->audio_seek(pos);
3141 int FFMPEG::video_seek(int stream, int64_t pos)
3143 int vidx = vstrm_index[stream].st_idx;
3144 FFVideoStream *vid = ffvideo[vidx];
3145 vid->video_seek(pos);
3150 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
3152 if( !has_audio || chn >= astrm_index.size() ) return -1;
3153 int aidx = astrm_index[chn].st_idx;
3154 FFAudioStream *aud = ffaudio[aidx];
3155 if( aud->load(pos, len) < len ) return -1;
3156 int ch = astrm_index[chn].st_ch;
3157 int ret = aud->read(samples,len,ch);
3161 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
3163 if( !has_video || layer >= vstrm_index.size() ) return -1;
3164 int vidx = vstrm_index[layer].st_idx;
3165 FFVideoStream *vid = ffvideo[vidx];
3166 return vid->load(vframe, pos);
3170 int FFMPEG::encode(int stream, double **samples, int len)
3172 FFAudioStream *aud = ffaudio[stream];
3173 return aud->encode(samples, len);
3177 int FFMPEG::encode(int stream, VFrame *frame)
3179 FFVideoStream *vid = ffvideo[stream];
3180 return vid->encode(frame);
3183 void FFMPEG::start_muxer()
3191 void FFMPEG::stop_muxer()
3200 void FFMPEG::flow_off()
3203 flow_lock->lock("FFMPEG::flow_off");
3207 void FFMPEG::flow_on()
3211 flow_lock->unlock();
3214 void FFMPEG::flow_ctl()
3217 flow_lock->lock("FFMPEG::flow_ctl");
3218 flow_lock->unlock();
3222 int FFMPEG::mux_audio(FFrame *frm)
3224 FFStream *fst = frm->fst;
3225 AVCodecContext *ctx = fst->avctx;
3226 AVFrame *frame = *frm;
3227 AVRational tick_rate = {1, ctx->sample_rate};
3228 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
3229 int ret = fst->encode_frame(frame);
3231 ff_err(ret, "FFMPEG::mux_audio");
3232 return ret >= 0 ? 0 : 1;
3235 int FFMPEG::mux_video(FFrame *frm)
3237 FFStream *fst = frm->fst;
3238 AVFrame *frame = *frm;
3239 frame->pts = frm->position;
3240 int ret = fst->encode_frame(frame);
3242 ff_err(ret, "FFMPEG::mux_video");
3243 return ret >= 0 ? 0 : 1;
3249 double atm = -1, vtm = -1;
3250 FFrame *afrm = 0, *vfrm = 0;
3252 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
3253 FFStream *fst = ffaudio[i];
3254 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
3255 FFrame *frm = fst->frms.first;
3256 if( !frm ) { if( !done ) return; continue; }
3257 double tm = to_secs(frm->position, fst->avctx->time_base);
3258 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
3260 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
3261 FFStream *fst = ffvideo[i];
3262 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
3263 FFrame *frm = fst->frms.first;
3264 if( !frm ) { if( !done ) return; continue; }
3265 double tm = to_secs(frm->position, fst->avctx->time_base);
3266 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
3268 if( !demand ) flow_off();
3269 if( !afrm && !vfrm ) break;
3270 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
3271 vfrm->position, vfrm->fst->avctx->time_base,
3272 afrm->position, afrm->fst->avctx->time_base);
3273 FFrame *frm = v <= 0 ? vfrm : afrm;
3274 if( frm == afrm ) mux_audio(frm);
3275 if( frm == vfrm ) mux_video(frm);
3284 mux_lock->lock("FFMPEG::run");
3287 for( int i=0; i<ffaudio.size(); ++i )
3288 ffaudio[i]->drain();
3289 for( int i=0; i<ffvideo.size(); ++i )
3290 ffvideo[i]->drain();
3292 for( int i=0; i<ffaudio.size(); ++i )
3293 ffaudio[i]->flush();
3294 for( int i=0; i<ffvideo.size(); ++i )
3295 ffvideo[i]->flush();
3299 int FFMPEG::ff_total_audio_channels()
3301 return astrm_index.size();
3304 int FFMPEG::ff_total_astreams()
3306 return ffaudio.size();
3309 int FFMPEG::ff_audio_channels(int stream)
3311 return ffaudio[stream]->channels;
3314 int FFMPEG::ff_sample_rate(int stream)
3316 return ffaudio[stream]->sample_rate;
3319 const char* FFMPEG::ff_audio_format(int stream)
3321 AVStream *st = ffaudio[stream]->st;
3322 AVCodecID id = st->codecpar->codec_id;
3323 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
3324 return desc ? desc->name : _("Unknown");
3327 int FFMPEG::ff_audio_pid(int stream)
3329 return ffaudio[stream]->st->id;
3332 int64_t FFMPEG::ff_audio_samples(int stream)
3334 return ffaudio[stream]->length;
3337 // find audio astream/channels with this program,
3338 // or all program audio channels (astream=-1)
3339 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
3343 int vidx = ffvideo[vstream]->fidx;
3344 // find first program with this video stream
3345 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
3346 AVProgram *pgrm = fmt_ctx->programs[i];
3347 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
3348 int st_idx = pgrm->stream_index[j];
3349 AVStream *st = fmt_ctx->streams[st_idx];
3350 if( st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
3351 if( st_idx == vidx ) pidx = i;
3354 if( pidx < 0 ) return -1;
3356 int64_t channels = 0;
3357 AVProgram *pgrm = fmt_ctx->programs[pidx];
3358 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
3359 int aidx = pgrm->stream_index[j];
3360 AVStream *st = fmt_ctx->streams[aidx];
3361 if( st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
3362 if( astream > 0 ) { --astream; continue; }
3364 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
3365 if( ffaudio[i]->fidx == aidx ) astrm = i;
3367 if( ret < 0 ) ret = astrm;
3368 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
3369 channels |= mask << ffaudio[astrm]->channel0;
3371 if( !astream ) break;
3373 channel_mask = channels;
3378 int FFMPEG::ff_total_video_layers()
3380 return vstrm_index.size();
3383 int FFMPEG::ff_total_vstreams()
3385 return ffvideo.size();
3388 int FFMPEG::ff_video_width(int stream)
3390 FFVideoStream *vst = ffvideo[stream];
3391 return !vst->transpose ? vst->width : vst->height;
3394 int FFMPEG::ff_video_height(int stream)
3396 FFVideoStream *vst = ffvideo[stream];
3397 return !vst->transpose ? vst->height : vst->width;
3400 int FFMPEG::ff_set_video_width(int stream, int width)
3402 FFVideoStream *vst = ffvideo[stream];
3403 int *vw = !vst->transpose ? &vst->width : &vst->height, w = *vw;
3408 int FFMPEG::ff_set_video_height(int stream, int height)
3410 FFVideoStream *vst = ffvideo[stream];
3411 int *vh = !vst->transpose ? &vst->height : &vst->width, h = *vh;
3416 int FFMPEG::ff_coded_width(int stream)
3418 return ffvideo[stream]->avctx->coded_width;
3421 int FFMPEG::ff_coded_height(int stream)
3423 return ffvideo[stream]->avctx->coded_height;
3426 float FFMPEG::ff_aspect_ratio(int stream)
3428 return ffvideo[stream]->aspect_ratio;
3431 const char* FFMPEG::ff_video_codec(int stream)
3433 AVStream *st = ffvideo[stream]->st;
3434 AVCodecID id = st->codecpar->codec_id;
3435 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
3436 return desc ? desc->name : _("Unknown");
3439 int FFMPEG::ff_color_range(int stream)
3441 return ffvideo[stream]->color_range;
3444 int FFMPEG::ff_color_space(int stream)
3446 return ffvideo[stream]->color_space;
3449 double FFMPEG::ff_frame_rate(int stream)
3451 return ffvideo[stream]->frame_rate;
3454 int64_t FFMPEG::ff_video_frames(int stream)
3456 return ffvideo[stream]->length;
3459 int FFMPEG::ff_video_pid(int stream)
3461 return ffvideo[stream]->st->id;
3464 int FFMPEG::ff_video_mpeg_color_range(int stream)
3466 return ffvideo[stream]->st->codecpar->color_range == AVCOL_RANGE_MPEG ? 1 : 0;
3469 int FFMPEG::ff_cpus()
3471 return !file_base ? 1 : file_base->file->cpus;
3474 const char *FFMPEG::ff_hw_dev()
3476 return &file_base->file->preferences->use_hw_dev[0];
3479 Preferences *FFMPEG::ff_prefs()
3481 return !file_base ? 0 : file_base->file->preferences;
3484 double FFVideoStream::get_rotation_angle()
3487 int *matrix = (int*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX, &size);
3488 int len = size/sizeof(*matrix);
3489 if( !matrix || len < 5 ) return 0;
3490 const double s = 1/65536.;
3491 double theta = (!matrix[0] && !matrix[3]) || (!matrix[1] && !matrix[4]) ? 0 :
3492 atan2( s*matrix[1] / hypot(s*matrix[1], s*matrix[4]),
3493 s*matrix[0] / hypot(s*matrix[0], s*matrix[3])) * 180/M_PI;
3497 int FFVideoStream::flip(double theta)
3501 Preferences *preferences = ffmpeg->ff_prefs();
3502 if( !preferences || !preferences->auto_rotate ) return ret;
3503 double tolerance = 1;
3504 if( fabs(theta-0) < tolerance ) return ret;
3505 if( (theta=fmod(theta, 360)) < 0 ) theta += 360;
3506 if( fabs(theta-90) < tolerance ) {
3507 if( (ret = insert_filter("transpose", "clock")) < 0 )
3511 else if( fabs(theta-180) < tolerance ) {
3512 if( (ret=insert_filter("hflip", 0)) < 0 )
3514 if( (ret=insert_filter("vflip", 0)) < 0 )
3517 else if (fabs(theta-270) < tolerance ) {
3518 if( (ret=insert_filter("transpose", "cclock")) < 0 )
3523 char angle[BCSTRLEN];
3524 sprintf(angle, "%f", theta*M_PI/180.);
3525 if( (ret=insert_filter("rotate", angle)) < 0 )
3531 int FFVideoStream::create_filter(const char *filter_spec)
3533 double theta = get_rotation_angle();
3534 if( !theta && !filter_spec )
3536 avfilter_register_all();
3538 const char *sp = filter_spec;
3539 char filter_name[BCSTRLEN], *np = filter_name;
3540 int i = sizeof(filter_name);
3541 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
3543 const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
3544 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_VIDEO ) {
3545 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
3549 AVCodecParameters *avpar = st->codecpar;
3550 int sa_num = avpar->sample_aspect_ratio.num;
3551 if( !sa_num ) sa_num = 1;
3552 int sa_den = avpar->sample_aspect_ratio.den;
3553 if( !sa_den ) sa_num = 1;
3555 int ret = 0; char args[BCTEXTLEN];
3556 AVPixelFormat pix_fmt = (AVPixelFormat)avpar->format;
3557 snprintf(args, sizeof(args),
3558 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
3559 avpar->width, avpar->height, (int)pix_fmt,
3560 st->time_base.num, st->time_base.den, sa_num, sa_den);
3563 ret = insert_filter("buffer", args, "in");
3564 buffersrc_ctx = filt_ctx;
3568 AVFilterContext *fsrc = filt_ctx;
3571 ret = insert_filter("buffersink", 0, "out");
3572 buffersink_ctx = filt_ctx;
3575 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
3576 (uint8_t*)&pix_fmt, sizeof(pix_fmt),
3577 AV_OPT_SEARCH_CHILDREN);
3580 ret = config_filters(filter_spec, fsrc);
3582 ff_err(ret, "FFVideoStream::create_filter");
3583 return ret >= 0 ? 0 : -1;
3586 int FFAudioStream::create_filter(const char *filter_spec)
3590 avfilter_register_all();
3592 const char *sp = filter_spec;
3593 char filter_name[BCSTRLEN], *np = filter_name;
3594 int i = sizeof(filter_name);
3595 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
3597 const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
3598 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_AUDIO ) {
3599 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
3603 int ret = 0; char args[BCTEXTLEN];
3604 AVCodecParameters *avpar = st->codecpar;
3605 AVSampleFormat sample_fmt = (AVSampleFormat)avpar->format;
3606 snprintf(args, sizeof(args),
3607 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
3608 st->time_base.num, st->time_base.den, avpar->sample_rate,
3609 av_get_sample_fmt_name(sample_fmt), avpar->channel_layout);
3612 ret = insert_filter("abuffer", args, "in");
3613 buffersrc_ctx = filt_ctx;
3615 AVFilterContext *fsrc = filt_ctx;
3618 ret = insert_filter("abuffersink", 0, "out");
3619 buffersink_ctx = filt_ctx;
3622 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
3623 (uint8_t*)&sample_fmt, sizeof(sample_fmt),
3624 AV_OPT_SEARCH_CHILDREN);
3626 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
3627 (uint8_t*)&avpar->channel_layout,
3628 sizeof(avpar->channel_layout), AV_OPT_SEARCH_CHILDREN);
3630 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
3631 (uint8_t*)&sample_rate, sizeof(sample_rate),
3632 AV_OPT_SEARCH_CHILDREN);
3634 ret = config_filters(filter_spec, fsrc);
3636 ff_err(ret, "FFAudioStream::create_filter");
3637 return ret >= 0 ? 0 : -1;
3640 int FFStream::insert_filter(const char *name, const char *arg, const char *inst_name)
3642 const AVFilter *filter = avfilter_get_by_name(name);
3643 if( !filter ) return -1;
3644 char filt_inst[BCSTRLEN];
3646 snprintf(filt_inst, sizeof(filt_inst), "%s_%d", name, ++filt_id);
3647 inst_name = filt_inst;
3650 filter_graph = avfilter_graph_alloc();
3651 AVFilterContext *fctx = 0;
3652 int ret = avfilter_graph_create_filter(&fctx,
3653 filter, inst_name, arg, NULL, filter_graph);
3654 if( ret >= 0 && filt_ctx )
3655 ret = avfilter_link(filt_ctx, 0, fctx, 0);
3659 avfilter_free(fctx);
3663 int FFStream::config_filters(const char *filter_spec, AVFilterContext *fsrc)
3666 AVFilterContext *fsink = buffersink_ctx;
3668 /* Endpoints for the filter graph. */
3669 AVFilterInOut *outputs = avfilter_inout_alloc();
3670 AVFilterInOut *inputs = avfilter_inout_alloc();
3671 if( !inputs || !outputs ) ret = -1;
3673 outputs->filter_ctx = fsrc;
3674 outputs->pad_idx = 0;
3676 if( !(outputs->name = av_strdup(fsrc->name)) ) ret = -1;
3679 inputs->filter_ctx = fsink;
3680 inputs->pad_idx = 0;
3682 if( !(inputs->name = av_strdup(fsink->name)) ) ret = -1;
3685 int len = strlen(fsrc->name)+2 + strlen(filter_spec) + 1;
3686 char spec[len]; sprintf(spec, "[%s]%s", fsrc->name, filter_spec);
3687 ret = avfilter_graph_parse_ptr(filter_graph, spec,
3688 &inputs, &outputs, NULL);
3690 avfilter_inout_free(&inputs);
3691 avfilter_inout_free(&outputs);
3694 ret = avfilter_link(fsrc, 0, fsink, 0);
3696 ret = avfilter_graph_config(filter_graph, NULL);
3698 ff_err(ret, "FFStream::create_filter");
3699 avfilter_graph_free(&filter_graph);
3706 AVCodecContext *FFMPEG::activate_decoder(AVStream *st)
3708 AVDictionary *copts = 0;
3709 av_dict_copy(&copts, opts, 0);
3710 AVCodecID codec_id = st->codecpar->codec_id;
3711 AVCodec *decoder = 0;
3712 switch( st->codecpar->codec_type ) {
3713 case AVMEDIA_TYPE_VIDEO:
3714 if( opt_video_decoder )
3715 decoder = avcodec_find_decoder_by_name(opt_video_decoder);
3717 video_codec_remaps.update(codec_id, decoder);
3719 case AVMEDIA_TYPE_AUDIO:
3720 if( opt_audio_decoder )
3721 decoder = avcodec_find_decoder_by_name(opt_audio_decoder);
3723 audio_codec_remaps.update(codec_id, decoder);
3728 if( !decoder && !(decoder = avcodec_find_decoder(codec_id)) ) {
3729 eprintf(_("cant find decoder codec %d\n"), (int)codec_id);
3732 AVCodecContext *avctx = avcodec_alloc_context3(decoder);
3734 eprintf(_("cant allocate codec context\n"));
3737 avcodec_parameters_to_context(avctx, st->codecpar);
3738 if( !av_dict_get(copts, "threads", NULL, 0) )
3739 avctx->thread_count = ff_cpus();
3740 int ret = avcodec_open2(avctx, decoder, &copts);
3741 av_dict_free(&copts);
3743 avcodec_free_context(&avctx);
3749 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
3752 av_init_packet(&pkt);
3753 AVFrame *frame = av_frame_alloc();
3755 fprintf(stderr,"FFMPEG::scan: ");
3756 fprintf(stderr,_("av_frame_alloc failed\n"));
3757 fprintf(stderr,"FFMPEG::scan:file=%s\n", file_base->asset->path);
3761 index_state->add_video_markers(ffvideo.size());
3762 index_state->add_audio_markers(ffaudio.size());
3764 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
3765 AVStream *st = fmt_ctx->streams[i];
3766 AVCodecContext *avctx = activate_decoder(st);
3768 AVCodecParameters *avpar = st->codecpar;
3769 switch( avpar->codec_type ) {
3770 case AVMEDIA_TYPE_VIDEO: {
3771 int vidx = ffvideo.size();
3772 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
3773 if( vidx < 0 ) break;
3774 ffvideo[vidx]->avctx = avctx;
3776 case AVMEDIA_TYPE_AUDIO: {
3777 int aidx = ffaudio.size();
3778 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3779 if( aidx < 0 ) break;
3780 ffaudio[aidx]->avctx = avctx;
3785 fprintf(stderr,"FFMPEG::scan: ");
3786 fprintf(stderr,_("codec open failed\n"));
3787 fprintf(stderr,"FFMPEG::scan:file=%s\n", file_base->asset->path);
3788 avcodec_free_context(&avctx);
3792 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
3793 AVStream *st = fmt_ctx->streams[i];
3794 AVCodecParameters *avpar = st->codecpar;
3795 if( avpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
3796 int64_t tstmp = st->start_time;
3797 if( tstmp == AV_NOPTS_VALUE ) continue;
3798 int aidx = ffaudio.size();
3799 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3800 if( aidx < 0 ) continue;
3801 FFAudioStream *aud = ffaudio[aidx];
3802 tstmp -= aud->nudge;
3803 double secs = to_secs(tstmp, st->time_base);
3804 aud->curr_pos = secs * aud->sample_rate + 0.5;
3808 for( int64_t count=0; !*canceled; ++count ) {
3809 av_packet_unref(&pkt);
3810 pkt.data = 0; pkt.size = 0;
3812 int ret = av_read_frame(fmt_ctx, &pkt);
3814 if( ret == AVERROR_EOF ) break;
3815 if( ++errs > 100 ) {
3816 ff_err(ret,_("over 100 read_frame errs\n"));
3821 if( !pkt.data ) continue;
3822 int i = pkt.stream_index;
3823 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
3824 AVStream *st = fmt_ctx->streams[i];
3825 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
3827 AVCodecParameters *avpar = st->codecpar;
3828 switch( avpar->codec_type ) {
3829 case AVMEDIA_TYPE_VIDEO: {
3830 int vidx = ffvideo.size();
3831 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
3832 if( vidx < 0 ) break;
3833 FFVideoStream *vid = ffvideo[vidx];
3834 if( !vid->avctx ) break;
3835 int64_t tstmp = pkt.pts;
3836 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
3837 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
3838 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
3839 double secs = to_secs(tstmp, st->time_base);
3840 int64_t frm = secs * vid->frame_rate + 0.5;
3841 if( frm < 0 ) frm = 0;
3842 index_state->put_video_mark(vidx, frm, pkt.pos);
3845 ret = avcodec_send_packet(vid->avctx, pkt);
3846 if( ret < 0 ) break;
3847 while( (ret=vid->decode_frame(frame)) > 0 ) {}
3850 case AVMEDIA_TYPE_AUDIO: {
3851 int aidx = ffaudio.size();
3852 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3853 if( aidx < 0 ) break;
3854 FFAudioStream *aud = ffaudio[aidx];
3855 if( !aud->avctx ) break;
3856 int64_t tstmp = pkt.pts;
3857 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
3858 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
3859 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
3860 double secs = to_secs(tstmp, st->time_base);
3861 int64_t sample = secs * aud->sample_rate + 0.5;
3863 index_state->put_audio_mark(aidx, sample, pkt.pos);
3865 ret = avcodec_send_packet(aud->avctx, &pkt);
3866 if( ret < 0 ) break;
3867 int ch = aud->channel0, nch = aud->channels;
3868 int64_t pos = index_state->pos(ch);
3869 if( pos != aud->curr_pos ) {
3870 if( abs(pos-aud->curr_pos) > 1 )
3871 printf("audio%d pad %jd %jd (%jd)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
3872 index_state->pad_data(ch, nch, aud->curr_pos);
3874 while( (ret=aud->decode_frame(frame)) > 0 ) {
3875 //if( frame->channels != nch ) break;
3876 aud->init_swr(frame->channels, frame->format, frame->sample_rate);
3878 int len = aud->get_samples(samples,
3879 &frame->extended_data[0], frame->nb_samples);
3880 pos = aud->curr_pos;
3881 if( (aud->curr_pos += len) >= 0 ) {
3883 samples += -pos * nch;
3884 len = aud->curr_pos;
3886 for( int i=0; i<nch; ++i )
3887 index_state->put_data(ch+i,nch,samples+i,len);
3894 av_frame_free(&frame);
3898 void FFStream::load_markers(IndexMarks &marks, double rate)
3901 int64_t sz = marks.size();
3902 int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
3903 int nb_ent = st->nb_index_entries;
3904 // some formats already have an index
3906 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
3907 int64_t tstmp = ep->timestamp;
3908 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
3909 double secs = ffmpeg->to_secs(tstmp, st->time_base);
3910 int64_t no = secs * rate;
3911 while( in < sz && marks[in].no <= no ) ++in;
3913 int64_t len = sz - in;
3914 int64_t count = max_entries - nb_ent;
3915 if( count > len ) count = len;
3916 for( int i=0; i<count; ++i ) {
3917 int k = in + i * len / count;
3918 int64_t no = marks[k].no, pos = marks[k].pos;
3919 double secs = (double)no / rate;
3920 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
3921 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
3922 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);
3928 * 1) if the format context has a timecode
3929 * return fmt_ctx->timecode - 0
3930 * 2) if the layer/channel has a timecode
3931 * return st->timecode - (start_time-nudge)
3932 * 3) find the 1st program with stream, find 1st program video stream,
3933 * if video stream has a timecode, return st->timecode - (start_time-nudge)
3934 * 4) find timecode in any stream, return st->timecode
3935 * 5) read 100 packets, save ofs=pkt.pts*st->time_base - st->nudge:
3936 * decode frame for video stream of 1st program
3937 * if frame->timecode has a timecode, return frame->timecode - ofs
3938 * if side_data has gop timecode, return gop->timecode - ofs
3939 * if side_data has smpte timecode, return smpte->timecode - ofs
3940 * 6) if the filename/url scans *date_time.ext, return date_time
3941 * 7) if stat works on the filename/url, return mtime
3942 * 8) return -1 failure
3944 double FFMPEG::get_initial_timecode(int data_type, int channel, double frame_rate)
3946 AVRational rate = check_frame_rate(0, frame_rate);
3947 if( !rate.num ) return -1;
3948 // format context timecode
3949 AVDictionaryEntry *tc = av_dict_get(fmt_ctx->metadata, "timecode", 0, 0);
3950 if( tc ) return ff_get_timecode(tc->value, rate, 0);
3952 if( open_decoder() ) return -1;
3955 int codec_type = -1, fidx = -1;
3956 switch( data_type ) {
3958 codec_type = AVMEDIA_TYPE_AUDIO;
3959 int aidx = astrm_index[channel].st_idx;
3960 FFAudioStream *aud = ffaudio[aidx];
3964 AVDictionaryEntry *tref = av_dict_get(fmt_ctx->metadata, "time_reference", 0, 0);
3965 if( tref && aud && aud->sample_rate )
3966 return strtod(tref->value, 0) / aud->sample_rate;
3969 codec_type = AVMEDIA_TYPE_VIDEO;
3970 int vidx = vstrm_index[channel].st_idx;
3971 FFVideoStream *vid = ffvideo[vidx];
3977 if( codec_type < 0 ) return -1;
3979 tc = av_dict_get(st->metadata, "timecode", 0, 0);
3982 // find first program which references this stream
3984 for( int i=0, m=fmt_ctx->nb_programs; pidx<0 && i<m; ++i ) {
3985 AVProgram *pgrm = fmt_ctx->programs[i];
3986 for( int j=0, n=pgrm->nb_stream_indexes; j<n; ++j ) {
3987 int st_idx = pgrm->stream_index[j];
3988 if( st_idx == fidx ) { pidx = i; break; }
3993 AVProgram *pgrm = fmt_ctx->programs[pidx];
3994 for( int j=0, n=pgrm->nb_stream_indexes; j<n; ++j ) {
3995 int st_idx = pgrm->stream_index[j];
3996 AVStream *tst = fmt_ctx->streams[st_idx];
3997 if( !tst ) continue;
3998 if( tst->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
3999 st = tst; fidx = st_idx;
4005 for( int i=0, n=fmt_ctx->nb_streams; i<n; ++i ) {
4006 AVStream *tst = fmt_ctx->streams[i];
4007 if( !tst ) continue;
4008 if( tst->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
4015 tc = av_dict_get(st->metadata, "timecode", 0, 0);
4019 // any timecode, includes -data- streams
4020 for( int i=0, n=fmt_ctx->nb_streams; i<n; ++i ) {
4021 AVStream *tst = fmt_ctx->streams[i];
4022 if( !tst ) continue;
4023 if( (tc = av_dict_get(tst->metadata, "timecode", 0, 0)) ) {
4030 if( st && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
4031 if( st->r_frame_rate.num && st->r_frame_rate.den )
4032 rate = st->r_frame_rate;
4033 nudge = st->start_time;
4034 for( int i=0; i<ffvideo.size(); ++i ) {
4035 if( ffvideo[i]->st == st ) {
4036 nudge = ffvideo[i]->nudge;
4042 if( tc ) { // return timecode
4043 double secs = st->start_time == AV_NOPTS_VALUE ? 0 :
4044 to_secs(st->start_time - nudge, st->time_base);
4045 return ff_get_timecode(tc->value, rate, secs);
4048 if( !st || fidx < 0 ) return -1;
4051 AVCodecContext *av_ctx = activate_decoder(st);
4053 fprintf(stderr,"activate_decoder failed\n");
4056 avCodecContext avctx(av_ctx); // auto deletes
4057 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO &&
4058 avctx->framerate.num && avctx->framerate.den )
4059 rate = avctx->framerate;
4061 avPacket pkt; // auto deletes
4062 avFrame frame; // auto deletes
4064 fprintf(stderr,"av_frame_alloc failed\n");
4068 int64_t max_packets = 100;
4069 char tcbuf[AV_TIMECODE_STR_SIZE];
4071 for( int64_t count=0; count<max_packets; ++count ) {
4072 av_packet_unref(pkt);
4073 pkt->data = 0; pkt->size = 0;
4075 int ret = av_read_frame(fmt_ctx, pkt);
4077 if( ret == AVERROR_EOF ) break;
4078 if( ++errs > 100 ) {
4079 fprintf(stderr,"over 100 read_frame errs\n");
4084 if( !pkt->data ) continue;
4085 int i = pkt->stream_index;
4086 if( i != fidx ) continue;
4087 int64_t tstmp = pkt->pts;
4088 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt->dts;
4089 double secs = to_secs(tstmp - nudge, st->time_base);
4090 ret = avcodec_send_packet(avctx, pkt);
4091 if( ret < 0 ) return -1;
4093 while( (ret = avcodec_receive_frame(avctx, frame)) >= 0 ) {
4094 if( (tc = av_dict_get(frame->metadata, "timecode", 0, 0)) )
4095 return ff_get_timecode(tc->value, rate, secs);
4096 int k = frame->nb_side_data;
4097 AVFrameSideData *side_data = 0;
4099 side_data = frame->side_data[k];
4100 switch( side_data->type ) {
4101 case AV_FRAME_DATA_GOP_TIMECODE: {
4102 int64_t data = *(int64_t *)side_data->data;
4103 int sz = sizeof(data);
4104 if( side_data->size >= sz ) {
4105 av_timecode_make_mpeg_tc_string(tcbuf, data);
4106 return ff_get_timecode(tcbuf, rate, secs);
4109 case AV_FRAME_DATA_S12M_TIMECODE: {
4110 uint32_t *data = (uint32_t *)side_data->data;
4111 int n = data[0], sz = (n+1)*sizeof(*data);
4112 if( side_data->size >= sz ) {
4113 av_timecode_make_smpte_tc_string(tcbuf, data[n], 0);
4114 return ff_get_timecode(tcbuf, rate, secs);
4123 char *path = fmt_ctx->url;
4124 char *bp = strrchr(path, '/');
4125 if( !bp ) bp = path; else ++bp;
4126 char *cp = strrchr(bp, '.');
4127 if( cp && (cp-=(8+1+6)) >= bp ) {
4129 int year,mon,day, hour,min,sec, frm=0;
4130 if( sscanf(cp,"%4d%2d%2d%[_-]%2d%2d%2d",
4131 &year,&mon,&day, sep, &hour,&min,&sec) == 7 ) {
4133 // year>=1970,mon=1..12,day=1..31, hour=0..23,min=0..59,sec=0..60
4134 if( (ch=='_' || ch=='-' ) &&
4135 year >= 1970 && mon>=1 && mon<=12 && day>=1 && day<=31 &&
4136 hour>=0 && hour<24 && min>=0 && min<60 && sec>=0 && sec<=60 ) {
4137 sprintf(tcbuf,"%d:%02d:%02d:%02d", hour,min,sec, frm);
4138 return ff_get_timecode(tcbuf, rate, 0);
4143 if( stat(path, &tst) >= 0 ) {
4144 time_t t = (time_t)tst.st_mtim.tv_sec;
4146 localtime_r(&t, &tm);
4147 int64_t us = tst.st_mtim.tv_nsec / 1000;
4148 int frm = us/1000000. * frame_rate;
4149 sprintf(tcbuf,"%d:%02d:%02d:%02d", tm.tm_hour, tm.tm_min, tm.tm_sec, frm);
4150 return ff_get_timecode(tcbuf, rate, 0);
4155 double FFMPEG::ff_get_timecode(char *str, AVRational rate, double pos)
4158 if( av_timecode_init_from_string(&tc, rate, str, fmt_ctx) )
4160 double secs = (double)tc.start / tc.fps - pos;
4161 if( secs < 0 ) secs = 0;
4165 double FFMPEG::get_timecode(const char *path, int data_type, int channel, double rate)
4168 if( ffmpeg.init_decoder(path) ) return -1;
4169 return ffmpeg.get_initial_timecode(data_type, channel, rate);