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;
285 FFStream::~FFStream()
287 if( reading > 0 || writing > 0 ) avcodec_close(avctx);
288 if( avctx ) avcodec_free_context(&avctx);
289 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
290 if( hw_device_ctx ) av_buffer_unref(&hw_device_ctx);
291 if( bsfc ) av_bsf_free(&bsfc);
292 while( frms.first ) frms.remove(frms.first);
293 if( filter_graph ) avfilter_graph_free(&filter_graph);
294 if( frame ) av_frame_free(&frame);
295 if( fframe ) av_frame_free(&fframe);
297 if( stats_fp ) fclose(stats_fp);
298 if( stats_in ) av_freep(&stats_in);
299 delete [] stats_filename;
302 void FFStream::ff_lock(const char *cp)
304 FFMPEG::fflock.lock(cp);
307 void FFStream::ff_unlock()
309 FFMPEG::fflock.unlock();
312 void FFStream::queue(FFrame *frm)
314 frm_lock->lock("FFStream::queue");
318 ffmpeg->mux_lock->unlock();
321 void FFStream::dequeue(FFrame *frm)
323 frm_lock->lock("FFStream::dequeue");
325 frms.remove_pointer(frm);
329 int FFStream::encode_activate()
332 writing = ffmpeg->encode_activate();
336 // this is a global parameter that really should be in the context
337 static AVPixelFormat hw_pix_fmt = AV_PIX_FMT_NONE; // protected by ff_lock
339 // goofy maneuver to attach a hw_format to an av_context
340 #define GET_HW_PIXFMT(fn, fmt) \
341 static AVPixelFormat get_hw_##fn(AVCodecContext *ctx, const enum AVPixelFormat *pix_fmts) { \
344 GET_HW_PIXFMT(vaapi, AV_PIX_FMT_VAAPI)
345 GET_HW_PIXFMT(vdpau, AV_PIX_FMT_VDPAU)
346 GET_HW_PIXFMT(cuda, AV_PIX_FMT_CUDA)
347 GET_HW_PIXFMT(nv12, AV_PIX_FMT_NV12)
349 static enum AVPixelFormat get_hw_format(AVCodecContext *ctx,
350 const enum AVPixelFormat *pix_fmts)
352 for( const enum AVPixelFormat *p=pix_fmts; *p!=AV_PIX_FMT_NONE; ++p ) {
353 if( *p != hw_pix_fmt ) continue;
355 case AV_PIX_FMT_VAAPI: ctx->get_format = get_hw_vaapi; return *p;
356 case AV_PIX_FMT_VDPAU: ctx->get_format = get_hw_vdpau; return *p;
357 case AV_PIX_FMT_CUDA: ctx->get_format = get_hw_cuda; return *p;
358 case AV_PIX_FMT_NV12: ctx->get_format = get_hw_nv12; return *p;
360 fprintf(stderr, "Unknown HW surface format: %s\n",
361 av_get_pix_fmt_name(*p));
365 fprintf(stderr, "Failed to get HW surface format.\n");
366 return hw_pix_fmt = AV_PIX_FMT_NONE;
370 AVHWDeviceType FFStream::decode_hw_activate()
372 return AV_HWDEVICE_TYPE_NONE;
375 int FFStream::decode_hw_format(AVCodec *decoder, AVHWDeviceType type)
380 int FFStream::decode_activate()
382 if( reading < 0 && (reading=ffmpeg->decode_activate()) > 0 ) {
383 ff_lock("FFStream::decode_activate");
385 AVDictionary *copts = 0;
386 av_dict_copy(&copts, ffmpeg->opts, 0);
388 AVHWDeviceType hw_type = decode_hw_activate();
390 // this should be avformat_copy_context(), but no copy avail
391 ret = avformat_open_input(&fmt_ctx,
392 ffmpeg->fmt_ctx->url, ffmpeg->fmt_ctx->iformat, &copts);
394 ret = avformat_find_stream_info(fmt_ctx, 0);
395 st = fmt_ctx->streams[fidx];
398 while( ret >= 0 && st != 0 && !reading ) {
399 AVCodecID codec_id = st->codecpar->codec_id;
400 AVCodec *decoder = 0;
402 if( ffmpeg->opt_video_decoder )
403 decoder = avcodec_find_decoder_by_name(ffmpeg->opt_video_decoder);
405 ffmpeg->video_codec_remaps.update(codec_id, decoder);
407 else if( is_audio() ) {
408 if( ffmpeg->opt_audio_decoder )
409 decoder = avcodec_find_decoder_by_name(ffmpeg->opt_audio_decoder);
411 ffmpeg->audio_codec_remaps.update(codec_id, decoder);
414 decoder = avcodec_find_decoder(codec_id);
415 avctx = avcodec_alloc_context3(decoder);
417 eprintf(_("cant allocate codec context\n"));
418 ret = AVERROR(ENOMEM);
420 if( ret >= 0 && hw_type != AV_HWDEVICE_TYPE_NONE ) {
421 ret = decode_hw_format(decoder, hw_type);
422 if( !ret ) hw_type = AV_HWDEVICE_TYPE_NONE;
425 avcodec_parameters_to_context(avctx, st->codecpar);
426 if( !av_dict_get(copts, "threads", NULL, 0) )
427 avctx->thread_count = ffmpeg->ff_cpus();
428 ret = avcodec_open2(avctx, decoder, &copts);
430 if( ret >= 0 && hw_type != AV_HWDEVICE_TYPE_NONE ) {
436 AVPacket *pkt = (AVPacket*)ipkt;
437 ret = avcodec_send_packet(avctx, pkt);
438 if( ret < 0 || hw_pix_fmt == AV_PIX_FMT_NONE ) {
439 ff_err(ret, "HW device init failed, using SW decode.\nfile:%s\n",
440 ffmpeg->fmt_ctx->url);
441 avcodec_close(avctx);
442 avcodec_free_context(&avctx);
443 av_buffer_unref(&hw_device_ctx);
445 hw_type = AV_HWDEVICE_TYPE_NONE;
446 int flags = AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_ANY;
448 av_seek_frame(fmt_ctx, idx, INT64_MIN, flags);
449 need_packet = 1; flushed = 0;
450 seeked = 1; st_eof(0);
460 eprintf(_("open decoder failed\n"));
463 eprintf(_("can't open input file: %s\n"), ffmpeg->fmt_ctx->url);
464 av_dict_free(&copts);
470 int FFStream::read_packet()
472 av_packet_unref(ipkt);
473 int ret = av_read_frame(fmt_ctx, ipkt);
476 if( ret == AVERROR_EOF ) return 0;
477 ff_err(ret, "FFStream::read_packet: av_read_frame failed\n");
484 int FFStream::decode(AVFrame *frame)
487 int retries = MAX_RETRY;
489 while( ret >= 0 && !flushed && --retries >= 0 ) {
491 if( (ret=read_packet()) < 0 ) break;
492 AVPacket *pkt = ret > 0 ? (AVPacket*)ipkt : 0;
494 if( pkt->stream_index != st->index ) continue;
495 if( !pkt->data || !pkt->size ) continue;
497 if( (ret=avcodec_send_packet(avctx, pkt)) < 0 ) {
498 ff_err(ret, "FFStream::decode: avcodec_send_packet failed.\nfile:%s\n",
499 ffmpeg->fmt_ctx->url);
505 if( (ret=decode_frame(frame)) > 0 ) break;
513 fprintf(stderr, "FFStream::decode: Retry limit\n");
517 fprintf(stderr, "FFStream::decode: failed\n");
521 int FFStream::load_filter(AVFrame *frame)
523 int ret = av_buffersrc_add_frame_flags(buffersrc_ctx, frame, 0);
525 eprintf(_("av_buffersrc_add_frame_flags failed\n"));
529 int FFStream::read_filter(AVFrame *frame)
531 int ret = av_buffersink_get_frame(buffersink_ctx, frame);
533 if( ret == AVERROR(EAGAIN) ) return 0;
534 if( ret == AVERROR_EOF ) { st_eof(1); return -1; }
535 ff_err(ret, "FFStream::read_filter: av_buffersink_get_frame failed\n");
541 int FFStream::read_frame(AVFrame *frame)
543 av_frame_unref(frame);
544 if( !filter_graph || !buffersrc_ctx || !buffersink_ctx )
545 return decode(frame);
546 if( !fframe && !(fframe=av_frame_alloc()) ) {
547 fprintf(stderr, "FFStream::read_frame: av_frame_alloc failed\n");
551 while( !flushed && !(ret=read_filter(frame)) ) {
552 if( (ret=decode(fframe)) < 0 ) break;
553 if( ret > 0 && (ret=load_filter(fframe)) < 0 ) break;
558 int FFStream::write_packet(FFPacket &pkt)
562 av_packet_rescale_ts(pkt, avctx->time_base, st->time_base);
563 pkt->stream_index = st->index;
564 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, pkt);
567 ret = av_bsf_send_packet(bsfc, pkt);
570 if( (ret=av_bsf_receive_packet(bsfc, bs)) < 0 ) {
571 if( ret == AVERROR(EAGAIN) ) return 0;
572 if( ret == AVERROR_EOF ) return -1;
575 av_packet_rescale_ts(bs, avctx->time_base, st->time_base);
576 bs->stream_index = st->index;
577 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, bs);
581 ff_err(ret, "FFStream::write_packet: write packet failed.\nfile:%s\n",
582 ffmpeg->fmt_ctx->url);
586 int FFStream::encode_frame(AVFrame *frame)
588 int pkts = 0, ret = 0;
589 for( int retry=MAX_RETRY; --retry>=0; ) {
591 ret = avcodec_send_frame(avctx, frame);
592 if( !ret && frame ) return pkts;
593 if( ret < 0 && ret != AVERROR(EAGAIN) ) break;
595 ret = avcodec_receive_packet(avctx, opkt);
596 if( !frame && ret == AVERROR_EOF ) return pkts;
598 ret = write_packet(opkt);
601 if( frame && stats_fp ) {
602 ret = write_stats_file();
606 ff_err(ret, "FFStream::encode_frame: encode failed.\nfile: %s\n",
607 ffmpeg->fmt_ctx->url);
611 int FFStream::flush()
615 int ret = encode_frame(0);
616 if( ret >= 0 && stats_fp ) {
617 ret = write_stats_file();
621 ff_err(ret, "FFStream::flush failed\n:file:%s\n",
622 ffmpeg->fmt_ctx->url);
623 return ret >= 0 ? 0 : 1;
627 int FFStream::open_stats_file()
629 stats_fp = fopen(stats_filename,"w");
630 return stats_fp ? 0 : AVERROR(errno);
633 int FFStream::close_stats_file()
636 fclose(stats_fp); stats_fp = 0;
641 int FFStream::read_stats_file()
643 int64_t len = 0; struct stat stats_st;
644 int fd = open(stats_filename, O_RDONLY);
645 int ret = fd >= 0 ? 0: ENOENT;
646 if( !ret && fstat(fd, &stats_st) )
649 len = stats_st.st_size;
650 stats_in = (char *)av_malloc(len+1);
654 if( !ret && read(fd, stats_in, len+1) != len )
658 avctx->stats_in = stats_in;
662 return !ret ? 0 : AVERROR(ret);
665 int FFStream::write_stats_file()
668 if( avctx->stats_out && (ret=strlen(avctx->stats_out)) > 0 ) {
669 int len = fwrite(avctx->stats_out, 1, ret, stats_fp);
671 ff_err(ret = AVERROR(errno), "FFStream::write_stats_file.\n%file:%s\n",
672 ffmpeg->fmt_ctx->url);
677 int FFStream::init_stats_file()
680 if( (pass & 2) && (ret = read_stats_file()) < 0 )
681 ff_err(ret, "stat file read: %s", stats_filename);
682 if( (pass & 1) && (ret=open_stats_file()) < 0 )
683 ff_err(ret, "stat file open: %s", stats_filename);
684 return ret >= 0 ? 0 : ret;
687 int FFStream::seek(int64_t no, double rate)
689 // default ffmpeg native seek
691 int64_t pos = no, pkt_pos = -1;
692 IndexMarks *index_markers = get_markers();
693 if( index_markers && index_markers->size() > 1 ) {
694 IndexMarks &marks = *index_markers;
695 int i = marks.find(pos);
696 int64_t n = i < 0 ? (i=0) : marks[i].no;
697 // if indexed seek point not too far away (<30 secs), use index
698 if( no-n < 30*rate ) {
701 if( i < marks.size() ) pkt_pos = marks[i].pos;
705 if( pos == curr_pos ) return 0;
706 double secs = pos < 0 ? 0. : pos / rate;
707 AVRational time_base = st->time_base;
708 int64_t tstmp = time_base.num > 0 ? secs * time_base.den/time_base.num : 0;
710 if( st->nb_index_entries > 0 ) tstmp = st->index_entries[0].timestamp;
711 else if( st->start_time != AV_NOPTS_VALUE ) tstmp = st->start_time;
712 else if( st->first_dts != AV_NOPTS_VALUE ) tstmp = st->first_dts;
713 else tstmp = INT64_MIN+1;
715 else if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
718 // seek all streams using the default timebase.
719 // this is how ffmpeg and ffplay work. stream seeks are less tested.
720 tstmp = av_rescale_q(tstmp, time_base, AV_TIME_BASE_Q);
724 avcodec_flush_buffers(avctx);
725 avformat_flush(fmt_ctx);
727 int64_t seek = tstmp;
728 int flags = AVSEEK_FLAG_ANY;
729 if( !(fmt_ctx->iformat->flags & AVFMT_NO_BYTE_SEEK) && pkt_pos >= 0 ) {
731 flags = AVSEEK_FLAG_BYTE;
733 int ret = avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, seek, INT64_MAX, flags);
735 // finds the first index frame below the target time
736 int flags = AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_ANY;
737 int ret = av_seek_frame(fmt_ctx, idx, tstmp, flags);
739 int retry = MAX_RETRY;
741 need_packet = 0; flushed = 0;
742 seeked = 1; st_eof(0);
743 // read up to retry packets, limited to npkts in stream, and not pkt.pos past pkt_pos
744 while( --retry >= 0 ) {
745 if( read_packet() <= 0 ) { ret = -1; break; }
746 if( ipkt->stream_index != st->index ) continue;
747 if( !ipkt->data || !ipkt->size ) continue;
748 if( pkt_pos >= 0 && ipkt->pos >= pkt_pos ) break;
749 if( --npkts <= 0 ) break;
750 int64_t pkt_ts = ipkt->dts != AV_NOPTS_VALUE ? ipkt->dts : ipkt->pts;
751 if( pkt_ts == AV_NOPTS_VALUE ) continue;
752 if( pkt_ts >= tstmp ) break;
755 fprintf(stderr,"FFStream::seek: retry limit, pos=%jd tstmp=%jd\n",pos,tstmp);
759 ret = avcodec_send_packet(avctx, ipkt);
761 //some codecs need more than one pkt to resync
762 if( ret == AVERROR_INVALIDDATA ) ret = 0;
764 ff_err(ret, "FFStream::avcodec_send_packet failed.\nseek:%s\n",
765 ffmpeg->fmt_ctx->url);
770 printf("** seek fail %jd, %jd\n", pos, tstmp);
771 seeked = need_packet = 0;
775 //printf("seeked pos = %ld, %ld\n", pos, tstmp);
776 seek_pos = curr_pos = pos;
780 FFAudioStream::FFAudioStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
781 : FFStream(ffmpeg, strm, fidx)
784 channel0 = channels = 0;
787 frame_sz = AUDIO_MIN_FRAME_SZ;
789 resample_context = 0;
790 swr_ichs = swr_ifmt = swr_irate = 0;
799 bfr = new float[bsz];
804 FFAudioStream::~FFAudioStream()
806 if( resample_context ) swr_free(&resample_context);
811 void FFAudioStream::init_swr(int ichs, int ifmt, int irate)
813 if( resample_context ) {
814 if( swr_ichs == ichs && swr_ifmt == ifmt && swr_irate == irate )
816 swr_free(&resample_context);
818 swr_ichs = ichs; swr_ifmt = ifmt; swr_irate = irate;
819 if( ichs == channels && ifmt == AV_SAMPLE_FMT_FLT && irate == sample_rate )
821 uint64_t ilayout = av_get_default_channel_layout(ichs);
822 if( !ilayout ) ilayout = ((uint64_t)1<<ichs) - 1;
823 uint64_t olayout = av_get_default_channel_layout(channels);
824 if( !olayout ) olayout = ((uint64_t)1<<channels) - 1;
825 resample_context = swr_alloc_set_opts(NULL,
826 olayout, AV_SAMPLE_FMT_FLT, sample_rate,
827 ilayout, (AVSampleFormat)ifmt, irate,
829 if( resample_context )
830 swr_init(resample_context);
833 int FFAudioStream::get_samples(float *&samples, uint8_t **data, int len)
835 samples = *(float **)data;
836 if( resample_context ) {
837 if( len > aud_bfr_sz ) {
843 aud_bfr = new float[aud_bfr_sz*channels];
845 int ret = swr_convert(resample_context,
846 (uint8_t**)&aud_bfr, aud_bfr_sz, (const uint8_t**)data, len);
848 ff_err(ret, "FFAudioStream::get_samples: swr_convert failed\n");
857 int FFAudioStream::load_history(uint8_t **data, int len)
860 len = get_samples(samples, data, len);
862 // biggest user bfr since seek + frame
863 realloc(mbsz + len + 1, channels);
869 int FFAudioStream::decode_frame(AVFrame *frame)
871 int first_frame = seeked; seeked = 0;
872 frame->best_effort_timestamp = AV_NOPTS_VALUE;
873 int ret = avcodec_receive_frame(avctx, frame);
875 if( first_frame ) return 0;
876 if( ret == AVERROR(EAGAIN) ) return 0;
877 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
878 ff_err(ret, "FFAudioStream::decode_frame: Could not read audio frame.\nfile:%s\n",
879 ffmpeg->fmt_ctx->url);
882 int64_t pkt_ts = frame->best_effort_timestamp;
883 if( pkt_ts != AV_NOPTS_VALUE ) {
884 double ts = ffmpeg->to_secs(pkt_ts - nudge, st->time_base);
885 double t = (double)curr_pos / sample_rate;
886 // some time_base clocks are very grainy, too grainy for audio (clicks, pops)
887 if( fabs(ts - t) > AUDIO_PTS_TOLERANCE )
888 curr_pos = ts * sample_rate + 0.5;
893 int FFAudioStream::encode_activate()
895 if( writing >= 0 ) return writing;
896 if( !avctx->codec ) return writing = 0;
897 frame_sz = avctx->codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE ?
898 10000 : avctx->frame_size;
899 return FFStream::encode_activate();
902 int64_t FFAudioStream::load_buffer(double ** const sp, int len)
904 reserve(len+1, st->codecpar->channels);
905 for( int ch=0; ch<nch; ++ch )
906 write(sp[ch], len, ch);
910 int FFAudioStream::in_history(int64_t pos)
912 if( pos > curr_pos ) return 0;
914 if( len > sz ) len = sz;
915 if( pos < curr_pos - len ) return 0;
920 int FFAudioStream::init_frame(AVFrame *frame)
922 frame->nb_samples = frame_sz;
923 frame->format = avctx->sample_fmt;
924 frame->channel_layout = avctx->channel_layout;
925 frame->sample_rate = avctx->sample_rate;
926 int ret = av_frame_get_buffer(frame, 0);
928 ff_err(ret, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
932 int FFAudioStream::load(int64_t pos, int len)
934 if( audio_seek(pos) < 0 ) return -1;
935 if( !frame && !(frame=av_frame_alloc()) ) {
936 fprintf(stderr, "FFAudioStream::load: av_frame_alloc failed\n");
939 if( mbsz < len ) mbsz = len;
940 int64_t end_pos = pos + len;
941 int ret = 0, i = len / frame_sz + MAX_RETRY;
942 while( ret>=0 && !flushed && curr_pos<end_pos && --i>=0 ) {
943 ret = read_frame(frame);
944 if( ret > 0 && frame->nb_samples > 0 ) {
945 init_swr(frame->channels, frame->format, frame->sample_rate);
946 load_history(&frame->extended_data[0], frame->nb_samples);
947 curr_pos += frame->nb_samples;
950 if( end_pos > curr_pos ) {
951 zero(end_pos - curr_pos);
954 len = curr_pos - pos;
959 int FFAudioStream::audio_seek(int64_t pos)
961 if( decode_activate() <= 0 ) return -1;
962 if( !st->codecpar ) return -1;
963 if( in_history(pos) ) return 0;
964 if( pos == curr_pos ) return 0;
965 reset_history(); mbsz = 0;
966 // guarentee preload > 1sec samples
967 if( (pos-=sample_rate) < 0 ) pos = 0;
968 if( seek(pos, sample_rate) < 0 ) return -1;
972 int FFAudioStream::encode(double **samples, int len)
974 if( encode_activate() <= 0 ) return -1;
977 int64_t count = samples ? load_buffer(samples, len) : used();
978 int frame_sz1 = samples ? frame_sz-1 : 0;
981 while( ret >= 0 && count > frame_sz1 ) {
982 frm = new FFrame(this);
983 if( (ret=frm->initted()) < 0 ) break;
984 AVFrame *frame = *frm;
985 len = count >= frame_sz ? frame_sz : count;
986 float *bfrp = get_outp(len);
987 ret = swr_convert(resample_context,
988 (uint8_t **)frame->extended_data, len,
989 (const uint8_t **)&bfrp, len);
991 ff_err(ret, "FFAudioStream::encode: swr_convert failed\n");
994 frame->nb_samples = len;
995 frm->queue(curr_pos);
1002 return ret >= 0 ? 0 : 1;
1005 int FFAudioStream::drain()
1010 int FFAudioStream::encode_frame(AVFrame *frame)
1012 return FFStream::encode_frame(frame);
1015 int FFAudioStream::write_packet(FFPacket &pkt)
1017 return FFStream::write_packet(pkt);
1020 void FFAudioStream::load_markers()
1022 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1023 if( !index_state || idx >= index_state->audio_markers.size() ) return;
1024 if( index_state->marker_status == MARKERS_NOTTESTED ) return;
1025 FFStream::load_markers(*index_state->audio_markers[idx], sample_rate);
1028 IndexMarks *FFAudioStream::get_markers()
1030 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1031 if( !index_state || idx >= index_state->audio_markers.size() ) return 0;
1032 return index_state->audio_markers[idx];
1035 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
1036 : FFStream(ffmpeg, strm, fidx),
1037 FFVideoConvert(ffmpeg->ff_prefs())
1045 top_field_first = 0;
1048 FFVideoStream::~FFVideoStream()
1052 AVHWDeviceType FFVideoStream::decode_hw_activate()
1054 AVHWDeviceType type = AV_HWDEVICE_TYPE_NONE;
1055 const char *hw_dev = ffmpeg->opt_hw_dev;
1056 if( !hw_dev ) hw_dev = getenv("CIN_HW_DEV");
1057 if( !hw_dev ) hw_dev = ffmpeg->ff_hw_dev();
1058 if( hw_dev && *hw_dev &&
1059 strcmp("none", hw_dev) && strcmp(_("none"), hw_dev) ) {
1060 type = av_hwdevice_find_type_by_name(hw_dev);
1061 if( type == AV_HWDEVICE_TYPE_NONE ) {
1062 fprintf(stderr, "Device type %s is not supported.\n", hw_dev);
1063 fprintf(stderr, "Available device types:");
1064 while( (type = av_hwdevice_iterate_types(type)) != AV_HWDEVICE_TYPE_NONE )
1065 fprintf(stderr, " %s", av_hwdevice_get_type_name(type));
1066 fprintf(stderr, "\n");
1072 int FFVideoStream::decode_hw_format(AVCodec *decoder, AVHWDeviceType type)
1075 hw_pix_fmt = AV_PIX_FMT_NONE;
1076 for( int i=0; ; ++i ) {
1077 const AVCodecHWConfig *config = avcodec_get_hw_config(decoder, i);
1079 fprintf(stderr, "Decoder %s does not support device type %s.\n",
1080 decoder->name, av_hwdevice_get_type_name(type));
1083 if( (config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX) != 0 &&
1084 config->device_type == type ) {
1085 hw_pix_fmt = config->pix_fmt;
1089 if( hw_pix_fmt >= 0 ) {
1090 hw_pixfmt = hw_pix_fmt;
1091 avctx->get_format = get_hw_format;
1092 ret = av_hwdevice_ctx_create(&hw_device_ctx, type, 0, 0, 0);
1094 avctx->hw_device_ctx = av_buffer_ref(hw_device_ctx);
1098 ff_err(ret, "Failed HW device create.\ndev:%s\n",
1099 av_hwdevice_get_type_name(type));
1104 AVHWDeviceType FFVideoStream::encode_hw_activate(const char *hw_dev)
1106 AVBufferRef *hw_device_ctx = 0;
1107 AVBufferRef *hw_frames_ref = 0;
1108 AVHWDeviceType type = AV_HWDEVICE_TYPE_NONE;
1109 if( strcmp(_("none"), hw_dev) ) {
1110 type = av_hwdevice_find_type_by_name(hw_dev);
1111 if( type != AV_HWDEVICE_TYPE_VAAPI ) {
1112 fprintf(stderr, "currently, only vaapi hw encode is supported\n");
1113 type = AV_HWDEVICE_TYPE_NONE;
1116 if( type != AV_HWDEVICE_TYPE_NONE ) {
1117 int ret = av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_VAAPI, 0, 0, 0);
1119 ff_err(ret, "Failed to create a HW device.\n");
1120 type = AV_HWDEVICE_TYPE_NONE;
1123 if( type != AV_HWDEVICE_TYPE_NONE ) {
1124 hw_frames_ref = av_hwframe_ctx_alloc(hw_device_ctx);
1125 if( !hw_frames_ref ) {
1126 fprintf(stderr, "Failed to create HW frame context.\n");
1127 type = AV_HWDEVICE_TYPE_NONE;
1130 if( type != AV_HWDEVICE_TYPE_NONE ) {
1131 AVHWFramesContext *frames_ctx = (AVHWFramesContext *)(hw_frames_ref->data);
1132 frames_ctx->format = AV_PIX_FMT_VAAPI;
1133 frames_ctx->sw_format = AV_PIX_FMT_NV12;
1134 frames_ctx->width = width;
1135 frames_ctx->height = height;
1136 frames_ctx->initial_pool_size = 0; // 200;
1137 int ret = av_hwframe_ctx_init(hw_frames_ref);
1139 avctx->hw_frames_ctx = av_buffer_ref(hw_frames_ref);
1140 if( !avctx->hw_frames_ctx ) ret = AVERROR(ENOMEM);
1143 ff_err(ret, "Failed to initialize HW frame context.\n");
1144 type = AV_HWDEVICE_TYPE_NONE;
1146 av_buffer_unref(&hw_frames_ref);
1151 int FFVideoStream::encode_hw_write(FFrame *picture)
1154 AVFrame *hw_frm = 0;
1155 switch( avctx->pix_fmt ) {
1156 case AV_PIX_FMT_VAAPI:
1157 hw_frm = av_frame_alloc();
1158 if( !hw_frm ) { ret = AVERROR(ENOMEM); break; }
1159 ret = av_hwframe_get_buffer(avctx->hw_frames_ctx, hw_frm, 0);
1160 if( ret < 0 ) break;
1161 ret = av_hwframe_transfer_data(hw_frm, *picture, 0);
1162 if( ret < 0 ) break;
1163 picture->set_hw_frame(hw_frm);
1168 av_frame_free(&hw_frm);
1169 ff_err(ret, "Error while transferring frame data to GPU.\n");
1173 int FFVideoStream::decode_frame(AVFrame *frame)
1175 int first_frame = seeked; seeked = 0;
1176 int ret = avcodec_receive_frame(avctx, frame);
1178 if( first_frame ) return 0;
1179 if( ret == AVERROR(EAGAIN) ) return 0;
1180 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
1181 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame.\nfile:%s\n,",
1182 ffmpeg->fmt_ctx->url);
1185 int64_t pkt_ts = frame->best_effort_timestamp;
1186 if( pkt_ts != AV_NOPTS_VALUE )
1187 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * frame_rate + 0.5;
1191 int FFVideoStream::load(VFrame *vframe, int64_t pos)
1193 int ret = video_seek(pos);
1194 if( ret < 0 ) return -1;
1195 if( !frame && !(frame=av_frame_alloc()) ) {
1196 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
1199 int i = MAX_RETRY + pos - curr_pos;
1200 while( ret>=0 && !flushed && curr_pos<=pos && --i>=0 ) {
1201 ret = read_frame(frame);
1202 if( ret > 0 ) ++curr_pos;
1204 if( frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0 )
1207 ret = convert_cmodel(vframe, frame);
1209 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
1213 int FFVideoStream::video_seek(int64_t pos)
1215 if( decode_activate() <= 0 ) return -1;
1216 if( !st->codecpar ) return -1;
1217 if( pos == curr_pos-1 && !seeked ) return 0;
1218 // if close enough, just read up to current
1219 int gop = avctx->gop_size;
1220 if( gop < 4 ) gop = 4;
1221 if( gop > 64 ) gop = 64;
1222 int read_limit = curr_pos + 3*gop;
1223 if( pos >= curr_pos && pos <= read_limit ) return 0;
1224 // guarentee preload more than 2*gop frames
1225 if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
1229 int FFVideoStream::init_frame(AVFrame *picture)
1231 switch( avctx->pix_fmt ) {
1232 case AV_PIX_FMT_VAAPI:
1233 picture->format = AV_PIX_FMT_NV12;
1236 picture->format = avctx->pix_fmt;
1239 picture->width = avctx->width;
1240 picture->height = avctx->height;
1241 int ret = av_frame_get_buffer(picture, 32);
1245 int FFVideoStream::encode(VFrame *vframe)
1247 if( encode_activate() <= 0 ) return -1;
1249 FFrame *picture = new FFrame(this);
1250 int ret = picture->initted();
1252 AVFrame *frame = *picture;
1253 frame->pts = curr_pos;
1254 ret = convert_pixfmt(vframe, frame);
1256 if( ret >= 0 && avctx->hw_frames_ctx )
1257 encode_hw_write(picture);
1259 picture->queue(curr_pos);
1263 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
1266 return ret >= 0 ? 0 : 1;
1269 int FFVideoStream::drain()
1274 int FFVideoStream::encode_frame(AVFrame *frame)
1277 frame->interlaced_frame = interlaced;
1278 frame->top_field_first = top_field_first;
1280 if( frame && frame->format == AV_PIX_FMT_VAAPI ) { // ugly
1281 int ret = avcodec_send_frame(avctx, frame);
1282 for( int retry=MAX_RETRY; !ret && --retry>=0; ) {
1283 FFPacket pkt; av_init_packet(pkt);
1284 pkt->data = NULL; pkt->size = 0;
1285 if( (ret=avcodec_receive_packet(avctx, pkt)) < 0 ) {
1286 if( ret == AVERROR(EAGAIN) ) ret = 0; // weird
1289 ret = write_packet(pkt);
1290 pkt->stream_index = 0;
1291 av_packet_unref(pkt);
1294 ff_err(ret, "FFStream::encode_frame: vaapi encode failed.\nfile: %s\n",
1295 ffmpeg->fmt_ctx->url);
1300 return FFStream::encode_frame(frame);
1303 int FFVideoStream::write_packet(FFPacket &pkt)
1305 if( !(ffmpeg->fmt_ctx->oformat->flags & AVFMT_VARIABLE_FPS) )
1307 return FFStream::write_packet(pkt);
1310 AVPixelFormat FFVideoConvert::color_model_to_pix_fmt(int color_model)
1312 switch( color_model ) {
1313 case BC_YUV422: return AV_PIX_FMT_YUYV422;
1314 case BC_RGB888: return AV_PIX_FMT_RGB24;
1315 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
1316 case BC_BGR8888: return AV_PIX_FMT_BGR0;
1317 case BC_BGR888: return AV_PIX_FMT_BGR24;
1318 case BC_ARGB8888: return AV_PIX_FMT_ARGB;
1319 case BC_ABGR8888: return AV_PIX_FMT_ABGR;
1320 case BC_RGB8: return AV_PIX_FMT_RGB8;
1321 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
1322 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
1323 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
1324 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
1325 case BC_RGB565: return AV_PIX_FMT_RGB565;
1326 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
1327 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
1328 case BC_AYUV16161616: return AV_PIX_FMT_AYUV64LE;
1329 case BC_GBRP: return AV_PIX_FMT_GBRP;
1333 return AV_PIX_FMT_NB;
1336 int FFVideoConvert::pix_fmt_to_color_model(AVPixelFormat pix_fmt)
1339 case AV_PIX_FMT_YUYV422: return BC_YUV422;
1340 case AV_PIX_FMT_RGB24: return BC_RGB888;
1341 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
1342 case AV_PIX_FMT_BGR0: return BC_BGR8888;
1343 case AV_PIX_FMT_BGR24: return BC_BGR888;
1344 case AV_PIX_FMT_ARGB: return BC_ARGB8888;
1345 case AV_PIX_FMT_ABGR: return BC_ABGR8888;
1346 case AV_PIX_FMT_RGB8: return BC_RGB8;
1347 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
1348 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
1349 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
1350 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
1351 case AV_PIX_FMT_RGB565: return BC_RGB565;
1352 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
1353 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
1354 case AV_PIX_FMT_AYUV64LE: return BC_AYUV16161616;
1355 case AV_PIX_FMT_GBRP: return BC_GBRP;
1362 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip)
1364 AVFrame *ipic = av_frame_alloc();
1365 int ret = convert_picture_vframe(frame, ip, ipic);
1366 av_frame_free(&ipic);
1370 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip, AVFrame *ipic)
1371 { // picture = vframe
1372 int cmodel = frame->get_color_model();
1373 AVPixelFormat ofmt = color_model_to_pix_fmt(cmodel);
1374 if( ofmt == AV_PIX_FMT_NB ) return -1;
1375 int size = av_image_fill_arrays(ipic->data, ipic->linesize,
1376 frame->get_data(), ofmt, frame->get_w(), frame->get_h(), 1);
1377 if( size < 0 ) return -1;
1379 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1380 int ysz = bpp * frame->get_w(), usz = ysz;
1390 // override av_image_fill_arrays() for planar types
1391 ipic->data[0] = frame->get_y(); ipic->linesize[0] = ysz;
1392 ipic->data[1] = frame->get_u(); ipic->linesize[1] = usz;
1393 ipic->data[2] = frame->get_v(); ipic->linesize[2] = usz;
1396 ipic->data[0] = frame->get_data();
1397 ipic->linesize[0] = frame->get_bytes_per_line();
1401 AVPixelFormat pix_fmt = (AVPixelFormat)ip->format;
1402 FFVideoStream *vid =(FFVideoStream *)this;
1403 if( pix_fmt == vid->hw_pixfmt ) {
1405 if( !sw_frame && !(sw_frame=av_frame_alloc()) )
1406 ret = AVERROR(ENOMEM);
1408 ret = av_hwframe_transfer_data(sw_frame, ip, 0);
1410 pix_fmt = (AVPixelFormat)ip->format;
1413 eprintf(_("Error retrieving data from GPU to CPU\nfile: %s\n"),
1414 vid->ffmpeg->fmt_ctx->url);
1418 convert_ctx = sws_getCachedContext(convert_ctx, ip->width, ip->height, pix_fmt,
1419 frame->get_w(), frame->get_h(), ofmt, SWS_POINT, NULL, NULL, NULL);
1420 if( !convert_ctx ) {
1421 fprintf(stderr, "FFVideoConvert::convert_picture_frame:"
1422 " sws_getCachedContext() failed\n");
1426 int color_range = 0;
1427 switch( preferences->yuv_color_range ) {
1428 case BC_COLORS_JPEG: color_range = 1; break;
1429 case BC_COLORS_MPEG: color_range = 0; break;
1431 int ff_color_space = SWS_CS_ITU601;
1432 switch( preferences->yuv_color_space ) {
1433 case BC_COLORS_BT601: ff_color_space = SWS_CS_ITU601; break;
1434 case BC_COLORS_BT709: ff_color_space = SWS_CS_ITU709; break;
1435 case BC_COLORS_BT2020: ff_color_space = SWS_CS_BT2020; break;
1437 const int *color_table = sws_getCoefficients(ff_color_space);
1439 int *inv_table, *table, src_range, dst_range;
1440 int brightness, contrast, saturation;
1441 if( !sws_getColorspaceDetails(convert_ctx,
1442 &inv_table, &src_range, &table, &dst_range,
1443 &brightness, &contrast, &saturation) ) {
1444 if( src_range != color_range || dst_range != color_range ||
1445 inv_table != color_table || table != color_table )
1446 sws_setColorspaceDetails(convert_ctx,
1447 color_table, color_range, color_table, color_range,
1448 brightness, contrast, saturation);
1451 int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ip->height,
1452 ipic->data, ipic->linesize);
1454 ff_err(ret, "FFVideoConvert::convert_picture_frame: sws_scale() failed\nfile: %s\n",
1455 vid->ffmpeg->fmt_ctx->url);
1461 int FFVideoConvert::convert_cmodel(VFrame *frame, AVFrame *ip)
1463 // try direct transfer
1464 if( !convert_picture_vframe(frame, ip) ) return 1;
1465 // use indirect transfer
1466 AVPixelFormat ifmt = (AVPixelFormat)ip->format;
1467 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
1469 for( int i = 0; i <desc->nb_components; ++i ) {
1470 int bits = desc->comp[i].depth;
1471 if( bits > max_bits ) max_bits = bits;
1473 int imodel = pix_fmt_to_color_model(ifmt);
1474 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1475 int cmodel = frame->get_color_model();
1476 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1477 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1478 imodel = cmodel_is_yuv ?
1479 (BC_CModels::has_alpha(cmodel) ?
1481 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1482 (BC_CModels::has_alpha(cmodel) ?
1483 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1484 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1486 VFrame vframe(ip->width, ip->height, imodel);
1487 if( convert_picture_vframe(&vframe, ip) ) return -1;
1488 frame->transfer_from(&vframe);
1492 int FFVideoConvert::transfer_cmodel(VFrame *frame, AVFrame *ifp)
1494 int ret = convert_cmodel(frame, ifp);
1496 const AVDictionary *src = ifp->metadata;
1497 AVDictionaryEntry *t = NULL;
1498 BC_Hash *hp = frame->get_params();
1500 while( (t=av_dict_get(src, "", t, AV_DICT_IGNORE_SUFFIX)) )
1501 hp->update(t->key, t->value);
1506 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op)
1508 AVFrame *opic = av_frame_alloc();
1509 int ret = convert_vframe_picture(frame, op, opic);
1510 av_frame_free(&opic);
1514 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op, AVFrame *opic)
1515 { // vframe = picture
1516 int cmodel = frame->get_color_model();
1517 AVPixelFormat ifmt = color_model_to_pix_fmt(cmodel);
1518 if( ifmt == AV_PIX_FMT_NB ) return -1;
1519 int size = av_image_fill_arrays(opic->data, opic->linesize,
1520 frame->get_data(), ifmt, frame->get_w(), frame->get_h(), 1);
1521 if( size < 0 ) return -1;
1523 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1524 int ysz = bpp * frame->get_w(), usz = ysz;
1534 // override av_image_fill_arrays() for planar types
1535 opic->data[0] = frame->get_y(); opic->linesize[0] = ysz;
1536 opic->data[1] = frame->get_u(); opic->linesize[1] = usz;
1537 opic->data[2] = frame->get_v(); opic->linesize[2] = usz;
1540 opic->data[0] = frame->get_data();
1541 opic->linesize[0] = frame->get_bytes_per_line();
1545 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1546 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(),
1547 ifmt, op->width, op->height, ofmt, SWS_POINT, NULL, NULL, NULL);
1548 if( !convert_ctx ) {
1549 fprintf(stderr, "FFVideoConvert::convert_frame_picture:"
1550 " sws_getCachedContext() failed\n");
1555 int color_range = 0;
1556 switch( preferences->yuv_color_range ) {
1557 case BC_COLORS_JPEG: color_range = 1; break;
1558 case BC_COLORS_MPEG: color_range = 0; break;
1560 int ff_color_space = SWS_CS_ITU601;
1561 switch( preferences->yuv_color_space ) {
1562 case BC_COLORS_BT601: ff_color_space = SWS_CS_ITU601; break;
1563 case BC_COLORS_BT709: ff_color_space = SWS_CS_ITU709; break;
1564 case BC_COLORS_BT2020: ff_color_space = SWS_CS_BT2020; break;
1566 const int *color_table = sws_getCoefficients(ff_color_space);
1568 int *inv_table, *table, src_range, dst_range;
1569 int brightness, contrast, saturation;
1570 if( !sws_getColorspaceDetails(convert_ctx,
1571 &inv_table, &src_range, &table, &dst_range,
1572 &brightness, &contrast, &saturation) ) {
1573 if( dst_range != color_range || table != color_table )
1574 sws_setColorspaceDetails(convert_ctx,
1575 inv_table, src_range, color_table, color_range,
1576 brightness, contrast, saturation);
1579 int ret = sws_scale(convert_ctx, opic->data, opic->linesize, 0, frame->get_h(),
1580 op->data, op->linesize);
1582 ff_err(ret, "FFVideoConvert::convert_frame_picture: sws_scale() failed\n");
1588 int FFVideoConvert::convert_pixfmt(VFrame *frame, AVFrame *op)
1590 // try direct transfer
1591 if( !convert_vframe_picture(frame, op) ) return 1;
1592 // use indirect transfer
1593 int cmodel = frame->get_color_model();
1594 int max_bits = BC_CModels::calculate_pixelsize(cmodel) * 8;
1595 max_bits /= BC_CModels::components(cmodel);
1596 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1597 int imodel = pix_fmt_to_color_model(ofmt);
1598 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1599 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1600 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1601 imodel = cmodel_is_yuv ?
1602 (BC_CModels::has_alpha(cmodel) ?
1604 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1605 (BC_CModels::has_alpha(cmodel) ?
1606 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1607 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1609 VFrame vframe(frame->get_w(), frame->get_h(), imodel);
1610 vframe.transfer_from(frame);
1611 if( !convert_vframe_picture(&vframe, op) ) return 1;
1615 int FFVideoConvert::transfer_pixfmt(VFrame *frame, AVFrame *ofp)
1617 int ret = convert_pixfmt(frame, ofp);
1619 BC_Hash *hp = frame->get_params();
1620 AVDictionary **dict = &ofp->metadata;
1621 //av_dict_free(dict);
1622 for( int i=0; i<hp->size(); ++i ) {
1623 char *key = hp->get_key(i), *val = hp->get_value(i);
1624 av_dict_set(dict, key, val, 0);
1630 void FFVideoStream::load_markers()
1632 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1633 if( !index_state || idx >= index_state->video_markers.size() ) return;
1634 FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
1637 IndexMarks *FFVideoStream::get_markers()
1639 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1640 if( !index_state || idx >= index_state->video_markers.size() ) return 0;
1641 return !index_state ? 0 : index_state->video_markers[idx];
1645 FFMPEG::FFMPEG(FileBase *file_base)
1648 this->file_base = file_base;
1649 memset(file_format,0,sizeof(file_format));
1650 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
1651 flow_lock = new Condition(1,"FFStream::flow_lock",0);
1654 decoding = encoding = 0;
1655 has_audio = has_video = 0;
1658 opt_video_filter = 0;
1659 opt_audio_filter = 0;
1661 opt_video_decoder = 0;
1662 opt_audio_decoder = 0;
1664 char option_path[BCTEXTLEN];
1665 set_option_path(option_path, "%s", "ffmpeg.opts");
1666 read_options(option_path, opts);
1671 ff_lock("FFMPEG::~FFMPEG()");
1673 ffaudio.remove_all_objects();
1674 ffvideo.remove_all_objects();
1675 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1679 av_dict_free(&opts);
1680 delete [] opt_video_filter;
1681 delete [] opt_audio_filter;
1682 delete [] opt_hw_dev;
1685 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1687 const int *p = codec->supported_samplerates;
1688 if( !p ) return sample_rate;
1690 if( *p == sample_rate ) return *p;
1696 static inline AVRational std_frame_rate(int i)
1698 static const int m1 = 1001*12, m2 = 1000*12;
1699 static const int freqs[] = {
1700 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1701 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
1703 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1704 return (AVRational) { freq, 1001*12 };
1707 AVRational FFMPEG::check_frame_rate(AVCodec *codec, double frame_rate)
1709 const AVRational *p = codec->supported_framerates;
1710 AVRational rate, best_rate = (AVRational) { 0, 0 };
1711 double max_err = 1.; int i = 0;
1712 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1713 double framerate = (double) rate.num / rate.den;
1714 double err = fabs(frame_rate/framerate - 1.);
1715 if( err >= max_err ) continue;
1719 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1722 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1725 double display_aspect = asset->width / (double)asset->height;
1726 double sample_aspect = display_aspect / asset->aspect_ratio;
1727 int width = 1000000, height = width * sample_aspect + 0.5;
1729 MWindow::create_aspect_ratio(w, h, width, height);
1730 return (AVRational){(int)w, (int)h};
1733 return (AVRational){1, 1};
1737 AVRational FFMPEG::to_time_base(int sample_rate)
1739 return (AVRational){1, sample_rate};
1742 int FFMPEG::get_fmt_score(AVSampleFormat dst_fmt, AVSampleFormat src_fmt)
1745 int dst_planar = av_sample_fmt_is_planar(dst_fmt);
1746 int src_planar = av_sample_fmt_is_planar(src_fmt);
1747 if( dst_planar != src_planar ) ++score;
1748 int dst_bytes = av_get_bytes_per_sample(dst_fmt);
1749 int src_bytes = av_get_bytes_per_sample(src_fmt);
1750 score += (src_bytes > dst_bytes ? 100 : -10) * (src_bytes - dst_bytes);
1751 int src_packed = av_get_packed_sample_fmt(src_fmt);
1752 int dst_packed = av_get_packed_sample_fmt(dst_fmt);
1753 if( dst_packed == AV_SAMPLE_FMT_S32 && src_packed == AV_SAMPLE_FMT_FLT ) score += 20;
1754 if( dst_packed == AV_SAMPLE_FMT_FLT && src_packed == AV_SAMPLE_FMT_S32 ) score += 2;
1758 AVSampleFormat FFMPEG::find_best_sample_fmt_of_list(
1759 const AVSampleFormat *sample_fmts, AVSampleFormat src_fmt)
1761 AVSampleFormat best = AV_SAMPLE_FMT_NONE;
1762 int best_score = get_fmt_score(best, src_fmt);
1763 for( int i=0; sample_fmts[i] >= 0; ++i ) {
1764 AVSampleFormat sample_fmt = sample_fmts[i];
1765 int score = get_fmt_score(sample_fmt, src_fmt);
1766 if( score >= best_score ) continue;
1767 best = sample_fmt; best_score = score;
1773 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
1775 char *ep = path + BCTEXTLEN-1;
1776 strncpy(path, File::get_cindat_path(), ep-path);
1777 strncat(path, "/ffmpeg/", ep-path);
1778 path += strlen(path);
1781 path += vsnprintf(path, ep-path, fmt, ap);
1786 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
1791 set_option_path(path, "%s/%s", type, spec);
1794 int FFMPEG::get_format(char *format, const char *path, const char *spec)
1796 char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
1797 get_option_path(option_path, path, spec);
1798 FILE *fp = fopen(option_path,"r");
1801 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1803 line[sizeof(line)-1] = 0;
1804 ret = scan_option_line(line, format, codec);
1810 int FFMPEG::get_codec(char *codec, const char *path, const char *spec)
1812 char option_path[BCTEXTLEN], line[BCTEXTLEN], format[BCTEXTLEN];
1813 get_option_path(option_path, path, spec);
1814 FILE *fp = fopen(option_path,"r");
1817 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1820 line[sizeof(line)-1] = 0;
1821 ret = scan_option_line(line, format, codec);
1824 char *vp = codec, *ep = vp+BCTEXTLEN-1;
1825 while( vp < ep && *vp && *vp != '|' ) ++vp;
1826 if( *vp == '|' ) --vp;
1827 while( vp > codec && (*vp==' ' || *vp=='\t') ) *vp-- = 0;
1832 int FFMPEG::get_file_format()
1834 char audio_muxer[BCSTRLEN], video_muxer[BCSTRLEN];
1835 char audio_format[BCSTRLEN], video_format[BCSTRLEN];
1836 audio_muxer[0] = audio_format[0] = 0;
1837 video_muxer[0] = video_format[0] = 0;
1838 Asset *asset = file_base->asset;
1839 int ret = asset ? 0 : 1;
1840 if( !ret && asset->audio_data ) {
1841 if( !(ret=get_format(audio_format, "audio", asset->acodec)) ) {
1842 if( get_format(audio_muxer, "format", audio_format) ) {
1843 strcpy(audio_muxer, audio_format);
1844 audio_format[0] = 0;
1848 if( !ret && asset->video_data ) {
1849 if( !(ret=get_format(video_format, "video", asset->vcodec)) ) {
1850 if( get_format(video_muxer, "format", video_format) ) {
1851 strcpy(video_muxer, video_format);
1852 video_format[0] = 0;
1856 if( !ret && !audio_muxer[0] && !video_muxer[0] )
1858 if( !ret && audio_muxer[0] && video_muxer[0] &&
1859 strcmp(audio_muxer, video_muxer) ) ret = -1;
1860 if( !ret && audio_format[0] && video_format[0] &&
1861 strcmp(audio_format, video_format) ) ret = -1;
1863 strcpy(file_format, !audio_format[0] && !video_format[0] ?
1864 (audio_muxer[0] ? audio_muxer : video_muxer) :
1865 (audio_format[0] ? audio_format : video_format));
1869 int FFMPEG::scan_option_line(const char *cp, char *tag, char *val)
1871 while( *cp == ' ' || *cp == '\t' ) ++cp;
1872 const char *bp = cp;
1873 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' && *cp != '\n' ) ++cp;
1875 if( !len || len > BCSTRLEN-1 ) return 1;
1876 while( bp < cp ) *tag++ = *bp++;
1878 while( *cp == ' ' || *cp == '\t' ) ++cp;
1879 if( *cp == '=' ) ++cp;
1880 while( *cp == ' ' || *cp == '\t' ) ++cp;
1882 while( *cp && *cp != '\n' ) ++cp;
1884 if( len > BCTEXTLEN-1 ) return 1;
1885 while( bp < cp ) *val++ = *bp++;
1890 int FFMPEG::can_render(const char *fformat, const char *type)
1893 char option_path[BCTEXTLEN];
1894 FFMPEG::set_option_path(option_path, type);
1895 fs.update(option_path);
1896 int total_files = fs.total_files();
1897 for( int i=0; i<total_files; ++i ) {
1898 const char *name = fs.get_entry(i)->get_name();
1899 const char *ext = strrchr(name,'.');
1900 if( !ext ) continue;
1901 if( !strcmp(fformat, ++ext) ) return 1;
1906 int FFMPEG::get_ff_option(const char *nm, const char *options, char *value)
1908 for( const char *cp=options; *cp!=0; ) {
1909 char line[BCTEXTLEN], *bp = line, *ep = bp+sizeof(line)-1;
1910 while( bp < ep && *cp && *cp!='\n' ) *bp++ = *cp++;
1913 if( !line[0] || line[0] == '#' || line[0] == ';' ) continue;
1914 char key[BCSTRLEN], val[BCTEXTLEN];
1915 if( FFMPEG::scan_option_line(line, key, val) ) continue;
1916 if( !strcmp(key, nm) ) {
1917 strncpy(value, val, BCSTRLEN);
1924 void FFMPEG::scan_audio_options(Asset *asset, EDL *edl)
1926 char cin_sample_fmt[BCSTRLEN];
1927 int cin_fmt = AV_SAMPLE_FMT_NONE;
1928 const char *options = asset->ff_audio_options;
1929 if( !get_ff_option("cin_sample_fmt", options, cin_sample_fmt) )
1930 cin_fmt = (int)av_get_sample_fmt(cin_sample_fmt);
1932 char audio_codec[BCSTRLEN]; audio_codec[0] = 0;
1933 AVCodec *av_codec = !FFMPEG::get_codec(audio_codec, "audio", asset->acodec) ?
1934 avcodec_find_encoder_by_name(audio_codec) : 0;
1935 if( av_codec && av_codec->sample_fmts )
1936 cin_fmt = find_best_sample_fmt_of_list(av_codec->sample_fmts, AV_SAMPLE_FMT_FLT);
1938 if( cin_fmt < 0 ) cin_fmt = AV_SAMPLE_FMT_S16;
1939 const char *name = av_get_sample_fmt_name((AVSampleFormat)cin_fmt);
1940 if( !name ) name = _("None");
1941 strcpy(asset->ff_sample_format, name);
1943 char value[BCSTRLEN];
1944 if( !get_ff_option("cin_bitrate", options, value) )
1945 asset->ff_audio_bitrate = atoi(value);
1946 if( !get_ff_option("cin_quality", options, value) )
1947 asset->ff_audio_quality = atoi(value);
1950 void FFMPEG::load_audio_options(Asset *asset, EDL *edl)
1952 char options_path[BCTEXTLEN];
1953 set_option_path(options_path, "audio/%s", asset->acodec);
1954 if( !load_options(options_path,
1955 asset->ff_audio_options,
1956 sizeof(asset->ff_audio_options)) )
1957 scan_audio_options(asset, edl);
1960 void FFMPEG::scan_video_options(Asset *asset, EDL *edl)
1962 char cin_pix_fmt[BCSTRLEN];
1963 int cin_fmt = AV_PIX_FMT_NONE;
1964 const char *options = asset->ff_video_options;
1965 if( !get_ff_option("cin_pix_fmt", options, cin_pix_fmt) )
1966 cin_fmt = (int)av_get_pix_fmt(cin_pix_fmt);
1968 char video_codec[BCSTRLEN]; video_codec[0] = 0;
1969 AVCodec *av_codec = !get_codec(video_codec, "video", asset->vcodec) ?
1970 avcodec_find_encoder_by_name(video_codec) : 0;
1971 if( av_codec && av_codec->pix_fmts ) {
1972 if( 0 && edl ) { // frequently picks a bad answer
1973 int color_model = edl->session->color_model;
1974 int max_bits = BC_CModels::calculate_pixelsize(color_model) * 8;
1975 max_bits /= BC_CModels::components(color_model);
1976 cin_fmt = avcodec_find_best_pix_fmt_of_list(av_codec->pix_fmts,
1977 (BC_CModels::is_yuv(color_model) ?
1978 (max_bits > 8 ? AV_PIX_FMT_AYUV64LE : AV_PIX_FMT_YUV444P) :
1979 (max_bits > 8 ? AV_PIX_FMT_RGB48LE : AV_PIX_FMT_RGB24)), 0, 0);
1982 cin_fmt = av_codec->pix_fmts[0];
1985 if( cin_fmt < 0 ) cin_fmt = AV_PIX_FMT_YUV420P;
1986 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get((AVPixelFormat)cin_fmt);
1987 const char *name = desc ? desc->name : _("None");
1988 strcpy(asset->ff_pixel_format, name);
1990 char value[BCSTRLEN];
1991 if( !get_ff_option("cin_bitrate", options, value) )
1992 asset->ff_video_bitrate = atoi(value);
1993 if( !get_ff_option("cin_quality", options, value) )
1994 asset->ff_video_quality = atoi(value);
1997 void FFMPEG::load_video_options(Asset *asset, EDL *edl)
1999 char options_path[BCTEXTLEN];
2000 set_option_path(options_path, "video/%s", asset->vcodec);
2001 if( !load_options(options_path,
2002 asset->ff_video_options,
2003 sizeof(asset->ff_video_options)) )
2004 scan_video_options(asset, edl);
2007 int FFMPEG::load_defaults(const char *path, const char *type,
2008 char *codec, char *codec_options, int len)
2010 char default_file[BCTEXTLEN];
2011 set_option_path(default_file, "%s/%s.dfl", path, type);
2012 FILE *fp = fopen(default_file,"r");
2014 fgets(codec, BCSTRLEN, fp);
2016 while( *cp && *cp!='\n' ) ++cp;
2018 while( len > 0 && fgets(codec_options, len, fp) ) {
2019 int n = strlen(codec_options);
2020 codec_options += n; len -= n;
2023 set_option_path(default_file, "%s/%s", path, codec);
2024 return load_options(default_file, codec_options, len);
2027 void FFMPEG::set_asset_format(Asset *asset, EDL *edl, const char *text)
2029 if( asset->format != FILE_FFMPEG ) return;
2030 if( text != asset->fformat )
2031 strcpy(asset->fformat, text);
2032 if( asset->audio_data && !asset->ff_audio_options[0] ) {
2033 if( !load_defaults("audio", text, asset->acodec,
2034 asset->ff_audio_options, sizeof(asset->ff_audio_options)) )
2035 scan_audio_options(asset, edl);
2037 asset->audio_data = 0;
2039 if( asset->video_data && !asset->ff_video_options[0] ) {
2040 if( !load_defaults("video", text, asset->vcodec,
2041 asset->ff_video_options, sizeof(asset->ff_video_options)) )
2042 scan_video_options(asset, edl);
2044 asset->video_data = 0;
2048 int FFMPEG::get_encoder(const char *options,
2049 char *format, char *codec, char *bsfilter)
2051 FILE *fp = fopen(options,"r");
2053 eprintf(_("options open failed %s\n"),options);
2056 char line[BCTEXTLEN];
2057 if( !fgets(line, sizeof(line), fp) ||
2058 scan_encoder(line, format, codec, bsfilter) )
2059 eprintf(_("format/codec not found %s\n"), options);
2064 int FFMPEG::scan_encoder(const char *line,
2065 char *format, char *codec, char *bsfilter)
2067 format[0] = codec[0] = bsfilter[0] = 0;
2068 if( scan_option_line(line, format, codec) ) return 1;
2070 while( *cp && *cp != '|' ) ++cp;
2071 if( !*cp ) return 0;
2073 do { *bp-- = 0; } while( bp>=codec && (*bp==' ' || *bp == '\t' ) );
2074 while( *++cp && (*cp==' ' || *cp == '\t') );
2076 for( int i=BCTEXTLEN; --i>0 && *cp; ) *bp++ = *cp++;
2081 int FFMPEG::read_options(const char *options, AVDictionary *&opts, int skip)
2083 FILE *fp = fopen(options,"r");
2086 while( !ret && --skip >= 0 ) {
2088 while( ch >= 0 && ch != '\n' ) ch = getc(fp);
2089 if( ch < 0 ) ret = 1;
2092 ret = read_options(fp, options, opts);
2097 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
2099 FILE *fp = fmemopen((void *)options,strlen(options),"r");
2101 int ret = read_options(fp, options, opts);
2103 AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
2104 if( tag ) st->id = strtol(tag->value,0,0);
2108 FFCodecRemap::FFCodecRemap()
2113 FFCodecRemap::~FFCodecRemap()
2115 delete [] old_codec;
2116 delete [] new_codec;
2119 int FFCodecRemaps::add(const char *val)
2121 char old_codec[BCSTRLEN], new_codec[BCSTRLEN];
2122 if( sscanf(val, " %63[a-zA-z0-9_-] = %63[a-z0-9_-]",
2123 &old_codec[0], &new_codec[0]) != 2 ) return 1;
2124 FFCodecRemap &remap = append();
2125 remap.old_codec = cstrdup(old_codec);
2126 remap.new_codec = cstrdup(new_codec);
2131 int FFCodecRemaps::update(AVCodecID &codec_id, AVCodec *&decoder)
2133 AVCodec *codec = avcodec_find_decoder(codec_id);
2134 if( !codec ) return -1;
2135 const char *name = codec->name;
2136 FFCodecRemaps &map = *this;
2138 while( --k >= 0 && strcmp(map[k].old_codec, name) );
2139 if( k < 0 ) return 1;
2140 const char *new_codec = map[k].new_codec;
2141 codec = avcodec_find_decoder_by_name(new_codec);
2142 if( !codec ) return -1;
2147 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
2149 int ret = 0, no = 0;
2150 char line[BCTEXTLEN];
2151 while( !ret && fgets(line, sizeof(line), fp) ) {
2152 line[sizeof(line)-1] = 0;
2153 if( line[0] == '#' ) continue;
2154 if( line[0] == '\n' ) continue;
2155 char key[BCSTRLEN], val[BCTEXTLEN];
2156 if( scan_option_line(line, key, val) ) {
2157 eprintf(_("err reading %s: line %d\n"), options, no);
2161 if( !strcmp(key, "duration") )
2162 opt_duration = strtod(val, 0);
2163 else if( !strcmp(key, "video_decoder") )
2164 opt_video_decoder = cstrdup(val);
2165 else if( !strcmp(key, "audio_decoder") )
2166 opt_audio_decoder = cstrdup(val);
2167 else if( !strcmp(key, "remap_video_decoder") )
2168 video_codec_remaps.add(val);
2169 else if( !strcmp(key, "remap_audio_decoder") )
2170 audio_codec_remaps.add(val);
2171 else if( !strcmp(key, "video_filter") )
2172 opt_video_filter = cstrdup(val);
2173 else if( !strcmp(key, "audio_filter") )
2174 opt_audio_filter = cstrdup(val);
2175 else if( !strcmp(key, "cin_hw_dev") )
2176 opt_hw_dev = cstrdup(val);
2177 else if( !strcmp(key, "loglevel") )
2180 av_dict_set(&opts, key, val, 0);
2186 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
2188 char option_path[BCTEXTLEN];
2189 set_option_path(option_path, "%s", options);
2190 return read_options(option_path, opts);
2193 int FFMPEG::load_options(const char *path, char *bfr, int len)
2196 FILE *fp = fopen(path, "r");
2198 fgets(bfr, len, fp); // skip hdr
2199 len = fread(bfr, 1, len-1, fp);
2200 if( len < 0 ) len = 0;
2206 void FFMPEG::set_loglevel(const char *ap)
2208 if( !ap || !*ap ) return;
2213 { "quiet" , AV_LOG_QUIET },
2214 { "panic" , AV_LOG_PANIC },
2215 { "fatal" , AV_LOG_FATAL },
2216 { "error" , AV_LOG_ERROR },
2217 { "warning", AV_LOG_WARNING },
2218 { "info" , AV_LOG_INFO },
2219 { "verbose", AV_LOG_VERBOSE },
2220 { "debug" , AV_LOG_DEBUG },
2222 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
2223 if( !strcmp(log_levels[i].name, ap) ) {
2224 av_log_set_level(log_levels[i].level);
2228 av_log_set_level(atoi(ap));
2231 double FFMPEG::to_secs(int64_t time, AVRational time_base)
2233 double base_time = time == AV_NOPTS_VALUE ? 0 :
2234 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
2235 return base_time / AV_TIME_BASE;
2238 int FFMPEG::info(char *text, int len)
2240 if( len <= 0 ) return 0;
2242 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
2244 report("format: %s\n",fmt_ctx->iformat->name);
2245 if( ffvideo.size() > 0 )
2246 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
2247 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
2248 FFVideoStream *vid = ffvideo[vidx];
2249 AVStream *st = vid->st;
2250 AVCodecID codec_id = st->codecpar->codec_id;
2251 report(_("vid%d (%d), id 0x%06x:\n"), vid->idx, vid->fidx, codec_id);
2252 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
2253 report(" video%d %s", vidx+1, desc ? desc->name : " (unkn)");
2254 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
2255 AVPixelFormat pix_fmt = (AVPixelFormat)st->codecpar->format;
2256 const char *pfn = av_get_pix_fmt_name(pix_fmt);
2257 report(" pix %s\n", pfn ? pfn : "(unkn)");
2258 double secs = to_secs(st->duration, st->time_base);
2259 int64_t length = secs * vid->frame_rate + 0.5;
2260 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
2261 int64_t nudge = ofs * vid->frame_rate;
2262 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
2263 report(" %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
2264 int hrs = secs/3600; secs -= hrs*3600;
2265 int mins = secs/60; secs -= mins*60;
2266 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
2268 if( ffaudio.size() > 0 )
2269 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
2270 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2271 FFAudioStream *aud = ffaudio[aidx];
2272 AVStream *st = aud->st;
2273 AVCodecID codec_id = st->codecpar->codec_id;
2274 report(_("aud%d (%d), id 0x%06x:\n"), aud->idx, aud->fidx, codec_id);
2275 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
2276 int nch = aud->channels, ch0 = aud->channel0+1;
2277 report(" audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
2278 AVSampleFormat sample_fmt = (AVSampleFormat)st->codecpar->format;
2279 const char *fmt = av_get_sample_fmt_name(sample_fmt);
2280 report(" %s %d", fmt, aud->sample_rate);
2281 int sample_bits = av_get_bits_per_sample(codec_id);
2282 report(" %dbits\n", sample_bits);
2283 double secs = to_secs(st->duration, st->time_base);
2284 int64_t length = secs * aud->sample_rate + 0.5;
2285 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
2286 int64_t nudge = ofs * aud->sample_rate;
2287 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
2288 report(" %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
2289 int hrs = secs/3600; secs -= hrs*3600;
2290 int mins = secs/60; secs -= mins*60;
2291 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
2293 if( fmt_ctx->nb_programs > 0 )
2294 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
2295 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
2296 report("program %d", i+1);
2297 AVProgram *pgrm = fmt_ctx->programs[i];
2298 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2299 int idx = pgrm->stream_index[j];
2300 int vidx = ffvideo.size();
2301 while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
2303 report(", vid%d", vidx);
2306 int aidx = ffaudio.size();
2307 while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
2309 report(", aud%d", aidx);
2312 report(", (%d)", pgrm->stream_index[j]);
2317 AVDictionaryEntry *tag = 0;
2318 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
2319 report("%s=%s\n", tag->key, tag->value);
2328 int FFMPEG::init_decoder(const char *filename)
2330 ff_lock("FFMPEG::init_decoder");
2332 char file_opts[BCTEXTLEN];
2333 strcpy(file_opts, filename);
2334 char *bp = strrchr(file_opts, '/');
2335 if( !bp ) bp = file_opts;
2336 char *sp = strrchr(bp, '.');
2337 if( !sp ) sp = bp + strlen(bp);
2339 AVInputFormat *ifmt = 0;
2341 strcpy(sp, ".opts");
2342 fp = fopen(file_opts, "r");
2345 read_options(fp, file_opts, opts);
2347 AVDictionaryEntry *tag;
2348 if( (tag=av_dict_get(opts, "format", NULL, 0)) != 0 ) {
2349 ifmt = av_find_input_format(tag->value);
2353 load_options("decode.opts", opts);
2354 AVDictionary *fopts = 0;
2355 av_dict_copy(&fopts, opts, 0);
2356 int ret = avformat_open_input(&fmt_ctx, filename, ifmt, &fopts);
2357 av_dict_free(&fopts);
2359 ret = avformat_find_stream_info(fmt_ctx, NULL);
2364 return !ret ? 0 : 1;
2367 int FFMPEG::open_decoder()
2370 if( stat(fmt_ctx->url, &st) < 0 ) {
2371 eprintf(_("can't stat file: %s\n"), fmt_ctx->url);
2375 int64_t file_bits = 8 * st.st_size;
2376 if( !fmt_ctx->bit_rate && opt_duration > 0 )
2377 fmt_ctx->bit_rate = file_bits / opt_duration;
2380 if( fmt_ctx->bit_rate > 0 ) {
2381 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2382 AVStream *st = fmt_ctx->streams[i];
2383 if( st->duration != AV_NOPTS_VALUE ) continue;
2384 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
2385 st->duration = av_rescale(file_bits, st->time_base.den,
2386 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
2390 if( estimated && !(fflags & FF_ESTM_TIMES) ) {
2391 fflags |= FF_ESTM_TIMES;
2392 printf("FFMPEG::open_decoder: some stream times estimated: %s\n",
2396 ff_lock("FFMPEG::open_decoder");
2397 int ret = 0, bad_time = 0;
2398 for( int i=0; !ret && i<(int)fmt_ctx->nb_streams; ++i ) {
2399 AVStream *st = fmt_ctx->streams[i];
2400 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
2401 AVCodecParameters *avpar = st->codecpar;
2402 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avpar->codec_id);
2403 if( !codec_desc ) continue;
2404 switch( avpar->codec_type ) {
2405 case AVMEDIA_TYPE_VIDEO: {
2406 if( avpar->width < 1 ) continue;
2407 if( avpar->height < 1 ) continue;
2408 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
2409 if( framerate.num < 1 ) continue;
2411 int vidx = ffvideo.size();
2412 FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
2413 vstrm_index.append(ffidx(vidx, 0));
2414 ffvideo.append(vid);
2415 vid->width = avpar->width;
2416 vid->height = avpar->height;
2417 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
2418 double secs = to_secs(st->duration, st->time_base);
2419 vid->length = secs * vid->frame_rate;
2420 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
2421 vid->nudge = st->start_time;
2423 if( opt_video_filter )
2424 ret = vid->create_filter(opt_video_filter, avpar);
2426 case AVMEDIA_TYPE_AUDIO: {
2427 if( avpar->channels < 1 ) continue;
2428 if( avpar->sample_rate < 1 ) continue;
2430 int aidx = ffaudio.size();
2431 FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
2432 ffaudio.append(aud);
2433 aud->channel0 = astrm_index.size();
2434 aud->channels = avpar->channels;
2435 for( int ch=0; ch<aud->channels; ++ch )
2436 astrm_index.append(ffidx(aidx, ch));
2437 aud->sample_rate = avpar->sample_rate;
2438 double secs = to_secs(st->duration, st->time_base);
2439 aud->length = secs * aud->sample_rate;
2440 aud->init_swr(aud->channels, avpar->format, aud->sample_rate);
2441 aud->nudge = st->start_time;
2443 if( opt_audio_filter )
2444 ret = aud->create_filter(opt_audio_filter, avpar);
2449 if( bad_time && !(fflags & FF_BAD_TIMES) ) {
2450 fflags |= FF_BAD_TIMES;
2451 printf(_("FFMPEG::open_decoder: some stream have bad times: %s\n"),
2455 return ret < 0 ? -1 : 0;
2459 int FFMPEG::init_encoder(const char *filename)
2461 // try access first for named pipes
2462 int ret = access(filename, W_OK);
2464 int fd = ::open(filename,O_WRONLY);
2465 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
2466 if( fd >= 0 ) { close(fd); ret = 0; }
2469 eprintf(_("bad file path: %s\n"), filename);
2472 ret = get_file_format();
2474 eprintf(_("bad file format: %s\n"), filename);
2478 eprintf(_("mismatch audio/video file format: %s\n"), filename);
2481 ff_lock("FFMPEG::init_encoder");
2483 char format[BCSTRLEN];
2484 if( get_format(format, "format", file_format) )
2485 strcpy(format, file_format);
2486 avformat_alloc_output_context2(&fmt_ctx, 0, format, filename);
2488 eprintf(_("failed: %s\n"), filename);
2493 load_options("encode.opts", opts);
2499 int FFMPEG::open_encoder(const char *type, const char *spec)
2502 Asset *asset = file_base->asset;
2503 char *filename = asset->path;
2504 AVDictionary *sopts = 0;
2505 av_dict_copy(&sopts, opts, 0);
2506 char option_path[BCTEXTLEN];
2507 set_option_path(option_path, "%s/%s.opts", type, type);
2508 read_options(option_path, sopts);
2509 get_option_path(option_path, type, spec);
2510 char format_name[BCSTRLEN], codec_name[BCTEXTLEN], bsfilter[BCTEXTLEN];
2511 if( get_encoder(option_path, format_name, codec_name, bsfilter) ) {
2512 eprintf(_("get_encoder failed %s:%s\n"), option_path, filename);
2517 if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
2519 else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
2520 else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
2523 ff_lock("FFMPEG::open_encoder");
2526 AVCodecContext *ctx = 0;
2528 const AVCodecDescriptor *codec_desc = 0;
2529 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
2531 eprintf(_("cant find codec %s:%s\n"), codec_name, filename);
2535 codec_desc = avcodec_descriptor_get(codec->id);
2537 eprintf(_("unknown codec %s:%s\n"), codec_name, filename);
2542 st = avformat_new_stream(fmt_ctx, 0);
2544 eprintf(_("cant create stream %s:%s\n"), codec_name, filename);
2549 switch( codec_desc->type ) {
2550 case AVMEDIA_TYPE_AUDIO: {
2552 eprintf(_("duplicate audio %s:%s\n"), codec_name, filename);
2556 if( scan_options(asset->ff_audio_options, sopts, st) ) {
2557 eprintf(_("bad audio options %s:%s\n"), codec_name, filename);
2562 ctx = avcodec_alloc_context3(codec);
2563 if( asset->ff_audio_bitrate > 0 ) {
2564 ctx->bit_rate = asset->ff_audio_bitrate;
2566 sprintf(arg, "%d", asset->ff_audio_bitrate);
2567 av_dict_set(&sopts, "b", arg, 0);
2569 else if( asset->ff_audio_quality >= 0 ) {
2570 ctx->global_quality = asset->ff_audio_quality * FF_QP2LAMBDA;
2571 ctx->qmin = ctx->qmax = asset->ff_audio_quality;
2572 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2573 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2574 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2576 av_dict_set(&sopts, "flags", "+qscale", 0);
2577 sprintf(arg, "%d", asset->ff_audio_quality);
2578 av_dict_set(&sopts, "qscale", arg, 0);
2579 sprintf(arg, "%d", ctx->global_quality);
2580 av_dict_set(&sopts, "global_quality", arg, 0);
2582 int aidx = ffaudio.size();
2583 int fidx = aidx + ffvideo.size();
2584 FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
2585 aud->avctx = ctx; ffaudio.append(aud); fst = aud;
2586 aud->sample_rate = asset->sample_rate;
2587 ctx->channels = aud->channels = asset->channels;
2588 for( int ch=0; ch<aud->channels; ++ch )
2589 astrm_index.append(ffidx(aidx, ch));
2590 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
2591 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
2592 if( !ctx->sample_rate ) {
2593 eprintf(_("check_sample_rate failed %s\n"), filename);
2597 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
2598 AVSampleFormat sample_fmt = av_get_sample_fmt(asset->ff_sample_format);
2599 if( sample_fmt == AV_SAMPLE_FMT_NONE )
2600 sample_fmt = codec->sample_fmts ? codec->sample_fmts[0] : AV_SAMPLE_FMT_S16;
2601 ctx->sample_fmt = sample_fmt;
2602 uint64_t layout = av_get_default_channel_layout(ctx->channels);
2603 aud->resample_context = swr_alloc_set_opts(NULL,
2604 layout, ctx->sample_fmt, aud->sample_rate,
2605 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
2607 swr_init(aud->resample_context);
2610 case AVMEDIA_TYPE_VIDEO: {
2612 eprintf(_("duplicate video %s:%s\n"), codec_name, filename);
2616 if( scan_options(asset->ff_video_options, sopts, st) ) {
2617 eprintf(_("bad video options %s:%s\n"), codec_name, filename);
2622 ctx = avcodec_alloc_context3(codec);
2623 if( asset->ff_video_bitrate > 0 ) {
2624 ctx->bit_rate = asset->ff_video_bitrate;
2626 sprintf(arg, "%d", asset->ff_video_bitrate);
2627 av_dict_set(&sopts, "b", arg, 0);
2629 else if( asset->ff_video_quality >= 0 ) {
2630 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
2631 ctx->qmin = ctx->qmax = asset->ff_video_quality;
2632 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2633 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2634 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2636 av_dict_set(&sopts, "flags", "+qscale", 0);
2637 sprintf(arg, "%d", asset->ff_video_quality);
2638 av_dict_set(&sopts, "qscale", arg, 0);
2639 sprintf(arg, "%d", ctx->global_quality);
2640 av_dict_set(&sopts, "global_quality", arg, 0);
2642 int vidx = ffvideo.size();
2643 int fidx = vidx + ffaudio.size();
2644 FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
2645 vstrm_index.append(ffidx(vidx, 0));
2646 vid->avctx = ctx; ffvideo.append(vid); fst = vid;
2647 vid->width = asset->width;
2648 vid->height = asset->height;
2649 vid->frame_rate = asset->frame_rate;
2651 AVPixelFormat pix_fmt = av_get_pix_fmt(asset->ff_pixel_format);
2652 if( opt_hw_dev != 0 ) {
2653 AVHWDeviceType hw_type = vid->encode_hw_activate(opt_hw_dev);
2655 case AV_HWDEVICE_TYPE_VAAPI:
2656 pix_fmt = AV_PIX_FMT_VAAPI;
2658 case AV_HWDEVICE_TYPE_NONE:
2662 if( pix_fmt == AV_PIX_FMT_NONE )
2663 pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
2664 ctx->pix_fmt = pix_fmt;
2666 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
2667 int mask_w = (1<<desc->log2_chroma_w)-1;
2668 ctx->width = (vid->width+mask_w) & ~mask_w;
2669 int mask_h = (1<<desc->log2_chroma_h)-1;
2670 ctx->height = (vid->height+mask_h) & ~mask_h;
2671 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
2672 AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
2673 if( !frame_rate.num || !frame_rate.den ) {
2674 eprintf(_("check_frame_rate failed %s\n"), filename);
2678 av_reduce(&frame_rate.num, &frame_rate.den,
2679 frame_rate.num, frame_rate.den, INT_MAX);
2680 ctx->framerate = (AVRational) { frame_rate.num, frame_rate.den };
2681 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
2682 st->avg_frame_rate = frame_rate;
2683 st->time_base = ctx->time_base;
2685 vid->interlaced = asset->interlace_mode == ILACE_MODE_TOP_FIRST ||
2686 asset->interlace_mode == ILACE_MODE_BOTTOM_FIRST ? 1 : 0;
2687 vid->top_field_first = asset->interlace_mode == ILACE_MODE_TOP_FIRST ? 1 : 0;
2690 eprintf(_("not audio/video, %s:%s\n"), codec_name, filename);
2695 AVDictionaryEntry *tag;
2696 if( (tag=av_dict_get(sopts, "cin_stats_filename", NULL, 0)) != 0 ) {
2697 char suffix[BCSTRLEN]; sprintf(suffix,"-%d.log",fst->fidx);
2698 fst->stats_filename = cstrcat(2, tag->value, suffix);
2700 if( (tag=av_dict_get(sopts, "flags", NULL, 0)) != 0 ) {
2701 int pass = fst->pass;
2702 char *cp = tag->value;
2704 int ch = *cp++, pfx = ch=='-' ? -1 : ch=='+' ? 1 : 0;
2705 if( !isalnum(!pfx ? ch : (ch=*cp++)) ) continue;
2706 char id[BCSTRLEN], *bp = id, *ep = bp+sizeof(id)-1;
2707 for( *bp++=ch; isalnum(ch=*cp); ++cp )
2708 if( bp < ep ) *bp++ = ch;
2710 if( !strcmp(id, "pass1") ) {
2711 pass = pfx<0 ? (pass&~1) : pfx>0 ? (pass|1) : 1;
2713 else if( !strcmp(id, "pass2") ) {
2714 pass = pfx<0 ? (pass&~2) : pfx>0 ? (pass|2) : 2;
2717 if( (fst->pass=pass) ) {
2718 if( pass & 1 ) ctx->flags |= AV_CODEC_FLAG_PASS1;
2719 if( pass & 2 ) ctx->flags |= AV_CODEC_FLAG_PASS2;
2725 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
2726 ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
2727 if( fst->stats_filename && (ret=fst->init_stats_file()) )
2728 eprintf(_("error: stats file = %s\n"), fst->stats_filename);
2731 av_dict_set(&sopts, "cin_bitrate", 0, 0);
2732 av_dict_set(&sopts, "cin_quality", 0, 0);
2734 if( !av_dict_get(sopts, "threads", NULL, 0) )
2735 ctx->thread_count = ff_cpus();
2736 ret = avcodec_open2(ctx, codec, &sopts);
2738 ret = avcodec_parameters_from_context(st->codecpar, ctx);
2740 fprintf(stderr, "Could not copy the stream parameters\n");
2743 _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
2744 ret = avcodec_copy_context(st->codec, ctx);
2745 _Pragma("GCC diagnostic warning \"-Wdeprecated-declarations\"")
2747 fprintf(stderr, "Could not copy the stream context\n");
2750 ff_err(ret,"FFMPEG::open_encoder");
2751 eprintf(_("open failed %s:%s\n"), codec_name, filename);
2757 if( !ret && fst && bsfilter[0] ) {
2758 ret = av_bsf_list_parse_str(bsfilter, &fst->bsfc);
2760 ff_err(ret,"FFMPEG::open_encoder");
2761 eprintf(_("bitstream filter failed %s:\n%s\n"), filename, bsfilter);
2772 av_dict_free(&sopts);
2776 int FFMPEG::close_encoder()
2779 if( encoding > 0 ) {
2780 av_write_trailer(fmt_ctx);
2781 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
2782 avio_closep(&fmt_ctx->pb);
2788 int FFMPEG::decode_activate()
2790 if( decoding < 0 ) {
2792 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
2793 ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
2794 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
2795 ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
2796 // set nudges for each program stream set
2797 const int64_t min_nudge = INT64_MIN+1;
2798 int npgrms = fmt_ctx->nb_programs;
2799 for( int i=0; i<npgrms; ++i ) {
2800 AVProgram *pgrm = fmt_ctx->programs[i];
2801 // first start time video stream
2802 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2803 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2804 int fidx = pgrm->stream_index[j];
2805 AVStream *st = fmt_ctx->streams[fidx];
2806 AVCodecParameters *avpar = st->codecpar;
2807 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2808 if( st->start_time == AV_NOPTS_VALUE ) continue;
2809 if( vstart_time < st->start_time )
2810 vstart_time = st->start_time;
2813 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2814 if( st->start_time == AV_NOPTS_VALUE ) continue;
2815 if( astart_time < st->start_time )
2816 astart_time = st->start_time;
2820 //since frame rate is much more grainy than sample rate, it is better to
2821 // align using video, so that total absolute error is minimized.
2822 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2823 astart_time > min_nudge ? astart_time : AV_NOPTS_VALUE;
2824 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2825 int fidx = pgrm->stream_index[j];
2826 AVStream *st = fmt_ctx->streams[fidx];
2827 AVCodecParameters *avpar = st->codecpar;
2828 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2829 for( int k=0; k<ffvideo.size(); ++k ) {
2830 if( ffvideo[k]->fidx != fidx ) continue;
2831 ffvideo[k]->nudge = nudge;
2835 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2836 for( int k=0; k<ffaudio.size(); ++k ) {
2837 if( ffaudio[k]->fidx != fidx ) continue;
2838 ffaudio[k]->nudge = nudge;
2844 // set nudges for any streams not yet set
2845 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2846 int nstreams = fmt_ctx->nb_streams;
2847 for( int i=0; i<nstreams; ++i ) {
2848 AVStream *st = fmt_ctx->streams[i];
2849 AVCodecParameters *avpar = st->codecpar;
2850 switch( avpar->codec_type ) {
2851 case AVMEDIA_TYPE_VIDEO: {
2852 if( st->start_time == AV_NOPTS_VALUE ) continue;
2853 int vidx = ffvideo.size();
2854 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
2855 if( vidx < 0 ) continue;
2856 if( ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
2857 if( vstart_time < st->start_time )
2858 vstart_time = st->start_time;
2860 case AVMEDIA_TYPE_AUDIO: {
2861 if( st->start_time == AV_NOPTS_VALUE ) continue;
2862 int aidx = ffaudio.size();
2863 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
2864 if( aidx < 0 ) continue;
2865 if( ffaudio[aidx]->frame_sz < avpar->frame_size )
2866 ffaudio[aidx]->frame_sz = avpar->frame_size;
2867 if( ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
2868 if( astart_time < st->start_time )
2869 astart_time = st->start_time;
2874 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2875 astart_time > min_nudge ? astart_time : 0;
2876 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
2877 if( ffvideo[vidx]->nudge == AV_NOPTS_VALUE )
2878 ffvideo[vidx]->nudge = nudge;
2880 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2881 if( ffaudio[aidx]->nudge == AV_NOPTS_VALUE )
2882 ffaudio[aidx]->nudge = nudge;
2889 int FFMPEG::encode_activate()
2892 if( encoding < 0 ) {
2894 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
2895 (ret=avio_open(&fmt_ctx->pb, fmt_ctx->url, AVIO_FLAG_WRITE)) < 0 ) {
2896 ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
2902 AVProgram *prog = av_new_program(fmt_ctx, prog_id);
2903 for( int i=0; i< ffvideo.size(); ++i )
2904 av_program_add_stream_index(fmt_ctx, prog_id, ffvideo[i]->fidx);
2905 for( int i=0; i< ffaudio.size(); ++i )
2906 av_program_add_stream_index(fmt_ctx, prog_id, ffaudio[i]->fidx);
2907 int pi = fmt_ctx->nb_programs;
2908 while( --pi >= 0 && fmt_ctx->programs[pi]->id != prog_id );
2909 AVDictionary **meta = &prog->metadata;
2910 av_dict_set(meta, "service_provider", "cin5", 0);
2911 const char *path = fmt_ctx->url, *bp = strrchr(path,'/');
2912 if( bp ) path = bp + 1;
2913 av_dict_set(meta, "title", path, 0);
2915 if( ffaudio.size() ) {
2916 const char *ep = getenv("CIN_AUDIO_LANG"), *lp = 0;
2917 if( !ep && (lp=getenv("LANG")) ) { // some are guesses
2918 static struct { const char lc[3], lng[4]; } lcode[] = {
2919 { "en", "eng" }, { "de", "ger" }, { "es", "spa" },
2920 { "eu", "bas" }, { "fr", "fre" }, { "el", "gre" },
2921 { "hi", "hin" }, { "it", "ita" }, { "ja", "jap" },
2922 { "ko", "kor" }, { "du", "dut" }, { "pl", "pol" },
2923 { "pt", "por" }, { "ru", "rus" }, { "sl", "slv" },
2924 { "uk", "ukr" }, { "vi", "vie" }, { "zh", "chi" },
2926 for( int i=sizeof(lcode)/sizeof(lcode[0]); --i>=0 && !ep; )
2927 if( !strncmp(lcode[i].lc,lp,2) ) ep = lcode[i].lng;
2929 if( !ep ) ep = "und";
2931 strncpy(lang,ep,3); lang[3] = 0;
2932 AVStream *st = ffaudio[0]->st;
2933 av_dict_set(&st->metadata,"language",lang,0);
2936 AVDictionary *fopts = 0;
2937 char option_path[BCTEXTLEN];
2938 set_option_path(option_path, "format/%s", file_format);
2939 read_options(option_path, fopts, 1);
2940 ret = avformat_write_header(fmt_ctx, &fopts);
2942 ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
2946 av_dict_free(&fopts);
2953 int FFMPEG::audio_seek(int stream, int64_t pos)
2955 int aidx = astrm_index[stream].st_idx;
2956 FFAudioStream *aud = ffaudio[aidx];
2957 aud->audio_seek(pos);
2961 int FFMPEG::video_seek(int stream, int64_t pos)
2963 int vidx = vstrm_index[stream].st_idx;
2964 FFVideoStream *vid = ffvideo[vidx];
2965 vid->video_seek(pos);
2970 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
2972 if( !has_audio || chn >= astrm_index.size() ) return -1;
2973 int aidx = astrm_index[chn].st_idx;
2974 FFAudioStream *aud = ffaudio[aidx];
2975 if( aud->load(pos, len) < len ) return -1;
2976 int ch = astrm_index[chn].st_ch;
2977 int ret = aud->read(samples,len,ch);
2981 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
2983 if( !has_video || layer >= vstrm_index.size() ) return -1;
2984 int vidx = vstrm_index[layer].st_idx;
2985 FFVideoStream *vid = ffvideo[vidx];
2986 return vid->load(vframe, pos);
2990 int FFMPEG::encode(int stream, double **samples, int len)
2992 FFAudioStream *aud = ffaudio[stream];
2993 return aud->encode(samples, len);
2997 int FFMPEG::encode(int stream, VFrame *frame)
2999 FFVideoStream *vid = ffvideo[stream];
3000 return vid->encode(frame);
3003 void FFMPEG::start_muxer()
3011 void FFMPEG::stop_muxer()
3020 void FFMPEG::flow_off()
3023 flow_lock->lock("FFMPEG::flow_off");
3027 void FFMPEG::flow_on()
3031 flow_lock->unlock();
3034 void FFMPEG::flow_ctl()
3037 flow_lock->lock("FFMPEG::flow_ctl");
3038 flow_lock->unlock();
3042 int FFMPEG::mux_audio(FFrame *frm)
3044 FFStream *fst = frm->fst;
3045 AVCodecContext *ctx = fst->avctx;
3046 AVFrame *frame = *frm;
3047 AVRational tick_rate = {1, ctx->sample_rate};
3048 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
3049 int ret = fst->encode_frame(frame);
3051 ff_err(ret, "FFMPEG::mux_audio");
3052 return ret >= 0 ? 0 : 1;
3055 int FFMPEG::mux_video(FFrame *frm)
3057 FFStream *fst = frm->fst;
3058 AVFrame *frame = *frm;
3059 frame->pts = frm->position;
3060 int ret = fst->encode_frame(frame);
3062 ff_err(ret, "FFMPEG::mux_video");
3063 return ret >= 0 ? 0 : 1;
3069 double atm = -1, vtm = -1;
3070 FFrame *afrm = 0, *vfrm = 0;
3072 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
3073 FFStream *fst = ffaudio[i];
3074 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
3075 FFrame *frm = fst->frms.first;
3076 if( !frm ) { if( !done ) return; continue; }
3077 double tm = to_secs(frm->position, fst->avctx->time_base);
3078 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
3080 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
3081 FFStream *fst = ffvideo[i];
3082 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
3083 FFrame *frm = fst->frms.first;
3084 if( !frm ) { if( !done ) return; continue; }
3085 double tm = to_secs(frm->position, fst->avctx->time_base);
3086 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
3088 if( !demand ) flow_off();
3089 if( !afrm && !vfrm ) break;
3090 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
3091 vfrm->position, vfrm->fst->avctx->time_base,
3092 afrm->position, afrm->fst->avctx->time_base);
3093 FFrame *frm = v <= 0 ? vfrm : afrm;
3094 if( frm == afrm ) mux_audio(frm);
3095 if( frm == vfrm ) mux_video(frm);
3104 mux_lock->lock("FFMPEG::run");
3107 for( int i=0; i<ffaudio.size(); ++i )
3108 ffaudio[i]->drain();
3109 for( int i=0; i<ffvideo.size(); ++i )
3110 ffvideo[i]->drain();
3112 for( int i=0; i<ffaudio.size(); ++i )
3113 ffaudio[i]->flush();
3114 for( int i=0; i<ffvideo.size(); ++i )
3115 ffvideo[i]->flush();
3119 int FFMPEG::ff_total_audio_channels()
3121 return astrm_index.size();
3124 int FFMPEG::ff_total_astreams()
3126 return ffaudio.size();
3129 int FFMPEG::ff_audio_channels(int stream)
3131 return ffaudio[stream]->channels;
3134 int FFMPEG::ff_sample_rate(int stream)
3136 return ffaudio[stream]->sample_rate;
3139 const char* FFMPEG::ff_audio_format(int stream)
3141 AVStream *st = ffaudio[stream]->st;
3142 AVCodecID id = st->codecpar->codec_id;
3143 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
3144 return desc ? desc->name : _("Unknown");
3147 int FFMPEG::ff_audio_pid(int stream)
3149 return ffaudio[stream]->st->id;
3152 int64_t FFMPEG::ff_audio_samples(int stream)
3154 return ffaudio[stream]->length;
3157 // find audio astream/channels with this program,
3158 // or all program audio channels (astream=-1)
3159 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
3163 int vidx = ffvideo[vstream]->fidx;
3164 // find first program with this video stream
3165 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
3166 AVProgram *pgrm = fmt_ctx->programs[i];
3167 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
3168 int st_idx = pgrm->stream_index[j];
3169 AVStream *st = fmt_ctx->streams[st_idx];
3170 if( st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
3171 if( st_idx == vidx ) pidx = i;
3174 if( pidx < 0 ) return -1;
3176 int64_t channels = 0;
3177 AVProgram *pgrm = fmt_ctx->programs[pidx];
3178 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
3179 int aidx = pgrm->stream_index[j];
3180 AVStream *st = fmt_ctx->streams[aidx];
3181 if( st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
3182 if( astream > 0 ) { --astream; continue; }
3184 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
3185 if( ffaudio[i]->fidx == aidx ) astrm = i;
3187 if( ret < 0 ) ret = astrm;
3188 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
3189 channels |= mask << ffaudio[astrm]->channel0;
3191 if( !astream ) break;
3193 channel_mask = channels;
3198 int FFMPEG::ff_total_video_layers()
3200 return vstrm_index.size();
3203 int FFMPEG::ff_total_vstreams()
3205 return ffvideo.size();
3208 int FFMPEG::ff_video_width(int stream)
3210 return ffvideo[stream]->width;
3213 int FFMPEG::ff_video_height(int stream)
3215 return ffvideo[stream]->height;
3218 int FFMPEG::ff_set_video_width(int stream, int width)
3220 int w = ffvideo[stream]->width;
3221 ffvideo[stream]->width = width;
3225 int FFMPEG::ff_set_video_height(int stream, int height)
3227 int h = ffvideo[stream]->height;
3228 ffvideo[stream]->height = height;
3232 int FFMPEG::ff_coded_width(int stream)
3234 return ffvideo[stream]->avctx->coded_width;
3237 int FFMPEG::ff_coded_height(int stream)
3239 return ffvideo[stream]->avctx->coded_height;
3242 float FFMPEG::ff_aspect_ratio(int stream)
3244 return ffvideo[stream]->aspect_ratio;
3247 const char* FFMPEG::ff_video_format(int stream)
3249 AVStream *st = ffvideo[stream]->st;
3250 AVCodecID id = st->codecpar->codec_id;
3251 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
3252 return desc ? desc->name : _("Unknown");
3255 double FFMPEG::ff_frame_rate(int stream)
3257 return ffvideo[stream]->frame_rate;
3260 int64_t FFMPEG::ff_video_frames(int stream)
3262 return ffvideo[stream]->length;
3265 int FFMPEG::ff_video_pid(int stream)
3267 return ffvideo[stream]->st->id;
3270 int FFMPEG::ff_video_mpeg_color_range(int stream)
3272 return ffvideo[stream]->st->codecpar->color_range == AVCOL_RANGE_MPEG ? 1 : 0;
3275 int FFMPEG::ff_cpus()
3277 return file_base->file->cpus;
3280 const char *FFMPEG::ff_hw_dev()
3282 return &file_base->file->preferences->use_hw_dev[0];
3285 Preferences *FFMPEG::ff_prefs()
3287 return !file_base ? 0 : file_base->file->preferences;
3290 int FFVideoStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
3292 avfilter_register_all();
3293 const char *sp = filter_spec;
3294 char filter_name[BCSTRLEN], *np = filter_name;
3295 int i = sizeof(filter_name);
3296 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
3298 const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
3299 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_VIDEO ) {
3300 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
3303 filter_graph = avfilter_graph_alloc();
3304 const AVFilter *buffersrc = avfilter_get_by_name("buffer");
3305 const AVFilter *buffersink = avfilter_get_by_name("buffersink");
3307 int ret = 0; char args[BCTEXTLEN];
3308 AVPixelFormat pix_fmt = (AVPixelFormat)avpar->format;
3309 snprintf(args, sizeof(args),
3310 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
3311 avpar->width, avpar->height, (int)pix_fmt,
3312 st->time_base.num, st->time_base.den,
3313 avpar->sample_aspect_ratio.num, avpar->sample_aspect_ratio.den);
3315 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
3316 args, NULL, filter_graph);
3318 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
3319 NULL, NULL, filter_graph);
3321 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
3322 (uint8_t*)&pix_fmt, sizeof(pix_fmt),
3323 AV_OPT_SEARCH_CHILDREN);
3325 ff_err(ret, "FFVideoStream::create_filter");
3327 ret = FFStream::create_filter(filter_spec);
3328 return ret >= 0 ? 0 : -1;
3331 int FFAudioStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
3333 avfilter_register_all();
3334 const char *sp = filter_spec;
3335 char filter_name[BCSTRLEN], *np = filter_name;
3336 int i = sizeof(filter_name);
3337 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
3339 const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
3340 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_AUDIO ) {
3341 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
3344 filter_graph = avfilter_graph_alloc();
3345 const AVFilter *buffersrc = avfilter_get_by_name("abuffer");
3346 const AVFilter *buffersink = avfilter_get_by_name("abuffersink");
3347 int ret = 0; char args[BCTEXTLEN];
3348 AVSampleFormat sample_fmt = (AVSampleFormat)avpar->format;
3349 snprintf(args, sizeof(args),
3350 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
3351 st->time_base.num, st->time_base.den, avpar->sample_rate,
3352 av_get_sample_fmt_name(sample_fmt), avpar->channel_layout);
3354 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
3355 args, NULL, filter_graph);
3357 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
3358 NULL, NULL, filter_graph);
3360 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
3361 (uint8_t*)&sample_fmt, sizeof(sample_fmt),
3362 AV_OPT_SEARCH_CHILDREN);
3364 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
3365 (uint8_t*)&avpar->channel_layout,
3366 sizeof(avpar->channel_layout), AV_OPT_SEARCH_CHILDREN);
3368 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
3369 (uint8_t*)&sample_rate, sizeof(sample_rate),
3370 AV_OPT_SEARCH_CHILDREN);
3372 ff_err(ret, "FFAudioStream::create_filter");
3374 ret = FFStream::create_filter(filter_spec);
3375 return ret >= 0 ? 0 : -1;
3378 int FFStream::create_filter(const char *filter_spec)
3380 /* Endpoints for the filter graph. */
3381 AVFilterInOut *outputs = avfilter_inout_alloc();
3382 outputs->name = av_strdup("in");
3383 outputs->filter_ctx = buffersrc_ctx;
3384 outputs->pad_idx = 0;
3387 AVFilterInOut *inputs = avfilter_inout_alloc();
3388 inputs->name = av_strdup("out");
3389 inputs->filter_ctx = buffersink_ctx;
3390 inputs->pad_idx = 0;
3393 int ret = !outputs->name || !inputs->name ? -1 : 0;
3395 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
3396 &inputs, &outputs, NULL);
3398 ret = avfilter_graph_config(filter_graph, NULL);
3401 ff_err(ret, "FFStream::create_filter");
3402 avfilter_graph_free(&filter_graph);
3405 avfilter_inout_free(&inputs);
3406 avfilter_inout_free(&outputs);
3410 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
3413 av_init_packet(&pkt);
3414 AVFrame *frame = av_frame_alloc();
3416 fprintf(stderr,"FFMPEG::scan: ");
3417 fprintf(stderr,_("av_frame_alloc failed\n"));
3418 fprintf(stderr,"FFMPEG::scan:file=%s\n", file_base->asset->path);
3422 index_state->add_video_markers(ffvideo.size());
3423 index_state->add_audio_markers(ffaudio.size());
3425 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
3427 AVDictionary *copts = 0;
3428 av_dict_copy(&copts, opts, 0);
3429 AVStream *st = fmt_ctx->streams[i];
3430 AVCodecID codec_id = st->codecpar->codec_id;
3431 AVCodec *decoder = avcodec_find_decoder(codec_id);
3432 AVCodecContext *avctx = avcodec_alloc_context3(decoder);
3434 eprintf(_("cant allocate codec context\n"));
3435 ret = AVERROR(ENOMEM);
3438 avcodec_parameters_to_context(avctx, st->codecpar);
3439 if( !av_dict_get(copts, "threads", NULL, 0) )
3440 avctx->thread_count = ff_cpus();
3441 ret = avcodec_open2(avctx, decoder, &copts);
3443 av_dict_free(&copts);
3445 AVCodecParameters *avpar = st->codecpar;
3446 switch( avpar->codec_type ) {
3447 case AVMEDIA_TYPE_VIDEO: {
3448 int vidx = ffvideo.size();
3449 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
3450 if( vidx < 0 ) break;
3451 ffvideo[vidx]->avctx = avctx;
3453 case AVMEDIA_TYPE_AUDIO: {
3454 int aidx = ffaudio.size();
3455 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3456 if( aidx < 0 ) break;
3457 ffaudio[aidx]->avctx = avctx;
3462 fprintf(stderr,"FFMPEG::scan: ");
3463 fprintf(stderr,_("codec open failed\n"));
3464 fprintf(stderr,"FFMPEG::scan:file=%s\n", file_base->asset->path);
3465 avcodec_free_context(&avctx);
3469 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
3470 AVStream *st = fmt_ctx->streams[i];
3471 AVCodecParameters *avpar = st->codecpar;
3472 if( avpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
3473 int64_t tstmp = st->start_time;
3474 if( tstmp == AV_NOPTS_VALUE ) continue;
3475 int aidx = ffaudio.size();
3476 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3477 if( aidx < 0 ) continue;
3478 FFAudioStream *aud = ffaudio[aidx];
3479 tstmp -= aud->nudge;
3480 double secs = to_secs(tstmp, st->time_base);
3481 aud->curr_pos = secs * aud->sample_rate + 0.5;
3485 for( int64_t count=0; !*canceled; ++count ) {
3486 av_packet_unref(&pkt);
3487 pkt.data = 0; pkt.size = 0;
3489 int ret = av_read_frame(fmt_ctx, &pkt);
3491 if( ret == AVERROR_EOF ) break;
3492 if( ++errs > 100 ) {
3493 ff_err(ret,_("over 100 read_frame errs\n"));
3498 if( !pkt.data ) continue;
3499 int i = pkt.stream_index;
3500 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
3501 AVStream *st = fmt_ctx->streams[i];
3502 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
3504 AVCodecParameters *avpar = st->codecpar;
3505 switch( avpar->codec_type ) {
3506 case AVMEDIA_TYPE_VIDEO: {
3507 int vidx = ffvideo.size();
3508 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
3509 if( vidx < 0 ) break;
3510 FFVideoStream *vid = ffvideo[vidx];
3511 if( !vid->avctx ) break;
3512 int64_t tstmp = pkt.dts;
3513 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.pts;
3514 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
3515 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
3516 double secs = to_secs(tstmp, st->time_base);
3517 int64_t frm = secs * vid->frame_rate + 0.5;
3518 if( frm < 0 ) frm = 0;
3519 index_state->put_video_mark(vidx, frm, pkt.pos);
3522 ret = avcodec_send_packet(vid->avctx, pkt);
3523 if( ret < 0 ) break;
3524 while( (ret=vid->decode_frame(frame)) > 0 ) {}
3527 case AVMEDIA_TYPE_AUDIO: {
3528 int aidx = ffaudio.size();
3529 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3530 if( aidx < 0 ) break;
3531 FFAudioStream *aud = ffaudio[aidx];
3532 if( !aud->avctx ) break;
3533 int64_t tstmp = pkt.pts;
3534 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
3535 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
3536 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
3537 double secs = to_secs(tstmp, st->time_base);
3538 int64_t sample = secs * aud->sample_rate + 0.5;
3540 index_state->put_audio_mark(aidx, sample, pkt.pos);
3542 ret = avcodec_send_packet(aud->avctx, &pkt);
3543 if( ret < 0 ) break;
3544 int ch = aud->channel0, nch = aud->channels;
3545 int64_t pos = index_state->pos(ch);
3546 if( pos != aud->curr_pos ) {
3547 if( abs(pos-aud->curr_pos) > 1 )
3548 printf("audio%d pad %jd %jd (%jd)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
3549 index_state->pad_data(ch, nch, aud->curr_pos);
3551 while( (ret=aud->decode_frame(frame)) > 0 ) {
3552 //if( frame->channels != nch ) break;
3553 aud->init_swr(frame->channels, frame->format, frame->sample_rate);
3555 int len = aud->get_samples(samples,
3556 &frame->extended_data[0], frame->nb_samples);
3557 pos = aud->curr_pos;
3558 if( (aud->curr_pos += len) >= 0 ) {
3560 samples += -pos * nch;
3561 len = aud->curr_pos;
3563 for( int i=0; i<nch; ++i )
3564 index_state->put_data(ch+i,nch,samples+i,len);
3571 av_frame_free(&frame);
3575 void FFStream::load_markers(IndexMarks &marks, double rate)
3578 int64_t sz = marks.size();
3579 int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
3580 int nb_ent = st->nb_index_entries;
3581 // some formats already have an index
3583 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
3584 int64_t tstmp = ep->timestamp;
3585 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
3586 double secs = ffmpeg->to_secs(tstmp, st->time_base);
3587 int64_t no = secs * rate;
3588 while( in < sz && marks[in].no <= no ) ++in;
3590 int64_t len = sz - in;
3591 int64_t count = max_entries - nb_ent;
3592 if( count > len ) count = len;
3593 for( int i=0; i<count; ++i ) {
3594 int k = in + i * len / count;
3595 int64_t no = marks[k].no, pos = marks[k].pos;
3596 double secs = (double)no / rate;
3597 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
3598 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
3599 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);