10 // work arounds (centos)
13 #define INT64_MAX 9223372036854775807LL
15 #define MAX_RETRY 1000
18 #include "bccmodels.h"
20 #include "fileffmpeg.h"
23 #include "indexfile.h"
26 #include "mainerror.h"
31 #define VIDEO_INBUF_SIZE 0x10000
32 #define AUDIO_INBUF_SIZE 0x10000
33 #define VIDEO_REFILL_THRESH 0
34 #define AUDIO_REFILL_THRESH 0x1000
36 Mutex FFMPEG::fflock("FFMPEG::fflock");
38 static void ff_err(int ret, const char *fmt, ...)
43 vsnprintf(msg, sizeof(msg), fmt, ap);
45 char errmsg[BCSTRLEN];
46 av_strerror(ret, errmsg, sizeof(errmsg));
47 fprintf(stderr,_("%s err: %s\n"),msg, errmsg);
53 pkt.data = 0; pkt.size = 0;
55 void FFPacket::finit()
57 av_packet_unref(&pkt);
60 FFrame::FFrame(FFStream *fst)
63 frm = av_frame_alloc();
64 init = fst->init_frame(frm);
72 void FFrame::queue(int64_t pos)
78 void FFrame::dequeue()
83 int FFAudioStream::read(float *fp, long len)
91 while( --k >= 0 ) *fp++ = *op++;
92 if( op >= lmt ) op = bfr;
97 void FFAudioStream::realloc(long nsz, int nch, long len)
100 float *np = new float[bsz];
101 inp = np + read(np, len) * nch;
106 delete [] bfr; bfr = np;
109 void FFAudioStream::realloc(long nsz, int nch)
111 if( nsz > sz || this->nch != nch ) {
112 long len = this->nch != nch ? 0 : hpos;
113 if( len > sz ) len = sz;
115 realloc(nsz, nch, len);
119 void FFAudioStream::reserve(long nsz, int nch)
121 long len = (inp - outp) / nch;
123 if( nsz > sz || this->nch != nch ) {
124 if( this->nch != nch ) len = 0;
125 realloc(nsz, nch, len);
128 if( (len*=nch) > 0 && bfr != outp )
129 memmove(bfr, outp, len*sizeof(*bfr));
134 long FFAudioStream::used()
136 long len = inp>=outp ? inp-outp : inp-bfr + lmt-outp;
139 long FFAudioStream::avail()
142 if( in1 >= lmt ) in1 = bfr;
143 long len = outp >= in1 ? outp-in1 : outp-bfr + lmt-in1;
146 void FFAudioStream::reset_history()
152 void FFAudioStream::iseek(int64_t ofs)
154 outp = inp - ofs*nch;
155 if( outp < bfr ) outp += sz*nch;
158 float *FFAudioStream::get_outp(int ofs)
165 int64_t FFAudioStream::put_inp(int ofs)
168 return (inp-outp) / nch;
171 int FFAudioStream::write(const float *fp, long len)
179 while( --k >= 0 ) *ip++ = *fp++;
180 if( ip >= lmt ) ip = bfr;
187 int FFAudioStream::zero(long len)
195 while( --k >= 0 ) *ip++ = 0;
196 if( ip >= lmt ) ip = bfr;
203 // does not advance outp
204 int FFAudioStream::read(double *dp, long len, int ch)
207 float *op = outp + ch;
208 float *lmt1 = lmt + nch-1;
210 int k = (lmt1 - op) / nch;
213 while( --k >= 0 ) { *dp++ = *op; op += nch; }
214 if( op >= lmt ) op -= sz*nch;
219 // load linear buffer, no wrapping allowed, does not advance inp
220 int FFAudioStream::write(const double *dp, long len, int ch)
223 float *ip = inp + ch;
224 while( --n >= 0 ) { *ip = *dp++; ip += nch; }
229 FFStream::FFStream(FFMPEG *ffmpeg, AVStream *st, int fidx)
231 this->ffmpeg = ffmpeg;
234 frm_lock = new Mutex("FFStream::frm_lock");
240 nudge = AV_NOPTS_VALUE;
241 seek_pos = curr_pos = 0;
243 reading = writing = 0;
249 FFStream::~FFStream()
251 if( reading > 0 || writing > 0 ) avcodec_close(st->codec);
252 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
253 while( frms.first ) frms.remove(frms.first);
254 if( filter_graph ) avfilter_graph_free(&filter_graph);
255 if( frame ) av_frame_free(&frame);
256 if( fframe ) av_frame_free(&fframe);
257 bsfilter.remove_all_objects();
261 void FFStream::ff_lock(const char *cp)
263 FFMPEG::fflock.lock(cp);
266 void FFStream::ff_unlock()
268 FFMPEG::fflock.unlock();
271 void FFStream::queue(FFrame *frm)
273 frm_lock->lock("FFStream::queue");
277 ffmpeg->mux_lock->unlock();
280 void FFStream::dequeue(FFrame *frm)
282 frm_lock->lock("FFStream::dequeue");
284 frms.remove_pointer(frm);
288 int FFStream::encode_activate()
291 writing = ffmpeg->encode_activate();
295 int FFStream::decode_activate()
297 if( reading < 0 && (reading=ffmpeg->decode_activate()) > 0 ) {
298 ff_lock("FFStream::decode_activate");
300 AVDictionary *copts = 0;
301 av_dict_copy(&copts, ffmpeg->opts, 0);
303 // this should be avformat_copy_context(), but no copy avail
304 ret = avformat_open_input(&fmt_ctx, ffmpeg->fmt_ctx->filename, NULL, &copts);
306 ret = avformat_find_stream_info(fmt_ctx, 0);
307 st = fmt_ctx->streams[fidx];
311 AVCodecID codec_id = st->codec->codec_id;
312 AVCodec *decoder = avcodec_find_decoder(codec_id);
313 ret = avcodec_open2(st->codec, decoder, &copts);
317 eprintf(_("open decoder failed\n"));
320 eprintf(_("can't clone input file\n"));
321 av_dict_free(&copts);
327 int FFStream::read_packet()
329 av_packet_unref(ipkt);
330 int ret = av_read_frame(fmt_ctx, ipkt);
333 if( ret == AVERROR_EOF ) {
334 ipkt->stream_index = st->index;
337 ff_err(ret, "FFStream::read_packet: av_read_frame failed\n");
344 int FFStream::decode(AVFrame *frame)
347 int retries = MAX_RETRY;
350 while( ret >= 0 && !flushed && --retries >= 0 && !got_frame ) {
353 if( (ret=read_packet()) < 0 ) break;
355 if( ipkt->stream_index == st->index ) {
356 while( (ipkt->size > 0 || !ipkt->data) && !got_frame ) {
357 ret = decode_frame(ipkt, frame, got_frame);
358 if( ret < 0 ) need_packet = 1;
359 if( ret <= 0 || !ipkt->data ) break;
372 fprintf(stderr, "FFStream::decode: Retry limit\n");
376 fprintf(stderr, "FFStream::decode: failed\n");
381 int FFStream::load_filter(AVFrame *frame)
383 int ret = av_buffersrc_add_frame_flags(buffersrc_ctx,
384 frame, AV_BUFFERSRC_FLAG_KEEP_REF);
386 av_frame_unref(frame);
387 eprintf(_("av_buffersrc_add_frame_flags failed\n"));
392 int FFStream::read_filter(AVFrame *frame)
394 int ret = av_buffersink_get_frame(buffersink_ctx, frame);
396 if( ret == AVERROR(EAGAIN) ) return 0;
397 if( ret == AVERROR_EOF ) { st_eof(1); return -1; }
398 ff_err(ret, "FFStream::read_filter: av_buffersink_get_frame failed\n");
404 int FFStream::read_frame(AVFrame *frame)
406 if( !filter_graph || !buffersrc_ctx || !buffersink_ctx )
407 return decode(frame);
408 if( !fframe && !(fframe=av_frame_alloc()) ) {
409 fprintf(stderr, "FFStream::read_frame: av_frame_alloc failed\n");
413 while( !flushed && !(ret=read_filter(frame)) ) {
414 if( (ret=decode(fframe)) < 0 ) break;
415 if( ret > 0 && (ret=load_filter(fframe)) < 0 ) break;
420 int FFStream::write_packet(FFPacket &pkt)
423 av_packet_rescale_ts(pkt, st->codec->time_base, st->time_base);
424 pkt->stream_index = st->index;
425 return av_interleaved_write_frame(ffmpeg->fmt_ctx, pkt);
428 int FFStream::flush()
436 ret = encode_frame(pkt, 0, got_packet);
437 if( ret < 0 || !got_packet ) break;
438 ret = write_packet(pkt);
441 ff_err(ret, "FFStream::flush");
442 return ret >= 0 ? 0 : 1;
445 int FFStream::seek(int64_t no, double rate)
447 int64_t tstmp = -INT64_MAX+1;
448 // default ffmpeg native seek
450 int64_t pos = no, plmt = -1;
451 IndexMarks *index_markers = get_markers();
452 if( index_markers && index_markers->size() > 1 ) {
453 IndexMarks &marks = *index_markers;
454 int i = marks.find(pos);
455 int64_t n = i < 0 ? (i=0) : marks[i].no;
456 // if indexed seek point not too far away (<30 secs), use index
457 if( no-n < 30*rate ) {
460 if( i < marks.size() ) plmt = marks[i].pos;
465 double secs = pos / rate;
466 tstmp = secs * st->time_base.den / st->time_base.num;
467 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
469 int ret = avformat_seek_file(fmt_ctx, st->index,
470 -INT64_MAX, tstmp, INT64_MAX, AVSEEK_FLAG_ANY);
472 avcodec_flush_buffers(st->codec);
473 ipkt.finit(); ipkt.init();
474 need_packet = 0; flushed = 0;
475 seeked = 1; st_eof(0);
476 // read up to retry packets, limited to npkts in stream, and not past pkt.pos plmt
478 if( read_packet() <= 0 ) { ret = -1; break; }
479 if( plmt >= 0 && ipkt->pos >= plmt ) break;
480 if( ipkt->stream_index != st->index ) continue;
481 if( --npkts <= 0 ) break;
482 int64_t pkt_ts = ipkt->dts != AV_NOPTS_VALUE ? ipkt->dts : ipkt->pts;
483 if( pkt_ts == AV_NOPTS_VALUE ) continue;
484 if( pkt_ts >= tstmp ) break;
488 //printf("** seek fail %ld, %ld\n", pos, tstmp);
489 seeked = need_packet = 0;
493 //printf("seeked pos = %ld, %ld\n", pos, tstmp);
494 seek_pos = curr_pos = pos;
498 FFAudioStream::FFAudioStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
499 : FFStream(ffmpeg, strm, fidx)
502 channel0 = channels = 0;
506 resample_context = 0;
515 bfr = new float[bsz];
520 FFAudioStream::~FFAudioStream()
522 if( resample_context ) swr_free(&resample_context);
527 int FFAudioStream::get_samples(float *&samples, uint8_t **data, int len)
529 samples = *(float **)data;
530 if( resample_context ) {
531 if( len > aud_bfr_sz ) {
537 aud_bfr = new float[aud_bfr_sz*channels];
539 int ret = swr_convert(resample_context,
540 (uint8_t**)&aud_bfr, aud_bfr_sz, (const uint8_t**)data, len);
542 ff_err(ret, "FFAudioStream::get_samples: swr_convert failed\n");
551 int FFAudioStream::load_history(uint8_t **data, int len)
554 len = get_samples(samples, data, len);
556 // biggest user bfr since seek + frame
557 realloc(mbsz + len + 1, channels);
563 int FFAudioStream::decode_frame(AVPacket *pkt, AVFrame *frame, int &got_frame)
565 int first_frame = seeked; seeked = 0;
566 int ret = avcodec_decode_audio4(st->codec, frame, &got_frame, pkt);
568 if( first_frame ) return 0;
569 ff_err(ret, "FFAudioStream::decode_frame: Could not read audio frame\n");
573 int64_t pkt_ts = av_frame_get_best_effort_timestamp(frame);
574 if( pkt_ts != AV_NOPTS_VALUE )
575 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * sample_rate + 0.5;
580 int FFAudioStream::encode_activate()
582 if( writing >= 0 ) return writing;
583 AVCodecContext *ctx = st->codec;
584 frame_sz = ctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE ?
585 10000 : ctx->frame_size;
586 return FFStream::encode_activate();
589 int FFAudioStream::nb_samples()
591 AVCodecContext *ctx = st->codec;
592 return ctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE ?
593 10000 : ctx->frame_size;
596 int64_t FFAudioStream::load_buffer(double ** const sp, int len)
598 reserve(len+1, st->codec->channels);
599 for( int ch=0; ch<nch; ++ch )
600 write(sp[ch], len, ch);
604 int FFAudioStream::in_history(int64_t pos)
606 if( pos > curr_pos ) return 0;
608 if( len > sz ) len = sz;
609 if( pos < curr_pos - len ) return 0;
614 int FFAudioStream::init_frame(AVFrame *frame)
616 AVCodecContext *ctx = st->codec;
617 frame->nb_samples = frame_sz;
618 frame->format = ctx->sample_fmt;
619 frame->channel_layout = ctx->channel_layout;
620 frame->sample_rate = ctx->sample_rate;
621 int ret = av_frame_get_buffer(frame, 0);
623 ff_err(ret, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
627 int FFAudioStream::load(int64_t pos, int len)
629 if( audio_seek(pos) < 0 ) return -1;
630 if( !frame && !(frame=av_frame_alloc()) ) {
631 fprintf(stderr, "FFAudioStream::load: av_frame_alloc failed\n");
634 if( mbsz < len ) mbsz = len;
635 int64_t end_pos = pos + len;
637 for( int i=0; ret>=0 && !flushed && curr_pos<end_pos && i<MAX_RETRY; ++i ) {
638 ret = read_frame(frame);
640 load_history(&frame->extended_data[0], frame->nb_samples);
641 curr_pos += frame->nb_samples;
644 if( end_pos > curr_pos ) {
645 zero(end_pos - curr_pos);
648 len = curr_pos - pos;
653 int FFAudioStream::audio_seek(int64_t pos)
655 if( decode_activate() < 0 ) return -1;
656 if( !st->codec || !st->codec->codec ) return -1;
657 if( in_history(pos) ) return 0;
658 if( pos == curr_pos ) return 0;
659 reset_history(); mbsz = 0;
660 // guarentee preload > 1sec samples
661 if( seek(pos-sample_rate, sample_rate) < 0 ) return -1;
665 int FFAudioStream::encode(double **samples, int len)
667 if( encode_activate() <= 0 ) return -1;
670 int64_t count = load_buffer(samples, len);
673 while( ret >= 0 && count >= frame_sz ) {
674 frm = new FFrame(this);
675 if( (ret=frm->initted()) < 0 ) break;
676 AVFrame *frame = *frm;
677 float *bfrp = get_outp(frame_sz);
678 ret = swr_convert(resample_context,
679 (uint8_t **)frame->extended_data, frame_sz,
680 (const uint8_t **)&bfrp, frame_sz);
682 ff_err(ret, "FFAudioStream::encode: swr_convert failed\n");
685 frm->queue(curr_pos);
687 curr_pos += frame_sz;
692 return ret >= 0 ? 0 : 1;
695 int FFAudioStream::encode_frame(AVPacket *pkt, AVFrame *frame, int &got_packet)
697 int ret = avcodec_encode_audio2(st->codec, pkt, frame, &got_packet);
699 ff_err(ret, "FFAudioStream::encode_frame: encode audio failed\n");
705 void FFAudioStream::load_markers()
707 IndexState *index_state = ffmpeg->file_base->asset->index_state;
708 if( !index_state || idx >= index_state->audio_markers.size() ) return;
709 if( index_state->marker_status == MARKERS_NOTTESTED ) return;
710 FFStream::load_markers(*index_state->audio_markers[idx], sample_rate);
713 IndexMarks *FFAudioStream::get_markers()
715 IndexState *index_state = ffmpeg->file_base->asset->index_state;
716 if( !index_state || idx >= index_state->audio_markers.size() ) return 0;
717 return index_state->audio_markers[idx];
720 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
721 : FFStream(ffmpeg, strm, fidx)
730 FFVideoStream::~FFVideoStream()
734 int FFVideoStream::decode_frame(AVPacket *pkt, AVFrame *frame, int &got_frame)
736 int first_frame = seeked; seeked = 0;
737 int ret = avcodec_decode_video2(st->codec, frame, &got_frame, pkt);
739 if( first_frame ) return 0;
740 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame\n");
743 else // this is right out of ffplay, looks questionable ???
747 int64_t pkt_ts = av_frame_get_best_effort_timestamp(frame);
748 if( pkt_ts != AV_NOPTS_VALUE )
749 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * frame_rate + 0.5;
754 int FFVideoStream::load(VFrame *vframe, int64_t pos)
756 int ret = video_seek(pos);
757 if( ret < 0 ) return -1;
758 if( !frame && !(frame=av_frame_alloc()) ) {
759 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
762 for( int i=0; ret>=0 && !flushed && curr_pos<=pos && i<MAX_RETRY; ++i ) {
763 ret = read_frame(frame);
764 if( ret > 0 ) ++curr_pos;
766 if( frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0 )
769 ret = convert_cmodel(vframe, frame);
771 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
775 int FFVideoStream::video_seek(int64_t pos)
777 if( decode_activate() < 0 ) return -1;
778 if( !st->codec || !st->codec->codec ) return -1;
779 if( pos == curr_pos-1 && !seeked ) return 0;
780 // if close enough, just read up to current
781 int gop = st->codec->gop_size;
782 if( gop < 4 ) gop = 4;
783 if( gop > 64 ) gop = 64;
784 int read_limit = curr_pos + 3*gop;
785 if( pos >= curr_pos && pos <= read_limit ) return 0;
786 // guarentee preload more than 2*gop frames
787 if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
791 int FFVideoStream::init_frame(AVFrame *picture)
793 AVCodecContext *ctx = st->codec;
794 picture->format = ctx->pix_fmt;
795 picture->width = ctx->width;
796 picture->height = ctx->height;
797 int ret = av_frame_get_buffer(picture, 32);
801 int FFVideoStream::encode(VFrame *vframe)
803 if( encode_activate() <= 0 ) return -1;
805 FFrame *picture = new FFrame(this);
806 int ret = picture->initted();
808 AVFrame *frame = *picture;
809 frame->pts = curr_pos;
810 ret = convert_pixfmt(vframe, frame);
813 picture->queue(curr_pos);
817 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
820 return ret >= 0 ? 0 : 1;
823 int FFVideoStream::encode_frame(AVPacket *pkt, AVFrame *frame, int &got_packet)
825 int ret = avcodec_encode_video2(st->codec, pkt, frame, &got_packet);
827 ff_err(ret, "FFVideoStream::encode_frame: encode video failed\n");
833 AVPixelFormat FFVideoConvert::color_model_to_pix_fmt(int color_model)
835 switch( color_model ) {
836 case BC_YUV422: return AV_PIX_FMT_YUYV422;
837 case BC_RGB888: return AV_PIX_FMT_RGB24;
838 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
839 case BC_BGR8888: return AV_PIX_FMT_BGR0;
840 case BC_BGR888: return AV_PIX_FMT_BGR24;
841 case BC_ARGB8888: return AV_PIX_FMT_ARGB;
842 case BC_ABGR8888: return AV_PIX_FMT_ABGR;
843 case BC_RGB8: return AV_PIX_FMT_RGB8;
844 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
845 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
846 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
847 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
848 case BC_RGB565: return AV_PIX_FMT_RGB565;
849 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
850 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
854 return AV_PIX_FMT_NB;
857 int FFVideoConvert::pix_fmt_to_color_model(AVPixelFormat pix_fmt)
860 case AV_PIX_FMT_YUYV422: return BC_YUV422;
861 case AV_PIX_FMT_RGB24: return BC_RGB888;
862 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
863 case AV_PIX_FMT_BGR0: return BC_BGR8888;
864 case AV_PIX_FMT_BGR24: return BC_BGR888;
865 case AV_PIX_FMT_ARGB: return BC_ARGB8888;
866 case AV_PIX_FMT_ABGR: return BC_ABGR8888;
867 case AV_PIX_FMT_RGB8: return BC_RGB8;
868 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
869 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
870 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
871 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
872 case AV_PIX_FMT_RGB565: return BC_RGB565;
873 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
874 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
881 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip)
883 AVFrame *ipic = av_frame_alloc();
884 int ret = convert_picture_vframe(frame, ip, ipic);
885 av_frame_free(&ipic);
889 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip, AVFrame *ipic)
891 int cmodel = frame->get_color_model();
892 AVPixelFormat ofmt = color_model_to_pix_fmt(cmodel);
893 if( ofmt == AV_PIX_FMT_NB ) return -1;
894 int size = av_image_fill_arrays(ipic->data, ipic->linesize,
895 frame->get_data(), ofmt, frame->get_w(), frame->get_h(), 1);
896 if( size < 0 ) return -1;
898 int bpp = BC_CModels::calculate_pixelsize(cmodel);
899 int ysz = bpp * frame->get_w(), usz = ysz;
908 // override av_image_fill_arrays() for planar types
909 ipic->data[0] = frame->get_y(); ipic->linesize[0] = ysz;
910 ipic->data[1] = frame->get_u(); ipic->linesize[1] = usz;
911 ipic->data[2] = frame->get_v(); ipic->linesize[2] = usz;
914 ipic->data[0] = frame->get_data();
915 ipic->linesize[0] = frame->get_bytes_per_line();
919 AVPixelFormat pix_fmt = (AVPixelFormat)ip->format;
920 convert_ctx = sws_getCachedContext(convert_ctx, ip->width, ip->height, pix_fmt,
921 frame->get_w(), frame->get_h(), ofmt, SWS_BICUBIC, NULL, NULL, NULL);
923 fprintf(stderr, "FFVideoConvert::convert_picture_frame:"
924 " sws_getCachedContext() failed\n");
927 int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ip->height,
928 ipic->data, ipic->linesize);
930 ff_err(ret, "FFVideoConvert::convert_picture_frame: sws_scale() failed\n");
936 int FFVideoConvert::convert_cmodel(VFrame *frame, AVFrame *ip)
938 // try direct transfer
939 if( !convert_picture_vframe(frame, ip) ) return 1;
940 // use indirect transfer
941 AVPixelFormat pix_fmt = (AVPixelFormat)ip->format;
942 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
944 for( int i = 0; i <desc->nb_components; ++i ) {
945 int bits = desc->comp[i].depth;
946 if( bits > max_bits ) max_bits = bits;
948 // from libavcodec/pixdesc.c
949 #define pixdesc_has_alpha(pixdesc) ((pixdesc)->nb_components == 2 || \
950 (pixdesc)->nb_components == 4 || (pixdesc)->flags & AV_PIX_FMT_FLAG_PAL)
951 int icolor_model = pixdesc_has_alpha(desc) ?
952 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
953 (max_bits > 8 ? BC_RGB161616 : BC_RGB888) ;
954 VFrame vframe(ip->width, ip->height, icolor_model);
955 if( convert_picture_vframe(&vframe, ip) ) return -1;
956 frame->transfer_from(&vframe);
960 int FFVideoConvert::transfer_cmodel(VFrame *frame, AVFrame *ifp)
962 int ret = convert_cmodel(frame, ifp);
964 const AVDictionary *src = av_frame_get_metadata(ifp);
965 AVDictionaryEntry *t = NULL;
966 BC_Hash *hp = frame->get_params();
968 while( (t=av_dict_get(src, "", t, AV_DICT_IGNORE_SUFFIX)) )
969 hp->update(t->key, t->value);
974 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op)
976 AVFrame *opic = av_frame_alloc();
977 int ret = convert_vframe_picture(frame, op, opic);
978 av_frame_free(&opic);
982 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op, AVFrame *opic)
984 int cmodel = frame->get_color_model();
985 AVPixelFormat ifmt = color_model_to_pix_fmt(cmodel);
986 if( ifmt == AV_PIX_FMT_NB ) return -1;
987 int size = av_image_fill_arrays(opic->data, opic->linesize,
988 frame->get_data(), ifmt, frame->get_w(), frame->get_h(), 1);
989 if( size < 0 ) return -1;
991 int bpp = BC_CModels::calculate_pixelsize(cmodel);
992 int ysz = bpp * frame->get_w(), usz = ysz;
1001 // override av_image_fill_arrays() for planar types
1002 opic->data[0] = frame->get_y(); opic->linesize[0] = ysz;
1003 opic->data[1] = frame->get_u(); opic->linesize[1] = usz;
1004 opic->data[2] = frame->get_v(); opic->linesize[2] = usz;
1007 opic->data[0] = frame->get_data();
1008 opic->linesize[0] = frame->get_bytes_per_line();
1012 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1013 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(),
1014 ifmt, op->width, op->height, ofmt, SWS_BICUBIC, NULL, NULL, NULL);
1015 if( !convert_ctx ) {
1016 fprintf(stderr, "FFVideoConvert::convert_frame_picture:"
1017 " sws_getCachedContext() failed\n");
1020 int ret = sws_scale(convert_ctx, opic->data, opic->linesize, 0, frame->get_h(),
1021 op->data, op->linesize);
1023 ff_err(ret, "FFVideoConvert::convert_frame_picture: sws_scale() failed\n");
1029 int FFVideoConvert::convert_pixfmt(VFrame *frame, AVFrame *op)
1031 // try direct transfer
1032 if( !convert_vframe_picture(frame, op) ) return 1;
1033 // use indirect transfer
1034 int colormodel = frame->get_color_model();
1035 int bits = BC_CModels::calculate_pixelsize(colormodel) * 8;
1036 bits /= BC_CModels::components(colormodel);
1037 int icolor_model = BC_CModels::has_alpha(colormodel) ?
1038 (bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1039 (bits > 8 ? BC_RGB161616: BC_RGB888) ;
1040 VFrame vframe(frame->get_w(), frame->get_h(), icolor_model);
1041 vframe.transfer_from(frame);
1042 if( !convert_vframe_picture(&vframe, op) ) return 1;
1046 int FFVideoConvert::transfer_pixfmt(VFrame *frame, AVFrame *ofp)
1048 int ret = convert_pixfmt(frame, ofp);
1050 BC_Hash *hp = frame->get_params();
1051 AVDictionary **dict = avpriv_frame_get_metadatap(ofp);
1052 //av_dict_free(dict);
1053 for( int i=0; i<hp->size(); ++i ) {
1054 char *key = hp->get_key(i), *val = hp->get_value(i);
1055 av_dict_set(dict, key, val, 0);
1061 void FFVideoStream::load_markers()
1063 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1064 if( !index_state || idx >= index_state->video_markers.size() ) return;
1065 FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
1068 IndexMarks *FFVideoStream::get_markers()
1070 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1071 if( !index_state || idx >= index_state->video_markers.size() ) return 0;
1072 return !index_state ? 0 : index_state->video_markers[idx];
1076 FFMPEG::FFMPEG(FileBase *file_base)
1079 this->file_base = file_base;
1080 memset(file_format,0,sizeof(file_format));
1081 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
1082 flow_lock = new Condition(1,"FFStream::flow_lock",0);
1085 decoding = encoding = 0;
1086 has_audio = has_video = 0;
1089 opt_video_filter = 0;
1090 opt_audio_filter = 0;
1091 char option_path[BCTEXTLEN];
1092 set_option_path(option_path, "%s", "ffmpeg.opts");
1093 read_options(option_path, opts);
1098 ff_lock("FFMPEG::~FFMPEG()");
1100 ffaudio.remove_all_objects();
1101 ffvideo.remove_all_objects();
1102 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1106 av_dict_free(&opts);
1107 delete [] opt_video_filter;
1108 delete [] opt_audio_filter;
1111 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1113 const int *p = codec->supported_samplerates;
1114 if( !p ) return sample_rate;
1116 if( *p == sample_rate ) return *p;
1122 static inline AVRational std_frame_rate(int i)
1124 static const int m1 = 1001*12, m2 = 1000*12;
1125 static const int freqs[] = {
1126 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1127 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
1129 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1130 return (AVRational) { freq, 1001*12 };
1133 AVRational FFMPEG::check_frame_rate(AVCodec *codec, double frame_rate)
1135 const AVRational *p = codec->supported_framerates;
1136 AVRational rate, best_rate = (AVRational) { 0, 0 };
1137 double max_err = 1.; int i = 0;
1138 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1139 double framerate = (double) rate.num / rate.den;
1140 double err = fabs(frame_rate/framerate - 1.);
1141 if( err >= max_err ) continue;
1145 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1148 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1151 double display_aspect = asset->width / (double)asset->height;
1152 double sample_aspect = asset->aspect_ratio / display_aspect;
1153 int width = 1000000, height = width * sample_aspect + 0.5;
1155 MWindow::create_aspect_ratio(w, h, width, height);
1156 return (AVRational){(int)h, (int)w};
1159 return (AVRational){1, 1};
1163 AVRational FFMPEG::to_time_base(int sample_rate)
1165 return (AVRational){1, sample_rate};
1168 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
1170 char *ep = path + BCTEXTLEN-1;
1171 strncpy(path, File::get_cindat_path(), ep-path);
1172 strncat(path, "/ffmpeg/", ep-path);
1173 path += strlen(path);
1176 path += vsnprintf(path, ep-path, fmt, ap);
1181 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
1186 set_option_path(path, "%s/%s", type, spec);
1189 int FFMPEG::get_format(char *format, const char *path, const char *spec)
1191 char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
1192 get_option_path(option_path, path, spec);
1193 FILE *fp = fopen(option_path,"r");
1196 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1198 line[sizeof(line)-1] = 0;
1199 ret = scan_option_line(line, format, codec);
1205 int FFMPEG::get_codec(char *codec, const char *path, const char *spec)
1207 char option_path[BCTEXTLEN], line[BCTEXTLEN], format[BCTEXTLEN];
1208 get_option_path(option_path, path, spec);
1209 FILE *fp = fopen(option_path,"r");
1212 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1215 line[sizeof(line)-1] = 0;
1216 ret = scan_option_line(line, format, codec);
1219 char *vp = codec, *ep = vp+BCTEXTLEN-1;
1220 while( vp < ep && *vp && *vp != '|' ) ++vp;
1221 if( *vp == '|' ) --vp;
1222 while( vp > codec && (*vp==' ' || *vp=='\t') ) *vp-- = 0;
1227 int FFMPEG::get_file_format()
1230 char audio_format[BCSTRLEN], video_format[BCSTRLEN];
1231 file_format[0] = audio_format[0] = video_format[0] = 0;
1232 Asset *asset = file_base->asset;
1233 if( !ret && asset->audio_data )
1234 ret = get_format(audio_format, "audio", asset->acodec);
1235 if( !ret && asset->video_data )
1236 ret = get_format(video_format, "video", asset->vcodec);
1237 if( !ret && !audio_format[0] && !video_format[0] )
1239 if( !ret && audio_format[0] && video_format[0] &&
1240 strcmp(audio_format, video_format) ) ret = -1;
1242 strcpy(file_format, audio_format[0] ? audio_format : video_format);
1246 int FFMPEG::scan_option_line(char *cp, char *tag, char *val)
1248 while( *cp == ' ' || *cp == '\t' ) ++cp;
1250 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' ) ++cp;
1252 if( !len || len > BCSTRLEN-1 ) return 1;
1253 while( bp < cp ) *tag++ = *bp++;
1255 while( *cp == ' ' || *cp == '\t' ) ++cp;
1256 if( *cp == '=' ) ++cp;
1257 while( *cp == ' ' || *cp == '\t' ) ++cp;
1259 while( *cp && *cp != '\n' ) ++cp;
1261 if( len > BCTEXTLEN-1 ) return 1;
1262 while( bp < cp ) *val++ = *bp++;
1267 int FFMPEG::load_defaults(const char *path, const char *type,
1268 char *codec, char *codec_options, int len)
1270 char default_file[BCTEXTLEN];
1271 FFMPEG::set_option_path(default_file, "%s/%s.dfl", path, type);
1272 FILE *fp = fopen(default_file,"r");
1274 fgets(codec, BCSTRLEN, fp);
1276 while( *cp && *cp!='\n' ) ++cp;
1278 while( len > 0 && fgets(codec_options, len, fp) ) {
1279 int n = strlen(codec_options);
1280 codec_options += n; len -= n;
1283 FFMPEG::set_option_path(default_file, "%s/%s", path, codec);
1284 return FFMPEG::load_options(default_file, codec_options, len);
1287 void FFMPEG::set_asset_format(Asset *asset, const char *text)
1289 if( asset->format != FILE_FFMPEG ) return;
1290 strcpy(asset->fformat, text);
1291 if( !asset->ff_audio_options[0] ) {
1292 asset->audio_data = !load_defaults("audio", text, asset->acodec,
1293 asset->ff_audio_options, sizeof(asset->ff_audio_options));
1295 if( !asset->ff_video_options[0] ) {
1296 asset->video_data = !load_defaults("video", text, asset->vcodec,
1297 asset->ff_video_options, sizeof(asset->ff_video_options));
1301 int FFMPEG::get_encoder(const char *options,
1302 char *format, char *codec, char *bsfilter, char *bsargs)
1304 FILE *fp = fopen(options,"r");
1306 eprintf(_("options open failed %s\n"),options);
1309 if( get_encoder(fp, format, codec, bsfilter, bsargs) )
1310 eprintf(_("format/codec not found %s\n"), options);
1315 int FFMPEG::get_encoder(FILE *fp,
1316 char *format, char *codec, char *bsfilter, char *bsargs)
1318 format[0] = codec[0] = bsfilter[0] = bsargs[0] = 0;
1319 char line[BCTEXTLEN];
1320 if( !fgets(line, sizeof(line), fp) ) return 1;
1321 line[sizeof(line)-1] = 0;
1322 if( scan_option_line(line, format, codec) ) return 1;
1324 while( *cp && *cp != '|' ) ++cp;
1325 if( !*cp ) return 0;
1326 if( scan_option_line(cp+1, bsfilter, bsargs) ) return 1;
1327 do { *cp-- = 0; } while( cp>=codec && (*cp==' ' || *cp == '\t' ) );
1331 int FFMPEG::read_options(const char *options, AVDictionary *&opts)
1333 FILE *fp = fopen(options,"r");
1335 int ret = read_options(fp, options, opts);
1340 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
1342 FILE *fp = fmemopen((void *)options,strlen(options),"r");
1344 int ret = read_options(fp, options, opts);
1346 AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
1347 if( tag ) st->id = strtol(tag->value,0,0);
1351 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
1353 int ret = 0, no = 0;
1354 char line[BCTEXTLEN];
1355 while( !ret && fgets(line, sizeof(line), fp) ) {
1356 line[sizeof(line)-1] = 0;
1358 if( line[0] == '#' ) continue;
1359 if( line[0] == '\n' ) continue;
1360 char key[BCSTRLEN], val[BCTEXTLEN];
1361 if( scan_option_line(line, key, val) ) {
1362 eprintf(_("err reading %s: line %d\n"), options, no);
1366 if( !strcmp(key, "duration") )
1367 opt_duration = strtod(val, 0);
1368 else if( !strcmp(key, "video_filter") )
1369 opt_video_filter = cstrdup(val);
1370 else if( !strcmp(key, "audio_filter") )
1371 opt_audio_filter = cstrdup(val);
1372 else if( !strcmp(key, "loglevel") )
1375 av_dict_set(&opts, key, val, 0);
1381 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
1383 char option_path[BCTEXTLEN];
1384 set_option_path(option_path, "%s", options);
1385 return read_options(option_path, opts);
1388 int FFMPEG::load_options(const char *path, char *bfr, int len)
1391 FILE *fp = fopen(path, "r");
1393 fgets(bfr, len, fp); // skip hdr
1394 len = fread(bfr, 1, len-1, fp);
1395 if( len < 0 ) len = 0;
1401 void FFMPEG::set_loglevel(const char *ap)
1403 if( !ap || !*ap ) return;
1408 { "quiet" , AV_LOG_QUIET },
1409 { "panic" , AV_LOG_PANIC },
1410 { "fatal" , AV_LOG_FATAL },
1411 { "error" , AV_LOG_ERROR },
1412 { "warning", AV_LOG_WARNING },
1413 { "info" , AV_LOG_INFO },
1414 { "verbose", AV_LOG_VERBOSE },
1415 { "debug" , AV_LOG_DEBUG },
1417 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
1418 if( !strcmp(log_levels[i].name, ap) ) {
1419 av_log_set_level(log_levels[i].level);
1423 av_log_set_level(atoi(ap));
1426 double FFMPEG::to_secs(int64_t time, AVRational time_base)
1428 double base_time = time == AV_NOPTS_VALUE ? 0 :
1429 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
1430 return base_time / AV_TIME_BASE;
1433 int FFMPEG::info(char *text, int len)
1435 if( len <= 0 ) return 0;
1437 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
1439 if( ffvideo.size() > 0 )
1440 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
1441 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
1442 FFVideoStream *vid = ffvideo[vidx];
1443 AVStream *st = vid->st;
1444 AVCodecContext *avctx = st->codec;
1445 report(_("vid%d (%d), id 0x%06x:\n"), vid->idx, vid->fidx, avctx->codec_id);
1446 const AVCodecDescriptor *desc = avcodec_descriptor_get(avctx->codec_id);
1447 report(" video%d %s", vidx+1, desc ? desc->name : " (unkn)");
1448 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
1449 const char *pfn = av_get_pix_fmt_name(avctx->pix_fmt);
1450 report(" pix %s\n", pfn ? pfn : "(unkn)");
1451 double secs = to_secs(st->duration, st->time_base);
1452 int64_t length = secs * vid->frame_rate + 0.5;
1453 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
1454 int64_t nudge = ofs * vid->frame_rate;
1455 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1456 report(" %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
1457 int hrs = secs/3600; secs -= hrs*3600;
1458 int mins = secs/60; secs -= mins*60;
1459 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1461 if( ffaudio.size() > 0 )
1462 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
1463 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
1464 FFAudioStream *aud = ffaudio[aidx];
1465 AVStream *st = aud->st;
1466 AVCodecContext *avctx = st->codec;
1467 report(_("aud%d (%d), id 0x%06x:\n"), aud->idx, aud->fidx, avctx->codec_id);
1468 const AVCodecDescriptor *desc = avcodec_descriptor_get(avctx->codec_id);
1469 int nch = aud->channels, ch0 = aud->channel0+1;
1470 report(" audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
1471 const char *fmt = av_get_sample_fmt_name(avctx->sample_fmt);
1472 report(" %s %d", fmt, aud->sample_rate);
1473 int sample_bits = av_get_bits_per_sample(avctx->codec_id);
1474 report(" %dbits\n", sample_bits);
1475 double secs = to_secs(st->duration, st->time_base);
1476 int64_t length = secs * aud->sample_rate + 0.5;
1477 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
1478 int64_t nudge = ofs * aud->sample_rate;
1479 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1480 report(" %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
1481 int hrs = secs/3600; secs -= hrs*3600;
1482 int mins = secs/60; secs -= mins*60;
1483 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1485 if( fmt_ctx->nb_programs > 0 )
1486 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
1487 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
1488 report("program %d", i+1);
1489 AVProgram *pgrm = fmt_ctx->programs[i];
1490 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1491 int idx = pgrm->stream_index[j];
1492 int vidx = ffvideo.size();
1493 while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
1495 report(", vid%d", vidx);
1498 int aidx = ffaudio.size();
1499 while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
1501 report(", aud%d", aidx);
1504 report(", (%d)", pgrm->stream_index[j]);
1509 AVDictionaryEntry *tag = 0;
1510 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
1511 report("%s=%s\n", tag->key, tag->value);
1520 int FFMPEG::init_decoder(const char *filename)
1522 ff_lock("FFMPEG::init_decoder");
1524 char file_opts[BCTEXTLEN];
1525 char *bp = strrchr(strcpy(file_opts, filename), '/');
1526 char *sp = strrchr(!bp ? file_opts : bp, '.');
1529 strcpy(sp, ".opts");
1530 fp = fopen(file_opts, "r");
1533 read_options(fp, file_opts, opts);
1537 load_options("decode.opts", opts);
1538 AVDictionary *fopts = 0;
1539 av_dict_copy(&fopts, opts, 0);
1540 int ret = avformat_open_input(&fmt_ctx, filename, NULL, &fopts);
1541 av_dict_free(&fopts);
1543 ret = avformat_find_stream_info(fmt_ctx, NULL);
1548 return !ret ? 0 : 1;
1551 int FFMPEG::open_decoder()
1554 if( stat(fmt_ctx->filename, &st) < 0 ) {
1555 eprintf(_("can't stat file: %s\n"), fmt_ctx->filename);
1559 int64_t file_bits = 8 * st.st_size;
1560 if( !fmt_ctx->bit_rate && opt_duration > 0 )
1561 fmt_ctx->bit_rate = file_bits / opt_duration;
1564 if( fmt_ctx->bit_rate > 0 ) {
1565 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1566 AVStream *st = fmt_ctx->streams[i];
1567 if( st->duration != AV_NOPTS_VALUE ) continue;
1568 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
1569 st->duration = av_rescale(file_bits, st->time_base.den,
1570 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
1575 printf("FFMPEG::open_decoder: some stream times estimated\n");
1577 ff_lock("FFMPEG::open_decoder");
1578 int ret = 0, bad_time = 0;
1579 for( int i=0; !ret && i<(int)fmt_ctx->nb_streams; ++i ) {
1580 AVStream *st = fmt_ctx->streams[i];
1581 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
1582 AVCodecContext *avctx = st->codec;
1583 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avctx->codec_id);
1584 if( !codec_desc ) continue;
1585 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1586 if( avctx->width < 1 ) continue;
1587 if( avctx->height < 1 ) continue;
1588 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
1589 if( framerate.num < 1 ) continue;
1591 int vidx = ffvideo.size();
1592 FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
1593 vstrm_index.append(ffidx(vidx, 0));
1594 ffvideo.append(vid);
1595 vid->width = avctx->width;
1596 vid->height = avctx->height;
1597 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
1598 double secs = to_secs(st->duration, st->time_base);
1599 vid->length = secs * vid->frame_rate;
1600 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
1601 vid->nudge = st->start_time;
1603 if( opt_video_filter )
1604 ret = vid->create_filter(opt_video_filter, avctx,avctx);
1606 else if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1607 if( avctx->channels < 1 ) continue;
1608 if( avctx->sample_rate < 1 ) continue;
1610 int aidx = ffaudio.size();
1611 FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
1612 ffaudio.append(aud);
1613 aud->channel0 = astrm_index.size();
1614 aud->channels = avctx->channels;
1615 for( int ch=0; ch<aud->channels; ++ch )
1616 astrm_index.append(ffidx(aidx, ch));
1617 aud->sample_rate = avctx->sample_rate;
1618 double secs = to_secs(st->duration, st->time_base);
1619 aud->length = secs * aud->sample_rate;
1620 if( avctx->sample_fmt != AV_SAMPLE_FMT_FLT ) {
1621 uint64_t layout = av_get_default_channel_layout(avctx->channels);
1622 if( !layout ) layout = ((uint64_t)1<<aud->channels) - 1;
1623 aud->resample_context = swr_alloc_set_opts(NULL,
1624 layout, AV_SAMPLE_FMT_FLT, avctx->sample_rate,
1625 layout, avctx->sample_fmt, avctx->sample_rate,
1627 swr_init(aud->resample_context);
1629 aud->nudge = st->start_time;
1631 if( opt_audio_filter )
1632 ret = aud->create_filter(opt_audio_filter, avctx,avctx);
1636 printf("FFMPEG::open_decoder: some stream have bad times\n");
1638 return ret < 0 ? -1 : 0;
1642 int FFMPEG::init_encoder(const char *filename)
1644 int fd = ::open(filename,O_WRONLY);
1645 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
1647 eprintf(_("bad file path: %s\n"), filename);
1651 int ret = get_file_format();
1653 eprintf(_("bad file format: %s\n"), filename);
1657 eprintf(_("mismatch audio/video file format: %s\n"), filename);
1660 ff_lock("FFMPEG::init_encoder");
1662 avformat_alloc_output_context2(&fmt_ctx, 0, file_format, filename);
1664 eprintf(_("failed: %s\n"), filename);
1669 load_options("encode.opts", opts);
1675 int FFMPEG::open_encoder(const char *type, const char *spec)
1678 Asset *asset = file_base->asset;
1679 char *filename = asset->path;
1680 AVDictionary *sopts = 0;
1681 av_dict_copy(&sopts, opts, 0);
1682 char option_path[BCTEXTLEN];
1683 set_option_path(option_path, "%s/%s.opts", type, type);
1684 read_options(option_path, sopts);
1685 get_option_path(option_path, type, spec);
1686 char format_name[BCSTRLEN], codec_name[BCTEXTLEN];
1687 char bsfilter[BCSTRLEN], bsargs[BCTEXTLEN];
1688 if( get_encoder(option_path, format_name, codec_name, bsfilter, bsargs) ) {
1689 eprintf(_("get_encoder failed %s:%s\n"), option_path, filename);
1693 if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
1694 else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
1695 else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
1698 ff_lock("FFMPEG::open_encoder");
1702 const AVCodecDescriptor *codec_desc = 0;
1703 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
1705 eprintf(_("cant find codec %s:%s\n"), codec_name, filename);
1709 codec_desc = avcodec_descriptor_get(codec->id);
1711 eprintf(_("unknown codec %s:%s\n"), codec_name, filename);
1716 st = avformat_new_stream(fmt_ctx, 0);
1718 eprintf(_("cant create stream %s:%s\n"), codec_name, filename);
1723 AVCodecContext *ctx = st->codec;
1724 switch( codec_desc->type ) {
1725 case AVMEDIA_TYPE_AUDIO: {
1727 eprintf(_("duplicate audio %s:%s\n"), codec_name, filename);
1732 if( scan_options(asset->ff_audio_options, sopts, st) ) {
1733 eprintf(_("bad audio options %s:%s\n"), codec_name, filename);
1737 if( asset->ff_audio_bitrate > 0 ) {
1738 ctx->bit_rate = asset->ff_audio_bitrate;
1740 sprintf(arg, "%d", asset->ff_audio_bitrate);
1741 av_dict_set(&sopts, "b", arg, 0);
1743 int aidx = ffaudio.size();
1744 int fidx = aidx + ffvideo.size();
1745 FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
1746 ffaudio.append(aud); fst = aud;
1747 aud->sample_rate = asset->sample_rate;
1748 ctx->channels = aud->channels = asset->channels;
1749 for( int ch=0; ch<aud->channels; ++ch )
1750 astrm_index.append(ffidx(aidx, ch));
1751 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
1752 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
1753 if( !ctx->sample_rate ) {
1754 eprintf(_("check_sample_rate failed %s\n"), filename);
1758 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
1759 ctx->sample_fmt = codec->sample_fmts[0];
1760 uint64_t layout = av_get_default_channel_layout(ctx->channels);
1761 aud->resample_context = swr_alloc_set_opts(NULL,
1762 layout, ctx->sample_fmt, aud->sample_rate,
1763 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
1765 swr_init(aud->resample_context);
1768 case AVMEDIA_TYPE_VIDEO: {
1770 eprintf(_("duplicate video %s:%s\n"), codec_name, filename);
1775 if( scan_options(asset->ff_video_options, sopts, st) ) {
1776 eprintf(_("bad video options %s:%s\n"), codec_name, filename);
1780 if( asset->ff_video_bitrate > 0 ) {
1781 ctx->bit_rate = asset->ff_video_bitrate;
1783 sprintf(arg, "%d", asset->ff_video_bitrate);
1784 av_dict_set(&sopts, "b", arg, 0);
1786 else if( asset->ff_video_quality > 0 ) {
1787 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
1788 ctx->qmin = ctx->qmax = asset->ff_video_quality;
1789 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
1790 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
1791 ctx->flags |= CODEC_FLAG_QSCALE;
1793 av_dict_set(&sopts, "flags", "+qscale", 0);
1794 sprintf(arg, "%d", asset->ff_video_quality);
1795 av_dict_set(&sopts, "qscale", arg, 0);
1796 sprintf(arg, "%d", ctx->global_quality);
1797 av_dict_set(&sopts, "global_quality", arg, 0);
1799 int vidx = ffvideo.size();
1800 int fidx = vidx + ffaudio.size();
1801 FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
1802 vstrm_index.append(ffidx(vidx, 0));
1803 ffvideo.append(vid); fst = vid;
1804 vid->width = asset->width;
1805 ctx->width = (vid->width+3) & ~3;
1806 vid->height = asset->height;
1807 ctx->height = (vid->height+3) & ~3;
1808 vid->frame_rate = asset->frame_rate;
1809 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
1810 ctx->pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
1811 AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
1812 if( !frame_rate.num || !frame_rate.den ) {
1813 eprintf(_("check_frame_rate failed %s\n"), filename);
1817 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
1818 st->time_base = ctx->time_base;
1822 eprintf(_("not audio/video, %s:%s\n"), codec_name, filename);
1827 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
1828 st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
1830 ret = avcodec_open2(st->codec, codec, &sopts);
1832 ff_err(ret,"FFMPEG::open_encoder");
1833 eprintf(_("open failed %s:%s\n"), codec_name, filename);
1840 if( fst && bsfilter[0] )
1841 fst->add_bsfilter(bsfilter, !bsargs[0] ? 0 : bsargs);
1848 av_dict_free(&sopts);
1852 int FFMPEG::close_encoder()
1855 if( encoding > 0 ) {
1856 av_write_trailer(fmt_ctx);
1857 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
1858 avio_closep(&fmt_ctx->pb);
1864 int FFMPEG::decode_activate()
1866 if( decoding < 0 ) {
1868 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
1869 ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
1870 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
1871 ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
1872 // set nudges for each program stream set
1873 int npgrms = fmt_ctx->nb_programs;
1874 for( int i=0; i<npgrms; ++i ) {
1875 AVProgram *pgrm = fmt_ctx->programs[i];
1876 // first start time video stream
1877 int64_t vstart_time = -1, astart_time = -1;
1878 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1879 int fidx = pgrm->stream_index[j];
1880 AVStream *st = fmt_ctx->streams[fidx];
1881 AVCodecContext *avctx = st->codec;
1882 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1883 if( st->start_time == AV_NOPTS_VALUE ) continue;
1884 if( vstart_time > st->start_time ) continue;
1885 vstart_time = st->start_time;
1888 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1889 if( st->start_time == AV_NOPTS_VALUE ) continue;
1890 if( astart_time > st->start_time ) continue;
1891 astart_time = st->start_time;
1895 // match program streams to max start_time
1896 int64_t nudge = vstart_time > astart_time ? vstart_time : astart_time;
1897 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1898 int fidx = pgrm->stream_index[j];
1899 AVStream *st = fmt_ctx->streams[fidx];
1900 AVCodecContext *avctx = st->codec;
1901 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1902 for( int k=0; k<ffvideo.size(); ++k ) {
1903 if( ffvideo[k]->fidx != fidx ) continue;
1904 ffvideo[k]->nudge = nudge;
1908 if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1909 for( int k=0; k<ffaudio.size(); ++k ) {
1910 if( ffaudio[k]->fidx != fidx ) continue;
1911 ffaudio[k]->nudge = nudge;
1917 // set nudges for any streams not yet set
1918 int64_t vstart_time = 0, astart_time = 0;
1919 int nstreams = fmt_ctx->nb_streams;
1920 for( int i=0; i<nstreams; ++i ) {
1921 AVStream *st = fmt_ctx->streams[i];
1922 AVCodecContext *avctx = st->codec;
1923 switch( avctx->codec_type ) {
1924 case AVMEDIA_TYPE_VIDEO: {
1925 if( st->start_time == AV_NOPTS_VALUE ) continue;
1926 int vidx = ffvideo.size();
1927 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
1928 if( vidx >= 0 && ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
1929 if( vstart_time >= st->start_time ) continue;
1930 vstart_time = st->start_time;
1932 case AVMEDIA_TYPE_AUDIO: {
1933 if( st->start_time == AV_NOPTS_VALUE ) continue;
1934 int aidx = ffaudio.size();
1935 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
1936 if( aidx >= 0 && ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
1937 if( astart_time >= st->start_time ) continue;
1938 astart_time = st->start_time;
1943 int64_t nudge = vstart_time > astart_time ? vstart_time : astart_time;
1944 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
1945 if( ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
1946 ffvideo[vidx]->nudge = nudge;
1948 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
1949 if( ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
1950 ffaudio[aidx]->nudge = nudge;
1957 int FFMPEG::encode_activate()
1960 if( encoding < 0 ) {
1962 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
1963 (ret=avio_open(&fmt_ctx->pb, fmt_ctx->filename, AVIO_FLAG_WRITE)) < 0 ) {
1964 ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
1969 AVDictionary *fopts = 0;
1970 char option_path[BCTEXTLEN];
1971 set_option_path(option_path, "format/%s", file_format);
1972 read_options(option_path, fopts);
1973 ret = avformat_write_header(fmt_ctx, &fopts);
1974 av_dict_free(&fopts);
1976 ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
1986 int FFMPEG::audio_seek(int stream, int64_t pos)
1988 int aidx = astrm_index[stream].st_idx;
1989 FFAudioStream *aud = ffaudio[aidx];
1990 aud->audio_seek(pos);
1994 int FFMPEG::video_seek(int stream, int64_t pos)
1996 int vidx = vstrm_index[stream].st_idx;
1997 FFVideoStream *vid = ffvideo[vidx];
1998 vid->video_seek(pos);
2003 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
2005 if( !has_audio || chn >= astrm_index.size() ) return -1;
2006 int aidx = astrm_index[chn].st_idx;
2007 FFAudioStream *aud = ffaudio[aidx];
2008 if( aud->load(pos, len) < len ) return -1;
2009 int ch = astrm_index[chn].st_ch;
2010 int ret = aud->read(samples,len,ch);
2014 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
2016 if( !has_video || layer >= vstrm_index.size() ) return -1;
2017 int vidx = vstrm_index[layer].st_idx;
2018 FFVideoStream *vid = ffvideo[vidx];
2019 return vid->load(vframe, pos);
2023 int FFMPEG::encode(int stream, double **samples, int len)
2025 FFAudioStream *aud = ffaudio[stream];
2026 return aud->encode(samples, len);
2030 int FFMPEG::encode(int stream, VFrame *frame)
2032 FFVideoStream *vid = ffvideo[stream];
2033 return vid->encode(frame);
2036 void FFMPEG::start_muxer()
2044 void FFMPEG::stop_muxer()
2053 void FFMPEG::flow_off()
2056 flow_lock->lock("FFMPEG::flow_off");
2060 void FFMPEG::flow_on()
2064 flow_lock->unlock();
2067 void FFMPEG::flow_ctl()
2070 flow_lock->lock("FFMPEG::flow_ctl");
2071 flow_lock->unlock();
2075 int FFMPEG::mux_audio(FFrame *frm)
2078 FFStream *fst = frm->fst;
2079 AVCodecContext *ctx = fst->st->codec;
2080 AVFrame *frame = *frm;
2081 AVRational tick_rate = {1, ctx->sample_rate};
2082 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
2084 int ret = fst->encode_frame(pkt, frame, got_packet);
2085 if( ret >= 0 && got_packet )
2086 ret = fst->write_packet(pkt);
2088 ff_err(ret, "FFMPEG::mux_audio");
2089 return ret >= 0 ? 0 : 1;
2092 int FFMPEG::mux_video(FFrame *frm)
2095 FFStream *fst = frm->fst;
2096 AVFrame *frame = *frm;
2097 frame->pts = frm->position;
2099 int ret = fst->encode_frame(pkt, frame, got_packet);
2100 if( ret >= 0 && got_packet )
2101 ret = fst->write_packet(pkt);
2103 ff_err(ret, "FFMPEG::mux_video");
2104 return ret >= 0 ? 0 : 1;
2110 double atm = -1, vtm = -1;
2111 FFrame *afrm = 0, *vfrm = 0;
2113 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
2114 FFStream *fst = ffaudio[i];
2115 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
2116 FFrame *frm = fst->frms.first;
2117 if( !frm ) { if( !done ) return; continue; }
2118 double tm = to_secs(frm->position, fst->st->codec->time_base);
2119 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
2121 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
2122 FFStream *fst = ffvideo[i];
2123 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
2124 FFrame *frm = fst->frms.first;
2125 if( !frm ) { if( !done ) return; continue; }
2126 double tm = to_secs(frm->position, fst->st->codec->time_base);
2127 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
2129 if( !demand ) flow_off();
2130 if( !afrm && !vfrm ) break;
2131 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
2132 vfrm->position, vfrm->fst->st->codec->time_base,
2133 afrm->position, afrm->fst->st->codec->time_base);
2134 FFrame *frm = v <= 0 ? vfrm : afrm;
2135 if( frm == afrm ) mux_audio(frm);
2136 if( frm == vfrm ) mux_video(frm);
2145 mux_lock->lock("FFMPEG::run");
2149 for( int i=0; i<ffaudio.size(); ++i )
2150 ffaudio[i]->flush();
2151 for( int i=0; i<ffvideo.size(); ++i )
2152 ffvideo[i]->flush();
2156 int FFMPEG::ff_total_audio_channels()
2158 return astrm_index.size();
2161 int FFMPEG::ff_total_astreams()
2163 return ffaudio.size();
2166 int FFMPEG::ff_audio_channels(int stream)
2168 return ffaudio[stream]->channels;
2171 int FFMPEG::ff_sample_rate(int stream)
2173 return ffaudio[stream]->sample_rate;
2176 const char* FFMPEG::ff_audio_format(int stream)
2178 AVStream *st = ffaudio[stream]->st;
2179 AVCodecID id = st->codec->codec_id;
2180 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2181 return desc ? desc->name : _("Unknown");
2184 int FFMPEG::ff_audio_pid(int stream)
2186 return ffaudio[stream]->st->id;
2189 int64_t FFMPEG::ff_audio_samples(int stream)
2191 return ffaudio[stream]->length;
2194 // find audio astream/channels with this program,
2195 // or all program audio channels (astream=-1)
2196 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
2200 int vidx = ffvideo[vstream]->fidx;
2201 // find first program with this video stream
2202 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
2203 AVProgram *pgrm = fmt_ctx->programs[i];
2204 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
2205 int st_idx = pgrm->stream_index[j];
2206 AVStream *st = fmt_ctx->streams[st_idx];
2207 if( st->codec->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
2208 if( st_idx == vidx ) pidx = i;
2211 if( pidx < 0 ) return -1;
2213 int64_t channels = 0;
2214 AVProgram *pgrm = fmt_ctx->programs[pidx];
2215 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2216 int aidx = pgrm->stream_index[j];
2217 AVStream *st = fmt_ctx->streams[aidx];
2218 if( st->codec->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
2219 if( astream > 0 ) { --astream; continue; }
2221 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
2222 if( ffaudio[i]->fidx == aidx ) astrm = i;
2224 if( ret < 0 ) ret = astrm;
2225 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
2226 channels |= mask << ffaudio[astrm]->channel0;
2228 if( !astream ) break;
2230 channel_mask = channels;
2235 int FFMPEG::ff_total_video_layers()
2237 return vstrm_index.size();
2240 int FFMPEG::ff_total_vstreams()
2242 return ffvideo.size();
2245 int FFMPEG::ff_video_width(int stream)
2247 return ffvideo[stream]->width;
2250 int FFMPEG::ff_video_height(int stream)
2252 return ffvideo[stream]->height;
2255 int FFMPEG::ff_set_video_width(int stream, int width)
2257 int w = ffvideo[stream]->width;
2258 ffvideo[stream]->width = width;
2262 int FFMPEG::ff_set_video_height(int stream, int height)
2264 int h = ffvideo[stream]->height;
2265 ffvideo[stream]->height = height;
2269 int FFMPEG::ff_coded_width(int stream)
2271 AVStream *st = ffvideo[stream]->st;
2272 return st->codec->coded_width;
2275 int FFMPEG::ff_coded_height(int stream)
2277 AVStream *st = ffvideo[stream]->st;
2278 return st->codec->coded_height;
2281 float FFMPEG::ff_aspect_ratio(int stream)
2283 return ffvideo[stream]->aspect_ratio;
2286 const char* FFMPEG::ff_video_format(int stream)
2288 AVStream *st = ffvideo[stream]->st;
2289 AVCodecID id = st->codec->codec_id;
2290 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2291 return desc ? desc->name : _("Unknown");
2294 double FFMPEG::ff_frame_rate(int stream)
2296 return ffvideo[stream]->frame_rate;
2299 int64_t FFMPEG::ff_video_frames(int stream)
2301 return ffvideo[stream]->length;
2304 int FFMPEG::ff_video_pid(int stream)
2306 return ffvideo[stream]->st->id;
2310 int FFMPEG::ff_cpus()
2312 return file_base->file->cpus;
2315 int FFVideoStream::create_filter(const char *filter_spec,
2316 AVCodecContext *src_ctx, AVCodecContext *sink_ctx)
2318 avfilter_register_all();
2319 const char *sp = filter_spec;
2320 char filter_name[BCSTRLEN], *np = filter_name;
2321 int i = sizeof(filter_name);
2322 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
2324 AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
2325 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_VIDEO ) {
2326 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
2329 filter_graph = avfilter_graph_alloc();
2330 AVFilter *buffersrc = avfilter_get_by_name("buffer");
2331 AVFilter *buffersink = avfilter_get_by_name("buffersink");
2333 int ret = 0; char args[BCTEXTLEN];
2334 snprintf(args, sizeof(args),
2335 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
2336 src_ctx->width, src_ctx->height, src_ctx->pix_fmt,
2337 src_ctx->time_base.num, src_ctx->time_base.den,
2338 src_ctx->sample_aspect_ratio.num, src_ctx->sample_aspect_ratio.den);
2340 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2341 args, NULL, filter_graph);
2343 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2344 NULL, NULL, filter_graph);
2346 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
2347 (uint8_t*)&sink_ctx->pix_fmt, sizeof(sink_ctx->pix_fmt),
2348 AV_OPT_SEARCH_CHILDREN);
2350 ff_err(ret, "FFVideoStream::create_filter");
2352 ret = FFStream::create_filter(filter_spec);
2353 return ret >= 0 ? 0 : -1;
2356 int FFAudioStream::create_filter(const char *filter_spec,
2357 AVCodecContext *src_ctx, AVCodecContext *sink_ctx)
2359 avfilter_register_all();
2360 const char *sp = filter_spec;
2361 char filter_name[BCSTRLEN], *np = filter_name;
2362 int i = sizeof(filter_name);
2363 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
2365 AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
2366 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_AUDIO ) {
2367 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
2370 filter_graph = avfilter_graph_alloc();
2371 AVFilter *buffersrc = avfilter_get_by_name("abuffer");
2372 AVFilter *buffersink = avfilter_get_by_name("abuffersink");
2373 int ret = 0; char args[BCTEXTLEN];
2374 snprintf(args, sizeof(args),
2375 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
2376 src_ctx->time_base.num, src_ctx->time_base.den, src_ctx->sample_rate,
2377 av_get_sample_fmt_name(src_ctx->sample_fmt), src_ctx->channel_layout);
2379 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2380 args, NULL, filter_graph);
2382 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2383 NULL, NULL, filter_graph);
2385 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
2386 (uint8_t*)&sink_ctx->sample_fmt, sizeof(sink_ctx->sample_fmt),
2387 AV_OPT_SEARCH_CHILDREN);
2389 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
2390 (uint8_t*)&sink_ctx->channel_layout,
2391 sizeof(sink_ctx->channel_layout), AV_OPT_SEARCH_CHILDREN);
2393 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
2394 (uint8_t*)&sink_ctx->sample_rate, sizeof(sink_ctx->sample_rate),
2395 AV_OPT_SEARCH_CHILDREN);
2397 ff_err(ret, "FFAudioStream::create_filter");
2399 ret = FFStream::create_filter(filter_spec);
2400 return ret >= 0 ? 0 : -1;
2403 int FFStream::create_filter(const char *filter_spec)
2405 /* Endpoints for the filter graph. */
2406 AVFilterInOut *outputs = avfilter_inout_alloc();
2407 outputs->name = av_strdup("in");
2408 outputs->filter_ctx = buffersrc_ctx;
2409 outputs->pad_idx = 0;
2412 AVFilterInOut *inputs = avfilter_inout_alloc();
2413 inputs->name = av_strdup("out");
2414 inputs->filter_ctx = buffersink_ctx;
2415 inputs->pad_idx = 0;
2418 int ret = !outputs->name || !inputs->name ? -1 : 0;
2420 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
2421 &inputs, &outputs, NULL);
2423 ret = avfilter_graph_config(filter_graph, NULL);
2426 ff_err(ret, "FFStream::create_filter");
2427 avfilter_graph_free(&filter_graph);
2430 avfilter_inout_free(&inputs);
2431 avfilter_inout_free(&outputs);
2435 void FFStream::add_bsfilter(const char *bsf, const char *ap)
2437 bsfilter.append(new BSFilter(bsf,ap));
2440 int FFStream::bs_filter(AVPacket *pkt)
2442 if( !bsfilter.size() ) return 0;
2443 av_packet_split_side_data(pkt);
2446 for( int i=0; i<bsfilter.size(); ++i ) {
2447 AVPacket bspkt = *pkt;
2448 ret = av_bitstream_filter_filter(bsfilter[i]->bsfc,
2449 st->codec, bsfilter[i]->args, &bspkt.data, &bspkt.size,
2450 pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY);
2451 if( ret < 0 ) break;
2452 int size = bspkt.size;
2453 uint8_t *data = bspkt.data;
2454 if( !ret && bspkt.data != pkt->data ) {
2456 data = (uint8_t *)av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
2457 if( !data ) { ret = AVERROR(ENOMEM); break; }
2458 memcpy(data, bspkt.data, size);
2459 memset(data+size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2463 pkt->side_data = 0; pkt->side_data_elems = 0;
2464 av_packet_unref(pkt);
2465 ret = av_packet_from_data(&bspkt, data, size);
2466 if( ret < 0 ) break;
2471 ff_err(ret,"FFStream::bs_filter");
2475 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
2478 av_init_packet(&pkt);
2479 AVFrame *frame = av_frame_alloc();
2481 fprintf(stderr,"FFMPEG::scan: ");
2482 fprintf(stderr,_("av_frame_alloc failed\n"));
2486 index_state->add_video_markers(ffvideo.size());
2487 index_state->add_audio_markers(ffaudio.size());
2489 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2490 AVDictionary *copts = 0;
2491 av_dict_copy(&copts, opts, 0);
2492 AVStream *st = fmt_ctx->streams[i];
2493 AVCodecID codec_id = st->codec->codec_id;
2494 AVCodec *decoder = avcodec_find_decoder(codec_id);
2495 if( avcodec_open2(st->codec, decoder, &copts) < 0 ) {
2496 fprintf(stderr,"FFMPEG::scan: ");
2497 fprintf(stderr,_("codec open failed\n"));
2499 av_dict_free(&copts);
2502 for( int64_t count=0; !*canceled; ++count ) {
2503 av_packet_unref(&pkt);
2504 pkt.data = 0; pkt.size = 0;
2506 int ret = av_read_frame(fmt_ctx, &pkt);
2508 if( ret == AVERROR_EOF ) break;
2509 if( ++errs > 100 ) {
2510 ff_err(ret,_("over 100 read_frame errs\n"));
2515 if( !pkt.data ) continue;
2516 int i = pkt.stream_index;
2517 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
2518 AVStream *st = fmt_ctx->streams[i];
2519 AVCodecContext *avctx = st->codec;
2520 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
2522 switch( avctx->codec_type ) {
2523 case AVMEDIA_TYPE_VIDEO: {
2524 int vidx = ffvideo.size();
2525 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
2526 if( vidx < 0 ) break;
2527 FFVideoStream *vid = ffvideo[vidx];
2528 int64_t tstmp = pkt.dts;
2529 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.pts;
2530 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
2531 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
2532 double secs = to_secs(tstmp, st->time_base);
2533 int64_t frm = secs * vid->frame_rate + 0.5;
2534 if( frm < 0 ) frm = 0;
2535 index_state->put_video_mark(vidx, frm, pkt.pos);
2538 while( pkt.size > 0 ) {
2539 av_frame_unref(frame);
2541 int ret = vid->decode_frame(&pkt, frame, got_frame);
2542 if( ret <= 0 ) break;
2543 // if( got_frame ) {}
2549 case AVMEDIA_TYPE_AUDIO: {
2550 int aidx = ffaudio.size();
2551 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
2552 if( aidx < 0 ) break;
2553 FFAudioStream *aud = ffaudio[aidx];
2554 int64_t tstmp = pkt.pts;
2555 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
2556 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
2557 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
2558 double secs = to_secs(tstmp, st->time_base);
2559 int64_t sample = secs * aud->sample_rate + 0.5;
2560 if( sample < 0 ) sample = 0;
2561 index_state->put_audio_mark(aidx, sample, pkt.pos);
2563 while( pkt.size > 0 ) {
2564 int ch = aud->channel0, nch = aud->channels;
2565 int64_t pos = index_state->pos(ch);
2566 if( pos != aud->curr_pos ) {
2567 if( abs(pos-aud->curr_pos) > 1 )
2568 printf("audio%d pad %jd %jd (%jd)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
2569 index_state->pad_data(ch, nch, aud->curr_pos);
2571 av_frame_unref(frame);
2573 int ret = aud->decode_frame(&pkt, frame, got_frame);
2574 if( ret <= 0 ) break;
2575 if( got_frame && frame->channels == nch ) {
2577 int len = aud->get_samples(samples,
2578 &frame->extended_data[0], frame->nb_samples);
2579 for( int i=0; i<nch; ++i )
2580 index_state->put_data(ch+i,nch,samples+i,len);
2581 aud->curr_pos += len;
2590 av_frame_free(&frame);
2594 void FFStream::load_markers(IndexMarks &marks, double rate)
2597 int64_t sz = marks.size();
2598 int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
2599 int nb_ent = st->nb_index_entries;
2600 // some formats already have an index
2602 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
2603 int64_t tstmp = ep->timestamp;
2604 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
2605 double secs = ffmpeg->to_secs(tstmp, st->time_base);
2606 int64_t no = secs * rate;
2607 while( in < sz && marks[in].no <= no ) ++in;
2609 int64_t len = sz - in;
2610 int64_t count = max_entries - nb_ent;
2611 if( count > len ) count = len;
2612 for( int i=0; i<count; ++i ) {
2613 int k = in + i * len / count;
2614 int64_t no = marks[k].no, pos = marks[k].pos;
2615 double secs = (double)no / rate;
2616 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
2617 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
2618 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);