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"
36 #include "mainerror.h"
38 #include "preferences.h"
44 #define av_register_all(s)
45 #define avfilter_register_all(s)
48 #define VIDEO_INBUF_SIZE 0x10000
49 #define AUDIO_INBUF_SIZE 0x10000
50 #define VIDEO_REFILL_THRESH 0
51 #define AUDIO_REFILL_THRESH 0x1000
52 #define AUDIO_MIN_FRAME_SZ 128
54 #define FF_ESTM_TIMES 0x0001
55 #define FF_BAD_TIMES 0x0002
57 Mutex FFMPEG::fflock("FFMPEG::fflock");
59 static void ff_err(int ret, const char *fmt, ...)
64 vsnprintf(msg, sizeof(msg), fmt, ap);
66 char errmsg[BCSTRLEN];
67 av_strerror(ret, errmsg, sizeof(errmsg));
68 fprintf(stderr,_("%s err: %s\n"),msg, errmsg);
74 pkt.data = 0; pkt.size = 0;
76 void FFPacket::finit()
78 av_packet_unref(&pkt);
81 FFrame::FFrame(FFStream *fst)
84 frm = av_frame_alloc();
85 init = fst->init_frame(frm);
93 void FFrame::queue(int64_t pos)
99 void FFrame::dequeue()
104 void FFrame::set_hw_frame(AVFrame *frame)
110 int FFAudioStream::read(float *fp, long len)
118 while( --k >= 0 ) *fp++ = *op++;
119 if( op >= lmt ) op = bfr;
124 void FFAudioStream::realloc(long nsz, int nch, long len)
126 long bsz = nsz * nch;
127 float *np = new float[bsz];
128 inp = np + read(np, len) * nch;
133 delete [] bfr; bfr = np;
136 void FFAudioStream::realloc(long nsz, int nch)
138 if( nsz > sz || this->nch != nch ) {
139 long len = this->nch != nch ? 0 : hpos;
140 if( len > sz ) len = sz;
142 realloc(nsz, nch, len);
146 void FFAudioStream::reserve(long nsz, int nch)
148 long len = (inp - outp) / nch;
150 if( nsz > sz || this->nch != nch ) {
151 if( this->nch != nch ) len = 0;
152 realloc(nsz, nch, len);
155 if( (len*=nch) > 0 && bfr != outp )
156 memmove(bfr, outp, len*sizeof(*bfr));
161 long FFAudioStream::used()
163 long len = inp>=outp ? inp-outp : inp-bfr + lmt-outp;
166 long FFAudioStream::avail()
169 if( in1 >= lmt ) in1 = bfr;
170 long len = outp >= in1 ? outp-in1 : outp-bfr + lmt-in1;
173 void FFAudioStream::reset_history()
177 memset(bfr, 0, lmt-bfr);
180 void FFAudioStream::iseek(int64_t ofs)
182 if( ofs > hpos ) ofs = hpos;
183 if( ofs > sz ) ofs = sz;
184 outp = inp - ofs*nch;
185 if( outp < bfr ) outp += sz*nch;
188 float *FFAudioStream::get_outp(int ofs)
195 int64_t FFAudioStream::put_inp(int ofs)
198 return (inp-outp) / nch;
201 int FFAudioStream::write(const float *fp, long len)
209 while( --k >= 0 ) *ip++ = *fp++;
210 if( ip >= lmt ) ip = bfr;
217 int FFAudioStream::zero(long len)
225 while( --k >= 0 ) *ip++ = 0;
226 if( ip >= lmt ) ip = bfr;
233 // does not advance outp
234 int FFAudioStream::read(double *dp, long len, int ch)
237 float *op = outp + ch;
238 float *lmt1 = lmt + nch-1;
240 int k = (lmt1 - op) / nch;
243 while( --k >= 0 ) { *dp++ = *op; op += nch; }
244 if( op >= lmt ) op -= sz*nch;
249 // load linear buffer, no wrapping allowed, does not advance inp
250 int FFAudioStream::write(const double *dp, long len, int ch)
253 float *ip = inp + ch;
254 while( --n >= 0 ) { *ip = *dp++; ip += nch; }
259 FFStream::FFStream(FFMPEG *ffmpeg, AVStream *st, int fidx)
261 this->ffmpeg = ffmpeg;
264 frm_lock = new Mutex("FFStream::frm_lock");
273 nudge = AV_NOPTS_VALUE;
274 seek_pos = curr_pos = 0;
275 seeking = 0; seeked = 1;
277 reading = writing = 0;
278 hw_pixfmt = AV_PIX_FMT_NONE;
291 FFStream::~FFStream()
293 frm_lock->lock("FFStream::~FFStream");
294 if( reading > 0 || writing > 0 ) avcodec_close(avctx);
295 if( avctx ) avcodec_free_context(&avctx);
296 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
297 if( hw_device_ctx ) av_buffer_unref(&hw_device_ctx);
298 if( bsfc ) av_bsf_free(&bsfc);
299 while( frms.first ) frms.remove(frms.first);
300 if( filter_graph ) avfilter_graph_free(&filter_graph);
301 if( frame ) av_frame_free(&frame);
302 if( fframe ) av_frame_free(&fframe);
303 if( probe_frame ) av_frame_free(&probe_frame);
306 if( stats_fp ) fclose(stats_fp);
307 if( stats_in ) av_freep(&stats_in);
308 delete [] stats_filename;
311 void FFStream::ff_lock(const char *cp)
313 FFMPEG::fflock.lock(cp);
316 void FFStream::ff_unlock()
318 FFMPEG::fflock.unlock();
321 void FFStream::queue(FFrame *frm)
323 frm_lock->lock("FFStream::queue");
327 ffmpeg->mux_lock->unlock();
330 void FFStream::dequeue(FFrame *frm)
332 frm_lock->lock("FFStream::dequeue");
334 frms.remove_pointer(frm);
338 int FFStream::encode_activate()
341 writing = ffmpeg->encode_activate();
345 // this is a global parameter that really should be in the context
346 static AVPixelFormat hw_pix_fmt = AV_PIX_FMT_NONE; // protected by ff_lock
348 // goofy maneuver to attach a hw_format to an av_context
349 #define GET_HW_PIXFMT(fn, fmt) \
350 static AVPixelFormat get_hw_##fn(AVCodecContext *ctx, const enum AVPixelFormat *pix_fmts) { \
353 GET_HW_PIXFMT(vaapi, AV_PIX_FMT_VAAPI)
354 GET_HW_PIXFMT(vdpau, AV_PIX_FMT_VDPAU)
355 GET_HW_PIXFMT(cuda, AV_PIX_FMT_CUDA)
356 GET_HW_PIXFMT(nv12, AV_PIX_FMT_NV12)
358 static enum AVPixelFormat get_hw_format(AVCodecContext *ctx,
359 const enum AVPixelFormat *pix_fmts)
361 for( const enum AVPixelFormat *p=pix_fmts; *p!=AV_PIX_FMT_NONE; ++p ) {
362 if( *p != hw_pix_fmt ) continue;
364 case AV_PIX_FMT_VAAPI: ctx->get_format = get_hw_vaapi; return *p;
365 case AV_PIX_FMT_VDPAU: ctx->get_format = get_hw_vdpau; return *p;
366 case AV_PIX_FMT_CUDA: ctx->get_format = get_hw_cuda; return *p;
367 case AV_PIX_FMT_NV12: ctx->get_format = get_hw_nv12; return *p;
369 fprintf(stderr, "Unknown HW surface format: %s\n",
370 av_get_pix_fmt_name(*p));
374 fprintf(stderr, "Failed to get HW surface format.\n");
375 return hw_pix_fmt = AV_PIX_FMT_NONE;
379 AVHWDeviceType FFStream::decode_hw_activate()
381 return AV_HWDEVICE_TYPE_NONE;
384 int FFStream::decode_hw_format(AVCodec *decoder, AVHWDeviceType type)
389 int FFStream::decode_activate()
391 if( reading < 0 && (reading=ffmpeg->decode_activate()) > 0 ) {
392 ff_lock("FFStream::decode_activate");
394 AVDictionary *copts = 0;
395 av_dict_copy(&copts, ffmpeg->opts, 0);
397 AVHWDeviceType hw_type = decode_hw_activate();
399 // this should be avformat_copy_context(), but no copy avail
400 ret = avformat_open_input(&fmt_ctx,
401 ffmpeg->fmt_ctx->url, ffmpeg->fmt_ctx->iformat, &copts);
403 ret = avformat_find_stream_info(fmt_ctx, 0);
404 st = fmt_ctx->streams[fidx];
407 while( ret >= 0 && st != 0 && !reading ) {
408 AVCodecID codec_id = st->codecpar->codec_id;
409 AVCodec *decoder = 0;
411 if( ffmpeg->opt_video_decoder )
412 decoder = avcodec_find_decoder_by_name(ffmpeg->opt_video_decoder);
414 ffmpeg->video_codec_remaps.update(codec_id, decoder);
416 else if( is_audio() ) {
417 if( ffmpeg->opt_audio_decoder )
418 decoder = avcodec_find_decoder_by_name(ffmpeg->opt_audio_decoder);
420 ffmpeg->audio_codec_remaps.update(codec_id, decoder);
423 decoder = avcodec_find_decoder(codec_id);
424 avctx = avcodec_alloc_context3(decoder);
426 eprintf(_("cant allocate codec context\n"));
427 ret = AVERROR(ENOMEM);
429 if( ret >= 0 && hw_type != AV_HWDEVICE_TYPE_NONE ) {
430 ret = decode_hw_format(decoder, hw_type);
433 avcodec_parameters_to_context(avctx, st->codecpar);
434 if( !av_dict_get(copts, "threads", NULL, 0) )
435 avctx->thread_count = ffmpeg->ff_cpus();
436 ret = avcodec_open2(avctx, decoder, &copts);
438 AVFrame *hw_frame = 0;
439 if( ret >= 0 && hw_type != AV_HWDEVICE_TYPE_NONE ) {
440 if( !(hw_frame=av_frame_alloc()) ) {
441 fprintf(stderr, "FFStream::decode_activate: av_frame_alloc failed\n");
442 ret = AVERROR(ENOMEM);
445 ret = decode(hw_frame);
447 if( ret < 0 && hw_type != AV_HWDEVICE_TYPE_NONE ) {
448 ff_err(ret, "HW device init failed, using SW decode.\nfile:%s\n",
449 ffmpeg->fmt_ctx->url);
450 avcodec_close(avctx);
451 avcodec_free_context(&avctx);
452 av_buffer_unref(&hw_device_ctx);
454 av_frame_free(&hw_frame);
455 hw_type = AV_HWDEVICE_TYPE_NONE;
456 int flags = AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_ANY;
458 av_seek_frame(fmt_ctx, idx, 0, flags);
459 need_packet = 1; flushed = 0;
460 seeked = 1; st_eof(0);
464 probe_frame = hw_frame;
468 eprintf(_("open decoder failed\n"));
471 eprintf(_("can't open input file: %s\n"), ffmpeg->fmt_ctx->url);
472 av_dict_free(&copts);
478 int FFStream::read_packet()
480 av_packet_unref(ipkt);
481 int ret = av_read_frame(fmt_ctx, ipkt);
484 if( ret == AVERROR_EOF ) return 0;
485 ff_err(ret, "FFStream::read_packet: av_read_frame failed\n");
492 int FFStream::decode(AVFrame *frame)
494 if( probe_frame ) { // hw probe reads first frame
495 av_frame_ref(frame, probe_frame);
496 av_frame_free(&probe_frame);
500 int retries = MAX_RETRY;
501 frm_lock->lock("FFStream::decode");
502 while( ret >= 0 && !flushed && --retries >= 0 ) {
504 if( (ret=read_packet()) < 0 ) break;
505 AVPacket *pkt = ret > 0 ? (AVPacket*)ipkt : 0;
507 if( pkt->stream_index != st->index ) continue;
508 if( !pkt->data || !pkt->size ) continue;
510 if( (ret=avcodec_send_packet(avctx, pkt)) < 0 ) {
511 ff_err(ret, "FFStream::decode: avcodec_send_packet failed.\nfile:%s\n",
512 ffmpeg->fmt_ctx->url);
518 if( (ret=decode_frame(frame)) > 0 ) break;
527 fprintf(stderr, "FFStream::decode: Retry limit\n");
531 fprintf(stderr, "FFStream::decode: failed\n");
535 int FFStream::load_filter(AVFrame *frame)
537 int ret = av_buffersrc_add_frame_flags(buffersrc_ctx, frame, 0);
539 eprintf(_("av_buffersrc_add_frame_flags failed\n"));
543 int FFStream::read_filter(AVFrame *frame)
545 int ret = av_buffersink_get_frame(buffersink_ctx, frame);
547 if( ret == AVERROR(EAGAIN) ) return 0;
548 if( ret == AVERROR_EOF ) { st_eof(1); return -1; }
549 ff_err(ret, "FFStream::read_filter: av_buffersink_get_frame failed\n");
555 int FFStream::read_frame(AVFrame *frame)
557 av_frame_unref(frame);
558 if( !filter_graph || !buffersrc_ctx || !buffersink_ctx )
559 return decode(frame);
560 if( !fframe && !(fframe=av_frame_alloc()) ) {
561 fprintf(stderr, "FFStream::read_frame: av_frame_alloc failed\n");
565 while( !flushed && !(ret=read_filter(frame)) ) {
566 if( (ret=decode(fframe)) < 0 ) break;
567 if( ret > 0 && (ret=load_filter(fframe)) < 0 ) break;
572 int FFStream::write_packet(FFPacket &pkt)
576 av_packet_rescale_ts(pkt, avctx->time_base, st->time_base);
577 pkt->stream_index = st->index;
578 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, pkt);
581 ret = av_bsf_send_packet(bsfc, pkt);
584 if( (ret=av_bsf_receive_packet(bsfc, bs)) < 0 ) {
585 if( ret == AVERROR(EAGAIN) ) return 0;
586 if( ret == AVERROR_EOF ) return -1;
589 av_packet_rescale_ts(bs, avctx->time_base, st->time_base);
590 bs->stream_index = st->index;
591 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, bs);
595 ff_err(ret, "FFStream::write_packet: write packet failed.\nfile:%s\n",
596 ffmpeg->fmt_ctx->url);
600 int FFStream::encode_frame(AVFrame *frame)
602 int pkts = 0, ret = 0;
603 for( int retry=MAX_RETRY; --retry>=0; ) {
605 ret = avcodec_send_frame(avctx, frame);
606 if( !ret && frame ) return pkts;
607 if( ret < 0 && ret != AVERROR(EAGAIN) ) break;
608 if ( ret == AVERROR(EAGAIN) && !frame ) continue;
610 ret = avcodec_receive_packet(avctx, opkt);
611 if( !frame && ret == AVERROR_EOF ) return pkts;
613 ret = write_packet(opkt);
616 if( frame && stats_fp ) {
617 ret = write_stats_file();
621 ff_err(ret, "FFStream::encode_frame: encode failed.\nfile: %s\n",
622 ffmpeg->fmt_ctx->url);
626 int FFStream::flush()
630 int ret = encode_frame(0);
631 if( ret >= 0 && stats_fp ) {
632 ret = write_stats_file();
636 ff_err(ret, "FFStream::flush failed\n:file:%s\n",
637 ffmpeg->fmt_ctx->url);
638 return ret >= 0 ? 0 : 1;
642 int FFStream::open_stats_file()
644 stats_fp = fopen(stats_filename,"w");
645 return stats_fp ? 0 : AVERROR(errno);
648 int FFStream::close_stats_file()
651 fclose(stats_fp); stats_fp = 0;
656 int FFStream::read_stats_file()
658 int64_t len = 0; struct stat stats_st;
659 int fd = open(stats_filename, O_RDONLY);
660 int ret = fd >= 0 ? 0: ENOENT;
661 if( !ret && fstat(fd, &stats_st) )
664 len = stats_st.st_size;
665 stats_in = (char *)av_malloc(len+1);
669 if( !ret && read(fd, stats_in, len+1) != len )
673 avctx->stats_in = stats_in;
677 return !ret ? 0 : AVERROR(ret);
680 int FFStream::write_stats_file()
683 if( avctx->stats_out && (ret=strlen(avctx->stats_out)) > 0 ) {
684 int len = fwrite(avctx->stats_out, 1, ret, stats_fp);
686 ff_err(ret = AVERROR(errno), "FFStream::write_stats_file.\n%file:%s\n",
687 ffmpeg->fmt_ctx->url);
692 int FFStream::init_stats_file()
695 if( (pass & 2) && (ret = read_stats_file()) < 0 )
696 ff_err(ret, "stat file read: %s", stats_filename);
697 if( (pass & 1) && (ret=open_stats_file()) < 0 )
698 ff_err(ret, "stat file open: %s", stats_filename);
699 return ret >= 0 ? 0 : ret;
702 int FFStream::seek(int64_t no, double rate)
704 // default ffmpeg native seek
706 int64_t pos = no, pkt_pos = -1;
707 IndexMarks *index_markers = get_markers();
708 if( index_markers && index_markers->size() > 1 ) {
709 IndexMarks &marks = *index_markers;
710 int i = marks.find(pos);
711 int64_t n = i < 0 ? (i=0) : marks[i].no;
712 // if indexed seek point not too far away (<30 secs), use index
713 if( no-n < 30*rate ) {
716 if( i < marks.size() ) pkt_pos = marks[i].pos;
720 if( pos == curr_pos ) return 0;
722 double secs = pos < 0 ? 0. : pos / rate;
723 AVRational time_base = st->time_base;
724 int64_t tstmp = time_base.num > 0 ? secs * time_base.den/time_base.num : 0;
726 if( st->nb_index_entries > 0 ) tstmp = st->index_entries[0].timestamp;
727 else if( st->start_time != AV_NOPTS_VALUE ) tstmp = st->start_time;
728 else if( st->first_dts != AV_NOPTS_VALUE ) tstmp = st->first_dts;
729 else tstmp = INT64_MIN+1;
731 else if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
734 // seek all streams using the default timebase.
735 // this is how ffmpeg and ffplay work. stream seeks are less tested.
736 tstmp = av_rescale_q(tstmp, time_base, AV_TIME_BASE_Q);
739 frm_lock->lock("FFStream::seek");
740 av_frame_free(&probe_frame);
741 avcodec_flush_buffers(avctx);
742 avformat_flush(fmt_ctx);
744 int64_t seek = tstmp;
745 int flags = AVSEEK_FLAG_ANY;
746 if( !(fmt_ctx->iformat->flags & AVFMT_NO_BYTE_SEEK) && pkt_pos >= 0 ) {
748 flags = AVSEEK_FLAG_BYTE;
750 int ret = avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, seek, INT64_MAX, flags);
752 // finds the first index frame below the target time
753 int flags = AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_ANY;
754 int ret = av_seek_frame(fmt_ctx, idx, tstmp, flags);
756 int retry = MAX_RETRY;
758 need_packet = 0; flushed = 0;
759 seeked = 1; st_eof(0);
760 // read up to retry packets, limited to npkts in stream, and not pkt.pos past pkt_pos
761 while( --retry >= 0 ) {
762 if( read_packet() <= 0 ) { ret = -1; break; }
763 if( ipkt->stream_index != st->index ) continue;
764 if( !ipkt->data || !ipkt->size ) continue;
765 if( pkt_pos >= 0 && ipkt->pos >= pkt_pos ) break;
766 if( --npkts <= 0 ) break;
767 int64_t pkt_ts = ipkt->dts != AV_NOPTS_VALUE ? ipkt->dts : ipkt->pts;
768 if( pkt_ts == AV_NOPTS_VALUE ) continue;
769 if( pkt_ts >= tstmp ) break;
772 ff_err(AVERROR(EIO), "FFStream::seek: %s\n"
773 " retry limit, pos=%jd tstmp=%jd, ",
774 ffmpeg->fmt_ctx->url, pos, tstmp);
778 ret = avcodec_send_packet(avctx, ipkt);
780 //some codecs need more than one pkt to resync
781 if( ret == AVERROR_INVALIDDATA ) ret = 0;
783 ff_err(ret, "FFStream::avcodec_send_packet failed.\nseek:%s\n",
784 ffmpeg->fmt_ctx->url);
790 printf("** seek fail %jd, %jd\n", pos, tstmp);
791 seeked = need_packet = 0;
795 //printf("seeked pos = %ld, %ld\n", pos, tstmp);
796 seek_pos = curr_pos = pos;
800 FFAudioStream::FFAudioStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
801 : FFStream(ffmpeg, strm, fidx)
804 channel0 = channels = 0;
807 frame_sz = AUDIO_MIN_FRAME_SZ;
809 resample_context = 0;
810 swr_ichs = swr_ifmt = swr_irate = 0;
819 bfr = new float[bsz];
824 FFAudioStream::~FFAudioStream()
826 if( resample_context ) swr_free(&resample_context);
831 void FFAudioStream::init_swr(int ichs, int ifmt, int irate)
833 if( resample_context ) {
834 if( swr_ichs == ichs && swr_ifmt == ifmt && swr_irate == irate )
836 swr_free(&resample_context);
838 swr_ichs = ichs; swr_ifmt = ifmt; swr_irate = irate;
839 if( ichs == channels && ifmt == AV_SAMPLE_FMT_FLT && irate == sample_rate )
841 uint64_t ilayout = av_get_default_channel_layout(ichs);
842 if( !ilayout ) ilayout = ((uint64_t)1<<ichs) - 1;
843 uint64_t olayout = av_get_default_channel_layout(channels);
844 if( !olayout ) olayout = ((uint64_t)1<<channels) - 1;
845 resample_context = swr_alloc_set_opts(NULL,
846 olayout, AV_SAMPLE_FMT_FLT, sample_rate,
847 ilayout, (AVSampleFormat)ifmt, irate,
849 if( resample_context )
850 swr_init(resample_context);
853 int FFAudioStream::get_samples(float *&samples, uint8_t **data, int len)
855 samples = *(float **)data;
856 if( resample_context ) {
857 if( len > aud_bfr_sz ) {
863 aud_bfr = new float[aud_bfr_sz*channels];
865 int ret = swr_convert(resample_context,
866 (uint8_t**)&aud_bfr, aud_bfr_sz, (const uint8_t**)data, len);
868 ff_err(ret, "FFAudioStream::get_samples: swr_convert failed\n");
877 int FFAudioStream::load_history(uint8_t **data, int len)
880 len = get_samples(samples, data, len);
882 // biggest user bfr since seek + frame
883 realloc(mbsz + len + 1, channels);
889 int FFAudioStream::decode_frame(AVFrame *frame)
891 int first_frame = seeked; seeked = 0;
892 frame->best_effort_timestamp = AV_NOPTS_VALUE;
893 int ret = avcodec_receive_frame(avctx, frame);
895 if( first_frame ) return 0;
896 if( ret == AVERROR(EAGAIN) ) return 0;
897 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
898 ff_err(ret, "FFAudioStream::decode_frame: Could not read audio frame.\nfile:%s\n",
899 ffmpeg->fmt_ctx->url);
902 int64_t pkt_ts = frame->best_effort_timestamp;
903 if( pkt_ts != AV_NOPTS_VALUE ) {
904 double ts = ffmpeg->to_secs(pkt_ts - nudge, st->time_base);
905 double t = (double)curr_pos / sample_rate;
906 // some time_base clocks are very grainy, too grainy for audio (clicks, pops)
907 if( fabs(ts - t) > AUDIO_PTS_TOLERANCE )
908 curr_pos = ts * sample_rate + 0.5;
913 int FFAudioStream::encode_activate()
915 if( writing >= 0 ) return writing;
916 if( !avctx->codec ) return writing = 0;
917 frame_sz = avctx->codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE ?
918 10000 : avctx->frame_size;
919 return FFStream::encode_activate();
922 int64_t FFAudioStream::load_buffer(double ** const sp, int len)
924 reserve(len+1, st->codecpar->channels);
925 for( int ch=0; ch<nch; ++ch )
926 write(sp[ch], len, ch);
930 int FFAudioStream::in_history(int64_t pos)
932 if( pos > curr_pos ) return 0;
934 if( len > sz ) len = sz;
935 if( pos < curr_pos - len ) return 0;
940 int FFAudioStream::init_frame(AVFrame *frame)
942 frame->nb_samples = frame_sz;
943 frame->format = avctx->sample_fmt;
944 frame->channel_layout = avctx->channel_layout;
945 frame->sample_rate = avctx->sample_rate;
946 int ret = av_frame_get_buffer(frame, 0);
948 ff_err(ret, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
952 int FFAudioStream::load(int64_t pos, int len)
954 if( audio_seek(pos) < 0 ) return -1;
955 if( !frame && !(frame=av_frame_alloc()) ) {
956 fprintf(stderr, "FFAudioStream::load: av_frame_alloc failed\n");
959 if( mbsz < len ) mbsz = len;
960 int64_t end_pos = pos + len;
961 int ret = 0, i = len / frame_sz + MAX_RETRY;
962 while( ret>=0 && !flushed && curr_pos<end_pos && --i>=0 ) {
963 ret = read_frame(frame);
964 if( ret > 0 && frame->nb_samples > 0 ) {
965 init_swr(frame->channels, frame->format, frame->sample_rate);
966 load_history(&frame->extended_data[0], frame->nb_samples);
967 curr_pos += frame->nb_samples;
970 if( end_pos > curr_pos ) {
971 zero(end_pos - curr_pos);
974 len = curr_pos - pos;
979 int FFAudioStream::audio_seek(int64_t pos)
981 if( decode_activate() <= 0 ) return -1;
982 if( !st->codecpar ) return -1;
983 if( in_history(pos) ) return 0;
984 if( pos == curr_pos ) return 0;
985 reset_history(); mbsz = 0;
986 // guarentee preload > 1sec samples
987 if( (pos-=sample_rate) < 0 ) pos = 0;
988 if( seek(pos, sample_rate) < 0 ) return -1;
992 int FFAudioStream::encode(double **samples, int len)
994 if( encode_activate() <= 0 ) return -1;
997 int64_t count = samples ? load_buffer(samples, len) : used();
998 int frame_sz1 = samples ? frame_sz-1 : 0;
1001 while( ret >= 0 && count > frame_sz1 ) {
1002 frm = new FFrame(this);
1003 if( (ret=frm->initted()) < 0 ) break;
1004 AVFrame *frame = *frm;
1005 len = count >= frame_sz ? frame_sz : count;
1006 float *bfrp = get_outp(len);
1007 ret = swr_convert(resample_context,
1008 (uint8_t **)frame->extended_data, len,
1009 (const uint8_t **)&bfrp, len);
1011 ff_err(ret, "FFAudioStream::encode: swr_convert failed\n");
1014 frame->nb_samples = len;
1015 frm->queue(curr_pos);
1022 return ret >= 0 ? 0 : 1;
1025 int FFAudioStream::drain()
1030 int FFAudioStream::encode_frame(AVFrame *frame)
1032 return FFStream::encode_frame(frame);
1035 int FFAudioStream::write_packet(FFPacket &pkt)
1037 return FFStream::write_packet(pkt);
1040 void FFAudioStream::load_markers()
1042 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1043 if( !index_state || idx >= index_state->audio_markers.size() ) return;
1044 if( index_state->marker_status == MARKERS_NOTTESTED ) return;
1045 FFStream::load_markers(*index_state->audio_markers[idx], sample_rate);
1048 IndexMarks *FFAudioStream::get_markers()
1050 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1051 if( !index_state || idx >= index_state->audio_markers.size() ) return 0;
1052 return index_state->audio_markers[idx];
1055 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
1056 : FFStream(ffmpeg, strm, fidx),
1057 FFVideoConvert(ffmpeg->ff_prefs())
1066 top_field_first = 0;
1072 FFVideoStream::~FFVideoStream()
1074 if( fconvert_ctx ) sws_freeContext(fconvert_ctx);
1077 AVHWDeviceType FFVideoStream::decode_hw_activate()
1079 AVHWDeviceType type = AV_HWDEVICE_TYPE_NONE;
1080 const char *hw_dev = ffmpeg->opt_hw_dev;
1081 if( !hw_dev ) hw_dev = getenv("CIN_HW_DEV");
1082 if( !hw_dev ) hw_dev = ffmpeg->ff_hw_dev();
1083 if( hw_dev && *hw_dev &&
1084 strcmp("none", hw_dev) && strcmp(_("none"), hw_dev) ) {
1085 type = av_hwdevice_find_type_by_name(hw_dev);
1086 if( type == AV_HWDEVICE_TYPE_NONE ) {
1087 fprintf(stderr, "Device type %s is not supported.\n", hw_dev);
1088 fprintf(stderr, "Available device types:");
1089 while( (type = av_hwdevice_iterate_types(type)) != AV_HWDEVICE_TYPE_NONE )
1090 fprintf(stderr, " %s", av_hwdevice_get_type_name(type));
1091 fprintf(stderr, "\n");
1097 int FFVideoStream::decode_hw_format(AVCodec *decoder, AVHWDeviceType type)
1100 hw_pix_fmt = AV_PIX_FMT_NONE;
1101 for( int i=0; ; ++i ) {
1102 const AVCodecHWConfig *config = avcodec_get_hw_config(decoder, i);
1104 fprintf(stderr, "Decoder %s does not support device type %s.\n",
1105 decoder->name, av_hwdevice_get_type_name(type));
1109 if( (config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX) != 0 &&
1110 config->device_type == type ) {
1111 hw_pix_fmt = config->pix_fmt;
1115 if( hw_pix_fmt >= 0 ) {
1116 hw_pixfmt = hw_pix_fmt;
1117 avctx->get_format = get_hw_format;
1118 ret = av_hwdevice_ctx_create(&hw_device_ctx, type, 0, 0, 0);
1120 avctx->hw_device_ctx = av_buffer_ref(hw_device_ctx);
1124 ff_err(ret, "Failed HW device create.\ndev:%s\n",
1125 av_hwdevice_get_type_name(type));
1132 AVHWDeviceType FFVideoStream::encode_hw_activate(const char *hw_dev)
1134 AVBufferRef *hw_device_ctx = 0;
1135 AVBufferRef *hw_frames_ref = 0;
1136 AVHWDeviceType type = AV_HWDEVICE_TYPE_NONE;
1137 if( strcmp(_("none"), hw_dev) ) {
1138 type = av_hwdevice_find_type_by_name(hw_dev);
1139 if( type != AV_HWDEVICE_TYPE_VAAPI ) {
1140 fprintf(stderr, "currently, only vaapi hw encode is supported\n");
1141 type = AV_HWDEVICE_TYPE_NONE;
1144 if( type != AV_HWDEVICE_TYPE_NONE ) {
1145 int ret = av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_VAAPI, 0, 0, 0);
1147 ff_err(ret, "Failed to create a HW device.\n");
1148 type = AV_HWDEVICE_TYPE_NONE;
1151 if( type != AV_HWDEVICE_TYPE_NONE ) {
1152 hw_frames_ref = av_hwframe_ctx_alloc(hw_device_ctx);
1153 if( !hw_frames_ref ) {
1154 fprintf(stderr, "Failed to create HW frame context.\n");
1155 type = AV_HWDEVICE_TYPE_NONE;
1158 if( type != AV_HWDEVICE_TYPE_NONE ) {
1159 AVHWFramesContext *frames_ctx = (AVHWFramesContext *)(hw_frames_ref->data);
1160 frames_ctx->format = AV_PIX_FMT_VAAPI;
1161 frames_ctx->sw_format = AV_PIX_FMT_NV12;
1162 frames_ctx->width = width;
1163 frames_ctx->height = height;
1164 frames_ctx->initial_pool_size = 0; // 200;
1165 int ret = av_hwframe_ctx_init(hw_frames_ref);
1167 avctx->hw_frames_ctx = av_buffer_ref(hw_frames_ref);
1168 if( !avctx->hw_frames_ctx ) ret = AVERROR(ENOMEM);
1171 ff_err(ret, "Failed to initialize HW frame context.\n");
1172 type = AV_HWDEVICE_TYPE_NONE;
1174 av_buffer_unref(&hw_frames_ref);
1179 int FFVideoStream::encode_hw_write(FFrame *picture)
1182 AVFrame *hw_frm = 0;
1183 switch( avctx->pix_fmt ) {
1184 case AV_PIX_FMT_VAAPI:
1185 hw_frm = av_frame_alloc();
1186 if( !hw_frm ) { ret = AVERROR(ENOMEM); break; }
1187 ret = av_hwframe_get_buffer(avctx->hw_frames_ctx, hw_frm, 0);
1188 if( ret < 0 ) break;
1189 ret = av_hwframe_transfer_data(hw_frm, *picture, 0);
1190 if( ret < 0 ) break;
1191 picture->set_hw_frame(hw_frm);
1196 av_frame_free(&hw_frm);
1197 ff_err(ret, "Error while transferring frame data to GPU.\n");
1201 int FFVideoStream::decode_frame(AVFrame *frame)
1203 int first_frame = seeked; seeked = 0;
1204 int ret = avcodec_receive_frame(avctx, frame);
1206 if( first_frame ) return 0;
1207 if( ret == AVERROR(EAGAIN) ) return 0;
1208 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
1209 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame.\nfile:%s\n,",
1210 ffmpeg->fmt_ctx->url);
1213 int64_t pkt_ts = frame->best_effort_timestamp;
1214 if( pkt_ts != AV_NOPTS_VALUE )
1215 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * frame_rate + 0.5;
1219 int FFVideoStream::probe(int64_t pos)
1221 int ret = video_seek(pos);
1222 if( ret < 0 ) return -1;
1223 if( !frame && !(frame=av_frame_alloc()) ) {
1224 fprintf(stderr, "FFVideoStream::probe: av_frame_alloc failed\n");
1228 if (ffmpeg->interlace_from_codec) return 1;
1230 ret = read_frame(frame);
1232 //printf("codec interlace: %i \n",frame->interlaced_frame);
1233 //printf("codec tff: %i \n",frame->top_field_first);
1235 if (!frame->interlaced_frame)
1236 ffmpeg->interlace_from_codec = AV_FIELD_PROGRESSIVE;
1237 if ((frame->interlaced_frame) && (frame->top_field_first))
1238 ffmpeg->interlace_from_codec = AV_FIELD_TT;
1239 if ((frame->interlaced_frame) && (!frame->top_field_first))
1240 ffmpeg->interlace_from_codec = AV_FIELD_BB;
1241 //printf("Interlace mode from codec: %i\n", ffmpeg->interlace_from_codec);
1245 if( frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0 )
1248 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
1249 av_frame_free(&frame);
1253 int FFVideoStream::load(VFrame *vframe, int64_t pos)
1255 int ret = video_seek(pos);
1256 if( ret < 0 ) return -1;
1257 if( !frame && !(frame=av_frame_alloc()) ) {
1258 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
1263 int i = MAX_RETRY + pos - curr_pos;
1264 int64_t cache_start = 0;
1265 while( ret>=0 && !flushed && curr_pos<=pos && --i>=0 ) {
1266 ret = read_frame(frame);
1268 if( frame->key_frame && seeking < 0 ) {
1269 int use_cache = ffmpeg->get_use_cache();
1270 if( use_cache < 0 ) {
1271 // for reverse read, reload file frame_cache from keyframe to pos
1272 ffmpeg->purge_cache();
1273 int count = preferences->cache_size /
1274 vframe->get_data_size() / 2; // try to burn only 1/2 of cache
1275 cache_start = pos - count + 1;
1281 if( seeking > 0 && curr_pos >= cache_start && curr_pos < pos ) {
1282 int vw =vframe->get_w(), vh = vframe->get_h();
1283 int vcolor_model = vframe->get_color_model();
1284 // do not use shm here, puts too much pressure on 32bit systems
1285 VFrame *cache_frame = new VFrame(vw, vh, vcolor_model, 0);
1286 ret = convert_cmodel(cache_frame, frame);
1288 ffmpeg->put_cache_frame(cache_frame, curr_pos);
1294 if( frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0 )
1297 ret = convert_cmodel(vframe, frame);
1299 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
1303 int FFVideoStream::video_seek(int64_t pos)
1305 if( decode_activate() <= 0 ) return -1;
1306 if( !st->codecpar ) return -1;
1307 if( pos == curr_pos-1 && !seeked ) return 0;
1308 // if close enough, just read up to current
1309 int gop = avctx->gop_size;
1310 if( gop < 4 ) gop = 4;
1311 if( gop > 64 ) gop = 64;
1312 int read_limit = curr_pos + 3*gop;
1313 if( pos >= curr_pos && pos <= read_limit ) return 0;
1314 // guarentee preload more than 2*gop frames
1315 if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
1319 int FFVideoStream::init_frame(AVFrame *picture)
1321 switch( avctx->pix_fmt ) {
1322 case AV_PIX_FMT_VAAPI:
1323 picture->format = AV_PIX_FMT_NV12;
1326 picture->format = avctx->pix_fmt;
1329 picture->width = avctx->width;
1330 picture->height = avctx->height;
1331 int ret = av_frame_get_buffer(picture, 32);
1335 int FFVideoStream::convert_hw_frame(AVFrame *ifrm, AVFrame *ofrm)
1337 AVPixelFormat ifmt = (AVPixelFormat)ifrm->format;
1338 AVPixelFormat ofmt = (AVPixelFormat)st->codecpar->format;
1339 ofrm->width = ifrm->width;
1340 ofrm->height = ifrm->height;
1341 ofrm->format = ofmt;
1342 int ret = av_frame_get_buffer(ofrm, 32);
1344 ff_err(ret, "FFVideoStream::convert_hw_frame:"
1345 " av_frame_get_buffer failed\n");
1348 fconvert_ctx = sws_getCachedContext(fconvert_ctx,
1349 ifrm->width, ifrm->height, ifmt,
1350 ofrm->width, ofrm->height, ofmt,
1351 SWS_POINT, NULL, NULL, NULL);
1352 if( !fconvert_ctx ) {
1353 ff_err(AVERROR(EINVAL), "FFVideoStream::convert_hw_frame:"
1354 " sws_getCachedContext() failed\n");
1357 int codec_range = st->codecpar->color_range;
1358 int codec_space = st->codecpar->color_space;
1359 const int *codec_table = sws_getCoefficients(codec_space);
1360 int *inv_table, *table, src_range, dst_range;
1361 int brightness, contrast, saturation;
1362 if( !sws_getColorspaceDetails(fconvert_ctx,
1363 &inv_table, &src_range, &table, &dst_range,
1364 &brightness, &contrast, &saturation) ) {
1365 if( src_range != codec_range || dst_range != codec_range ||
1366 inv_table != codec_table || table != codec_table )
1367 sws_setColorspaceDetails(fconvert_ctx,
1368 codec_table, codec_range, codec_table, codec_range,
1369 brightness, contrast, saturation);
1371 ret = sws_scale(fconvert_ctx,
1372 ifrm->data, ifrm->linesize, 0, ifrm->height,
1373 ofrm->data, ofrm->linesize);
1375 ff_err(ret, "FFVideoStream::convert_hw_frame:"
1376 " sws_scale() failed\nfile: %s\n",
1377 ffmpeg->fmt_ctx->url);
1383 int FFVideoStream::load_filter(AVFrame *frame)
1385 AVPixelFormat pix_fmt = (AVPixelFormat)frame->format;
1386 if( pix_fmt == hw_pixfmt ) {
1387 AVFrame *hw_frame = this->frame;
1388 av_frame_unref(hw_frame);
1389 int ret = av_hwframe_transfer_data(hw_frame, frame, 0);
1391 eprintf(_("Error retrieving data from GPU to CPU\nfile: %s\n"),
1392 ffmpeg->fmt_ctx->url);
1395 av_frame_unref(frame);
1396 ret = convert_hw_frame(hw_frame, frame);
1398 eprintf(_("Error converting data from GPU to CPU\nfile: %s\n"),
1399 ffmpeg->fmt_ctx->url);
1402 av_frame_unref(hw_frame);
1404 return FFStream::load_filter(frame);
1407 int FFVideoStream::encode(VFrame *vframe)
1409 if( encode_activate() <= 0 ) return -1;
1411 FFrame *picture = new FFrame(this);
1412 int ret = picture->initted();
1414 AVFrame *frame = *picture;
1415 frame->pts = curr_pos;
1416 ret = convert_pixfmt(vframe, frame);
1418 if( ret >= 0 && avctx->hw_frames_ctx )
1419 encode_hw_write(picture);
1421 picture->queue(curr_pos);
1425 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
1428 return ret >= 0 ? 0 : 1;
1431 int FFVideoStream::drain()
1437 int FFVideoStream::encode_frame(AVFrame *frame)
1440 frame->interlaced_frame = interlaced;
1441 frame->top_field_first = top_field_first;
1443 if( frame && frame->format == AV_PIX_FMT_VAAPI ) { // ugly
1444 int ret = avcodec_send_frame(avctx, frame);
1445 for( int retry=MAX_RETRY; !ret && --retry>=0; ) {
1446 FFPacket pkt; av_init_packet(pkt);
1447 pkt->data = NULL; pkt->size = 0;
1448 if( (ret=avcodec_receive_packet(avctx, pkt)) < 0 ) {
1449 if( ret == AVERROR(EAGAIN) ) ret = 0; // weird
1452 ret = write_packet(pkt);
1453 pkt->stream_index = 0;
1454 av_packet_unref(pkt);
1457 ff_err(ret, "FFStream::encode_frame: vaapi encode failed.\nfile: %s\n",
1458 ffmpeg->fmt_ctx->url);
1463 return FFStream::encode_frame(frame);
1466 int FFVideoStream::write_packet(FFPacket &pkt)
1468 if( !(ffmpeg->fmt_ctx->oformat->flags & AVFMT_VARIABLE_FPS) )
1470 return FFStream::write_packet(pkt);
1473 AVPixelFormat FFVideoConvert::color_model_to_pix_fmt(int color_model)
1475 switch( color_model ) {
1476 case BC_YUV422: return AV_PIX_FMT_YUYV422;
1477 case BC_RGB888: return AV_PIX_FMT_RGB24;
1478 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
1479 case BC_BGR8888: return AV_PIX_FMT_BGR0;
1480 case BC_BGR888: return AV_PIX_FMT_BGR24;
1481 case BC_ARGB8888: return AV_PIX_FMT_ARGB;
1482 case BC_ABGR8888: return AV_PIX_FMT_ABGR;
1483 case BC_RGB8: return AV_PIX_FMT_RGB8;
1484 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
1485 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
1486 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
1487 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
1488 case BC_RGB565: return AV_PIX_FMT_RGB565;
1489 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
1490 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
1491 case BC_AYUV16161616: return AV_PIX_FMT_AYUV64LE;
1492 case BC_GBRP: return AV_PIX_FMT_GBRP;
1496 return AV_PIX_FMT_NB;
1499 int FFVideoConvert::pix_fmt_to_color_model(AVPixelFormat pix_fmt)
1502 case AV_PIX_FMT_YUYV422: return BC_YUV422;
1503 case AV_PIX_FMT_RGB24: return BC_RGB888;
1504 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
1505 case AV_PIX_FMT_BGR0: return BC_BGR8888;
1506 case AV_PIX_FMT_BGR24: return BC_BGR888;
1507 case AV_PIX_FMT_ARGB: return BC_ARGB8888;
1508 case AV_PIX_FMT_ABGR: return BC_ABGR8888;
1509 case AV_PIX_FMT_RGB8: return BC_RGB8;
1510 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
1511 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
1512 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
1513 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
1514 case AV_PIX_FMT_RGB565: return BC_RGB565;
1515 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
1516 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
1517 case AV_PIX_FMT_AYUV64LE: return BC_AYUV16161616;
1518 case AV_PIX_FMT_GBRP: return BC_GBRP;
1525 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip)
1527 AVFrame *ipic = av_frame_alloc();
1528 int ret = convert_picture_vframe(frame, ip, ipic);
1529 av_frame_free(&ipic);
1533 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip, AVFrame *ipic)
1534 { // picture = vframe
1535 int cmodel = frame->get_color_model();
1536 AVPixelFormat ofmt = color_model_to_pix_fmt(cmodel);
1537 if( ofmt == AV_PIX_FMT_NB ) return -1;
1538 int size = av_image_fill_arrays(ipic->data, ipic->linesize,
1539 frame->get_data(), ofmt, frame->get_w(), frame->get_h(), 1);
1540 if( size < 0 ) return -1;
1542 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1543 int ysz = bpp * frame->get_w(), usz = ysz;
1553 // override av_image_fill_arrays() for planar types
1554 ipic->data[0] = frame->get_y(); ipic->linesize[0] = ysz;
1555 ipic->data[1] = frame->get_u(); ipic->linesize[1] = usz;
1556 ipic->data[2] = frame->get_v(); ipic->linesize[2] = usz;
1559 ipic->data[0] = frame->get_data();
1560 ipic->linesize[0] = frame->get_bytes_per_line();
1564 AVPixelFormat pix_fmt = (AVPixelFormat)ip->format;
1565 FFVideoStream *vid =(FFVideoStream *)this;
1566 if( pix_fmt == vid->hw_pixfmt ) {
1568 if( !sw_frame && !(sw_frame=av_frame_alloc()) )
1569 ret = AVERROR(ENOMEM);
1571 ret = av_hwframe_transfer_data(sw_frame, ip, 0);
1573 pix_fmt = (AVPixelFormat)ip->format;
1576 eprintf(_("Error retrieving data from GPU to CPU\nfile: %s\n"),
1577 vid->ffmpeg->fmt_ctx->url);
1581 convert_ctx = sws_getCachedContext(convert_ctx, ip->width, ip->height, pix_fmt,
1582 frame->get_w(), frame->get_h(), ofmt, SWS_POINT, NULL, NULL, NULL);
1583 if( !convert_ctx ) {
1584 fprintf(stderr, "FFVideoConvert::convert_picture_frame:"
1585 " sws_getCachedContext() failed\n");
1589 int color_range = 0;
1590 switch( preferences->yuv_color_range ) {
1591 case BC_COLORS_JPEG: color_range = 1; break;
1592 case BC_COLORS_MPEG: color_range = 0; break;
1594 int color_space = SWS_CS_ITU601;
1595 switch( preferences->yuv_color_space ) {
1596 case BC_COLORS_BT601_PAL: color_space = SWS_CS_ITU601; break;
1597 case BC_COLORS_BT601_NTSC: color_space = SWS_CS_SMPTE170M; break;
1598 case BC_COLORS_BT709: color_space = SWS_CS_ITU709; break;
1599 case BC_COLORS_BT2020_NCL:
1600 case BC_COLORS_BT2020_CL: color_space = SWS_CS_BT2020; break;
1602 const int *color_table = sws_getCoefficients(color_space);
1604 int *inv_table, *table, src_range, dst_range;
1605 int brightness, contrast, saturation;
1606 if( !sws_getColorspaceDetails(convert_ctx,
1607 &inv_table, &src_range, &table, &dst_range,
1608 &brightness, &contrast, &saturation) ) {
1609 if( src_range != color_range || dst_range != color_range ||
1610 inv_table != color_table || table != color_table )
1611 sws_setColorspaceDetails(convert_ctx,
1612 color_table, color_range, color_table, color_range,
1613 brightness, contrast, saturation);
1616 int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ip->height,
1617 ipic->data, ipic->linesize);
1619 ff_err(ret, "FFVideoConvert::convert_picture_frame: sws_scale() failed\nfile: %s\n",
1620 vid->ffmpeg->fmt_ctx->url);
1626 int FFVideoConvert::convert_cmodel(VFrame *frame, AVFrame *ip)
1628 // try direct transfer
1629 if( !convert_picture_vframe(frame, ip) ) return 1;
1630 // use indirect transfer
1631 AVPixelFormat ifmt = (AVPixelFormat)ip->format;
1632 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
1634 for( int i = 0; i <desc->nb_components; ++i ) {
1635 int bits = desc->comp[i].depth;
1636 if( bits > max_bits ) max_bits = bits;
1638 int imodel = pix_fmt_to_color_model(ifmt);
1639 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1640 int cmodel = frame->get_color_model();
1641 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1642 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1643 imodel = cmodel_is_yuv ?
1644 (BC_CModels::has_alpha(cmodel) ?
1646 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1647 (BC_CModels::has_alpha(cmodel) ?
1648 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1649 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1651 VFrame vframe(ip->width, ip->height, imodel);
1652 if( convert_picture_vframe(&vframe, ip) ) return -1;
1653 frame->transfer_from(&vframe);
1657 int FFVideoConvert::transfer_cmodel(VFrame *frame, AVFrame *ifp)
1659 int ret = convert_cmodel(frame, ifp);
1661 const AVDictionary *src = ifp->metadata;
1662 AVDictionaryEntry *t = NULL;
1663 BC_Hash *hp = frame->get_params();
1665 while( (t=av_dict_get(src, "", t, AV_DICT_IGNORE_SUFFIX)) )
1666 hp->update(t->key, t->value);
1671 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op)
1673 AVFrame *opic = av_frame_alloc();
1674 int ret = convert_vframe_picture(frame, op, opic);
1675 av_frame_free(&opic);
1679 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op, AVFrame *opic)
1680 { // vframe = picture
1681 int cmodel = frame->get_color_model();
1682 AVPixelFormat ifmt = color_model_to_pix_fmt(cmodel);
1683 if( ifmt == AV_PIX_FMT_NB ) return -1;
1684 int size = av_image_fill_arrays(opic->data, opic->linesize,
1685 frame->get_data(), ifmt, frame->get_w(), frame->get_h(), 1);
1686 if( size < 0 ) return -1;
1688 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1689 int ysz = bpp * frame->get_w(), usz = ysz;
1699 // override av_image_fill_arrays() for planar types
1700 opic->data[0] = frame->get_y(); opic->linesize[0] = ysz;
1701 opic->data[1] = frame->get_u(); opic->linesize[1] = usz;
1702 opic->data[2] = frame->get_v(); opic->linesize[2] = usz;
1705 opic->data[0] = frame->get_data();
1706 opic->linesize[0] = frame->get_bytes_per_line();
1710 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1711 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(),
1712 ifmt, op->width, op->height, ofmt, SWS_POINT, NULL, NULL, NULL);
1713 if( !convert_ctx ) {
1714 fprintf(stderr, "FFVideoConvert::convert_frame_picture:"
1715 " sws_getCachedContext() failed\n");
1720 int color_range = 0;
1721 switch( preferences->yuv_color_range ) {
1722 case BC_COLORS_JPEG: color_range = 1; break;
1723 case BC_COLORS_MPEG: color_range = 0; break;
1725 int color_space = SWS_CS_ITU601;
1726 switch( preferences->yuv_color_space ) {
1727 case BC_COLORS_BT601_PAL: color_space = SWS_CS_ITU601; break;
1728 case BC_COLORS_BT601_NTSC: color_space = SWS_CS_SMPTE170M; break;
1729 case BC_COLORS_BT709: color_space = SWS_CS_ITU709; break;
1730 case BC_COLORS_BT2020_NCL:
1731 case BC_COLORS_BT2020_CL: color_space = SWS_CS_BT2020; break;
1733 const int *color_table = sws_getCoefficients(color_space);
1735 int *inv_table, *table, src_range, dst_range;
1736 int brightness, contrast, saturation;
1737 if( !sws_getColorspaceDetails(convert_ctx,
1738 &inv_table, &src_range, &table, &dst_range,
1739 &brightness, &contrast, &saturation) ) {
1740 if( dst_range != color_range || table != color_table )
1741 sws_setColorspaceDetails(convert_ctx,
1742 inv_table, src_range, color_table, color_range,
1743 brightness, contrast, saturation);
1746 int ret = sws_scale(convert_ctx, opic->data, opic->linesize, 0, frame->get_h(),
1747 op->data, op->linesize);
1749 ff_err(ret, "FFVideoConvert::convert_frame_picture: sws_scale() failed\n");
1755 int FFVideoConvert::convert_pixfmt(VFrame *frame, AVFrame *op)
1757 // try direct transfer
1758 if( !convert_vframe_picture(frame, op) ) return 1;
1759 // use indirect transfer
1760 int cmodel = frame->get_color_model();
1761 int max_bits = BC_CModels::calculate_pixelsize(cmodel) * 8;
1762 max_bits /= BC_CModels::components(cmodel);
1763 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1764 int imodel = pix_fmt_to_color_model(ofmt);
1765 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1766 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1767 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1768 imodel = cmodel_is_yuv ?
1769 (BC_CModels::has_alpha(cmodel) ?
1771 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1772 (BC_CModels::has_alpha(cmodel) ?
1773 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1774 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1776 VFrame vframe(frame->get_w(), frame->get_h(), imodel);
1777 vframe.transfer_from(frame);
1778 if( !convert_vframe_picture(&vframe, op) ) return 1;
1782 int FFVideoConvert::transfer_pixfmt(VFrame *frame, AVFrame *ofp)
1784 int ret = convert_pixfmt(frame, ofp);
1786 BC_Hash *hp = frame->get_params();
1787 AVDictionary **dict = &ofp->metadata;
1788 //av_dict_free(dict);
1789 for( int i=0; i<hp->size(); ++i ) {
1790 char *key = hp->get_key(i), *val = hp->get_value(i);
1791 av_dict_set(dict, key, val, 0);
1797 void FFVideoStream::load_markers()
1799 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1800 if( !index_state || idx >= index_state->video_markers.size() ) return;
1801 FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
1804 IndexMarks *FFVideoStream::get_markers()
1806 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1807 if( !index_state || idx >= index_state->video_markers.size() ) return 0;
1808 return !index_state ? 0 : index_state->video_markers[idx];
1812 FFMPEG::FFMPEG(FileBase *file_base)
1815 this->file_base = file_base;
1816 memset(file_format,0,sizeof(file_format));
1817 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
1818 flow_lock = new Condition(1,"FFStream::flow_lock",0);
1821 decoding = encoding = 0;
1822 has_audio = has_video = 0;
1823 interlace_from_codec = 0;
1826 opt_video_filter = 0;
1827 opt_audio_filter = 0;
1829 opt_video_decoder = 0;
1830 opt_audio_decoder = 0;
1832 char option_path[BCTEXTLEN];
1833 set_option_path(option_path, "%s", "ffmpeg.opts");
1834 read_options(option_path, opts);
1839 ff_lock("FFMPEG::~FFMPEG()");
1841 ffaudio.remove_all_objects();
1842 ffvideo.remove_all_objects();
1843 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1847 av_dict_free(&opts);
1848 delete [] opt_video_filter;
1849 delete [] opt_audio_filter;
1850 delete [] opt_hw_dev;
1853 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1855 const int *p = codec->supported_samplerates;
1856 if( !p ) return sample_rate;
1858 if( *p == sample_rate ) return *p;
1864 // check_frame_rate and std_frame_rate needed for 23.976
1865 // and 59.94 fps mpeg2
1866 static inline AVRational std_frame_rate(int i)
1868 static const int m1 = 1001*12, m2 = 1000*12;
1869 static const int freqs[] = {
1870 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1871 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 90*m2,
1872 100*m2, 120*m2, 144*m2, 72*m2, 0,
1874 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1875 return (AVRational) { freq, 1001*12 };
1878 AVRational FFMPEG::check_frame_rate(const AVRational *p, double frame_rate)
1880 AVRational rate, best_rate = (AVRational) { 0, 0 };
1881 double max_err = 1.; int i = 0;
1882 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1883 double framerate = (double) rate.num / rate.den;
1884 double err = fabs(frame_rate/framerate - 1.);
1885 if( err >= max_err ) continue;
1889 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1892 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1895 double display_aspect = asset->width / (double)asset->height;
1896 double sample_aspect = display_aspect / asset->aspect_ratio;
1897 int width = 1000000, height = width * sample_aspect + 0.5;
1899 MWindow::create_aspect_ratio(w, h, width, height);
1900 return (AVRational){(int)w, (int)h};
1903 return (AVRational){1, 1};
1907 AVRational FFMPEG::to_time_base(int sample_rate)
1909 return (AVRational){1, sample_rate};
1912 int FFMPEG::get_fmt_score(AVSampleFormat dst_fmt, AVSampleFormat src_fmt)
1915 int dst_planar = av_sample_fmt_is_planar(dst_fmt);
1916 int src_planar = av_sample_fmt_is_planar(src_fmt);
1917 if( dst_planar != src_planar ) ++score;
1918 int dst_bytes = av_get_bytes_per_sample(dst_fmt);
1919 int src_bytes = av_get_bytes_per_sample(src_fmt);
1920 score += (src_bytes > dst_bytes ? 100 : -10) * (src_bytes - dst_bytes);
1921 int src_packed = av_get_packed_sample_fmt(src_fmt);
1922 int dst_packed = av_get_packed_sample_fmt(dst_fmt);
1923 if( dst_packed == AV_SAMPLE_FMT_S32 && src_packed == AV_SAMPLE_FMT_FLT ) score += 20;
1924 if( dst_packed == AV_SAMPLE_FMT_FLT && src_packed == AV_SAMPLE_FMT_S32 ) score += 2;
1928 AVSampleFormat FFMPEG::find_best_sample_fmt_of_list(
1929 const AVSampleFormat *sample_fmts, AVSampleFormat src_fmt)
1931 AVSampleFormat best = AV_SAMPLE_FMT_NONE;
1932 int best_score = get_fmt_score(best, src_fmt);
1933 for( int i=0; sample_fmts[i] >= 0; ++i ) {
1934 AVSampleFormat sample_fmt = sample_fmts[i];
1935 int score = get_fmt_score(sample_fmt, src_fmt);
1936 if( score >= best_score ) continue;
1937 best = sample_fmt; best_score = score;
1943 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
1945 char *ep = path + BCTEXTLEN-1;
1946 strncpy(path, File::get_cindat_path(), ep-path);
1947 strncat(path, "/ffmpeg/", ep-path);
1948 path += strlen(path);
1951 path += vsnprintf(path, ep-path, fmt, ap);
1956 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
1961 set_option_path(path, "%s/%s", type, spec);
1964 int FFMPEG::get_format(char *format, const char *path, const char *spec)
1966 char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
1967 get_option_path(option_path, path, spec);
1968 FILE *fp = fopen(option_path,"r");
1971 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1973 line[sizeof(line)-1] = 0;
1974 ret = scan_option_line(line, format, codec);
1980 int FFMPEG::get_codec(char *codec, const char *path, const char *spec)
1982 char option_path[BCTEXTLEN], line[BCTEXTLEN], format[BCTEXTLEN];
1983 get_option_path(option_path, path, spec);
1984 FILE *fp = fopen(option_path,"r");
1987 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1990 line[sizeof(line)-1] = 0;
1991 ret = scan_option_line(line, format, codec);
1994 char *vp = codec, *ep = vp+BCTEXTLEN-1;
1995 while( vp < ep && *vp && *vp != '|' ) ++vp;
1996 if( *vp == '|' ) --vp;
1997 while( vp > codec && (*vp==' ' || *vp=='\t') ) *vp-- = 0;
2002 int FFMPEG::get_file_format()
2004 char audio_muxer[BCSTRLEN], video_muxer[BCSTRLEN];
2005 char audio_format[BCSTRLEN], video_format[BCSTRLEN];
2006 audio_muxer[0] = audio_format[0] = 0;
2007 video_muxer[0] = video_format[0] = 0;
2008 Asset *asset = file_base->asset;
2009 int ret = asset ? 0 : 1;
2010 if( !ret && asset->audio_data ) {
2011 if( !(ret=get_format(audio_format, "audio", asset->acodec)) ) {
2012 if( get_format(audio_muxer, "format", audio_format) ) {
2013 strcpy(audio_muxer, audio_format);
2014 audio_format[0] = 0;
2018 if( !ret && asset->video_data ) {
2019 if( !(ret=get_format(video_format, "video", asset->vcodec)) ) {
2020 if( get_format(video_muxer, "format", video_format) ) {
2021 strcpy(video_muxer, video_format);
2022 video_format[0] = 0;
2026 if( !ret && !audio_muxer[0] && !video_muxer[0] )
2028 if( !ret && audio_muxer[0] && video_muxer[0] &&
2029 strcmp(audio_muxer, video_muxer) ) ret = -1;
2030 if( !ret && audio_format[0] && video_format[0] &&
2031 strcmp(audio_format, video_format) ) ret = -1;
2033 strcpy(file_format, !audio_format[0] && !video_format[0] ?
2034 (audio_muxer[0] ? audio_muxer : video_muxer) :
2035 (audio_format[0] ? audio_format : video_format));
2039 int FFMPEG::scan_option_line(const char *cp, char *tag, char *val)
2041 while( *cp == ' ' || *cp == '\t' ) ++cp;
2042 const char *bp = cp;
2043 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' && *cp != '\n' ) ++cp;
2045 if( !len || len > BCSTRLEN-1 ) return 1;
2046 while( bp < cp ) *tag++ = *bp++;
2048 while( *cp == ' ' || *cp == '\t' ) ++cp;
2049 if( *cp == '=' ) ++cp;
2050 while( *cp == ' ' || *cp == '\t' ) ++cp;
2052 while( *cp && *cp != '\n' ) ++cp;
2054 if( len > BCTEXTLEN-1 ) return 1;
2055 while( bp < cp ) *val++ = *bp++;
2060 int FFMPEG::can_render(const char *fformat, const char *type)
2063 char option_path[BCTEXTLEN];
2064 FFMPEG::set_option_path(option_path, type);
2065 fs.update(option_path);
2066 int total_files = fs.total_files();
2067 for( int i=0; i<total_files; ++i ) {
2068 const char *name = fs.get_entry(i)->get_name();
2069 const char *ext = strrchr(name,'.');
2070 if( !ext ) continue;
2071 if( !strcmp(fformat, ++ext) ) return 1;
2076 int FFMPEG::get_ff_option(const char *nm, const char *options, char *value)
2078 for( const char *cp=options; *cp!=0; ) {
2079 char line[BCTEXTLEN], *bp = line, *ep = bp+sizeof(line)-1;
2080 while( bp < ep && *cp && *cp!='\n' ) *bp++ = *cp++;
2083 if( !line[0] || line[0] == '#' || line[0] == ';' ) continue;
2084 char key[BCSTRLEN], val[BCTEXTLEN];
2085 if( FFMPEG::scan_option_line(line, key, val) ) continue;
2086 if( !strcmp(key, nm) ) {
2087 strncpy(value, val, BCSTRLEN);
2094 void FFMPEG::scan_audio_options(Asset *asset, EDL *edl)
2096 char cin_sample_fmt[BCSTRLEN];
2097 int cin_fmt = AV_SAMPLE_FMT_NONE;
2098 const char *options = asset->ff_audio_options;
2099 if( !get_ff_option("cin_sample_fmt", options, cin_sample_fmt) )
2100 cin_fmt = (int)av_get_sample_fmt(cin_sample_fmt);
2102 char audio_codec[BCSTRLEN]; audio_codec[0] = 0;
2103 AVCodec *av_codec = !FFMPEG::get_codec(audio_codec, "audio", asset->acodec) ?
2104 avcodec_find_encoder_by_name(audio_codec) : 0;
2105 if( av_codec && av_codec->sample_fmts )
2106 cin_fmt = find_best_sample_fmt_of_list(av_codec->sample_fmts, AV_SAMPLE_FMT_FLT);
2108 if( cin_fmt < 0 ) cin_fmt = AV_SAMPLE_FMT_S16;
2109 const char *name = av_get_sample_fmt_name((AVSampleFormat)cin_fmt);
2110 if( !name ) name = _("None");
2111 strcpy(asset->ff_sample_format, name);
2113 char value[BCSTRLEN];
2114 if( !get_ff_option("cin_bitrate", options, value) )
2115 asset->ff_audio_bitrate = atoi(value);
2116 if( !get_ff_option("cin_quality", options, value) )
2117 asset->ff_audio_quality = atoi(value);
2120 void FFMPEG::load_audio_options(Asset *asset, EDL *edl)
2122 char options_path[BCTEXTLEN];
2123 set_option_path(options_path, "audio/%s", asset->acodec);
2124 if( !load_options(options_path,
2125 asset->ff_audio_options,
2126 sizeof(asset->ff_audio_options)) )
2127 scan_audio_options(asset, edl);
2130 void FFMPEG::scan_video_options(Asset *asset, EDL *edl)
2132 char cin_pix_fmt[BCSTRLEN];
2133 int cin_fmt = AV_PIX_FMT_NONE;
2134 const char *options = asset->ff_video_options;
2135 if( !get_ff_option("cin_pix_fmt", options, cin_pix_fmt) )
2136 cin_fmt = (int)av_get_pix_fmt(cin_pix_fmt);
2138 char video_codec[BCSTRLEN]; video_codec[0] = 0;
2139 AVCodec *av_codec = !get_codec(video_codec, "video", asset->vcodec) ?
2140 avcodec_find_encoder_by_name(video_codec) : 0;
2141 if( av_codec && av_codec->pix_fmts ) {
2142 if( 0 && edl ) { // frequently picks a bad answer
2143 int color_model = edl->session->color_model;
2144 int max_bits = BC_CModels::calculate_pixelsize(color_model) * 8;
2145 max_bits /= BC_CModels::components(color_model);
2146 cin_fmt = avcodec_find_best_pix_fmt_of_list(av_codec->pix_fmts,
2147 (BC_CModels::is_yuv(color_model) ?
2148 (max_bits > 8 ? AV_PIX_FMT_AYUV64LE : AV_PIX_FMT_YUV444P) :
2149 (max_bits > 8 ? AV_PIX_FMT_RGB48LE : AV_PIX_FMT_RGB24)), 0, 0);
2152 cin_fmt = av_codec->pix_fmts[0];
2155 if( cin_fmt < 0 ) cin_fmt = AV_PIX_FMT_YUV420P;
2156 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get((AVPixelFormat)cin_fmt);
2157 const char *name = desc ? desc->name : _("None");
2158 strcpy(asset->ff_pixel_format, name);
2160 char value[BCSTRLEN];
2161 if( !get_ff_option("cin_bitrate", options, value) )
2162 asset->ff_video_bitrate = atoi(value);
2163 if( !get_ff_option("cin_quality", options, value) )
2164 asset->ff_video_quality = atoi(value);
2167 void FFMPEG::load_video_options(Asset *asset, EDL *edl)
2169 char options_path[BCTEXTLEN];
2170 set_option_path(options_path, "video/%s", asset->vcodec);
2171 if( !load_options(options_path,
2172 asset->ff_video_options,
2173 sizeof(asset->ff_video_options)) )
2174 scan_video_options(asset, edl);
2177 void FFMPEG::scan_format_options(Asset *asset, EDL *edl)
2181 void FFMPEG::load_format_options(Asset *asset, EDL *edl)
2183 char options_path[BCTEXTLEN];
2184 set_option_path(options_path, "format/%s", asset->fformat);
2185 if( !load_options(options_path,
2186 asset->ff_format_options,
2187 sizeof(asset->ff_format_options)) )
2188 scan_format_options(asset, edl);
2191 int FFMPEG::load_defaults(const char *path, const char *type,
2192 char *codec, char *codec_options, int len)
2194 char default_file[BCTEXTLEN];
2195 set_option_path(default_file, "%s/%s.dfl", path, type);
2196 FILE *fp = fopen(default_file,"r");
2198 fgets(codec, BCSTRLEN, fp);
2200 while( *cp && *cp!='\n' ) ++cp;
2202 while( len > 0 && fgets(codec_options, len, fp) ) {
2203 int n = strlen(codec_options);
2204 codec_options += n; len -= n;
2207 set_option_path(default_file, "%s/%s", path, codec);
2208 return load_options(default_file, codec_options, len);
2211 void FFMPEG::set_asset_format(Asset *asset, EDL *edl, const char *text)
2213 if( asset->format != FILE_FFMPEG ) return;
2214 if( text != asset->fformat )
2215 strcpy(asset->fformat, text);
2216 if( !asset->ff_format_options[0] )
2217 load_format_options(asset, edl);
2218 if( asset->audio_data && !asset->ff_audio_options[0] ) {
2219 if( !load_defaults("audio", text, asset->acodec,
2220 asset->ff_audio_options, sizeof(asset->ff_audio_options)) )
2221 scan_audio_options(asset, edl);
2223 asset->audio_data = 0;
2225 if( asset->video_data && !asset->ff_video_options[0] ) {
2226 if( !load_defaults("video", text, asset->vcodec,
2227 asset->ff_video_options, sizeof(asset->ff_video_options)) )
2228 scan_video_options(asset, edl);
2230 asset->video_data = 0;
2234 int FFMPEG::get_encoder(const char *options,
2235 char *format, char *codec, char *bsfilter)
2237 FILE *fp = fopen(options,"r");
2239 eprintf(_("options open failed %s\n"),options);
2242 char line[BCTEXTLEN];
2243 if( !fgets(line, sizeof(line), fp) ||
2244 scan_encoder(line, format, codec, bsfilter) )
2245 eprintf(_("format/codec not found %s\n"), options);
2250 int FFMPEG::scan_encoder(const char *line,
2251 char *format, char *codec, char *bsfilter)
2253 format[0] = codec[0] = bsfilter[0] = 0;
2254 if( scan_option_line(line, format, codec) ) return 1;
2256 while( *cp && *cp != '|' ) ++cp;
2257 if( !*cp ) return 0;
2259 do { *bp-- = 0; } while( bp>=codec && (*bp==' ' || *bp == '\t' ) );
2260 while( *++cp && (*cp==' ' || *cp == '\t') );
2262 for( int i=BCTEXTLEN; --i>0 && *cp; ) *bp++ = *cp++;
2267 int FFMPEG::read_options(const char *options, AVDictionary *&opts, int skip)
2269 FILE *fp = fopen(options,"r");
2272 while( !ret && --skip >= 0 ) {
2274 while( ch >= 0 && ch != '\n' ) ch = getc(fp);
2275 if( ch < 0 ) ret = 1;
2278 ret = read_options(fp, options, opts);
2283 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
2285 FILE *fp = fmemopen((void *)options,strlen(options),"r");
2287 int ret = read_options(fp, options, opts);
2290 AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
2291 if( tag ) st->id = strtol(tag->value,0,0);
2296 void FFMPEG::put_cache_frame(VFrame *frame, int64_t position)
2298 file_base->file->put_cache_frame(frame, position, 0);
2301 int FFMPEG::get_use_cache()
2303 return file_base->file->get_use_cache();
2306 void FFMPEG::purge_cache()
2308 file_base->file->purge_cache();
2311 FFCodecRemap::FFCodecRemap()
2316 FFCodecRemap::~FFCodecRemap()
2318 delete [] old_codec;
2319 delete [] new_codec;
2322 int FFCodecRemaps::add(const char *val)
2324 char old_codec[BCSTRLEN], new_codec[BCSTRLEN];
2325 if( sscanf(val, " %63[a-zA-z0-9_-] = %63[a-z0-9_-]",
2326 &old_codec[0], &new_codec[0]) != 2 ) return 1;
2327 FFCodecRemap &remap = append();
2328 remap.old_codec = cstrdup(old_codec);
2329 remap.new_codec = cstrdup(new_codec);
2334 int FFCodecRemaps::update(AVCodecID &codec_id, AVCodec *&decoder)
2336 AVCodec *codec = avcodec_find_decoder(codec_id);
2337 if( !codec ) return -1;
2338 const char *name = codec->name;
2339 FFCodecRemaps &map = *this;
2341 while( --k >= 0 && strcmp(map[k].old_codec, name) );
2342 if( k < 0 ) return 1;
2343 const char *new_codec = map[k].new_codec;
2344 codec = avcodec_find_decoder_by_name(new_codec);
2345 if( !codec ) return -1;
2350 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
2352 int ret = 0, no = 0;
2353 char line[BCTEXTLEN];
2354 while( !ret && fgets(line, sizeof(line), fp) ) {
2355 line[sizeof(line)-1] = 0;
2356 if( line[0] == '#' ) continue;
2357 if( line[0] == '\n' ) continue;
2358 char key[BCSTRLEN], val[BCTEXTLEN];
2359 if( scan_option_line(line, key, val) ) {
2360 eprintf(_("err reading %s: line %d\n"), options, no);
2364 if( !strcmp(key, "duration") )
2365 opt_duration = strtod(val, 0);
2366 else if( !strcmp(key, "video_decoder") )
2367 opt_video_decoder = cstrdup(val);
2368 else if( !strcmp(key, "audio_decoder") )
2369 opt_audio_decoder = cstrdup(val);
2370 else if( !strcmp(key, "remap_video_decoder") )
2371 video_codec_remaps.add(val);
2372 else if( !strcmp(key, "remap_audio_decoder") )
2373 audio_codec_remaps.add(val);
2374 else if( !strcmp(key, "video_filter") )
2375 opt_video_filter = cstrdup(val);
2376 else if( !strcmp(key, "audio_filter") )
2377 opt_audio_filter = cstrdup(val);
2378 else if( !strcmp(key, "cin_hw_dev") )
2379 opt_hw_dev = cstrdup(val);
2380 else if( !strcmp(key, "loglevel") )
2383 av_dict_set(&opts, key, val, 0);
2389 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
2391 char option_path[BCTEXTLEN];
2392 set_option_path(option_path, "%s", options);
2393 return read_options(option_path, opts);
2396 int FFMPEG::load_options(const char *path, char *bfr, int len)
2399 FILE *fp = fopen(path, "r");
2401 fgets(bfr, len, fp); // skip hdr
2402 len = fread(bfr, 1, len-1, fp);
2403 if( len < 0 ) len = 0;
2409 void FFMPEG::set_loglevel(const char *ap)
2411 if( !ap || !*ap ) return;
2416 { "quiet" , AV_LOG_QUIET },
2417 { "panic" , AV_LOG_PANIC },
2418 { "fatal" , AV_LOG_FATAL },
2419 { "error" , AV_LOG_ERROR },
2420 { "warning", AV_LOG_WARNING },
2421 { "info" , AV_LOG_INFO },
2422 { "verbose", AV_LOG_VERBOSE },
2423 { "debug" , AV_LOG_DEBUG },
2425 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
2426 if( !strcmp(log_levels[i].name, ap) ) {
2427 av_log_set_level(log_levels[i].level);
2431 av_log_set_level(atoi(ap));
2434 double FFMPEG::to_secs(int64_t time, AVRational time_base)
2436 double base_time = time == AV_NOPTS_VALUE ? 0 :
2437 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
2438 return base_time / AV_TIME_BASE;
2441 int FFMPEG::info(char *text, int len)
2443 if( len <= 0 ) return 0;
2445 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
2447 report("format: %s\n",fmt_ctx->iformat->name);
2448 if( ffvideo.size() > 0 )
2449 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
2450 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
2451 const char *unkn = _("(unkn)");
2452 FFVideoStream *vid = ffvideo[vidx];
2453 AVStream *st = vid->st;
2454 AVCodecID codec_id = st->codecpar->codec_id;
2455 report(_("vid%d (%d), id 0x%06x:\n"), vid->idx, vid->fidx, codec_id);
2456 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
2457 report(" video%d %s ", vidx+1, desc ? desc->name : unkn);
2458 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
2459 AVPixelFormat pix_fmt = (AVPixelFormat)st->codecpar->format;
2460 const char *pfn = av_get_pix_fmt_name(pix_fmt);
2461 report(" pix %s\n", pfn ? pfn : unkn);
2462 int interlace = st->codecpar->field_order;
2463 report(" interlace (container level): %i\n", interlace ? interlace : -1);
2464 int interlace_codec = interlace_from_codec;
2465 report(" interlace (codec level): %i\n", interlace_codec ? interlace_codec : -1);
2466 enum AVColorSpace space = st->codecpar->color_space;
2467 const char *nm = av_color_space_name(space);
2468 report(" color space:%s", nm ? nm : unkn);
2469 enum AVColorRange range = st->codecpar->color_range;
2470 const char *rg = av_color_range_name(range);
2471 report("/ range:%s\n", rg ? rg : unkn);
2472 double secs = to_secs(st->duration, st->time_base);
2473 int64_t length = secs * vid->frame_rate + 0.5;
2474 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
2475 int64_t nudge = ofs * vid->frame_rate;
2476 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
2477 report(" %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
2478 int hrs = secs/3600; secs -= hrs*3600;
2479 int mins = secs/60; secs -= mins*60;
2480 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
2481 double theta = vid->get_rotation_angle();
2482 if( fabs(theta) > 1 )
2483 report(" rotation angle: %0.1f\n", theta);
2485 if( ffaudio.size() > 0 )
2486 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
2487 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2488 FFAudioStream *aud = ffaudio[aidx];
2489 AVStream *st = aud->st;
2490 AVCodecID codec_id = st->codecpar->codec_id;
2491 report(_("aud%d (%d), id 0x%06x:\n"), aud->idx, aud->fidx, codec_id);
2492 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
2493 int nch = aud->channels, ch0 = aud->channel0+1;
2494 report(" audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
2495 AVSampleFormat sample_fmt = (AVSampleFormat)st->codecpar->format;
2496 const char *fmt = av_get_sample_fmt_name(sample_fmt);
2497 report(" %s %d", fmt, aud->sample_rate);
2498 int sample_bits = av_get_bits_per_sample(codec_id);
2499 report(" %dbits\n", sample_bits);
2500 double secs = to_secs(st->duration, st->time_base);
2501 int64_t length = secs * aud->sample_rate + 0.5;
2502 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
2503 int64_t nudge = ofs * aud->sample_rate;
2504 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
2505 report(" %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
2506 int hrs = secs/3600; secs -= hrs*3600;
2507 int mins = secs/60; secs -= mins*60;
2508 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
2510 if( fmt_ctx->nb_programs > 0 )
2511 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
2512 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
2513 report("program %d", i+1);
2514 AVProgram *pgrm = fmt_ctx->programs[i];
2515 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2516 int idx = pgrm->stream_index[j];
2517 int vidx = ffvideo.size();
2518 while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
2520 report(", vid%d", vidx);
2523 int aidx = ffaudio.size();
2524 while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
2526 report(", aud%d", aidx);
2529 report(", (%d)", pgrm->stream_index[j]);
2534 AVDictionaryEntry *tag = 0;
2535 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
2536 report("%s=%s\n", tag->key, tag->value);
2545 int FFMPEG::init_decoder(const char *filename)
2547 ff_lock("FFMPEG::init_decoder");
2549 char file_opts[BCTEXTLEN];
2550 strcpy(file_opts, filename);
2551 char *bp = strrchr(file_opts, '/');
2552 if( !bp ) bp = file_opts;
2553 char *sp = strrchr(bp, '.');
2554 if( !sp ) sp = bp + strlen(bp);
2556 AVInputFormat *ifmt = 0;
2558 strcpy(sp, ".opts");
2559 fp = fopen(file_opts, "r");
2562 read_options(fp, file_opts, opts);
2564 AVDictionaryEntry *tag;
2565 if( (tag=av_dict_get(opts, "format", NULL, 0)) != 0 ) {
2566 ifmt = av_find_input_format(tag->value);
2570 load_options("decode.opts", opts);
2571 AVDictionary *fopts = 0;
2572 av_dict_copy(&fopts, opts, 0);
2573 int ret = avformat_open_input(&fmt_ctx, filename, ifmt, &fopts);
2574 av_dict_free(&fopts);
2576 ret = avformat_find_stream_info(fmt_ctx, NULL);
2581 return !ret ? 0 : 1;
2584 int FFMPEG::open_decoder()
2587 if( stat(fmt_ctx->url, &st) < 0 ) {
2588 eprintf(_("can't stat file: %s\n"), fmt_ctx->url);
2592 int64_t file_bits = 8 * st.st_size;
2593 if( !fmt_ctx->bit_rate && opt_duration > 0 )
2594 fmt_ctx->bit_rate = file_bits / opt_duration;
2597 if( fmt_ctx->bit_rate > 0 ) {
2598 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2599 AVStream *st = fmt_ctx->streams[i];
2600 if( st->duration != AV_NOPTS_VALUE ) continue;
2601 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
2602 st->duration = av_rescale(file_bits, st->time_base.den,
2603 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
2607 if( estimated && !(fflags & FF_ESTM_TIMES) ) {
2608 fflags |= FF_ESTM_TIMES;
2609 printf("FFMPEG::open_decoder: some stream times estimated: %s\n",
2613 ff_lock("FFMPEG::open_decoder");
2614 int ret = 0, bad_time = 0;
2615 for( int i=0; !ret && i<(int)fmt_ctx->nb_streams; ++i ) {
2616 AVStream *st = fmt_ctx->streams[i];
2617 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
2618 AVCodecParameters *avpar = st->codecpar;
2619 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avpar->codec_id);
2620 if( !codec_desc ) continue;
2621 switch( avpar->codec_type ) {
2622 case AVMEDIA_TYPE_VIDEO: {
2623 if( avpar->width < 1 ) continue;
2624 if( avpar->height < 1 ) continue;
2625 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
2626 if( framerate.num < 1 ) continue;
2628 int vidx = ffvideo.size();
2629 FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
2630 vstrm_index.append(ffidx(vidx, 0));
2631 ffvideo.append(vid);
2632 vid->width = avpar->width;
2633 vid->height = avpar->height;
2634 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
2635 switch( avpar->color_range ) {
2636 case AVCOL_RANGE_MPEG:
2637 vid->color_range = BC_COLORS_MPEG;
2639 case AVCOL_RANGE_JPEG:
2640 vid->color_range = BC_COLORS_JPEG;
2643 vid->color_range = !file_base ? BC_COLORS_JPEG :
2644 file_base->file->preferences->yuv_color_range;
2647 switch( avpar->color_space ) {
2648 case AVCOL_SPC_BT470BG:
2649 vid->color_space = BC_COLORS_BT601_PAL;
2651 case AVCOL_SPC_SMPTE170M:
2652 vid->color_space = BC_COLORS_BT601_NTSC;
2654 case AVCOL_SPC_BT709:
2655 vid->color_space = BC_COLORS_BT709;
2657 case AVCOL_SPC_BT2020_NCL:
2658 vid->color_space = BC_COLORS_BT2020_NCL;
2660 case AVCOL_SPC_BT2020_CL:
2661 vid->color_space = BC_COLORS_BT2020_CL;
2664 vid->color_space = !file_base ? BC_COLORS_BT601_NTSC :
2665 file_base->file->preferences->yuv_color_space;
2668 double secs = to_secs(st->duration, st->time_base);
2669 vid->length = secs * vid->frame_rate;
2670 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
2671 vid->nudge = st->start_time;
2673 ret = vid->create_filter(opt_video_filter);
2675 case AVMEDIA_TYPE_AUDIO: {
2676 if( avpar->channels < 1 ) continue;
2677 if( avpar->sample_rate < 1 ) continue;
2679 int aidx = ffaudio.size();
2680 FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
2681 ffaudio.append(aud);
2682 aud->channel0 = astrm_index.size();
2683 aud->channels = avpar->channels;
2684 for( int ch=0; ch<aud->channels; ++ch )
2685 astrm_index.append(ffidx(aidx, ch));
2686 aud->sample_rate = avpar->sample_rate;
2687 double secs = to_secs(st->duration, st->time_base);
2688 aud->length = secs * aud->sample_rate;
2689 aud->init_swr(aud->channels, avpar->format, aud->sample_rate);
2690 aud->nudge = st->start_time;
2692 ret = aud->create_filter(opt_audio_filter);
2697 if( bad_time && !(fflags & FF_BAD_TIMES) ) {
2698 fflags |= FF_BAD_TIMES;
2699 printf(_("FFMPEG::open_decoder: some stream have bad times: %s\n"),
2703 return ret < 0 ? -1 : 0;
2707 int FFMPEG::init_encoder(const char *filename)
2709 // try access first for named pipes
2710 int ret = access(filename, W_OK);
2712 int fd = ::open(filename,O_WRONLY);
2713 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
2714 if( fd >= 0 ) { close(fd); ret = 0; }
2717 eprintf(_("bad file path: %s\n"), filename);
2720 ret = get_file_format();
2722 eprintf(_("bad file format: %s\n"), filename);
2726 eprintf(_("mismatch audio/video file format: %s\n"), filename);
2729 ff_lock("FFMPEG::init_encoder");
2731 char format[BCSTRLEN];
2732 if( get_format(format, "format", file_format) )
2733 strcpy(format, file_format);
2734 avformat_alloc_output_context2(&fmt_ctx, 0, format, filename);
2736 eprintf(_("failed: %s\n"), filename);
2741 load_options("encode.opts", opts);
2747 int FFMPEG::open_encoder(const char *type, const char *spec)
2750 Asset *asset = file_base->asset;
2751 char *filename = asset->path;
2752 AVDictionary *sopts = 0;
2753 av_dict_copy(&sopts, opts, 0);
2754 char option_path[BCTEXTLEN];
2755 set_option_path(option_path, "%s/%s.opts", type, type);
2756 read_options(option_path, sopts);
2757 get_option_path(option_path, type, spec);
2758 char format_name[BCSTRLEN], codec_name[BCTEXTLEN], bsfilter[BCTEXTLEN];
2759 if( get_encoder(option_path, format_name, codec_name, bsfilter) ) {
2760 eprintf(_("get_encoder failed %s:%s\n"), option_path, filename);
2765 if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
2767 else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
2768 else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
2771 ff_lock("FFMPEG::open_encoder");
2774 AVCodecContext *ctx = 0;
2776 const AVCodecDescriptor *codec_desc = 0;
2777 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
2779 eprintf(_("cant find codec %s:%s\n"), codec_name, filename);
2783 codec_desc = avcodec_descriptor_get(codec->id);
2785 eprintf(_("unknown codec %s:%s\n"), codec_name, filename);
2790 st = avformat_new_stream(fmt_ctx, 0);
2792 eprintf(_("cant create stream %s:%s\n"), codec_name, filename);
2797 switch( codec_desc->type ) {
2798 case AVMEDIA_TYPE_AUDIO: {
2800 eprintf(_("duplicate audio %s:%s\n"), codec_name, filename);
2804 if( scan_options(asset->ff_audio_options, sopts, st) ) {
2805 eprintf(_("bad audio options %s:%s\n"), codec_name, filename);
2810 ctx = avcodec_alloc_context3(codec);
2811 if( asset->ff_audio_bitrate > 0 ) {
2812 ctx->bit_rate = asset->ff_audio_bitrate;
2814 sprintf(arg, "%d", asset->ff_audio_bitrate);
2815 av_dict_set(&sopts, "b", arg, 0);
2817 else if( asset->ff_audio_quality >= 0 ) {
2818 ctx->global_quality = asset->ff_audio_quality * FF_QP2LAMBDA;
2819 ctx->qmin = ctx->qmax = asset->ff_audio_quality;
2820 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2821 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2822 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2824 av_dict_set(&sopts, "flags", "+qscale", 0);
2825 sprintf(arg, "%d", asset->ff_audio_quality);
2826 av_dict_set(&sopts, "qscale", arg, 0);
2827 sprintf(arg, "%d", ctx->global_quality);
2828 av_dict_set(&sopts, "global_quality", arg, 0);
2830 int aidx = ffaudio.size();
2831 int fidx = aidx + ffvideo.size();
2832 FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
2833 aud->avctx = ctx; ffaudio.append(aud); fst = aud;
2834 aud->sample_rate = asset->sample_rate;
2835 ctx->channels = aud->channels = asset->channels;
2836 for( int ch=0; ch<aud->channels; ++ch )
2837 astrm_index.append(ffidx(aidx, ch));
2838 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
2839 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
2840 if( !ctx->sample_rate ) {
2841 eprintf(_("check_sample_rate failed %s\n"), filename);
2845 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
2846 AVSampleFormat sample_fmt = av_get_sample_fmt(asset->ff_sample_format);
2847 if( sample_fmt == AV_SAMPLE_FMT_NONE )
2848 sample_fmt = codec->sample_fmts ? codec->sample_fmts[0] : AV_SAMPLE_FMT_S16;
2849 ctx->sample_fmt = sample_fmt;
2850 uint64_t layout = av_get_default_channel_layout(ctx->channels);
2851 aud->resample_context = swr_alloc_set_opts(NULL,
2852 layout, ctx->sample_fmt, aud->sample_rate,
2853 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
2855 swr_init(aud->resample_context);
2858 case AVMEDIA_TYPE_VIDEO: {
2860 eprintf(_("duplicate video %s:%s\n"), codec_name, filename);
2864 if( scan_options(asset->ff_video_options, sopts, st) ) {
2865 eprintf(_("bad video options %s:%s\n"), codec_name, filename);
2870 ctx = avcodec_alloc_context3(codec);
2871 if( asset->ff_video_bitrate > 0 ) {
2872 ctx->bit_rate = asset->ff_video_bitrate;
2874 sprintf(arg, "%d", asset->ff_video_bitrate);
2875 av_dict_set(&sopts, "b", arg, 0);
2877 else if( asset->ff_video_quality >= 0 ) {
2878 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
2879 ctx->qmin = ctx->qmax = asset->ff_video_quality;
2880 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2881 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2882 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2884 av_dict_set(&sopts, "flags", "+qscale", 0);
2885 sprintf(arg, "%d", asset->ff_video_quality);
2886 av_dict_set(&sopts, "qscale", arg, 0);
2887 sprintf(arg, "%d", ctx->global_quality);
2888 av_dict_set(&sopts, "global_quality", arg, 0);
2890 int vidx = ffvideo.size();
2891 int fidx = vidx + ffaudio.size();
2892 FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
2893 vstrm_index.append(ffidx(vidx, 0));
2894 vid->avctx = ctx; ffvideo.append(vid); fst = vid;
2895 vid->width = asset->width;
2896 vid->height = asset->height;
2897 vid->frame_rate = asset->frame_rate;
2898 if( (vid->color_range = asset->ff_color_range) < 0 )
2899 vid->color_range = file_base->file->preferences->yuv_color_range;
2900 switch( vid->color_range ) {
2901 case BC_COLORS_MPEG: ctx->color_range = AVCOL_RANGE_MPEG; break;
2902 case BC_COLORS_JPEG: ctx->color_range = AVCOL_RANGE_JPEG; break;
2904 if( (vid->color_space = asset->ff_color_space) < 0 )
2905 vid->color_space = file_base->file->preferences->yuv_color_space;
2906 switch( vid->color_space ) {
2907 case BC_COLORS_BT601_NTSC: ctx->colorspace = AVCOL_SPC_SMPTE170M; break;
2908 case BC_COLORS_BT601_PAL: ctx->colorspace = AVCOL_SPC_BT470BG; break;
2909 case BC_COLORS_BT709: ctx->colorspace = AVCOL_SPC_BT709; break;
2910 case BC_COLORS_BT2020_NCL: ctx->colorspace = AVCOL_SPC_BT2020_NCL; break;
2911 case BC_COLORS_BT2020_CL: ctx->colorspace = AVCOL_SPC_BT2020_CL; break;
2913 AVPixelFormat pix_fmt = av_get_pix_fmt(asset->ff_pixel_format);
2914 if( opt_hw_dev != 0 ) {
2915 AVHWDeviceType hw_type = vid->encode_hw_activate(opt_hw_dev);
2917 case AV_HWDEVICE_TYPE_VAAPI:
2918 pix_fmt = AV_PIX_FMT_VAAPI;
2920 case AV_HWDEVICE_TYPE_NONE:
2924 if( pix_fmt == AV_PIX_FMT_NONE )
2925 pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
2926 ctx->pix_fmt = pix_fmt;
2928 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
2929 int mask_w = (1<<desc->log2_chroma_w)-1;
2930 ctx->width = (vid->width+mask_w) & ~mask_w;
2931 int mask_h = (1<<desc->log2_chroma_h)-1;
2932 ctx->height = (vid->height+mask_h) & ~mask_h;
2933 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
2934 AVRational frame_rate;
2935 if (ctx->codec->id == AV_CODEC_ID_MPEG1VIDEO ||
2936 ctx->codec->id == AV_CODEC_ID_MPEG2VIDEO)
2937 frame_rate = check_frame_rate(codec->supported_framerates, vid->frame_rate);
2939 frame_rate = av_d2q(vid->frame_rate, INT_MAX);
2940 if( !frame_rate.num || !frame_rate.den ) {
2941 eprintf(_("check_frame_rate failed %s\n"), filename);
2945 av_reduce(&frame_rate.num, &frame_rate.den,
2946 frame_rate.num, frame_rate.den, INT_MAX);
2947 ctx->framerate = (AVRational) { frame_rate.num, frame_rate.den };
2948 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
2949 st->avg_frame_rate = frame_rate;
2950 st->time_base = ctx->time_base;
2952 vid->interlaced = asset->interlace_mode == ILACE_MODE_TOP_FIRST ||
2953 asset->interlace_mode == ILACE_MODE_BOTTOM_FIRST ? 1 : 0;
2954 vid->top_field_first = asset->interlace_mode == ILACE_MODE_TOP_FIRST ? 1 : 0;
2955 switch (asset->interlace_mode) {
2956 case ILACE_MODE_TOP_FIRST:
2957 if (ctx->codec->id == AV_CODEC_ID_MJPEG)
2958 av_dict_set(&sopts, "field_order", "tt", 0);
2960 av_dict_set(&sopts, "field_order", "tb", 0);
2961 if (ctx->codec_id != AV_CODEC_ID_MJPEG)
2962 av_dict_set(&sopts, "flags", "+ilme+ildct", 0);
2964 case ILACE_MODE_BOTTOM_FIRST:
2965 if (ctx->codec->id == AV_CODEC_ID_MJPEG)
2966 av_dict_set(&sopts, "field_order", "bb", 0);
2968 av_dict_set(&sopts, "field_order", "bt", 0);
2969 if (ctx->codec_id != AV_CODEC_ID_MJPEG)
2970 av_dict_set(&sopts, "flags", "+ilme+ildct", 0);
2972 case ILACE_MODE_NOTINTERLACED: av_dict_set(&sopts, "field_order", "progressive", 0); break;
2976 eprintf(_("not audio/video, %s:%s\n"), codec_name, filename);
2981 AVDictionaryEntry *tag;
2982 if( (tag=av_dict_get(sopts, "cin_stats_filename", NULL, 0)) != 0 ) {
2983 char suffix[BCSTRLEN]; sprintf(suffix,"-%d.log",fst->fidx);
2984 fst->stats_filename = cstrcat(2, tag->value, suffix);
2986 if( (tag=av_dict_get(sopts, "flags", NULL, 0)) != 0 ) {
2987 int pass = fst->pass;
2988 char *cp = tag->value;
2990 int ch = *cp++, pfx = ch=='-' ? -1 : ch=='+' ? 1 : 0;
2991 if( !isalnum(!pfx ? ch : (ch=*cp++)) ) continue;
2992 char id[BCSTRLEN], *bp = id, *ep = bp+sizeof(id)-1;
2993 for( *bp++=ch; isalnum(ch=*cp); ++cp )
2994 if( bp < ep ) *bp++ = ch;
2996 if( !strcmp(id, "pass1") ) {
2997 pass = pfx<0 ? (pass&~1) : pfx>0 ? (pass|1) : 1;
2999 else if( !strcmp(id, "pass2") ) {
3000 pass = pfx<0 ? (pass&~2) : pfx>0 ? (pass|2) : 2;
3003 if( (fst->pass=pass) ) {
3004 if( pass & 1 ) ctx->flags |= AV_CODEC_FLAG_PASS1;
3005 if( pass & 2 ) ctx->flags |= AV_CODEC_FLAG_PASS2;
3011 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
3012 ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
3013 if( fst->stats_filename && (ret=fst->init_stats_file()) )
3014 eprintf(_("error: stats file = %s\n"), fst->stats_filename);
3017 av_dict_set(&sopts, "cin_bitrate", 0, 0);
3018 av_dict_set(&sopts, "cin_quality", 0, 0);
3020 if( !av_dict_get(sopts, "threads", NULL, 0) )
3021 ctx->thread_count = ff_cpus();
3022 ret = avcodec_open2(ctx, codec, &sopts);
3024 ret = avcodec_parameters_from_context(st->codecpar, ctx);
3026 fprintf(stderr, "Could not copy the stream parameters\n");
3029 _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
3030 ret = avcodec_copy_context(st->codec, ctx);
3031 _Pragma("GCC diagnostic warning \"-Wdeprecated-declarations\"")
3033 fprintf(stderr, "Could not copy the stream context\n");
3036 ff_err(ret,"FFMPEG::open_encoder");
3037 eprintf(_("open failed %s:%s\n"), codec_name, filename);
3043 if( !ret && fst && bsfilter[0] ) {
3044 ret = av_bsf_list_parse_str(bsfilter, &fst->bsfc);
3046 ff_err(ret,"FFMPEG::open_encoder");
3047 eprintf(_("bitstream filter failed %s:\n%s\n"), filename, bsfilter);
3058 av_dict_free(&sopts);
3062 int FFMPEG::close_encoder()
3065 if( encoding > 0 ) {
3066 av_write_trailer(fmt_ctx);
3067 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
3068 avio_closep(&fmt_ctx->pb);
3074 int FFMPEG::decode_activate()
3076 if( decoding < 0 ) {
3078 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
3079 ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
3080 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
3081 ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
3082 // set nudges for each program stream set
3083 const int64_t min_nudge = INT64_MIN+1;
3084 int npgrms = fmt_ctx->nb_programs;
3085 for( int i=0; i<npgrms; ++i ) {
3086 AVProgram *pgrm = fmt_ctx->programs[i];
3087 // first start time video stream
3088 int64_t vstart_time = min_nudge, astart_time = min_nudge;
3089 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
3090 int fidx = pgrm->stream_index[j];
3091 AVStream *st = fmt_ctx->streams[fidx];
3092 AVCodecParameters *avpar = st->codecpar;
3093 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
3094 if( st->start_time == AV_NOPTS_VALUE ) continue;
3095 if( vstart_time < st->start_time )
3096 vstart_time = st->start_time;
3099 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
3100 if( st->start_time == AV_NOPTS_VALUE ) continue;
3101 if( astart_time < st->start_time )
3102 astart_time = st->start_time;
3106 //since frame rate is much more grainy than sample rate, it is better to
3107 // align using video, so that total absolute error is minimized.
3108 int64_t nudge = vstart_time > min_nudge ? vstart_time :
3109 astart_time > min_nudge ? astart_time : AV_NOPTS_VALUE;
3110 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
3111 int fidx = pgrm->stream_index[j];
3112 AVStream *st = fmt_ctx->streams[fidx];
3113 AVCodecParameters *avpar = st->codecpar;
3114 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
3115 for( int k=0; k<ffvideo.size(); ++k ) {
3116 if( ffvideo[k]->fidx != fidx ) continue;
3117 ffvideo[k]->nudge = nudge;
3121 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
3122 for( int k=0; k<ffaudio.size(); ++k ) {
3123 if( ffaudio[k]->fidx != fidx ) continue;
3124 ffaudio[k]->nudge = nudge;
3130 // set nudges for any streams not yet set
3131 int64_t vstart_time = min_nudge, astart_time = min_nudge;
3132 int nstreams = fmt_ctx->nb_streams;
3133 for( int i=0; i<nstreams; ++i ) {
3134 AVStream *st = fmt_ctx->streams[i];
3135 AVCodecParameters *avpar = st->codecpar;
3136 switch( avpar->codec_type ) {
3137 case AVMEDIA_TYPE_VIDEO: {
3138 if( st->start_time == AV_NOPTS_VALUE ) continue;
3139 int vidx = ffvideo.size();
3140 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
3141 if( vidx < 0 ) continue;
3142 if( ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
3143 if( vstart_time < st->start_time )
3144 vstart_time = st->start_time;
3146 case AVMEDIA_TYPE_AUDIO: {
3147 if( st->start_time == AV_NOPTS_VALUE ) continue;
3148 int aidx = ffaudio.size();
3149 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
3150 if( aidx < 0 ) continue;
3151 if( ffaudio[aidx]->frame_sz < avpar->frame_size )
3152 ffaudio[aidx]->frame_sz = avpar->frame_size;
3153 if( ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
3154 if( astart_time < st->start_time )
3155 astart_time = st->start_time;
3160 int64_t nudge = vstart_time > min_nudge ? vstart_time :
3161 astart_time > min_nudge ? astart_time : 0;
3162 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
3163 if( ffvideo[vidx]->nudge == AV_NOPTS_VALUE )
3164 ffvideo[vidx]->nudge = nudge;
3166 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
3167 if( ffaudio[aidx]->nudge == AV_NOPTS_VALUE )
3168 ffaudio[aidx]->nudge = nudge;
3175 int FFMPEG::encode_activate()
3178 if( encoding < 0 ) {
3180 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
3181 (ret=avio_open(&fmt_ctx->pb, fmt_ctx->url, AVIO_FLAG_WRITE)) < 0 ) {
3182 ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
3186 if( !strcmp(file_format, "image2") ) {
3187 Asset *asset = file_base->asset;
3188 const char *filename = asset->path;
3189 FILE *fp = fopen(filename,"w");
3191 eprintf(_("Cant write image2 header file: %s\n %m"), filename);
3194 fprintf(fp, "IMAGE2\n");
3195 fprintf(fp, "# Frame rate: %f\n", asset->frame_rate);
3196 fprintf(fp, "# Width: %d\n", asset->width);
3197 fprintf(fp, "# Height: %d\n", asset->height);
3201 AVProgram *prog = av_new_program(fmt_ctx, prog_id);
3202 for( int i=0; i< ffvideo.size(); ++i )
3203 av_program_add_stream_index(fmt_ctx, prog_id, ffvideo[i]->fidx);
3204 for( int i=0; i< ffaudio.size(); ++i )
3205 av_program_add_stream_index(fmt_ctx, prog_id, ffaudio[i]->fidx);
3206 int pi = fmt_ctx->nb_programs;
3207 while( --pi >= 0 && fmt_ctx->programs[pi]->id != prog_id );
3208 AVDictionary **meta = &prog->metadata;
3209 av_dict_set(meta, "service_provider", "cin5", 0);
3210 const char *path = fmt_ctx->url, *bp = strrchr(path,'/');
3211 if( bp ) path = bp + 1;
3212 av_dict_set(meta, "title", path, 0);
3214 if( ffaudio.size() ) {
3215 const char *ep = getenv("CIN_AUDIO_LANG"), *lp = 0;
3216 if( !ep && (lp=getenv("LANG")) ) { // some are guesses
3217 static struct { const char lc[3], lng[4]; } lcode[] = {
3218 { "en", "eng" }, { "de", "ger" }, { "es", "spa" },
3219 { "eu", "bas" }, { "fr", "fre" }, { "el", "gre" },
3220 { "hi", "hin" }, { "it", "ita" }, { "ja", "jap" },
3221 { "ko", "kor" }, { "du", "dut" }, { "pl", "pol" },
3222 { "pt", "por" }, { "ru", "rus" }, { "sl", "slv" },
3223 { "uk", "ukr" }, { "vi", "vie" }, { "zh", "chi" },
3225 for( int i=sizeof(lcode)/sizeof(lcode[0]); --i>=0 && !ep; )
3226 if( !strncmp(lcode[i].lc,lp,2) ) ep = lcode[i].lng;
3228 if( !ep ) ep = "und";
3230 strncpy(lang,ep,3); lang[3] = 0;
3231 AVStream *st = ffaudio[0]->st;
3232 av_dict_set(&st->metadata,"language",lang,0);
3235 AVDictionary *fopts = 0;
3236 char option_path[BCTEXTLEN];
3237 set_option_path(option_path, "format/%s", file_format);
3238 read_options(option_path, fopts, 1);
3239 av_dict_copy(&fopts, opts, 0);
3240 if( scan_options(file_base->asset->ff_format_options, fopts, 0) ) {
3241 eprintf(_("bad format options %s\n"), file_base->asset->path);
3245 ret = avformat_write_header(fmt_ctx, &fopts);
3247 ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
3251 av_dict_free(&fopts);
3258 int FFMPEG::audio_seek(int stream, int64_t pos)
3260 int aidx = astrm_index[stream].st_idx;
3261 FFAudioStream *aud = ffaudio[aidx];
3262 aud->audio_seek(pos);
3266 int FFMPEG::video_probe(int64_t pos)
3268 int vidx = vstrm_index[0].st_idx;
3269 FFVideoStream *vid = ffvideo[vidx];
3272 int interlace1 = interlace_from_codec;
3273 //printf("interlace from codec: %i\n", interlace1);
3279 return ILACE_MODE_TOP_FIRST;
3282 return ILACE_MODE_BOTTOM_FIRST;
3283 case AV_FIELD_PROGRESSIVE:
3284 return ILACE_MODE_NOTINTERLACED;
3286 return ILACE_MODE_UNDETECTED;
3293 int FFMPEG::video_seek(int stream, int64_t pos)
3295 int vidx = vstrm_index[stream].st_idx;
3296 FFVideoStream *vid = ffvideo[vidx];
3297 vid->video_seek(pos);
3302 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
3304 if( !has_audio || chn >= astrm_index.size() ) return -1;
3305 int aidx = astrm_index[chn].st_idx;
3306 FFAudioStream *aud = ffaudio[aidx];
3307 if( aud->load(pos, len) < len ) return -1;
3308 int ch = astrm_index[chn].st_ch;
3309 int ret = aud->read(samples,len,ch);
3313 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
3315 if( !has_video || layer >= vstrm_index.size() ) return -1;
3316 int vidx = vstrm_index[layer].st_idx;
3317 FFVideoStream *vid = ffvideo[vidx];
3318 return vid->load(vframe, pos);
3322 int FFMPEG::encode(int stream, double **samples, int len)
3324 FFAudioStream *aud = ffaudio[stream];
3325 return aud->encode(samples, len);
3329 int FFMPEG::encode(int stream, VFrame *frame)
3331 FFVideoStream *vid = ffvideo[stream];
3332 return vid->encode(frame);
3335 void FFMPEG::start_muxer()
3343 void FFMPEG::stop_muxer()
3352 void FFMPEG::flow_off()
3355 flow_lock->lock("FFMPEG::flow_off");
3359 void FFMPEG::flow_on()
3363 flow_lock->unlock();
3366 void FFMPEG::flow_ctl()
3369 flow_lock->lock("FFMPEG::flow_ctl");
3370 flow_lock->unlock();
3374 int FFMPEG::mux_audio(FFrame *frm)
3376 FFStream *fst = frm->fst;
3377 AVCodecContext *ctx = fst->avctx;
3378 AVFrame *frame = *frm;
3379 AVRational tick_rate = {1, ctx->sample_rate};
3380 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
3381 int ret = fst->encode_frame(frame);
3383 ff_err(ret, "FFMPEG::mux_audio");
3384 return ret >= 0 ? 0 : 1;
3387 int FFMPEG::mux_video(FFrame *frm)
3389 FFStream *fst = frm->fst;
3390 AVFrame *frame = *frm;
3391 frame->pts = frm->position;
3392 int ret = fst->encode_frame(frame);
3394 ff_err(ret, "FFMPEG::mux_video");
3395 return ret >= 0 ? 0 : 1;
3401 double atm = -1, vtm = -1;
3402 FFrame *afrm = 0, *vfrm = 0;
3404 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
3405 FFStream *fst = ffaudio[i];
3406 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
3407 FFrame *frm = fst->frms.first;
3408 if( !frm ) { if( !done ) return; continue; }
3409 double tm = to_secs(frm->position, fst->avctx->time_base);
3410 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
3412 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
3413 FFStream *fst = ffvideo[i];
3414 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
3415 FFrame *frm = fst->frms.first;
3416 if( !frm ) { if( !done ) return; continue; }
3417 double tm = to_secs(frm->position, fst->avctx->time_base);
3418 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
3420 if( !demand ) flow_off();
3421 if( !afrm && !vfrm ) break;
3422 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
3423 vfrm->position, vfrm->fst->avctx->time_base,
3424 afrm->position, afrm->fst->avctx->time_base);
3425 FFrame *frm = v <= 0 ? vfrm : afrm;
3426 if( frm == afrm ) mux_audio(frm);
3427 if( frm == vfrm ) mux_video(frm);
3436 mux_lock->lock("FFMPEG::run");
3439 for( int i=0; i<ffaudio.size(); ++i )
3440 ffaudio[i]->drain();
3441 for( int i=0; i<ffvideo.size(); ++i )
3442 ffvideo[i]->drain();
3444 for( int i=0; i<ffaudio.size(); ++i )
3445 ffaudio[i]->flush();
3446 for( int i=0; i<ffvideo.size(); ++i )
3447 ffvideo[i]->flush();
3451 int FFMPEG::ff_total_audio_channels()
3453 return astrm_index.size();
3456 int FFMPEG::ff_total_astreams()
3458 return ffaudio.size();
3461 int FFMPEG::ff_audio_channels(int stream)
3463 return ffaudio[stream]->channels;
3466 int FFMPEG::ff_sample_rate(int stream)
3468 return ffaudio[stream]->sample_rate;
3471 const char* FFMPEG::ff_audio_format(int stream)
3473 AVStream *st = ffaudio[stream]->st;
3474 AVCodecID id = st->codecpar->codec_id;
3475 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
3476 return desc ? desc->name : _("Unknown");
3479 int FFMPEG::ff_audio_pid(int stream)
3481 return ffaudio[stream]->st->id;
3484 int64_t FFMPEG::ff_audio_samples(int stream)
3486 return ffaudio[stream]->length;
3489 // find audio astream/channels with this program,
3490 // or all program audio channels (astream=-1)
3491 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
3495 int vidx = ffvideo[vstream]->fidx;
3496 // find first program with this video stream
3497 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
3498 AVProgram *pgrm = fmt_ctx->programs[i];
3499 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
3500 int st_idx = pgrm->stream_index[j];
3501 AVStream *st = fmt_ctx->streams[st_idx];
3502 if( st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
3503 if( st_idx == vidx ) pidx = i;
3506 if( pidx < 0 ) return -1;
3508 int64_t channels = 0;
3509 AVProgram *pgrm = fmt_ctx->programs[pidx];
3510 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
3511 int aidx = pgrm->stream_index[j];
3512 AVStream *st = fmt_ctx->streams[aidx];
3513 if( st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
3514 if( astream > 0 ) { --astream; continue; }
3516 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
3517 if( ffaudio[i]->fidx == aidx ) astrm = i;
3519 if( ret < 0 ) ret = astrm;
3520 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
3521 channels |= mask << ffaudio[astrm]->channel0;
3523 if( !astream ) break;
3525 channel_mask = channels;
3530 int FFMPEG::ff_total_video_layers()
3532 return vstrm_index.size();
3535 int FFMPEG::ff_total_vstreams()
3537 return ffvideo.size();
3540 int FFMPEG::ff_video_width(int stream)
3542 FFVideoStream *vst = ffvideo[stream];
3543 return !vst->transpose ? vst->width : vst->height;
3546 int FFMPEG::ff_video_height(int stream)
3548 FFVideoStream *vst = ffvideo[stream];
3549 return !vst->transpose ? vst->height : vst->width;
3552 int FFMPEG::ff_set_video_width(int stream, int width)
3554 FFVideoStream *vst = ffvideo[stream];
3555 int *vw = !vst->transpose ? &vst->width : &vst->height, w = *vw;
3560 int FFMPEG::ff_set_video_height(int stream, int height)
3562 FFVideoStream *vst = ffvideo[stream];
3563 int *vh = !vst->transpose ? &vst->height : &vst->width, h = *vh;
3568 int FFMPEG::ff_coded_width(int stream)
3570 return ffvideo[stream]->avctx->coded_width;
3573 int FFMPEG::ff_coded_height(int stream)
3575 return ffvideo[stream]->avctx->coded_height;
3578 float FFMPEG::ff_aspect_ratio(int stream)
3580 //return ffvideo[stream]->aspect_ratio;
3581 AVFormatContext *fmt_ctx = ffvideo[stream]->fmt_ctx;
3582 AVStream *strm = ffvideo[stream]->st;
3583 AVCodecParameters *par = ffvideo[stream]->st->codecpar;
3585 AVRational sar = av_guess_sample_aspect_ratio(fmt_ctx, strm, NULL);
3587 av_reduce(&dar.num, &dar.den,
3588 par->width * sar.num,
3589 par->height * sar.den,
3593 return ffvideo[stream]->aspect_ratio;
3596 const char* FFMPEG::ff_video_codec(int stream)
3598 AVStream *st = ffvideo[stream]->st;
3599 AVCodecID id = st->codecpar->codec_id;
3600 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
3601 return desc ? desc->name : _("Unknown");
3604 int FFMPEG::ff_color_range(int stream)
3606 return ffvideo[stream]->color_range;
3609 int FFMPEG::ff_color_space(int stream)
3611 return ffvideo[stream]->color_space;
3614 double FFMPEG::ff_frame_rate(int stream)
3616 return ffvideo[stream]->frame_rate;
3619 int64_t FFMPEG::ff_video_frames(int stream)
3621 return ffvideo[stream]->length;
3624 int FFMPEG::ff_video_pid(int stream)
3626 return ffvideo[stream]->st->id;
3629 int FFMPEG::ff_video_mpeg_color_range(int stream)
3631 return ffvideo[stream]->st->codecpar->color_range == AVCOL_RANGE_MPEG ? 1 : 0;
3634 int FFMPEG::ff_interlace(int stream)
3636 // https://ffmpeg.org/doxygen/trunk/structAVCodecParserContext.html
3637 /* reads from demuxer because codec frame not ready */
3638 int interlace0 = ffvideo[stream]->st->codecpar->field_order;
3644 return ILACE_MODE_TOP_FIRST;
3647 return ILACE_MODE_BOTTOM_FIRST;
3648 case AV_FIELD_PROGRESSIVE:
3649 return ILACE_MODE_NOTINTERLACED;
3651 return ILACE_MODE_UNDETECTED;
3658 int FFMPEG::ff_cpus()
3660 return !file_base ? 1 : file_base->file->cpus;
3663 const char *FFMPEG::ff_hw_dev()
3665 return &file_base->file->preferences->use_hw_dev[0];
3668 Preferences *FFMPEG::ff_prefs()
3670 return !file_base ? 0 : file_base->file->preferences;
3673 double FFVideoStream::get_rotation_angle()
3676 int *matrix = (int*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX, &size);
3677 int len = size/sizeof(*matrix);
3678 if( !matrix || len < 5 ) return 0;
3679 const double s = 1/65536.;
3680 double theta = (!matrix[0] && !matrix[3]) || (!matrix[1] && !matrix[4]) ? 0 :
3681 atan2( s*matrix[1] / hypot(s*matrix[1], s*matrix[4]),
3682 s*matrix[0] / hypot(s*matrix[0], s*matrix[3])) * 180/M_PI;
3686 int FFVideoStream::flip(double theta)
3690 Preferences *preferences = ffmpeg->ff_prefs();
3691 if( !preferences || !preferences->auto_rotate ) return ret;
3692 double tolerance = 1;
3693 if( fabs(theta-0) < tolerance ) return ret;
3694 if( (theta=fmod(theta, 360)) < 0 ) theta += 360;
3695 if( fabs(theta-90) < tolerance ) {
3696 if( (ret = insert_filter("transpose", "clock")) < 0 )
3700 else if( fabs(theta-180) < tolerance ) {
3701 if( (ret=insert_filter("hflip", 0)) < 0 )
3703 if( (ret=insert_filter("vflip", 0)) < 0 )
3706 else if (fabs(theta-270) < tolerance ) {
3707 if( (ret=insert_filter("transpose", "cclock")) < 0 )
3712 char angle[BCSTRLEN];
3713 sprintf(angle, "%f", theta*M_PI/180.);
3714 if( (ret=insert_filter("rotate", angle)) < 0 )
3720 int FFVideoStream::create_filter(const char *filter_spec)
3722 double theta = get_rotation_angle();
3723 if( !theta && !filter_spec )
3725 avfilter_register_all();
3727 const char *sp = filter_spec;
3728 char filter_name[BCSTRLEN], *np = filter_name;
3729 int i = sizeof(filter_name);
3730 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
3732 const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
3733 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_VIDEO ) {
3734 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
3738 AVCodecParameters *avpar = st->codecpar;
3739 int sa_num = avpar->sample_aspect_ratio.num;
3740 if( !sa_num ) sa_num = 1;
3741 int sa_den = avpar->sample_aspect_ratio.den;
3742 if( !sa_den ) sa_num = 1;
3744 int ret = 0; char args[BCTEXTLEN];
3745 AVPixelFormat pix_fmt = (AVPixelFormat)avpar->format;
3746 snprintf(args, sizeof(args),
3747 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
3748 avpar->width, avpar->height, (int)pix_fmt,
3749 st->time_base.num, st->time_base.den, sa_num, sa_den);
3752 ret = insert_filter("buffer", args, "in");
3753 buffersrc_ctx = filt_ctx;
3757 AVFilterContext *fsrc = filt_ctx;
3760 ret = insert_filter("buffersink", 0, "out");
3761 buffersink_ctx = filt_ctx;
3764 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
3765 (uint8_t*)&pix_fmt, sizeof(pix_fmt),
3766 AV_OPT_SEARCH_CHILDREN);
3769 ret = config_filters(filter_spec, fsrc);
3771 ff_err(ret, "FFVideoStream::create_filter");
3772 return ret >= 0 ? 0 : -1;
3775 int FFAudioStream::create_filter(const char *filter_spec)
3779 avfilter_register_all();
3781 const char *sp = filter_spec;
3782 char filter_name[BCSTRLEN], *np = filter_name;
3783 int i = sizeof(filter_name);
3784 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
3786 const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
3787 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_AUDIO ) {
3788 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
3792 int ret = 0; char args[BCTEXTLEN];
3793 AVCodecParameters *avpar = st->codecpar;
3794 AVSampleFormat sample_fmt = (AVSampleFormat)avpar->format;
3795 snprintf(args, sizeof(args),
3796 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
3797 st->time_base.num, st->time_base.den, avpar->sample_rate,
3798 av_get_sample_fmt_name(sample_fmt), avpar->channel_layout);
3801 ret = insert_filter("abuffer", args, "in");
3802 buffersrc_ctx = filt_ctx;
3804 AVFilterContext *fsrc = filt_ctx;
3807 ret = insert_filter("abuffersink", 0, "out");
3808 buffersink_ctx = filt_ctx;
3811 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
3812 (uint8_t*)&sample_fmt, sizeof(sample_fmt),
3813 AV_OPT_SEARCH_CHILDREN);
3815 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
3816 (uint8_t*)&avpar->channel_layout,
3817 sizeof(avpar->channel_layout), AV_OPT_SEARCH_CHILDREN);
3819 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
3820 (uint8_t*)&sample_rate, sizeof(sample_rate),
3821 AV_OPT_SEARCH_CHILDREN);
3823 ret = config_filters(filter_spec, fsrc);
3825 ff_err(ret, "FFAudioStream::create_filter");
3826 return ret >= 0 ? 0 : -1;
3829 int FFStream::insert_filter(const char *name, const char *arg, const char *inst_name)
3831 const AVFilter *filter = avfilter_get_by_name(name);
3832 if( !filter ) return -1;
3833 char filt_inst[BCSTRLEN];
3835 snprintf(filt_inst, sizeof(filt_inst), "%s_%d", name, ++filt_id);
3836 inst_name = filt_inst;
3839 filter_graph = avfilter_graph_alloc();
3840 AVFilterContext *fctx = 0;
3841 int ret = avfilter_graph_create_filter(&fctx,
3842 filter, inst_name, arg, NULL, filter_graph);
3843 if( ret >= 0 && filt_ctx )
3844 ret = avfilter_link(filt_ctx, 0, fctx, 0);
3848 avfilter_free(fctx);
3852 int FFStream::config_filters(const char *filter_spec, AVFilterContext *fsrc)
3855 AVFilterContext *fsink = buffersink_ctx;
3857 /* Endpoints for the filter graph. */
3858 AVFilterInOut *outputs = avfilter_inout_alloc();
3859 AVFilterInOut *inputs = avfilter_inout_alloc();
3860 if( !inputs || !outputs ) ret = -1;
3862 outputs->filter_ctx = fsrc;
3863 outputs->pad_idx = 0;
3865 if( !(outputs->name = av_strdup(fsrc->name)) ) ret = -1;
3868 inputs->filter_ctx = fsink;
3869 inputs->pad_idx = 0;
3871 if( !(inputs->name = av_strdup(fsink->name)) ) ret = -1;
3874 int len = strlen(fsrc->name)+2 + strlen(filter_spec) + 1;
3875 char spec[len]; sprintf(spec, "[%s]%s", fsrc->name, filter_spec);
3876 ret = avfilter_graph_parse_ptr(filter_graph, spec,
3877 &inputs, &outputs, NULL);
3879 avfilter_inout_free(&inputs);
3880 avfilter_inout_free(&outputs);
3883 ret = avfilter_link(fsrc, 0, fsink, 0);
3885 ret = avfilter_graph_config(filter_graph, NULL);
3887 ff_err(ret, "FFStream::create_filter");
3888 avfilter_graph_free(&filter_graph);
3895 AVCodecContext *FFMPEG::activate_decoder(AVStream *st)
3897 AVDictionary *copts = 0;
3898 av_dict_copy(&copts, opts, 0);
3899 AVCodecID codec_id = st->codecpar->codec_id;
3900 AVCodec *decoder = 0;
3901 switch( st->codecpar->codec_type ) {
3902 case AVMEDIA_TYPE_VIDEO:
3903 if( opt_video_decoder )
3904 decoder = avcodec_find_decoder_by_name(opt_video_decoder);
3906 video_codec_remaps.update(codec_id, decoder);
3908 case AVMEDIA_TYPE_AUDIO:
3909 if( opt_audio_decoder )
3910 decoder = avcodec_find_decoder_by_name(opt_audio_decoder);
3912 audio_codec_remaps.update(codec_id, decoder);
3917 if( !decoder && !(decoder = avcodec_find_decoder(codec_id)) ) {
3918 eprintf(_("cant find decoder codec %d\n"), (int)codec_id);
3921 AVCodecContext *avctx = avcodec_alloc_context3(decoder);
3923 eprintf(_("cant allocate codec context\n"));
3926 avcodec_parameters_to_context(avctx, st->codecpar);
3927 if( !av_dict_get(copts, "threads", NULL, 0) )
3928 avctx->thread_count = ff_cpus();
3929 int ret = avcodec_open2(avctx, decoder, &copts);
3930 av_dict_free(&copts);
3932 avcodec_free_context(&avctx);
3938 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
3941 av_init_packet(&pkt);
3942 AVFrame *frame = av_frame_alloc();
3944 fprintf(stderr,"FFMPEG::scan: ");
3945 fprintf(stderr,_("av_frame_alloc failed\n"));
3946 fprintf(stderr,"FFMPEG::scan:file=%s\n", file_base->asset->path);
3950 index_state->add_video_markers(ffvideo.size());
3951 index_state->add_audio_markers(ffaudio.size());
3953 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
3954 AVStream *st = fmt_ctx->streams[i];
3955 AVCodecContext *avctx = activate_decoder(st);
3957 AVCodecParameters *avpar = st->codecpar;
3958 switch( avpar->codec_type ) {
3959 case AVMEDIA_TYPE_VIDEO: {
3960 int vidx = ffvideo.size();
3961 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
3962 if( vidx < 0 ) break;
3963 ffvideo[vidx]->avctx = avctx;
3965 case AVMEDIA_TYPE_AUDIO: {
3966 int aidx = ffaudio.size();
3967 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3968 if( aidx < 0 ) break;
3969 ffaudio[aidx]->avctx = avctx;
3974 fprintf(stderr,"FFMPEG::scan: ");
3975 fprintf(stderr,_("codec open failed\n"));
3976 fprintf(stderr,"FFMPEG::scan:file=%s\n", file_base->asset->path);
3977 avcodec_free_context(&avctx);
3981 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
3982 AVStream *st = fmt_ctx->streams[i];
3983 AVCodecParameters *avpar = st->codecpar;
3984 if( avpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
3985 int64_t tstmp = st->start_time;
3986 if( tstmp == AV_NOPTS_VALUE ) continue;
3987 int aidx = ffaudio.size();
3988 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3989 if( aidx < 0 ) continue;
3990 FFAudioStream *aud = ffaudio[aidx];
3991 tstmp -= aud->nudge;
3992 double secs = to_secs(tstmp, st->time_base);
3993 aud->curr_pos = secs * aud->sample_rate + 0.5;
3997 for( int64_t count=0; !*canceled; ++count ) {
3998 av_packet_unref(&pkt);
3999 pkt.data = 0; pkt.size = 0;
4001 int ret = av_read_frame(fmt_ctx, &pkt);
4003 if( ret == AVERROR_EOF ) break;
4004 if( ++errs > 100 ) {
4005 ff_err(ret,_("over 100 read_frame errs\n"));
4010 if( !pkt.data ) continue;
4011 int i = pkt.stream_index;
4012 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
4013 AVStream *st = fmt_ctx->streams[i];
4014 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
4016 AVCodecParameters *avpar = st->codecpar;
4017 switch( avpar->codec_type ) {
4018 case AVMEDIA_TYPE_VIDEO: {
4019 int vidx = ffvideo.size();
4020 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
4021 if( vidx < 0 ) break;
4022 FFVideoStream *vid = ffvideo[vidx];
4023 if( !vid->avctx ) break;
4024 int64_t tstmp = pkt.pts;
4025 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
4026 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
4027 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
4028 double secs = to_secs(tstmp, st->time_base);
4029 int64_t frm = secs * vid->frame_rate + 0.5;
4030 if( frm < 0 ) frm = 0;
4031 index_state->put_video_mark(vidx, frm, pkt.pos);
4034 ret = avcodec_send_packet(vid->avctx, pkt);
4035 if( ret < 0 ) break;
4036 while( (ret=vid->decode_frame(frame)) > 0 ) {}
4039 case AVMEDIA_TYPE_AUDIO: {
4040 int aidx = ffaudio.size();
4041 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
4042 if( aidx < 0 ) break;
4043 FFAudioStream *aud = ffaudio[aidx];
4044 if( !aud->avctx ) break;
4045 int64_t tstmp = pkt.pts;
4046 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
4047 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
4048 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
4049 double secs = to_secs(tstmp, st->time_base);
4050 int64_t sample = secs * aud->sample_rate + 0.5;
4052 index_state->put_audio_mark(aidx, sample, pkt.pos);
4054 ret = avcodec_send_packet(aud->avctx, &pkt);
4055 if( ret < 0 ) break;
4056 int ch = aud->channel0, nch = aud->channels;
4057 int64_t pos = index_state->pos(ch);
4058 if( pos != aud->curr_pos ) {
4059 if( abs(pos-aud->curr_pos) > 1 )
4060 printf("audio%d pad %jd %jd (%jd)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
4061 index_state->pad_data(ch, nch, aud->curr_pos);
4063 while( (ret=aud->decode_frame(frame)) > 0 ) {
4064 //if( frame->channels != nch ) break;
4065 aud->init_swr(frame->channels, frame->format, frame->sample_rate);
4067 int len = aud->get_samples(samples,
4068 &frame->extended_data[0], frame->nb_samples);
4069 pos = aud->curr_pos;
4070 if( (aud->curr_pos += len) >= 0 ) {
4072 samples += -pos * nch;
4073 len = aud->curr_pos;
4075 for( int i=0; i<nch; ++i )
4076 index_state->put_data(ch+i,nch,samples+i,len);
4083 av_frame_free(&frame);
4087 void FFStream::load_markers(IndexMarks &marks, double rate)
4090 int64_t sz = marks.size();
4091 int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
4092 int nb_ent = st->nb_index_entries;
4093 // some formats already have an index
4095 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
4096 int64_t tstmp = ep->timestamp;
4097 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
4098 double secs = ffmpeg->to_secs(tstmp, st->time_base);
4099 int64_t no = secs * rate;
4100 while( in < sz && marks[in].no <= no ) ++in;
4102 int64_t len = sz - in;
4103 int64_t count = max_entries - nb_ent;
4104 if( count > len ) count = len;
4105 for( int i=0; i<count; ++i ) {
4106 int k = in + i * len / count;
4107 int64_t no = marks[k].no, pos = marks[k].pos;
4108 double secs = (double)no / rate;
4109 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
4110 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
4111 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);
4117 * 1) if the format context has a timecode
4118 * return fmt_ctx->timecode - 0
4119 * 2) if the layer/channel has a timecode
4120 * return st->timecode - (start_time-nudge)
4121 * 3) find the 1st program with stream, find 1st program video stream,
4122 * if video stream has a timecode, return st->timecode - (start_time-nudge)
4123 * 4) find timecode in any stream, return st->timecode
4124 * 5) read 100 packets, save ofs=pkt.pts*st->time_base - st->nudge:
4125 * decode frame for video stream of 1st program
4126 * if frame->timecode has a timecode, return frame->timecode - ofs
4127 * if side_data has gop timecode, return gop->timecode - ofs
4128 * if side_data has smpte timecode, return smpte->timecode - ofs
4129 * 6) if the filename/url scans *date_time.ext, return date_time
4130 * 7) if stat works on the filename/url, return mtime
4131 * 8) return -1 failure
4133 double FFMPEG::get_initial_timecode(int data_type, int channel, double frame_rate)
4135 AVRational rate = check_frame_rate(0, frame_rate);
4136 if( !rate.num ) return -1;
4137 // format context timecode
4138 AVDictionaryEntry *tc = av_dict_get(fmt_ctx->metadata, "timecode", 0, 0);
4139 if( tc ) return ff_get_timecode(tc->value, rate, 0);
4141 if( open_decoder() ) return -1;
4144 int codec_type = -1, fidx = -1;
4145 switch( data_type ) {
4147 codec_type = AVMEDIA_TYPE_AUDIO;
4148 int aidx = astrm_index[channel].st_idx;
4149 FFAudioStream *aud = ffaudio[aidx];
4153 AVDictionaryEntry *tref = av_dict_get(fmt_ctx->metadata, "time_reference", 0, 0);
4154 if( tref && aud && aud->sample_rate )
4155 return strtod(tref->value, 0) / aud->sample_rate;
4158 codec_type = AVMEDIA_TYPE_VIDEO;
4159 int vidx = vstrm_index[channel].st_idx;
4160 FFVideoStream *vid = ffvideo[vidx];
4166 if( codec_type < 0 ) return -1;
4168 tc = av_dict_get(st->metadata, "timecode", 0, 0);
4171 // find first program which references this stream
4173 for( int i=0, m=fmt_ctx->nb_programs; pidx<0 && i<m; ++i ) {
4174 AVProgram *pgrm = fmt_ctx->programs[i];
4175 for( int j=0, n=pgrm->nb_stream_indexes; j<n; ++j ) {
4176 int st_idx = pgrm->stream_index[j];
4177 if( st_idx == fidx ) { pidx = i; break; }
4182 AVProgram *pgrm = fmt_ctx->programs[pidx];
4183 for( int j=0, n=pgrm->nb_stream_indexes; j<n; ++j ) {
4184 int st_idx = pgrm->stream_index[j];
4185 AVStream *tst = fmt_ctx->streams[st_idx];
4186 if( !tst ) continue;
4187 if( tst->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
4188 st = tst; fidx = st_idx;
4194 for( int i=0, n=fmt_ctx->nb_streams; i<n; ++i ) {
4195 AVStream *tst = fmt_ctx->streams[i];
4196 if( !tst ) continue;
4197 if( tst->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
4204 tc = av_dict_get(st->metadata, "timecode", 0, 0);
4208 // any timecode, includes -data- streams
4209 for( int i=0, n=fmt_ctx->nb_streams; i<n; ++i ) {
4210 AVStream *tst = fmt_ctx->streams[i];
4211 if( !tst ) continue;
4212 if( (tc = av_dict_get(tst->metadata, "timecode", 0, 0)) ) {
4219 if( st && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
4220 if( st->r_frame_rate.num && st->r_frame_rate.den )
4221 rate = st->r_frame_rate;
4222 nudge = st->start_time;
4223 for( int i=0; i<ffvideo.size(); ++i ) {
4224 if( ffvideo[i]->st == st ) {
4225 nudge = ffvideo[i]->nudge;
4231 if( tc ) { // return timecode
4232 double secs = st->start_time == AV_NOPTS_VALUE ? 0 :
4233 to_secs(st->start_time - nudge, st->time_base);
4234 return ff_get_timecode(tc->value, rate, secs);
4237 if( !st || fidx < 0 ) return -1;
4240 AVCodecContext *av_ctx = activate_decoder(st);
4242 fprintf(stderr,"activate_decoder failed\n");
4245 avCodecContext avctx(av_ctx); // auto deletes
4246 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO &&
4247 avctx->framerate.num && avctx->framerate.den )
4248 rate = avctx->framerate;
4250 avPacket pkt; // auto deletes
4251 avFrame frame; // auto deletes
4253 fprintf(stderr,"av_frame_alloc failed\n");
4257 int64_t max_packets = 100;
4258 char tcbuf[AV_TIMECODE_STR_SIZE];
4260 for( int64_t count=0; count<max_packets; ++count ) {
4261 av_packet_unref(pkt);
4262 pkt->data = 0; pkt->size = 0;
4264 int ret = av_read_frame(fmt_ctx, pkt);
4266 if( ret == AVERROR_EOF ) break;
4267 if( ++errs > 100 ) {
4268 fprintf(stderr,"over 100 read_frame errs\n");
4273 if( !pkt->data ) continue;
4274 int i = pkt->stream_index;
4275 if( i != fidx ) continue;
4276 int64_t tstmp = pkt->pts;
4277 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt->dts;
4278 double secs = to_secs(tstmp - nudge, st->time_base);
4279 ret = avcodec_send_packet(avctx, pkt);
4280 if( ret < 0 ) return -1;
4282 while( (ret = avcodec_receive_frame(avctx, frame)) >= 0 ) {
4283 if( (tc = av_dict_get(frame->metadata, "timecode", 0, 0)) )
4284 return ff_get_timecode(tc->value, rate, secs);
4285 int k = frame->nb_side_data;
4286 AVFrameSideData *side_data = 0;
4288 side_data = frame->side_data[k];
4289 switch( side_data->type ) {
4290 case AV_FRAME_DATA_GOP_TIMECODE: {
4291 int64_t data = *(int64_t *)side_data->data;
4292 int sz = sizeof(data);
4293 if( side_data->size >= sz ) {
4294 av_timecode_make_mpeg_tc_string(tcbuf, data);
4295 return ff_get_timecode(tcbuf, rate, secs);
4298 case AV_FRAME_DATA_S12M_TIMECODE: {
4299 uint32_t *data = (uint32_t *)side_data->data;
4300 int n = data[0], sz = (n+1)*sizeof(*data);
4301 if( side_data->size >= sz ) {
4302 av_timecode_make_smpte_tc_string(tcbuf, data[n], 0);
4303 return ff_get_timecode(tcbuf, rate, secs);
4312 char *path = fmt_ctx->url;
4313 char *bp = strrchr(path, '/');
4314 if( !bp ) bp = path; else ++bp;
4315 char *cp = strrchr(bp, '.');
4316 if( cp && (cp-=(8+1+6)) >= bp ) {
4318 int year,mon,day, hour,min,sec, frm=0;
4319 if( sscanf(cp,"%4d%2d%2d%[_-]%2d%2d%2d",
4320 &year,&mon,&day, sep, &hour,&min,&sec) == 7 ) {
4322 // year>=1970,mon=1..12,day=1..31, hour=0..23,min=0..59,sec=0..60
4323 if( (ch=='_' || ch=='-' ) &&
4324 year >= 1970 && mon>=1 && mon<=12 && day>=1 && day<=31 &&
4325 hour>=0 && hour<24 && min>=0 && min<60 && sec>=0 && sec<=60 ) {
4326 sprintf(tcbuf,"%d:%02d:%02d:%02d", hour,min,sec, frm);
4327 return ff_get_timecode(tcbuf, rate, 0);
4332 if( stat(path, &tst) >= 0 ) {
4333 time_t t = (time_t)tst.st_mtim.tv_sec;
4335 localtime_r(&t, &tm);
4336 int64_t us = tst.st_mtim.tv_nsec / 1000;
4337 int frm = us/1000000. * frame_rate;
4338 sprintf(tcbuf,"%d:%02d:%02d:%02d", tm.tm_hour, tm.tm_min, tm.tm_sec, frm);
4339 return ff_get_timecode(tcbuf, rate, 0);
4344 double FFMPEG::ff_get_timecode(char *str, AVRational rate, double pos)
4347 if( av_timecode_init_from_string(&tc, rate, str, fmt_ctx) )
4349 double secs = (double)tc.start / tc.fps - pos;
4350 if( secs < 0 ) secs = 0;
4354 double FFMPEG::get_timecode(const char *path, int data_type, int channel, double rate)
4357 if( ffmpeg.init_decoder(path) ) return -1;
4358 return ffmpeg.get_initial_timecode(data_type, channel, rate);