3 * Copyright (C) 2012-2014 Paolo Rampino
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
31 // work arounds (centos)
34 #define INT64_MAX 9223372036854775807LL
36 #define MAX_RETRY 1000
37 // max pts/curr_pos drift allowed before correction (in seconds)
38 #define AUDIO_PTS_TOLERANCE 0.04
41 #include "bccmodels.h"
44 #include "edlsession.h"
46 #include "fileffmpeg.h"
47 #include "filesystem.h"
49 #include "indexfile.h"
50 #include "interlacemodes.h"
55 #include "mainerror.h"
57 #include "preferences.h"
63 #define av_register_all(s)
64 #define avfilter_register_all(s)
67 #define VIDEO_INBUF_SIZE 0x10000
68 #define AUDIO_INBUF_SIZE 0x10000
69 #define VIDEO_REFILL_THRESH 0
70 #define AUDIO_REFILL_THRESH 0x1000
71 #define AUDIO_MIN_FRAME_SZ 128
73 #define FF_ESTM_TIMES 0x0001
74 #define FF_BAD_TIMES 0x0002
76 Mutex FFMPEG::fflock("FFMPEG::fflock");
78 static void ff_err(int ret, const char *fmt, ...)
83 vsnprintf(msg, sizeof(msg), fmt, ap);
85 char errmsg[BCSTRLEN];
86 av_strerror(ret, errmsg, sizeof(errmsg));
87 fprintf(stderr,_("%s err: %s\n"),msg, errmsg);
93 pkt.data = 0; pkt.size = 0;
95 void FFPacket::finit()
97 av_packet_unref(&pkt);
100 FFrame::FFrame(FFStream *fst)
103 frm = av_frame_alloc();
104 init = fst->init_frame(frm);
112 void FFrame::queue(int64_t pos)
118 void FFrame::dequeue()
123 void FFrame::set_hw_frame(AVFrame *frame)
129 int FFAudioStream::read(float *fp, long len)
137 while( --k >= 0 ) *fp++ = *op++;
138 if( op >= lmt ) op = bfr;
143 void FFAudioStream::realloc(long nsz, int nch, long len)
145 long bsz = nsz * nch;
146 float *np = new float[bsz];
147 inp = np + read(np, len) * nch;
152 delete [] bfr; bfr = np;
155 void FFAudioStream::realloc(long nsz, int nch)
157 if( nsz > sz || this->nch != nch ) {
158 long len = this->nch != nch ? 0 : hpos;
159 if( len > sz ) len = sz;
161 realloc(nsz, nch, len);
165 void FFAudioStream::reserve(long nsz, int nch)
167 long len = (inp - outp) / nch;
169 if( nsz > sz || this->nch != nch ) {
170 if( this->nch != nch ) len = 0;
171 realloc(nsz, nch, len);
174 if( (len*=nch) > 0 && bfr != outp )
175 memmove(bfr, outp, len*sizeof(*bfr));
180 long FFAudioStream::used()
182 long len = inp>=outp ? inp-outp : inp-bfr + lmt-outp;
185 long FFAudioStream::avail()
188 if( in1 >= lmt ) in1 = bfr;
189 long len = outp >= in1 ? outp-in1 : outp-bfr + lmt-in1;
192 void FFAudioStream::reset_history()
196 memset(bfr, 0, lmt-bfr);
199 void FFAudioStream::iseek(int64_t ofs)
201 if( ofs > hpos ) ofs = hpos;
202 if( ofs > sz ) ofs = sz;
203 outp = inp - ofs*nch;
204 if( outp < bfr ) outp += sz*nch;
207 float *FFAudioStream::get_outp(int ofs)
214 int64_t FFAudioStream::put_inp(int ofs)
217 return (inp-outp) / nch;
220 int FFAudioStream::write(const float *fp, long len)
228 while( --k >= 0 ) *ip++ = *fp++;
229 if( ip >= lmt ) ip = bfr;
236 int FFAudioStream::zero(long len)
244 while( --k >= 0 ) *ip++ = 0;
245 if( ip >= lmt ) ip = bfr;
252 // does not advance outp
253 int FFAudioStream::read(double *dp, long len, int ch)
256 float *op = outp + ch;
257 float *lmt1 = lmt + nch-1;
259 int k = (lmt1 - op) / nch;
262 while( --k >= 0 ) { *dp++ = *op; op += nch; }
263 if( op >= lmt ) op -= sz*nch;
268 // load linear buffer, no wrapping allowed, does not advance inp
269 int FFAudioStream::write(const double *dp, long len, int ch)
272 float *ip = inp + ch;
273 while( --n >= 0 ) { *ip = *dp++; ip += nch; }
278 FFStream::FFStream(FFMPEG *ffmpeg, AVStream *st, int fidx)
280 this->ffmpeg = ffmpeg;
283 frm_lock = new Mutex("FFStream::frm_lock");
292 nudge = AV_NOPTS_VALUE;
293 seek_pos = curr_pos = 0;
294 seeking = 0; seeked = 1;
296 reading = writing = 0;
297 hw_pixfmt = AV_PIX_FMT_NONE;
310 FFStream::~FFStream()
312 frm_lock->lock("FFStream::~FFStream");
313 if( reading > 0 || writing > 0 ) avcodec_close(avctx);
314 if( avctx ) avcodec_free_context(&avctx);
315 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
316 if( hw_device_ctx ) av_buffer_unref(&hw_device_ctx);
317 if( bsfc ) av_bsf_free(&bsfc);
318 while( frms.first ) frms.remove(frms.first);
319 if( filter_graph ) avfilter_graph_free(&filter_graph);
320 if( frame ) av_frame_free(&frame);
321 if( fframe ) av_frame_free(&fframe);
322 if( probe_frame ) av_frame_free(&probe_frame);
325 if( stats_fp ) fclose(stats_fp);
326 if( stats_in ) av_freep(&stats_in);
327 delete [] stats_filename;
330 void FFStream::ff_lock(const char *cp)
332 FFMPEG::fflock.lock(cp);
335 void FFStream::ff_unlock()
337 FFMPEG::fflock.unlock();
340 void FFStream::queue(FFrame *frm)
342 frm_lock->lock("FFStream::queue");
346 ffmpeg->mux_lock->unlock();
349 void FFStream::dequeue(FFrame *frm)
351 frm_lock->lock("FFStream::dequeue");
353 frms.remove_pointer(frm);
357 int FFStream::encode_activate()
360 writing = ffmpeg->encode_activate();
364 // this is a global parameter that really should be in the context
365 static AVPixelFormat hw_pix_fmt = AV_PIX_FMT_NONE; // protected by ff_lock
367 // goofy maneuver to attach a hw_format to an av_context
368 #define GET_HW_PIXFMT(fn, fmt) \
369 static AVPixelFormat get_hw_##fn(AVCodecContext *ctx, const enum AVPixelFormat *pix_fmts) { \
372 GET_HW_PIXFMT(vaapi, AV_PIX_FMT_VAAPI)
373 GET_HW_PIXFMT(vdpau, AV_PIX_FMT_VDPAU)
374 GET_HW_PIXFMT(cuda, AV_PIX_FMT_CUDA)
375 GET_HW_PIXFMT(nv12, AV_PIX_FMT_NV12)
377 static enum AVPixelFormat get_hw_format(AVCodecContext *ctx,
378 const enum AVPixelFormat *pix_fmts)
380 for( const enum AVPixelFormat *p=pix_fmts; *p!=AV_PIX_FMT_NONE; ++p ) {
381 if( *p != hw_pix_fmt ) continue;
383 case AV_PIX_FMT_VAAPI: ctx->get_format = get_hw_vaapi; return *p;
384 case AV_PIX_FMT_VDPAU: ctx->get_format = get_hw_vdpau; return *p;
385 case AV_PIX_FMT_CUDA: ctx->get_format = get_hw_cuda; return *p;
386 case AV_PIX_FMT_NV12: ctx->get_format = get_hw_nv12; return *p;
388 fprintf(stderr, "Unknown HW surface format: %s\n",
389 av_get_pix_fmt_name(*p));
393 fprintf(stderr, "Failed to get HW surface format.\n");
394 return hw_pix_fmt = AV_PIX_FMT_NONE;
398 AVHWDeviceType FFStream::decode_hw_activate()
400 return AV_HWDEVICE_TYPE_NONE;
402 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
403 int FFStream::decode_hw_format(const AVCodec *decoder, AVHWDeviceType type)
405 int FFStream::decode_hw_format(AVCodec *decoder, AVHWDeviceType type)
411 int FFStream::decode_activate()
413 if( reading < 0 && (reading=ffmpeg->decode_activate()) > 0 ) {
414 ff_lock("FFStream::decode_activate");
416 AVDictionary *copts = 0;
417 av_dict_copy(&copts, ffmpeg->opts, 0);
419 AVHWDeviceType hw_type = decode_hw_activate();
421 // this should be avformat_copy_context(), but no copy avail
422 ret = avformat_open_input(&fmt_ctx,
423 ffmpeg->fmt_ctx->url, ffmpeg->fmt_ctx->iformat, &copts);
425 ret = avformat_find_stream_info(fmt_ctx, 0);
426 st = fmt_ctx->streams[fidx];
429 while( ret >= 0 && st != 0 && !reading ) {
430 AVCodecID codec_id = st->codecpar->codec_id;
431 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
432 const AVCodec *decoder = 0;
434 AVCodec *decoder = 0;
437 if( ffmpeg->opt_video_decoder )
438 decoder = avcodec_find_decoder_by_name(ffmpeg->opt_video_decoder);
440 ffmpeg->video_codec_remaps.update(codec_id, decoder);
442 else if( is_audio() ) {
443 if( ffmpeg->opt_audio_decoder )
444 decoder = avcodec_find_decoder_by_name(ffmpeg->opt_audio_decoder);
446 ffmpeg->audio_codec_remaps.update(codec_id, decoder);
449 decoder = avcodec_find_decoder(codec_id);
450 avctx = avcodec_alloc_context3(decoder);
452 eprintf(_("cant allocate codec context\n"));
453 ret = AVERROR(ENOMEM);
455 if( ret >= 0 && hw_type != AV_HWDEVICE_TYPE_NONE ) {
456 ret = decode_hw_format(decoder, hw_type);
459 avcodec_parameters_to_context(avctx, st->codecpar);
460 if( !av_dict_get(copts, "threads", NULL, 0) )
461 avctx->thread_count = ffmpeg->ff_cpus();
462 ret = avcodec_open2(avctx, decoder, &copts);
464 AVFrame *hw_frame = 0;
465 if( ret >= 0 && hw_type != AV_HWDEVICE_TYPE_NONE ) {
466 if( !(hw_frame=av_frame_alloc()) ) {
467 fprintf(stderr, "FFStream::decode_activate: av_frame_alloc failed\n");
468 ret = AVERROR(ENOMEM);
471 ret = decode(hw_frame);
473 if( ret < 0 && hw_type != AV_HWDEVICE_TYPE_NONE ) {
474 ff_err(ret, "HW device init failed, using SW decode.\nfile:%s\n",
475 ffmpeg->fmt_ctx->url);
476 avcodec_close(avctx);
477 avcodec_free_context(&avctx);
478 av_buffer_unref(&hw_device_ctx);
480 av_frame_free(&hw_frame);
481 hw_type = AV_HWDEVICE_TYPE_NONE;
482 int flags = AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_ANY;
484 av_seek_frame(fmt_ctx, idx, 0, flags);
485 need_packet = 1; flushed = 0;
486 seeked = 1; st_eof(0);
490 probe_frame = hw_frame;
494 eprintf(_("open decoder failed\n"));
497 eprintf(_("can't open input file: %s\n"), ffmpeg->fmt_ctx->url);
498 av_dict_free(&copts);
504 int FFStream::read_packet()
506 av_packet_unref(ipkt);
507 int ret = av_read_frame(fmt_ctx, ipkt);
510 if( ret == AVERROR_EOF ) return 0;
511 ff_err(ret, "FFStream::read_packet: av_read_frame failed\n");
518 int FFStream::decode(AVFrame *frame)
520 if( probe_frame ) { // hw probe reads first frame
521 av_frame_ref(frame, probe_frame);
522 av_frame_free(&probe_frame);
526 int retries = MAX_RETRY;
527 frm_lock->lock("FFStream::decode");
528 while( ret >= 0 && !flushed && --retries >= 0 ) {
530 if( (ret=read_packet()) < 0 ) break;
531 AVPacket *pkt = ret > 0 ? (AVPacket*)ipkt : 0;
533 if( pkt->stream_index != st->index ) continue;
534 if( !pkt->data || !pkt->size ) continue;
536 if( (ret=avcodec_send_packet(avctx, pkt)) < 0 ) {
537 ff_err(ret, "FFStream::decode: avcodec_send_packet failed.\nfile:%s\n",
538 ffmpeg->fmt_ctx->url);
544 if( (ret=decode_frame(frame)) > 0 ) break;
553 fprintf(stderr, "FFStream::decode: Retry limit\n");
557 fprintf(stderr, "FFStream::decode: failed\n");
561 int FFStream::load_filter(AVFrame *frame)
563 int ret = av_buffersrc_add_frame_flags(buffersrc_ctx, frame, 0);
565 eprintf(_("av_buffersrc_add_frame_flags failed\n"));
569 int FFStream::read_filter(AVFrame *frame)
571 int ret = av_buffersink_get_frame(buffersink_ctx, frame);
573 if( ret == AVERROR(EAGAIN) ) return 0;
574 if( ret == AVERROR_EOF ) { st_eof(1); return -1; }
575 ff_err(ret, "FFStream::read_filter: av_buffersink_get_frame failed\n");
581 int FFStream::read_frame(AVFrame *frame)
583 av_frame_unref(frame);
584 if( !filter_graph || !buffersrc_ctx || !buffersink_ctx )
585 return decode(frame);
586 if( !fframe && !(fframe=av_frame_alloc()) ) {
587 fprintf(stderr, "FFStream::read_frame: av_frame_alloc failed\n");
591 while( !flushed && !(ret=read_filter(frame)) ) {
592 if( (ret=decode(fframe)) < 0 ) break;
593 if( ret > 0 && (ret=load_filter(fframe)) < 0 ) break;
598 int FFStream::write_packet(FFPacket &pkt)
602 av_packet_rescale_ts(pkt, avctx->time_base, st->time_base);
603 pkt->stream_index = st->index;
604 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, pkt);
607 bsfc->time_base_in = st->time_base;
608 avcodec_parameters_copy(bsfc->par_in, st->codecpar);
611 ret = av_bsf_send_packet(bsfc, pkt);
614 if( (ret=av_bsf_receive_packet(bsfc, bs)) < 0 ) {
615 if( ret == AVERROR(EAGAIN) ) return 0;
616 if( ret == AVERROR_EOF ) return -1;
619 //printf(" filter name %s \n", bsfc->filter[0].name);
620 //avcodec_parameters_copy(ffmpeg->fmt_ctx->streams[0]->codecpar, bsfc->par_out);
621 //avcodec_parameters_copy(st->codecpar, bsfc->par_out);
622 av_packet_rescale_ts(bs, avctx->time_base, st->time_base);
623 bs->stream_index = st->index;
624 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, bs);
628 ff_err(ret, "FFStream::write_packet: write packet failed.\nfile:%s\n",
629 ffmpeg->fmt_ctx->url);
633 int FFStream::encode_frame(AVFrame *frame)
635 int pkts = 0, ret = 0;
636 for( int retry=MAX_RETRY; --retry>=0; ) {
638 ret = avcodec_send_frame(avctx, frame);
639 if( !ret && frame ) return pkts;
640 if( ret < 0 && ret != AVERROR(EAGAIN) ) break;
641 if ( ret == AVERROR(EAGAIN) && !frame ) continue;
643 ret = avcodec_receive_packet(avctx, opkt);
644 if( !frame && ret == AVERROR_EOF ) return pkts;
646 ret = write_packet(opkt);
649 if( frame && stats_fp ) {
650 ret = write_stats_file();
654 ff_err(ret, "FFStream::encode_frame: encode failed.\nfile: %s\n",
655 ffmpeg->fmt_ctx->url);
659 int FFStream::flush()
663 int ret = encode_frame(0);
664 if( ret >= 0 && stats_fp ) {
665 ret = write_stats_file();
669 ff_err(ret, "FFStream::flush failed\n:file:%s\n",
670 ffmpeg->fmt_ctx->url);
671 return ret >= 0 ? 0 : 1;
675 int FFStream::open_stats_file()
677 stats_fp = fopen(stats_filename,"w");
678 return stats_fp ? 0 : AVERROR(errno);
681 int FFStream::close_stats_file()
684 fclose(stats_fp); stats_fp = 0;
689 int FFStream::read_stats_file()
691 int64_t len = 0; struct stat stats_st;
692 int fd = open(stats_filename, O_RDONLY);
693 int ret = fd >= 0 ? 0: ENOENT;
694 if( !ret && fstat(fd, &stats_st) )
697 len = stats_st.st_size;
698 stats_in = (char *)av_malloc(len+1);
702 if( !ret && read(fd, stats_in, len+1) != len )
706 avctx->stats_in = stats_in;
710 return !ret ? 0 : AVERROR(ret);
713 int FFStream::write_stats_file()
716 if( avctx->stats_out && (ret=strlen(avctx->stats_out)) > 0 ) {
717 int len = fwrite(avctx->stats_out, 1, ret, stats_fp);
719 ff_err(ret = AVERROR(errno), "FFStream::write_stats_file.\n%file:%s\n",
720 ffmpeg->fmt_ctx->url);
725 int FFStream::init_stats_file()
728 if( (pass & 2) && (ret = read_stats_file()) < 0 )
729 ff_err(ret, "stat file read: %s", stats_filename);
730 if( (pass & 1) && (ret=open_stats_file()) < 0 )
731 ff_err(ret, "stat file open: %s", stats_filename);
732 return ret >= 0 ? 0 : ret;
735 int FFStream::seek(int64_t no, double rate)
737 // default ffmpeg native seek
739 int64_t pos = no, pkt_pos = -1;
740 IndexMarks *index_markers = get_markers();
741 if( index_markers && index_markers->size() > 1 ) {
742 IndexMarks &marks = *index_markers;
743 int i = marks.find(pos);
744 int64_t n = i < 0 ? (i=0) : marks[i].no;
745 // if indexed seek point not too far away (<30 secs), use index
746 if( no-n < 30*rate ) {
749 if( i < marks.size() ) pkt_pos = marks[i].pos;
753 if( pos == curr_pos ) return 0;
755 double secs = pos < 0 ? 0. : pos / rate;
756 AVRational time_base = st->time_base;
757 int64_t tstmp = time_base.num > 0 ? secs * time_base.den/time_base.num : 0;
758 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
759 int nb_index_entries = avformat_index_get_entries_count(st);
762 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
763 if( nb_index_entries > 0 ) tstmp = (avformat_index_get_entry(st, 0))->timestamp;
765 if( st->nb_index_entries > 0 ) tstmp = st->index_entries[0].timestamp;
767 else if( st->start_time != AV_NOPTS_VALUE ) tstmp = st->start_time;
768 #if LIBAVCODEC_VERSION_INT <= AV_VERSION_INT(58,134,100)
769 else if( st->first_dts != AV_NOPTS_VALUE ) tstmp = st->first_dts;
771 else tstmp = INT64_MIN+1;
773 else if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
776 // seek all streams using the default timebase.
777 // this is how ffmpeg and ffplay work. stream seeks are less tested.
778 tstmp = av_rescale_q(tstmp, time_base, AV_TIME_BASE_Q);
781 frm_lock->lock("FFStream::seek");
782 av_frame_free(&probe_frame);
783 avcodec_flush_buffers(avctx);
784 avformat_flush(fmt_ctx);
786 int64_t seek = tstmp;
787 int flags = AVSEEK_FLAG_ANY;
788 if( !(fmt_ctx->iformat->flags & AVFMT_NO_BYTE_SEEK) && pkt_pos >= 0 ) {
790 flags = AVSEEK_FLAG_BYTE;
792 int ret = avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, seek, INT64_MAX, flags);
794 // finds the first index frame below the target time
795 int flags = AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_ANY;
796 int ret = av_seek_frame(fmt_ctx, idx, tstmp, flags);
798 int retry = MAX_RETRY;
800 need_packet = 0; flushed = 0;
801 seeked = 1; st_eof(0);
802 // read up to retry packets, limited to npkts in stream, and not pkt.pos past pkt_pos
803 while( --retry >= 0 ) {
804 if( read_packet() <= 0 ) { ret = -1; break; }
805 if( ipkt->stream_index != st->index ) continue;
806 if( !ipkt->data || !ipkt->size ) continue;
807 if( pkt_pos >= 0 && ipkt->pos >= pkt_pos ) break;
808 if( --npkts <= 0 ) break;
809 int64_t pkt_ts = ipkt->dts != AV_NOPTS_VALUE ? ipkt->dts : ipkt->pts;
810 if( pkt_ts == AV_NOPTS_VALUE ) continue;
811 if( pkt_ts >= tstmp ) break;
814 ff_err(AVERROR(EIO), "FFStream::seek: %s\n"
815 " retry limit, pos=%jd tstmp=%jd, ",
816 ffmpeg->fmt_ctx->url, pos, tstmp);
820 ret = avcodec_send_packet(avctx, ipkt);
822 //some codecs need more than one pkt to resync
823 if( ret == AVERROR_INVALIDDATA ) ret = 0;
825 ff_err(ret, "FFStream::avcodec_send_packet failed.\nseek:%s\n",
826 ffmpeg->fmt_ctx->url);
832 printf("** seek fail %jd, %jd\n", pos, tstmp);
833 seeked = need_packet = 0;
837 //printf("seeked pos = %ld, %ld\n", pos, tstmp);
838 seek_pos = curr_pos = pos;
842 FFAudioStream::FFAudioStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
843 : FFStream(ffmpeg, strm, fidx)
846 channel0 = channels = 0;
849 frame_sz = AUDIO_MIN_FRAME_SZ;
851 resample_context = 0;
852 swr_ichs = swr_ifmt = swr_irate = 0;
861 bfr = new float[bsz];
866 FFAudioStream::~FFAudioStream()
868 if( resample_context ) swr_free(&resample_context);
873 void FFAudioStream::init_swr(int ichs, int ifmt, int irate)
875 if( resample_context ) {
876 if( swr_ichs == ichs && swr_ifmt == ifmt && swr_irate == irate )
878 swr_free(&resample_context);
880 swr_ichs = ichs; swr_ifmt = ifmt; swr_irate = irate;
881 if( ichs == channels && ifmt == AV_SAMPLE_FMT_FLT && irate == sample_rate )
883 uint64_t ilayout = av_get_default_channel_layout(ichs);
884 if( !ilayout ) ilayout = ((uint64_t)1<<ichs) - 1;
885 uint64_t olayout = av_get_default_channel_layout(channels);
886 if( !olayout ) olayout = ((uint64_t)1<<channels) - 1;
887 resample_context = swr_alloc_set_opts(NULL,
888 olayout, AV_SAMPLE_FMT_FLT, sample_rate,
889 ilayout, (AVSampleFormat)ifmt, irate,
891 if( resample_context )
892 swr_init(resample_context);
895 int FFAudioStream::get_samples(float *&samples, uint8_t **data, int len)
897 samples = *(float **)data;
898 if( resample_context ) {
899 if( len > aud_bfr_sz ) {
905 aud_bfr = new float[aud_bfr_sz*channels];
907 int ret = swr_convert(resample_context,
908 (uint8_t**)&aud_bfr, aud_bfr_sz, (const uint8_t**)data, len);
910 ff_err(ret, "FFAudioStream::get_samples: swr_convert failed\n");
919 int FFAudioStream::load_history(uint8_t **data, int len)
922 len = get_samples(samples, data, len);
924 // biggest user bfr since seek + frame
925 realloc(mbsz + len + 1, channels);
931 int FFAudioStream::decode_frame(AVFrame *frame)
933 int first_frame = seeked; seeked = 0;
934 frame->best_effort_timestamp = AV_NOPTS_VALUE;
935 int ret = avcodec_receive_frame(avctx, frame);
937 if( first_frame ) return 0;
938 if( ret == AVERROR(EAGAIN) ) return 0;
939 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
940 ff_err(ret, "FFAudioStream::decode_frame: Could not read audio frame.\nfile:%s\n",
941 ffmpeg->fmt_ctx->url);
944 int64_t pkt_ts = frame->best_effort_timestamp;
945 if( pkt_ts != AV_NOPTS_VALUE ) {
946 double ts = ffmpeg->to_secs(pkt_ts - nudge, st->time_base);
947 double t = (double)curr_pos / sample_rate;
948 // some time_base clocks are very grainy, too grainy for audio (clicks, pops)
949 if( fabs(ts - t) > AUDIO_PTS_TOLERANCE )
950 curr_pos = ts * sample_rate + 0.5;
955 int FFAudioStream::encode_activate()
957 if( writing >= 0 ) return writing;
958 if( !avctx->codec ) return writing = 0;
959 frame_sz = avctx->codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE ?
960 10000 : avctx->frame_size;
961 return FFStream::encode_activate();
964 int64_t FFAudioStream::load_buffer(double ** const sp, int len)
966 reserve(len+1, st->codecpar->channels);
967 for( int ch=0; ch<nch; ++ch )
968 write(sp[ch], len, ch);
972 int FFAudioStream::in_history(int64_t pos)
974 if( pos > curr_pos ) return 0;
976 if( len > sz ) len = sz;
977 if( pos < curr_pos - len ) return 0;
982 int FFAudioStream::init_frame(AVFrame *frame)
984 frame->nb_samples = frame_sz;
985 frame->format = avctx->sample_fmt;
986 frame->channel_layout = avctx->channel_layout;
987 frame->sample_rate = avctx->sample_rate;
988 int ret = av_frame_get_buffer(frame, 0);
990 ff_err(ret, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
994 int FFAudioStream::load(int64_t pos, int len)
996 if( audio_seek(pos) < 0 ) return -1;
997 if( !frame && !(frame=av_frame_alloc()) ) {
998 fprintf(stderr, "FFAudioStream::load: av_frame_alloc failed\n");
1001 if( mbsz < len ) mbsz = len;
1002 int64_t end_pos = pos + len;
1003 int ret = 0, i = len / frame_sz + MAX_RETRY;
1004 while( ret>=0 && !flushed && curr_pos<end_pos && --i>=0 ) {
1005 ret = read_frame(frame);
1006 if( ret > 0 && frame->nb_samples > 0 ) {
1007 init_swr(frame->channels, frame->format, frame->sample_rate);
1008 load_history(&frame->extended_data[0], frame->nb_samples);
1009 curr_pos += frame->nb_samples;
1012 if( end_pos > curr_pos ) {
1013 zero(end_pos - curr_pos);
1016 len = curr_pos - pos;
1021 int FFAudioStream::audio_seek(int64_t pos)
1023 if( decode_activate() <= 0 ) return -1;
1024 if( !st->codecpar ) return -1;
1025 if( in_history(pos) ) return 0;
1026 if( pos == curr_pos ) return 0;
1027 reset_history(); mbsz = 0;
1028 // guarentee preload > 1sec samples
1029 if( (pos-=sample_rate) < 0 ) pos = 0;
1030 if( seek(pos, sample_rate) < 0 ) return -1;
1034 int FFAudioStream::encode(double **samples, int len)
1036 if( encode_activate() <= 0 ) return -1;
1039 int64_t count = samples ? load_buffer(samples, len) : used();
1040 int frame_sz1 = samples ? frame_sz-1 : 0;
1043 while( ret >= 0 && count > frame_sz1 ) {
1044 frm = new FFrame(this);
1045 if( (ret=frm->initted()) < 0 ) break;
1046 AVFrame *frame = *frm;
1047 len = count >= frame_sz ? frame_sz : count;
1048 float *bfrp = get_outp(len);
1049 ret = swr_convert(resample_context,
1050 (uint8_t **)frame->extended_data, len,
1051 (const uint8_t **)&bfrp, len);
1053 ff_err(ret, "FFAudioStream::encode: swr_convert failed\n");
1056 frame->nb_samples = len;
1057 frm->queue(curr_pos);
1064 return ret >= 0 ? 0 : 1;
1067 int FFAudioStream::drain()
1072 int FFAudioStream::encode_frame(AVFrame *frame)
1074 return FFStream::encode_frame(frame);
1077 int FFAudioStream::write_packet(FFPacket &pkt)
1079 return FFStream::write_packet(pkt);
1082 void FFAudioStream::load_markers()
1084 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1085 if( !index_state || idx >= index_state->audio_markers.size() ) return;
1086 if( index_state->marker_status == MARKERS_NOTTESTED ) return;
1087 FFStream::load_markers(*index_state->audio_markers[idx], sample_rate);
1090 IndexMarks *FFAudioStream::get_markers()
1092 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1093 if( !index_state || idx >= index_state->audio_markers.size() ) return 0;
1094 return index_state->audio_markers[idx];
1097 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
1098 : FFStream(ffmpeg, strm, fidx),
1099 FFVideoConvert(ffmpeg->ff_prefs())
1108 top_field_first = 0;
1114 FFVideoStream::~FFVideoStream()
1116 if( fconvert_ctx ) sws_freeContext(fconvert_ctx);
1119 AVHWDeviceType FFVideoStream::decode_hw_activate()
1121 AVHWDeviceType type = AV_HWDEVICE_TYPE_NONE;
1122 const char *hw_dev = ffmpeg->opt_hw_dev;
1123 if( !hw_dev ) hw_dev = getenv("CIN_HW_DEV");
1124 if( !hw_dev ) hw_dev = ffmpeg->ff_hw_dev();
1125 if( hw_dev && *hw_dev &&
1126 strcmp("none", hw_dev) && strcmp(_("none"), hw_dev) ) {
1127 type = av_hwdevice_find_type_by_name(hw_dev);
1128 if( type == AV_HWDEVICE_TYPE_NONE ) {
1129 fprintf(stderr, "Device type %s is not supported.\n", hw_dev);
1130 fprintf(stderr, "Available device types:");
1131 while( (type = av_hwdevice_iterate_types(type)) != AV_HWDEVICE_TYPE_NONE )
1132 fprintf(stderr, " %s", av_hwdevice_get_type_name(type));
1133 fprintf(stderr, "\n");
1138 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
1139 int FFVideoStream::decode_hw_format(const AVCodec *decoder, AVHWDeviceType type)
1141 int FFVideoStream::decode_hw_format(AVCodec *decoder, AVHWDeviceType type)
1145 hw_pix_fmt = AV_PIX_FMT_NONE;
1146 for( int i=0; ; ++i ) {
1147 const AVCodecHWConfig *config = avcodec_get_hw_config(decoder, i);
1149 fprintf(stderr, "Decoder %s does not support device type %s.\n",
1150 decoder->name, av_hwdevice_get_type_name(type));
1154 if( (config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX) != 0 &&
1155 config->device_type == type ) {
1156 hw_pix_fmt = config->pix_fmt;
1160 if( hw_pix_fmt >= 0 ) {
1161 hw_pixfmt = hw_pix_fmt;
1162 avctx->get_format = get_hw_format;
1163 const char *drm_node = getenv("CIN_DRM_DEC");
1164 if(drm_node && type==AV_HWDEVICE_TYPE_VAAPI) {
1165 ret = av_hwdevice_ctx_create(&hw_device_ctx, type, drm_node, 0, 0);
1168 ret = av_hwdevice_ctx_create(&hw_device_ctx, type, 0, 0, 0);
1172 avctx->hw_device_ctx = av_buffer_ref(hw_device_ctx);
1176 ff_err(ret, "Failed HW device create.\ndev:%s\n",
1177 av_hwdevice_get_type_name(type));
1184 AVHWDeviceType FFVideoStream::encode_hw_activate(const char *hw_dev)
1186 const char *drm_node_enc = getenv("CIN_DRM_ENC");
1187 AVBufferRef *hw_device_ctx = 0;
1188 AVBufferRef *hw_frames_ref = 0;
1189 AVHWDeviceType type = AV_HWDEVICE_TYPE_NONE;
1190 if( strcmp(_("none"), hw_dev) ) {
1191 type = av_hwdevice_find_type_by_name(hw_dev);
1192 if( type != AV_HWDEVICE_TYPE_VAAPI ) {
1193 fprintf(stderr, "currently, only vaapi hw encode is supported\n");
1194 type = AV_HWDEVICE_TYPE_NONE;
1197 if( type != AV_HWDEVICE_TYPE_NONE ) {
1200 ret = av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_VAAPI, drm_node_enc, 0, 0);
1202 ret = av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_VAAPI, 0, 0, 0);
1205 ff_err(ret, "Failed to create a HW device.\n");
1206 type = AV_HWDEVICE_TYPE_NONE;
1209 if( type != AV_HWDEVICE_TYPE_NONE ) {
1210 hw_frames_ref = av_hwframe_ctx_alloc(hw_device_ctx);
1211 if( !hw_frames_ref ) {
1212 fprintf(stderr, "Failed to create HW frame context.\n");
1213 type = AV_HWDEVICE_TYPE_NONE;
1216 if( type != AV_HWDEVICE_TYPE_NONE ) {
1217 AVHWFramesContext *frames_ctx = (AVHWFramesContext *)(hw_frames_ref->data);
1218 frames_ctx->format = AV_PIX_FMT_VAAPI;
1219 frames_ctx->sw_format = AV_PIX_FMT_NV12;
1220 frames_ctx->width = width;
1221 frames_ctx->height = height;
1222 frames_ctx->initial_pool_size = 0; // 200;
1223 int ret = av_hwframe_ctx_init(hw_frames_ref);
1225 avctx->hw_frames_ctx = av_buffer_ref(hw_frames_ref);
1226 if( !avctx->hw_frames_ctx ) ret = AVERROR(ENOMEM);
1229 ff_err(ret, "Failed to initialize HW frame context.\n");
1230 type = AV_HWDEVICE_TYPE_NONE;
1232 av_buffer_unref(&hw_frames_ref);
1237 int FFVideoStream::encode_hw_write(FFrame *picture)
1240 AVFrame *hw_frm = 0;
1241 switch( avctx->pix_fmt ) {
1242 case AV_PIX_FMT_VAAPI:
1243 hw_frm = av_frame_alloc();
1244 if( !hw_frm ) { ret = AVERROR(ENOMEM); break; }
1245 ret = av_hwframe_get_buffer(avctx->hw_frames_ctx, hw_frm, 0);
1246 if( ret < 0 ) break;
1247 ret = av_hwframe_transfer_data(hw_frm, *picture, 0);
1248 if( ret < 0 ) break;
1249 picture->set_hw_frame(hw_frm);
1254 av_frame_free(&hw_frm);
1255 ff_err(ret, "Error while transferring frame data to GPU.\n");
1259 int FFVideoStream::decode_frame(AVFrame *frame)
1261 int first_frame = seeked; seeked = 0;
1262 int ret = avcodec_receive_frame(avctx, frame);
1264 if( first_frame ) return 0;
1265 if( ret == AVERROR(EAGAIN) ) return 0;
1266 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
1267 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame.\nfile:%s\n,",
1268 ffmpeg->fmt_ctx->url);
1271 int64_t pkt_ts = frame->best_effort_timestamp;
1272 if( pkt_ts != AV_NOPTS_VALUE )
1273 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * frame_rate + 0.5;
1277 int FFVideoStream::probe(int64_t pos)
1279 int ret = video_seek(pos);
1280 if( ret < 0 ) return -1;
1281 if( !frame && !(frame=av_frame_alloc()) ) {
1282 fprintf(stderr, "FFVideoStream::probe: av_frame_alloc failed\n");
1286 if (ffmpeg->interlace_from_codec) return 1;
1288 ret = read_frame(frame);
1290 //printf("codec interlace: %i \n",frame->interlaced_frame);
1291 //printf("codec tff: %i \n",frame->top_field_first);
1293 if (!frame->interlaced_frame)
1294 ffmpeg->interlace_from_codec = AV_FIELD_PROGRESSIVE;
1295 if ((frame->interlaced_frame) && (frame->top_field_first))
1296 ffmpeg->interlace_from_codec = AV_FIELD_TT;
1297 if ((frame->interlaced_frame) && (!frame->top_field_first))
1298 ffmpeg->interlace_from_codec = AV_FIELD_BB;
1299 //printf("Interlace mode from codec: %i\n", ffmpeg->interlace_from_codec);
1303 if( frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0 )
1306 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
1307 av_frame_free(&frame);
1311 int FFVideoStream::load(VFrame *vframe, int64_t pos)
1313 int ret = video_seek(pos);
1314 if( ret < 0 ) return -1;
1315 if( !frame && !(frame=av_frame_alloc()) ) {
1316 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
1321 int i = MAX_RETRY + pos - curr_pos;
1322 int64_t cache_start = 0;
1323 while( ret>=0 && !flushed && curr_pos<=pos && --i>=0 ) {
1324 ret = read_frame(frame);
1326 if( frame->key_frame && seeking < 0 ) {
1327 int use_cache = ffmpeg->get_use_cache();
1328 if( use_cache < 0 ) {
1329 // for reverse read, reload file frame_cache from keyframe to pos
1330 ffmpeg->purge_cache();
1331 int count = preferences->cache_size /
1332 vframe->get_data_size() / 2; // try to burn only 1/2 of cache
1333 cache_start = pos - count + 1;
1339 if( seeking > 0 && curr_pos >= cache_start && curr_pos < pos ) {
1340 int vw =vframe->get_w(), vh = vframe->get_h();
1341 int vcolor_model = vframe->get_color_model();
1342 // do not use shm here, puts too much pressure on 32bit systems
1343 VFrame *cache_frame = new VFrame(vw, vh, vcolor_model, 0);
1344 ret = convert_cmodel(cache_frame, frame);
1346 ffmpeg->put_cache_frame(cache_frame, curr_pos);
1352 if( frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0 )
1355 ret = convert_cmodel(vframe, frame);
1357 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
1361 int FFVideoStream::video_seek(int64_t pos)
1363 if( decode_activate() <= 0 ) return -1;
1364 if( !st->codecpar ) return -1;
1365 if( pos == curr_pos-1 && !seeked ) return 0;
1366 // if close enough, just read up to current
1367 int gop = avctx->gop_size;
1368 if( gop < 4 ) gop = 4;
1369 if( gop > 64 ) gop = 64;
1370 int read_limit = curr_pos + 3*gop;
1371 if( pos >= curr_pos && pos <= read_limit ) return 0;
1372 // guarentee preload more than 2*gop frames
1373 if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
1377 int FFVideoStream::init_frame(AVFrame *picture)
1379 switch( avctx->pix_fmt ) {
1380 case AV_PIX_FMT_VAAPI:
1381 picture->format = AV_PIX_FMT_NV12;
1384 picture->format = avctx->pix_fmt;
1387 picture->width = avctx->width;
1388 picture->height = avctx->height;
1389 int ret = av_frame_get_buffer(picture, 32);
1393 int FFVideoStream::convert_hw_frame(AVFrame *ifrm, AVFrame *ofrm)
1395 AVPixelFormat ifmt = (AVPixelFormat)ifrm->format;
1396 AVPixelFormat ofmt = (AVPixelFormat)st->codecpar->format;
1397 ofrm->width = ifrm->width;
1398 ofrm->height = ifrm->height;
1399 ofrm->format = ofmt;
1400 int ret = av_frame_get_buffer(ofrm, 32);
1402 ff_err(ret, "FFVideoStream::convert_hw_frame:"
1403 " av_frame_get_buffer failed\n");
1406 fconvert_ctx = sws_getCachedContext(fconvert_ctx,
1407 ifrm->width, ifrm->height, ifmt,
1408 ofrm->width, ofrm->height, ofmt,
1409 SWS_POINT, NULL, NULL, NULL);
1410 if( !fconvert_ctx ) {
1411 ff_err(AVERROR(EINVAL), "FFVideoStream::convert_hw_frame:"
1412 " sws_getCachedContext() failed\n");
1415 int codec_range = st->codecpar->color_range;
1416 int codec_space = st->codecpar->color_space;
1417 const int *codec_table = sws_getCoefficients(codec_space);
1418 int *inv_table, *table, src_range, dst_range;
1419 int brightness, contrast, saturation;
1420 if( !sws_getColorspaceDetails(fconvert_ctx,
1421 &inv_table, &src_range, &table, &dst_range,
1422 &brightness, &contrast, &saturation) ) {
1423 if( src_range != codec_range || dst_range != codec_range ||
1424 inv_table != codec_table || table != codec_table )
1425 sws_setColorspaceDetails(fconvert_ctx,
1426 codec_table, codec_range, codec_table, codec_range,
1427 brightness, contrast, saturation);
1429 ret = sws_scale(fconvert_ctx,
1430 ifrm->data, ifrm->linesize, 0, ifrm->height,
1431 ofrm->data, ofrm->linesize);
1433 ff_err(ret, "FFVideoStream::convert_hw_frame:"
1434 " sws_scale() failed\nfile: %s\n",
1435 ffmpeg->fmt_ctx->url);
1441 int FFVideoStream::load_filter(AVFrame *frame)
1443 AVPixelFormat pix_fmt = (AVPixelFormat)frame->format;
1444 if( pix_fmt == hw_pixfmt ) {
1445 AVFrame *hw_frame = this->frame;
1446 av_frame_unref(hw_frame);
1447 int ret = av_hwframe_transfer_data(hw_frame, frame, 0);
1449 eprintf(_("Error retrieving data from GPU to CPU\nfile: %s\n"),
1450 ffmpeg->fmt_ctx->url);
1453 av_frame_unref(frame);
1454 ret = convert_hw_frame(hw_frame, frame);
1456 eprintf(_("Error converting data from GPU to CPU\nfile: %s\n"),
1457 ffmpeg->fmt_ctx->url);
1460 av_frame_unref(hw_frame);
1462 return FFStream::load_filter(frame);
1465 int FFVideoStream::encode(VFrame *vframe)
1467 if( encode_activate() <= 0 ) return -1;
1469 FFrame *picture = new FFrame(this);
1470 int ret = picture->initted();
1472 AVFrame *frame = *picture;
1473 frame->pts = curr_pos;
1474 ret = convert_pixfmt(vframe, frame);
1476 if( ret >= 0 && avctx->hw_frames_ctx )
1477 encode_hw_write(picture);
1479 picture->queue(curr_pos);
1483 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
1486 return ret >= 0 ? 0 : 1;
1489 int FFVideoStream::drain()
1495 int FFVideoStream::encode_frame(AVFrame *frame)
1498 frame->interlaced_frame = interlaced;
1499 frame->top_field_first = top_field_first;
1501 if( frame && frame->format == AV_PIX_FMT_VAAPI ) { // ugly
1502 int ret = avcodec_send_frame(avctx, frame);
1503 for( int retry=MAX_RETRY; !ret && --retry>=0; ) {
1504 FFPacket pkt; av_init_packet(pkt);
1505 pkt->data = NULL; pkt->size = 0;
1506 if( (ret=avcodec_receive_packet(avctx, pkt)) < 0 ) {
1507 if( ret == AVERROR(EAGAIN) ) ret = 0; // weird
1510 ret = write_packet(pkt);
1511 pkt->stream_index = 0;
1512 av_packet_unref(pkt);
1515 ff_err(ret, "FFStream::encode_frame: vaapi encode failed.\nfile: %s\n",
1516 ffmpeg->fmt_ctx->url);
1521 return FFStream::encode_frame(frame);
1524 int FFVideoStream::write_packet(FFPacket &pkt)
1526 if( !(ffmpeg->fmt_ctx->oformat->flags & AVFMT_VARIABLE_FPS) )
1528 return FFStream::write_packet(pkt);
1531 AVPixelFormat FFVideoConvert::color_model_to_pix_fmt(int color_model)
1533 switch( color_model ) {
1534 case BC_YUV422: return AV_PIX_FMT_YUYV422;
1535 case BC_RGB888: return AV_PIX_FMT_RGB24;
1536 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
1537 case BC_BGR8888: return AV_PIX_FMT_BGR0;
1538 case BC_BGR888: return AV_PIX_FMT_BGR24;
1539 case BC_ARGB8888: return AV_PIX_FMT_ARGB;
1540 case BC_ABGR8888: return AV_PIX_FMT_ABGR;
1541 case BC_RGB8: return AV_PIX_FMT_RGB8;
1542 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
1543 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
1544 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
1545 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
1546 case BC_RGB565: return AV_PIX_FMT_RGB565;
1547 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
1548 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
1549 case BC_AYUV16161616: return AV_PIX_FMT_AYUV64LE;
1550 case BC_GBRP: return AV_PIX_FMT_GBRP;
1554 return AV_PIX_FMT_NB;
1557 int FFVideoConvert::pix_fmt_to_color_model(AVPixelFormat pix_fmt)
1560 case AV_PIX_FMT_YUYV422: return BC_YUV422;
1561 case AV_PIX_FMT_RGB24: return BC_RGB888;
1562 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
1563 case AV_PIX_FMT_BGR0: return BC_BGR8888;
1564 case AV_PIX_FMT_BGR24: return BC_BGR888;
1565 case AV_PIX_FMT_ARGB: return BC_ARGB8888;
1566 case AV_PIX_FMT_ABGR: return BC_ABGR8888;
1567 case AV_PIX_FMT_RGB8: return BC_RGB8;
1568 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
1569 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
1570 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
1571 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
1572 case AV_PIX_FMT_RGB565: return BC_RGB565;
1573 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
1574 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
1575 case AV_PIX_FMT_AYUV64LE: return BC_AYUV16161616;
1576 case AV_PIX_FMT_GBRP: return BC_GBRP;
1583 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip)
1585 AVFrame *ipic = av_frame_alloc();
1586 int ret = convert_picture_vframe(frame, ip, ipic);
1587 av_frame_free(&ipic);
1591 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip, AVFrame *ipic)
1592 { // picture = vframe
1593 int cmodel = frame->get_color_model();
1594 AVPixelFormat ofmt = color_model_to_pix_fmt(cmodel);
1595 if( ofmt == AV_PIX_FMT_NB ) return -1;
1596 int size = av_image_fill_arrays(ipic->data, ipic->linesize,
1597 frame->get_data(), ofmt, frame->get_w(), frame->get_h(), 1);
1598 if( size < 0 ) return -1;
1600 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1601 int ysz = bpp * frame->get_w(), usz = ysz;
1611 // override av_image_fill_arrays() for planar types
1612 ipic->data[0] = frame->get_y(); ipic->linesize[0] = ysz;
1613 ipic->data[1] = frame->get_u(); ipic->linesize[1] = usz;
1614 ipic->data[2] = frame->get_v(); ipic->linesize[2] = usz;
1617 ipic->data[0] = frame->get_data();
1618 ipic->linesize[0] = frame->get_bytes_per_line();
1622 AVPixelFormat pix_fmt = (AVPixelFormat)ip->format;
1623 FFVideoStream *vid =(FFVideoStream *)this;
1624 if( pix_fmt == vid->hw_pixfmt ) {
1626 if( !sw_frame && !(sw_frame=av_frame_alloc()) )
1627 ret = AVERROR(ENOMEM);
1629 ret = av_hwframe_transfer_data(sw_frame, ip, 0);
1631 pix_fmt = (AVPixelFormat)ip->format;
1634 eprintf(_("Error retrieving data from GPU to CPU\nfile: %s\n"),
1635 vid->ffmpeg->fmt_ctx->url);
1639 convert_ctx = sws_getCachedContext(convert_ctx, ip->width, ip->height, pix_fmt,
1640 frame->get_w(), frame->get_h(), ofmt, SWS_POINT, NULL, NULL, NULL);
1641 if( !convert_ctx ) {
1642 fprintf(stderr, "FFVideoConvert::convert_picture_frame:"
1643 " sws_getCachedContext() failed\n");
1647 int color_range = 0;
1648 switch( preferences->yuv_color_range ) {
1649 case BC_COLORS_JPEG: color_range = 1; break;
1650 case BC_COLORS_MPEG: color_range = 0; break;
1652 int color_space = SWS_CS_ITU601;
1653 switch( preferences->yuv_color_space ) {
1654 case BC_COLORS_BT601_PAL: color_space = SWS_CS_ITU601; break;
1655 case BC_COLORS_BT601_NTSC: color_space = SWS_CS_SMPTE170M; break;
1656 case BC_COLORS_BT709: color_space = SWS_CS_ITU709; break;
1657 case BC_COLORS_BT2020_NCL:
1658 case BC_COLORS_BT2020_CL: color_space = SWS_CS_BT2020; break;
1660 const int *color_table = sws_getCoefficients(color_space);
1662 int *inv_table, *table, src_range, dst_range;
1663 int brightness, contrast, saturation;
1664 if( !sws_getColorspaceDetails(convert_ctx,
1665 &inv_table, &src_range, &table, &dst_range,
1666 &brightness, &contrast, &saturation) ) {
1667 if( src_range != color_range || dst_range != color_range ||
1668 inv_table != color_table || table != color_table )
1669 sws_setColorspaceDetails(convert_ctx,
1670 color_table, color_range, color_table, color_range,
1671 brightness, contrast, saturation);
1674 int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ip->height,
1675 ipic->data, ipic->linesize);
1677 ff_err(ret, "FFVideoConvert::convert_picture_frame: sws_scale() failed\nfile: %s\n",
1678 vid->ffmpeg->fmt_ctx->url);
1684 int FFVideoConvert::convert_cmodel(VFrame *frame, AVFrame *ip)
1686 // try direct transfer
1687 if( !convert_picture_vframe(frame, ip) ) return 1;
1688 // use indirect transfer
1689 AVPixelFormat ifmt = (AVPixelFormat)ip->format;
1690 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
1692 for( int i = 0; i <desc->nb_components; ++i ) {
1693 int bits = desc->comp[i].depth;
1694 if( bits > max_bits ) max_bits = bits;
1696 int imodel = pix_fmt_to_color_model(ifmt);
1697 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1698 int cmodel = frame->get_color_model();
1699 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1700 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1701 imodel = cmodel_is_yuv ?
1702 (BC_CModels::has_alpha(cmodel) ?
1704 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1705 (BC_CModels::has_alpha(cmodel) ?
1706 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1707 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1709 VFrame vframe(ip->width, ip->height, imodel);
1710 if( convert_picture_vframe(&vframe, ip) ) return -1;
1711 frame->transfer_from(&vframe);
1715 int FFVideoConvert::transfer_cmodel(VFrame *frame, AVFrame *ifp)
1717 int ret = convert_cmodel(frame, ifp);
1719 const AVDictionary *src = ifp->metadata;
1720 AVDictionaryEntry *t = NULL;
1721 BC_Hash *hp = frame->get_params();
1723 while( (t=av_dict_get(src, "", t, AV_DICT_IGNORE_SUFFIX)) )
1724 hp->update(t->key, t->value);
1729 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op)
1731 AVFrame *opic = av_frame_alloc();
1732 int ret = convert_vframe_picture(frame, op, opic);
1733 av_frame_free(&opic);
1737 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op, AVFrame *opic)
1738 { // vframe = picture
1739 int cmodel = frame->get_color_model();
1740 AVPixelFormat ifmt = color_model_to_pix_fmt(cmodel);
1741 if( ifmt == AV_PIX_FMT_NB ) return -1;
1742 int size = av_image_fill_arrays(opic->data, opic->linesize,
1743 frame->get_data(), ifmt, frame->get_w(), frame->get_h(), 1);
1744 if( size < 0 ) return -1;
1746 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1747 int ysz = bpp * frame->get_w(), usz = ysz;
1757 // override av_image_fill_arrays() for planar types
1758 opic->data[0] = frame->get_y(); opic->linesize[0] = ysz;
1759 opic->data[1] = frame->get_u(); opic->linesize[1] = usz;
1760 opic->data[2] = frame->get_v(); opic->linesize[2] = usz;
1763 opic->data[0] = frame->get_data();
1764 opic->linesize[0] = frame->get_bytes_per_line();
1768 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1769 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(),
1770 ifmt, op->width, op->height, ofmt, SWS_POINT, NULL, NULL, NULL);
1771 if( !convert_ctx ) {
1772 fprintf(stderr, "FFVideoConvert::convert_frame_picture:"
1773 " sws_getCachedContext() failed\n");
1778 int color_range = 0;
1779 switch( preferences->yuv_color_range ) {
1780 case BC_COLORS_JPEG: color_range = 1; break;
1781 case BC_COLORS_MPEG: color_range = 0; break;
1783 int color_space = SWS_CS_ITU601;
1784 switch( preferences->yuv_color_space ) {
1785 case BC_COLORS_BT601_PAL: color_space = SWS_CS_ITU601; break;
1786 case BC_COLORS_BT601_NTSC: color_space = SWS_CS_SMPTE170M; break;
1787 case BC_COLORS_BT709: color_space = SWS_CS_ITU709; break;
1788 case BC_COLORS_BT2020_NCL:
1789 case BC_COLORS_BT2020_CL: color_space = SWS_CS_BT2020; break;
1791 const int *color_table = sws_getCoefficients(color_space);
1793 int *inv_table, *table, src_range, dst_range;
1794 int brightness, contrast, saturation;
1795 if( !sws_getColorspaceDetails(convert_ctx,
1796 &inv_table, &src_range, &table, &dst_range,
1797 &brightness, &contrast, &saturation) ) {
1798 if( dst_range != color_range || table != color_table )
1799 sws_setColorspaceDetails(convert_ctx,
1800 inv_table, src_range, color_table, color_range,
1801 brightness, contrast, saturation);
1804 int ret = sws_scale(convert_ctx, opic->data, opic->linesize, 0, frame->get_h(),
1805 op->data, op->linesize);
1807 ff_err(ret, "FFVideoConvert::convert_frame_picture: sws_scale() failed\n");
1813 int FFVideoConvert::convert_pixfmt(VFrame *frame, AVFrame *op)
1815 // try direct transfer
1816 if( !convert_vframe_picture(frame, op) ) return 1;
1817 // use indirect transfer
1818 int cmodel = frame->get_color_model();
1819 int max_bits = BC_CModels::calculate_pixelsize(cmodel) * 8;
1820 max_bits /= BC_CModels::components(cmodel);
1821 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1822 int imodel = pix_fmt_to_color_model(ofmt);
1823 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1824 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1825 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1826 imodel = cmodel_is_yuv ?
1827 (BC_CModels::has_alpha(cmodel) ?
1829 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1830 (BC_CModels::has_alpha(cmodel) ?
1831 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1832 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1834 VFrame vframe(frame->get_w(), frame->get_h(), imodel);
1835 vframe.transfer_from(frame);
1836 if( !convert_vframe_picture(&vframe, op) ) return 1;
1840 int FFVideoConvert::transfer_pixfmt(VFrame *frame, AVFrame *ofp)
1842 int ret = convert_pixfmt(frame, ofp);
1844 BC_Hash *hp = frame->get_params();
1845 AVDictionary **dict = &ofp->metadata;
1846 //av_dict_free(dict);
1847 for( int i=0; i<hp->size(); ++i ) {
1848 char *key = hp->get_key(i), *val = hp->get_value(i);
1849 av_dict_set(dict, key, val, 0);
1855 void FFVideoStream::load_markers()
1857 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1858 if( !index_state || idx >= index_state->video_markers.size() ) return;
1859 FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
1862 IndexMarks *FFVideoStream::get_markers()
1864 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1865 if( !index_state || idx >= index_state->video_markers.size() ) return 0;
1866 return !index_state ? 0 : index_state->video_markers[idx];
1870 FFMPEG::FFMPEG(FileBase *file_base)
1873 this->file_base = file_base;
1874 memset(file_format,0,sizeof(file_format));
1875 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
1876 flow_lock = new Condition(1,"FFStream::flow_lock",0);
1879 decoding = encoding = 0;
1880 has_audio = has_video = 0;
1881 interlace_from_codec = 0;
1884 opt_video_filter = 0;
1885 opt_audio_filter = 0;
1887 opt_video_decoder = 0;
1888 opt_audio_decoder = 0;
1890 char option_path[BCTEXTLEN];
1891 set_option_path(option_path, "%s", "ffmpeg.opts");
1892 read_options(option_path, opts);
1897 ff_lock("FFMPEG::~FFMPEG()");
1899 ffaudio.remove_all_objects();
1900 ffvideo.remove_all_objects();
1901 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1905 av_dict_free(&opts);
1906 delete [] opt_video_filter;
1907 delete [] opt_audio_filter;
1908 delete [] opt_hw_dev;
1911 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
1912 int FFMPEG::check_sample_rate(const AVCodec *codec, int sample_rate)
1914 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1917 const int *p = codec->supported_samplerates;
1918 if( !p ) return sample_rate;
1920 if( *p == sample_rate ) return *p;
1926 // check_frame_rate and std_frame_rate needed for 23.976
1927 // and 59.94 fps mpeg2
1928 static inline AVRational std_frame_rate(int i)
1930 static const int m1 = 1001*12, m2 = 1000*12;
1931 static const int freqs[] = {
1932 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1933 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 90*m2,
1934 100*m2, 120*m2, 144*m2, 72*m2, 0,
1936 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1937 return (AVRational) { freq, 1001*12 };
1940 AVRational FFMPEG::check_frame_rate(const AVRational *p, double frame_rate)
1942 AVRational rate, best_rate = (AVRational) { 0, 0 };
1943 double max_err = 1.; int i = 0;
1944 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1945 double framerate = (double) rate.num / rate.den;
1946 double err = fabs(frame_rate/framerate - 1.);
1947 if( err >= max_err ) continue;
1951 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1954 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1957 double display_aspect = asset->width / (double)asset->height;
1958 double sample_aspect = display_aspect / asset->aspect_ratio;
1959 int width = 1000000, height = width * sample_aspect + 0.5;
1961 MWindow::create_aspect_ratio(w, h, width, height);
1962 return (AVRational){(int)w, (int)h};
1965 return (AVRational){1, 1};
1969 AVRational FFMPEG::to_time_base(int sample_rate)
1971 return (AVRational){1, sample_rate};
1974 int FFMPEG::get_fmt_score(AVSampleFormat dst_fmt, AVSampleFormat src_fmt)
1977 int dst_planar = av_sample_fmt_is_planar(dst_fmt);
1978 int src_planar = av_sample_fmt_is_planar(src_fmt);
1979 if( dst_planar != src_planar ) ++score;
1980 int dst_bytes = av_get_bytes_per_sample(dst_fmt);
1981 int src_bytes = av_get_bytes_per_sample(src_fmt);
1982 score += (src_bytes > dst_bytes ? 100 : -10) * (src_bytes - dst_bytes);
1983 int src_packed = av_get_packed_sample_fmt(src_fmt);
1984 int dst_packed = av_get_packed_sample_fmt(dst_fmt);
1985 if( dst_packed == AV_SAMPLE_FMT_S32 && src_packed == AV_SAMPLE_FMT_FLT ) score += 20;
1986 if( dst_packed == AV_SAMPLE_FMT_FLT && src_packed == AV_SAMPLE_FMT_S32 ) score += 2;
1990 AVSampleFormat FFMPEG::find_best_sample_fmt_of_list(
1991 const AVSampleFormat *sample_fmts, AVSampleFormat src_fmt)
1993 AVSampleFormat best = AV_SAMPLE_FMT_NONE;
1994 int best_score = get_fmt_score(best, src_fmt);
1995 for( int i=0; sample_fmts[i] >= 0; ++i ) {
1996 AVSampleFormat sample_fmt = sample_fmts[i];
1997 int score = get_fmt_score(sample_fmt, src_fmt);
1998 if( score >= best_score ) continue;
1999 best = sample_fmt; best_score = score;
2005 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
2007 char *ep = path + BCTEXTLEN-1;
2008 strncpy(path, File::get_cindat_path(), ep-path);
2009 strncat(path, "/ffmpeg/", ep-path);
2010 path += strlen(path);
2013 path += vsnprintf(path, ep-path, fmt, ap);
2018 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
2023 set_option_path(path, "%s/%s", type, spec);
2026 int FFMPEG::get_format(char *format, const char *path, const char *spec)
2028 char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
2029 get_option_path(option_path, path, spec);
2030 FILE *fp = fopen(option_path,"r");
2033 if( !fgets(line, sizeof(line), fp) ) ret = 1;
2035 line[sizeof(line)-1] = 0;
2036 ret = scan_option_line(line, format, codec);
2042 int FFMPEG::get_codec(char *codec, const char *path, const char *spec)
2044 char option_path[BCTEXTLEN], line[BCTEXTLEN], format[BCTEXTLEN];
2045 get_option_path(option_path, path, spec);
2046 FILE *fp = fopen(option_path,"r");
2049 if( !fgets(line, sizeof(line), fp) ) ret = 1;
2052 line[sizeof(line)-1] = 0;
2053 ret = scan_option_line(line, format, codec);
2056 char *vp = codec, *ep = vp+BCTEXTLEN-1;
2057 while( vp < ep && *vp && *vp != '|' ) ++vp;
2058 if( *vp == '|' ) --vp;
2059 while( vp > codec && (*vp==' ' || *vp=='\t') ) *vp-- = 0;
2064 int FFMPEG::get_file_format()
2066 char audio_muxer[BCSTRLEN], video_muxer[BCSTRLEN];
2067 char audio_format[BCSTRLEN], video_format[BCSTRLEN];
2068 audio_muxer[0] = audio_format[0] = 0;
2069 video_muxer[0] = video_format[0] = 0;
2070 Asset *asset = file_base->asset;
2071 int ret = asset ? 0 : 1;
2072 if( !ret && asset->audio_data ) {
2073 if( !(ret=get_format(audio_format, "audio", asset->acodec)) ) {
2074 if( get_format(audio_muxer, "format", audio_format) ) {
2075 strcpy(audio_muxer, audio_format);
2076 audio_format[0] = 0;
2080 if( !ret && asset->video_data ) {
2081 if( !(ret=get_format(video_format, "video", asset->vcodec)) ) {
2082 if( get_format(video_muxer, "format", video_format) ) {
2083 strcpy(video_muxer, video_format);
2084 video_format[0] = 0;
2088 if( !ret && !audio_muxer[0] && !video_muxer[0] )
2090 if( !ret && audio_muxer[0] && video_muxer[0] &&
2091 strcmp(audio_muxer, video_muxer) ) ret = -1;
2092 if( !ret && audio_format[0] && video_format[0] &&
2093 strcmp(audio_format, video_format) ) ret = -1;
2095 strcpy(file_format, !audio_format[0] && !video_format[0] ?
2096 (audio_muxer[0] ? audio_muxer : video_muxer) :
2097 (audio_format[0] ? audio_format : video_format));
2101 int FFMPEG::scan_option_line(const char *cp, char *tag, char *val)
2103 while( *cp == ' ' || *cp == '\t' ) ++cp;
2104 const char *bp = cp;
2105 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' && *cp != '\n' ) ++cp;
2107 if( !len || len > BCSTRLEN-1 ) return 1;
2108 while( bp < cp ) *tag++ = *bp++;
2110 while( *cp == ' ' || *cp == '\t' ) ++cp;
2111 if( *cp == '=' ) ++cp;
2112 while( *cp == ' ' || *cp == '\t' ) ++cp;
2114 while( *cp && *cp != '\n' ) ++cp;
2116 if( len > BCTEXTLEN-1 ) return 1;
2117 while( bp < cp ) *val++ = *bp++;
2122 int FFMPEG::can_render(const char *fformat, const char *type)
2125 char option_path[BCTEXTLEN];
2126 FFMPEG::set_option_path(option_path, type);
2127 fs.update(option_path);
2128 int total_files = fs.total_files();
2129 for( int i=0; i<total_files; ++i ) {
2130 const char *name = fs.get_entry(i)->get_name();
2131 const char *ext = strrchr(name,'.');
2132 if( !ext ) continue;
2133 if( !strcmp(fformat, ++ext) ) return 1;
2138 int FFMPEG::get_ff_option(const char *nm, const char *options, char *value)
2140 for( const char *cp=options; *cp!=0; ) {
2141 char line[BCTEXTLEN], *bp = line, *ep = bp+sizeof(line)-1;
2142 while( bp < ep && *cp && *cp!='\n' ) *bp++ = *cp++;
2145 if( !line[0] || line[0] == '#' || line[0] == ';' ) continue;
2146 char key[BCSTRLEN], val[BCTEXTLEN];
2147 if( FFMPEG::scan_option_line(line, key, val) ) continue;
2148 if( !strcmp(key, nm) ) {
2149 strncpy(value, val, BCSTRLEN);
2156 void FFMPEG::scan_audio_options(Asset *asset, EDL *edl)
2158 char cin_sample_fmt[BCSTRLEN];
2159 int cin_fmt = AV_SAMPLE_FMT_NONE;
2160 const char *options = asset->ff_audio_options;
2161 if( !get_ff_option("cin_sample_fmt", options, cin_sample_fmt) )
2162 cin_fmt = (int)av_get_sample_fmt(cin_sample_fmt);
2164 char audio_codec[BCSTRLEN]; audio_codec[0] = 0;
2165 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,18,100)
2166 const AVCodec *av_codec = !FFMPEG::get_codec(audio_codec, "audio", asset->acodec) ?
2168 AVCodec *av_codec = !FFMPEG::get_codec(audio_codec, "audio", asset->acodec) ?
2170 avcodec_find_encoder_by_name(audio_codec) : 0;
2171 if( av_codec && av_codec->sample_fmts )
2172 cin_fmt = find_best_sample_fmt_of_list(av_codec->sample_fmts, AV_SAMPLE_FMT_FLT);
2174 if( cin_fmt < 0 ) cin_fmt = AV_SAMPLE_FMT_S16;
2175 const char *name = av_get_sample_fmt_name((AVSampleFormat)cin_fmt);
2176 if( !name ) name = _("None");
2177 strcpy(asset->ff_sample_format, name);
2179 char value[BCSTRLEN];
2180 if( !get_ff_option("cin_bitrate", options, value) )
2181 asset->ff_audio_bitrate = atoi(value);
2182 if( !get_ff_option("cin_quality", options, value) )
2183 asset->ff_audio_quality = atoi(value);
2186 void FFMPEG::load_audio_options(Asset *asset, EDL *edl)
2188 char options_path[BCTEXTLEN];
2189 set_option_path(options_path, "audio/%s", asset->acodec);
2190 if( !load_options(options_path,
2191 asset->ff_audio_options,
2192 sizeof(asset->ff_audio_options)) )
2193 scan_audio_options(asset, edl);
2196 void FFMPEG::scan_video_options(Asset *asset, EDL *edl)
2198 char cin_pix_fmt[BCSTRLEN];
2199 int cin_fmt = AV_PIX_FMT_NONE;
2200 const char *options = asset->ff_video_options;
2201 if( !get_ff_option("cin_pix_fmt", options, cin_pix_fmt) )
2202 cin_fmt = (int)av_get_pix_fmt(cin_pix_fmt);
2204 char video_codec[BCSTRLEN]; video_codec[0] = 0;
2205 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,18,100)
2206 const AVCodec *av_codec = !get_codec(video_codec, "video", asset->vcodec) ?
2208 AVCodec *av_codec = !get_codec(video_codec, "video", asset->vcodec) ?
2210 avcodec_find_encoder_by_name(video_codec) : 0;
2211 if( av_codec && av_codec->pix_fmts ) {
2212 if( 0 && edl ) { // frequently picks a bad answer
2213 int color_model = edl->session->color_model;
2214 int max_bits = BC_CModels::calculate_pixelsize(color_model) * 8;
2215 max_bits /= BC_CModels::components(color_model);
2216 cin_fmt = avcodec_find_best_pix_fmt_of_list(av_codec->pix_fmts,
2217 (BC_CModels::is_yuv(color_model) ?
2218 (max_bits > 8 ? AV_PIX_FMT_AYUV64LE : AV_PIX_FMT_YUV444P) :
2219 (max_bits > 8 ? AV_PIX_FMT_RGB48LE : AV_PIX_FMT_RGB24)), 0, 0);
2222 cin_fmt = av_codec->pix_fmts[0];
2225 if( cin_fmt < 0 ) cin_fmt = AV_PIX_FMT_YUV420P;
2226 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get((AVPixelFormat)cin_fmt);
2227 const char *name = desc ? desc->name : _("None");
2228 strcpy(asset->ff_pixel_format, name);
2230 char value[BCSTRLEN];
2231 if( !get_ff_option("cin_bitrate", options, value) )
2232 asset->ff_video_bitrate = atoi(value);
2233 if( !get_ff_option("cin_quality", options, value) )
2234 asset->ff_video_quality = atoi(value);
2237 void FFMPEG::load_video_options(Asset *asset, EDL *edl)
2239 char options_path[BCTEXTLEN];
2240 set_option_path(options_path, "video/%s", asset->vcodec);
2241 if( !load_options(options_path,
2242 asset->ff_video_options,
2243 sizeof(asset->ff_video_options)) )
2244 scan_video_options(asset, edl);
2247 void FFMPEG::scan_format_options(Asset *asset, EDL *edl)
2251 void FFMPEG::load_format_options(Asset *asset, EDL *edl)
2253 char options_path[BCTEXTLEN];
2254 set_option_path(options_path, "format/%s", asset->fformat);
2255 if( !load_options(options_path,
2256 asset->ff_format_options,
2257 sizeof(asset->ff_format_options)) )
2258 scan_format_options(asset, edl);
2261 int FFMPEG::load_defaults(const char *path, const char *type,
2262 char *codec, char *codec_options, int len)
2264 char default_file[BCTEXTLEN];
2265 set_option_path(default_file, "%s/%s.dfl", path, type);
2266 FILE *fp = fopen(default_file,"r");
2268 fgets(codec, BCSTRLEN, fp);
2270 while( *cp && *cp!='\n' ) ++cp;
2272 while( len > 0 && fgets(codec_options, len, fp) ) {
2273 int n = strlen(codec_options);
2274 codec_options += n; len -= n;
2277 set_option_path(default_file, "%s/%s", path, codec);
2278 return load_options(default_file, codec_options, len);
2281 void FFMPEG::set_asset_format(Asset *asset, EDL *edl, const char *text)
2283 if( asset->format != FILE_FFMPEG ) return;
2284 if( text != asset->fformat )
2285 strcpy(asset->fformat, text);
2286 if( !asset->ff_format_options[0] )
2287 load_format_options(asset, edl);
2288 if( asset->audio_data && !asset->ff_audio_options[0] ) {
2289 if( !load_defaults("audio", text, asset->acodec,
2290 asset->ff_audio_options, sizeof(asset->ff_audio_options)) )
2291 scan_audio_options(asset, edl);
2293 asset->audio_data = 0;
2295 if( asset->video_data && !asset->ff_video_options[0] ) {
2296 if( !load_defaults("video", text, asset->vcodec,
2297 asset->ff_video_options, sizeof(asset->ff_video_options)) )
2298 scan_video_options(asset, edl);
2300 asset->video_data = 0;
2304 int FFMPEG::get_encoder(const char *options,
2305 char *format, char *codec, char *bsfilter)
2307 FILE *fp = fopen(options,"r");
2309 eprintf(_("options open failed %s\n"),options);
2312 char line[BCTEXTLEN];
2313 if( !fgets(line, sizeof(line), fp) ||
2314 scan_encoder(line, format, codec, bsfilter) )
2315 eprintf(_("format/codec not found %s\n"), options);
2320 int FFMPEG::scan_encoder(const char *line,
2321 char *format, char *codec, char *bsfilter)
2323 format[0] = codec[0] = bsfilter[0] = 0;
2324 if( scan_option_line(line, format, codec) ) return 1;
2326 while( *cp && *cp != '|' ) ++cp;
2327 if( !*cp ) return 0;
2329 do { *bp-- = 0; } while( bp>=codec && (*bp==' ' || *bp == '\t' ) );
2330 while( *++cp && (*cp==' ' || *cp == '\t') );
2332 for( int i=BCTEXTLEN; --i>0 && *cp; ) *bp++ = *cp++;
2337 int FFMPEG::read_options(const char *options, AVDictionary *&opts, int skip)
2339 FILE *fp = fopen(options,"r");
2342 while( !ret && --skip >= 0 ) {
2344 while( ch >= 0 && ch != '\n' ) ch = getc(fp);
2345 if( ch < 0 ) ret = 1;
2348 ret = read_options(fp, options, opts);
2353 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
2355 FILE *fp = fmemopen((void *)options,strlen(options),"r");
2357 int ret = read_options(fp, options, opts);
2360 AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
2361 if( tag ) st->id = strtol(tag->value,0,0);
2366 void FFMPEG::put_cache_frame(VFrame *frame, int64_t position)
2368 file_base->file->put_cache_frame(frame, position, 0);
2371 int FFMPEG::get_use_cache()
2373 return file_base->file->get_use_cache();
2376 void FFMPEG::purge_cache()
2378 file_base->file->purge_cache();
2381 FFCodecRemap::FFCodecRemap()
2386 FFCodecRemap::~FFCodecRemap()
2388 delete [] old_codec;
2389 delete [] new_codec;
2392 int FFCodecRemaps::add(const char *val)
2394 char old_codec[BCSTRLEN], new_codec[BCSTRLEN];
2395 if( sscanf(val, " %63[a-zA-z0-9_-] = %63[a-z0-9_-]",
2396 &old_codec[0], &new_codec[0]) != 2 ) return 1;
2397 FFCodecRemap &remap = append();
2398 remap.old_codec = cstrdup(old_codec);
2399 remap.new_codec = cstrdup(new_codec);
2403 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
2404 int FFCodecRemaps::update(AVCodecID &codec_id, const AVCodec *&decoder)
2406 const AVCodec *codec = avcodec_find_decoder(codec_id);
2408 int FFCodecRemaps::update(AVCodecID &codec_id, AVCodec *&decoder)
2410 AVCodec *codec = avcodec_find_decoder(codec_id);
2412 if( !codec ) return -1;
2413 const char *name = codec->name;
2414 FFCodecRemaps &map = *this;
2416 while( --k >= 0 && strcmp(map[k].old_codec, name) );
2417 if( k < 0 ) return 1;
2418 const char *new_codec = map[k].new_codec;
2419 codec = avcodec_find_decoder_by_name(new_codec);
2420 if( !codec ) return -1;
2425 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
2427 int ret = 0, no = 0;
2428 char line[BCTEXTLEN];
2429 while( !ret && fgets(line, sizeof(line), fp) ) {
2430 line[sizeof(line)-1] = 0;
2431 if( line[0] == '#' ) continue;
2432 if( line[0] == '\n' ) continue;
2433 char key[BCSTRLEN], val[BCTEXTLEN];
2434 if( scan_option_line(line, key, val) ) {
2435 eprintf(_("err reading %s: line %d\n"), options, no);
2439 if( !strcmp(key, "duration") )
2440 opt_duration = strtod(val, 0);
2441 else if( !strcmp(key, "video_decoder") )
2442 opt_video_decoder = cstrdup(val);
2443 else if( !strcmp(key, "audio_decoder") )
2444 opt_audio_decoder = cstrdup(val);
2445 else if( !strcmp(key, "remap_video_decoder") )
2446 video_codec_remaps.add(val);
2447 else if( !strcmp(key, "remap_audio_decoder") )
2448 audio_codec_remaps.add(val);
2449 else if( !strcmp(key, "video_filter") )
2450 opt_video_filter = cstrdup(val);
2451 else if( !strcmp(key, "audio_filter") )
2452 opt_audio_filter = cstrdup(val);
2453 else if( !strcmp(key, "cin_hw_dev") )
2454 opt_hw_dev = cstrdup(val);
2455 else if( !strcmp(key, "loglevel") )
2458 av_dict_set(&opts, key, val, 0);
2464 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
2466 char option_path[BCTEXTLEN];
2467 set_option_path(option_path, "%s", options);
2468 return read_options(option_path, opts);
2471 int FFMPEG::load_options(const char *path, char *bfr, int len)
2474 FILE *fp = fopen(path, "r");
2476 fgets(bfr, len, fp); // skip hdr
2477 len = fread(bfr, 1, len-1, fp);
2478 if( len < 0 ) len = 0;
2484 void FFMPEG::set_loglevel(const char *ap)
2486 if( !ap || !*ap ) return;
2491 { "quiet" , AV_LOG_QUIET },
2492 { "panic" , AV_LOG_PANIC },
2493 { "fatal" , AV_LOG_FATAL },
2494 { "error" , AV_LOG_ERROR },
2495 { "warning", AV_LOG_WARNING },
2496 { "info" , AV_LOG_INFO },
2497 { "verbose", AV_LOG_VERBOSE },
2498 { "debug" , AV_LOG_DEBUG },
2500 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
2501 if( !strcmp(log_levels[i].name, ap) ) {
2502 av_log_set_level(log_levels[i].level);
2506 av_log_set_level(atoi(ap));
2509 double FFMPEG::to_secs(int64_t time, AVRational time_base)
2511 double base_time = time == AV_NOPTS_VALUE ? 0 :
2512 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
2513 return base_time / AV_TIME_BASE;
2516 int FFMPEG::info(char *text, int len)
2518 if( len <= 0 ) return 0;
2520 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
2522 report("format: %s\n",fmt_ctx->iformat->name);
2523 if( ffvideo.size() > 0 )
2524 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
2525 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
2526 const char *unkn = _("(unkn)");
2527 FFVideoStream *vid = ffvideo[vidx];
2528 AVStream *st = vid->st;
2529 AVCodecID codec_id = st->codecpar->codec_id;
2530 report(_("vid%d (%d), id 0x%06x:\n"), vid->idx, vid->fidx, codec_id);
2531 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
2532 report(" video%d %s ", vidx+1, desc ? desc->name : unkn);
2533 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
2534 AVPixelFormat pix_fmt = (AVPixelFormat)st->codecpar->format;
2535 const char *pfn = av_get_pix_fmt_name(pix_fmt);
2536 report(" pix %s\n", pfn ? pfn : unkn);
2537 int interlace = st->codecpar->field_order;
2538 report(" interlace (container level): %i\n", interlace ? interlace : -1);
2539 int interlace_codec = interlace_from_codec;
2540 report(" interlace (codec level): %i\n", interlace_codec ? interlace_codec : -1);
2541 enum AVColorSpace space = st->codecpar->color_space;
2542 const char *nm = av_color_space_name(space);
2543 report(" color space:%s", nm ? nm : unkn);
2544 enum AVColorRange range = st->codecpar->color_range;
2545 const char *rg = av_color_range_name(range);
2546 report("/ range:%s\n", rg ? rg : unkn);
2547 double secs = to_secs(st->duration, st->time_base);
2548 int64_t length = secs * vid->frame_rate + 0.5;
2549 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
2550 int64_t nudge = ofs * vid->frame_rate;
2551 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
2552 report(" %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
2553 int hrs = secs/3600; secs -= hrs*3600;
2554 int mins = secs/60; secs -= mins*60;
2555 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
2556 double theta = vid->get_rotation_angle();
2557 if( fabs(theta) > 1 )
2558 report(" rotation angle: %0.1f\n", theta);
2560 if( ffaudio.size() > 0 )
2561 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
2562 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2563 FFAudioStream *aud = ffaudio[aidx];
2564 AVStream *st = aud->st;
2565 AVCodecID codec_id = st->codecpar->codec_id;
2566 report(_("aud%d (%d), id 0x%06x:\n"), aud->idx, aud->fidx, codec_id);
2567 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
2568 int nch = aud->channels, ch0 = aud->channel0+1;
2569 report(" audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
2570 AVSampleFormat sample_fmt = (AVSampleFormat)st->codecpar->format;
2571 const char *fmt = av_get_sample_fmt_name(sample_fmt);
2572 report(" %s %d", fmt, aud->sample_rate);
2573 int sample_bits = av_get_bits_per_sample(codec_id);
2574 report(" %dbits\n", sample_bits);
2575 double secs = to_secs(st->duration, st->time_base);
2576 int64_t length = secs * aud->sample_rate + 0.5;
2577 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
2578 int64_t nudge = ofs * aud->sample_rate;
2579 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
2580 report(" %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
2581 int hrs = secs/3600; secs -= hrs*3600;
2582 int mins = secs/60; secs -= mins*60;
2583 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
2585 if( fmt_ctx->nb_programs > 0 )
2586 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
2587 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
2588 report("program %d", i+1);
2589 AVProgram *pgrm = fmt_ctx->programs[i];
2590 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2591 int idx = pgrm->stream_index[j];
2592 int vidx = ffvideo.size();
2593 while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
2595 report(", vid%d", vidx);
2598 int aidx = ffaudio.size();
2599 while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
2601 report(", aud%d", aidx);
2604 report(", (%d)", pgrm->stream_index[j]);
2609 AVDictionaryEntry *tag = 0;
2610 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
2611 report("%s=%s\n", tag->key, tag->value);
2620 int FFMPEG::init_decoder(const char *filename)
2622 ff_lock("FFMPEG::init_decoder");
2624 char file_opts[BCTEXTLEN];
2625 strcpy(file_opts, filename);
2626 char *bp = strrchr(file_opts, '/');
2627 if( !bp ) bp = file_opts;
2628 char *sp = strrchr(bp, '.');
2629 if( !sp ) sp = bp + strlen(bp);
2631 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,18,100)
2632 const AVInputFormat *ifmt = 0;
2634 AVInputFormat *ifmt = 0;
2637 strcpy(sp, ".opts");
2638 fp = fopen(file_opts, "r");
2641 read_options(fp, file_opts, opts);
2643 AVDictionaryEntry *tag;
2644 if( (tag=av_dict_get(opts, "format", NULL, 0)) != 0 ) {
2645 ifmt = av_find_input_format(tag->value);
2649 load_options("decode.opts", opts);
2650 AVDictionary *fopts = 0;
2651 av_dict_copy(&fopts, opts, 0);
2652 int ret = avformat_open_input(&fmt_ctx, filename, ifmt, &fopts);
2653 av_dict_free(&fopts);
2655 ret = avformat_find_stream_info(fmt_ctx, NULL);
2660 return !ret ? 0 : 1;
2663 int FFMPEG::open_decoder()
2666 if( stat(fmt_ctx->url, &st) < 0 ) {
2667 eprintf(_("can't stat file: %s\n"), fmt_ctx->url);
2671 int64_t file_bits = 8 * st.st_size;
2672 if( !fmt_ctx->bit_rate && opt_duration > 0 )
2673 fmt_ctx->bit_rate = file_bits / opt_duration;
2676 if( fmt_ctx->bit_rate > 0 ) {
2677 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2678 AVStream *st = fmt_ctx->streams[i];
2679 if( st->duration != AV_NOPTS_VALUE ) continue;
2680 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
2681 st->duration = av_rescale(file_bits, st->time_base.den,
2682 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
2686 if( estimated && !(fflags & FF_ESTM_TIMES) ) {
2687 fflags |= FF_ESTM_TIMES;
2688 printf("FFMPEG::open_decoder: some stream times estimated: %s\n",
2692 ff_lock("FFMPEG::open_decoder");
2693 int ret = 0, bad_time = 0;
2694 for( int i=0; !ret && i<(int)fmt_ctx->nb_streams; ++i ) {
2695 AVStream *st = fmt_ctx->streams[i];
2696 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
2697 AVCodecParameters *avpar = st->codecpar;
2698 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avpar->codec_id);
2699 if( !codec_desc ) continue;
2700 switch( avpar->codec_type ) {
2701 case AVMEDIA_TYPE_VIDEO: {
2702 if( avpar->width < 1 ) continue;
2703 if( avpar->height < 1 ) continue;
2704 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
2705 if( framerate.num < 1 ) continue;
2707 int vidx = ffvideo.size();
2708 FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
2709 vstrm_index.append(ffidx(vidx, 0));
2710 ffvideo.append(vid);
2711 vid->width = avpar->width;
2712 vid->height = avpar->height;
2713 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
2714 switch( avpar->color_range ) {
2715 case AVCOL_RANGE_MPEG:
2716 vid->color_range = BC_COLORS_MPEG;
2718 case AVCOL_RANGE_JPEG:
2719 vid->color_range = BC_COLORS_JPEG;
2722 vid->color_range = !file_base ? BC_COLORS_JPEG :
2723 file_base->file->preferences->yuv_color_range;
2726 switch( avpar->color_space ) {
2727 case AVCOL_SPC_BT470BG:
2728 vid->color_space = BC_COLORS_BT601_PAL;
2730 case AVCOL_SPC_SMPTE170M:
2731 vid->color_space = BC_COLORS_BT601_NTSC;
2733 case AVCOL_SPC_BT709:
2734 vid->color_space = BC_COLORS_BT709;
2736 case AVCOL_SPC_BT2020_NCL:
2737 vid->color_space = BC_COLORS_BT2020_NCL;
2739 case AVCOL_SPC_BT2020_CL:
2740 vid->color_space = BC_COLORS_BT2020_CL;
2743 vid->color_space = !file_base ? BC_COLORS_BT601_NTSC :
2744 file_base->file->preferences->yuv_color_space;
2747 double secs = to_secs(st->duration, st->time_base);
2748 vid->length = secs * vid->frame_rate;
2749 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
2750 vid->nudge = st->start_time;
2752 ret = vid->create_filter(opt_video_filter);
2754 case AVMEDIA_TYPE_AUDIO: {
2755 if( avpar->channels < 1 ) continue;
2756 if( avpar->sample_rate < 1 ) continue;
2758 int aidx = ffaudio.size();
2759 FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
2760 ffaudio.append(aud);
2761 aud->channel0 = astrm_index.size();
2762 aud->channels = avpar->channels;
2763 for( int ch=0; ch<aud->channels; ++ch )
2764 astrm_index.append(ffidx(aidx, ch));
2765 aud->sample_rate = avpar->sample_rate;
2766 double secs = to_secs(st->duration, st->time_base);
2767 aud->length = secs * aud->sample_rate;
2768 aud->init_swr(aud->channels, avpar->format, aud->sample_rate);
2769 aud->nudge = st->start_time;
2771 ret = aud->create_filter(opt_audio_filter);
2776 if( bad_time && !(fflags & FF_BAD_TIMES) ) {
2777 fflags |= FF_BAD_TIMES;
2778 printf(_("FFMPEG::open_decoder: some stream have bad times: %s\n"),
2782 return ret < 0 ? -1 : 0;
2786 int FFMPEG::init_encoder(const char *filename)
2788 // try access first for named pipes
2789 int ret = access(filename, W_OK);
2791 int fd = ::open(filename,O_WRONLY);
2792 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
2793 if( fd >= 0 ) { close(fd); ret = 0; }
2796 eprintf(_("bad file path: %s\n"), filename);
2799 ret = get_file_format();
2801 eprintf(_("bad file format: %s\n"), filename);
2805 eprintf(_("mismatch audio/video file format: %s\n"), filename);
2808 ff_lock("FFMPEG::init_encoder");
2810 char format[BCSTRLEN];
2811 if( get_format(format, "format", file_format) )
2812 strcpy(format, file_format);
2813 avformat_alloc_output_context2(&fmt_ctx, 0, format, filename);
2815 eprintf(_("failed: %s\n"), filename);
2820 load_options("encode.opts", opts);
2826 int FFMPEG::open_encoder(const char *type, const char *spec)
2829 Asset *asset = file_base->asset;
2830 char *filename = asset->path;
2831 AVDictionary *sopts = 0;
2832 av_dict_copy(&sopts, opts, 0);
2833 char option_path[BCTEXTLEN];
2834 set_option_path(option_path, "%s/%s.opts", type, type);
2835 read_options(option_path, sopts);
2836 get_option_path(option_path, type, spec);
2837 char format_name[BCSTRLEN], codec_name[BCTEXTLEN], bsfilter[BCTEXTLEN];
2838 if( get_encoder(option_path, format_name, codec_name, bsfilter) ) {
2839 eprintf(_("get_encoder failed %s:%s\n"), option_path, filename);
2844 if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
2846 else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
2847 else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
2850 ff_lock("FFMPEG::open_encoder");
2853 AVCodecContext *ctx = 0;
2855 const AVCodecDescriptor *codec_desc = 0;
2856 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
2857 const AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
2859 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
2862 eprintf(_("cant find codec %s:%s\n"), codec_name, filename);
2866 codec_desc = avcodec_descriptor_get(codec->id);
2868 eprintf(_("unknown codec %s:%s\n"), codec_name, filename);
2873 st = avformat_new_stream(fmt_ctx, 0);
2875 eprintf(_("cant create stream %s:%s\n"), codec_name, filename);
2880 switch( codec_desc->type ) {
2881 case AVMEDIA_TYPE_AUDIO: {
2883 eprintf(_("duplicate audio %s:%s\n"), codec_name, filename);
2887 if( scan_options(asset->ff_audio_options, sopts, st) ) {
2888 eprintf(_("bad audio options %s:%s\n"), codec_name, filename);
2893 ctx = avcodec_alloc_context3(codec);
2894 if( asset->ff_audio_bitrate > 0 ) {
2895 ctx->bit_rate = asset->ff_audio_bitrate;
2897 sprintf(arg, "%d", asset->ff_audio_bitrate);
2898 av_dict_set(&sopts, "b", arg, 0);
2900 else if( asset->ff_audio_quality >= 0 ) {
2901 ctx->global_quality = asset->ff_audio_quality * FF_QP2LAMBDA;
2902 ctx->qmin = ctx->qmax = asset->ff_audio_quality;
2903 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2904 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2905 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2907 av_dict_set(&sopts, "flags", "+qscale", 0);
2908 sprintf(arg, "%d", asset->ff_audio_quality);
2909 av_dict_set(&sopts, "qscale", arg, 0);
2910 sprintf(arg, "%d", ctx->global_quality);
2911 av_dict_set(&sopts, "global_quality", arg, 0);
2913 int aidx = ffaudio.size();
2914 int fidx = aidx + ffvideo.size();
2915 FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
2916 aud->avctx = ctx; ffaudio.append(aud); fst = aud;
2917 aud->sample_rate = asset->sample_rate;
2918 ctx->channels = aud->channels = asset->channels;
2919 for( int ch=0; ch<aud->channels; ++ch )
2920 astrm_index.append(ffidx(aidx, ch));
2921 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
2922 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
2923 if( !ctx->sample_rate ) {
2924 eprintf(_("check_sample_rate failed %s\n"), filename);
2928 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
2929 AVSampleFormat sample_fmt = av_get_sample_fmt(asset->ff_sample_format);
2930 if( sample_fmt == AV_SAMPLE_FMT_NONE )
2931 sample_fmt = codec->sample_fmts ? codec->sample_fmts[0] : AV_SAMPLE_FMT_S16;
2932 ctx->sample_fmt = sample_fmt;
2933 uint64_t layout = av_get_default_channel_layout(ctx->channels);
2934 aud->resample_context = swr_alloc_set_opts(NULL,
2935 layout, ctx->sample_fmt, aud->sample_rate,
2936 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
2938 swr_init(aud->resample_context);
2941 case AVMEDIA_TYPE_VIDEO: {
2943 eprintf(_("duplicate video %s:%s\n"), codec_name, filename);
2947 if( scan_options(asset->ff_video_options, sopts, st) ) {
2948 eprintf(_("bad video options %s:%s\n"), codec_name, filename);
2953 ctx = avcodec_alloc_context3(codec);
2954 if( asset->ff_video_bitrate > 0 ) {
2955 ctx->bit_rate = asset->ff_video_bitrate;
2957 sprintf(arg, "%d", asset->ff_video_bitrate);
2958 av_dict_set(&sopts, "b", arg, 0);
2960 else if( asset->ff_video_quality >= 0 ) {
2961 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
2962 ctx->qmin = ctx->qmax = asset->ff_video_quality;
2963 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2964 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2965 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2967 av_dict_set(&sopts, "flags", "+qscale", 0);
2968 sprintf(arg, "%d", asset->ff_video_quality);
2969 av_dict_set(&sopts, "qscale", arg, 0);
2970 sprintf(arg, "%d", ctx->global_quality);
2971 av_dict_set(&sopts, "global_quality", arg, 0);
2973 int vidx = ffvideo.size();
2974 int fidx = vidx + ffaudio.size();
2975 FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
2976 vstrm_index.append(ffidx(vidx, 0));
2977 vid->avctx = ctx; ffvideo.append(vid); fst = vid;
2978 vid->width = asset->width;
2979 vid->height = asset->height;
2980 vid->frame_rate = asset->frame_rate;
2982 char tc_str[20] = "00:00:00:00";
2984 if(asset->timecode > 0)
2985 Units::totext(tc_str, asset->timecode, TIME_HMSF, 0, asset->frame_rate, 0);
2986 //printf("tc: %s \n", tc_str);
2987 av_dict_set(&st->metadata, "timecode", tc_str, 0);
2989 if( (vid->color_range = asset->ff_color_range) < 0 )
2990 vid->color_range = file_base->file->preferences->yuv_color_range;
2991 switch( vid->color_range ) {
2992 case BC_COLORS_MPEG: ctx->color_range = AVCOL_RANGE_MPEG; break;
2993 case BC_COLORS_JPEG: ctx->color_range = AVCOL_RANGE_JPEG; break;
2995 if( (vid->color_space = asset->ff_color_space) < 0 )
2996 vid->color_space = file_base->file->preferences->yuv_color_space;
2997 switch( vid->color_space ) {
2998 case BC_COLORS_BT601_NTSC: ctx->colorspace = AVCOL_SPC_SMPTE170M; break;
2999 case BC_COLORS_BT601_PAL: ctx->colorspace = AVCOL_SPC_BT470BG; break;
3000 case BC_COLORS_BT709: ctx->colorspace = AVCOL_SPC_BT709; break;
3001 case BC_COLORS_BT2020_NCL: ctx->colorspace = AVCOL_SPC_BT2020_NCL; break;
3002 case BC_COLORS_BT2020_CL: ctx->colorspace = AVCOL_SPC_BT2020_CL; break;
3004 AVPixelFormat pix_fmt = av_get_pix_fmt(asset->ff_pixel_format);
3005 if( opt_hw_dev != 0 ) {
3006 AVHWDeviceType hw_type = vid->encode_hw_activate(opt_hw_dev);
3008 case AV_HWDEVICE_TYPE_VAAPI:
3009 pix_fmt = AV_PIX_FMT_VAAPI;
3011 case AV_HWDEVICE_TYPE_NONE:
3015 if( pix_fmt == AV_PIX_FMT_NONE )
3016 pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
3017 ctx->pix_fmt = pix_fmt;
3019 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
3020 int mask_w = (1<<desc->log2_chroma_w)-1;
3021 ctx->width = (vid->width+mask_w) & ~mask_w;
3022 int mask_h = (1<<desc->log2_chroma_h)-1;
3023 ctx->height = (vid->height+mask_h) & ~mask_h;
3024 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
3025 AVRational frame_rate;
3026 if (ctx->codec->id == AV_CODEC_ID_MPEG1VIDEO ||
3027 ctx->codec->id == AV_CODEC_ID_MPEG2VIDEO)
3028 frame_rate = check_frame_rate(codec->supported_framerates, vid->frame_rate);
3030 frame_rate = av_d2q(vid->frame_rate, INT_MAX);
3031 if( !frame_rate.num || !frame_rate.den ) {
3032 eprintf(_("check_frame_rate failed %s\n"), filename);
3036 av_reduce(&frame_rate.num, &frame_rate.den,
3037 frame_rate.num, frame_rate.den, INT_MAX);
3038 ctx->framerate = (AVRational) { frame_rate.num, frame_rate.den };
3039 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
3040 st->avg_frame_rate = frame_rate;
3041 st->time_base = ctx->time_base;
3043 vid->interlaced = asset->interlace_mode == ILACE_MODE_TOP_FIRST ||
3044 asset->interlace_mode == ILACE_MODE_BOTTOM_FIRST ? 1 : 0;
3045 vid->top_field_first = asset->interlace_mode == ILACE_MODE_TOP_FIRST ? 1 : 0;
3046 switch (asset->interlace_mode) {
3047 case ILACE_MODE_TOP_FIRST:
3048 if (ctx->codec->id == AV_CODEC_ID_MJPEG)
3049 av_dict_set(&sopts, "field_order", "tt", 0);
3051 av_dict_set(&sopts, "field_order", "tb", 0);
3052 if (ctx->codec_id != AV_CODEC_ID_MJPEG)
3053 av_dict_set(&sopts, "flags", "+ilme+ildct", 0);
3055 case ILACE_MODE_BOTTOM_FIRST:
3056 if (ctx->codec->id == AV_CODEC_ID_MJPEG)
3057 av_dict_set(&sopts, "field_order", "bb", 0);
3059 av_dict_set(&sopts, "field_order", "bt", 0);
3060 if (ctx->codec_id != AV_CODEC_ID_MJPEG)
3061 av_dict_set(&sopts, "flags", "+ilme+ildct", 0);
3063 case ILACE_MODE_NOTINTERLACED: av_dict_set(&sopts, "field_order", "progressive", 0); break;
3067 eprintf(_("not audio/video, %s:%s\n"), codec_name, filename);
3072 AVDictionaryEntry *tag;
3073 if( (tag=av_dict_get(sopts, "cin_stats_filename", NULL, 0)) != 0 ) {
3074 char suffix[BCSTRLEN]; sprintf(suffix,"-%d.log",fst->fidx);
3075 fst->stats_filename = cstrcat(2, tag->value, suffix);
3077 if( (tag=av_dict_get(sopts, "flags", NULL, 0)) != 0 ) {
3078 int pass = fst->pass;
3079 char *cp = tag->value;
3081 int ch = *cp++, pfx = ch=='-' ? -1 : ch=='+' ? 1 : 0;
3082 if( !isalnum(!pfx ? ch : (ch=*cp++)) ) continue;
3083 char id[BCSTRLEN], *bp = id, *ep = bp+sizeof(id)-1;
3084 for( *bp++=ch; isalnum(ch=*cp); ++cp )
3085 if( bp < ep ) *bp++ = ch;
3087 if( !strcmp(id, "pass1") ) {
3088 pass = pfx<0 ? (pass&~1) : pfx>0 ? (pass|1) : 1;
3090 else if( !strcmp(id, "pass2") ) {
3091 pass = pfx<0 ? (pass&~2) : pfx>0 ? (pass|2) : 2;
3094 if( (fst->pass=pass) ) {
3095 if( pass & 1 ) ctx->flags |= AV_CODEC_FLAG_PASS1;
3096 if( pass & 2 ) ctx->flags |= AV_CODEC_FLAG_PASS2;
3102 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
3103 ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
3104 if( fst->stats_filename && (ret=fst->init_stats_file()) )
3105 eprintf(_("error: stats file = %s\n"), fst->stats_filename);
3108 av_dict_set(&sopts, "cin_bitrate", 0, 0);
3109 av_dict_set(&sopts, "cin_quality", 0, 0);
3111 if( !av_dict_get(sopts, "threads", NULL, 0) )
3112 ctx->thread_count = ff_cpus();
3113 ret = avcodec_open2(ctx, codec, &sopts);
3115 ret = avcodec_parameters_from_context(st->codecpar, ctx);
3117 fprintf(stderr, "Could not copy the stream parameters\n");
3120 _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
3121 #if LIBAVCODEC_VERSION_INT <= AV_VERSION_INT(58,134,100)
3122 ret = avcodec_copy_context(st->codec, ctx);
3124 ret = avcodec_parameters_to_context(ctx, st->codecpar);
3126 _Pragma("GCC diagnostic warning \"-Wdeprecated-declarations\"")
3128 fprintf(stderr, "Could not copy the stream context\n");
3131 ff_err(ret,"FFMPEG::open_encoder");
3132 eprintf(_("open failed %s:%s\n"), codec_name, filename);
3138 if( !ret && fst && bsfilter[0] ) {
3139 ret = av_bsf_list_parse_str(bsfilter, &fst->bsfc);
3141 ff_err(ret,"FFMPEG::open_encoder");
3142 eprintf(_("bitstream filter failed %s:\n%s\n"), filename, bsfilter);
3153 av_dict_free(&sopts);
3157 int FFMPEG::close_encoder()
3160 if( encoding > 0 ) {
3161 av_write_trailer(fmt_ctx);
3162 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
3163 avio_closep(&fmt_ctx->pb);
3169 int FFMPEG::decode_activate()
3171 if( decoding < 0 ) {
3173 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
3174 ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
3175 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
3176 ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
3177 // set nudges for each program stream set
3178 const int64_t min_nudge = INT64_MIN+1;
3179 int npgrms = fmt_ctx->nb_programs;
3180 for( int i=0; i<npgrms; ++i ) {
3181 AVProgram *pgrm = fmt_ctx->programs[i];
3182 // first start time video stream
3183 int64_t vstart_time = min_nudge, astart_time = min_nudge;
3184 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
3185 int fidx = pgrm->stream_index[j];
3186 AVStream *st = fmt_ctx->streams[fidx];
3187 AVCodecParameters *avpar = st->codecpar;
3188 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
3189 if( st->start_time == AV_NOPTS_VALUE ) continue;
3190 if( vstart_time < st->start_time )
3191 vstart_time = st->start_time;
3194 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
3195 if( st->start_time == AV_NOPTS_VALUE ) continue;
3196 if( astart_time < st->start_time )
3197 astart_time = st->start_time;
3201 //since frame rate is much more grainy than sample rate, it is better to
3202 // align using video, so that total absolute error is minimized.
3203 int64_t nudge = vstart_time > min_nudge ? vstart_time :
3204 astart_time > min_nudge ? astart_time : AV_NOPTS_VALUE;
3205 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
3206 int fidx = pgrm->stream_index[j];
3207 AVStream *st = fmt_ctx->streams[fidx];
3208 AVCodecParameters *avpar = st->codecpar;
3209 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
3210 for( int k=0; k<ffvideo.size(); ++k ) {
3211 if( ffvideo[k]->fidx != fidx ) continue;
3212 ffvideo[k]->nudge = nudge;
3216 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
3217 for( int k=0; k<ffaudio.size(); ++k ) {
3218 if( ffaudio[k]->fidx != fidx ) continue;
3219 ffaudio[k]->nudge = nudge;
3225 // set nudges for any streams not yet set
3226 int64_t vstart_time = min_nudge, astart_time = min_nudge;
3227 int nstreams = fmt_ctx->nb_streams;
3228 for( int i=0; i<nstreams; ++i ) {
3229 AVStream *st = fmt_ctx->streams[i];
3230 AVCodecParameters *avpar = st->codecpar;
3231 switch( avpar->codec_type ) {
3232 case AVMEDIA_TYPE_VIDEO: {
3233 if( st->start_time == AV_NOPTS_VALUE ) continue;
3234 int vidx = ffvideo.size();
3235 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
3236 if( vidx < 0 ) continue;
3237 if( ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
3238 if( vstart_time < st->start_time )
3239 vstart_time = st->start_time;
3241 case AVMEDIA_TYPE_AUDIO: {
3242 if( st->start_time == AV_NOPTS_VALUE ) continue;
3243 int aidx = ffaudio.size();
3244 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
3245 if( aidx < 0 ) continue;
3246 if( ffaudio[aidx]->frame_sz < avpar->frame_size )
3247 ffaudio[aidx]->frame_sz = avpar->frame_size;
3248 if( ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
3249 if( astart_time < st->start_time )
3250 astart_time = st->start_time;
3255 int64_t nudge = vstart_time > min_nudge ? vstart_time :
3256 astart_time > min_nudge ? astart_time : 0;
3257 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
3258 if( ffvideo[vidx]->nudge == AV_NOPTS_VALUE )
3259 ffvideo[vidx]->nudge = nudge;
3261 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
3262 if( ffaudio[aidx]->nudge == AV_NOPTS_VALUE )
3263 ffaudio[aidx]->nudge = nudge;
3270 int FFMPEG::encode_activate()
3273 if( encoding < 0 ) {
3275 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
3276 (ret=avio_open(&fmt_ctx->pb, fmt_ctx->url, AVIO_FLAG_WRITE)) < 0 ) {
3277 ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
3281 if( !strcmp(file_format, "image2") ) {
3282 Asset *asset = file_base->asset;
3283 const char *filename = asset->path;
3284 FILE *fp = fopen(filename,"w");
3286 eprintf(_("Cant write image2 header file: %s\n %m"), filename);
3289 fprintf(fp, "IMAGE2\n");
3290 fprintf(fp, "# Frame rate: %f\n", asset->frame_rate);
3291 fprintf(fp, "# Width: %d\n", asset->width);
3292 fprintf(fp, "# Height: %d\n", asset->height);
3296 AVProgram *prog = av_new_program(fmt_ctx, prog_id);
3297 for( int i=0; i< ffvideo.size(); ++i )
3298 av_program_add_stream_index(fmt_ctx, prog_id, ffvideo[i]->fidx);
3299 for( int i=0; i< ffaudio.size(); ++i )
3300 av_program_add_stream_index(fmt_ctx, prog_id, ffaudio[i]->fidx);
3301 int pi = fmt_ctx->nb_programs;
3302 while( --pi >= 0 && fmt_ctx->programs[pi]->id != prog_id );
3303 AVDictionary **meta = &prog->metadata;
3304 av_dict_set(meta, "service_provider", "cin5", 0);
3305 const char *path = fmt_ctx->url, *bp = strrchr(path,'/');
3306 if( bp ) path = bp + 1;
3307 av_dict_set(meta, "title", path, 0);
3309 if( ffaudio.size() ) {
3310 const char *ep = getenv("CIN_AUDIO_LANG"), *lp = 0;
3311 if( !ep && (lp=getenv("LANG")) ) { // some are guesses
3312 static struct { const char lc[3], lng[4]; } lcode[] = {
3313 { "en", "eng" }, { "de", "ger" }, { "es", "spa" },
3314 { "eu", "bas" }, { "fr", "fre" }, { "el", "gre" },
3315 { "hi", "hin" }, { "it", "ita" }, { "ja", "jap" },
3316 { "ko", "kor" }, { "du", "dut" }, { "pl", "pol" },
3317 { "pt", "por" }, { "ru", "rus" }, { "sl", "slv" },
3318 { "uk", "ukr" }, { "vi", "vie" }, { "zh", "chi" },
3320 for( int i=sizeof(lcode)/sizeof(lcode[0]); --i>=0 && !ep; )
3321 if( !strncmp(lcode[i].lc,lp,2) ) ep = lcode[i].lng;
3323 if( !ep ) ep = "und";
3325 strncpy(lang,ep,3); lang[3] = 0;
3326 AVStream *st = ffaudio[0]->st;
3327 av_dict_set(&st->metadata,"language",lang,0);
3330 AVDictionary *fopts = 0;
3331 char option_path[BCTEXTLEN];
3332 set_option_path(option_path, "format/%s", file_format);
3333 read_options(option_path, fopts, 1);
3334 av_dict_copy(&fopts, opts, 0);
3335 if( scan_options(file_base->asset->ff_format_options, fopts, 0) ) {
3336 eprintf(_("bad format options %s\n"), file_base->asset->path);
3340 ret = avformat_write_header(fmt_ctx, &fopts);
3342 ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
3346 av_dict_free(&fopts);
3353 int FFMPEG::audio_seek(int stream, int64_t pos)
3355 int aidx = astrm_index[stream].st_idx;
3356 FFAudioStream *aud = ffaudio[aidx];
3357 aud->audio_seek(pos);
3361 int FFMPEG::video_probe(int64_t pos)
3363 int vidx = vstrm_index[0].st_idx;
3364 FFVideoStream *vid = ffvideo[vidx];
3367 int interlace1 = interlace_from_codec;
3368 //printf("interlace from codec: %i\n", interlace1);
3374 return ILACE_MODE_TOP_FIRST;
3377 return ILACE_MODE_BOTTOM_FIRST;
3378 case AV_FIELD_PROGRESSIVE:
3379 return ILACE_MODE_NOTINTERLACED;
3381 return ILACE_MODE_UNDETECTED;
3388 int FFMPEG::video_seek(int stream, int64_t pos)
3390 int vidx = vstrm_index[stream].st_idx;
3391 FFVideoStream *vid = ffvideo[vidx];
3392 vid->video_seek(pos);
3397 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
3399 if( !has_audio || chn >= astrm_index.size() ) return -1;
3400 int aidx = astrm_index[chn].st_idx;
3401 FFAudioStream *aud = ffaudio[aidx];
3402 if( aud->load(pos, len) < len ) return -1;
3403 int ch = astrm_index[chn].st_ch;
3404 int ret = aud->read(samples,len,ch);
3408 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
3410 if( !has_video || layer >= vstrm_index.size() ) return -1;
3411 int vidx = vstrm_index[layer].st_idx;
3412 FFVideoStream *vid = ffvideo[vidx];
3413 return vid->load(vframe, pos);
3417 int FFMPEG::encode(int stream, double **samples, int len)
3419 FFAudioStream *aud = ffaudio[stream];
3420 return aud->encode(samples, len);
3424 int FFMPEG::encode(int stream, VFrame *frame)
3426 FFVideoStream *vid = ffvideo[stream];
3427 return vid->encode(frame);
3430 void FFMPEG::start_muxer()
3438 void FFMPEG::stop_muxer()
3447 void FFMPEG::flow_off()
3450 flow_lock->lock("FFMPEG::flow_off");
3454 void FFMPEG::flow_on()
3458 flow_lock->unlock();
3461 void FFMPEG::flow_ctl()
3464 flow_lock->lock("FFMPEG::flow_ctl");
3465 flow_lock->unlock();
3469 int FFMPEG::mux_audio(FFrame *frm)
3471 FFStream *fst = frm->fst;
3472 AVCodecContext *ctx = fst->avctx;
3473 AVFrame *frame = *frm;
3474 AVRational tick_rate = {1, ctx->sample_rate};
3475 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
3476 int ret = fst->encode_frame(frame);
3478 ff_err(ret, "FFMPEG::mux_audio");
3479 return ret >= 0 ? 0 : 1;
3482 int FFMPEG::mux_video(FFrame *frm)
3484 FFStream *fst = frm->fst;
3485 AVFrame *frame = *frm;
3486 frame->pts = frm->position;
3487 int ret = fst->encode_frame(frame);
3489 ff_err(ret, "FFMPEG::mux_video");
3490 return ret >= 0 ? 0 : 1;
3496 double atm = -1, vtm = -1;
3497 FFrame *afrm = 0, *vfrm = 0;
3499 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
3500 FFStream *fst = ffaudio[i];
3501 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
3502 FFrame *frm = fst->frms.first;
3503 if( !frm ) { if( !done ) return; continue; }
3504 double tm = to_secs(frm->position, fst->avctx->time_base);
3505 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
3507 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
3508 FFStream *fst = ffvideo[i];
3509 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
3510 FFrame *frm = fst->frms.first;
3511 if( !frm ) { if( !done ) return; continue; }
3512 double tm = to_secs(frm->position, fst->avctx->time_base);
3513 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
3515 if( !demand ) flow_off();
3516 if( !afrm && !vfrm ) break;
3517 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
3518 vfrm->position, vfrm->fst->avctx->time_base,
3519 afrm->position, afrm->fst->avctx->time_base);
3520 FFrame *frm = v <= 0 ? vfrm : afrm;
3521 if( frm == afrm ) mux_audio(frm);
3522 if( frm == vfrm ) mux_video(frm);
3531 mux_lock->lock("FFMPEG::run");
3534 for( int i=0; i<ffaudio.size(); ++i )
3535 ffaudio[i]->drain();
3536 for( int i=0; i<ffvideo.size(); ++i )
3537 ffvideo[i]->drain();
3539 for( int i=0; i<ffaudio.size(); ++i )
3540 ffaudio[i]->flush();
3541 for( int i=0; i<ffvideo.size(); ++i )
3542 ffvideo[i]->flush();
3546 int FFMPEG::ff_total_audio_channels()
3548 return astrm_index.size();
3551 int FFMPEG::ff_total_astreams()
3553 return ffaudio.size();
3556 int FFMPEG::ff_audio_channels(int stream)
3558 return ffaudio[stream]->channels;
3561 int FFMPEG::ff_sample_rate(int stream)
3563 return ffaudio[stream]->sample_rate;
3566 const char* FFMPEG::ff_audio_format(int stream)
3568 AVStream *st = ffaudio[stream]->st;
3569 AVCodecID id = st->codecpar->codec_id;
3570 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
3571 return desc ? desc->name : _("Unknown");
3574 int FFMPEG::ff_audio_pid(int stream)
3576 return ffaudio[stream]->st->id;
3579 int64_t FFMPEG::ff_audio_samples(int stream)
3581 return ffaudio[stream]->length;
3584 // find audio astream/channels with this program,
3585 // or all program audio channels (astream=-1)
3586 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
3590 int vidx = ffvideo[vstream]->fidx;
3591 // find first program with this video stream
3592 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
3593 AVProgram *pgrm = fmt_ctx->programs[i];
3594 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
3595 int st_idx = pgrm->stream_index[j];
3596 AVStream *st = fmt_ctx->streams[st_idx];
3597 if( st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
3598 if( st_idx == vidx ) pidx = i;
3601 if( pidx < 0 ) return -1;
3603 int64_t channels = 0;
3604 AVProgram *pgrm = fmt_ctx->programs[pidx];
3605 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
3606 int aidx = pgrm->stream_index[j];
3607 AVStream *st = fmt_ctx->streams[aidx];
3608 if( st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
3609 if( astream > 0 ) { --astream; continue; }
3611 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
3612 if( ffaudio[i]->fidx == aidx ) astrm = i;
3614 if( ret < 0 ) ret = astrm;
3615 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
3616 channels |= mask << ffaudio[astrm]->channel0;
3618 if( !astream ) break;
3620 channel_mask = channels;
3625 int FFMPEG::ff_total_video_layers()
3627 return vstrm_index.size();
3630 int FFMPEG::ff_total_vstreams()
3632 return ffvideo.size();
3635 int FFMPEG::ff_video_width(int stream)
3637 FFVideoStream *vst = ffvideo[stream];
3638 return !vst->transpose ? vst->width : vst->height;
3641 int FFMPEG::ff_video_height(int stream)
3643 FFVideoStream *vst = ffvideo[stream];
3644 return !vst->transpose ? vst->height : vst->width;
3647 int FFMPEG::ff_set_video_width(int stream, int width)
3649 FFVideoStream *vst = ffvideo[stream];
3650 int *vw = !vst->transpose ? &vst->width : &vst->height, w = *vw;
3655 int FFMPEG::ff_set_video_height(int stream, int height)
3657 FFVideoStream *vst = ffvideo[stream];
3658 int *vh = !vst->transpose ? &vst->height : &vst->width, h = *vh;
3663 int FFMPEG::ff_coded_width(int stream)
3665 return ffvideo[stream]->avctx->coded_width;
3668 int FFMPEG::ff_coded_height(int stream)
3670 return ffvideo[stream]->avctx->coded_height;
3673 float FFMPEG::ff_aspect_ratio(int stream)
3675 //return ffvideo[stream]->aspect_ratio;
3676 AVFormatContext *fmt_ctx = ffvideo[stream]->fmt_ctx;
3677 AVStream *strm = ffvideo[stream]->st;
3678 AVCodecParameters *par = ffvideo[stream]->st->codecpar;
3680 AVRational sar = av_guess_sample_aspect_ratio(fmt_ctx, strm, NULL);
3681 if (sar.num && ffvideo[stream]->get_rotation_angle() == 0) {
3682 av_reduce(&dar.num, &dar.den,
3683 par->width * sar.num,
3684 par->height * sar.den,
3688 return ffvideo[stream]->aspect_ratio;
3691 const char* FFMPEG::ff_video_codec(int stream)
3693 AVStream *st = ffvideo[stream]->st;
3694 AVCodecID id = st->codecpar->codec_id;
3695 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
3696 return desc ? desc->name : _("Unknown");
3699 int FFMPEG::ff_color_range(int stream)
3701 return ffvideo[stream]->color_range;
3704 int FFMPEG::ff_color_space(int stream)
3706 return ffvideo[stream]->color_space;
3709 double FFMPEG::ff_frame_rate(int stream)
3711 return ffvideo[stream]->frame_rate;
3714 int64_t FFMPEG::ff_video_frames(int stream)
3716 return ffvideo[stream]->length;
3719 int FFMPEG::ff_video_pid(int stream)
3721 return ffvideo[stream]->st->id;
3724 int FFMPEG::ff_video_mpeg_color_range(int stream)
3726 return ffvideo[stream]->st->codecpar->color_range == AVCOL_RANGE_MPEG ? 1 : 0;
3729 int FFMPEG::ff_interlace(int stream)
3731 // https://ffmpeg.org/doxygen/trunk/structAVCodecParserContext.html
3732 /* reads from demuxer because codec frame not ready */
3733 int interlace0 = ffvideo[stream]->st->codecpar->field_order;
3739 return ILACE_MODE_TOP_FIRST;
3742 return ILACE_MODE_BOTTOM_FIRST;
3743 case AV_FIELD_PROGRESSIVE:
3744 return ILACE_MODE_NOTINTERLACED;
3746 return ILACE_MODE_UNDETECTED;
3753 int FFMPEG::ff_cpus()
3755 return !file_base ? 1 : file_base->file->cpus;
3758 const char *FFMPEG::ff_hw_dev()
3760 return &file_base->file->preferences->use_hw_dev[0];
3763 Preferences *FFMPEG::ff_prefs()
3765 return !file_base ? 0 : file_base->file->preferences;
3768 double FFVideoStream::get_rotation_angle()
3770 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
3775 int *matrix = (int*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX, &size);
3776 int len = size/sizeof(*matrix);
3777 if( !matrix || len < 5 ) return 0;
3778 const double s = 1/65536.;
3779 double theta = (!matrix[0] && !matrix[3]) || (!matrix[1] && !matrix[4]) ? 0 :
3780 atan2( s*matrix[1] / hypot(s*matrix[1], s*matrix[4]),
3781 s*matrix[0] / hypot(s*matrix[0], s*matrix[3])) * 180/M_PI;
3785 int FFVideoStream::flip(double theta)
3789 Preferences *preferences = ffmpeg->ff_prefs();
3790 if( !preferences || !preferences->auto_rotate ) return ret;
3791 double tolerance = 1;
3792 if( fabs(theta-0) < tolerance ) return ret;
3793 if( (theta=fmod(theta, 360)) < 0 ) theta += 360;
3794 if( fabs(theta-90) < tolerance ) {
3795 if( (ret = insert_filter("transpose", "clock")) < 0 )
3799 else if( fabs(theta-180) < tolerance ) {
3800 if( (ret=insert_filter("hflip", 0)) < 0 )
3802 if( (ret=insert_filter("vflip", 0)) < 0 )
3805 else if (fabs(theta-270) < tolerance ) {
3806 if( (ret=insert_filter("transpose", "cclock")) < 0 )
3811 char angle[BCSTRLEN];
3812 sprintf(angle, "%f", theta*M_PI/180.);
3813 if( (ret=insert_filter("rotate", angle)) < 0 )
3819 int FFVideoStream::create_filter(const char *filter_spec)
3821 double theta = get_rotation_angle();
3822 if( !theta && !filter_spec )
3824 avfilter_register_all();
3826 const char *sp = filter_spec;
3827 char filter_name[BCSTRLEN], *np = filter_name;
3828 int i = sizeof(filter_name);
3829 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
3831 const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
3832 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_VIDEO ) {
3833 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
3837 AVCodecParameters *avpar = st->codecpar;
3838 int sa_num = avpar->sample_aspect_ratio.num;
3839 if( !sa_num ) sa_num = 1;
3840 int sa_den = avpar->sample_aspect_ratio.den;
3841 if( !sa_den ) sa_num = 1;
3843 int ret = 0; char args[BCTEXTLEN];
3844 AVPixelFormat pix_fmt = (AVPixelFormat)avpar->format;
3845 snprintf(args, sizeof(args),
3846 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
3847 avpar->width, avpar->height, (int)pix_fmt,
3848 st->time_base.num, st->time_base.den, sa_num, sa_den);
3851 ret = insert_filter("buffer", args, "in");
3852 buffersrc_ctx = filt_ctx;
3856 AVFilterContext *fsrc = filt_ctx;
3859 ret = insert_filter("buffersink", 0, "out");
3860 buffersink_ctx = filt_ctx;
3863 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
3864 (uint8_t*)&pix_fmt, sizeof(pix_fmt),
3865 AV_OPT_SEARCH_CHILDREN);
3868 ret = config_filters(filter_spec, fsrc);
3870 ff_err(ret, "FFVideoStream::create_filter");
3871 return ret >= 0 ? 0 : -1;
3874 int FFAudioStream::create_filter(const char *filter_spec)
3878 avfilter_register_all();
3880 const char *sp = filter_spec;
3881 char filter_name[BCSTRLEN], *np = filter_name;
3882 int i = sizeof(filter_name);
3883 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
3885 const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
3886 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_AUDIO ) {
3887 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
3891 int ret = 0; char args[BCTEXTLEN];
3892 AVCodecParameters *avpar = st->codecpar;
3893 AVSampleFormat sample_fmt = (AVSampleFormat)avpar->format;
3894 snprintf(args, sizeof(args),
3895 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
3896 st->time_base.num, st->time_base.den, avpar->sample_rate,
3897 av_get_sample_fmt_name(sample_fmt), avpar->channel_layout);
3900 ret = insert_filter("abuffer", args, "in");
3901 buffersrc_ctx = filt_ctx;
3903 AVFilterContext *fsrc = filt_ctx;
3906 ret = insert_filter("abuffersink", 0, "out");
3907 buffersink_ctx = filt_ctx;
3910 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
3911 (uint8_t*)&sample_fmt, sizeof(sample_fmt),
3912 AV_OPT_SEARCH_CHILDREN);
3914 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
3915 (uint8_t*)&avpar->channel_layout,
3916 sizeof(avpar->channel_layout), AV_OPT_SEARCH_CHILDREN);
3918 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
3919 (uint8_t*)&sample_rate, sizeof(sample_rate),
3920 AV_OPT_SEARCH_CHILDREN);
3922 ret = config_filters(filter_spec, fsrc);
3924 ff_err(ret, "FFAudioStream::create_filter");
3925 return ret >= 0 ? 0 : -1;
3928 int FFStream::insert_filter(const char *name, const char *arg, const char *inst_name)
3930 const AVFilter *filter = avfilter_get_by_name(name);
3931 if( !filter ) return -1;
3932 char filt_inst[BCSTRLEN];
3934 snprintf(filt_inst, sizeof(filt_inst), "%s_%d", name, ++filt_id);
3935 inst_name = filt_inst;
3938 filter_graph = avfilter_graph_alloc();
3939 AVFilterContext *fctx = 0;
3940 int ret = avfilter_graph_create_filter(&fctx,
3941 filter, inst_name, arg, NULL, filter_graph);
3942 if( ret >= 0 && filt_ctx )
3943 ret = avfilter_link(filt_ctx, 0, fctx, 0);
3947 avfilter_free(fctx);
3951 int FFStream::config_filters(const char *filter_spec, AVFilterContext *fsrc)
3954 AVFilterContext *fsink = buffersink_ctx;
3956 /* Endpoints for the filter graph. */
3957 AVFilterInOut *outputs = avfilter_inout_alloc();
3958 AVFilterInOut *inputs = avfilter_inout_alloc();
3959 if( !inputs || !outputs ) ret = -1;
3961 outputs->filter_ctx = fsrc;
3962 outputs->pad_idx = 0;
3964 if( !(outputs->name = av_strdup(fsrc->name)) ) ret = -1;
3967 inputs->filter_ctx = fsink;
3968 inputs->pad_idx = 0;
3970 if( !(inputs->name = av_strdup(fsink->name)) ) ret = -1;
3973 int len = strlen(fsrc->name)+2 + strlen(filter_spec) + 1;
3974 char spec[len]; sprintf(spec, "[%s]%s", fsrc->name, filter_spec);
3975 ret = avfilter_graph_parse_ptr(filter_graph, spec,
3976 &inputs, &outputs, NULL);
3978 avfilter_inout_free(&inputs);
3979 avfilter_inout_free(&outputs);
3982 ret = avfilter_link(fsrc, 0, fsink, 0);
3984 ret = avfilter_graph_config(filter_graph, NULL);
3986 ff_err(ret, "FFStream::create_filter");
3987 avfilter_graph_free(&filter_graph);
3994 AVCodecContext *FFMPEG::activate_decoder(AVStream *st)
3996 AVDictionary *copts = 0;
3997 av_dict_copy(&copts, opts, 0);
3998 AVCodecID codec_id = st->codecpar->codec_id;
3999 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
4000 const AVCodec *decoder = 0;
4002 AVCodec *decoder = 0;
4004 switch( st->codecpar->codec_type ) {
4005 case AVMEDIA_TYPE_VIDEO:
4006 if( opt_video_decoder )
4007 decoder = avcodec_find_decoder_by_name(opt_video_decoder);
4009 video_codec_remaps.update(codec_id, decoder);
4011 case AVMEDIA_TYPE_AUDIO:
4012 if( opt_audio_decoder )
4013 decoder = avcodec_find_decoder_by_name(opt_audio_decoder);
4015 audio_codec_remaps.update(codec_id, decoder);
4020 if( !decoder && !(decoder = avcodec_find_decoder(codec_id)) ) {
4021 eprintf(_("cant find decoder codec %d\n"), (int)codec_id);
4024 AVCodecContext *avctx = avcodec_alloc_context3(decoder);
4026 eprintf(_("cant allocate codec context\n"));
4029 avcodec_parameters_to_context(avctx, st->codecpar);
4030 if( !av_dict_get(copts, "threads", NULL, 0) )
4031 avctx->thread_count = ff_cpus();
4032 int ret = avcodec_open2(avctx, decoder, &copts);
4033 av_dict_free(&copts);
4035 avcodec_free_context(&avctx);
4041 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
4044 av_init_packet(&pkt);
4045 AVFrame *frame = av_frame_alloc();
4047 fprintf(stderr,"FFMPEG::scan: ");
4048 fprintf(stderr,_("av_frame_alloc failed\n"));
4049 fprintf(stderr,"FFMPEG::scan:file=%s\n", file_base->asset->path);
4053 index_state->add_video_markers(ffvideo.size());
4054 index_state->add_audio_markers(ffaudio.size());
4056 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
4057 AVStream *st = fmt_ctx->streams[i];
4058 AVCodecContext *avctx = activate_decoder(st);
4060 AVCodecParameters *avpar = st->codecpar;
4061 switch( avpar->codec_type ) {
4062 case AVMEDIA_TYPE_VIDEO: {
4063 int vidx = ffvideo.size();
4064 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
4065 if( vidx < 0 ) break;
4066 ffvideo[vidx]->avctx = avctx;
4068 case AVMEDIA_TYPE_AUDIO: {
4069 int aidx = ffaudio.size();
4070 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
4071 if( aidx < 0 ) break;
4072 ffaudio[aidx]->avctx = avctx;
4077 fprintf(stderr,"FFMPEG::scan: ");
4078 fprintf(stderr,_("codec open failed\n"));
4079 fprintf(stderr,"FFMPEG::scan:file=%s\n", file_base->asset->path);
4080 avcodec_free_context(&avctx);
4084 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
4085 AVStream *st = fmt_ctx->streams[i];
4086 AVCodecParameters *avpar = st->codecpar;
4087 if( avpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
4088 int64_t tstmp = st->start_time;
4089 if( tstmp == AV_NOPTS_VALUE ) continue;
4090 int aidx = ffaudio.size();
4091 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
4092 if( aidx < 0 ) continue;
4093 FFAudioStream *aud = ffaudio[aidx];
4094 tstmp -= aud->nudge;
4095 double secs = to_secs(tstmp, st->time_base);
4096 aud->curr_pos = secs * aud->sample_rate + 0.5;
4100 for( int64_t count=0; !*canceled; ++count ) {
4101 av_packet_unref(&pkt);
4102 pkt.data = 0; pkt.size = 0;
4104 int ret = av_read_frame(fmt_ctx, &pkt);
4106 if( ret == AVERROR_EOF ) break;
4107 if( ++errs > 100 ) {
4108 ff_err(ret,_("over 100 read_frame errs\n"));
4113 if( !pkt.data ) continue;
4114 int i = pkt.stream_index;
4115 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
4116 AVStream *st = fmt_ctx->streams[i];
4117 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
4119 AVCodecParameters *avpar = st->codecpar;
4120 switch( avpar->codec_type ) {
4121 case AVMEDIA_TYPE_VIDEO: {
4122 int vidx = ffvideo.size();
4123 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
4124 if( vidx < 0 ) break;
4125 FFVideoStream *vid = ffvideo[vidx];
4126 if( !vid->avctx ) break;
4127 int64_t tstmp = pkt.pts;
4128 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
4129 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
4130 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
4131 double secs = to_secs(tstmp, st->time_base);
4132 int64_t frm = secs * vid->frame_rate + 0.5;
4133 if( frm < 0 ) frm = 0;
4134 index_state->put_video_mark(vidx, frm, pkt.pos);
4137 ret = avcodec_send_packet(vid->avctx, pkt);
4138 if( ret < 0 ) break;
4139 while( (ret=vid->decode_frame(frame)) > 0 ) {}
4142 case AVMEDIA_TYPE_AUDIO: {
4143 int aidx = ffaudio.size();
4144 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
4145 if( aidx < 0 ) break;
4146 FFAudioStream *aud = ffaudio[aidx];
4147 if( !aud->avctx ) break;
4148 int64_t tstmp = pkt.pts;
4149 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
4150 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
4151 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
4152 double secs = to_secs(tstmp, st->time_base);
4153 int64_t sample = secs * aud->sample_rate + 0.5;
4155 index_state->put_audio_mark(aidx, sample, pkt.pos);
4157 ret = avcodec_send_packet(aud->avctx, &pkt);
4158 if( ret < 0 ) break;
4159 int ch = aud->channel0, nch = aud->channels;
4160 int64_t pos = index_state->pos(ch);
4161 if( pos != aud->curr_pos ) {
4162 if( abs(pos-aud->curr_pos) > 1 )
4163 printf("audio%d pad %jd %jd (%jd)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
4164 index_state->pad_data(ch, nch, aud->curr_pos);
4166 while( (ret=aud->decode_frame(frame)) > 0 ) {
4167 //if( frame->channels != nch ) break;
4168 aud->init_swr(frame->channels, frame->format, frame->sample_rate);
4170 int len = aud->get_samples(samples,
4171 &frame->extended_data[0], frame->nb_samples);
4172 pos = aud->curr_pos;
4173 if( (aud->curr_pos += len) >= 0 ) {
4175 samples += -pos * nch;
4176 len = aud->curr_pos;
4178 for( int i=0; i<nch; ++i )
4179 index_state->put_data(ch+i,nch,samples+i,len);
4186 av_frame_free(&frame);
4190 void FFStream::load_markers(IndexMarks &marks, double rate)
4193 int64_t sz = marks.size();
4194 int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
4195 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
4196 int nb_ent = avformat_index_get_entries_count(st);
4198 #if LIBAVCODEC_VERSION_INT <= AV_VERSION_INT(58,134,100)
4199 int nb_ent = st->nb_index_entries;
4201 // some formats already have an index
4203 #if LIBAVCODEC_VERSION_INT <= AV_VERSION_INT(58,134,100)
4204 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
4206 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
4207 const AVIndexEntry *ep = avformat_index_get_entry(st, nb_ent-1);
4209 int64_t tstmp = ep->timestamp;
4210 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
4211 double secs = ffmpeg->to_secs(tstmp, st->time_base);
4212 int64_t no = secs * rate;
4213 while( in < sz && marks[in].no <= no ) ++in;
4215 int64_t len = sz - in;
4216 int64_t count = max_entries - nb_ent;
4217 if( count > len ) count = len;
4218 for( int i=0; i<count; ++i ) {
4219 int k = in + i * len / count;
4220 int64_t no = marks[k].no, pos = marks[k].pos;
4221 double secs = (double)no / rate;
4222 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
4223 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
4224 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);
4230 * 1) if the format context has a timecode
4231 * return fmt_ctx->timecode - 0
4232 * 2) if the layer/channel has a timecode
4233 * return st->timecode - (start_time-nudge)
4234 * 3) find the 1st program with stream, find 1st program video stream,
4235 * if video stream has a timecode, return st->timecode - (start_time-nudge)
4236 * 4) find timecode in any stream, return st->timecode
4237 * 5) read 100 packets, save ofs=pkt.pts*st->time_base - st->nudge:
4238 * decode frame for video stream of 1st program
4239 * if frame->timecode has a timecode, return frame->timecode - ofs
4240 * if side_data has gop timecode, return gop->timecode - ofs
4241 * if side_data has smpte timecode, return smpte->timecode - ofs
4242 * 6) if the filename/url scans *date_time.ext, return date_time
4243 * 7) if stat works on the filename/url, return mtime
4244 * 8) return -1 failure
4246 double FFMPEG::get_initial_timecode(int data_type, int channel, double frame_rate)
4248 AVRational rate = check_frame_rate(0, frame_rate);
4249 if( !rate.num ) return -1;
4250 // format context timecode
4251 AVDictionaryEntry *tc = av_dict_get(fmt_ctx->metadata, "timecode", 0, 0);
4252 if( tc ) return ff_get_timecode(tc->value, rate, 0);
4254 if( open_decoder() ) return -1;
4257 int codec_type = -1, fidx = -1;
4258 switch( data_type ) {
4260 codec_type = AVMEDIA_TYPE_AUDIO;
4261 int aidx = astrm_index[channel].st_idx;
4262 FFAudioStream *aud = ffaudio[aidx];
4266 AVDictionaryEntry *tref = av_dict_get(fmt_ctx->metadata, "time_reference", 0, 0);
4267 if( tref && aud && aud->sample_rate )
4268 return strtod(tref->value, 0) / aud->sample_rate;
4271 codec_type = AVMEDIA_TYPE_VIDEO;
4272 int vidx = vstrm_index[channel].st_idx;
4273 FFVideoStream *vid = ffvideo[vidx];
4279 if( codec_type < 0 ) return -1;
4281 tc = av_dict_get(st->metadata, "timecode", 0, 0);
4284 // find first program which references this stream
4286 for( int i=0, m=fmt_ctx->nb_programs; pidx<0 && i<m; ++i ) {
4287 AVProgram *pgrm = fmt_ctx->programs[i];
4288 for( int j=0, n=pgrm->nb_stream_indexes; j<n; ++j ) {
4289 int st_idx = pgrm->stream_index[j];
4290 if( st_idx == fidx ) { pidx = i; break; }
4295 AVProgram *pgrm = fmt_ctx->programs[pidx];
4296 for( int j=0, n=pgrm->nb_stream_indexes; j<n; ++j ) {
4297 int st_idx = pgrm->stream_index[j];
4298 AVStream *tst = fmt_ctx->streams[st_idx];
4299 if( !tst ) continue;
4300 if( tst->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
4301 st = tst; fidx = st_idx;
4307 for( int i=0, n=fmt_ctx->nb_streams; i<n; ++i ) {
4308 AVStream *tst = fmt_ctx->streams[i];
4309 if( !tst ) continue;
4310 if( tst->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
4317 tc = av_dict_get(st->metadata, "timecode", 0, 0);
4321 // any timecode, includes -data- streams
4322 for( int i=0, n=fmt_ctx->nb_streams; i<n; ++i ) {
4323 AVStream *tst = fmt_ctx->streams[i];
4324 if( !tst ) continue;
4325 if( (tc = av_dict_get(tst->metadata, "timecode", 0, 0)) ) {
4332 if( st && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
4333 if( st->r_frame_rate.num && st->r_frame_rate.den )
4334 rate = st->r_frame_rate;
4335 nudge = st->start_time;
4336 for( int i=0; i<ffvideo.size(); ++i ) {
4337 if( ffvideo[i]->st == st ) {
4338 nudge = ffvideo[i]->nudge;
4344 if( tc ) { // return timecode
4345 double secs = st->start_time == AV_NOPTS_VALUE ? 0 :
4346 to_secs(st->start_time - nudge, st->time_base);
4347 return ff_get_timecode(tc->value, rate, secs);
4350 if( !st || fidx < 0 ) return -1;
4353 AVCodecContext *av_ctx = activate_decoder(st);
4355 fprintf(stderr,"activate_decoder failed\n");
4358 avCodecContext avctx(av_ctx); // auto deletes
4359 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO &&
4360 avctx->framerate.num && avctx->framerate.den )
4361 rate = avctx->framerate;
4363 avPacket pkt; // auto deletes
4364 avFrame frame; // auto deletes
4366 fprintf(stderr,"av_frame_alloc failed\n");
4370 int64_t max_packets = 100;
4371 char tcbuf[AV_TIMECODE_STR_SIZE];
4373 for( int64_t count=0; count<max_packets; ++count ) {
4374 av_packet_unref(pkt);
4375 pkt->data = 0; pkt->size = 0;
4377 int ret = av_read_frame(fmt_ctx, pkt);
4379 if( ret == AVERROR_EOF ) break;
4380 if( ++errs > 100 ) {
4381 fprintf(stderr,"over 100 read_frame errs\n");
4386 if( !pkt->data ) continue;
4387 int i = pkt->stream_index;
4388 if( i != fidx ) continue;
4389 int64_t tstmp = pkt->pts;
4390 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt->dts;
4391 double secs = to_secs(tstmp - nudge, st->time_base);
4392 ret = avcodec_send_packet(avctx, pkt);
4393 if( ret < 0 ) return -1;
4395 while( (ret = avcodec_receive_frame(avctx, frame)) >= 0 ) {
4396 if( (tc = av_dict_get(frame->metadata, "timecode", 0, 0)) )
4397 return ff_get_timecode(tc->value, rate, secs);
4398 int k = frame->nb_side_data;
4399 AVFrameSideData *side_data = 0;
4401 side_data = frame->side_data[k];
4402 switch( side_data->type ) {
4403 case AV_FRAME_DATA_GOP_TIMECODE: {
4404 int64_t data = *(int64_t *)side_data->data;
4405 int sz = sizeof(data);
4406 if( side_data->size >= sz ) {
4407 av_timecode_make_mpeg_tc_string(tcbuf, data);
4408 return ff_get_timecode(tcbuf, rate, secs);
4411 case AV_FRAME_DATA_S12M_TIMECODE: {
4412 uint32_t *data = (uint32_t *)side_data->data;
4413 int n = data[0], sz = (n+1)*sizeof(*data);
4414 if( side_data->size >= sz ) {
4415 av_timecode_make_smpte_tc_string(tcbuf, data[n], 0);
4416 return ff_get_timecode(tcbuf, rate, secs);
4425 char *path = fmt_ctx->url;
4426 char *bp = strrchr(path, '/');
4427 if( !bp ) bp = path; else ++bp;
4428 char *cp = strrchr(bp, '.');
4429 if( cp && (cp-=(8+1+6)) >= bp ) {
4431 int year,mon,day, hour,min,sec, frm=0;
4432 if( sscanf(cp,"%4d%2d%2d%[_-]%2d%2d%2d",
4433 &year,&mon,&day, sep, &hour,&min,&sec) == 7 ) {
4435 // year>=1970,mon=1..12,day=1..31, hour=0..23,min=0..59,sec=0..60
4436 if( (ch=='_' || ch=='-' ) &&
4437 year >= 1970 && mon>=1 && mon<=12 && day>=1 && day<=31 &&
4438 hour>=0 && hour<24 && min>=0 && min<60 && sec>=0 && sec<=60 ) {
4439 sprintf(tcbuf,"%d:%02d:%02d:%02d", hour,min,sec, frm);
4440 return ff_get_timecode(tcbuf, rate, 0);
4445 if( stat(path, &tst) >= 0 ) {
4446 time_t t = (time_t)tst.st_mtim.tv_sec;
4448 localtime_r(&t, &tm);
4449 int64_t us = tst.st_mtim.tv_nsec / 1000;
4450 int frm = us/1000000. * frame_rate;
4451 sprintf(tcbuf,"%d:%02d:%02d:%02d", tm.tm_hour, tm.tm_min, tm.tm_sec, frm);
4452 return ff_get_timecode(tcbuf, rate, 0);
4457 double FFMPEG::ff_get_timecode(char *str, AVRational rate, double pos)
4460 if( av_timecode_init_from_string(&tc, rate, str, fmt_ctx) )
4462 double secs = (double)tc.start / tc.fps - pos;
4463 if( secs < 0 ) secs = 0;
4467 double FFMPEG::get_timecode(const char *path, int data_type, int channel, double rate)
4470 if( ffmpeg.init_decoder(path) ) return -1;
4471 return ffmpeg.get_initial_timecode(data_type, channel, rate);