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 || ret == AVERROR(EAGAIN) )) return pkts;
645 //if( ret < 0 ) break;
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);
2548 AVRational sar = av_guess_sample_aspect_ratio(fmt_ctx, st, NULL);
2549 AVRational display_aspect_ratio;
2552 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
2553 st->codecpar->width * (int64_t)sar.num,
2554 st->codecpar->height * (int64_t)sar.den,
2556 /* report(" Guessed SAR: %d:%d, ", sar.num, sar.den );
2557 report("DAR: %d:%d \n", display_aspect_ratio.num, display_aspect_ratio.den); */
2559 if (st->sample_aspect_ratio.num)
2561 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
2562 st->codecpar->width * (int64_t)st->sample_aspect_ratio.num,
2563 st->codecpar->height * (int64_t)st->sample_aspect_ratio.den,
2565 report(" container Detected SAR: %d:%d , DAR %d:%d \n", st->sample_aspect_ratio.num, st->sample_aspect_ratio.den, display_aspect_ratio.num, display_aspect_ratio.den);
2567 if (st->codecpar->sample_aspect_ratio.num)
2569 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
2570 st->codecpar->width * (int64_t)st->codecpar->sample_aspect_ratio.num,
2571 st->codecpar->height * (int64_t)st->codecpar->sample_aspect_ratio.den,
2573 report(" codec Detected SAR: %d:%d , DAR %d:%d \n", st->codecpar->sample_aspect_ratio.num, st->codecpar->sample_aspect_ratio.den, display_aspect_ratio.num, display_aspect_ratio.den);
2575 double secs = to_secs(st->duration, st->time_base);
2576 int64_t length = secs * vid->frame_rate + 0.5;
2577 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
2578 int64_t nudge = ofs * vid->frame_rate;
2579 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
2580 report(" %jd%c%jd frms %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);
2584 double theta = vid->get_rotation_angle();
2585 if( fabs(theta) > 1 )
2586 report(" rotation angle: %0.1f\n", theta);
2588 if( ffaudio.size() > 0 )
2589 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
2590 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2591 FFAudioStream *aud = ffaudio[aidx];
2592 AVStream *st = aud->st;
2593 AVCodecID codec_id = st->codecpar->codec_id;
2594 report(_("aud%d (%d), id 0x%06x:\n"), aud->idx, aud->fidx, codec_id);
2595 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
2596 int nch = aud->channels, ch0 = aud->channel0+1;
2597 report(" audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
2598 AVSampleFormat sample_fmt = (AVSampleFormat)st->codecpar->format;
2599 const char *fmt = av_get_sample_fmt_name(sample_fmt);
2600 report(" %s %d", fmt, aud->sample_rate);
2601 int sample_bits = av_get_bits_per_sample(codec_id);
2602 report(" %dbits\n", sample_bits);
2603 double secs = to_secs(st->duration, st->time_base);
2604 int64_t length = secs * aud->sample_rate + 0.5;
2605 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
2606 int64_t nudge = ofs * aud->sample_rate;
2607 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
2608 report(" %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
2609 int hrs = secs/3600; secs -= hrs*3600;
2610 int mins = secs/60; secs -= mins*60;
2611 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
2613 if( fmt_ctx->nb_programs > 0 )
2614 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
2615 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
2616 report("program %d", i+1);
2617 AVProgram *pgrm = fmt_ctx->programs[i];
2618 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2619 int idx = pgrm->stream_index[j];
2620 int vidx = ffvideo.size();
2621 while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
2623 report(", vid%d", vidx);
2626 int aidx = ffaudio.size();
2627 while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
2629 report(", aud%d", aidx);
2632 report(", (%d)", pgrm->stream_index[j]);
2637 AVDictionaryEntry *tag = 0;
2638 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
2639 report("%s=%s\n", tag->key, tag->value);
2648 int FFMPEG::init_decoder(const char *filename)
2650 ff_lock("FFMPEG::init_decoder");
2652 char file_opts[BCTEXTLEN];
2653 strcpy(file_opts, filename);
2654 char *bp = strrchr(file_opts, '/');
2655 if( !bp ) bp = file_opts;
2656 char *sp = strrchr(bp, '.');
2657 if( !sp ) sp = bp + strlen(bp);
2659 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,18,100)
2660 const AVInputFormat *ifmt = 0;
2662 AVInputFormat *ifmt = 0;
2665 strcpy(sp, ".opts");
2666 fp = fopen(file_opts, "r");
2669 read_options(fp, file_opts, opts);
2671 AVDictionaryEntry *tag;
2672 if( (tag=av_dict_get(opts, "format", NULL, 0)) != 0 ) {
2673 ifmt = av_find_input_format(tag->value);
2677 load_options("decode.opts", opts);
2678 AVDictionary *fopts = 0;
2679 av_dict_copy(&fopts, opts, 0);
2680 int ret = avformat_open_input(&fmt_ctx, filename, ifmt, &fopts);
2681 av_dict_free(&fopts);
2683 ret = avformat_find_stream_info(fmt_ctx, NULL);
2688 return !ret ? 0 : 1;
2691 int FFMPEG::open_decoder()
2694 if( stat(fmt_ctx->url, &st) < 0 ) {
2695 eprintf(_("can't stat file: %s\n"), fmt_ctx->url);
2699 int64_t file_bits = 8 * st.st_size;
2700 if( !fmt_ctx->bit_rate && opt_duration > 0 )
2701 fmt_ctx->bit_rate = file_bits / opt_duration;
2704 if( fmt_ctx->bit_rate > 0 ) {
2705 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2706 AVStream *st = fmt_ctx->streams[i];
2707 if( st->duration != AV_NOPTS_VALUE ) continue;
2708 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
2709 st->duration = av_rescale(file_bits, st->time_base.den,
2710 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
2714 if( estimated && !(fflags & FF_ESTM_TIMES) ) {
2715 fflags |= FF_ESTM_TIMES;
2716 printf("FFMPEG::open_decoder: some stream times estimated: %s\n",
2720 ff_lock("FFMPEG::open_decoder");
2721 int ret = 0, bad_time = 0;
2722 for( int i=0; !ret && i<(int)fmt_ctx->nb_streams; ++i ) {
2723 AVStream *st = fmt_ctx->streams[i];
2724 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
2725 AVCodecParameters *avpar = st->codecpar;
2726 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avpar->codec_id);
2727 if( !codec_desc ) continue;
2728 switch( avpar->codec_type ) {
2729 case AVMEDIA_TYPE_VIDEO: {
2730 if( avpar->width < 1 ) continue;
2731 if( avpar->height < 1 ) continue;
2732 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
2733 if( framerate.num < 1 ) continue;
2735 int vidx = ffvideo.size();
2736 FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
2737 vstrm_index.append(ffidx(vidx, 0));
2738 ffvideo.append(vid);
2739 vid->width = avpar->width;
2740 vid->height = avpar->height;
2741 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
2742 switch( avpar->color_range ) {
2743 case AVCOL_RANGE_MPEG:
2744 vid->color_range = BC_COLORS_MPEG;
2746 case AVCOL_RANGE_JPEG:
2747 vid->color_range = BC_COLORS_JPEG;
2750 vid->color_range = !file_base ? BC_COLORS_JPEG :
2751 file_base->file->preferences->yuv_color_range;
2754 switch( avpar->color_space ) {
2755 case AVCOL_SPC_BT470BG:
2756 vid->color_space = BC_COLORS_BT601_PAL;
2758 case AVCOL_SPC_SMPTE170M:
2759 vid->color_space = BC_COLORS_BT601_NTSC;
2761 case AVCOL_SPC_BT709:
2762 vid->color_space = BC_COLORS_BT709;
2764 case AVCOL_SPC_BT2020_NCL:
2765 vid->color_space = BC_COLORS_BT2020_NCL;
2767 case AVCOL_SPC_BT2020_CL:
2768 vid->color_space = BC_COLORS_BT2020_CL;
2771 vid->color_space = !file_base ? BC_COLORS_BT601_NTSC :
2772 file_base->file->preferences->yuv_color_space;
2775 double secs = to_secs(st->duration, st->time_base);
2776 vid->length = secs * vid->frame_rate;
2777 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
2778 vid->nudge = st->start_time;
2780 ret = vid->create_filter(opt_video_filter);
2782 case AVMEDIA_TYPE_AUDIO: {
2783 if( avpar->channels < 1 ) continue;
2784 if( avpar->sample_rate < 1 ) continue;
2786 int aidx = ffaudio.size();
2787 FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
2788 ffaudio.append(aud);
2789 aud->channel0 = astrm_index.size();
2790 aud->channels = avpar->channels;
2791 for( int ch=0; ch<aud->channels; ++ch )
2792 astrm_index.append(ffidx(aidx, ch));
2793 aud->sample_rate = avpar->sample_rate;
2794 double secs = to_secs(st->duration, st->time_base);
2795 aud->length = secs * aud->sample_rate;
2796 aud->init_swr(aud->channels, avpar->format, aud->sample_rate);
2797 aud->nudge = st->start_time;
2799 ret = aud->create_filter(opt_audio_filter);
2804 if( bad_time && !(fflags & FF_BAD_TIMES) ) {
2805 fflags |= FF_BAD_TIMES;
2806 printf(_("FFMPEG::open_decoder: some stream have bad times: %s\n"),
2810 return ret < 0 ? -1 : 0;
2814 int FFMPEG::init_encoder(const char *filename)
2816 // try access first for named pipes
2817 int ret = access(filename, W_OK);
2819 int fd = ::open(filename,O_WRONLY);
2820 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
2821 if( fd >= 0 ) { close(fd); ret = 0; }
2824 eprintf(_("bad file path: %s\n"), filename);
2827 ret = get_file_format();
2829 eprintf(_("bad file format: %s\n"), filename);
2833 eprintf(_("mismatch audio/video file format: %s\n"), filename);
2836 ff_lock("FFMPEG::init_encoder");
2838 char format[BCSTRLEN];
2839 if( get_format(format, "format", file_format) )
2840 strcpy(format, file_format);
2841 avformat_alloc_output_context2(&fmt_ctx, 0, format, filename);
2843 eprintf(_("failed: %s\n"), filename);
2848 load_options("encode.opts", opts);
2854 int FFMPEG::open_encoder(const char *type, const char *spec)
2857 Asset *asset = file_base->asset;
2858 char *filename = asset->path;
2859 AVDictionary *sopts = 0;
2860 av_dict_copy(&sopts, opts, 0);
2861 char option_path[BCTEXTLEN];
2862 set_option_path(option_path, "%s/%s.opts", type, type);
2863 read_options(option_path, sopts);
2864 get_option_path(option_path, type, spec);
2865 char format_name[BCSTRLEN], codec_name[BCTEXTLEN], bsfilter[BCTEXTLEN];
2866 if( get_encoder(option_path, format_name, codec_name, bsfilter) ) {
2867 eprintf(_("get_encoder failed %s:%s\n"), option_path, filename);
2872 if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
2874 else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
2875 else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
2878 ff_lock("FFMPEG::open_encoder");
2881 AVCodecContext *ctx = 0;
2883 const AVCodecDescriptor *codec_desc = 0;
2884 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
2885 const AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
2887 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
2890 eprintf(_("cant find codec %s:%s\n"), codec_name, filename);
2894 codec_desc = avcodec_descriptor_get(codec->id);
2896 eprintf(_("unknown codec %s:%s\n"), codec_name, filename);
2901 st = avformat_new_stream(fmt_ctx, 0);
2903 eprintf(_("cant create stream %s:%s\n"), codec_name, filename);
2908 switch( codec_desc->type ) {
2909 case AVMEDIA_TYPE_AUDIO: {
2911 eprintf(_("duplicate audio %s:%s\n"), codec_name, filename);
2915 if( scan_options(asset->ff_audio_options, sopts, st) ) {
2916 eprintf(_("bad audio options %s:%s\n"), codec_name, filename);
2921 ctx = avcodec_alloc_context3(codec);
2922 if( asset->ff_audio_bitrate > 0 ) {
2923 ctx->bit_rate = asset->ff_audio_bitrate;
2925 sprintf(arg, "%d", asset->ff_audio_bitrate);
2926 av_dict_set(&sopts, "b", arg, 0);
2928 else if( asset->ff_audio_quality >= 0 ) {
2929 ctx->global_quality = asset->ff_audio_quality * FF_QP2LAMBDA;
2930 ctx->qmin = ctx->qmax = asset->ff_audio_quality;
2931 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2932 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2933 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2935 av_dict_set(&sopts, "flags", "+qscale", 0);
2936 sprintf(arg, "%d", asset->ff_audio_quality);
2937 av_dict_set(&sopts, "qscale", arg, 0);
2938 sprintf(arg, "%d", ctx->global_quality);
2939 av_dict_set(&sopts, "global_quality", arg, 0);
2941 int aidx = ffaudio.size();
2942 int fidx = aidx + ffvideo.size();
2943 FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
2944 aud->avctx = ctx; ffaudio.append(aud); fst = aud;
2945 aud->sample_rate = asset->sample_rate;
2946 ctx->channels = aud->channels = asset->channels;
2947 for( int ch=0; ch<aud->channels; ++ch )
2948 astrm_index.append(ffidx(aidx, ch));
2949 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
2950 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
2951 if( !ctx->sample_rate ) {
2952 eprintf(_("check_sample_rate failed %s\n"), filename);
2956 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
2957 AVSampleFormat sample_fmt = av_get_sample_fmt(asset->ff_sample_format);
2958 if( sample_fmt == AV_SAMPLE_FMT_NONE )
2959 sample_fmt = codec->sample_fmts ? codec->sample_fmts[0] : AV_SAMPLE_FMT_S16;
2960 ctx->sample_fmt = sample_fmt;
2961 uint64_t layout = av_get_default_channel_layout(ctx->channels);
2962 aud->resample_context = swr_alloc_set_opts(NULL,
2963 layout, ctx->sample_fmt, aud->sample_rate,
2964 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
2966 swr_init(aud->resample_context);
2969 case AVMEDIA_TYPE_VIDEO: {
2971 eprintf(_("duplicate video %s:%s\n"), codec_name, filename);
2975 if( scan_options(asset->ff_video_options, sopts, st) ) {
2976 eprintf(_("bad video options %s:%s\n"), codec_name, filename);
2981 ctx = avcodec_alloc_context3(codec);
2982 if( asset->ff_video_bitrate > 0 ) {
2983 ctx->bit_rate = asset->ff_video_bitrate;
2985 sprintf(arg, "%d", asset->ff_video_bitrate);
2986 av_dict_set(&sopts, "b", arg, 0);
2988 else if( asset->ff_video_quality >= 0 ) {
2989 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
2990 ctx->qmin = ctx->qmax = asset->ff_video_quality;
2991 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2992 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2993 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2995 av_dict_set(&sopts, "flags", "+qscale", 0);
2996 sprintf(arg, "%d", asset->ff_video_quality);
2997 av_dict_set(&sopts, "qscale", arg, 0);
2998 sprintf(arg, "%d", ctx->global_quality);
2999 av_dict_set(&sopts, "global_quality", arg, 0);
3001 int vidx = ffvideo.size();
3002 int fidx = vidx + ffaudio.size();
3003 FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
3004 vstrm_index.append(ffidx(vidx, 0));
3005 vid->avctx = ctx; ffvideo.append(vid); fst = vid;
3006 vid->width = asset->width;
3007 vid->height = asset->height;
3008 vid->frame_rate = asset->frame_rate;
3010 char tc_str[20] = "00:00:00:00";
3012 if(asset->timecode > 0)
3013 Units::totext(tc_str, asset->timecode, TIME_HMSF, 0, asset->frame_rate, 0);
3014 //printf("tc: %s \n", tc_str);
3015 av_dict_set(&st->metadata, "timecode", tc_str, 0);
3017 if( (vid->color_range = asset->ff_color_range) < 0 )
3018 vid->color_range = file_base->file->preferences->yuv_color_range;
3019 switch( vid->color_range ) {
3020 case BC_COLORS_MPEG: ctx->color_range = AVCOL_RANGE_MPEG; break;
3021 case BC_COLORS_JPEG: ctx->color_range = AVCOL_RANGE_JPEG; break;
3023 if( (vid->color_space = asset->ff_color_space) < 0 )
3024 vid->color_space = file_base->file->preferences->yuv_color_space;
3025 switch( vid->color_space ) {
3026 case BC_COLORS_BT601_NTSC: ctx->colorspace = AVCOL_SPC_SMPTE170M; break;
3027 case BC_COLORS_BT601_PAL: ctx->colorspace = AVCOL_SPC_BT470BG; break;
3028 case BC_COLORS_BT709: ctx->colorspace = AVCOL_SPC_BT709; break;
3029 case BC_COLORS_BT2020_NCL: ctx->colorspace = AVCOL_SPC_BT2020_NCL; break;
3030 case BC_COLORS_BT2020_CL: ctx->colorspace = AVCOL_SPC_BT2020_CL; break;
3032 AVPixelFormat pix_fmt = av_get_pix_fmt(asset->ff_pixel_format);
3033 if( opt_hw_dev != 0 ) {
3034 AVHWDeviceType hw_type = vid->encode_hw_activate(opt_hw_dev);
3036 case AV_HWDEVICE_TYPE_VAAPI:
3037 pix_fmt = AV_PIX_FMT_VAAPI;
3039 case AV_HWDEVICE_TYPE_NONE:
3043 if( pix_fmt == AV_PIX_FMT_NONE )
3044 pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
3045 ctx->pix_fmt = pix_fmt;
3047 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
3048 int mask_w = (1<<desc->log2_chroma_w)-1;
3049 ctx->width = (vid->width+mask_w) & ~mask_w;
3050 int mask_h = (1<<desc->log2_chroma_h)-1;
3051 ctx->height = (vid->height+mask_h) & ~mask_h;
3052 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
3053 AVRational frame_rate;
3054 if (ctx->codec->id == AV_CODEC_ID_MPEG1VIDEO ||
3055 ctx->codec->id == AV_CODEC_ID_MPEG2VIDEO)
3056 frame_rate = check_frame_rate(codec->supported_framerates, vid->frame_rate);
3058 frame_rate = av_d2q(vid->frame_rate, INT_MAX);
3059 if( !frame_rate.num || !frame_rate.den ) {
3060 eprintf(_("check_frame_rate failed %s\n"), filename);
3064 av_reduce(&frame_rate.num, &frame_rate.den,
3065 frame_rate.num, frame_rate.den, INT_MAX);
3066 ctx->framerate = (AVRational) { frame_rate.num, frame_rate.den };
3067 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
3068 if(!strcmp(format_name, "webm") || !strcmp(format_name, "matroska") || !strcmp(format_name, "mov") ||
3069 !strcmp(format_name, "qt") || !strcmp(format_name, "mp4") || !strcmp(format_name, "avi") ||
3070 !strcmp(format_name, "dv") || !strcmp(format_name, "yuv4mpegpipe"))
3072 if (to_sample_aspect_ratio(asset).den > 0)
3073 st->sample_aspect_ratio = to_sample_aspect_ratio(asset);
3075 st->avg_frame_rate = frame_rate;
3076 st->time_base = ctx->time_base;
3078 vid->interlaced = asset->interlace_mode == ILACE_MODE_TOP_FIRST ||
3079 asset->interlace_mode == ILACE_MODE_BOTTOM_FIRST ? 1 : 0;
3080 vid->top_field_first = asset->interlace_mode == ILACE_MODE_TOP_FIRST ? 1 : 0;
3081 switch (asset->interlace_mode) {
3082 case ILACE_MODE_TOP_FIRST:
3083 if (ctx->codec->id == AV_CODEC_ID_MJPEG)
3084 av_dict_set(&sopts, "field_order", "tt", 0);
3086 av_dict_set(&sopts, "field_order", "tb", 0);
3087 if (ctx->codec_id != AV_CODEC_ID_MJPEG)
3088 av_dict_set(&sopts, "flags", "+ilme+ildct", 0);
3090 case ILACE_MODE_BOTTOM_FIRST:
3091 if (ctx->codec->id == AV_CODEC_ID_MJPEG)
3092 av_dict_set(&sopts, "field_order", "bb", 0);
3094 av_dict_set(&sopts, "field_order", "bt", 0);
3095 if (ctx->codec_id != AV_CODEC_ID_MJPEG)
3096 av_dict_set(&sopts, "flags", "+ilme+ildct", 0);
3098 case ILACE_MODE_NOTINTERLACED: av_dict_set(&sopts, "field_order", "progressive", 0); break;
3102 eprintf(_("not audio/video, %s:%s\n"), codec_name, filename);
3107 AVDictionaryEntry *tag;
3108 if( (tag=av_dict_get(sopts, "cin_stats_filename", NULL, 0)) != 0 ) {
3109 char suffix[BCSTRLEN]; sprintf(suffix,"-%d.log",fst->fidx);
3110 fst->stats_filename = cstrcat(2, tag->value, suffix);
3112 if( (tag=av_dict_get(sopts, "flags", NULL, 0)) != 0 ) {
3113 int pass = fst->pass;
3114 char *cp = tag->value;
3116 int ch = *cp++, pfx = ch=='-' ? -1 : ch=='+' ? 1 : 0;
3117 if( !isalnum(!pfx ? ch : (ch=*cp++)) ) continue;
3118 char id[BCSTRLEN], *bp = id, *ep = bp+sizeof(id)-1;
3119 for( *bp++=ch; isalnum(ch=*cp); ++cp )
3120 if( bp < ep ) *bp++ = ch;
3122 if( !strcmp(id, "pass1") ) {
3123 pass = pfx<0 ? (pass&~1) : pfx>0 ? (pass|1) : 1;
3125 else if( !strcmp(id, "pass2") ) {
3126 pass = pfx<0 ? (pass&~2) : pfx>0 ? (pass|2) : 2;
3129 if( (fst->pass=pass) ) {
3130 if( pass & 1 ) ctx->flags |= AV_CODEC_FLAG_PASS1;
3131 if( pass & 2 ) ctx->flags |= AV_CODEC_FLAG_PASS2;
3137 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
3138 ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
3139 if( fst->stats_filename && (ret=fst->init_stats_file()) )
3140 eprintf(_("error: stats file = %s\n"), fst->stats_filename);
3143 av_dict_set(&sopts, "cin_bitrate", 0, 0);
3144 av_dict_set(&sopts, "cin_quality", 0, 0);
3146 if( !av_dict_get(sopts, "threads", NULL, 0) )
3147 ctx->thread_count = ff_cpus();
3148 ret = avcodec_open2(ctx, codec, &sopts);
3150 ret = avcodec_parameters_from_context(st->codecpar, ctx);
3152 fprintf(stderr, "Could not copy the stream parameters\n");
3155 _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
3156 #if LIBAVCODEC_VERSION_INT <= AV_VERSION_INT(58,134,100)
3157 ret = avcodec_copy_context(st->codec, ctx);
3159 ret = avcodec_parameters_to_context(ctx, st->codecpar);
3161 _Pragma("GCC diagnostic warning \"-Wdeprecated-declarations\"")
3163 fprintf(stderr, "Could not copy the stream context\n");
3166 ff_err(ret,"FFMPEG::open_encoder");
3167 eprintf(_("open failed %s:%s\n"), codec_name, filename);
3173 if( !ret && fst && bsfilter[0] ) {
3174 ret = av_bsf_list_parse_str(bsfilter, &fst->bsfc);
3176 ff_err(ret,"FFMPEG::open_encoder");
3177 eprintf(_("bitstream filter failed %s:\n%s\n"), filename, bsfilter);
3188 av_dict_free(&sopts);
3192 int FFMPEG::close_encoder()
3195 if( encoding > 0 ) {
3196 av_write_trailer(fmt_ctx);
3197 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
3198 avio_closep(&fmt_ctx->pb);
3204 int FFMPEG::decode_activate()
3206 if( decoding < 0 ) {
3208 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
3209 ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
3210 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
3211 ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
3212 // set nudges for each program stream set
3213 const int64_t min_nudge = INT64_MIN+1;
3214 int npgrms = fmt_ctx->nb_programs;
3215 for( int i=0; i<npgrms; ++i ) {
3216 AVProgram *pgrm = fmt_ctx->programs[i];
3217 // first start time video stream
3218 int64_t vstart_time = min_nudge, astart_time = min_nudge;
3219 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
3220 int fidx = pgrm->stream_index[j];
3221 AVStream *st = fmt_ctx->streams[fidx];
3222 AVCodecParameters *avpar = st->codecpar;
3223 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
3224 if( st->start_time == AV_NOPTS_VALUE ) continue;
3225 if( vstart_time < st->start_time )
3226 vstart_time = st->start_time;
3229 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
3230 if( st->start_time == AV_NOPTS_VALUE ) continue;
3231 if( astart_time < st->start_time )
3232 astart_time = st->start_time;
3236 //since frame rate is much more grainy than sample rate, it is better to
3237 // align using video, so that total absolute error is minimized.
3238 int64_t nudge = vstart_time > min_nudge ? vstart_time :
3239 astart_time > min_nudge ? astart_time : AV_NOPTS_VALUE;
3240 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
3241 int fidx = pgrm->stream_index[j];
3242 AVStream *st = fmt_ctx->streams[fidx];
3243 AVCodecParameters *avpar = st->codecpar;
3244 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
3245 for( int k=0; k<ffvideo.size(); ++k ) {
3246 if( ffvideo[k]->fidx != fidx ) continue;
3247 ffvideo[k]->nudge = nudge;
3251 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
3252 for( int k=0; k<ffaudio.size(); ++k ) {
3253 if( ffaudio[k]->fidx != fidx ) continue;
3254 ffaudio[k]->nudge = nudge;
3260 // set nudges for any streams not yet set
3261 int64_t vstart_time = min_nudge, astart_time = min_nudge;
3262 int nstreams = fmt_ctx->nb_streams;
3263 for( int i=0; i<nstreams; ++i ) {
3264 AVStream *st = fmt_ctx->streams[i];
3265 AVCodecParameters *avpar = st->codecpar;
3266 switch( avpar->codec_type ) {
3267 case AVMEDIA_TYPE_VIDEO: {
3268 if( st->start_time == AV_NOPTS_VALUE ) continue;
3269 int vidx = ffvideo.size();
3270 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
3271 if( vidx < 0 ) continue;
3272 if( ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
3273 if( vstart_time < st->start_time )
3274 vstart_time = st->start_time;
3276 case AVMEDIA_TYPE_AUDIO: {
3277 if( st->start_time == AV_NOPTS_VALUE ) continue;
3278 int aidx = ffaudio.size();
3279 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
3280 if( aidx < 0 ) continue;
3281 if( ffaudio[aidx]->frame_sz < avpar->frame_size )
3282 ffaudio[aidx]->frame_sz = avpar->frame_size;
3283 if( ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
3284 if( astart_time < st->start_time )
3285 astart_time = st->start_time;
3290 int64_t nudge = vstart_time > min_nudge ? vstart_time :
3291 astart_time > min_nudge ? astart_time : 0;
3292 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
3293 if( ffvideo[vidx]->nudge == AV_NOPTS_VALUE )
3294 ffvideo[vidx]->nudge = nudge;
3296 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
3297 if( ffaudio[aidx]->nudge == AV_NOPTS_VALUE )
3298 ffaudio[aidx]->nudge = nudge;
3305 int FFMPEG::encode_activate()
3308 if( encoding < 0 ) {
3310 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
3311 (ret=avio_open(&fmt_ctx->pb, fmt_ctx->url, AVIO_FLAG_WRITE)) < 0 ) {
3312 ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
3316 if( !strcmp(file_format, "image2") ) {
3317 Asset *asset = file_base->asset;
3318 const char *filename = asset->path;
3319 FILE *fp = fopen(filename,"w");
3321 eprintf(_("Cant write image2 header file: %s\n %m"), filename);
3324 fprintf(fp, "IMAGE2\n");
3325 fprintf(fp, "# Frame rate: %f\n", asset->frame_rate);
3326 fprintf(fp, "# Width: %d\n", asset->width);
3327 fprintf(fp, "# Height: %d\n", asset->height);
3331 AVProgram *prog = av_new_program(fmt_ctx, prog_id);
3332 for( int i=0; i< ffvideo.size(); ++i )
3333 av_program_add_stream_index(fmt_ctx, prog_id, ffvideo[i]->fidx);
3334 for( int i=0; i< ffaudio.size(); ++i )
3335 av_program_add_stream_index(fmt_ctx, prog_id, ffaudio[i]->fidx);
3336 int pi = fmt_ctx->nb_programs;
3337 while( --pi >= 0 && fmt_ctx->programs[pi]->id != prog_id );
3338 AVDictionary **meta = &prog->metadata;
3339 av_dict_set(meta, "service_provider", "cin5", 0);
3340 const char *path = fmt_ctx->url, *bp = strrchr(path,'/');
3341 if( bp ) path = bp + 1;
3342 av_dict_set(meta, "title", path, 0);
3344 if( ffaudio.size() ) {
3345 const char *ep = getenv("CIN_AUDIO_LANG"), *lp = 0;
3346 if( !ep && (lp=getenv("LANG")) ) { // some are guesses
3347 static struct { const char lc[3], lng[4]; } lcode[] = {
3348 { "en", "eng" }, { "de", "ger" }, { "es", "spa" },
3349 { "eu", "bas" }, { "fr", "fre" }, { "el", "gre" },
3350 { "hi", "hin" }, { "it", "ita" }, { "ja", "jap" },
3351 { "ko", "kor" }, { "du", "dut" }, { "pl", "pol" },
3352 { "pt", "por" }, { "ru", "rus" }, { "sl", "slv" },
3353 { "uk", "ukr" }, { "vi", "vie" }, { "zh", "chi" },
3355 for( int i=sizeof(lcode)/sizeof(lcode[0]); --i>=0 && !ep; )
3356 if( !strncmp(lcode[i].lc,lp,2) ) ep = lcode[i].lng;
3358 if( !ep ) ep = "und";
3360 strncpy(lang,ep,3); lang[3] = 0;
3361 AVStream *st = ffaudio[0]->st;
3362 av_dict_set(&st->metadata,"language",lang,0);
3365 AVDictionary *fopts = 0;
3366 char option_path[BCTEXTLEN];
3367 set_option_path(option_path, "format/%s", file_format);
3368 read_options(option_path, fopts, 1);
3369 av_dict_copy(&fopts, opts, 0);
3370 if( scan_options(file_base->asset->ff_format_options, fopts, 0) ) {
3371 eprintf(_("bad format options %s\n"), file_base->asset->path);
3375 ret = avformat_write_header(fmt_ctx, &fopts);
3377 ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
3381 av_dict_free(&fopts);
3388 int FFMPEG::audio_seek(int stream, int64_t pos)
3390 int aidx = astrm_index[stream].st_idx;
3391 FFAudioStream *aud = ffaudio[aidx];
3392 aud->audio_seek(pos);
3396 int FFMPEG::video_probe(int64_t pos)
3398 int vidx = vstrm_index[0].st_idx;
3399 FFVideoStream *vid = ffvideo[vidx];
3402 int interlace1 = interlace_from_codec;
3403 //printf("interlace from codec: %i\n", interlace1);
3409 return ILACE_MODE_TOP_FIRST;
3412 return ILACE_MODE_BOTTOM_FIRST;
3413 case AV_FIELD_PROGRESSIVE:
3414 return ILACE_MODE_NOTINTERLACED;
3416 return ILACE_MODE_UNDETECTED;
3423 int FFMPEG::video_seek(int stream, int64_t pos)
3425 int vidx = vstrm_index[stream].st_idx;
3426 FFVideoStream *vid = ffvideo[vidx];
3427 vid->video_seek(pos);
3432 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
3434 if( !has_audio || chn >= astrm_index.size() ) return -1;
3435 int aidx = astrm_index[chn].st_idx;
3436 FFAudioStream *aud = ffaudio[aidx];
3437 if( aud->load(pos, len) < len ) return -1;
3438 int ch = astrm_index[chn].st_ch;
3439 int ret = aud->read(samples,len,ch);
3443 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
3445 if( !has_video || layer >= vstrm_index.size() ) return -1;
3446 int vidx = vstrm_index[layer].st_idx;
3447 FFVideoStream *vid = ffvideo[vidx];
3448 return vid->load(vframe, pos);
3452 int FFMPEG::encode(int stream, double **samples, int len)
3454 FFAudioStream *aud = ffaudio[stream];
3455 return aud->encode(samples, len);
3459 int FFMPEG::encode(int stream, VFrame *frame)
3461 FFVideoStream *vid = ffvideo[stream];
3462 return vid->encode(frame);
3465 void FFMPEG::start_muxer()
3473 void FFMPEG::stop_muxer()
3482 void FFMPEG::flow_off()
3485 flow_lock->lock("FFMPEG::flow_off");
3489 void FFMPEG::flow_on()
3493 flow_lock->unlock();
3496 void FFMPEG::flow_ctl()
3499 flow_lock->lock("FFMPEG::flow_ctl");
3500 flow_lock->unlock();
3504 int FFMPEG::mux_audio(FFrame *frm)
3506 FFStream *fst = frm->fst;
3507 AVCodecContext *ctx = fst->avctx;
3508 AVFrame *frame = *frm;
3509 AVRational tick_rate = {1, ctx->sample_rate};
3510 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
3511 int ret = fst->encode_frame(frame);
3513 ff_err(ret, "FFMPEG::mux_audio");
3514 return ret >= 0 ? 0 : 1;
3517 int FFMPEG::mux_video(FFrame *frm)
3519 FFStream *fst = frm->fst;
3520 AVFrame *frame = *frm;
3521 frame->pts = frm->position;
3522 int ret = fst->encode_frame(frame);
3524 ff_err(ret, "FFMPEG::mux_video");
3525 return ret >= 0 ? 0 : 1;
3531 double atm = -1, vtm = -1;
3532 FFrame *afrm = 0, *vfrm = 0;
3534 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
3535 FFStream *fst = ffaudio[i];
3536 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
3537 FFrame *frm = fst->frms.first;
3538 if( !frm ) { if( !done ) return; continue; }
3539 double tm = to_secs(frm->position, fst->avctx->time_base);
3540 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
3542 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
3543 FFStream *fst = ffvideo[i];
3544 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
3545 FFrame *frm = fst->frms.first;
3546 if( !frm ) { if( !done ) return; continue; }
3547 double tm = to_secs(frm->position, fst->avctx->time_base);
3548 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
3550 if( !demand ) flow_off();
3551 if( !afrm && !vfrm ) break;
3552 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
3553 vfrm->position, vfrm->fst->avctx->time_base,
3554 afrm->position, afrm->fst->avctx->time_base);
3555 FFrame *frm = v <= 0 ? vfrm : afrm;
3556 if( frm == afrm ) mux_audio(frm);
3557 if( frm == vfrm ) mux_video(frm);
3566 mux_lock->lock("FFMPEG::run");
3569 for( int i=0; i<ffaudio.size(); ++i )
3570 ffaudio[i]->drain();
3571 for( int i=0; i<ffvideo.size(); ++i )
3572 ffvideo[i]->drain();
3574 for( int i=0; i<ffaudio.size(); ++i )
3575 ffaudio[i]->flush();
3576 for( int i=0; i<ffvideo.size(); ++i )
3577 ffvideo[i]->flush();
3581 int FFMPEG::ff_total_audio_channels()
3583 return astrm_index.size();
3586 int FFMPEG::ff_total_astreams()
3588 return ffaudio.size();
3591 int FFMPEG::ff_audio_channels(int stream)
3593 return ffaudio[stream]->channels;
3596 int FFMPEG::ff_sample_rate(int stream)
3598 return ffaudio[stream]->sample_rate;
3601 const char* FFMPEG::ff_audio_format(int stream)
3603 AVStream *st = ffaudio[stream]->st;
3604 AVCodecID id = st->codecpar->codec_id;
3605 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
3606 return desc ? desc->name : _("Unknown");
3609 int FFMPEG::ff_audio_pid(int stream)
3611 return ffaudio[stream]->st->id;
3614 int64_t FFMPEG::ff_audio_samples(int stream)
3616 return ffaudio[stream]->length;
3619 // find audio astream/channels with this program,
3620 // or all program audio channels (astream=-1)
3621 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
3625 int vidx = ffvideo[vstream]->fidx;
3626 // find first program with this video stream
3627 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
3628 AVProgram *pgrm = fmt_ctx->programs[i];
3629 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
3630 int st_idx = pgrm->stream_index[j];
3631 AVStream *st = fmt_ctx->streams[st_idx];
3632 if( st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
3633 if( st_idx == vidx ) pidx = i;
3636 if( pidx < 0 ) return -1;
3638 int64_t channels = 0;
3639 AVProgram *pgrm = fmt_ctx->programs[pidx];
3640 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
3641 int aidx = pgrm->stream_index[j];
3642 AVStream *st = fmt_ctx->streams[aidx];
3643 if( st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
3644 if( astream > 0 ) { --astream; continue; }
3646 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
3647 if( ffaudio[i]->fidx == aidx ) astrm = i;
3649 if( ret < 0 ) ret = astrm;
3650 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
3651 channels |= mask << ffaudio[astrm]->channel0;
3653 if( !astream ) break;
3655 channel_mask = channels;
3660 int FFMPEG::ff_total_video_layers()
3662 return vstrm_index.size();
3665 int FFMPEG::ff_total_vstreams()
3667 return ffvideo.size();
3670 int FFMPEG::ff_video_width(int stream)
3672 FFVideoStream *vst = ffvideo[stream];
3673 return !vst->transpose ? vst->width : vst->height;
3676 int FFMPEG::ff_video_height(int stream)
3678 FFVideoStream *vst = ffvideo[stream];
3679 return !vst->transpose ? vst->height : vst->width;
3682 int FFMPEG::ff_set_video_width(int stream, int width)
3684 FFVideoStream *vst = ffvideo[stream];
3685 int *vw = !vst->transpose ? &vst->width : &vst->height, w = *vw;
3690 int FFMPEG::ff_set_video_height(int stream, int height)
3692 FFVideoStream *vst = ffvideo[stream];
3693 int *vh = !vst->transpose ? &vst->height : &vst->width, h = *vh;
3698 int FFMPEG::ff_coded_width(int stream)
3700 return ffvideo[stream]->avctx->coded_width;
3703 int FFMPEG::ff_coded_height(int stream)
3705 return ffvideo[stream]->avctx->coded_height;
3708 float FFMPEG::ff_aspect_ratio(int stream)
3710 //return ffvideo[stream]->aspect_ratio;
3711 AVFormatContext *fmt_ctx = ffvideo[stream]->fmt_ctx;
3712 AVStream *strm = ffvideo[stream]->st;
3713 AVCodecParameters *par = ffvideo[stream]->st->codecpar;
3715 AVRational sar = av_guess_sample_aspect_ratio(fmt_ctx, strm, NULL);
3716 if (sar.num && ffvideo[stream]->get_rotation_angle() == 0) {
3717 av_reduce(&dar.num, &dar.den,
3718 par->width * sar.num,
3719 par->height * sar.den,
3723 return ffvideo[stream]->aspect_ratio;
3726 const char* FFMPEG::ff_video_codec(int stream)
3728 AVStream *st = ffvideo[stream]->st;
3729 AVCodecID id = st->codecpar->codec_id;
3730 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
3731 return desc ? desc->name : _("Unknown");
3734 int FFMPEG::ff_color_range(int stream)
3736 return ffvideo[stream]->color_range;
3739 int FFMPEG::ff_color_space(int stream)
3741 return ffvideo[stream]->color_space;
3744 double FFMPEG::ff_frame_rate(int stream)
3746 return ffvideo[stream]->frame_rate;
3749 int64_t FFMPEG::ff_video_frames(int stream)
3751 return ffvideo[stream]->length;
3754 int FFMPEG::ff_video_pid(int stream)
3756 return ffvideo[stream]->st->id;
3759 int FFMPEG::ff_video_mpeg_color_range(int stream)
3761 return ffvideo[stream]->st->codecpar->color_range == AVCOL_RANGE_MPEG ? 1 : 0;
3764 int FFMPEG::ff_interlace(int stream)
3766 // https://ffmpeg.org/doxygen/trunk/structAVCodecParserContext.html
3767 /* reads from demuxer because codec frame not ready */
3768 int interlace0 = ffvideo[stream]->st->codecpar->field_order;
3774 return ILACE_MODE_TOP_FIRST;
3777 return ILACE_MODE_BOTTOM_FIRST;
3778 case AV_FIELD_PROGRESSIVE:
3779 return ILACE_MODE_NOTINTERLACED;
3781 return ILACE_MODE_UNDETECTED;
3788 int FFMPEG::ff_cpus()
3790 return !file_base ? 1 : file_base->file->cpus;
3793 const char *FFMPEG::ff_hw_dev()
3795 return &file_base->file->preferences->use_hw_dev[0];
3798 Preferences *FFMPEG::ff_prefs()
3800 return !file_base ? 0 : file_base->file->preferences;
3803 double FFVideoStream::get_rotation_angle()
3805 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
3810 int *matrix = (int*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX, &size);
3811 int len = size/sizeof(*matrix);
3812 if( !matrix || len < 5 ) return 0;
3813 const double s = 1/65536.;
3814 double theta = (!matrix[0] && !matrix[3]) || (!matrix[1] && !matrix[4]) ? 0 :
3815 atan2( s*matrix[1] / hypot(s*matrix[1], s*matrix[4]),
3816 s*matrix[0] / hypot(s*matrix[0], s*matrix[3])) * 180/M_PI;
3820 int FFVideoStream::flip(double theta)
3824 Preferences *preferences = ffmpeg->ff_prefs();
3825 if( !preferences || !preferences->auto_rotate ) return ret;
3826 double tolerance = 1;
3827 if( fabs(theta-0) < tolerance ) return ret;
3828 if( (theta=fmod(theta, 360)) < 0 ) theta += 360;
3829 if( fabs(theta-90) < tolerance ) {
3830 if( (ret = insert_filter("transpose", "clock")) < 0 )
3834 else if( fabs(theta-180) < tolerance ) {
3835 if( (ret=insert_filter("hflip", 0)) < 0 )
3837 if( (ret=insert_filter("vflip", 0)) < 0 )
3840 else if (fabs(theta-270) < tolerance ) {
3841 if( (ret=insert_filter("transpose", "cclock")) < 0 )
3846 char angle[BCSTRLEN];
3847 sprintf(angle, "%f", theta*M_PI/180.);
3848 if( (ret=insert_filter("rotate", angle)) < 0 )
3854 int FFVideoStream::create_filter(const char *filter_spec)
3856 double theta = get_rotation_angle();
3857 if( !theta && !filter_spec )
3859 avfilter_register_all();
3861 const char *sp = filter_spec;
3862 char filter_name[BCSTRLEN], *np = filter_name;
3863 int i = sizeof(filter_name);
3864 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
3866 const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
3867 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_VIDEO ) {
3868 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
3872 AVCodecParameters *avpar = st->codecpar;
3873 int sa_num = avpar->sample_aspect_ratio.num;
3874 if( !sa_num ) sa_num = 1;
3875 int sa_den = avpar->sample_aspect_ratio.den;
3876 if( !sa_den ) sa_num = 1;
3878 int ret = 0; char args[BCTEXTLEN];
3879 AVPixelFormat pix_fmt = (AVPixelFormat)avpar->format;
3880 snprintf(args, sizeof(args),
3881 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
3882 avpar->width, avpar->height, (int)pix_fmt,
3883 st->time_base.num, st->time_base.den, sa_num, sa_den);
3886 ret = insert_filter("buffer", args, "in");
3887 buffersrc_ctx = filt_ctx;
3891 AVFilterContext *fsrc = filt_ctx;
3894 ret = insert_filter("buffersink", 0, "out");
3895 buffersink_ctx = filt_ctx;
3898 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
3899 (uint8_t*)&pix_fmt, sizeof(pix_fmt),
3900 AV_OPT_SEARCH_CHILDREN);
3903 ret = config_filters(filter_spec, fsrc);
3905 ff_err(ret, "FFVideoStream::create_filter");
3906 return ret >= 0 ? 0 : -1;
3909 int FFAudioStream::create_filter(const char *filter_spec)
3913 avfilter_register_all();
3915 const char *sp = filter_spec;
3916 char filter_name[BCSTRLEN], *np = filter_name;
3917 int i = sizeof(filter_name);
3918 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
3920 const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
3921 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_AUDIO ) {
3922 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
3926 int ret = 0; char args[BCTEXTLEN];
3927 AVCodecParameters *avpar = st->codecpar;
3928 AVSampleFormat sample_fmt = (AVSampleFormat)avpar->format;
3929 snprintf(args, sizeof(args),
3930 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
3931 st->time_base.num, st->time_base.den, avpar->sample_rate,
3932 av_get_sample_fmt_name(sample_fmt), avpar->channel_layout);
3935 ret = insert_filter("abuffer", args, "in");
3936 buffersrc_ctx = filt_ctx;
3938 AVFilterContext *fsrc = filt_ctx;
3941 ret = insert_filter("abuffersink", 0, "out");
3942 buffersink_ctx = filt_ctx;
3945 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
3946 (uint8_t*)&sample_fmt, sizeof(sample_fmt),
3947 AV_OPT_SEARCH_CHILDREN);
3949 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
3950 (uint8_t*)&avpar->channel_layout,
3951 sizeof(avpar->channel_layout), AV_OPT_SEARCH_CHILDREN);
3953 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
3954 (uint8_t*)&sample_rate, sizeof(sample_rate),
3955 AV_OPT_SEARCH_CHILDREN);
3957 ret = config_filters(filter_spec, fsrc);
3959 ff_err(ret, "FFAudioStream::create_filter");
3960 return ret >= 0 ? 0 : -1;
3963 int FFStream::insert_filter(const char *name, const char *arg, const char *inst_name)
3965 const AVFilter *filter = avfilter_get_by_name(name);
3966 if( !filter ) return -1;
3967 char filt_inst[BCSTRLEN];
3969 snprintf(filt_inst, sizeof(filt_inst), "%s_%d", name, ++filt_id);
3970 inst_name = filt_inst;
3973 filter_graph = avfilter_graph_alloc();
3974 AVFilterContext *fctx = 0;
3975 int ret = avfilter_graph_create_filter(&fctx,
3976 filter, inst_name, arg, NULL, filter_graph);
3977 if( ret >= 0 && filt_ctx )
3978 ret = avfilter_link(filt_ctx, 0, fctx, 0);
3982 avfilter_free(fctx);
3986 int FFStream::config_filters(const char *filter_spec, AVFilterContext *fsrc)
3989 AVFilterContext *fsink = buffersink_ctx;
3991 /* Endpoints for the filter graph. */
3992 AVFilterInOut *outputs = avfilter_inout_alloc();
3993 AVFilterInOut *inputs = avfilter_inout_alloc();
3994 if( !inputs || !outputs ) ret = -1;
3996 outputs->filter_ctx = fsrc;
3997 outputs->pad_idx = 0;
3999 if( !(outputs->name = av_strdup(fsrc->name)) ) ret = -1;
4002 inputs->filter_ctx = fsink;
4003 inputs->pad_idx = 0;
4005 if( !(inputs->name = av_strdup(fsink->name)) ) ret = -1;
4008 int len = strlen(fsrc->name)+2 + strlen(filter_spec) + 1;
4009 char spec[len]; sprintf(spec, "[%s]%s", fsrc->name, filter_spec);
4010 ret = avfilter_graph_parse_ptr(filter_graph, spec,
4011 &inputs, &outputs, NULL);
4013 avfilter_inout_free(&inputs);
4014 avfilter_inout_free(&outputs);
4017 ret = avfilter_link(fsrc, 0, fsink, 0);
4019 ret = avfilter_graph_config(filter_graph, NULL);
4021 ff_err(ret, "FFStream::create_filter");
4022 avfilter_graph_free(&filter_graph);
4029 AVCodecContext *FFMPEG::activate_decoder(AVStream *st)
4031 AVDictionary *copts = 0;
4032 av_dict_copy(&copts, opts, 0);
4033 AVCodecID codec_id = st->codecpar->codec_id;
4034 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
4035 const AVCodec *decoder = 0;
4037 AVCodec *decoder = 0;
4039 switch( st->codecpar->codec_type ) {
4040 case AVMEDIA_TYPE_VIDEO:
4041 if( opt_video_decoder )
4042 decoder = avcodec_find_decoder_by_name(opt_video_decoder);
4044 video_codec_remaps.update(codec_id, decoder);
4046 case AVMEDIA_TYPE_AUDIO:
4047 if( opt_audio_decoder )
4048 decoder = avcodec_find_decoder_by_name(opt_audio_decoder);
4050 audio_codec_remaps.update(codec_id, decoder);
4055 if( !decoder && !(decoder = avcodec_find_decoder(codec_id)) ) {
4056 eprintf(_("cant find decoder codec %d\n"), (int)codec_id);
4059 AVCodecContext *avctx = avcodec_alloc_context3(decoder);
4061 eprintf(_("cant allocate codec context\n"));
4064 avcodec_parameters_to_context(avctx, st->codecpar);
4065 if( !av_dict_get(copts, "threads", NULL, 0) )
4066 avctx->thread_count = ff_cpus();
4067 int ret = avcodec_open2(avctx, decoder, &copts);
4068 av_dict_free(&copts);
4070 avcodec_free_context(&avctx);
4076 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
4079 av_init_packet(&pkt);
4080 AVFrame *frame = av_frame_alloc();
4082 fprintf(stderr,"FFMPEG::scan: ");
4083 fprintf(stderr,_("av_frame_alloc failed\n"));
4084 fprintf(stderr,"FFMPEG::scan:file=%s\n", file_base->asset->path);
4088 index_state->add_video_markers(ffvideo.size());
4089 index_state->add_audio_markers(ffaudio.size());
4091 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
4092 AVStream *st = fmt_ctx->streams[i];
4093 AVCodecContext *avctx = activate_decoder(st);
4095 AVCodecParameters *avpar = st->codecpar;
4096 switch( avpar->codec_type ) {
4097 case AVMEDIA_TYPE_VIDEO: {
4098 int vidx = ffvideo.size();
4099 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
4100 if( vidx < 0 ) break;
4101 ffvideo[vidx]->avctx = avctx;
4103 case AVMEDIA_TYPE_AUDIO: {
4104 int aidx = ffaudio.size();
4105 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
4106 if( aidx < 0 ) break;
4107 ffaudio[aidx]->avctx = avctx;
4112 fprintf(stderr,"FFMPEG::scan: ");
4113 fprintf(stderr,_("codec open failed\n"));
4114 fprintf(stderr,"FFMPEG::scan:file=%s\n", file_base->asset->path);
4115 avcodec_free_context(&avctx);
4119 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
4120 AVStream *st = fmt_ctx->streams[i];
4121 AVCodecParameters *avpar = st->codecpar;
4122 if( avpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
4123 int64_t tstmp = st->start_time;
4124 if( tstmp == AV_NOPTS_VALUE ) continue;
4125 int aidx = ffaudio.size();
4126 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
4127 if( aidx < 0 ) continue;
4128 FFAudioStream *aud = ffaudio[aidx];
4129 tstmp -= aud->nudge;
4130 double secs = to_secs(tstmp, st->time_base);
4131 aud->curr_pos = secs * aud->sample_rate + 0.5;
4135 for( int64_t count=0; !*canceled; ++count ) {
4136 av_packet_unref(&pkt);
4137 pkt.data = 0; pkt.size = 0;
4139 int ret = av_read_frame(fmt_ctx, &pkt);
4141 if( ret == AVERROR_EOF ) break;
4142 if( ++errs > 100 ) {
4143 ff_err(ret,_("over 100 read_frame errs\n"));
4148 if( !pkt.data ) continue;
4149 int i = pkt.stream_index;
4150 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
4151 AVStream *st = fmt_ctx->streams[i];
4152 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
4154 AVCodecParameters *avpar = st->codecpar;
4155 switch( avpar->codec_type ) {
4156 case AVMEDIA_TYPE_VIDEO: {
4157 int vidx = ffvideo.size();
4158 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
4159 if( vidx < 0 ) break;
4160 FFVideoStream *vid = ffvideo[vidx];
4161 if( !vid->avctx ) break;
4162 int64_t tstmp = pkt.pts;
4163 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
4164 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
4165 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
4166 double secs = to_secs(tstmp, st->time_base);
4167 int64_t frm = secs * vid->frame_rate + 0.5;
4168 if( frm < 0 ) frm = 0;
4169 index_state->put_video_mark(vidx, frm, pkt.pos);
4172 ret = avcodec_send_packet(vid->avctx, pkt);
4173 if( ret < 0 ) break;
4174 while( (ret=vid->decode_frame(frame)) > 0 ) {}
4177 case AVMEDIA_TYPE_AUDIO: {
4178 int aidx = ffaudio.size();
4179 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
4180 if( aidx < 0 ) break;
4181 FFAudioStream *aud = ffaudio[aidx];
4182 if( !aud->avctx ) break;
4183 int64_t tstmp = pkt.pts;
4184 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
4185 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
4186 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
4187 double secs = to_secs(tstmp, st->time_base);
4188 int64_t sample = secs * aud->sample_rate + 0.5;
4190 index_state->put_audio_mark(aidx, sample, pkt.pos);
4192 ret = avcodec_send_packet(aud->avctx, &pkt);
4193 if( ret < 0 ) break;
4194 int ch = aud->channel0, nch = aud->channels;
4195 int64_t pos = index_state->pos(ch);
4196 if( pos != aud->curr_pos ) {
4197 if( abs(pos-aud->curr_pos) > 1 )
4198 printf("audio%d pad %jd %jd (%jd)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
4199 index_state->pad_data(ch, nch, aud->curr_pos);
4201 while( (ret=aud->decode_frame(frame)) > 0 ) {
4202 //if( frame->channels != nch ) break;
4203 aud->init_swr(frame->channels, frame->format, frame->sample_rate);
4205 int len = aud->get_samples(samples,
4206 &frame->extended_data[0], frame->nb_samples);
4207 pos = aud->curr_pos;
4208 if( (aud->curr_pos += len) >= 0 ) {
4210 samples += -pos * nch;
4211 len = aud->curr_pos;
4213 for( int i=0; i<nch; ++i )
4214 index_state->put_data(ch+i,nch,samples+i,len);
4221 av_frame_free(&frame);
4225 void FFStream::load_markers(IndexMarks &marks, double rate)
4228 int64_t sz = marks.size();
4229 int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
4230 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
4231 int nb_ent = avformat_index_get_entries_count(st);
4233 #if LIBAVCODEC_VERSION_INT <= AV_VERSION_INT(58,134,100)
4234 int nb_ent = st->nb_index_entries;
4236 // some formats already have an index
4238 #if LIBAVCODEC_VERSION_INT <= AV_VERSION_INT(58,134,100)
4239 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
4241 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
4242 const AVIndexEntry *ep = avformat_index_get_entry(st, nb_ent-1);
4244 int64_t tstmp = ep->timestamp;
4245 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
4246 double secs = ffmpeg->to_secs(tstmp, st->time_base);
4247 int64_t no = secs * rate;
4248 while( in < sz && marks[in].no <= no ) ++in;
4250 int64_t len = sz - in;
4251 int64_t count = max_entries - nb_ent;
4252 if( count > len ) count = len;
4253 for( int i=0; i<count; ++i ) {
4254 int k = in + i * len / count;
4255 int64_t no = marks[k].no, pos = marks[k].pos;
4256 double secs = (double)no / rate;
4257 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
4258 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
4259 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);
4265 * 1) if the format context has a timecode
4266 * return fmt_ctx->timecode - 0
4267 * 2) if the layer/channel has a timecode
4268 * return st->timecode - (start_time-nudge)
4269 * 3) find the 1st program with stream, find 1st program video stream,
4270 * if video stream has a timecode, return st->timecode - (start_time-nudge)
4271 * 4) find timecode in any stream, return st->timecode
4272 * 5) read 100 packets, save ofs=pkt.pts*st->time_base - st->nudge:
4273 * decode frame for video stream of 1st program
4274 * if frame->timecode has a timecode, return frame->timecode - ofs
4275 * if side_data has gop timecode, return gop->timecode - ofs
4276 * if side_data has smpte timecode, return smpte->timecode - ofs
4277 * 6) if the filename/url scans *date_time.ext, return date_time
4278 * 7) if stat works on the filename/url, return mtime
4279 * 8) return -1 failure
4281 double FFMPEG::get_initial_timecode(int data_type, int channel, double frame_rate)
4283 AVRational rate = check_frame_rate(0, frame_rate);
4284 if( !rate.num ) return -1;
4285 // format context timecode
4286 AVDictionaryEntry *tc = av_dict_get(fmt_ctx->metadata, "timecode", 0, 0);
4287 if( tc ) return ff_get_timecode(tc->value, rate, 0);
4289 if( open_decoder() ) return -1;
4292 int codec_type = -1, fidx = -1;
4293 switch( data_type ) {
4295 codec_type = AVMEDIA_TYPE_AUDIO;
4296 int aidx = astrm_index[channel].st_idx;
4297 FFAudioStream *aud = ffaudio[aidx];
4301 AVDictionaryEntry *tref = av_dict_get(fmt_ctx->metadata, "time_reference", 0, 0);
4302 if( tref && aud && aud->sample_rate )
4303 return strtod(tref->value, 0) / aud->sample_rate;
4306 codec_type = AVMEDIA_TYPE_VIDEO;
4307 int vidx = vstrm_index[channel].st_idx;
4308 FFVideoStream *vid = ffvideo[vidx];
4314 if( codec_type < 0 ) return -1;
4316 tc = av_dict_get(st->metadata, "timecode", 0, 0);
4319 // find first program which references this stream
4321 for( int i=0, m=fmt_ctx->nb_programs; pidx<0 && i<m; ++i ) {
4322 AVProgram *pgrm = fmt_ctx->programs[i];
4323 for( int j=0, n=pgrm->nb_stream_indexes; j<n; ++j ) {
4324 int st_idx = pgrm->stream_index[j];
4325 if( st_idx == fidx ) { pidx = i; break; }
4330 AVProgram *pgrm = fmt_ctx->programs[pidx];
4331 for( int j=0, n=pgrm->nb_stream_indexes; j<n; ++j ) {
4332 int st_idx = pgrm->stream_index[j];
4333 AVStream *tst = fmt_ctx->streams[st_idx];
4334 if( !tst ) continue;
4335 if( tst->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
4336 st = tst; fidx = st_idx;
4342 for( int i=0, n=fmt_ctx->nb_streams; i<n; ++i ) {
4343 AVStream *tst = fmt_ctx->streams[i];
4344 if( !tst ) continue;
4345 if( tst->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
4352 tc = av_dict_get(st->metadata, "timecode", 0, 0);
4356 // any timecode, includes -data- streams
4357 for( int i=0, n=fmt_ctx->nb_streams; i<n; ++i ) {
4358 AVStream *tst = fmt_ctx->streams[i];
4359 if( !tst ) continue;
4360 if( (tc = av_dict_get(tst->metadata, "timecode", 0, 0)) ) {
4367 if( st && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
4368 if( st->r_frame_rate.num && st->r_frame_rate.den )
4369 rate = st->r_frame_rate;
4370 nudge = st->start_time;
4371 for( int i=0; i<ffvideo.size(); ++i ) {
4372 if( ffvideo[i]->st == st ) {
4373 nudge = ffvideo[i]->nudge;
4379 if( tc ) { // return timecode
4380 double secs = st->start_time == AV_NOPTS_VALUE ? 0 :
4381 to_secs(st->start_time - nudge, st->time_base);
4382 return ff_get_timecode(tc->value, rate, secs);
4385 if( !st || fidx < 0 ) return -1;
4388 AVCodecContext *av_ctx = activate_decoder(st);
4390 fprintf(stderr,"activate_decoder failed\n");
4393 avCodecContext avctx(av_ctx); // auto deletes
4394 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO &&
4395 avctx->framerate.num && avctx->framerate.den )
4396 rate = avctx->framerate;
4398 avPacket pkt; // auto deletes
4399 avFrame frame; // auto deletes
4401 fprintf(stderr,"av_frame_alloc failed\n");
4405 int64_t max_packets = 100;
4406 char tcbuf[AV_TIMECODE_STR_SIZE];
4408 for( int64_t count=0; count<max_packets; ++count ) {
4409 av_packet_unref(pkt);
4410 pkt->data = 0; pkt->size = 0;
4412 int ret = av_read_frame(fmt_ctx, pkt);
4414 if( ret == AVERROR_EOF ) break;
4415 if( ++errs > 100 ) {
4416 fprintf(stderr,"over 100 read_frame errs\n");
4421 if( !pkt->data ) continue;
4422 int i = pkt->stream_index;
4423 if( i != fidx ) continue;
4424 int64_t tstmp = pkt->pts;
4425 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt->dts;
4426 double secs = to_secs(tstmp - nudge, st->time_base);
4427 ret = avcodec_send_packet(avctx, pkt);
4428 if( ret < 0 ) return -1;
4430 while( (ret = avcodec_receive_frame(avctx, frame)) >= 0 ) {
4431 if( (tc = av_dict_get(frame->metadata, "timecode", 0, 0)) )
4432 return ff_get_timecode(tc->value, rate, secs);
4433 int k = frame->nb_side_data;
4434 AVFrameSideData *side_data = 0;
4436 side_data = frame->side_data[k];
4437 switch( side_data->type ) {
4438 case AV_FRAME_DATA_GOP_TIMECODE: {
4439 int64_t data = *(int64_t *)side_data->data;
4440 int sz = sizeof(data);
4441 if( side_data->size >= sz ) {
4442 av_timecode_make_mpeg_tc_string(tcbuf, data);
4443 return ff_get_timecode(tcbuf, rate, secs);
4446 case AV_FRAME_DATA_S12M_TIMECODE: {
4447 uint32_t *data = (uint32_t *)side_data->data;
4448 int n = data[0], sz = (n+1)*sizeof(*data);
4449 if( side_data->size >= sz ) {
4450 av_timecode_make_smpte_tc_string(tcbuf, data[n], 0);
4451 return ff_get_timecode(tcbuf, rate, secs);
4460 char *path = fmt_ctx->url;
4461 char *bp = strrchr(path, '/');
4462 if( !bp ) bp = path; else ++bp;
4463 char *cp = strrchr(bp, '.');
4464 if( cp && (cp-=(8+1+6)) >= bp ) {
4466 int year,mon,day, hour,min,sec, frm=0;
4467 if( sscanf(cp,"%4d%2d%2d%[_-]%2d%2d%2d",
4468 &year,&mon,&day, sep, &hour,&min,&sec) == 7 ) {
4470 // year>=1970,mon=1..12,day=1..31, hour=0..23,min=0..59,sec=0..60
4471 if( (ch=='_' || ch=='-' ) &&
4472 year >= 1970 && mon>=1 && mon<=12 && day>=1 && day<=31 &&
4473 hour>=0 && hour<24 && min>=0 && min<60 && sec>=0 && sec<=60 ) {
4474 sprintf(tcbuf,"%d:%02d:%02d:%02d", hour,min,sec, frm);
4475 return ff_get_timecode(tcbuf, rate, 0);
4480 if( stat(path, &tst) >= 0 ) {
4481 time_t t = (time_t)tst.st_mtim.tv_sec;
4483 localtime_r(&t, &tm);
4484 int64_t us = tst.st_mtim.tv_nsec / 1000;
4485 int frm = us/1000000. * frame_rate;
4486 sprintf(tcbuf,"%d:%02d:%02d:%02d", tm.tm_hour, tm.tm_min, tm.tm_sec, frm);
4487 return ff_get_timecode(tcbuf, rate, 0);
4492 double FFMPEG::ff_get_timecode(char *str, AVRational rate, double pos)
4495 if( av_timecode_init_from_string(&tc, rate, str, fmt_ctx) )
4497 double secs = (double)tc.start / tc.fps - pos;
4498 if( secs < 0 ) secs = 0;
4502 double FFMPEG::get_timecode(const char *path, int data_type, int channel, double rate)
4505 if( ffmpeg.init_decoder(path) ) return -1;
4506 return ffmpeg.get_initial_timecode(data_type, channel, rate);