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;
1252 int FFVideoStream::load(VFrame *vframe, int64_t pos)
1254 int ret = video_seek(pos);
1255 if( ret < 0 ) return -1;
1256 if( !frame && !(frame=av_frame_alloc()) ) {
1257 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
1262 int i = MAX_RETRY + pos - curr_pos;
1263 int64_t cache_start = 0;
1264 while( ret>=0 && !flushed && curr_pos<=pos && --i>=0 ) {
1265 ret = read_frame(frame);
1267 if( frame->key_frame && seeking < 0 ) {
1268 int use_cache = ffmpeg->get_use_cache();
1269 if( use_cache < 0 ) {
1270 // for reverse read, reload file frame_cache from keyframe to pos
1271 ffmpeg->purge_cache();
1272 int count = preferences->cache_size /
1273 vframe->get_data_size() / 2; // try to burn only 1/2 of cache
1274 cache_start = pos - count + 1;
1280 if( seeking > 0 && curr_pos >= cache_start && curr_pos < pos ) {
1281 int vw =vframe->get_w(), vh = vframe->get_h();
1282 int vcolor_model = vframe->get_color_model();
1283 // do not use shm here, puts too much pressure on 32bit systems
1284 VFrame *cache_frame = new VFrame(vw, vh, vcolor_model, 0);
1285 ret = convert_cmodel(cache_frame, frame);
1287 ffmpeg->put_cache_frame(cache_frame, curr_pos);
1293 if( frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0 )
1296 ret = convert_cmodel(vframe, frame);
1298 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
1302 int FFVideoStream::video_seek(int64_t pos)
1304 if( decode_activate() <= 0 ) return -1;
1305 if( !st->codecpar ) return -1;
1306 if( pos == curr_pos-1 && !seeked ) return 0;
1307 // if close enough, just read up to current
1308 int gop = avctx->gop_size;
1309 if( gop < 4 ) gop = 4;
1310 if( gop > 64 ) gop = 64;
1311 int read_limit = curr_pos + 3*gop;
1312 if( pos >= curr_pos && pos <= read_limit ) return 0;
1313 // guarentee preload more than 2*gop frames
1314 if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
1318 int FFVideoStream::init_frame(AVFrame *picture)
1320 switch( avctx->pix_fmt ) {
1321 case AV_PIX_FMT_VAAPI:
1322 picture->format = AV_PIX_FMT_NV12;
1325 picture->format = avctx->pix_fmt;
1328 picture->width = avctx->width;
1329 picture->height = avctx->height;
1330 int ret = av_frame_get_buffer(picture, 32);
1334 int FFVideoStream::convert_hw_frame(AVFrame *ifrm, AVFrame *ofrm)
1336 AVPixelFormat ifmt = (AVPixelFormat)ifrm->format;
1337 AVPixelFormat ofmt = (AVPixelFormat)st->codecpar->format;
1338 ofrm->width = ifrm->width;
1339 ofrm->height = ifrm->height;
1340 ofrm->format = ofmt;
1341 int ret = av_frame_get_buffer(ofrm, 32);
1343 ff_err(ret, "FFVideoStream::convert_hw_frame:"
1344 " av_frame_get_buffer failed\n");
1347 fconvert_ctx = sws_getCachedContext(fconvert_ctx,
1348 ifrm->width, ifrm->height, ifmt,
1349 ofrm->width, ofrm->height, ofmt,
1350 SWS_POINT, NULL, NULL, NULL);
1351 if( !fconvert_ctx ) {
1352 ff_err(AVERROR(EINVAL), "FFVideoStream::convert_hw_frame:"
1353 " sws_getCachedContext() failed\n");
1356 int codec_range = st->codecpar->color_range;
1357 int codec_space = st->codecpar->color_space;
1358 const int *codec_table = sws_getCoefficients(codec_space);
1359 int *inv_table, *table, src_range, dst_range;
1360 int brightness, contrast, saturation;
1361 if( !sws_getColorspaceDetails(fconvert_ctx,
1362 &inv_table, &src_range, &table, &dst_range,
1363 &brightness, &contrast, &saturation) ) {
1364 if( src_range != codec_range || dst_range != codec_range ||
1365 inv_table != codec_table || table != codec_table )
1366 sws_setColorspaceDetails(fconvert_ctx,
1367 codec_table, codec_range, codec_table, codec_range,
1368 brightness, contrast, saturation);
1370 ret = sws_scale(fconvert_ctx,
1371 ifrm->data, ifrm->linesize, 0, ifrm->height,
1372 ofrm->data, ofrm->linesize);
1374 ff_err(ret, "FFVideoStream::convert_hw_frame:"
1375 " sws_scale() failed\nfile: %s\n",
1376 ffmpeg->fmt_ctx->url);
1382 int FFVideoStream::load_filter(AVFrame *frame)
1384 AVPixelFormat pix_fmt = (AVPixelFormat)frame->format;
1385 if( pix_fmt == hw_pixfmt ) {
1386 AVFrame *hw_frame = this->frame;
1387 av_frame_unref(hw_frame);
1388 int ret = av_hwframe_transfer_data(hw_frame, frame, 0);
1390 eprintf(_("Error retrieving data from GPU to CPU\nfile: %s\n"),
1391 ffmpeg->fmt_ctx->url);
1394 av_frame_unref(frame);
1395 ret = convert_hw_frame(hw_frame, frame);
1397 eprintf(_("Error converting data from GPU to CPU\nfile: %s\n"),
1398 ffmpeg->fmt_ctx->url);
1401 av_frame_unref(hw_frame);
1403 return FFStream::load_filter(frame);
1406 int FFVideoStream::encode(VFrame *vframe)
1408 if( encode_activate() <= 0 ) return -1;
1410 FFrame *picture = new FFrame(this);
1411 int ret = picture->initted();
1413 AVFrame *frame = *picture;
1414 frame->pts = curr_pos;
1415 ret = convert_pixfmt(vframe, frame);
1417 if( ret >= 0 && avctx->hw_frames_ctx )
1418 encode_hw_write(picture);
1420 picture->queue(curr_pos);
1424 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
1427 return ret >= 0 ? 0 : 1;
1430 int FFVideoStream::drain()
1436 int FFVideoStream::encode_frame(AVFrame *frame)
1439 frame->interlaced_frame = interlaced;
1440 frame->top_field_first = top_field_first;
1442 if( frame && frame->format == AV_PIX_FMT_VAAPI ) { // ugly
1443 int ret = avcodec_send_frame(avctx, frame);
1444 for( int retry=MAX_RETRY; !ret && --retry>=0; ) {
1445 FFPacket pkt; av_init_packet(pkt);
1446 pkt->data = NULL; pkt->size = 0;
1447 if( (ret=avcodec_receive_packet(avctx, pkt)) < 0 ) {
1448 if( ret == AVERROR(EAGAIN) ) ret = 0; // weird
1451 ret = write_packet(pkt);
1452 pkt->stream_index = 0;
1453 av_packet_unref(pkt);
1456 ff_err(ret, "FFStream::encode_frame: vaapi encode failed.\nfile: %s\n",
1457 ffmpeg->fmt_ctx->url);
1462 return FFStream::encode_frame(frame);
1465 int FFVideoStream::write_packet(FFPacket &pkt)
1467 if( !(ffmpeg->fmt_ctx->oformat->flags & AVFMT_VARIABLE_FPS) )
1469 return FFStream::write_packet(pkt);
1472 AVPixelFormat FFVideoConvert::color_model_to_pix_fmt(int color_model)
1474 switch( color_model ) {
1475 case BC_YUV422: return AV_PIX_FMT_YUYV422;
1476 case BC_RGB888: return AV_PIX_FMT_RGB24;
1477 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
1478 case BC_BGR8888: return AV_PIX_FMT_BGR0;
1479 case BC_BGR888: return AV_PIX_FMT_BGR24;
1480 case BC_ARGB8888: return AV_PIX_FMT_ARGB;
1481 case BC_ABGR8888: return AV_PIX_FMT_ABGR;
1482 case BC_RGB8: return AV_PIX_FMT_RGB8;
1483 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
1484 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
1485 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
1486 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
1487 case BC_RGB565: return AV_PIX_FMT_RGB565;
1488 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
1489 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
1490 case BC_AYUV16161616: return AV_PIX_FMT_AYUV64LE;
1491 case BC_GBRP: return AV_PIX_FMT_GBRP;
1495 return AV_PIX_FMT_NB;
1498 int FFVideoConvert::pix_fmt_to_color_model(AVPixelFormat pix_fmt)
1501 case AV_PIX_FMT_YUYV422: return BC_YUV422;
1502 case AV_PIX_FMT_RGB24: return BC_RGB888;
1503 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
1504 case AV_PIX_FMT_BGR0: return BC_BGR8888;
1505 case AV_PIX_FMT_BGR24: return BC_BGR888;
1506 case AV_PIX_FMT_ARGB: return BC_ARGB8888;
1507 case AV_PIX_FMT_ABGR: return BC_ABGR8888;
1508 case AV_PIX_FMT_RGB8: return BC_RGB8;
1509 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
1510 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
1511 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
1512 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
1513 case AV_PIX_FMT_RGB565: return BC_RGB565;
1514 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
1515 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
1516 case AV_PIX_FMT_AYUV64LE: return BC_AYUV16161616;
1517 case AV_PIX_FMT_GBRP: return BC_GBRP;
1524 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip)
1526 AVFrame *ipic = av_frame_alloc();
1527 int ret = convert_picture_vframe(frame, ip, ipic);
1528 av_frame_free(&ipic);
1532 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip, AVFrame *ipic)
1533 { // picture = vframe
1534 int cmodel = frame->get_color_model();
1535 AVPixelFormat ofmt = color_model_to_pix_fmt(cmodel);
1536 if( ofmt == AV_PIX_FMT_NB ) return -1;
1537 int size = av_image_fill_arrays(ipic->data, ipic->linesize,
1538 frame->get_data(), ofmt, frame->get_w(), frame->get_h(), 1);
1539 if( size < 0 ) return -1;
1541 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1542 int ysz = bpp * frame->get_w(), usz = ysz;
1552 // override av_image_fill_arrays() for planar types
1553 ipic->data[0] = frame->get_y(); ipic->linesize[0] = ysz;
1554 ipic->data[1] = frame->get_u(); ipic->linesize[1] = usz;
1555 ipic->data[2] = frame->get_v(); ipic->linesize[2] = usz;
1558 ipic->data[0] = frame->get_data();
1559 ipic->linesize[0] = frame->get_bytes_per_line();
1563 AVPixelFormat pix_fmt = (AVPixelFormat)ip->format;
1564 FFVideoStream *vid =(FFVideoStream *)this;
1565 if( pix_fmt == vid->hw_pixfmt ) {
1567 if( !sw_frame && !(sw_frame=av_frame_alloc()) )
1568 ret = AVERROR(ENOMEM);
1570 ret = av_hwframe_transfer_data(sw_frame, ip, 0);
1572 pix_fmt = (AVPixelFormat)ip->format;
1575 eprintf(_("Error retrieving data from GPU to CPU\nfile: %s\n"),
1576 vid->ffmpeg->fmt_ctx->url);
1580 convert_ctx = sws_getCachedContext(convert_ctx, ip->width, ip->height, pix_fmt,
1581 frame->get_w(), frame->get_h(), ofmt, SWS_POINT, NULL, NULL, NULL);
1582 if( !convert_ctx ) {
1583 fprintf(stderr, "FFVideoConvert::convert_picture_frame:"
1584 " sws_getCachedContext() failed\n");
1588 int color_range = 0;
1589 switch( preferences->yuv_color_range ) {
1590 case BC_COLORS_JPEG: color_range = 1; break;
1591 case BC_COLORS_MPEG: color_range = 0; break;
1593 int color_space = SWS_CS_ITU601;
1594 switch( preferences->yuv_color_space ) {
1595 case BC_COLORS_BT601_PAL: color_space = SWS_CS_ITU601; break;
1596 case BC_COLORS_BT601_NTSC: color_space = SWS_CS_SMPTE170M; break;
1597 case BC_COLORS_BT709: color_space = SWS_CS_ITU709; break;
1598 case BC_COLORS_BT2020_NCL:
1599 case BC_COLORS_BT2020_CL: color_space = SWS_CS_BT2020; break;
1601 const int *color_table = sws_getCoefficients(color_space);
1603 int *inv_table, *table, src_range, dst_range;
1604 int brightness, contrast, saturation;
1605 if( !sws_getColorspaceDetails(convert_ctx,
1606 &inv_table, &src_range, &table, &dst_range,
1607 &brightness, &contrast, &saturation) ) {
1608 if( src_range != color_range || dst_range != color_range ||
1609 inv_table != color_table || table != color_table )
1610 sws_setColorspaceDetails(convert_ctx,
1611 color_table, color_range, color_table, color_range,
1612 brightness, contrast, saturation);
1615 int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ip->height,
1616 ipic->data, ipic->linesize);
1618 ff_err(ret, "FFVideoConvert::convert_picture_frame: sws_scale() failed\nfile: %s\n",
1619 vid->ffmpeg->fmt_ctx->url);
1625 int FFVideoConvert::convert_cmodel(VFrame *frame, AVFrame *ip)
1627 // try direct transfer
1628 if( !convert_picture_vframe(frame, ip) ) return 1;
1629 // use indirect transfer
1630 AVPixelFormat ifmt = (AVPixelFormat)ip->format;
1631 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
1633 for( int i = 0; i <desc->nb_components; ++i ) {
1634 int bits = desc->comp[i].depth;
1635 if( bits > max_bits ) max_bits = bits;
1637 int imodel = pix_fmt_to_color_model(ifmt);
1638 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1639 int cmodel = frame->get_color_model();
1640 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1641 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1642 imodel = cmodel_is_yuv ?
1643 (BC_CModels::has_alpha(cmodel) ?
1645 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1646 (BC_CModels::has_alpha(cmodel) ?
1647 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1648 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1650 VFrame vframe(ip->width, ip->height, imodel);
1651 if( convert_picture_vframe(&vframe, ip) ) return -1;
1652 frame->transfer_from(&vframe);
1656 int FFVideoConvert::transfer_cmodel(VFrame *frame, AVFrame *ifp)
1658 int ret = convert_cmodel(frame, ifp);
1660 const AVDictionary *src = ifp->metadata;
1661 AVDictionaryEntry *t = NULL;
1662 BC_Hash *hp = frame->get_params();
1664 while( (t=av_dict_get(src, "", t, AV_DICT_IGNORE_SUFFIX)) )
1665 hp->update(t->key, t->value);
1670 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op)
1672 AVFrame *opic = av_frame_alloc();
1673 int ret = convert_vframe_picture(frame, op, opic);
1674 av_frame_free(&opic);
1678 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op, AVFrame *opic)
1679 { // vframe = picture
1680 int cmodel = frame->get_color_model();
1681 AVPixelFormat ifmt = color_model_to_pix_fmt(cmodel);
1682 if( ifmt == AV_PIX_FMT_NB ) return -1;
1683 int size = av_image_fill_arrays(opic->data, opic->linesize,
1684 frame->get_data(), ifmt, frame->get_w(), frame->get_h(), 1);
1685 if( size < 0 ) return -1;
1687 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1688 int ysz = bpp * frame->get_w(), usz = ysz;
1698 // override av_image_fill_arrays() for planar types
1699 opic->data[0] = frame->get_y(); opic->linesize[0] = ysz;
1700 opic->data[1] = frame->get_u(); opic->linesize[1] = usz;
1701 opic->data[2] = frame->get_v(); opic->linesize[2] = usz;
1704 opic->data[0] = frame->get_data();
1705 opic->linesize[0] = frame->get_bytes_per_line();
1709 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1710 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(),
1711 ifmt, op->width, op->height, ofmt, SWS_POINT, NULL, NULL, NULL);
1712 if( !convert_ctx ) {
1713 fprintf(stderr, "FFVideoConvert::convert_frame_picture:"
1714 " sws_getCachedContext() failed\n");
1719 int color_range = 0;
1720 switch( preferences->yuv_color_range ) {
1721 case BC_COLORS_JPEG: color_range = 1; break;
1722 case BC_COLORS_MPEG: color_range = 0; break;
1724 int color_space = SWS_CS_ITU601;
1725 switch( preferences->yuv_color_space ) {
1726 case BC_COLORS_BT601_PAL: color_space = SWS_CS_ITU601; break;
1727 case BC_COLORS_BT601_NTSC: color_space = SWS_CS_SMPTE170M; break;
1728 case BC_COLORS_BT709: color_space = SWS_CS_ITU709; break;
1729 case BC_COLORS_BT2020_NCL:
1730 case BC_COLORS_BT2020_CL: color_space = SWS_CS_BT2020; break;
1732 const int *color_table = sws_getCoefficients(color_space);
1734 int *inv_table, *table, src_range, dst_range;
1735 int brightness, contrast, saturation;
1736 if( !sws_getColorspaceDetails(convert_ctx,
1737 &inv_table, &src_range, &table, &dst_range,
1738 &brightness, &contrast, &saturation) ) {
1739 if( dst_range != color_range || table != color_table )
1740 sws_setColorspaceDetails(convert_ctx,
1741 inv_table, src_range, color_table, color_range,
1742 brightness, contrast, saturation);
1745 int ret = sws_scale(convert_ctx, opic->data, opic->linesize, 0, frame->get_h(),
1746 op->data, op->linesize);
1748 ff_err(ret, "FFVideoConvert::convert_frame_picture: sws_scale() failed\n");
1754 int FFVideoConvert::convert_pixfmt(VFrame *frame, AVFrame *op)
1756 // try direct transfer
1757 if( !convert_vframe_picture(frame, op) ) return 1;
1758 // use indirect transfer
1759 int cmodel = frame->get_color_model();
1760 int max_bits = BC_CModels::calculate_pixelsize(cmodel) * 8;
1761 max_bits /= BC_CModels::components(cmodel);
1762 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1763 int imodel = pix_fmt_to_color_model(ofmt);
1764 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1765 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1766 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1767 imodel = cmodel_is_yuv ?
1768 (BC_CModels::has_alpha(cmodel) ?
1770 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1771 (BC_CModels::has_alpha(cmodel) ?
1772 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1773 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1775 VFrame vframe(frame->get_w(), frame->get_h(), imodel);
1776 vframe.transfer_from(frame);
1777 if( !convert_vframe_picture(&vframe, op) ) return 1;
1781 int FFVideoConvert::transfer_pixfmt(VFrame *frame, AVFrame *ofp)
1783 int ret = convert_pixfmt(frame, ofp);
1785 BC_Hash *hp = frame->get_params();
1786 AVDictionary **dict = &ofp->metadata;
1787 //av_dict_free(dict);
1788 for( int i=0; i<hp->size(); ++i ) {
1789 char *key = hp->get_key(i), *val = hp->get_value(i);
1790 av_dict_set(dict, key, val, 0);
1796 void FFVideoStream::load_markers()
1798 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1799 if( !index_state || idx >= index_state->video_markers.size() ) return;
1800 FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
1803 IndexMarks *FFVideoStream::get_markers()
1805 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1806 if( !index_state || idx >= index_state->video_markers.size() ) return 0;
1807 return !index_state ? 0 : index_state->video_markers[idx];
1811 FFMPEG::FFMPEG(FileBase *file_base)
1814 this->file_base = file_base;
1815 memset(file_format,0,sizeof(file_format));
1816 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
1817 flow_lock = new Condition(1,"FFStream::flow_lock",0);
1820 decoding = encoding = 0;
1821 has_audio = has_video = 0;
1822 interlace_from_codec = 0;
1825 opt_video_filter = 0;
1826 opt_audio_filter = 0;
1828 opt_video_decoder = 0;
1829 opt_audio_decoder = 0;
1831 char option_path[BCTEXTLEN];
1832 set_option_path(option_path, "%s", "ffmpeg.opts");
1833 read_options(option_path, opts);
1838 ff_lock("FFMPEG::~FFMPEG()");
1840 ffaudio.remove_all_objects();
1841 ffvideo.remove_all_objects();
1842 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1846 av_dict_free(&opts);
1847 delete [] opt_video_filter;
1848 delete [] opt_audio_filter;
1849 delete [] opt_hw_dev;
1852 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1854 const int *p = codec->supported_samplerates;
1855 if( !p ) return sample_rate;
1857 if( *p == sample_rate ) return *p;
1863 // check_frame_rate and std_frame_rate needed for 23.976
1864 // and 59.94 fps mpeg2
1865 static inline AVRational std_frame_rate(int i)
1867 static const int m1 = 1001*12, m2 = 1000*12;
1868 static const int freqs[] = {
1869 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1870 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 90*m2,
1871 100*m2, 120*m2, 144*m2, 72*m2, 0,
1873 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1874 return (AVRational) { freq, 1001*12 };
1877 AVRational FFMPEG::check_frame_rate(const AVRational *p, double frame_rate)
1879 AVRational rate, best_rate = (AVRational) { 0, 0 };
1880 double max_err = 1.; int i = 0;
1881 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1882 double framerate = (double) rate.num / rate.den;
1883 double err = fabs(frame_rate/framerate - 1.);
1884 if( err >= max_err ) continue;
1888 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1891 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1894 double display_aspect = asset->width / (double)asset->height;
1895 double sample_aspect = display_aspect / asset->aspect_ratio;
1896 int width = 1000000, height = width * sample_aspect + 0.5;
1898 MWindow::create_aspect_ratio(w, h, width, height);
1899 return (AVRational){(int)w, (int)h};
1902 return (AVRational){1, 1};
1906 AVRational FFMPEG::to_time_base(int sample_rate)
1908 return (AVRational){1, sample_rate};
1911 int FFMPEG::get_fmt_score(AVSampleFormat dst_fmt, AVSampleFormat src_fmt)
1914 int dst_planar = av_sample_fmt_is_planar(dst_fmt);
1915 int src_planar = av_sample_fmt_is_planar(src_fmt);
1916 if( dst_planar != src_planar ) ++score;
1917 int dst_bytes = av_get_bytes_per_sample(dst_fmt);
1918 int src_bytes = av_get_bytes_per_sample(src_fmt);
1919 score += (src_bytes > dst_bytes ? 100 : -10) * (src_bytes - dst_bytes);
1920 int src_packed = av_get_packed_sample_fmt(src_fmt);
1921 int dst_packed = av_get_packed_sample_fmt(dst_fmt);
1922 if( dst_packed == AV_SAMPLE_FMT_S32 && src_packed == AV_SAMPLE_FMT_FLT ) score += 20;
1923 if( dst_packed == AV_SAMPLE_FMT_FLT && src_packed == AV_SAMPLE_FMT_S32 ) score += 2;
1927 AVSampleFormat FFMPEG::find_best_sample_fmt_of_list(
1928 const AVSampleFormat *sample_fmts, AVSampleFormat src_fmt)
1930 AVSampleFormat best = AV_SAMPLE_FMT_NONE;
1931 int best_score = get_fmt_score(best, src_fmt);
1932 for( int i=0; sample_fmts[i] >= 0; ++i ) {
1933 AVSampleFormat sample_fmt = sample_fmts[i];
1934 int score = get_fmt_score(sample_fmt, src_fmt);
1935 if( score >= best_score ) continue;
1936 best = sample_fmt; best_score = score;
1942 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
1944 char *ep = path + BCTEXTLEN-1;
1945 strncpy(path, File::get_cindat_path(), ep-path);
1946 strncat(path, "/ffmpeg/", ep-path);
1947 path += strlen(path);
1950 path += vsnprintf(path, ep-path, fmt, ap);
1955 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
1960 set_option_path(path, "%s/%s", type, spec);
1963 int FFMPEG::get_format(char *format, const char *path, const char *spec)
1965 char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
1966 get_option_path(option_path, path, spec);
1967 FILE *fp = fopen(option_path,"r");
1970 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1972 line[sizeof(line)-1] = 0;
1973 ret = scan_option_line(line, format, codec);
1979 int FFMPEG::get_codec(char *codec, const char *path, const char *spec)
1981 char option_path[BCTEXTLEN], line[BCTEXTLEN], format[BCTEXTLEN];
1982 get_option_path(option_path, path, spec);
1983 FILE *fp = fopen(option_path,"r");
1986 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1989 line[sizeof(line)-1] = 0;
1990 ret = scan_option_line(line, format, codec);
1993 char *vp = codec, *ep = vp+BCTEXTLEN-1;
1994 while( vp < ep && *vp && *vp != '|' ) ++vp;
1995 if( *vp == '|' ) --vp;
1996 while( vp > codec && (*vp==' ' || *vp=='\t') ) *vp-- = 0;
2001 int FFMPEG::get_file_format()
2003 char audio_muxer[BCSTRLEN], video_muxer[BCSTRLEN];
2004 char audio_format[BCSTRLEN], video_format[BCSTRLEN];
2005 audio_muxer[0] = audio_format[0] = 0;
2006 video_muxer[0] = video_format[0] = 0;
2007 Asset *asset = file_base->asset;
2008 int ret = asset ? 0 : 1;
2009 if( !ret && asset->audio_data ) {
2010 if( !(ret=get_format(audio_format, "audio", asset->acodec)) ) {
2011 if( get_format(audio_muxer, "format", audio_format) ) {
2012 strcpy(audio_muxer, audio_format);
2013 audio_format[0] = 0;
2017 if( !ret && asset->video_data ) {
2018 if( !(ret=get_format(video_format, "video", asset->vcodec)) ) {
2019 if( get_format(video_muxer, "format", video_format) ) {
2020 strcpy(video_muxer, video_format);
2021 video_format[0] = 0;
2025 if( !ret && !audio_muxer[0] && !video_muxer[0] )
2027 if( !ret && audio_muxer[0] && video_muxer[0] &&
2028 strcmp(audio_muxer, video_muxer) ) ret = -1;
2029 if( !ret && audio_format[0] && video_format[0] &&
2030 strcmp(audio_format, video_format) ) ret = -1;
2032 strcpy(file_format, !audio_format[0] && !video_format[0] ?
2033 (audio_muxer[0] ? audio_muxer : video_muxer) :
2034 (audio_format[0] ? audio_format : video_format));
2038 int FFMPEG::scan_option_line(const char *cp, char *tag, char *val)
2040 while( *cp == ' ' || *cp == '\t' ) ++cp;
2041 const char *bp = cp;
2042 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' && *cp != '\n' ) ++cp;
2044 if( !len || len > BCSTRLEN-1 ) return 1;
2045 while( bp < cp ) *tag++ = *bp++;
2047 while( *cp == ' ' || *cp == '\t' ) ++cp;
2048 if( *cp == '=' ) ++cp;
2049 while( *cp == ' ' || *cp == '\t' ) ++cp;
2051 while( *cp && *cp != '\n' ) ++cp;
2053 if( len > BCTEXTLEN-1 ) return 1;
2054 while( bp < cp ) *val++ = *bp++;
2059 int FFMPEG::can_render(const char *fformat, const char *type)
2062 char option_path[BCTEXTLEN];
2063 FFMPEG::set_option_path(option_path, type);
2064 fs.update(option_path);
2065 int total_files = fs.total_files();
2066 for( int i=0; i<total_files; ++i ) {
2067 const char *name = fs.get_entry(i)->get_name();
2068 const char *ext = strrchr(name,'.');
2069 if( !ext ) continue;
2070 if( !strcmp(fformat, ++ext) ) return 1;
2075 int FFMPEG::get_ff_option(const char *nm, const char *options, char *value)
2077 for( const char *cp=options; *cp!=0; ) {
2078 char line[BCTEXTLEN], *bp = line, *ep = bp+sizeof(line)-1;
2079 while( bp < ep && *cp && *cp!='\n' ) *bp++ = *cp++;
2082 if( !line[0] || line[0] == '#' || line[0] == ';' ) continue;
2083 char key[BCSTRLEN], val[BCTEXTLEN];
2084 if( FFMPEG::scan_option_line(line, key, val) ) continue;
2085 if( !strcmp(key, nm) ) {
2086 strncpy(value, val, BCSTRLEN);
2093 void FFMPEG::scan_audio_options(Asset *asset, EDL *edl)
2095 char cin_sample_fmt[BCSTRLEN];
2096 int cin_fmt = AV_SAMPLE_FMT_NONE;
2097 const char *options = asset->ff_audio_options;
2098 if( !get_ff_option("cin_sample_fmt", options, cin_sample_fmt) )
2099 cin_fmt = (int)av_get_sample_fmt(cin_sample_fmt);
2101 char audio_codec[BCSTRLEN]; audio_codec[0] = 0;
2102 AVCodec *av_codec = !FFMPEG::get_codec(audio_codec, "audio", asset->acodec) ?
2103 avcodec_find_encoder_by_name(audio_codec) : 0;
2104 if( av_codec && av_codec->sample_fmts )
2105 cin_fmt = find_best_sample_fmt_of_list(av_codec->sample_fmts, AV_SAMPLE_FMT_FLT);
2107 if( cin_fmt < 0 ) cin_fmt = AV_SAMPLE_FMT_S16;
2108 const char *name = av_get_sample_fmt_name((AVSampleFormat)cin_fmt);
2109 if( !name ) name = _("None");
2110 strcpy(asset->ff_sample_format, name);
2112 char value[BCSTRLEN];
2113 if( !get_ff_option("cin_bitrate", options, value) )
2114 asset->ff_audio_bitrate = atoi(value);
2115 if( !get_ff_option("cin_quality", options, value) )
2116 asset->ff_audio_quality = atoi(value);
2119 void FFMPEG::load_audio_options(Asset *asset, EDL *edl)
2121 char options_path[BCTEXTLEN];
2122 set_option_path(options_path, "audio/%s", asset->acodec);
2123 if( !load_options(options_path,
2124 asset->ff_audio_options,
2125 sizeof(asset->ff_audio_options)) )
2126 scan_audio_options(asset, edl);
2129 void FFMPEG::scan_video_options(Asset *asset, EDL *edl)
2131 char cin_pix_fmt[BCSTRLEN];
2132 int cin_fmt = AV_PIX_FMT_NONE;
2133 const char *options = asset->ff_video_options;
2134 if( !get_ff_option("cin_pix_fmt", options, cin_pix_fmt) )
2135 cin_fmt = (int)av_get_pix_fmt(cin_pix_fmt);
2137 char video_codec[BCSTRLEN]; video_codec[0] = 0;
2138 AVCodec *av_codec = !get_codec(video_codec, "video", asset->vcodec) ?
2139 avcodec_find_encoder_by_name(video_codec) : 0;
2140 if( av_codec && av_codec->pix_fmts ) {
2141 if( 0 && edl ) { // frequently picks a bad answer
2142 int color_model = edl->session->color_model;
2143 int max_bits = BC_CModels::calculate_pixelsize(color_model) * 8;
2144 max_bits /= BC_CModels::components(color_model);
2145 cin_fmt = avcodec_find_best_pix_fmt_of_list(av_codec->pix_fmts,
2146 (BC_CModels::is_yuv(color_model) ?
2147 (max_bits > 8 ? AV_PIX_FMT_AYUV64LE : AV_PIX_FMT_YUV444P) :
2148 (max_bits > 8 ? AV_PIX_FMT_RGB48LE : AV_PIX_FMT_RGB24)), 0, 0);
2151 cin_fmt = av_codec->pix_fmts[0];
2154 if( cin_fmt < 0 ) cin_fmt = AV_PIX_FMT_YUV420P;
2155 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get((AVPixelFormat)cin_fmt);
2156 const char *name = desc ? desc->name : _("None");
2157 strcpy(asset->ff_pixel_format, name);
2159 char value[BCSTRLEN];
2160 if( !get_ff_option("cin_bitrate", options, value) )
2161 asset->ff_video_bitrate = atoi(value);
2162 if( !get_ff_option("cin_quality", options, value) )
2163 asset->ff_video_quality = atoi(value);
2166 void FFMPEG::load_video_options(Asset *asset, EDL *edl)
2168 char options_path[BCTEXTLEN];
2169 set_option_path(options_path, "video/%s", asset->vcodec);
2170 if( !load_options(options_path,
2171 asset->ff_video_options,
2172 sizeof(asset->ff_video_options)) )
2173 scan_video_options(asset, edl);
2176 void FFMPEG::scan_format_options(Asset *asset, EDL *edl)
2180 void FFMPEG::load_format_options(Asset *asset, EDL *edl)
2182 char options_path[BCTEXTLEN];
2183 set_option_path(options_path, "format/%s", asset->fformat);
2184 if( !load_options(options_path,
2185 asset->ff_format_options,
2186 sizeof(asset->ff_format_options)) )
2187 scan_format_options(asset, edl);
2190 int FFMPEG::load_defaults(const char *path, const char *type,
2191 char *codec, char *codec_options, int len)
2193 char default_file[BCTEXTLEN];
2194 set_option_path(default_file, "%s/%s.dfl", path, type);
2195 FILE *fp = fopen(default_file,"r");
2197 fgets(codec, BCSTRLEN, fp);
2199 while( *cp && *cp!='\n' ) ++cp;
2201 while( len > 0 && fgets(codec_options, len, fp) ) {
2202 int n = strlen(codec_options);
2203 codec_options += n; len -= n;
2206 set_option_path(default_file, "%s/%s", path, codec);
2207 return load_options(default_file, codec_options, len);
2210 void FFMPEG::set_asset_format(Asset *asset, EDL *edl, const char *text)
2212 if( asset->format != FILE_FFMPEG ) return;
2213 if( text != asset->fformat )
2214 strcpy(asset->fformat, text);
2215 if( !asset->ff_format_options[0] )
2216 load_format_options(asset, edl);
2217 if( asset->audio_data && !asset->ff_audio_options[0] ) {
2218 if( !load_defaults("audio", text, asset->acodec,
2219 asset->ff_audio_options, sizeof(asset->ff_audio_options)) )
2220 scan_audio_options(asset, edl);
2222 asset->audio_data = 0;
2224 if( asset->video_data && !asset->ff_video_options[0] ) {
2225 if( !load_defaults("video", text, asset->vcodec,
2226 asset->ff_video_options, sizeof(asset->ff_video_options)) )
2227 scan_video_options(asset, edl);
2229 asset->video_data = 0;
2233 int FFMPEG::get_encoder(const char *options,
2234 char *format, char *codec, char *bsfilter)
2236 FILE *fp = fopen(options,"r");
2238 eprintf(_("options open failed %s\n"),options);
2241 char line[BCTEXTLEN];
2242 if( !fgets(line, sizeof(line), fp) ||
2243 scan_encoder(line, format, codec, bsfilter) )
2244 eprintf(_("format/codec not found %s\n"), options);
2249 int FFMPEG::scan_encoder(const char *line,
2250 char *format, char *codec, char *bsfilter)
2252 format[0] = codec[0] = bsfilter[0] = 0;
2253 if( scan_option_line(line, format, codec) ) return 1;
2255 while( *cp && *cp != '|' ) ++cp;
2256 if( !*cp ) return 0;
2258 do { *bp-- = 0; } while( bp>=codec && (*bp==' ' || *bp == '\t' ) );
2259 while( *++cp && (*cp==' ' || *cp == '\t') );
2261 for( int i=BCTEXTLEN; --i>0 && *cp; ) *bp++ = *cp++;
2266 int FFMPEG::read_options(const char *options, AVDictionary *&opts, int skip)
2268 FILE *fp = fopen(options,"r");
2271 while( !ret && --skip >= 0 ) {
2273 while( ch >= 0 && ch != '\n' ) ch = getc(fp);
2274 if( ch < 0 ) ret = 1;
2277 ret = read_options(fp, options, opts);
2282 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
2284 FILE *fp = fmemopen((void *)options,strlen(options),"r");
2286 int ret = read_options(fp, options, opts);
2289 AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
2290 if( tag ) st->id = strtol(tag->value,0,0);
2295 void FFMPEG::put_cache_frame(VFrame *frame, int64_t position)
2297 file_base->file->put_cache_frame(frame, position, 0);
2300 int FFMPEG::get_use_cache()
2302 return file_base->file->get_use_cache();
2305 void FFMPEG::purge_cache()
2307 file_base->file->purge_cache();
2310 FFCodecRemap::FFCodecRemap()
2315 FFCodecRemap::~FFCodecRemap()
2317 delete [] old_codec;
2318 delete [] new_codec;
2321 int FFCodecRemaps::add(const char *val)
2323 char old_codec[BCSTRLEN], new_codec[BCSTRLEN];
2324 if( sscanf(val, " %63[a-zA-z0-9_-] = %63[a-z0-9_-]",
2325 &old_codec[0], &new_codec[0]) != 2 ) return 1;
2326 FFCodecRemap &remap = append();
2327 remap.old_codec = cstrdup(old_codec);
2328 remap.new_codec = cstrdup(new_codec);
2333 int FFCodecRemaps::update(AVCodecID &codec_id, AVCodec *&decoder)
2335 AVCodec *codec = avcodec_find_decoder(codec_id);
2336 if( !codec ) return -1;
2337 const char *name = codec->name;
2338 FFCodecRemaps &map = *this;
2340 while( --k >= 0 && strcmp(map[k].old_codec, name) );
2341 if( k < 0 ) return 1;
2342 const char *new_codec = map[k].new_codec;
2343 codec = avcodec_find_decoder_by_name(new_codec);
2344 if( !codec ) return -1;
2349 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
2351 int ret = 0, no = 0;
2352 char line[BCTEXTLEN];
2353 while( !ret && fgets(line, sizeof(line), fp) ) {
2354 line[sizeof(line)-1] = 0;
2355 if( line[0] == '#' ) continue;
2356 if( line[0] == '\n' ) continue;
2357 char key[BCSTRLEN], val[BCTEXTLEN];
2358 if( scan_option_line(line, key, val) ) {
2359 eprintf(_("err reading %s: line %d\n"), options, no);
2363 if( !strcmp(key, "duration") )
2364 opt_duration = strtod(val, 0);
2365 else if( !strcmp(key, "video_decoder") )
2366 opt_video_decoder = cstrdup(val);
2367 else if( !strcmp(key, "audio_decoder") )
2368 opt_audio_decoder = cstrdup(val);
2369 else if( !strcmp(key, "remap_video_decoder") )
2370 video_codec_remaps.add(val);
2371 else if( !strcmp(key, "remap_audio_decoder") )
2372 audio_codec_remaps.add(val);
2373 else if( !strcmp(key, "video_filter") )
2374 opt_video_filter = cstrdup(val);
2375 else if( !strcmp(key, "audio_filter") )
2376 opt_audio_filter = cstrdup(val);
2377 else if( !strcmp(key, "cin_hw_dev") )
2378 opt_hw_dev = cstrdup(val);
2379 else if( !strcmp(key, "loglevel") )
2382 av_dict_set(&opts, key, val, 0);
2388 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
2390 char option_path[BCTEXTLEN];
2391 set_option_path(option_path, "%s", options);
2392 return read_options(option_path, opts);
2395 int FFMPEG::load_options(const char *path, char *bfr, int len)
2398 FILE *fp = fopen(path, "r");
2400 fgets(bfr, len, fp); // skip hdr
2401 len = fread(bfr, 1, len-1, fp);
2402 if( len < 0 ) len = 0;
2408 void FFMPEG::set_loglevel(const char *ap)
2410 if( !ap || !*ap ) return;
2415 { "quiet" , AV_LOG_QUIET },
2416 { "panic" , AV_LOG_PANIC },
2417 { "fatal" , AV_LOG_FATAL },
2418 { "error" , AV_LOG_ERROR },
2419 { "warning", AV_LOG_WARNING },
2420 { "info" , AV_LOG_INFO },
2421 { "verbose", AV_LOG_VERBOSE },
2422 { "debug" , AV_LOG_DEBUG },
2424 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
2425 if( !strcmp(log_levels[i].name, ap) ) {
2426 av_log_set_level(log_levels[i].level);
2430 av_log_set_level(atoi(ap));
2433 double FFMPEG::to_secs(int64_t time, AVRational time_base)
2435 double base_time = time == AV_NOPTS_VALUE ? 0 :
2436 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
2437 return base_time / AV_TIME_BASE;
2440 int FFMPEG::info(char *text, int len)
2442 if( len <= 0 ) return 0;
2444 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
2446 report("format: %s\n",fmt_ctx->iformat->name);
2447 if( ffvideo.size() > 0 )
2448 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
2449 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
2450 const char *unkn = _("(unkn)");
2451 FFVideoStream *vid = ffvideo[vidx];
2452 AVStream *st = vid->st;
2453 AVCodecID codec_id = st->codecpar->codec_id;
2454 report(_("vid%d (%d), id 0x%06x:\n"), vid->idx, vid->fidx, codec_id);
2455 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
2456 report(" video%d %s ", vidx+1, desc ? desc->name : unkn);
2457 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
2458 AVPixelFormat pix_fmt = (AVPixelFormat)st->codecpar->format;
2459 const char *pfn = av_get_pix_fmt_name(pix_fmt);
2460 report(" pix %s\n", pfn ? pfn : unkn);
2461 int interlace = st->codecpar->field_order;
2462 report(" interlace (container level): %i\n", interlace ? interlace : -1);
2463 int interlace_codec = interlace_from_codec;
2464 report(" interlace (codec level): %i\n", interlace_codec ? interlace_codec : -1);
2465 enum AVColorSpace space = st->codecpar->color_space;
2466 const char *nm = av_color_space_name(space);
2467 report(" color space:%s", nm ? nm : unkn);
2468 enum AVColorRange range = st->codecpar->color_range;
2469 const char *rg = av_color_range_name(range);
2470 report("/ range:%s\n", rg ? rg : unkn);
2471 double secs = to_secs(st->duration, st->time_base);
2472 int64_t length = secs * vid->frame_rate + 0.5;
2473 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
2474 int64_t nudge = ofs * vid->frame_rate;
2475 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
2476 report(" %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
2477 int hrs = secs/3600; secs -= hrs*3600;
2478 int mins = secs/60; secs -= mins*60;
2479 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
2480 double theta = vid->get_rotation_angle();
2481 if( fabs(theta) > 1 )
2482 report(" rotation angle: %0.1f\n", theta);
2484 if( ffaudio.size() > 0 )
2485 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
2486 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2487 FFAudioStream *aud = ffaudio[aidx];
2488 AVStream *st = aud->st;
2489 AVCodecID codec_id = st->codecpar->codec_id;
2490 report(_("aud%d (%d), id 0x%06x:\n"), aud->idx, aud->fidx, codec_id);
2491 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
2492 int nch = aud->channels, ch0 = aud->channel0+1;
2493 report(" audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
2494 AVSampleFormat sample_fmt = (AVSampleFormat)st->codecpar->format;
2495 const char *fmt = av_get_sample_fmt_name(sample_fmt);
2496 report(" %s %d", fmt, aud->sample_rate);
2497 int sample_bits = av_get_bits_per_sample(codec_id);
2498 report(" %dbits\n", sample_bits);
2499 double secs = to_secs(st->duration, st->time_base);
2500 int64_t length = secs * aud->sample_rate + 0.5;
2501 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
2502 int64_t nudge = ofs * aud->sample_rate;
2503 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
2504 report(" %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
2505 int hrs = secs/3600; secs -= hrs*3600;
2506 int mins = secs/60; secs -= mins*60;
2507 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
2509 if( fmt_ctx->nb_programs > 0 )
2510 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
2511 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
2512 report("program %d", i+1);
2513 AVProgram *pgrm = fmt_ctx->programs[i];
2514 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2515 int idx = pgrm->stream_index[j];
2516 int vidx = ffvideo.size();
2517 while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
2519 report(", vid%d", vidx);
2522 int aidx = ffaudio.size();
2523 while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
2525 report(", aud%d", aidx);
2528 report(", (%d)", pgrm->stream_index[j]);
2533 AVDictionaryEntry *tag = 0;
2534 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
2535 report("%s=%s\n", tag->key, tag->value);
2544 int FFMPEG::init_decoder(const char *filename)
2546 ff_lock("FFMPEG::init_decoder");
2548 char file_opts[BCTEXTLEN];
2549 strcpy(file_opts, filename);
2550 char *bp = strrchr(file_opts, '/');
2551 if( !bp ) bp = file_opts;
2552 char *sp = strrchr(bp, '.');
2553 if( !sp ) sp = bp + strlen(bp);
2555 AVInputFormat *ifmt = 0;
2557 strcpy(sp, ".opts");
2558 fp = fopen(file_opts, "r");
2561 read_options(fp, file_opts, opts);
2563 AVDictionaryEntry *tag;
2564 if( (tag=av_dict_get(opts, "format", NULL, 0)) != 0 ) {
2565 ifmt = av_find_input_format(tag->value);
2569 load_options("decode.opts", opts);
2570 AVDictionary *fopts = 0;
2571 av_dict_copy(&fopts, opts, 0);
2572 int ret = avformat_open_input(&fmt_ctx, filename, ifmt, &fopts);
2573 av_dict_free(&fopts);
2575 ret = avformat_find_stream_info(fmt_ctx, NULL);
2580 return !ret ? 0 : 1;
2583 int FFMPEG::open_decoder()
2586 if( stat(fmt_ctx->url, &st) < 0 ) {
2587 eprintf(_("can't stat file: %s\n"), fmt_ctx->url);
2591 int64_t file_bits = 8 * st.st_size;
2592 if( !fmt_ctx->bit_rate && opt_duration > 0 )
2593 fmt_ctx->bit_rate = file_bits / opt_duration;
2596 if( fmt_ctx->bit_rate > 0 ) {
2597 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2598 AVStream *st = fmt_ctx->streams[i];
2599 if( st->duration != AV_NOPTS_VALUE ) continue;
2600 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
2601 st->duration = av_rescale(file_bits, st->time_base.den,
2602 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
2606 if( estimated && !(fflags & FF_ESTM_TIMES) ) {
2607 fflags |= FF_ESTM_TIMES;
2608 printf("FFMPEG::open_decoder: some stream times estimated: %s\n",
2612 ff_lock("FFMPEG::open_decoder");
2613 int ret = 0, bad_time = 0;
2614 for( int i=0; !ret && i<(int)fmt_ctx->nb_streams; ++i ) {
2615 AVStream *st = fmt_ctx->streams[i];
2616 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
2617 AVCodecParameters *avpar = st->codecpar;
2618 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avpar->codec_id);
2619 if( !codec_desc ) continue;
2620 switch( avpar->codec_type ) {
2621 case AVMEDIA_TYPE_VIDEO: {
2622 if( avpar->width < 1 ) continue;
2623 if( avpar->height < 1 ) continue;
2624 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
2625 if( framerate.num < 1 ) continue;
2627 int vidx = ffvideo.size();
2628 FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
2629 vstrm_index.append(ffidx(vidx, 0));
2630 ffvideo.append(vid);
2631 vid->width = avpar->width;
2632 vid->height = avpar->height;
2633 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
2634 switch( avpar->color_range ) {
2635 case AVCOL_RANGE_MPEG:
2636 vid->color_range = BC_COLORS_MPEG;
2638 case AVCOL_RANGE_JPEG:
2639 vid->color_range = BC_COLORS_JPEG;
2642 vid->color_range = !file_base ? BC_COLORS_JPEG :
2643 file_base->file->preferences->yuv_color_range;
2646 switch( avpar->color_space ) {
2647 case AVCOL_SPC_BT470BG:
2648 vid->color_space = BC_COLORS_BT601_PAL;
2650 case AVCOL_SPC_SMPTE170M:
2651 vid->color_space = BC_COLORS_BT601_NTSC;
2653 case AVCOL_SPC_BT709:
2654 vid->color_space = BC_COLORS_BT709;
2656 case AVCOL_SPC_BT2020_NCL:
2657 vid->color_space = BC_COLORS_BT2020_NCL;
2659 case AVCOL_SPC_BT2020_CL:
2660 vid->color_space = BC_COLORS_BT2020_CL;
2663 vid->color_space = !file_base ? BC_COLORS_BT601_NTSC :
2664 file_base->file->preferences->yuv_color_space;
2667 double secs = to_secs(st->duration, st->time_base);
2668 vid->length = secs * vid->frame_rate;
2669 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
2670 vid->nudge = st->start_time;
2672 ret = vid->create_filter(opt_video_filter);
2674 case AVMEDIA_TYPE_AUDIO: {
2675 if( avpar->channels < 1 ) continue;
2676 if( avpar->sample_rate < 1 ) continue;
2678 int aidx = ffaudio.size();
2679 FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
2680 ffaudio.append(aud);
2681 aud->channel0 = astrm_index.size();
2682 aud->channels = avpar->channels;
2683 for( int ch=0; ch<aud->channels; ++ch )
2684 astrm_index.append(ffidx(aidx, ch));
2685 aud->sample_rate = avpar->sample_rate;
2686 double secs = to_secs(st->duration, st->time_base);
2687 aud->length = secs * aud->sample_rate;
2688 aud->init_swr(aud->channels, avpar->format, aud->sample_rate);
2689 aud->nudge = st->start_time;
2691 ret = aud->create_filter(opt_audio_filter);
2696 if( bad_time && !(fflags & FF_BAD_TIMES) ) {
2697 fflags |= FF_BAD_TIMES;
2698 printf(_("FFMPEG::open_decoder: some stream have bad times: %s\n"),
2702 return ret < 0 ? -1 : 0;
2706 int FFMPEG::init_encoder(const char *filename)
2708 // try access first for named pipes
2709 int ret = access(filename, W_OK);
2711 int fd = ::open(filename,O_WRONLY);
2712 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
2713 if( fd >= 0 ) { close(fd); ret = 0; }
2716 eprintf(_("bad file path: %s\n"), filename);
2719 ret = get_file_format();
2721 eprintf(_("bad file format: %s\n"), filename);
2725 eprintf(_("mismatch audio/video file format: %s\n"), filename);
2728 ff_lock("FFMPEG::init_encoder");
2730 char format[BCSTRLEN];
2731 if( get_format(format, "format", file_format) )
2732 strcpy(format, file_format);
2733 avformat_alloc_output_context2(&fmt_ctx, 0, format, filename);
2735 eprintf(_("failed: %s\n"), filename);
2740 load_options("encode.opts", opts);
2746 int FFMPEG::open_encoder(const char *type, const char *spec)
2749 Asset *asset = file_base->asset;
2750 char *filename = asset->path;
2751 AVDictionary *sopts = 0;
2752 av_dict_copy(&sopts, opts, 0);
2753 char option_path[BCTEXTLEN];
2754 set_option_path(option_path, "%s/%s.opts", type, type);
2755 read_options(option_path, sopts);
2756 get_option_path(option_path, type, spec);
2757 char format_name[BCSTRLEN], codec_name[BCTEXTLEN], bsfilter[BCTEXTLEN];
2758 if( get_encoder(option_path, format_name, codec_name, bsfilter) ) {
2759 eprintf(_("get_encoder failed %s:%s\n"), option_path, filename);
2764 if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
2766 else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
2767 else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
2770 ff_lock("FFMPEG::open_encoder");
2773 AVCodecContext *ctx = 0;
2775 const AVCodecDescriptor *codec_desc = 0;
2776 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
2778 eprintf(_("cant find codec %s:%s\n"), codec_name, filename);
2782 codec_desc = avcodec_descriptor_get(codec->id);
2784 eprintf(_("unknown codec %s:%s\n"), codec_name, filename);
2789 st = avformat_new_stream(fmt_ctx, 0);
2791 eprintf(_("cant create stream %s:%s\n"), codec_name, filename);
2796 switch( codec_desc->type ) {
2797 case AVMEDIA_TYPE_AUDIO: {
2799 eprintf(_("duplicate audio %s:%s\n"), codec_name, filename);
2803 if( scan_options(asset->ff_audio_options, sopts, st) ) {
2804 eprintf(_("bad audio options %s:%s\n"), codec_name, filename);
2809 ctx = avcodec_alloc_context3(codec);
2810 if( asset->ff_audio_bitrate > 0 ) {
2811 ctx->bit_rate = asset->ff_audio_bitrate;
2813 sprintf(arg, "%d", asset->ff_audio_bitrate);
2814 av_dict_set(&sopts, "b", arg, 0);
2816 else if( asset->ff_audio_quality >= 0 ) {
2817 ctx->global_quality = asset->ff_audio_quality * FF_QP2LAMBDA;
2818 ctx->qmin = ctx->qmax = asset->ff_audio_quality;
2819 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2820 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2821 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2823 av_dict_set(&sopts, "flags", "+qscale", 0);
2824 sprintf(arg, "%d", asset->ff_audio_quality);
2825 av_dict_set(&sopts, "qscale", arg, 0);
2826 sprintf(arg, "%d", ctx->global_quality);
2827 av_dict_set(&sopts, "global_quality", arg, 0);
2829 int aidx = ffaudio.size();
2830 int fidx = aidx + ffvideo.size();
2831 FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
2832 aud->avctx = ctx; ffaudio.append(aud); fst = aud;
2833 aud->sample_rate = asset->sample_rate;
2834 ctx->channels = aud->channels = asset->channels;
2835 for( int ch=0; ch<aud->channels; ++ch )
2836 astrm_index.append(ffidx(aidx, ch));
2837 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
2838 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
2839 if( !ctx->sample_rate ) {
2840 eprintf(_("check_sample_rate failed %s\n"), filename);
2844 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
2845 AVSampleFormat sample_fmt = av_get_sample_fmt(asset->ff_sample_format);
2846 if( sample_fmt == AV_SAMPLE_FMT_NONE )
2847 sample_fmt = codec->sample_fmts ? codec->sample_fmts[0] : AV_SAMPLE_FMT_S16;
2848 ctx->sample_fmt = sample_fmt;
2849 uint64_t layout = av_get_default_channel_layout(ctx->channels);
2850 aud->resample_context = swr_alloc_set_opts(NULL,
2851 layout, ctx->sample_fmt, aud->sample_rate,
2852 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
2854 swr_init(aud->resample_context);
2857 case AVMEDIA_TYPE_VIDEO: {
2859 eprintf(_("duplicate video %s:%s\n"), codec_name, filename);
2863 if( scan_options(asset->ff_video_options, sopts, st) ) {
2864 eprintf(_("bad video options %s:%s\n"), codec_name, filename);
2869 ctx = avcodec_alloc_context3(codec);
2870 if( asset->ff_video_bitrate > 0 ) {
2871 ctx->bit_rate = asset->ff_video_bitrate;
2873 sprintf(arg, "%d", asset->ff_video_bitrate);
2874 av_dict_set(&sopts, "b", arg, 0);
2876 else if( asset->ff_video_quality >= 0 ) {
2877 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
2878 ctx->qmin = ctx->qmax = asset->ff_video_quality;
2879 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2880 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2881 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2883 av_dict_set(&sopts, "flags", "+qscale", 0);
2884 sprintf(arg, "%d", asset->ff_video_quality);
2885 av_dict_set(&sopts, "qscale", arg, 0);
2886 sprintf(arg, "%d", ctx->global_quality);
2887 av_dict_set(&sopts, "global_quality", arg, 0);
2889 int vidx = ffvideo.size();
2890 int fidx = vidx + ffaudio.size();
2891 FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
2892 vstrm_index.append(ffidx(vidx, 0));
2893 vid->avctx = ctx; ffvideo.append(vid); fst = vid;
2894 vid->width = asset->width;
2895 vid->height = asset->height;
2896 vid->frame_rate = asset->frame_rate;
2897 if( (vid->color_range = asset->ff_color_range) < 0 )
2898 vid->color_range = file_base->file->preferences->yuv_color_range;
2899 switch( vid->color_range ) {
2900 case BC_COLORS_MPEG: ctx->color_range = AVCOL_RANGE_MPEG; break;
2901 case BC_COLORS_JPEG: ctx->color_range = AVCOL_RANGE_JPEG; break;
2903 if( (vid->color_space = asset->ff_color_space) < 0 )
2904 vid->color_space = file_base->file->preferences->yuv_color_space;
2905 switch( vid->color_space ) {
2906 case BC_COLORS_BT601_NTSC: ctx->colorspace = AVCOL_SPC_SMPTE170M; break;
2907 case BC_COLORS_BT601_PAL: ctx->colorspace = AVCOL_SPC_BT470BG; break;
2908 case BC_COLORS_BT709: ctx->colorspace = AVCOL_SPC_BT709; break;
2909 case BC_COLORS_BT2020_NCL: ctx->colorspace = AVCOL_SPC_BT2020_NCL; break;
2910 case BC_COLORS_BT2020_CL: ctx->colorspace = AVCOL_SPC_BT2020_CL; break;
2912 AVPixelFormat pix_fmt = av_get_pix_fmt(asset->ff_pixel_format);
2913 if( opt_hw_dev != 0 ) {
2914 AVHWDeviceType hw_type = vid->encode_hw_activate(opt_hw_dev);
2916 case AV_HWDEVICE_TYPE_VAAPI:
2917 pix_fmt = AV_PIX_FMT_VAAPI;
2919 case AV_HWDEVICE_TYPE_NONE:
2923 if( pix_fmt == AV_PIX_FMT_NONE )
2924 pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
2925 ctx->pix_fmt = pix_fmt;
2927 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
2928 int mask_w = (1<<desc->log2_chroma_w)-1;
2929 ctx->width = (vid->width+mask_w) & ~mask_w;
2930 int mask_h = (1<<desc->log2_chroma_h)-1;
2931 ctx->height = (vid->height+mask_h) & ~mask_h;
2932 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
2933 AVRational frame_rate;
2934 if (ctx->codec->id == AV_CODEC_ID_MPEG1VIDEO ||
2935 ctx->codec->id == AV_CODEC_ID_MPEG2VIDEO)
2936 frame_rate = check_frame_rate(codec->supported_framerates, vid->frame_rate);
2938 frame_rate = av_d2q(vid->frame_rate, INT_MAX);
2939 if( !frame_rate.num || !frame_rate.den ) {
2940 eprintf(_("check_frame_rate failed %s\n"), filename);
2944 av_reduce(&frame_rate.num, &frame_rate.den,
2945 frame_rate.num, frame_rate.den, INT_MAX);
2946 ctx->framerate = (AVRational) { frame_rate.num, frame_rate.den };
2947 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
2948 st->avg_frame_rate = frame_rate;
2949 st->time_base = ctx->time_base;
2951 vid->interlaced = asset->interlace_mode == ILACE_MODE_TOP_FIRST ||
2952 asset->interlace_mode == ILACE_MODE_BOTTOM_FIRST ? 1 : 0;
2953 vid->top_field_first = asset->interlace_mode == ILACE_MODE_TOP_FIRST ? 1 : 0;
2954 switch (asset->interlace_mode) {
2955 case ILACE_MODE_TOP_FIRST:
2956 if (ctx->codec->id == AV_CODEC_ID_MJPEG)
2957 av_dict_set(&sopts, "field_order", "tt", 0);
2959 av_dict_set(&sopts, "field_order", "tb", 0);
2960 if (ctx->codec_id != AV_CODEC_ID_MJPEG)
2961 av_dict_set(&sopts, "flags", "+ilme+ildct", 0);
2963 case ILACE_MODE_BOTTOM_FIRST:
2964 if (ctx->codec->id == AV_CODEC_ID_MJPEG)
2965 av_dict_set(&sopts, "field_order", "bb", 0);
2967 av_dict_set(&sopts, "field_order", "bt", 0);
2968 if (ctx->codec_id != AV_CODEC_ID_MJPEG)
2969 av_dict_set(&sopts, "flags", "+ilme+ildct", 0);
2971 case ILACE_MODE_NOTINTERLACED: av_dict_set(&sopts, "field_order", "progressive", 0); break;
2975 eprintf(_("not audio/video, %s:%s\n"), codec_name, filename);
2980 AVDictionaryEntry *tag;
2981 if( (tag=av_dict_get(sopts, "cin_stats_filename", NULL, 0)) != 0 ) {
2982 char suffix[BCSTRLEN]; sprintf(suffix,"-%d.log",fst->fidx);
2983 fst->stats_filename = cstrcat(2, tag->value, suffix);
2985 if( (tag=av_dict_get(sopts, "flags", NULL, 0)) != 0 ) {
2986 int pass = fst->pass;
2987 char *cp = tag->value;
2989 int ch = *cp++, pfx = ch=='-' ? -1 : ch=='+' ? 1 : 0;
2990 if( !isalnum(!pfx ? ch : (ch=*cp++)) ) continue;
2991 char id[BCSTRLEN], *bp = id, *ep = bp+sizeof(id)-1;
2992 for( *bp++=ch; isalnum(ch=*cp); ++cp )
2993 if( bp < ep ) *bp++ = ch;
2995 if( !strcmp(id, "pass1") ) {
2996 pass = pfx<0 ? (pass&~1) : pfx>0 ? (pass|1) : 1;
2998 else if( !strcmp(id, "pass2") ) {
2999 pass = pfx<0 ? (pass&~2) : pfx>0 ? (pass|2) : 2;
3002 if( (fst->pass=pass) ) {
3003 if( pass & 1 ) ctx->flags |= AV_CODEC_FLAG_PASS1;
3004 if( pass & 2 ) ctx->flags |= AV_CODEC_FLAG_PASS2;
3010 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
3011 ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
3012 if( fst->stats_filename && (ret=fst->init_stats_file()) )
3013 eprintf(_("error: stats file = %s\n"), fst->stats_filename);
3016 av_dict_set(&sopts, "cin_bitrate", 0, 0);
3017 av_dict_set(&sopts, "cin_quality", 0, 0);
3019 if( !av_dict_get(sopts, "threads", NULL, 0) )
3020 ctx->thread_count = ff_cpus();
3021 ret = avcodec_open2(ctx, codec, &sopts);
3023 ret = avcodec_parameters_from_context(st->codecpar, ctx);
3025 fprintf(stderr, "Could not copy the stream parameters\n");
3028 _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
3029 ret = avcodec_copy_context(st->codec, ctx);
3030 _Pragma("GCC diagnostic warning \"-Wdeprecated-declarations\"")
3032 fprintf(stderr, "Could not copy the stream context\n");
3035 ff_err(ret,"FFMPEG::open_encoder");
3036 eprintf(_("open failed %s:%s\n"), codec_name, filename);
3042 if( !ret && fst && bsfilter[0] ) {
3043 ret = av_bsf_list_parse_str(bsfilter, &fst->bsfc);
3045 ff_err(ret,"FFMPEG::open_encoder");
3046 eprintf(_("bitstream filter failed %s:\n%s\n"), filename, bsfilter);
3057 av_dict_free(&sopts);
3061 int FFMPEG::close_encoder()
3064 if( encoding > 0 ) {
3065 av_write_trailer(fmt_ctx);
3066 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
3067 avio_closep(&fmt_ctx->pb);
3073 int FFMPEG::decode_activate()
3075 if( decoding < 0 ) {
3077 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
3078 ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
3079 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
3080 ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
3081 // set nudges for each program stream set
3082 const int64_t min_nudge = INT64_MIN+1;
3083 int npgrms = fmt_ctx->nb_programs;
3084 for( int i=0; i<npgrms; ++i ) {
3085 AVProgram *pgrm = fmt_ctx->programs[i];
3086 // first start time video stream
3087 int64_t vstart_time = min_nudge, astart_time = min_nudge;
3088 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
3089 int fidx = pgrm->stream_index[j];
3090 AVStream *st = fmt_ctx->streams[fidx];
3091 AVCodecParameters *avpar = st->codecpar;
3092 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
3093 if( st->start_time == AV_NOPTS_VALUE ) continue;
3094 if( vstart_time < st->start_time )
3095 vstart_time = st->start_time;
3098 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
3099 if( st->start_time == AV_NOPTS_VALUE ) continue;
3100 if( astart_time < st->start_time )
3101 astart_time = st->start_time;
3105 //since frame rate is much more grainy than sample rate, it is better to
3106 // align using video, so that total absolute error is minimized.
3107 int64_t nudge = vstart_time > min_nudge ? vstart_time :
3108 astart_time > min_nudge ? astart_time : AV_NOPTS_VALUE;
3109 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
3110 int fidx = pgrm->stream_index[j];
3111 AVStream *st = fmt_ctx->streams[fidx];
3112 AVCodecParameters *avpar = st->codecpar;
3113 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
3114 for( int k=0; k<ffvideo.size(); ++k ) {
3115 if( ffvideo[k]->fidx != fidx ) continue;
3116 ffvideo[k]->nudge = nudge;
3120 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
3121 for( int k=0; k<ffaudio.size(); ++k ) {
3122 if( ffaudio[k]->fidx != fidx ) continue;
3123 ffaudio[k]->nudge = nudge;
3129 // set nudges for any streams not yet set
3130 int64_t vstart_time = min_nudge, astart_time = min_nudge;
3131 int nstreams = fmt_ctx->nb_streams;
3132 for( int i=0; i<nstreams; ++i ) {
3133 AVStream *st = fmt_ctx->streams[i];
3134 AVCodecParameters *avpar = st->codecpar;
3135 switch( avpar->codec_type ) {
3136 case AVMEDIA_TYPE_VIDEO: {
3137 if( st->start_time == AV_NOPTS_VALUE ) continue;
3138 int vidx = ffvideo.size();
3139 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
3140 if( vidx < 0 ) continue;
3141 if( ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
3142 if( vstart_time < st->start_time )
3143 vstart_time = st->start_time;
3145 case AVMEDIA_TYPE_AUDIO: {
3146 if( st->start_time == AV_NOPTS_VALUE ) continue;
3147 int aidx = ffaudio.size();
3148 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
3149 if( aidx < 0 ) continue;
3150 if( ffaudio[aidx]->frame_sz < avpar->frame_size )
3151 ffaudio[aidx]->frame_sz = avpar->frame_size;
3152 if( ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
3153 if( astart_time < st->start_time )
3154 astart_time = st->start_time;
3159 int64_t nudge = vstart_time > min_nudge ? vstart_time :
3160 astart_time > min_nudge ? astart_time : 0;
3161 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
3162 if( ffvideo[vidx]->nudge == AV_NOPTS_VALUE )
3163 ffvideo[vidx]->nudge = nudge;
3165 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
3166 if( ffaudio[aidx]->nudge == AV_NOPTS_VALUE )
3167 ffaudio[aidx]->nudge = nudge;
3174 int FFMPEG::encode_activate()
3177 if( encoding < 0 ) {
3179 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
3180 (ret=avio_open(&fmt_ctx->pb, fmt_ctx->url, AVIO_FLAG_WRITE)) < 0 ) {
3181 ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
3185 if( !strcmp(file_format, "image2") ) {
3186 Asset *asset = file_base->asset;
3187 const char *filename = asset->path;
3188 FILE *fp = fopen(filename,"w");
3190 eprintf(_("Cant write image2 header file: %s\n %m"), filename);
3193 fprintf(fp, "IMAGE2\n");
3194 fprintf(fp, "# Frame rate: %f\n", asset->frame_rate);
3195 fprintf(fp, "# Width: %d\n", asset->width);
3196 fprintf(fp, "# Height: %d\n", asset->height);
3200 AVProgram *prog = av_new_program(fmt_ctx, prog_id);
3201 for( int i=0; i< ffvideo.size(); ++i )
3202 av_program_add_stream_index(fmt_ctx, prog_id, ffvideo[i]->fidx);
3203 for( int i=0; i< ffaudio.size(); ++i )
3204 av_program_add_stream_index(fmt_ctx, prog_id, ffaudio[i]->fidx);
3205 int pi = fmt_ctx->nb_programs;
3206 while( --pi >= 0 && fmt_ctx->programs[pi]->id != prog_id );
3207 AVDictionary **meta = &prog->metadata;
3208 av_dict_set(meta, "service_provider", "cin5", 0);
3209 const char *path = fmt_ctx->url, *bp = strrchr(path,'/');
3210 if( bp ) path = bp + 1;
3211 av_dict_set(meta, "title", path, 0);
3213 if( ffaudio.size() ) {
3214 const char *ep = getenv("CIN_AUDIO_LANG"), *lp = 0;
3215 if( !ep && (lp=getenv("LANG")) ) { // some are guesses
3216 static struct { const char lc[3], lng[4]; } lcode[] = {
3217 { "en", "eng" }, { "de", "ger" }, { "es", "spa" },
3218 { "eu", "bas" }, { "fr", "fre" }, { "el", "gre" },
3219 { "hi", "hin" }, { "it", "ita" }, { "ja", "jap" },
3220 { "ko", "kor" }, { "du", "dut" }, { "pl", "pol" },
3221 { "pt", "por" }, { "ru", "rus" }, { "sl", "slv" },
3222 { "uk", "ukr" }, { "vi", "vie" }, { "zh", "chi" },
3224 for( int i=sizeof(lcode)/sizeof(lcode[0]); --i>=0 && !ep; )
3225 if( !strncmp(lcode[i].lc,lp,2) ) ep = lcode[i].lng;
3227 if( !ep ) ep = "und";
3229 strncpy(lang,ep,3); lang[3] = 0;
3230 AVStream *st = ffaudio[0]->st;
3231 av_dict_set(&st->metadata,"language",lang,0);
3234 AVDictionary *fopts = 0;
3235 char option_path[BCTEXTLEN];
3236 set_option_path(option_path, "format/%s", file_format);
3237 read_options(option_path, fopts, 1);
3238 av_dict_copy(&fopts, opts, 0);
3239 if( scan_options(file_base->asset->ff_format_options, fopts, 0) ) {
3240 eprintf(_("bad format options %s\n"), file_base->asset->path);
3244 ret = avformat_write_header(fmt_ctx, &fopts);
3246 ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
3250 av_dict_free(&fopts);
3257 int FFMPEG::audio_seek(int stream, int64_t pos)
3259 int aidx = astrm_index[stream].st_idx;
3260 FFAudioStream *aud = ffaudio[aidx];
3261 aud->audio_seek(pos);
3265 int FFMPEG::video_probe(int64_t pos)
3267 int vidx = vstrm_index[0].st_idx;
3268 FFVideoStream *vid = ffvideo[vidx];
3271 int interlace1 = interlace_from_codec;
3272 //printf("interlace from codec: %i\n", interlace1);
3278 return ILACE_MODE_TOP_FIRST;
3281 return ILACE_MODE_BOTTOM_FIRST;
3282 case AV_FIELD_PROGRESSIVE:
3283 return ILACE_MODE_NOTINTERLACED;
3285 return ILACE_MODE_UNDETECTED;
3292 int FFMPEG::video_seek(int stream, int64_t pos)
3294 int vidx = vstrm_index[stream].st_idx;
3295 FFVideoStream *vid = ffvideo[vidx];
3296 vid->video_seek(pos);
3301 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
3303 if( !has_audio || chn >= astrm_index.size() ) return -1;
3304 int aidx = astrm_index[chn].st_idx;
3305 FFAudioStream *aud = ffaudio[aidx];
3306 if( aud->load(pos, len) < len ) return -1;
3307 int ch = astrm_index[chn].st_ch;
3308 int ret = aud->read(samples,len,ch);
3312 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
3314 if( !has_video || layer >= vstrm_index.size() ) return -1;
3315 int vidx = vstrm_index[layer].st_idx;
3316 FFVideoStream *vid = ffvideo[vidx];
3317 return vid->load(vframe, pos);
3321 int FFMPEG::encode(int stream, double **samples, int len)
3323 FFAudioStream *aud = ffaudio[stream];
3324 return aud->encode(samples, len);
3328 int FFMPEG::encode(int stream, VFrame *frame)
3330 FFVideoStream *vid = ffvideo[stream];
3331 return vid->encode(frame);
3334 void FFMPEG::start_muxer()
3342 void FFMPEG::stop_muxer()
3351 void FFMPEG::flow_off()
3354 flow_lock->lock("FFMPEG::flow_off");
3358 void FFMPEG::flow_on()
3362 flow_lock->unlock();
3365 void FFMPEG::flow_ctl()
3368 flow_lock->lock("FFMPEG::flow_ctl");
3369 flow_lock->unlock();
3373 int FFMPEG::mux_audio(FFrame *frm)
3375 FFStream *fst = frm->fst;
3376 AVCodecContext *ctx = fst->avctx;
3377 AVFrame *frame = *frm;
3378 AVRational tick_rate = {1, ctx->sample_rate};
3379 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
3380 int ret = fst->encode_frame(frame);
3382 ff_err(ret, "FFMPEG::mux_audio");
3383 return ret >= 0 ? 0 : 1;
3386 int FFMPEG::mux_video(FFrame *frm)
3388 FFStream *fst = frm->fst;
3389 AVFrame *frame = *frm;
3390 frame->pts = frm->position;
3391 int ret = fst->encode_frame(frame);
3393 ff_err(ret, "FFMPEG::mux_video");
3394 return ret >= 0 ? 0 : 1;
3400 double atm = -1, vtm = -1;
3401 FFrame *afrm = 0, *vfrm = 0;
3403 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
3404 FFStream *fst = ffaudio[i];
3405 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
3406 FFrame *frm = fst->frms.first;
3407 if( !frm ) { if( !done ) return; continue; }
3408 double tm = to_secs(frm->position, fst->avctx->time_base);
3409 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
3411 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
3412 FFStream *fst = ffvideo[i];
3413 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
3414 FFrame *frm = fst->frms.first;
3415 if( !frm ) { if( !done ) return; continue; }
3416 double tm = to_secs(frm->position, fst->avctx->time_base);
3417 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
3419 if( !demand ) flow_off();
3420 if( !afrm && !vfrm ) break;
3421 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
3422 vfrm->position, vfrm->fst->avctx->time_base,
3423 afrm->position, afrm->fst->avctx->time_base);
3424 FFrame *frm = v <= 0 ? vfrm : afrm;
3425 if( frm == afrm ) mux_audio(frm);
3426 if( frm == vfrm ) mux_video(frm);
3435 mux_lock->lock("FFMPEG::run");
3438 for( int i=0; i<ffaudio.size(); ++i )
3439 ffaudio[i]->drain();
3440 for( int i=0; i<ffvideo.size(); ++i )
3441 ffvideo[i]->drain();
3443 for( int i=0; i<ffaudio.size(); ++i )
3444 ffaudio[i]->flush();
3445 for( int i=0; i<ffvideo.size(); ++i )
3446 ffvideo[i]->flush();
3450 int FFMPEG::ff_total_audio_channels()
3452 return astrm_index.size();
3455 int FFMPEG::ff_total_astreams()
3457 return ffaudio.size();
3460 int FFMPEG::ff_audio_channels(int stream)
3462 return ffaudio[stream]->channels;
3465 int FFMPEG::ff_sample_rate(int stream)
3467 return ffaudio[stream]->sample_rate;
3470 const char* FFMPEG::ff_audio_format(int stream)
3472 AVStream *st = ffaudio[stream]->st;
3473 AVCodecID id = st->codecpar->codec_id;
3474 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
3475 return desc ? desc->name : _("Unknown");
3478 int FFMPEG::ff_audio_pid(int stream)
3480 return ffaudio[stream]->st->id;
3483 int64_t FFMPEG::ff_audio_samples(int stream)
3485 return ffaudio[stream]->length;
3488 // find audio astream/channels with this program,
3489 // or all program audio channels (astream=-1)
3490 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
3494 int vidx = ffvideo[vstream]->fidx;
3495 // find first program with this video stream
3496 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
3497 AVProgram *pgrm = fmt_ctx->programs[i];
3498 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
3499 int st_idx = pgrm->stream_index[j];
3500 AVStream *st = fmt_ctx->streams[st_idx];
3501 if( st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
3502 if( st_idx == vidx ) pidx = i;
3505 if( pidx < 0 ) return -1;
3507 int64_t channels = 0;
3508 AVProgram *pgrm = fmt_ctx->programs[pidx];
3509 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
3510 int aidx = pgrm->stream_index[j];
3511 AVStream *st = fmt_ctx->streams[aidx];
3512 if( st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
3513 if( astream > 0 ) { --astream; continue; }
3515 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
3516 if( ffaudio[i]->fidx == aidx ) astrm = i;
3518 if( ret < 0 ) ret = astrm;
3519 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
3520 channels |= mask << ffaudio[astrm]->channel0;
3522 if( !astream ) break;
3524 channel_mask = channels;
3529 int FFMPEG::ff_total_video_layers()
3531 return vstrm_index.size();
3534 int FFMPEG::ff_total_vstreams()
3536 return ffvideo.size();
3539 int FFMPEG::ff_video_width(int stream)
3541 FFVideoStream *vst = ffvideo[stream];
3542 return !vst->transpose ? vst->width : vst->height;
3545 int FFMPEG::ff_video_height(int stream)
3547 FFVideoStream *vst = ffvideo[stream];
3548 return !vst->transpose ? vst->height : vst->width;
3551 int FFMPEG::ff_set_video_width(int stream, int width)
3553 FFVideoStream *vst = ffvideo[stream];
3554 int *vw = !vst->transpose ? &vst->width : &vst->height, w = *vw;
3559 int FFMPEG::ff_set_video_height(int stream, int height)
3561 FFVideoStream *vst = ffvideo[stream];
3562 int *vh = !vst->transpose ? &vst->height : &vst->width, h = *vh;
3567 int FFMPEG::ff_coded_width(int stream)
3569 return ffvideo[stream]->avctx->coded_width;
3572 int FFMPEG::ff_coded_height(int stream)
3574 return ffvideo[stream]->avctx->coded_height;
3577 float FFMPEG::ff_aspect_ratio(int stream)
3579 //return ffvideo[stream]->aspect_ratio;
3580 AVFormatContext *fmt_ctx = ffvideo[stream]->fmt_ctx;
3581 AVStream *strm = ffvideo[stream]->st;
3582 AVCodecParameters *par = ffvideo[stream]->st->codecpar;
3584 AVRational sar = av_guess_sample_aspect_ratio(fmt_ctx, strm, NULL);
3586 av_reduce(&dar.num, &dar.den,
3587 par->width * sar.num,
3588 par->height * sar.den,
3592 return ffvideo[stream]->aspect_ratio;
3595 const char* FFMPEG::ff_video_codec(int stream)
3597 AVStream *st = ffvideo[stream]->st;
3598 AVCodecID id = st->codecpar->codec_id;
3599 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
3600 return desc ? desc->name : _("Unknown");
3603 int FFMPEG::ff_color_range(int stream)
3605 return ffvideo[stream]->color_range;
3608 int FFMPEG::ff_color_space(int stream)
3610 return ffvideo[stream]->color_space;
3613 double FFMPEG::ff_frame_rate(int stream)
3615 return ffvideo[stream]->frame_rate;
3618 int64_t FFMPEG::ff_video_frames(int stream)
3620 return ffvideo[stream]->length;
3623 int FFMPEG::ff_video_pid(int stream)
3625 return ffvideo[stream]->st->id;
3628 int FFMPEG::ff_video_mpeg_color_range(int stream)
3630 return ffvideo[stream]->st->codecpar->color_range == AVCOL_RANGE_MPEG ? 1 : 0;
3633 int FFMPEG::ff_interlace(int stream)
3635 // https://ffmpeg.org/doxygen/trunk/structAVCodecParserContext.html
3636 /* reads from demuxer because codec frame not ready */
3637 int interlace0 = ffvideo[stream]->st->codecpar->field_order;
3643 return ILACE_MODE_TOP_FIRST;
3646 return ILACE_MODE_BOTTOM_FIRST;
3647 case AV_FIELD_PROGRESSIVE:
3648 return ILACE_MODE_NOTINTERLACED;
3650 return ILACE_MODE_UNDETECTED;
3657 int FFMPEG::ff_cpus()
3659 return !file_base ? 1 : file_base->file->cpus;
3662 const char *FFMPEG::ff_hw_dev()
3664 return &file_base->file->preferences->use_hw_dev[0];
3667 Preferences *FFMPEG::ff_prefs()
3669 return !file_base ? 0 : file_base->file->preferences;
3672 double FFVideoStream::get_rotation_angle()
3675 int *matrix = (int*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX, &size);
3676 int len = size/sizeof(*matrix);
3677 if( !matrix || len < 5 ) return 0;
3678 const double s = 1/65536.;
3679 double theta = (!matrix[0] && !matrix[3]) || (!matrix[1] && !matrix[4]) ? 0 :
3680 atan2( s*matrix[1] / hypot(s*matrix[1], s*matrix[4]),
3681 s*matrix[0] / hypot(s*matrix[0], s*matrix[3])) * 180/M_PI;
3685 int FFVideoStream::flip(double theta)
3689 Preferences *preferences = ffmpeg->ff_prefs();
3690 if( !preferences || !preferences->auto_rotate ) return ret;
3691 double tolerance = 1;
3692 if( fabs(theta-0) < tolerance ) return ret;
3693 if( (theta=fmod(theta, 360)) < 0 ) theta += 360;
3694 if( fabs(theta-90) < tolerance ) {
3695 if( (ret = insert_filter("transpose", "clock")) < 0 )
3699 else if( fabs(theta-180) < tolerance ) {
3700 if( (ret=insert_filter("hflip", 0)) < 0 )
3702 if( (ret=insert_filter("vflip", 0)) < 0 )
3705 else if (fabs(theta-270) < tolerance ) {
3706 if( (ret=insert_filter("transpose", "cclock")) < 0 )
3711 char angle[BCSTRLEN];
3712 sprintf(angle, "%f", theta*M_PI/180.);
3713 if( (ret=insert_filter("rotate", angle)) < 0 )
3719 int FFVideoStream::create_filter(const char *filter_spec)
3721 double theta = get_rotation_angle();
3722 if( !theta && !filter_spec )
3724 avfilter_register_all();
3726 const char *sp = filter_spec;
3727 char filter_name[BCSTRLEN], *np = filter_name;
3728 int i = sizeof(filter_name);
3729 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
3731 const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
3732 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_VIDEO ) {
3733 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
3737 AVCodecParameters *avpar = st->codecpar;
3738 int sa_num = avpar->sample_aspect_ratio.num;
3739 if( !sa_num ) sa_num = 1;
3740 int sa_den = avpar->sample_aspect_ratio.den;
3741 if( !sa_den ) sa_num = 1;
3743 int ret = 0; char args[BCTEXTLEN];
3744 AVPixelFormat pix_fmt = (AVPixelFormat)avpar->format;
3745 snprintf(args, sizeof(args),
3746 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
3747 avpar->width, avpar->height, (int)pix_fmt,
3748 st->time_base.num, st->time_base.den, sa_num, sa_den);
3751 ret = insert_filter("buffer", args, "in");
3752 buffersrc_ctx = filt_ctx;
3756 AVFilterContext *fsrc = filt_ctx;
3759 ret = insert_filter("buffersink", 0, "out");
3760 buffersink_ctx = filt_ctx;
3763 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
3764 (uint8_t*)&pix_fmt, sizeof(pix_fmt),
3765 AV_OPT_SEARCH_CHILDREN);
3768 ret = config_filters(filter_spec, fsrc);
3770 ff_err(ret, "FFVideoStream::create_filter");
3771 return ret >= 0 ? 0 : -1;
3774 int FFAudioStream::create_filter(const char *filter_spec)
3778 avfilter_register_all();
3780 const char *sp = filter_spec;
3781 char filter_name[BCSTRLEN], *np = filter_name;
3782 int i = sizeof(filter_name);
3783 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
3785 const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
3786 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_AUDIO ) {
3787 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
3791 int ret = 0; char args[BCTEXTLEN];
3792 AVCodecParameters *avpar = st->codecpar;
3793 AVSampleFormat sample_fmt = (AVSampleFormat)avpar->format;
3794 snprintf(args, sizeof(args),
3795 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
3796 st->time_base.num, st->time_base.den, avpar->sample_rate,
3797 av_get_sample_fmt_name(sample_fmt), avpar->channel_layout);
3800 ret = insert_filter("abuffer", args, "in");
3801 buffersrc_ctx = filt_ctx;
3803 AVFilterContext *fsrc = filt_ctx;
3806 ret = insert_filter("abuffersink", 0, "out");
3807 buffersink_ctx = filt_ctx;
3810 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
3811 (uint8_t*)&sample_fmt, sizeof(sample_fmt),
3812 AV_OPT_SEARCH_CHILDREN);
3814 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
3815 (uint8_t*)&avpar->channel_layout,
3816 sizeof(avpar->channel_layout), AV_OPT_SEARCH_CHILDREN);
3818 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
3819 (uint8_t*)&sample_rate, sizeof(sample_rate),
3820 AV_OPT_SEARCH_CHILDREN);
3822 ret = config_filters(filter_spec, fsrc);
3824 ff_err(ret, "FFAudioStream::create_filter");
3825 return ret >= 0 ? 0 : -1;
3828 int FFStream::insert_filter(const char *name, const char *arg, const char *inst_name)
3830 const AVFilter *filter = avfilter_get_by_name(name);
3831 if( !filter ) return -1;
3832 char filt_inst[BCSTRLEN];
3834 snprintf(filt_inst, sizeof(filt_inst), "%s_%d", name, ++filt_id);
3835 inst_name = filt_inst;
3838 filter_graph = avfilter_graph_alloc();
3839 AVFilterContext *fctx = 0;
3840 int ret = avfilter_graph_create_filter(&fctx,
3841 filter, inst_name, arg, NULL, filter_graph);
3842 if( ret >= 0 && filt_ctx )
3843 ret = avfilter_link(filt_ctx, 0, fctx, 0);
3847 avfilter_free(fctx);
3851 int FFStream::config_filters(const char *filter_spec, AVFilterContext *fsrc)
3854 AVFilterContext *fsink = buffersink_ctx;
3856 /* Endpoints for the filter graph. */
3857 AVFilterInOut *outputs = avfilter_inout_alloc();
3858 AVFilterInOut *inputs = avfilter_inout_alloc();
3859 if( !inputs || !outputs ) ret = -1;
3861 outputs->filter_ctx = fsrc;
3862 outputs->pad_idx = 0;
3864 if( !(outputs->name = av_strdup(fsrc->name)) ) ret = -1;
3867 inputs->filter_ctx = fsink;
3868 inputs->pad_idx = 0;
3870 if( !(inputs->name = av_strdup(fsink->name)) ) ret = -1;
3873 int len = strlen(fsrc->name)+2 + strlen(filter_spec) + 1;
3874 char spec[len]; sprintf(spec, "[%s]%s", fsrc->name, filter_spec);
3875 ret = avfilter_graph_parse_ptr(filter_graph, spec,
3876 &inputs, &outputs, NULL);
3878 avfilter_inout_free(&inputs);
3879 avfilter_inout_free(&outputs);
3882 ret = avfilter_link(fsrc, 0, fsink, 0);
3884 ret = avfilter_graph_config(filter_graph, NULL);
3886 ff_err(ret, "FFStream::create_filter");
3887 avfilter_graph_free(&filter_graph);
3894 AVCodecContext *FFMPEG::activate_decoder(AVStream *st)
3896 AVDictionary *copts = 0;
3897 av_dict_copy(&copts, opts, 0);
3898 AVCodecID codec_id = st->codecpar->codec_id;
3899 AVCodec *decoder = 0;
3900 switch( st->codecpar->codec_type ) {
3901 case AVMEDIA_TYPE_VIDEO:
3902 if( opt_video_decoder )
3903 decoder = avcodec_find_decoder_by_name(opt_video_decoder);
3905 video_codec_remaps.update(codec_id, decoder);
3907 case AVMEDIA_TYPE_AUDIO:
3908 if( opt_audio_decoder )
3909 decoder = avcodec_find_decoder_by_name(opt_audio_decoder);
3911 audio_codec_remaps.update(codec_id, decoder);
3916 if( !decoder && !(decoder = avcodec_find_decoder(codec_id)) ) {
3917 eprintf(_("cant find decoder codec %d\n"), (int)codec_id);
3920 AVCodecContext *avctx = avcodec_alloc_context3(decoder);
3922 eprintf(_("cant allocate codec context\n"));
3925 avcodec_parameters_to_context(avctx, st->codecpar);
3926 if( !av_dict_get(copts, "threads", NULL, 0) )
3927 avctx->thread_count = ff_cpus();
3928 int ret = avcodec_open2(avctx, decoder, &copts);
3929 av_dict_free(&copts);
3931 avcodec_free_context(&avctx);
3937 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
3940 av_init_packet(&pkt);
3941 AVFrame *frame = av_frame_alloc();
3943 fprintf(stderr,"FFMPEG::scan: ");
3944 fprintf(stderr,_("av_frame_alloc failed\n"));
3945 fprintf(stderr,"FFMPEG::scan:file=%s\n", file_base->asset->path);
3949 index_state->add_video_markers(ffvideo.size());
3950 index_state->add_audio_markers(ffaudio.size());
3952 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
3953 AVStream *st = fmt_ctx->streams[i];
3954 AVCodecContext *avctx = activate_decoder(st);
3956 AVCodecParameters *avpar = st->codecpar;
3957 switch( avpar->codec_type ) {
3958 case AVMEDIA_TYPE_VIDEO: {
3959 int vidx = ffvideo.size();
3960 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
3961 if( vidx < 0 ) break;
3962 ffvideo[vidx]->avctx = avctx;
3964 case AVMEDIA_TYPE_AUDIO: {
3965 int aidx = ffaudio.size();
3966 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3967 if( aidx < 0 ) break;
3968 ffaudio[aidx]->avctx = avctx;
3973 fprintf(stderr,"FFMPEG::scan: ");
3974 fprintf(stderr,_("codec open failed\n"));
3975 fprintf(stderr,"FFMPEG::scan:file=%s\n", file_base->asset->path);
3976 avcodec_free_context(&avctx);
3980 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
3981 AVStream *st = fmt_ctx->streams[i];
3982 AVCodecParameters *avpar = st->codecpar;
3983 if( avpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
3984 int64_t tstmp = st->start_time;
3985 if( tstmp == AV_NOPTS_VALUE ) continue;
3986 int aidx = ffaudio.size();
3987 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3988 if( aidx < 0 ) continue;
3989 FFAudioStream *aud = ffaudio[aidx];
3990 tstmp -= aud->nudge;
3991 double secs = to_secs(tstmp, st->time_base);
3992 aud->curr_pos = secs * aud->sample_rate + 0.5;
3996 for( int64_t count=0; !*canceled; ++count ) {
3997 av_packet_unref(&pkt);
3998 pkt.data = 0; pkt.size = 0;
4000 int ret = av_read_frame(fmt_ctx, &pkt);
4002 if( ret == AVERROR_EOF ) break;
4003 if( ++errs > 100 ) {
4004 ff_err(ret,_("over 100 read_frame errs\n"));
4009 if( !pkt.data ) continue;
4010 int i = pkt.stream_index;
4011 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
4012 AVStream *st = fmt_ctx->streams[i];
4013 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
4015 AVCodecParameters *avpar = st->codecpar;
4016 switch( avpar->codec_type ) {
4017 case AVMEDIA_TYPE_VIDEO: {
4018 int vidx = ffvideo.size();
4019 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
4020 if( vidx < 0 ) break;
4021 FFVideoStream *vid = ffvideo[vidx];
4022 if( !vid->avctx ) break;
4023 int64_t tstmp = pkt.pts;
4024 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
4025 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
4026 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
4027 double secs = to_secs(tstmp, st->time_base);
4028 int64_t frm = secs * vid->frame_rate + 0.5;
4029 if( frm < 0 ) frm = 0;
4030 index_state->put_video_mark(vidx, frm, pkt.pos);
4033 ret = avcodec_send_packet(vid->avctx, pkt);
4034 if( ret < 0 ) break;
4035 while( (ret=vid->decode_frame(frame)) > 0 ) {}
4038 case AVMEDIA_TYPE_AUDIO: {
4039 int aidx = ffaudio.size();
4040 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
4041 if( aidx < 0 ) break;
4042 FFAudioStream *aud = ffaudio[aidx];
4043 if( !aud->avctx ) break;
4044 int64_t tstmp = pkt.pts;
4045 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
4046 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
4047 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
4048 double secs = to_secs(tstmp, st->time_base);
4049 int64_t sample = secs * aud->sample_rate + 0.5;
4051 index_state->put_audio_mark(aidx, sample, pkt.pos);
4053 ret = avcodec_send_packet(aud->avctx, &pkt);
4054 if( ret < 0 ) break;
4055 int ch = aud->channel0, nch = aud->channels;
4056 int64_t pos = index_state->pos(ch);
4057 if( pos != aud->curr_pos ) {
4058 if( abs(pos-aud->curr_pos) > 1 )
4059 printf("audio%d pad %jd %jd (%jd)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
4060 index_state->pad_data(ch, nch, aud->curr_pos);
4062 while( (ret=aud->decode_frame(frame)) > 0 ) {
4063 //if( frame->channels != nch ) break;
4064 aud->init_swr(frame->channels, frame->format, frame->sample_rate);
4066 int len = aud->get_samples(samples,
4067 &frame->extended_data[0], frame->nb_samples);
4068 pos = aud->curr_pos;
4069 if( (aud->curr_pos += len) >= 0 ) {
4071 samples += -pos * nch;
4072 len = aud->curr_pos;
4074 for( int i=0; i<nch; ++i )
4075 index_state->put_data(ch+i,nch,samples+i,len);
4082 av_frame_free(&frame);
4086 void FFStream::load_markers(IndexMarks &marks, double rate)
4089 int64_t sz = marks.size();
4090 int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
4091 int nb_ent = st->nb_index_entries;
4092 // some formats already have an index
4094 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
4095 int64_t tstmp = ep->timestamp;
4096 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
4097 double secs = ffmpeg->to_secs(tstmp, st->time_base);
4098 int64_t no = secs * rate;
4099 while( in < sz && marks[in].no <= no ) ++in;
4101 int64_t len = sz - in;
4102 int64_t count = max_entries - nb_ent;
4103 if( count > len ) count = len;
4104 for( int i=0; i<count; ++i ) {
4105 int k = in + i * len / count;
4106 int64_t no = marks[k].no, pos = marks[k].pos;
4107 double secs = (double)no / rate;
4108 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
4109 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
4110 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);
4116 * 1) if the format context has a timecode
4117 * return fmt_ctx->timecode - 0
4118 * 2) if the layer/channel has a timecode
4119 * return st->timecode - (start_time-nudge)
4120 * 3) find the 1st program with stream, find 1st program video stream,
4121 * if video stream has a timecode, return st->timecode - (start_time-nudge)
4122 * 4) find timecode in any stream, return st->timecode
4123 * 5) read 100 packets, save ofs=pkt.pts*st->time_base - st->nudge:
4124 * decode frame for video stream of 1st program
4125 * if frame->timecode has a timecode, return frame->timecode - ofs
4126 * if side_data has gop timecode, return gop->timecode - ofs
4127 * if side_data has smpte timecode, return smpte->timecode - ofs
4128 * 6) if the filename/url scans *date_time.ext, return date_time
4129 * 7) if stat works on the filename/url, return mtime
4130 * 8) return -1 failure
4132 double FFMPEG::get_initial_timecode(int data_type, int channel, double frame_rate)
4134 AVRational rate = check_frame_rate(0, frame_rate);
4135 if( !rate.num ) return -1;
4136 // format context timecode
4137 AVDictionaryEntry *tc = av_dict_get(fmt_ctx->metadata, "timecode", 0, 0);
4138 if( tc ) return ff_get_timecode(tc->value, rate, 0);
4140 if( open_decoder() ) return -1;
4143 int codec_type = -1, fidx = -1;
4144 switch( data_type ) {
4146 codec_type = AVMEDIA_TYPE_AUDIO;
4147 int aidx = astrm_index[channel].st_idx;
4148 FFAudioStream *aud = ffaudio[aidx];
4152 AVDictionaryEntry *tref = av_dict_get(fmt_ctx->metadata, "time_reference", 0, 0);
4153 if( tref && aud && aud->sample_rate )
4154 return strtod(tref->value, 0) / aud->sample_rate;
4157 codec_type = AVMEDIA_TYPE_VIDEO;
4158 int vidx = vstrm_index[channel].st_idx;
4159 FFVideoStream *vid = ffvideo[vidx];
4165 if( codec_type < 0 ) return -1;
4167 tc = av_dict_get(st->metadata, "timecode", 0, 0);
4170 // find first program which references this stream
4172 for( int i=0, m=fmt_ctx->nb_programs; pidx<0 && i<m; ++i ) {
4173 AVProgram *pgrm = fmt_ctx->programs[i];
4174 for( int j=0, n=pgrm->nb_stream_indexes; j<n; ++j ) {
4175 int st_idx = pgrm->stream_index[j];
4176 if( st_idx == fidx ) { pidx = i; break; }
4181 AVProgram *pgrm = fmt_ctx->programs[pidx];
4182 for( int j=0, n=pgrm->nb_stream_indexes; j<n; ++j ) {
4183 int st_idx = pgrm->stream_index[j];
4184 AVStream *tst = fmt_ctx->streams[st_idx];
4185 if( !tst ) continue;
4186 if( tst->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
4187 st = tst; fidx = st_idx;
4193 for( int i=0, n=fmt_ctx->nb_streams; i<n; ++i ) {
4194 AVStream *tst = fmt_ctx->streams[i];
4195 if( !tst ) continue;
4196 if( tst->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
4203 tc = av_dict_get(st->metadata, "timecode", 0, 0);
4207 // any timecode, includes -data- streams
4208 for( int i=0, n=fmt_ctx->nb_streams; i<n; ++i ) {
4209 AVStream *tst = fmt_ctx->streams[i];
4210 if( !tst ) continue;
4211 if( (tc = av_dict_get(tst->metadata, "timecode", 0, 0)) ) {
4218 if( st && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
4219 if( st->r_frame_rate.num && st->r_frame_rate.den )
4220 rate = st->r_frame_rate;
4221 nudge = st->start_time;
4222 for( int i=0; i<ffvideo.size(); ++i ) {
4223 if( ffvideo[i]->st == st ) {
4224 nudge = ffvideo[i]->nudge;
4230 if( tc ) { // return timecode
4231 double secs = st->start_time == AV_NOPTS_VALUE ? 0 :
4232 to_secs(st->start_time - nudge, st->time_base);
4233 return ff_get_timecode(tc->value, rate, secs);
4236 if( !st || fidx < 0 ) return -1;
4239 AVCodecContext *av_ctx = activate_decoder(st);
4241 fprintf(stderr,"activate_decoder failed\n");
4244 avCodecContext avctx(av_ctx); // auto deletes
4245 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO &&
4246 avctx->framerate.num && avctx->framerate.den )
4247 rate = avctx->framerate;
4249 avPacket pkt; // auto deletes
4250 avFrame frame; // auto deletes
4252 fprintf(stderr,"av_frame_alloc failed\n");
4256 int64_t max_packets = 100;
4257 char tcbuf[AV_TIMECODE_STR_SIZE];
4259 for( int64_t count=0; count<max_packets; ++count ) {
4260 av_packet_unref(pkt);
4261 pkt->data = 0; pkt->size = 0;
4263 int ret = av_read_frame(fmt_ctx, pkt);
4265 if( ret == AVERROR_EOF ) break;
4266 if( ++errs > 100 ) {
4267 fprintf(stderr,"over 100 read_frame errs\n");
4272 if( !pkt->data ) continue;
4273 int i = pkt->stream_index;
4274 if( i != fidx ) continue;
4275 int64_t tstmp = pkt->pts;
4276 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt->dts;
4277 double secs = to_secs(tstmp - nudge, st->time_base);
4278 ret = avcodec_send_packet(avctx, pkt);
4279 if( ret < 0 ) return -1;
4281 while( (ret = avcodec_receive_frame(avctx, frame)) >= 0 ) {
4282 if( (tc = av_dict_get(frame->metadata, "timecode", 0, 0)) )
4283 return ff_get_timecode(tc->value, rate, secs);
4284 int k = frame->nb_side_data;
4285 AVFrameSideData *side_data = 0;
4287 side_data = frame->side_data[k];
4288 switch( side_data->type ) {
4289 case AV_FRAME_DATA_GOP_TIMECODE: {
4290 int64_t data = *(int64_t *)side_data->data;
4291 int sz = sizeof(data);
4292 if( side_data->size >= sz ) {
4293 av_timecode_make_mpeg_tc_string(tcbuf, data);
4294 return ff_get_timecode(tcbuf, rate, secs);
4297 case AV_FRAME_DATA_S12M_TIMECODE: {
4298 uint32_t *data = (uint32_t *)side_data->data;
4299 int n = data[0], sz = (n+1)*sizeof(*data);
4300 if( side_data->size >= sz ) {
4301 av_timecode_make_smpte_tc_string(tcbuf, data[n], 0);
4302 return ff_get_timecode(tcbuf, rate, secs);
4311 char *path = fmt_ctx->url;
4312 char *bp = strrchr(path, '/');
4313 if( !bp ) bp = path; else ++bp;
4314 char *cp = strrchr(bp, '.');
4315 if( cp && (cp-=(8+1+6)) >= bp ) {
4317 int year,mon,day, hour,min,sec, frm=0;
4318 if( sscanf(cp,"%4d%2d%2d%[_-]%2d%2d%2d",
4319 &year,&mon,&day, sep, &hour,&min,&sec) == 7 ) {
4321 // year>=1970,mon=1..12,day=1..31, hour=0..23,min=0..59,sec=0..60
4322 if( (ch=='_' || ch=='-' ) &&
4323 year >= 1970 && mon>=1 && mon<=12 && day>=1 && day<=31 &&
4324 hour>=0 && hour<24 && min>=0 && min<60 && sec>=0 && sec<=60 ) {
4325 sprintf(tcbuf,"%d:%02d:%02d:%02d", hour,min,sec, frm);
4326 return ff_get_timecode(tcbuf, rate, 0);
4331 if( stat(path, &tst) >= 0 ) {
4332 time_t t = (time_t)tst.st_mtim.tv_sec;
4334 localtime_r(&t, &tm);
4335 int64_t us = tst.st_mtim.tv_nsec / 1000;
4336 int frm = us/1000000. * frame_rate;
4337 sprintf(tcbuf,"%d:%02d:%02d:%02d", tm.tm_hour, tm.tm_min, tm.tm_sec, frm);
4338 return ff_get_timecode(tcbuf, rate, 0);
4343 double FFMPEG::ff_get_timecode(char *str, AVRational rate, double pos)
4346 if( av_timecode_init_from_string(&tc, rate, str, fmt_ctx) )
4348 double secs = (double)tc.start / tc.fps - pos;
4349 if( secs < 0 ) secs = 0;
4353 double FFMPEG::get_timecode(const char *path, int data_type, int channel, double rate)
4356 if( ffmpeg.init_decoder(path) ) return -1;
4357 return ffmpeg.get_initial_timecode(data_type, channel, rate);