12 // work arounds (centos)
15 #define INT64_MAX 9223372036854775807LL
17 #define MAX_RETRY 1000
18 // max pts/curr_pos drift allowed before correction (in seconds)
19 #define AUDIO_PTS_TOLERANCE 0.04
22 #include "bccmodels.h"
25 #include "edlsession.h"
27 #include "fileffmpeg.h"
28 #include "filesystem.h"
30 #include "indexfile.h"
31 #include "interlacemodes.h"
34 #include "mainerror.h"
36 #include "preferences.h"
42 #define av_register_all(s)
43 #define avfilter_register_all(s)
46 #define VIDEO_INBUF_SIZE 0x10000
47 #define AUDIO_INBUF_SIZE 0x10000
48 #define VIDEO_REFILL_THRESH 0
49 #define AUDIO_REFILL_THRESH 0x1000
50 #define AUDIO_MIN_FRAME_SZ 128
52 #define FF_ESTM_TIMES 0x0001
53 #define FF_BAD_TIMES 0x0002
55 Mutex FFMPEG::fflock("FFMPEG::fflock");
57 static void ff_err(int ret, const char *fmt, ...)
62 vsnprintf(msg, sizeof(msg), fmt, ap);
64 char errmsg[BCSTRLEN];
65 av_strerror(ret, errmsg, sizeof(errmsg));
66 fprintf(stderr,_("%s err: %s\n"),msg, errmsg);
72 pkt.data = 0; pkt.size = 0;
74 void FFPacket::finit()
76 av_packet_unref(&pkt);
79 FFrame::FFrame(FFStream *fst)
82 frm = av_frame_alloc();
83 init = fst->init_frame(frm);
91 void FFrame::queue(int64_t pos)
97 void FFrame::dequeue()
102 void FFrame::set_hw_frame(AVFrame *frame)
108 int FFAudioStream::read(float *fp, long len)
116 while( --k >= 0 ) *fp++ = *op++;
117 if( op >= lmt ) op = bfr;
122 void FFAudioStream::realloc(long nsz, int nch, long len)
124 long bsz = nsz * nch;
125 float *np = new float[bsz];
126 inp = np + read(np, len) * nch;
131 delete [] bfr; bfr = np;
134 void FFAudioStream::realloc(long nsz, int nch)
136 if( nsz > sz || this->nch != nch ) {
137 long len = this->nch != nch ? 0 : hpos;
138 if( len > sz ) len = sz;
140 realloc(nsz, nch, len);
144 void FFAudioStream::reserve(long nsz, int nch)
146 long len = (inp - outp) / nch;
148 if( nsz > sz || this->nch != nch ) {
149 if( this->nch != nch ) len = 0;
150 realloc(nsz, nch, len);
153 if( (len*=nch) > 0 && bfr != outp )
154 memmove(bfr, outp, len*sizeof(*bfr));
159 long FFAudioStream::used()
161 long len = inp>=outp ? inp-outp : inp-bfr + lmt-outp;
164 long FFAudioStream::avail()
167 if( in1 >= lmt ) in1 = bfr;
168 long len = outp >= in1 ? outp-in1 : outp-bfr + lmt-in1;
171 void FFAudioStream::reset_history()
175 memset(bfr, 0, lmt-bfr);
178 void FFAudioStream::iseek(int64_t ofs)
180 if( ofs > hpos ) ofs = hpos;
181 if( ofs > sz ) ofs = sz;
182 outp = inp - ofs*nch;
183 if( outp < bfr ) outp += sz*nch;
186 float *FFAudioStream::get_outp(int ofs)
193 int64_t FFAudioStream::put_inp(int ofs)
196 return (inp-outp) / nch;
199 int FFAudioStream::write(const float *fp, long len)
207 while( --k >= 0 ) *ip++ = *fp++;
208 if( ip >= lmt ) ip = bfr;
215 int FFAudioStream::zero(long len)
223 while( --k >= 0 ) *ip++ = 0;
224 if( ip >= lmt ) ip = bfr;
231 // does not advance outp
232 int FFAudioStream::read(double *dp, long len, int ch)
235 float *op = outp + ch;
236 float *lmt1 = lmt + nch-1;
238 int k = (lmt1 - op) / nch;
241 while( --k >= 0 ) { *dp++ = *op; op += nch; }
242 if( op >= lmt ) op -= sz*nch;
247 // load linear buffer, no wrapping allowed, does not advance inp
248 int FFAudioStream::write(const double *dp, long len, int ch)
251 float *ip = inp + ch;
252 while( --n >= 0 ) { *ip = *dp++; ip += nch; }
257 FFStream::FFStream(FFMPEG *ffmpeg, AVStream *st, int fidx)
259 this->ffmpeg = ffmpeg;
262 frm_lock = new Mutex("FFStream::frm_lock");
269 nudge = AV_NOPTS_VALUE;
270 seek_pos = curr_pos = 0;
272 reading = writing = 0;
273 hw_pixfmt = AV_PIX_FMT_NONE;
285 FFStream::~FFStream()
287 if( reading > 0 || writing > 0 ) avcodec_close(avctx);
288 if( avctx ) avcodec_free_context(&avctx);
289 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
290 if( hw_device_ctx ) av_buffer_unref(&hw_device_ctx);
291 if( bsfc ) av_bsf_free(&bsfc);
292 while( frms.first ) frms.remove(frms.first);
293 if( filter_graph ) avfilter_graph_free(&filter_graph);
294 if( frame ) av_frame_free(&frame);
295 if( fframe ) av_frame_free(&fframe);
297 if( stats_fp ) fclose(stats_fp);
298 if( stats_in ) av_freep(&stats_in);
299 delete [] stats_filename;
302 void FFStream::ff_lock(const char *cp)
304 FFMPEG::fflock.lock(cp);
307 void FFStream::ff_unlock()
309 FFMPEG::fflock.unlock();
312 void FFStream::queue(FFrame *frm)
314 frm_lock->lock("FFStream::queue");
318 ffmpeg->mux_lock->unlock();
321 void FFStream::dequeue(FFrame *frm)
323 frm_lock->lock("FFStream::dequeue");
325 frms.remove_pointer(frm);
329 int FFStream::encode_activate()
332 writing = ffmpeg->encode_activate();
336 // this is a global parameter that really should be in the context
337 static AVPixelFormat hw_pix_fmt = AV_PIX_FMT_NONE; // protected by ff_lock
339 // goofy maneuver to attach a hw_format to an av_context
340 #define GET_HW_PIXFMT(fn, fmt) \
341 static AVPixelFormat get_hw_##fn(AVCodecContext *ctx, const enum AVPixelFormat *pix_fmts) { \
344 GET_HW_PIXFMT(vaapi, AV_PIX_FMT_VAAPI)
345 GET_HW_PIXFMT(vdpau, AV_PIX_FMT_VDPAU)
346 GET_HW_PIXFMT(cuda, AV_PIX_FMT_CUDA)
347 GET_HW_PIXFMT(nv12, AV_PIX_FMT_NV12)
349 static enum AVPixelFormat get_hw_format(AVCodecContext *ctx,
350 const enum AVPixelFormat *pix_fmts)
352 for( const enum AVPixelFormat *p=pix_fmts; *p!=AV_PIX_FMT_NONE; ++p ) {
353 if( *p != hw_pix_fmt ) continue;
355 case AV_PIX_FMT_VAAPI: ctx->get_format = get_hw_vaapi; return *p;
356 case AV_PIX_FMT_VDPAU: ctx->get_format = get_hw_vdpau; return *p;
357 case AV_PIX_FMT_CUDA: ctx->get_format = get_hw_cuda; return *p;
358 case AV_PIX_FMT_NV12: ctx->get_format = get_hw_nv12; return *p;
360 fprintf(stderr, "Unknown HW surface format: %s\n",
361 av_get_pix_fmt_name(*p));
365 fprintf(stderr, "Failed to get HW surface format.\n");
366 return hw_pix_fmt = AV_PIX_FMT_NONE;
370 AVHWDeviceType FFStream::decode_hw_activate()
372 return AV_HWDEVICE_TYPE_NONE;
375 int FFStream::decode_hw_format(AVCodec *decoder, AVHWDeviceType type)
380 int FFStream::decode_activate()
382 if( reading < 0 && (reading=ffmpeg->decode_activate()) > 0 ) {
383 ff_lock("FFStream::decode_activate");
385 AVDictionary *copts = 0;
386 av_dict_copy(&copts, ffmpeg->opts, 0);
388 AVHWDeviceType hw_type = decode_hw_activate();
390 // this should be avformat_copy_context(), but no copy avail
391 ret = avformat_open_input(&fmt_ctx,
392 ffmpeg->fmt_ctx->url, ffmpeg->fmt_ctx->iformat, &copts);
394 ret = avformat_find_stream_info(fmt_ctx, 0);
395 st = fmt_ctx->streams[fidx];
398 while( ret >= 0 && st != 0 && !reading ) {
399 AVCodecID codec_id = st->codecpar->codec_id;
400 AVCodec *decoder = 0;
402 if( ffmpeg->opt_video_decoder )
403 decoder = avcodec_find_decoder_by_name(ffmpeg->opt_video_decoder);
405 ffmpeg->video_codec_remaps.update(codec_id, decoder);
407 else if( is_audio() ) {
408 if( ffmpeg->opt_audio_decoder )
409 decoder = avcodec_find_decoder_by_name(ffmpeg->opt_audio_decoder);
411 ffmpeg->audio_codec_remaps.update(codec_id, decoder);
414 decoder = avcodec_find_decoder(codec_id);
415 avctx = avcodec_alloc_context3(decoder);
417 eprintf(_("cant allocate codec context\n"));
418 ret = AVERROR(ENOMEM);
420 if( ret >= 0 && hw_type != AV_HWDEVICE_TYPE_NONE ) {
421 ret = decode_hw_format(decoder, hw_type);
422 if( !ret ) hw_type = AV_HWDEVICE_TYPE_NONE;
425 avcodec_parameters_to_context(avctx, st->codecpar);
426 if( !av_dict_get(copts, "threads", NULL, 0) )
427 avctx->thread_count = ffmpeg->ff_cpus();
428 ret = avcodec_open2(avctx, decoder, &copts);
430 if( ret >= 0 && hw_type != AV_HWDEVICE_TYPE_NONE ) {
436 AVPacket *pkt = (AVPacket*)ipkt;
437 ret = avcodec_send_packet(avctx, pkt);
438 if( ret < 0 || hw_pix_fmt == AV_PIX_FMT_NONE ) {
439 ff_err(ret, "HW device init failed, using SW decode.\nfile:%s\n",
440 ffmpeg->fmt_ctx->url);
441 avcodec_close(avctx);
442 avcodec_free_context(&avctx);
443 av_buffer_unref(&hw_device_ctx);
445 hw_type = AV_HWDEVICE_TYPE_NONE;
446 int flags = AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_ANY;
448 av_seek_frame(fmt_ctx, idx, INT64_MIN, flags);
449 need_packet = 1; flushed = 0;
450 seeked = 1; st_eof(0);
460 eprintf(_("open decoder failed\n"));
463 eprintf(_("can't open input file: %s\n"), ffmpeg->fmt_ctx->url);
464 av_dict_free(&copts);
470 int FFStream::read_packet()
472 av_packet_unref(ipkt);
473 int ret = av_read_frame(fmt_ctx, ipkt);
476 if( ret == AVERROR_EOF ) return 0;
477 ff_err(ret, "FFStream::read_packet: av_read_frame failed\n");
484 int FFStream::decode(AVFrame *frame)
487 int retries = MAX_RETRY;
489 while( ret >= 0 && !flushed && --retries >= 0 ) {
491 if( (ret=read_packet()) < 0 ) break;
492 AVPacket *pkt = ret > 0 ? (AVPacket*)ipkt : 0;
494 if( pkt->stream_index != st->index ) continue;
495 if( !pkt->data || !pkt->size ) continue;
497 if( (ret=avcodec_send_packet(avctx, pkt)) < 0 ) {
498 ff_err(ret, "FFStream::decode: avcodec_send_packet failed.\nfile:%s\n",
499 ffmpeg->fmt_ctx->url);
505 if( (ret=decode_frame(frame)) > 0 ) break;
513 fprintf(stderr, "FFStream::decode: Retry limit\n");
517 fprintf(stderr, "FFStream::decode: failed\n");
521 int FFStream::load_filter(AVFrame *frame)
523 int ret = av_buffersrc_add_frame_flags(buffersrc_ctx, frame, 0);
525 eprintf(_("av_buffersrc_add_frame_flags failed\n"));
529 int FFStream::read_filter(AVFrame *frame)
531 int ret = av_buffersink_get_frame(buffersink_ctx, frame);
533 if( ret == AVERROR(EAGAIN) ) return 0;
534 if( ret == AVERROR_EOF ) { st_eof(1); return -1; }
535 ff_err(ret, "FFStream::read_filter: av_buffersink_get_frame failed\n");
541 int FFStream::read_frame(AVFrame *frame)
543 av_frame_unref(frame);
544 if( !filter_graph || !buffersrc_ctx || !buffersink_ctx )
545 return decode(frame);
546 if( !fframe && !(fframe=av_frame_alloc()) ) {
547 fprintf(stderr, "FFStream::read_frame: av_frame_alloc failed\n");
551 while( !flushed && !(ret=read_filter(frame)) ) {
552 if( (ret=decode(fframe)) < 0 ) break;
553 if( ret > 0 && (ret=load_filter(fframe)) < 0 ) break;
558 int FFStream::write_packet(FFPacket &pkt)
562 av_packet_rescale_ts(pkt, avctx->time_base, st->time_base);
563 pkt->stream_index = st->index;
564 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, pkt);
567 ret = av_bsf_send_packet(bsfc, pkt);
570 if( (ret=av_bsf_receive_packet(bsfc, bs)) < 0 ) {
571 if( ret == AVERROR(EAGAIN) ) return 0;
572 if( ret == AVERROR_EOF ) return -1;
575 av_packet_rescale_ts(bs, avctx->time_base, st->time_base);
576 bs->stream_index = st->index;
577 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, bs);
581 ff_err(ret, "FFStream::write_packet: write packet failed.\nfile:%s\n",
582 ffmpeg->fmt_ctx->url);
586 int FFStream::encode_frame(AVFrame *frame)
588 int pkts = 0, ret = 0;
589 for( int retry=MAX_RETRY; --retry>=0; ) {
591 ret = avcodec_send_frame(avctx, frame);
592 if( !ret && frame ) return pkts;
593 if( ret < 0 && ret != AVERROR(EAGAIN) ) break;
595 ret = avcodec_receive_packet(avctx, opkt);
596 if( !frame && ret == AVERROR_EOF ) return pkts;
598 ret = write_packet(opkt);
601 if( frame && stats_fp ) {
602 ret = write_stats_file();
606 ff_err(ret, "FFStream::encode_frame: encode failed.\nfile: %s\n",
607 ffmpeg->fmt_ctx->url);
611 int FFStream::flush()
615 int ret = encode_frame(0);
616 if( ret >= 0 && stats_fp ) {
617 ret = write_stats_file();
621 ff_err(ret, "FFStream::flush failed\n:file:%s\n",
622 ffmpeg->fmt_ctx->url);
623 return ret >= 0 ? 0 : 1;
627 int FFStream::open_stats_file()
629 stats_fp = fopen(stats_filename,"w");
630 return stats_fp ? 0 : AVERROR(errno);
633 int FFStream::close_stats_file()
636 fclose(stats_fp); stats_fp = 0;
641 int FFStream::read_stats_file()
643 int64_t len = 0; struct stat stats_st;
644 int fd = open(stats_filename, O_RDONLY);
645 int ret = fd >= 0 ? 0: ENOENT;
646 if( !ret && fstat(fd, &stats_st) )
649 len = stats_st.st_size;
650 stats_in = (char *)av_malloc(len+1);
654 if( !ret && read(fd, stats_in, len+1) != len )
658 avctx->stats_in = stats_in;
662 return !ret ? 0 : AVERROR(ret);
665 int FFStream::write_stats_file()
668 if( avctx->stats_out && (ret=strlen(avctx->stats_out)) > 0 ) {
669 int len = fwrite(avctx->stats_out, 1, ret, stats_fp);
671 ff_err(ret = AVERROR(errno), "FFStream::write_stats_file.\n%file:%s\n",
672 ffmpeg->fmt_ctx->url);
677 int FFStream::init_stats_file()
680 if( (pass & 2) && (ret = read_stats_file()) < 0 )
681 ff_err(ret, "stat file read: %s", stats_filename);
682 if( (pass & 1) && (ret=open_stats_file()) < 0 )
683 ff_err(ret, "stat file open: %s", stats_filename);
684 return ret >= 0 ? 0 : ret;
687 int FFStream::seek(int64_t no, double rate)
689 // default ffmpeg native seek
691 int64_t pos = no, pkt_pos = -1;
692 IndexMarks *index_markers = get_markers();
693 if( index_markers && index_markers->size() > 1 ) {
694 IndexMarks &marks = *index_markers;
695 int i = marks.find(pos);
696 int64_t n = i < 0 ? (i=0) : marks[i].no;
697 // if indexed seek point not too far away (<30 secs), use index
698 if( no-n < 30*rate ) {
701 if( i < marks.size() ) pkt_pos = marks[i].pos;
705 if( pos == curr_pos ) return 0;
706 double secs = pos < 0 ? 0. : pos / rate;
707 AVRational time_base = st->time_base;
708 int64_t tstmp = time_base.num > 0 ? secs * time_base.den/time_base.num : 0;
710 if( st->nb_index_entries > 0 ) tstmp = st->index_entries[0].timestamp;
711 else if( st->start_time != AV_NOPTS_VALUE ) tstmp = st->start_time;
712 else if( st->first_dts != AV_NOPTS_VALUE ) tstmp = st->first_dts;
713 else tstmp = INT64_MIN+1;
715 else if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
718 // seek all streams using the default timebase.
719 // this is how ffmpeg and ffplay work. stream seeks are less tested.
720 tstmp = av_rescale_q(tstmp, time_base, AV_TIME_BASE_Q);
724 avcodec_flush_buffers(avctx);
725 avformat_flush(fmt_ctx);
727 int64_t seek = tstmp;
728 int flags = AVSEEK_FLAG_ANY;
729 if( !(fmt_ctx->iformat->flags & AVFMT_NO_BYTE_SEEK) && pkt_pos >= 0 ) {
731 flags = AVSEEK_FLAG_BYTE;
733 int ret = avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, seek, INT64_MAX, flags);
735 // finds the first index frame below the target time
736 int flags = AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_ANY;
737 int ret = av_seek_frame(fmt_ctx, idx, tstmp, flags);
739 int retry = MAX_RETRY;
741 need_packet = 0; flushed = 0;
742 seeked = 1; st_eof(0);
743 // read up to retry packets, limited to npkts in stream, and not pkt.pos past pkt_pos
744 while( --retry >= 0 ) {
745 if( read_packet() <= 0 ) { ret = -1; break; }
746 if( ipkt->stream_index != st->index ) continue;
747 if( !ipkt->data || !ipkt->size ) continue;
748 if( pkt_pos >= 0 && ipkt->pos >= pkt_pos ) break;
749 if( --npkts <= 0 ) break;
750 int64_t pkt_ts = ipkt->dts != AV_NOPTS_VALUE ? ipkt->dts : ipkt->pts;
751 if( pkt_ts == AV_NOPTS_VALUE ) continue;
752 if( pkt_ts >= tstmp ) break;
755 fprintf(stderr,"FFStream::seek: retry limit, pos=%jd tstmp=%jd\n",pos,tstmp);
759 ret = avcodec_send_packet(avctx, ipkt);
761 //some codecs need more than one pkt to resync
762 if( ret == AVERROR_INVALIDDATA ) ret = 0;
764 ff_err(ret, "FFStream::avcodec_send_packet failed.\nseek:%s\n",
765 ffmpeg->fmt_ctx->url);
770 printf("** seek fail %jd, %jd\n", pos, tstmp);
771 seeked = need_packet = 0;
775 //printf("seeked pos = %ld, %ld\n", pos, tstmp);
776 seek_pos = curr_pos = pos;
780 FFAudioStream::FFAudioStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
781 : FFStream(ffmpeg, strm, fidx)
784 channel0 = channels = 0;
787 frame_sz = AUDIO_MIN_FRAME_SZ;
789 resample_context = 0;
790 swr_ichs = swr_ifmt = swr_irate = 0;
799 bfr = new float[bsz];
804 FFAudioStream::~FFAudioStream()
806 if( resample_context ) swr_free(&resample_context);
811 void FFAudioStream::init_swr(int ichs, int ifmt, int irate)
813 if( resample_context ) {
814 if( swr_ichs == ichs && swr_ifmt == ifmt && swr_irate == irate )
816 swr_free(&resample_context);
818 swr_ichs = ichs; swr_ifmt = ifmt; swr_irate = irate;
819 if( ichs == channels && ifmt == AV_SAMPLE_FMT_FLT && irate == sample_rate )
821 uint64_t ilayout = av_get_default_channel_layout(ichs);
822 if( !ilayout ) ilayout = ((uint64_t)1<<ichs) - 1;
823 uint64_t olayout = av_get_default_channel_layout(channels);
824 if( !olayout ) olayout = ((uint64_t)1<<channels) - 1;
825 resample_context = swr_alloc_set_opts(NULL,
826 olayout, AV_SAMPLE_FMT_FLT, sample_rate,
827 ilayout, (AVSampleFormat)ifmt, irate,
829 if( resample_context )
830 swr_init(resample_context);
833 int FFAudioStream::get_samples(float *&samples, uint8_t **data, int len)
835 samples = *(float **)data;
836 if( resample_context ) {
837 if( len > aud_bfr_sz ) {
843 aud_bfr = new float[aud_bfr_sz*channels];
845 int ret = swr_convert(resample_context,
846 (uint8_t**)&aud_bfr, aud_bfr_sz, (const uint8_t**)data, len);
848 ff_err(ret, "FFAudioStream::get_samples: swr_convert failed\n");
857 int FFAudioStream::load_history(uint8_t **data, int len)
860 len = get_samples(samples, data, len);
862 // biggest user bfr since seek + frame
863 realloc(mbsz + len + 1, channels);
869 int FFAudioStream::decode_frame(AVFrame *frame)
871 int first_frame = seeked; seeked = 0;
872 frame->best_effort_timestamp = AV_NOPTS_VALUE;
873 int ret = avcodec_receive_frame(avctx, frame);
875 if( first_frame ) return 0;
876 if( ret == AVERROR(EAGAIN) ) return 0;
877 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
878 ff_err(ret, "FFAudioStream::decode_frame: Could not read audio frame.\nfile:%s\n",
879 ffmpeg->fmt_ctx->url);
882 int64_t pkt_ts = frame->best_effort_timestamp;
883 if( pkt_ts != AV_NOPTS_VALUE ) {
884 double ts = ffmpeg->to_secs(pkt_ts - nudge, st->time_base);
885 double t = (double)curr_pos / sample_rate;
886 // some time_base clocks are very grainy, too grainy for audio (clicks, pops)
887 if( fabs(ts - t) > AUDIO_PTS_TOLERANCE )
888 curr_pos = ts * sample_rate + 0.5;
893 int FFAudioStream::encode_activate()
895 if( writing >= 0 ) return writing;
896 if( !avctx->codec ) return writing = 0;
897 frame_sz = avctx->codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE ?
898 10000 : avctx->frame_size;
899 return FFStream::encode_activate();
902 int64_t FFAudioStream::load_buffer(double ** const sp, int len)
904 reserve(len+1, st->codecpar->channels);
905 for( int ch=0; ch<nch; ++ch )
906 write(sp[ch], len, ch);
910 int FFAudioStream::in_history(int64_t pos)
912 if( pos > curr_pos ) return 0;
914 if( len > sz ) len = sz;
915 if( pos < curr_pos - len ) return 0;
920 int FFAudioStream::init_frame(AVFrame *frame)
922 frame->nb_samples = frame_sz;
923 frame->format = avctx->sample_fmt;
924 frame->channel_layout = avctx->channel_layout;
925 frame->sample_rate = avctx->sample_rate;
926 int ret = av_frame_get_buffer(frame, 0);
928 ff_err(ret, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
932 int FFAudioStream::load(int64_t pos, int len)
934 if( audio_seek(pos) < 0 ) return -1;
935 if( !frame && !(frame=av_frame_alloc()) ) {
936 fprintf(stderr, "FFAudioStream::load: av_frame_alloc failed\n");
939 if( mbsz < len ) mbsz = len;
940 int64_t end_pos = pos + len;
941 int ret = 0, i = len / frame_sz + MAX_RETRY;
942 while( ret>=0 && !flushed && curr_pos<end_pos && --i>=0 ) {
943 ret = read_frame(frame);
944 if( ret > 0 && frame->nb_samples > 0 ) {
945 init_swr(frame->channels, frame->format, frame->sample_rate);
946 load_history(&frame->extended_data[0], frame->nb_samples);
947 curr_pos += frame->nb_samples;
950 if( end_pos > curr_pos ) {
951 zero(end_pos - curr_pos);
954 len = curr_pos - pos;
959 int FFAudioStream::audio_seek(int64_t pos)
961 if( decode_activate() <= 0 ) return -1;
962 if( !st->codecpar ) return -1;
963 if( in_history(pos) ) return 0;
964 if( pos == curr_pos ) return 0;
965 reset_history(); mbsz = 0;
966 // guarentee preload > 1sec samples
967 if( (pos-=sample_rate) < 0 ) pos = 0;
968 if( seek(pos, sample_rate) < 0 ) return -1;
972 int FFAudioStream::encode(double **samples, int len)
974 if( encode_activate() <= 0 ) return -1;
977 int64_t count = samples ? load_buffer(samples, len) : used();
978 int frame_sz1 = samples ? frame_sz-1 : 0;
981 while( ret >= 0 && count > frame_sz1 ) {
982 frm = new FFrame(this);
983 if( (ret=frm->initted()) < 0 ) break;
984 AVFrame *frame = *frm;
985 len = count >= frame_sz ? frame_sz : count;
986 float *bfrp = get_outp(len);
987 ret = swr_convert(resample_context,
988 (uint8_t **)frame->extended_data, len,
989 (const uint8_t **)&bfrp, len);
991 ff_err(ret, "FFAudioStream::encode: swr_convert failed\n");
994 frame->nb_samples = len;
995 frm->queue(curr_pos);
1002 return ret >= 0 ? 0 : 1;
1005 int FFAudioStream::drain()
1010 int FFAudioStream::encode_frame(AVFrame *frame)
1012 return FFStream::encode_frame(frame);
1015 int FFAudioStream::write_packet(FFPacket &pkt)
1017 return FFStream::write_packet(pkt);
1020 void FFAudioStream::load_markers()
1022 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1023 if( !index_state || idx >= index_state->audio_markers.size() ) return;
1024 if( index_state->marker_status == MARKERS_NOTTESTED ) return;
1025 FFStream::load_markers(*index_state->audio_markers[idx], sample_rate);
1028 IndexMarks *FFAudioStream::get_markers()
1030 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1031 if( !index_state || idx >= index_state->audio_markers.size() ) return 0;
1032 return index_state->audio_markers[idx];
1035 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
1036 : FFStream(ffmpeg, strm, fidx),
1037 FFVideoConvert(ffmpeg->ff_prefs())
1045 top_field_first = 0;
1050 FFVideoStream::~FFVideoStream()
1054 AVHWDeviceType FFVideoStream::decode_hw_activate()
1056 AVHWDeviceType type = AV_HWDEVICE_TYPE_NONE;
1057 const char *hw_dev = ffmpeg->opt_hw_dev;
1058 if( !hw_dev ) hw_dev = getenv("CIN_HW_DEV");
1059 if( !hw_dev ) hw_dev = ffmpeg->ff_hw_dev();
1060 if( hw_dev && *hw_dev &&
1061 strcmp("none", hw_dev) && strcmp(_("none"), hw_dev) ) {
1062 type = av_hwdevice_find_type_by_name(hw_dev);
1063 if( type == AV_HWDEVICE_TYPE_NONE ) {
1064 fprintf(stderr, "Device type %s is not supported.\n", hw_dev);
1065 fprintf(stderr, "Available device types:");
1066 while( (type = av_hwdevice_iterate_types(type)) != AV_HWDEVICE_TYPE_NONE )
1067 fprintf(stderr, " %s", av_hwdevice_get_type_name(type));
1068 fprintf(stderr, "\n");
1074 int FFVideoStream::decode_hw_format(AVCodec *decoder, AVHWDeviceType type)
1077 hw_pix_fmt = AV_PIX_FMT_NONE;
1078 for( int i=0; ; ++i ) {
1079 const AVCodecHWConfig *config = avcodec_get_hw_config(decoder, i);
1081 fprintf(stderr, "Decoder %s does not support device type %s.\n",
1082 decoder->name, av_hwdevice_get_type_name(type));
1085 if( (config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX) != 0 &&
1086 config->device_type == type ) {
1087 hw_pix_fmt = config->pix_fmt;
1091 if( hw_pix_fmt >= 0 ) {
1092 hw_pixfmt = hw_pix_fmt;
1093 avctx->get_format = get_hw_format;
1094 ret = av_hwdevice_ctx_create(&hw_device_ctx, type, 0, 0, 0);
1096 avctx->hw_device_ctx = av_buffer_ref(hw_device_ctx);
1100 ff_err(ret, "Failed HW device create.\ndev:%s\n",
1101 av_hwdevice_get_type_name(type));
1106 AVHWDeviceType FFVideoStream::encode_hw_activate(const char *hw_dev)
1108 AVBufferRef *hw_device_ctx = 0;
1109 AVBufferRef *hw_frames_ref = 0;
1110 AVHWDeviceType type = AV_HWDEVICE_TYPE_NONE;
1111 if( strcmp(_("none"), hw_dev) ) {
1112 type = av_hwdevice_find_type_by_name(hw_dev);
1113 if( type != AV_HWDEVICE_TYPE_VAAPI ) {
1114 fprintf(stderr, "currently, only vaapi hw encode is supported\n");
1115 type = AV_HWDEVICE_TYPE_NONE;
1118 if( type != AV_HWDEVICE_TYPE_NONE ) {
1119 int ret = av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_VAAPI, 0, 0, 0);
1121 ff_err(ret, "Failed to create a HW device.\n");
1122 type = AV_HWDEVICE_TYPE_NONE;
1125 if( type != AV_HWDEVICE_TYPE_NONE ) {
1126 hw_frames_ref = av_hwframe_ctx_alloc(hw_device_ctx);
1127 if( !hw_frames_ref ) {
1128 fprintf(stderr, "Failed to create HW frame context.\n");
1129 type = AV_HWDEVICE_TYPE_NONE;
1132 if( type != AV_HWDEVICE_TYPE_NONE ) {
1133 AVHWFramesContext *frames_ctx = (AVHWFramesContext *)(hw_frames_ref->data);
1134 frames_ctx->format = AV_PIX_FMT_VAAPI;
1135 frames_ctx->sw_format = AV_PIX_FMT_NV12;
1136 frames_ctx->width = width;
1137 frames_ctx->height = height;
1138 frames_ctx->initial_pool_size = 0; // 200;
1139 int ret = av_hwframe_ctx_init(hw_frames_ref);
1141 avctx->hw_frames_ctx = av_buffer_ref(hw_frames_ref);
1142 if( !avctx->hw_frames_ctx ) ret = AVERROR(ENOMEM);
1145 ff_err(ret, "Failed to initialize HW frame context.\n");
1146 type = AV_HWDEVICE_TYPE_NONE;
1148 av_buffer_unref(&hw_frames_ref);
1153 int FFVideoStream::encode_hw_write(FFrame *picture)
1156 AVFrame *hw_frm = 0;
1157 switch( avctx->pix_fmt ) {
1158 case AV_PIX_FMT_VAAPI:
1159 hw_frm = av_frame_alloc();
1160 if( !hw_frm ) { ret = AVERROR(ENOMEM); break; }
1161 ret = av_hwframe_get_buffer(avctx->hw_frames_ctx, hw_frm, 0);
1162 if( ret < 0 ) break;
1163 ret = av_hwframe_transfer_data(hw_frm, *picture, 0);
1164 if( ret < 0 ) break;
1165 picture->set_hw_frame(hw_frm);
1170 av_frame_free(&hw_frm);
1171 ff_err(ret, "Error while transferring frame data to GPU.\n");
1175 int FFVideoStream::decode_frame(AVFrame *frame)
1177 int first_frame = seeked; seeked = 0;
1178 int ret = avcodec_receive_frame(avctx, frame);
1180 if( first_frame ) return 0;
1181 if( ret == AVERROR(EAGAIN) ) return 0;
1182 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
1183 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame.\nfile:%s\n,",
1184 ffmpeg->fmt_ctx->url);
1187 int64_t pkt_ts = frame->best_effort_timestamp;
1188 if( pkt_ts != AV_NOPTS_VALUE )
1189 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * frame_rate + 0.5;
1193 int FFVideoStream::load(VFrame *vframe, int64_t pos)
1195 int ret = video_seek(pos);
1196 if( ret < 0 ) return -1;
1197 if( !frame && !(frame=av_frame_alloc()) ) {
1198 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
1201 int i = MAX_RETRY + pos - curr_pos;
1202 while( ret>=0 && !flushed && curr_pos<=pos && --i>=0 ) {
1203 ret = read_frame(frame);
1204 if( ret > 0 ) ++curr_pos;
1206 if( frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0 )
1209 ret = convert_cmodel(vframe, frame);
1211 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
1215 int FFVideoStream::video_seek(int64_t pos)
1217 if( decode_activate() <= 0 ) return -1;
1218 if( !st->codecpar ) return -1;
1219 if( pos == curr_pos-1 && !seeked ) return 0;
1220 // if close enough, just read up to current
1221 int gop = avctx->gop_size;
1222 if( gop < 4 ) gop = 4;
1223 if( gop > 64 ) gop = 64;
1224 int read_limit = curr_pos + 3*gop;
1225 if( pos >= curr_pos && pos <= read_limit ) return 0;
1226 // guarentee preload more than 2*gop frames
1227 if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
1231 int FFVideoStream::init_frame(AVFrame *picture)
1233 switch( avctx->pix_fmt ) {
1234 case AV_PIX_FMT_VAAPI:
1235 picture->format = AV_PIX_FMT_NV12;
1238 picture->format = avctx->pix_fmt;
1241 picture->width = avctx->width;
1242 picture->height = avctx->height;
1243 int ret = av_frame_get_buffer(picture, 32);
1247 int FFVideoStream::encode(VFrame *vframe)
1249 if( encode_activate() <= 0 ) return -1;
1251 FFrame *picture = new FFrame(this);
1252 int ret = picture->initted();
1254 AVFrame *frame = *picture;
1255 frame->pts = curr_pos;
1256 ret = convert_pixfmt(vframe, frame);
1258 if( ret >= 0 && avctx->hw_frames_ctx )
1259 encode_hw_write(picture);
1261 picture->queue(curr_pos);
1265 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
1268 return ret >= 0 ? 0 : 1;
1271 int FFVideoStream::drain()
1276 int FFVideoStream::encode_frame(AVFrame *frame)
1279 frame->interlaced_frame = interlaced;
1280 frame->top_field_first = top_field_first;
1282 if( frame && frame->format == AV_PIX_FMT_VAAPI ) { // ugly
1283 int ret = avcodec_send_frame(avctx, frame);
1284 for( int retry=MAX_RETRY; !ret && --retry>=0; ) {
1285 FFPacket pkt; av_init_packet(pkt);
1286 pkt->data = NULL; pkt->size = 0;
1287 if( (ret=avcodec_receive_packet(avctx, pkt)) < 0 ) {
1288 if( ret == AVERROR(EAGAIN) ) ret = 0; // weird
1291 ret = write_packet(pkt);
1292 pkt->stream_index = 0;
1293 av_packet_unref(pkt);
1296 ff_err(ret, "FFStream::encode_frame: vaapi encode failed.\nfile: %s\n",
1297 ffmpeg->fmt_ctx->url);
1302 return FFStream::encode_frame(frame);
1305 int FFVideoStream::write_packet(FFPacket &pkt)
1307 if( !(ffmpeg->fmt_ctx->oformat->flags & AVFMT_VARIABLE_FPS) )
1309 return FFStream::write_packet(pkt);
1312 AVPixelFormat FFVideoConvert::color_model_to_pix_fmt(int color_model)
1314 switch( color_model ) {
1315 case BC_YUV422: return AV_PIX_FMT_YUYV422;
1316 case BC_RGB888: return AV_PIX_FMT_RGB24;
1317 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
1318 case BC_BGR8888: return AV_PIX_FMT_BGR0;
1319 case BC_BGR888: return AV_PIX_FMT_BGR24;
1320 case BC_ARGB8888: return AV_PIX_FMT_ARGB;
1321 case BC_ABGR8888: return AV_PIX_FMT_ABGR;
1322 case BC_RGB8: return AV_PIX_FMT_RGB8;
1323 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
1324 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
1325 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
1326 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
1327 case BC_RGB565: return AV_PIX_FMT_RGB565;
1328 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
1329 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
1330 case BC_AYUV16161616: return AV_PIX_FMT_AYUV64LE;
1331 case BC_GBRP: return AV_PIX_FMT_GBRP;
1335 return AV_PIX_FMT_NB;
1338 int FFVideoConvert::pix_fmt_to_color_model(AVPixelFormat pix_fmt)
1341 case AV_PIX_FMT_YUYV422: return BC_YUV422;
1342 case AV_PIX_FMT_RGB24: return BC_RGB888;
1343 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
1344 case AV_PIX_FMT_BGR0: return BC_BGR8888;
1345 case AV_PIX_FMT_BGR24: return BC_BGR888;
1346 case AV_PIX_FMT_ARGB: return BC_ARGB8888;
1347 case AV_PIX_FMT_ABGR: return BC_ABGR8888;
1348 case AV_PIX_FMT_RGB8: return BC_RGB8;
1349 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
1350 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
1351 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
1352 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
1353 case AV_PIX_FMT_RGB565: return BC_RGB565;
1354 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
1355 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
1356 case AV_PIX_FMT_AYUV64LE: return BC_AYUV16161616;
1357 case AV_PIX_FMT_GBRP: return BC_GBRP;
1364 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip)
1366 AVFrame *ipic = av_frame_alloc();
1367 int ret = convert_picture_vframe(frame, ip, ipic);
1368 av_frame_free(&ipic);
1372 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip, AVFrame *ipic)
1373 { // picture = vframe
1374 int cmodel = frame->get_color_model();
1375 AVPixelFormat ofmt = color_model_to_pix_fmt(cmodel);
1376 if( ofmt == AV_PIX_FMT_NB ) return -1;
1377 int size = av_image_fill_arrays(ipic->data, ipic->linesize,
1378 frame->get_data(), ofmt, frame->get_w(), frame->get_h(), 1);
1379 if( size < 0 ) return -1;
1381 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1382 int ysz = bpp * frame->get_w(), usz = ysz;
1392 // override av_image_fill_arrays() for planar types
1393 ipic->data[0] = frame->get_y(); ipic->linesize[0] = ysz;
1394 ipic->data[1] = frame->get_u(); ipic->linesize[1] = usz;
1395 ipic->data[2] = frame->get_v(); ipic->linesize[2] = usz;
1398 ipic->data[0] = frame->get_data();
1399 ipic->linesize[0] = frame->get_bytes_per_line();
1403 AVPixelFormat pix_fmt = (AVPixelFormat)ip->format;
1404 FFVideoStream *vid =(FFVideoStream *)this;
1405 if( pix_fmt == vid->hw_pixfmt ) {
1407 if( !sw_frame && !(sw_frame=av_frame_alloc()) )
1408 ret = AVERROR(ENOMEM);
1410 ret = av_hwframe_transfer_data(sw_frame, ip, 0);
1412 pix_fmt = (AVPixelFormat)ip->format;
1415 eprintf(_("Error retrieving data from GPU to CPU\nfile: %s\n"),
1416 vid->ffmpeg->fmt_ctx->url);
1420 convert_ctx = sws_getCachedContext(convert_ctx, ip->width, ip->height, pix_fmt,
1421 frame->get_w(), frame->get_h(), ofmt, SWS_POINT, NULL, NULL, NULL);
1422 if( !convert_ctx ) {
1423 fprintf(stderr, "FFVideoConvert::convert_picture_frame:"
1424 " sws_getCachedContext() failed\n");
1428 int color_range = 0;
1429 switch( preferences->yuv_color_range ) {
1430 case BC_COLORS_JPEG: color_range = 1; break;
1431 case BC_COLORS_MPEG: color_range = 0; break;
1433 int color_space = SWS_CS_ITU601;
1434 switch( preferences->yuv_color_space ) {
1435 case BC_COLORS_BT601: color_space = SWS_CS_ITU601; break;
1436 case BC_COLORS_BT709: color_space = SWS_CS_ITU709; break;
1437 case BC_COLORS_BT2020: color_space = SWS_CS_BT2020; break;
1439 const int *color_table = sws_getCoefficients(color_space);
1441 int *inv_table, *table, src_range, dst_range;
1442 int brightness, contrast, saturation;
1443 if( !sws_getColorspaceDetails(convert_ctx,
1444 &inv_table, &src_range, &table, &dst_range,
1445 &brightness, &contrast, &saturation) ) {
1446 if( src_range != color_range || dst_range != color_range ||
1447 inv_table != color_table || table != color_table )
1448 sws_setColorspaceDetails(convert_ctx,
1449 color_table, color_range, color_table, color_range,
1450 brightness, contrast, saturation);
1453 int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ip->height,
1454 ipic->data, ipic->linesize);
1456 ff_err(ret, "FFVideoConvert::convert_picture_frame: sws_scale() failed\nfile: %s\n",
1457 vid->ffmpeg->fmt_ctx->url);
1463 int FFVideoConvert::convert_cmodel(VFrame *frame, AVFrame *ip)
1465 // try direct transfer
1466 if( !convert_picture_vframe(frame, ip) ) return 1;
1467 // use indirect transfer
1468 AVPixelFormat ifmt = (AVPixelFormat)ip->format;
1469 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
1471 for( int i = 0; i <desc->nb_components; ++i ) {
1472 int bits = desc->comp[i].depth;
1473 if( bits > max_bits ) max_bits = bits;
1475 int imodel = pix_fmt_to_color_model(ifmt);
1476 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1477 int cmodel = frame->get_color_model();
1478 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1479 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1480 imodel = cmodel_is_yuv ?
1481 (BC_CModels::has_alpha(cmodel) ?
1483 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1484 (BC_CModels::has_alpha(cmodel) ?
1485 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1486 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1488 VFrame vframe(ip->width, ip->height, imodel);
1489 if( convert_picture_vframe(&vframe, ip) ) return -1;
1490 frame->transfer_from(&vframe);
1494 int FFVideoConvert::transfer_cmodel(VFrame *frame, AVFrame *ifp)
1496 int ret = convert_cmodel(frame, ifp);
1498 const AVDictionary *src = ifp->metadata;
1499 AVDictionaryEntry *t = NULL;
1500 BC_Hash *hp = frame->get_params();
1502 while( (t=av_dict_get(src, "", t, AV_DICT_IGNORE_SUFFIX)) )
1503 hp->update(t->key, t->value);
1508 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op)
1510 AVFrame *opic = av_frame_alloc();
1511 int ret = convert_vframe_picture(frame, op, opic);
1512 av_frame_free(&opic);
1516 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op, AVFrame *opic)
1517 { // vframe = picture
1518 int cmodel = frame->get_color_model();
1519 AVPixelFormat ifmt = color_model_to_pix_fmt(cmodel);
1520 if( ifmt == AV_PIX_FMT_NB ) return -1;
1521 int size = av_image_fill_arrays(opic->data, opic->linesize,
1522 frame->get_data(), ifmt, frame->get_w(), frame->get_h(), 1);
1523 if( size < 0 ) return -1;
1525 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1526 int ysz = bpp * frame->get_w(), usz = ysz;
1536 // override av_image_fill_arrays() for planar types
1537 opic->data[0] = frame->get_y(); opic->linesize[0] = ysz;
1538 opic->data[1] = frame->get_u(); opic->linesize[1] = usz;
1539 opic->data[2] = frame->get_v(); opic->linesize[2] = usz;
1542 opic->data[0] = frame->get_data();
1543 opic->linesize[0] = frame->get_bytes_per_line();
1547 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1548 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(),
1549 ifmt, op->width, op->height, ofmt, SWS_POINT, NULL, NULL, NULL);
1550 if( !convert_ctx ) {
1551 fprintf(stderr, "FFVideoConvert::convert_frame_picture:"
1552 " sws_getCachedContext() failed\n");
1557 int color_range = 0;
1558 switch( preferences->yuv_color_range ) {
1559 case BC_COLORS_JPEG: color_range = 1; break;
1560 case BC_COLORS_MPEG: color_range = 0; break;
1562 int color_space = SWS_CS_ITU601;
1563 switch( preferences->yuv_color_space ) {
1564 case BC_COLORS_BT601: color_space = SWS_CS_ITU601; break;
1565 case BC_COLORS_BT709: color_space = SWS_CS_ITU709; break;
1566 case BC_COLORS_BT2020: color_space = SWS_CS_BT2020; break;
1568 const int *color_table = sws_getCoefficients(color_space);
1570 int *inv_table, *table, src_range, dst_range;
1571 int brightness, contrast, saturation;
1572 if( !sws_getColorspaceDetails(convert_ctx,
1573 &inv_table, &src_range, &table, &dst_range,
1574 &brightness, &contrast, &saturation) ) {
1575 if( dst_range != color_range || table != color_table )
1576 sws_setColorspaceDetails(convert_ctx,
1577 inv_table, src_range, color_table, color_range,
1578 brightness, contrast, saturation);
1581 int ret = sws_scale(convert_ctx, opic->data, opic->linesize, 0, frame->get_h(),
1582 op->data, op->linesize);
1584 ff_err(ret, "FFVideoConvert::convert_frame_picture: sws_scale() failed\n");
1590 int FFVideoConvert::convert_pixfmt(VFrame *frame, AVFrame *op)
1592 // try direct transfer
1593 if( !convert_vframe_picture(frame, op) ) return 1;
1594 // use indirect transfer
1595 int cmodel = frame->get_color_model();
1596 int max_bits = BC_CModels::calculate_pixelsize(cmodel) * 8;
1597 max_bits /= BC_CModels::components(cmodel);
1598 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1599 int imodel = pix_fmt_to_color_model(ofmt);
1600 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1601 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1602 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1603 imodel = cmodel_is_yuv ?
1604 (BC_CModels::has_alpha(cmodel) ?
1606 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1607 (BC_CModels::has_alpha(cmodel) ?
1608 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1609 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1611 VFrame vframe(frame->get_w(), frame->get_h(), imodel);
1612 vframe.transfer_from(frame);
1613 if( !convert_vframe_picture(&vframe, op) ) return 1;
1617 int FFVideoConvert::transfer_pixfmt(VFrame *frame, AVFrame *ofp)
1619 int ret = convert_pixfmt(frame, ofp);
1621 BC_Hash *hp = frame->get_params();
1622 AVDictionary **dict = &ofp->metadata;
1623 //av_dict_free(dict);
1624 for( int i=0; i<hp->size(); ++i ) {
1625 char *key = hp->get_key(i), *val = hp->get_value(i);
1626 av_dict_set(dict, key, val, 0);
1632 void FFVideoStream::load_markers()
1634 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1635 if( !index_state || idx >= index_state->video_markers.size() ) return;
1636 FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
1639 IndexMarks *FFVideoStream::get_markers()
1641 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1642 if( !index_state || idx >= index_state->video_markers.size() ) return 0;
1643 return !index_state ? 0 : index_state->video_markers[idx];
1647 FFMPEG::FFMPEG(FileBase *file_base)
1650 this->file_base = file_base;
1651 memset(file_format,0,sizeof(file_format));
1652 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
1653 flow_lock = new Condition(1,"FFStream::flow_lock",0);
1656 decoding = encoding = 0;
1657 has_audio = has_video = 0;
1660 opt_video_filter = 0;
1661 opt_audio_filter = 0;
1663 opt_video_decoder = 0;
1664 opt_audio_decoder = 0;
1666 char option_path[BCTEXTLEN];
1667 set_option_path(option_path, "%s", "ffmpeg.opts");
1668 read_options(option_path, opts);
1673 ff_lock("FFMPEG::~FFMPEG()");
1675 ffaudio.remove_all_objects();
1676 ffvideo.remove_all_objects();
1677 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1681 av_dict_free(&opts);
1682 delete [] opt_video_filter;
1683 delete [] opt_audio_filter;
1684 delete [] opt_hw_dev;
1687 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1689 const int *p = codec->supported_samplerates;
1690 if( !p ) return sample_rate;
1692 if( *p == sample_rate ) return *p;
1698 static inline AVRational std_frame_rate(int i)
1700 static const int m1 = 1001*12, m2 = 1000*12;
1701 static const int freqs[] = {
1702 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1703 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
1705 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1706 return (AVRational) { freq, 1001*12 };
1709 AVRational FFMPEG::check_frame_rate(AVCodec *codec, double frame_rate)
1711 const AVRational *p = codec->supported_framerates;
1712 AVRational rate, best_rate = (AVRational) { 0, 0 };
1713 double max_err = 1.; int i = 0;
1714 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1715 double framerate = (double) rate.num / rate.den;
1716 double err = fabs(frame_rate/framerate - 1.);
1717 if( err >= max_err ) continue;
1721 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1724 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1727 double display_aspect = asset->width / (double)asset->height;
1728 double sample_aspect = display_aspect / asset->aspect_ratio;
1729 int width = 1000000, height = width * sample_aspect + 0.5;
1731 MWindow::create_aspect_ratio(w, h, width, height);
1732 return (AVRational){(int)w, (int)h};
1735 return (AVRational){1, 1};
1739 AVRational FFMPEG::to_time_base(int sample_rate)
1741 return (AVRational){1, sample_rate};
1744 int FFMPEG::get_fmt_score(AVSampleFormat dst_fmt, AVSampleFormat src_fmt)
1747 int dst_planar = av_sample_fmt_is_planar(dst_fmt);
1748 int src_planar = av_sample_fmt_is_planar(src_fmt);
1749 if( dst_planar != src_planar ) ++score;
1750 int dst_bytes = av_get_bytes_per_sample(dst_fmt);
1751 int src_bytes = av_get_bytes_per_sample(src_fmt);
1752 score += (src_bytes > dst_bytes ? 100 : -10) * (src_bytes - dst_bytes);
1753 int src_packed = av_get_packed_sample_fmt(src_fmt);
1754 int dst_packed = av_get_packed_sample_fmt(dst_fmt);
1755 if( dst_packed == AV_SAMPLE_FMT_S32 && src_packed == AV_SAMPLE_FMT_FLT ) score += 20;
1756 if( dst_packed == AV_SAMPLE_FMT_FLT && src_packed == AV_SAMPLE_FMT_S32 ) score += 2;
1760 AVSampleFormat FFMPEG::find_best_sample_fmt_of_list(
1761 const AVSampleFormat *sample_fmts, AVSampleFormat src_fmt)
1763 AVSampleFormat best = AV_SAMPLE_FMT_NONE;
1764 int best_score = get_fmt_score(best, src_fmt);
1765 for( int i=0; sample_fmts[i] >= 0; ++i ) {
1766 AVSampleFormat sample_fmt = sample_fmts[i];
1767 int score = get_fmt_score(sample_fmt, src_fmt);
1768 if( score >= best_score ) continue;
1769 best = sample_fmt; best_score = score;
1775 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
1777 char *ep = path + BCTEXTLEN-1;
1778 strncpy(path, File::get_cindat_path(), ep-path);
1779 strncat(path, "/ffmpeg/", ep-path);
1780 path += strlen(path);
1783 path += vsnprintf(path, ep-path, fmt, ap);
1788 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
1793 set_option_path(path, "%s/%s", type, spec);
1796 int FFMPEG::get_format(char *format, const char *path, const char *spec)
1798 char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
1799 get_option_path(option_path, path, spec);
1800 FILE *fp = fopen(option_path,"r");
1803 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1805 line[sizeof(line)-1] = 0;
1806 ret = scan_option_line(line, format, codec);
1812 int FFMPEG::get_codec(char *codec, const char *path, const char *spec)
1814 char option_path[BCTEXTLEN], line[BCTEXTLEN], format[BCTEXTLEN];
1815 get_option_path(option_path, path, spec);
1816 FILE *fp = fopen(option_path,"r");
1819 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1822 line[sizeof(line)-1] = 0;
1823 ret = scan_option_line(line, format, codec);
1826 char *vp = codec, *ep = vp+BCTEXTLEN-1;
1827 while( vp < ep && *vp && *vp != '|' ) ++vp;
1828 if( *vp == '|' ) --vp;
1829 while( vp > codec && (*vp==' ' || *vp=='\t') ) *vp-- = 0;
1834 int FFMPEG::get_file_format()
1836 char audio_muxer[BCSTRLEN], video_muxer[BCSTRLEN];
1837 char audio_format[BCSTRLEN], video_format[BCSTRLEN];
1838 audio_muxer[0] = audio_format[0] = 0;
1839 video_muxer[0] = video_format[0] = 0;
1840 Asset *asset = file_base->asset;
1841 int ret = asset ? 0 : 1;
1842 if( !ret && asset->audio_data ) {
1843 if( !(ret=get_format(audio_format, "audio", asset->acodec)) ) {
1844 if( get_format(audio_muxer, "format", audio_format) ) {
1845 strcpy(audio_muxer, audio_format);
1846 audio_format[0] = 0;
1850 if( !ret && asset->video_data ) {
1851 if( !(ret=get_format(video_format, "video", asset->vcodec)) ) {
1852 if( get_format(video_muxer, "format", video_format) ) {
1853 strcpy(video_muxer, video_format);
1854 video_format[0] = 0;
1858 if( !ret && !audio_muxer[0] && !video_muxer[0] )
1860 if( !ret && audio_muxer[0] && video_muxer[0] &&
1861 strcmp(audio_muxer, video_muxer) ) ret = -1;
1862 if( !ret && audio_format[0] && video_format[0] &&
1863 strcmp(audio_format, video_format) ) ret = -1;
1865 strcpy(file_format, !audio_format[0] && !video_format[0] ?
1866 (audio_muxer[0] ? audio_muxer : video_muxer) :
1867 (audio_format[0] ? audio_format : video_format));
1871 int FFMPEG::scan_option_line(const char *cp, char *tag, char *val)
1873 while( *cp == ' ' || *cp == '\t' ) ++cp;
1874 const char *bp = cp;
1875 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' && *cp != '\n' ) ++cp;
1877 if( !len || len > BCSTRLEN-1 ) return 1;
1878 while( bp < cp ) *tag++ = *bp++;
1880 while( *cp == ' ' || *cp == '\t' ) ++cp;
1881 if( *cp == '=' ) ++cp;
1882 while( *cp == ' ' || *cp == '\t' ) ++cp;
1884 while( *cp && *cp != '\n' ) ++cp;
1886 if( len > BCTEXTLEN-1 ) return 1;
1887 while( bp < cp ) *val++ = *bp++;
1892 int FFMPEG::can_render(const char *fformat, const char *type)
1895 char option_path[BCTEXTLEN];
1896 FFMPEG::set_option_path(option_path, type);
1897 fs.update(option_path);
1898 int total_files = fs.total_files();
1899 for( int i=0; i<total_files; ++i ) {
1900 const char *name = fs.get_entry(i)->get_name();
1901 const char *ext = strrchr(name,'.');
1902 if( !ext ) continue;
1903 if( !strcmp(fformat, ++ext) ) return 1;
1908 int FFMPEG::get_ff_option(const char *nm, const char *options, char *value)
1910 for( const char *cp=options; *cp!=0; ) {
1911 char line[BCTEXTLEN], *bp = line, *ep = bp+sizeof(line)-1;
1912 while( bp < ep && *cp && *cp!='\n' ) *bp++ = *cp++;
1915 if( !line[0] || line[0] == '#' || line[0] == ';' ) continue;
1916 char key[BCSTRLEN], val[BCTEXTLEN];
1917 if( FFMPEG::scan_option_line(line, key, val) ) continue;
1918 if( !strcmp(key, nm) ) {
1919 strncpy(value, val, BCSTRLEN);
1926 void FFMPEG::scan_audio_options(Asset *asset, EDL *edl)
1928 char cin_sample_fmt[BCSTRLEN];
1929 int cin_fmt = AV_SAMPLE_FMT_NONE;
1930 const char *options = asset->ff_audio_options;
1931 if( !get_ff_option("cin_sample_fmt", options, cin_sample_fmt) )
1932 cin_fmt = (int)av_get_sample_fmt(cin_sample_fmt);
1934 char audio_codec[BCSTRLEN]; audio_codec[0] = 0;
1935 AVCodec *av_codec = !FFMPEG::get_codec(audio_codec, "audio", asset->acodec) ?
1936 avcodec_find_encoder_by_name(audio_codec) : 0;
1937 if( av_codec && av_codec->sample_fmts )
1938 cin_fmt = find_best_sample_fmt_of_list(av_codec->sample_fmts, AV_SAMPLE_FMT_FLT);
1940 if( cin_fmt < 0 ) cin_fmt = AV_SAMPLE_FMT_S16;
1941 const char *name = av_get_sample_fmt_name((AVSampleFormat)cin_fmt);
1942 if( !name ) name = _("None");
1943 strcpy(asset->ff_sample_format, name);
1945 char value[BCSTRLEN];
1946 if( !get_ff_option("cin_bitrate", options, value) )
1947 asset->ff_audio_bitrate = atoi(value);
1948 if( !get_ff_option("cin_quality", options, value) )
1949 asset->ff_audio_quality = atoi(value);
1952 void FFMPEG::load_audio_options(Asset *asset, EDL *edl)
1954 char options_path[BCTEXTLEN];
1955 set_option_path(options_path, "audio/%s", asset->acodec);
1956 if( !load_options(options_path,
1957 asset->ff_audio_options,
1958 sizeof(asset->ff_audio_options)) )
1959 scan_audio_options(asset, edl);
1962 void FFMPEG::scan_video_options(Asset *asset, EDL *edl)
1964 char cin_pix_fmt[BCSTRLEN];
1965 int cin_fmt = AV_PIX_FMT_NONE;
1966 const char *options = asset->ff_video_options;
1967 if( !get_ff_option("cin_pix_fmt", options, cin_pix_fmt) )
1968 cin_fmt = (int)av_get_pix_fmt(cin_pix_fmt);
1970 char video_codec[BCSTRLEN]; video_codec[0] = 0;
1971 AVCodec *av_codec = !get_codec(video_codec, "video", asset->vcodec) ?
1972 avcodec_find_encoder_by_name(video_codec) : 0;
1973 if( av_codec && av_codec->pix_fmts ) {
1974 if( 0 && edl ) { // frequently picks a bad answer
1975 int color_model = edl->session->color_model;
1976 int max_bits = BC_CModels::calculate_pixelsize(color_model) * 8;
1977 max_bits /= BC_CModels::components(color_model);
1978 cin_fmt = avcodec_find_best_pix_fmt_of_list(av_codec->pix_fmts,
1979 (BC_CModels::is_yuv(color_model) ?
1980 (max_bits > 8 ? AV_PIX_FMT_AYUV64LE : AV_PIX_FMT_YUV444P) :
1981 (max_bits > 8 ? AV_PIX_FMT_RGB48LE : AV_PIX_FMT_RGB24)), 0, 0);
1984 cin_fmt = av_codec->pix_fmts[0];
1987 if( cin_fmt < 0 ) cin_fmt = AV_PIX_FMT_YUV420P;
1988 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get((AVPixelFormat)cin_fmt);
1989 const char *name = desc ? desc->name : _("None");
1990 strcpy(asset->ff_pixel_format, name);
1992 char value[BCSTRLEN];
1993 if( !get_ff_option("cin_bitrate", options, value) )
1994 asset->ff_video_bitrate = atoi(value);
1995 if( !get_ff_option("cin_quality", options, value) )
1996 asset->ff_video_quality = atoi(value);
1999 void FFMPEG::load_video_options(Asset *asset, EDL *edl)
2001 char options_path[BCTEXTLEN];
2002 set_option_path(options_path, "video/%s", asset->vcodec);
2003 if( !load_options(options_path,
2004 asset->ff_video_options,
2005 sizeof(asset->ff_video_options)) )
2006 scan_video_options(asset, edl);
2009 void FFMPEG::scan_format_options(Asset *asset, EDL *edl)
2013 void FFMPEG::load_format_options(Asset *asset, EDL *edl)
2015 char options_path[BCTEXTLEN];
2016 set_option_path(options_path, "format/%s", asset->fformat);
2017 if( !load_options(options_path,
2018 asset->ff_format_options,
2019 sizeof(asset->ff_format_options)) )
2020 scan_format_options(asset, edl);
2023 int FFMPEG::load_defaults(const char *path, const char *type,
2024 char *codec, char *codec_options, int len)
2026 char default_file[BCTEXTLEN];
2027 set_option_path(default_file, "%s/%s.dfl", path, type);
2028 FILE *fp = fopen(default_file,"r");
2030 fgets(codec, BCSTRLEN, fp);
2032 while( *cp && *cp!='\n' ) ++cp;
2034 while( len > 0 && fgets(codec_options, len, fp) ) {
2035 int n = strlen(codec_options);
2036 codec_options += n; len -= n;
2039 set_option_path(default_file, "%s/%s", path, codec);
2040 return load_options(default_file, codec_options, len);
2043 void FFMPEG::set_asset_format(Asset *asset, EDL *edl, const char *text)
2045 if( asset->format != FILE_FFMPEG ) return;
2046 if( text != asset->fformat )
2047 strcpy(asset->fformat, text);
2048 if( !asset->ff_format_options[0] )
2049 load_format_options(asset, edl);
2050 if( asset->audio_data && !asset->ff_audio_options[0] ) {
2051 if( !load_defaults("audio", text, asset->acodec,
2052 asset->ff_audio_options, sizeof(asset->ff_audio_options)) )
2053 scan_audio_options(asset, edl);
2055 asset->audio_data = 0;
2057 if( asset->video_data && !asset->ff_video_options[0] ) {
2058 if( !load_defaults("video", text, asset->vcodec,
2059 asset->ff_video_options, sizeof(asset->ff_video_options)) )
2060 scan_video_options(asset, edl);
2062 asset->video_data = 0;
2066 int FFMPEG::get_encoder(const char *options,
2067 char *format, char *codec, char *bsfilter)
2069 FILE *fp = fopen(options,"r");
2071 eprintf(_("options open failed %s\n"),options);
2074 char line[BCTEXTLEN];
2075 if( !fgets(line, sizeof(line), fp) ||
2076 scan_encoder(line, format, codec, bsfilter) )
2077 eprintf(_("format/codec not found %s\n"), options);
2082 int FFMPEG::scan_encoder(const char *line,
2083 char *format, char *codec, char *bsfilter)
2085 format[0] = codec[0] = bsfilter[0] = 0;
2086 if( scan_option_line(line, format, codec) ) return 1;
2088 while( *cp && *cp != '|' ) ++cp;
2089 if( !*cp ) return 0;
2091 do { *bp-- = 0; } while( bp>=codec && (*bp==' ' || *bp == '\t' ) );
2092 while( *++cp && (*cp==' ' || *cp == '\t') );
2094 for( int i=BCTEXTLEN; --i>0 && *cp; ) *bp++ = *cp++;
2099 int FFMPEG::read_options(const char *options, AVDictionary *&opts, int skip)
2101 FILE *fp = fopen(options,"r");
2104 while( !ret && --skip >= 0 ) {
2106 while( ch >= 0 && ch != '\n' ) ch = getc(fp);
2107 if( ch < 0 ) ret = 1;
2110 ret = read_options(fp, options, opts);
2115 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
2117 FILE *fp = fmemopen((void *)options,strlen(options),"r");
2119 int ret = read_options(fp, options, opts);
2122 AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
2123 if( tag ) st->id = strtol(tag->value,0,0);
2128 FFCodecRemap::FFCodecRemap()
2133 FFCodecRemap::~FFCodecRemap()
2135 delete [] old_codec;
2136 delete [] new_codec;
2139 int FFCodecRemaps::add(const char *val)
2141 char old_codec[BCSTRLEN], new_codec[BCSTRLEN];
2142 if( sscanf(val, " %63[a-zA-z0-9_-] = %63[a-z0-9_-]",
2143 &old_codec[0], &new_codec[0]) != 2 ) return 1;
2144 FFCodecRemap &remap = append();
2145 remap.old_codec = cstrdup(old_codec);
2146 remap.new_codec = cstrdup(new_codec);
2151 int FFCodecRemaps::update(AVCodecID &codec_id, AVCodec *&decoder)
2153 AVCodec *codec = avcodec_find_decoder(codec_id);
2154 if( !codec ) return -1;
2155 const char *name = codec->name;
2156 FFCodecRemaps &map = *this;
2158 while( --k >= 0 && strcmp(map[k].old_codec, name) );
2159 if( k < 0 ) return 1;
2160 const char *new_codec = map[k].new_codec;
2161 codec = avcodec_find_decoder_by_name(new_codec);
2162 if( !codec ) return -1;
2167 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
2169 int ret = 0, no = 0;
2170 char line[BCTEXTLEN];
2171 while( !ret && fgets(line, sizeof(line), fp) ) {
2172 line[sizeof(line)-1] = 0;
2173 if( line[0] == '#' ) continue;
2174 if( line[0] == '\n' ) continue;
2175 char key[BCSTRLEN], val[BCTEXTLEN];
2176 if( scan_option_line(line, key, val) ) {
2177 eprintf(_("err reading %s: line %d\n"), options, no);
2181 if( !strcmp(key, "duration") )
2182 opt_duration = strtod(val, 0);
2183 else if( !strcmp(key, "video_decoder") )
2184 opt_video_decoder = cstrdup(val);
2185 else if( !strcmp(key, "audio_decoder") )
2186 opt_audio_decoder = cstrdup(val);
2187 else if( !strcmp(key, "remap_video_decoder") )
2188 video_codec_remaps.add(val);
2189 else if( !strcmp(key, "remap_audio_decoder") )
2190 audio_codec_remaps.add(val);
2191 else if( !strcmp(key, "video_filter") )
2192 opt_video_filter = cstrdup(val);
2193 else if( !strcmp(key, "audio_filter") )
2194 opt_audio_filter = cstrdup(val);
2195 else if( !strcmp(key, "cin_hw_dev") )
2196 opt_hw_dev = cstrdup(val);
2197 else if( !strcmp(key, "loglevel") )
2200 av_dict_set(&opts, key, val, 0);
2206 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
2208 char option_path[BCTEXTLEN];
2209 set_option_path(option_path, "%s", options);
2210 return read_options(option_path, opts);
2213 int FFMPEG::load_options(const char *path, char *bfr, int len)
2216 FILE *fp = fopen(path, "r");
2218 fgets(bfr, len, fp); // skip hdr
2219 len = fread(bfr, 1, len-1, fp);
2220 if( len < 0 ) len = 0;
2226 void FFMPEG::set_loglevel(const char *ap)
2228 if( !ap || !*ap ) return;
2233 { "quiet" , AV_LOG_QUIET },
2234 { "panic" , AV_LOG_PANIC },
2235 { "fatal" , AV_LOG_FATAL },
2236 { "error" , AV_LOG_ERROR },
2237 { "warning", AV_LOG_WARNING },
2238 { "info" , AV_LOG_INFO },
2239 { "verbose", AV_LOG_VERBOSE },
2240 { "debug" , AV_LOG_DEBUG },
2242 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
2243 if( !strcmp(log_levels[i].name, ap) ) {
2244 av_log_set_level(log_levels[i].level);
2248 av_log_set_level(atoi(ap));
2251 double FFMPEG::to_secs(int64_t time, AVRational time_base)
2253 double base_time = time == AV_NOPTS_VALUE ? 0 :
2254 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
2255 return base_time / AV_TIME_BASE;
2258 int FFMPEG::info(char *text, int len)
2260 if( len <= 0 ) return 0;
2262 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
2264 report("format: %s\n",fmt_ctx->iformat->name);
2265 if( ffvideo.size() > 0 )
2266 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
2267 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
2268 const char *unkn = _("(unkn)");
2269 FFVideoStream *vid = ffvideo[vidx];
2270 AVStream *st = vid->st;
2271 AVCodecID codec_id = st->codecpar->codec_id;
2272 report(_("vid%d (%d), id 0x%06x:\n"), vid->idx, vid->fidx, codec_id);
2273 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
2274 report(" video%d %s ", vidx+1, desc ? desc->name : unkn);
2275 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
2276 AVPixelFormat pix_fmt = (AVPixelFormat)st->codecpar->format;
2277 const char *pfn = av_get_pix_fmt_name(pix_fmt);
2278 report(" pix %s\n", pfn ? pfn : unkn);
2279 enum AVColorSpace space = st->codecpar->color_space;
2280 const char *nm = av_color_space_name(space);
2281 report(" color space:%s", nm ? nm : unkn);
2282 enum AVColorRange range = st->codecpar->color_range;
2283 const char *rg = av_color_range_name(range);
2284 report("/ range:%s\n", rg ? rg : unkn);
2285 double secs = to_secs(st->duration, st->time_base);
2286 int64_t length = secs * vid->frame_rate + 0.5;
2287 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
2288 int64_t nudge = ofs * vid->frame_rate;
2289 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
2290 report(" %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
2291 int hrs = secs/3600; secs -= hrs*3600;
2292 int mins = secs/60; secs -= mins*60;
2293 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
2295 if( ffaudio.size() > 0 )
2296 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
2297 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2298 FFAudioStream *aud = ffaudio[aidx];
2299 AVStream *st = aud->st;
2300 AVCodecID codec_id = st->codecpar->codec_id;
2301 report(_("aud%d (%d), id 0x%06x:\n"), aud->idx, aud->fidx, codec_id);
2302 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
2303 int nch = aud->channels, ch0 = aud->channel0+1;
2304 report(" audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
2305 AVSampleFormat sample_fmt = (AVSampleFormat)st->codecpar->format;
2306 const char *fmt = av_get_sample_fmt_name(sample_fmt);
2307 report(" %s %d", fmt, aud->sample_rate);
2308 int sample_bits = av_get_bits_per_sample(codec_id);
2309 report(" %dbits\n", sample_bits);
2310 double secs = to_secs(st->duration, st->time_base);
2311 int64_t length = secs * aud->sample_rate + 0.5;
2312 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
2313 int64_t nudge = ofs * aud->sample_rate;
2314 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
2315 report(" %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
2316 int hrs = secs/3600; secs -= hrs*3600;
2317 int mins = secs/60; secs -= mins*60;
2318 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
2320 if( fmt_ctx->nb_programs > 0 )
2321 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
2322 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
2323 report("program %d", i+1);
2324 AVProgram *pgrm = fmt_ctx->programs[i];
2325 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2326 int idx = pgrm->stream_index[j];
2327 int vidx = ffvideo.size();
2328 while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
2330 report(", vid%d", vidx);
2333 int aidx = ffaudio.size();
2334 while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
2336 report(", aud%d", aidx);
2339 report(", (%d)", pgrm->stream_index[j]);
2344 AVDictionaryEntry *tag = 0;
2345 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
2346 report("%s=%s\n", tag->key, tag->value);
2355 int FFMPEG::init_decoder(const char *filename)
2357 ff_lock("FFMPEG::init_decoder");
2359 char file_opts[BCTEXTLEN];
2360 strcpy(file_opts, filename);
2361 char *bp = strrchr(file_opts, '/');
2362 if( !bp ) bp = file_opts;
2363 char *sp = strrchr(bp, '.');
2364 if( !sp ) sp = bp + strlen(bp);
2366 AVInputFormat *ifmt = 0;
2368 strcpy(sp, ".opts");
2369 fp = fopen(file_opts, "r");
2372 read_options(fp, file_opts, opts);
2374 AVDictionaryEntry *tag;
2375 if( (tag=av_dict_get(opts, "format", NULL, 0)) != 0 ) {
2376 ifmt = av_find_input_format(tag->value);
2380 load_options("decode.opts", opts);
2381 AVDictionary *fopts = 0;
2382 av_dict_copy(&fopts, opts, 0);
2383 int ret = avformat_open_input(&fmt_ctx, filename, ifmt, &fopts);
2384 av_dict_free(&fopts);
2386 ret = avformat_find_stream_info(fmt_ctx, NULL);
2391 return !ret ? 0 : 1;
2394 int FFMPEG::open_decoder()
2397 if( stat(fmt_ctx->url, &st) < 0 ) {
2398 eprintf(_("can't stat file: %s\n"), fmt_ctx->url);
2402 int64_t file_bits = 8 * st.st_size;
2403 if( !fmt_ctx->bit_rate && opt_duration > 0 )
2404 fmt_ctx->bit_rate = file_bits / opt_duration;
2407 if( fmt_ctx->bit_rate > 0 ) {
2408 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2409 AVStream *st = fmt_ctx->streams[i];
2410 if( st->duration != AV_NOPTS_VALUE ) continue;
2411 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
2412 st->duration = av_rescale(file_bits, st->time_base.den,
2413 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
2417 if( estimated && !(fflags & FF_ESTM_TIMES) ) {
2418 fflags |= FF_ESTM_TIMES;
2419 printf("FFMPEG::open_decoder: some stream times estimated: %s\n",
2423 ff_lock("FFMPEG::open_decoder");
2424 int ret = 0, bad_time = 0;
2425 for( int i=0; !ret && i<(int)fmt_ctx->nb_streams; ++i ) {
2426 AVStream *st = fmt_ctx->streams[i];
2427 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
2428 AVCodecParameters *avpar = st->codecpar;
2429 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avpar->codec_id);
2430 if( !codec_desc ) continue;
2431 switch( avpar->codec_type ) {
2432 case AVMEDIA_TYPE_VIDEO: {
2433 if( avpar->width < 1 ) continue;
2434 if( avpar->height < 1 ) continue;
2435 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
2436 if( framerate.num < 1 ) continue;
2438 int vidx = ffvideo.size();
2439 FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
2440 vstrm_index.append(ffidx(vidx, 0));
2441 ffvideo.append(vid);
2442 vid->width = avpar->width;
2443 vid->height = avpar->height;
2444 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
2445 switch( avpar->color_range ) {
2446 case AVCOL_RANGE_MPEG:
2447 vid->color_range = BC_COLORS_MPEG;
2449 case AVCOL_RANGE_JPEG:
2450 vid->color_range = BC_COLORS_JPEG;
2453 vid->color_range = !file_base ? BC_COLORS_JPEG :
2454 file_base->file->preferences->yuv_color_range;
2457 switch( avpar->color_space ) {
2458 case AVCOL_SPC_BT470BG:
2459 case AVCOL_SPC_SMPTE170M:
2460 vid->color_space = BC_COLORS_BT601;
2462 case AVCOL_SPC_BT709:
2463 vid->color_space = BC_COLORS_BT709;
2465 case AVCOL_SPC_BT2020_NCL:
2466 case AVCOL_SPC_BT2020_CL:
2467 vid->color_space = BC_COLORS_BT2020;
2470 vid->color_space = !file_base ? BC_COLORS_BT601 :
2471 file_base->file->preferences->yuv_color_space;
2474 double secs = to_secs(st->duration, st->time_base);
2475 vid->length = secs * vid->frame_rate;
2476 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
2477 vid->nudge = st->start_time;
2479 if( opt_video_filter )
2480 ret = vid->create_filter(opt_video_filter, avpar);
2482 case AVMEDIA_TYPE_AUDIO: {
2483 if( avpar->channels < 1 ) continue;
2484 if( avpar->sample_rate < 1 ) continue;
2486 int aidx = ffaudio.size();
2487 FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
2488 ffaudio.append(aud);
2489 aud->channel0 = astrm_index.size();
2490 aud->channels = avpar->channels;
2491 for( int ch=0; ch<aud->channels; ++ch )
2492 astrm_index.append(ffidx(aidx, ch));
2493 aud->sample_rate = avpar->sample_rate;
2494 double secs = to_secs(st->duration, st->time_base);
2495 aud->length = secs * aud->sample_rate;
2496 aud->init_swr(aud->channels, avpar->format, aud->sample_rate);
2497 aud->nudge = st->start_time;
2499 if( opt_audio_filter )
2500 ret = aud->create_filter(opt_audio_filter, avpar);
2505 if( bad_time && !(fflags & FF_BAD_TIMES) ) {
2506 fflags |= FF_BAD_TIMES;
2507 printf(_("FFMPEG::open_decoder: some stream have bad times: %s\n"),
2511 return ret < 0 ? -1 : 0;
2515 int FFMPEG::init_encoder(const char *filename)
2517 // try access first for named pipes
2518 int ret = access(filename, W_OK);
2520 int fd = ::open(filename,O_WRONLY);
2521 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
2522 if( fd >= 0 ) { close(fd); ret = 0; }
2525 eprintf(_("bad file path: %s\n"), filename);
2528 ret = get_file_format();
2530 eprintf(_("bad file format: %s\n"), filename);
2534 eprintf(_("mismatch audio/video file format: %s\n"), filename);
2537 ff_lock("FFMPEG::init_encoder");
2539 char format[BCSTRLEN];
2540 if( get_format(format, "format", file_format) )
2541 strcpy(format, file_format);
2542 avformat_alloc_output_context2(&fmt_ctx, 0, format, filename);
2544 eprintf(_("failed: %s\n"), filename);
2549 load_options("encode.opts", opts);
2555 int FFMPEG::open_encoder(const char *type, const char *spec)
2558 Asset *asset = file_base->asset;
2559 char *filename = asset->path;
2560 AVDictionary *sopts = 0;
2561 av_dict_copy(&sopts, opts, 0);
2562 char option_path[BCTEXTLEN];
2563 set_option_path(option_path, "%s/%s.opts", type, type);
2564 read_options(option_path, sopts);
2565 get_option_path(option_path, type, spec);
2566 char format_name[BCSTRLEN], codec_name[BCTEXTLEN], bsfilter[BCTEXTLEN];
2567 if( get_encoder(option_path, format_name, codec_name, bsfilter) ) {
2568 eprintf(_("get_encoder failed %s:%s\n"), option_path, filename);
2573 if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
2575 else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
2576 else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
2579 ff_lock("FFMPEG::open_encoder");
2582 AVCodecContext *ctx = 0;
2584 const AVCodecDescriptor *codec_desc = 0;
2585 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
2587 eprintf(_("cant find codec %s:%s\n"), codec_name, filename);
2591 codec_desc = avcodec_descriptor_get(codec->id);
2593 eprintf(_("unknown codec %s:%s\n"), codec_name, filename);
2598 st = avformat_new_stream(fmt_ctx, 0);
2600 eprintf(_("cant create stream %s:%s\n"), codec_name, filename);
2605 switch( codec_desc->type ) {
2606 case AVMEDIA_TYPE_AUDIO: {
2608 eprintf(_("duplicate audio %s:%s\n"), codec_name, filename);
2612 if( scan_options(asset->ff_audio_options, sopts, st) ) {
2613 eprintf(_("bad audio options %s:%s\n"), codec_name, filename);
2618 ctx = avcodec_alloc_context3(codec);
2619 if( asset->ff_audio_bitrate > 0 ) {
2620 ctx->bit_rate = asset->ff_audio_bitrate;
2622 sprintf(arg, "%d", asset->ff_audio_bitrate);
2623 av_dict_set(&sopts, "b", arg, 0);
2625 else if( asset->ff_audio_quality >= 0 ) {
2626 ctx->global_quality = asset->ff_audio_quality * FF_QP2LAMBDA;
2627 ctx->qmin = ctx->qmax = asset->ff_audio_quality;
2628 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2629 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2630 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2632 av_dict_set(&sopts, "flags", "+qscale", 0);
2633 sprintf(arg, "%d", asset->ff_audio_quality);
2634 av_dict_set(&sopts, "qscale", arg, 0);
2635 sprintf(arg, "%d", ctx->global_quality);
2636 av_dict_set(&sopts, "global_quality", arg, 0);
2638 int aidx = ffaudio.size();
2639 int fidx = aidx + ffvideo.size();
2640 FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
2641 aud->avctx = ctx; ffaudio.append(aud); fst = aud;
2642 aud->sample_rate = asset->sample_rate;
2643 ctx->channels = aud->channels = asset->channels;
2644 for( int ch=0; ch<aud->channels; ++ch )
2645 astrm_index.append(ffidx(aidx, ch));
2646 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
2647 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
2648 if( !ctx->sample_rate ) {
2649 eprintf(_("check_sample_rate failed %s\n"), filename);
2653 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
2654 AVSampleFormat sample_fmt = av_get_sample_fmt(asset->ff_sample_format);
2655 if( sample_fmt == AV_SAMPLE_FMT_NONE )
2656 sample_fmt = codec->sample_fmts ? codec->sample_fmts[0] : AV_SAMPLE_FMT_S16;
2657 ctx->sample_fmt = sample_fmt;
2658 uint64_t layout = av_get_default_channel_layout(ctx->channels);
2659 aud->resample_context = swr_alloc_set_opts(NULL,
2660 layout, ctx->sample_fmt, aud->sample_rate,
2661 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
2663 swr_init(aud->resample_context);
2666 case AVMEDIA_TYPE_VIDEO: {
2668 eprintf(_("duplicate video %s:%s\n"), codec_name, filename);
2672 if( scan_options(asset->ff_video_options, sopts, st) ) {
2673 eprintf(_("bad video options %s:%s\n"), codec_name, filename);
2678 ctx = avcodec_alloc_context3(codec);
2679 if( asset->ff_video_bitrate > 0 ) {
2680 ctx->bit_rate = asset->ff_video_bitrate;
2682 sprintf(arg, "%d", asset->ff_video_bitrate);
2683 av_dict_set(&sopts, "b", arg, 0);
2685 else if( asset->ff_video_quality >= 0 ) {
2686 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
2687 ctx->qmin = ctx->qmax = asset->ff_video_quality;
2688 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2689 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2690 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2692 av_dict_set(&sopts, "flags", "+qscale", 0);
2693 sprintf(arg, "%d", asset->ff_video_quality);
2694 av_dict_set(&sopts, "qscale", arg, 0);
2695 sprintf(arg, "%d", ctx->global_quality);
2696 av_dict_set(&sopts, "global_quality", arg, 0);
2698 int vidx = ffvideo.size();
2699 int fidx = vidx + ffaudio.size();
2700 FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
2701 vstrm_index.append(ffidx(vidx, 0));
2702 vid->avctx = ctx; ffvideo.append(vid); fst = vid;
2703 vid->width = asset->width;
2704 vid->height = asset->height;
2705 vid->frame_rate = asset->frame_rate;
2706 if( (vid->color_range = asset->ff_color_range) < 0 )
2707 vid->color_range = file_base->file->preferences->yuv_color_range;
2708 switch( vid->color_range ) {
2709 case BC_COLORS_MPEG: ctx->color_range = AVCOL_RANGE_MPEG; break;
2710 case BC_COLORS_JPEG: ctx->color_range = AVCOL_RANGE_JPEG; break;
2712 if( (vid->color_space = asset->ff_color_space) < 0 )
2713 vid->color_space = file_base->file->preferences->yuv_color_space;
2714 switch( vid->color_space ) {
2715 case BC_COLORS_BT601: ctx->colorspace = AVCOL_SPC_SMPTE170M; break;
2716 case BC_COLORS_BT709: ctx->colorspace = AVCOL_SPC_BT709; break;
2717 case BC_COLORS_BT2020: ctx->colorspace = AVCOL_SPC_BT2020_NCL; break;
2719 AVPixelFormat pix_fmt = av_get_pix_fmt(asset->ff_pixel_format);
2720 if( opt_hw_dev != 0 ) {
2721 AVHWDeviceType hw_type = vid->encode_hw_activate(opt_hw_dev);
2723 case AV_HWDEVICE_TYPE_VAAPI:
2724 pix_fmt = AV_PIX_FMT_VAAPI;
2726 case AV_HWDEVICE_TYPE_NONE:
2730 if( pix_fmt == AV_PIX_FMT_NONE )
2731 pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
2732 ctx->pix_fmt = pix_fmt;
2734 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
2735 int mask_w = (1<<desc->log2_chroma_w)-1;
2736 ctx->width = (vid->width+mask_w) & ~mask_w;
2737 int mask_h = (1<<desc->log2_chroma_h)-1;
2738 ctx->height = (vid->height+mask_h) & ~mask_h;
2739 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
2740 AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
2741 if( !frame_rate.num || !frame_rate.den ) {
2742 eprintf(_("check_frame_rate failed %s\n"), filename);
2746 av_reduce(&frame_rate.num, &frame_rate.den,
2747 frame_rate.num, frame_rate.den, INT_MAX);
2748 ctx->framerate = (AVRational) { frame_rate.num, frame_rate.den };
2749 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
2750 st->avg_frame_rate = frame_rate;
2751 st->time_base = ctx->time_base;
2753 vid->interlaced = asset->interlace_mode == ILACE_MODE_TOP_FIRST ||
2754 asset->interlace_mode == ILACE_MODE_BOTTOM_FIRST ? 1 : 0;
2755 vid->top_field_first = asset->interlace_mode == ILACE_MODE_TOP_FIRST ? 1 : 0;
2758 eprintf(_("not audio/video, %s:%s\n"), codec_name, filename);
2763 AVDictionaryEntry *tag;
2764 if( (tag=av_dict_get(sopts, "cin_stats_filename", NULL, 0)) != 0 ) {
2765 char suffix[BCSTRLEN]; sprintf(suffix,"-%d.log",fst->fidx);
2766 fst->stats_filename = cstrcat(2, tag->value, suffix);
2768 if( (tag=av_dict_get(sopts, "flags", NULL, 0)) != 0 ) {
2769 int pass = fst->pass;
2770 char *cp = tag->value;
2772 int ch = *cp++, pfx = ch=='-' ? -1 : ch=='+' ? 1 : 0;
2773 if( !isalnum(!pfx ? ch : (ch=*cp++)) ) continue;
2774 char id[BCSTRLEN], *bp = id, *ep = bp+sizeof(id)-1;
2775 for( *bp++=ch; isalnum(ch=*cp); ++cp )
2776 if( bp < ep ) *bp++ = ch;
2778 if( !strcmp(id, "pass1") ) {
2779 pass = pfx<0 ? (pass&~1) : pfx>0 ? (pass|1) : 1;
2781 else if( !strcmp(id, "pass2") ) {
2782 pass = pfx<0 ? (pass&~2) : pfx>0 ? (pass|2) : 2;
2785 if( (fst->pass=pass) ) {
2786 if( pass & 1 ) ctx->flags |= AV_CODEC_FLAG_PASS1;
2787 if( pass & 2 ) ctx->flags |= AV_CODEC_FLAG_PASS2;
2793 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
2794 ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
2795 if( fst->stats_filename && (ret=fst->init_stats_file()) )
2796 eprintf(_("error: stats file = %s\n"), fst->stats_filename);
2799 av_dict_set(&sopts, "cin_bitrate", 0, 0);
2800 av_dict_set(&sopts, "cin_quality", 0, 0);
2802 if( !av_dict_get(sopts, "threads", NULL, 0) )
2803 ctx->thread_count = ff_cpus();
2804 ret = avcodec_open2(ctx, codec, &sopts);
2806 ret = avcodec_parameters_from_context(st->codecpar, ctx);
2808 fprintf(stderr, "Could not copy the stream parameters\n");
2811 _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
2812 ret = avcodec_copy_context(st->codec, ctx);
2813 _Pragma("GCC diagnostic warning \"-Wdeprecated-declarations\"")
2815 fprintf(stderr, "Could not copy the stream context\n");
2818 ff_err(ret,"FFMPEG::open_encoder");
2819 eprintf(_("open failed %s:%s\n"), codec_name, filename);
2825 if( !ret && fst && bsfilter[0] ) {
2826 ret = av_bsf_list_parse_str(bsfilter, &fst->bsfc);
2828 ff_err(ret,"FFMPEG::open_encoder");
2829 eprintf(_("bitstream filter failed %s:\n%s\n"), filename, bsfilter);
2840 av_dict_free(&sopts);
2844 int FFMPEG::close_encoder()
2847 if( encoding > 0 ) {
2848 av_write_trailer(fmt_ctx);
2849 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
2850 avio_closep(&fmt_ctx->pb);
2856 int FFMPEG::decode_activate()
2858 if( decoding < 0 ) {
2860 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
2861 ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
2862 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
2863 ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
2864 // set nudges for each program stream set
2865 const int64_t min_nudge = INT64_MIN+1;
2866 int npgrms = fmt_ctx->nb_programs;
2867 for( int i=0; i<npgrms; ++i ) {
2868 AVProgram *pgrm = fmt_ctx->programs[i];
2869 // first start time video stream
2870 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2871 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2872 int fidx = pgrm->stream_index[j];
2873 AVStream *st = fmt_ctx->streams[fidx];
2874 AVCodecParameters *avpar = st->codecpar;
2875 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2876 if( st->start_time == AV_NOPTS_VALUE ) continue;
2877 if( vstart_time < st->start_time )
2878 vstart_time = st->start_time;
2881 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2882 if( st->start_time == AV_NOPTS_VALUE ) continue;
2883 if( astart_time < st->start_time )
2884 astart_time = st->start_time;
2888 //since frame rate is much more grainy than sample rate, it is better to
2889 // align using video, so that total absolute error is minimized.
2890 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2891 astart_time > min_nudge ? astart_time : AV_NOPTS_VALUE;
2892 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2893 int fidx = pgrm->stream_index[j];
2894 AVStream *st = fmt_ctx->streams[fidx];
2895 AVCodecParameters *avpar = st->codecpar;
2896 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2897 for( int k=0; k<ffvideo.size(); ++k ) {
2898 if( ffvideo[k]->fidx != fidx ) continue;
2899 ffvideo[k]->nudge = nudge;
2903 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2904 for( int k=0; k<ffaudio.size(); ++k ) {
2905 if( ffaudio[k]->fidx != fidx ) continue;
2906 ffaudio[k]->nudge = nudge;
2912 // set nudges for any streams not yet set
2913 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2914 int nstreams = fmt_ctx->nb_streams;
2915 for( int i=0; i<nstreams; ++i ) {
2916 AVStream *st = fmt_ctx->streams[i];
2917 AVCodecParameters *avpar = st->codecpar;
2918 switch( avpar->codec_type ) {
2919 case AVMEDIA_TYPE_VIDEO: {
2920 if( st->start_time == AV_NOPTS_VALUE ) continue;
2921 int vidx = ffvideo.size();
2922 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
2923 if( vidx < 0 ) continue;
2924 if( ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
2925 if( vstart_time < st->start_time )
2926 vstart_time = st->start_time;
2928 case AVMEDIA_TYPE_AUDIO: {
2929 if( st->start_time == AV_NOPTS_VALUE ) continue;
2930 int aidx = ffaudio.size();
2931 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
2932 if( aidx < 0 ) continue;
2933 if( ffaudio[aidx]->frame_sz < avpar->frame_size )
2934 ffaudio[aidx]->frame_sz = avpar->frame_size;
2935 if( ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
2936 if( astart_time < st->start_time )
2937 astart_time = st->start_time;
2942 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2943 astart_time > min_nudge ? astart_time : 0;
2944 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
2945 if( ffvideo[vidx]->nudge == AV_NOPTS_VALUE )
2946 ffvideo[vidx]->nudge = nudge;
2948 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2949 if( ffaudio[aidx]->nudge == AV_NOPTS_VALUE )
2950 ffaudio[aidx]->nudge = nudge;
2957 int FFMPEG::encode_activate()
2960 if( encoding < 0 ) {
2962 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
2963 (ret=avio_open(&fmt_ctx->pb, fmt_ctx->url, AVIO_FLAG_WRITE)) < 0 ) {
2964 ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
2970 AVProgram *prog = av_new_program(fmt_ctx, prog_id);
2971 for( int i=0; i< ffvideo.size(); ++i )
2972 av_program_add_stream_index(fmt_ctx, prog_id, ffvideo[i]->fidx);
2973 for( int i=0; i< ffaudio.size(); ++i )
2974 av_program_add_stream_index(fmt_ctx, prog_id, ffaudio[i]->fidx);
2975 int pi = fmt_ctx->nb_programs;
2976 while( --pi >= 0 && fmt_ctx->programs[pi]->id != prog_id );
2977 AVDictionary **meta = &prog->metadata;
2978 av_dict_set(meta, "service_provider", "cin5", 0);
2979 const char *path = fmt_ctx->url, *bp = strrchr(path,'/');
2980 if( bp ) path = bp + 1;
2981 av_dict_set(meta, "title", path, 0);
2983 if( ffaudio.size() ) {
2984 const char *ep = getenv("CIN_AUDIO_LANG"), *lp = 0;
2985 if( !ep && (lp=getenv("LANG")) ) { // some are guesses
2986 static struct { const char lc[3], lng[4]; } lcode[] = {
2987 { "en", "eng" }, { "de", "ger" }, { "es", "spa" },
2988 { "eu", "bas" }, { "fr", "fre" }, { "el", "gre" },
2989 { "hi", "hin" }, { "it", "ita" }, { "ja", "jap" },
2990 { "ko", "kor" }, { "du", "dut" }, { "pl", "pol" },
2991 { "pt", "por" }, { "ru", "rus" }, { "sl", "slv" },
2992 { "uk", "ukr" }, { "vi", "vie" }, { "zh", "chi" },
2994 for( int i=sizeof(lcode)/sizeof(lcode[0]); --i>=0 && !ep; )
2995 if( !strncmp(lcode[i].lc,lp,2) ) ep = lcode[i].lng;
2997 if( !ep ) ep = "und";
2999 strncpy(lang,ep,3); lang[3] = 0;
3000 AVStream *st = ffaudio[0]->st;
3001 av_dict_set(&st->metadata,"language",lang,0);
3004 AVDictionary *fopts = 0;
3005 char option_path[BCTEXTLEN];
3006 set_option_path(option_path, "format/%s", file_format);
3007 read_options(option_path, fopts, 1);
3008 av_dict_copy(&fopts, opts, 0);
3009 if( scan_options(file_base->asset->ff_format_options, fopts, 0) ) {
3010 eprintf(_("bad format options %s\n"), file_base->asset->path);
3014 ret = avformat_write_header(fmt_ctx, &fopts);
3016 ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
3020 av_dict_free(&fopts);
3027 int FFMPEG::audio_seek(int stream, int64_t pos)
3029 int aidx = astrm_index[stream].st_idx;
3030 FFAudioStream *aud = ffaudio[aidx];
3031 aud->audio_seek(pos);
3035 int FFMPEG::video_seek(int stream, int64_t pos)
3037 int vidx = vstrm_index[stream].st_idx;
3038 FFVideoStream *vid = ffvideo[vidx];
3039 vid->video_seek(pos);
3044 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
3046 if( !has_audio || chn >= astrm_index.size() ) return -1;
3047 int aidx = astrm_index[chn].st_idx;
3048 FFAudioStream *aud = ffaudio[aidx];
3049 if( aud->load(pos, len) < len ) return -1;
3050 int ch = astrm_index[chn].st_ch;
3051 int ret = aud->read(samples,len,ch);
3055 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
3057 if( !has_video || layer >= vstrm_index.size() ) return -1;
3058 int vidx = vstrm_index[layer].st_idx;
3059 FFVideoStream *vid = ffvideo[vidx];
3060 return vid->load(vframe, pos);
3064 int FFMPEG::encode(int stream, double **samples, int len)
3066 FFAudioStream *aud = ffaudio[stream];
3067 return aud->encode(samples, len);
3071 int FFMPEG::encode(int stream, VFrame *frame)
3073 FFVideoStream *vid = ffvideo[stream];
3074 return vid->encode(frame);
3077 void FFMPEG::start_muxer()
3085 void FFMPEG::stop_muxer()
3094 void FFMPEG::flow_off()
3097 flow_lock->lock("FFMPEG::flow_off");
3101 void FFMPEG::flow_on()
3105 flow_lock->unlock();
3108 void FFMPEG::flow_ctl()
3111 flow_lock->lock("FFMPEG::flow_ctl");
3112 flow_lock->unlock();
3116 int FFMPEG::mux_audio(FFrame *frm)
3118 FFStream *fst = frm->fst;
3119 AVCodecContext *ctx = fst->avctx;
3120 AVFrame *frame = *frm;
3121 AVRational tick_rate = {1, ctx->sample_rate};
3122 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
3123 int ret = fst->encode_frame(frame);
3125 ff_err(ret, "FFMPEG::mux_audio");
3126 return ret >= 0 ? 0 : 1;
3129 int FFMPEG::mux_video(FFrame *frm)
3131 FFStream *fst = frm->fst;
3132 AVFrame *frame = *frm;
3133 frame->pts = frm->position;
3134 int ret = fst->encode_frame(frame);
3136 ff_err(ret, "FFMPEG::mux_video");
3137 return ret >= 0 ? 0 : 1;
3143 double atm = -1, vtm = -1;
3144 FFrame *afrm = 0, *vfrm = 0;
3146 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
3147 FFStream *fst = ffaudio[i];
3148 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
3149 FFrame *frm = fst->frms.first;
3150 if( !frm ) { if( !done ) return; continue; }
3151 double tm = to_secs(frm->position, fst->avctx->time_base);
3152 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
3154 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
3155 FFStream *fst = ffvideo[i];
3156 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
3157 FFrame *frm = fst->frms.first;
3158 if( !frm ) { if( !done ) return; continue; }
3159 double tm = to_secs(frm->position, fst->avctx->time_base);
3160 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
3162 if( !demand ) flow_off();
3163 if( !afrm && !vfrm ) break;
3164 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
3165 vfrm->position, vfrm->fst->avctx->time_base,
3166 afrm->position, afrm->fst->avctx->time_base);
3167 FFrame *frm = v <= 0 ? vfrm : afrm;
3168 if( frm == afrm ) mux_audio(frm);
3169 if( frm == vfrm ) mux_video(frm);
3178 mux_lock->lock("FFMPEG::run");
3181 for( int i=0; i<ffaudio.size(); ++i )
3182 ffaudio[i]->drain();
3183 for( int i=0; i<ffvideo.size(); ++i )
3184 ffvideo[i]->drain();
3186 for( int i=0; i<ffaudio.size(); ++i )
3187 ffaudio[i]->flush();
3188 for( int i=0; i<ffvideo.size(); ++i )
3189 ffvideo[i]->flush();
3193 int FFMPEG::ff_total_audio_channels()
3195 return astrm_index.size();
3198 int FFMPEG::ff_total_astreams()
3200 return ffaudio.size();
3203 int FFMPEG::ff_audio_channels(int stream)
3205 return ffaudio[stream]->channels;
3208 int FFMPEG::ff_sample_rate(int stream)
3210 return ffaudio[stream]->sample_rate;
3213 const char* FFMPEG::ff_audio_format(int stream)
3215 AVStream *st = ffaudio[stream]->st;
3216 AVCodecID id = st->codecpar->codec_id;
3217 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
3218 return desc ? desc->name : _("Unknown");
3221 int FFMPEG::ff_audio_pid(int stream)
3223 return ffaudio[stream]->st->id;
3226 int64_t FFMPEG::ff_audio_samples(int stream)
3228 return ffaudio[stream]->length;
3231 // find audio astream/channels with this program,
3232 // or all program audio channels (astream=-1)
3233 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
3237 int vidx = ffvideo[vstream]->fidx;
3238 // find first program with this video stream
3239 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
3240 AVProgram *pgrm = fmt_ctx->programs[i];
3241 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
3242 int st_idx = pgrm->stream_index[j];
3243 AVStream *st = fmt_ctx->streams[st_idx];
3244 if( st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
3245 if( st_idx == vidx ) pidx = i;
3248 if( pidx < 0 ) return -1;
3250 int64_t channels = 0;
3251 AVProgram *pgrm = fmt_ctx->programs[pidx];
3252 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
3253 int aidx = pgrm->stream_index[j];
3254 AVStream *st = fmt_ctx->streams[aidx];
3255 if( st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
3256 if( astream > 0 ) { --astream; continue; }
3258 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
3259 if( ffaudio[i]->fidx == aidx ) astrm = i;
3261 if( ret < 0 ) ret = astrm;
3262 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
3263 channels |= mask << ffaudio[astrm]->channel0;
3265 if( !astream ) break;
3267 channel_mask = channels;
3272 int FFMPEG::ff_total_video_layers()
3274 return vstrm_index.size();
3277 int FFMPEG::ff_total_vstreams()
3279 return ffvideo.size();
3282 int FFMPEG::ff_video_width(int stream)
3284 return ffvideo[stream]->width;
3287 int FFMPEG::ff_video_height(int stream)
3289 return ffvideo[stream]->height;
3292 int FFMPEG::ff_set_video_width(int stream, int width)
3294 int w = ffvideo[stream]->width;
3295 ffvideo[stream]->width = width;
3299 int FFMPEG::ff_set_video_height(int stream, int height)
3301 int h = ffvideo[stream]->height;
3302 ffvideo[stream]->height = height;
3306 int FFMPEG::ff_coded_width(int stream)
3308 return ffvideo[stream]->avctx->coded_width;
3311 int FFMPEG::ff_coded_height(int stream)
3313 return ffvideo[stream]->avctx->coded_height;
3316 float FFMPEG::ff_aspect_ratio(int stream)
3318 return ffvideo[stream]->aspect_ratio;
3321 const char* FFMPEG::ff_video_format(int stream)
3323 AVStream *st = ffvideo[stream]->st;
3324 AVCodecID id = st->codecpar->codec_id;
3325 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
3326 return desc ? desc->name : _("Unknown");
3329 int FFMPEG::ff_color_range(int stream)
3331 return ffvideo[stream]->color_range;
3334 int FFMPEG::ff_color_space(int stream)
3336 return ffvideo[stream]->color_space;
3339 double FFMPEG::ff_frame_rate(int stream)
3341 return ffvideo[stream]->frame_rate;
3344 int64_t FFMPEG::ff_video_frames(int stream)
3346 return ffvideo[stream]->length;
3349 int FFMPEG::ff_video_pid(int stream)
3351 return ffvideo[stream]->st->id;
3354 int FFMPEG::ff_video_mpeg_color_range(int stream)
3356 return ffvideo[stream]->st->codecpar->color_range == AVCOL_RANGE_MPEG ? 1 : 0;
3359 int FFMPEG::ff_cpus()
3361 return file_base->file->cpus;
3364 const char *FFMPEG::ff_hw_dev()
3366 return &file_base->file->preferences->use_hw_dev[0];
3369 Preferences *FFMPEG::ff_prefs()
3371 return !file_base ? 0 : file_base->file->preferences;
3374 int FFVideoStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
3376 avfilter_register_all();
3377 const char *sp = filter_spec;
3378 char filter_name[BCSTRLEN], *np = filter_name;
3379 int i = sizeof(filter_name);
3380 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
3382 const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
3383 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_VIDEO ) {
3384 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
3387 filter_graph = avfilter_graph_alloc();
3388 const AVFilter *buffersrc = avfilter_get_by_name("buffer");
3389 const AVFilter *buffersink = avfilter_get_by_name("buffersink");
3391 int ret = 0; char args[BCTEXTLEN];
3392 AVPixelFormat pix_fmt = (AVPixelFormat)avpar->format;
3393 snprintf(args, sizeof(args),
3394 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
3395 avpar->width, avpar->height, (int)pix_fmt,
3396 st->time_base.num, st->time_base.den,
3397 avpar->sample_aspect_ratio.num, avpar->sample_aspect_ratio.den);
3399 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
3400 args, NULL, filter_graph);
3402 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
3403 NULL, NULL, filter_graph);
3405 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
3406 (uint8_t*)&pix_fmt, sizeof(pix_fmt),
3407 AV_OPT_SEARCH_CHILDREN);
3409 ff_err(ret, "FFVideoStream::create_filter");
3411 ret = FFStream::create_filter(filter_spec);
3412 return ret >= 0 ? 0 : -1;
3415 int FFAudioStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
3417 avfilter_register_all();
3418 const char *sp = filter_spec;
3419 char filter_name[BCSTRLEN], *np = filter_name;
3420 int i = sizeof(filter_name);
3421 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
3423 const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
3424 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_AUDIO ) {
3425 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
3428 filter_graph = avfilter_graph_alloc();
3429 const AVFilter *buffersrc = avfilter_get_by_name("abuffer");
3430 const AVFilter *buffersink = avfilter_get_by_name("abuffersink");
3431 int ret = 0; char args[BCTEXTLEN];
3432 AVSampleFormat sample_fmt = (AVSampleFormat)avpar->format;
3433 snprintf(args, sizeof(args),
3434 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
3435 st->time_base.num, st->time_base.den, avpar->sample_rate,
3436 av_get_sample_fmt_name(sample_fmt), avpar->channel_layout);
3438 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
3439 args, NULL, filter_graph);
3441 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
3442 NULL, NULL, filter_graph);
3444 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
3445 (uint8_t*)&sample_fmt, sizeof(sample_fmt),
3446 AV_OPT_SEARCH_CHILDREN);
3448 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
3449 (uint8_t*)&avpar->channel_layout,
3450 sizeof(avpar->channel_layout), AV_OPT_SEARCH_CHILDREN);
3452 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
3453 (uint8_t*)&sample_rate, sizeof(sample_rate),
3454 AV_OPT_SEARCH_CHILDREN);
3456 ff_err(ret, "FFAudioStream::create_filter");
3458 ret = FFStream::create_filter(filter_spec);
3459 return ret >= 0 ? 0 : -1;
3462 int FFStream::create_filter(const char *filter_spec)
3464 /* Endpoints for the filter graph. */
3465 AVFilterInOut *outputs = avfilter_inout_alloc();
3466 outputs->name = av_strdup("in");
3467 outputs->filter_ctx = buffersrc_ctx;
3468 outputs->pad_idx = 0;
3471 AVFilterInOut *inputs = avfilter_inout_alloc();
3472 inputs->name = av_strdup("out");
3473 inputs->filter_ctx = buffersink_ctx;
3474 inputs->pad_idx = 0;
3477 int ret = !outputs->name || !inputs->name ? -1 : 0;
3479 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
3480 &inputs, &outputs, NULL);
3482 ret = avfilter_graph_config(filter_graph, NULL);
3485 ff_err(ret, "FFStream::create_filter");
3486 avfilter_graph_free(&filter_graph);
3489 avfilter_inout_free(&inputs);
3490 avfilter_inout_free(&outputs);
3494 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
3497 av_init_packet(&pkt);
3498 AVFrame *frame = av_frame_alloc();
3500 fprintf(stderr,"FFMPEG::scan: ");
3501 fprintf(stderr,_("av_frame_alloc failed\n"));
3502 fprintf(stderr,"FFMPEG::scan:file=%s\n", file_base->asset->path);
3506 index_state->add_video_markers(ffvideo.size());
3507 index_state->add_audio_markers(ffaudio.size());
3509 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
3511 AVDictionary *copts = 0;
3512 av_dict_copy(&copts, opts, 0);
3513 AVStream *st = fmt_ctx->streams[i];
3514 AVCodecID codec_id = st->codecpar->codec_id;
3515 AVCodec *decoder = avcodec_find_decoder(codec_id);
3516 AVCodecContext *avctx = avcodec_alloc_context3(decoder);
3518 eprintf(_("cant allocate codec context\n"));
3519 ret = AVERROR(ENOMEM);
3522 avcodec_parameters_to_context(avctx, st->codecpar);
3523 if( !av_dict_get(copts, "threads", NULL, 0) )
3524 avctx->thread_count = ff_cpus();
3525 ret = avcodec_open2(avctx, decoder, &copts);
3527 av_dict_free(&copts);
3529 AVCodecParameters *avpar = st->codecpar;
3530 switch( avpar->codec_type ) {
3531 case AVMEDIA_TYPE_VIDEO: {
3532 int vidx = ffvideo.size();
3533 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
3534 if( vidx < 0 ) break;
3535 ffvideo[vidx]->avctx = avctx;
3537 case AVMEDIA_TYPE_AUDIO: {
3538 int aidx = ffaudio.size();
3539 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3540 if( aidx < 0 ) break;
3541 ffaudio[aidx]->avctx = avctx;
3546 fprintf(stderr,"FFMPEG::scan: ");
3547 fprintf(stderr,_("codec open failed\n"));
3548 fprintf(stderr,"FFMPEG::scan:file=%s\n", file_base->asset->path);
3549 avcodec_free_context(&avctx);
3553 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
3554 AVStream *st = fmt_ctx->streams[i];
3555 AVCodecParameters *avpar = st->codecpar;
3556 if( avpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
3557 int64_t tstmp = st->start_time;
3558 if( tstmp == AV_NOPTS_VALUE ) continue;
3559 int aidx = ffaudio.size();
3560 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3561 if( aidx < 0 ) continue;
3562 FFAudioStream *aud = ffaudio[aidx];
3563 tstmp -= aud->nudge;
3564 double secs = to_secs(tstmp, st->time_base);
3565 aud->curr_pos = secs * aud->sample_rate + 0.5;
3569 for( int64_t count=0; !*canceled; ++count ) {
3570 av_packet_unref(&pkt);
3571 pkt.data = 0; pkt.size = 0;
3573 int ret = av_read_frame(fmt_ctx, &pkt);
3575 if( ret == AVERROR_EOF ) break;
3576 if( ++errs > 100 ) {
3577 ff_err(ret,_("over 100 read_frame errs\n"));
3582 if( !pkt.data ) continue;
3583 int i = pkt.stream_index;
3584 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
3585 AVStream *st = fmt_ctx->streams[i];
3586 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
3588 AVCodecParameters *avpar = st->codecpar;
3589 switch( avpar->codec_type ) {
3590 case AVMEDIA_TYPE_VIDEO: {
3591 int vidx = ffvideo.size();
3592 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
3593 if( vidx < 0 ) break;
3594 FFVideoStream *vid = ffvideo[vidx];
3595 if( !vid->avctx ) break;
3596 int64_t tstmp = pkt.dts;
3597 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.pts;
3598 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
3599 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
3600 double secs = to_secs(tstmp, st->time_base);
3601 int64_t frm = secs * vid->frame_rate + 0.5;
3602 if( frm < 0 ) frm = 0;
3603 index_state->put_video_mark(vidx, frm, pkt.pos);
3606 ret = avcodec_send_packet(vid->avctx, pkt);
3607 if( ret < 0 ) break;
3608 while( (ret=vid->decode_frame(frame)) > 0 ) {}
3611 case AVMEDIA_TYPE_AUDIO: {
3612 int aidx = ffaudio.size();
3613 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3614 if( aidx < 0 ) break;
3615 FFAudioStream *aud = ffaudio[aidx];
3616 if( !aud->avctx ) break;
3617 int64_t tstmp = pkt.pts;
3618 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
3619 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
3620 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
3621 double secs = to_secs(tstmp, st->time_base);
3622 int64_t sample = secs * aud->sample_rate + 0.5;
3624 index_state->put_audio_mark(aidx, sample, pkt.pos);
3626 ret = avcodec_send_packet(aud->avctx, &pkt);
3627 if( ret < 0 ) break;
3628 int ch = aud->channel0, nch = aud->channels;
3629 int64_t pos = index_state->pos(ch);
3630 if( pos != aud->curr_pos ) {
3631 if( abs(pos-aud->curr_pos) > 1 )
3632 printf("audio%d pad %jd %jd (%jd)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
3633 index_state->pad_data(ch, nch, aud->curr_pos);
3635 while( (ret=aud->decode_frame(frame)) > 0 ) {
3636 //if( frame->channels != nch ) break;
3637 aud->init_swr(frame->channels, frame->format, frame->sample_rate);
3639 int len = aud->get_samples(samples,
3640 &frame->extended_data[0], frame->nb_samples);
3641 pos = aud->curr_pos;
3642 if( (aud->curr_pos += len) >= 0 ) {
3644 samples += -pos * nch;
3645 len = aud->curr_pos;
3647 for( int i=0; i<nch; ++i )
3648 index_state->put_data(ch+i,nch,samples+i,len);
3655 av_frame_free(&frame);
3659 void FFStream::load_markers(IndexMarks &marks, double rate)
3662 int64_t sz = marks.size();
3663 int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
3664 int nb_ent = st->nb_index_entries;
3665 // some formats already have an index
3667 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
3668 int64_t tstmp = ep->timestamp;
3669 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
3670 double secs = ffmpeg->to_secs(tstmp, st->time_base);
3671 int64_t no = secs * rate;
3672 while( in < sz && marks[in].no <= no ) ++in;
3674 int64_t len = sz - in;
3675 int64_t count = max_entries - nb_ent;
3676 if( count > len ) count = len;
3677 for( int i=0; i<count; ++i ) {
3678 int k = in + i * len / count;
3679 int64_t no = marks[k].no, pos = marks[k].pos;
3680 double secs = (double)no / rate;
3681 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
3682 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
3683 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);