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;
383 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
384 int FFStream::decode_hw_format(const AVCodec *decoder, AVHWDeviceType type)
386 int FFStream::decode_hw_format(AVCodec *decoder, AVHWDeviceType type)
392 int FFStream::decode_activate()
394 if( reading < 0 && (reading=ffmpeg->decode_activate()) > 0 ) {
395 ff_lock("FFStream::decode_activate");
397 AVDictionary *copts = 0;
398 av_dict_copy(&copts, ffmpeg->opts, 0);
400 AVHWDeviceType hw_type = decode_hw_activate();
402 // this should be avformat_copy_context(), but no copy avail
403 ret = avformat_open_input(&fmt_ctx,
404 ffmpeg->fmt_ctx->url, ffmpeg->fmt_ctx->iformat, &copts);
406 ret = avformat_find_stream_info(fmt_ctx, 0);
407 st = fmt_ctx->streams[fidx];
410 while( ret >= 0 && st != 0 && !reading ) {
411 AVCodecID codec_id = st->codecpar->codec_id;
412 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
413 const AVCodec *decoder = 0;
415 AVCodec *decoder = 0;
418 if( ffmpeg->opt_video_decoder )
419 decoder = avcodec_find_decoder_by_name(ffmpeg->opt_video_decoder);
421 ffmpeg->video_codec_remaps.update(codec_id, decoder);
423 else if( is_audio() ) {
424 if( ffmpeg->opt_audio_decoder )
425 decoder = avcodec_find_decoder_by_name(ffmpeg->opt_audio_decoder);
427 ffmpeg->audio_codec_remaps.update(codec_id, decoder);
430 decoder = avcodec_find_decoder(codec_id);
431 avctx = avcodec_alloc_context3(decoder);
433 eprintf(_("cant allocate codec context\n"));
434 ret = AVERROR(ENOMEM);
436 if( ret >= 0 && hw_type != AV_HWDEVICE_TYPE_NONE ) {
437 ret = decode_hw_format(decoder, hw_type);
440 avcodec_parameters_to_context(avctx, st->codecpar);
441 if( !av_dict_get(copts, "threads", NULL, 0) )
442 avctx->thread_count = ffmpeg->ff_cpus();
443 ret = avcodec_open2(avctx, decoder, &copts);
445 AVFrame *hw_frame = 0;
446 if( ret >= 0 && hw_type != AV_HWDEVICE_TYPE_NONE ) {
447 if( !(hw_frame=av_frame_alloc()) ) {
448 fprintf(stderr, "FFStream::decode_activate: av_frame_alloc failed\n");
449 ret = AVERROR(ENOMEM);
452 ret = decode(hw_frame);
454 if( ret < 0 && hw_type != AV_HWDEVICE_TYPE_NONE ) {
455 ff_err(ret, "HW device init failed, using SW decode.\nfile:%s\n",
456 ffmpeg->fmt_ctx->url);
457 avcodec_close(avctx);
458 avcodec_free_context(&avctx);
459 av_buffer_unref(&hw_device_ctx);
461 av_frame_free(&hw_frame);
462 hw_type = AV_HWDEVICE_TYPE_NONE;
463 int flags = AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_ANY;
465 av_seek_frame(fmt_ctx, idx, 0, flags);
466 need_packet = 1; flushed = 0;
467 seeked = 1; st_eof(0);
471 probe_frame = hw_frame;
475 eprintf(_("open decoder failed\n"));
478 eprintf(_("can't open input file: %s\n"), ffmpeg->fmt_ctx->url);
479 av_dict_free(&copts);
485 int FFStream::read_packet()
487 av_packet_unref(ipkt);
488 int ret = av_read_frame(fmt_ctx, ipkt);
491 if( ret == AVERROR_EOF ) return 0;
492 ff_err(ret, "FFStream::read_packet: av_read_frame failed\n");
499 int FFStream::decode(AVFrame *frame)
501 if( probe_frame ) { // hw probe reads first frame
502 av_frame_ref(frame, probe_frame);
503 av_frame_free(&probe_frame);
507 int retries = MAX_RETRY;
508 frm_lock->lock("FFStream::decode");
509 while( ret >= 0 && !flushed && --retries >= 0 ) {
511 if( (ret=read_packet()) < 0 ) break;
512 AVPacket *pkt = ret > 0 ? (AVPacket*)ipkt : 0;
514 if( pkt->stream_index != st->index ) continue;
515 if( !pkt->data || !pkt->size ) continue;
517 if( (ret=avcodec_send_packet(avctx, pkt)) < 0 ) {
518 ff_err(ret, "FFStream::decode: avcodec_send_packet failed.\nfile:%s\n",
519 ffmpeg->fmt_ctx->url);
525 if( (ret=decode_frame(frame)) > 0 ) break;
534 fprintf(stderr, "FFStream::decode: Retry limit\n");
538 fprintf(stderr, "FFStream::decode: failed\n");
542 int FFStream::load_filter(AVFrame *frame)
544 int ret = av_buffersrc_add_frame_flags(buffersrc_ctx, frame, 0);
546 eprintf(_("av_buffersrc_add_frame_flags failed\n"));
550 int FFStream::read_filter(AVFrame *frame)
552 int ret = av_buffersink_get_frame(buffersink_ctx, frame);
554 if( ret == AVERROR(EAGAIN) ) return 0;
555 if( ret == AVERROR_EOF ) { st_eof(1); return -1; }
556 ff_err(ret, "FFStream::read_filter: av_buffersink_get_frame failed\n");
562 int FFStream::read_frame(AVFrame *frame)
564 av_frame_unref(frame);
565 if( !filter_graph || !buffersrc_ctx || !buffersink_ctx )
566 return decode(frame);
567 if( !fframe && !(fframe=av_frame_alloc()) ) {
568 fprintf(stderr, "FFStream::read_frame: av_frame_alloc failed\n");
572 while( !flushed && !(ret=read_filter(frame)) ) {
573 if( (ret=decode(fframe)) < 0 ) break;
574 if( ret > 0 && (ret=load_filter(fframe)) < 0 ) break;
579 int FFStream::write_packet(FFPacket &pkt)
583 av_packet_rescale_ts(pkt, avctx->time_base, st->time_base);
584 pkt->stream_index = st->index;
585 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, pkt);
588 ret = av_bsf_send_packet(bsfc, pkt);
591 if( (ret=av_bsf_receive_packet(bsfc, bs)) < 0 ) {
592 if( ret == AVERROR(EAGAIN) ) return 0;
593 if( ret == AVERROR_EOF ) return -1;
596 av_packet_rescale_ts(bs, avctx->time_base, st->time_base);
597 bs->stream_index = st->index;
598 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, bs);
602 ff_err(ret, "FFStream::write_packet: write packet failed.\nfile:%s\n",
603 ffmpeg->fmt_ctx->url);
607 int FFStream::encode_frame(AVFrame *frame)
609 int pkts = 0, ret = 0;
610 for( int retry=MAX_RETRY; --retry>=0; ) {
612 ret = avcodec_send_frame(avctx, frame);
613 if( !ret && frame ) return pkts;
614 if( ret < 0 && ret != AVERROR(EAGAIN) ) break;
615 if ( ret == AVERROR(EAGAIN) && !frame ) continue;
617 ret = avcodec_receive_packet(avctx, opkt);
618 if( !frame && ret == AVERROR_EOF ) return pkts;
620 ret = write_packet(opkt);
623 if( frame && stats_fp ) {
624 ret = write_stats_file();
628 ff_err(ret, "FFStream::encode_frame: encode failed.\nfile: %s\n",
629 ffmpeg->fmt_ctx->url);
633 int FFStream::flush()
637 int ret = encode_frame(0);
638 if( ret >= 0 && stats_fp ) {
639 ret = write_stats_file();
643 ff_err(ret, "FFStream::flush failed\n:file:%s\n",
644 ffmpeg->fmt_ctx->url);
645 return ret >= 0 ? 0 : 1;
649 int FFStream::open_stats_file()
651 stats_fp = fopen(stats_filename,"w");
652 return stats_fp ? 0 : AVERROR(errno);
655 int FFStream::close_stats_file()
658 fclose(stats_fp); stats_fp = 0;
663 int FFStream::read_stats_file()
665 int64_t len = 0; struct stat stats_st;
666 int fd = open(stats_filename, O_RDONLY);
667 int ret = fd >= 0 ? 0: ENOENT;
668 if( !ret && fstat(fd, &stats_st) )
671 len = stats_st.st_size;
672 stats_in = (char *)av_malloc(len+1);
676 if( !ret && read(fd, stats_in, len+1) != len )
680 avctx->stats_in = stats_in;
684 return !ret ? 0 : AVERROR(ret);
687 int FFStream::write_stats_file()
690 if( avctx->stats_out && (ret=strlen(avctx->stats_out)) > 0 ) {
691 int len = fwrite(avctx->stats_out, 1, ret, stats_fp);
693 ff_err(ret = AVERROR(errno), "FFStream::write_stats_file.\n%file:%s\n",
694 ffmpeg->fmt_ctx->url);
699 int FFStream::init_stats_file()
702 if( (pass & 2) && (ret = read_stats_file()) < 0 )
703 ff_err(ret, "stat file read: %s", stats_filename);
704 if( (pass & 1) && (ret=open_stats_file()) < 0 )
705 ff_err(ret, "stat file open: %s", stats_filename);
706 return ret >= 0 ? 0 : ret;
709 int FFStream::seek(int64_t no, double rate)
711 // default ffmpeg native seek
713 int64_t pos = no, pkt_pos = -1;
714 IndexMarks *index_markers = get_markers();
715 if( index_markers && index_markers->size() > 1 ) {
716 IndexMarks &marks = *index_markers;
717 int i = marks.find(pos);
718 int64_t n = i < 0 ? (i=0) : marks[i].no;
719 // if indexed seek point not too far away (<30 secs), use index
720 if( no-n < 30*rate ) {
723 if( i < marks.size() ) pkt_pos = marks[i].pos;
727 if( pos == curr_pos ) return 0;
729 double secs = pos < 0 ? 0. : pos / rate;
730 AVRational time_base = st->time_base;
731 int64_t tstmp = time_base.num > 0 ? secs * time_base.den/time_base.num : 0;
732 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
733 int nb_index_entries = avformat_index_get_entries_count(st);
736 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
737 if( nb_index_entries > 0 ) tstmp = (avformat_index_get_entry(st, 0))->timestamp;
739 if( st->nb_index_entries > 0 ) tstmp = st->index_entries[0].timestamp;
741 else if( st->start_time != AV_NOPTS_VALUE ) tstmp = st->start_time;
742 #if LIBAVCODEC_VERSION_INT <= AV_VERSION_INT(58,134,100)
743 else if( st->first_dts != AV_NOPTS_VALUE ) tstmp = st->first_dts;
745 else tstmp = INT64_MIN+1;
747 else if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
750 // seek all streams using the default timebase.
751 // this is how ffmpeg and ffplay work. stream seeks are less tested.
752 tstmp = av_rescale_q(tstmp, time_base, AV_TIME_BASE_Q);
755 frm_lock->lock("FFStream::seek");
756 av_frame_free(&probe_frame);
757 avcodec_flush_buffers(avctx);
758 avformat_flush(fmt_ctx);
760 int64_t seek = tstmp;
761 int flags = AVSEEK_FLAG_ANY;
762 if( !(fmt_ctx->iformat->flags & AVFMT_NO_BYTE_SEEK) && pkt_pos >= 0 ) {
764 flags = AVSEEK_FLAG_BYTE;
766 int ret = avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, seek, INT64_MAX, flags);
768 // finds the first index frame below the target time
769 int flags = AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_ANY;
770 int ret = av_seek_frame(fmt_ctx, idx, tstmp, flags);
772 int retry = MAX_RETRY;
774 need_packet = 0; flushed = 0;
775 seeked = 1; st_eof(0);
776 // read up to retry packets, limited to npkts in stream, and not pkt.pos past pkt_pos
777 while( --retry >= 0 ) {
778 if( read_packet() <= 0 ) { ret = -1; break; }
779 if( ipkt->stream_index != st->index ) continue;
780 if( !ipkt->data || !ipkt->size ) continue;
781 if( pkt_pos >= 0 && ipkt->pos >= pkt_pos ) break;
782 if( --npkts <= 0 ) break;
783 int64_t pkt_ts = ipkt->dts != AV_NOPTS_VALUE ? ipkt->dts : ipkt->pts;
784 if( pkt_ts == AV_NOPTS_VALUE ) continue;
785 if( pkt_ts >= tstmp ) break;
788 ff_err(AVERROR(EIO), "FFStream::seek: %s\n"
789 " retry limit, pos=%jd tstmp=%jd, ",
790 ffmpeg->fmt_ctx->url, pos, tstmp);
794 ret = avcodec_send_packet(avctx, ipkt);
796 //some codecs need more than one pkt to resync
797 if( ret == AVERROR_INVALIDDATA ) ret = 0;
799 ff_err(ret, "FFStream::avcodec_send_packet failed.\nseek:%s\n",
800 ffmpeg->fmt_ctx->url);
806 printf("** seek fail %jd, %jd\n", pos, tstmp);
807 seeked = need_packet = 0;
811 //printf("seeked pos = %ld, %ld\n", pos, tstmp);
812 seek_pos = curr_pos = pos;
816 FFAudioStream::FFAudioStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
817 : FFStream(ffmpeg, strm, fidx)
820 channel0 = channels = 0;
823 frame_sz = AUDIO_MIN_FRAME_SZ;
825 resample_context = 0;
826 swr_ichs = swr_ifmt = swr_irate = 0;
835 bfr = new float[bsz];
840 FFAudioStream::~FFAudioStream()
842 if( resample_context ) swr_free(&resample_context);
847 void FFAudioStream::init_swr(int ichs, int ifmt, int irate)
849 if( resample_context ) {
850 if( swr_ichs == ichs && swr_ifmt == ifmt && swr_irate == irate )
852 swr_free(&resample_context);
854 swr_ichs = ichs; swr_ifmt = ifmt; swr_irate = irate;
855 if( ichs == channels && ifmt == AV_SAMPLE_FMT_FLT && irate == sample_rate )
857 uint64_t ilayout = av_get_default_channel_layout(ichs);
858 if( !ilayout ) ilayout = ((uint64_t)1<<ichs) - 1;
859 uint64_t olayout = av_get_default_channel_layout(channels);
860 if( !olayout ) olayout = ((uint64_t)1<<channels) - 1;
861 resample_context = swr_alloc_set_opts(NULL,
862 olayout, AV_SAMPLE_FMT_FLT, sample_rate,
863 ilayout, (AVSampleFormat)ifmt, irate,
865 if( resample_context )
866 swr_init(resample_context);
869 int FFAudioStream::get_samples(float *&samples, uint8_t **data, int len)
871 samples = *(float **)data;
872 if( resample_context ) {
873 if( len > aud_bfr_sz ) {
879 aud_bfr = new float[aud_bfr_sz*channels];
881 int ret = swr_convert(resample_context,
882 (uint8_t**)&aud_bfr, aud_bfr_sz, (const uint8_t**)data, len);
884 ff_err(ret, "FFAudioStream::get_samples: swr_convert failed\n");
893 int FFAudioStream::load_history(uint8_t **data, int len)
896 len = get_samples(samples, data, len);
898 // biggest user bfr since seek + frame
899 realloc(mbsz + len + 1, channels);
905 int FFAudioStream::decode_frame(AVFrame *frame)
907 int first_frame = seeked; seeked = 0;
908 frame->best_effort_timestamp = AV_NOPTS_VALUE;
909 int ret = avcodec_receive_frame(avctx, frame);
911 if( first_frame ) return 0;
912 if( ret == AVERROR(EAGAIN) ) return 0;
913 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
914 ff_err(ret, "FFAudioStream::decode_frame: Could not read audio frame.\nfile:%s\n",
915 ffmpeg->fmt_ctx->url);
918 int64_t pkt_ts = frame->best_effort_timestamp;
919 if( pkt_ts != AV_NOPTS_VALUE ) {
920 double ts = ffmpeg->to_secs(pkt_ts - nudge, st->time_base);
921 double t = (double)curr_pos / sample_rate;
922 // some time_base clocks are very grainy, too grainy for audio (clicks, pops)
923 if( fabs(ts - t) > AUDIO_PTS_TOLERANCE )
924 curr_pos = ts * sample_rate + 0.5;
929 int FFAudioStream::encode_activate()
931 if( writing >= 0 ) return writing;
932 if( !avctx->codec ) return writing = 0;
933 frame_sz = avctx->codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE ?
934 10000 : avctx->frame_size;
935 return FFStream::encode_activate();
938 int64_t FFAudioStream::load_buffer(double ** const sp, int len)
940 reserve(len+1, st->codecpar->channels);
941 for( int ch=0; ch<nch; ++ch )
942 write(sp[ch], len, ch);
946 int FFAudioStream::in_history(int64_t pos)
948 if( pos > curr_pos ) return 0;
950 if( len > sz ) len = sz;
951 if( pos < curr_pos - len ) return 0;
956 int FFAudioStream::init_frame(AVFrame *frame)
958 frame->nb_samples = frame_sz;
959 frame->format = avctx->sample_fmt;
960 frame->channel_layout = avctx->channel_layout;
961 frame->sample_rate = avctx->sample_rate;
962 int ret = av_frame_get_buffer(frame, 0);
964 ff_err(ret, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
968 int FFAudioStream::load(int64_t pos, int len)
970 if( audio_seek(pos) < 0 ) return -1;
971 if( !frame && !(frame=av_frame_alloc()) ) {
972 fprintf(stderr, "FFAudioStream::load: av_frame_alloc failed\n");
975 if( mbsz < len ) mbsz = len;
976 int64_t end_pos = pos + len;
977 int ret = 0, i = len / frame_sz + MAX_RETRY;
978 while( ret>=0 && !flushed && curr_pos<end_pos && --i>=0 ) {
979 ret = read_frame(frame);
980 if( ret > 0 && frame->nb_samples > 0 ) {
981 init_swr(frame->channels, frame->format, frame->sample_rate);
982 load_history(&frame->extended_data[0], frame->nb_samples);
983 curr_pos += frame->nb_samples;
986 if( end_pos > curr_pos ) {
987 zero(end_pos - curr_pos);
990 len = curr_pos - pos;
995 int FFAudioStream::audio_seek(int64_t pos)
997 if( decode_activate() <= 0 ) return -1;
998 if( !st->codecpar ) return -1;
999 if( in_history(pos) ) return 0;
1000 if( pos == curr_pos ) return 0;
1001 reset_history(); mbsz = 0;
1002 // guarentee preload > 1sec samples
1003 if( (pos-=sample_rate) < 0 ) pos = 0;
1004 if( seek(pos, sample_rate) < 0 ) return -1;
1008 int FFAudioStream::encode(double **samples, int len)
1010 if( encode_activate() <= 0 ) return -1;
1013 int64_t count = samples ? load_buffer(samples, len) : used();
1014 int frame_sz1 = samples ? frame_sz-1 : 0;
1017 while( ret >= 0 && count > frame_sz1 ) {
1018 frm = new FFrame(this);
1019 if( (ret=frm->initted()) < 0 ) break;
1020 AVFrame *frame = *frm;
1021 len = count >= frame_sz ? frame_sz : count;
1022 float *bfrp = get_outp(len);
1023 ret = swr_convert(resample_context,
1024 (uint8_t **)frame->extended_data, len,
1025 (const uint8_t **)&bfrp, len);
1027 ff_err(ret, "FFAudioStream::encode: swr_convert failed\n");
1030 frame->nb_samples = len;
1031 frm->queue(curr_pos);
1038 return ret >= 0 ? 0 : 1;
1041 int FFAudioStream::drain()
1046 int FFAudioStream::encode_frame(AVFrame *frame)
1048 return FFStream::encode_frame(frame);
1051 int FFAudioStream::write_packet(FFPacket &pkt)
1053 return FFStream::write_packet(pkt);
1056 void FFAudioStream::load_markers()
1058 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1059 if( !index_state || idx >= index_state->audio_markers.size() ) return;
1060 if( index_state->marker_status == MARKERS_NOTTESTED ) return;
1061 FFStream::load_markers(*index_state->audio_markers[idx], sample_rate);
1064 IndexMarks *FFAudioStream::get_markers()
1066 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1067 if( !index_state || idx >= index_state->audio_markers.size() ) return 0;
1068 return index_state->audio_markers[idx];
1071 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
1072 : FFStream(ffmpeg, strm, fidx),
1073 FFVideoConvert(ffmpeg->ff_prefs())
1082 top_field_first = 0;
1088 FFVideoStream::~FFVideoStream()
1090 if( fconvert_ctx ) sws_freeContext(fconvert_ctx);
1093 AVHWDeviceType FFVideoStream::decode_hw_activate()
1095 AVHWDeviceType type = AV_HWDEVICE_TYPE_NONE;
1096 const char *hw_dev = ffmpeg->opt_hw_dev;
1097 if( !hw_dev ) hw_dev = getenv("CIN_HW_DEV");
1098 if( !hw_dev ) hw_dev = ffmpeg->ff_hw_dev();
1099 if( hw_dev && *hw_dev &&
1100 strcmp("none", hw_dev) && strcmp(_("none"), hw_dev) ) {
1101 type = av_hwdevice_find_type_by_name(hw_dev);
1102 if( type == AV_HWDEVICE_TYPE_NONE ) {
1103 fprintf(stderr, "Device type %s is not supported.\n", hw_dev);
1104 fprintf(stderr, "Available device types:");
1105 while( (type = av_hwdevice_iterate_types(type)) != AV_HWDEVICE_TYPE_NONE )
1106 fprintf(stderr, " %s", av_hwdevice_get_type_name(type));
1107 fprintf(stderr, "\n");
1112 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
1113 int FFVideoStream::decode_hw_format(const AVCodec *decoder, AVHWDeviceType type)
1115 int FFVideoStream::decode_hw_format(AVCodec *decoder, AVHWDeviceType type)
1119 hw_pix_fmt = AV_PIX_FMT_NONE;
1120 for( int i=0; ; ++i ) {
1121 const AVCodecHWConfig *config = avcodec_get_hw_config(decoder, i);
1123 fprintf(stderr, "Decoder %s does not support device type %s.\n",
1124 decoder->name, av_hwdevice_get_type_name(type));
1128 if( (config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX) != 0 &&
1129 config->device_type == type ) {
1130 hw_pix_fmt = config->pix_fmt;
1134 if( hw_pix_fmt >= 0 ) {
1135 hw_pixfmt = hw_pix_fmt;
1136 avctx->get_format = get_hw_format;
1137 ret = av_hwdevice_ctx_create(&hw_device_ctx, type, 0, 0, 0);
1139 avctx->hw_device_ctx = av_buffer_ref(hw_device_ctx);
1143 ff_err(ret, "Failed HW device create.\ndev:%s\n",
1144 av_hwdevice_get_type_name(type));
1151 AVHWDeviceType FFVideoStream::encode_hw_activate(const char *hw_dev)
1153 AVBufferRef *hw_device_ctx = 0;
1154 AVBufferRef *hw_frames_ref = 0;
1155 AVHWDeviceType type = AV_HWDEVICE_TYPE_NONE;
1156 if( strcmp(_("none"), hw_dev) ) {
1157 type = av_hwdevice_find_type_by_name(hw_dev);
1158 if( type != AV_HWDEVICE_TYPE_VAAPI ) {
1159 fprintf(stderr, "currently, only vaapi hw encode is supported\n");
1160 type = AV_HWDEVICE_TYPE_NONE;
1163 if( type != AV_HWDEVICE_TYPE_NONE ) {
1164 int ret = av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_VAAPI, 0, 0, 0);
1166 ff_err(ret, "Failed to create a HW device.\n");
1167 type = AV_HWDEVICE_TYPE_NONE;
1170 if( type != AV_HWDEVICE_TYPE_NONE ) {
1171 hw_frames_ref = av_hwframe_ctx_alloc(hw_device_ctx);
1172 if( !hw_frames_ref ) {
1173 fprintf(stderr, "Failed to create HW frame context.\n");
1174 type = AV_HWDEVICE_TYPE_NONE;
1177 if( type != AV_HWDEVICE_TYPE_NONE ) {
1178 AVHWFramesContext *frames_ctx = (AVHWFramesContext *)(hw_frames_ref->data);
1179 frames_ctx->format = AV_PIX_FMT_VAAPI;
1180 frames_ctx->sw_format = AV_PIX_FMT_NV12;
1181 frames_ctx->width = width;
1182 frames_ctx->height = height;
1183 frames_ctx->initial_pool_size = 0; // 200;
1184 int ret = av_hwframe_ctx_init(hw_frames_ref);
1186 avctx->hw_frames_ctx = av_buffer_ref(hw_frames_ref);
1187 if( !avctx->hw_frames_ctx ) ret = AVERROR(ENOMEM);
1190 ff_err(ret, "Failed to initialize HW frame context.\n");
1191 type = AV_HWDEVICE_TYPE_NONE;
1193 av_buffer_unref(&hw_frames_ref);
1198 int FFVideoStream::encode_hw_write(FFrame *picture)
1201 AVFrame *hw_frm = 0;
1202 switch( avctx->pix_fmt ) {
1203 case AV_PIX_FMT_VAAPI:
1204 hw_frm = av_frame_alloc();
1205 if( !hw_frm ) { ret = AVERROR(ENOMEM); break; }
1206 ret = av_hwframe_get_buffer(avctx->hw_frames_ctx, hw_frm, 0);
1207 if( ret < 0 ) break;
1208 ret = av_hwframe_transfer_data(hw_frm, *picture, 0);
1209 if( ret < 0 ) break;
1210 picture->set_hw_frame(hw_frm);
1215 av_frame_free(&hw_frm);
1216 ff_err(ret, "Error while transferring frame data to GPU.\n");
1220 int FFVideoStream::decode_frame(AVFrame *frame)
1222 int first_frame = seeked; seeked = 0;
1223 int ret = avcodec_receive_frame(avctx, frame);
1225 if( first_frame ) return 0;
1226 if( ret == AVERROR(EAGAIN) ) return 0;
1227 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
1228 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame.\nfile:%s\n,",
1229 ffmpeg->fmt_ctx->url);
1232 int64_t pkt_ts = frame->best_effort_timestamp;
1233 if( pkt_ts != AV_NOPTS_VALUE )
1234 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * frame_rate + 0.5;
1238 int FFVideoStream::probe(int64_t pos)
1240 int ret = video_seek(pos);
1241 if( ret < 0 ) return -1;
1242 if( !frame && !(frame=av_frame_alloc()) ) {
1243 fprintf(stderr, "FFVideoStream::probe: av_frame_alloc failed\n");
1247 if (ffmpeg->interlace_from_codec) return 1;
1249 ret = read_frame(frame);
1251 //printf("codec interlace: %i \n",frame->interlaced_frame);
1252 //printf("codec tff: %i \n",frame->top_field_first);
1254 if (!frame->interlaced_frame)
1255 ffmpeg->interlace_from_codec = AV_FIELD_PROGRESSIVE;
1256 if ((frame->interlaced_frame) && (frame->top_field_first))
1257 ffmpeg->interlace_from_codec = AV_FIELD_TT;
1258 if ((frame->interlaced_frame) && (!frame->top_field_first))
1259 ffmpeg->interlace_from_codec = AV_FIELD_BB;
1260 //printf("Interlace mode from codec: %i\n", ffmpeg->interlace_from_codec);
1264 if( frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0 )
1267 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
1268 av_frame_free(&frame);
1272 int FFVideoStream::load(VFrame *vframe, int64_t pos)
1274 int ret = video_seek(pos);
1275 if( ret < 0 ) return -1;
1276 if( !frame && !(frame=av_frame_alloc()) ) {
1277 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
1282 int i = MAX_RETRY + pos - curr_pos;
1283 int64_t cache_start = 0;
1284 while( ret>=0 && !flushed && curr_pos<=pos && --i>=0 ) {
1285 ret = read_frame(frame);
1287 if( frame->key_frame && seeking < 0 ) {
1288 int use_cache = ffmpeg->get_use_cache();
1289 if( use_cache < 0 ) {
1290 // for reverse read, reload file frame_cache from keyframe to pos
1291 ffmpeg->purge_cache();
1292 int count = preferences->cache_size /
1293 vframe->get_data_size() / 2; // try to burn only 1/2 of cache
1294 cache_start = pos - count + 1;
1300 if( seeking > 0 && curr_pos >= cache_start && curr_pos < pos ) {
1301 int vw =vframe->get_w(), vh = vframe->get_h();
1302 int vcolor_model = vframe->get_color_model();
1303 // do not use shm here, puts too much pressure on 32bit systems
1304 VFrame *cache_frame = new VFrame(vw, vh, vcolor_model, 0);
1305 ret = convert_cmodel(cache_frame, frame);
1307 ffmpeg->put_cache_frame(cache_frame, curr_pos);
1313 if( frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0 )
1316 ret = convert_cmodel(vframe, frame);
1318 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
1322 int FFVideoStream::video_seek(int64_t pos)
1324 if( decode_activate() <= 0 ) return -1;
1325 if( !st->codecpar ) return -1;
1326 if( pos == curr_pos-1 && !seeked ) return 0;
1327 // if close enough, just read up to current
1328 int gop = avctx->gop_size;
1329 if( gop < 4 ) gop = 4;
1330 if( gop > 64 ) gop = 64;
1331 int read_limit = curr_pos + 3*gop;
1332 if( pos >= curr_pos && pos <= read_limit ) return 0;
1333 // guarentee preload more than 2*gop frames
1334 if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
1338 int FFVideoStream::init_frame(AVFrame *picture)
1340 switch( avctx->pix_fmt ) {
1341 case AV_PIX_FMT_VAAPI:
1342 picture->format = AV_PIX_FMT_NV12;
1345 picture->format = avctx->pix_fmt;
1348 picture->width = avctx->width;
1349 picture->height = avctx->height;
1350 int ret = av_frame_get_buffer(picture, 32);
1354 int FFVideoStream::convert_hw_frame(AVFrame *ifrm, AVFrame *ofrm)
1356 AVPixelFormat ifmt = (AVPixelFormat)ifrm->format;
1357 AVPixelFormat ofmt = (AVPixelFormat)st->codecpar->format;
1358 ofrm->width = ifrm->width;
1359 ofrm->height = ifrm->height;
1360 ofrm->format = ofmt;
1361 int ret = av_frame_get_buffer(ofrm, 32);
1363 ff_err(ret, "FFVideoStream::convert_hw_frame:"
1364 " av_frame_get_buffer failed\n");
1367 fconvert_ctx = sws_getCachedContext(fconvert_ctx,
1368 ifrm->width, ifrm->height, ifmt,
1369 ofrm->width, ofrm->height, ofmt,
1370 SWS_POINT, NULL, NULL, NULL);
1371 if( !fconvert_ctx ) {
1372 ff_err(AVERROR(EINVAL), "FFVideoStream::convert_hw_frame:"
1373 " sws_getCachedContext() failed\n");
1376 int codec_range = st->codecpar->color_range;
1377 int codec_space = st->codecpar->color_space;
1378 const int *codec_table = sws_getCoefficients(codec_space);
1379 int *inv_table, *table, src_range, dst_range;
1380 int brightness, contrast, saturation;
1381 if( !sws_getColorspaceDetails(fconvert_ctx,
1382 &inv_table, &src_range, &table, &dst_range,
1383 &brightness, &contrast, &saturation) ) {
1384 if( src_range != codec_range || dst_range != codec_range ||
1385 inv_table != codec_table || table != codec_table )
1386 sws_setColorspaceDetails(fconvert_ctx,
1387 codec_table, codec_range, codec_table, codec_range,
1388 brightness, contrast, saturation);
1390 ret = sws_scale(fconvert_ctx,
1391 ifrm->data, ifrm->linesize, 0, ifrm->height,
1392 ofrm->data, ofrm->linesize);
1394 ff_err(ret, "FFVideoStream::convert_hw_frame:"
1395 " sws_scale() failed\nfile: %s\n",
1396 ffmpeg->fmt_ctx->url);
1402 int FFVideoStream::load_filter(AVFrame *frame)
1404 AVPixelFormat pix_fmt = (AVPixelFormat)frame->format;
1405 if( pix_fmt == hw_pixfmt ) {
1406 AVFrame *hw_frame = this->frame;
1407 av_frame_unref(hw_frame);
1408 int ret = av_hwframe_transfer_data(hw_frame, frame, 0);
1410 eprintf(_("Error retrieving data from GPU to CPU\nfile: %s\n"),
1411 ffmpeg->fmt_ctx->url);
1414 av_frame_unref(frame);
1415 ret = convert_hw_frame(hw_frame, frame);
1417 eprintf(_("Error converting data from GPU to CPU\nfile: %s\n"),
1418 ffmpeg->fmt_ctx->url);
1421 av_frame_unref(hw_frame);
1423 return FFStream::load_filter(frame);
1426 int FFVideoStream::encode(VFrame *vframe)
1428 if( encode_activate() <= 0 ) return -1;
1430 FFrame *picture = new FFrame(this);
1431 int ret = picture->initted();
1433 AVFrame *frame = *picture;
1434 frame->pts = curr_pos;
1435 ret = convert_pixfmt(vframe, frame);
1437 if( ret >= 0 && avctx->hw_frames_ctx )
1438 encode_hw_write(picture);
1440 picture->queue(curr_pos);
1444 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
1447 return ret >= 0 ? 0 : 1;
1450 int FFVideoStream::drain()
1456 int FFVideoStream::encode_frame(AVFrame *frame)
1459 frame->interlaced_frame = interlaced;
1460 frame->top_field_first = top_field_first;
1462 if( frame && frame->format == AV_PIX_FMT_VAAPI ) { // ugly
1463 int ret = avcodec_send_frame(avctx, frame);
1464 for( int retry=MAX_RETRY; !ret && --retry>=0; ) {
1465 FFPacket pkt; av_init_packet(pkt);
1466 pkt->data = NULL; pkt->size = 0;
1467 if( (ret=avcodec_receive_packet(avctx, pkt)) < 0 ) {
1468 if( ret == AVERROR(EAGAIN) ) ret = 0; // weird
1471 ret = write_packet(pkt);
1472 pkt->stream_index = 0;
1473 av_packet_unref(pkt);
1476 ff_err(ret, "FFStream::encode_frame: vaapi encode failed.\nfile: %s\n",
1477 ffmpeg->fmt_ctx->url);
1482 return FFStream::encode_frame(frame);
1485 int FFVideoStream::write_packet(FFPacket &pkt)
1487 if( !(ffmpeg->fmt_ctx->oformat->flags & AVFMT_VARIABLE_FPS) )
1489 return FFStream::write_packet(pkt);
1492 AVPixelFormat FFVideoConvert::color_model_to_pix_fmt(int color_model)
1494 switch( color_model ) {
1495 case BC_YUV422: return AV_PIX_FMT_YUYV422;
1496 case BC_RGB888: return AV_PIX_FMT_RGB24;
1497 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
1498 case BC_BGR8888: return AV_PIX_FMT_BGR0;
1499 case BC_BGR888: return AV_PIX_FMT_BGR24;
1500 case BC_ARGB8888: return AV_PIX_FMT_ARGB;
1501 case BC_ABGR8888: return AV_PIX_FMT_ABGR;
1502 case BC_RGB8: return AV_PIX_FMT_RGB8;
1503 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
1504 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
1505 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
1506 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
1507 case BC_RGB565: return AV_PIX_FMT_RGB565;
1508 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
1509 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
1510 case BC_AYUV16161616: return AV_PIX_FMT_AYUV64LE;
1511 case BC_GBRP: return AV_PIX_FMT_GBRP;
1515 return AV_PIX_FMT_NB;
1518 int FFVideoConvert::pix_fmt_to_color_model(AVPixelFormat pix_fmt)
1521 case AV_PIX_FMT_YUYV422: return BC_YUV422;
1522 case AV_PIX_FMT_RGB24: return BC_RGB888;
1523 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
1524 case AV_PIX_FMT_BGR0: return BC_BGR8888;
1525 case AV_PIX_FMT_BGR24: return BC_BGR888;
1526 case AV_PIX_FMT_ARGB: return BC_ARGB8888;
1527 case AV_PIX_FMT_ABGR: return BC_ABGR8888;
1528 case AV_PIX_FMT_RGB8: return BC_RGB8;
1529 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
1530 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
1531 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
1532 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
1533 case AV_PIX_FMT_RGB565: return BC_RGB565;
1534 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
1535 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
1536 case AV_PIX_FMT_AYUV64LE: return BC_AYUV16161616;
1537 case AV_PIX_FMT_GBRP: return BC_GBRP;
1544 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip)
1546 AVFrame *ipic = av_frame_alloc();
1547 int ret = convert_picture_vframe(frame, ip, ipic);
1548 av_frame_free(&ipic);
1552 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip, AVFrame *ipic)
1553 { // picture = vframe
1554 int cmodel = frame->get_color_model();
1555 AVPixelFormat ofmt = color_model_to_pix_fmt(cmodel);
1556 if( ofmt == AV_PIX_FMT_NB ) return -1;
1557 int size = av_image_fill_arrays(ipic->data, ipic->linesize,
1558 frame->get_data(), ofmt, frame->get_w(), frame->get_h(), 1);
1559 if( size < 0 ) return -1;
1561 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1562 int ysz = bpp * frame->get_w(), usz = ysz;
1572 // override av_image_fill_arrays() for planar types
1573 ipic->data[0] = frame->get_y(); ipic->linesize[0] = ysz;
1574 ipic->data[1] = frame->get_u(); ipic->linesize[1] = usz;
1575 ipic->data[2] = frame->get_v(); ipic->linesize[2] = usz;
1578 ipic->data[0] = frame->get_data();
1579 ipic->linesize[0] = frame->get_bytes_per_line();
1583 AVPixelFormat pix_fmt = (AVPixelFormat)ip->format;
1584 FFVideoStream *vid =(FFVideoStream *)this;
1585 if( pix_fmt == vid->hw_pixfmt ) {
1587 if( !sw_frame && !(sw_frame=av_frame_alloc()) )
1588 ret = AVERROR(ENOMEM);
1590 ret = av_hwframe_transfer_data(sw_frame, ip, 0);
1592 pix_fmt = (AVPixelFormat)ip->format;
1595 eprintf(_("Error retrieving data from GPU to CPU\nfile: %s\n"),
1596 vid->ffmpeg->fmt_ctx->url);
1600 convert_ctx = sws_getCachedContext(convert_ctx, ip->width, ip->height, pix_fmt,
1601 frame->get_w(), frame->get_h(), ofmt, SWS_POINT, NULL, NULL, NULL);
1602 if( !convert_ctx ) {
1603 fprintf(stderr, "FFVideoConvert::convert_picture_frame:"
1604 " sws_getCachedContext() failed\n");
1608 int color_range = 0;
1609 switch( preferences->yuv_color_range ) {
1610 case BC_COLORS_JPEG: color_range = 1; break;
1611 case BC_COLORS_MPEG: color_range = 0; break;
1613 int color_space = SWS_CS_ITU601;
1614 switch( preferences->yuv_color_space ) {
1615 case BC_COLORS_BT601_PAL: color_space = SWS_CS_ITU601; break;
1616 case BC_COLORS_BT601_NTSC: color_space = SWS_CS_SMPTE170M; break;
1617 case BC_COLORS_BT709: color_space = SWS_CS_ITU709; break;
1618 case BC_COLORS_BT2020_NCL:
1619 case BC_COLORS_BT2020_CL: color_space = SWS_CS_BT2020; break;
1621 const int *color_table = sws_getCoefficients(color_space);
1623 int *inv_table, *table, src_range, dst_range;
1624 int brightness, contrast, saturation;
1625 if( !sws_getColorspaceDetails(convert_ctx,
1626 &inv_table, &src_range, &table, &dst_range,
1627 &brightness, &contrast, &saturation) ) {
1628 if( src_range != color_range || dst_range != color_range ||
1629 inv_table != color_table || table != color_table )
1630 sws_setColorspaceDetails(convert_ctx,
1631 color_table, color_range, color_table, color_range,
1632 brightness, contrast, saturation);
1635 int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ip->height,
1636 ipic->data, ipic->linesize);
1638 ff_err(ret, "FFVideoConvert::convert_picture_frame: sws_scale() failed\nfile: %s\n",
1639 vid->ffmpeg->fmt_ctx->url);
1645 int FFVideoConvert::convert_cmodel(VFrame *frame, AVFrame *ip)
1647 // try direct transfer
1648 if( !convert_picture_vframe(frame, ip) ) return 1;
1649 // use indirect transfer
1650 AVPixelFormat ifmt = (AVPixelFormat)ip->format;
1651 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
1653 for( int i = 0; i <desc->nb_components; ++i ) {
1654 int bits = desc->comp[i].depth;
1655 if( bits > max_bits ) max_bits = bits;
1657 int imodel = pix_fmt_to_color_model(ifmt);
1658 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1659 int cmodel = frame->get_color_model();
1660 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1661 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1662 imodel = cmodel_is_yuv ?
1663 (BC_CModels::has_alpha(cmodel) ?
1665 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1666 (BC_CModels::has_alpha(cmodel) ?
1667 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1668 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1670 VFrame vframe(ip->width, ip->height, imodel);
1671 if( convert_picture_vframe(&vframe, ip) ) return -1;
1672 frame->transfer_from(&vframe);
1676 int FFVideoConvert::transfer_cmodel(VFrame *frame, AVFrame *ifp)
1678 int ret = convert_cmodel(frame, ifp);
1680 const AVDictionary *src = ifp->metadata;
1681 AVDictionaryEntry *t = NULL;
1682 BC_Hash *hp = frame->get_params();
1684 while( (t=av_dict_get(src, "", t, AV_DICT_IGNORE_SUFFIX)) )
1685 hp->update(t->key, t->value);
1690 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op)
1692 AVFrame *opic = av_frame_alloc();
1693 int ret = convert_vframe_picture(frame, op, opic);
1694 av_frame_free(&opic);
1698 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op, AVFrame *opic)
1699 { // vframe = picture
1700 int cmodel = frame->get_color_model();
1701 AVPixelFormat ifmt = color_model_to_pix_fmt(cmodel);
1702 if( ifmt == AV_PIX_FMT_NB ) return -1;
1703 int size = av_image_fill_arrays(opic->data, opic->linesize,
1704 frame->get_data(), ifmt, frame->get_w(), frame->get_h(), 1);
1705 if( size < 0 ) return -1;
1707 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1708 int ysz = bpp * frame->get_w(), usz = ysz;
1718 // override av_image_fill_arrays() for planar types
1719 opic->data[0] = frame->get_y(); opic->linesize[0] = ysz;
1720 opic->data[1] = frame->get_u(); opic->linesize[1] = usz;
1721 opic->data[2] = frame->get_v(); opic->linesize[2] = usz;
1724 opic->data[0] = frame->get_data();
1725 opic->linesize[0] = frame->get_bytes_per_line();
1729 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1730 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(),
1731 ifmt, op->width, op->height, ofmt, SWS_POINT, NULL, NULL, NULL);
1732 if( !convert_ctx ) {
1733 fprintf(stderr, "FFVideoConvert::convert_frame_picture:"
1734 " sws_getCachedContext() failed\n");
1739 int color_range = 0;
1740 switch( preferences->yuv_color_range ) {
1741 case BC_COLORS_JPEG: color_range = 1; break;
1742 case BC_COLORS_MPEG: color_range = 0; break;
1744 int color_space = SWS_CS_ITU601;
1745 switch( preferences->yuv_color_space ) {
1746 case BC_COLORS_BT601_PAL: color_space = SWS_CS_ITU601; break;
1747 case BC_COLORS_BT601_NTSC: color_space = SWS_CS_SMPTE170M; break;
1748 case BC_COLORS_BT709: color_space = SWS_CS_ITU709; break;
1749 case BC_COLORS_BT2020_NCL:
1750 case BC_COLORS_BT2020_CL: color_space = SWS_CS_BT2020; break;
1752 const int *color_table = sws_getCoefficients(color_space);
1754 int *inv_table, *table, src_range, dst_range;
1755 int brightness, contrast, saturation;
1756 if( !sws_getColorspaceDetails(convert_ctx,
1757 &inv_table, &src_range, &table, &dst_range,
1758 &brightness, &contrast, &saturation) ) {
1759 if( dst_range != color_range || table != color_table )
1760 sws_setColorspaceDetails(convert_ctx,
1761 inv_table, src_range, color_table, color_range,
1762 brightness, contrast, saturation);
1765 int ret = sws_scale(convert_ctx, opic->data, opic->linesize, 0, frame->get_h(),
1766 op->data, op->linesize);
1768 ff_err(ret, "FFVideoConvert::convert_frame_picture: sws_scale() failed\n");
1774 int FFVideoConvert::convert_pixfmt(VFrame *frame, AVFrame *op)
1776 // try direct transfer
1777 if( !convert_vframe_picture(frame, op) ) return 1;
1778 // use indirect transfer
1779 int cmodel = frame->get_color_model();
1780 int max_bits = BC_CModels::calculate_pixelsize(cmodel) * 8;
1781 max_bits /= BC_CModels::components(cmodel);
1782 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1783 int imodel = pix_fmt_to_color_model(ofmt);
1784 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1785 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1786 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1787 imodel = cmodel_is_yuv ?
1788 (BC_CModels::has_alpha(cmodel) ?
1790 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1791 (BC_CModels::has_alpha(cmodel) ?
1792 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1793 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1795 VFrame vframe(frame->get_w(), frame->get_h(), imodel);
1796 vframe.transfer_from(frame);
1797 if( !convert_vframe_picture(&vframe, op) ) return 1;
1801 int FFVideoConvert::transfer_pixfmt(VFrame *frame, AVFrame *ofp)
1803 int ret = convert_pixfmt(frame, ofp);
1805 BC_Hash *hp = frame->get_params();
1806 AVDictionary **dict = &ofp->metadata;
1807 //av_dict_free(dict);
1808 for( int i=0; i<hp->size(); ++i ) {
1809 char *key = hp->get_key(i), *val = hp->get_value(i);
1810 av_dict_set(dict, key, val, 0);
1816 void FFVideoStream::load_markers()
1818 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1819 if( !index_state || idx >= index_state->video_markers.size() ) return;
1820 FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
1823 IndexMarks *FFVideoStream::get_markers()
1825 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1826 if( !index_state || idx >= index_state->video_markers.size() ) return 0;
1827 return !index_state ? 0 : index_state->video_markers[idx];
1831 FFMPEG::FFMPEG(FileBase *file_base)
1834 this->file_base = file_base;
1835 memset(file_format,0,sizeof(file_format));
1836 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
1837 flow_lock = new Condition(1,"FFStream::flow_lock",0);
1840 decoding = encoding = 0;
1841 has_audio = has_video = 0;
1842 interlace_from_codec = 0;
1845 opt_video_filter = 0;
1846 opt_audio_filter = 0;
1848 opt_video_decoder = 0;
1849 opt_audio_decoder = 0;
1851 char option_path[BCTEXTLEN];
1852 set_option_path(option_path, "%s", "ffmpeg.opts");
1853 read_options(option_path, opts);
1858 ff_lock("FFMPEG::~FFMPEG()");
1860 ffaudio.remove_all_objects();
1861 ffvideo.remove_all_objects();
1862 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1866 av_dict_free(&opts);
1867 delete [] opt_video_filter;
1868 delete [] opt_audio_filter;
1869 delete [] opt_hw_dev;
1872 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
1873 int FFMPEG::check_sample_rate(const AVCodec *codec, int sample_rate)
1875 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1878 const int *p = codec->supported_samplerates;
1879 if( !p ) return sample_rate;
1881 if( *p == sample_rate ) return *p;
1887 // check_frame_rate and std_frame_rate needed for 23.976
1888 // and 59.94 fps mpeg2
1889 static inline AVRational std_frame_rate(int i)
1891 static const int m1 = 1001*12, m2 = 1000*12;
1892 static const int freqs[] = {
1893 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1894 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 90*m2,
1895 100*m2, 120*m2, 144*m2, 72*m2, 0,
1897 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1898 return (AVRational) { freq, 1001*12 };
1901 AVRational FFMPEG::check_frame_rate(const AVRational *p, double frame_rate)
1903 AVRational rate, best_rate = (AVRational) { 0, 0 };
1904 double max_err = 1.; int i = 0;
1905 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1906 double framerate = (double) rate.num / rate.den;
1907 double err = fabs(frame_rate/framerate - 1.);
1908 if( err >= max_err ) continue;
1912 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1915 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1918 double display_aspect = asset->width / (double)asset->height;
1919 double sample_aspect = display_aspect / asset->aspect_ratio;
1920 int width = 1000000, height = width * sample_aspect + 0.5;
1922 MWindow::create_aspect_ratio(w, h, width, height);
1923 return (AVRational){(int)w, (int)h};
1926 return (AVRational){1, 1};
1930 AVRational FFMPEG::to_time_base(int sample_rate)
1932 return (AVRational){1, sample_rate};
1935 int FFMPEG::get_fmt_score(AVSampleFormat dst_fmt, AVSampleFormat src_fmt)
1938 int dst_planar = av_sample_fmt_is_planar(dst_fmt);
1939 int src_planar = av_sample_fmt_is_planar(src_fmt);
1940 if( dst_planar != src_planar ) ++score;
1941 int dst_bytes = av_get_bytes_per_sample(dst_fmt);
1942 int src_bytes = av_get_bytes_per_sample(src_fmt);
1943 score += (src_bytes > dst_bytes ? 100 : -10) * (src_bytes - dst_bytes);
1944 int src_packed = av_get_packed_sample_fmt(src_fmt);
1945 int dst_packed = av_get_packed_sample_fmt(dst_fmt);
1946 if( dst_packed == AV_SAMPLE_FMT_S32 && src_packed == AV_SAMPLE_FMT_FLT ) score += 20;
1947 if( dst_packed == AV_SAMPLE_FMT_FLT && src_packed == AV_SAMPLE_FMT_S32 ) score += 2;
1951 AVSampleFormat FFMPEG::find_best_sample_fmt_of_list(
1952 const AVSampleFormat *sample_fmts, AVSampleFormat src_fmt)
1954 AVSampleFormat best = AV_SAMPLE_FMT_NONE;
1955 int best_score = get_fmt_score(best, src_fmt);
1956 for( int i=0; sample_fmts[i] >= 0; ++i ) {
1957 AVSampleFormat sample_fmt = sample_fmts[i];
1958 int score = get_fmt_score(sample_fmt, src_fmt);
1959 if( score >= best_score ) continue;
1960 best = sample_fmt; best_score = score;
1966 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
1968 char *ep = path + BCTEXTLEN-1;
1969 strncpy(path, File::get_cindat_path(), ep-path);
1970 strncat(path, "/ffmpeg/", ep-path);
1971 path += strlen(path);
1974 path += vsnprintf(path, ep-path, fmt, ap);
1979 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
1984 set_option_path(path, "%s/%s", type, spec);
1987 int FFMPEG::get_format(char *format, const char *path, const char *spec)
1989 char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
1990 get_option_path(option_path, path, spec);
1991 FILE *fp = fopen(option_path,"r");
1994 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1996 line[sizeof(line)-1] = 0;
1997 ret = scan_option_line(line, format, codec);
2003 int FFMPEG::get_codec(char *codec, const char *path, const char *spec)
2005 char option_path[BCTEXTLEN], line[BCTEXTLEN], format[BCTEXTLEN];
2006 get_option_path(option_path, path, spec);
2007 FILE *fp = fopen(option_path,"r");
2010 if( !fgets(line, sizeof(line), fp) ) ret = 1;
2013 line[sizeof(line)-1] = 0;
2014 ret = scan_option_line(line, format, codec);
2017 char *vp = codec, *ep = vp+BCTEXTLEN-1;
2018 while( vp < ep && *vp && *vp != '|' ) ++vp;
2019 if( *vp == '|' ) --vp;
2020 while( vp > codec && (*vp==' ' || *vp=='\t') ) *vp-- = 0;
2025 int FFMPEG::get_file_format()
2027 char audio_muxer[BCSTRLEN], video_muxer[BCSTRLEN];
2028 char audio_format[BCSTRLEN], video_format[BCSTRLEN];
2029 audio_muxer[0] = audio_format[0] = 0;
2030 video_muxer[0] = video_format[0] = 0;
2031 Asset *asset = file_base->asset;
2032 int ret = asset ? 0 : 1;
2033 if( !ret && asset->audio_data ) {
2034 if( !(ret=get_format(audio_format, "audio", asset->acodec)) ) {
2035 if( get_format(audio_muxer, "format", audio_format) ) {
2036 strcpy(audio_muxer, audio_format);
2037 audio_format[0] = 0;
2041 if( !ret && asset->video_data ) {
2042 if( !(ret=get_format(video_format, "video", asset->vcodec)) ) {
2043 if( get_format(video_muxer, "format", video_format) ) {
2044 strcpy(video_muxer, video_format);
2045 video_format[0] = 0;
2049 if( !ret && !audio_muxer[0] && !video_muxer[0] )
2051 if( !ret && audio_muxer[0] && video_muxer[0] &&
2052 strcmp(audio_muxer, video_muxer) ) ret = -1;
2053 if( !ret && audio_format[0] && video_format[0] &&
2054 strcmp(audio_format, video_format) ) ret = -1;
2056 strcpy(file_format, !audio_format[0] && !video_format[0] ?
2057 (audio_muxer[0] ? audio_muxer : video_muxer) :
2058 (audio_format[0] ? audio_format : video_format));
2062 int FFMPEG::scan_option_line(const char *cp, char *tag, char *val)
2064 while( *cp == ' ' || *cp == '\t' ) ++cp;
2065 const char *bp = cp;
2066 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' && *cp != '\n' ) ++cp;
2068 if( !len || len > BCSTRLEN-1 ) return 1;
2069 while( bp < cp ) *tag++ = *bp++;
2071 while( *cp == ' ' || *cp == '\t' ) ++cp;
2072 if( *cp == '=' ) ++cp;
2073 while( *cp == ' ' || *cp == '\t' ) ++cp;
2075 while( *cp && *cp != '\n' ) ++cp;
2077 if( len > BCTEXTLEN-1 ) return 1;
2078 while( bp < cp ) *val++ = *bp++;
2083 int FFMPEG::can_render(const char *fformat, const char *type)
2086 char option_path[BCTEXTLEN];
2087 FFMPEG::set_option_path(option_path, type);
2088 fs.update(option_path);
2089 int total_files = fs.total_files();
2090 for( int i=0; i<total_files; ++i ) {
2091 const char *name = fs.get_entry(i)->get_name();
2092 const char *ext = strrchr(name,'.');
2093 if( !ext ) continue;
2094 if( !strcmp(fformat, ++ext) ) return 1;
2099 int FFMPEG::get_ff_option(const char *nm, const char *options, char *value)
2101 for( const char *cp=options; *cp!=0; ) {
2102 char line[BCTEXTLEN], *bp = line, *ep = bp+sizeof(line)-1;
2103 while( bp < ep && *cp && *cp!='\n' ) *bp++ = *cp++;
2106 if( !line[0] || line[0] == '#' || line[0] == ';' ) continue;
2107 char key[BCSTRLEN], val[BCTEXTLEN];
2108 if( FFMPEG::scan_option_line(line, key, val) ) continue;
2109 if( !strcmp(key, nm) ) {
2110 strncpy(value, val, BCSTRLEN);
2117 void FFMPEG::scan_audio_options(Asset *asset, EDL *edl)
2119 char cin_sample_fmt[BCSTRLEN];
2120 int cin_fmt = AV_SAMPLE_FMT_NONE;
2121 const char *options = asset->ff_audio_options;
2122 if( !get_ff_option("cin_sample_fmt", options, cin_sample_fmt) )
2123 cin_fmt = (int)av_get_sample_fmt(cin_sample_fmt);
2125 char audio_codec[BCSTRLEN]; audio_codec[0] = 0;
2126 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,18,100)
2127 const AVCodec *av_codec = !FFMPEG::get_codec(audio_codec, "audio", asset->acodec) ?
2129 AVCodec *av_codec = !FFMPEG::get_codec(audio_codec, "audio", asset->acodec) ?
2131 avcodec_find_encoder_by_name(audio_codec) : 0;
2132 if( av_codec && av_codec->sample_fmts )
2133 cin_fmt = find_best_sample_fmt_of_list(av_codec->sample_fmts, AV_SAMPLE_FMT_FLT);
2135 if( cin_fmt < 0 ) cin_fmt = AV_SAMPLE_FMT_S16;
2136 const char *name = av_get_sample_fmt_name((AVSampleFormat)cin_fmt);
2137 if( !name ) name = _("None");
2138 strcpy(asset->ff_sample_format, name);
2140 char value[BCSTRLEN];
2141 if( !get_ff_option("cin_bitrate", options, value) )
2142 asset->ff_audio_bitrate = atoi(value);
2143 if( !get_ff_option("cin_quality", options, value) )
2144 asset->ff_audio_quality = atoi(value);
2147 void FFMPEG::load_audio_options(Asset *asset, EDL *edl)
2149 char options_path[BCTEXTLEN];
2150 set_option_path(options_path, "audio/%s", asset->acodec);
2151 if( !load_options(options_path,
2152 asset->ff_audio_options,
2153 sizeof(asset->ff_audio_options)) )
2154 scan_audio_options(asset, edl);
2157 void FFMPEG::scan_video_options(Asset *asset, EDL *edl)
2159 char cin_pix_fmt[BCSTRLEN];
2160 int cin_fmt = AV_PIX_FMT_NONE;
2161 const char *options = asset->ff_video_options;
2162 if( !get_ff_option("cin_pix_fmt", options, cin_pix_fmt) )
2163 cin_fmt = (int)av_get_pix_fmt(cin_pix_fmt);
2165 char video_codec[BCSTRLEN]; video_codec[0] = 0;
2166 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,18,100)
2167 const AVCodec *av_codec = !get_codec(video_codec, "video", asset->vcodec) ?
2169 AVCodec *av_codec = !get_codec(video_codec, "video", asset->vcodec) ?
2171 avcodec_find_encoder_by_name(video_codec) : 0;
2172 if( av_codec && av_codec->pix_fmts ) {
2173 if( 0 && edl ) { // frequently picks a bad answer
2174 int color_model = edl->session->color_model;
2175 int max_bits = BC_CModels::calculate_pixelsize(color_model) * 8;
2176 max_bits /= BC_CModels::components(color_model);
2177 cin_fmt = avcodec_find_best_pix_fmt_of_list(av_codec->pix_fmts,
2178 (BC_CModels::is_yuv(color_model) ?
2179 (max_bits > 8 ? AV_PIX_FMT_AYUV64LE : AV_PIX_FMT_YUV444P) :
2180 (max_bits > 8 ? AV_PIX_FMT_RGB48LE : AV_PIX_FMT_RGB24)), 0, 0);
2183 cin_fmt = av_codec->pix_fmts[0];
2186 if( cin_fmt < 0 ) cin_fmt = AV_PIX_FMT_YUV420P;
2187 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get((AVPixelFormat)cin_fmt);
2188 const char *name = desc ? desc->name : _("None");
2189 strcpy(asset->ff_pixel_format, name);
2191 char value[BCSTRLEN];
2192 if( !get_ff_option("cin_bitrate", options, value) )
2193 asset->ff_video_bitrate = atoi(value);
2194 if( !get_ff_option("cin_quality", options, value) )
2195 asset->ff_video_quality = atoi(value);
2198 void FFMPEG::load_video_options(Asset *asset, EDL *edl)
2200 char options_path[BCTEXTLEN];
2201 set_option_path(options_path, "video/%s", asset->vcodec);
2202 if( !load_options(options_path,
2203 asset->ff_video_options,
2204 sizeof(asset->ff_video_options)) )
2205 scan_video_options(asset, edl);
2208 void FFMPEG::scan_format_options(Asset *asset, EDL *edl)
2212 void FFMPEG::load_format_options(Asset *asset, EDL *edl)
2214 char options_path[BCTEXTLEN];
2215 set_option_path(options_path, "format/%s", asset->fformat);
2216 if( !load_options(options_path,
2217 asset->ff_format_options,
2218 sizeof(asset->ff_format_options)) )
2219 scan_format_options(asset, edl);
2222 int FFMPEG::load_defaults(const char *path, const char *type,
2223 char *codec, char *codec_options, int len)
2225 char default_file[BCTEXTLEN];
2226 set_option_path(default_file, "%s/%s.dfl", path, type);
2227 FILE *fp = fopen(default_file,"r");
2229 fgets(codec, BCSTRLEN, fp);
2231 while( *cp && *cp!='\n' ) ++cp;
2233 while( len > 0 && fgets(codec_options, len, fp) ) {
2234 int n = strlen(codec_options);
2235 codec_options += n; len -= n;
2238 set_option_path(default_file, "%s/%s", path, codec);
2239 return load_options(default_file, codec_options, len);
2242 void FFMPEG::set_asset_format(Asset *asset, EDL *edl, const char *text)
2244 if( asset->format != FILE_FFMPEG ) return;
2245 if( text != asset->fformat )
2246 strcpy(asset->fformat, text);
2247 if( !asset->ff_format_options[0] )
2248 load_format_options(asset, edl);
2249 if( asset->audio_data && !asset->ff_audio_options[0] ) {
2250 if( !load_defaults("audio", text, asset->acodec,
2251 asset->ff_audio_options, sizeof(asset->ff_audio_options)) )
2252 scan_audio_options(asset, edl);
2254 asset->audio_data = 0;
2256 if( asset->video_data && !asset->ff_video_options[0] ) {
2257 if( !load_defaults("video", text, asset->vcodec,
2258 asset->ff_video_options, sizeof(asset->ff_video_options)) )
2259 scan_video_options(asset, edl);
2261 asset->video_data = 0;
2265 int FFMPEG::get_encoder(const char *options,
2266 char *format, char *codec, char *bsfilter)
2268 FILE *fp = fopen(options,"r");
2270 eprintf(_("options open failed %s\n"),options);
2273 char line[BCTEXTLEN];
2274 if( !fgets(line, sizeof(line), fp) ||
2275 scan_encoder(line, format, codec, bsfilter) )
2276 eprintf(_("format/codec not found %s\n"), options);
2281 int FFMPEG::scan_encoder(const char *line,
2282 char *format, char *codec, char *bsfilter)
2284 format[0] = codec[0] = bsfilter[0] = 0;
2285 if( scan_option_line(line, format, codec) ) return 1;
2287 while( *cp && *cp != '|' ) ++cp;
2288 if( !*cp ) return 0;
2290 do { *bp-- = 0; } while( bp>=codec && (*bp==' ' || *bp == '\t' ) );
2291 while( *++cp && (*cp==' ' || *cp == '\t') );
2293 for( int i=BCTEXTLEN; --i>0 && *cp; ) *bp++ = *cp++;
2298 int FFMPEG::read_options(const char *options, AVDictionary *&opts, int skip)
2300 FILE *fp = fopen(options,"r");
2303 while( !ret && --skip >= 0 ) {
2305 while( ch >= 0 && ch != '\n' ) ch = getc(fp);
2306 if( ch < 0 ) ret = 1;
2309 ret = read_options(fp, options, opts);
2314 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
2316 FILE *fp = fmemopen((void *)options,strlen(options),"r");
2318 int ret = read_options(fp, options, opts);
2321 AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
2322 if( tag ) st->id = strtol(tag->value,0,0);
2327 void FFMPEG::put_cache_frame(VFrame *frame, int64_t position)
2329 file_base->file->put_cache_frame(frame, position, 0);
2332 int FFMPEG::get_use_cache()
2334 return file_base->file->get_use_cache();
2337 void FFMPEG::purge_cache()
2339 file_base->file->purge_cache();
2342 FFCodecRemap::FFCodecRemap()
2347 FFCodecRemap::~FFCodecRemap()
2349 delete [] old_codec;
2350 delete [] new_codec;
2353 int FFCodecRemaps::add(const char *val)
2355 char old_codec[BCSTRLEN], new_codec[BCSTRLEN];
2356 if( sscanf(val, " %63[a-zA-z0-9_-] = %63[a-z0-9_-]",
2357 &old_codec[0], &new_codec[0]) != 2 ) return 1;
2358 FFCodecRemap &remap = append();
2359 remap.old_codec = cstrdup(old_codec);
2360 remap.new_codec = cstrdup(new_codec);
2364 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
2365 int FFCodecRemaps::update(AVCodecID &codec_id, const AVCodec *&decoder)
2367 const AVCodec *codec = avcodec_find_decoder(codec_id);
2369 int FFCodecRemaps::update(AVCodecID &codec_id, AVCodec *&decoder)
2371 AVCodec *codec = avcodec_find_decoder(codec_id);
2373 if( !codec ) return -1;
2374 const char *name = codec->name;
2375 FFCodecRemaps &map = *this;
2377 while( --k >= 0 && strcmp(map[k].old_codec, name) );
2378 if( k < 0 ) return 1;
2379 const char *new_codec = map[k].new_codec;
2380 codec = avcodec_find_decoder_by_name(new_codec);
2381 if( !codec ) return -1;
2386 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
2388 int ret = 0, no = 0;
2389 char line[BCTEXTLEN];
2390 while( !ret && fgets(line, sizeof(line), fp) ) {
2391 line[sizeof(line)-1] = 0;
2392 if( line[0] == '#' ) continue;
2393 if( line[0] == '\n' ) continue;
2394 char key[BCSTRLEN], val[BCTEXTLEN];
2395 if( scan_option_line(line, key, val) ) {
2396 eprintf(_("err reading %s: line %d\n"), options, no);
2400 if( !strcmp(key, "duration") )
2401 opt_duration = strtod(val, 0);
2402 else if( !strcmp(key, "video_decoder") )
2403 opt_video_decoder = cstrdup(val);
2404 else if( !strcmp(key, "audio_decoder") )
2405 opt_audio_decoder = cstrdup(val);
2406 else if( !strcmp(key, "remap_video_decoder") )
2407 video_codec_remaps.add(val);
2408 else if( !strcmp(key, "remap_audio_decoder") )
2409 audio_codec_remaps.add(val);
2410 else if( !strcmp(key, "video_filter") )
2411 opt_video_filter = cstrdup(val);
2412 else if( !strcmp(key, "audio_filter") )
2413 opt_audio_filter = cstrdup(val);
2414 else if( !strcmp(key, "cin_hw_dev") )
2415 opt_hw_dev = cstrdup(val);
2416 else if( !strcmp(key, "loglevel") )
2419 av_dict_set(&opts, key, val, 0);
2425 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
2427 char option_path[BCTEXTLEN];
2428 set_option_path(option_path, "%s", options);
2429 return read_options(option_path, opts);
2432 int FFMPEG::load_options(const char *path, char *bfr, int len)
2435 FILE *fp = fopen(path, "r");
2437 fgets(bfr, len, fp); // skip hdr
2438 len = fread(bfr, 1, len-1, fp);
2439 if( len < 0 ) len = 0;
2445 void FFMPEG::set_loglevel(const char *ap)
2447 if( !ap || !*ap ) return;
2452 { "quiet" , AV_LOG_QUIET },
2453 { "panic" , AV_LOG_PANIC },
2454 { "fatal" , AV_LOG_FATAL },
2455 { "error" , AV_LOG_ERROR },
2456 { "warning", AV_LOG_WARNING },
2457 { "info" , AV_LOG_INFO },
2458 { "verbose", AV_LOG_VERBOSE },
2459 { "debug" , AV_LOG_DEBUG },
2461 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
2462 if( !strcmp(log_levels[i].name, ap) ) {
2463 av_log_set_level(log_levels[i].level);
2467 av_log_set_level(atoi(ap));
2470 double FFMPEG::to_secs(int64_t time, AVRational time_base)
2472 double base_time = time == AV_NOPTS_VALUE ? 0 :
2473 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
2474 return base_time / AV_TIME_BASE;
2477 int FFMPEG::info(char *text, int len)
2479 if( len <= 0 ) return 0;
2481 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
2483 report("format: %s\n",fmt_ctx->iformat->name);
2484 if( ffvideo.size() > 0 )
2485 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
2486 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
2487 const char *unkn = _("(unkn)");
2488 FFVideoStream *vid = ffvideo[vidx];
2489 AVStream *st = vid->st;
2490 AVCodecID codec_id = st->codecpar->codec_id;
2491 report(_("vid%d (%d), id 0x%06x:\n"), vid->idx, vid->fidx, codec_id);
2492 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
2493 report(" video%d %s ", vidx+1, desc ? desc->name : unkn);
2494 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
2495 AVPixelFormat pix_fmt = (AVPixelFormat)st->codecpar->format;
2496 const char *pfn = av_get_pix_fmt_name(pix_fmt);
2497 report(" pix %s\n", pfn ? pfn : unkn);
2498 int interlace = st->codecpar->field_order;
2499 report(" interlace (container level): %i\n", interlace ? interlace : -1);
2500 int interlace_codec = interlace_from_codec;
2501 report(" interlace (codec level): %i\n", interlace_codec ? interlace_codec : -1);
2502 enum AVColorSpace space = st->codecpar->color_space;
2503 const char *nm = av_color_space_name(space);
2504 report(" color space:%s", nm ? nm : unkn);
2505 enum AVColorRange range = st->codecpar->color_range;
2506 const char *rg = av_color_range_name(range);
2507 report("/ range:%s\n", rg ? rg : unkn);
2508 double secs = to_secs(st->duration, st->time_base);
2509 int64_t length = secs * vid->frame_rate + 0.5;
2510 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
2511 int64_t nudge = ofs * vid->frame_rate;
2512 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
2513 report(" %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
2514 int hrs = secs/3600; secs -= hrs*3600;
2515 int mins = secs/60; secs -= mins*60;
2516 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
2517 double theta = vid->get_rotation_angle();
2518 if( fabs(theta) > 1 )
2519 report(" rotation angle: %0.1f\n", theta);
2521 if( ffaudio.size() > 0 )
2522 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
2523 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2524 FFAudioStream *aud = ffaudio[aidx];
2525 AVStream *st = aud->st;
2526 AVCodecID codec_id = st->codecpar->codec_id;
2527 report(_("aud%d (%d), id 0x%06x:\n"), aud->idx, aud->fidx, codec_id);
2528 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
2529 int nch = aud->channels, ch0 = aud->channel0+1;
2530 report(" audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
2531 AVSampleFormat sample_fmt = (AVSampleFormat)st->codecpar->format;
2532 const char *fmt = av_get_sample_fmt_name(sample_fmt);
2533 report(" %s %d", fmt, aud->sample_rate);
2534 int sample_bits = av_get_bits_per_sample(codec_id);
2535 report(" %dbits\n", sample_bits);
2536 double secs = to_secs(st->duration, st->time_base);
2537 int64_t length = secs * aud->sample_rate + 0.5;
2538 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
2539 int64_t nudge = ofs * aud->sample_rate;
2540 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
2541 report(" %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
2542 int hrs = secs/3600; secs -= hrs*3600;
2543 int mins = secs/60; secs -= mins*60;
2544 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
2546 if( fmt_ctx->nb_programs > 0 )
2547 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
2548 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
2549 report("program %d", i+1);
2550 AVProgram *pgrm = fmt_ctx->programs[i];
2551 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2552 int idx = pgrm->stream_index[j];
2553 int vidx = ffvideo.size();
2554 while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
2556 report(", vid%d", vidx);
2559 int aidx = ffaudio.size();
2560 while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
2562 report(", aud%d", aidx);
2565 report(", (%d)", pgrm->stream_index[j]);
2570 AVDictionaryEntry *tag = 0;
2571 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
2572 report("%s=%s\n", tag->key, tag->value);
2581 int FFMPEG::init_decoder(const char *filename)
2583 ff_lock("FFMPEG::init_decoder");
2585 char file_opts[BCTEXTLEN];
2586 strcpy(file_opts, filename);
2587 char *bp = strrchr(file_opts, '/');
2588 if( !bp ) bp = file_opts;
2589 char *sp = strrchr(bp, '.');
2590 if( !sp ) sp = bp + strlen(bp);
2592 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,18,100)
2593 const AVInputFormat *ifmt = 0;
2595 AVInputFormat *ifmt = 0;
2598 strcpy(sp, ".opts");
2599 fp = fopen(file_opts, "r");
2602 read_options(fp, file_opts, opts);
2604 AVDictionaryEntry *tag;
2605 if( (tag=av_dict_get(opts, "format", NULL, 0)) != 0 ) {
2606 ifmt = av_find_input_format(tag->value);
2610 load_options("decode.opts", opts);
2611 AVDictionary *fopts = 0;
2612 av_dict_copy(&fopts, opts, 0);
2613 int ret = avformat_open_input(&fmt_ctx, filename, ifmt, &fopts);
2614 av_dict_free(&fopts);
2616 ret = avformat_find_stream_info(fmt_ctx, NULL);
2621 return !ret ? 0 : 1;
2624 int FFMPEG::open_decoder()
2627 if( stat(fmt_ctx->url, &st) < 0 ) {
2628 eprintf(_("can't stat file: %s\n"), fmt_ctx->url);
2632 int64_t file_bits = 8 * st.st_size;
2633 if( !fmt_ctx->bit_rate && opt_duration > 0 )
2634 fmt_ctx->bit_rate = file_bits / opt_duration;
2637 if( fmt_ctx->bit_rate > 0 ) {
2638 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2639 AVStream *st = fmt_ctx->streams[i];
2640 if( st->duration != AV_NOPTS_VALUE ) continue;
2641 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
2642 st->duration = av_rescale(file_bits, st->time_base.den,
2643 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
2647 if( estimated && !(fflags & FF_ESTM_TIMES) ) {
2648 fflags |= FF_ESTM_TIMES;
2649 printf("FFMPEG::open_decoder: some stream times estimated: %s\n",
2653 ff_lock("FFMPEG::open_decoder");
2654 int ret = 0, bad_time = 0;
2655 for( int i=0; !ret && i<(int)fmt_ctx->nb_streams; ++i ) {
2656 AVStream *st = fmt_ctx->streams[i];
2657 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
2658 AVCodecParameters *avpar = st->codecpar;
2659 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avpar->codec_id);
2660 if( !codec_desc ) continue;
2661 switch( avpar->codec_type ) {
2662 case AVMEDIA_TYPE_VIDEO: {
2663 if( avpar->width < 1 ) continue;
2664 if( avpar->height < 1 ) continue;
2665 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
2666 if( framerate.num < 1 ) continue;
2668 int vidx = ffvideo.size();
2669 FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
2670 vstrm_index.append(ffidx(vidx, 0));
2671 ffvideo.append(vid);
2672 vid->width = avpar->width;
2673 vid->height = avpar->height;
2674 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
2675 switch( avpar->color_range ) {
2676 case AVCOL_RANGE_MPEG:
2677 vid->color_range = BC_COLORS_MPEG;
2679 case AVCOL_RANGE_JPEG:
2680 vid->color_range = BC_COLORS_JPEG;
2683 vid->color_range = !file_base ? BC_COLORS_JPEG :
2684 file_base->file->preferences->yuv_color_range;
2687 switch( avpar->color_space ) {
2688 case AVCOL_SPC_BT470BG:
2689 vid->color_space = BC_COLORS_BT601_PAL;
2691 case AVCOL_SPC_SMPTE170M:
2692 vid->color_space = BC_COLORS_BT601_NTSC;
2694 case AVCOL_SPC_BT709:
2695 vid->color_space = BC_COLORS_BT709;
2697 case AVCOL_SPC_BT2020_NCL:
2698 vid->color_space = BC_COLORS_BT2020_NCL;
2700 case AVCOL_SPC_BT2020_CL:
2701 vid->color_space = BC_COLORS_BT2020_CL;
2704 vid->color_space = !file_base ? BC_COLORS_BT601_NTSC :
2705 file_base->file->preferences->yuv_color_space;
2708 double secs = to_secs(st->duration, st->time_base);
2709 vid->length = secs * vid->frame_rate;
2710 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
2711 vid->nudge = st->start_time;
2713 ret = vid->create_filter(opt_video_filter);
2715 case AVMEDIA_TYPE_AUDIO: {
2716 if( avpar->channels < 1 ) continue;
2717 if( avpar->sample_rate < 1 ) continue;
2719 int aidx = ffaudio.size();
2720 FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
2721 ffaudio.append(aud);
2722 aud->channel0 = astrm_index.size();
2723 aud->channels = avpar->channels;
2724 for( int ch=0; ch<aud->channels; ++ch )
2725 astrm_index.append(ffidx(aidx, ch));
2726 aud->sample_rate = avpar->sample_rate;
2727 double secs = to_secs(st->duration, st->time_base);
2728 aud->length = secs * aud->sample_rate;
2729 aud->init_swr(aud->channels, avpar->format, aud->sample_rate);
2730 aud->nudge = st->start_time;
2732 ret = aud->create_filter(opt_audio_filter);
2737 if( bad_time && !(fflags & FF_BAD_TIMES) ) {
2738 fflags |= FF_BAD_TIMES;
2739 printf(_("FFMPEG::open_decoder: some stream have bad times: %s\n"),
2743 return ret < 0 ? -1 : 0;
2747 int FFMPEG::init_encoder(const char *filename)
2749 // try access first for named pipes
2750 int ret = access(filename, W_OK);
2752 int fd = ::open(filename,O_WRONLY);
2753 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
2754 if( fd >= 0 ) { close(fd); ret = 0; }
2757 eprintf(_("bad file path: %s\n"), filename);
2760 ret = get_file_format();
2762 eprintf(_("bad file format: %s\n"), filename);
2766 eprintf(_("mismatch audio/video file format: %s\n"), filename);
2769 ff_lock("FFMPEG::init_encoder");
2771 char format[BCSTRLEN];
2772 if( get_format(format, "format", file_format) )
2773 strcpy(format, file_format);
2774 avformat_alloc_output_context2(&fmt_ctx, 0, format, filename);
2776 eprintf(_("failed: %s\n"), filename);
2781 load_options("encode.opts", opts);
2787 int FFMPEG::open_encoder(const char *type, const char *spec)
2790 Asset *asset = file_base->asset;
2791 char *filename = asset->path;
2792 AVDictionary *sopts = 0;
2793 av_dict_copy(&sopts, opts, 0);
2794 char option_path[BCTEXTLEN];
2795 set_option_path(option_path, "%s/%s.opts", type, type);
2796 read_options(option_path, sopts);
2797 get_option_path(option_path, type, spec);
2798 char format_name[BCSTRLEN], codec_name[BCTEXTLEN], bsfilter[BCTEXTLEN];
2799 if( get_encoder(option_path, format_name, codec_name, bsfilter) ) {
2800 eprintf(_("get_encoder failed %s:%s\n"), option_path, filename);
2805 if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
2807 else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
2808 else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
2811 ff_lock("FFMPEG::open_encoder");
2814 AVCodecContext *ctx = 0;
2816 const AVCodecDescriptor *codec_desc = 0;
2817 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
2818 const AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
2820 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
2823 eprintf(_("cant find codec %s:%s\n"), codec_name, filename);
2827 codec_desc = avcodec_descriptor_get(codec->id);
2829 eprintf(_("unknown codec %s:%s\n"), codec_name, filename);
2834 st = avformat_new_stream(fmt_ctx, 0);
2836 eprintf(_("cant create stream %s:%s\n"), codec_name, filename);
2841 switch( codec_desc->type ) {
2842 case AVMEDIA_TYPE_AUDIO: {
2844 eprintf(_("duplicate audio %s:%s\n"), codec_name, filename);
2848 if( scan_options(asset->ff_audio_options, sopts, st) ) {
2849 eprintf(_("bad audio options %s:%s\n"), codec_name, filename);
2854 ctx = avcodec_alloc_context3(codec);
2855 if( asset->ff_audio_bitrate > 0 ) {
2856 ctx->bit_rate = asset->ff_audio_bitrate;
2858 sprintf(arg, "%d", asset->ff_audio_bitrate);
2859 av_dict_set(&sopts, "b", arg, 0);
2861 else if( asset->ff_audio_quality >= 0 ) {
2862 ctx->global_quality = asset->ff_audio_quality * FF_QP2LAMBDA;
2863 ctx->qmin = ctx->qmax = asset->ff_audio_quality;
2864 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2865 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2866 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2868 av_dict_set(&sopts, "flags", "+qscale", 0);
2869 sprintf(arg, "%d", asset->ff_audio_quality);
2870 av_dict_set(&sopts, "qscale", arg, 0);
2871 sprintf(arg, "%d", ctx->global_quality);
2872 av_dict_set(&sopts, "global_quality", arg, 0);
2874 int aidx = ffaudio.size();
2875 int fidx = aidx + ffvideo.size();
2876 FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
2877 aud->avctx = ctx; ffaudio.append(aud); fst = aud;
2878 aud->sample_rate = asset->sample_rate;
2879 ctx->channels = aud->channels = asset->channels;
2880 for( int ch=0; ch<aud->channels; ++ch )
2881 astrm_index.append(ffidx(aidx, ch));
2882 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
2883 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
2884 if( !ctx->sample_rate ) {
2885 eprintf(_("check_sample_rate failed %s\n"), filename);
2889 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
2890 AVSampleFormat sample_fmt = av_get_sample_fmt(asset->ff_sample_format);
2891 if( sample_fmt == AV_SAMPLE_FMT_NONE )
2892 sample_fmt = codec->sample_fmts ? codec->sample_fmts[0] : AV_SAMPLE_FMT_S16;
2893 ctx->sample_fmt = sample_fmt;
2894 uint64_t layout = av_get_default_channel_layout(ctx->channels);
2895 aud->resample_context = swr_alloc_set_opts(NULL,
2896 layout, ctx->sample_fmt, aud->sample_rate,
2897 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
2899 swr_init(aud->resample_context);
2902 case AVMEDIA_TYPE_VIDEO: {
2904 eprintf(_("duplicate video %s:%s\n"), codec_name, filename);
2908 if( scan_options(asset->ff_video_options, sopts, st) ) {
2909 eprintf(_("bad video options %s:%s\n"), codec_name, filename);
2914 ctx = avcodec_alloc_context3(codec);
2915 if( asset->ff_video_bitrate > 0 ) {
2916 ctx->bit_rate = asset->ff_video_bitrate;
2918 sprintf(arg, "%d", asset->ff_video_bitrate);
2919 av_dict_set(&sopts, "b", arg, 0);
2921 else if( asset->ff_video_quality >= 0 ) {
2922 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
2923 ctx->qmin = ctx->qmax = asset->ff_video_quality;
2924 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2925 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2926 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2928 av_dict_set(&sopts, "flags", "+qscale", 0);
2929 sprintf(arg, "%d", asset->ff_video_quality);
2930 av_dict_set(&sopts, "qscale", arg, 0);
2931 sprintf(arg, "%d", ctx->global_quality);
2932 av_dict_set(&sopts, "global_quality", arg, 0);
2934 int vidx = ffvideo.size();
2935 int fidx = vidx + ffaudio.size();
2936 FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
2937 vstrm_index.append(ffidx(vidx, 0));
2938 vid->avctx = ctx; ffvideo.append(vid); fst = vid;
2939 vid->width = asset->width;
2940 vid->height = asset->height;
2941 vid->frame_rate = asset->frame_rate;
2942 if( (vid->color_range = asset->ff_color_range) < 0 )
2943 vid->color_range = file_base->file->preferences->yuv_color_range;
2944 switch( vid->color_range ) {
2945 case BC_COLORS_MPEG: ctx->color_range = AVCOL_RANGE_MPEG; break;
2946 case BC_COLORS_JPEG: ctx->color_range = AVCOL_RANGE_JPEG; break;
2948 if( (vid->color_space = asset->ff_color_space) < 0 )
2949 vid->color_space = file_base->file->preferences->yuv_color_space;
2950 switch( vid->color_space ) {
2951 case BC_COLORS_BT601_NTSC: ctx->colorspace = AVCOL_SPC_SMPTE170M; break;
2952 case BC_COLORS_BT601_PAL: ctx->colorspace = AVCOL_SPC_BT470BG; break;
2953 case BC_COLORS_BT709: ctx->colorspace = AVCOL_SPC_BT709; break;
2954 case BC_COLORS_BT2020_NCL: ctx->colorspace = AVCOL_SPC_BT2020_NCL; break;
2955 case BC_COLORS_BT2020_CL: ctx->colorspace = AVCOL_SPC_BT2020_CL; break;
2957 AVPixelFormat pix_fmt = av_get_pix_fmt(asset->ff_pixel_format);
2958 if( opt_hw_dev != 0 ) {
2959 AVHWDeviceType hw_type = vid->encode_hw_activate(opt_hw_dev);
2961 case AV_HWDEVICE_TYPE_VAAPI:
2962 pix_fmt = AV_PIX_FMT_VAAPI;
2964 case AV_HWDEVICE_TYPE_NONE:
2968 if( pix_fmt == AV_PIX_FMT_NONE )
2969 pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
2970 ctx->pix_fmt = pix_fmt;
2972 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
2973 int mask_w = (1<<desc->log2_chroma_w)-1;
2974 ctx->width = (vid->width+mask_w) & ~mask_w;
2975 int mask_h = (1<<desc->log2_chroma_h)-1;
2976 ctx->height = (vid->height+mask_h) & ~mask_h;
2977 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
2978 AVRational frame_rate;
2979 if (ctx->codec->id == AV_CODEC_ID_MPEG1VIDEO ||
2980 ctx->codec->id == AV_CODEC_ID_MPEG2VIDEO)
2981 frame_rate = check_frame_rate(codec->supported_framerates, vid->frame_rate);
2983 frame_rate = av_d2q(vid->frame_rate, INT_MAX);
2984 if( !frame_rate.num || !frame_rate.den ) {
2985 eprintf(_("check_frame_rate failed %s\n"), filename);
2989 av_reduce(&frame_rate.num, &frame_rate.den,
2990 frame_rate.num, frame_rate.den, INT_MAX);
2991 ctx->framerate = (AVRational) { frame_rate.num, frame_rate.den };
2992 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
2993 st->avg_frame_rate = frame_rate;
2994 st->time_base = ctx->time_base;
2996 vid->interlaced = asset->interlace_mode == ILACE_MODE_TOP_FIRST ||
2997 asset->interlace_mode == ILACE_MODE_BOTTOM_FIRST ? 1 : 0;
2998 vid->top_field_first = asset->interlace_mode == ILACE_MODE_TOP_FIRST ? 1 : 0;
2999 switch (asset->interlace_mode) {
3000 case ILACE_MODE_TOP_FIRST:
3001 if (ctx->codec->id == AV_CODEC_ID_MJPEG)
3002 av_dict_set(&sopts, "field_order", "tt", 0);
3004 av_dict_set(&sopts, "field_order", "tb", 0);
3005 if (ctx->codec_id != AV_CODEC_ID_MJPEG)
3006 av_dict_set(&sopts, "flags", "+ilme+ildct", 0);
3008 case ILACE_MODE_BOTTOM_FIRST:
3009 if (ctx->codec->id == AV_CODEC_ID_MJPEG)
3010 av_dict_set(&sopts, "field_order", "bb", 0);
3012 av_dict_set(&sopts, "field_order", "bt", 0);
3013 if (ctx->codec_id != AV_CODEC_ID_MJPEG)
3014 av_dict_set(&sopts, "flags", "+ilme+ildct", 0);
3016 case ILACE_MODE_NOTINTERLACED: av_dict_set(&sopts, "field_order", "progressive", 0); break;
3020 eprintf(_("not audio/video, %s:%s\n"), codec_name, filename);
3025 AVDictionaryEntry *tag;
3026 if( (tag=av_dict_get(sopts, "cin_stats_filename", NULL, 0)) != 0 ) {
3027 char suffix[BCSTRLEN]; sprintf(suffix,"-%d.log",fst->fidx);
3028 fst->stats_filename = cstrcat(2, tag->value, suffix);
3030 if( (tag=av_dict_get(sopts, "flags", NULL, 0)) != 0 ) {
3031 int pass = fst->pass;
3032 char *cp = tag->value;
3034 int ch = *cp++, pfx = ch=='-' ? -1 : ch=='+' ? 1 : 0;
3035 if( !isalnum(!pfx ? ch : (ch=*cp++)) ) continue;
3036 char id[BCSTRLEN], *bp = id, *ep = bp+sizeof(id)-1;
3037 for( *bp++=ch; isalnum(ch=*cp); ++cp )
3038 if( bp < ep ) *bp++ = ch;
3040 if( !strcmp(id, "pass1") ) {
3041 pass = pfx<0 ? (pass&~1) : pfx>0 ? (pass|1) : 1;
3043 else if( !strcmp(id, "pass2") ) {
3044 pass = pfx<0 ? (pass&~2) : pfx>0 ? (pass|2) : 2;
3047 if( (fst->pass=pass) ) {
3048 if( pass & 1 ) ctx->flags |= AV_CODEC_FLAG_PASS1;
3049 if( pass & 2 ) ctx->flags |= AV_CODEC_FLAG_PASS2;
3055 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
3056 ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
3057 if( fst->stats_filename && (ret=fst->init_stats_file()) )
3058 eprintf(_("error: stats file = %s\n"), fst->stats_filename);
3061 av_dict_set(&sopts, "cin_bitrate", 0, 0);
3062 av_dict_set(&sopts, "cin_quality", 0, 0);
3064 if( !av_dict_get(sopts, "threads", NULL, 0) )
3065 ctx->thread_count = ff_cpus();
3066 ret = avcodec_open2(ctx, codec, &sopts);
3068 ret = avcodec_parameters_from_context(st->codecpar, ctx);
3070 fprintf(stderr, "Could not copy the stream parameters\n");
3073 _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
3074 #if LIBAVCODEC_VERSION_INT <= AV_VERSION_INT(58,134,100)
3075 ret = avcodec_copy_context(st->codec, ctx);
3077 ret = avcodec_parameters_to_context(ctx, st->codecpar);
3079 _Pragma("GCC diagnostic warning \"-Wdeprecated-declarations\"")
3081 fprintf(stderr, "Could not copy the stream context\n");
3084 ff_err(ret,"FFMPEG::open_encoder");
3085 eprintf(_("open failed %s:%s\n"), codec_name, filename);
3091 if( !ret && fst && bsfilter[0] ) {
3092 ret = av_bsf_list_parse_str(bsfilter, &fst->bsfc);
3094 ff_err(ret,"FFMPEG::open_encoder");
3095 eprintf(_("bitstream filter failed %s:\n%s\n"), filename, bsfilter);
3106 av_dict_free(&sopts);
3110 int FFMPEG::close_encoder()
3113 if( encoding > 0 ) {
3114 av_write_trailer(fmt_ctx);
3115 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
3116 avio_closep(&fmt_ctx->pb);
3122 int FFMPEG::decode_activate()
3124 if( decoding < 0 ) {
3126 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
3127 ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
3128 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
3129 ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
3130 // set nudges for each program stream set
3131 const int64_t min_nudge = INT64_MIN+1;
3132 int npgrms = fmt_ctx->nb_programs;
3133 for( int i=0; i<npgrms; ++i ) {
3134 AVProgram *pgrm = fmt_ctx->programs[i];
3135 // first start time video stream
3136 int64_t vstart_time = min_nudge, astart_time = min_nudge;
3137 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
3138 int fidx = pgrm->stream_index[j];
3139 AVStream *st = fmt_ctx->streams[fidx];
3140 AVCodecParameters *avpar = st->codecpar;
3141 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
3142 if( st->start_time == AV_NOPTS_VALUE ) continue;
3143 if( vstart_time < st->start_time )
3144 vstart_time = st->start_time;
3147 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
3148 if( st->start_time == AV_NOPTS_VALUE ) continue;
3149 if( astart_time < st->start_time )
3150 astart_time = st->start_time;
3154 //since frame rate is much more grainy than sample rate, it is better to
3155 // align using video, so that total absolute error is minimized.
3156 int64_t nudge = vstart_time > min_nudge ? vstart_time :
3157 astart_time > min_nudge ? astart_time : AV_NOPTS_VALUE;
3158 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
3159 int fidx = pgrm->stream_index[j];
3160 AVStream *st = fmt_ctx->streams[fidx];
3161 AVCodecParameters *avpar = st->codecpar;
3162 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
3163 for( int k=0; k<ffvideo.size(); ++k ) {
3164 if( ffvideo[k]->fidx != fidx ) continue;
3165 ffvideo[k]->nudge = nudge;
3169 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
3170 for( int k=0; k<ffaudio.size(); ++k ) {
3171 if( ffaudio[k]->fidx != fidx ) continue;
3172 ffaudio[k]->nudge = nudge;
3178 // set nudges for any streams not yet set
3179 int64_t vstart_time = min_nudge, astart_time = min_nudge;
3180 int nstreams = fmt_ctx->nb_streams;
3181 for( int i=0; i<nstreams; ++i ) {
3182 AVStream *st = fmt_ctx->streams[i];
3183 AVCodecParameters *avpar = st->codecpar;
3184 switch( avpar->codec_type ) {
3185 case AVMEDIA_TYPE_VIDEO: {
3186 if( st->start_time == AV_NOPTS_VALUE ) continue;
3187 int vidx = ffvideo.size();
3188 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
3189 if( vidx < 0 ) continue;
3190 if( ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
3191 if( vstart_time < st->start_time )
3192 vstart_time = st->start_time;
3194 case AVMEDIA_TYPE_AUDIO: {
3195 if( st->start_time == AV_NOPTS_VALUE ) continue;
3196 int aidx = ffaudio.size();
3197 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
3198 if( aidx < 0 ) continue;
3199 if( ffaudio[aidx]->frame_sz < avpar->frame_size )
3200 ffaudio[aidx]->frame_sz = avpar->frame_size;
3201 if( ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
3202 if( astart_time < st->start_time )
3203 astart_time = st->start_time;
3208 int64_t nudge = vstart_time > min_nudge ? vstart_time :
3209 astart_time > min_nudge ? astart_time : 0;
3210 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
3211 if( ffvideo[vidx]->nudge == AV_NOPTS_VALUE )
3212 ffvideo[vidx]->nudge = nudge;
3214 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
3215 if( ffaudio[aidx]->nudge == AV_NOPTS_VALUE )
3216 ffaudio[aidx]->nudge = nudge;
3223 int FFMPEG::encode_activate()
3226 if( encoding < 0 ) {
3228 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
3229 (ret=avio_open(&fmt_ctx->pb, fmt_ctx->url, AVIO_FLAG_WRITE)) < 0 ) {
3230 ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
3234 if( !strcmp(file_format, "image2") ) {
3235 Asset *asset = file_base->asset;
3236 const char *filename = asset->path;
3237 FILE *fp = fopen(filename,"w");
3239 eprintf(_("Cant write image2 header file: %s\n %m"), filename);
3242 fprintf(fp, "IMAGE2\n");
3243 fprintf(fp, "# Frame rate: %f\n", asset->frame_rate);
3244 fprintf(fp, "# Width: %d\n", asset->width);
3245 fprintf(fp, "# Height: %d\n", asset->height);
3249 AVProgram *prog = av_new_program(fmt_ctx, prog_id);
3250 for( int i=0; i< ffvideo.size(); ++i )
3251 av_program_add_stream_index(fmt_ctx, prog_id, ffvideo[i]->fidx);
3252 for( int i=0; i< ffaudio.size(); ++i )
3253 av_program_add_stream_index(fmt_ctx, prog_id, ffaudio[i]->fidx);
3254 int pi = fmt_ctx->nb_programs;
3255 while( --pi >= 0 && fmt_ctx->programs[pi]->id != prog_id );
3256 AVDictionary **meta = &prog->metadata;
3257 av_dict_set(meta, "service_provider", "cin5", 0);
3258 const char *path = fmt_ctx->url, *bp = strrchr(path,'/');
3259 if( bp ) path = bp + 1;
3260 av_dict_set(meta, "title", path, 0);
3262 if( ffaudio.size() ) {
3263 const char *ep = getenv("CIN_AUDIO_LANG"), *lp = 0;
3264 if( !ep && (lp=getenv("LANG")) ) { // some are guesses
3265 static struct { const char lc[3], lng[4]; } lcode[] = {
3266 { "en", "eng" }, { "de", "ger" }, { "es", "spa" },
3267 { "eu", "bas" }, { "fr", "fre" }, { "el", "gre" },
3268 { "hi", "hin" }, { "it", "ita" }, { "ja", "jap" },
3269 { "ko", "kor" }, { "du", "dut" }, { "pl", "pol" },
3270 { "pt", "por" }, { "ru", "rus" }, { "sl", "slv" },
3271 { "uk", "ukr" }, { "vi", "vie" }, { "zh", "chi" },
3273 for( int i=sizeof(lcode)/sizeof(lcode[0]); --i>=0 && !ep; )
3274 if( !strncmp(lcode[i].lc,lp,2) ) ep = lcode[i].lng;
3276 if( !ep ) ep = "und";
3278 strncpy(lang,ep,3); lang[3] = 0;
3279 AVStream *st = ffaudio[0]->st;
3280 av_dict_set(&st->metadata,"language",lang,0);
3283 AVDictionary *fopts = 0;
3284 char option_path[BCTEXTLEN];
3285 set_option_path(option_path, "format/%s", file_format);
3286 read_options(option_path, fopts, 1);
3287 av_dict_copy(&fopts, opts, 0);
3288 if( scan_options(file_base->asset->ff_format_options, fopts, 0) ) {
3289 eprintf(_("bad format options %s\n"), file_base->asset->path);
3293 ret = avformat_write_header(fmt_ctx, &fopts);
3295 ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
3299 av_dict_free(&fopts);
3306 int FFMPEG::audio_seek(int stream, int64_t pos)
3308 int aidx = astrm_index[stream].st_idx;
3309 FFAudioStream *aud = ffaudio[aidx];
3310 aud->audio_seek(pos);
3314 int FFMPEG::video_probe(int64_t pos)
3316 int vidx = vstrm_index[0].st_idx;
3317 FFVideoStream *vid = ffvideo[vidx];
3320 int interlace1 = interlace_from_codec;
3321 //printf("interlace from codec: %i\n", interlace1);
3327 return ILACE_MODE_TOP_FIRST;
3330 return ILACE_MODE_BOTTOM_FIRST;
3331 case AV_FIELD_PROGRESSIVE:
3332 return ILACE_MODE_NOTINTERLACED;
3334 return ILACE_MODE_UNDETECTED;
3341 int FFMPEG::video_seek(int stream, int64_t pos)
3343 int vidx = vstrm_index[stream].st_idx;
3344 FFVideoStream *vid = ffvideo[vidx];
3345 vid->video_seek(pos);
3350 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
3352 if( !has_audio || chn >= astrm_index.size() ) return -1;
3353 int aidx = astrm_index[chn].st_idx;
3354 FFAudioStream *aud = ffaudio[aidx];
3355 if( aud->load(pos, len) < len ) return -1;
3356 int ch = astrm_index[chn].st_ch;
3357 int ret = aud->read(samples,len,ch);
3361 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
3363 if( !has_video || layer >= vstrm_index.size() ) return -1;
3364 int vidx = vstrm_index[layer].st_idx;
3365 FFVideoStream *vid = ffvideo[vidx];
3366 return vid->load(vframe, pos);
3370 int FFMPEG::encode(int stream, double **samples, int len)
3372 FFAudioStream *aud = ffaudio[stream];
3373 return aud->encode(samples, len);
3377 int FFMPEG::encode(int stream, VFrame *frame)
3379 FFVideoStream *vid = ffvideo[stream];
3380 return vid->encode(frame);
3383 void FFMPEG::start_muxer()
3391 void FFMPEG::stop_muxer()
3400 void FFMPEG::flow_off()
3403 flow_lock->lock("FFMPEG::flow_off");
3407 void FFMPEG::flow_on()
3411 flow_lock->unlock();
3414 void FFMPEG::flow_ctl()
3417 flow_lock->lock("FFMPEG::flow_ctl");
3418 flow_lock->unlock();
3422 int FFMPEG::mux_audio(FFrame *frm)
3424 FFStream *fst = frm->fst;
3425 AVCodecContext *ctx = fst->avctx;
3426 AVFrame *frame = *frm;
3427 AVRational tick_rate = {1, ctx->sample_rate};
3428 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
3429 int ret = fst->encode_frame(frame);
3431 ff_err(ret, "FFMPEG::mux_audio");
3432 return ret >= 0 ? 0 : 1;
3435 int FFMPEG::mux_video(FFrame *frm)
3437 FFStream *fst = frm->fst;
3438 AVFrame *frame = *frm;
3439 frame->pts = frm->position;
3440 int ret = fst->encode_frame(frame);
3442 ff_err(ret, "FFMPEG::mux_video");
3443 return ret >= 0 ? 0 : 1;
3449 double atm = -1, vtm = -1;
3450 FFrame *afrm = 0, *vfrm = 0;
3452 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
3453 FFStream *fst = ffaudio[i];
3454 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
3455 FFrame *frm = fst->frms.first;
3456 if( !frm ) { if( !done ) return; continue; }
3457 double tm = to_secs(frm->position, fst->avctx->time_base);
3458 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
3460 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
3461 FFStream *fst = ffvideo[i];
3462 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
3463 FFrame *frm = fst->frms.first;
3464 if( !frm ) { if( !done ) return; continue; }
3465 double tm = to_secs(frm->position, fst->avctx->time_base);
3466 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
3468 if( !demand ) flow_off();
3469 if( !afrm && !vfrm ) break;
3470 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
3471 vfrm->position, vfrm->fst->avctx->time_base,
3472 afrm->position, afrm->fst->avctx->time_base);
3473 FFrame *frm = v <= 0 ? vfrm : afrm;
3474 if( frm == afrm ) mux_audio(frm);
3475 if( frm == vfrm ) mux_video(frm);
3484 mux_lock->lock("FFMPEG::run");
3487 for( int i=0; i<ffaudio.size(); ++i )
3488 ffaudio[i]->drain();
3489 for( int i=0; i<ffvideo.size(); ++i )
3490 ffvideo[i]->drain();
3492 for( int i=0; i<ffaudio.size(); ++i )
3493 ffaudio[i]->flush();
3494 for( int i=0; i<ffvideo.size(); ++i )
3495 ffvideo[i]->flush();
3499 int FFMPEG::ff_total_audio_channels()
3501 return astrm_index.size();
3504 int FFMPEG::ff_total_astreams()
3506 return ffaudio.size();
3509 int FFMPEG::ff_audio_channels(int stream)
3511 return ffaudio[stream]->channels;
3514 int FFMPEG::ff_sample_rate(int stream)
3516 return ffaudio[stream]->sample_rate;
3519 const char* FFMPEG::ff_audio_format(int stream)
3521 AVStream *st = ffaudio[stream]->st;
3522 AVCodecID id = st->codecpar->codec_id;
3523 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
3524 return desc ? desc->name : _("Unknown");
3527 int FFMPEG::ff_audio_pid(int stream)
3529 return ffaudio[stream]->st->id;
3532 int64_t FFMPEG::ff_audio_samples(int stream)
3534 return ffaudio[stream]->length;
3537 // find audio astream/channels with this program,
3538 // or all program audio channels (astream=-1)
3539 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
3543 int vidx = ffvideo[vstream]->fidx;
3544 // find first program with this video stream
3545 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
3546 AVProgram *pgrm = fmt_ctx->programs[i];
3547 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
3548 int st_idx = pgrm->stream_index[j];
3549 AVStream *st = fmt_ctx->streams[st_idx];
3550 if( st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
3551 if( st_idx == vidx ) pidx = i;
3554 if( pidx < 0 ) return -1;
3556 int64_t channels = 0;
3557 AVProgram *pgrm = fmt_ctx->programs[pidx];
3558 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
3559 int aidx = pgrm->stream_index[j];
3560 AVStream *st = fmt_ctx->streams[aidx];
3561 if( st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
3562 if( astream > 0 ) { --astream; continue; }
3564 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
3565 if( ffaudio[i]->fidx == aidx ) astrm = i;
3567 if( ret < 0 ) ret = astrm;
3568 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
3569 channels |= mask << ffaudio[astrm]->channel0;
3571 if( !astream ) break;
3573 channel_mask = channels;
3578 int FFMPEG::ff_total_video_layers()
3580 return vstrm_index.size();
3583 int FFMPEG::ff_total_vstreams()
3585 return ffvideo.size();
3588 int FFMPEG::ff_video_width(int stream)
3590 FFVideoStream *vst = ffvideo[stream];
3591 return !vst->transpose ? vst->width : vst->height;
3594 int FFMPEG::ff_video_height(int stream)
3596 FFVideoStream *vst = ffvideo[stream];
3597 return !vst->transpose ? vst->height : vst->width;
3600 int FFMPEG::ff_set_video_width(int stream, int width)
3602 FFVideoStream *vst = ffvideo[stream];
3603 int *vw = !vst->transpose ? &vst->width : &vst->height, w = *vw;
3608 int FFMPEG::ff_set_video_height(int stream, int height)
3610 FFVideoStream *vst = ffvideo[stream];
3611 int *vh = !vst->transpose ? &vst->height : &vst->width, h = *vh;
3616 int FFMPEG::ff_coded_width(int stream)
3618 return ffvideo[stream]->avctx->coded_width;
3621 int FFMPEG::ff_coded_height(int stream)
3623 return ffvideo[stream]->avctx->coded_height;
3626 float FFMPEG::ff_aspect_ratio(int stream)
3628 //return ffvideo[stream]->aspect_ratio;
3629 AVFormatContext *fmt_ctx = ffvideo[stream]->fmt_ctx;
3630 AVStream *strm = ffvideo[stream]->st;
3631 AVCodecParameters *par = ffvideo[stream]->st->codecpar;
3633 AVRational sar = av_guess_sample_aspect_ratio(fmt_ctx, strm, NULL);
3635 av_reduce(&dar.num, &dar.den,
3636 par->width * sar.num,
3637 par->height * sar.den,
3641 return ffvideo[stream]->aspect_ratio;
3644 const char* FFMPEG::ff_video_codec(int stream)
3646 AVStream *st = ffvideo[stream]->st;
3647 AVCodecID id = st->codecpar->codec_id;
3648 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
3649 return desc ? desc->name : _("Unknown");
3652 int FFMPEG::ff_color_range(int stream)
3654 return ffvideo[stream]->color_range;
3657 int FFMPEG::ff_color_space(int stream)
3659 return ffvideo[stream]->color_space;
3662 double FFMPEG::ff_frame_rate(int stream)
3664 return ffvideo[stream]->frame_rate;
3667 int64_t FFMPEG::ff_video_frames(int stream)
3669 return ffvideo[stream]->length;
3672 int FFMPEG::ff_video_pid(int stream)
3674 return ffvideo[stream]->st->id;
3677 int FFMPEG::ff_video_mpeg_color_range(int stream)
3679 return ffvideo[stream]->st->codecpar->color_range == AVCOL_RANGE_MPEG ? 1 : 0;
3682 int FFMPEG::ff_interlace(int stream)
3684 // https://ffmpeg.org/doxygen/trunk/structAVCodecParserContext.html
3685 /* reads from demuxer because codec frame not ready */
3686 int interlace0 = ffvideo[stream]->st->codecpar->field_order;
3692 return ILACE_MODE_TOP_FIRST;
3695 return ILACE_MODE_BOTTOM_FIRST;
3696 case AV_FIELD_PROGRESSIVE:
3697 return ILACE_MODE_NOTINTERLACED;
3699 return ILACE_MODE_UNDETECTED;
3706 int FFMPEG::ff_cpus()
3708 return !file_base ? 1 : file_base->file->cpus;
3711 const char *FFMPEG::ff_hw_dev()
3713 return &file_base->file->preferences->use_hw_dev[0];
3716 Preferences *FFMPEG::ff_prefs()
3718 return !file_base ? 0 : file_base->file->preferences;
3721 double FFVideoStream::get_rotation_angle()
3723 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
3728 int *matrix = (int*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX, &size);
3729 int len = size/sizeof(*matrix);
3730 if( !matrix || len < 5 ) return 0;
3731 const double s = 1/65536.;
3732 double theta = (!matrix[0] && !matrix[3]) || (!matrix[1] && !matrix[4]) ? 0 :
3733 atan2( s*matrix[1] / hypot(s*matrix[1], s*matrix[4]),
3734 s*matrix[0] / hypot(s*matrix[0], s*matrix[3])) * 180/M_PI;
3738 int FFVideoStream::flip(double theta)
3742 Preferences *preferences = ffmpeg->ff_prefs();
3743 if( !preferences || !preferences->auto_rotate ) return ret;
3744 double tolerance = 1;
3745 if( fabs(theta-0) < tolerance ) return ret;
3746 if( (theta=fmod(theta, 360)) < 0 ) theta += 360;
3747 if( fabs(theta-90) < tolerance ) {
3748 if( (ret = insert_filter("transpose", "clock")) < 0 )
3752 else if( fabs(theta-180) < tolerance ) {
3753 if( (ret=insert_filter("hflip", 0)) < 0 )
3755 if( (ret=insert_filter("vflip", 0)) < 0 )
3758 else if (fabs(theta-270) < tolerance ) {
3759 if( (ret=insert_filter("transpose", "cclock")) < 0 )
3764 char angle[BCSTRLEN];
3765 sprintf(angle, "%f", theta*M_PI/180.);
3766 if( (ret=insert_filter("rotate", angle)) < 0 )
3772 int FFVideoStream::create_filter(const char *filter_spec)
3774 double theta = get_rotation_angle();
3775 if( !theta && !filter_spec )
3777 avfilter_register_all();
3779 const char *sp = filter_spec;
3780 char filter_name[BCSTRLEN], *np = filter_name;
3781 int i = sizeof(filter_name);
3782 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
3784 const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
3785 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_VIDEO ) {
3786 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
3790 AVCodecParameters *avpar = st->codecpar;
3791 int sa_num = avpar->sample_aspect_ratio.num;
3792 if( !sa_num ) sa_num = 1;
3793 int sa_den = avpar->sample_aspect_ratio.den;
3794 if( !sa_den ) sa_num = 1;
3796 int ret = 0; char args[BCTEXTLEN];
3797 AVPixelFormat pix_fmt = (AVPixelFormat)avpar->format;
3798 snprintf(args, sizeof(args),
3799 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
3800 avpar->width, avpar->height, (int)pix_fmt,
3801 st->time_base.num, st->time_base.den, sa_num, sa_den);
3804 ret = insert_filter("buffer", args, "in");
3805 buffersrc_ctx = filt_ctx;
3809 AVFilterContext *fsrc = filt_ctx;
3812 ret = insert_filter("buffersink", 0, "out");
3813 buffersink_ctx = filt_ctx;
3816 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
3817 (uint8_t*)&pix_fmt, sizeof(pix_fmt),
3818 AV_OPT_SEARCH_CHILDREN);
3821 ret = config_filters(filter_spec, fsrc);
3823 ff_err(ret, "FFVideoStream::create_filter");
3824 return ret >= 0 ? 0 : -1;
3827 int FFAudioStream::create_filter(const char *filter_spec)
3831 avfilter_register_all();
3833 const char *sp = filter_spec;
3834 char filter_name[BCSTRLEN], *np = filter_name;
3835 int i = sizeof(filter_name);
3836 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
3838 const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
3839 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_AUDIO ) {
3840 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
3844 int ret = 0; char args[BCTEXTLEN];
3845 AVCodecParameters *avpar = st->codecpar;
3846 AVSampleFormat sample_fmt = (AVSampleFormat)avpar->format;
3847 snprintf(args, sizeof(args),
3848 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
3849 st->time_base.num, st->time_base.den, avpar->sample_rate,
3850 av_get_sample_fmt_name(sample_fmt), avpar->channel_layout);
3853 ret = insert_filter("abuffer", args, "in");
3854 buffersrc_ctx = filt_ctx;
3856 AVFilterContext *fsrc = filt_ctx;
3859 ret = insert_filter("abuffersink", 0, "out");
3860 buffersink_ctx = filt_ctx;
3863 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
3864 (uint8_t*)&sample_fmt, sizeof(sample_fmt),
3865 AV_OPT_SEARCH_CHILDREN);
3867 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
3868 (uint8_t*)&avpar->channel_layout,
3869 sizeof(avpar->channel_layout), AV_OPT_SEARCH_CHILDREN);
3871 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
3872 (uint8_t*)&sample_rate, sizeof(sample_rate),
3873 AV_OPT_SEARCH_CHILDREN);
3875 ret = config_filters(filter_spec, fsrc);
3877 ff_err(ret, "FFAudioStream::create_filter");
3878 return ret >= 0 ? 0 : -1;
3881 int FFStream::insert_filter(const char *name, const char *arg, const char *inst_name)
3883 const AVFilter *filter = avfilter_get_by_name(name);
3884 if( !filter ) return -1;
3885 char filt_inst[BCSTRLEN];
3887 snprintf(filt_inst, sizeof(filt_inst), "%s_%d", name, ++filt_id);
3888 inst_name = filt_inst;
3891 filter_graph = avfilter_graph_alloc();
3892 AVFilterContext *fctx = 0;
3893 int ret = avfilter_graph_create_filter(&fctx,
3894 filter, inst_name, arg, NULL, filter_graph);
3895 if( ret >= 0 && filt_ctx )
3896 ret = avfilter_link(filt_ctx, 0, fctx, 0);
3900 avfilter_free(fctx);
3904 int FFStream::config_filters(const char *filter_spec, AVFilterContext *fsrc)
3907 AVFilterContext *fsink = buffersink_ctx;
3909 /* Endpoints for the filter graph. */
3910 AVFilterInOut *outputs = avfilter_inout_alloc();
3911 AVFilterInOut *inputs = avfilter_inout_alloc();
3912 if( !inputs || !outputs ) ret = -1;
3914 outputs->filter_ctx = fsrc;
3915 outputs->pad_idx = 0;
3917 if( !(outputs->name = av_strdup(fsrc->name)) ) ret = -1;
3920 inputs->filter_ctx = fsink;
3921 inputs->pad_idx = 0;
3923 if( !(inputs->name = av_strdup(fsink->name)) ) ret = -1;
3926 int len = strlen(fsrc->name)+2 + strlen(filter_spec) + 1;
3927 char spec[len]; sprintf(spec, "[%s]%s", fsrc->name, filter_spec);
3928 ret = avfilter_graph_parse_ptr(filter_graph, spec,
3929 &inputs, &outputs, NULL);
3931 avfilter_inout_free(&inputs);
3932 avfilter_inout_free(&outputs);
3935 ret = avfilter_link(fsrc, 0, fsink, 0);
3937 ret = avfilter_graph_config(filter_graph, NULL);
3939 ff_err(ret, "FFStream::create_filter");
3940 avfilter_graph_free(&filter_graph);
3947 AVCodecContext *FFMPEG::activate_decoder(AVStream *st)
3949 AVDictionary *copts = 0;
3950 av_dict_copy(&copts, opts, 0);
3951 AVCodecID codec_id = st->codecpar->codec_id;
3952 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
3953 const AVCodec *decoder = 0;
3955 AVCodec *decoder = 0;
3957 switch( st->codecpar->codec_type ) {
3958 case AVMEDIA_TYPE_VIDEO:
3959 if( opt_video_decoder )
3960 decoder = avcodec_find_decoder_by_name(opt_video_decoder);
3962 video_codec_remaps.update(codec_id, decoder);
3964 case AVMEDIA_TYPE_AUDIO:
3965 if( opt_audio_decoder )
3966 decoder = avcodec_find_decoder_by_name(opt_audio_decoder);
3968 audio_codec_remaps.update(codec_id, decoder);
3973 if( !decoder && !(decoder = avcodec_find_decoder(codec_id)) ) {
3974 eprintf(_("cant find decoder codec %d\n"), (int)codec_id);
3977 AVCodecContext *avctx = avcodec_alloc_context3(decoder);
3979 eprintf(_("cant allocate codec context\n"));
3982 avcodec_parameters_to_context(avctx, st->codecpar);
3983 if( !av_dict_get(copts, "threads", NULL, 0) )
3984 avctx->thread_count = ff_cpus();
3985 int ret = avcodec_open2(avctx, decoder, &copts);
3986 av_dict_free(&copts);
3988 avcodec_free_context(&avctx);
3994 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
3997 av_init_packet(&pkt);
3998 AVFrame *frame = av_frame_alloc();
4000 fprintf(stderr,"FFMPEG::scan: ");
4001 fprintf(stderr,_("av_frame_alloc failed\n"));
4002 fprintf(stderr,"FFMPEG::scan:file=%s\n", file_base->asset->path);
4006 index_state->add_video_markers(ffvideo.size());
4007 index_state->add_audio_markers(ffaudio.size());
4009 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
4010 AVStream *st = fmt_ctx->streams[i];
4011 AVCodecContext *avctx = activate_decoder(st);
4013 AVCodecParameters *avpar = st->codecpar;
4014 switch( avpar->codec_type ) {
4015 case AVMEDIA_TYPE_VIDEO: {
4016 int vidx = ffvideo.size();
4017 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
4018 if( vidx < 0 ) break;
4019 ffvideo[vidx]->avctx = avctx;
4021 case AVMEDIA_TYPE_AUDIO: {
4022 int aidx = ffaudio.size();
4023 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
4024 if( aidx < 0 ) break;
4025 ffaudio[aidx]->avctx = avctx;
4030 fprintf(stderr,"FFMPEG::scan: ");
4031 fprintf(stderr,_("codec open failed\n"));
4032 fprintf(stderr,"FFMPEG::scan:file=%s\n", file_base->asset->path);
4033 avcodec_free_context(&avctx);
4037 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
4038 AVStream *st = fmt_ctx->streams[i];
4039 AVCodecParameters *avpar = st->codecpar;
4040 if( avpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
4041 int64_t tstmp = st->start_time;
4042 if( tstmp == AV_NOPTS_VALUE ) continue;
4043 int aidx = ffaudio.size();
4044 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
4045 if( aidx < 0 ) continue;
4046 FFAudioStream *aud = ffaudio[aidx];
4047 tstmp -= aud->nudge;
4048 double secs = to_secs(tstmp, st->time_base);
4049 aud->curr_pos = secs * aud->sample_rate + 0.5;
4053 for( int64_t count=0; !*canceled; ++count ) {
4054 av_packet_unref(&pkt);
4055 pkt.data = 0; pkt.size = 0;
4057 int ret = av_read_frame(fmt_ctx, &pkt);
4059 if( ret == AVERROR_EOF ) break;
4060 if( ++errs > 100 ) {
4061 ff_err(ret,_("over 100 read_frame errs\n"));
4066 if( !pkt.data ) continue;
4067 int i = pkt.stream_index;
4068 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
4069 AVStream *st = fmt_ctx->streams[i];
4070 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
4072 AVCodecParameters *avpar = st->codecpar;
4073 switch( avpar->codec_type ) {
4074 case AVMEDIA_TYPE_VIDEO: {
4075 int vidx = ffvideo.size();
4076 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
4077 if( vidx < 0 ) break;
4078 FFVideoStream *vid = ffvideo[vidx];
4079 if( !vid->avctx ) break;
4080 int64_t tstmp = pkt.pts;
4081 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
4082 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
4083 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
4084 double secs = to_secs(tstmp, st->time_base);
4085 int64_t frm = secs * vid->frame_rate + 0.5;
4086 if( frm < 0 ) frm = 0;
4087 index_state->put_video_mark(vidx, frm, pkt.pos);
4090 ret = avcodec_send_packet(vid->avctx, pkt);
4091 if( ret < 0 ) break;
4092 while( (ret=vid->decode_frame(frame)) > 0 ) {}
4095 case AVMEDIA_TYPE_AUDIO: {
4096 int aidx = ffaudio.size();
4097 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
4098 if( aidx < 0 ) break;
4099 FFAudioStream *aud = ffaudio[aidx];
4100 if( !aud->avctx ) break;
4101 int64_t tstmp = pkt.pts;
4102 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
4103 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
4104 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
4105 double secs = to_secs(tstmp, st->time_base);
4106 int64_t sample = secs * aud->sample_rate + 0.5;
4108 index_state->put_audio_mark(aidx, sample, pkt.pos);
4110 ret = avcodec_send_packet(aud->avctx, &pkt);
4111 if( ret < 0 ) break;
4112 int ch = aud->channel0, nch = aud->channels;
4113 int64_t pos = index_state->pos(ch);
4114 if( pos != aud->curr_pos ) {
4115 if( abs(pos-aud->curr_pos) > 1 )
4116 printf("audio%d pad %jd %jd (%jd)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
4117 index_state->pad_data(ch, nch, aud->curr_pos);
4119 while( (ret=aud->decode_frame(frame)) > 0 ) {
4120 //if( frame->channels != nch ) break;
4121 aud->init_swr(frame->channels, frame->format, frame->sample_rate);
4123 int len = aud->get_samples(samples,
4124 &frame->extended_data[0], frame->nb_samples);
4125 pos = aud->curr_pos;
4126 if( (aud->curr_pos += len) >= 0 ) {
4128 samples += -pos * nch;
4129 len = aud->curr_pos;
4131 for( int i=0; i<nch; ++i )
4132 index_state->put_data(ch+i,nch,samples+i,len);
4139 av_frame_free(&frame);
4143 void FFStream::load_markers(IndexMarks &marks, double rate)
4146 int64_t sz = marks.size();
4147 int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
4148 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
4149 int nb_ent = avformat_index_get_entries_count(st);
4151 #if LIBAVCODEC_VERSION_INT <= AV_VERSION_INT(58,134,100)
4152 int nb_ent = st->nb_index_entries;
4154 // some formats already have an index
4156 #if LIBAVCODEC_VERSION_INT <= AV_VERSION_INT(58,134,100)
4157 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
4159 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
4160 const AVIndexEntry *ep = avformat_index_get_entry(st, nb_ent-1);
4162 int64_t tstmp = ep->timestamp;
4163 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
4164 double secs = ffmpeg->to_secs(tstmp, st->time_base);
4165 int64_t no = secs * rate;
4166 while( in < sz && marks[in].no <= no ) ++in;
4168 int64_t len = sz - in;
4169 int64_t count = max_entries - nb_ent;
4170 if( count > len ) count = len;
4171 for( int i=0; i<count; ++i ) {
4172 int k = in + i * len / count;
4173 int64_t no = marks[k].no, pos = marks[k].pos;
4174 double secs = (double)no / rate;
4175 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
4176 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
4177 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);
4183 * 1) if the format context has a timecode
4184 * return fmt_ctx->timecode - 0
4185 * 2) if the layer/channel has a timecode
4186 * return st->timecode - (start_time-nudge)
4187 * 3) find the 1st program with stream, find 1st program video stream,
4188 * if video stream has a timecode, return st->timecode - (start_time-nudge)
4189 * 4) find timecode in any stream, return st->timecode
4190 * 5) read 100 packets, save ofs=pkt.pts*st->time_base - st->nudge:
4191 * decode frame for video stream of 1st program
4192 * if frame->timecode has a timecode, return frame->timecode - ofs
4193 * if side_data has gop timecode, return gop->timecode - ofs
4194 * if side_data has smpte timecode, return smpte->timecode - ofs
4195 * 6) if the filename/url scans *date_time.ext, return date_time
4196 * 7) if stat works on the filename/url, return mtime
4197 * 8) return -1 failure
4199 double FFMPEG::get_initial_timecode(int data_type, int channel, double frame_rate)
4201 AVRational rate = check_frame_rate(0, frame_rate);
4202 if( !rate.num ) return -1;
4203 // format context timecode
4204 AVDictionaryEntry *tc = av_dict_get(fmt_ctx->metadata, "timecode", 0, 0);
4205 if( tc ) return ff_get_timecode(tc->value, rate, 0);
4207 if( open_decoder() ) return -1;
4210 int codec_type = -1, fidx = -1;
4211 switch( data_type ) {
4213 codec_type = AVMEDIA_TYPE_AUDIO;
4214 int aidx = astrm_index[channel].st_idx;
4215 FFAudioStream *aud = ffaudio[aidx];
4219 AVDictionaryEntry *tref = av_dict_get(fmt_ctx->metadata, "time_reference", 0, 0);
4220 if( tref && aud && aud->sample_rate )
4221 return strtod(tref->value, 0) / aud->sample_rate;
4224 codec_type = AVMEDIA_TYPE_VIDEO;
4225 int vidx = vstrm_index[channel].st_idx;
4226 FFVideoStream *vid = ffvideo[vidx];
4232 if( codec_type < 0 ) return -1;
4234 tc = av_dict_get(st->metadata, "timecode", 0, 0);
4237 // find first program which references this stream
4239 for( int i=0, m=fmt_ctx->nb_programs; pidx<0 && i<m; ++i ) {
4240 AVProgram *pgrm = fmt_ctx->programs[i];
4241 for( int j=0, n=pgrm->nb_stream_indexes; j<n; ++j ) {
4242 int st_idx = pgrm->stream_index[j];
4243 if( st_idx == fidx ) { pidx = i; break; }
4248 AVProgram *pgrm = fmt_ctx->programs[pidx];
4249 for( int j=0, n=pgrm->nb_stream_indexes; j<n; ++j ) {
4250 int st_idx = pgrm->stream_index[j];
4251 AVStream *tst = fmt_ctx->streams[st_idx];
4252 if( !tst ) continue;
4253 if( tst->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
4254 st = tst; fidx = st_idx;
4260 for( int i=0, n=fmt_ctx->nb_streams; i<n; ++i ) {
4261 AVStream *tst = fmt_ctx->streams[i];
4262 if( !tst ) continue;
4263 if( tst->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
4270 tc = av_dict_get(st->metadata, "timecode", 0, 0);
4274 // any timecode, includes -data- streams
4275 for( int i=0, n=fmt_ctx->nb_streams; i<n; ++i ) {
4276 AVStream *tst = fmt_ctx->streams[i];
4277 if( !tst ) continue;
4278 if( (tc = av_dict_get(tst->metadata, "timecode", 0, 0)) ) {
4285 if( st && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
4286 if( st->r_frame_rate.num && st->r_frame_rate.den )
4287 rate = st->r_frame_rate;
4288 nudge = st->start_time;
4289 for( int i=0; i<ffvideo.size(); ++i ) {
4290 if( ffvideo[i]->st == st ) {
4291 nudge = ffvideo[i]->nudge;
4297 if( tc ) { // return timecode
4298 double secs = st->start_time == AV_NOPTS_VALUE ? 0 :
4299 to_secs(st->start_time - nudge, st->time_base);
4300 return ff_get_timecode(tc->value, rate, secs);
4303 if( !st || fidx < 0 ) return -1;
4306 AVCodecContext *av_ctx = activate_decoder(st);
4308 fprintf(stderr,"activate_decoder failed\n");
4311 avCodecContext avctx(av_ctx); // auto deletes
4312 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO &&
4313 avctx->framerate.num && avctx->framerate.den )
4314 rate = avctx->framerate;
4316 avPacket pkt; // auto deletes
4317 avFrame frame; // auto deletes
4319 fprintf(stderr,"av_frame_alloc failed\n");
4323 int64_t max_packets = 100;
4324 char tcbuf[AV_TIMECODE_STR_SIZE];
4326 for( int64_t count=0; count<max_packets; ++count ) {
4327 av_packet_unref(pkt);
4328 pkt->data = 0; pkt->size = 0;
4330 int ret = av_read_frame(fmt_ctx, pkt);
4332 if( ret == AVERROR_EOF ) break;
4333 if( ++errs > 100 ) {
4334 fprintf(stderr,"over 100 read_frame errs\n");
4339 if( !pkt->data ) continue;
4340 int i = pkt->stream_index;
4341 if( i != fidx ) continue;
4342 int64_t tstmp = pkt->pts;
4343 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt->dts;
4344 double secs = to_secs(tstmp - nudge, st->time_base);
4345 ret = avcodec_send_packet(avctx, pkt);
4346 if( ret < 0 ) return -1;
4348 while( (ret = avcodec_receive_frame(avctx, frame)) >= 0 ) {
4349 if( (tc = av_dict_get(frame->metadata, "timecode", 0, 0)) )
4350 return ff_get_timecode(tc->value, rate, secs);
4351 int k = frame->nb_side_data;
4352 AVFrameSideData *side_data = 0;
4354 side_data = frame->side_data[k];
4355 switch( side_data->type ) {
4356 case AV_FRAME_DATA_GOP_TIMECODE: {
4357 int64_t data = *(int64_t *)side_data->data;
4358 int sz = sizeof(data);
4359 if( side_data->size >= sz ) {
4360 av_timecode_make_mpeg_tc_string(tcbuf, data);
4361 return ff_get_timecode(tcbuf, rate, secs);
4364 case AV_FRAME_DATA_S12M_TIMECODE: {
4365 uint32_t *data = (uint32_t *)side_data->data;
4366 int n = data[0], sz = (n+1)*sizeof(*data);
4367 if( side_data->size >= sz ) {
4368 av_timecode_make_smpte_tc_string(tcbuf, data[n], 0);
4369 return ff_get_timecode(tcbuf, rate, secs);
4378 char *path = fmt_ctx->url;
4379 char *bp = strrchr(path, '/');
4380 if( !bp ) bp = path; else ++bp;
4381 char *cp = strrchr(bp, '.');
4382 if( cp && (cp-=(8+1+6)) >= bp ) {
4384 int year,mon,day, hour,min,sec, frm=0;
4385 if( sscanf(cp,"%4d%2d%2d%[_-]%2d%2d%2d",
4386 &year,&mon,&day, sep, &hour,&min,&sec) == 7 ) {
4388 // year>=1970,mon=1..12,day=1..31, hour=0..23,min=0..59,sec=0..60
4389 if( (ch=='_' || ch=='-' ) &&
4390 year >= 1970 && mon>=1 && mon<=12 && day>=1 && day<=31 &&
4391 hour>=0 && hour<24 && min>=0 && min<60 && sec>=0 && sec<=60 ) {
4392 sprintf(tcbuf,"%d:%02d:%02d:%02d", hour,min,sec, frm);
4393 return ff_get_timecode(tcbuf, rate, 0);
4398 if( stat(path, &tst) >= 0 ) {
4399 time_t t = (time_t)tst.st_mtim.tv_sec;
4401 localtime_r(&t, &tm);
4402 int64_t us = tst.st_mtim.tv_nsec / 1000;
4403 int frm = us/1000000. * frame_rate;
4404 sprintf(tcbuf,"%d:%02d:%02d:%02d", tm.tm_hour, tm.tm_min, tm.tm_sec, frm);
4405 return ff_get_timecode(tcbuf, rate, 0);
4410 double FFMPEG::ff_get_timecode(char *str, AVRational rate, double pos)
4413 if( av_timecode_init_from_string(&tc, rate, str, fmt_ctx) )
4415 double secs = (double)tc.start / tc.fps - pos;
4416 if( secs < 0 ) secs = 0;
4420 double FFMPEG::get_timecode(const char *path, int data_type, int channel, double rate)
4423 if( ffmpeg.init_decoder(path) ) return -1;
4424 return ffmpeg.get_initial_timecode(data_type, channel, rate);