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");
269 nudge = AV_NOPTS_VALUE;
270 seek_pos = curr_pos = 0;
272 reading = writing = 0;
273 hw_pixfmt = AV_PIX_FMT_NONE;
286 FFStream::~FFStream()
288 frm_lock->lock("FFStream::~FFStream");
289 if( reading > 0 || writing > 0 ) avcodec_close(avctx);
290 if( avctx ) avcodec_free_context(&avctx);
291 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
292 if( hw_device_ctx ) av_buffer_unref(&hw_device_ctx);
293 if( bsfc ) av_bsf_free(&bsfc);
294 while( frms.first ) frms.remove(frms.first);
295 if( filter_graph ) avfilter_graph_free(&filter_graph);
296 if( frame ) av_frame_free(&frame);
297 if( fframe ) av_frame_free(&fframe);
298 if( probe_frame ) av_frame_free(&probe_frame);
301 if( stats_fp ) fclose(stats_fp);
302 if( stats_in ) av_freep(&stats_in);
303 delete [] stats_filename;
306 void FFStream::ff_lock(const char *cp)
308 FFMPEG::fflock.lock(cp);
311 void FFStream::ff_unlock()
313 FFMPEG::fflock.unlock();
316 void FFStream::queue(FFrame *frm)
318 frm_lock->lock("FFStream::queue");
322 ffmpeg->mux_lock->unlock();
325 void FFStream::dequeue(FFrame *frm)
327 frm_lock->lock("FFStream::dequeue");
329 frms.remove_pointer(frm);
333 int FFStream::encode_activate()
336 writing = ffmpeg->encode_activate();
340 // this is a global parameter that really should be in the context
341 static AVPixelFormat hw_pix_fmt = AV_PIX_FMT_NONE; // protected by ff_lock
343 // goofy maneuver to attach a hw_format to an av_context
344 #define GET_HW_PIXFMT(fn, fmt) \
345 static AVPixelFormat get_hw_##fn(AVCodecContext *ctx, const enum AVPixelFormat *pix_fmts) { \
348 GET_HW_PIXFMT(vaapi, AV_PIX_FMT_VAAPI)
349 GET_HW_PIXFMT(vdpau, AV_PIX_FMT_VDPAU)
350 GET_HW_PIXFMT(cuda, AV_PIX_FMT_CUDA)
351 GET_HW_PIXFMT(nv12, AV_PIX_FMT_NV12)
353 static enum AVPixelFormat get_hw_format(AVCodecContext *ctx,
354 const enum AVPixelFormat *pix_fmts)
356 for( const enum AVPixelFormat *p=pix_fmts; *p!=AV_PIX_FMT_NONE; ++p ) {
357 if( *p != hw_pix_fmt ) continue;
359 case AV_PIX_FMT_VAAPI: ctx->get_format = get_hw_vaapi; return *p;
360 case AV_PIX_FMT_VDPAU: ctx->get_format = get_hw_vdpau; return *p;
361 case AV_PIX_FMT_CUDA: ctx->get_format = get_hw_cuda; return *p;
362 case AV_PIX_FMT_NV12: ctx->get_format = get_hw_nv12; return *p;
364 fprintf(stderr, "Unknown HW surface format: %s\n",
365 av_get_pix_fmt_name(*p));
369 fprintf(stderr, "Failed to get HW surface format.\n");
370 return hw_pix_fmt = AV_PIX_FMT_NONE;
374 AVHWDeviceType FFStream::decode_hw_activate()
376 return AV_HWDEVICE_TYPE_NONE;
379 int FFStream::decode_hw_format(AVCodec *decoder, AVHWDeviceType type)
384 int FFStream::decode_activate()
386 if( reading < 0 && (reading=ffmpeg->decode_activate()) > 0 ) {
387 ff_lock("FFStream::decode_activate");
389 AVDictionary *copts = 0;
390 av_dict_copy(&copts, ffmpeg->opts, 0);
392 AVHWDeviceType hw_type = decode_hw_activate();
394 // this should be avformat_copy_context(), but no copy avail
395 ret = avformat_open_input(&fmt_ctx,
396 ffmpeg->fmt_ctx->url, ffmpeg->fmt_ctx->iformat, &copts);
398 ret = avformat_find_stream_info(fmt_ctx, 0);
399 st = fmt_ctx->streams[fidx];
402 while( ret >= 0 && st != 0 && !reading ) {
403 AVCodecID codec_id = st->codecpar->codec_id;
404 AVCodec *decoder = 0;
406 if( ffmpeg->opt_video_decoder )
407 decoder = avcodec_find_decoder_by_name(ffmpeg->opt_video_decoder);
409 ffmpeg->video_codec_remaps.update(codec_id, decoder);
411 else if( is_audio() ) {
412 if( ffmpeg->opt_audio_decoder )
413 decoder = avcodec_find_decoder_by_name(ffmpeg->opt_audio_decoder);
415 ffmpeg->audio_codec_remaps.update(codec_id, decoder);
418 decoder = avcodec_find_decoder(codec_id);
419 avctx = avcodec_alloc_context3(decoder);
421 eprintf(_("cant allocate codec context\n"));
422 ret = AVERROR(ENOMEM);
424 if( ret >= 0 && hw_type != AV_HWDEVICE_TYPE_NONE ) {
425 ret = decode_hw_format(decoder, hw_type);
428 avcodec_parameters_to_context(avctx, st->codecpar);
429 if( !av_dict_get(copts, "threads", NULL, 0) )
430 avctx->thread_count = ffmpeg->ff_cpus();
431 ret = avcodec_open2(avctx, decoder, &copts);
433 AVFrame *hw_frame = 0;
434 if( ret >= 0 && hw_type != AV_HWDEVICE_TYPE_NONE ) {
435 if( !(hw_frame=av_frame_alloc()) ) {
436 fprintf(stderr, "FFStream::decode_activate: av_frame_alloc failed\n");
437 ret = AVERROR(ENOMEM);
440 ret = decode(hw_frame);
442 if( ret < 0 && hw_type != AV_HWDEVICE_TYPE_NONE ) {
443 ff_err(ret, "HW device init failed, using SW decode.\nfile:%s\n",
444 ffmpeg->fmt_ctx->url);
445 avcodec_close(avctx);
446 avcodec_free_context(&avctx);
447 av_buffer_unref(&hw_device_ctx);
449 av_frame_free(&hw_frame);
450 hw_type = AV_HWDEVICE_TYPE_NONE;
451 int flags = AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_ANY;
453 av_seek_frame(fmt_ctx, idx, 0, flags);
454 need_packet = 1; flushed = 0;
455 seeked = 1; st_eof(0);
459 probe_frame = hw_frame;
463 eprintf(_("open decoder failed\n"));
466 eprintf(_("can't open input file: %s\n"), ffmpeg->fmt_ctx->url);
467 av_dict_free(&copts);
473 int FFStream::read_packet()
475 av_packet_unref(ipkt);
476 int ret = av_read_frame(fmt_ctx, ipkt);
479 if( ret == AVERROR_EOF ) return 0;
480 ff_err(ret, "FFStream::read_packet: av_read_frame failed\n");
487 int FFStream::decode(AVFrame *frame)
489 if( probe_frame ) { // hw probe reads first frame
490 av_frame_ref(frame, probe_frame);
491 av_frame_free(&probe_frame);
495 int retries = MAX_RETRY;
496 frm_lock->lock("FFStream::decode");
497 while( ret >= 0 && !flushed && --retries >= 0 ) {
499 if( (ret=read_packet()) < 0 ) break;
500 AVPacket *pkt = ret > 0 ? (AVPacket*)ipkt : 0;
502 if( pkt->stream_index != st->index ) continue;
503 if( !pkt->data || !pkt->size ) continue;
505 if( (ret=avcodec_send_packet(avctx, pkt)) < 0 ) {
506 ff_err(ret, "FFStream::decode: avcodec_send_packet failed.\nfile:%s\n",
507 ffmpeg->fmt_ctx->url);
513 if( (ret=decode_frame(frame)) > 0 ) break;
522 fprintf(stderr, "FFStream::decode: Retry limit\n");
526 fprintf(stderr, "FFStream::decode: failed\n");
530 int FFStream::load_filter(AVFrame *frame)
532 int ret = av_buffersrc_add_frame_flags(buffersrc_ctx, frame, 0);
534 eprintf(_("av_buffersrc_add_frame_flags failed\n"));
538 int FFStream::read_filter(AVFrame *frame)
540 int ret = av_buffersink_get_frame(buffersink_ctx, frame);
542 if( ret == AVERROR(EAGAIN) ) return 0;
543 if( ret == AVERROR_EOF ) { st_eof(1); return -1; }
544 ff_err(ret, "FFStream::read_filter: av_buffersink_get_frame failed\n");
550 int FFStream::read_frame(AVFrame *frame)
552 av_frame_unref(frame);
553 if( !filter_graph || !buffersrc_ctx || !buffersink_ctx )
554 return decode(frame);
555 if( !fframe && !(fframe=av_frame_alloc()) ) {
556 fprintf(stderr, "FFStream::read_frame: av_frame_alloc failed\n");
560 while( !flushed && !(ret=read_filter(frame)) ) {
561 if( (ret=decode(fframe)) < 0 ) break;
562 if( ret > 0 && (ret=load_filter(fframe)) < 0 ) break;
567 int FFStream::write_packet(FFPacket &pkt)
571 av_packet_rescale_ts(pkt, avctx->time_base, st->time_base);
572 pkt->stream_index = st->index;
573 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, pkt);
576 ret = av_bsf_send_packet(bsfc, pkt);
579 if( (ret=av_bsf_receive_packet(bsfc, bs)) < 0 ) {
580 if( ret == AVERROR(EAGAIN) ) return 0;
581 if( ret == AVERROR_EOF ) return -1;
584 av_packet_rescale_ts(bs, avctx->time_base, st->time_base);
585 bs->stream_index = st->index;
586 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, bs);
590 ff_err(ret, "FFStream::write_packet: write packet failed.\nfile:%s\n",
591 ffmpeg->fmt_ctx->url);
595 int FFStream::encode_frame(AVFrame *frame)
597 int pkts = 0, ret = 0;
598 for( int retry=MAX_RETRY; --retry>=0; ) {
600 ret = avcodec_send_frame(avctx, frame);
601 if( !ret && frame ) return pkts;
602 if( ret < 0 && ret != AVERROR(EAGAIN) ) break;
604 ret = avcodec_receive_packet(avctx, opkt);
605 if( !frame && ret == AVERROR_EOF ) return pkts;
607 ret = write_packet(opkt);
610 if( frame && stats_fp ) {
611 ret = write_stats_file();
615 ff_err(ret, "FFStream::encode_frame: encode failed.\nfile: %s\n",
616 ffmpeg->fmt_ctx->url);
620 int FFStream::flush()
624 int ret = encode_frame(0);
625 if( ret >= 0 && stats_fp ) {
626 ret = write_stats_file();
630 ff_err(ret, "FFStream::flush failed\n:file:%s\n",
631 ffmpeg->fmt_ctx->url);
632 return ret >= 0 ? 0 : 1;
636 int FFStream::open_stats_file()
638 stats_fp = fopen(stats_filename,"w");
639 return stats_fp ? 0 : AVERROR(errno);
642 int FFStream::close_stats_file()
645 fclose(stats_fp); stats_fp = 0;
650 int FFStream::read_stats_file()
652 int64_t len = 0; struct stat stats_st;
653 int fd = open(stats_filename, O_RDONLY);
654 int ret = fd >= 0 ? 0: ENOENT;
655 if( !ret && fstat(fd, &stats_st) )
658 len = stats_st.st_size;
659 stats_in = (char *)av_malloc(len+1);
663 if( !ret && read(fd, stats_in, len+1) != len )
667 avctx->stats_in = stats_in;
671 return !ret ? 0 : AVERROR(ret);
674 int FFStream::write_stats_file()
677 if( avctx->stats_out && (ret=strlen(avctx->stats_out)) > 0 ) {
678 int len = fwrite(avctx->stats_out, 1, ret, stats_fp);
680 ff_err(ret = AVERROR(errno), "FFStream::write_stats_file.\n%file:%s\n",
681 ffmpeg->fmt_ctx->url);
686 int FFStream::init_stats_file()
689 if( (pass & 2) && (ret = read_stats_file()) < 0 )
690 ff_err(ret, "stat file read: %s", stats_filename);
691 if( (pass & 1) && (ret=open_stats_file()) < 0 )
692 ff_err(ret, "stat file open: %s", stats_filename);
693 return ret >= 0 ? 0 : ret;
696 int FFStream::seek(int64_t no, double rate)
698 // default ffmpeg native seek
700 int64_t pos = no, pkt_pos = -1;
701 IndexMarks *index_markers = get_markers();
702 if( index_markers && index_markers->size() > 1 ) {
703 IndexMarks &marks = *index_markers;
704 int i = marks.find(pos);
705 int64_t n = i < 0 ? (i=0) : marks[i].no;
706 // if indexed seek point not too far away (<30 secs), use index
707 if( no-n < 30*rate ) {
710 if( i < marks.size() ) pkt_pos = marks[i].pos;
714 if( pos == curr_pos ) return 0;
715 double secs = pos < 0 ? 0. : pos / rate;
716 AVRational time_base = st->time_base;
717 int64_t tstmp = time_base.num > 0 ? secs * time_base.den/time_base.num : 0;
719 if( st->nb_index_entries > 0 ) tstmp = st->index_entries[0].timestamp;
720 else if( st->start_time != AV_NOPTS_VALUE ) tstmp = st->start_time;
721 else if( st->first_dts != AV_NOPTS_VALUE ) tstmp = st->first_dts;
722 else tstmp = INT64_MIN+1;
724 else if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
727 // seek all streams using the default timebase.
728 // this is how ffmpeg and ffplay work. stream seeks are less tested.
729 tstmp = av_rescale_q(tstmp, time_base, AV_TIME_BASE_Q);
732 frm_lock->lock("FFStream::seek");
733 av_frame_free(&probe_frame);
734 avcodec_flush_buffers(avctx);
735 avformat_flush(fmt_ctx);
737 int64_t seek = tstmp;
738 int flags = AVSEEK_FLAG_ANY;
739 if( !(fmt_ctx->iformat->flags & AVFMT_NO_BYTE_SEEK) && pkt_pos >= 0 ) {
741 flags = AVSEEK_FLAG_BYTE;
743 int ret = avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, seek, INT64_MAX, flags);
745 // finds the first index frame below the target time
746 int flags = AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_ANY;
747 int ret = av_seek_frame(fmt_ctx, idx, tstmp, flags);
749 int retry = MAX_RETRY;
751 need_packet = 0; flushed = 0;
752 seeked = 1; st_eof(0);
753 // read up to retry packets, limited to npkts in stream, and not pkt.pos past pkt_pos
754 while( --retry >= 0 ) {
755 if( read_packet() <= 0 ) { ret = -1; break; }
756 if( ipkt->stream_index != st->index ) continue;
757 if( !ipkt->data || !ipkt->size ) continue;
758 if( pkt_pos >= 0 && ipkt->pos >= pkt_pos ) break;
759 if( --npkts <= 0 ) break;
760 int64_t pkt_ts = ipkt->dts != AV_NOPTS_VALUE ? ipkt->dts : ipkt->pts;
761 if( pkt_ts == AV_NOPTS_VALUE ) continue;
762 if( pkt_ts >= tstmp ) break;
765 ff_err(AVERROR(EIO), "FFStream::seek: %s\n"
766 " retry limit, pos=%jd tstmp=%jd, ",
767 ffmpeg->fmt_ctx->url, pos, tstmp);
771 ret = avcodec_send_packet(avctx, ipkt);
773 //some codecs need more than one pkt to resync
774 if( ret == AVERROR_INVALIDDATA ) ret = 0;
776 ff_err(ret, "FFStream::avcodec_send_packet failed.\nseek:%s\n",
777 ffmpeg->fmt_ctx->url);
783 printf("** seek fail %jd, %jd\n", pos, tstmp);
784 seeked = need_packet = 0;
788 //printf("seeked pos = %ld, %ld\n", pos, tstmp);
789 seek_pos = curr_pos = pos;
793 FFAudioStream::FFAudioStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
794 : FFStream(ffmpeg, strm, fidx)
797 channel0 = channels = 0;
800 frame_sz = AUDIO_MIN_FRAME_SZ;
802 resample_context = 0;
803 swr_ichs = swr_ifmt = swr_irate = 0;
812 bfr = new float[bsz];
817 FFAudioStream::~FFAudioStream()
819 if( resample_context ) swr_free(&resample_context);
824 void FFAudioStream::init_swr(int ichs, int ifmt, int irate)
826 if( resample_context ) {
827 if( swr_ichs == ichs && swr_ifmt == ifmt && swr_irate == irate )
829 swr_free(&resample_context);
831 swr_ichs = ichs; swr_ifmt = ifmt; swr_irate = irate;
832 if( ichs == channels && ifmt == AV_SAMPLE_FMT_FLT && irate == sample_rate )
834 uint64_t ilayout = av_get_default_channel_layout(ichs);
835 if( !ilayout ) ilayout = ((uint64_t)1<<ichs) - 1;
836 uint64_t olayout = av_get_default_channel_layout(channels);
837 if( !olayout ) olayout = ((uint64_t)1<<channels) - 1;
838 resample_context = swr_alloc_set_opts(NULL,
839 olayout, AV_SAMPLE_FMT_FLT, sample_rate,
840 ilayout, (AVSampleFormat)ifmt, irate,
842 if( resample_context )
843 swr_init(resample_context);
846 int FFAudioStream::get_samples(float *&samples, uint8_t **data, int len)
848 samples = *(float **)data;
849 if( resample_context ) {
850 if( len > aud_bfr_sz ) {
856 aud_bfr = new float[aud_bfr_sz*channels];
858 int ret = swr_convert(resample_context,
859 (uint8_t**)&aud_bfr, aud_bfr_sz, (const uint8_t**)data, len);
861 ff_err(ret, "FFAudioStream::get_samples: swr_convert failed\n");
870 int FFAudioStream::load_history(uint8_t **data, int len)
873 len = get_samples(samples, data, len);
875 // biggest user bfr since seek + frame
876 realloc(mbsz + len + 1, channels);
882 int FFAudioStream::decode_frame(AVFrame *frame)
884 int first_frame = seeked; seeked = 0;
885 frame->best_effort_timestamp = AV_NOPTS_VALUE;
886 int ret = avcodec_receive_frame(avctx, frame);
888 if( first_frame ) return 0;
889 if( ret == AVERROR(EAGAIN) ) return 0;
890 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
891 ff_err(ret, "FFAudioStream::decode_frame: Could not read audio frame.\nfile:%s\n",
892 ffmpeg->fmt_ctx->url);
895 int64_t pkt_ts = frame->best_effort_timestamp;
896 if( pkt_ts != AV_NOPTS_VALUE ) {
897 double ts = ffmpeg->to_secs(pkt_ts - nudge, st->time_base);
898 double t = (double)curr_pos / sample_rate;
899 // some time_base clocks are very grainy, too grainy for audio (clicks, pops)
900 if( fabs(ts - t) > AUDIO_PTS_TOLERANCE )
901 curr_pos = ts * sample_rate + 0.5;
906 int FFAudioStream::encode_activate()
908 if( writing >= 0 ) return writing;
909 if( !avctx->codec ) return writing = 0;
910 frame_sz = avctx->codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE ?
911 10000 : avctx->frame_size;
912 return FFStream::encode_activate();
915 int64_t FFAudioStream::load_buffer(double ** const sp, int len)
917 reserve(len+1, st->codecpar->channels);
918 for( int ch=0; ch<nch; ++ch )
919 write(sp[ch], len, ch);
923 int FFAudioStream::in_history(int64_t pos)
925 if( pos > curr_pos ) return 0;
927 if( len > sz ) len = sz;
928 if( pos < curr_pos - len ) return 0;
933 int FFAudioStream::init_frame(AVFrame *frame)
935 frame->nb_samples = frame_sz;
936 frame->format = avctx->sample_fmt;
937 frame->channel_layout = avctx->channel_layout;
938 frame->sample_rate = avctx->sample_rate;
939 int ret = av_frame_get_buffer(frame, 0);
941 ff_err(ret, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
945 int FFAudioStream::load(int64_t pos, int len)
947 if( audio_seek(pos) < 0 ) return -1;
948 if( !frame && !(frame=av_frame_alloc()) ) {
949 fprintf(stderr, "FFAudioStream::load: av_frame_alloc failed\n");
952 if( mbsz < len ) mbsz = len;
953 int64_t end_pos = pos + len;
954 int ret = 0, i = len / frame_sz + MAX_RETRY;
955 while( ret>=0 && !flushed && curr_pos<end_pos && --i>=0 ) {
956 ret = read_frame(frame);
957 if( ret > 0 && frame->nb_samples > 0 ) {
958 init_swr(frame->channels, frame->format, frame->sample_rate);
959 load_history(&frame->extended_data[0], frame->nb_samples);
960 curr_pos += frame->nb_samples;
963 if( end_pos > curr_pos ) {
964 zero(end_pos - curr_pos);
967 len = curr_pos - pos;
972 int FFAudioStream::audio_seek(int64_t pos)
974 if( decode_activate() <= 0 ) return -1;
975 if( !st->codecpar ) return -1;
976 if( in_history(pos) ) return 0;
977 if( pos == curr_pos ) return 0;
978 reset_history(); mbsz = 0;
979 // guarentee preload > 1sec samples
980 if( (pos-=sample_rate) < 0 ) pos = 0;
981 if( seek(pos, sample_rate) < 0 ) return -1;
985 int FFAudioStream::encode(double **samples, int len)
987 if( encode_activate() <= 0 ) return -1;
990 int64_t count = samples ? load_buffer(samples, len) : used();
991 int frame_sz1 = samples ? frame_sz-1 : 0;
994 while( ret >= 0 && count > frame_sz1 ) {
995 frm = new FFrame(this);
996 if( (ret=frm->initted()) < 0 ) break;
997 AVFrame *frame = *frm;
998 len = count >= frame_sz ? frame_sz : count;
999 float *bfrp = get_outp(len);
1000 ret = swr_convert(resample_context,
1001 (uint8_t **)frame->extended_data, len,
1002 (const uint8_t **)&bfrp, len);
1004 ff_err(ret, "FFAudioStream::encode: swr_convert failed\n");
1007 frame->nb_samples = len;
1008 frm->queue(curr_pos);
1015 return ret >= 0 ? 0 : 1;
1018 int FFAudioStream::drain()
1023 int FFAudioStream::encode_frame(AVFrame *frame)
1025 return FFStream::encode_frame(frame);
1028 int FFAudioStream::write_packet(FFPacket &pkt)
1030 return FFStream::write_packet(pkt);
1033 void FFAudioStream::load_markers()
1035 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1036 if( !index_state || idx >= index_state->audio_markers.size() ) return;
1037 if( index_state->marker_status == MARKERS_NOTTESTED ) return;
1038 FFStream::load_markers(*index_state->audio_markers[idx], sample_rate);
1041 IndexMarks *FFAudioStream::get_markers()
1043 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1044 if( !index_state || idx >= index_state->audio_markers.size() ) return 0;
1045 return index_state->audio_markers[idx];
1048 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
1049 : FFStream(ffmpeg, strm, fidx),
1050 FFVideoConvert(ffmpeg->ff_prefs())
1059 top_field_first = 0;
1064 FFVideoStream::~FFVideoStream()
1068 AVHWDeviceType FFVideoStream::decode_hw_activate()
1070 AVHWDeviceType type = AV_HWDEVICE_TYPE_NONE;
1071 const char *hw_dev = ffmpeg->opt_hw_dev;
1072 if( !hw_dev ) hw_dev = getenv("CIN_HW_DEV");
1073 if( !hw_dev ) hw_dev = ffmpeg->ff_hw_dev();
1074 if( hw_dev && *hw_dev &&
1075 strcmp("none", hw_dev) && strcmp(_("none"), hw_dev) ) {
1076 type = av_hwdevice_find_type_by_name(hw_dev);
1077 if( type == AV_HWDEVICE_TYPE_NONE ) {
1078 fprintf(stderr, "Device type %s is not supported.\n", hw_dev);
1079 fprintf(stderr, "Available device types:");
1080 while( (type = av_hwdevice_iterate_types(type)) != AV_HWDEVICE_TYPE_NONE )
1081 fprintf(stderr, " %s", av_hwdevice_get_type_name(type));
1082 fprintf(stderr, "\n");
1088 int FFVideoStream::decode_hw_format(AVCodec *decoder, AVHWDeviceType type)
1091 hw_pix_fmt = AV_PIX_FMT_NONE;
1092 for( int i=0; ; ++i ) {
1093 const AVCodecHWConfig *config = avcodec_get_hw_config(decoder, i);
1095 fprintf(stderr, "Decoder %s does not support device type %s.\n",
1096 decoder->name, av_hwdevice_get_type_name(type));
1100 if( (config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX) != 0 &&
1101 config->device_type == type ) {
1102 hw_pix_fmt = config->pix_fmt;
1106 if( hw_pix_fmt >= 0 ) {
1107 hw_pixfmt = hw_pix_fmt;
1108 avctx->get_format = get_hw_format;
1109 ret = av_hwdevice_ctx_create(&hw_device_ctx, type, 0, 0, 0);
1111 avctx->hw_device_ctx = av_buffer_ref(hw_device_ctx);
1115 ff_err(ret, "Failed HW device create.\ndev:%s\n",
1116 av_hwdevice_get_type_name(type));
1123 AVHWDeviceType FFVideoStream::encode_hw_activate(const char *hw_dev)
1125 AVBufferRef *hw_device_ctx = 0;
1126 AVBufferRef *hw_frames_ref = 0;
1127 AVHWDeviceType type = AV_HWDEVICE_TYPE_NONE;
1128 if( strcmp(_("none"), hw_dev) ) {
1129 type = av_hwdevice_find_type_by_name(hw_dev);
1130 if( type != AV_HWDEVICE_TYPE_VAAPI ) {
1131 fprintf(stderr, "currently, only vaapi hw encode is supported\n");
1132 type = AV_HWDEVICE_TYPE_NONE;
1135 if( type != AV_HWDEVICE_TYPE_NONE ) {
1136 int ret = av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_VAAPI, 0, 0, 0);
1138 ff_err(ret, "Failed to create a HW device.\n");
1139 type = AV_HWDEVICE_TYPE_NONE;
1142 if( type != AV_HWDEVICE_TYPE_NONE ) {
1143 hw_frames_ref = av_hwframe_ctx_alloc(hw_device_ctx);
1144 if( !hw_frames_ref ) {
1145 fprintf(stderr, "Failed to create HW frame context.\n");
1146 type = AV_HWDEVICE_TYPE_NONE;
1149 if( type != AV_HWDEVICE_TYPE_NONE ) {
1150 AVHWFramesContext *frames_ctx = (AVHWFramesContext *)(hw_frames_ref->data);
1151 frames_ctx->format = AV_PIX_FMT_VAAPI;
1152 frames_ctx->sw_format = AV_PIX_FMT_NV12;
1153 frames_ctx->width = width;
1154 frames_ctx->height = height;
1155 frames_ctx->initial_pool_size = 0; // 200;
1156 int ret = av_hwframe_ctx_init(hw_frames_ref);
1158 avctx->hw_frames_ctx = av_buffer_ref(hw_frames_ref);
1159 if( !avctx->hw_frames_ctx ) ret = AVERROR(ENOMEM);
1162 ff_err(ret, "Failed to initialize HW frame context.\n");
1163 type = AV_HWDEVICE_TYPE_NONE;
1165 av_buffer_unref(&hw_frames_ref);
1170 int FFVideoStream::encode_hw_write(FFrame *picture)
1173 AVFrame *hw_frm = 0;
1174 switch( avctx->pix_fmt ) {
1175 case AV_PIX_FMT_VAAPI:
1176 hw_frm = av_frame_alloc();
1177 if( !hw_frm ) { ret = AVERROR(ENOMEM); break; }
1178 ret = av_hwframe_get_buffer(avctx->hw_frames_ctx, hw_frm, 0);
1179 if( ret < 0 ) break;
1180 ret = av_hwframe_transfer_data(hw_frm, *picture, 0);
1181 if( ret < 0 ) break;
1182 picture->set_hw_frame(hw_frm);
1187 av_frame_free(&hw_frm);
1188 ff_err(ret, "Error while transferring frame data to GPU.\n");
1192 int FFVideoStream::decode_frame(AVFrame *frame)
1194 int first_frame = seeked; seeked = 0;
1195 int ret = avcodec_receive_frame(avctx, frame);
1197 if( first_frame ) return 0;
1198 if( ret == AVERROR(EAGAIN) ) return 0;
1199 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
1200 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame.\nfile:%s\n,",
1201 ffmpeg->fmt_ctx->url);
1204 int64_t pkt_ts = frame->best_effort_timestamp;
1205 if( pkt_ts != AV_NOPTS_VALUE )
1206 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * frame_rate + 0.5;
1210 int FFVideoStream::load(VFrame *vframe, int64_t pos)
1212 int ret = video_seek(pos);
1213 if( ret < 0 ) return -1;
1214 if( !frame && !(frame=av_frame_alloc()) ) {
1215 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
1218 int i = MAX_RETRY + pos - curr_pos;
1219 while( ret>=0 && !flushed && curr_pos<=pos && --i>=0 ) {
1220 ret = read_frame(frame);
1221 if( ret > 0 ) ++curr_pos;
1223 if( frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0 )
1226 ret = convert_cmodel(vframe, frame);
1228 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
1232 int FFVideoStream::video_seek(int64_t pos)
1234 if( decode_activate() <= 0 ) return -1;
1235 if( !st->codecpar ) return -1;
1236 if( pos == curr_pos-1 && !seeked ) return 0;
1237 // if close enough, just read up to current
1238 int gop = avctx->gop_size;
1239 if( gop < 4 ) gop = 4;
1240 if( gop > 64 ) gop = 64;
1241 int read_limit = curr_pos + 3*gop;
1242 if( pos >= curr_pos && pos <= read_limit ) return 0;
1243 // guarentee preload more than 2*gop frames
1244 if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
1248 int FFVideoStream::init_frame(AVFrame *picture)
1250 switch( avctx->pix_fmt ) {
1251 case AV_PIX_FMT_VAAPI:
1252 picture->format = AV_PIX_FMT_NV12;
1255 picture->format = avctx->pix_fmt;
1258 picture->width = avctx->width;
1259 picture->height = avctx->height;
1260 int ret = av_frame_get_buffer(picture, 32);
1264 int FFVideoStream::encode(VFrame *vframe)
1266 if( encode_activate() <= 0 ) return -1;
1268 FFrame *picture = new FFrame(this);
1269 int ret = picture->initted();
1271 AVFrame *frame = *picture;
1272 frame->pts = curr_pos;
1273 ret = convert_pixfmt(vframe, frame);
1275 if( ret >= 0 && avctx->hw_frames_ctx )
1276 encode_hw_write(picture);
1278 picture->queue(curr_pos);
1282 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
1285 return ret >= 0 ? 0 : 1;
1288 int FFVideoStream::drain()
1293 int FFVideoStream::encode_frame(AVFrame *frame)
1296 frame->interlaced_frame = interlaced;
1297 frame->top_field_first = top_field_first;
1299 if( frame && frame->format == AV_PIX_FMT_VAAPI ) { // ugly
1300 int ret = avcodec_send_frame(avctx, frame);
1301 for( int retry=MAX_RETRY; !ret && --retry>=0; ) {
1302 FFPacket pkt; av_init_packet(pkt);
1303 pkt->data = NULL; pkt->size = 0;
1304 if( (ret=avcodec_receive_packet(avctx, pkt)) < 0 ) {
1305 if( ret == AVERROR(EAGAIN) ) ret = 0; // weird
1308 ret = write_packet(pkt);
1309 pkt->stream_index = 0;
1310 av_packet_unref(pkt);
1313 ff_err(ret, "FFStream::encode_frame: vaapi encode failed.\nfile: %s\n",
1314 ffmpeg->fmt_ctx->url);
1319 return FFStream::encode_frame(frame);
1322 int FFVideoStream::write_packet(FFPacket &pkt)
1324 if( !(ffmpeg->fmt_ctx->oformat->flags & AVFMT_VARIABLE_FPS) )
1326 return FFStream::write_packet(pkt);
1329 AVPixelFormat FFVideoConvert::color_model_to_pix_fmt(int color_model)
1331 switch( color_model ) {
1332 case BC_YUV422: return AV_PIX_FMT_YUYV422;
1333 case BC_RGB888: return AV_PIX_FMT_RGB24;
1334 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
1335 case BC_BGR8888: return AV_PIX_FMT_BGR0;
1336 case BC_BGR888: return AV_PIX_FMT_BGR24;
1337 case BC_ARGB8888: return AV_PIX_FMT_ARGB;
1338 case BC_ABGR8888: return AV_PIX_FMT_ABGR;
1339 case BC_RGB8: return AV_PIX_FMT_RGB8;
1340 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
1341 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
1342 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
1343 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
1344 case BC_RGB565: return AV_PIX_FMT_RGB565;
1345 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
1346 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
1347 case BC_AYUV16161616: return AV_PIX_FMT_AYUV64LE;
1348 case BC_GBRP: return AV_PIX_FMT_GBRP;
1352 return AV_PIX_FMT_NB;
1355 int FFVideoConvert::pix_fmt_to_color_model(AVPixelFormat pix_fmt)
1358 case AV_PIX_FMT_YUYV422: return BC_YUV422;
1359 case AV_PIX_FMT_RGB24: return BC_RGB888;
1360 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
1361 case AV_PIX_FMT_BGR0: return BC_BGR8888;
1362 case AV_PIX_FMT_BGR24: return BC_BGR888;
1363 case AV_PIX_FMT_ARGB: return BC_ARGB8888;
1364 case AV_PIX_FMT_ABGR: return BC_ABGR8888;
1365 case AV_PIX_FMT_RGB8: return BC_RGB8;
1366 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
1367 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
1368 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
1369 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
1370 case AV_PIX_FMT_RGB565: return BC_RGB565;
1371 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
1372 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
1373 case AV_PIX_FMT_AYUV64LE: return BC_AYUV16161616;
1374 case AV_PIX_FMT_GBRP: return BC_GBRP;
1381 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip)
1383 AVFrame *ipic = av_frame_alloc();
1384 int ret = convert_picture_vframe(frame, ip, ipic);
1385 av_frame_free(&ipic);
1389 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip, AVFrame *ipic)
1390 { // picture = vframe
1391 int cmodel = frame->get_color_model();
1392 AVPixelFormat ofmt = color_model_to_pix_fmt(cmodel);
1393 if( ofmt == AV_PIX_FMT_NB ) return -1;
1394 int size = av_image_fill_arrays(ipic->data, ipic->linesize,
1395 frame->get_data(), ofmt, frame->get_w(), frame->get_h(), 1);
1396 if( size < 0 ) return -1;
1398 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1399 int ysz = bpp * frame->get_w(), usz = ysz;
1409 // override av_image_fill_arrays() for planar types
1410 ipic->data[0] = frame->get_y(); ipic->linesize[0] = ysz;
1411 ipic->data[1] = frame->get_u(); ipic->linesize[1] = usz;
1412 ipic->data[2] = frame->get_v(); ipic->linesize[2] = usz;
1415 ipic->data[0] = frame->get_data();
1416 ipic->linesize[0] = frame->get_bytes_per_line();
1420 AVPixelFormat pix_fmt = (AVPixelFormat)ip->format;
1421 FFVideoStream *vid =(FFVideoStream *)this;
1422 if( pix_fmt == vid->hw_pixfmt ) {
1424 if( !sw_frame && !(sw_frame=av_frame_alloc()) )
1425 ret = AVERROR(ENOMEM);
1427 ret = av_hwframe_transfer_data(sw_frame, ip, 0);
1429 pix_fmt = (AVPixelFormat)ip->format;
1432 eprintf(_("Error retrieving data from GPU to CPU\nfile: %s\n"),
1433 vid->ffmpeg->fmt_ctx->url);
1437 convert_ctx = sws_getCachedContext(convert_ctx, ip->width, ip->height, pix_fmt,
1438 frame->get_w(), frame->get_h(), ofmt, SWS_POINT, NULL, NULL, NULL);
1439 if( !convert_ctx ) {
1440 fprintf(stderr, "FFVideoConvert::convert_picture_frame:"
1441 " sws_getCachedContext() failed\n");
1445 int color_range = 0;
1446 switch( preferences->yuv_color_range ) {
1447 case BC_COLORS_JPEG: color_range = 1; break;
1448 case BC_COLORS_MPEG: color_range = 0; break;
1450 int color_space = SWS_CS_ITU601;
1451 switch( preferences->yuv_color_space ) {
1452 case BC_COLORS_BT601: color_space = SWS_CS_ITU601; break;
1453 case BC_COLORS_BT709: color_space = SWS_CS_ITU709; break;
1454 case BC_COLORS_BT2020: color_space = SWS_CS_BT2020; break;
1456 const int *color_table = sws_getCoefficients(color_space);
1458 int *inv_table, *table, src_range, dst_range;
1459 int brightness, contrast, saturation;
1460 if( !sws_getColorspaceDetails(convert_ctx,
1461 &inv_table, &src_range, &table, &dst_range,
1462 &brightness, &contrast, &saturation) ) {
1463 if( src_range != color_range || dst_range != color_range ||
1464 inv_table != color_table || table != color_table )
1465 sws_setColorspaceDetails(convert_ctx,
1466 color_table, color_range, color_table, color_range,
1467 brightness, contrast, saturation);
1470 int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ip->height,
1471 ipic->data, ipic->linesize);
1473 ff_err(ret, "FFVideoConvert::convert_picture_frame: sws_scale() failed\nfile: %s\n",
1474 vid->ffmpeg->fmt_ctx->url);
1480 int FFVideoConvert::convert_cmodel(VFrame *frame, AVFrame *ip)
1482 // try direct transfer
1483 if( !convert_picture_vframe(frame, ip) ) return 1;
1484 // use indirect transfer
1485 AVPixelFormat ifmt = (AVPixelFormat)ip->format;
1486 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
1488 for( int i = 0; i <desc->nb_components; ++i ) {
1489 int bits = desc->comp[i].depth;
1490 if( bits > max_bits ) max_bits = bits;
1492 int imodel = pix_fmt_to_color_model(ifmt);
1493 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1494 int cmodel = frame->get_color_model();
1495 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1496 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1497 imodel = cmodel_is_yuv ?
1498 (BC_CModels::has_alpha(cmodel) ?
1500 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1501 (BC_CModels::has_alpha(cmodel) ?
1502 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1503 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1505 VFrame vframe(ip->width, ip->height, imodel);
1506 if( convert_picture_vframe(&vframe, ip) ) return -1;
1507 frame->transfer_from(&vframe);
1511 int FFVideoConvert::transfer_cmodel(VFrame *frame, AVFrame *ifp)
1513 int ret = convert_cmodel(frame, ifp);
1515 const AVDictionary *src = ifp->metadata;
1516 AVDictionaryEntry *t = NULL;
1517 BC_Hash *hp = frame->get_params();
1519 while( (t=av_dict_get(src, "", t, AV_DICT_IGNORE_SUFFIX)) )
1520 hp->update(t->key, t->value);
1525 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op)
1527 AVFrame *opic = av_frame_alloc();
1528 int ret = convert_vframe_picture(frame, op, opic);
1529 av_frame_free(&opic);
1533 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op, AVFrame *opic)
1534 { // vframe = picture
1535 int cmodel = frame->get_color_model();
1536 AVPixelFormat ifmt = color_model_to_pix_fmt(cmodel);
1537 if( ifmt == AV_PIX_FMT_NB ) return -1;
1538 int size = av_image_fill_arrays(opic->data, opic->linesize,
1539 frame->get_data(), ifmt, frame->get_w(), frame->get_h(), 1);
1540 if( size < 0 ) return -1;
1542 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1543 int ysz = bpp * frame->get_w(), usz = ysz;
1553 // override av_image_fill_arrays() for planar types
1554 opic->data[0] = frame->get_y(); opic->linesize[0] = ysz;
1555 opic->data[1] = frame->get_u(); opic->linesize[1] = usz;
1556 opic->data[2] = frame->get_v(); opic->linesize[2] = usz;
1559 opic->data[0] = frame->get_data();
1560 opic->linesize[0] = frame->get_bytes_per_line();
1564 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1565 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(),
1566 ifmt, op->width, op->height, ofmt, SWS_POINT, NULL, NULL, NULL);
1567 if( !convert_ctx ) {
1568 fprintf(stderr, "FFVideoConvert::convert_frame_picture:"
1569 " sws_getCachedContext() failed\n");
1574 int color_range = 0;
1575 switch( preferences->yuv_color_range ) {
1576 case BC_COLORS_JPEG: color_range = 1; break;
1577 case BC_COLORS_MPEG: color_range = 0; break;
1579 int color_space = SWS_CS_ITU601;
1580 switch( preferences->yuv_color_space ) {
1581 case BC_COLORS_BT601: color_space = SWS_CS_ITU601; break;
1582 case BC_COLORS_BT709: color_space = SWS_CS_ITU709; break;
1583 case BC_COLORS_BT2020: color_space = SWS_CS_BT2020; break;
1585 const int *color_table = sws_getCoefficients(color_space);
1587 int *inv_table, *table, src_range, dst_range;
1588 int brightness, contrast, saturation;
1589 if( !sws_getColorspaceDetails(convert_ctx,
1590 &inv_table, &src_range, &table, &dst_range,
1591 &brightness, &contrast, &saturation) ) {
1592 if( dst_range != color_range || table != color_table )
1593 sws_setColorspaceDetails(convert_ctx,
1594 inv_table, src_range, color_table, color_range,
1595 brightness, contrast, saturation);
1598 int ret = sws_scale(convert_ctx, opic->data, opic->linesize, 0, frame->get_h(),
1599 op->data, op->linesize);
1601 ff_err(ret, "FFVideoConvert::convert_frame_picture: sws_scale() failed\n");
1607 int FFVideoConvert::convert_pixfmt(VFrame *frame, AVFrame *op)
1609 // try direct transfer
1610 if( !convert_vframe_picture(frame, op) ) return 1;
1611 // use indirect transfer
1612 int cmodel = frame->get_color_model();
1613 int max_bits = BC_CModels::calculate_pixelsize(cmodel) * 8;
1614 max_bits /= BC_CModels::components(cmodel);
1615 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1616 int imodel = pix_fmt_to_color_model(ofmt);
1617 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1618 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1619 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1620 imodel = cmodel_is_yuv ?
1621 (BC_CModels::has_alpha(cmodel) ?
1623 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1624 (BC_CModels::has_alpha(cmodel) ?
1625 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1626 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1628 VFrame vframe(frame->get_w(), frame->get_h(), imodel);
1629 vframe.transfer_from(frame);
1630 if( !convert_vframe_picture(&vframe, op) ) return 1;
1634 int FFVideoConvert::transfer_pixfmt(VFrame *frame, AVFrame *ofp)
1636 int ret = convert_pixfmt(frame, ofp);
1638 BC_Hash *hp = frame->get_params();
1639 AVDictionary **dict = &ofp->metadata;
1640 //av_dict_free(dict);
1641 for( int i=0; i<hp->size(); ++i ) {
1642 char *key = hp->get_key(i), *val = hp->get_value(i);
1643 av_dict_set(dict, key, val, 0);
1649 void FFVideoStream::load_markers()
1651 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1652 if( !index_state || idx >= index_state->video_markers.size() ) return;
1653 FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
1656 IndexMarks *FFVideoStream::get_markers()
1658 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1659 if( !index_state || idx >= index_state->video_markers.size() ) return 0;
1660 return !index_state ? 0 : index_state->video_markers[idx];
1663 double FFVideoStream::get_rotation_angle()
1666 int *matrix = (int*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX, &size);
1667 int len = size/sizeof(*matrix);
1668 if( !matrix || len < 5 ) return 0;
1669 const double s = 1/65536.;
1670 double theta = (!matrix[0] && !matrix[3]) || (!matrix[1] && !matrix[4]) ? 0 :
1671 atan2( s*matrix[1] / hypot(s*matrix[1], s*matrix[4]),
1672 s*matrix[0] / hypot(s*matrix[0], s*matrix[3])) * 180/M_PI;
1676 void FFVideoStream::flip()
1679 if( !ffmpeg->file_base ) return;
1680 double theta = get_rotation_angle(), tolerance = 1;
1681 if( fabs(theta-0) < tolerance ) return;
1682 if( fabs(theta-90) < tolerance ) {
1683 create_filter("transpose=clock", st->codecpar);
1686 else if( fabs(theta-180) < tolerance ) {
1687 create_filter("hflip", st->codecpar);
1688 create_filter("vflip", st->codecpar);
1690 else if (fabs(theta-270) < tolerance ) {
1691 create_filter("transpose=cclock", st->codecpar);
1695 char rotate[BCSTRLEN];
1696 sprintf(rotate, "rotate=%f", theta*M_PI/180.);
1697 create_filter(rotate, st->codecpar);
1702 FFMPEG::FFMPEG(FileBase *file_base)
1705 this->file_base = file_base;
1706 memset(file_format,0,sizeof(file_format));
1707 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
1708 flow_lock = new Condition(1,"FFStream::flow_lock",0);
1711 decoding = encoding = 0;
1712 has_audio = has_video = 0;
1715 opt_video_filter = 0;
1716 opt_audio_filter = 0;
1718 opt_video_decoder = 0;
1719 opt_audio_decoder = 0;
1721 char option_path[BCTEXTLEN];
1722 set_option_path(option_path, "%s", "ffmpeg.opts");
1723 read_options(option_path, opts);
1728 ff_lock("FFMPEG::~FFMPEG()");
1730 ffaudio.remove_all_objects();
1731 ffvideo.remove_all_objects();
1732 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1736 av_dict_free(&opts);
1737 delete [] opt_video_filter;
1738 delete [] opt_audio_filter;
1739 delete [] opt_hw_dev;
1742 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1744 const int *p = codec->supported_samplerates;
1745 if( !p ) return sample_rate;
1747 if( *p == sample_rate ) return *p;
1753 static inline AVRational std_frame_rate(int i)
1755 static const int m1 = 1001*12, m2 = 1000*12;
1756 static const int freqs[] = {
1757 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1758 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
1760 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1761 return (AVRational) { freq, 1001*12 };
1764 AVRational FFMPEG::check_frame_rate(const AVRational *p, double frame_rate)
1766 AVRational rate, best_rate = (AVRational) { 0, 0 };
1767 double max_err = 1.; int i = 0;
1768 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1769 double framerate = (double) rate.num / rate.den;
1770 double err = fabs(frame_rate/framerate - 1.);
1771 if( err >= max_err ) continue;
1775 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1778 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1781 double display_aspect = asset->width / (double)asset->height;
1782 double sample_aspect = display_aspect / asset->aspect_ratio;
1783 int width = 1000000, height = width * sample_aspect + 0.5;
1785 MWindow::create_aspect_ratio(w, h, width, height);
1786 return (AVRational){(int)w, (int)h};
1789 return (AVRational){1, 1};
1793 AVRational FFMPEG::to_time_base(int sample_rate)
1795 return (AVRational){1, sample_rate};
1798 int FFMPEG::get_fmt_score(AVSampleFormat dst_fmt, AVSampleFormat src_fmt)
1801 int dst_planar = av_sample_fmt_is_planar(dst_fmt);
1802 int src_planar = av_sample_fmt_is_planar(src_fmt);
1803 if( dst_planar != src_planar ) ++score;
1804 int dst_bytes = av_get_bytes_per_sample(dst_fmt);
1805 int src_bytes = av_get_bytes_per_sample(src_fmt);
1806 score += (src_bytes > dst_bytes ? 100 : -10) * (src_bytes - dst_bytes);
1807 int src_packed = av_get_packed_sample_fmt(src_fmt);
1808 int dst_packed = av_get_packed_sample_fmt(dst_fmt);
1809 if( dst_packed == AV_SAMPLE_FMT_S32 && src_packed == AV_SAMPLE_FMT_FLT ) score += 20;
1810 if( dst_packed == AV_SAMPLE_FMT_FLT && src_packed == AV_SAMPLE_FMT_S32 ) score += 2;
1814 AVSampleFormat FFMPEG::find_best_sample_fmt_of_list(
1815 const AVSampleFormat *sample_fmts, AVSampleFormat src_fmt)
1817 AVSampleFormat best = AV_SAMPLE_FMT_NONE;
1818 int best_score = get_fmt_score(best, src_fmt);
1819 for( int i=0; sample_fmts[i] >= 0; ++i ) {
1820 AVSampleFormat sample_fmt = sample_fmts[i];
1821 int score = get_fmt_score(sample_fmt, src_fmt);
1822 if( score >= best_score ) continue;
1823 best = sample_fmt; best_score = score;
1829 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
1831 char *ep = path + BCTEXTLEN-1;
1832 strncpy(path, File::get_cindat_path(), ep-path);
1833 strncat(path, "/ffmpeg/", ep-path);
1834 path += strlen(path);
1837 path += vsnprintf(path, ep-path, fmt, ap);
1842 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
1847 set_option_path(path, "%s/%s", type, spec);
1850 int FFMPEG::get_format(char *format, const char *path, const char *spec)
1852 char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
1853 get_option_path(option_path, path, spec);
1854 FILE *fp = fopen(option_path,"r");
1857 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1859 line[sizeof(line)-1] = 0;
1860 ret = scan_option_line(line, format, codec);
1866 int FFMPEG::get_codec(char *codec, const char *path, const char *spec)
1868 char option_path[BCTEXTLEN], line[BCTEXTLEN], format[BCTEXTLEN];
1869 get_option_path(option_path, path, spec);
1870 FILE *fp = fopen(option_path,"r");
1873 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1876 line[sizeof(line)-1] = 0;
1877 ret = scan_option_line(line, format, codec);
1880 char *vp = codec, *ep = vp+BCTEXTLEN-1;
1881 while( vp < ep && *vp && *vp != '|' ) ++vp;
1882 if( *vp == '|' ) --vp;
1883 while( vp > codec && (*vp==' ' || *vp=='\t') ) *vp-- = 0;
1888 int FFMPEG::get_file_format()
1890 char audio_muxer[BCSTRLEN], video_muxer[BCSTRLEN];
1891 char audio_format[BCSTRLEN], video_format[BCSTRLEN];
1892 audio_muxer[0] = audio_format[0] = 0;
1893 video_muxer[0] = video_format[0] = 0;
1894 Asset *asset = file_base->asset;
1895 int ret = asset ? 0 : 1;
1896 if( !ret && asset->audio_data ) {
1897 if( !(ret=get_format(audio_format, "audio", asset->acodec)) ) {
1898 if( get_format(audio_muxer, "format", audio_format) ) {
1899 strcpy(audio_muxer, audio_format);
1900 audio_format[0] = 0;
1904 if( !ret && asset->video_data ) {
1905 if( !(ret=get_format(video_format, "video", asset->vcodec)) ) {
1906 if( get_format(video_muxer, "format", video_format) ) {
1907 strcpy(video_muxer, video_format);
1908 video_format[0] = 0;
1912 if( !ret && !audio_muxer[0] && !video_muxer[0] )
1914 if( !ret && audio_muxer[0] && video_muxer[0] &&
1915 strcmp(audio_muxer, video_muxer) ) ret = -1;
1916 if( !ret && audio_format[0] && video_format[0] &&
1917 strcmp(audio_format, video_format) ) ret = -1;
1919 strcpy(file_format, !audio_format[0] && !video_format[0] ?
1920 (audio_muxer[0] ? audio_muxer : video_muxer) :
1921 (audio_format[0] ? audio_format : video_format));
1925 int FFMPEG::scan_option_line(const char *cp, char *tag, char *val)
1927 while( *cp == ' ' || *cp == '\t' ) ++cp;
1928 const char *bp = cp;
1929 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' && *cp != '\n' ) ++cp;
1931 if( !len || len > BCSTRLEN-1 ) return 1;
1932 while( bp < cp ) *tag++ = *bp++;
1934 while( *cp == ' ' || *cp == '\t' ) ++cp;
1935 if( *cp == '=' ) ++cp;
1936 while( *cp == ' ' || *cp == '\t' ) ++cp;
1938 while( *cp && *cp != '\n' ) ++cp;
1940 if( len > BCTEXTLEN-1 ) return 1;
1941 while( bp < cp ) *val++ = *bp++;
1946 int FFMPEG::can_render(const char *fformat, const char *type)
1949 char option_path[BCTEXTLEN];
1950 FFMPEG::set_option_path(option_path, type);
1951 fs.update(option_path);
1952 int total_files = fs.total_files();
1953 for( int i=0; i<total_files; ++i ) {
1954 const char *name = fs.get_entry(i)->get_name();
1955 const char *ext = strrchr(name,'.');
1956 if( !ext ) continue;
1957 if( !strcmp(fformat, ++ext) ) return 1;
1962 int FFMPEG::get_ff_option(const char *nm, const char *options, char *value)
1964 for( const char *cp=options; *cp!=0; ) {
1965 char line[BCTEXTLEN], *bp = line, *ep = bp+sizeof(line)-1;
1966 while( bp < ep && *cp && *cp!='\n' ) *bp++ = *cp++;
1969 if( !line[0] || line[0] == '#' || line[0] == ';' ) continue;
1970 char key[BCSTRLEN], val[BCTEXTLEN];
1971 if( FFMPEG::scan_option_line(line, key, val) ) continue;
1972 if( !strcmp(key, nm) ) {
1973 strncpy(value, val, BCSTRLEN);
1980 void FFMPEG::scan_audio_options(Asset *asset, EDL *edl)
1982 char cin_sample_fmt[BCSTRLEN];
1983 int cin_fmt = AV_SAMPLE_FMT_NONE;
1984 const char *options = asset->ff_audio_options;
1985 if( !get_ff_option("cin_sample_fmt", options, cin_sample_fmt) )
1986 cin_fmt = (int)av_get_sample_fmt(cin_sample_fmt);
1988 char audio_codec[BCSTRLEN]; audio_codec[0] = 0;
1989 AVCodec *av_codec = !FFMPEG::get_codec(audio_codec, "audio", asset->acodec) ?
1990 avcodec_find_encoder_by_name(audio_codec) : 0;
1991 if( av_codec && av_codec->sample_fmts )
1992 cin_fmt = find_best_sample_fmt_of_list(av_codec->sample_fmts, AV_SAMPLE_FMT_FLT);
1994 if( cin_fmt < 0 ) cin_fmt = AV_SAMPLE_FMT_S16;
1995 const char *name = av_get_sample_fmt_name((AVSampleFormat)cin_fmt);
1996 if( !name ) name = _("None");
1997 strcpy(asset->ff_sample_format, name);
1999 char value[BCSTRLEN];
2000 if( !get_ff_option("cin_bitrate", options, value) )
2001 asset->ff_audio_bitrate = atoi(value);
2002 if( !get_ff_option("cin_quality", options, value) )
2003 asset->ff_audio_quality = atoi(value);
2006 void FFMPEG::load_audio_options(Asset *asset, EDL *edl)
2008 char options_path[BCTEXTLEN];
2009 set_option_path(options_path, "audio/%s", asset->acodec);
2010 if( !load_options(options_path,
2011 asset->ff_audio_options,
2012 sizeof(asset->ff_audio_options)) )
2013 scan_audio_options(asset, edl);
2016 void FFMPEG::scan_video_options(Asset *asset, EDL *edl)
2018 char cin_pix_fmt[BCSTRLEN];
2019 int cin_fmt = AV_PIX_FMT_NONE;
2020 const char *options = asset->ff_video_options;
2021 if( !get_ff_option("cin_pix_fmt", options, cin_pix_fmt) )
2022 cin_fmt = (int)av_get_pix_fmt(cin_pix_fmt);
2024 char video_codec[BCSTRLEN]; video_codec[0] = 0;
2025 AVCodec *av_codec = !get_codec(video_codec, "video", asset->vcodec) ?
2026 avcodec_find_encoder_by_name(video_codec) : 0;
2027 if( av_codec && av_codec->pix_fmts ) {
2028 if( 0 && edl ) { // frequently picks a bad answer
2029 int color_model = edl->session->color_model;
2030 int max_bits = BC_CModels::calculate_pixelsize(color_model) * 8;
2031 max_bits /= BC_CModels::components(color_model);
2032 cin_fmt = avcodec_find_best_pix_fmt_of_list(av_codec->pix_fmts,
2033 (BC_CModels::is_yuv(color_model) ?
2034 (max_bits > 8 ? AV_PIX_FMT_AYUV64LE : AV_PIX_FMT_YUV444P) :
2035 (max_bits > 8 ? AV_PIX_FMT_RGB48LE : AV_PIX_FMT_RGB24)), 0, 0);
2038 cin_fmt = av_codec->pix_fmts[0];
2041 if( cin_fmt < 0 ) cin_fmt = AV_PIX_FMT_YUV420P;
2042 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get((AVPixelFormat)cin_fmt);
2043 const char *name = desc ? desc->name : _("None");
2044 strcpy(asset->ff_pixel_format, name);
2046 char value[BCSTRLEN];
2047 if( !get_ff_option("cin_bitrate", options, value) )
2048 asset->ff_video_bitrate = atoi(value);
2049 if( !get_ff_option("cin_quality", options, value) )
2050 asset->ff_video_quality = atoi(value);
2053 void FFMPEG::load_video_options(Asset *asset, EDL *edl)
2055 char options_path[BCTEXTLEN];
2056 set_option_path(options_path, "video/%s", asset->vcodec);
2057 if( !load_options(options_path,
2058 asset->ff_video_options,
2059 sizeof(asset->ff_video_options)) )
2060 scan_video_options(asset, edl);
2063 void FFMPEG::scan_format_options(Asset *asset, EDL *edl)
2067 void FFMPEG::load_format_options(Asset *asset, EDL *edl)
2069 char options_path[BCTEXTLEN];
2070 set_option_path(options_path, "format/%s", asset->fformat);
2071 if( !load_options(options_path,
2072 asset->ff_format_options,
2073 sizeof(asset->ff_format_options)) )
2074 scan_format_options(asset, edl);
2077 int FFMPEG::load_defaults(const char *path, const char *type,
2078 char *codec, char *codec_options, int len)
2080 char default_file[BCTEXTLEN];
2081 set_option_path(default_file, "%s/%s.dfl", path, type);
2082 FILE *fp = fopen(default_file,"r");
2084 fgets(codec, BCSTRLEN, fp);
2086 while( *cp && *cp!='\n' ) ++cp;
2088 while( len > 0 && fgets(codec_options, len, fp) ) {
2089 int n = strlen(codec_options);
2090 codec_options += n; len -= n;
2093 set_option_path(default_file, "%s/%s", path, codec);
2094 return load_options(default_file, codec_options, len);
2097 void FFMPEG::set_asset_format(Asset *asset, EDL *edl, const char *text)
2099 if( asset->format != FILE_FFMPEG ) return;
2100 if( text != asset->fformat )
2101 strcpy(asset->fformat, text);
2102 if( !asset->ff_format_options[0] )
2103 load_format_options(asset, edl);
2104 if( asset->audio_data && !asset->ff_audio_options[0] ) {
2105 if( !load_defaults("audio", text, asset->acodec,
2106 asset->ff_audio_options, sizeof(asset->ff_audio_options)) )
2107 scan_audio_options(asset, edl);
2109 asset->audio_data = 0;
2111 if( asset->video_data && !asset->ff_video_options[0] ) {
2112 if( !load_defaults("video", text, asset->vcodec,
2113 asset->ff_video_options, sizeof(asset->ff_video_options)) )
2114 scan_video_options(asset, edl);
2116 asset->video_data = 0;
2120 int FFMPEG::get_encoder(const char *options,
2121 char *format, char *codec, char *bsfilter)
2123 FILE *fp = fopen(options,"r");
2125 eprintf(_("options open failed %s\n"),options);
2128 char line[BCTEXTLEN];
2129 if( !fgets(line, sizeof(line), fp) ||
2130 scan_encoder(line, format, codec, bsfilter) )
2131 eprintf(_("format/codec not found %s\n"), options);
2136 int FFMPEG::scan_encoder(const char *line,
2137 char *format, char *codec, char *bsfilter)
2139 format[0] = codec[0] = bsfilter[0] = 0;
2140 if( scan_option_line(line, format, codec) ) return 1;
2142 while( *cp && *cp != '|' ) ++cp;
2143 if( !*cp ) return 0;
2145 do { *bp-- = 0; } while( bp>=codec && (*bp==' ' || *bp == '\t' ) );
2146 while( *++cp && (*cp==' ' || *cp == '\t') );
2148 for( int i=BCTEXTLEN; --i>0 && *cp; ) *bp++ = *cp++;
2153 int FFMPEG::read_options(const char *options, AVDictionary *&opts, int skip)
2155 FILE *fp = fopen(options,"r");
2158 while( !ret && --skip >= 0 ) {
2160 while( ch >= 0 && ch != '\n' ) ch = getc(fp);
2161 if( ch < 0 ) ret = 1;
2164 ret = read_options(fp, options, opts);
2169 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
2171 FILE *fp = fmemopen((void *)options,strlen(options),"r");
2173 int ret = read_options(fp, options, opts);
2176 AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
2177 if( tag ) st->id = strtol(tag->value,0,0);
2182 FFCodecRemap::FFCodecRemap()
2187 FFCodecRemap::~FFCodecRemap()
2189 delete [] old_codec;
2190 delete [] new_codec;
2193 int FFCodecRemaps::add(const char *val)
2195 char old_codec[BCSTRLEN], new_codec[BCSTRLEN];
2196 if( sscanf(val, " %63[a-zA-z0-9_-] = %63[a-z0-9_-]",
2197 &old_codec[0], &new_codec[0]) != 2 ) return 1;
2198 FFCodecRemap &remap = append();
2199 remap.old_codec = cstrdup(old_codec);
2200 remap.new_codec = cstrdup(new_codec);
2205 int FFCodecRemaps::update(AVCodecID &codec_id, AVCodec *&decoder)
2207 AVCodec *codec = avcodec_find_decoder(codec_id);
2208 if( !codec ) return -1;
2209 const char *name = codec->name;
2210 FFCodecRemaps &map = *this;
2212 while( --k >= 0 && strcmp(map[k].old_codec, name) );
2213 if( k < 0 ) return 1;
2214 const char *new_codec = map[k].new_codec;
2215 codec = avcodec_find_decoder_by_name(new_codec);
2216 if( !codec ) return -1;
2221 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
2223 int ret = 0, no = 0;
2224 char line[BCTEXTLEN];
2225 while( !ret && fgets(line, sizeof(line), fp) ) {
2226 line[sizeof(line)-1] = 0;
2227 if( line[0] == '#' ) continue;
2228 if( line[0] == '\n' ) continue;
2229 char key[BCSTRLEN], val[BCTEXTLEN];
2230 if( scan_option_line(line, key, val) ) {
2231 eprintf(_("err reading %s: line %d\n"), options, no);
2235 if( !strcmp(key, "duration") )
2236 opt_duration = strtod(val, 0);
2237 else if( !strcmp(key, "video_decoder") )
2238 opt_video_decoder = cstrdup(val);
2239 else if( !strcmp(key, "audio_decoder") )
2240 opt_audio_decoder = cstrdup(val);
2241 else if( !strcmp(key, "remap_video_decoder") )
2242 video_codec_remaps.add(val);
2243 else if( !strcmp(key, "remap_audio_decoder") )
2244 audio_codec_remaps.add(val);
2245 else if( !strcmp(key, "video_filter") )
2246 opt_video_filter = cstrdup(val);
2247 else if( !strcmp(key, "audio_filter") )
2248 opt_audio_filter = cstrdup(val);
2249 else if( !strcmp(key, "cin_hw_dev") )
2250 opt_hw_dev = cstrdup(val);
2251 else if( !strcmp(key, "loglevel") )
2254 av_dict_set(&opts, key, val, 0);
2260 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
2262 char option_path[BCTEXTLEN];
2263 set_option_path(option_path, "%s", options);
2264 return read_options(option_path, opts);
2267 int FFMPEG::load_options(const char *path, char *bfr, int len)
2270 FILE *fp = fopen(path, "r");
2272 fgets(bfr, len, fp); // skip hdr
2273 len = fread(bfr, 1, len-1, fp);
2274 if( len < 0 ) len = 0;
2280 void FFMPEG::set_loglevel(const char *ap)
2282 if( !ap || !*ap ) return;
2287 { "quiet" , AV_LOG_QUIET },
2288 { "panic" , AV_LOG_PANIC },
2289 { "fatal" , AV_LOG_FATAL },
2290 { "error" , AV_LOG_ERROR },
2291 { "warning", AV_LOG_WARNING },
2292 { "info" , AV_LOG_INFO },
2293 { "verbose", AV_LOG_VERBOSE },
2294 { "debug" , AV_LOG_DEBUG },
2296 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
2297 if( !strcmp(log_levels[i].name, ap) ) {
2298 av_log_set_level(log_levels[i].level);
2302 av_log_set_level(atoi(ap));
2305 double FFMPEG::to_secs(int64_t time, AVRational time_base)
2307 double base_time = time == AV_NOPTS_VALUE ? 0 :
2308 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
2309 return base_time / AV_TIME_BASE;
2312 int FFMPEG::info(char *text, int len)
2314 if( len <= 0 ) return 0;
2316 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
2318 report("format: %s\n",fmt_ctx->iformat->name);
2319 if( ffvideo.size() > 0 )
2320 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
2321 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
2322 const char *unkn = _("(unkn)");
2323 FFVideoStream *vid = ffvideo[vidx];
2324 AVStream *st = vid->st;
2325 AVCodecID codec_id = st->codecpar->codec_id;
2326 report(_("vid%d (%d), id 0x%06x:\n"), vid->idx, vid->fidx, codec_id);
2327 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
2328 report(" video%d %s ", vidx+1, desc ? desc->name : unkn);
2329 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
2330 AVPixelFormat pix_fmt = (AVPixelFormat)st->codecpar->format;
2331 const char *pfn = av_get_pix_fmt_name(pix_fmt);
2332 report(" pix %s\n", pfn ? pfn : unkn);
2333 enum AVColorSpace space = st->codecpar->color_space;
2334 const char *nm = av_color_space_name(space);
2335 report(" color space:%s", nm ? nm : unkn);
2336 enum AVColorRange range = st->codecpar->color_range;
2337 const char *rg = av_color_range_name(range);
2338 report("/ range:%s\n", rg ? rg : unkn);
2339 double secs = to_secs(st->duration, st->time_base);
2340 int64_t length = secs * vid->frame_rate + 0.5;
2341 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
2342 int64_t nudge = ofs * vid->frame_rate;
2343 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
2344 report(" %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
2345 int hrs = secs/3600; secs -= hrs*3600;
2346 int mins = secs/60; secs -= mins*60;
2347 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
2348 double theta = vid->get_rotation_angle();
2349 if( fabs(theta) > 1 )
2350 report(" rotation angle: %0.1f\n", theta);
2352 if( ffaudio.size() > 0 )
2353 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
2354 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2355 FFAudioStream *aud = ffaudio[aidx];
2356 AVStream *st = aud->st;
2357 AVCodecID codec_id = st->codecpar->codec_id;
2358 report(_("aud%d (%d), id 0x%06x:\n"), aud->idx, aud->fidx, codec_id);
2359 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
2360 int nch = aud->channels, ch0 = aud->channel0+1;
2361 report(" audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
2362 AVSampleFormat sample_fmt = (AVSampleFormat)st->codecpar->format;
2363 const char *fmt = av_get_sample_fmt_name(sample_fmt);
2364 report(" %s %d", fmt, aud->sample_rate);
2365 int sample_bits = av_get_bits_per_sample(codec_id);
2366 report(" %dbits\n", sample_bits);
2367 double secs = to_secs(st->duration, st->time_base);
2368 int64_t length = secs * aud->sample_rate + 0.5;
2369 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
2370 int64_t nudge = ofs * aud->sample_rate;
2371 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
2372 report(" %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
2373 int hrs = secs/3600; secs -= hrs*3600;
2374 int mins = secs/60; secs -= mins*60;
2375 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
2377 if( fmt_ctx->nb_programs > 0 )
2378 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
2379 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
2380 report("program %d", i+1);
2381 AVProgram *pgrm = fmt_ctx->programs[i];
2382 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2383 int idx = pgrm->stream_index[j];
2384 int vidx = ffvideo.size();
2385 while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
2387 report(", vid%d", vidx);
2390 int aidx = ffaudio.size();
2391 while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
2393 report(", aud%d", aidx);
2396 report(", (%d)", pgrm->stream_index[j]);
2401 AVDictionaryEntry *tag = 0;
2402 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
2403 report("%s=%s\n", tag->key, tag->value);
2412 int FFMPEG::init_decoder(const char *filename)
2414 ff_lock("FFMPEG::init_decoder");
2416 char file_opts[BCTEXTLEN];
2417 strcpy(file_opts, filename);
2418 char *bp = strrchr(file_opts, '/');
2419 if( !bp ) bp = file_opts;
2420 char *sp = strrchr(bp, '.');
2421 if( !sp ) sp = bp + strlen(bp);
2423 AVInputFormat *ifmt = 0;
2425 strcpy(sp, ".opts");
2426 fp = fopen(file_opts, "r");
2429 read_options(fp, file_opts, opts);
2431 AVDictionaryEntry *tag;
2432 if( (tag=av_dict_get(opts, "format", NULL, 0)) != 0 ) {
2433 ifmt = av_find_input_format(tag->value);
2437 load_options("decode.opts", opts);
2438 AVDictionary *fopts = 0;
2439 av_dict_copy(&fopts, opts, 0);
2440 int ret = avformat_open_input(&fmt_ctx, filename, ifmt, &fopts);
2441 av_dict_free(&fopts);
2443 ret = avformat_find_stream_info(fmt_ctx, NULL);
2448 return !ret ? 0 : 1;
2451 int FFMPEG::open_decoder()
2454 if( stat(fmt_ctx->url, &st) < 0 ) {
2455 eprintf(_("can't stat file: %s\n"), fmt_ctx->url);
2459 int64_t file_bits = 8 * st.st_size;
2460 if( !fmt_ctx->bit_rate && opt_duration > 0 )
2461 fmt_ctx->bit_rate = file_bits / opt_duration;
2464 if( fmt_ctx->bit_rate > 0 ) {
2465 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2466 AVStream *st = fmt_ctx->streams[i];
2467 if( st->duration != AV_NOPTS_VALUE ) continue;
2468 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
2469 st->duration = av_rescale(file_bits, st->time_base.den,
2470 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
2474 if( estimated && !(fflags & FF_ESTM_TIMES) ) {
2475 fflags |= FF_ESTM_TIMES;
2476 printf("FFMPEG::open_decoder: some stream times estimated: %s\n",
2480 ff_lock("FFMPEG::open_decoder");
2481 int ret = 0, bad_time = 0;
2482 for( int i=0; !ret && i<(int)fmt_ctx->nb_streams; ++i ) {
2483 AVStream *st = fmt_ctx->streams[i];
2484 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
2485 AVCodecParameters *avpar = st->codecpar;
2486 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avpar->codec_id);
2487 if( !codec_desc ) continue;
2488 switch( avpar->codec_type ) {
2489 case AVMEDIA_TYPE_VIDEO: {
2490 if( avpar->width < 1 ) continue;
2491 if( avpar->height < 1 ) continue;
2492 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
2493 if( framerate.num < 1 ) continue;
2495 int vidx = ffvideo.size();
2496 FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
2497 vstrm_index.append(ffidx(vidx, 0));
2498 ffvideo.append(vid);
2499 vid->width = avpar->width;
2500 vid->height = avpar->height;
2501 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
2502 switch( avpar->color_range ) {
2503 case AVCOL_RANGE_MPEG:
2504 vid->color_range = BC_COLORS_MPEG;
2506 case AVCOL_RANGE_JPEG:
2507 vid->color_range = BC_COLORS_JPEG;
2510 vid->color_range = !file_base ? BC_COLORS_JPEG :
2511 file_base->file->preferences->yuv_color_range;
2514 switch( avpar->color_space ) {
2515 case AVCOL_SPC_BT470BG:
2516 case AVCOL_SPC_SMPTE170M:
2517 vid->color_space = BC_COLORS_BT601;
2519 case AVCOL_SPC_BT709:
2520 vid->color_space = BC_COLORS_BT709;
2522 case AVCOL_SPC_BT2020_NCL:
2523 case AVCOL_SPC_BT2020_CL:
2524 vid->color_space = BC_COLORS_BT2020;
2527 vid->color_space = !file_base ? BC_COLORS_BT601 :
2528 file_base->file->preferences->yuv_color_space;
2531 double secs = to_secs(st->duration, st->time_base);
2532 vid->length = secs * vid->frame_rate;
2533 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
2534 vid->nudge = st->start_time;
2536 if( opt_video_filter )
2537 ret = vid->create_filter(opt_video_filter, avpar);
2538 if( file_base && file_base->file->preferences->auto_rotate )
2541 case AVMEDIA_TYPE_AUDIO: {
2542 if( avpar->channels < 1 ) continue;
2543 if( avpar->sample_rate < 1 ) continue;
2545 int aidx = ffaudio.size();
2546 FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
2547 ffaudio.append(aud);
2548 aud->channel0 = astrm_index.size();
2549 aud->channels = avpar->channels;
2550 for( int ch=0; ch<aud->channels; ++ch )
2551 astrm_index.append(ffidx(aidx, ch));
2552 aud->sample_rate = avpar->sample_rate;
2553 double secs = to_secs(st->duration, st->time_base);
2554 aud->length = secs * aud->sample_rate;
2555 aud->init_swr(aud->channels, avpar->format, aud->sample_rate);
2556 aud->nudge = st->start_time;
2558 if( opt_audio_filter )
2559 ret = aud->create_filter(opt_audio_filter, avpar);
2564 if( bad_time && !(fflags & FF_BAD_TIMES) ) {
2565 fflags |= FF_BAD_TIMES;
2566 printf(_("FFMPEG::open_decoder: some stream have bad times: %s\n"),
2570 return ret < 0 ? -1 : 0;
2574 int FFMPEG::init_encoder(const char *filename)
2576 // try access first for named pipes
2577 int ret = access(filename, W_OK);
2579 int fd = ::open(filename,O_WRONLY);
2580 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
2581 if( fd >= 0 ) { close(fd); ret = 0; }
2584 eprintf(_("bad file path: %s\n"), filename);
2587 ret = get_file_format();
2589 eprintf(_("bad file format: %s\n"), filename);
2593 eprintf(_("mismatch audio/video file format: %s\n"), filename);
2596 ff_lock("FFMPEG::init_encoder");
2598 char format[BCSTRLEN];
2599 if( get_format(format, "format", file_format) )
2600 strcpy(format, file_format);
2601 avformat_alloc_output_context2(&fmt_ctx, 0, format, filename);
2603 eprintf(_("failed: %s\n"), filename);
2608 load_options("encode.opts", opts);
2614 int FFMPEG::open_encoder(const char *type, const char *spec)
2617 Asset *asset = file_base->asset;
2618 char *filename = asset->path;
2619 AVDictionary *sopts = 0;
2620 av_dict_copy(&sopts, opts, 0);
2621 char option_path[BCTEXTLEN];
2622 set_option_path(option_path, "%s/%s.opts", type, type);
2623 read_options(option_path, sopts);
2624 get_option_path(option_path, type, spec);
2625 char format_name[BCSTRLEN], codec_name[BCTEXTLEN], bsfilter[BCTEXTLEN];
2626 if( get_encoder(option_path, format_name, codec_name, bsfilter) ) {
2627 eprintf(_("get_encoder failed %s:%s\n"), option_path, filename);
2632 if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
2634 else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
2635 else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
2638 ff_lock("FFMPEG::open_encoder");
2641 AVCodecContext *ctx = 0;
2643 const AVCodecDescriptor *codec_desc = 0;
2644 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
2646 eprintf(_("cant find codec %s:%s\n"), codec_name, filename);
2650 codec_desc = avcodec_descriptor_get(codec->id);
2652 eprintf(_("unknown codec %s:%s\n"), codec_name, filename);
2657 st = avformat_new_stream(fmt_ctx, 0);
2659 eprintf(_("cant create stream %s:%s\n"), codec_name, filename);
2664 switch( codec_desc->type ) {
2665 case AVMEDIA_TYPE_AUDIO: {
2667 eprintf(_("duplicate audio %s:%s\n"), codec_name, filename);
2671 if( scan_options(asset->ff_audio_options, sopts, st) ) {
2672 eprintf(_("bad audio options %s:%s\n"), codec_name, filename);
2677 ctx = avcodec_alloc_context3(codec);
2678 if( asset->ff_audio_bitrate > 0 ) {
2679 ctx->bit_rate = asset->ff_audio_bitrate;
2681 sprintf(arg, "%d", asset->ff_audio_bitrate);
2682 av_dict_set(&sopts, "b", arg, 0);
2684 else if( asset->ff_audio_quality >= 0 ) {
2685 ctx->global_quality = asset->ff_audio_quality * FF_QP2LAMBDA;
2686 ctx->qmin = ctx->qmax = asset->ff_audio_quality;
2687 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2688 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2689 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2691 av_dict_set(&sopts, "flags", "+qscale", 0);
2692 sprintf(arg, "%d", asset->ff_audio_quality);
2693 av_dict_set(&sopts, "qscale", arg, 0);
2694 sprintf(arg, "%d", ctx->global_quality);
2695 av_dict_set(&sopts, "global_quality", arg, 0);
2697 int aidx = ffaudio.size();
2698 int fidx = aidx + ffvideo.size();
2699 FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
2700 aud->avctx = ctx; ffaudio.append(aud); fst = aud;
2701 aud->sample_rate = asset->sample_rate;
2702 ctx->channels = aud->channels = asset->channels;
2703 for( int ch=0; ch<aud->channels; ++ch )
2704 astrm_index.append(ffidx(aidx, ch));
2705 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
2706 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
2707 if( !ctx->sample_rate ) {
2708 eprintf(_("check_sample_rate failed %s\n"), filename);
2712 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
2713 AVSampleFormat sample_fmt = av_get_sample_fmt(asset->ff_sample_format);
2714 if( sample_fmt == AV_SAMPLE_FMT_NONE )
2715 sample_fmt = codec->sample_fmts ? codec->sample_fmts[0] : AV_SAMPLE_FMT_S16;
2716 ctx->sample_fmt = sample_fmt;
2717 uint64_t layout = av_get_default_channel_layout(ctx->channels);
2718 aud->resample_context = swr_alloc_set_opts(NULL,
2719 layout, ctx->sample_fmt, aud->sample_rate,
2720 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
2722 swr_init(aud->resample_context);
2725 case AVMEDIA_TYPE_VIDEO: {
2727 eprintf(_("duplicate video %s:%s\n"), codec_name, filename);
2731 if( scan_options(asset->ff_video_options, sopts, st) ) {
2732 eprintf(_("bad video options %s:%s\n"), codec_name, filename);
2737 ctx = avcodec_alloc_context3(codec);
2738 if( asset->ff_video_bitrate > 0 ) {
2739 ctx->bit_rate = asset->ff_video_bitrate;
2741 sprintf(arg, "%d", asset->ff_video_bitrate);
2742 av_dict_set(&sopts, "b", arg, 0);
2744 else if( asset->ff_video_quality >= 0 ) {
2745 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
2746 ctx->qmin = ctx->qmax = asset->ff_video_quality;
2747 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2748 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2749 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2751 av_dict_set(&sopts, "flags", "+qscale", 0);
2752 sprintf(arg, "%d", asset->ff_video_quality);
2753 av_dict_set(&sopts, "qscale", arg, 0);
2754 sprintf(arg, "%d", ctx->global_quality);
2755 av_dict_set(&sopts, "global_quality", arg, 0);
2757 int vidx = ffvideo.size();
2758 int fidx = vidx + ffaudio.size();
2759 FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
2760 vstrm_index.append(ffidx(vidx, 0));
2761 vid->avctx = ctx; ffvideo.append(vid); fst = vid;
2762 vid->width = asset->width;
2763 vid->height = asset->height;
2764 vid->frame_rate = asset->frame_rate;
2765 if( (vid->color_range = asset->ff_color_range) < 0 )
2766 vid->color_range = file_base->file->preferences->yuv_color_range;
2767 switch( vid->color_range ) {
2768 case BC_COLORS_MPEG: ctx->color_range = AVCOL_RANGE_MPEG; break;
2769 case BC_COLORS_JPEG: ctx->color_range = AVCOL_RANGE_JPEG; break;
2771 if( (vid->color_space = asset->ff_color_space) < 0 )
2772 vid->color_space = file_base->file->preferences->yuv_color_space;
2773 switch( vid->color_space ) {
2774 case BC_COLORS_BT601: ctx->colorspace = AVCOL_SPC_SMPTE170M; break;
2775 case BC_COLORS_BT709: ctx->colorspace = AVCOL_SPC_BT709; break;
2776 case BC_COLORS_BT2020: ctx->colorspace = AVCOL_SPC_BT2020_NCL; break;
2778 AVPixelFormat pix_fmt = av_get_pix_fmt(asset->ff_pixel_format);
2779 if( opt_hw_dev != 0 ) {
2780 AVHWDeviceType hw_type = vid->encode_hw_activate(opt_hw_dev);
2782 case AV_HWDEVICE_TYPE_VAAPI:
2783 pix_fmt = AV_PIX_FMT_VAAPI;
2785 case AV_HWDEVICE_TYPE_NONE:
2789 if( pix_fmt == AV_PIX_FMT_NONE )
2790 pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
2791 ctx->pix_fmt = pix_fmt;
2793 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
2794 int mask_w = (1<<desc->log2_chroma_w)-1;
2795 ctx->width = (vid->width+mask_w) & ~mask_w;
2796 int mask_h = (1<<desc->log2_chroma_h)-1;
2797 ctx->height = (vid->height+mask_h) & ~mask_h;
2798 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
2799 AVRational frame_rate = check_frame_rate(codec->supported_framerates, vid->frame_rate);
2800 if( !frame_rate.num || !frame_rate.den ) {
2801 eprintf(_("check_frame_rate failed %s\n"), filename);
2805 av_reduce(&frame_rate.num, &frame_rate.den,
2806 frame_rate.num, frame_rate.den, INT_MAX);
2807 ctx->framerate = (AVRational) { frame_rate.num, frame_rate.den };
2808 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
2809 st->avg_frame_rate = frame_rate;
2810 st->time_base = ctx->time_base;
2812 vid->interlaced = asset->interlace_mode == ILACE_MODE_TOP_FIRST ||
2813 asset->interlace_mode == ILACE_MODE_BOTTOM_FIRST ? 1 : 0;
2814 vid->top_field_first = asset->interlace_mode == ILACE_MODE_TOP_FIRST ? 1 : 0;
2817 eprintf(_("not audio/video, %s:%s\n"), codec_name, filename);
2822 AVDictionaryEntry *tag;
2823 if( (tag=av_dict_get(sopts, "cin_stats_filename", NULL, 0)) != 0 ) {
2824 char suffix[BCSTRLEN]; sprintf(suffix,"-%d.log",fst->fidx);
2825 fst->stats_filename = cstrcat(2, tag->value, suffix);
2827 if( (tag=av_dict_get(sopts, "flags", NULL, 0)) != 0 ) {
2828 int pass = fst->pass;
2829 char *cp = tag->value;
2831 int ch = *cp++, pfx = ch=='-' ? -1 : ch=='+' ? 1 : 0;
2832 if( !isalnum(!pfx ? ch : (ch=*cp++)) ) continue;
2833 char id[BCSTRLEN], *bp = id, *ep = bp+sizeof(id)-1;
2834 for( *bp++=ch; isalnum(ch=*cp); ++cp )
2835 if( bp < ep ) *bp++ = ch;
2837 if( !strcmp(id, "pass1") ) {
2838 pass = pfx<0 ? (pass&~1) : pfx>0 ? (pass|1) : 1;
2840 else if( !strcmp(id, "pass2") ) {
2841 pass = pfx<0 ? (pass&~2) : pfx>0 ? (pass|2) : 2;
2844 if( (fst->pass=pass) ) {
2845 if( pass & 1 ) ctx->flags |= AV_CODEC_FLAG_PASS1;
2846 if( pass & 2 ) ctx->flags |= AV_CODEC_FLAG_PASS2;
2852 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
2853 ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
2854 if( fst->stats_filename && (ret=fst->init_stats_file()) )
2855 eprintf(_("error: stats file = %s\n"), fst->stats_filename);
2858 av_dict_set(&sopts, "cin_bitrate", 0, 0);
2859 av_dict_set(&sopts, "cin_quality", 0, 0);
2861 if( !av_dict_get(sopts, "threads", NULL, 0) )
2862 ctx->thread_count = ff_cpus();
2863 ret = avcodec_open2(ctx, codec, &sopts);
2865 ret = avcodec_parameters_from_context(st->codecpar, ctx);
2867 fprintf(stderr, "Could not copy the stream parameters\n");
2870 _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
2871 ret = avcodec_copy_context(st->codec, ctx);
2872 _Pragma("GCC diagnostic warning \"-Wdeprecated-declarations\"")
2874 fprintf(stderr, "Could not copy the stream context\n");
2877 ff_err(ret,"FFMPEG::open_encoder");
2878 eprintf(_("open failed %s:%s\n"), codec_name, filename);
2884 if( !ret && fst && bsfilter[0] ) {
2885 ret = av_bsf_list_parse_str(bsfilter, &fst->bsfc);
2887 ff_err(ret,"FFMPEG::open_encoder");
2888 eprintf(_("bitstream filter failed %s:\n%s\n"), filename, bsfilter);
2899 av_dict_free(&sopts);
2903 int FFMPEG::close_encoder()
2906 if( encoding > 0 ) {
2907 av_write_trailer(fmt_ctx);
2908 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
2909 avio_closep(&fmt_ctx->pb);
2915 int FFMPEG::decode_activate()
2917 if( decoding < 0 ) {
2919 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
2920 ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
2921 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
2922 ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
2923 // set nudges for each program stream set
2924 const int64_t min_nudge = INT64_MIN+1;
2925 int npgrms = fmt_ctx->nb_programs;
2926 for( int i=0; i<npgrms; ++i ) {
2927 AVProgram *pgrm = fmt_ctx->programs[i];
2928 // first start time video stream
2929 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2930 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2931 int fidx = pgrm->stream_index[j];
2932 AVStream *st = fmt_ctx->streams[fidx];
2933 AVCodecParameters *avpar = st->codecpar;
2934 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2935 if( st->start_time == AV_NOPTS_VALUE ) continue;
2936 if( vstart_time < st->start_time )
2937 vstart_time = st->start_time;
2940 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2941 if( st->start_time == AV_NOPTS_VALUE ) continue;
2942 if( astart_time < st->start_time )
2943 astart_time = st->start_time;
2947 //since frame rate is much more grainy than sample rate, it is better to
2948 // align using video, so that total absolute error is minimized.
2949 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2950 astart_time > min_nudge ? astart_time : AV_NOPTS_VALUE;
2951 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2952 int fidx = pgrm->stream_index[j];
2953 AVStream *st = fmt_ctx->streams[fidx];
2954 AVCodecParameters *avpar = st->codecpar;
2955 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2956 for( int k=0; k<ffvideo.size(); ++k ) {
2957 if( ffvideo[k]->fidx != fidx ) continue;
2958 ffvideo[k]->nudge = nudge;
2962 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2963 for( int k=0; k<ffaudio.size(); ++k ) {
2964 if( ffaudio[k]->fidx != fidx ) continue;
2965 ffaudio[k]->nudge = nudge;
2971 // set nudges for any streams not yet set
2972 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2973 int nstreams = fmt_ctx->nb_streams;
2974 for( int i=0; i<nstreams; ++i ) {
2975 AVStream *st = fmt_ctx->streams[i];
2976 AVCodecParameters *avpar = st->codecpar;
2977 switch( avpar->codec_type ) {
2978 case AVMEDIA_TYPE_VIDEO: {
2979 if( st->start_time == AV_NOPTS_VALUE ) continue;
2980 int vidx = ffvideo.size();
2981 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
2982 if( vidx < 0 ) continue;
2983 if( ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
2984 if( vstart_time < st->start_time )
2985 vstart_time = st->start_time;
2987 case AVMEDIA_TYPE_AUDIO: {
2988 if( st->start_time == AV_NOPTS_VALUE ) continue;
2989 int aidx = ffaudio.size();
2990 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
2991 if( aidx < 0 ) continue;
2992 if( ffaudio[aidx]->frame_sz < avpar->frame_size )
2993 ffaudio[aidx]->frame_sz = avpar->frame_size;
2994 if( ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
2995 if( astart_time < st->start_time )
2996 astart_time = st->start_time;
3001 int64_t nudge = vstart_time > min_nudge ? vstart_time :
3002 astart_time > min_nudge ? astart_time : 0;
3003 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
3004 if( ffvideo[vidx]->nudge == AV_NOPTS_VALUE )
3005 ffvideo[vidx]->nudge = nudge;
3007 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
3008 if( ffaudio[aidx]->nudge == AV_NOPTS_VALUE )
3009 ffaudio[aidx]->nudge = nudge;
3016 int FFMPEG::encode_activate()
3019 if( encoding < 0 ) {
3021 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
3022 (ret=avio_open(&fmt_ctx->pb, fmt_ctx->url, AVIO_FLAG_WRITE)) < 0 ) {
3023 ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
3027 if( !strcmp(file_format, "image2") ) {
3028 Asset *asset = file_base->asset;
3029 const char *filename = asset->path;
3030 FILE *fp = fopen(filename,"w");
3032 eprintf(_("Cant write image2 header file: %s\n %m"), filename);
3035 fprintf(fp, "IMAGE2\n");
3036 fprintf(fp, "# Frame rate: %f\n", asset->frame_rate);
3037 fprintf(fp, "# Width: %d\n", asset->width);
3038 fprintf(fp, "# Height: %d\n", asset->height);
3042 AVProgram *prog = av_new_program(fmt_ctx, prog_id);
3043 for( int i=0; i< ffvideo.size(); ++i )
3044 av_program_add_stream_index(fmt_ctx, prog_id, ffvideo[i]->fidx);
3045 for( int i=0; i< ffaudio.size(); ++i )
3046 av_program_add_stream_index(fmt_ctx, prog_id, ffaudio[i]->fidx);
3047 int pi = fmt_ctx->nb_programs;
3048 while( --pi >= 0 && fmt_ctx->programs[pi]->id != prog_id );
3049 AVDictionary **meta = &prog->metadata;
3050 av_dict_set(meta, "service_provider", "cin5", 0);
3051 const char *path = fmt_ctx->url, *bp = strrchr(path,'/');
3052 if( bp ) path = bp + 1;
3053 av_dict_set(meta, "title", path, 0);
3055 if( ffaudio.size() ) {
3056 const char *ep = getenv("CIN_AUDIO_LANG"), *lp = 0;
3057 if( !ep && (lp=getenv("LANG")) ) { // some are guesses
3058 static struct { const char lc[3], lng[4]; } lcode[] = {
3059 { "en", "eng" }, { "de", "ger" }, { "es", "spa" },
3060 { "eu", "bas" }, { "fr", "fre" }, { "el", "gre" },
3061 { "hi", "hin" }, { "it", "ita" }, { "ja", "jap" },
3062 { "ko", "kor" }, { "du", "dut" }, { "pl", "pol" },
3063 { "pt", "por" }, { "ru", "rus" }, { "sl", "slv" },
3064 { "uk", "ukr" }, { "vi", "vie" }, { "zh", "chi" },
3066 for( int i=sizeof(lcode)/sizeof(lcode[0]); --i>=0 && !ep; )
3067 if( !strncmp(lcode[i].lc,lp,2) ) ep = lcode[i].lng;
3069 if( !ep ) ep = "und";
3071 strncpy(lang,ep,3); lang[3] = 0;
3072 AVStream *st = ffaudio[0]->st;
3073 av_dict_set(&st->metadata,"language",lang,0);
3076 AVDictionary *fopts = 0;
3077 char option_path[BCTEXTLEN];
3078 set_option_path(option_path, "format/%s", file_format);
3079 read_options(option_path, fopts, 1);
3080 av_dict_copy(&fopts, opts, 0);
3081 if( scan_options(file_base->asset->ff_format_options, fopts, 0) ) {
3082 eprintf(_("bad format options %s\n"), file_base->asset->path);
3086 ret = avformat_write_header(fmt_ctx, &fopts);
3088 ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
3092 av_dict_free(&fopts);
3099 int FFMPEG::audio_seek(int stream, int64_t pos)
3101 int aidx = astrm_index[stream].st_idx;
3102 FFAudioStream *aud = ffaudio[aidx];
3103 aud->audio_seek(pos);
3107 int FFMPEG::video_seek(int stream, int64_t pos)
3109 int vidx = vstrm_index[stream].st_idx;
3110 FFVideoStream *vid = ffvideo[vidx];
3111 vid->video_seek(pos);
3116 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
3118 if( !has_audio || chn >= astrm_index.size() ) return -1;
3119 int aidx = astrm_index[chn].st_idx;
3120 FFAudioStream *aud = ffaudio[aidx];
3121 if( aud->load(pos, len) < len ) return -1;
3122 int ch = astrm_index[chn].st_ch;
3123 int ret = aud->read(samples,len,ch);
3127 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
3129 if( !has_video || layer >= vstrm_index.size() ) return -1;
3130 int vidx = vstrm_index[layer].st_idx;
3131 FFVideoStream *vid = ffvideo[vidx];
3132 return vid->load(vframe, pos);
3136 int FFMPEG::encode(int stream, double **samples, int len)
3138 FFAudioStream *aud = ffaudio[stream];
3139 return aud->encode(samples, len);
3143 int FFMPEG::encode(int stream, VFrame *frame)
3145 FFVideoStream *vid = ffvideo[stream];
3146 return vid->encode(frame);
3149 void FFMPEG::start_muxer()
3157 void FFMPEG::stop_muxer()
3166 void FFMPEG::flow_off()
3169 flow_lock->lock("FFMPEG::flow_off");
3173 void FFMPEG::flow_on()
3177 flow_lock->unlock();
3180 void FFMPEG::flow_ctl()
3183 flow_lock->lock("FFMPEG::flow_ctl");
3184 flow_lock->unlock();
3188 int FFMPEG::mux_audio(FFrame *frm)
3190 FFStream *fst = frm->fst;
3191 AVCodecContext *ctx = fst->avctx;
3192 AVFrame *frame = *frm;
3193 AVRational tick_rate = {1, ctx->sample_rate};
3194 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
3195 int ret = fst->encode_frame(frame);
3197 ff_err(ret, "FFMPEG::mux_audio");
3198 return ret >= 0 ? 0 : 1;
3201 int FFMPEG::mux_video(FFrame *frm)
3203 FFStream *fst = frm->fst;
3204 AVFrame *frame = *frm;
3205 frame->pts = frm->position;
3206 int ret = fst->encode_frame(frame);
3208 ff_err(ret, "FFMPEG::mux_video");
3209 return ret >= 0 ? 0 : 1;
3215 double atm = -1, vtm = -1;
3216 FFrame *afrm = 0, *vfrm = 0;
3218 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
3219 FFStream *fst = ffaudio[i];
3220 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
3221 FFrame *frm = fst->frms.first;
3222 if( !frm ) { if( !done ) return; continue; }
3223 double tm = to_secs(frm->position, fst->avctx->time_base);
3224 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
3226 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
3227 FFStream *fst = ffvideo[i];
3228 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
3229 FFrame *frm = fst->frms.first;
3230 if( !frm ) { if( !done ) return; continue; }
3231 double tm = to_secs(frm->position, fst->avctx->time_base);
3232 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
3234 if( !demand ) flow_off();
3235 if( !afrm && !vfrm ) break;
3236 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
3237 vfrm->position, vfrm->fst->avctx->time_base,
3238 afrm->position, afrm->fst->avctx->time_base);
3239 FFrame *frm = v <= 0 ? vfrm : afrm;
3240 if( frm == afrm ) mux_audio(frm);
3241 if( frm == vfrm ) mux_video(frm);
3250 mux_lock->lock("FFMPEG::run");
3253 for( int i=0; i<ffaudio.size(); ++i )
3254 ffaudio[i]->drain();
3255 for( int i=0; i<ffvideo.size(); ++i )
3256 ffvideo[i]->drain();
3258 for( int i=0; i<ffaudio.size(); ++i )
3259 ffaudio[i]->flush();
3260 for( int i=0; i<ffvideo.size(); ++i )
3261 ffvideo[i]->flush();
3265 int FFMPEG::ff_total_audio_channels()
3267 return astrm_index.size();
3270 int FFMPEG::ff_total_astreams()
3272 return ffaudio.size();
3275 int FFMPEG::ff_audio_channels(int stream)
3277 return ffaudio[stream]->channels;
3280 int FFMPEG::ff_sample_rate(int stream)
3282 return ffaudio[stream]->sample_rate;
3285 const char* FFMPEG::ff_audio_format(int stream)
3287 AVStream *st = ffaudio[stream]->st;
3288 AVCodecID id = st->codecpar->codec_id;
3289 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
3290 return desc ? desc->name : _("Unknown");
3293 int FFMPEG::ff_audio_pid(int stream)
3295 return ffaudio[stream]->st->id;
3298 int64_t FFMPEG::ff_audio_samples(int stream)
3300 return ffaudio[stream]->length;
3303 // find audio astream/channels with this program,
3304 // or all program audio channels (astream=-1)
3305 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
3309 int vidx = ffvideo[vstream]->fidx;
3310 // find first program with this video stream
3311 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
3312 AVProgram *pgrm = fmt_ctx->programs[i];
3313 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
3314 int st_idx = pgrm->stream_index[j];
3315 AVStream *st = fmt_ctx->streams[st_idx];
3316 if( st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
3317 if( st_idx == vidx ) pidx = i;
3320 if( pidx < 0 ) return -1;
3322 int64_t channels = 0;
3323 AVProgram *pgrm = fmt_ctx->programs[pidx];
3324 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
3325 int aidx = pgrm->stream_index[j];
3326 AVStream *st = fmt_ctx->streams[aidx];
3327 if( st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
3328 if( astream > 0 ) { --astream; continue; }
3330 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
3331 if( ffaudio[i]->fidx == aidx ) astrm = i;
3333 if( ret < 0 ) ret = astrm;
3334 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
3335 channels |= mask << ffaudio[astrm]->channel0;
3337 if( !astream ) break;
3339 channel_mask = channels;
3344 int FFMPEG::ff_total_video_layers()
3346 return vstrm_index.size();
3349 int FFMPEG::ff_total_vstreams()
3351 return ffvideo.size();
3354 int FFMPEG::ff_video_width(int stream)
3356 FFVideoStream *vst = ffvideo[stream];
3357 return !vst->transpose ? vst->width : vst->height;
3360 int FFMPEG::ff_video_height(int stream)
3362 FFVideoStream *vst = ffvideo[stream];
3363 return !vst->transpose ? vst->height : vst->width;
3366 int FFMPEG::ff_set_video_width(int stream, int width)
3368 FFVideoStream *vst = ffvideo[stream];
3369 int *vw = !vst->transpose ? &vst->width : &vst->height, w = *vw;
3374 int FFMPEG::ff_set_video_height(int stream, int height)
3376 FFVideoStream *vst = ffvideo[stream];
3377 int *vh = !vst->transpose ? &vst->height : &vst->width, h = *vh;
3382 int FFMPEG::ff_coded_width(int stream)
3384 return ffvideo[stream]->avctx->coded_width;
3387 int FFMPEG::ff_coded_height(int stream)
3389 return ffvideo[stream]->avctx->coded_height;
3392 float FFMPEG::ff_aspect_ratio(int stream)
3394 return ffvideo[stream]->aspect_ratio;
3397 const char* FFMPEG::ff_video_codec(int stream)
3399 AVStream *st = ffvideo[stream]->st;
3400 AVCodecID id = st->codecpar->codec_id;
3401 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
3402 return desc ? desc->name : _("Unknown");
3405 int FFMPEG::ff_color_range(int stream)
3407 return ffvideo[stream]->color_range;
3410 int FFMPEG::ff_color_space(int stream)
3412 return ffvideo[stream]->color_space;
3415 double FFMPEG::ff_frame_rate(int stream)
3417 return ffvideo[stream]->frame_rate;
3420 int64_t FFMPEG::ff_video_frames(int stream)
3422 return ffvideo[stream]->length;
3425 int FFMPEG::ff_video_pid(int stream)
3427 return ffvideo[stream]->st->id;
3430 int FFMPEG::ff_video_mpeg_color_range(int stream)
3432 return ffvideo[stream]->st->codecpar->color_range == AVCOL_RANGE_MPEG ? 1 : 0;
3435 int FFMPEG::ff_cpus()
3437 return !file_base ? 1 : file_base->file->cpus;
3440 const char *FFMPEG::ff_hw_dev()
3442 return &file_base->file->preferences->use_hw_dev[0];
3445 Preferences *FFMPEG::ff_prefs()
3447 return !file_base ? 0 : file_base->file->preferences;
3450 int FFVideoStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
3452 avfilter_register_all();
3453 const char *sp = filter_spec;
3454 char filter_name[BCSTRLEN], *np = filter_name;
3455 int i = sizeof(filter_name);
3456 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
3458 const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
3459 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_VIDEO ) {
3460 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
3463 filter_graph = avfilter_graph_alloc();
3464 const AVFilter *buffersrc = avfilter_get_by_name("buffer");
3465 const AVFilter *buffersink = avfilter_get_by_name("buffersink");
3466 int sa_num = avpar->sample_aspect_ratio.num;
3467 if( !sa_num ) sa_num = 1;
3468 int sa_den = avpar->sample_aspect_ratio.den;
3469 if( !sa_den ) sa_num = 1;
3471 int ret = 0; char args[BCTEXTLEN];
3472 AVPixelFormat pix_fmt = (AVPixelFormat)avpar->format;
3473 snprintf(args, sizeof(args),
3474 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
3475 avpar->width, avpar->height, (int)pix_fmt,
3476 st->time_base.num, st->time_base.den, sa_num, sa_den);
3478 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
3479 args, NULL, filter_graph);
3481 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
3482 NULL, NULL, filter_graph);
3484 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
3485 (uint8_t*)&pix_fmt, sizeof(pix_fmt),
3486 AV_OPT_SEARCH_CHILDREN);
3488 ff_err(ret, "FFVideoStream::create_filter");
3490 ret = FFStream::create_filter(filter_spec);
3491 return ret >= 0 ? 0 : -1;
3494 int FFAudioStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
3496 avfilter_register_all();
3497 const char *sp = filter_spec;
3498 char filter_name[BCSTRLEN], *np = filter_name;
3499 int i = sizeof(filter_name);
3500 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
3502 const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
3503 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_AUDIO ) {
3504 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
3507 filter_graph = avfilter_graph_alloc();
3508 const AVFilter *buffersrc = avfilter_get_by_name("abuffer");
3509 const AVFilter *buffersink = avfilter_get_by_name("abuffersink");
3510 int ret = 0; char args[BCTEXTLEN];
3511 AVSampleFormat sample_fmt = (AVSampleFormat)avpar->format;
3512 snprintf(args, sizeof(args),
3513 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
3514 st->time_base.num, st->time_base.den, avpar->sample_rate,
3515 av_get_sample_fmt_name(sample_fmt), avpar->channel_layout);
3517 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
3518 args, NULL, filter_graph);
3520 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
3521 NULL, NULL, filter_graph);
3523 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
3524 (uint8_t*)&sample_fmt, sizeof(sample_fmt),
3525 AV_OPT_SEARCH_CHILDREN);
3527 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
3528 (uint8_t*)&avpar->channel_layout,
3529 sizeof(avpar->channel_layout), AV_OPT_SEARCH_CHILDREN);
3531 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
3532 (uint8_t*)&sample_rate, sizeof(sample_rate),
3533 AV_OPT_SEARCH_CHILDREN);
3535 ff_err(ret, "FFAudioStream::create_filter");
3537 ret = FFStream::create_filter(filter_spec);
3538 return ret >= 0 ? 0 : -1;
3541 int FFStream::create_filter(const char *filter_spec)
3543 /* Endpoints for the filter graph. */
3544 AVFilterInOut *outputs = avfilter_inout_alloc();
3545 outputs->name = av_strdup("in");
3546 outputs->filter_ctx = buffersrc_ctx;
3547 outputs->pad_idx = 0;
3550 AVFilterInOut *inputs = avfilter_inout_alloc();
3551 inputs->name = av_strdup("out");
3552 inputs->filter_ctx = buffersink_ctx;
3553 inputs->pad_idx = 0;
3556 int ret = !outputs->name || !inputs->name ? -1 : 0;
3558 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
3559 &inputs, &outputs, NULL);
3561 ret = avfilter_graph_config(filter_graph, NULL);
3564 ff_err(ret, "FFStream::create_filter");
3565 avfilter_graph_free(&filter_graph);
3568 avfilter_inout_free(&inputs);
3569 avfilter_inout_free(&outputs);
3574 AVCodecContext *FFMPEG::activate_decoder(AVStream *st)
3576 AVDictionary *copts = 0;
3577 av_dict_copy(&copts, opts, 0);
3578 AVCodecID codec_id = st->codecpar->codec_id;
3579 AVCodec *decoder = 0;
3580 switch( st->codecpar->codec_type ) {
3581 case AVMEDIA_TYPE_VIDEO:
3582 if( opt_video_decoder )
3583 decoder = avcodec_find_decoder_by_name(opt_video_decoder);
3585 video_codec_remaps.update(codec_id, decoder);
3587 case AVMEDIA_TYPE_AUDIO:
3588 if( opt_audio_decoder )
3589 decoder = avcodec_find_decoder_by_name(opt_audio_decoder);
3591 audio_codec_remaps.update(codec_id, decoder);
3596 if( !decoder && !(decoder = avcodec_find_decoder(codec_id)) ) {
3597 eprintf(_("cant find decoder codec %d\n"), (int)codec_id);
3600 AVCodecContext *avctx = avcodec_alloc_context3(decoder);
3602 eprintf(_("cant allocate codec context\n"));
3605 avcodec_parameters_to_context(avctx, st->codecpar);
3606 if( !av_dict_get(copts, "threads", NULL, 0) )
3607 avctx->thread_count = ff_cpus();
3608 int ret = avcodec_open2(avctx, decoder, &copts);
3609 av_dict_free(&copts);
3611 avcodec_free_context(&avctx);
3617 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
3620 av_init_packet(&pkt);
3621 AVFrame *frame = av_frame_alloc();
3623 fprintf(stderr,"FFMPEG::scan: ");
3624 fprintf(stderr,_("av_frame_alloc failed\n"));
3625 fprintf(stderr,"FFMPEG::scan:file=%s\n", file_base->asset->path);
3629 index_state->add_video_markers(ffvideo.size());
3630 index_state->add_audio_markers(ffaudio.size());
3632 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
3633 AVStream *st = fmt_ctx->streams[i];
3634 AVCodecContext *avctx = activate_decoder(st);
3636 AVCodecParameters *avpar = st->codecpar;
3637 switch( avpar->codec_type ) {
3638 case AVMEDIA_TYPE_VIDEO: {
3639 int vidx = ffvideo.size();
3640 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
3641 if( vidx < 0 ) break;
3642 ffvideo[vidx]->avctx = avctx;
3644 case AVMEDIA_TYPE_AUDIO: {
3645 int aidx = ffaudio.size();
3646 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3647 if( aidx < 0 ) break;
3648 ffaudio[aidx]->avctx = avctx;
3653 fprintf(stderr,"FFMPEG::scan: ");
3654 fprintf(stderr,_("codec open failed\n"));
3655 fprintf(stderr,"FFMPEG::scan:file=%s\n", file_base->asset->path);
3656 avcodec_free_context(&avctx);
3660 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
3661 AVStream *st = fmt_ctx->streams[i];
3662 AVCodecParameters *avpar = st->codecpar;
3663 if( avpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
3664 int64_t tstmp = st->start_time;
3665 if( tstmp == AV_NOPTS_VALUE ) continue;
3666 int aidx = ffaudio.size();
3667 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3668 if( aidx < 0 ) continue;
3669 FFAudioStream *aud = ffaudio[aidx];
3670 tstmp -= aud->nudge;
3671 double secs = to_secs(tstmp, st->time_base);
3672 aud->curr_pos = secs * aud->sample_rate + 0.5;
3676 for( int64_t count=0; !*canceled; ++count ) {
3677 av_packet_unref(&pkt);
3678 pkt.data = 0; pkt.size = 0;
3680 int ret = av_read_frame(fmt_ctx, &pkt);
3682 if( ret == AVERROR_EOF ) break;
3683 if( ++errs > 100 ) {
3684 ff_err(ret,_("over 100 read_frame errs\n"));
3689 if( !pkt.data ) continue;
3690 int i = pkt.stream_index;
3691 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
3692 AVStream *st = fmt_ctx->streams[i];
3693 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
3695 AVCodecParameters *avpar = st->codecpar;
3696 switch( avpar->codec_type ) {
3697 case AVMEDIA_TYPE_VIDEO: {
3698 int vidx = ffvideo.size();
3699 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
3700 if( vidx < 0 ) break;
3701 FFVideoStream *vid = ffvideo[vidx];
3702 if( !vid->avctx ) break;
3703 int64_t tstmp = pkt.pts;
3704 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
3705 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
3706 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
3707 double secs = to_secs(tstmp, st->time_base);
3708 int64_t frm = secs * vid->frame_rate + 0.5;
3709 if( frm < 0 ) frm = 0;
3710 index_state->put_video_mark(vidx, frm, pkt.pos);
3713 ret = avcodec_send_packet(vid->avctx, pkt);
3714 if( ret < 0 ) break;
3715 while( (ret=vid->decode_frame(frame)) > 0 ) {}
3718 case AVMEDIA_TYPE_AUDIO: {
3719 int aidx = ffaudio.size();
3720 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3721 if( aidx < 0 ) break;
3722 FFAudioStream *aud = ffaudio[aidx];
3723 if( !aud->avctx ) break;
3724 int64_t tstmp = pkt.pts;
3725 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
3726 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
3727 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
3728 double secs = to_secs(tstmp, st->time_base);
3729 int64_t sample = secs * aud->sample_rate + 0.5;
3731 index_state->put_audio_mark(aidx, sample, pkt.pos);
3733 ret = avcodec_send_packet(aud->avctx, &pkt);
3734 if( ret < 0 ) break;
3735 int ch = aud->channel0, nch = aud->channels;
3736 int64_t pos = index_state->pos(ch);
3737 if( pos != aud->curr_pos ) {
3738 if( abs(pos-aud->curr_pos) > 1 )
3739 printf("audio%d pad %jd %jd (%jd)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
3740 index_state->pad_data(ch, nch, aud->curr_pos);
3742 while( (ret=aud->decode_frame(frame)) > 0 ) {
3743 //if( frame->channels != nch ) break;
3744 aud->init_swr(frame->channels, frame->format, frame->sample_rate);
3746 int len = aud->get_samples(samples,
3747 &frame->extended_data[0], frame->nb_samples);
3748 pos = aud->curr_pos;
3749 if( (aud->curr_pos += len) >= 0 ) {
3751 samples += -pos * nch;
3752 len = aud->curr_pos;
3754 for( int i=0; i<nch; ++i )
3755 index_state->put_data(ch+i,nch,samples+i,len);
3762 av_frame_free(&frame);
3766 void FFStream::load_markers(IndexMarks &marks, double rate)
3769 int64_t sz = marks.size();
3770 int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
3771 int nb_ent = st->nb_index_entries;
3772 // some formats already have an index
3774 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
3775 int64_t tstmp = ep->timestamp;
3776 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
3777 double secs = ffmpeg->to_secs(tstmp, st->time_base);
3778 int64_t no = secs * rate;
3779 while( in < sz && marks[in].no <= no ) ++in;
3781 int64_t len = sz - in;
3782 int64_t count = max_entries - nb_ent;
3783 if( count > len ) count = len;
3784 for( int i=0; i<count; ++i ) {
3785 int k = in + i * len / count;
3786 int64_t no = marks[k].no, pos = marks[k].pos;
3787 double secs = (double)no / rate;
3788 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
3789 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
3790 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);
3796 * 1) if the format context has a timecode
3797 * return fmt_ctx->timecode - 0
3798 * 2) if the layer/channel has a timecode
3799 * return st->timecode - (start_time-nudge)
3800 * 3) find the 1st program with stream, find 1st program video stream,
3801 * if video stream has a timecode, return st->timecode - (start_time-nudge)
3802 * 4) find timecode in any stream, return st->timecode
3803 * 5) read 100 packets, save ofs=pkt.pts*st->time_base - st->nudge:
3804 * decode frame for video stream of 1st program
3805 * if frame->timecode has a timecode, return frame->timecode - ofs
3806 * if side_data has gop timecode, return gop->timecode - ofs
3807 * if side_data has smpte timecode, return smpte->timecode - ofs
3808 * 6) if the filename/url scans *date_time.ext, return date_time
3809 * 7) if stat works on the filename/url, return mtime
3810 * 8) return -1 failure
3812 double FFMPEG::get_initial_timecode(int data_type, int channel, double frame_rate)
3814 AVRational rate = check_frame_rate(0, frame_rate);
3815 if( !rate.num ) return -1;
3816 // format context timecode
3817 AVDictionaryEntry *tc = av_dict_get(fmt_ctx->metadata, "timecode", 0, 0);
3818 if( tc ) return ff_get_timecode(tc->value, rate, 0);
3820 if( open_decoder() ) return -1;
3823 int codec_type = -1, fidx = -1;
3824 switch( data_type ) {
3826 codec_type = AVMEDIA_TYPE_AUDIO;
3827 int aidx = astrm_index[channel].st_idx;
3828 FFAudioStream *aud = ffaudio[aidx];
3834 codec_type = AVMEDIA_TYPE_VIDEO;
3835 int vidx = vstrm_index[channel].st_idx;
3836 FFVideoStream *vid = ffvideo[vidx];
3842 if( codec_type < 0 ) return -1;
3844 tc = av_dict_get(st->metadata, "timecode", 0, 0);
3847 // find first program which references this stream
3849 for( int i=0, m=fmt_ctx->nb_programs; pidx<0 && i<m; ++i ) {
3850 AVProgram *pgrm = fmt_ctx->programs[i];
3851 for( int j=0, n=pgrm->nb_stream_indexes; j<n; ++j ) {
3852 int st_idx = pgrm->stream_index[j];
3853 if( st_idx == fidx ) { pidx = i; break; }
3858 AVProgram *pgrm = fmt_ctx->programs[pidx];
3859 for( int j=0, n=pgrm->nb_stream_indexes; j<n; ++j ) {
3860 int st_idx = pgrm->stream_index[j];
3861 AVStream *tst = fmt_ctx->streams[st_idx];
3862 if( !tst ) continue;
3863 if( tst->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
3864 st = tst; fidx = st_idx;
3870 for( int i=0, n=fmt_ctx->nb_streams; i<n; ++i ) {
3871 AVStream *tst = fmt_ctx->streams[i];
3872 if( !tst ) continue;
3873 if( tst->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
3880 tc = av_dict_get(st->metadata, "timecode", 0, 0);
3884 // any timecode, includes -data- streams
3885 for( int i=0, n=fmt_ctx->nb_streams; i<n; ++i ) {
3886 AVStream *tst = fmt_ctx->streams[i];
3887 if( !tst ) continue;
3888 if( (tc = av_dict_get(tst->metadata, "timecode", 0, 0)) ) {
3895 if( st && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
3896 if( st->r_frame_rate.num && st->r_frame_rate.den )
3897 rate = st->r_frame_rate;
3898 nudge = st->start_time;
3899 for( int i=0; i<ffvideo.size(); ++i ) {
3900 if( ffvideo[i]->st == st ) {
3901 nudge = ffvideo[i]->nudge;
3907 if( tc ) { // return timecode
3908 double secs = st->start_time == AV_NOPTS_VALUE ? 0 :
3909 to_secs(st->start_time - nudge, st->time_base);
3910 return ff_get_timecode(tc->value, rate, secs);
3913 if( !st || fidx < 0 ) return -1;
3916 AVCodecContext *av_ctx = activate_decoder(st);
3918 fprintf(stderr,"activate_decoder failed\n");
3921 avCodecContext avctx(av_ctx); // auto deletes
3922 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO &&
3923 avctx->framerate.num && avctx->framerate.den )
3924 rate = avctx->framerate;
3926 avPacket pkt; // auto deletes
3927 avFrame frame; // auto deletes
3929 fprintf(stderr,"av_frame_alloc failed\n");
3933 int64_t max_packets = 100;
3934 char tcbuf[AV_TIMECODE_STR_SIZE];
3936 for( int64_t count=0; count<max_packets; ++count ) {
3937 av_packet_unref(pkt);
3938 pkt->data = 0; pkt->size = 0;
3940 int ret = av_read_frame(fmt_ctx, pkt);
3942 if( ret == AVERROR_EOF ) break;
3943 if( ++errs > 100 ) {
3944 fprintf(stderr,"over 100 read_frame errs\n");
3949 if( !pkt->data ) continue;
3950 int i = pkt->stream_index;
3951 if( i != fidx ) continue;
3952 int64_t tstmp = pkt->pts;
3953 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt->dts;
3954 double secs = to_secs(tstmp - nudge, st->time_base);
3955 ret = avcodec_send_packet(avctx, pkt);
3956 if( ret < 0 ) return -1;
3958 while( (ret = avcodec_receive_frame(avctx, frame)) >= 0 ) {
3959 if( (tc = av_dict_get(frame->metadata, "timecode", 0, 0)) )
3960 return ff_get_timecode(tc->value, rate, secs);
3961 int k = frame->nb_side_data;
3962 AVFrameSideData *side_data = 0;
3964 side_data = frame->side_data[k];
3965 switch( side_data->type ) {
3966 case AV_FRAME_DATA_GOP_TIMECODE: {
3967 int64_t data = *(int64_t *)side_data->data;
3968 int sz = sizeof(data);
3969 if( side_data->size >= sz ) {
3970 av_timecode_make_mpeg_tc_string(tcbuf, data);
3971 return ff_get_timecode(tcbuf, rate, secs);
3974 case AV_FRAME_DATA_S12M_TIMECODE: {
3975 uint32_t *data = (uint32_t *)side_data->data;
3976 int n = data[0], sz = (n+1)*sizeof(*data);
3977 if( side_data->size >= sz ) {
3978 av_timecode_make_smpte_tc_string(tcbuf, data[n], 0);
3979 return ff_get_timecode(tcbuf, rate, secs);
3988 char *path = fmt_ctx->url;
3989 char *bp = strrchr(path, '/');
3990 if( !bp ) bp = path; else ++bp;
3991 char *cp = strrchr(bp, '.');
3992 if( cp && (cp-=(8+1+6)) >= bp ) {
3994 int year,mon,day, hour,min,sec, frm=0;
3995 if( sscanf(cp,"%4d%2d%2d%[_-]%2d%2d%2d",
3996 &year,&mon,&day, sep, &hour,&min,&sec) == 7 ) {
3998 // year>=1970,mon=1..12,day=1..31, hour=0..23,min=0..59,sec=0..60
3999 if( (ch=='_' || ch=='-' ) &&
4000 year >= 1970 && mon>=1 && mon<=12 && day>=1 && day<=31 &&
4001 hour>=0 && hour<24 && min>=0 && min<60 && sec>=0 && sec<=60 ) {
4002 sprintf(tcbuf,"%d:%02d:%02d:%02d", hour,min,sec, frm);
4003 return ff_get_timecode(tcbuf, rate, 0);
4008 if( stat(path, &tst) >= 0 ) {
4009 time_t t = (time_t)tst.st_mtim.tv_sec;
4011 localtime_r(&t, &tm);
4012 int64_t us = tst.st_mtim.tv_nsec / 1000;
4013 int frm = us/1000000. * frame_rate;
4014 sprintf(tcbuf,"%d:%02d:%02d:%02d", tm.tm_hour, tm.tm_min, tm.tm_sec, frm);
4015 return ff_get_timecode(tcbuf, rate, 0);
4020 double FFMPEG::ff_get_timecode(char *str, AVRational rate, double pos)
4023 if( av_timecode_init_from_string(&tc, rate, str, fmt_ctx) )
4025 double secs = (double)tc.start / tc.fps - pos;
4026 if( secs < 0 ) secs = 0;
4030 double FFMPEG::get_timecode(const char *path, int data_type, int channel, double rate)
4033 if( ffmpeg.init_decoder(path) ) return -1;
4034 return ffmpeg.get_initial_timecode(data_type, channel, rate);