12 // work arounds (centos)
15 #define INT64_MAX 9223372036854775807LL
17 #define MAX_RETRY 1000
18 // max pts/curr_pos drift allowed before correction (in seconds)
19 #define AUDIO_PTS_TOLERANCE 0.04
22 #include "bccmodels.h"
25 #include "edlsession.h"
27 #include "fileffmpeg.h"
28 #include "filesystem.h"
30 #include "indexfile.h"
31 #include "interlacemodes.h"
34 #include "mainerror.h"
36 #include "preferences.h"
42 #define av_register_all(s)
43 #define avfilter_register_all(s)
46 #define VIDEO_INBUF_SIZE 0x10000
47 #define AUDIO_INBUF_SIZE 0x10000
48 #define VIDEO_REFILL_THRESH 0
49 #define AUDIO_REFILL_THRESH 0x1000
50 #define AUDIO_MIN_FRAME_SZ 128
52 #define FF_ESTM_TIMES 0x0001
53 #define FF_BAD_TIMES 0x0002
55 Mutex FFMPEG::fflock("FFMPEG::fflock");
57 static void ff_err(int ret, const char *fmt, ...)
62 vsnprintf(msg, sizeof(msg), fmt, ap);
64 char errmsg[BCSTRLEN];
65 av_strerror(ret, errmsg, sizeof(errmsg));
66 fprintf(stderr,_("%s err: %s\n"),msg, errmsg);
72 pkt.data = 0; pkt.size = 0;
74 void FFPacket::finit()
76 av_packet_unref(&pkt);
79 FFrame::FFrame(FFStream *fst)
82 frm = av_frame_alloc();
83 init = fst->init_frame(frm);
91 void FFrame::queue(int64_t pos)
97 void FFrame::dequeue()
102 void FFrame::set_hw_frame(AVFrame *frame)
108 int FFAudioStream::read(float *fp, long len)
116 while( --k >= 0 ) *fp++ = *op++;
117 if( op >= lmt ) op = bfr;
122 void FFAudioStream::realloc(long nsz, int nch, long len)
124 long bsz = nsz * nch;
125 float *np = new float[bsz];
126 inp = np + read(np, len) * nch;
131 delete [] bfr; bfr = np;
134 void FFAudioStream::realloc(long nsz, int nch)
136 if( nsz > sz || this->nch != nch ) {
137 long len = this->nch != nch ? 0 : hpos;
138 if( len > sz ) len = sz;
140 realloc(nsz, nch, len);
144 void FFAudioStream::reserve(long nsz, int nch)
146 long len = (inp - outp) / nch;
148 if( nsz > sz || this->nch != nch ) {
149 if( this->nch != nch ) len = 0;
150 realloc(nsz, nch, len);
153 if( (len*=nch) > 0 && bfr != outp )
154 memmove(bfr, outp, len*sizeof(*bfr));
159 long FFAudioStream::used()
161 long len = inp>=outp ? inp-outp : inp-bfr + lmt-outp;
164 long FFAudioStream::avail()
167 if( in1 >= lmt ) in1 = bfr;
168 long len = outp >= in1 ? outp-in1 : outp-bfr + lmt-in1;
171 void FFAudioStream::reset_history()
175 memset(bfr, 0, lmt-bfr);
178 void FFAudioStream::iseek(int64_t ofs)
180 if( ofs > hpos ) ofs = hpos;
181 if( ofs > sz ) ofs = sz;
182 outp = inp - ofs*nch;
183 if( outp < bfr ) outp += sz*nch;
186 float *FFAudioStream::get_outp(int ofs)
193 int64_t FFAudioStream::put_inp(int ofs)
196 return (inp-outp) / nch;
199 int FFAudioStream::write(const float *fp, long len)
207 while( --k >= 0 ) *ip++ = *fp++;
208 if( ip >= lmt ) ip = bfr;
215 int FFAudioStream::zero(long len)
223 while( --k >= 0 ) *ip++ = 0;
224 if( ip >= lmt ) ip = bfr;
231 // does not advance outp
232 int FFAudioStream::read(double *dp, long len, int ch)
235 float *op = outp + ch;
236 float *lmt1 = lmt + nch-1;
238 int k = (lmt1 - op) / nch;
241 while( --k >= 0 ) { *dp++ = *op; op += nch; }
242 if( op >= lmt ) op -= sz*nch;
247 // load linear buffer, no wrapping allowed, does not advance inp
248 int FFAudioStream::write(const double *dp, long len, int ch)
251 float *ip = inp + ch;
252 while( --n >= 0 ) { *ip = *dp++; ip += nch; }
257 FFStream::FFStream(FFMPEG *ffmpeg, AVStream *st, int fidx)
259 this->ffmpeg = ffmpeg;
262 frm_lock = new Mutex("FFStream::frm_lock");
271 nudge = AV_NOPTS_VALUE;
272 seek_pos = curr_pos = 0;
273 seeking = 0; seeked = 1;
275 reading = writing = 0;
276 hw_pixfmt = AV_PIX_FMT_NONE;
289 FFStream::~FFStream()
291 frm_lock->lock("FFStream::~FFStream");
292 if( reading > 0 || writing > 0 ) avcodec_close(avctx);
293 if( avctx ) avcodec_free_context(&avctx);
294 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
295 if( hw_device_ctx ) av_buffer_unref(&hw_device_ctx);
296 if( bsfc ) av_bsf_free(&bsfc);
297 while( frms.first ) frms.remove(frms.first);
298 if( filter_graph ) avfilter_graph_free(&filter_graph);
299 if( frame ) av_frame_free(&frame);
300 if( fframe ) av_frame_free(&fframe);
301 if( probe_frame ) av_frame_free(&probe_frame);
304 if( stats_fp ) fclose(stats_fp);
305 if( stats_in ) av_freep(&stats_in);
306 delete [] stats_filename;
309 void FFStream::ff_lock(const char *cp)
311 FFMPEG::fflock.lock(cp);
314 void FFStream::ff_unlock()
316 FFMPEG::fflock.unlock();
319 void FFStream::queue(FFrame *frm)
321 frm_lock->lock("FFStream::queue");
325 ffmpeg->mux_lock->unlock();
328 void FFStream::dequeue(FFrame *frm)
330 frm_lock->lock("FFStream::dequeue");
332 frms.remove_pointer(frm);
336 int FFStream::encode_activate()
339 writing = ffmpeg->encode_activate();
343 // this is a global parameter that really should be in the context
344 static AVPixelFormat hw_pix_fmt = AV_PIX_FMT_NONE; // protected by ff_lock
346 // goofy maneuver to attach a hw_format to an av_context
347 #define GET_HW_PIXFMT(fn, fmt) \
348 static AVPixelFormat get_hw_##fn(AVCodecContext *ctx, const enum AVPixelFormat *pix_fmts) { \
351 GET_HW_PIXFMT(vaapi, AV_PIX_FMT_VAAPI)
352 GET_HW_PIXFMT(vdpau, AV_PIX_FMT_VDPAU)
353 GET_HW_PIXFMT(cuda, AV_PIX_FMT_CUDA)
354 GET_HW_PIXFMT(nv12, AV_PIX_FMT_NV12)
356 static enum AVPixelFormat get_hw_format(AVCodecContext *ctx,
357 const enum AVPixelFormat *pix_fmts)
359 for( const enum AVPixelFormat *p=pix_fmts; *p!=AV_PIX_FMT_NONE; ++p ) {
360 if( *p != hw_pix_fmt ) continue;
362 case AV_PIX_FMT_VAAPI: ctx->get_format = get_hw_vaapi; return *p;
363 case AV_PIX_FMT_VDPAU: ctx->get_format = get_hw_vdpau; return *p;
364 case AV_PIX_FMT_CUDA: ctx->get_format = get_hw_cuda; return *p;
365 case AV_PIX_FMT_NV12: ctx->get_format = get_hw_nv12; return *p;
367 fprintf(stderr, "Unknown HW surface format: %s\n",
368 av_get_pix_fmt_name(*p));
372 fprintf(stderr, "Failed to get HW surface format.\n");
373 return hw_pix_fmt = AV_PIX_FMT_NONE;
377 AVHWDeviceType FFStream::decode_hw_activate()
379 return AV_HWDEVICE_TYPE_NONE;
382 int FFStream::decode_hw_format(AVCodec *decoder, AVHWDeviceType type)
387 int FFStream::decode_activate()
389 if( reading < 0 && (reading=ffmpeg->decode_activate()) > 0 ) {
390 ff_lock("FFStream::decode_activate");
392 AVDictionary *copts = 0;
393 av_dict_copy(&copts, ffmpeg->opts, 0);
395 AVHWDeviceType hw_type = decode_hw_activate();
397 // this should be avformat_copy_context(), but no copy avail
398 ret = avformat_open_input(&fmt_ctx,
399 ffmpeg->fmt_ctx->url, ffmpeg->fmt_ctx->iformat, &copts);
401 ret = avformat_find_stream_info(fmt_ctx, 0);
402 st = fmt_ctx->streams[fidx];
405 while( ret >= 0 && st != 0 && !reading ) {
406 AVCodecID codec_id = st->codecpar->codec_id;
407 AVCodec *decoder = 0;
409 if( ffmpeg->opt_video_decoder )
410 decoder = avcodec_find_decoder_by_name(ffmpeg->opt_video_decoder);
412 ffmpeg->video_codec_remaps.update(codec_id, decoder);
414 else if( is_audio() ) {
415 if( ffmpeg->opt_audio_decoder )
416 decoder = avcodec_find_decoder_by_name(ffmpeg->opt_audio_decoder);
418 ffmpeg->audio_codec_remaps.update(codec_id, decoder);
421 decoder = avcodec_find_decoder(codec_id);
422 avctx = avcodec_alloc_context3(decoder);
424 eprintf(_("cant allocate codec context\n"));
425 ret = AVERROR(ENOMEM);
427 if( ret >= 0 && hw_type != AV_HWDEVICE_TYPE_NONE ) {
428 ret = decode_hw_format(decoder, hw_type);
431 avcodec_parameters_to_context(avctx, st->codecpar);
432 if( !av_dict_get(copts, "threads", NULL, 0) )
433 avctx->thread_count = ffmpeg->ff_cpus();
434 ret = avcodec_open2(avctx, decoder, &copts);
436 AVFrame *hw_frame = 0;
437 if( ret >= 0 && hw_type != AV_HWDEVICE_TYPE_NONE ) {
438 if( !(hw_frame=av_frame_alloc()) ) {
439 fprintf(stderr, "FFStream::decode_activate: av_frame_alloc failed\n");
440 ret = AVERROR(ENOMEM);
443 ret = decode(hw_frame);
445 if( ret < 0 && hw_type != AV_HWDEVICE_TYPE_NONE ) {
446 ff_err(ret, "HW device init failed, using SW decode.\nfile:%s\n",
447 ffmpeg->fmt_ctx->url);
448 avcodec_close(avctx);
449 avcodec_free_context(&avctx);
450 av_buffer_unref(&hw_device_ctx);
452 av_frame_free(&hw_frame);
453 hw_type = AV_HWDEVICE_TYPE_NONE;
454 int flags = AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_ANY;
456 av_seek_frame(fmt_ctx, idx, 0, flags);
457 need_packet = 1; flushed = 0;
458 seeked = 1; st_eof(0);
462 probe_frame = hw_frame;
466 eprintf(_("open decoder failed\n"));
469 eprintf(_("can't open input file: %s\n"), ffmpeg->fmt_ctx->url);
470 av_dict_free(&copts);
476 int FFStream::read_packet()
478 av_packet_unref(ipkt);
479 int ret = av_read_frame(fmt_ctx, ipkt);
482 if( ret == AVERROR_EOF ) return 0;
483 ff_err(ret, "FFStream::read_packet: av_read_frame failed\n");
490 int FFStream::decode(AVFrame *frame)
492 if( probe_frame ) { // hw probe reads first frame
493 av_frame_ref(frame, probe_frame);
494 av_frame_free(&probe_frame);
498 int retries = MAX_RETRY;
499 frm_lock->lock("FFStream::decode");
500 while( ret >= 0 && !flushed && --retries >= 0 ) {
502 if( (ret=read_packet()) < 0 ) break;
503 AVPacket *pkt = ret > 0 ? (AVPacket*)ipkt : 0;
505 if( pkt->stream_index != st->index ) continue;
506 if( !pkt->data || !pkt->size ) continue;
508 if( (ret=avcodec_send_packet(avctx, pkt)) < 0 ) {
509 ff_err(ret, "FFStream::decode: avcodec_send_packet failed.\nfile:%s\n",
510 ffmpeg->fmt_ctx->url);
516 if( (ret=decode_frame(frame)) > 0 ) break;
525 fprintf(stderr, "FFStream::decode: Retry limit\n");
529 fprintf(stderr, "FFStream::decode: failed\n");
533 int FFStream::load_filter(AVFrame *frame)
535 int ret = av_buffersrc_add_frame_flags(buffersrc_ctx, frame, 0);
537 eprintf(_("av_buffersrc_add_frame_flags failed\n"));
541 int FFStream::read_filter(AVFrame *frame)
543 int ret = av_buffersink_get_frame(buffersink_ctx, frame);
545 if( ret == AVERROR(EAGAIN) ) return 0;
546 if( ret == AVERROR_EOF ) { st_eof(1); return -1; }
547 ff_err(ret, "FFStream::read_filter: av_buffersink_get_frame failed\n");
553 int FFStream::read_frame(AVFrame *frame)
555 av_frame_unref(frame);
556 if( !filter_graph || !buffersrc_ctx || !buffersink_ctx )
557 return decode(frame);
558 if( !fframe && !(fframe=av_frame_alloc()) ) {
559 fprintf(stderr, "FFStream::read_frame: av_frame_alloc failed\n");
563 while( !flushed && !(ret=read_filter(frame)) ) {
564 if( (ret=decode(fframe)) < 0 ) break;
565 if( ret > 0 && (ret=load_filter(fframe)) < 0 ) break;
570 int FFStream::write_packet(FFPacket &pkt)
574 av_packet_rescale_ts(pkt, avctx->time_base, st->time_base);
575 pkt->stream_index = st->index;
576 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, pkt);
579 ret = av_bsf_send_packet(bsfc, pkt);
582 if( (ret=av_bsf_receive_packet(bsfc, bs)) < 0 ) {
583 if( ret == AVERROR(EAGAIN) ) return 0;
584 if( ret == AVERROR_EOF ) return -1;
587 av_packet_rescale_ts(bs, avctx->time_base, st->time_base);
588 bs->stream_index = st->index;
589 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, bs);
593 ff_err(ret, "FFStream::write_packet: write packet failed.\nfile:%s\n",
594 ffmpeg->fmt_ctx->url);
598 int FFStream::encode_frame(AVFrame *frame)
600 int pkts = 0, ret = 0;
601 for( int retry=MAX_RETRY; --retry>=0; ) {
603 ret = avcodec_send_frame(avctx, frame);
604 if( !ret && frame ) return pkts;
605 if( ret < 0 && ret != AVERROR(EAGAIN) ) break;
607 ret = avcodec_receive_packet(avctx, opkt);
608 if( !frame && ret == AVERROR_EOF ) return pkts;
610 ret = write_packet(opkt);
613 if( frame && stats_fp ) {
614 ret = write_stats_file();
618 ff_err(ret, "FFStream::encode_frame: encode failed.\nfile: %s\n",
619 ffmpeg->fmt_ctx->url);
623 int FFStream::flush()
627 int ret = encode_frame(0);
628 if( ret >= 0 && stats_fp ) {
629 ret = write_stats_file();
633 ff_err(ret, "FFStream::flush failed\n:file:%s\n",
634 ffmpeg->fmt_ctx->url);
635 return ret >= 0 ? 0 : 1;
639 int FFStream::open_stats_file()
641 stats_fp = fopen(stats_filename,"w");
642 return stats_fp ? 0 : AVERROR(errno);
645 int FFStream::close_stats_file()
648 fclose(stats_fp); stats_fp = 0;
653 int FFStream::read_stats_file()
655 int64_t len = 0; struct stat stats_st;
656 int fd = open(stats_filename, O_RDONLY);
657 int ret = fd >= 0 ? 0: ENOENT;
658 if( !ret && fstat(fd, &stats_st) )
661 len = stats_st.st_size;
662 stats_in = (char *)av_malloc(len+1);
666 if( !ret && read(fd, stats_in, len+1) != len )
670 avctx->stats_in = stats_in;
674 return !ret ? 0 : AVERROR(ret);
677 int FFStream::write_stats_file()
680 if( avctx->stats_out && (ret=strlen(avctx->stats_out)) > 0 ) {
681 int len = fwrite(avctx->stats_out, 1, ret, stats_fp);
683 ff_err(ret = AVERROR(errno), "FFStream::write_stats_file.\n%file:%s\n",
684 ffmpeg->fmt_ctx->url);
689 int FFStream::init_stats_file()
692 if( (pass & 2) && (ret = read_stats_file()) < 0 )
693 ff_err(ret, "stat file read: %s", stats_filename);
694 if( (pass & 1) && (ret=open_stats_file()) < 0 )
695 ff_err(ret, "stat file open: %s", stats_filename);
696 return ret >= 0 ? 0 : ret;
699 int FFStream::seek(int64_t no, double rate)
701 // default ffmpeg native seek
703 int64_t pos = no, pkt_pos = -1;
704 IndexMarks *index_markers = get_markers();
705 if( index_markers && index_markers->size() > 1 ) {
706 IndexMarks &marks = *index_markers;
707 int i = marks.find(pos);
708 int64_t n = i < 0 ? (i=0) : marks[i].no;
709 // if indexed seek point not too far away (<30 secs), use index
710 if( no-n < 30*rate ) {
713 if( i < marks.size() ) pkt_pos = marks[i].pos;
717 if( pos == curr_pos ) return 0;
719 double secs = pos < 0 ? 0. : pos / rate;
720 AVRational time_base = st->time_base;
721 int64_t tstmp = time_base.num > 0 ? secs * time_base.den/time_base.num : 0;
723 if( st->nb_index_entries > 0 ) tstmp = st->index_entries[0].timestamp;
724 else if( st->start_time != AV_NOPTS_VALUE ) tstmp = st->start_time;
725 else if( st->first_dts != AV_NOPTS_VALUE ) tstmp = st->first_dts;
726 else tstmp = INT64_MIN+1;
728 else if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
731 // seek all streams using the default timebase.
732 // this is how ffmpeg and ffplay work. stream seeks are less tested.
733 tstmp = av_rescale_q(tstmp, time_base, AV_TIME_BASE_Q);
736 frm_lock->lock("FFStream::seek");
737 av_frame_free(&probe_frame);
738 avcodec_flush_buffers(avctx);
739 avformat_flush(fmt_ctx);
741 int64_t seek = tstmp;
742 int flags = AVSEEK_FLAG_ANY;
743 if( !(fmt_ctx->iformat->flags & AVFMT_NO_BYTE_SEEK) && pkt_pos >= 0 ) {
745 flags = AVSEEK_FLAG_BYTE;
747 int ret = avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, seek, INT64_MAX, flags);
749 // finds the first index frame below the target time
750 int flags = AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_ANY;
751 int ret = av_seek_frame(fmt_ctx, idx, tstmp, flags);
753 int retry = MAX_RETRY;
755 need_packet = 0; flushed = 0;
756 seeked = 1; st_eof(0);
757 // read up to retry packets, limited to npkts in stream, and not pkt.pos past pkt_pos
758 while( --retry >= 0 ) {
759 if( read_packet() <= 0 ) { ret = -1; break; }
760 if( ipkt->stream_index != st->index ) continue;
761 if( !ipkt->data || !ipkt->size ) continue;
762 if( pkt_pos >= 0 && ipkt->pos >= pkt_pos ) break;
763 if( --npkts <= 0 ) break;
764 int64_t pkt_ts = ipkt->dts != AV_NOPTS_VALUE ? ipkt->dts : ipkt->pts;
765 if( pkt_ts == AV_NOPTS_VALUE ) continue;
766 if( pkt_ts >= tstmp ) break;
769 ff_err(AVERROR(EIO), "FFStream::seek: %s\n"
770 " retry limit, pos=%jd tstmp=%jd, ",
771 ffmpeg->fmt_ctx->url, pos, tstmp);
775 ret = avcodec_send_packet(avctx, ipkt);
777 //some codecs need more than one pkt to resync
778 if( ret == AVERROR_INVALIDDATA ) ret = 0;
780 ff_err(ret, "FFStream::avcodec_send_packet failed.\nseek:%s\n",
781 ffmpeg->fmt_ctx->url);
787 printf("** seek fail %jd, %jd\n", pos, tstmp);
788 seeked = need_packet = 0;
792 //printf("seeked pos = %ld, %ld\n", pos, tstmp);
793 seek_pos = curr_pos = pos;
797 FFAudioStream::FFAudioStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
798 : FFStream(ffmpeg, strm, fidx)
801 channel0 = channels = 0;
804 frame_sz = AUDIO_MIN_FRAME_SZ;
806 resample_context = 0;
807 swr_ichs = swr_ifmt = swr_irate = 0;
816 bfr = new float[bsz];
821 FFAudioStream::~FFAudioStream()
823 if( resample_context ) swr_free(&resample_context);
828 void FFAudioStream::init_swr(int ichs, int ifmt, int irate)
830 if( resample_context ) {
831 if( swr_ichs == ichs && swr_ifmt == ifmt && swr_irate == irate )
833 swr_free(&resample_context);
835 swr_ichs = ichs; swr_ifmt = ifmt; swr_irate = irate;
836 if( ichs == channels && ifmt == AV_SAMPLE_FMT_FLT && irate == sample_rate )
838 uint64_t ilayout = av_get_default_channel_layout(ichs);
839 if( !ilayout ) ilayout = ((uint64_t)1<<ichs) - 1;
840 uint64_t olayout = av_get_default_channel_layout(channels);
841 if( !olayout ) olayout = ((uint64_t)1<<channels) - 1;
842 resample_context = swr_alloc_set_opts(NULL,
843 olayout, AV_SAMPLE_FMT_FLT, sample_rate,
844 ilayout, (AVSampleFormat)ifmt, irate,
846 if( resample_context )
847 swr_init(resample_context);
850 int FFAudioStream::get_samples(float *&samples, uint8_t **data, int len)
852 samples = *(float **)data;
853 if( resample_context ) {
854 if( len > aud_bfr_sz ) {
860 aud_bfr = new float[aud_bfr_sz*channels];
862 int ret = swr_convert(resample_context,
863 (uint8_t**)&aud_bfr, aud_bfr_sz, (const uint8_t**)data, len);
865 ff_err(ret, "FFAudioStream::get_samples: swr_convert failed\n");
874 int FFAudioStream::load_history(uint8_t **data, int len)
877 len = get_samples(samples, data, len);
879 // biggest user bfr since seek + frame
880 realloc(mbsz + len + 1, channels);
886 int FFAudioStream::decode_frame(AVFrame *frame)
888 int first_frame = seeked; seeked = 0;
889 frame->best_effort_timestamp = AV_NOPTS_VALUE;
890 int ret = avcodec_receive_frame(avctx, frame);
892 if( first_frame ) return 0;
893 if( ret == AVERROR(EAGAIN) ) return 0;
894 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
895 ff_err(ret, "FFAudioStream::decode_frame: Could not read audio frame.\nfile:%s\n",
896 ffmpeg->fmt_ctx->url);
899 int64_t pkt_ts = frame->best_effort_timestamp;
900 if( pkt_ts != AV_NOPTS_VALUE ) {
901 double ts = ffmpeg->to_secs(pkt_ts - nudge, st->time_base);
902 double t = (double)curr_pos / sample_rate;
903 // some time_base clocks are very grainy, too grainy for audio (clicks, pops)
904 if( fabs(ts - t) > AUDIO_PTS_TOLERANCE )
905 curr_pos = ts * sample_rate + 0.5;
910 int FFAudioStream::encode_activate()
912 if( writing >= 0 ) return writing;
913 if( !avctx->codec ) return writing = 0;
914 frame_sz = avctx->codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE ?
915 10000 : avctx->frame_size;
916 return FFStream::encode_activate();
919 int64_t FFAudioStream::load_buffer(double ** const sp, int len)
921 reserve(len+1, st->codecpar->channels);
922 for( int ch=0; ch<nch; ++ch )
923 write(sp[ch], len, ch);
927 int FFAudioStream::in_history(int64_t pos)
929 if( pos > curr_pos ) return 0;
931 if( len > sz ) len = sz;
932 if( pos < curr_pos - len ) return 0;
937 int FFAudioStream::init_frame(AVFrame *frame)
939 frame->nb_samples = frame_sz;
940 frame->format = avctx->sample_fmt;
941 frame->channel_layout = avctx->channel_layout;
942 frame->sample_rate = avctx->sample_rate;
943 int ret = av_frame_get_buffer(frame, 0);
945 ff_err(ret, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
949 int FFAudioStream::load(int64_t pos, int len)
951 if( audio_seek(pos) < 0 ) return -1;
952 if( !frame && !(frame=av_frame_alloc()) ) {
953 fprintf(stderr, "FFAudioStream::load: av_frame_alloc failed\n");
956 if( mbsz < len ) mbsz = len;
957 int64_t end_pos = pos + len;
958 int ret = 0, i = len / frame_sz + MAX_RETRY;
959 while( ret>=0 && !flushed && curr_pos<end_pos && --i>=0 ) {
960 ret = read_frame(frame);
961 if( ret > 0 && frame->nb_samples > 0 ) {
962 init_swr(frame->channels, frame->format, frame->sample_rate);
963 load_history(&frame->extended_data[0], frame->nb_samples);
964 curr_pos += frame->nb_samples;
967 if( end_pos > curr_pos ) {
968 zero(end_pos - curr_pos);
971 len = curr_pos - pos;
976 int FFAudioStream::audio_seek(int64_t pos)
978 if( decode_activate() <= 0 ) return -1;
979 if( !st->codecpar ) return -1;
980 if( in_history(pos) ) return 0;
981 if( pos == curr_pos ) return 0;
982 reset_history(); mbsz = 0;
983 // guarentee preload > 1sec samples
984 if( (pos-=sample_rate) < 0 ) pos = 0;
985 if( seek(pos, sample_rate) < 0 ) return -1;
989 int FFAudioStream::encode(double **samples, int len)
991 if( encode_activate() <= 0 ) return -1;
994 int64_t count = samples ? load_buffer(samples, len) : used();
995 int frame_sz1 = samples ? frame_sz-1 : 0;
998 while( ret >= 0 && count > frame_sz1 ) {
999 frm = new FFrame(this);
1000 if( (ret=frm->initted()) < 0 ) break;
1001 AVFrame *frame = *frm;
1002 len = count >= frame_sz ? frame_sz : count;
1003 float *bfrp = get_outp(len);
1004 ret = swr_convert(resample_context,
1005 (uint8_t **)frame->extended_data, len,
1006 (const uint8_t **)&bfrp, len);
1008 ff_err(ret, "FFAudioStream::encode: swr_convert failed\n");
1011 frame->nb_samples = len;
1012 frm->queue(curr_pos);
1019 return ret >= 0 ? 0 : 1;
1022 int FFAudioStream::drain()
1027 int FFAudioStream::encode_frame(AVFrame *frame)
1029 return FFStream::encode_frame(frame);
1032 int FFAudioStream::write_packet(FFPacket &pkt)
1034 return FFStream::write_packet(pkt);
1037 void FFAudioStream::load_markers()
1039 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1040 if( !index_state || idx >= index_state->audio_markers.size() ) return;
1041 if( index_state->marker_status == MARKERS_NOTTESTED ) return;
1042 FFStream::load_markers(*index_state->audio_markers[idx], sample_rate);
1045 IndexMarks *FFAudioStream::get_markers()
1047 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1048 if( !index_state || idx >= index_state->audio_markers.size() ) return 0;
1049 return index_state->audio_markers[idx];
1052 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
1053 : FFStream(ffmpeg, strm, fidx),
1054 FFVideoConvert(ffmpeg->ff_prefs())
1063 top_field_first = 0;
1069 FFVideoStream::~FFVideoStream()
1071 if( fconvert_ctx ) sws_freeContext(fconvert_ctx);
1074 AVHWDeviceType FFVideoStream::decode_hw_activate()
1076 AVHWDeviceType type = AV_HWDEVICE_TYPE_NONE;
1077 const char *hw_dev = ffmpeg->opt_hw_dev;
1078 if( !hw_dev ) hw_dev = getenv("CIN_HW_DEV");
1079 if( !hw_dev ) hw_dev = ffmpeg->ff_hw_dev();
1080 if( hw_dev && *hw_dev &&
1081 strcmp("none", hw_dev) && strcmp(_("none"), hw_dev) ) {
1082 type = av_hwdevice_find_type_by_name(hw_dev);
1083 if( type == AV_HWDEVICE_TYPE_NONE ) {
1084 fprintf(stderr, "Device type %s is not supported.\n", hw_dev);
1085 fprintf(stderr, "Available device types:");
1086 while( (type = av_hwdevice_iterate_types(type)) != AV_HWDEVICE_TYPE_NONE )
1087 fprintf(stderr, " %s", av_hwdevice_get_type_name(type));
1088 fprintf(stderr, "\n");
1094 int FFVideoStream::decode_hw_format(AVCodec *decoder, AVHWDeviceType type)
1097 hw_pix_fmt = AV_PIX_FMT_NONE;
1098 for( int i=0; ; ++i ) {
1099 const AVCodecHWConfig *config = avcodec_get_hw_config(decoder, i);
1101 fprintf(stderr, "Decoder %s does not support device type %s.\n",
1102 decoder->name, av_hwdevice_get_type_name(type));
1106 if( (config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX) != 0 &&
1107 config->device_type == type ) {
1108 hw_pix_fmt = config->pix_fmt;
1112 if( hw_pix_fmt >= 0 ) {
1113 hw_pixfmt = hw_pix_fmt;
1114 avctx->get_format = get_hw_format;
1115 ret = av_hwdevice_ctx_create(&hw_device_ctx, type, 0, 0, 0);
1117 avctx->hw_device_ctx = av_buffer_ref(hw_device_ctx);
1121 ff_err(ret, "Failed HW device create.\ndev:%s\n",
1122 av_hwdevice_get_type_name(type));
1129 AVHWDeviceType FFVideoStream::encode_hw_activate(const char *hw_dev)
1131 AVBufferRef *hw_device_ctx = 0;
1132 AVBufferRef *hw_frames_ref = 0;
1133 AVHWDeviceType type = AV_HWDEVICE_TYPE_NONE;
1134 if( strcmp(_("none"), hw_dev) ) {
1135 type = av_hwdevice_find_type_by_name(hw_dev);
1136 if( type != AV_HWDEVICE_TYPE_VAAPI ) {
1137 fprintf(stderr, "currently, only vaapi hw encode is supported\n");
1138 type = AV_HWDEVICE_TYPE_NONE;
1141 if( type != AV_HWDEVICE_TYPE_NONE ) {
1142 int ret = av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_VAAPI, 0, 0, 0);
1144 ff_err(ret, "Failed to create a HW device.\n");
1145 type = AV_HWDEVICE_TYPE_NONE;
1148 if( type != AV_HWDEVICE_TYPE_NONE ) {
1149 hw_frames_ref = av_hwframe_ctx_alloc(hw_device_ctx);
1150 if( !hw_frames_ref ) {
1151 fprintf(stderr, "Failed to create HW frame context.\n");
1152 type = AV_HWDEVICE_TYPE_NONE;
1155 if( type != AV_HWDEVICE_TYPE_NONE ) {
1156 AVHWFramesContext *frames_ctx = (AVHWFramesContext *)(hw_frames_ref->data);
1157 frames_ctx->format = AV_PIX_FMT_VAAPI;
1158 frames_ctx->sw_format = AV_PIX_FMT_NV12;
1159 frames_ctx->width = width;
1160 frames_ctx->height = height;
1161 frames_ctx->initial_pool_size = 0; // 200;
1162 int ret = av_hwframe_ctx_init(hw_frames_ref);
1164 avctx->hw_frames_ctx = av_buffer_ref(hw_frames_ref);
1165 if( !avctx->hw_frames_ctx ) ret = AVERROR(ENOMEM);
1168 ff_err(ret, "Failed to initialize HW frame context.\n");
1169 type = AV_HWDEVICE_TYPE_NONE;
1171 av_buffer_unref(&hw_frames_ref);
1176 int FFVideoStream::encode_hw_write(FFrame *picture)
1179 AVFrame *hw_frm = 0;
1180 switch( avctx->pix_fmt ) {
1181 case AV_PIX_FMT_VAAPI:
1182 hw_frm = av_frame_alloc();
1183 if( !hw_frm ) { ret = AVERROR(ENOMEM); break; }
1184 ret = av_hwframe_get_buffer(avctx->hw_frames_ctx, hw_frm, 0);
1185 if( ret < 0 ) break;
1186 ret = av_hwframe_transfer_data(hw_frm, *picture, 0);
1187 if( ret < 0 ) break;
1188 picture->set_hw_frame(hw_frm);
1193 av_frame_free(&hw_frm);
1194 ff_err(ret, "Error while transferring frame data to GPU.\n");
1198 int FFVideoStream::decode_frame(AVFrame *frame)
1200 int first_frame = seeked; seeked = 0;
1201 int ret = avcodec_receive_frame(avctx, frame);
1203 if( first_frame ) return 0;
1204 if( ret == AVERROR(EAGAIN) ) return 0;
1205 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
1206 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame.\nfile:%s\n,",
1207 ffmpeg->fmt_ctx->url);
1210 int64_t pkt_ts = frame->best_effort_timestamp;
1211 if( pkt_ts != AV_NOPTS_VALUE )
1212 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * frame_rate + 0.5;
1216 int FFVideoStream::probe(int64_t pos)
1218 int ret = video_seek(pos);
1219 if( ret < 0 ) return -1;
1220 if( !frame && !(frame=av_frame_alloc()) ) {
1221 fprintf(stderr, "FFVideoStream::probe: av_frame_alloc failed\n");
1225 if (ffmpeg->interlace_from_codec) return 1;
1227 ret = read_frame(frame);
1229 //printf("codec interlace: %i \n",frame->interlaced_frame);
1230 //printf("codec tff: %i \n",frame->top_field_first);
1232 if (!frame->interlaced_frame)
1233 ffmpeg->interlace_from_codec = AV_FIELD_PROGRESSIVE;
1234 if ((frame->interlaced_frame) && (frame->top_field_first))
1235 ffmpeg->interlace_from_codec = AV_FIELD_TT;
1236 if ((frame->interlaced_frame) && (!frame->top_field_first))
1237 ffmpeg->interlace_from_codec = AV_FIELD_BB;
1238 //printf("Interlace mode from codec: %i\n", ffmpeg->interlace_from_codec);
1242 if( frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0 )
1245 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
1249 int FFVideoStream::load(VFrame *vframe, int64_t pos)
1251 int ret = video_seek(pos);
1252 if( ret < 0 ) return -1;
1253 if( !frame && !(frame=av_frame_alloc()) ) {
1254 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
1259 int i = MAX_RETRY + pos - curr_pos;
1260 int64_t cache_start = 0;
1261 while( ret>=0 && !flushed && curr_pos<=pos && --i>=0 ) {
1262 ret = read_frame(frame);
1264 if( frame->key_frame && seeking < 0 ) {
1265 int use_cache = ffmpeg->get_use_cache();
1266 if( use_cache < 0 ) {
1267 // for reverse read, reload file frame_cache from keyframe to pos
1268 ffmpeg->purge_cache();
1269 int count = preferences->cache_size /
1270 vframe->get_data_size() / 2; // try to burn only 1/2 of cache
1271 cache_start = pos - count + 1;
1277 if( seeking > 0 && curr_pos >= cache_start && curr_pos < pos ) {
1278 int vw =vframe->get_w(), vh = vframe->get_h();
1279 int vcolor_model = vframe->get_color_model();
1280 // do not use shm here, puts too much pressure on 32bit systems
1281 VFrame *cache_frame = new VFrame(vw, vh, vcolor_model, 0);
1282 ret = convert_cmodel(cache_frame, frame);
1284 ffmpeg->put_cache_frame(cache_frame, curr_pos);
1290 if( frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0 )
1293 ret = convert_cmodel(vframe, frame);
1295 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
1299 int FFVideoStream::video_seek(int64_t pos)
1301 if( decode_activate() <= 0 ) return -1;
1302 if( !st->codecpar ) return -1;
1303 if( pos == curr_pos-1 && !seeked ) return 0;
1304 // if close enough, just read up to current
1305 int gop = avctx->gop_size;
1306 if( gop < 4 ) gop = 4;
1307 if( gop > 64 ) gop = 64;
1308 int read_limit = curr_pos + 3*gop;
1309 if( pos >= curr_pos && pos <= read_limit ) return 0;
1310 // guarentee preload more than 2*gop frames
1311 if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
1315 int FFVideoStream::init_frame(AVFrame *picture)
1317 switch( avctx->pix_fmt ) {
1318 case AV_PIX_FMT_VAAPI:
1319 picture->format = AV_PIX_FMT_NV12;
1322 picture->format = avctx->pix_fmt;
1325 picture->width = avctx->width;
1326 picture->height = avctx->height;
1327 int ret = av_frame_get_buffer(picture, 32);
1331 int FFVideoStream::convert_hw_frame(AVFrame *ifrm, AVFrame *ofrm)
1333 AVPixelFormat ifmt = (AVPixelFormat)ifrm->format;
1334 AVPixelFormat ofmt = (AVPixelFormat)st->codecpar->format;
1335 ofrm->width = ifrm->width;
1336 ofrm->height = ifrm->height;
1337 ofrm->format = ofmt;
1338 int ret = av_frame_get_buffer(ofrm, 32);
1340 ff_err(ret, "FFVideoStream::convert_hw_frame:"
1341 " av_frame_get_buffer failed\n");
1344 fconvert_ctx = sws_getCachedContext(fconvert_ctx,
1345 ifrm->width, ifrm->height, ifmt,
1346 ofrm->width, ofrm->height, ofmt,
1347 SWS_POINT, NULL, NULL, NULL);
1348 if( !fconvert_ctx ) {
1349 ff_err(AVERROR(EINVAL), "FFVideoStream::convert_hw_frame:"
1350 " sws_getCachedContext() failed\n");
1353 int codec_range = st->codecpar->color_range;
1354 int codec_space = st->codecpar->color_space;
1355 const int *codec_table = sws_getCoefficients(codec_space);
1356 int *inv_table, *table, src_range, dst_range;
1357 int brightness, contrast, saturation;
1358 if( !sws_getColorspaceDetails(fconvert_ctx,
1359 &inv_table, &src_range, &table, &dst_range,
1360 &brightness, &contrast, &saturation) ) {
1361 if( src_range != codec_range || dst_range != codec_range ||
1362 inv_table != codec_table || table != codec_table )
1363 sws_setColorspaceDetails(fconvert_ctx,
1364 codec_table, codec_range, codec_table, codec_range,
1365 brightness, contrast, saturation);
1367 ret = sws_scale(fconvert_ctx,
1368 ifrm->data, ifrm->linesize, 0, ifrm->height,
1369 ofrm->data, ofrm->linesize);
1371 ff_err(ret, "FFVideoStream::convert_hw_frame:"
1372 " sws_scale() failed\nfile: %s\n",
1373 ffmpeg->fmt_ctx->url);
1379 int FFVideoStream::load_filter(AVFrame *frame)
1381 AVPixelFormat pix_fmt = (AVPixelFormat)frame->format;
1382 if( pix_fmt == hw_pixfmt ) {
1383 AVFrame *hw_frame = this->frame;
1384 av_frame_unref(hw_frame);
1385 int ret = av_hwframe_transfer_data(hw_frame, frame, 0);
1387 eprintf(_("Error retrieving data from GPU to CPU\nfile: %s\n"),
1388 ffmpeg->fmt_ctx->url);
1391 av_frame_unref(frame);
1392 ret = convert_hw_frame(hw_frame, frame);
1394 eprintf(_("Error converting data from GPU to CPU\nfile: %s\n"),
1395 ffmpeg->fmt_ctx->url);
1398 av_frame_unref(hw_frame);
1400 return FFStream::load_filter(frame);
1403 int FFVideoStream::encode(VFrame *vframe)
1405 if( encode_activate() <= 0 ) return -1;
1407 FFrame *picture = new FFrame(this);
1408 int ret = picture->initted();
1410 AVFrame *frame = *picture;
1411 frame->pts = curr_pos;
1412 ret = convert_pixfmt(vframe, frame);
1414 if( ret >= 0 && avctx->hw_frames_ctx )
1415 encode_hw_write(picture);
1417 picture->queue(curr_pos);
1421 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
1424 return ret >= 0 ? 0 : 1;
1427 int FFVideoStream::drain()
1433 int FFVideoStream::encode_frame(AVFrame *frame)
1436 frame->interlaced_frame = interlaced;
1437 frame->top_field_first = top_field_first;
1439 if( frame && frame->format == AV_PIX_FMT_VAAPI ) { // ugly
1440 int ret = avcodec_send_frame(avctx, frame);
1441 for( int retry=MAX_RETRY; !ret && --retry>=0; ) {
1442 FFPacket pkt; av_init_packet(pkt);
1443 pkt->data = NULL; pkt->size = 0;
1444 if( (ret=avcodec_receive_packet(avctx, pkt)) < 0 ) {
1445 if( ret == AVERROR(EAGAIN) ) ret = 0; // weird
1448 ret = write_packet(pkt);
1449 pkt->stream_index = 0;
1450 av_packet_unref(pkt);
1453 ff_err(ret, "FFStream::encode_frame: vaapi encode failed.\nfile: %s\n",
1454 ffmpeg->fmt_ctx->url);
1459 return FFStream::encode_frame(frame);
1462 int FFVideoStream::write_packet(FFPacket &pkt)
1464 if( !(ffmpeg->fmt_ctx->oformat->flags & AVFMT_VARIABLE_FPS) )
1466 return FFStream::write_packet(pkt);
1469 AVPixelFormat FFVideoConvert::color_model_to_pix_fmt(int color_model)
1471 switch( color_model ) {
1472 case BC_YUV422: return AV_PIX_FMT_YUYV422;
1473 case BC_RGB888: return AV_PIX_FMT_RGB24;
1474 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
1475 case BC_BGR8888: return AV_PIX_FMT_BGR0;
1476 case BC_BGR888: return AV_PIX_FMT_BGR24;
1477 case BC_ARGB8888: return AV_PIX_FMT_ARGB;
1478 case BC_ABGR8888: return AV_PIX_FMT_ABGR;
1479 case BC_RGB8: return AV_PIX_FMT_RGB8;
1480 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
1481 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
1482 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
1483 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
1484 case BC_RGB565: return AV_PIX_FMT_RGB565;
1485 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
1486 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
1487 case BC_AYUV16161616: return AV_PIX_FMT_AYUV64LE;
1488 case BC_GBRP: return AV_PIX_FMT_GBRP;
1492 return AV_PIX_FMT_NB;
1495 int FFVideoConvert::pix_fmt_to_color_model(AVPixelFormat pix_fmt)
1498 case AV_PIX_FMT_YUYV422: return BC_YUV422;
1499 case AV_PIX_FMT_RGB24: return BC_RGB888;
1500 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
1501 case AV_PIX_FMT_BGR0: return BC_BGR8888;
1502 case AV_PIX_FMT_BGR24: return BC_BGR888;
1503 case AV_PIX_FMT_ARGB: return BC_ARGB8888;
1504 case AV_PIX_FMT_ABGR: return BC_ABGR8888;
1505 case AV_PIX_FMT_RGB8: return BC_RGB8;
1506 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
1507 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
1508 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
1509 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
1510 case AV_PIX_FMT_RGB565: return BC_RGB565;
1511 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
1512 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
1513 case AV_PIX_FMT_AYUV64LE: return BC_AYUV16161616;
1514 case AV_PIX_FMT_GBRP: return BC_GBRP;
1521 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip)
1523 AVFrame *ipic = av_frame_alloc();
1524 int ret = convert_picture_vframe(frame, ip, ipic);
1525 av_frame_free(&ipic);
1529 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip, AVFrame *ipic)
1530 { // picture = vframe
1531 int cmodel = frame->get_color_model();
1532 AVPixelFormat ofmt = color_model_to_pix_fmt(cmodel);
1533 if( ofmt == AV_PIX_FMT_NB ) return -1;
1534 int size = av_image_fill_arrays(ipic->data, ipic->linesize,
1535 frame->get_data(), ofmt, frame->get_w(), frame->get_h(), 1);
1536 if( size < 0 ) return -1;
1538 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1539 int ysz = bpp * frame->get_w(), usz = ysz;
1549 // override av_image_fill_arrays() for planar types
1550 ipic->data[0] = frame->get_y(); ipic->linesize[0] = ysz;
1551 ipic->data[1] = frame->get_u(); ipic->linesize[1] = usz;
1552 ipic->data[2] = frame->get_v(); ipic->linesize[2] = usz;
1555 ipic->data[0] = frame->get_data();
1556 ipic->linesize[0] = frame->get_bytes_per_line();
1560 AVPixelFormat pix_fmt = (AVPixelFormat)ip->format;
1561 FFVideoStream *vid =(FFVideoStream *)this;
1562 if( pix_fmt == vid->hw_pixfmt ) {
1564 if( !sw_frame && !(sw_frame=av_frame_alloc()) )
1565 ret = AVERROR(ENOMEM);
1567 ret = av_hwframe_transfer_data(sw_frame, ip, 0);
1569 pix_fmt = (AVPixelFormat)ip->format;
1572 eprintf(_("Error retrieving data from GPU to CPU\nfile: %s\n"),
1573 vid->ffmpeg->fmt_ctx->url);
1577 convert_ctx = sws_getCachedContext(convert_ctx, ip->width, ip->height, pix_fmt,
1578 frame->get_w(), frame->get_h(), ofmt, SWS_POINT, NULL, NULL, NULL);
1579 if( !convert_ctx ) {
1580 fprintf(stderr, "FFVideoConvert::convert_picture_frame:"
1581 " sws_getCachedContext() failed\n");
1585 int color_range = 0;
1586 switch( preferences->yuv_color_range ) {
1587 case BC_COLORS_JPEG: color_range = 1; break;
1588 case BC_COLORS_MPEG: color_range = 0; break;
1590 int color_space = SWS_CS_ITU601;
1591 switch( preferences->yuv_color_space ) {
1592 case BC_COLORS_BT601_PAL: color_space = SWS_CS_ITU601; break;
1593 case BC_COLORS_BT601_NTSC: color_space = SWS_CS_SMPTE170M; break;
1594 case BC_COLORS_BT709: color_space = SWS_CS_ITU709; break;
1595 case BC_COLORS_BT2020_NCL:
1596 case BC_COLORS_BT2020_CL: color_space = SWS_CS_BT2020; break;
1598 const int *color_table = sws_getCoefficients(color_space);
1600 int *inv_table, *table, src_range, dst_range;
1601 int brightness, contrast, saturation;
1602 if( !sws_getColorspaceDetails(convert_ctx,
1603 &inv_table, &src_range, &table, &dst_range,
1604 &brightness, &contrast, &saturation) ) {
1605 if( src_range != color_range || dst_range != color_range ||
1606 inv_table != color_table || table != color_table )
1607 sws_setColorspaceDetails(convert_ctx,
1608 color_table, color_range, color_table, color_range,
1609 brightness, contrast, saturation);
1612 int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ip->height,
1613 ipic->data, ipic->linesize);
1615 ff_err(ret, "FFVideoConvert::convert_picture_frame: sws_scale() failed\nfile: %s\n",
1616 vid->ffmpeg->fmt_ctx->url);
1622 int FFVideoConvert::convert_cmodel(VFrame *frame, AVFrame *ip)
1624 // try direct transfer
1625 if( !convert_picture_vframe(frame, ip) ) return 1;
1626 // use indirect transfer
1627 AVPixelFormat ifmt = (AVPixelFormat)ip->format;
1628 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
1630 for( int i = 0; i <desc->nb_components; ++i ) {
1631 int bits = desc->comp[i].depth;
1632 if( bits > max_bits ) max_bits = bits;
1634 int imodel = pix_fmt_to_color_model(ifmt);
1635 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1636 int cmodel = frame->get_color_model();
1637 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1638 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1639 imodel = cmodel_is_yuv ?
1640 (BC_CModels::has_alpha(cmodel) ?
1642 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1643 (BC_CModels::has_alpha(cmodel) ?
1644 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1645 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1647 VFrame vframe(ip->width, ip->height, imodel);
1648 if( convert_picture_vframe(&vframe, ip) ) return -1;
1649 frame->transfer_from(&vframe);
1653 int FFVideoConvert::transfer_cmodel(VFrame *frame, AVFrame *ifp)
1655 int ret = convert_cmodel(frame, ifp);
1657 const AVDictionary *src = ifp->metadata;
1658 AVDictionaryEntry *t = NULL;
1659 BC_Hash *hp = frame->get_params();
1661 while( (t=av_dict_get(src, "", t, AV_DICT_IGNORE_SUFFIX)) )
1662 hp->update(t->key, t->value);
1667 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op)
1669 AVFrame *opic = av_frame_alloc();
1670 int ret = convert_vframe_picture(frame, op, opic);
1671 av_frame_free(&opic);
1675 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op, AVFrame *opic)
1676 { // vframe = picture
1677 int cmodel = frame->get_color_model();
1678 AVPixelFormat ifmt = color_model_to_pix_fmt(cmodel);
1679 if( ifmt == AV_PIX_FMT_NB ) return -1;
1680 int size = av_image_fill_arrays(opic->data, opic->linesize,
1681 frame->get_data(), ifmt, frame->get_w(), frame->get_h(), 1);
1682 if( size < 0 ) return -1;
1684 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1685 int ysz = bpp * frame->get_w(), usz = ysz;
1695 // override av_image_fill_arrays() for planar types
1696 opic->data[0] = frame->get_y(); opic->linesize[0] = ysz;
1697 opic->data[1] = frame->get_u(); opic->linesize[1] = usz;
1698 opic->data[2] = frame->get_v(); opic->linesize[2] = usz;
1701 opic->data[0] = frame->get_data();
1702 opic->linesize[0] = frame->get_bytes_per_line();
1706 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1707 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(),
1708 ifmt, op->width, op->height, ofmt, SWS_POINT, NULL, NULL, NULL);
1709 if( !convert_ctx ) {
1710 fprintf(stderr, "FFVideoConvert::convert_frame_picture:"
1711 " sws_getCachedContext() failed\n");
1716 int color_range = 0;
1717 switch( preferences->yuv_color_range ) {
1718 case BC_COLORS_JPEG: color_range = 1; break;
1719 case BC_COLORS_MPEG: color_range = 0; break;
1721 int color_space = SWS_CS_ITU601;
1722 switch( preferences->yuv_color_space ) {
1723 case BC_COLORS_BT601_PAL: color_space = SWS_CS_ITU601; break;
1724 case BC_COLORS_BT601_NTSC: color_space = SWS_CS_SMPTE170M; break;
1725 case BC_COLORS_BT709: color_space = SWS_CS_ITU709; break;
1726 case BC_COLORS_BT2020_NCL:
1727 case BC_COLORS_BT2020_CL: color_space = SWS_CS_BT2020; break;
1729 const int *color_table = sws_getCoefficients(color_space);
1731 int *inv_table, *table, src_range, dst_range;
1732 int brightness, contrast, saturation;
1733 if( !sws_getColorspaceDetails(convert_ctx,
1734 &inv_table, &src_range, &table, &dst_range,
1735 &brightness, &contrast, &saturation) ) {
1736 if( dst_range != color_range || table != color_table )
1737 sws_setColorspaceDetails(convert_ctx,
1738 inv_table, src_range, color_table, color_range,
1739 brightness, contrast, saturation);
1742 int ret = sws_scale(convert_ctx, opic->data, opic->linesize, 0, frame->get_h(),
1743 op->data, op->linesize);
1745 ff_err(ret, "FFVideoConvert::convert_frame_picture: sws_scale() failed\n");
1751 int FFVideoConvert::convert_pixfmt(VFrame *frame, AVFrame *op)
1753 // try direct transfer
1754 if( !convert_vframe_picture(frame, op) ) return 1;
1755 // use indirect transfer
1756 int cmodel = frame->get_color_model();
1757 int max_bits = BC_CModels::calculate_pixelsize(cmodel) * 8;
1758 max_bits /= BC_CModels::components(cmodel);
1759 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1760 int imodel = pix_fmt_to_color_model(ofmt);
1761 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1762 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1763 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1764 imodel = cmodel_is_yuv ?
1765 (BC_CModels::has_alpha(cmodel) ?
1767 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1768 (BC_CModels::has_alpha(cmodel) ?
1769 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1770 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1772 VFrame vframe(frame->get_w(), frame->get_h(), imodel);
1773 vframe.transfer_from(frame);
1774 if( !convert_vframe_picture(&vframe, op) ) return 1;
1778 int FFVideoConvert::transfer_pixfmt(VFrame *frame, AVFrame *ofp)
1780 int ret = convert_pixfmt(frame, ofp);
1782 BC_Hash *hp = frame->get_params();
1783 AVDictionary **dict = &ofp->metadata;
1784 //av_dict_free(dict);
1785 for( int i=0; i<hp->size(); ++i ) {
1786 char *key = hp->get_key(i), *val = hp->get_value(i);
1787 av_dict_set(dict, key, val, 0);
1793 void FFVideoStream::load_markers()
1795 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1796 if( !index_state || idx >= index_state->video_markers.size() ) return;
1797 FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
1800 IndexMarks *FFVideoStream::get_markers()
1802 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1803 if( !index_state || idx >= index_state->video_markers.size() ) return 0;
1804 return !index_state ? 0 : index_state->video_markers[idx];
1808 FFMPEG::FFMPEG(FileBase *file_base)
1811 this->file_base = file_base;
1812 memset(file_format,0,sizeof(file_format));
1813 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
1814 flow_lock = new Condition(1,"FFStream::flow_lock",0);
1817 decoding = encoding = 0;
1818 has_audio = has_video = 0;
1819 interlace_from_codec = 0;
1822 opt_video_filter = 0;
1823 opt_audio_filter = 0;
1825 opt_video_decoder = 0;
1826 opt_audio_decoder = 0;
1828 char option_path[BCTEXTLEN];
1829 set_option_path(option_path, "%s", "ffmpeg.opts");
1830 read_options(option_path, opts);
1835 ff_lock("FFMPEG::~FFMPEG()");
1837 ffaudio.remove_all_objects();
1838 ffvideo.remove_all_objects();
1839 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1843 av_dict_free(&opts);
1844 delete [] opt_video_filter;
1845 delete [] opt_audio_filter;
1846 delete [] opt_hw_dev;
1849 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1851 const int *p = codec->supported_samplerates;
1852 if( !p ) return sample_rate;
1854 if( *p == sample_rate ) return *p;
1860 // check_frame_rate and std_frame_rate needed for 23.976
1861 // and 59.94 fps mpeg2
1862 static inline AVRational std_frame_rate(int i)
1864 static const int m1 = 1001*12, m2 = 1000*12;
1865 static const int freqs[] = {
1866 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1867 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 90*m2,
1868 100*m2, 120*m2, 144*m2, 72*m2, 0,
1870 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1871 return (AVRational) { freq, 1001*12 };
1874 AVRational FFMPEG::check_frame_rate(const AVRational *p, double frame_rate)
1876 AVRational rate, best_rate = (AVRational) { 0, 0 };
1877 double max_err = 1.; int i = 0;
1878 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1879 double framerate = (double) rate.num / rate.den;
1880 double err = fabs(frame_rate/framerate - 1.);
1881 if( err >= max_err ) continue;
1885 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1888 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1891 double display_aspect = asset->width / (double)asset->height;
1892 double sample_aspect = display_aspect / asset->aspect_ratio;
1893 int width = 1000000, height = width * sample_aspect + 0.5;
1895 MWindow::create_aspect_ratio(w, h, width, height);
1896 return (AVRational){(int)w, (int)h};
1899 return (AVRational){1, 1};
1903 AVRational FFMPEG::to_time_base(int sample_rate)
1905 return (AVRational){1, sample_rate};
1908 int FFMPEG::get_fmt_score(AVSampleFormat dst_fmt, AVSampleFormat src_fmt)
1911 int dst_planar = av_sample_fmt_is_planar(dst_fmt);
1912 int src_planar = av_sample_fmt_is_planar(src_fmt);
1913 if( dst_planar != src_planar ) ++score;
1914 int dst_bytes = av_get_bytes_per_sample(dst_fmt);
1915 int src_bytes = av_get_bytes_per_sample(src_fmt);
1916 score += (src_bytes > dst_bytes ? 100 : -10) * (src_bytes - dst_bytes);
1917 int src_packed = av_get_packed_sample_fmt(src_fmt);
1918 int dst_packed = av_get_packed_sample_fmt(dst_fmt);
1919 if( dst_packed == AV_SAMPLE_FMT_S32 && src_packed == AV_SAMPLE_FMT_FLT ) score += 20;
1920 if( dst_packed == AV_SAMPLE_FMT_FLT && src_packed == AV_SAMPLE_FMT_S32 ) score += 2;
1924 AVSampleFormat FFMPEG::find_best_sample_fmt_of_list(
1925 const AVSampleFormat *sample_fmts, AVSampleFormat src_fmt)
1927 AVSampleFormat best = AV_SAMPLE_FMT_NONE;
1928 int best_score = get_fmt_score(best, src_fmt);
1929 for( int i=0; sample_fmts[i] >= 0; ++i ) {
1930 AVSampleFormat sample_fmt = sample_fmts[i];
1931 int score = get_fmt_score(sample_fmt, src_fmt);
1932 if( score >= best_score ) continue;
1933 best = sample_fmt; best_score = score;
1939 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
1941 char *ep = path + BCTEXTLEN-1;
1942 strncpy(path, File::get_cindat_path(), ep-path);
1943 strncat(path, "/ffmpeg/", ep-path);
1944 path += strlen(path);
1947 path += vsnprintf(path, ep-path, fmt, ap);
1952 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
1957 set_option_path(path, "%s/%s", type, spec);
1960 int FFMPEG::get_format(char *format, const char *path, const char *spec)
1962 char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
1963 get_option_path(option_path, path, spec);
1964 FILE *fp = fopen(option_path,"r");
1967 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1969 line[sizeof(line)-1] = 0;
1970 ret = scan_option_line(line, format, codec);
1976 int FFMPEG::get_codec(char *codec, const char *path, const char *spec)
1978 char option_path[BCTEXTLEN], line[BCTEXTLEN], format[BCTEXTLEN];
1979 get_option_path(option_path, path, spec);
1980 FILE *fp = fopen(option_path,"r");
1983 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1986 line[sizeof(line)-1] = 0;
1987 ret = scan_option_line(line, format, codec);
1990 char *vp = codec, *ep = vp+BCTEXTLEN-1;
1991 while( vp < ep && *vp && *vp != '|' ) ++vp;
1992 if( *vp == '|' ) --vp;
1993 while( vp > codec && (*vp==' ' || *vp=='\t') ) *vp-- = 0;
1998 int FFMPEG::get_file_format()
2000 char audio_muxer[BCSTRLEN], video_muxer[BCSTRLEN];
2001 char audio_format[BCSTRLEN], video_format[BCSTRLEN];
2002 audio_muxer[0] = audio_format[0] = 0;
2003 video_muxer[0] = video_format[0] = 0;
2004 Asset *asset = file_base->asset;
2005 int ret = asset ? 0 : 1;
2006 if( !ret && asset->audio_data ) {
2007 if( !(ret=get_format(audio_format, "audio", asset->acodec)) ) {
2008 if( get_format(audio_muxer, "format", audio_format) ) {
2009 strcpy(audio_muxer, audio_format);
2010 audio_format[0] = 0;
2014 if( !ret && asset->video_data ) {
2015 if( !(ret=get_format(video_format, "video", asset->vcodec)) ) {
2016 if( get_format(video_muxer, "format", video_format) ) {
2017 strcpy(video_muxer, video_format);
2018 video_format[0] = 0;
2022 if( !ret && !audio_muxer[0] && !video_muxer[0] )
2024 if( !ret && audio_muxer[0] && video_muxer[0] &&
2025 strcmp(audio_muxer, video_muxer) ) ret = -1;
2026 if( !ret && audio_format[0] && video_format[0] &&
2027 strcmp(audio_format, video_format) ) ret = -1;
2029 strcpy(file_format, !audio_format[0] && !video_format[0] ?
2030 (audio_muxer[0] ? audio_muxer : video_muxer) :
2031 (audio_format[0] ? audio_format : video_format));
2035 int FFMPEG::scan_option_line(const char *cp, char *tag, char *val)
2037 while( *cp == ' ' || *cp == '\t' ) ++cp;
2038 const char *bp = cp;
2039 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' && *cp != '\n' ) ++cp;
2041 if( !len || len > BCSTRLEN-1 ) return 1;
2042 while( bp < cp ) *tag++ = *bp++;
2044 while( *cp == ' ' || *cp == '\t' ) ++cp;
2045 if( *cp == '=' ) ++cp;
2046 while( *cp == ' ' || *cp == '\t' ) ++cp;
2048 while( *cp && *cp != '\n' ) ++cp;
2050 if( len > BCTEXTLEN-1 ) return 1;
2051 while( bp < cp ) *val++ = *bp++;
2056 int FFMPEG::can_render(const char *fformat, const char *type)
2059 char option_path[BCTEXTLEN];
2060 FFMPEG::set_option_path(option_path, type);
2061 fs.update(option_path);
2062 int total_files = fs.total_files();
2063 for( int i=0; i<total_files; ++i ) {
2064 const char *name = fs.get_entry(i)->get_name();
2065 const char *ext = strrchr(name,'.');
2066 if( !ext ) continue;
2067 if( !strcmp(fformat, ++ext) ) return 1;
2072 int FFMPEG::get_ff_option(const char *nm, const char *options, char *value)
2074 for( const char *cp=options; *cp!=0; ) {
2075 char line[BCTEXTLEN], *bp = line, *ep = bp+sizeof(line)-1;
2076 while( bp < ep && *cp && *cp!='\n' ) *bp++ = *cp++;
2079 if( !line[0] || line[0] == '#' || line[0] == ';' ) continue;
2080 char key[BCSTRLEN], val[BCTEXTLEN];
2081 if( FFMPEG::scan_option_line(line, key, val) ) continue;
2082 if( !strcmp(key, nm) ) {
2083 strncpy(value, val, BCSTRLEN);
2090 void FFMPEG::scan_audio_options(Asset *asset, EDL *edl)
2092 char cin_sample_fmt[BCSTRLEN];
2093 int cin_fmt = AV_SAMPLE_FMT_NONE;
2094 const char *options = asset->ff_audio_options;
2095 if( !get_ff_option("cin_sample_fmt", options, cin_sample_fmt) )
2096 cin_fmt = (int)av_get_sample_fmt(cin_sample_fmt);
2098 char audio_codec[BCSTRLEN]; audio_codec[0] = 0;
2099 AVCodec *av_codec = !FFMPEG::get_codec(audio_codec, "audio", asset->acodec) ?
2100 avcodec_find_encoder_by_name(audio_codec) : 0;
2101 if( av_codec && av_codec->sample_fmts )
2102 cin_fmt = find_best_sample_fmt_of_list(av_codec->sample_fmts, AV_SAMPLE_FMT_FLT);
2104 if( cin_fmt < 0 ) cin_fmt = AV_SAMPLE_FMT_S16;
2105 const char *name = av_get_sample_fmt_name((AVSampleFormat)cin_fmt);
2106 if( !name ) name = _("None");
2107 strcpy(asset->ff_sample_format, name);
2109 char value[BCSTRLEN];
2110 if( !get_ff_option("cin_bitrate", options, value) )
2111 asset->ff_audio_bitrate = atoi(value);
2112 if( !get_ff_option("cin_quality", options, value) )
2113 asset->ff_audio_quality = atoi(value);
2116 void FFMPEG::load_audio_options(Asset *asset, EDL *edl)
2118 char options_path[BCTEXTLEN];
2119 set_option_path(options_path, "audio/%s", asset->acodec);
2120 if( !load_options(options_path,
2121 asset->ff_audio_options,
2122 sizeof(asset->ff_audio_options)) )
2123 scan_audio_options(asset, edl);
2126 void FFMPEG::scan_video_options(Asset *asset, EDL *edl)
2128 char cin_pix_fmt[BCSTRLEN];
2129 int cin_fmt = AV_PIX_FMT_NONE;
2130 const char *options = asset->ff_video_options;
2131 if( !get_ff_option("cin_pix_fmt", options, cin_pix_fmt) )
2132 cin_fmt = (int)av_get_pix_fmt(cin_pix_fmt);
2134 char video_codec[BCSTRLEN]; video_codec[0] = 0;
2135 AVCodec *av_codec = !get_codec(video_codec, "video", asset->vcodec) ?
2136 avcodec_find_encoder_by_name(video_codec) : 0;
2137 if( av_codec && av_codec->pix_fmts ) {
2138 if( 0 && edl ) { // frequently picks a bad answer
2139 int color_model = edl->session->color_model;
2140 int max_bits = BC_CModels::calculate_pixelsize(color_model) * 8;
2141 max_bits /= BC_CModels::components(color_model);
2142 cin_fmt = avcodec_find_best_pix_fmt_of_list(av_codec->pix_fmts,
2143 (BC_CModels::is_yuv(color_model) ?
2144 (max_bits > 8 ? AV_PIX_FMT_AYUV64LE : AV_PIX_FMT_YUV444P) :
2145 (max_bits > 8 ? AV_PIX_FMT_RGB48LE : AV_PIX_FMT_RGB24)), 0, 0);
2148 cin_fmt = av_codec->pix_fmts[0];
2151 if( cin_fmt < 0 ) cin_fmt = AV_PIX_FMT_YUV420P;
2152 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get((AVPixelFormat)cin_fmt);
2153 const char *name = desc ? desc->name : _("None");
2154 strcpy(asset->ff_pixel_format, name);
2156 char value[BCSTRLEN];
2157 if( !get_ff_option("cin_bitrate", options, value) )
2158 asset->ff_video_bitrate = atoi(value);
2159 if( !get_ff_option("cin_quality", options, value) )
2160 asset->ff_video_quality = atoi(value);
2163 void FFMPEG::load_video_options(Asset *asset, EDL *edl)
2165 char options_path[BCTEXTLEN];
2166 set_option_path(options_path, "video/%s", asset->vcodec);
2167 if( !load_options(options_path,
2168 asset->ff_video_options,
2169 sizeof(asset->ff_video_options)) )
2170 scan_video_options(asset, edl);
2173 void FFMPEG::scan_format_options(Asset *asset, EDL *edl)
2177 void FFMPEG::load_format_options(Asset *asset, EDL *edl)
2179 char options_path[BCTEXTLEN];
2180 set_option_path(options_path, "format/%s", asset->fformat);
2181 if( !load_options(options_path,
2182 asset->ff_format_options,
2183 sizeof(asset->ff_format_options)) )
2184 scan_format_options(asset, edl);
2187 int FFMPEG::load_defaults(const char *path, const char *type,
2188 char *codec, char *codec_options, int len)
2190 char default_file[BCTEXTLEN];
2191 set_option_path(default_file, "%s/%s.dfl", path, type);
2192 FILE *fp = fopen(default_file,"r");
2194 fgets(codec, BCSTRLEN, fp);
2196 while( *cp && *cp!='\n' ) ++cp;
2198 while( len > 0 && fgets(codec_options, len, fp) ) {
2199 int n = strlen(codec_options);
2200 codec_options += n; len -= n;
2203 set_option_path(default_file, "%s/%s", path, codec);
2204 return load_options(default_file, codec_options, len);
2207 void FFMPEG::set_asset_format(Asset *asset, EDL *edl, const char *text)
2209 if( asset->format != FILE_FFMPEG ) return;
2210 if( text != asset->fformat )
2211 strcpy(asset->fformat, text);
2212 if( !asset->ff_format_options[0] )
2213 load_format_options(asset, edl);
2214 if( asset->audio_data && !asset->ff_audio_options[0] ) {
2215 if( !load_defaults("audio", text, asset->acodec,
2216 asset->ff_audio_options, sizeof(asset->ff_audio_options)) )
2217 scan_audio_options(asset, edl);
2219 asset->audio_data = 0;
2221 if( asset->video_data && !asset->ff_video_options[0] ) {
2222 if( !load_defaults("video", text, asset->vcodec,
2223 asset->ff_video_options, sizeof(asset->ff_video_options)) )
2224 scan_video_options(asset, edl);
2226 asset->video_data = 0;
2230 int FFMPEG::get_encoder(const char *options,
2231 char *format, char *codec, char *bsfilter)
2233 FILE *fp = fopen(options,"r");
2235 eprintf(_("options open failed %s\n"),options);
2238 char line[BCTEXTLEN];
2239 if( !fgets(line, sizeof(line), fp) ||
2240 scan_encoder(line, format, codec, bsfilter) )
2241 eprintf(_("format/codec not found %s\n"), options);
2246 int FFMPEG::scan_encoder(const char *line,
2247 char *format, char *codec, char *bsfilter)
2249 format[0] = codec[0] = bsfilter[0] = 0;
2250 if( scan_option_line(line, format, codec) ) return 1;
2252 while( *cp && *cp != '|' ) ++cp;
2253 if( !*cp ) return 0;
2255 do { *bp-- = 0; } while( bp>=codec && (*bp==' ' || *bp == '\t' ) );
2256 while( *++cp && (*cp==' ' || *cp == '\t') );
2258 for( int i=BCTEXTLEN; --i>0 && *cp; ) *bp++ = *cp++;
2263 int FFMPEG::read_options(const char *options, AVDictionary *&opts, int skip)
2265 FILE *fp = fopen(options,"r");
2268 while( !ret && --skip >= 0 ) {
2270 while( ch >= 0 && ch != '\n' ) ch = getc(fp);
2271 if( ch < 0 ) ret = 1;
2274 ret = read_options(fp, options, opts);
2279 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
2281 FILE *fp = fmemopen((void *)options,strlen(options),"r");
2283 int ret = read_options(fp, options, opts);
2286 AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
2287 if( tag ) st->id = strtol(tag->value,0,0);
2292 void FFMPEG::put_cache_frame(VFrame *frame, int64_t position)
2294 file_base->file->put_cache_frame(frame, position, 0);
2297 int FFMPEG::get_use_cache()
2299 return file_base->file->get_use_cache();
2302 void FFMPEG::purge_cache()
2304 file_base->file->purge_cache();
2307 FFCodecRemap::FFCodecRemap()
2312 FFCodecRemap::~FFCodecRemap()
2314 delete [] old_codec;
2315 delete [] new_codec;
2318 int FFCodecRemaps::add(const char *val)
2320 char old_codec[BCSTRLEN], new_codec[BCSTRLEN];
2321 if( sscanf(val, " %63[a-zA-z0-9_-] = %63[a-z0-9_-]",
2322 &old_codec[0], &new_codec[0]) != 2 ) return 1;
2323 FFCodecRemap &remap = append();
2324 remap.old_codec = cstrdup(old_codec);
2325 remap.new_codec = cstrdup(new_codec);
2330 int FFCodecRemaps::update(AVCodecID &codec_id, AVCodec *&decoder)
2332 AVCodec *codec = avcodec_find_decoder(codec_id);
2333 if( !codec ) return -1;
2334 const char *name = codec->name;
2335 FFCodecRemaps &map = *this;
2337 while( --k >= 0 && strcmp(map[k].old_codec, name) );
2338 if( k < 0 ) return 1;
2339 const char *new_codec = map[k].new_codec;
2340 codec = avcodec_find_decoder_by_name(new_codec);
2341 if( !codec ) return -1;
2346 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
2348 int ret = 0, no = 0;
2349 char line[BCTEXTLEN];
2350 while( !ret && fgets(line, sizeof(line), fp) ) {
2351 line[sizeof(line)-1] = 0;
2352 if( line[0] == '#' ) continue;
2353 if( line[0] == '\n' ) continue;
2354 char key[BCSTRLEN], val[BCTEXTLEN];
2355 if( scan_option_line(line, key, val) ) {
2356 eprintf(_("err reading %s: line %d\n"), options, no);
2360 if( !strcmp(key, "duration") )
2361 opt_duration = strtod(val, 0);
2362 else if( !strcmp(key, "video_decoder") )
2363 opt_video_decoder = cstrdup(val);
2364 else if( !strcmp(key, "audio_decoder") )
2365 opt_audio_decoder = cstrdup(val);
2366 else if( !strcmp(key, "remap_video_decoder") )
2367 video_codec_remaps.add(val);
2368 else if( !strcmp(key, "remap_audio_decoder") )
2369 audio_codec_remaps.add(val);
2370 else if( !strcmp(key, "video_filter") )
2371 opt_video_filter = cstrdup(val);
2372 else if( !strcmp(key, "audio_filter") )
2373 opt_audio_filter = cstrdup(val);
2374 else if( !strcmp(key, "cin_hw_dev") )
2375 opt_hw_dev = cstrdup(val);
2376 else if( !strcmp(key, "loglevel") )
2379 av_dict_set(&opts, key, val, 0);
2385 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
2387 char option_path[BCTEXTLEN];
2388 set_option_path(option_path, "%s", options);
2389 return read_options(option_path, opts);
2392 int FFMPEG::load_options(const char *path, char *bfr, int len)
2395 FILE *fp = fopen(path, "r");
2397 fgets(bfr, len, fp); // skip hdr
2398 len = fread(bfr, 1, len-1, fp);
2399 if( len < 0 ) len = 0;
2405 void FFMPEG::set_loglevel(const char *ap)
2407 if( !ap || !*ap ) return;
2412 { "quiet" , AV_LOG_QUIET },
2413 { "panic" , AV_LOG_PANIC },
2414 { "fatal" , AV_LOG_FATAL },
2415 { "error" , AV_LOG_ERROR },
2416 { "warning", AV_LOG_WARNING },
2417 { "info" , AV_LOG_INFO },
2418 { "verbose", AV_LOG_VERBOSE },
2419 { "debug" , AV_LOG_DEBUG },
2421 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
2422 if( !strcmp(log_levels[i].name, ap) ) {
2423 av_log_set_level(log_levels[i].level);
2427 av_log_set_level(atoi(ap));
2430 double FFMPEG::to_secs(int64_t time, AVRational time_base)
2432 double base_time = time == AV_NOPTS_VALUE ? 0 :
2433 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
2434 return base_time / AV_TIME_BASE;
2437 int FFMPEG::info(char *text, int len)
2439 if( len <= 0 ) return 0;
2441 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
2443 report("format: %s\n",fmt_ctx->iformat->name);
2444 if( ffvideo.size() > 0 )
2445 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
2446 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
2447 const char *unkn = _("(unkn)");
2448 FFVideoStream *vid = ffvideo[vidx];
2449 AVStream *st = vid->st;
2450 AVCodecID codec_id = st->codecpar->codec_id;
2451 report(_("vid%d (%d), id 0x%06x:\n"), vid->idx, vid->fidx, codec_id);
2452 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
2453 report(" video%d %s ", vidx+1, desc ? desc->name : unkn);
2454 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
2455 AVPixelFormat pix_fmt = (AVPixelFormat)st->codecpar->format;
2456 const char *pfn = av_get_pix_fmt_name(pix_fmt);
2457 report(" pix %s\n", pfn ? pfn : unkn);
2458 int interlace = st->codecpar->field_order;
2459 report(" interlace (container level): %i\n", interlace ? interlace : -1);
2460 int interlace_codec = interlace_from_codec;
2461 report(" interlace (codec level): %i\n", interlace_codec ? interlace_codec : -1);
2462 enum AVColorSpace space = st->codecpar->color_space;
2463 const char *nm = av_color_space_name(space);
2464 report(" color space:%s", nm ? nm : unkn);
2465 enum AVColorRange range = st->codecpar->color_range;
2466 const char *rg = av_color_range_name(range);
2467 report("/ range:%s\n", rg ? rg : unkn);
2468 double secs = to_secs(st->duration, st->time_base);
2469 int64_t length = secs * vid->frame_rate + 0.5;
2470 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
2471 int64_t nudge = ofs * vid->frame_rate;
2472 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
2473 report(" %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
2474 int hrs = secs/3600; secs -= hrs*3600;
2475 int mins = secs/60; secs -= mins*60;
2476 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
2477 double theta = vid->get_rotation_angle();
2478 if( fabs(theta) > 1 )
2479 report(" rotation angle: %0.1f\n", theta);
2481 if( ffaudio.size() > 0 )
2482 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
2483 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2484 FFAudioStream *aud = ffaudio[aidx];
2485 AVStream *st = aud->st;
2486 AVCodecID codec_id = st->codecpar->codec_id;
2487 report(_("aud%d (%d), id 0x%06x:\n"), aud->idx, aud->fidx, codec_id);
2488 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
2489 int nch = aud->channels, ch0 = aud->channel0+1;
2490 report(" audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
2491 AVSampleFormat sample_fmt = (AVSampleFormat)st->codecpar->format;
2492 const char *fmt = av_get_sample_fmt_name(sample_fmt);
2493 report(" %s %d", fmt, aud->sample_rate);
2494 int sample_bits = av_get_bits_per_sample(codec_id);
2495 report(" %dbits\n", sample_bits);
2496 double secs = to_secs(st->duration, st->time_base);
2497 int64_t length = secs * aud->sample_rate + 0.5;
2498 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
2499 int64_t nudge = ofs * aud->sample_rate;
2500 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
2501 report(" %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
2502 int hrs = secs/3600; secs -= hrs*3600;
2503 int mins = secs/60; secs -= mins*60;
2504 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
2506 if( fmt_ctx->nb_programs > 0 )
2507 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
2508 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
2509 report("program %d", i+1);
2510 AVProgram *pgrm = fmt_ctx->programs[i];
2511 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2512 int idx = pgrm->stream_index[j];
2513 int vidx = ffvideo.size();
2514 while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
2516 report(", vid%d", vidx);
2519 int aidx = ffaudio.size();
2520 while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
2522 report(", aud%d", aidx);
2525 report(", (%d)", pgrm->stream_index[j]);
2530 AVDictionaryEntry *tag = 0;
2531 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
2532 report("%s=%s\n", tag->key, tag->value);
2541 int FFMPEG::init_decoder(const char *filename)
2543 ff_lock("FFMPEG::init_decoder");
2545 char file_opts[BCTEXTLEN];
2546 strcpy(file_opts, filename);
2547 char *bp = strrchr(file_opts, '/');
2548 if( !bp ) bp = file_opts;
2549 char *sp = strrchr(bp, '.');
2550 if( !sp ) sp = bp + strlen(bp);
2552 AVInputFormat *ifmt = 0;
2554 strcpy(sp, ".opts");
2555 fp = fopen(file_opts, "r");
2558 read_options(fp, file_opts, opts);
2560 AVDictionaryEntry *tag;
2561 if( (tag=av_dict_get(opts, "format", NULL, 0)) != 0 ) {
2562 ifmt = av_find_input_format(tag->value);
2566 load_options("decode.opts", opts);
2567 AVDictionary *fopts = 0;
2568 av_dict_copy(&fopts, opts, 0);
2569 int ret = avformat_open_input(&fmt_ctx, filename, ifmt, &fopts);
2570 av_dict_free(&fopts);
2572 ret = avformat_find_stream_info(fmt_ctx, NULL);
2577 return !ret ? 0 : 1;
2580 int FFMPEG::open_decoder()
2583 if( stat(fmt_ctx->url, &st) < 0 ) {
2584 eprintf(_("can't stat file: %s\n"), fmt_ctx->url);
2588 int64_t file_bits = 8 * st.st_size;
2589 if( !fmt_ctx->bit_rate && opt_duration > 0 )
2590 fmt_ctx->bit_rate = file_bits / opt_duration;
2593 if( fmt_ctx->bit_rate > 0 ) {
2594 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2595 AVStream *st = fmt_ctx->streams[i];
2596 if( st->duration != AV_NOPTS_VALUE ) continue;
2597 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
2598 st->duration = av_rescale(file_bits, st->time_base.den,
2599 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
2603 if( estimated && !(fflags & FF_ESTM_TIMES) ) {
2604 fflags |= FF_ESTM_TIMES;
2605 printf("FFMPEG::open_decoder: some stream times estimated: %s\n",
2609 ff_lock("FFMPEG::open_decoder");
2610 int ret = 0, bad_time = 0;
2611 for( int i=0; !ret && i<(int)fmt_ctx->nb_streams; ++i ) {
2612 AVStream *st = fmt_ctx->streams[i];
2613 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
2614 AVCodecParameters *avpar = st->codecpar;
2615 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avpar->codec_id);
2616 if( !codec_desc ) continue;
2617 switch( avpar->codec_type ) {
2618 case AVMEDIA_TYPE_VIDEO: {
2619 if( avpar->width < 1 ) continue;
2620 if( avpar->height < 1 ) continue;
2621 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
2622 if( framerate.num < 1 ) continue;
2624 int vidx = ffvideo.size();
2625 FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
2626 vstrm_index.append(ffidx(vidx, 0));
2627 ffvideo.append(vid);
2628 vid->width = avpar->width;
2629 vid->height = avpar->height;
2630 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
2631 switch( avpar->color_range ) {
2632 case AVCOL_RANGE_MPEG:
2633 vid->color_range = BC_COLORS_MPEG;
2635 case AVCOL_RANGE_JPEG:
2636 vid->color_range = BC_COLORS_JPEG;
2639 vid->color_range = !file_base ? BC_COLORS_JPEG :
2640 file_base->file->preferences->yuv_color_range;
2643 switch( avpar->color_space ) {
2644 case AVCOL_SPC_BT470BG:
2645 vid->color_space = BC_COLORS_BT601_PAL;
2647 case AVCOL_SPC_SMPTE170M:
2648 vid->color_space = BC_COLORS_BT601_NTSC;
2650 case AVCOL_SPC_BT709:
2651 vid->color_space = BC_COLORS_BT709;
2653 case AVCOL_SPC_BT2020_NCL:
2654 vid->color_space = BC_COLORS_BT2020_NCL;
2656 case AVCOL_SPC_BT2020_CL:
2657 vid->color_space = BC_COLORS_BT2020_CL;
2660 vid->color_space = !file_base ? BC_COLORS_BT601_NTSC :
2661 file_base->file->preferences->yuv_color_space;
2664 double secs = to_secs(st->duration, st->time_base);
2665 vid->length = secs * vid->frame_rate;
2666 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
2667 vid->nudge = st->start_time;
2669 ret = vid->create_filter(opt_video_filter);
2671 case AVMEDIA_TYPE_AUDIO: {
2672 if( avpar->channels < 1 ) continue;
2673 if( avpar->sample_rate < 1 ) continue;
2675 int aidx = ffaudio.size();
2676 FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
2677 ffaudio.append(aud);
2678 aud->channel0 = astrm_index.size();
2679 aud->channels = avpar->channels;
2680 for( int ch=0; ch<aud->channels; ++ch )
2681 astrm_index.append(ffidx(aidx, ch));
2682 aud->sample_rate = avpar->sample_rate;
2683 double secs = to_secs(st->duration, st->time_base);
2684 aud->length = secs * aud->sample_rate;
2685 aud->init_swr(aud->channels, avpar->format, aud->sample_rate);
2686 aud->nudge = st->start_time;
2688 ret = aud->create_filter(opt_audio_filter);
2693 if( bad_time && !(fflags & FF_BAD_TIMES) ) {
2694 fflags |= FF_BAD_TIMES;
2695 printf(_("FFMPEG::open_decoder: some stream have bad times: %s\n"),
2699 return ret < 0 ? -1 : 0;
2703 int FFMPEG::init_encoder(const char *filename)
2705 // try access first for named pipes
2706 int ret = access(filename, W_OK);
2708 int fd = ::open(filename,O_WRONLY);
2709 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
2710 if( fd >= 0 ) { close(fd); ret = 0; }
2713 eprintf(_("bad file path: %s\n"), filename);
2716 ret = get_file_format();
2718 eprintf(_("bad file format: %s\n"), filename);
2722 eprintf(_("mismatch audio/video file format: %s\n"), filename);
2725 ff_lock("FFMPEG::init_encoder");
2727 char format[BCSTRLEN];
2728 if( get_format(format, "format", file_format) )
2729 strcpy(format, file_format);
2730 avformat_alloc_output_context2(&fmt_ctx, 0, format, filename);
2732 eprintf(_("failed: %s\n"), filename);
2737 load_options("encode.opts", opts);
2743 int FFMPEG::open_encoder(const char *type, const char *spec)
2746 Asset *asset = file_base->asset;
2747 char *filename = asset->path;
2748 AVDictionary *sopts = 0;
2749 av_dict_copy(&sopts, opts, 0);
2750 char option_path[BCTEXTLEN];
2751 set_option_path(option_path, "%s/%s.opts", type, type);
2752 read_options(option_path, sopts);
2753 get_option_path(option_path, type, spec);
2754 char format_name[BCSTRLEN], codec_name[BCTEXTLEN], bsfilter[BCTEXTLEN];
2755 if( get_encoder(option_path, format_name, codec_name, bsfilter) ) {
2756 eprintf(_("get_encoder failed %s:%s\n"), option_path, filename);
2761 if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
2763 else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
2764 else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
2767 ff_lock("FFMPEG::open_encoder");
2770 AVCodecContext *ctx = 0;
2772 const AVCodecDescriptor *codec_desc = 0;
2773 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
2775 eprintf(_("cant find codec %s:%s\n"), codec_name, filename);
2779 codec_desc = avcodec_descriptor_get(codec->id);
2781 eprintf(_("unknown codec %s:%s\n"), codec_name, filename);
2786 st = avformat_new_stream(fmt_ctx, 0);
2788 eprintf(_("cant create stream %s:%s\n"), codec_name, filename);
2793 switch( codec_desc->type ) {
2794 case AVMEDIA_TYPE_AUDIO: {
2796 eprintf(_("duplicate audio %s:%s\n"), codec_name, filename);
2800 if( scan_options(asset->ff_audio_options, sopts, st) ) {
2801 eprintf(_("bad audio options %s:%s\n"), codec_name, filename);
2806 ctx = avcodec_alloc_context3(codec);
2807 if( asset->ff_audio_bitrate > 0 ) {
2808 ctx->bit_rate = asset->ff_audio_bitrate;
2810 sprintf(arg, "%d", asset->ff_audio_bitrate);
2811 av_dict_set(&sopts, "b", arg, 0);
2813 else if( asset->ff_audio_quality >= 0 ) {
2814 ctx->global_quality = asset->ff_audio_quality * FF_QP2LAMBDA;
2815 ctx->qmin = ctx->qmax = asset->ff_audio_quality;
2816 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2817 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2818 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2820 av_dict_set(&sopts, "flags", "+qscale", 0);
2821 sprintf(arg, "%d", asset->ff_audio_quality);
2822 av_dict_set(&sopts, "qscale", arg, 0);
2823 sprintf(arg, "%d", ctx->global_quality);
2824 av_dict_set(&sopts, "global_quality", arg, 0);
2826 int aidx = ffaudio.size();
2827 int fidx = aidx + ffvideo.size();
2828 FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
2829 aud->avctx = ctx; ffaudio.append(aud); fst = aud;
2830 aud->sample_rate = asset->sample_rate;
2831 ctx->channels = aud->channels = asset->channels;
2832 for( int ch=0; ch<aud->channels; ++ch )
2833 astrm_index.append(ffidx(aidx, ch));
2834 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
2835 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
2836 if( !ctx->sample_rate ) {
2837 eprintf(_("check_sample_rate failed %s\n"), filename);
2841 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
2842 AVSampleFormat sample_fmt = av_get_sample_fmt(asset->ff_sample_format);
2843 if( sample_fmt == AV_SAMPLE_FMT_NONE )
2844 sample_fmt = codec->sample_fmts ? codec->sample_fmts[0] : AV_SAMPLE_FMT_S16;
2845 ctx->sample_fmt = sample_fmt;
2846 uint64_t layout = av_get_default_channel_layout(ctx->channels);
2847 aud->resample_context = swr_alloc_set_opts(NULL,
2848 layout, ctx->sample_fmt, aud->sample_rate,
2849 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
2851 swr_init(aud->resample_context);
2854 case AVMEDIA_TYPE_VIDEO: {
2856 eprintf(_("duplicate video %s:%s\n"), codec_name, filename);
2860 if( scan_options(asset->ff_video_options, sopts, st) ) {
2861 eprintf(_("bad video options %s:%s\n"), codec_name, filename);
2866 ctx = avcodec_alloc_context3(codec);
2867 if( asset->ff_video_bitrate > 0 ) {
2868 ctx->bit_rate = asset->ff_video_bitrate;
2870 sprintf(arg, "%d", asset->ff_video_bitrate);
2871 av_dict_set(&sopts, "b", arg, 0);
2873 else if( asset->ff_video_quality >= 0 ) {
2874 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
2875 ctx->qmin = ctx->qmax = asset->ff_video_quality;
2876 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2877 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2878 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2880 av_dict_set(&sopts, "flags", "+qscale", 0);
2881 sprintf(arg, "%d", asset->ff_video_quality);
2882 av_dict_set(&sopts, "qscale", arg, 0);
2883 sprintf(arg, "%d", ctx->global_quality);
2884 av_dict_set(&sopts, "global_quality", arg, 0);
2886 int vidx = ffvideo.size();
2887 int fidx = vidx + ffaudio.size();
2888 FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
2889 vstrm_index.append(ffidx(vidx, 0));
2890 vid->avctx = ctx; ffvideo.append(vid); fst = vid;
2891 vid->width = asset->width;
2892 vid->height = asset->height;
2893 vid->frame_rate = asset->frame_rate;
2894 if( (vid->color_range = asset->ff_color_range) < 0 )
2895 vid->color_range = file_base->file->preferences->yuv_color_range;
2896 switch( vid->color_range ) {
2897 case BC_COLORS_MPEG: ctx->color_range = AVCOL_RANGE_MPEG; break;
2898 case BC_COLORS_JPEG: ctx->color_range = AVCOL_RANGE_JPEG; break;
2900 if( (vid->color_space = asset->ff_color_space) < 0 )
2901 vid->color_space = file_base->file->preferences->yuv_color_space;
2902 switch( vid->color_space ) {
2903 case BC_COLORS_BT601_NTSC: ctx->colorspace = AVCOL_SPC_SMPTE170M; break;
2904 case BC_COLORS_BT601_PAL: ctx->colorspace = AVCOL_SPC_BT470BG; break;
2905 case BC_COLORS_BT709: ctx->colorspace = AVCOL_SPC_BT709; break;
2906 case BC_COLORS_BT2020_NCL: ctx->colorspace = AVCOL_SPC_BT2020_NCL; break;
2907 case BC_COLORS_BT2020_CL: ctx->colorspace = AVCOL_SPC_BT2020_CL; break;
2909 AVPixelFormat pix_fmt = av_get_pix_fmt(asset->ff_pixel_format);
2910 if( opt_hw_dev != 0 ) {
2911 AVHWDeviceType hw_type = vid->encode_hw_activate(opt_hw_dev);
2913 case AV_HWDEVICE_TYPE_VAAPI:
2914 pix_fmt = AV_PIX_FMT_VAAPI;
2916 case AV_HWDEVICE_TYPE_NONE:
2920 if( pix_fmt == AV_PIX_FMT_NONE )
2921 pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
2922 ctx->pix_fmt = pix_fmt;
2924 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
2925 int mask_w = (1<<desc->log2_chroma_w)-1;
2926 ctx->width = (vid->width+mask_w) & ~mask_w;
2927 int mask_h = (1<<desc->log2_chroma_h)-1;
2928 ctx->height = (vid->height+mask_h) & ~mask_h;
2929 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
2930 AVRational frame_rate;
2931 if (ctx->codec->id == AV_CODEC_ID_MPEG1VIDEO ||
2932 ctx->codec->id == AV_CODEC_ID_MPEG2VIDEO)
2933 frame_rate = check_frame_rate(codec->supported_framerates, vid->frame_rate);
2935 frame_rate = av_d2q(vid->frame_rate, INT_MAX);
2936 if( !frame_rate.num || !frame_rate.den ) {
2937 eprintf(_("check_frame_rate failed %s\n"), filename);
2941 av_reduce(&frame_rate.num, &frame_rate.den,
2942 frame_rate.num, frame_rate.den, INT_MAX);
2943 ctx->framerate = (AVRational) { frame_rate.num, frame_rate.den };
2944 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
2945 st->avg_frame_rate = frame_rate;
2946 st->time_base = ctx->time_base;
2948 vid->interlaced = asset->interlace_mode == ILACE_MODE_TOP_FIRST ||
2949 asset->interlace_mode == ILACE_MODE_BOTTOM_FIRST ? 1 : 0;
2950 vid->top_field_first = asset->interlace_mode == ILACE_MODE_TOP_FIRST ? 1 : 0;
2951 switch (asset->interlace_mode) {
2952 case ILACE_MODE_TOP_FIRST:
2953 if (ctx->codec->id == AV_CODEC_ID_MJPEG)
2954 av_dict_set(&sopts, "field_order", "tt", 0);
2956 av_dict_set(&sopts, "field_order", "tb", 0);
2957 if (ctx->codec_id != AV_CODEC_ID_MJPEG)
2958 av_dict_set(&sopts, "flags", "+ilme+ildct", 0);
2960 case ILACE_MODE_BOTTOM_FIRST:
2961 if (ctx->codec->id == AV_CODEC_ID_MJPEG)
2962 av_dict_set(&sopts, "field_order", "bb", 0);
2964 av_dict_set(&sopts, "field_order", "bt", 0);
2965 if (ctx->codec_id != AV_CODEC_ID_MJPEG)
2966 av_dict_set(&sopts, "flags", "+ilme+ildct", 0);
2968 case ILACE_MODE_NOTINTERLACED: av_dict_set(&sopts, "field_order", "progressive", 0); break;
2972 eprintf(_("not audio/video, %s:%s\n"), codec_name, filename);
2977 AVDictionaryEntry *tag;
2978 if( (tag=av_dict_get(sopts, "cin_stats_filename", NULL, 0)) != 0 ) {
2979 char suffix[BCSTRLEN]; sprintf(suffix,"-%d.log",fst->fidx);
2980 fst->stats_filename = cstrcat(2, tag->value, suffix);
2982 if( (tag=av_dict_get(sopts, "flags", NULL, 0)) != 0 ) {
2983 int pass = fst->pass;
2984 char *cp = tag->value;
2986 int ch = *cp++, pfx = ch=='-' ? -1 : ch=='+' ? 1 : 0;
2987 if( !isalnum(!pfx ? ch : (ch=*cp++)) ) continue;
2988 char id[BCSTRLEN], *bp = id, *ep = bp+sizeof(id)-1;
2989 for( *bp++=ch; isalnum(ch=*cp); ++cp )
2990 if( bp < ep ) *bp++ = ch;
2992 if( !strcmp(id, "pass1") ) {
2993 pass = pfx<0 ? (pass&~1) : pfx>0 ? (pass|1) : 1;
2995 else if( !strcmp(id, "pass2") ) {
2996 pass = pfx<0 ? (pass&~2) : pfx>0 ? (pass|2) : 2;
2999 if( (fst->pass=pass) ) {
3000 if( pass & 1 ) ctx->flags |= AV_CODEC_FLAG_PASS1;
3001 if( pass & 2 ) ctx->flags |= AV_CODEC_FLAG_PASS2;
3007 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
3008 ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
3009 if( fst->stats_filename && (ret=fst->init_stats_file()) )
3010 eprintf(_("error: stats file = %s\n"), fst->stats_filename);
3013 av_dict_set(&sopts, "cin_bitrate", 0, 0);
3014 av_dict_set(&sopts, "cin_quality", 0, 0);
3016 if( !av_dict_get(sopts, "threads", NULL, 0) )
3017 ctx->thread_count = ff_cpus();
3018 ret = avcodec_open2(ctx, codec, &sopts);
3020 ret = avcodec_parameters_from_context(st->codecpar, ctx);
3022 fprintf(stderr, "Could not copy the stream parameters\n");
3025 _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
3026 ret = avcodec_copy_context(st->codec, ctx);
3027 _Pragma("GCC diagnostic warning \"-Wdeprecated-declarations\"")
3029 fprintf(stderr, "Could not copy the stream context\n");
3032 ff_err(ret,"FFMPEG::open_encoder");
3033 eprintf(_("open failed %s:%s\n"), codec_name, filename);
3039 if( !ret && fst && bsfilter[0] ) {
3040 ret = av_bsf_list_parse_str(bsfilter, &fst->bsfc);
3042 ff_err(ret,"FFMPEG::open_encoder");
3043 eprintf(_("bitstream filter failed %s:\n%s\n"), filename, bsfilter);
3054 av_dict_free(&sopts);
3058 int FFMPEG::close_encoder()
3061 if( encoding > 0 ) {
3062 av_write_trailer(fmt_ctx);
3063 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
3064 avio_closep(&fmt_ctx->pb);
3070 int FFMPEG::decode_activate()
3072 if( decoding < 0 ) {
3074 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
3075 ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
3076 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
3077 ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
3078 // set nudges for each program stream set
3079 const int64_t min_nudge = INT64_MIN+1;
3080 int npgrms = fmt_ctx->nb_programs;
3081 for( int i=0; i<npgrms; ++i ) {
3082 AVProgram *pgrm = fmt_ctx->programs[i];
3083 // first start time video stream
3084 int64_t vstart_time = min_nudge, astart_time = min_nudge;
3085 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
3086 int fidx = pgrm->stream_index[j];
3087 AVStream *st = fmt_ctx->streams[fidx];
3088 AVCodecParameters *avpar = st->codecpar;
3089 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
3090 if( st->start_time == AV_NOPTS_VALUE ) continue;
3091 if( vstart_time < st->start_time )
3092 vstart_time = st->start_time;
3095 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
3096 if( st->start_time == AV_NOPTS_VALUE ) continue;
3097 if( astart_time < st->start_time )
3098 astart_time = st->start_time;
3102 //since frame rate is much more grainy than sample rate, it is better to
3103 // align using video, so that total absolute error is minimized.
3104 int64_t nudge = vstart_time > min_nudge ? vstart_time :
3105 astart_time > min_nudge ? astart_time : AV_NOPTS_VALUE;
3106 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
3107 int fidx = pgrm->stream_index[j];
3108 AVStream *st = fmt_ctx->streams[fidx];
3109 AVCodecParameters *avpar = st->codecpar;
3110 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
3111 for( int k=0; k<ffvideo.size(); ++k ) {
3112 if( ffvideo[k]->fidx != fidx ) continue;
3113 ffvideo[k]->nudge = nudge;
3117 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
3118 for( int k=0; k<ffaudio.size(); ++k ) {
3119 if( ffaudio[k]->fidx != fidx ) continue;
3120 ffaudio[k]->nudge = nudge;
3126 // set nudges for any streams not yet set
3127 int64_t vstart_time = min_nudge, astart_time = min_nudge;
3128 int nstreams = fmt_ctx->nb_streams;
3129 for( int i=0; i<nstreams; ++i ) {
3130 AVStream *st = fmt_ctx->streams[i];
3131 AVCodecParameters *avpar = st->codecpar;
3132 switch( avpar->codec_type ) {
3133 case AVMEDIA_TYPE_VIDEO: {
3134 if( st->start_time == AV_NOPTS_VALUE ) continue;
3135 int vidx = ffvideo.size();
3136 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
3137 if( vidx < 0 ) continue;
3138 if( ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
3139 if( vstart_time < st->start_time )
3140 vstart_time = st->start_time;
3142 case AVMEDIA_TYPE_AUDIO: {
3143 if( st->start_time == AV_NOPTS_VALUE ) continue;
3144 int aidx = ffaudio.size();
3145 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
3146 if( aidx < 0 ) continue;
3147 if( ffaudio[aidx]->frame_sz < avpar->frame_size )
3148 ffaudio[aidx]->frame_sz = avpar->frame_size;
3149 if( ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
3150 if( astart_time < st->start_time )
3151 astart_time = st->start_time;
3156 int64_t nudge = vstart_time > min_nudge ? vstart_time :
3157 astart_time > min_nudge ? astart_time : 0;
3158 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
3159 if( ffvideo[vidx]->nudge == AV_NOPTS_VALUE )
3160 ffvideo[vidx]->nudge = nudge;
3162 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
3163 if( ffaudio[aidx]->nudge == AV_NOPTS_VALUE )
3164 ffaudio[aidx]->nudge = nudge;
3171 int FFMPEG::encode_activate()
3174 if( encoding < 0 ) {
3176 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
3177 (ret=avio_open(&fmt_ctx->pb, fmt_ctx->url, AVIO_FLAG_WRITE)) < 0 ) {
3178 ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
3182 if( !strcmp(file_format, "image2") ) {
3183 Asset *asset = file_base->asset;
3184 const char *filename = asset->path;
3185 FILE *fp = fopen(filename,"w");
3187 eprintf(_("Cant write image2 header file: %s\n %m"), filename);
3190 fprintf(fp, "IMAGE2\n");
3191 fprintf(fp, "# Frame rate: %f\n", asset->frame_rate);
3192 fprintf(fp, "# Width: %d\n", asset->width);
3193 fprintf(fp, "# Height: %d\n", asset->height);
3197 AVProgram *prog = av_new_program(fmt_ctx, prog_id);
3198 for( int i=0; i< ffvideo.size(); ++i )
3199 av_program_add_stream_index(fmt_ctx, prog_id, ffvideo[i]->fidx);
3200 for( int i=0; i< ffaudio.size(); ++i )
3201 av_program_add_stream_index(fmt_ctx, prog_id, ffaudio[i]->fidx);
3202 int pi = fmt_ctx->nb_programs;
3203 while( --pi >= 0 && fmt_ctx->programs[pi]->id != prog_id );
3204 AVDictionary **meta = &prog->metadata;
3205 av_dict_set(meta, "service_provider", "cin5", 0);
3206 const char *path = fmt_ctx->url, *bp = strrchr(path,'/');
3207 if( bp ) path = bp + 1;
3208 av_dict_set(meta, "title", path, 0);
3210 if( ffaudio.size() ) {
3211 const char *ep = getenv("CIN_AUDIO_LANG"), *lp = 0;
3212 if( !ep && (lp=getenv("LANG")) ) { // some are guesses
3213 static struct { const char lc[3], lng[4]; } lcode[] = {
3214 { "en", "eng" }, { "de", "ger" }, { "es", "spa" },
3215 { "eu", "bas" }, { "fr", "fre" }, { "el", "gre" },
3216 { "hi", "hin" }, { "it", "ita" }, { "ja", "jap" },
3217 { "ko", "kor" }, { "du", "dut" }, { "pl", "pol" },
3218 { "pt", "por" }, { "ru", "rus" }, { "sl", "slv" },
3219 { "uk", "ukr" }, { "vi", "vie" }, { "zh", "chi" },
3221 for( int i=sizeof(lcode)/sizeof(lcode[0]); --i>=0 && !ep; )
3222 if( !strncmp(lcode[i].lc,lp,2) ) ep = lcode[i].lng;
3224 if( !ep ) ep = "und";
3226 strncpy(lang,ep,3); lang[3] = 0;
3227 AVStream *st = ffaudio[0]->st;
3228 av_dict_set(&st->metadata,"language",lang,0);
3231 AVDictionary *fopts = 0;
3232 char option_path[BCTEXTLEN];
3233 set_option_path(option_path, "format/%s", file_format);
3234 read_options(option_path, fopts, 1);
3235 av_dict_copy(&fopts, opts, 0);
3236 if( scan_options(file_base->asset->ff_format_options, fopts, 0) ) {
3237 eprintf(_("bad format options %s\n"), file_base->asset->path);
3241 ret = avformat_write_header(fmt_ctx, &fopts);
3243 ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
3247 av_dict_free(&fopts);
3254 int FFMPEG::audio_seek(int stream, int64_t pos)
3256 int aidx = astrm_index[stream].st_idx;
3257 FFAudioStream *aud = ffaudio[aidx];
3258 aud->audio_seek(pos);
3262 int FFMPEG::video_probe(int64_t pos)
3264 int vidx = vstrm_index[0].st_idx;
3265 FFVideoStream *vid = ffvideo[vidx];
3268 int interlace1 = interlace_from_codec;
3269 //printf("interlace from codec: %i\n", interlace1);
3275 return ILACE_MODE_TOP_FIRST;
3278 return ILACE_MODE_BOTTOM_FIRST;
3279 case AV_FIELD_PROGRESSIVE:
3280 return ILACE_MODE_NOTINTERLACED;
3282 return ILACE_MODE_UNDETECTED;
3289 int FFMPEG::video_seek(int stream, int64_t pos)
3291 int vidx = vstrm_index[stream].st_idx;
3292 FFVideoStream *vid = ffvideo[vidx];
3293 vid->video_seek(pos);
3298 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
3300 if( !has_audio || chn >= astrm_index.size() ) return -1;
3301 int aidx = astrm_index[chn].st_idx;
3302 FFAudioStream *aud = ffaudio[aidx];
3303 if( aud->load(pos, len) < len ) return -1;
3304 int ch = astrm_index[chn].st_ch;
3305 int ret = aud->read(samples,len,ch);
3309 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
3311 if( !has_video || layer >= vstrm_index.size() ) return -1;
3312 int vidx = vstrm_index[layer].st_idx;
3313 FFVideoStream *vid = ffvideo[vidx];
3314 return vid->load(vframe, pos);
3318 int FFMPEG::encode(int stream, double **samples, int len)
3320 FFAudioStream *aud = ffaudio[stream];
3321 return aud->encode(samples, len);
3325 int FFMPEG::encode(int stream, VFrame *frame)
3327 FFVideoStream *vid = ffvideo[stream];
3328 return vid->encode(frame);
3331 void FFMPEG::start_muxer()
3339 void FFMPEG::stop_muxer()
3348 void FFMPEG::flow_off()
3351 flow_lock->lock("FFMPEG::flow_off");
3355 void FFMPEG::flow_on()
3359 flow_lock->unlock();
3362 void FFMPEG::flow_ctl()
3365 flow_lock->lock("FFMPEG::flow_ctl");
3366 flow_lock->unlock();
3370 int FFMPEG::mux_audio(FFrame *frm)
3372 FFStream *fst = frm->fst;
3373 AVCodecContext *ctx = fst->avctx;
3374 AVFrame *frame = *frm;
3375 AVRational tick_rate = {1, ctx->sample_rate};
3376 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
3377 int ret = fst->encode_frame(frame);
3379 ff_err(ret, "FFMPEG::mux_audio");
3380 return ret >= 0 ? 0 : 1;
3383 int FFMPEG::mux_video(FFrame *frm)
3385 FFStream *fst = frm->fst;
3386 AVFrame *frame = *frm;
3387 frame->pts = frm->position;
3388 int ret = fst->encode_frame(frame);
3390 ff_err(ret, "FFMPEG::mux_video");
3391 return ret >= 0 ? 0 : 1;
3397 double atm = -1, vtm = -1;
3398 FFrame *afrm = 0, *vfrm = 0;
3400 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
3401 FFStream *fst = ffaudio[i];
3402 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
3403 FFrame *frm = fst->frms.first;
3404 if( !frm ) { if( !done ) return; continue; }
3405 double tm = to_secs(frm->position, fst->avctx->time_base);
3406 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
3408 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
3409 FFStream *fst = ffvideo[i];
3410 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
3411 FFrame *frm = fst->frms.first;
3412 if( !frm ) { if( !done ) return; continue; }
3413 double tm = to_secs(frm->position, fst->avctx->time_base);
3414 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
3416 if( !demand ) flow_off();
3417 if( !afrm && !vfrm ) break;
3418 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
3419 vfrm->position, vfrm->fst->avctx->time_base,
3420 afrm->position, afrm->fst->avctx->time_base);
3421 FFrame *frm = v <= 0 ? vfrm : afrm;
3422 if( frm == afrm ) mux_audio(frm);
3423 if( frm == vfrm ) mux_video(frm);
3432 mux_lock->lock("FFMPEG::run");
3435 for( int i=0; i<ffaudio.size(); ++i )
3436 ffaudio[i]->drain();
3437 for( int i=0; i<ffvideo.size(); ++i )
3438 ffvideo[i]->drain();
3440 for( int i=0; i<ffaudio.size(); ++i )
3441 ffaudio[i]->flush();
3442 for( int i=0; i<ffvideo.size(); ++i )
3443 ffvideo[i]->flush();
3447 int FFMPEG::ff_total_audio_channels()
3449 return astrm_index.size();
3452 int FFMPEG::ff_total_astreams()
3454 return ffaudio.size();
3457 int FFMPEG::ff_audio_channels(int stream)
3459 return ffaudio[stream]->channels;
3462 int FFMPEG::ff_sample_rate(int stream)
3464 return ffaudio[stream]->sample_rate;
3467 const char* FFMPEG::ff_audio_format(int stream)
3469 AVStream *st = ffaudio[stream]->st;
3470 AVCodecID id = st->codecpar->codec_id;
3471 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
3472 return desc ? desc->name : _("Unknown");
3475 int FFMPEG::ff_audio_pid(int stream)
3477 return ffaudio[stream]->st->id;
3480 int64_t FFMPEG::ff_audio_samples(int stream)
3482 return ffaudio[stream]->length;
3485 // find audio astream/channels with this program,
3486 // or all program audio channels (astream=-1)
3487 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
3491 int vidx = ffvideo[vstream]->fidx;
3492 // find first program with this video stream
3493 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
3494 AVProgram *pgrm = fmt_ctx->programs[i];
3495 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
3496 int st_idx = pgrm->stream_index[j];
3497 AVStream *st = fmt_ctx->streams[st_idx];
3498 if( st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
3499 if( st_idx == vidx ) pidx = i;
3502 if( pidx < 0 ) return -1;
3504 int64_t channels = 0;
3505 AVProgram *pgrm = fmt_ctx->programs[pidx];
3506 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
3507 int aidx = pgrm->stream_index[j];
3508 AVStream *st = fmt_ctx->streams[aidx];
3509 if( st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
3510 if( astream > 0 ) { --astream; continue; }
3512 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
3513 if( ffaudio[i]->fidx == aidx ) astrm = i;
3515 if( ret < 0 ) ret = astrm;
3516 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
3517 channels |= mask << ffaudio[astrm]->channel0;
3519 if( !astream ) break;
3521 channel_mask = channels;
3526 int FFMPEG::ff_total_video_layers()
3528 return vstrm_index.size();
3531 int FFMPEG::ff_total_vstreams()
3533 return ffvideo.size();
3536 int FFMPEG::ff_video_width(int stream)
3538 FFVideoStream *vst = ffvideo[stream];
3539 return !vst->transpose ? vst->width : vst->height;
3542 int FFMPEG::ff_video_height(int stream)
3544 FFVideoStream *vst = ffvideo[stream];
3545 return !vst->transpose ? vst->height : vst->width;
3548 int FFMPEG::ff_set_video_width(int stream, int width)
3550 FFVideoStream *vst = ffvideo[stream];
3551 int *vw = !vst->transpose ? &vst->width : &vst->height, w = *vw;
3556 int FFMPEG::ff_set_video_height(int stream, int height)
3558 FFVideoStream *vst = ffvideo[stream];
3559 int *vh = !vst->transpose ? &vst->height : &vst->width, h = *vh;
3564 int FFMPEG::ff_coded_width(int stream)
3566 return ffvideo[stream]->avctx->coded_width;
3569 int FFMPEG::ff_coded_height(int stream)
3571 return ffvideo[stream]->avctx->coded_height;
3574 float FFMPEG::ff_aspect_ratio(int stream)
3576 //return ffvideo[stream]->aspect_ratio;
3577 AVFormatContext *fmt_ctx = ffvideo[stream]->fmt_ctx;
3578 AVStream *strm = ffvideo[stream]->st;
3579 AVCodecParameters *par = ffvideo[stream]->st->codecpar;
3581 AVRational sar = av_guess_sample_aspect_ratio(fmt_ctx, strm, NULL);
3583 av_reduce(&dar.num, &dar.den,
3584 par->width * sar.num,
3585 par->height * sar.den,
3589 return ffvideo[stream]->aspect_ratio;
3592 const char* FFMPEG::ff_video_codec(int stream)
3594 AVStream *st = ffvideo[stream]->st;
3595 AVCodecID id = st->codecpar->codec_id;
3596 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
3597 return desc ? desc->name : _("Unknown");
3600 int FFMPEG::ff_color_range(int stream)
3602 return ffvideo[stream]->color_range;
3605 int FFMPEG::ff_color_space(int stream)
3607 return ffvideo[stream]->color_space;
3610 double FFMPEG::ff_frame_rate(int stream)
3612 return ffvideo[stream]->frame_rate;
3615 int64_t FFMPEG::ff_video_frames(int stream)
3617 return ffvideo[stream]->length;
3620 int FFMPEG::ff_video_pid(int stream)
3622 return ffvideo[stream]->st->id;
3625 int FFMPEG::ff_video_mpeg_color_range(int stream)
3627 return ffvideo[stream]->st->codecpar->color_range == AVCOL_RANGE_MPEG ? 1 : 0;
3630 int FFMPEG::ff_interlace(int stream)
3632 // https://ffmpeg.org/doxygen/trunk/structAVCodecParserContext.html
3633 /* reads from demuxer because codec frame not ready */
3634 int interlace0 = ffvideo[stream]->st->codecpar->field_order;
3640 return ILACE_MODE_TOP_FIRST;
3643 return ILACE_MODE_BOTTOM_FIRST;
3644 case AV_FIELD_PROGRESSIVE:
3645 return ILACE_MODE_NOTINTERLACED;
3647 return ILACE_MODE_UNDETECTED;
3654 int FFMPEG::ff_cpus()
3656 return !file_base ? 1 : file_base->file->cpus;
3659 const char *FFMPEG::ff_hw_dev()
3661 return &file_base->file->preferences->use_hw_dev[0];
3664 Preferences *FFMPEG::ff_prefs()
3666 return !file_base ? 0 : file_base->file->preferences;
3669 double FFVideoStream::get_rotation_angle()
3672 int *matrix = (int*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX, &size);
3673 int len = size/sizeof(*matrix);
3674 if( !matrix || len < 5 ) return 0;
3675 const double s = 1/65536.;
3676 double theta = (!matrix[0] && !matrix[3]) || (!matrix[1] && !matrix[4]) ? 0 :
3677 atan2( s*matrix[1] / hypot(s*matrix[1], s*matrix[4]),
3678 s*matrix[0] / hypot(s*matrix[0], s*matrix[3])) * 180/M_PI;
3682 int FFVideoStream::flip(double theta)
3686 Preferences *preferences = ffmpeg->ff_prefs();
3687 if( !preferences || !preferences->auto_rotate ) return ret;
3688 double tolerance = 1;
3689 if( fabs(theta-0) < tolerance ) return ret;
3690 if( (theta=fmod(theta, 360)) < 0 ) theta += 360;
3691 if( fabs(theta-90) < tolerance ) {
3692 if( (ret = insert_filter("transpose", "clock")) < 0 )
3696 else if( fabs(theta-180) < tolerance ) {
3697 if( (ret=insert_filter("hflip", 0)) < 0 )
3699 if( (ret=insert_filter("vflip", 0)) < 0 )
3702 else if (fabs(theta-270) < tolerance ) {
3703 if( (ret=insert_filter("transpose", "cclock")) < 0 )
3708 char angle[BCSTRLEN];
3709 sprintf(angle, "%f", theta*M_PI/180.);
3710 if( (ret=insert_filter("rotate", angle)) < 0 )
3716 int FFVideoStream::create_filter(const char *filter_spec)
3718 double theta = get_rotation_angle();
3719 if( !theta && !filter_spec )
3721 avfilter_register_all();
3723 const char *sp = filter_spec;
3724 char filter_name[BCSTRLEN], *np = filter_name;
3725 int i = sizeof(filter_name);
3726 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
3728 const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
3729 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_VIDEO ) {
3730 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
3734 AVCodecParameters *avpar = st->codecpar;
3735 int sa_num = avpar->sample_aspect_ratio.num;
3736 if( !sa_num ) sa_num = 1;
3737 int sa_den = avpar->sample_aspect_ratio.den;
3738 if( !sa_den ) sa_num = 1;
3740 int ret = 0; char args[BCTEXTLEN];
3741 AVPixelFormat pix_fmt = (AVPixelFormat)avpar->format;
3742 snprintf(args, sizeof(args),
3743 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
3744 avpar->width, avpar->height, (int)pix_fmt,
3745 st->time_base.num, st->time_base.den, sa_num, sa_den);
3748 ret = insert_filter("buffer", args, "in");
3749 buffersrc_ctx = filt_ctx;
3753 AVFilterContext *fsrc = filt_ctx;
3756 ret = insert_filter("buffersink", 0, "out");
3757 buffersink_ctx = filt_ctx;
3760 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
3761 (uint8_t*)&pix_fmt, sizeof(pix_fmt),
3762 AV_OPT_SEARCH_CHILDREN);
3765 ret = config_filters(filter_spec, fsrc);
3767 ff_err(ret, "FFVideoStream::create_filter");
3768 return ret >= 0 ? 0 : -1;
3771 int FFAudioStream::create_filter(const char *filter_spec)
3775 avfilter_register_all();
3777 const char *sp = filter_spec;
3778 char filter_name[BCSTRLEN], *np = filter_name;
3779 int i = sizeof(filter_name);
3780 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
3782 const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
3783 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_AUDIO ) {
3784 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
3788 int ret = 0; char args[BCTEXTLEN];
3789 AVCodecParameters *avpar = st->codecpar;
3790 AVSampleFormat sample_fmt = (AVSampleFormat)avpar->format;
3791 snprintf(args, sizeof(args),
3792 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
3793 st->time_base.num, st->time_base.den, avpar->sample_rate,
3794 av_get_sample_fmt_name(sample_fmt), avpar->channel_layout);
3797 ret = insert_filter("abuffer", args, "in");
3798 buffersrc_ctx = filt_ctx;
3800 AVFilterContext *fsrc = filt_ctx;
3803 ret = insert_filter("abuffersink", 0, "out");
3804 buffersink_ctx = filt_ctx;
3807 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
3808 (uint8_t*)&sample_fmt, sizeof(sample_fmt),
3809 AV_OPT_SEARCH_CHILDREN);
3811 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
3812 (uint8_t*)&avpar->channel_layout,
3813 sizeof(avpar->channel_layout), AV_OPT_SEARCH_CHILDREN);
3815 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
3816 (uint8_t*)&sample_rate, sizeof(sample_rate),
3817 AV_OPT_SEARCH_CHILDREN);
3819 ret = config_filters(filter_spec, fsrc);
3821 ff_err(ret, "FFAudioStream::create_filter");
3822 return ret >= 0 ? 0 : -1;
3825 int FFStream::insert_filter(const char *name, const char *arg, const char *inst_name)
3827 const AVFilter *filter = avfilter_get_by_name(name);
3828 if( !filter ) return -1;
3829 char filt_inst[BCSTRLEN];
3831 snprintf(filt_inst, sizeof(filt_inst), "%s_%d", name, ++filt_id);
3832 inst_name = filt_inst;
3835 filter_graph = avfilter_graph_alloc();
3836 AVFilterContext *fctx = 0;
3837 int ret = avfilter_graph_create_filter(&fctx,
3838 filter, inst_name, arg, NULL, filter_graph);
3839 if( ret >= 0 && filt_ctx )
3840 ret = avfilter_link(filt_ctx, 0, fctx, 0);
3844 avfilter_free(fctx);
3848 int FFStream::config_filters(const char *filter_spec, AVFilterContext *fsrc)
3851 AVFilterContext *fsink = buffersink_ctx;
3853 /* Endpoints for the filter graph. */
3854 AVFilterInOut *outputs = avfilter_inout_alloc();
3855 AVFilterInOut *inputs = avfilter_inout_alloc();
3856 if( !inputs || !outputs ) ret = -1;
3858 outputs->filter_ctx = fsrc;
3859 outputs->pad_idx = 0;
3861 if( !(outputs->name = av_strdup(fsrc->name)) ) ret = -1;
3864 inputs->filter_ctx = fsink;
3865 inputs->pad_idx = 0;
3867 if( !(inputs->name = av_strdup(fsink->name)) ) ret = -1;
3870 int len = strlen(fsrc->name)+2 + strlen(filter_spec) + 1;
3871 char spec[len]; sprintf(spec, "[%s]%s", fsrc->name, filter_spec);
3872 ret = avfilter_graph_parse_ptr(filter_graph, spec,
3873 &inputs, &outputs, NULL);
3875 avfilter_inout_free(&inputs);
3876 avfilter_inout_free(&outputs);
3879 ret = avfilter_link(fsrc, 0, fsink, 0);
3881 ret = avfilter_graph_config(filter_graph, NULL);
3883 ff_err(ret, "FFStream::create_filter");
3884 avfilter_graph_free(&filter_graph);
3891 AVCodecContext *FFMPEG::activate_decoder(AVStream *st)
3893 AVDictionary *copts = 0;
3894 av_dict_copy(&copts, opts, 0);
3895 AVCodecID codec_id = st->codecpar->codec_id;
3896 AVCodec *decoder = 0;
3897 switch( st->codecpar->codec_type ) {
3898 case AVMEDIA_TYPE_VIDEO:
3899 if( opt_video_decoder )
3900 decoder = avcodec_find_decoder_by_name(opt_video_decoder);
3902 video_codec_remaps.update(codec_id, decoder);
3904 case AVMEDIA_TYPE_AUDIO:
3905 if( opt_audio_decoder )
3906 decoder = avcodec_find_decoder_by_name(opt_audio_decoder);
3908 audio_codec_remaps.update(codec_id, decoder);
3913 if( !decoder && !(decoder = avcodec_find_decoder(codec_id)) ) {
3914 eprintf(_("cant find decoder codec %d\n"), (int)codec_id);
3917 AVCodecContext *avctx = avcodec_alloc_context3(decoder);
3919 eprintf(_("cant allocate codec context\n"));
3922 avcodec_parameters_to_context(avctx, st->codecpar);
3923 if( !av_dict_get(copts, "threads", NULL, 0) )
3924 avctx->thread_count = ff_cpus();
3925 int ret = avcodec_open2(avctx, decoder, &copts);
3926 av_dict_free(&copts);
3928 avcodec_free_context(&avctx);
3934 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
3937 av_init_packet(&pkt);
3938 AVFrame *frame = av_frame_alloc();
3940 fprintf(stderr,"FFMPEG::scan: ");
3941 fprintf(stderr,_("av_frame_alloc failed\n"));
3942 fprintf(stderr,"FFMPEG::scan:file=%s\n", file_base->asset->path);
3946 index_state->add_video_markers(ffvideo.size());
3947 index_state->add_audio_markers(ffaudio.size());
3949 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
3950 AVStream *st = fmt_ctx->streams[i];
3951 AVCodecContext *avctx = activate_decoder(st);
3953 AVCodecParameters *avpar = st->codecpar;
3954 switch( avpar->codec_type ) {
3955 case AVMEDIA_TYPE_VIDEO: {
3956 int vidx = ffvideo.size();
3957 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
3958 if( vidx < 0 ) break;
3959 ffvideo[vidx]->avctx = avctx;
3961 case AVMEDIA_TYPE_AUDIO: {
3962 int aidx = ffaudio.size();
3963 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3964 if( aidx < 0 ) break;
3965 ffaudio[aidx]->avctx = avctx;
3970 fprintf(stderr,"FFMPEG::scan: ");
3971 fprintf(stderr,_("codec open failed\n"));
3972 fprintf(stderr,"FFMPEG::scan:file=%s\n", file_base->asset->path);
3973 avcodec_free_context(&avctx);
3977 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
3978 AVStream *st = fmt_ctx->streams[i];
3979 AVCodecParameters *avpar = st->codecpar;
3980 if( avpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
3981 int64_t tstmp = st->start_time;
3982 if( tstmp == AV_NOPTS_VALUE ) continue;
3983 int aidx = ffaudio.size();
3984 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3985 if( aidx < 0 ) continue;
3986 FFAudioStream *aud = ffaudio[aidx];
3987 tstmp -= aud->nudge;
3988 double secs = to_secs(tstmp, st->time_base);
3989 aud->curr_pos = secs * aud->sample_rate + 0.5;
3993 for( int64_t count=0; !*canceled; ++count ) {
3994 av_packet_unref(&pkt);
3995 pkt.data = 0; pkt.size = 0;
3997 int ret = av_read_frame(fmt_ctx, &pkt);
3999 if( ret == AVERROR_EOF ) break;
4000 if( ++errs > 100 ) {
4001 ff_err(ret,_("over 100 read_frame errs\n"));
4006 if( !pkt.data ) continue;
4007 int i = pkt.stream_index;
4008 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
4009 AVStream *st = fmt_ctx->streams[i];
4010 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
4012 AVCodecParameters *avpar = st->codecpar;
4013 switch( avpar->codec_type ) {
4014 case AVMEDIA_TYPE_VIDEO: {
4015 int vidx = ffvideo.size();
4016 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
4017 if( vidx < 0 ) break;
4018 FFVideoStream *vid = ffvideo[vidx];
4019 if( !vid->avctx ) break;
4020 int64_t tstmp = pkt.pts;
4021 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
4022 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
4023 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
4024 double secs = to_secs(tstmp, st->time_base);
4025 int64_t frm = secs * vid->frame_rate + 0.5;
4026 if( frm < 0 ) frm = 0;
4027 index_state->put_video_mark(vidx, frm, pkt.pos);
4030 ret = avcodec_send_packet(vid->avctx, pkt);
4031 if( ret < 0 ) break;
4032 while( (ret=vid->decode_frame(frame)) > 0 ) {}
4035 case AVMEDIA_TYPE_AUDIO: {
4036 int aidx = ffaudio.size();
4037 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
4038 if( aidx < 0 ) break;
4039 FFAudioStream *aud = ffaudio[aidx];
4040 if( !aud->avctx ) break;
4041 int64_t tstmp = pkt.pts;
4042 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
4043 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
4044 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
4045 double secs = to_secs(tstmp, st->time_base);
4046 int64_t sample = secs * aud->sample_rate + 0.5;
4048 index_state->put_audio_mark(aidx, sample, pkt.pos);
4050 ret = avcodec_send_packet(aud->avctx, &pkt);
4051 if( ret < 0 ) break;
4052 int ch = aud->channel0, nch = aud->channels;
4053 int64_t pos = index_state->pos(ch);
4054 if( pos != aud->curr_pos ) {
4055 if( abs(pos-aud->curr_pos) > 1 )
4056 printf("audio%d pad %jd %jd (%jd)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
4057 index_state->pad_data(ch, nch, aud->curr_pos);
4059 while( (ret=aud->decode_frame(frame)) > 0 ) {
4060 //if( frame->channels != nch ) break;
4061 aud->init_swr(frame->channels, frame->format, frame->sample_rate);
4063 int len = aud->get_samples(samples,
4064 &frame->extended_data[0], frame->nb_samples);
4065 pos = aud->curr_pos;
4066 if( (aud->curr_pos += len) >= 0 ) {
4068 samples += -pos * nch;
4069 len = aud->curr_pos;
4071 for( int i=0; i<nch; ++i )
4072 index_state->put_data(ch+i,nch,samples+i,len);
4079 av_frame_free(&frame);
4083 void FFStream::load_markers(IndexMarks &marks, double rate)
4086 int64_t sz = marks.size();
4087 int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
4088 int nb_ent = st->nb_index_entries;
4089 // some formats already have an index
4091 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
4092 int64_t tstmp = ep->timestamp;
4093 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
4094 double secs = ffmpeg->to_secs(tstmp, st->time_base);
4095 int64_t no = secs * rate;
4096 while( in < sz && marks[in].no <= no ) ++in;
4098 int64_t len = sz - in;
4099 int64_t count = max_entries - nb_ent;
4100 if( count > len ) count = len;
4101 for( int i=0; i<count; ++i ) {
4102 int k = in + i * len / count;
4103 int64_t no = marks[k].no, pos = marks[k].pos;
4104 double secs = (double)no / rate;
4105 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
4106 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
4107 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);
4113 * 1) if the format context has a timecode
4114 * return fmt_ctx->timecode - 0
4115 * 2) if the layer/channel has a timecode
4116 * return st->timecode - (start_time-nudge)
4117 * 3) find the 1st program with stream, find 1st program video stream,
4118 * if video stream has a timecode, return st->timecode - (start_time-nudge)
4119 * 4) find timecode in any stream, return st->timecode
4120 * 5) read 100 packets, save ofs=pkt.pts*st->time_base - st->nudge:
4121 * decode frame for video stream of 1st program
4122 * if frame->timecode has a timecode, return frame->timecode - ofs
4123 * if side_data has gop timecode, return gop->timecode - ofs
4124 * if side_data has smpte timecode, return smpte->timecode - ofs
4125 * 6) if the filename/url scans *date_time.ext, return date_time
4126 * 7) if stat works on the filename/url, return mtime
4127 * 8) return -1 failure
4129 double FFMPEG::get_initial_timecode(int data_type, int channel, double frame_rate)
4131 AVRational rate = check_frame_rate(0, frame_rate);
4132 if( !rate.num ) return -1;
4133 // format context timecode
4134 AVDictionaryEntry *tc = av_dict_get(fmt_ctx->metadata, "timecode", 0, 0);
4135 if( tc ) return ff_get_timecode(tc->value, rate, 0);
4137 if( open_decoder() ) return -1;
4140 int codec_type = -1, fidx = -1;
4141 switch( data_type ) {
4143 codec_type = AVMEDIA_TYPE_AUDIO;
4144 int aidx = astrm_index[channel].st_idx;
4145 FFAudioStream *aud = ffaudio[aidx];
4149 AVDictionaryEntry *tref = av_dict_get(fmt_ctx->metadata, "time_reference", 0, 0);
4150 if( tref && aud && aud->sample_rate )
4151 return strtod(tref->value, 0) / aud->sample_rate;
4154 codec_type = AVMEDIA_TYPE_VIDEO;
4155 int vidx = vstrm_index[channel].st_idx;
4156 FFVideoStream *vid = ffvideo[vidx];
4162 if( codec_type < 0 ) return -1;
4164 tc = av_dict_get(st->metadata, "timecode", 0, 0);
4167 // find first program which references this stream
4169 for( int i=0, m=fmt_ctx->nb_programs; pidx<0 && i<m; ++i ) {
4170 AVProgram *pgrm = fmt_ctx->programs[i];
4171 for( int j=0, n=pgrm->nb_stream_indexes; j<n; ++j ) {
4172 int st_idx = pgrm->stream_index[j];
4173 if( st_idx == fidx ) { pidx = i; break; }
4178 AVProgram *pgrm = fmt_ctx->programs[pidx];
4179 for( int j=0, n=pgrm->nb_stream_indexes; j<n; ++j ) {
4180 int st_idx = pgrm->stream_index[j];
4181 AVStream *tst = fmt_ctx->streams[st_idx];
4182 if( !tst ) continue;
4183 if( tst->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
4184 st = tst; fidx = st_idx;
4190 for( int i=0, n=fmt_ctx->nb_streams; i<n; ++i ) {
4191 AVStream *tst = fmt_ctx->streams[i];
4192 if( !tst ) continue;
4193 if( tst->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
4200 tc = av_dict_get(st->metadata, "timecode", 0, 0);
4204 // any timecode, includes -data- streams
4205 for( int i=0, n=fmt_ctx->nb_streams; i<n; ++i ) {
4206 AVStream *tst = fmt_ctx->streams[i];
4207 if( !tst ) continue;
4208 if( (tc = av_dict_get(tst->metadata, "timecode", 0, 0)) ) {
4215 if( st && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
4216 if( st->r_frame_rate.num && st->r_frame_rate.den )
4217 rate = st->r_frame_rate;
4218 nudge = st->start_time;
4219 for( int i=0; i<ffvideo.size(); ++i ) {
4220 if( ffvideo[i]->st == st ) {
4221 nudge = ffvideo[i]->nudge;
4227 if( tc ) { // return timecode
4228 double secs = st->start_time == AV_NOPTS_VALUE ? 0 :
4229 to_secs(st->start_time - nudge, st->time_base);
4230 return ff_get_timecode(tc->value, rate, secs);
4233 if( !st || fidx < 0 ) return -1;
4236 AVCodecContext *av_ctx = activate_decoder(st);
4238 fprintf(stderr,"activate_decoder failed\n");
4241 avCodecContext avctx(av_ctx); // auto deletes
4242 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO &&
4243 avctx->framerate.num && avctx->framerate.den )
4244 rate = avctx->framerate;
4246 avPacket pkt; // auto deletes
4247 avFrame frame; // auto deletes
4249 fprintf(stderr,"av_frame_alloc failed\n");
4253 int64_t max_packets = 100;
4254 char tcbuf[AV_TIMECODE_STR_SIZE];
4256 for( int64_t count=0; count<max_packets; ++count ) {
4257 av_packet_unref(pkt);
4258 pkt->data = 0; pkt->size = 0;
4260 int ret = av_read_frame(fmt_ctx, pkt);
4262 if( ret == AVERROR_EOF ) break;
4263 if( ++errs > 100 ) {
4264 fprintf(stderr,"over 100 read_frame errs\n");
4269 if( !pkt->data ) continue;
4270 int i = pkt->stream_index;
4271 if( i != fidx ) continue;
4272 int64_t tstmp = pkt->pts;
4273 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt->dts;
4274 double secs = to_secs(tstmp - nudge, st->time_base);
4275 ret = avcodec_send_packet(avctx, pkt);
4276 if( ret < 0 ) return -1;
4278 while( (ret = avcodec_receive_frame(avctx, frame)) >= 0 ) {
4279 if( (tc = av_dict_get(frame->metadata, "timecode", 0, 0)) )
4280 return ff_get_timecode(tc->value, rate, secs);
4281 int k = frame->nb_side_data;
4282 AVFrameSideData *side_data = 0;
4284 side_data = frame->side_data[k];
4285 switch( side_data->type ) {
4286 case AV_FRAME_DATA_GOP_TIMECODE: {
4287 int64_t data = *(int64_t *)side_data->data;
4288 int sz = sizeof(data);
4289 if( side_data->size >= sz ) {
4290 av_timecode_make_mpeg_tc_string(tcbuf, data);
4291 return ff_get_timecode(tcbuf, rate, secs);
4294 case AV_FRAME_DATA_S12M_TIMECODE: {
4295 uint32_t *data = (uint32_t *)side_data->data;
4296 int n = data[0], sz = (n+1)*sizeof(*data);
4297 if( side_data->size >= sz ) {
4298 av_timecode_make_smpte_tc_string(tcbuf, data[n], 0);
4299 return ff_get_timecode(tcbuf, rate, secs);
4308 char *path = fmt_ctx->url;
4309 char *bp = strrchr(path, '/');
4310 if( !bp ) bp = path; else ++bp;
4311 char *cp = strrchr(bp, '.');
4312 if( cp && (cp-=(8+1+6)) >= bp ) {
4314 int year,mon,day, hour,min,sec, frm=0;
4315 if( sscanf(cp,"%4d%2d%2d%[_-]%2d%2d%2d",
4316 &year,&mon,&day, sep, &hour,&min,&sec) == 7 ) {
4318 // year>=1970,mon=1..12,day=1..31, hour=0..23,min=0..59,sec=0..60
4319 if( (ch=='_' || ch=='-' ) &&
4320 year >= 1970 && mon>=1 && mon<=12 && day>=1 && day<=31 &&
4321 hour>=0 && hour<24 && min>=0 && min<60 && sec>=0 && sec<=60 ) {
4322 sprintf(tcbuf,"%d:%02d:%02d:%02d", hour,min,sec, frm);
4323 return ff_get_timecode(tcbuf, rate, 0);
4328 if( stat(path, &tst) >= 0 ) {
4329 time_t t = (time_t)tst.st_mtim.tv_sec;
4331 localtime_r(&t, &tm);
4332 int64_t us = tst.st_mtim.tv_nsec / 1000;
4333 int frm = us/1000000. * frame_rate;
4334 sprintf(tcbuf,"%d:%02d:%02d:%02d", tm.tm_hour, tm.tm_min, tm.tm_sec, frm);
4335 return ff_get_timecode(tcbuf, rate, 0);
4340 double FFMPEG::ff_get_timecode(char *str, AVRational rate, double pos)
4343 if( av_timecode_init_from_string(&tc, rate, str, fmt_ctx) )
4345 double secs = (double)tc.start / tc.fps - pos;
4346 if( secs < 0 ) secs = 0;
4350 double FFMPEG::get_timecode(const char *path, int data_type, int channel, double rate)
4353 if( ffmpeg.init_decoder(path) ) return -1;
4354 return ffmpeg.get_initial_timecode(data_type, channel, rate);