12 // work arounds (centos)
15 #define INT64_MAX 9223372036854775807LL
17 #define MAX_RETRY 1000
18 // max pts/curr_pos drift allowed before correction (in seconds)
19 #define AUDIO_PTS_TOLERANCE 0.04
22 #include "bccmodels.h"
25 #include "edlsession.h"
27 #include "fileffmpeg.h"
28 #include "filesystem.h"
30 #include "indexfile.h"
31 #include "interlacemodes.h"
34 #include "mainerror.h"
36 #include "preferences.h"
42 #define av_register_all(s)
43 #define avfilter_register_all(s)
46 #define VIDEO_INBUF_SIZE 0x10000
47 #define AUDIO_INBUF_SIZE 0x10000
48 #define VIDEO_REFILL_THRESH 0
49 #define AUDIO_REFILL_THRESH 0x1000
50 #define AUDIO_MIN_FRAME_SZ 128
52 #define FF_ESTM_TIMES 0x0001
53 #define FF_BAD_TIMES 0x0002
55 Mutex FFMPEG::fflock("FFMPEG::fflock");
57 static void ff_err(int ret, const char *fmt, ...)
62 vsnprintf(msg, sizeof(msg), fmt, ap);
64 char errmsg[BCSTRLEN];
65 av_strerror(ret, errmsg, sizeof(errmsg));
66 fprintf(stderr,_("%s err: %s\n"),msg, errmsg);
72 pkt.data = 0; pkt.size = 0;
74 void FFPacket::finit()
76 av_packet_unref(&pkt);
79 FFrame::FFrame(FFStream *fst)
82 frm = av_frame_alloc();
83 init = fst->init_frame(frm);
91 void FFrame::queue(int64_t pos)
97 void FFrame::dequeue()
102 void FFrame::set_hw_frame(AVFrame *frame)
108 int FFAudioStream::read(float *fp, long len)
116 while( --k >= 0 ) *fp++ = *op++;
117 if( op >= lmt ) op = bfr;
122 void FFAudioStream::realloc(long nsz, int nch, long len)
124 long bsz = nsz * nch;
125 float *np = new float[bsz];
126 inp = np + read(np, len) * nch;
131 delete [] bfr; bfr = np;
134 void FFAudioStream::realloc(long nsz, int nch)
136 if( nsz > sz || this->nch != nch ) {
137 long len = this->nch != nch ? 0 : hpos;
138 if( len > sz ) len = sz;
140 realloc(nsz, nch, len);
144 void FFAudioStream::reserve(long nsz, int nch)
146 long len = (inp - outp) / nch;
148 if( nsz > sz || this->nch != nch ) {
149 if( this->nch != nch ) len = 0;
150 realloc(nsz, nch, len);
153 if( (len*=nch) > 0 && bfr != outp )
154 memmove(bfr, outp, len*sizeof(*bfr));
159 long FFAudioStream::used()
161 long len = inp>=outp ? inp-outp : inp-bfr + lmt-outp;
164 long FFAudioStream::avail()
167 if( in1 >= lmt ) in1 = bfr;
168 long len = outp >= in1 ? outp-in1 : outp-bfr + lmt-in1;
171 void FFAudioStream::reset_history()
175 memset(bfr, 0, lmt-bfr);
178 void FFAudioStream::iseek(int64_t ofs)
180 if( ofs > hpos ) ofs = hpos;
181 if( ofs > sz ) ofs = sz;
182 outp = inp - ofs*nch;
183 if( outp < bfr ) outp += sz*nch;
186 float *FFAudioStream::get_outp(int ofs)
193 int64_t FFAudioStream::put_inp(int ofs)
196 return (inp-outp) / nch;
199 int FFAudioStream::write(const float *fp, long len)
207 while( --k >= 0 ) *ip++ = *fp++;
208 if( ip >= lmt ) ip = bfr;
215 int FFAudioStream::zero(long len)
223 while( --k >= 0 ) *ip++ = 0;
224 if( ip >= lmt ) ip = bfr;
231 // does not advance outp
232 int FFAudioStream::read(double *dp, long len, int ch)
235 float *op = outp + ch;
236 float *lmt1 = lmt + nch-1;
238 int k = (lmt1 - op) / nch;
241 while( --k >= 0 ) { *dp++ = *op; op += nch; }
242 if( op >= lmt ) op -= sz*nch;
247 // load linear buffer, no wrapping allowed, does not advance inp
248 int FFAudioStream::write(const double *dp, long len, int ch)
251 float *ip = inp + ch;
252 while( --n >= 0 ) { *ip = *dp++; ip += nch; }
257 FFStream::FFStream(FFMPEG *ffmpeg, AVStream *st, int fidx)
259 this->ffmpeg = ffmpeg;
262 frm_lock = new Mutex("FFStream::frm_lock");
269 nudge = AV_NOPTS_VALUE;
270 seek_pos = curr_pos = 0;
272 reading = writing = 0;
273 hw_pixfmt = AV_PIX_FMT_NONE;
286 FFStream::~FFStream()
288 if( reading > 0 || writing > 0 ) avcodec_close(avctx);
289 if( avctx ) avcodec_free_context(&avctx);
290 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
291 if( hw_device_ctx ) av_buffer_unref(&hw_device_ctx);
292 if( bsfc ) av_bsf_free(&bsfc);
293 while( frms.first ) frms.remove(frms.first);
294 if( filter_graph ) avfilter_graph_free(&filter_graph);
295 if( frame ) av_frame_free(&frame);
296 if( fframe ) av_frame_free(&fframe);
297 if( probe_frame ) av_frame_free(&probe_frame);
299 if( stats_fp ) fclose(stats_fp);
300 if( stats_in ) av_freep(&stats_in);
301 delete [] stats_filename;
304 void FFStream::ff_lock(const char *cp)
306 FFMPEG::fflock.lock(cp);
309 void FFStream::ff_unlock()
311 FFMPEG::fflock.unlock();
314 void FFStream::queue(FFrame *frm)
316 frm_lock->lock("FFStream::queue");
320 ffmpeg->mux_lock->unlock();
323 void FFStream::dequeue(FFrame *frm)
325 frm_lock->lock("FFStream::dequeue");
327 frms.remove_pointer(frm);
331 int FFStream::encode_activate()
334 writing = ffmpeg->encode_activate();
338 // this is a global parameter that really should be in the context
339 static AVPixelFormat hw_pix_fmt = AV_PIX_FMT_NONE; // protected by ff_lock
341 // goofy maneuver to attach a hw_format to an av_context
342 #define GET_HW_PIXFMT(fn, fmt) \
343 static AVPixelFormat get_hw_##fn(AVCodecContext *ctx, const enum AVPixelFormat *pix_fmts) { \
346 GET_HW_PIXFMT(vaapi, AV_PIX_FMT_VAAPI)
347 GET_HW_PIXFMT(vdpau, AV_PIX_FMT_VDPAU)
348 GET_HW_PIXFMT(cuda, AV_PIX_FMT_CUDA)
349 GET_HW_PIXFMT(nv12, AV_PIX_FMT_NV12)
351 static enum AVPixelFormat get_hw_format(AVCodecContext *ctx,
352 const enum AVPixelFormat *pix_fmts)
354 for( const enum AVPixelFormat *p=pix_fmts; *p!=AV_PIX_FMT_NONE; ++p ) {
355 if( *p != hw_pix_fmt ) continue;
357 case AV_PIX_FMT_VAAPI: ctx->get_format = get_hw_vaapi; return *p;
358 case AV_PIX_FMT_VDPAU: ctx->get_format = get_hw_vdpau; return *p;
359 case AV_PIX_FMT_CUDA: ctx->get_format = get_hw_cuda; return *p;
360 case AV_PIX_FMT_NV12: ctx->get_format = get_hw_nv12; return *p;
362 fprintf(stderr, "Unknown HW surface format: %s\n",
363 av_get_pix_fmt_name(*p));
367 fprintf(stderr, "Failed to get HW surface format.\n");
368 return hw_pix_fmt = AV_PIX_FMT_NONE;
372 AVHWDeviceType FFStream::decode_hw_activate()
374 return AV_HWDEVICE_TYPE_NONE;
377 int FFStream::decode_hw_format(AVCodec *decoder, AVHWDeviceType type)
382 int FFStream::decode_activate()
384 if( reading < 0 && (reading=ffmpeg->decode_activate()) > 0 ) {
385 ff_lock("FFStream::decode_activate");
387 AVDictionary *copts = 0;
388 av_dict_copy(&copts, ffmpeg->opts, 0);
390 AVHWDeviceType hw_type = decode_hw_activate();
392 // this should be avformat_copy_context(), but no copy avail
393 ret = avformat_open_input(&fmt_ctx,
394 ffmpeg->fmt_ctx->url, ffmpeg->fmt_ctx->iformat, &copts);
396 ret = avformat_find_stream_info(fmt_ctx, 0);
397 st = fmt_ctx->streams[fidx];
400 while( ret >= 0 && st != 0 && !reading ) {
401 AVCodecID codec_id = st->codecpar->codec_id;
402 AVCodec *decoder = 0;
404 if( ffmpeg->opt_video_decoder )
405 decoder = avcodec_find_decoder_by_name(ffmpeg->opt_video_decoder);
407 ffmpeg->video_codec_remaps.update(codec_id, decoder);
409 else if( is_audio() ) {
410 if( ffmpeg->opt_audio_decoder )
411 decoder = avcodec_find_decoder_by_name(ffmpeg->opt_audio_decoder);
413 ffmpeg->audio_codec_remaps.update(codec_id, decoder);
416 decoder = avcodec_find_decoder(codec_id);
417 avctx = avcodec_alloc_context3(decoder);
419 eprintf(_("cant allocate codec context\n"));
420 ret = AVERROR(ENOMEM);
422 if( ret >= 0 && hw_type != AV_HWDEVICE_TYPE_NONE ) {
423 ret = decode_hw_format(decoder, hw_type);
424 if( !ret ) hw_type = AV_HWDEVICE_TYPE_NONE;
427 avcodec_parameters_to_context(avctx, st->codecpar);
428 if( !av_dict_get(copts, "threads", NULL, 0) )
429 avctx->thread_count = ffmpeg->ff_cpus();
430 ret = avcodec_open2(avctx, decoder, &copts);
432 if( ret >= 0 && hw_type != AV_HWDEVICE_TYPE_NONE ) {
433 AVFrame *frame = av_frame_alloc();
435 fprintf(stderr, "FFStream::decode_activate: av_frame_alloc failed\n");
436 ret = AVERROR(ENOMEM);
440 if( ret < 0 || hw_pix_fmt == AV_PIX_FMT_NONE ) {
441 ff_err(ret, "HW device init failed, using SW decode.\nfile:%s\n",
442 ffmpeg->fmt_ctx->url);
443 avcodec_close(avctx);
444 avcodec_free_context(&avctx);
445 av_buffer_unref(&hw_device_ctx);
447 av_frame_free(&frame);
448 hw_type = AV_HWDEVICE_TYPE_NONE;
449 int flags = AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_ANY;
451 av_seek_frame(fmt_ctx, idx, INT64_MIN, flags);
452 need_packet = 1; flushed = 0;
453 seeked = 1; st_eof(0);
463 eprintf(_("open decoder failed\n"));
466 eprintf(_("can't open input file: %s\n"), ffmpeg->fmt_ctx->url);
467 av_dict_free(&copts);
473 int FFStream::read_packet()
475 av_packet_unref(ipkt);
476 int ret = av_read_frame(fmt_ctx, ipkt);
479 if( ret == AVERROR_EOF ) return 0;
480 ff_err(ret, "FFStream::read_packet: av_read_frame failed\n");
487 int FFStream::decode(AVFrame *frame)
489 if( probe_frame ) { // hw probe reads first frame
490 av_frame_ref(frame, probe_frame);
491 av_frame_free(&probe_frame);
495 int retries = MAX_RETRY;
497 while( ret >= 0 && !flushed && --retries >= 0 ) {
499 if( (ret=read_packet()) < 0 ) break;
500 AVPacket *pkt = ret > 0 ? (AVPacket*)ipkt : 0;
502 if( pkt->stream_index != st->index ) continue;
503 if( !pkt->data || !pkt->size ) continue;
505 if( (ret=avcodec_send_packet(avctx, pkt)) < 0 ) {
506 ff_err(ret, "FFStream::decode: avcodec_send_packet failed.\nfile:%s\n",
507 ffmpeg->fmt_ctx->url);
513 if( (ret=decode_frame(frame)) > 0 ) break;
521 fprintf(stderr, "FFStream::decode: Retry limit\n");
525 fprintf(stderr, "FFStream::decode: failed\n");
529 int FFStream::load_filter(AVFrame *frame)
531 int ret = av_buffersrc_add_frame_flags(buffersrc_ctx, frame, 0);
533 eprintf(_("av_buffersrc_add_frame_flags failed\n"));
537 int FFStream::read_filter(AVFrame *frame)
539 int ret = av_buffersink_get_frame(buffersink_ctx, frame);
541 if( ret == AVERROR(EAGAIN) ) return 0;
542 if( ret == AVERROR_EOF ) { st_eof(1); return -1; }
543 ff_err(ret, "FFStream::read_filter: av_buffersink_get_frame failed\n");
549 int FFStream::read_frame(AVFrame *frame)
551 av_frame_unref(frame);
552 if( !filter_graph || !buffersrc_ctx || !buffersink_ctx )
553 return decode(frame);
554 if( !fframe && !(fframe=av_frame_alloc()) ) {
555 fprintf(stderr, "FFStream::read_frame: av_frame_alloc failed\n");
559 while( !flushed && !(ret=read_filter(frame)) ) {
560 if( (ret=decode(fframe)) < 0 ) break;
561 if( ret > 0 && (ret=load_filter(fframe)) < 0 ) break;
566 int FFStream::write_packet(FFPacket &pkt)
570 av_packet_rescale_ts(pkt, avctx->time_base, st->time_base);
571 pkt->stream_index = st->index;
572 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, pkt);
575 ret = av_bsf_send_packet(bsfc, pkt);
578 if( (ret=av_bsf_receive_packet(bsfc, bs)) < 0 ) {
579 if( ret == AVERROR(EAGAIN) ) return 0;
580 if( ret == AVERROR_EOF ) return -1;
583 av_packet_rescale_ts(bs, avctx->time_base, st->time_base);
584 bs->stream_index = st->index;
585 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, bs);
589 ff_err(ret, "FFStream::write_packet: write packet failed.\nfile:%s\n",
590 ffmpeg->fmt_ctx->url);
594 int FFStream::encode_frame(AVFrame *frame)
596 int pkts = 0, ret = 0;
597 for( int retry=MAX_RETRY; --retry>=0; ) {
599 ret = avcodec_send_frame(avctx, frame);
600 if( !ret && frame ) return pkts;
601 if( ret < 0 && ret != AVERROR(EAGAIN) ) break;
603 ret = avcodec_receive_packet(avctx, opkt);
604 if( !frame && ret == AVERROR_EOF ) return pkts;
606 ret = write_packet(opkt);
609 if( frame && stats_fp ) {
610 ret = write_stats_file();
614 ff_err(ret, "FFStream::encode_frame: encode failed.\nfile: %s\n",
615 ffmpeg->fmt_ctx->url);
619 int FFStream::flush()
623 int ret = encode_frame(0);
624 if( ret >= 0 && stats_fp ) {
625 ret = write_stats_file();
629 ff_err(ret, "FFStream::flush failed\n:file:%s\n",
630 ffmpeg->fmt_ctx->url);
631 return ret >= 0 ? 0 : 1;
635 int FFStream::open_stats_file()
637 stats_fp = fopen(stats_filename,"w");
638 return stats_fp ? 0 : AVERROR(errno);
641 int FFStream::close_stats_file()
644 fclose(stats_fp); stats_fp = 0;
649 int FFStream::read_stats_file()
651 int64_t len = 0; struct stat stats_st;
652 int fd = open(stats_filename, O_RDONLY);
653 int ret = fd >= 0 ? 0: ENOENT;
654 if( !ret && fstat(fd, &stats_st) )
657 len = stats_st.st_size;
658 stats_in = (char *)av_malloc(len+1);
662 if( !ret && read(fd, stats_in, len+1) != len )
666 avctx->stats_in = stats_in;
670 return !ret ? 0 : AVERROR(ret);
673 int FFStream::write_stats_file()
676 if( avctx->stats_out && (ret=strlen(avctx->stats_out)) > 0 ) {
677 int len = fwrite(avctx->stats_out, 1, ret, stats_fp);
679 ff_err(ret = AVERROR(errno), "FFStream::write_stats_file.\n%file:%s\n",
680 ffmpeg->fmt_ctx->url);
685 int FFStream::init_stats_file()
688 if( (pass & 2) && (ret = read_stats_file()) < 0 )
689 ff_err(ret, "stat file read: %s", stats_filename);
690 if( (pass & 1) && (ret=open_stats_file()) < 0 )
691 ff_err(ret, "stat file open: %s", stats_filename);
692 return ret >= 0 ? 0 : ret;
695 int FFStream::seek(int64_t no, double rate)
697 // default ffmpeg native seek
699 int64_t pos = no, pkt_pos = -1;
700 IndexMarks *index_markers = get_markers();
701 if( index_markers && index_markers->size() > 1 ) {
702 IndexMarks &marks = *index_markers;
703 int i = marks.find(pos);
704 int64_t n = i < 0 ? (i=0) : marks[i].no;
705 // if indexed seek point not too far away (<30 secs), use index
706 if( no-n < 30*rate ) {
709 if( i < marks.size() ) pkt_pos = marks[i].pos;
713 if( pos == curr_pos ) return 0;
714 double secs = pos < 0 ? 0. : pos / rate;
715 AVRational time_base = st->time_base;
716 int64_t tstmp = time_base.num > 0 ? secs * time_base.den/time_base.num : 0;
718 if( st->nb_index_entries > 0 ) tstmp = st->index_entries[0].timestamp;
719 else if( st->start_time != AV_NOPTS_VALUE ) tstmp = st->start_time;
720 else if( st->first_dts != AV_NOPTS_VALUE ) tstmp = st->first_dts;
721 else tstmp = INT64_MIN+1;
723 else if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
726 // seek all streams using the default timebase.
727 // this is how ffmpeg and ffplay work. stream seeks are less tested.
728 tstmp = av_rescale_q(tstmp, time_base, AV_TIME_BASE_Q);
731 av_frame_free(&probe_frame);
732 avcodec_flush_buffers(avctx);
733 avformat_flush(fmt_ctx);
735 int64_t seek = tstmp;
736 int flags = AVSEEK_FLAG_ANY;
737 if( !(fmt_ctx->iformat->flags & AVFMT_NO_BYTE_SEEK) && pkt_pos >= 0 ) {
739 flags = AVSEEK_FLAG_BYTE;
741 int ret = avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, seek, INT64_MAX, flags);
743 // finds the first index frame below the target time
744 int flags = AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_ANY;
745 int ret = av_seek_frame(fmt_ctx, idx, tstmp, flags);
747 int retry = MAX_RETRY;
749 need_packet = 0; flushed = 0;
750 seeked = 1; st_eof(0);
751 // read up to retry packets, limited to npkts in stream, and not pkt.pos past pkt_pos
752 while( --retry >= 0 ) {
753 if( read_packet() <= 0 ) { ret = -1; break; }
754 if( ipkt->stream_index != st->index ) continue;
755 if( !ipkt->data || !ipkt->size ) continue;
756 if( pkt_pos >= 0 && ipkt->pos >= pkt_pos ) break;
757 if( --npkts <= 0 ) break;
758 int64_t pkt_ts = ipkt->dts != AV_NOPTS_VALUE ? ipkt->dts : ipkt->pts;
759 if( pkt_ts == AV_NOPTS_VALUE ) continue;
760 if( pkt_ts >= tstmp ) break;
763 fprintf(stderr,"FFStream::seek: retry limit, pos=%jd tstmp=%jd\n",pos,tstmp);
767 ret = avcodec_send_packet(avctx, ipkt);
769 //some codecs need more than one pkt to resync
770 if( ret == AVERROR_INVALIDDATA ) ret = 0;
772 ff_err(ret, "FFStream::avcodec_send_packet failed.\nseek:%s\n",
773 ffmpeg->fmt_ctx->url);
778 printf("** seek fail %jd, %jd\n", pos, tstmp);
779 seeked = need_packet = 0;
783 //printf("seeked pos = %ld, %ld\n", pos, tstmp);
784 seek_pos = curr_pos = pos;
788 FFAudioStream::FFAudioStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
789 : FFStream(ffmpeg, strm, fidx)
792 channel0 = channels = 0;
795 frame_sz = AUDIO_MIN_FRAME_SZ;
797 resample_context = 0;
798 swr_ichs = swr_ifmt = swr_irate = 0;
807 bfr = new float[bsz];
812 FFAudioStream::~FFAudioStream()
814 if( resample_context ) swr_free(&resample_context);
819 void FFAudioStream::init_swr(int ichs, int ifmt, int irate)
821 if( resample_context ) {
822 if( swr_ichs == ichs && swr_ifmt == ifmt && swr_irate == irate )
824 swr_free(&resample_context);
826 swr_ichs = ichs; swr_ifmt = ifmt; swr_irate = irate;
827 if( ichs == channels && ifmt == AV_SAMPLE_FMT_FLT && irate == sample_rate )
829 uint64_t ilayout = av_get_default_channel_layout(ichs);
830 if( !ilayout ) ilayout = ((uint64_t)1<<ichs) - 1;
831 uint64_t olayout = av_get_default_channel_layout(channels);
832 if( !olayout ) olayout = ((uint64_t)1<<channels) - 1;
833 resample_context = swr_alloc_set_opts(NULL,
834 olayout, AV_SAMPLE_FMT_FLT, sample_rate,
835 ilayout, (AVSampleFormat)ifmt, irate,
837 if( resample_context )
838 swr_init(resample_context);
841 int FFAudioStream::get_samples(float *&samples, uint8_t **data, int len)
843 samples = *(float **)data;
844 if( resample_context ) {
845 if( len > aud_bfr_sz ) {
851 aud_bfr = new float[aud_bfr_sz*channels];
853 int ret = swr_convert(resample_context,
854 (uint8_t**)&aud_bfr, aud_bfr_sz, (const uint8_t**)data, len);
856 ff_err(ret, "FFAudioStream::get_samples: swr_convert failed\n");
865 int FFAudioStream::load_history(uint8_t **data, int len)
868 len = get_samples(samples, data, len);
870 // biggest user bfr since seek + frame
871 realloc(mbsz + len + 1, channels);
877 int FFAudioStream::decode_frame(AVFrame *frame)
879 int first_frame = seeked; seeked = 0;
880 frame->best_effort_timestamp = AV_NOPTS_VALUE;
881 int ret = avcodec_receive_frame(avctx, frame);
883 if( first_frame ) return 0;
884 if( ret == AVERROR(EAGAIN) ) return 0;
885 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
886 ff_err(ret, "FFAudioStream::decode_frame: Could not read audio frame.\nfile:%s\n",
887 ffmpeg->fmt_ctx->url);
890 int64_t pkt_ts = frame->best_effort_timestamp;
891 if( pkt_ts != AV_NOPTS_VALUE ) {
892 double ts = ffmpeg->to_secs(pkt_ts - nudge, st->time_base);
893 double t = (double)curr_pos / sample_rate;
894 // some time_base clocks are very grainy, too grainy for audio (clicks, pops)
895 if( fabs(ts - t) > AUDIO_PTS_TOLERANCE )
896 curr_pos = ts * sample_rate + 0.5;
901 int FFAudioStream::encode_activate()
903 if( writing >= 0 ) return writing;
904 if( !avctx->codec ) return writing = 0;
905 frame_sz = avctx->codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE ?
906 10000 : avctx->frame_size;
907 return FFStream::encode_activate();
910 int64_t FFAudioStream::load_buffer(double ** const sp, int len)
912 reserve(len+1, st->codecpar->channels);
913 for( int ch=0; ch<nch; ++ch )
914 write(sp[ch], len, ch);
918 int FFAudioStream::in_history(int64_t pos)
920 if( pos > curr_pos ) return 0;
922 if( len > sz ) len = sz;
923 if( pos < curr_pos - len ) return 0;
928 int FFAudioStream::init_frame(AVFrame *frame)
930 frame->nb_samples = frame_sz;
931 frame->format = avctx->sample_fmt;
932 frame->channel_layout = avctx->channel_layout;
933 frame->sample_rate = avctx->sample_rate;
934 int ret = av_frame_get_buffer(frame, 0);
936 ff_err(ret, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
940 int FFAudioStream::load(int64_t pos, int len)
942 if( audio_seek(pos) < 0 ) return -1;
943 if( !frame && !(frame=av_frame_alloc()) ) {
944 fprintf(stderr, "FFAudioStream::load: av_frame_alloc failed\n");
947 if( mbsz < len ) mbsz = len;
948 int64_t end_pos = pos + len;
949 int ret = 0, i = len / frame_sz + MAX_RETRY;
950 while( ret>=0 && !flushed && curr_pos<end_pos && --i>=0 ) {
951 ret = read_frame(frame);
952 if( ret > 0 && frame->nb_samples > 0 ) {
953 init_swr(frame->channels, frame->format, frame->sample_rate);
954 load_history(&frame->extended_data[0], frame->nb_samples);
955 curr_pos += frame->nb_samples;
958 if( end_pos > curr_pos ) {
959 zero(end_pos - curr_pos);
962 len = curr_pos - pos;
967 int FFAudioStream::audio_seek(int64_t pos)
969 if( decode_activate() <= 0 ) return -1;
970 if( !st->codecpar ) return -1;
971 if( in_history(pos) ) return 0;
972 if( pos == curr_pos ) return 0;
973 reset_history(); mbsz = 0;
974 // guarentee preload > 1sec samples
975 if( (pos-=sample_rate) < 0 ) pos = 0;
976 if( seek(pos, sample_rate) < 0 ) return -1;
980 int FFAudioStream::encode(double **samples, int len)
982 if( encode_activate() <= 0 ) return -1;
985 int64_t count = samples ? load_buffer(samples, len) : used();
986 int frame_sz1 = samples ? frame_sz-1 : 0;
989 while( ret >= 0 && count > frame_sz1 ) {
990 frm = new FFrame(this);
991 if( (ret=frm->initted()) < 0 ) break;
992 AVFrame *frame = *frm;
993 len = count >= frame_sz ? frame_sz : count;
994 float *bfrp = get_outp(len);
995 ret = swr_convert(resample_context,
996 (uint8_t **)frame->extended_data, len,
997 (const uint8_t **)&bfrp, len);
999 ff_err(ret, "FFAudioStream::encode: swr_convert failed\n");
1002 frame->nb_samples = len;
1003 frm->queue(curr_pos);
1010 return ret >= 0 ? 0 : 1;
1013 int FFAudioStream::drain()
1018 int FFAudioStream::encode_frame(AVFrame *frame)
1020 return FFStream::encode_frame(frame);
1023 int FFAudioStream::write_packet(FFPacket &pkt)
1025 return FFStream::write_packet(pkt);
1028 void FFAudioStream::load_markers()
1030 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1031 if( !index_state || idx >= index_state->audio_markers.size() ) return;
1032 if( index_state->marker_status == MARKERS_NOTTESTED ) return;
1033 FFStream::load_markers(*index_state->audio_markers[idx], sample_rate);
1036 IndexMarks *FFAudioStream::get_markers()
1038 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1039 if( !index_state || idx >= index_state->audio_markers.size() ) return 0;
1040 return index_state->audio_markers[idx];
1043 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
1044 : FFStream(ffmpeg, strm, fidx),
1045 FFVideoConvert(ffmpeg->ff_prefs())
1053 top_field_first = 0;
1058 FFVideoStream::~FFVideoStream()
1062 AVHWDeviceType FFVideoStream::decode_hw_activate()
1064 AVHWDeviceType type = AV_HWDEVICE_TYPE_NONE;
1065 const char *hw_dev = ffmpeg->opt_hw_dev;
1066 if( !hw_dev ) hw_dev = getenv("CIN_HW_DEV");
1067 if( !hw_dev ) hw_dev = ffmpeg->ff_hw_dev();
1068 if( hw_dev && *hw_dev &&
1069 strcmp("none", hw_dev) && strcmp(_("none"), hw_dev) ) {
1070 type = av_hwdevice_find_type_by_name(hw_dev);
1071 if( type == AV_HWDEVICE_TYPE_NONE ) {
1072 fprintf(stderr, "Device type %s is not supported.\n", hw_dev);
1073 fprintf(stderr, "Available device types:");
1074 while( (type = av_hwdevice_iterate_types(type)) != AV_HWDEVICE_TYPE_NONE )
1075 fprintf(stderr, " %s", av_hwdevice_get_type_name(type));
1076 fprintf(stderr, "\n");
1082 int FFVideoStream::decode_hw_format(AVCodec *decoder, AVHWDeviceType type)
1085 hw_pix_fmt = AV_PIX_FMT_NONE;
1086 for( int i=0; ; ++i ) {
1087 const AVCodecHWConfig *config = avcodec_get_hw_config(decoder, i);
1089 fprintf(stderr, "Decoder %s does not support device type %s.\n",
1090 decoder->name, av_hwdevice_get_type_name(type));
1093 if( (config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX) != 0 &&
1094 config->device_type == type ) {
1095 hw_pix_fmt = config->pix_fmt;
1099 if( hw_pix_fmt >= 0 ) {
1100 hw_pixfmt = hw_pix_fmt;
1101 avctx->get_format = get_hw_format;
1102 ret = av_hwdevice_ctx_create(&hw_device_ctx, type, 0, 0, 0);
1104 avctx->hw_device_ctx = av_buffer_ref(hw_device_ctx);
1108 ff_err(ret, "Failed HW device create.\ndev:%s\n",
1109 av_hwdevice_get_type_name(type));
1114 AVHWDeviceType FFVideoStream::encode_hw_activate(const char *hw_dev)
1116 AVBufferRef *hw_device_ctx = 0;
1117 AVBufferRef *hw_frames_ref = 0;
1118 AVHWDeviceType type = AV_HWDEVICE_TYPE_NONE;
1119 if( strcmp(_("none"), hw_dev) ) {
1120 type = av_hwdevice_find_type_by_name(hw_dev);
1121 if( type != AV_HWDEVICE_TYPE_VAAPI ) {
1122 fprintf(stderr, "currently, only vaapi hw encode is supported\n");
1123 type = AV_HWDEVICE_TYPE_NONE;
1126 if( type != AV_HWDEVICE_TYPE_NONE ) {
1127 int ret = av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_VAAPI, 0, 0, 0);
1129 ff_err(ret, "Failed to create a HW device.\n");
1130 type = AV_HWDEVICE_TYPE_NONE;
1133 if( type != AV_HWDEVICE_TYPE_NONE ) {
1134 hw_frames_ref = av_hwframe_ctx_alloc(hw_device_ctx);
1135 if( !hw_frames_ref ) {
1136 fprintf(stderr, "Failed to create HW frame context.\n");
1137 type = AV_HWDEVICE_TYPE_NONE;
1140 if( type != AV_HWDEVICE_TYPE_NONE ) {
1141 AVHWFramesContext *frames_ctx = (AVHWFramesContext *)(hw_frames_ref->data);
1142 frames_ctx->format = AV_PIX_FMT_VAAPI;
1143 frames_ctx->sw_format = AV_PIX_FMT_NV12;
1144 frames_ctx->width = width;
1145 frames_ctx->height = height;
1146 frames_ctx->initial_pool_size = 0; // 200;
1147 int ret = av_hwframe_ctx_init(hw_frames_ref);
1149 avctx->hw_frames_ctx = av_buffer_ref(hw_frames_ref);
1150 if( !avctx->hw_frames_ctx ) ret = AVERROR(ENOMEM);
1153 ff_err(ret, "Failed to initialize HW frame context.\n");
1154 type = AV_HWDEVICE_TYPE_NONE;
1156 av_buffer_unref(&hw_frames_ref);
1161 int FFVideoStream::encode_hw_write(FFrame *picture)
1164 AVFrame *hw_frm = 0;
1165 switch( avctx->pix_fmt ) {
1166 case AV_PIX_FMT_VAAPI:
1167 hw_frm = av_frame_alloc();
1168 if( !hw_frm ) { ret = AVERROR(ENOMEM); break; }
1169 ret = av_hwframe_get_buffer(avctx->hw_frames_ctx, hw_frm, 0);
1170 if( ret < 0 ) break;
1171 ret = av_hwframe_transfer_data(hw_frm, *picture, 0);
1172 if( ret < 0 ) break;
1173 picture->set_hw_frame(hw_frm);
1178 av_frame_free(&hw_frm);
1179 ff_err(ret, "Error while transferring frame data to GPU.\n");
1183 int FFVideoStream::decode_frame(AVFrame *frame)
1185 int first_frame = seeked; seeked = 0;
1186 int ret = avcodec_receive_frame(avctx, frame);
1188 if( first_frame ) return 0;
1189 if( ret == AVERROR(EAGAIN) ) return 0;
1190 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
1191 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame.\nfile:%s\n,",
1192 ffmpeg->fmt_ctx->url);
1195 int64_t pkt_ts = frame->best_effort_timestamp;
1196 if( pkt_ts != AV_NOPTS_VALUE )
1197 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * frame_rate + 0.5;
1201 int FFVideoStream::load(VFrame *vframe, int64_t pos)
1203 int ret = video_seek(pos);
1204 if( ret < 0 ) return -1;
1205 if( !frame && !(frame=av_frame_alloc()) ) {
1206 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
1209 int i = MAX_RETRY + pos - curr_pos;
1210 while( ret>=0 && !flushed && curr_pos<=pos && --i>=0 ) {
1211 ret = read_frame(frame);
1212 if( ret > 0 ) ++curr_pos;
1214 if( frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0 )
1217 ret = convert_cmodel(vframe, frame);
1219 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
1223 int FFVideoStream::video_seek(int64_t pos)
1225 if( decode_activate() <= 0 ) return -1;
1226 if( !st->codecpar ) return -1;
1227 if( pos == curr_pos-1 && !seeked ) return 0;
1228 // if close enough, just read up to current
1229 int gop = avctx->gop_size;
1230 if( gop < 4 ) gop = 4;
1231 if( gop > 64 ) gop = 64;
1232 int read_limit = curr_pos + 3*gop;
1233 if( pos >= curr_pos && pos <= read_limit ) return 0;
1234 // guarentee preload more than 2*gop frames
1235 if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
1239 int FFVideoStream::init_frame(AVFrame *picture)
1241 switch( avctx->pix_fmt ) {
1242 case AV_PIX_FMT_VAAPI:
1243 picture->format = AV_PIX_FMT_NV12;
1246 picture->format = avctx->pix_fmt;
1249 picture->width = avctx->width;
1250 picture->height = avctx->height;
1251 int ret = av_frame_get_buffer(picture, 32);
1255 int FFVideoStream::encode(VFrame *vframe)
1257 if( encode_activate() <= 0 ) return -1;
1259 FFrame *picture = new FFrame(this);
1260 int ret = picture->initted();
1262 AVFrame *frame = *picture;
1263 frame->pts = curr_pos;
1264 ret = convert_pixfmt(vframe, frame);
1266 if( ret >= 0 && avctx->hw_frames_ctx )
1267 encode_hw_write(picture);
1269 picture->queue(curr_pos);
1273 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
1276 return ret >= 0 ? 0 : 1;
1279 int FFVideoStream::drain()
1284 int FFVideoStream::encode_frame(AVFrame *frame)
1287 frame->interlaced_frame = interlaced;
1288 frame->top_field_first = top_field_first;
1290 if( frame && frame->format == AV_PIX_FMT_VAAPI ) { // ugly
1291 int ret = avcodec_send_frame(avctx, frame);
1292 for( int retry=MAX_RETRY; !ret && --retry>=0; ) {
1293 FFPacket pkt; av_init_packet(pkt);
1294 pkt->data = NULL; pkt->size = 0;
1295 if( (ret=avcodec_receive_packet(avctx, pkt)) < 0 ) {
1296 if( ret == AVERROR(EAGAIN) ) ret = 0; // weird
1299 ret = write_packet(pkt);
1300 pkt->stream_index = 0;
1301 av_packet_unref(pkt);
1304 ff_err(ret, "FFStream::encode_frame: vaapi encode failed.\nfile: %s\n",
1305 ffmpeg->fmt_ctx->url);
1310 return FFStream::encode_frame(frame);
1313 int FFVideoStream::write_packet(FFPacket &pkt)
1315 if( !(ffmpeg->fmt_ctx->oformat->flags & AVFMT_VARIABLE_FPS) )
1317 return FFStream::write_packet(pkt);
1320 AVPixelFormat FFVideoConvert::color_model_to_pix_fmt(int color_model)
1322 switch( color_model ) {
1323 case BC_YUV422: return AV_PIX_FMT_YUYV422;
1324 case BC_RGB888: return AV_PIX_FMT_RGB24;
1325 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
1326 case BC_BGR8888: return AV_PIX_FMT_BGR0;
1327 case BC_BGR888: return AV_PIX_FMT_BGR24;
1328 case BC_ARGB8888: return AV_PIX_FMT_ARGB;
1329 case BC_ABGR8888: return AV_PIX_FMT_ABGR;
1330 case BC_RGB8: return AV_PIX_FMT_RGB8;
1331 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
1332 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
1333 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
1334 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
1335 case BC_RGB565: return AV_PIX_FMT_RGB565;
1336 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
1337 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
1338 case BC_AYUV16161616: return AV_PIX_FMT_AYUV64LE;
1339 case BC_GBRP: return AV_PIX_FMT_GBRP;
1343 return AV_PIX_FMT_NB;
1346 int FFVideoConvert::pix_fmt_to_color_model(AVPixelFormat pix_fmt)
1349 case AV_PIX_FMT_YUYV422: return BC_YUV422;
1350 case AV_PIX_FMT_RGB24: return BC_RGB888;
1351 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
1352 case AV_PIX_FMT_BGR0: return BC_BGR8888;
1353 case AV_PIX_FMT_BGR24: return BC_BGR888;
1354 case AV_PIX_FMT_ARGB: return BC_ARGB8888;
1355 case AV_PIX_FMT_ABGR: return BC_ABGR8888;
1356 case AV_PIX_FMT_RGB8: return BC_RGB8;
1357 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
1358 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
1359 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
1360 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
1361 case AV_PIX_FMT_RGB565: return BC_RGB565;
1362 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
1363 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
1364 case AV_PIX_FMT_AYUV64LE: return BC_AYUV16161616;
1365 case AV_PIX_FMT_GBRP: return BC_GBRP;
1372 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip)
1374 AVFrame *ipic = av_frame_alloc();
1375 int ret = convert_picture_vframe(frame, ip, ipic);
1376 av_frame_free(&ipic);
1380 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip, AVFrame *ipic)
1381 { // picture = vframe
1382 int cmodel = frame->get_color_model();
1383 AVPixelFormat ofmt = color_model_to_pix_fmt(cmodel);
1384 if( ofmt == AV_PIX_FMT_NB ) return -1;
1385 int size = av_image_fill_arrays(ipic->data, ipic->linesize,
1386 frame->get_data(), ofmt, frame->get_w(), frame->get_h(), 1);
1387 if( size < 0 ) return -1;
1389 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1390 int ysz = bpp * frame->get_w(), usz = ysz;
1400 // override av_image_fill_arrays() for planar types
1401 ipic->data[0] = frame->get_y(); ipic->linesize[0] = ysz;
1402 ipic->data[1] = frame->get_u(); ipic->linesize[1] = usz;
1403 ipic->data[2] = frame->get_v(); ipic->linesize[2] = usz;
1406 ipic->data[0] = frame->get_data();
1407 ipic->linesize[0] = frame->get_bytes_per_line();
1411 AVPixelFormat pix_fmt = (AVPixelFormat)ip->format;
1412 FFVideoStream *vid =(FFVideoStream *)this;
1413 if( pix_fmt == vid->hw_pixfmt ) {
1415 if( !sw_frame && !(sw_frame=av_frame_alloc()) )
1416 ret = AVERROR(ENOMEM);
1418 ret = av_hwframe_transfer_data(sw_frame, ip, 0);
1420 pix_fmt = (AVPixelFormat)ip->format;
1423 eprintf(_("Error retrieving data from GPU to CPU\nfile: %s\n"),
1424 vid->ffmpeg->fmt_ctx->url);
1428 convert_ctx = sws_getCachedContext(convert_ctx, ip->width, ip->height, pix_fmt,
1429 frame->get_w(), frame->get_h(), ofmt, SWS_POINT, NULL, NULL, NULL);
1430 if( !convert_ctx ) {
1431 fprintf(stderr, "FFVideoConvert::convert_picture_frame:"
1432 " sws_getCachedContext() failed\n");
1436 int color_range = 0;
1437 switch( preferences->yuv_color_range ) {
1438 case BC_COLORS_JPEG: color_range = 1; break;
1439 case BC_COLORS_MPEG: color_range = 0; break;
1441 int color_space = SWS_CS_ITU601;
1442 switch( preferences->yuv_color_space ) {
1443 case BC_COLORS_BT601: color_space = SWS_CS_ITU601; break;
1444 case BC_COLORS_BT709: color_space = SWS_CS_ITU709; break;
1445 case BC_COLORS_BT2020: color_space = SWS_CS_BT2020; break;
1447 const int *color_table = sws_getCoefficients(color_space);
1449 int *inv_table, *table, src_range, dst_range;
1450 int brightness, contrast, saturation;
1451 if( !sws_getColorspaceDetails(convert_ctx,
1452 &inv_table, &src_range, &table, &dst_range,
1453 &brightness, &contrast, &saturation) ) {
1454 if( src_range != color_range || dst_range != color_range ||
1455 inv_table != color_table || table != color_table )
1456 sws_setColorspaceDetails(convert_ctx,
1457 color_table, color_range, color_table, color_range,
1458 brightness, contrast, saturation);
1461 int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ip->height,
1462 ipic->data, ipic->linesize);
1464 ff_err(ret, "FFVideoConvert::convert_picture_frame: sws_scale() failed\nfile: %s\n",
1465 vid->ffmpeg->fmt_ctx->url);
1471 int FFVideoConvert::convert_cmodel(VFrame *frame, AVFrame *ip)
1473 // try direct transfer
1474 if( !convert_picture_vframe(frame, ip) ) return 1;
1475 // use indirect transfer
1476 AVPixelFormat ifmt = (AVPixelFormat)ip->format;
1477 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
1479 for( int i = 0; i <desc->nb_components; ++i ) {
1480 int bits = desc->comp[i].depth;
1481 if( bits > max_bits ) max_bits = bits;
1483 int imodel = pix_fmt_to_color_model(ifmt);
1484 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1485 int cmodel = frame->get_color_model();
1486 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1487 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1488 imodel = cmodel_is_yuv ?
1489 (BC_CModels::has_alpha(cmodel) ?
1491 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1492 (BC_CModels::has_alpha(cmodel) ?
1493 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1494 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1496 VFrame vframe(ip->width, ip->height, imodel);
1497 if( convert_picture_vframe(&vframe, ip) ) return -1;
1498 frame->transfer_from(&vframe);
1502 int FFVideoConvert::transfer_cmodel(VFrame *frame, AVFrame *ifp)
1504 int ret = convert_cmodel(frame, ifp);
1506 const AVDictionary *src = ifp->metadata;
1507 AVDictionaryEntry *t = NULL;
1508 BC_Hash *hp = frame->get_params();
1510 while( (t=av_dict_get(src, "", t, AV_DICT_IGNORE_SUFFIX)) )
1511 hp->update(t->key, t->value);
1516 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op)
1518 AVFrame *opic = av_frame_alloc();
1519 int ret = convert_vframe_picture(frame, op, opic);
1520 av_frame_free(&opic);
1524 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op, AVFrame *opic)
1525 { // vframe = picture
1526 int cmodel = frame->get_color_model();
1527 AVPixelFormat ifmt = color_model_to_pix_fmt(cmodel);
1528 if( ifmt == AV_PIX_FMT_NB ) return -1;
1529 int size = av_image_fill_arrays(opic->data, opic->linesize,
1530 frame->get_data(), ifmt, frame->get_w(), frame->get_h(), 1);
1531 if( size < 0 ) return -1;
1533 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1534 int ysz = bpp * frame->get_w(), usz = ysz;
1544 // override av_image_fill_arrays() for planar types
1545 opic->data[0] = frame->get_y(); opic->linesize[0] = ysz;
1546 opic->data[1] = frame->get_u(); opic->linesize[1] = usz;
1547 opic->data[2] = frame->get_v(); opic->linesize[2] = usz;
1550 opic->data[0] = frame->get_data();
1551 opic->linesize[0] = frame->get_bytes_per_line();
1555 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1556 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(),
1557 ifmt, op->width, op->height, ofmt, SWS_POINT, NULL, NULL, NULL);
1558 if( !convert_ctx ) {
1559 fprintf(stderr, "FFVideoConvert::convert_frame_picture:"
1560 " sws_getCachedContext() failed\n");
1565 int color_range = 0;
1566 switch( preferences->yuv_color_range ) {
1567 case BC_COLORS_JPEG: color_range = 1; break;
1568 case BC_COLORS_MPEG: color_range = 0; break;
1570 int color_space = SWS_CS_ITU601;
1571 switch( preferences->yuv_color_space ) {
1572 case BC_COLORS_BT601: color_space = SWS_CS_ITU601; break;
1573 case BC_COLORS_BT709: color_space = SWS_CS_ITU709; break;
1574 case BC_COLORS_BT2020: color_space = SWS_CS_BT2020; break;
1576 const int *color_table = sws_getCoefficients(color_space);
1578 int *inv_table, *table, src_range, dst_range;
1579 int brightness, contrast, saturation;
1580 if( !sws_getColorspaceDetails(convert_ctx,
1581 &inv_table, &src_range, &table, &dst_range,
1582 &brightness, &contrast, &saturation) ) {
1583 if( dst_range != color_range || table != color_table )
1584 sws_setColorspaceDetails(convert_ctx,
1585 inv_table, src_range, color_table, color_range,
1586 brightness, contrast, saturation);
1589 int ret = sws_scale(convert_ctx, opic->data, opic->linesize, 0, frame->get_h(),
1590 op->data, op->linesize);
1592 ff_err(ret, "FFVideoConvert::convert_frame_picture: sws_scale() failed\n");
1598 int FFVideoConvert::convert_pixfmt(VFrame *frame, AVFrame *op)
1600 // try direct transfer
1601 if( !convert_vframe_picture(frame, op) ) return 1;
1602 // use indirect transfer
1603 int cmodel = frame->get_color_model();
1604 int max_bits = BC_CModels::calculate_pixelsize(cmodel) * 8;
1605 max_bits /= BC_CModels::components(cmodel);
1606 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1607 int imodel = pix_fmt_to_color_model(ofmt);
1608 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1609 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1610 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1611 imodel = cmodel_is_yuv ?
1612 (BC_CModels::has_alpha(cmodel) ?
1614 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1615 (BC_CModels::has_alpha(cmodel) ?
1616 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1617 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1619 VFrame vframe(frame->get_w(), frame->get_h(), imodel);
1620 vframe.transfer_from(frame);
1621 if( !convert_vframe_picture(&vframe, op) ) return 1;
1625 int FFVideoConvert::transfer_pixfmt(VFrame *frame, AVFrame *ofp)
1627 int ret = convert_pixfmt(frame, ofp);
1629 BC_Hash *hp = frame->get_params();
1630 AVDictionary **dict = &ofp->metadata;
1631 //av_dict_free(dict);
1632 for( int i=0; i<hp->size(); ++i ) {
1633 char *key = hp->get_key(i), *val = hp->get_value(i);
1634 av_dict_set(dict, key, val, 0);
1640 void FFVideoStream::load_markers()
1642 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1643 if( !index_state || idx >= index_state->video_markers.size() ) return;
1644 FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
1647 IndexMarks *FFVideoStream::get_markers()
1649 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1650 if( !index_state || idx >= index_state->video_markers.size() ) return 0;
1651 return !index_state ? 0 : index_state->video_markers[idx];
1655 FFMPEG::FFMPEG(FileBase *file_base)
1658 this->file_base = file_base;
1659 memset(file_format,0,sizeof(file_format));
1660 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
1661 flow_lock = new Condition(1,"FFStream::flow_lock",0);
1664 decoding = encoding = 0;
1665 has_audio = has_video = 0;
1668 opt_video_filter = 0;
1669 opt_audio_filter = 0;
1671 opt_video_decoder = 0;
1672 opt_audio_decoder = 0;
1674 char option_path[BCTEXTLEN];
1675 set_option_path(option_path, "%s", "ffmpeg.opts");
1676 read_options(option_path, opts);
1681 ff_lock("FFMPEG::~FFMPEG()");
1683 ffaudio.remove_all_objects();
1684 ffvideo.remove_all_objects();
1685 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1689 av_dict_free(&opts);
1690 delete [] opt_video_filter;
1691 delete [] opt_audio_filter;
1692 delete [] opt_hw_dev;
1695 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1697 const int *p = codec->supported_samplerates;
1698 if( !p ) return sample_rate;
1700 if( *p == sample_rate ) return *p;
1706 static inline AVRational std_frame_rate(int i)
1708 static const int m1 = 1001*12, m2 = 1000*12;
1709 static const int freqs[] = {
1710 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1711 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
1713 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1714 return (AVRational) { freq, 1001*12 };
1717 AVRational FFMPEG::check_frame_rate(AVCodec *codec, double frame_rate)
1719 const AVRational *p = codec->supported_framerates;
1720 AVRational rate, best_rate = (AVRational) { 0, 0 };
1721 double max_err = 1.; int i = 0;
1722 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1723 double framerate = (double) rate.num / rate.den;
1724 double err = fabs(frame_rate/framerate - 1.);
1725 if( err >= max_err ) continue;
1729 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1732 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1735 double display_aspect = asset->width / (double)asset->height;
1736 double sample_aspect = display_aspect / asset->aspect_ratio;
1737 int width = 1000000, height = width * sample_aspect + 0.5;
1739 MWindow::create_aspect_ratio(w, h, width, height);
1740 return (AVRational){(int)w, (int)h};
1743 return (AVRational){1, 1};
1747 AVRational FFMPEG::to_time_base(int sample_rate)
1749 return (AVRational){1, sample_rate};
1752 int FFMPEG::get_fmt_score(AVSampleFormat dst_fmt, AVSampleFormat src_fmt)
1755 int dst_planar = av_sample_fmt_is_planar(dst_fmt);
1756 int src_planar = av_sample_fmt_is_planar(src_fmt);
1757 if( dst_planar != src_planar ) ++score;
1758 int dst_bytes = av_get_bytes_per_sample(dst_fmt);
1759 int src_bytes = av_get_bytes_per_sample(src_fmt);
1760 score += (src_bytes > dst_bytes ? 100 : -10) * (src_bytes - dst_bytes);
1761 int src_packed = av_get_packed_sample_fmt(src_fmt);
1762 int dst_packed = av_get_packed_sample_fmt(dst_fmt);
1763 if( dst_packed == AV_SAMPLE_FMT_S32 && src_packed == AV_SAMPLE_FMT_FLT ) score += 20;
1764 if( dst_packed == AV_SAMPLE_FMT_FLT && src_packed == AV_SAMPLE_FMT_S32 ) score += 2;
1768 AVSampleFormat FFMPEG::find_best_sample_fmt_of_list(
1769 const AVSampleFormat *sample_fmts, AVSampleFormat src_fmt)
1771 AVSampleFormat best = AV_SAMPLE_FMT_NONE;
1772 int best_score = get_fmt_score(best, src_fmt);
1773 for( int i=0; sample_fmts[i] >= 0; ++i ) {
1774 AVSampleFormat sample_fmt = sample_fmts[i];
1775 int score = get_fmt_score(sample_fmt, src_fmt);
1776 if( score >= best_score ) continue;
1777 best = sample_fmt; best_score = score;
1783 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
1785 char *ep = path + BCTEXTLEN-1;
1786 strncpy(path, File::get_cindat_path(), ep-path);
1787 strncat(path, "/ffmpeg/", ep-path);
1788 path += strlen(path);
1791 path += vsnprintf(path, ep-path, fmt, ap);
1796 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
1801 set_option_path(path, "%s/%s", type, spec);
1804 int FFMPEG::get_format(char *format, const char *path, const char *spec)
1806 char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
1807 get_option_path(option_path, path, spec);
1808 FILE *fp = fopen(option_path,"r");
1811 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1813 line[sizeof(line)-1] = 0;
1814 ret = scan_option_line(line, format, codec);
1820 int FFMPEG::get_codec(char *codec, const char *path, const char *spec)
1822 char option_path[BCTEXTLEN], line[BCTEXTLEN], format[BCTEXTLEN];
1823 get_option_path(option_path, path, spec);
1824 FILE *fp = fopen(option_path,"r");
1827 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1830 line[sizeof(line)-1] = 0;
1831 ret = scan_option_line(line, format, codec);
1834 char *vp = codec, *ep = vp+BCTEXTLEN-1;
1835 while( vp < ep && *vp && *vp != '|' ) ++vp;
1836 if( *vp == '|' ) --vp;
1837 while( vp > codec && (*vp==' ' || *vp=='\t') ) *vp-- = 0;
1842 int FFMPEG::get_file_format()
1844 char audio_muxer[BCSTRLEN], video_muxer[BCSTRLEN];
1845 char audio_format[BCSTRLEN], video_format[BCSTRLEN];
1846 audio_muxer[0] = audio_format[0] = 0;
1847 video_muxer[0] = video_format[0] = 0;
1848 Asset *asset = file_base->asset;
1849 int ret = asset ? 0 : 1;
1850 if( !ret && asset->audio_data ) {
1851 if( !(ret=get_format(audio_format, "audio", asset->acodec)) ) {
1852 if( get_format(audio_muxer, "format", audio_format) ) {
1853 strcpy(audio_muxer, audio_format);
1854 audio_format[0] = 0;
1858 if( !ret && asset->video_data ) {
1859 if( !(ret=get_format(video_format, "video", asset->vcodec)) ) {
1860 if( get_format(video_muxer, "format", video_format) ) {
1861 strcpy(video_muxer, video_format);
1862 video_format[0] = 0;
1866 if( !ret && !audio_muxer[0] && !video_muxer[0] )
1868 if( !ret && audio_muxer[0] && video_muxer[0] &&
1869 strcmp(audio_muxer, video_muxer) ) ret = -1;
1870 if( !ret && audio_format[0] && video_format[0] &&
1871 strcmp(audio_format, video_format) ) ret = -1;
1873 strcpy(file_format, !audio_format[0] && !video_format[0] ?
1874 (audio_muxer[0] ? audio_muxer : video_muxer) :
1875 (audio_format[0] ? audio_format : video_format));
1879 int FFMPEG::scan_option_line(const char *cp, char *tag, char *val)
1881 while( *cp == ' ' || *cp == '\t' ) ++cp;
1882 const char *bp = cp;
1883 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' && *cp != '\n' ) ++cp;
1885 if( !len || len > BCSTRLEN-1 ) return 1;
1886 while( bp < cp ) *tag++ = *bp++;
1888 while( *cp == ' ' || *cp == '\t' ) ++cp;
1889 if( *cp == '=' ) ++cp;
1890 while( *cp == ' ' || *cp == '\t' ) ++cp;
1892 while( *cp && *cp != '\n' ) ++cp;
1894 if( len > BCTEXTLEN-1 ) return 1;
1895 while( bp < cp ) *val++ = *bp++;
1900 int FFMPEG::can_render(const char *fformat, const char *type)
1903 char option_path[BCTEXTLEN];
1904 FFMPEG::set_option_path(option_path, type);
1905 fs.update(option_path);
1906 int total_files = fs.total_files();
1907 for( int i=0; i<total_files; ++i ) {
1908 const char *name = fs.get_entry(i)->get_name();
1909 const char *ext = strrchr(name,'.');
1910 if( !ext ) continue;
1911 if( !strcmp(fformat, ++ext) ) return 1;
1916 int FFMPEG::get_ff_option(const char *nm, const char *options, char *value)
1918 for( const char *cp=options; *cp!=0; ) {
1919 char line[BCTEXTLEN], *bp = line, *ep = bp+sizeof(line)-1;
1920 while( bp < ep && *cp && *cp!='\n' ) *bp++ = *cp++;
1923 if( !line[0] || line[0] == '#' || line[0] == ';' ) continue;
1924 char key[BCSTRLEN], val[BCTEXTLEN];
1925 if( FFMPEG::scan_option_line(line, key, val) ) continue;
1926 if( !strcmp(key, nm) ) {
1927 strncpy(value, val, BCSTRLEN);
1934 void FFMPEG::scan_audio_options(Asset *asset, EDL *edl)
1936 char cin_sample_fmt[BCSTRLEN];
1937 int cin_fmt = AV_SAMPLE_FMT_NONE;
1938 const char *options = asset->ff_audio_options;
1939 if( !get_ff_option("cin_sample_fmt", options, cin_sample_fmt) )
1940 cin_fmt = (int)av_get_sample_fmt(cin_sample_fmt);
1942 char audio_codec[BCSTRLEN]; audio_codec[0] = 0;
1943 AVCodec *av_codec = !FFMPEG::get_codec(audio_codec, "audio", asset->acodec) ?
1944 avcodec_find_encoder_by_name(audio_codec) : 0;
1945 if( av_codec && av_codec->sample_fmts )
1946 cin_fmt = find_best_sample_fmt_of_list(av_codec->sample_fmts, AV_SAMPLE_FMT_FLT);
1948 if( cin_fmt < 0 ) cin_fmt = AV_SAMPLE_FMT_S16;
1949 const char *name = av_get_sample_fmt_name((AVSampleFormat)cin_fmt);
1950 if( !name ) name = _("None");
1951 strcpy(asset->ff_sample_format, name);
1953 char value[BCSTRLEN];
1954 if( !get_ff_option("cin_bitrate", options, value) )
1955 asset->ff_audio_bitrate = atoi(value);
1956 if( !get_ff_option("cin_quality", options, value) )
1957 asset->ff_audio_quality = atoi(value);
1960 void FFMPEG::load_audio_options(Asset *asset, EDL *edl)
1962 char options_path[BCTEXTLEN];
1963 set_option_path(options_path, "audio/%s", asset->acodec);
1964 if( !load_options(options_path,
1965 asset->ff_audio_options,
1966 sizeof(asset->ff_audio_options)) )
1967 scan_audio_options(asset, edl);
1970 void FFMPEG::scan_video_options(Asset *asset, EDL *edl)
1972 char cin_pix_fmt[BCSTRLEN];
1973 int cin_fmt = AV_PIX_FMT_NONE;
1974 const char *options = asset->ff_video_options;
1975 if( !get_ff_option("cin_pix_fmt", options, cin_pix_fmt) )
1976 cin_fmt = (int)av_get_pix_fmt(cin_pix_fmt);
1978 char video_codec[BCSTRLEN]; video_codec[0] = 0;
1979 AVCodec *av_codec = !get_codec(video_codec, "video", asset->vcodec) ?
1980 avcodec_find_encoder_by_name(video_codec) : 0;
1981 if( av_codec && av_codec->pix_fmts ) {
1982 if( 0 && edl ) { // frequently picks a bad answer
1983 int color_model = edl->session->color_model;
1984 int max_bits = BC_CModels::calculate_pixelsize(color_model) * 8;
1985 max_bits /= BC_CModels::components(color_model);
1986 cin_fmt = avcodec_find_best_pix_fmt_of_list(av_codec->pix_fmts,
1987 (BC_CModels::is_yuv(color_model) ?
1988 (max_bits > 8 ? AV_PIX_FMT_AYUV64LE : AV_PIX_FMT_YUV444P) :
1989 (max_bits > 8 ? AV_PIX_FMT_RGB48LE : AV_PIX_FMT_RGB24)), 0, 0);
1992 cin_fmt = av_codec->pix_fmts[0];
1995 if( cin_fmt < 0 ) cin_fmt = AV_PIX_FMT_YUV420P;
1996 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get((AVPixelFormat)cin_fmt);
1997 const char *name = desc ? desc->name : _("None");
1998 strcpy(asset->ff_pixel_format, name);
2000 char value[BCSTRLEN];
2001 if( !get_ff_option("cin_bitrate", options, value) )
2002 asset->ff_video_bitrate = atoi(value);
2003 if( !get_ff_option("cin_quality", options, value) )
2004 asset->ff_video_quality = atoi(value);
2007 void FFMPEG::load_video_options(Asset *asset, EDL *edl)
2009 char options_path[BCTEXTLEN];
2010 set_option_path(options_path, "video/%s", asset->vcodec);
2011 if( !load_options(options_path,
2012 asset->ff_video_options,
2013 sizeof(asset->ff_video_options)) )
2014 scan_video_options(asset, edl);
2017 void FFMPEG::scan_format_options(Asset *asset, EDL *edl)
2021 void FFMPEG::load_format_options(Asset *asset, EDL *edl)
2023 char options_path[BCTEXTLEN];
2024 set_option_path(options_path, "format/%s", asset->fformat);
2025 if( !load_options(options_path,
2026 asset->ff_format_options,
2027 sizeof(asset->ff_format_options)) )
2028 scan_format_options(asset, edl);
2031 int FFMPEG::load_defaults(const char *path, const char *type,
2032 char *codec, char *codec_options, int len)
2034 char default_file[BCTEXTLEN];
2035 set_option_path(default_file, "%s/%s.dfl", path, type);
2036 FILE *fp = fopen(default_file,"r");
2038 fgets(codec, BCSTRLEN, fp);
2040 while( *cp && *cp!='\n' ) ++cp;
2042 while( len > 0 && fgets(codec_options, len, fp) ) {
2043 int n = strlen(codec_options);
2044 codec_options += n; len -= n;
2047 set_option_path(default_file, "%s/%s", path, codec);
2048 return load_options(default_file, codec_options, len);
2051 void FFMPEG::set_asset_format(Asset *asset, EDL *edl, const char *text)
2053 if( asset->format != FILE_FFMPEG ) return;
2054 if( text != asset->fformat )
2055 strcpy(asset->fformat, text);
2056 if( !asset->ff_format_options[0] )
2057 load_format_options(asset, edl);
2058 if( asset->audio_data && !asset->ff_audio_options[0] ) {
2059 if( !load_defaults("audio", text, asset->acodec,
2060 asset->ff_audio_options, sizeof(asset->ff_audio_options)) )
2061 scan_audio_options(asset, edl);
2063 asset->audio_data = 0;
2065 if( asset->video_data && !asset->ff_video_options[0] ) {
2066 if( !load_defaults("video", text, asset->vcodec,
2067 asset->ff_video_options, sizeof(asset->ff_video_options)) )
2068 scan_video_options(asset, edl);
2070 asset->video_data = 0;
2074 int FFMPEG::get_encoder(const char *options,
2075 char *format, char *codec, char *bsfilter)
2077 FILE *fp = fopen(options,"r");
2079 eprintf(_("options open failed %s\n"),options);
2082 char line[BCTEXTLEN];
2083 if( !fgets(line, sizeof(line), fp) ||
2084 scan_encoder(line, format, codec, bsfilter) )
2085 eprintf(_("format/codec not found %s\n"), options);
2090 int FFMPEG::scan_encoder(const char *line,
2091 char *format, char *codec, char *bsfilter)
2093 format[0] = codec[0] = bsfilter[0] = 0;
2094 if( scan_option_line(line, format, codec) ) return 1;
2096 while( *cp && *cp != '|' ) ++cp;
2097 if( !*cp ) return 0;
2099 do { *bp-- = 0; } while( bp>=codec && (*bp==' ' || *bp == '\t' ) );
2100 while( *++cp && (*cp==' ' || *cp == '\t') );
2102 for( int i=BCTEXTLEN; --i>0 && *cp; ) *bp++ = *cp++;
2107 int FFMPEG::read_options(const char *options, AVDictionary *&opts, int skip)
2109 FILE *fp = fopen(options,"r");
2112 while( !ret && --skip >= 0 ) {
2114 while( ch >= 0 && ch != '\n' ) ch = getc(fp);
2115 if( ch < 0 ) ret = 1;
2118 ret = read_options(fp, options, opts);
2123 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
2125 FILE *fp = fmemopen((void *)options,strlen(options),"r");
2127 int ret = read_options(fp, options, opts);
2130 AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
2131 if( tag ) st->id = strtol(tag->value,0,0);
2136 FFCodecRemap::FFCodecRemap()
2141 FFCodecRemap::~FFCodecRemap()
2143 delete [] old_codec;
2144 delete [] new_codec;
2147 int FFCodecRemaps::add(const char *val)
2149 char old_codec[BCSTRLEN], new_codec[BCSTRLEN];
2150 if( sscanf(val, " %63[a-zA-z0-9_-] = %63[a-z0-9_-]",
2151 &old_codec[0], &new_codec[0]) != 2 ) return 1;
2152 FFCodecRemap &remap = append();
2153 remap.old_codec = cstrdup(old_codec);
2154 remap.new_codec = cstrdup(new_codec);
2159 int FFCodecRemaps::update(AVCodecID &codec_id, AVCodec *&decoder)
2161 AVCodec *codec = avcodec_find_decoder(codec_id);
2162 if( !codec ) return -1;
2163 const char *name = codec->name;
2164 FFCodecRemaps &map = *this;
2166 while( --k >= 0 && strcmp(map[k].old_codec, name) );
2167 if( k < 0 ) return 1;
2168 const char *new_codec = map[k].new_codec;
2169 codec = avcodec_find_decoder_by_name(new_codec);
2170 if( !codec ) return -1;
2175 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
2177 int ret = 0, no = 0;
2178 char line[BCTEXTLEN];
2179 while( !ret && fgets(line, sizeof(line), fp) ) {
2180 line[sizeof(line)-1] = 0;
2181 if( line[0] == '#' ) continue;
2182 if( line[0] == '\n' ) continue;
2183 char key[BCSTRLEN], val[BCTEXTLEN];
2184 if( scan_option_line(line, key, val) ) {
2185 eprintf(_("err reading %s: line %d\n"), options, no);
2189 if( !strcmp(key, "duration") )
2190 opt_duration = strtod(val, 0);
2191 else if( !strcmp(key, "video_decoder") )
2192 opt_video_decoder = cstrdup(val);
2193 else if( !strcmp(key, "audio_decoder") )
2194 opt_audio_decoder = cstrdup(val);
2195 else if( !strcmp(key, "remap_video_decoder") )
2196 video_codec_remaps.add(val);
2197 else if( !strcmp(key, "remap_audio_decoder") )
2198 audio_codec_remaps.add(val);
2199 else if( !strcmp(key, "video_filter") )
2200 opt_video_filter = cstrdup(val);
2201 else if( !strcmp(key, "audio_filter") )
2202 opt_audio_filter = cstrdup(val);
2203 else if( !strcmp(key, "cin_hw_dev") )
2204 opt_hw_dev = cstrdup(val);
2205 else if( !strcmp(key, "loglevel") )
2208 av_dict_set(&opts, key, val, 0);
2214 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
2216 char option_path[BCTEXTLEN];
2217 set_option_path(option_path, "%s", options);
2218 return read_options(option_path, opts);
2221 int FFMPEG::load_options(const char *path, char *bfr, int len)
2224 FILE *fp = fopen(path, "r");
2226 fgets(bfr, len, fp); // skip hdr
2227 len = fread(bfr, 1, len-1, fp);
2228 if( len < 0 ) len = 0;
2234 void FFMPEG::set_loglevel(const char *ap)
2236 if( !ap || !*ap ) return;
2241 { "quiet" , AV_LOG_QUIET },
2242 { "panic" , AV_LOG_PANIC },
2243 { "fatal" , AV_LOG_FATAL },
2244 { "error" , AV_LOG_ERROR },
2245 { "warning", AV_LOG_WARNING },
2246 { "info" , AV_LOG_INFO },
2247 { "verbose", AV_LOG_VERBOSE },
2248 { "debug" , AV_LOG_DEBUG },
2250 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
2251 if( !strcmp(log_levels[i].name, ap) ) {
2252 av_log_set_level(log_levels[i].level);
2256 av_log_set_level(atoi(ap));
2259 double FFMPEG::to_secs(int64_t time, AVRational time_base)
2261 double base_time = time == AV_NOPTS_VALUE ? 0 :
2262 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
2263 return base_time / AV_TIME_BASE;
2266 int FFMPEG::info(char *text, int len)
2268 if( len <= 0 ) return 0;
2270 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
2272 report("format: %s\n",fmt_ctx->iformat->name);
2273 if( ffvideo.size() > 0 )
2274 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
2275 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
2276 const char *unkn = _("(unkn)");
2277 FFVideoStream *vid = ffvideo[vidx];
2278 AVStream *st = vid->st;
2279 AVCodecID codec_id = st->codecpar->codec_id;
2280 report(_("vid%d (%d), id 0x%06x:\n"), vid->idx, vid->fidx, codec_id);
2281 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
2282 report(" video%d %s ", vidx+1, desc ? desc->name : unkn);
2283 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
2284 AVPixelFormat pix_fmt = (AVPixelFormat)st->codecpar->format;
2285 const char *pfn = av_get_pix_fmt_name(pix_fmt);
2286 report(" pix %s\n", pfn ? pfn : unkn);
2287 enum AVColorSpace space = st->codecpar->color_space;
2288 const char *nm = av_color_space_name(space);
2289 report(" color space:%s", nm ? nm : unkn);
2290 enum AVColorRange range = st->codecpar->color_range;
2291 const char *rg = av_color_range_name(range);
2292 report("/ range:%s\n", rg ? rg : unkn);
2293 double secs = to_secs(st->duration, st->time_base);
2294 int64_t length = secs * vid->frame_rate + 0.5;
2295 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
2296 int64_t nudge = ofs * vid->frame_rate;
2297 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
2298 report(" %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
2299 int hrs = secs/3600; secs -= hrs*3600;
2300 int mins = secs/60; secs -= mins*60;
2301 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
2303 if( ffaudio.size() > 0 )
2304 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
2305 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2306 FFAudioStream *aud = ffaudio[aidx];
2307 AVStream *st = aud->st;
2308 AVCodecID codec_id = st->codecpar->codec_id;
2309 report(_("aud%d (%d), id 0x%06x:\n"), aud->idx, aud->fidx, codec_id);
2310 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
2311 int nch = aud->channels, ch0 = aud->channel0+1;
2312 report(" audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
2313 AVSampleFormat sample_fmt = (AVSampleFormat)st->codecpar->format;
2314 const char *fmt = av_get_sample_fmt_name(sample_fmt);
2315 report(" %s %d", fmt, aud->sample_rate);
2316 int sample_bits = av_get_bits_per_sample(codec_id);
2317 report(" %dbits\n", sample_bits);
2318 double secs = to_secs(st->duration, st->time_base);
2319 int64_t length = secs * aud->sample_rate + 0.5;
2320 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
2321 int64_t nudge = ofs * aud->sample_rate;
2322 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
2323 report(" %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
2324 int hrs = secs/3600; secs -= hrs*3600;
2325 int mins = secs/60; secs -= mins*60;
2326 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
2328 if( fmt_ctx->nb_programs > 0 )
2329 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
2330 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
2331 report("program %d", i+1);
2332 AVProgram *pgrm = fmt_ctx->programs[i];
2333 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2334 int idx = pgrm->stream_index[j];
2335 int vidx = ffvideo.size();
2336 while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
2338 report(", vid%d", vidx);
2341 int aidx = ffaudio.size();
2342 while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
2344 report(", aud%d", aidx);
2347 report(", (%d)", pgrm->stream_index[j]);
2352 AVDictionaryEntry *tag = 0;
2353 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
2354 report("%s=%s\n", tag->key, tag->value);
2363 int FFMPEG::init_decoder(const char *filename)
2365 ff_lock("FFMPEG::init_decoder");
2367 char file_opts[BCTEXTLEN];
2368 strcpy(file_opts, filename);
2369 char *bp = strrchr(file_opts, '/');
2370 if( !bp ) bp = file_opts;
2371 char *sp = strrchr(bp, '.');
2372 if( !sp ) sp = bp + strlen(bp);
2374 AVInputFormat *ifmt = 0;
2376 strcpy(sp, ".opts");
2377 fp = fopen(file_opts, "r");
2380 read_options(fp, file_opts, opts);
2382 AVDictionaryEntry *tag;
2383 if( (tag=av_dict_get(opts, "format", NULL, 0)) != 0 ) {
2384 ifmt = av_find_input_format(tag->value);
2388 load_options("decode.opts", opts);
2389 AVDictionary *fopts = 0;
2390 av_dict_copy(&fopts, opts, 0);
2391 int ret = avformat_open_input(&fmt_ctx, filename, ifmt, &fopts);
2392 av_dict_free(&fopts);
2394 ret = avformat_find_stream_info(fmt_ctx, NULL);
2399 return !ret ? 0 : 1;
2402 int FFMPEG::open_decoder()
2405 if( stat(fmt_ctx->url, &st) < 0 ) {
2406 eprintf(_("can't stat file: %s\n"), fmt_ctx->url);
2410 int64_t file_bits = 8 * st.st_size;
2411 if( !fmt_ctx->bit_rate && opt_duration > 0 )
2412 fmt_ctx->bit_rate = file_bits / opt_duration;
2415 if( fmt_ctx->bit_rate > 0 ) {
2416 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2417 AVStream *st = fmt_ctx->streams[i];
2418 if( st->duration != AV_NOPTS_VALUE ) continue;
2419 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
2420 st->duration = av_rescale(file_bits, st->time_base.den,
2421 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
2425 if( estimated && !(fflags & FF_ESTM_TIMES) ) {
2426 fflags |= FF_ESTM_TIMES;
2427 printf("FFMPEG::open_decoder: some stream times estimated: %s\n",
2431 ff_lock("FFMPEG::open_decoder");
2432 int ret = 0, bad_time = 0;
2433 for( int i=0; !ret && i<(int)fmt_ctx->nb_streams; ++i ) {
2434 AVStream *st = fmt_ctx->streams[i];
2435 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
2436 AVCodecParameters *avpar = st->codecpar;
2437 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avpar->codec_id);
2438 if( !codec_desc ) continue;
2439 switch( avpar->codec_type ) {
2440 case AVMEDIA_TYPE_VIDEO: {
2441 if( avpar->width < 1 ) continue;
2442 if( avpar->height < 1 ) continue;
2443 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
2444 if( framerate.num < 1 ) continue;
2446 int vidx = ffvideo.size();
2447 FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
2448 vstrm_index.append(ffidx(vidx, 0));
2449 ffvideo.append(vid);
2450 vid->width = avpar->width;
2451 vid->height = avpar->height;
2452 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
2453 switch( avpar->color_range ) {
2454 case AVCOL_RANGE_MPEG:
2455 vid->color_range = BC_COLORS_MPEG;
2457 case AVCOL_RANGE_JPEG:
2458 vid->color_range = BC_COLORS_JPEG;
2461 vid->color_range = !file_base ? BC_COLORS_JPEG :
2462 file_base->file->preferences->yuv_color_range;
2465 switch( avpar->color_space ) {
2466 case AVCOL_SPC_BT470BG:
2467 case AVCOL_SPC_SMPTE170M:
2468 vid->color_space = BC_COLORS_BT601;
2470 case AVCOL_SPC_BT709:
2471 vid->color_space = BC_COLORS_BT709;
2473 case AVCOL_SPC_BT2020_NCL:
2474 case AVCOL_SPC_BT2020_CL:
2475 vid->color_space = BC_COLORS_BT2020;
2478 vid->color_space = !file_base ? BC_COLORS_BT601 :
2479 file_base->file->preferences->yuv_color_space;
2482 double secs = to_secs(st->duration, st->time_base);
2483 vid->length = secs * vid->frame_rate;
2484 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
2485 vid->nudge = st->start_time;
2487 if( opt_video_filter )
2488 ret = vid->create_filter(opt_video_filter, avpar);
2490 case AVMEDIA_TYPE_AUDIO: {
2491 if( avpar->channels < 1 ) continue;
2492 if( avpar->sample_rate < 1 ) continue;
2494 int aidx = ffaudio.size();
2495 FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
2496 ffaudio.append(aud);
2497 aud->channel0 = astrm_index.size();
2498 aud->channels = avpar->channels;
2499 for( int ch=0; ch<aud->channels; ++ch )
2500 astrm_index.append(ffidx(aidx, ch));
2501 aud->sample_rate = avpar->sample_rate;
2502 double secs = to_secs(st->duration, st->time_base);
2503 aud->length = secs * aud->sample_rate;
2504 aud->init_swr(aud->channels, avpar->format, aud->sample_rate);
2505 aud->nudge = st->start_time;
2507 if( opt_audio_filter )
2508 ret = aud->create_filter(opt_audio_filter, avpar);
2513 if( bad_time && !(fflags & FF_BAD_TIMES) ) {
2514 fflags |= FF_BAD_TIMES;
2515 printf(_("FFMPEG::open_decoder: some stream have bad times: %s\n"),
2519 return ret < 0 ? -1 : 0;
2523 int FFMPEG::init_encoder(const char *filename)
2525 // try access first for named pipes
2526 int ret = access(filename, W_OK);
2528 int fd = ::open(filename,O_WRONLY);
2529 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
2530 if( fd >= 0 ) { close(fd); ret = 0; }
2533 eprintf(_("bad file path: %s\n"), filename);
2536 ret = get_file_format();
2538 eprintf(_("bad file format: %s\n"), filename);
2542 eprintf(_("mismatch audio/video file format: %s\n"), filename);
2545 ff_lock("FFMPEG::init_encoder");
2547 char format[BCSTRLEN];
2548 if( get_format(format, "format", file_format) )
2549 strcpy(format, file_format);
2550 avformat_alloc_output_context2(&fmt_ctx, 0, format, filename);
2552 eprintf(_("failed: %s\n"), filename);
2557 load_options("encode.opts", opts);
2563 int FFMPEG::open_encoder(const char *type, const char *spec)
2566 Asset *asset = file_base->asset;
2567 char *filename = asset->path;
2568 AVDictionary *sopts = 0;
2569 av_dict_copy(&sopts, opts, 0);
2570 char option_path[BCTEXTLEN];
2571 set_option_path(option_path, "%s/%s.opts", type, type);
2572 read_options(option_path, sopts);
2573 get_option_path(option_path, type, spec);
2574 char format_name[BCSTRLEN], codec_name[BCTEXTLEN], bsfilter[BCTEXTLEN];
2575 if( get_encoder(option_path, format_name, codec_name, bsfilter) ) {
2576 eprintf(_("get_encoder failed %s:%s\n"), option_path, filename);
2581 if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
2583 else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
2584 else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
2587 ff_lock("FFMPEG::open_encoder");
2590 AVCodecContext *ctx = 0;
2592 const AVCodecDescriptor *codec_desc = 0;
2593 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
2595 eprintf(_("cant find codec %s:%s\n"), codec_name, filename);
2599 codec_desc = avcodec_descriptor_get(codec->id);
2601 eprintf(_("unknown codec %s:%s\n"), codec_name, filename);
2606 st = avformat_new_stream(fmt_ctx, 0);
2608 eprintf(_("cant create stream %s:%s\n"), codec_name, filename);
2613 switch( codec_desc->type ) {
2614 case AVMEDIA_TYPE_AUDIO: {
2616 eprintf(_("duplicate audio %s:%s\n"), codec_name, filename);
2620 if( scan_options(asset->ff_audio_options, sopts, st) ) {
2621 eprintf(_("bad audio options %s:%s\n"), codec_name, filename);
2626 ctx = avcodec_alloc_context3(codec);
2627 if( asset->ff_audio_bitrate > 0 ) {
2628 ctx->bit_rate = asset->ff_audio_bitrate;
2630 sprintf(arg, "%d", asset->ff_audio_bitrate);
2631 av_dict_set(&sopts, "b", arg, 0);
2633 else if( asset->ff_audio_quality >= 0 ) {
2634 ctx->global_quality = asset->ff_audio_quality * FF_QP2LAMBDA;
2635 ctx->qmin = ctx->qmax = asset->ff_audio_quality;
2636 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2637 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2638 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2640 av_dict_set(&sopts, "flags", "+qscale", 0);
2641 sprintf(arg, "%d", asset->ff_audio_quality);
2642 av_dict_set(&sopts, "qscale", arg, 0);
2643 sprintf(arg, "%d", ctx->global_quality);
2644 av_dict_set(&sopts, "global_quality", arg, 0);
2646 int aidx = ffaudio.size();
2647 int fidx = aidx + ffvideo.size();
2648 FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
2649 aud->avctx = ctx; ffaudio.append(aud); fst = aud;
2650 aud->sample_rate = asset->sample_rate;
2651 ctx->channels = aud->channels = asset->channels;
2652 for( int ch=0; ch<aud->channels; ++ch )
2653 astrm_index.append(ffidx(aidx, ch));
2654 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
2655 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
2656 if( !ctx->sample_rate ) {
2657 eprintf(_("check_sample_rate failed %s\n"), filename);
2661 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
2662 AVSampleFormat sample_fmt = av_get_sample_fmt(asset->ff_sample_format);
2663 if( sample_fmt == AV_SAMPLE_FMT_NONE )
2664 sample_fmt = codec->sample_fmts ? codec->sample_fmts[0] : AV_SAMPLE_FMT_S16;
2665 ctx->sample_fmt = sample_fmt;
2666 uint64_t layout = av_get_default_channel_layout(ctx->channels);
2667 aud->resample_context = swr_alloc_set_opts(NULL,
2668 layout, ctx->sample_fmt, aud->sample_rate,
2669 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
2671 swr_init(aud->resample_context);
2674 case AVMEDIA_TYPE_VIDEO: {
2676 eprintf(_("duplicate video %s:%s\n"), codec_name, filename);
2680 if( scan_options(asset->ff_video_options, sopts, st) ) {
2681 eprintf(_("bad video options %s:%s\n"), codec_name, filename);
2686 ctx = avcodec_alloc_context3(codec);
2687 if( asset->ff_video_bitrate > 0 ) {
2688 ctx->bit_rate = asset->ff_video_bitrate;
2690 sprintf(arg, "%d", asset->ff_video_bitrate);
2691 av_dict_set(&sopts, "b", arg, 0);
2693 else if( asset->ff_video_quality >= 0 ) {
2694 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
2695 ctx->qmin = ctx->qmax = asset->ff_video_quality;
2696 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2697 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2698 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2700 av_dict_set(&sopts, "flags", "+qscale", 0);
2701 sprintf(arg, "%d", asset->ff_video_quality);
2702 av_dict_set(&sopts, "qscale", arg, 0);
2703 sprintf(arg, "%d", ctx->global_quality);
2704 av_dict_set(&sopts, "global_quality", arg, 0);
2706 int vidx = ffvideo.size();
2707 int fidx = vidx + ffaudio.size();
2708 FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
2709 vstrm_index.append(ffidx(vidx, 0));
2710 vid->avctx = ctx; ffvideo.append(vid); fst = vid;
2711 vid->width = asset->width;
2712 vid->height = asset->height;
2713 vid->frame_rate = asset->frame_rate;
2714 if( (vid->color_range = asset->ff_color_range) < 0 )
2715 vid->color_range = file_base->file->preferences->yuv_color_range;
2716 switch( vid->color_range ) {
2717 case BC_COLORS_MPEG: ctx->color_range = AVCOL_RANGE_MPEG; break;
2718 case BC_COLORS_JPEG: ctx->color_range = AVCOL_RANGE_JPEG; break;
2720 if( (vid->color_space = asset->ff_color_space) < 0 )
2721 vid->color_space = file_base->file->preferences->yuv_color_space;
2722 switch( vid->color_space ) {
2723 case BC_COLORS_BT601: ctx->colorspace = AVCOL_SPC_SMPTE170M; break;
2724 case BC_COLORS_BT709: ctx->colorspace = AVCOL_SPC_BT709; break;
2725 case BC_COLORS_BT2020: ctx->colorspace = AVCOL_SPC_BT2020_NCL; break;
2727 AVPixelFormat pix_fmt = av_get_pix_fmt(asset->ff_pixel_format);
2728 if( opt_hw_dev != 0 ) {
2729 AVHWDeviceType hw_type = vid->encode_hw_activate(opt_hw_dev);
2731 case AV_HWDEVICE_TYPE_VAAPI:
2732 pix_fmt = AV_PIX_FMT_VAAPI;
2734 case AV_HWDEVICE_TYPE_NONE:
2738 if( pix_fmt == AV_PIX_FMT_NONE )
2739 pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
2740 ctx->pix_fmt = pix_fmt;
2742 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
2743 int mask_w = (1<<desc->log2_chroma_w)-1;
2744 ctx->width = (vid->width+mask_w) & ~mask_w;
2745 int mask_h = (1<<desc->log2_chroma_h)-1;
2746 ctx->height = (vid->height+mask_h) & ~mask_h;
2747 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
2748 AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
2749 if( !frame_rate.num || !frame_rate.den ) {
2750 eprintf(_("check_frame_rate failed %s\n"), filename);
2754 av_reduce(&frame_rate.num, &frame_rate.den,
2755 frame_rate.num, frame_rate.den, INT_MAX);
2756 ctx->framerate = (AVRational) { frame_rate.num, frame_rate.den };
2757 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
2758 st->avg_frame_rate = frame_rate;
2759 st->time_base = ctx->time_base;
2761 vid->interlaced = asset->interlace_mode == ILACE_MODE_TOP_FIRST ||
2762 asset->interlace_mode == ILACE_MODE_BOTTOM_FIRST ? 1 : 0;
2763 vid->top_field_first = asset->interlace_mode == ILACE_MODE_TOP_FIRST ? 1 : 0;
2766 eprintf(_("not audio/video, %s:%s\n"), codec_name, filename);
2771 AVDictionaryEntry *tag;
2772 if( (tag=av_dict_get(sopts, "cin_stats_filename", NULL, 0)) != 0 ) {
2773 char suffix[BCSTRLEN]; sprintf(suffix,"-%d.log",fst->fidx);
2774 fst->stats_filename = cstrcat(2, tag->value, suffix);
2776 if( (tag=av_dict_get(sopts, "flags", NULL, 0)) != 0 ) {
2777 int pass = fst->pass;
2778 char *cp = tag->value;
2780 int ch = *cp++, pfx = ch=='-' ? -1 : ch=='+' ? 1 : 0;
2781 if( !isalnum(!pfx ? ch : (ch=*cp++)) ) continue;
2782 char id[BCSTRLEN], *bp = id, *ep = bp+sizeof(id)-1;
2783 for( *bp++=ch; isalnum(ch=*cp); ++cp )
2784 if( bp < ep ) *bp++ = ch;
2786 if( !strcmp(id, "pass1") ) {
2787 pass = pfx<0 ? (pass&~1) : pfx>0 ? (pass|1) : 1;
2789 else if( !strcmp(id, "pass2") ) {
2790 pass = pfx<0 ? (pass&~2) : pfx>0 ? (pass|2) : 2;
2793 if( (fst->pass=pass) ) {
2794 if( pass & 1 ) ctx->flags |= AV_CODEC_FLAG_PASS1;
2795 if( pass & 2 ) ctx->flags |= AV_CODEC_FLAG_PASS2;
2801 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
2802 ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
2803 if( fst->stats_filename && (ret=fst->init_stats_file()) )
2804 eprintf(_("error: stats file = %s\n"), fst->stats_filename);
2807 av_dict_set(&sopts, "cin_bitrate", 0, 0);
2808 av_dict_set(&sopts, "cin_quality", 0, 0);
2810 if( !av_dict_get(sopts, "threads", NULL, 0) )
2811 ctx->thread_count = ff_cpus();
2812 ret = avcodec_open2(ctx, codec, &sopts);
2814 ret = avcodec_parameters_from_context(st->codecpar, ctx);
2816 fprintf(stderr, "Could not copy the stream parameters\n");
2819 _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
2820 ret = avcodec_copy_context(st->codec, ctx);
2821 _Pragma("GCC diagnostic warning \"-Wdeprecated-declarations\"")
2823 fprintf(stderr, "Could not copy the stream context\n");
2826 ff_err(ret,"FFMPEG::open_encoder");
2827 eprintf(_("open failed %s:%s\n"), codec_name, filename);
2833 if( !ret && fst && bsfilter[0] ) {
2834 ret = av_bsf_list_parse_str(bsfilter, &fst->bsfc);
2836 ff_err(ret,"FFMPEG::open_encoder");
2837 eprintf(_("bitstream filter failed %s:\n%s\n"), filename, bsfilter);
2848 av_dict_free(&sopts);
2852 int FFMPEG::close_encoder()
2855 if( encoding > 0 ) {
2856 av_write_trailer(fmt_ctx);
2857 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
2858 avio_closep(&fmt_ctx->pb);
2864 int FFMPEG::decode_activate()
2866 if( decoding < 0 ) {
2868 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
2869 ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
2870 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
2871 ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
2872 // set nudges for each program stream set
2873 const int64_t min_nudge = INT64_MIN+1;
2874 int npgrms = fmt_ctx->nb_programs;
2875 for( int i=0; i<npgrms; ++i ) {
2876 AVProgram *pgrm = fmt_ctx->programs[i];
2877 // first start time video stream
2878 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2879 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2880 int fidx = pgrm->stream_index[j];
2881 AVStream *st = fmt_ctx->streams[fidx];
2882 AVCodecParameters *avpar = st->codecpar;
2883 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2884 if( st->start_time == AV_NOPTS_VALUE ) continue;
2885 if( vstart_time < st->start_time )
2886 vstart_time = st->start_time;
2889 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2890 if( st->start_time == AV_NOPTS_VALUE ) continue;
2891 if( astart_time < st->start_time )
2892 astart_time = st->start_time;
2896 //since frame rate is much more grainy than sample rate, it is better to
2897 // align using video, so that total absolute error is minimized.
2898 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2899 astart_time > min_nudge ? astart_time : AV_NOPTS_VALUE;
2900 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2901 int fidx = pgrm->stream_index[j];
2902 AVStream *st = fmt_ctx->streams[fidx];
2903 AVCodecParameters *avpar = st->codecpar;
2904 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2905 for( int k=0; k<ffvideo.size(); ++k ) {
2906 if( ffvideo[k]->fidx != fidx ) continue;
2907 ffvideo[k]->nudge = nudge;
2911 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2912 for( int k=0; k<ffaudio.size(); ++k ) {
2913 if( ffaudio[k]->fidx != fidx ) continue;
2914 ffaudio[k]->nudge = nudge;
2920 // set nudges for any streams not yet set
2921 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2922 int nstreams = fmt_ctx->nb_streams;
2923 for( int i=0; i<nstreams; ++i ) {
2924 AVStream *st = fmt_ctx->streams[i];
2925 AVCodecParameters *avpar = st->codecpar;
2926 switch( avpar->codec_type ) {
2927 case AVMEDIA_TYPE_VIDEO: {
2928 if( st->start_time == AV_NOPTS_VALUE ) continue;
2929 int vidx = ffvideo.size();
2930 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
2931 if( vidx < 0 ) continue;
2932 if( ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
2933 if( vstart_time < st->start_time )
2934 vstart_time = st->start_time;
2936 case AVMEDIA_TYPE_AUDIO: {
2937 if( st->start_time == AV_NOPTS_VALUE ) continue;
2938 int aidx = ffaudio.size();
2939 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
2940 if( aidx < 0 ) continue;
2941 if( ffaudio[aidx]->frame_sz < avpar->frame_size )
2942 ffaudio[aidx]->frame_sz = avpar->frame_size;
2943 if( ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
2944 if( astart_time < st->start_time )
2945 astart_time = st->start_time;
2950 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2951 astart_time > min_nudge ? astart_time : 0;
2952 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
2953 if( ffvideo[vidx]->nudge == AV_NOPTS_VALUE )
2954 ffvideo[vidx]->nudge = nudge;
2956 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2957 if( ffaudio[aidx]->nudge == AV_NOPTS_VALUE )
2958 ffaudio[aidx]->nudge = nudge;
2965 int FFMPEG::encode_activate()
2968 if( encoding < 0 ) {
2970 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
2971 (ret=avio_open(&fmt_ctx->pb, fmt_ctx->url, AVIO_FLAG_WRITE)) < 0 ) {
2972 ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
2976 if( !strcmp(file_format, "image2") ) {
2977 Asset *asset = file_base->asset;
2978 const char *filename = asset->path;
2979 FILE *fp = fopen(filename,"w");
2981 eprintf(_("Cant write image2 header file: %s\n %m"), filename);
2984 fprintf(fp, "IMAGE2\n");
2985 fprintf(fp, "# Frame rate: %f\n", asset->frame_rate);
2986 fprintf(fp, "# Width: %d\n", asset->width);
2987 fprintf(fp, "# Height: %d\n", asset->height);
2991 AVProgram *prog = av_new_program(fmt_ctx, prog_id);
2992 for( int i=0; i< ffvideo.size(); ++i )
2993 av_program_add_stream_index(fmt_ctx, prog_id, ffvideo[i]->fidx);
2994 for( int i=0; i< ffaudio.size(); ++i )
2995 av_program_add_stream_index(fmt_ctx, prog_id, ffaudio[i]->fidx);
2996 int pi = fmt_ctx->nb_programs;
2997 while( --pi >= 0 && fmt_ctx->programs[pi]->id != prog_id );
2998 AVDictionary **meta = &prog->metadata;
2999 av_dict_set(meta, "service_provider", "cin5", 0);
3000 const char *path = fmt_ctx->url, *bp = strrchr(path,'/');
3001 if( bp ) path = bp + 1;
3002 av_dict_set(meta, "title", path, 0);
3004 if( ffaudio.size() ) {
3005 const char *ep = getenv("CIN_AUDIO_LANG"), *lp = 0;
3006 if( !ep && (lp=getenv("LANG")) ) { // some are guesses
3007 static struct { const char lc[3], lng[4]; } lcode[] = {
3008 { "en", "eng" }, { "de", "ger" }, { "es", "spa" },
3009 { "eu", "bas" }, { "fr", "fre" }, { "el", "gre" },
3010 { "hi", "hin" }, { "it", "ita" }, { "ja", "jap" },
3011 { "ko", "kor" }, { "du", "dut" }, { "pl", "pol" },
3012 { "pt", "por" }, { "ru", "rus" }, { "sl", "slv" },
3013 { "uk", "ukr" }, { "vi", "vie" }, { "zh", "chi" },
3015 for( int i=sizeof(lcode)/sizeof(lcode[0]); --i>=0 && !ep; )
3016 if( !strncmp(lcode[i].lc,lp,2) ) ep = lcode[i].lng;
3018 if( !ep ) ep = "und";
3020 strncpy(lang,ep,3); lang[3] = 0;
3021 AVStream *st = ffaudio[0]->st;
3022 av_dict_set(&st->metadata,"language",lang,0);
3025 AVDictionary *fopts = 0;
3026 char option_path[BCTEXTLEN];
3027 set_option_path(option_path, "format/%s", file_format);
3028 read_options(option_path, fopts, 1);
3029 av_dict_copy(&fopts, opts, 0);
3030 if( scan_options(file_base->asset->ff_format_options, fopts, 0) ) {
3031 eprintf(_("bad format options %s\n"), file_base->asset->path);
3035 ret = avformat_write_header(fmt_ctx, &fopts);
3037 ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
3041 av_dict_free(&fopts);
3048 int FFMPEG::audio_seek(int stream, int64_t pos)
3050 int aidx = astrm_index[stream].st_idx;
3051 FFAudioStream *aud = ffaudio[aidx];
3052 aud->audio_seek(pos);
3056 int FFMPEG::video_seek(int stream, int64_t pos)
3058 int vidx = vstrm_index[stream].st_idx;
3059 FFVideoStream *vid = ffvideo[vidx];
3060 vid->video_seek(pos);
3065 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
3067 if( !has_audio || chn >= astrm_index.size() ) return -1;
3068 int aidx = astrm_index[chn].st_idx;
3069 FFAudioStream *aud = ffaudio[aidx];
3070 if( aud->load(pos, len) < len ) return -1;
3071 int ch = astrm_index[chn].st_ch;
3072 int ret = aud->read(samples,len,ch);
3076 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
3078 if( !has_video || layer >= vstrm_index.size() ) return -1;
3079 int vidx = vstrm_index[layer].st_idx;
3080 FFVideoStream *vid = ffvideo[vidx];
3081 return vid->load(vframe, pos);
3085 int FFMPEG::encode(int stream, double **samples, int len)
3087 FFAudioStream *aud = ffaudio[stream];
3088 return aud->encode(samples, len);
3092 int FFMPEG::encode(int stream, VFrame *frame)
3094 FFVideoStream *vid = ffvideo[stream];
3095 return vid->encode(frame);
3098 void FFMPEG::start_muxer()
3106 void FFMPEG::stop_muxer()
3115 void FFMPEG::flow_off()
3118 flow_lock->lock("FFMPEG::flow_off");
3122 void FFMPEG::flow_on()
3126 flow_lock->unlock();
3129 void FFMPEG::flow_ctl()
3132 flow_lock->lock("FFMPEG::flow_ctl");
3133 flow_lock->unlock();
3137 int FFMPEG::mux_audio(FFrame *frm)
3139 FFStream *fst = frm->fst;
3140 AVCodecContext *ctx = fst->avctx;
3141 AVFrame *frame = *frm;
3142 AVRational tick_rate = {1, ctx->sample_rate};
3143 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
3144 int ret = fst->encode_frame(frame);
3146 ff_err(ret, "FFMPEG::mux_audio");
3147 return ret >= 0 ? 0 : 1;
3150 int FFMPEG::mux_video(FFrame *frm)
3152 FFStream *fst = frm->fst;
3153 AVFrame *frame = *frm;
3154 frame->pts = frm->position;
3155 int ret = fst->encode_frame(frame);
3157 ff_err(ret, "FFMPEG::mux_video");
3158 return ret >= 0 ? 0 : 1;
3164 double atm = -1, vtm = -1;
3165 FFrame *afrm = 0, *vfrm = 0;
3167 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
3168 FFStream *fst = ffaudio[i];
3169 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
3170 FFrame *frm = fst->frms.first;
3171 if( !frm ) { if( !done ) return; continue; }
3172 double tm = to_secs(frm->position, fst->avctx->time_base);
3173 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
3175 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
3176 FFStream *fst = ffvideo[i];
3177 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
3178 FFrame *frm = fst->frms.first;
3179 if( !frm ) { if( !done ) return; continue; }
3180 double tm = to_secs(frm->position, fst->avctx->time_base);
3181 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
3183 if( !demand ) flow_off();
3184 if( !afrm && !vfrm ) break;
3185 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
3186 vfrm->position, vfrm->fst->avctx->time_base,
3187 afrm->position, afrm->fst->avctx->time_base);
3188 FFrame *frm = v <= 0 ? vfrm : afrm;
3189 if( frm == afrm ) mux_audio(frm);
3190 if( frm == vfrm ) mux_video(frm);
3199 mux_lock->lock("FFMPEG::run");
3202 for( int i=0; i<ffaudio.size(); ++i )
3203 ffaudio[i]->drain();
3204 for( int i=0; i<ffvideo.size(); ++i )
3205 ffvideo[i]->drain();
3207 for( int i=0; i<ffaudio.size(); ++i )
3208 ffaudio[i]->flush();
3209 for( int i=0; i<ffvideo.size(); ++i )
3210 ffvideo[i]->flush();
3214 int FFMPEG::ff_total_audio_channels()
3216 return astrm_index.size();
3219 int FFMPEG::ff_total_astreams()
3221 return ffaudio.size();
3224 int FFMPEG::ff_audio_channels(int stream)
3226 return ffaudio[stream]->channels;
3229 int FFMPEG::ff_sample_rate(int stream)
3231 return ffaudio[stream]->sample_rate;
3234 const char* FFMPEG::ff_audio_format(int stream)
3236 AVStream *st = ffaudio[stream]->st;
3237 AVCodecID id = st->codecpar->codec_id;
3238 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
3239 return desc ? desc->name : _("Unknown");
3242 int FFMPEG::ff_audio_pid(int stream)
3244 return ffaudio[stream]->st->id;
3247 int64_t FFMPEG::ff_audio_samples(int stream)
3249 return ffaudio[stream]->length;
3252 // find audio astream/channels with this program,
3253 // or all program audio channels (astream=-1)
3254 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
3258 int vidx = ffvideo[vstream]->fidx;
3259 // find first program with this video stream
3260 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
3261 AVProgram *pgrm = fmt_ctx->programs[i];
3262 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
3263 int st_idx = pgrm->stream_index[j];
3264 AVStream *st = fmt_ctx->streams[st_idx];
3265 if( st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
3266 if( st_idx == vidx ) pidx = i;
3269 if( pidx < 0 ) return -1;
3271 int64_t channels = 0;
3272 AVProgram *pgrm = fmt_ctx->programs[pidx];
3273 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
3274 int aidx = pgrm->stream_index[j];
3275 AVStream *st = fmt_ctx->streams[aidx];
3276 if( st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
3277 if( astream > 0 ) { --astream; continue; }
3279 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
3280 if( ffaudio[i]->fidx == aidx ) astrm = i;
3282 if( ret < 0 ) ret = astrm;
3283 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
3284 channels |= mask << ffaudio[astrm]->channel0;
3286 if( !astream ) break;
3288 channel_mask = channels;
3293 int FFMPEG::ff_total_video_layers()
3295 return vstrm_index.size();
3298 int FFMPEG::ff_total_vstreams()
3300 return ffvideo.size();
3303 int FFMPEG::ff_video_width(int stream)
3305 return ffvideo[stream]->width;
3308 int FFMPEG::ff_video_height(int stream)
3310 return ffvideo[stream]->height;
3313 int FFMPEG::ff_set_video_width(int stream, int width)
3315 int w = ffvideo[stream]->width;
3316 ffvideo[stream]->width = width;
3320 int FFMPEG::ff_set_video_height(int stream, int height)
3322 int h = ffvideo[stream]->height;
3323 ffvideo[stream]->height = height;
3327 int FFMPEG::ff_coded_width(int stream)
3329 return ffvideo[stream]->avctx->coded_width;
3332 int FFMPEG::ff_coded_height(int stream)
3334 return ffvideo[stream]->avctx->coded_height;
3337 float FFMPEG::ff_aspect_ratio(int stream)
3339 return ffvideo[stream]->aspect_ratio;
3342 const char* FFMPEG::ff_video_codec(int stream)
3344 AVStream *st = ffvideo[stream]->st;
3345 AVCodecID id = st->codecpar->codec_id;
3346 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
3347 return desc ? desc->name : _("Unknown");
3350 int FFMPEG::ff_color_range(int stream)
3352 return ffvideo[stream]->color_range;
3355 int FFMPEG::ff_color_space(int stream)
3357 return ffvideo[stream]->color_space;
3360 double FFMPEG::ff_frame_rate(int stream)
3362 return ffvideo[stream]->frame_rate;
3365 int64_t FFMPEG::ff_video_frames(int stream)
3367 return ffvideo[stream]->length;
3370 int FFMPEG::ff_video_pid(int stream)
3372 return ffvideo[stream]->st->id;
3375 int FFMPEG::ff_video_mpeg_color_range(int stream)
3377 return ffvideo[stream]->st->codecpar->color_range == AVCOL_RANGE_MPEG ? 1 : 0;
3380 int FFMPEG::ff_cpus()
3382 return file_base->file->cpus;
3385 const char *FFMPEG::ff_hw_dev()
3387 return &file_base->file->preferences->use_hw_dev[0];
3390 Preferences *FFMPEG::ff_prefs()
3392 return !file_base ? 0 : file_base->file->preferences;
3395 int FFVideoStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
3397 avfilter_register_all();
3398 const char *sp = filter_spec;
3399 char filter_name[BCSTRLEN], *np = filter_name;
3400 int i = sizeof(filter_name);
3401 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
3403 const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
3404 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_VIDEO ) {
3405 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
3408 filter_graph = avfilter_graph_alloc();
3409 const AVFilter *buffersrc = avfilter_get_by_name("buffer");
3410 const AVFilter *buffersink = avfilter_get_by_name("buffersink");
3412 int ret = 0; char args[BCTEXTLEN];
3413 AVPixelFormat pix_fmt = (AVPixelFormat)avpar->format;
3414 snprintf(args, sizeof(args),
3415 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
3416 avpar->width, avpar->height, (int)pix_fmt,
3417 st->time_base.num, st->time_base.den,
3418 avpar->sample_aspect_ratio.num, avpar->sample_aspect_ratio.den);
3420 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
3421 args, NULL, filter_graph);
3423 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
3424 NULL, NULL, filter_graph);
3426 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
3427 (uint8_t*)&pix_fmt, sizeof(pix_fmt),
3428 AV_OPT_SEARCH_CHILDREN);
3430 ff_err(ret, "FFVideoStream::create_filter");
3432 ret = FFStream::create_filter(filter_spec);
3433 return ret >= 0 ? 0 : -1;
3436 int FFAudioStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
3438 avfilter_register_all();
3439 const char *sp = filter_spec;
3440 char filter_name[BCSTRLEN], *np = filter_name;
3441 int i = sizeof(filter_name);
3442 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
3444 const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
3445 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_AUDIO ) {
3446 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
3449 filter_graph = avfilter_graph_alloc();
3450 const AVFilter *buffersrc = avfilter_get_by_name("abuffer");
3451 const AVFilter *buffersink = avfilter_get_by_name("abuffersink");
3452 int ret = 0; char args[BCTEXTLEN];
3453 AVSampleFormat sample_fmt = (AVSampleFormat)avpar->format;
3454 snprintf(args, sizeof(args),
3455 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
3456 st->time_base.num, st->time_base.den, avpar->sample_rate,
3457 av_get_sample_fmt_name(sample_fmt), avpar->channel_layout);
3459 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
3460 args, NULL, filter_graph);
3462 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
3463 NULL, NULL, filter_graph);
3465 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
3466 (uint8_t*)&sample_fmt, sizeof(sample_fmt),
3467 AV_OPT_SEARCH_CHILDREN);
3469 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
3470 (uint8_t*)&avpar->channel_layout,
3471 sizeof(avpar->channel_layout), AV_OPT_SEARCH_CHILDREN);
3473 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
3474 (uint8_t*)&sample_rate, sizeof(sample_rate),
3475 AV_OPT_SEARCH_CHILDREN);
3477 ff_err(ret, "FFAudioStream::create_filter");
3479 ret = FFStream::create_filter(filter_spec);
3480 return ret >= 0 ? 0 : -1;
3483 int FFStream::create_filter(const char *filter_spec)
3485 /* Endpoints for the filter graph. */
3486 AVFilterInOut *outputs = avfilter_inout_alloc();
3487 outputs->name = av_strdup("in");
3488 outputs->filter_ctx = buffersrc_ctx;
3489 outputs->pad_idx = 0;
3492 AVFilterInOut *inputs = avfilter_inout_alloc();
3493 inputs->name = av_strdup("out");
3494 inputs->filter_ctx = buffersink_ctx;
3495 inputs->pad_idx = 0;
3498 int ret = !outputs->name || !inputs->name ? -1 : 0;
3500 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
3501 &inputs, &outputs, NULL);
3503 ret = avfilter_graph_config(filter_graph, NULL);
3506 ff_err(ret, "FFStream::create_filter");
3507 avfilter_graph_free(&filter_graph);
3510 avfilter_inout_free(&inputs);
3511 avfilter_inout_free(&outputs);
3515 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
3518 av_init_packet(&pkt);
3519 AVFrame *frame = av_frame_alloc();
3521 fprintf(stderr,"FFMPEG::scan: ");
3522 fprintf(stderr,_("av_frame_alloc failed\n"));
3523 fprintf(stderr,"FFMPEG::scan:file=%s\n", file_base->asset->path);
3527 index_state->add_video_markers(ffvideo.size());
3528 index_state->add_audio_markers(ffaudio.size());
3530 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
3532 AVDictionary *copts = 0;
3533 av_dict_copy(&copts, opts, 0);
3534 AVStream *st = fmt_ctx->streams[i];
3535 AVCodecID codec_id = st->codecpar->codec_id;
3536 AVCodec *decoder = avcodec_find_decoder(codec_id);
3537 AVCodecContext *avctx = avcodec_alloc_context3(decoder);
3539 eprintf(_("cant allocate codec context\n"));
3540 ret = AVERROR(ENOMEM);
3543 avcodec_parameters_to_context(avctx, st->codecpar);
3544 if( !av_dict_get(copts, "threads", NULL, 0) )
3545 avctx->thread_count = ff_cpus();
3546 ret = avcodec_open2(avctx, decoder, &copts);
3548 av_dict_free(&copts);
3550 AVCodecParameters *avpar = st->codecpar;
3551 switch( avpar->codec_type ) {
3552 case AVMEDIA_TYPE_VIDEO: {
3553 int vidx = ffvideo.size();
3554 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
3555 if( vidx < 0 ) break;
3556 ffvideo[vidx]->avctx = avctx;
3558 case AVMEDIA_TYPE_AUDIO: {
3559 int aidx = ffaudio.size();
3560 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3561 if( aidx < 0 ) break;
3562 ffaudio[aidx]->avctx = avctx;
3567 fprintf(stderr,"FFMPEG::scan: ");
3568 fprintf(stderr,_("codec open failed\n"));
3569 fprintf(stderr,"FFMPEG::scan:file=%s\n", file_base->asset->path);
3570 avcodec_free_context(&avctx);
3574 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
3575 AVStream *st = fmt_ctx->streams[i];
3576 AVCodecParameters *avpar = st->codecpar;
3577 if( avpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
3578 int64_t tstmp = st->start_time;
3579 if( tstmp == AV_NOPTS_VALUE ) continue;
3580 int aidx = ffaudio.size();
3581 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3582 if( aidx < 0 ) continue;
3583 FFAudioStream *aud = ffaudio[aidx];
3584 tstmp -= aud->nudge;
3585 double secs = to_secs(tstmp, st->time_base);
3586 aud->curr_pos = secs * aud->sample_rate + 0.5;
3590 for( int64_t count=0; !*canceled; ++count ) {
3591 av_packet_unref(&pkt);
3592 pkt.data = 0; pkt.size = 0;
3594 int ret = av_read_frame(fmt_ctx, &pkt);
3596 if( ret == AVERROR_EOF ) break;
3597 if( ++errs > 100 ) {
3598 ff_err(ret,_("over 100 read_frame errs\n"));
3603 if( !pkt.data ) continue;
3604 int i = pkt.stream_index;
3605 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
3606 AVStream *st = fmt_ctx->streams[i];
3607 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
3609 AVCodecParameters *avpar = st->codecpar;
3610 switch( avpar->codec_type ) {
3611 case AVMEDIA_TYPE_VIDEO: {
3612 int vidx = ffvideo.size();
3613 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
3614 if( vidx < 0 ) break;
3615 FFVideoStream *vid = ffvideo[vidx];
3616 if( !vid->avctx ) break;
3617 int64_t tstmp = pkt.dts;
3618 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.pts;
3619 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
3620 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
3621 double secs = to_secs(tstmp, st->time_base);
3622 int64_t frm = secs * vid->frame_rate + 0.5;
3623 if( frm < 0 ) frm = 0;
3624 index_state->put_video_mark(vidx, frm, pkt.pos);
3627 ret = avcodec_send_packet(vid->avctx, pkt);
3628 if( ret < 0 ) break;
3629 while( (ret=vid->decode_frame(frame)) > 0 ) {}
3632 case AVMEDIA_TYPE_AUDIO: {
3633 int aidx = ffaudio.size();
3634 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3635 if( aidx < 0 ) break;
3636 FFAudioStream *aud = ffaudio[aidx];
3637 if( !aud->avctx ) break;
3638 int64_t tstmp = pkt.pts;
3639 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
3640 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
3641 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
3642 double secs = to_secs(tstmp, st->time_base);
3643 int64_t sample = secs * aud->sample_rate + 0.5;
3645 index_state->put_audio_mark(aidx, sample, pkt.pos);
3647 ret = avcodec_send_packet(aud->avctx, &pkt);
3648 if( ret < 0 ) break;
3649 int ch = aud->channel0, nch = aud->channels;
3650 int64_t pos = index_state->pos(ch);
3651 if( pos != aud->curr_pos ) {
3652 if( abs(pos-aud->curr_pos) > 1 )
3653 printf("audio%d pad %jd %jd (%jd)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
3654 index_state->pad_data(ch, nch, aud->curr_pos);
3656 while( (ret=aud->decode_frame(frame)) > 0 ) {
3657 //if( frame->channels != nch ) break;
3658 aud->init_swr(frame->channels, frame->format, frame->sample_rate);
3660 int len = aud->get_samples(samples,
3661 &frame->extended_data[0], frame->nb_samples);
3662 pos = aud->curr_pos;
3663 if( (aud->curr_pos += len) >= 0 ) {
3665 samples += -pos * nch;
3666 len = aud->curr_pos;
3668 for( int i=0; i<nch; ++i )
3669 index_state->put_data(ch+i,nch,samples+i,len);
3676 av_frame_free(&frame);
3680 void FFStream::load_markers(IndexMarks &marks, double rate)
3683 int64_t sz = marks.size();
3684 int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
3685 int nb_ent = st->nb_index_entries;
3686 // some formats already have an index
3688 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
3689 int64_t tstmp = ep->timestamp;
3690 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
3691 double secs = ffmpeg->to_secs(tstmp, st->time_base);
3692 int64_t no = secs * rate;
3693 while( in < sz && marks[in].no <= no ) ++in;
3695 int64_t len = sz - in;
3696 int64_t count = max_entries - nb_ent;
3697 if( count > len ) count = len;
3698 for( int i=0; i<count; ++i ) {
3699 int k = in + i * len / count;
3700 int64_t no = marks[k].no, pos = marks[k].pos;
3701 double secs = (double)no / rate;
3702 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
3703 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
3704 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);