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 AVChannelLayout ilayout, olayout;
885 av_channel_layout_default(&ilayout, ichs);
886 //if( !ilayout ) ilayout = ((uint64_t)1<<ichs) - 1;
887 //uint64_t olayout = av_get_default_channel_layout(channels);
888 av_channel_layout_default(&olayout, channels);
889 //if( !olayout ) olayout = ((uint64_t)1<<channels) - 1;
891 swr_alloc_set_opts2(&resample_context,
892 &olayout, AV_SAMPLE_FMT_FLT, sample_rate,
893 &ilayout, (AVSampleFormat)ifmt, irate,
895 if( resample_context )
896 swr_init(resample_context);
899 int FFAudioStream::get_samples(float *&samples, uint8_t **data, int len)
901 samples = *(float **)data;
902 if( resample_context ) {
903 if( len > aud_bfr_sz ) {
909 aud_bfr = new float[aud_bfr_sz*channels];
911 int ret = swr_convert(resample_context,
912 (uint8_t**)&aud_bfr, aud_bfr_sz, (const uint8_t**)data, len);
914 ff_err(ret, "FFAudioStream::get_samples: swr_convert failed\n");
923 int FFAudioStream::load_history(uint8_t **data, int len)
926 len = get_samples(samples, data, len);
928 // biggest user bfr since seek + frame
929 realloc(mbsz + len + 1, channels);
935 int FFAudioStream::decode_frame(AVFrame *frame)
937 int first_frame = seeked; seeked = 0;
938 frame->best_effort_timestamp = AV_NOPTS_VALUE;
939 int ret = avcodec_receive_frame(avctx, frame);
941 if( first_frame ) return 0;
942 if( ret == AVERROR(EAGAIN) ) return 0;
943 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
944 ff_err(ret, "FFAudioStream::decode_frame: Could not read audio frame.\nfile:%s\n",
945 ffmpeg->fmt_ctx->url);
948 int64_t pkt_ts = frame->best_effort_timestamp;
949 if( pkt_ts != AV_NOPTS_VALUE ) {
950 double ts = ffmpeg->to_secs(pkt_ts - nudge, st->time_base);
951 double t = (double)curr_pos / sample_rate;
952 // some time_base clocks are very grainy, too grainy for audio (clicks, pops)
953 if( fabs(ts - t) > AUDIO_PTS_TOLERANCE )
954 curr_pos = ts * sample_rate + 0.5;
959 int FFAudioStream::encode_activate()
961 if( writing >= 0 ) return writing;
962 if( !avctx->codec ) return writing = 0;
963 frame_sz = avctx->codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE ?
964 10000 : avctx->frame_size;
965 return FFStream::encode_activate();
968 int64_t FFAudioStream::load_buffer(double ** const sp, int len)
970 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(61,3,100)
971 reserve(len+1, st->codecpar->ch_layout.nb_channels);
973 reserve(len+1, st->codecpar->channels);
975 for( int ch=0; ch<nch; ++ch )
976 write(sp[ch], len, ch);
980 int FFAudioStream::in_history(int64_t pos)
982 if( pos > curr_pos ) return 0;
984 if( len > sz ) len = sz;
985 if( pos < curr_pos - len ) return 0;
990 int FFAudioStream::init_frame(AVFrame *frame)
992 frame->nb_samples = frame_sz;
993 frame->format = avctx->sample_fmt;
994 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(61,3,100)
995 frame->ch_layout.u.mask = avctx->ch_layout.u.mask;
996 av_channel_layout_copy(&frame->ch_layout, &avctx->ch_layout);
998 frame->channel_layout = avctx->channel_layout;
1000 frame->sample_rate = avctx->sample_rate;
1001 int ret = av_frame_get_buffer(frame, 0);
1003 ff_err(ret, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
1007 int FFAudioStream::load(int64_t pos, int len)
1009 if( audio_seek(pos) < 0 ) return -1;
1010 if( !frame && !(frame=av_frame_alloc()) ) {
1011 fprintf(stderr, "FFAudioStream::load: av_frame_alloc failed\n");
1014 if( mbsz < len ) mbsz = len;
1015 int64_t end_pos = pos + len;
1016 int ret = 0, i = len / frame_sz + MAX_RETRY;
1017 while( ret>=0 && !flushed && curr_pos<end_pos && --i>=0 ) {
1018 ret = read_frame(frame);
1019 if( ret > 0 && frame->nb_samples > 0 ) {
1020 init_swr(frame->ch_layout.nb_channels, frame->format, frame->sample_rate);
1021 load_history(&frame->extended_data[0], frame->nb_samples);
1022 curr_pos += frame->nb_samples;
1025 if( end_pos > curr_pos ) {
1026 zero(end_pos - curr_pos);
1029 len = curr_pos - pos;
1034 int FFAudioStream::audio_seek(int64_t pos)
1036 if( decode_activate() <= 0 ) return -1;
1037 if( !st->codecpar ) return -1;
1038 if( in_history(pos) ) return 0;
1039 if( pos == curr_pos ) return 0;
1040 reset_history(); mbsz = 0;
1041 // guarentee preload > 1sec samples
1042 if( (pos-=sample_rate) < 0 ) pos = 0;
1043 if( seek(pos, sample_rate) < 0 ) return -1;
1047 int FFAudioStream::encode(double **samples, int len)
1049 if( encode_activate() <= 0 ) return -1;
1052 int64_t count = samples ? load_buffer(samples, len) : used();
1053 int frame_sz1 = samples ? frame_sz-1 : 0;
1056 while( ret >= 0 && count > frame_sz1 ) {
1057 frm = new FFrame(this);
1058 if( (ret=frm->initted()) < 0 ) break;
1059 AVFrame *frame = *frm;
1060 len = count >= frame_sz ? frame_sz : count;
1061 float *bfrp = get_outp(len);
1062 ret = swr_convert(resample_context,
1063 (uint8_t **)frame->extended_data, len,
1064 (const uint8_t **)&bfrp, len);
1066 ff_err(ret, "FFAudioStream::encode: swr_convert failed\n");
1069 frame->nb_samples = len;
1070 frm->queue(curr_pos);
1077 return ret >= 0 ? 0 : 1;
1080 int FFAudioStream::drain()
1085 int FFAudioStream::encode_frame(AVFrame *frame)
1087 return FFStream::encode_frame(frame);
1090 int FFAudioStream::write_packet(FFPacket &pkt)
1092 return FFStream::write_packet(pkt);
1095 void FFAudioStream::load_markers()
1097 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1098 if( !index_state || idx >= index_state->audio_markers.size() ) return;
1099 if( index_state->marker_status == MARKERS_NOTTESTED ) return;
1100 FFStream::load_markers(*index_state->audio_markers[idx], sample_rate);
1103 IndexMarks *FFAudioStream::get_markers()
1105 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1106 if( !index_state || idx >= index_state->audio_markers.size() ) return 0;
1107 return index_state->audio_markers[idx];
1110 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
1111 : FFStream(ffmpeg, strm, fidx),
1112 FFVideoConvert(ffmpeg->ff_prefs())
1121 top_field_first = 0;
1127 FFVideoStream::~FFVideoStream()
1129 if( fconvert_ctx ) sws_freeContext(fconvert_ctx);
1132 AVHWDeviceType FFVideoStream::decode_hw_activate()
1134 AVHWDeviceType type = AV_HWDEVICE_TYPE_NONE;
1135 const char *hw_dev = ffmpeg->opt_hw_dev;
1136 if( !hw_dev ) hw_dev = getenv("CIN_HW_DEV");
1137 if( !hw_dev ) hw_dev = ffmpeg->ff_hw_dev();
1138 if( hw_dev && *hw_dev &&
1139 strcmp("none", hw_dev) && strcmp(_("none"), hw_dev) ) {
1140 type = av_hwdevice_find_type_by_name(hw_dev);
1141 if( type == AV_HWDEVICE_TYPE_NONE ) {
1142 fprintf(stderr, "Device type %s is not supported.\n", hw_dev);
1143 fprintf(stderr, "Available device types:");
1144 while( (type = av_hwdevice_iterate_types(type)) != AV_HWDEVICE_TYPE_NONE )
1145 fprintf(stderr, " %s", av_hwdevice_get_type_name(type));
1146 fprintf(stderr, "\n");
1151 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
1152 int FFVideoStream::decode_hw_format(const AVCodec *decoder, AVHWDeviceType type)
1154 int FFVideoStream::decode_hw_format(AVCodec *decoder, AVHWDeviceType type)
1158 hw_pix_fmt = AV_PIX_FMT_NONE;
1159 for( int i=0; ; ++i ) {
1160 const AVCodecHWConfig *config = avcodec_get_hw_config(decoder, i);
1162 fprintf(stderr, "Decoder %s does not support device type %s.\n",
1163 decoder->name, av_hwdevice_get_type_name(type));
1167 if( (config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX) != 0 &&
1168 config->device_type == type ) {
1169 hw_pix_fmt = config->pix_fmt;
1173 if( hw_pix_fmt >= 0 ) {
1174 hw_pixfmt = hw_pix_fmt;
1175 avctx->get_format = get_hw_format;
1176 const char *drm_node = getenv("CIN_DRM_DEC");
1177 if(drm_node && type==AV_HWDEVICE_TYPE_VAAPI) {
1178 ret = av_hwdevice_ctx_create(&hw_device_ctx, type, drm_node, 0, 0);
1181 ret = av_hwdevice_ctx_create(&hw_device_ctx, type, 0, 0, 0);
1185 avctx->hw_device_ctx = av_buffer_ref(hw_device_ctx);
1189 ff_err(ret, "Failed HW device create.\ndev:%s\n",
1190 av_hwdevice_get_type_name(type));
1197 AVHWDeviceType FFVideoStream::encode_hw_activate(const char *hw_dev)
1199 const char *drm_node_enc = getenv("CIN_DRM_ENC");
1200 AVBufferRef *hw_device_ctx = 0;
1201 AVBufferRef *hw_frames_ref = 0;
1202 AVHWDeviceType type = AV_HWDEVICE_TYPE_NONE;
1203 if( strcmp(_("none"), hw_dev) ) {
1204 type = av_hwdevice_find_type_by_name(hw_dev);
1205 if( type != AV_HWDEVICE_TYPE_VAAPI ) {
1206 fprintf(stderr, "currently, only vaapi hw encode is supported\n");
1207 type = AV_HWDEVICE_TYPE_NONE;
1210 if( type != AV_HWDEVICE_TYPE_NONE ) {
1213 ret = av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_VAAPI, drm_node_enc, 0, 0);
1215 ret = av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_VAAPI, 0, 0, 0);
1218 ff_err(ret, "Failed to create a HW device.\n");
1219 type = AV_HWDEVICE_TYPE_NONE;
1222 if( type != AV_HWDEVICE_TYPE_NONE ) {
1223 hw_frames_ref = av_hwframe_ctx_alloc(hw_device_ctx);
1224 if( !hw_frames_ref ) {
1225 fprintf(stderr, "Failed to create HW frame context.\n");
1226 type = AV_HWDEVICE_TYPE_NONE;
1229 if( type != AV_HWDEVICE_TYPE_NONE ) {
1230 AVHWFramesContext *frames_ctx = (AVHWFramesContext *)(hw_frames_ref->data);
1231 frames_ctx->format = AV_PIX_FMT_VAAPI;
1232 frames_ctx->sw_format = AV_PIX_FMT_NV12;
1233 frames_ctx->width = width;
1234 frames_ctx->height = height;
1235 frames_ctx->initial_pool_size = 0; // 200;
1236 int ret = av_hwframe_ctx_init(hw_frames_ref);
1238 avctx->hw_frames_ctx = av_buffer_ref(hw_frames_ref);
1239 if( !avctx->hw_frames_ctx ) ret = AVERROR(ENOMEM);
1242 ff_err(ret, "Failed to initialize HW frame context.\n");
1243 type = AV_HWDEVICE_TYPE_NONE;
1245 av_buffer_unref(&hw_frames_ref);
1250 int FFVideoStream::encode_hw_write(FFrame *picture)
1253 AVFrame *hw_frm = 0;
1254 switch( avctx->pix_fmt ) {
1255 case AV_PIX_FMT_VAAPI:
1256 hw_frm = av_frame_alloc();
1257 if( !hw_frm ) { ret = AVERROR(ENOMEM); break; }
1258 ret = av_hwframe_get_buffer(avctx->hw_frames_ctx, hw_frm, 0);
1259 if( ret < 0 ) break;
1260 ret = av_hwframe_transfer_data(hw_frm, *picture, 0);
1261 if( ret < 0 ) break;
1262 picture->set_hw_frame(hw_frm);
1267 av_frame_free(&hw_frm);
1268 ff_err(ret, "Error while transferring frame data to GPU.\n");
1272 int FFVideoStream::decode_frame(AVFrame *frame)
1274 int first_frame = seeked; seeked = 0;
1275 int ret = avcodec_receive_frame(avctx, frame);
1277 if( first_frame ) return 0;
1278 if( ret == AVERROR(EAGAIN) ) return 0;
1279 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
1280 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame.\nfile:%s\n,",
1281 ffmpeg->fmt_ctx->url);
1284 int64_t pkt_ts = frame->best_effort_timestamp;
1285 if( pkt_ts != AV_NOPTS_VALUE )
1286 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * frame_rate + 0.5;
1290 int FFVideoStream::probe(int64_t pos)
1292 int ret = video_seek(pos);
1293 if( ret < 0 ) return -1;
1294 if( !frame && !(frame=av_frame_alloc()) ) {
1295 fprintf(stderr, "FFVideoStream::probe: av_frame_alloc failed\n");
1299 if (ffmpeg->interlace_from_codec) return 1;
1301 ret = read_frame(frame);
1303 //printf("codec interlace: %i \n",frame->interlaced_frame);
1304 //printf("codec tff: %i \n",frame->top_field_first);
1306 if (!frame->interlaced_frame)
1307 ffmpeg->interlace_from_codec = AV_FIELD_PROGRESSIVE;
1308 if ((frame->interlaced_frame) && (frame->top_field_first))
1309 ffmpeg->interlace_from_codec = AV_FIELD_TT;
1310 if ((frame->interlaced_frame) && (!frame->top_field_first))
1311 ffmpeg->interlace_from_codec = AV_FIELD_BB;
1312 //printf("Interlace mode from codec: %i\n", ffmpeg->interlace_from_codec);
1316 if( frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0 )
1319 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
1320 av_frame_free(&frame);
1324 int FFVideoStream::load(VFrame *vframe, int64_t pos)
1326 int ret = video_seek(pos);
1327 if( ret < 0 ) return -1;
1328 if( !frame && !(frame=av_frame_alloc()) ) {
1329 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
1334 int i = MAX_RETRY + pos - curr_pos;
1335 int64_t cache_start = 0;
1336 while( ret>=0 && !flushed && curr_pos<=pos && --i>=0 ) {
1337 ret = read_frame(frame);
1339 if( frame->key_frame && seeking < 0 ) {
1340 int use_cache = ffmpeg->get_use_cache();
1341 if( use_cache < 0 ) {
1342 // for reverse read, reload file frame_cache from keyframe to pos
1343 ffmpeg->purge_cache();
1344 int count = preferences->cache_size /
1345 vframe->get_data_size() / 2; // try to burn only 1/2 of cache
1346 cache_start = pos - count + 1;
1352 if( seeking > 0 && curr_pos >= cache_start && curr_pos < pos ) {
1353 int vw =vframe->get_w(), vh = vframe->get_h();
1354 int vcolor_model = vframe->get_color_model();
1355 // do not use shm here, puts too much pressure on 32bit systems
1356 VFrame *cache_frame = new VFrame(vw, vh, vcolor_model, 0);
1357 ret = convert_cmodel(cache_frame, frame);
1359 ffmpeg->put_cache_frame(cache_frame, curr_pos);
1365 if( frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0 )
1368 ret = convert_cmodel(vframe, frame);
1370 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
1374 int FFVideoStream::video_seek(int64_t pos)
1376 if( decode_activate() <= 0 ) return -1;
1377 if( !st->codecpar ) return -1;
1378 if( pos == curr_pos-1 && !seeked ) return 0;
1379 // if close enough, just read up to current
1380 int gop = avctx->gop_size;
1381 if( gop < 4 ) gop = 4;
1382 if( gop > 64 ) gop = 64;
1383 int read_limit = curr_pos + 3*gop;
1384 if( pos >= curr_pos && pos <= read_limit ) return 0;
1385 // guarentee preload more than 2*gop frames
1386 if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
1390 int FFVideoStream::init_frame(AVFrame *picture)
1392 switch( avctx->pix_fmt ) {
1393 case AV_PIX_FMT_VAAPI:
1394 picture->format = AV_PIX_FMT_NV12;
1397 picture->format = avctx->pix_fmt;
1400 picture->width = avctx->width;
1401 picture->height = avctx->height;
1402 int ret = av_frame_get_buffer(picture, 32);
1406 int FFVideoStream::convert_hw_frame(AVFrame *ifrm, AVFrame *ofrm)
1408 AVPixelFormat ifmt = (AVPixelFormat)ifrm->format;
1409 AVPixelFormat ofmt = (AVPixelFormat)st->codecpar->format;
1410 ofrm->width = ifrm->width;
1411 ofrm->height = ifrm->height;
1412 ofrm->format = ofmt;
1413 int ret = av_frame_get_buffer(ofrm, 32);
1415 ff_err(ret, "FFVideoStream::convert_hw_frame:"
1416 " av_frame_get_buffer failed\n");
1419 fconvert_ctx = sws_getCachedContext(fconvert_ctx,
1420 ifrm->width, ifrm->height, ifmt,
1421 ofrm->width, ofrm->height, ofmt,
1422 SWS_POINT, NULL, NULL, NULL);
1423 if( !fconvert_ctx ) {
1424 ff_err(AVERROR(EINVAL), "FFVideoStream::convert_hw_frame:"
1425 " sws_getCachedContext() failed\n");
1428 int codec_range = st->codecpar->color_range;
1429 int codec_space = st->codecpar->color_space;
1430 const int *codec_table = sws_getCoefficients(codec_space);
1431 int *inv_table, *table, src_range, dst_range;
1432 int brightness, contrast, saturation;
1433 if( !sws_getColorspaceDetails(fconvert_ctx,
1434 &inv_table, &src_range, &table, &dst_range,
1435 &brightness, &contrast, &saturation) ) {
1436 if( src_range != codec_range || dst_range != codec_range ||
1437 inv_table != codec_table || table != codec_table )
1438 sws_setColorspaceDetails(fconvert_ctx,
1439 codec_table, codec_range, codec_table, codec_range,
1440 brightness, contrast, saturation);
1442 ret = sws_scale(fconvert_ctx,
1443 ifrm->data, ifrm->linesize, 0, ifrm->height,
1444 ofrm->data, ofrm->linesize);
1446 ff_err(ret, "FFVideoStream::convert_hw_frame:"
1447 " sws_scale() failed\nfile: %s\n",
1448 ffmpeg->fmt_ctx->url);
1454 int FFVideoStream::load_filter(AVFrame *frame)
1456 AVPixelFormat pix_fmt = (AVPixelFormat)frame->format;
1457 if( pix_fmt == hw_pixfmt ) {
1458 AVFrame *hw_frame = this->frame;
1459 av_frame_unref(hw_frame);
1460 int ret = av_hwframe_transfer_data(hw_frame, frame, 0);
1462 eprintf(_("Error retrieving data from GPU to CPU\nfile: %s\n"),
1463 ffmpeg->fmt_ctx->url);
1466 av_frame_unref(frame);
1467 ret = convert_hw_frame(hw_frame, frame);
1469 eprintf(_("Error converting data from GPU to CPU\nfile: %s\n"),
1470 ffmpeg->fmt_ctx->url);
1473 av_frame_unref(hw_frame);
1475 return FFStream::load_filter(frame);
1478 int FFVideoStream::encode(VFrame *vframe)
1480 if( encode_activate() <= 0 ) return -1;
1482 FFrame *picture = new FFrame(this);
1483 int ret = picture->initted();
1485 AVFrame *frame = *picture;
1486 frame->pts = curr_pos;
1487 ret = convert_pixfmt(vframe, frame);
1489 if( ret >= 0 && avctx->hw_frames_ctx )
1490 encode_hw_write(picture);
1492 picture->queue(curr_pos);
1496 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
1499 return ret >= 0 ? 0 : 1;
1502 int FFVideoStream::drain()
1508 int FFVideoStream::encode_frame(AVFrame *frame)
1511 frame->interlaced_frame = interlaced;
1512 frame->top_field_first = top_field_first;
1514 if( frame && frame->format == AV_PIX_FMT_VAAPI ) { // ugly
1515 int ret = avcodec_send_frame(avctx, frame);
1516 for( int retry=MAX_RETRY; !ret && --retry>=0; ) {
1517 FFPacket pkt; av_init_packet(pkt);
1518 pkt->data = NULL; pkt->size = 0;
1519 if( (ret=avcodec_receive_packet(avctx, pkt)) < 0 ) {
1520 if( ret == AVERROR(EAGAIN) ) ret = 0; // weird
1523 ret = write_packet(pkt);
1524 pkt->stream_index = 0;
1525 av_packet_unref(pkt);
1528 ff_err(ret, "FFStream::encode_frame: vaapi encode failed.\nfile: %s\n",
1529 ffmpeg->fmt_ctx->url);
1534 return FFStream::encode_frame(frame);
1537 int FFVideoStream::write_packet(FFPacket &pkt)
1539 if( !(ffmpeg->fmt_ctx->oformat->flags & AVFMT_VARIABLE_FPS) )
1541 return FFStream::write_packet(pkt);
1544 AVPixelFormat FFVideoConvert::color_model_to_pix_fmt(int color_model)
1546 switch( color_model ) {
1547 case BC_YUV422: return AV_PIX_FMT_YUYV422;
1548 case BC_RGB888: return AV_PIX_FMT_RGB24;
1549 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
1550 case BC_BGR8888: return AV_PIX_FMT_BGR0;
1551 case BC_BGR888: return AV_PIX_FMT_BGR24;
1552 case BC_ARGB8888: return AV_PIX_FMT_ARGB;
1553 case BC_ABGR8888: return AV_PIX_FMT_ABGR;
1554 case BC_RGB8: return AV_PIX_FMT_RGB8;
1555 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
1556 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
1557 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
1558 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
1559 case BC_RGB565: return AV_PIX_FMT_RGB565;
1560 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
1561 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
1562 case BC_AYUV16161616: return AV_PIX_FMT_AYUV64LE;
1563 case BC_GBRP: return AV_PIX_FMT_GBRP;
1567 return AV_PIX_FMT_NB;
1570 int FFVideoConvert::pix_fmt_to_color_model(AVPixelFormat pix_fmt)
1573 case AV_PIX_FMT_YUYV422: return BC_YUV422;
1574 case AV_PIX_FMT_RGB24: return BC_RGB888;
1575 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
1576 case AV_PIX_FMT_BGR0: return BC_BGR8888;
1577 case AV_PIX_FMT_BGR24: return BC_BGR888;
1578 case AV_PIX_FMT_ARGB: return BC_ARGB8888;
1579 case AV_PIX_FMT_ABGR: return BC_ABGR8888;
1580 case AV_PIX_FMT_RGB8: return BC_RGB8;
1581 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
1582 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
1583 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
1584 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
1585 case AV_PIX_FMT_RGB565: return BC_RGB565;
1586 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
1587 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
1588 case AV_PIX_FMT_AYUV64LE: return BC_AYUV16161616;
1589 case AV_PIX_FMT_GBRP: return BC_GBRP;
1596 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip)
1598 AVFrame *ipic = av_frame_alloc();
1599 int ret = convert_picture_vframe(frame, ip, ipic);
1600 av_frame_free(&ipic);
1604 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip, AVFrame *ipic)
1605 { // picture = vframe
1606 int cmodel = frame->get_color_model();
1607 AVPixelFormat ofmt = color_model_to_pix_fmt(cmodel);
1608 if( ofmt == AV_PIX_FMT_NB ) return -1;
1609 int size = av_image_fill_arrays(ipic->data, ipic->linesize,
1610 frame->get_data(), ofmt, frame->get_w(), frame->get_h(), 1);
1611 if( size < 0 ) return -1;
1613 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1614 int ysz = bpp * frame->get_w(), usz = ysz;
1624 // override av_image_fill_arrays() for planar types
1625 ipic->data[0] = frame->get_y(); ipic->linesize[0] = ysz;
1626 ipic->data[1] = frame->get_u(); ipic->linesize[1] = usz;
1627 ipic->data[2] = frame->get_v(); ipic->linesize[2] = usz;
1630 ipic->data[0] = frame->get_data();
1631 ipic->linesize[0] = frame->get_bytes_per_line();
1635 AVPixelFormat pix_fmt = (AVPixelFormat)ip->format;
1636 FFVideoStream *vid =(FFVideoStream *)this;
1637 if( pix_fmt == vid->hw_pixfmt ) {
1639 if( !sw_frame && !(sw_frame=av_frame_alloc()) )
1640 ret = AVERROR(ENOMEM);
1642 ret = av_hwframe_transfer_data(sw_frame, ip, 0);
1644 pix_fmt = (AVPixelFormat)ip->format;
1647 eprintf(_("Error retrieving data from GPU to CPU\nfile: %s\n"),
1648 vid->ffmpeg->fmt_ctx->url);
1652 convert_ctx = sws_getCachedContext(convert_ctx, ip->width, ip->height, pix_fmt,
1653 frame->get_w(), frame->get_h(), ofmt, SWS_POINT, NULL, NULL, NULL);
1654 if( !convert_ctx ) {
1655 fprintf(stderr, "FFVideoConvert::convert_picture_frame:"
1656 " sws_getCachedContext() failed\n");
1660 int color_range = 0;
1661 switch( preferences->yuv_color_range ) {
1662 case BC_COLORS_JPEG: color_range = 1; break;
1663 case BC_COLORS_MPEG: color_range = 0; break;
1665 int color_space = SWS_CS_ITU601;
1666 switch( preferences->yuv_color_space ) {
1667 case BC_COLORS_BT601_PAL: color_space = SWS_CS_ITU601; break;
1668 case BC_COLORS_BT601_NTSC: color_space = SWS_CS_SMPTE170M; break;
1669 case BC_COLORS_BT709: color_space = SWS_CS_ITU709; break;
1670 case BC_COLORS_BT2020_NCL:
1671 case BC_COLORS_BT2020_CL: color_space = SWS_CS_BT2020; break;
1673 const int *color_table = sws_getCoefficients(color_space);
1675 int *inv_table, *table, src_range, dst_range;
1676 int brightness, contrast, saturation;
1677 if( !sws_getColorspaceDetails(convert_ctx,
1678 &inv_table, &src_range, &table, &dst_range,
1679 &brightness, &contrast, &saturation) ) {
1680 if( src_range != color_range || dst_range != color_range ||
1681 inv_table != color_table || table != color_table )
1682 sws_setColorspaceDetails(convert_ctx,
1683 color_table, color_range, color_table, color_range,
1684 brightness, contrast, saturation);
1687 int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ip->height,
1688 ipic->data, ipic->linesize);
1690 ff_err(ret, "FFVideoConvert::convert_picture_frame: sws_scale() failed\nfile: %s\n",
1691 vid->ffmpeg->fmt_ctx->url);
1697 int FFVideoConvert::convert_cmodel(VFrame *frame, AVFrame *ip)
1699 // try direct transfer
1700 if( !convert_picture_vframe(frame, ip) ) return 1;
1701 // use indirect transfer
1702 AVPixelFormat ifmt = (AVPixelFormat)ip->format;
1703 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
1705 for( int i = 0; i <desc->nb_components; ++i ) {
1706 int bits = desc->comp[i].depth;
1707 if( bits > max_bits ) max_bits = bits;
1709 int imodel = pix_fmt_to_color_model(ifmt);
1710 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1711 int cmodel = frame->get_color_model();
1712 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1713 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1714 imodel = cmodel_is_yuv ?
1715 (BC_CModels::has_alpha(cmodel) ?
1717 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1718 (BC_CModels::has_alpha(cmodel) ?
1719 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1720 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1722 VFrame vframe(ip->width, ip->height, imodel);
1723 if( convert_picture_vframe(&vframe, ip) ) return -1;
1724 frame->transfer_from(&vframe);
1728 int FFVideoConvert::transfer_cmodel(VFrame *frame, AVFrame *ifp)
1730 int ret = convert_cmodel(frame, ifp);
1732 const AVDictionary *src = ifp->metadata;
1733 AVDictionaryEntry *t = NULL;
1734 BC_Hash *hp = frame->get_params();
1736 while( (t=av_dict_get(src, "", t, AV_DICT_IGNORE_SUFFIX)) )
1737 hp->update(t->key, t->value);
1742 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op)
1744 AVFrame *opic = av_frame_alloc();
1745 int ret = convert_vframe_picture(frame, op, opic);
1746 av_frame_free(&opic);
1750 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op, AVFrame *opic)
1751 { // vframe = picture
1752 int cmodel = frame->get_color_model();
1753 AVPixelFormat ifmt = color_model_to_pix_fmt(cmodel);
1754 if( ifmt == AV_PIX_FMT_NB ) return -1;
1755 int size = av_image_fill_arrays(opic->data, opic->linesize,
1756 frame->get_data(), ifmt, frame->get_w(), frame->get_h(), 1);
1757 if( size < 0 ) return -1;
1759 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1760 int ysz = bpp * frame->get_w(), usz = ysz;
1770 // override av_image_fill_arrays() for planar types
1771 opic->data[0] = frame->get_y(); opic->linesize[0] = ysz;
1772 opic->data[1] = frame->get_u(); opic->linesize[1] = usz;
1773 opic->data[2] = frame->get_v(); opic->linesize[2] = usz;
1776 opic->data[0] = frame->get_data();
1777 opic->linesize[0] = frame->get_bytes_per_line();
1781 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1782 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(),
1783 ifmt, op->width, op->height, ofmt, SWS_POINT, NULL, NULL, NULL);
1784 if( !convert_ctx ) {
1785 fprintf(stderr, "FFVideoConvert::convert_frame_picture:"
1786 " sws_getCachedContext() failed\n");
1791 int color_range = 0;
1792 switch( preferences->yuv_color_range ) {
1793 case BC_COLORS_JPEG: color_range = 1; break;
1794 case BC_COLORS_MPEG: color_range = 0; break;
1796 int color_space = SWS_CS_ITU601;
1797 switch( preferences->yuv_color_space ) {
1798 case BC_COLORS_BT601_PAL: color_space = SWS_CS_ITU601; break;
1799 case BC_COLORS_BT601_NTSC: color_space = SWS_CS_SMPTE170M; break;
1800 case BC_COLORS_BT709: color_space = SWS_CS_ITU709; break;
1801 case BC_COLORS_BT2020_NCL:
1802 case BC_COLORS_BT2020_CL: color_space = SWS_CS_BT2020; break;
1804 const int *color_table = sws_getCoefficients(color_space);
1806 int *inv_table, *table, src_range, dst_range;
1807 int brightness, contrast, saturation;
1808 if( !sws_getColorspaceDetails(convert_ctx,
1809 &inv_table, &src_range, &table, &dst_range,
1810 &brightness, &contrast, &saturation) ) {
1811 if( dst_range != color_range || table != color_table )
1812 sws_setColorspaceDetails(convert_ctx,
1813 inv_table, src_range, color_table, color_range,
1814 brightness, contrast, saturation);
1817 int ret = sws_scale(convert_ctx, opic->data, opic->linesize, 0, frame->get_h(),
1818 op->data, op->linesize);
1820 ff_err(ret, "FFVideoConvert::convert_frame_picture: sws_scale() failed\n");
1826 int FFVideoConvert::convert_pixfmt(VFrame *frame, AVFrame *op)
1828 // try direct transfer
1829 if( !convert_vframe_picture(frame, op) ) return 1;
1830 // use indirect transfer
1831 int cmodel = frame->get_color_model();
1832 int max_bits = BC_CModels::calculate_pixelsize(cmodel) * 8;
1833 max_bits /= BC_CModels::components(cmodel);
1834 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1835 int imodel = pix_fmt_to_color_model(ofmt);
1836 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1837 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1838 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1839 imodel = cmodel_is_yuv ?
1840 (BC_CModels::has_alpha(cmodel) ?
1842 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1843 (BC_CModels::has_alpha(cmodel) ?
1844 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1845 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1847 VFrame vframe(frame->get_w(), frame->get_h(), imodel);
1848 vframe.transfer_from(frame);
1849 if( !convert_vframe_picture(&vframe, op) ) return 1;
1853 int FFVideoConvert::transfer_pixfmt(VFrame *frame, AVFrame *ofp)
1855 int ret = convert_pixfmt(frame, ofp);
1857 BC_Hash *hp = frame->get_params();
1858 AVDictionary **dict = &ofp->metadata;
1859 //av_dict_free(dict);
1860 for( int i=0; i<hp->size(); ++i ) {
1861 char *key = hp->get_key(i), *val = hp->get_value(i);
1862 av_dict_set(dict, key, val, 0);
1868 void FFVideoStream::load_markers()
1870 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1871 if( !index_state || idx >= index_state->video_markers.size() ) return;
1872 FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
1875 IndexMarks *FFVideoStream::get_markers()
1877 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1878 if( !index_state || idx >= index_state->video_markers.size() ) return 0;
1879 return !index_state ? 0 : index_state->video_markers[idx];
1883 FFMPEG::FFMPEG(FileBase *file_base)
1886 this->file_base = file_base;
1887 memset(file_format,0,sizeof(file_format));
1888 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
1889 flow_lock = new Condition(1,"FFStream::flow_lock",0);
1892 decoding = encoding = 0;
1893 has_audio = has_video = 0;
1894 interlace_from_codec = 0;
1897 opt_video_filter = 0;
1898 opt_audio_filter = 0;
1900 opt_video_decoder = 0;
1901 opt_audio_decoder = 0;
1903 char option_path[BCTEXTLEN];
1904 set_option_path(option_path, "%s", "ffmpeg.opts");
1905 read_options(option_path, opts);
1910 ff_lock("FFMPEG::~FFMPEG()");
1912 ffaudio.remove_all_objects();
1913 ffvideo.remove_all_objects();
1914 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1918 av_dict_free(&opts);
1919 delete [] opt_video_filter;
1920 delete [] opt_audio_filter;
1921 delete [] opt_hw_dev;
1924 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
1925 int FFMPEG::check_sample_rate(const AVCodec *codec, int sample_rate)
1927 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1930 const int *p = codec->supported_samplerates;
1931 if( !p ) return sample_rate;
1933 if( *p == sample_rate ) return *p;
1939 // check_frame_rate and std_frame_rate needed for 23.976
1940 // and 59.94 fps mpeg2
1941 static inline AVRational std_frame_rate(int i)
1943 static const int m1 = 1001*12, m2 = 1000*12;
1944 static const int freqs[] = {
1945 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1946 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 90*m2,
1947 100*m2, 120*m2, 144*m2, 72*m2, 0,
1949 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1950 return (AVRational) { freq, 1001*12 };
1953 AVRational FFMPEG::check_frame_rate(const AVRational *p, double frame_rate)
1955 AVRational rate, best_rate = (AVRational) { 0, 0 };
1956 double max_err = 1.; int i = 0;
1957 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1958 double framerate = (double) rate.num / rate.den;
1959 double err = fabs(frame_rate/framerate - 1.);
1960 if( err >= max_err ) continue;
1964 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1967 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1970 double display_aspect = asset->width / (double)asset->height;
1971 double sample_aspect = display_aspect / asset->aspect_ratio;
1972 int width = 1000000, height = width * sample_aspect + 0.5;
1974 MWindow::create_aspect_ratio(w, h, width, height);
1975 return (AVRational){(int)w, (int)h};
1978 return (AVRational){1, 1};
1982 AVRational FFMPEG::to_time_base(int sample_rate)
1984 return (AVRational){1, sample_rate};
1987 int FFMPEG::get_fmt_score(AVSampleFormat dst_fmt, AVSampleFormat src_fmt)
1990 int dst_planar = av_sample_fmt_is_planar(dst_fmt);
1991 int src_planar = av_sample_fmt_is_planar(src_fmt);
1992 if( dst_planar != src_planar ) ++score;
1993 int dst_bytes = av_get_bytes_per_sample(dst_fmt);
1994 int src_bytes = av_get_bytes_per_sample(src_fmt);
1995 score += (src_bytes > dst_bytes ? 100 : -10) * (src_bytes - dst_bytes);
1996 int src_packed = av_get_packed_sample_fmt(src_fmt);
1997 int dst_packed = av_get_packed_sample_fmt(dst_fmt);
1998 if( dst_packed == AV_SAMPLE_FMT_S32 && src_packed == AV_SAMPLE_FMT_FLT ) score += 20;
1999 if( dst_packed == AV_SAMPLE_FMT_FLT && src_packed == AV_SAMPLE_FMT_S32 ) score += 2;
2003 AVSampleFormat FFMPEG::find_best_sample_fmt_of_list(
2004 const AVSampleFormat *sample_fmts, AVSampleFormat src_fmt)
2006 AVSampleFormat best = AV_SAMPLE_FMT_NONE;
2007 int best_score = get_fmt_score(best, src_fmt);
2008 for( int i=0; sample_fmts[i] >= 0; ++i ) {
2009 AVSampleFormat sample_fmt = sample_fmts[i];
2010 int score = get_fmt_score(sample_fmt, src_fmt);
2011 if( score >= best_score ) continue;
2012 best = sample_fmt; best_score = score;
2018 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
2020 char *ep = path + BCTEXTLEN-1;
2021 strncpy(path, File::get_cindat_path(), ep-path);
2022 strncat(path, "/ffmpeg/", ep-path);
2023 path += strlen(path);
2026 path += vsnprintf(path, ep-path, fmt, ap);
2031 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
2036 set_option_path(path, "%s/%s", type, spec);
2039 int FFMPEG::get_format(char *format, const char *path, const char *spec)
2041 char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
2042 get_option_path(option_path, path, spec);
2043 FILE *fp = fopen(option_path,"r");
2046 if( !fgets(line, sizeof(line), fp) ) ret = 1;
2048 line[sizeof(line)-1] = 0;
2049 ret = scan_option_line(line, format, codec);
2055 int FFMPEG::get_codec(char *codec, const char *path, const char *spec)
2057 char option_path[BCTEXTLEN], line[BCTEXTLEN], format[BCTEXTLEN];
2058 get_option_path(option_path, path, spec);
2059 FILE *fp = fopen(option_path,"r");
2062 if( !fgets(line, sizeof(line), fp) ) ret = 1;
2065 line[sizeof(line)-1] = 0;
2066 ret = scan_option_line(line, format, codec);
2069 char *vp = codec, *ep = vp+BCTEXTLEN-1;
2070 while( vp < ep && *vp && *vp != '|' ) ++vp;
2071 if( *vp == '|' ) --vp;
2072 while( vp > codec && (*vp==' ' || *vp=='\t') ) *vp-- = 0;
2077 int FFMPEG::get_file_format()
2079 char audio_muxer[BCSTRLEN], video_muxer[BCSTRLEN];
2080 char audio_format[BCSTRLEN], video_format[BCSTRLEN];
2081 audio_muxer[0] = audio_format[0] = 0;
2082 video_muxer[0] = video_format[0] = 0;
2083 Asset *asset = file_base->asset;
2084 int ret = asset ? 0 : 1;
2085 if( !ret && asset->audio_data ) {
2086 if( !(ret=get_format(audio_format, "audio", asset->acodec)) ) {
2087 if( get_format(audio_muxer, "format", audio_format) ) {
2088 strcpy(audio_muxer, audio_format);
2089 audio_format[0] = 0;
2093 if( !ret && asset->video_data ) {
2094 if( !(ret=get_format(video_format, "video", asset->vcodec)) ) {
2095 if( get_format(video_muxer, "format", video_format) ) {
2096 strcpy(video_muxer, video_format);
2097 video_format[0] = 0;
2101 if( !ret && !audio_muxer[0] && !video_muxer[0] )
2103 if( !ret && audio_muxer[0] && video_muxer[0] &&
2104 strcmp(audio_muxer, video_muxer) ) ret = -1;
2105 if( !ret && audio_format[0] && video_format[0] &&
2106 strcmp(audio_format, video_format) ) ret = -1;
2108 strcpy(file_format, !audio_format[0] && !video_format[0] ?
2109 (audio_muxer[0] ? audio_muxer : video_muxer) :
2110 (audio_format[0] ? audio_format : video_format));
2114 int FFMPEG::scan_option_line(const char *cp, char *tag, char *val)
2116 while( *cp == ' ' || *cp == '\t' ) ++cp;
2117 const char *bp = cp;
2118 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' && *cp != '\n' ) ++cp;
2120 if( !len || len > BCSTRLEN-1 ) return 1;
2121 while( bp < cp ) *tag++ = *bp++;
2123 while( *cp == ' ' || *cp == '\t' ) ++cp;
2124 if( *cp == '=' ) ++cp;
2125 while( *cp == ' ' || *cp == '\t' ) ++cp;
2127 while( *cp && *cp != '\n' ) ++cp;
2129 if( len > BCTEXTLEN-1 ) return 1;
2130 while( bp < cp ) *val++ = *bp++;
2135 int FFMPEG::can_render(const char *fformat, const char *type)
2138 char option_path[BCTEXTLEN];
2139 FFMPEG::set_option_path(option_path, type);
2140 fs.update(option_path);
2141 int total_files = fs.total_files();
2142 for( int i=0; i<total_files; ++i ) {
2143 const char *name = fs.get_entry(i)->get_name();
2144 const char *ext = strrchr(name,'.');
2145 if( !ext ) continue;
2146 if( !strcmp(fformat, ++ext) ) return 1;
2151 int FFMPEG::get_ff_option(const char *nm, const char *options, char *value)
2153 for( const char *cp=options; *cp!=0; ) {
2154 char line[BCTEXTLEN], *bp = line, *ep = bp+sizeof(line)-1;
2155 while( bp < ep && *cp && *cp!='\n' ) *bp++ = *cp++;
2158 if( !line[0] || line[0] == '#' || line[0] == ';' ) continue;
2159 char key[BCSTRLEN], val[BCTEXTLEN];
2160 if( FFMPEG::scan_option_line(line, key, val) ) continue;
2161 if( !strcmp(key, nm) ) {
2162 strncpy(value, val, BCSTRLEN);
2169 void FFMPEG::scan_audio_options(Asset *asset, EDL *edl)
2171 char cin_sample_fmt[BCSTRLEN];
2172 int cin_fmt = AV_SAMPLE_FMT_NONE;
2173 const char *options = asset->ff_audio_options;
2174 if( !get_ff_option("cin_sample_fmt", options, cin_sample_fmt) )
2175 cin_fmt = (int)av_get_sample_fmt(cin_sample_fmt);
2177 char audio_codec[BCSTRLEN]; audio_codec[0] = 0;
2178 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,18,100)
2179 const AVCodec *av_codec = !FFMPEG::get_codec(audio_codec, "audio", asset->acodec) ?
2181 AVCodec *av_codec = !FFMPEG::get_codec(audio_codec, "audio", asset->acodec) ?
2183 avcodec_find_encoder_by_name(audio_codec) : 0;
2184 if( av_codec && av_codec->sample_fmts )
2185 cin_fmt = find_best_sample_fmt_of_list(av_codec->sample_fmts, AV_SAMPLE_FMT_FLT);
2187 if( cin_fmt < 0 ) cin_fmt = AV_SAMPLE_FMT_S16;
2188 const char *name = av_get_sample_fmt_name((AVSampleFormat)cin_fmt);
2189 if( !name ) name = _("None");
2190 strcpy(asset->ff_sample_format, name);
2192 char value[BCSTRLEN];
2193 if( !get_ff_option("cin_bitrate", options, value) )
2194 asset->ff_audio_bitrate = atoi(value);
2195 if( !get_ff_option("cin_quality", options, value) )
2196 asset->ff_audio_quality = atoi(value);
2199 void FFMPEG::load_audio_options(Asset *asset, EDL *edl)
2201 char options_path[BCTEXTLEN];
2202 set_option_path(options_path, "audio/%s", asset->acodec);
2203 if( !load_options(options_path,
2204 asset->ff_audio_options,
2205 sizeof(asset->ff_audio_options)) )
2206 scan_audio_options(asset, edl);
2209 void FFMPEG::scan_video_options(Asset *asset, EDL *edl)
2211 char cin_pix_fmt[BCSTRLEN];
2212 int cin_fmt = AV_PIX_FMT_NONE;
2213 const char *options = asset->ff_video_options;
2214 if( !get_ff_option("cin_pix_fmt", options, cin_pix_fmt) )
2215 cin_fmt = (int)av_get_pix_fmt(cin_pix_fmt);
2217 char video_codec[BCSTRLEN]; video_codec[0] = 0;
2218 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,18,100)
2219 const AVCodec *av_codec = !get_codec(video_codec, "video", asset->vcodec) ?
2221 AVCodec *av_codec = !get_codec(video_codec, "video", asset->vcodec) ?
2223 avcodec_find_encoder_by_name(video_codec) : 0;
2224 if( av_codec && av_codec->pix_fmts ) {
2225 if( 0 && edl ) { // frequently picks a bad answer
2226 int color_model = edl->session->color_model;
2227 int max_bits = BC_CModels::calculate_pixelsize(color_model) * 8;
2228 max_bits /= BC_CModels::components(color_model);
2229 cin_fmt = avcodec_find_best_pix_fmt_of_list(av_codec->pix_fmts,
2230 (BC_CModels::is_yuv(color_model) ?
2231 (max_bits > 8 ? AV_PIX_FMT_AYUV64LE : AV_PIX_FMT_YUV444P) :
2232 (max_bits > 8 ? AV_PIX_FMT_RGB48LE : AV_PIX_FMT_RGB24)), 0, 0);
2235 cin_fmt = av_codec->pix_fmts[0];
2238 if( cin_fmt < 0 ) cin_fmt = AV_PIX_FMT_YUV420P;
2239 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get((AVPixelFormat)cin_fmt);
2240 const char *name = desc ? desc->name : _("None");
2241 strcpy(asset->ff_pixel_format, name);
2243 char value[BCSTRLEN];
2244 if( !get_ff_option("cin_bitrate", options, value) )
2245 asset->ff_video_bitrate = atoi(value);
2246 if( !get_ff_option("cin_quality", options, value) )
2247 asset->ff_video_quality = atoi(value);
2250 void FFMPEG::load_video_options(Asset *asset, EDL *edl)
2252 char options_path[BCTEXTLEN];
2253 set_option_path(options_path, "video/%s", asset->vcodec);
2254 if( !load_options(options_path,
2255 asset->ff_video_options,
2256 sizeof(asset->ff_video_options)) )
2257 scan_video_options(asset, edl);
2260 void FFMPEG::scan_format_options(Asset *asset, EDL *edl)
2264 void FFMPEG::load_format_options(Asset *asset, EDL *edl)
2266 char options_path[BCTEXTLEN];
2267 set_option_path(options_path, "format/%s", asset->fformat);
2268 if( !load_options(options_path,
2269 asset->ff_format_options,
2270 sizeof(asset->ff_format_options)) )
2271 scan_format_options(asset, edl);
2274 int FFMPEG::load_defaults(const char *path, const char *type,
2275 char *codec, char *codec_options, int len)
2277 char default_file[BCTEXTLEN];
2278 set_option_path(default_file, "%s/%s.dfl", path, type);
2279 FILE *fp = fopen(default_file,"r");
2281 fgets(codec, BCSTRLEN, fp);
2283 while( *cp && *cp!='\n' ) ++cp;
2285 while( len > 0 && fgets(codec_options, len, fp) ) {
2286 int n = strlen(codec_options);
2287 codec_options += n; len -= n;
2290 set_option_path(default_file, "%s/%s", path, codec);
2291 return load_options(default_file, codec_options, len);
2294 void FFMPEG::set_asset_format(Asset *asset, EDL *edl, const char *text)
2296 if( asset->format != FILE_FFMPEG ) return;
2297 if( text != asset->fformat )
2298 strcpy(asset->fformat, text);
2299 if( !asset->ff_format_options[0] )
2300 load_format_options(asset, edl);
2301 if( asset->audio_data && !asset->ff_audio_options[0] ) {
2302 if( !load_defaults("audio", text, asset->acodec,
2303 asset->ff_audio_options, sizeof(asset->ff_audio_options)) )
2304 scan_audio_options(asset, edl);
2306 asset->audio_data = 0;
2308 if( asset->video_data && !asset->ff_video_options[0] ) {
2309 if( !load_defaults("video", text, asset->vcodec,
2310 asset->ff_video_options, sizeof(asset->ff_video_options)) )
2311 scan_video_options(asset, edl);
2313 asset->video_data = 0;
2317 int FFMPEG::get_encoder(const char *options,
2318 char *format, char *codec, char *bsfilter)
2320 FILE *fp = fopen(options,"r");
2322 eprintf(_("options open failed %s\n"),options);
2325 char line[BCTEXTLEN];
2326 if( !fgets(line, sizeof(line), fp) ||
2327 scan_encoder(line, format, codec, bsfilter) )
2328 eprintf(_("format/codec not found %s\n"), options);
2333 int FFMPEG::scan_encoder(const char *line,
2334 char *format, char *codec, char *bsfilter)
2336 format[0] = codec[0] = bsfilter[0] = 0;
2337 if( scan_option_line(line, format, codec) ) return 1;
2339 while( *cp && *cp != '|' ) ++cp;
2340 if( !*cp ) return 0;
2342 do { *bp-- = 0; } while( bp>=codec && (*bp==' ' || *bp == '\t' ) );
2343 while( *++cp && (*cp==' ' || *cp == '\t') );
2345 for( int i=BCTEXTLEN; --i>0 && *cp; ) *bp++ = *cp++;
2350 int FFMPEG::read_options(const char *options, AVDictionary *&opts, int skip)
2352 FILE *fp = fopen(options,"r");
2355 while( !ret && --skip >= 0 ) {
2357 while( ch >= 0 && ch != '\n' ) ch = getc(fp);
2358 if( ch < 0 ) ret = 1;
2361 ret = read_options(fp, options, opts);
2366 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
2368 FILE *fp = fmemopen((void *)options,strlen(options),"r");
2370 int ret = read_options(fp, options, opts);
2373 AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
2374 if( tag ) st->id = strtol(tag->value,0,0);
2379 void FFMPEG::put_cache_frame(VFrame *frame, int64_t position)
2381 file_base->file->put_cache_frame(frame, position, 0);
2384 int FFMPEG::get_use_cache()
2386 return file_base->file->get_use_cache();
2389 void FFMPEG::purge_cache()
2391 file_base->file->purge_cache();
2394 FFCodecRemap::FFCodecRemap()
2399 FFCodecRemap::~FFCodecRemap()
2401 delete [] old_codec;
2402 delete [] new_codec;
2405 int FFCodecRemaps::add(const char *val)
2407 char old_codec[BCSTRLEN], new_codec[BCSTRLEN];
2408 if( sscanf(val, " %63[a-zA-z0-9_-] = %63[a-z0-9_-]",
2409 &old_codec[0], &new_codec[0]) != 2 ) return 1;
2410 FFCodecRemap &remap = append();
2411 remap.old_codec = cstrdup(old_codec);
2412 remap.new_codec = cstrdup(new_codec);
2416 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
2417 int FFCodecRemaps::update(AVCodecID &codec_id, const AVCodec *&decoder)
2419 const AVCodec *codec = avcodec_find_decoder(codec_id);
2421 int FFCodecRemaps::update(AVCodecID &codec_id, AVCodec *&decoder)
2423 AVCodec *codec = avcodec_find_decoder(codec_id);
2425 if( !codec ) return -1;
2426 const char *name = codec->name;
2427 FFCodecRemaps &map = *this;
2429 while( --k >= 0 && strcmp(map[k].old_codec, name) );
2430 if( k < 0 ) return 1;
2431 const char *new_codec = map[k].new_codec;
2432 codec = avcodec_find_decoder_by_name(new_codec);
2433 if( !codec ) return -1;
2438 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
2440 int ret = 0, no = 0;
2441 char line[BCTEXTLEN];
2442 while( !ret && fgets(line, sizeof(line), fp) ) {
2443 line[sizeof(line)-1] = 0;
2444 if( line[0] == '#' ) continue;
2445 if( line[0] == '\n' ) continue;
2446 char key[BCSTRLEN], val[BCTEXTLEN];
2447 if( scan_option_line(line, key, val) ) {
2448 eprintf(_("err reading %s: line %d\n"), options, no);
2452 if( !strcmp(key, "duration") )
2453 opt_duration = strtod(val, 0);
2454 else if( !strcmp(key, "video_decoder") )
2455 opt_video_decoder = cstrdup(val);
2456 else if( !strcmp(key, "audio_decoder") )
2457 opt_audio_decoder = cstrdup(val);
2458 else if( !strcmp(key, "remap_video_decoder") )
2459 video_codec_remaps.add(val);
2460 else if( !strcmp(key, "remap_audio_decoder") )
2461 audio_codec_remaps.add(val);
2462 else if( !strcmp(key, "video_filter") )
2463 opt_video_filter = cstrdup(val);
2464 else if( !strcmp(key, "audio_filter") )
2465 opt_audio_filter = cstrdup(val);
2466 else if( !strcmp(key, "cin_hw_dev") )
2467 opt_hw_dev = cstrdup(val);
2468 else if( !strcmp(key, "loglevel") )
2471 av_dict_set(&opts, key, val, 0);
2477 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
2479 char option_path[BCTEXTLEN];
2480 set_option_path(option_path, "%s", options);
2481 return read_options(option_path, opts);
2484 int FFMPEG::load_options(const char *path, char *bfr, int len)
2487 FILE *fp = fopen(path, "r");
2489 fgets(bfr, len, fp); // skip hdr
2490 len = fread(bfr, 1, len-1, fp);
2491 if( len < 0 ) len = 0;
2497 void FFMPEG::set_loglevel(const char *ap)
2499 if( !ap || !*ap ) return;
2504 { "quiet" , AV_LOG_QUIET },
2505 { "panic" , AV_LOG_PANIC },
2506 { "fatal" , AV_LOG_FATAL },
2507 { "error" , AV_LOG_ERROR },
2508 { "warning", AV_LOG_WARNING },
2509 { "info" , AV_LOG_INFO },
2510 { "verbose", AV_LOG_VERBOSE },
2511 { "debug" , AV_LOG_DEBUG },
2513 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
2514 if( !strcmp(log_levels[i].name, ap) ) {
2515 av_log_set_level(log_levels[i].level);
2519 av_log_set_level(atoi(ap));
2522 double FFMPEG::to_secs(int64_t time, AVRational time_base)
2524 double base_time = time == AV_NOPTS_VALUE ? 0 :
2525 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
2526 return base_time / AV_TIME_BASE;
2529 int FFMPEG::info(char *text, int len)
2531 if( len <= 0 ) return 0;
2533 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
2535 report("format: %s\n",fmt_ctx->iformat->name);
2536 if( ffvideo.size() > 0 )
2537 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
2538 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
2539 const char *unkn = _("(unkn)");
2540 FFVideoStream *vid = ffvideo[vidx];
2541 AVStream *st = vid->st;
2542 AVCodecID codec_id = st->codecpar->codec_id;
2543 report(_("vid%d (%d), id 0x%06x:\n"), vid->idx, vid->fidx, codec_id);
2544 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
2545 report(" video%d %s ", vidx+1, desc ? desc->name : unkn);
2546 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
2547 AVPixelFormat pix_fmt = (AVPixelFormat)st->codecpar->format;
2548 const char *pfn = av_get_pix_fmt_name(pix_fmt);
2549 report(" pix %s\n", pfn ? pfn : unkn);
2550 int interlace = st->codecpar->field_order;
2551 report(" interlace (container level): %i\n", interlace ? interlace : -1);
2552 int interlace_codec = interlace_from_codec;
2553 report(" interlace (codec level): %i\n", interlace_codec ? interlace_codec : -1);
2554 enum AVColorSpace space = st->codecpar->color_space;
2555 const char *nm = av_color_space_name(space);
2556 report(" color space:%s", nm ? nm : unkn);
2557 enum AVColorRange range = st->codecpar->color_range;
2558 const char *rg = av_color_range_name(range);
2559 report("/ range:%s\n", rg ? rg : unkn);
2561 AVRational sar = av_guess_sample_aspect_ratio(fmt_ctx, st, NULL);
2562 AVRational display_aspect_ratio;
2565 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
2566 st->codecpar->width * (int64_t)sar.num,
2567 st->codecpar->height * (int64_t)sar.den,
2569 /* report(" Guessed SAR: %d:%d, ", sar.num, sar.den );
2570 report("DAR: %d:%d \n", display_aspect_ratio.num, display_aspect_ratio.den); */
2572 if (st->sample_aspect_ratio.num)
2574 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
2575 st->codecpar->width * (int64_t)st->sample_aspect_ratio.num,
2576 st->codecpar->height * (int64_t)st->sample_aspect_ratio.den,
2578 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);
2580 if (st->codecpar->sample_aspect_ratio.num)
2582 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
2583 st->codecpar->width * (int64_t)st->codecpar->sample_aspect_ratio.num,
2584 st->codecpar->height * (int64_t)st->codecpar->sample_aspect_ratio.den,
2586 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);
2588 double secs = to_secs(st->duration, st->time_base);
2589 int64_t length = secs * vid->frame_rate + 0.5;
2590 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
2591 int64_t nudge = ofs * vid->frame_rate;
2592 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
2593 report(" %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
2594 int hrs = secs/3600; secs -= hrs*3600;
2595 int mins = secs/60; secs -= mins*60;
2596 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
2597 double theta = vid->get_rotation_angle();
2598 if( fabs(theta) > 1 )
2599 report(" rotation angle: %0.1f\n", theta);
2601 if( ffaudio.size() > 0 )
2602 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
2603 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2604 FFAudioStream *aud = ffaudio[aidx];
2605 AVStream *st = aud->st;
2606 AVCodecID codec_id = st->codecpar->codec_id;
2607 report(_("aud%d (%d), id 0x%06x:\n"), aud->idx, aud->fidx, codec_id);
2608 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
2609 int nch = aud->channels, ch0 = aud->channel0+1;
2610 report(" audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
2611 AVSampleFormat sample_fmt = (AVSampleFormat)st->codecpar->format;
2612 const char *fmt = av_get_sample_fmt_name(sample_fmt);
2613 report(" %s %d", fmt, aud->sample_rate);
2614 int sample_bits = av_get_bits_per_sample(codec_id);
2615 report(" %dbits\n", sample_bits);
2616 double secs = to_secs(st->duration, st->time_base);
2617 int64_t length = secs * aud->sample_rate + 0.5;
2618 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
2619 int64_t nudge = ofs * aud->sample_rate;
2620 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
2621 report(" %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
2622 int hrs = secs/3600; secs -= hrs*3600;
2623 int mins = secs/60; secs -= mins*60;
2624 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
2626 if( fmt_ctx->nb_programs > 0 )
2627 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
2628 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
2629 report("program %d", i+1);
2630 AVProgram *pgrm = fmt_ctx->programs[i];
2631 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2632 int idx = pgrm->stream_index[j];
2633 int vidx = ffvideo.size();
2634 while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
2636 report(", vid%d", vidx);
2639 int aidx = ffaudio.size();
2640 while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
2642 report(", aud%d", aidx);
2645 report(", (%d)", pgrm->stream_index[j]);
2650 AVDictionaryEntry *tag = 0;
2651 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
2652 report("%s=%s\n", tag->key, tag->value);
2661 int FFMPEG::init_decoder(const char *filename)
2663 ff_lock("FFMPEG::init_decoder");
2665 char file_opts[BCTEXTLEN];
2666 strcpy(file_opts, filename);
2667 char *bp = strrchr(file_opts, '/');
2668 if( !bp ) bp = file_opts;
2669 char *sp = strrchr(bp, '.');
2670 if( !sp ) sp = bp + strlen(bp);
2672 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,18,100)
2673 const AVInputFormat *ifmt = 0;
2675 AVInputFormat *ifmt = 0;
2678 strcpy(sp, ".opts");
2679 fp = fopen(file_opts, "r");
2682 read_options(fp, file_opts, opts);
2684 AVDictionaryEntry *tag;
2685 if( (tag=av_dict_get(opts, "format", NULL, 0)) != 0 ) {
2686 ifmt = av_find_input_format(tag->value);
2690 load_options("decode.opts", opts);
2691 AVDictionary *fopts = 0;
2692 av_dict_copy(&fopts, opts, 0);
2693 int ret = avformat_open_input(&fmt_ctx, filename, ifmt, &fopts);
2694 av_dict_free(&fopts);
2696 ret = avformat_find_stream_info(fmt_ctx, NULL);
2701 return !ret ? 0 : 1;
2704 int FFMPEG::open_decoder()
2707 if( stat(fmt_ctx->url, &st) < 0 ) {
2708 eprintf(_("can't stat file: %s\n"), fmt_ctx->url);
2712 int64_t file_bits = 8 * st.st_size;
2713 if( !fmt_ctx->bit_rate && opt_duration > 0 )
2714 fmt_ctx->bit_rate = file_bits / opt_duration;
2717 if( fmt_ctx->bit_rate > 0 ) {
2718 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2719 AVStream *st = fmt_ctx->streams[i];
2720 if( st->duration != AV_NOPTS_VALUE ) continue;
2721 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
2722 st->duration = av_rescale(file_bits, st->time_base.den,
2723 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
2727 if( estimated && !(fflags & FF_ESTM_TIMES) ) {
2728 fflags |= FF_ESTM_TIMES;
2729 printf("FFMPEG::open_decoder: some stream times estimated: %s\n",
2733 ff_lock("FFMPEG::open_decoder");
2734 int ret = 0, bad_time = 0;
2735 for( int i=0; !ret && i<(int)fmt_ctx->nb_streams; ++i ) {
2736 AVStream *st = fmt_ctx->streams[i];
2737 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
2738 AVCodecParameters *avpar = st->codecpar;
2739 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avpar->codec_id);
2740 if( !codec_desc ) continue;
2741 switch( avpar->codec_type ) {
2742 case AVMEDIA_TYPE_VIDEO: {
2743 if( avpar->width < 1 ) continue;
2744 if( avpar->height < 1 ) continue;
2745 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
2746 if( framerate.num < 1 ) continue;
2748 int vidx = ffvideo.size();
2749 FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
2750 vstrm_index.append(ffidx(vidx, 0));
2751 ffvideo.append(vid);
2752 vid->width = avpar->width;
2753 vid->height = avpar->height;
2754 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
2755 switch( avpar->color_range ) {
2756 case AVCOL_RANGE_MPEG:
2757 vid->color_range = BC_COLORS_MPEG;
2759 case AVCOL_RANGE_JPEG:
2760 vid->color_range = BC_COLORS_JPEG;
2763 vid->color_range = !file_base ? BC_COLORS_JPEG :
2764 file_base->file->preferences->yuv_color_range;
2767 switch( avpar->color_space ) {
2768 case AVCOL_SPC_BT470BG:
2769 vid->color_space = BC_COLORS_BT601_PAL;
2771 case AVCOL_SPC_SMPTE170M:
2772 vid->color_space = BC_COLORS_BT601_NTSC;
2774 case AVCOL_SPC_BT709:
2775 vid->color_space = BC_COLORS_BT709;
2777 case AVCOL_SPC_BT2020_NCL:
2778 vid->color_space = BC_COLORS_BT2020_NCL;
2780 case AVCOL_SPC_BT2020_CL:
2781 vid->color_space = BC_COLORS_BT2020_CL;
2784 vid->color_space = !file_base ? BC_COLORS_BT601_NTSC :
2785 file_base->file->preferences->yuv_color_space;
2788 double secs = to_secs(st->duration, st->time_base);
2789 vid->length = secs * vid->frame_rate;
2790 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
2791 vid->nudge = st->start_time;
2793 ret = vid->create_filter(opt_video_filter);
2795 case AVMEDIA_TYPE_AUDIO: {
2796 if( avpar->ch_layout.nb_channels < 1 ) continue;
2797 if( avpar->sample_rate < 1 ) continue;
2799 int aidx = ffaudio.size();
2800 FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
2801 ffaudio.append(aud);
2802 aud->channel0 = astrm_index.size();
2803 aud->channels = avpar->ch_layout.nb_channels;
2804 for( int ch=0; ch<aud->channels; ++ch )
2805 astrm_index.append(ffidx(aidx, ch));
2806 aud->sample_rate = avpar->sample_rate;
2807 double secs = to_secs(st->duration, st->time_base);
2808 aud->length = secs * aud->sample_rate;
2809 aud->init_swr(aud->channels, avpar->format, aud->sample_rate);
2810 aud->nudge = st->start_time;
2812 ret = aud->create_filter(opt_audio_filter);
2817 if( bad_time && !(fflags & FF_BAD_TIMES) ) {
2818 fflags |= FF_BAD_TIMES;
2819 printf(_("FFMPEG::open_decoder: some stream have bad times: %s\n"),
2823 return ret < 0 ? -1 : 0;
2827 int FFMPEG::init_encoder(const char *filename)
2829 // try access first for named pipes
2830 int ret = access(filename, W_OK);
2832 int fd = ::open(filename,O_WRONLY);
2833 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
2834 if( fd >= 0 ) { close(fd); ret = 0; }
2837 eprintf(_("bad file path: %s\n"), filename);
2840 ret = get_file_format();
2842 eprintf(_("bad file format: %s\n"), filename);
2846 eprintf(_("mismatch audio/video file format: %s\n"), filename);
2849 ff_lock("FFMPEG::init_encoder");
2851 char format[BCSTRLEN];
2852 if( get_format(format, "format", file_format) )
2853 strcpy(format, file_format);
2854 avformat_alloc_output_context2(&fmt_ctx, 0, format, filename);
2856 eprintf(_("failed: %s\n"), filename);
2861 load_options("encode.opts", opts);
2867 int FFMPEG::open_encoder(const char *type, const char *spec)
2870 Asset *asset = file_base->asset;
2871 char *filename = asset->path;
2872 AVDictionary *sopts = 0;
2873 av_dict_copy(&sopts, opts, 0);
2874 char option_path[BCTEXTLEN];
2875 set_option_path(option_path, "%s/%s.opts", type, type);
2876 read_options(option_path, sopts);
2877 get_option_path(option_path, type, spec);
2878 char format_name[BCSTRLEN], codec_name[BCTEXTLEN], bsfilter[BCTEXTLEN];
2879 if( get_encoder(option_path, format_name, codec_name, bsfilter) ) {
2880 eprintf(_("get_encoder failed %s:%s\n"), option_path, filename);
2885 if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
2887 else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
2888 else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
2891 ff_lock("FFMPEG::open_encoder");
2894 AVCodecContext *ctx = 0;
2896 const AVCodecDescriptor *codec_desc = 0;
2897 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
2898 const AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
2900 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
2903 eprintf(_("cant find codec %s:%s\n"), codec_name, filename);
2907 codec_desc = avcodec_descriptor_get(codec->id);
2909 eprintf(_("unknown codec %s:%s\n"), codec_name, filename);
2914 st = avformat_new_stream(fmt_ctx, 0);
2916 eprintf(_("cant create stream %s:%s\n"), codec_name, filename);
2921 switch( codec_desc->type ) {
2922 case AVMEDIA_TYPE_AUDIO: {
2924 eprintf(_("duplicate audio %s:%s\n"), codec_name, filename);
2928 if( scan_options(asset->ff_audio_options, sopts, st) ) {
2929 eprintf(_("bad audio options %s:%s\n"), codec_name, filename);
2934 ctx = avcodec_alloc_context3(codec);
2935 if( asset->ff_audio_bitrate > 0 ) {
2936 ctx->bit_rate = asset->ff_audio_bitrate;
2938 sprintf(arg, "%d", asset->ff_audio_bitrate);
2939 av_dict_set(&sopts, "b", arg, 0);
2941 else if( asset->ff_audio_quality >= 0 ) {
2942 ctx->global_quality = asset->ff_audio_quality * FF_QP2LAMBDA;
2943 ctx->qmin = ctx->qmax = asset->ff_audio_quality;
2944 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2945 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2946 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2948 av_dict_set(&sopts, "flags", "+qscale", 0);
2949 sprintf(arg, "%d", asset->ff_audio_quality);
2950 av_dict_set(&sopts, "qscale", arg, 0);
2951 sprintf(arg, "%d", ctx->global_quality);
2952 av_dict_set(&sopts, "global_quality", arg, 0);
2954 int aidx = ffaudio.size();
2955 int fidx = aidx + ffvideo.size();
2956 FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
2957 aud->avctx = ctx; ffaudio.append(aud); fst = aud;
2958 aud->sample_rate = asset->sample_rate;
2959 ctx->ch_layout.nb_channels = aud->channels = asset->channels;
2960 for( int ch=0; ch<aud->channels; ++ch )
2961 astrm_index.append(ffidx(aidx, ch));
2962 AVChannelLayout ch_layout;
2963 av_channel_layout_default(&ch_layout, ctx->ch_layout.nb_channels);
2964 ctx->ch_layout.u.mask = ch_layout.u.mask;
2965 av_channel_layout_copy(&ctx->ch_layout, &ch_layout);
2966 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
2967 if( !ctx->sample_rate ) {
2968 eprintf(_("check_sample_rate failed %s\n"), filename);
2972 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
2973 AVSampleFormat sample_fmt = av_get_sample_fmt(asset->ff_sample_format);
2974 if( sample_fmt == AV_SAMPLE_FMT_NONE )
2975 sample_fmt = codec->sample_fmts ? codec->sample_fmts[0] : AV_SAMPLE_FMT_S16;
2976 ctx->sample_fmt = sample_fmt;
2977 //uint64_t layout = av_get_default_channel_layout(ctx->ch_layout.nb_channels);
2978 AVChannelLayout layout;
2979 av_channel_layout_default(&layout, ctx->ch_layout.nb_channels);
2980 swr_alloc_set_opts2(&aud->resample_context,
2981 &layout, ctx->sample_fmt, aud->sample_rate,
2982 &layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
2984 swr_init(aud->resample_context);
2987 case AVMEDIA_TYPE_VIDEO: {
2989 eprintf(_("duplicate video %s:%s\n"), codec_name, filename);
2993 if( scan_options(asset->ff_video_options, sopts, st) ) {
2994 eprintf(_("bad video options %s:%s\n"), codec_name, filename);
2999 ctx = avcodec_alloc_context3(codec);
3000 if( asset->ff_video_bitrate > 0 ) {
3001 ctx->bit_rate = asset->ff_video_bitrate;
3003 sprintf(arg, "%d", asset->ff_video_bitrate);
3004 av_dict_set(&sopts, "b", arg, 0);
3006 else if( asset->ff_video_quality >= 0 ) {
3007 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
3008 ctx->qmin = ctx->qmax = asset->ff_video_quality;
3009 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
3010 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
3011 ctx->flags |= AV_CODEC_FLAG_QSCALE;
3013 av_dict_set(&sopts, "flags", "+qscale", 0);
3014 sprintf(arg, "%d", asset->ff_video_quality);
3015 av_dict_set(&sopts, "qscale", arg, 0);
3016 sprintf(arg, "%d", ctx->global_quality);
3017 av_dict_set(&sopts, "global_quality", arg, 0);
3019 int vidx = ffvideo.size();
3020 int fidx = vidx + ffaudio.size();
3021 FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
3022 vstrm_index.append(ffidx(vidx, 0));
3023 vid->avctx = ctx; ffvideo.append(vid); fst = vid;
3024 vid->width = asset->width;
3025 vid->height = asset->height;
3026 vid->frame_rate = asset->frame_rate;
3028 char tc_str[20] = "00:00:00:00";
3030 if(asset->timecode > 0)
3031 Units::totext(tc_str, asset->timecode, TIME_HMSF, 0, asset->frame_rate, 0);
3032 //printf("tc: %s \n", tc_str);
3033 av_dict_set(&st->metadata, "timecode", tc_str, 0);
3035 if( (vid->color_range = asset->ff_color_range) < 0 )
3036 vid->color_range = file_base->file->preferences->yuv_color_range;
3037 switch( vid->color_range ) {
3038 case BC_COLORS_MPEG: ctx->color_range = AVCOL_RANGE_MPEG; break;
3039 case BC_COLORS_JPEG: ctx->color_range = AVCOL_RANGE_JPEG; break;
3041 if( (vid->color_space = asset->ff_color_space) < 0 )
3042 vid->color_space = file_base->file->preferences->yuv_color_space;
3043 switch( vid->color_space ) {
3044 case BC_COLORS_BT601_NTSC: ctx->colorspace = AVCOL_SPC_SMPTE170M; break;
3045 case BC_COLORS_BT601_PAL: ctx->colorspace = AVCOL_SPC_BT470BG; break;
3046 case BC_COLORS_BT709: ctx->colorspace = AVCOL_SPC_BT709; break;
3047 case BC_COLORS_BT2020_NCL: ctx->colorspace = AVCOL_SPC_BT2020_NCL; break;
3048 case BC_COLORS_BT2020_CL: ctx->colorspace = AVCOL_SPC_BT2020_CL; break;
3050 AVPixelFormat pix_fmt = av_get_pix_fmt(asset->ff_pixel_format);
3051 if( opt_hw_dev != 0 ) {
3052 AVHWDeviceType hw_type = vid->encode_hw_activate(opt_hw_dev);
3054 case AV_HWDEVICE_TYPE_VAAPI:
3055 pix_fmt = AV_PIX_FMT_VAAPI;
3057 case AV_HWDEVICE_TYPE_NONE:
3061 if( pix_fmt == AV_PIX_FMT_NONE )
3062 pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
3063 ctx->pix_fmt = pix_fmt;
3065 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
3066 int mask_w = (1<<desc->log2_chroma_w)-1;
3067 ctx->width = (vid->width+mask_w) & ~mask_w;
3068 int mask_h = (1<<desc->log2_chroma_h)-1;
3069 ctx->height = (vid->height+mask_h) & ~mask_h;
3070 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
3071 AVRational frame_rate;
3072 if (ctx->codec->id == AV_CODEC_ID_MPEG1VIDEO ||
3073 ctx->codec->id == AV_CODEC_ID_MPEG2VIDEO)
3074 frame_rate = check_frame_rate(codec->supported_framerates, vid->frame_rate);
3076 frame_rate = av_d2q(vid->frame_rate, INT_MAX);
3077 if( !frame_rate.num || !frame_rate.den ) {
3078 eprintf(_("check_frame_rate failed %s\n"), filename);
3082 av_reduce(&frame_rate.num, &frame_rate.den,
3083 frame_rate.num, frame_rate.den, INT_MAX);
3084 ctx->framerate = (AVRational) { frame_rate.num, frame_rate.den };
3085 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
3086 if(!strcmp(format_name, "webm") || !strcmp(format_name, "matroska") || !strcmp(format_name, "mov") ||
3087 !strcmp(format_name, "qt") || !strcmp(format_name, "mp4") || !strcmp(format_name, "avi") ||
3088 !strcmp(format_name, "dv") || !strcmp(format_name, "yuv4mpegpipe"))
3090 if (to_sample_aspect_ratio(asset).den > 0)
3091 st->sample_aspect_ratio = to_sample_aspect_ratio(asset);
3093 st->avg_frame_rate = frame_rate;
3094 st->time_base = ctx->time_base;
3096 vid->interlaced = asset->interlace_mode == ILACE_MODE_TOP_FIRST ||
3097 asset->interlace_mode == ILACE_MODE_BOTTOM_FIRST ? 1 : 0;
3098 vid->top_field_first = asset->interlace_mode == ILACE_MODE_TOP_FIRST ? 1 : 0;
3099 switch (asset->interlace_mode) {
3100 case ILACE_MODE_TOP_FIRST:
3101 if (ctx->codec->id == AV_CODEC_ID_MJPEG)
3102 av_dict_set(&sopts, "field_order", "tt", 0);
3104 av_dict_set(&sopts, "field_order", "tb", 0);
3105 if (ctx->codec_id != AV_CODEC_ID_MJPEG)
3106 av_dict_set(&sopts, "flags", "+ilme+ildct", 0);
3108 case ILACE_MODE_BOTTOM_FIRST:
3109 if (ctx->codec->id == AV_CODEC_ID_MJPEG)
3110 av_dict_set(&sopts, "field_order", "bb", 0);
3112 av_dict_set(&sopts, "field_order", "bt", 0);
3113 if (ctx->codec_id != AV_CODEC_ID_MJPEG)
3114 av_dict_set(&sopts, "flags", "+ilme+ildct", 0);
3116 case ILACE_MODE_NOTINTERLACED: av_dict_set(&sopts, "field_order", "progressive", 0); break;
3120 eprintf(_("not audio/video, %s:%s\n"), codec_name, filename);
3125 AVDictionaryEntry *tag;
3126 if( (tag=av_dict_get(sopts, "cin_stats_filename", NULL, 0)) != 0 ) {
3127 char suffix[BCSTRLEN]; sprintf(suffix,"-%d.log",fst->fidx);
3128 fst->stats_filename = cstrcat(2, tag->value, suffix);
3130 if( (tag=av_dict_get(sopts, "flags", NULL, 0)) != 0 ) {
3131 int pass = fst->pass;
3132 char *cp = tag->value;
3134 int ch = *cp++, pfx = ch=='-' ? -1 : ch=='+' ? 1 : 0;
3135 if( !isalnum(!pfx ? ch : (ch=*cp++)) ) continue;
3136 char id[BCSTRLEN], *bp = id, *ep = bp+sizeof(id)-1;
3137 for( *bp++=ch; isalnum(ch=*cp); ++cp )
3138 if( bp < ep ) *bp++ = ch;
3140 if( !strcmp(id, "pass1") ) {
3141 pass = pfx<0 ? (pass&~1) : pfx>0 ? (pass|1) : 1;
3143 else if( !strcmp(id, "pass2") ) {
3144 pass = pfx<0 ? (pass&~2) : pfx>0 ? (pass|2) : 2;
3147 if( (fst->pass=pass) ) {
3148 if( pass & 1 ) ctx->flags |= AV_CODEC_FLAG_PASS1;
3149 if( pass & 2 ) ctx->flags |= AV_CODEC_FLAG_PASS2;
3155 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
3156 ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
3157 if( fst->stats_filename && (ret=fst->init_stats_file()) )
3158 eprintf(_("error: stats file = %s\n"), fst->stats_filename);
3161 av_dict_set(&sopts, "cin_bitrate", 0, 0);
3162 av_dict_set(&sopts, "cin_quality", 0, 0);
3164 if( !av_dict_get(sopts, "threads", NULL, 0) )
3165 ctx->thread_count = ff_cpus();
3166 ret = avcodec_open2(ctx, codec, &sopts);
3168 ret = avcodec_parameters_from_context(st->codecpar, ctx);
3170 fprintf(stderr, "Could not copy the stream parameters\n");
3173 _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
3174 #if LIBAVCODEC_VERSION_INT <= AV_VERSION_INT(58,134,100)
3175 ret = avcodec_copy_context(st->codec, ctx);
3177 ret = avcodec_parameters_to_context(ctx, st->codecpar);
3179 _Pragma("GCC diagnostic warning \"-Wdeprecated-declarations\"")
3181 fprintf(stderr, "Could not copy the stream context\n");
3184 ff_err(ret,"FFMPEG::open_encoder");
3185 eprintf(_("open failed %s:%s\n"), codec_name, filename);
3191 if( !ret && fst && bsfilter[0] ) {
3192 ret = av_bsf_list_parse_str(bsfilter, &fst->bsfc);
3194 ff_err(ret,"FFMPEG::open_encoder");
3195 eprintf(_("bitstream filter failed %s:\n%s\n"), filename, bsfilter);
3206 av_dict_free(&sopts);
3210 int FFMPEG::close_encoder()
3213 if( encoding > 0 ) {
3214 av_write_trailer(fmt_ctx);
3215 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
3216 avio_closep(&fmt_ctx->pb);
3222 int FFMPEG::decode_activate()
3224 if( decoding < 0 ) {
3226 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
3227 ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
3228 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
3229 ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
3230 // set nudges for each program stream set
3231 const int64_t min_nudge = INT64_MIN+1;
3232 int npgrms = fmt_ctx->nb_programs;
3233 for( int i=0; i<npgrms; ++i ) {
3234 AVProgram *pgrm = fmt_ctx->programs[i];
3235 // first start time video stream
3236 int64_t vstart_time = min_nudge, astart_time = min_nudge;
3237 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
3238 int fidx = pgrm->stream_index[j];
3239 AVStream *st = fmt_ctx->streams[fidx];
3240 AVCodecParameters *avpar = st->codecpar;
3241 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
3242 if( st->start_time == AV_NOPTS_VALUE ) continue;
3243 if( vstart_time < st->start_time )
3244 vstart_time = st->start_time;
3247 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
3248 if( st->start_time == AV_NOPTS_VALUE ) continue;
3249 if( astart_time < st->start_time )
3250 astart_time = st->start_time;
3254 //since frame rate is much more grainy than sample rate, it is better to
3255 // align using video, so that total absolute error is minimized.
3256 int64_t nudge = vstart_time > min_nudge ? vstart_time :
3257 astart_time > min_nudge ? astart_time : AV_NOPTS_VALUE;
3258 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
3259 int fidx = pgrm->stream_index[j];
3260 AVStream *st = fmt_ctx->streams[fidx];
3261 AVCodecParameters *avpar = st->codecpar;
3262 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
3263 for( int k=0; k<ffvideo.size(); ++k ) {
3264 if( ffvideo[k]->fidx != fidx ) continue;
3265 ffvideo[k]->nudge = nudge;
3269 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
3270 for( int k=0; k<ffaudio.size(); ++k ) {
3271 if( ffaudio[k]->fidx != fidx ) continue;
3272 ffaudio[k]->nudge = nudge;
3278 // set nudges for any streams not yet set
3279 int64_t vstart_time = min_nudge, astart_time = min_nudge;
3280 int nstreams = fmt_ctx->nb_streams;
3281 for( int i=0; i<nstreams; ++i ) {
3282 AVStream *st = fmt_ctx->streams[i];
3283 AVCodecParameters *avpar = st->codecpar;
3284 switch( avpar->codec_type ) {
3285 case AVMEDIA_TYPE_VIDEO: {
3286 if( st->start_time == AV_NOPTS_VALUE ) continue;
3287 int vidx = ffvideo.size();
3288 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
3289 if( vidx < 0 ) continue;
3290 if( ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
3291 if( vstart_time < st->start_time )
3292 vstart_time = st->start_time;
3294 case AVMEDIA_TYPE_AUDIO: {
3295 if( st->start_time == AV_NOPTS_VALUE ) continue;
3296 int aidx = ffaudio.size();
3297 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
3298 if( aidx < 0 ) continue;
3299 if( ffaudio[aidx]->frame_sz < avpar->frame_size )
3300 ffaudio[aidx]->frame_sz = avpar->frame_size;
3301 if( ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
3302 if( astart_time < st->start_time )
3303 astart_time = st->start_time;
3308 int64_t nudge = vstart_time > min_nudge ? vstart_time :
3309 astart_time > min_nudge ? astart_time : 0;
3310 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
3311 if( ffvideo[vidx]->nudge == AV_NOPTS_VALUE )
3312 ffvideo[vidx]->nudge = nudge;
3314 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
3315 if( ffaudio[aidx]->nudge == AV_NOPTS_VALUE )
3316 ffaudio[aidx]->nudge = nudge;
3323 int FFMPEG::encode_activate()
3326 if( encoding < 0 ) {
3328 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
3329 (ret=avio_open(&fmt_ctx->pb, fmt_ctx->url, AVIO_FLAG_WRITE)) < 0 ) {
3330 ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
3334 if( !strcmp(file_format, "image2") ) {
3335 Asset *asset = file_base->asset;
3336 const char *filename = asset->path;
3337 FILE *fp = fopen(filename,"w");
3339 eprintf(_("Cant write image2 header file: %s\n %m"), filename);
3342 fprintf(fp, "IMAGE2\n");
3343 fprintf(fp, "# Frame rate: %f\n", asset->frame_rate);
3344 fprintf(fp, "# Width: %d\n", asset->width);
3345 fprintf(fp, "# Height: %d\n", asset->height);
3349 AVProgram *prog = av_new_program(fmt_ctx, prog_id);
3350 for( int i=0; i< ffvideo.size(); ++i )
3351 av_program_add_stream_index(fmt_ctx, prog_id, ffvideo[i]->fidx);
3352 for( int i=0; i< ffaudio.size(); ++i )
3353 av_program_add_stream_index(fmt_ctx, prog_id, ffaudio[i]->fidx);
3354 int pi = fmt_ctx->nb_programs;
3355 while( --pi >= 0 && fmt_ctx->programs[pi]->id != prog_id );
3356 AVDictionary **meta = &prog->metadata;
3357 av_dict_set(meta, "service_provider", "cin5", 0);
3358 const char *path = fmt_ctx->url, *bp = strrchr(path,'/');
3359 if( bp ) path = bp + 1;
3360 av_dict_set(meta, "title", path, 0);
3362 if( ffaudio.size() ) {
3363 const char *ep = getenv("CIN_AUDIO_LANG"), *lp = 0;
3364 if( !ep && (lp=getenv("LANG")) ) { // some are guesses
3365 static struct { const char lc[3], lng[4]; } lcode[] = {
3366 { "en", "eng" }, { "de", "ger" }, { "es", "spa" },
3367 { "eu", "bas" }, { "fr", "fre" }, { "el", "gre" },
3368 { "hi", "hin" }, { "it", "ita" }, { "ja", "jap" },
3369 { "ko", "kor" }, { "du", "dut" }, { "pl", "pol" },
3370 { "pt", "por" }, { "ru", "rus" }, { "sl", "slv" },
3371 { "uk", "ukr" }, { "vi", "vie" }, { "zh", "chi" },
3373 for( int i=sizeof(lcode)/sizeof(lcode[0]); --i>=0 && !ep; )
3374 if( !strncmp(lcode[i].lc,lp,2) ) ep = lcode[i].lng;
3376 if( !ep ) ep = "und";
3378 strncpy(lang,ep,3); lang[3] = 0;
3379 AVStream *st = ffaudio[0]->st;
3380 av_dict_set(&st->metadata,"language",lang,0);
3383 AVDictionary *fopts = 0;
3384 char option_path[BCTEXTLEN];
3385 set_option_path(option_path, "format/%s", file_format);
3386 read_options(option_path, fopts, 1);
3387 av_dict_copy(&fopts, opts, 0);
3388 if( scan_options(file_base->asset->ff_format_options, fopts, 0) ) {
3389 eprintf(_("bad format options %s\n"), file_base->asset->path);
3393 ret = avformat_write_header(fmt_ctx, &fopts);
3395 ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
3399 av_dict_free(&fopts);
3406 int FFMPEG::audio_seek(int stream, int64_t pos)
3408 int aidx = astrm_index[stream].st_idx;
3409 FFAudioStream *aud = ffaudio[aidx];
3410 aud->audio_seek(pos);
3414 int FFMPEG::video_probe(int64_t pos)
3416 int vidx = vstrm_index[0].st_idx;
3417 FFVideoStream *vid = ffvideo[vidx];
3420 int interlace1 = interlace_from_codec;
3421 //printf("interlace from codec: %i\n", interlace1);
3427 return ILACE_MODE_TOP_FIRST;
3430 return ILACE_MODE_BOTTOM_FIRST;
3431 case AV_FIELD_PROGRESSIVE:
3432 return ILACE_MODE_NOTINTERLACED;
3434 return ILACE_MODE_UNDETECTED;
3441 int FFMPEG::video_seek(int stream, int64_t pos)
3443 int vidx = vstrm_index[stream].st_idx;
3444 FFVideoStream *vid = ffvideo[vidx];
3445 vid->video_seek(pos);
3450 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
3452 if( !has_audio || chn >= astrm_index.size() ) return -1;
3453 int aidx = astrm_index[chn].st_idx;
3454 FFAudioStream *aud = ffaudio[aidx];
3455 if( aud->load(pos, len) < len ) return -1;
3456 int ch = astrm_index[chn].st_ch;
3457 int ret = aud->read(samples,len,ch);
3461 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
3463 if( !has_video || layer >= vstrm_index.size() ) return -1;
3464 int vidx = vstrm_index[layer].st_idx;
3465 FFVideoStream *vid = ffvideo[vidx];
3466 return vid->load(vframe, pos);
3470 int FFMPEG::encode(int stream, double **samples, int len)
3472 FFAudioStream *aud = ffaudio[stream];
3473 return aud->encode(samples, len);
3477 int FFMPEG::encode(int stream, VFrame *frame)
3479 FFVideoStream *vid = ffvideo[stream];
3480 return vid->encode(frame);
3483 void FFMPEG::start_muxer()
3491 void FFMPEG::stop_muxer()
3500 void FFMPEG::flow_off()
3503 flow_lock->lock("FFMPEG::flow_off");
3507 void FFMPEG::flow_on()
3511 flow_lock->unlock();
3514 void FFMPEG::flow_ctl()
3517 flow_lock->lock("FFMPEG::flow_ctl");
3518 flow_lock->unlock();
3522 int FFMPEG::mux_audio(FFrame *frm)
3524 FFStream *fst = frm->fst;
3525 AVCodecContext *ctx = fst->avctx;
3526 AVFrame *frame = *frm;
3527 AVRational tick_rate = {1, ctx->sample_rate};
3528 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
3529 int ret = fst->encode_frame(frame);
3531 ff_err(ret, "FFMPEG::mux_audio");
3532 return ret >= 0 ? 0 : 1;
3535 int FFMPEG::mux_video(FFrame *frm)
3537 FFStream *fst = frm->fst;
3538 AVFrame *frame = *frm;
3539 frame->pts = frm->position;
3540 int ret = fst->encode_frame(frame);
3542 ff_err(ret, "FFMPEG::mux_video");
3543 return ret >= 0 ? 0 : 1;
3549 double atm = -1, vtm = -1;
3550 FFrame *afrm = 0, *vfrm = 0;
3552 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
3553 FFStream *fst = ffaudio[i];
3554 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
3555 FFrame *frm = fst->frms.first;
3556 if( !frm ) { if( !done ) return; continue; }
3557 double tm = to_secs(frm->position, fst->avctx->time_base);
3558 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
3560 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
3561 FFStream *fst = ffvideo[i];
3562 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
3563 FFrame *frm = fst->frms.first;
3564 if( !frm ) { if( !done ) return; continue; }
3565 double tm = to_secs(frm->position, fst->avctx->time_base);
3566 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
3568 if( !demand ) flow_off();
3569 if( !afrm && !vfrm ) break;
3570 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
3571 vfrm->position, vfrm->fst->avctx->time_base,
3572 afrm->position, afrm->fst->avctx->time_base);
3573 FFrame *frm = v <= 0 ? vfrm : afrm;
3574 if( frm == afrm ) mux_audio(frm);
3575 if( frm == vfrm ) mux_video(frm);
3584 mux_lock->lock("FFMPEG::run");
3587 for( int i=0; i<ffaudio.size(); ++i )
3588 ffaudio[i]->drain();
3589 for( int i=0; i<ffvideo.size(); ++i )
3590 ffvideo[i]->drain();
3592 for( int i=0; i<ffaudio.size(); ++i )
3593 ffaudio[i]->flush();
3594 for( int i=0; i<ffvideo.size(); ++i )
3595 ffvideo[i]->flush();
3599 int FFMPEG::ff_total_audio_channels()
3601 return astrm_index.size();
3604 int FFMPEG::ff_total_astreams()
3606 return ffaudio.size();
3609 int FFMPEG::ff_audio_channels(int stream)
3611 return ffaudio[stream]->channels;
3614 int FFMPEG::ff_sample_rate(int stream)
3616 return ffaudio[stream]->sample_rate;
3619 const char* FFMPEG::ff_audio_format(int stream)
3621 AVStream *st = ffaudio[stream]->st;
3622 AVCodecID id = st->codecpar->codec_id;
3623 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
3624 return desc ? desc->name : _("Unknown");
3627 int FFMPEG::ff_audio_pid(int stream)
3629 return ffaudio[stream]->st->id;
3632 int64_t FFMPEG::ff_audio_samples(int stream)
3634 return ffaudio[stream]->length;
3637 // find audio astream/channels with this program,
3638 // or all program audio channels (astream=-1)
3639 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
3643 int vidx = ffvideo[vstream]->fidx;
3644 // find first program with this video stream
3645 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
3646 AVProgram *pgrm = fmt_ctx->programs[i];
3647 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
3648 int st_idx = pgrm->stream_index[j];
3649 AVStream *st = fmt_ctx->streams[st_idx];
3650 if( st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
3651 if( st_idx == vidx ) pidx = i;
3654 if( pidx < 0 ) return -1;
3656 int64_t channels = 0;
3657 AVProgram *pgrm = fmt_ctx->programs[pidx];
3658 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
3659 int aidx = pgrm->stream_index[j];
3660 AVStream *st = fmt_ctx->streams[aidx];
3661 if( st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
3662 if( astream > 0 ) { --astream; continue; }
3664 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
3665 if( ffaudio[i]->fidx == aidx ) astrm = i;
3667 if( ret < 0 ) ret = astrm;
3668 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
3669 channels |= mask << ffaudio[astrm]->channel0;
3671 if( !astream ) break;
3673 channel_mask = channels;
3678 int FFMPEG::ff_total_video_layers()
3680 return vstrm_index.size();
3683 int FFMPEG::ff_total_vstreams()
3685 return ffvideo.size();
3688 int FFMPEG::ff_video_width(int stream)
3690 FFVideoStream *vst = ffvideo[stream];
3691 return !vst->transpose ? vst->width : vst->height;
3694 int FFMPEG::ff_video_height(int stream)
3696 FFVideoStream *vst = ffvideo[stream];
3697 return !vst->transpose ? vst->height : vst->width;
3700 int FFMPEG::ff_set_video_width(int stream, int width)
3702 FFVideoStream *vst = ffvideo[stream];
3703 int *vw = !vst->transpose ? &vst->width : &vst->height, w = *vw;
3708 int FFMPEG::ff_set_video_height(int stream, int height)
3710 FFVideoStream *vst = ffvideo[stream];
3711 int *vh = !vst->transpose ? &vst->height : &vst->width, h = *vh;
3716 int FFMPEG::ff_coded_width(int stream)
3718 return ffvideo[stream]->avctx->coded_width;
3721 int FFMPEG::ff_coded_height(int stream)
3723 return ffvideo[stream]->avctx->coded_height;
3726 float FFMPEG::ff_aspect_ratio(int stream)
3728 //return ffvideo[stream]->aspect_ratio;
3729 AVFormatContext *fmt_ctx = ffvideo[stream]->fmt_ctx;
3730 AVStream *strm = ffvideo[stream]->st;
3731 AVCodecParameters *par = ffvideo[stream]->st->codecpar;
3733 AVRational sar = av_guess_sample_aspect_ratio(fmt_ctx, strm, NULL);
3734 if (sar.num && ffvideo[stream]->get_rotation_angle() == 0) {
3735 av_reduce(&dar.num, &dar.den,
3736 par->width * sar.num,
3737 par->height * sar.den,
3741 return ffvideo[stream]->aspect_ratio;
3744 const char* FFMPEG::ff_video_codec(int stream)
3746 AVStream *st = ffvideo[stream]->st;
3747 AVCodecID id = st->codecpar->codec_id;
3748 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
3749 return desc ? desc->name : _("Unknown");
3752 int FFMPEG::ff_color_range(int stream)
3754 return ffvideo[stream]->color_range;
3757 int FFMPEG::ff_color_space(int stream)
3759 return ffvideo[stream]->color_space;
3762 double FFMPEG::ff_frame_rate(int stream)
3764 return ffvideo[stream]->frame_rate;
3767 int64_t FFMPEG::ff_video_frames(int stream)
3769 return ffvideo[stream]->length;
3772 int FFMPEG::ff_video_pid(int stream)
3774 return ffvideo[stream]->st->id;
3777 int FFMPEG::ff_video_mpeg_color_range(int stream)
3779 return ffvideo[stream]->st->codecpar->color_range == AVCOL_RANGE_MPEG ? 1 : 0;
3782 int FFMPEG::ff_interlace(int stream)
3784 // https://ffmpeg.org/doxygen/trunk/structAVCodecParserContext.html
3785 /* reads from demuxer because codec frame not ready */
3786 int interlace0 = ffvideo[stream]->st->codecpar->field_order;
3792 return ILACE_MODE_TOP_FIRST;
3795 return ILACE_MODE_BOTTOM_FIRST;
3796 case AV_FIELD_PROGRESSIVE:
3797 return ILACE_MODE_NOTINTERLACED;
3799 return ILACE_MODE_UNDETECTED;
3806 int FFMPEG::ff_cpus()
3808 return !file_base ? 1 : file_base->file->cpus;
3811 const char *FFMPEG::ff_hw_dev()
3813 return &file_base->file->preferences->use_hw_dev[0];
3816 Preferences *FFMPEG::ff_prefs()
3818 return !file_base ? 0 : file_base->file->preferences;
3821 double FFVideoStream::get_rotation_angle()
3823 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
3828 int *matrix = (int*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX, &size);
3829 int len = size/sizeof(*matrix);
3830 if( !matrix || len < 5 ) return 0;
3831 const double s = 1/65536.;
3832 double theta = (!matrix[0] && !matrix[3]) || (!matrix[1] && !matrix[4]) ? 0 :
3833 atan2( s*matrix[1] / hypot(s*matrix[1], s*matrix[4]),
3834 s*matrix[0] / hypot(s*matrix[0], s*matrix[3])) * 180/M_PI;
3838 int FFVideoStream::flip(double theta)
3842 Preferences *preferences = ffmpeg->ff_prefs();
3843 if( !preferences || !preferences->auto_rotate ) return ret;
3844 double tolerance = 1;
3845 if( fabs(theta-0) < tolerance ) return ret;
3846 if( (theta=fmod(theta, 360)) < 0 ) theta += 360;
3847 if( fabs(theta-90) < tolerance ) {
3848 if( (ret = insert_filter("transpose", "clock")) < 0 )
3852 else if( fabs(theta-180) < tolerance ) {
3853 if( (ret=insert_filter("hflip", 0)) < 0 )
3855 if( (ret=insert_filter("vflip", 0)) < 0 )
3858 else if (fabs(theta-270) < tolerance ) {
3859 if( (ret=insert_filter("transpose", "cclock")) < 0 )
3864 char angle[BCSTRLEN];
3865 sprintf(angle, "%f", theta*M_PI/180.);
3866 if( (ret=insert_filter("rotate", angle)) < 0 )
3872 int FFVideoStream::create_filter(const char *filter_spec)
3874 double theta = get_rotation_angle();
3875 if( !theta && !filter_spec )
3877 avfilter_register_all();
3879 const char *sp = filter_spec;
3880 char filter_name[BCSTRLEN], *np = filter_name;
3881 int i = sizeof(filter_name);
3882 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
3884 const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
3885 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_VIDEO ) {
3886 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
3890 AVCodecParameters *avpar = st->codecpar;
3891 int sa_num = avpar->sample_aspect_ratio.num;
3892 if( !sa_num ) sa_num = 1;
3893 int sa_den = avpar->sample_aspect_ratio.den;
3894 if( !sa_den ) sa_num = 1;
3896 int ret = 0; char args[BCTEXTLEN];
3897 AVPixelFormat pix_fmt = (AVPixelFormat)avpar->format;
3898 snprintf(args, sizeof(args),
3899 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
3900 avpar->width, avpar->height, (int)pix_fmt,
3901 st->time_base.num, st->time_base.den, sa_num, sa_den);
3904 ret = insert_filter("buffer", args, "in");
3905 buffersrc_ctx = filt_ctx;
3909 AVFilterContext *fsrc = filt_ctx;
3912 ret = insert_filter("buffersink", 0, "out");
3913 buffersink_ctx = filt_ctx;
3916 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
3917 (uint8_t*)&pix_fmt, sizeof(pix_fmt),
3918 AV_OPT_SEARCH_CHILDREN);
3921 ret = config_filters(filter_spec, fsrc);
3923 ff_err(ret, "FFVideoStream::create_filter");
3924 return ret >= 0 ? 0 : -1;
3927 int FFAudioStream::create_filter(const char *filter_spec)
3931 avfilter_register_all();
3933 const char *sp = filter_spec;
3934 char filter_name[BCSTRLEN], *np = filter_name;
3935 int i = sizeof(filter_name);
3936 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
3938 const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
3939 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_AUDIO ) {
3940 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
3944 int ret = 0; char args[BCTEXTLEN];
3945 AVCodecParameters *avpar = st->codecpar;
3946 AVSampleFormat sample_fmt = (AVSampleFormat)avpar->format;
3947 snprintf(args, sizeof(args),
3948 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
3949 st->time_base.num, st->time_base.den, avpar->sample_rate,
3950 av_get_sample_fmt_name(sample_fmt), avpar->ch_layout.u.mask);
3953 ret = insert_filter("abuffer", args, "in");
3954 buffersrc_ctx = filt_ctx;
3956 AVFilterContext *fsrc = filt_ctx;
3959 ret = insert_filter("abuffersink", 0, "out");
3960 buffersink_ctx = filt_ctx;
3963 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
3964 (uint8_t*)&sample_fmt, sizeof(sample_fmt),
3965 AV_OPT_SEARCH_CHILDREN);
3967 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
3968 (uint8_t*)&avpar->ch_layout.u.mask,
3969 sizeof(avpar->ch_layout.u.mask), AV_OPT_SEARCH_CHILDREN);
3971 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
3972 (uint8_t*)&sample_rate, sizeof(sample_rate),
3973 AV_OPT_SEARCH_CHILDREN);
3975 ret = config_filters(filter_spec, fsrc);
3977 ff_err(ret, "FFAudioStream::create_filter");
3978 return ret >= 0 ? 0 : -1;
3981 int FFStream::insert_filter(const char *name, const char *arg, const char *inst_name)
3983 const AVFilter *filter = avfilter_get_by_name(name);
3984 if( !filter ) return -1;
3985 char filt_inst[BCSTRLEN];
3987 snprintf(filt_inst, sizeof(filt_inst), "%s_%d", name, ++filt_id);
3988 inst_name = filt_inst;
3991 filter_graph = avfilter_graph_alloc();
3992 AVFilterContext *fctx = 0;
3993 int ret = avfilter_graph_create_filter(&fctx,
3994 filter, inst_name, arg, NULL, filter_graph);
3995 if( ret >= 0 && filt_ctx )
3996 ret = avfilter_link(filt_ctx, 0, fctx, 0);
4000 avfilter_free(fctx);
4004 int FFStream::config_filters(const char *filter_spec, AVFilterContext *fsrc)
4007 AVFilterContext *fsink = buffersink_ctx;
4009 /* Endpoints for the filter graph. */
4010 AVFilterInOut *outputs = avfilter_inout_alloc();
4011 AVFilterInOut *inputs = avfilter_inout_alloc();
4012 if( !inputs || !outputs ) ret = -1;
4014 outputs->filter_ctx = fsrc;
4015 outputs->pad_idx = 0;
4017 if( !(outputs->name = av_strdup(fsrc->name)) ) ret = -1;
4020 inputs->filter_ctx = fsink;
4021 inputs->pad_idx = 0;
4023 if( !(inputs->name = av_strdup(fsink->name)) ) ret = -1;
4026 int len = strlen(fsrc->name)+2 + strlen(filter_spec) + 1;
4027 char spec[len]; sprintf(spec, "[%s]%s", fsrc->name, filter_spec);
4028 ret = avfilter_graph_parse_ptr(filter_graph, spec,
4029 &inputs, &outputs, NULL);
4031 avfilter_inout_free(&inputs);
4032 avfilter_inout_free(&outputs);
4035 ret = avfilter_link(fsrc, 0, fsink, 0);
4037 ret = avfilter_graph_config(filter_graph, NULL);
4039 ff_err(ret, "FFStream::create_filter");
4040 avfilter_graph_free(&filter_graph);
4047 AVCodecContext *FFMPEG::activate_decoder(AVStream *st)
4049 AVDictionary *copts = 0;
4050 av_dict_copy(&copts, opts, 0);
4051 AVCodecID codec_id = st->codecpar->codec_id;
4052 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
4053 const AVCodec *decoder = 0;
4055 AVCodec *decoder = 0;
4057 switch( st->codecpar->codec_type ) {
4058 case AVMEDIA_TYPE_VIDEO:
4059 if( opt_video_decoder )
4060 decoder = avcodec_find_decoder_by_name(opt_video_decoder);
4062 video_codec_remaps.update(codec_id, decoder);
4064 case AVMEDIA_TYPE_AUDIO:
4065 if( opt_audio_decoder )
4066 decoder = avcodec_find_decoder_by_name(opt_audio_decoder);
4068 audio_codec_remaps.update(codec_id, decoder);
4073 if( !decoder && !(decoder = avcodec_find_decoder(codec_id)) ) {
4074 eprintf(_("cant find decoder codec %d\n"), (int)codec_id);
4077 AVCodecContext *avctx = avcodec_alloc_context3(decoder);
4079 eprintf(_("cant allocate codec context\n"));
4082 avcodec_parameters_to_context(avctx, st->codecpar);
4083 if( !av_dict_get(copts, "threads", NULL, 0) )
4084 avctx->thread_count = ff_cpus();
4085 int ret = avcodec_open2(avctx, decoder, &copts);
4086 av_dict_free(&copts);
4088 avcodec_free_context(&avctx);
4094 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
4097 av_init_packet(&pkt);
4098 AVFrame *frame = av_frame_alloc();
4100 fprintf(stderr,"FFMPEG::scan: ");
4101 fprintf(stderr,_("av_frame_alloc failed\n"));
4102 fprintf(stderr,"FFMPEG::scan:file=%s\n", file_base->asset->path);
4106 index_state->add_video_markers(ffvideo.size());
4107 index_state->add_audio_markers(ffaudio.size());
4109 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
4110 AVStream *st = fmt_ctx->streams[i];
4111 AVCodecContext *avctx = activate_decoder(st);
4113 AVCodecParameters *avpar = st->codecpar;
4114 switch( avpar->codec_type ) {
4115 case AVMEDIA_TYPE_VIDEO: {
4116 int vidx = ffvideo.size();
4117 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
4118 if( vidx < 0 ) break;
4119 ffvideo[vidx]->avctx = avctx;
4121 case AVMEDIA_TYPE_AUDIO: {
4122 int aidx = ffaudio.size();
4123 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
4124 if( aidx < 0 ) break;
4125 ffaudio[aidx]->avctx = avctx;
4130 fprintf(stderr,"FFMPEG::scan: ");
4131 fprintf(stderr,_("codec open failed\n"));
4132 fprintf(stderr,"FFMPEG::scan:file=%s\n", file_base->asset->path);
4133 avcodec_free_context(&avctx);
4137 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
4138 AVStream *st = fmt_ctx->streams[i];
4139 AVCodecParameters *avpar = st->codecpar;
4140 if( avpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
4141 int64_t tstmp = st->start_time;
4142 if( tstmp == AV_NOPTS_VALUE ) continue;
4143 int aidx = ffaudio.size();
4144 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
4145 if( aidx < 0 ) continue;
4146 FFAudioStream *aud = ffaudio[aidx];
4147 tstmp -= aud->nudge;
4148 double secs = to_secs(tstmp, st->time_base);
4149 aud->curr_pos = secs * aud->sample_rate + 0.5;
4153 for( int64_t count=0; !*canceled; ++count ) {
4154 av_packet_unref(&pkt);
4155 pkt.data = 0; pkt.size = 0;
4157 int ret = av_read_frame(fmt_ctx, &pkt);
4159 if( ret == AVERROR_EOF ) break;
4160 if( ++errs > 100 ) {
4161 ff_err(ret,_("over 100 read_frame errs\n"));
4166 if( !pkt.data ) continue;
4167 int i = pkt.stream_index;
4168 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
4169 AVStream *st = fmt_ctx->streams[i];
4170 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
4172 AVCodecParameters *avpar = st->codecpar;
4173 switch( avpar->codec_type ) {
4174 case AVMEDIA_TYPE_VIDEO: {
4175 int vidx = ffvideo.size();
4176 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
4177 if( vidx < 0 ) break;
4178 FFVideoStream *vid = ffvideo[vidx];
4179 if( !vid->avctx ) break;
4180 int64_t tstmp = pkt.pts;
4181 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
4182 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
4183 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
4184 double secs = to_secs(tstmp, st->time_base);
4185 int64_t frm = secs * vid->frame_rate + 0.5;
4186 if( frm < 0 ) frm = 0;
4187 index_state->put_video_mark(vidx, frm, pkt.pos);
4190 ret = avcodec_send_packet(vid->avctx, pkt);
4191 if( ret < 0 ) break;
4192 while( (ret=vid->decode_frame(frame)) > 0 ) {}
4195 case AVMEDIA_TYPE_AUDIO: {
4196 int aidx = ffaudio.size();
4197 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
4198 if( aidx < 0 ) break;
4199 FFAudioStream *aud = ffaudio[aidx];
4200 if( !aud->avctx ) break;
4201 int64_t tstmp = pkt.pts;
4202 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
4203 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
4204 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
4205 double secs = to_secs(tstmp, st->time_base);
4206 int64_t sample = secs * aud->sample_rate + 0.5;
4208 index_state->put_audio_mark(aidx, sample, pkt.pos);
4210 ret = avcodec_send_packet(aud->avctx, &pkt);
4211 if( ret < 0 ) break;
4212 int ch = aud->channel0, nch = aud->channels;
4213 int64_t pos = index_state->pos(ch);
4214 if( pos != aud->curr_pos ) {
4215 if( abs(pos-aud->curr_pos) > 1 )
4216 printf("audio%d pad %jd %jd (%jd)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
4217 index_state->pad_data(ch, nch, aud->curr_pos);
4219 while( (ret=aud->decode_frame(frame)) > 0 ) {
4220 //if( frame->channels != nch ) break;
4221 aud->init_swr(frame->ch_layout.nb_channels, frame->format, frame->sample_rate);
4223 int len = aud->get_samples(samples,
4224 &frame->extended_data[0], frame->nb_samples);
4225 pos = aud->curr_pos;
4226 if( (aud->curr_pos += len) >= 0 ) {
4228 samples += -pos * nch;
4229 len = aud->curr_pos;
4231 for( int i=0; i<nch; ++i )
4232 index_state->put_data(ch+i,nch,samples+i,len);
4239 av_frame_free(&frame);
4243 void FFStream::load_markers(IndexMarks &marks, double rate)
4246 int64_t sz = marks.size();
4247 int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
4248 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
4249 int nb_ent = avformat_index_get_entries_count(st);
4251 #if LIBAVCODEC_VERSION_INT <= AV_VERSION_INT(58,134,100)
4252 int nb_ent = st->nb_index_entries;
4254 // some formats already have an index
4256 #if LIBAVCODEC_VERSION_INT <= AV_VERSION_INT(58,134,100)
4257 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
4259 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(59,16,100)
4260 const AVIndexEntry *ep = avformat_index_get_entry(st, nb_ent-1);
4262 int64_t tstmp = ep->timestamp;
4263 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
4264 double secs = ffmpeg->to_secs(tstmp, st->time_base);
4265 int64_t no = secs * rate;
4266 while( in < sz && marks[in].no <= no ) ++in;
4268 int64_t len = sz - in;
4269 int64_t count = max_entries - nb_ent;
4270 if( count > len ) count = len;
4271 for( int i=0; i<count; ++i ) {
4272 int k = in + i * len / count;
4273 int64_t no = marks[k].no, pos = marks[k].pos;
4274 double secs = (double)no / rate;
4275 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
4276 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
4277 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);
4283 * 1) if the format context has a timecode
4284 * return fmt_ctx->timecode - 0
4285 * 2) if the layer/channel has a timecode
4286 * return st->timecode - (start_time-nudge)
4287 * 3) find the 1st program with stream, find 1st program video stream,
4288 * if video stream has a timecode, return st->timecode - (start_time-nudge)
4289 * 4) find timecode in any stream, return st->timecode
4290 * 5) read 100 packets, save ofs=pkt.pts*st->time_base - st->nudge:
4291 * decode frame for video stream of 1st program
4292 * if frame->timecode has a timecode, return frame->timecode - ofs
4293 * if side_data has gop timecode, return gop->timecode - ofs
4294 * if side_data has smpte timecode, return smpte->timecode - ofs
4295 * 6) if the filename/url scans *date_time.ext, return date_time
4296 * 7) if stat works on the filename/url, return mtime
4297 * 8) return -1 failure
4299 double FFMPEG::get_initial_timecode(int data_type, int channel, double frame_rate)
4301 AVRational rate = check_frame_rate(0, frame_rate);
4302 if( !rate.num ) return -1;
4303 // format context timecode
4304 AVDictionaryEntry *tc = av_dict_get(fmt_ctx->metadata, "timecode", 0, 0);
4305 if( tc ) return ff_get_timecode(tc->value, rate, 0);
4307 if( open_decoder() ) return -1;
4310 int codec_type = -1, fidx = -1;
4311 switch( data_type ) {
4313 codec_type = AVMEDIA_TYPE_AUDIO;
4314 int aidx = astrm_index[channel].st_idx;
4315 FFAudioStream *aud = ffaudio[aidx];
4319 AVDictionaryEntry *tref = av_dict_get(fmt_ctx->metadata, "time_reference", 0, 0);
4320 if( tref && aud && aud->sample_rate )
4321 return strtod(tref->value, 0) / aud->sample_rate;
4324 codec_type = AVMEDIA_TYPE_VIDEO;
4325 int vidx = vstrm_index[channel].st_idx;
4326 FFVideoStream *vid = ffvideo[vidx];
4332 if( codec_type < 0 ) return -1;
4334 tc = av_dict_get(st->metadata, "timecode", 0, 0);
4337 // find first program which references this stream
4339 for( int i=0, m=fmt_ctx->nb_programs; pidx<0 && i<m; ++i ) {
4340 AVProgram *pgrm = fmt_ctx->programs[i];
4341 for( int j=0, n=pgrm->nb_stream_indexes; j<n; ++j ) {
4342 int st_idx = pgrm->stream_index[j];
4343 if( st_idx == fidx ) { pidx = i; break; }
4348 AVProgram *pgrm = fmt_ctx->programs[pidx];
4349 for( int j=0, n=pgrm->nb_stream_indexes; j<n; ++j ) {
4350 int st_idx = pgrm->stream_index[j];
4351 AVStream *tst = fmt_ctx->streams[st_idx];
4352 if( !tst ) continue;
4353 if( tst->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
4354 st = tst; fidx = st_idx;
4360 for( int i=0, n=fmt_ctx->nb_streams; i<n; ++i ) {
4361 AVStream *tst = fmt_ctx->streams[i];
4362 if( !tst ) continue;
4363 if( tst->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
4370 tc = av_dict_get(st->metadata, "timecode", 0, 0);
4374 // any timecode, includes -data- streams
4375 for( int i=0, n=fmt_ctx->nb_streams; i<n; ++i ) {
4376 AVStream *tst = fmt_ctx->streams[i];
4377 if( !tst ) continue;
4378 if( (tc = av_dict_get(tst->metadata, "timecode", 0, 0)) ) {
4385 if( st && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
4386 if( st->r_frame_rate.num && st->r_frame_rate.den )
4387 rate = st->r_frame_rate;
4388 nudge = st->start_time;
4389 for( int i=0; i<ffvideo.size(); ++i ) {
4390 if( ffvideo[i]->st == st ) {
4391 nudge = ffvideo[i]->nudge;
4397 if( tc ) { // return timecode
4398 double secs = st->start_time == AV_NOPTS_VALUE ? 0 :
4399 to_secs(st->start_time - nudge, st->time_base);
4400 return ff_get_timecode(tc->value, rate, secs);
4403 if( !st || fidx < 0 ) return -1;
4406 AVCodecContext *av_ctx = activate_decoder(st);
4408 fprintf(stderr,"activate_decoder failed\n");
4411 avCodecContext avctx(av_ctx); // auto deletes
4412 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO &&
4413 avctx->framerate.num && avctx->framerate.den )
4414 rate = avctx->framerate;
4416 avPacket pkt; // auto deletes
4417 avFrame frame; // auto deletes
4419 fprintf(stderr,"av_frame_alloc failed\n");
4423 int64_t max_packets = 100;
4424 char tcbuf[AV_TIMECODE_STR_SIZE];
4426 for( int64_t count=0; count<max_packets; ++count ) {
4427 av_packet_unref(pkt);
4428 pkt->data = 0; pkt->size = 0;
4430 int ret = av_read_frame(fmt_ctx, pkt);
4432 if( ret == AVERROR_EOF ) break;
4433 if( ++errs > 100 ) {
4434 fprintf(stderr,"over 100 read_frame errs\n");
4439 if( !pkt->data ) continue;
4440 int i = pkt->stream_index;
4441 if( i != fidx ) continue;
4442 int64_t tstmp = pkt->pts;
4443 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt->dts;
4444 double secs = to_secs(tstmp - nudge, st->time_base);
4445 ret = avcodec_send_packet(avctx, pkt);
4446 if( ret < 0 ) return -1;
4448 while( (ret = avcodec_receive_frame(avctx, frame)) >= 0 ) {
4449 if( (tc = av_dict_get(frame->metadata, "timecode", 0, 0)) )
4450 return ff_get_timecode(tc->value, rate, secs);
4451 int k = frame->nb_side_data;
4452 AVFrameSideData *side_data = 0;
4454 side_data = frame->side_data[k];
4455 switch( side_data->type ) {
4456 case AV_FRAME_DATA_GOP_TIMECODE: {
4457 int64_t data = *(int64_t *)side_data->data;
4458 int sz = sizeof(data);
4459 if( side_data->size >= sz ) {
4460 av_timecode_make_mpeg_tc_string(tcbuf, data);
4461 return ff_get_timecode(tcbuf, rate, secs);
4464 case AV_FRAME_DATA_S12M_TIMECODE: {
4465 uint32_t *data = (uint32_t *)side_data->data;
4466 int n = data[0], sz = (n+1)*sizeof(*data);
4467 if( side_data->size >= sz ) {
4468 av_timecode_make_smpte_tc_string(tcbuf, data[n], 0);
4469 return ff_get_timecode(tcbuf, rate, secs);
4478 char *path = fmt_ctx->url;
4479 char *bp = strrchr(path, '/');
4480 if( !bp ) bp = path; else ++bp;
4481 char *cp = strrchr(bp, '.');
4482 if( cp && (cp-=(8+1+6)) >= bp ) {
4484 int year,mon,day, hour,min,sec, frm=0;
4485 if( sscanf(cp,"%4d%2d%2d%[_-]%2d%2d%2d",
4486 &year,&mon,&day, sep, &hour,&min,&sec) == 7 ) {
4488 // year>=1970,mon=1..12,day=1..31, hour=0..23,min=0..59,sec=0..60
4489 if( (ch=='_' || ch=='-' ) &&
4490 year >= 1970 && mon>=1 && mon<=12 && day>=1 && day<=31 &&
4491 hour>=0 && hour<24 && min>=0 && min<60 && sec>=0 && sec<=60 ) {
4492 sprintf(tcbuf,"%d:%02d:%02d:%02d", hour,min,sec, frm);
4493 return ff_get_timecode(tcbuf, rate, 0);
4498 if( stat(path, &tst) >= 0 ) {
4499 time_t t = (time_t)tst.st_mtim.tv_sec;
4501 localtime_r(&t, &tm);
4502 int64_t us = tst.st_mtim.tv_nsec / 1000;
4503 int frm = us/1000000. * frame_rate;
4504 sprintf(tcbuf,"%d:%02d:%02d:%02d", tm.tm_hour, tm.tm_min, tm.tm_sec, frm);
4505 return ff_get_timecode(tcbuf, rate, 0);
4510 double FFMPEG::ff_get_timecode(char *str, AVRational rate, double pos)
4513 if( av_timecode_init_from_string(&tc, rate, str, fmt_ctx) )
4515 double secs = (double)tc.start / tc.fps - pos;
4516 if( secs < 0 ) secs = 0;
4520 double FFMPEG::get_timecode(const char *path, int data_type, int channel, double rate)
4523 if( ffmpeg.init_decoder(path) ) return -1;
4524 return ffmpeg.get_initial_timecode(data_type, channel, rate);