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;
244 reading = writing = 0;
250 FFStream::~FFStream()
252 if( reading > 0 || writing > 0 ) avcodec_close(st->codec);
253 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
254 while( frms.first ) frms.remove(frms.first);
255 if( filter_graph ) avfilter_graph_free(&filter_graph);
256 if( frame ) av_frame_free(&frame);
257 if( fframe ) av_frame_free(&fframe);
258 bsfilter.remove_all_objects();
262 void FFStream::ff_lock(const char *cp)
264 FFMPEG::fflock.lock(cp);
267 void FFStream::ff_unlock()
269 FFMPEG::fflock.unlock();
272 void FFStream::queue(FFrame *frm)
274 frm_lock->lock("FFStream::queue");
278 ffmpeg->mux_lock->unlock();
281 void FFStream::dequeue(FFrame *frm)
283 frm_lock->lock("FFStream::dequeue");
285 frms.remove_pointer(frm);
289 int FFStream::encode_activate()
292 writing = ffmpeg->encode_activate();
296 int FFStream::decode_activate()
298 if( reading < 0 && (reading=ffmpeg->decode_activate()) > 0 ) {
299 ff_lock("FFStream::decode_activate");
301 AVDictionary *copts = 0;
302 av_dict_copy(&copts, ffmpeg->opts, 0);
304 // this should be avformat_copy_context(), but no copy avail
305 ret = avformat_open_input(&fmt_ctx, ffmpeg->fmt_ctx->filename, NULL, &copts);
307 ret = avformat_find_stream_info(fmt_ctx, 0);
308 st = fmt_ctx->streams[fidx];
312 AVCodecID codec_id = st->codec->codec_id;
313 AVCodec *decoder = avcodec_find_decoder(codec_id);
314 ret = avcodec_open2(st->codec, decoder, &copts);
318 eprintf("FFStream::decode_activate: open decoder failed\n");
321 eprintf("FFStream::decode_activate: can't clone input file\n");
322 av_dict_free(&copts);
328 int FFStream::read_packet()
330 av_packet_unref(ipkt);
331 int ret = av_read_frame(fmt_ctx, ipkt);
334 if( ret == AVERROR_EOF ) {
335 ipkt->stream_index = st->index;
338 ff_err(ret, "FFStream::read_packet: av_read_frame failed\n");
345 int FFStream::decode(AVFrame *frame)
348 int retries = MAX_RETRY;
351 while( ret >= 0 && !flushed && --retries >= 0 && !got_frame ) {
354 if( (ret=read_packet()) < 0 ) break;
356 if( ipkt->stream_index == st->index ) {
357 while( (ipkt->size > 0 || !ipkt->data) && !got_frame ) {
358 ret = decode_frame(ipkt, frame, got_frame);
359 if( ret < 0 ) need_packet = 1;
360 if( ret <= 0 || !ipkt->data ) break;
373 fprintf(stderr, "FFStream::decode: Retry limit\n");
377 fprintf(stderr, "FFStream::decode: failed\n");
382 int FFStream::load_filter(AVFrame *frame)
384 int ret = av_buffersrc_add_frame_flags(buffersrc_ctx,
385 frame, AV_BUFFERSRC_FLAG_KEEP_REF);
387 av_frame_unref(frame);
388 eprintf("FFStream::load_filter: av_buffersrc_add_frame_flags failed\n");
393 int FFStream::read_filter(AVFrame *frame)
395 int ret = av_buffersink_get_frame(buffersink_ctx, frame);
397 if( ret == AVERROR(EAGAIN) ) return 0;
398 if( ret == AVERROR_EOF ) { st_eof(1); return -1; }
399 ff_err(ret, "FFStream::read_filter: av_buffersink_get_frame failed\n");
405 int FFStream::read_frame(AVFrame *frame)
407 if( !filter_graph || !buffersrc_ctx || !buffersink_ctx )
408 return decode(frame);
409 if( !fframe && !(fframe=av_frame_alloc()) ) {
410 fprintf(stderr, "FFStream::read_frame: av_frame_alloc failed\n");
414 while( !flushed && !(ret=read_filter(frame)) ) {
415 if( (ret=decode(fframe)) < 0 ) break;
416 if( ret > 0 && (ret=load_filter(fframe)) < 0 ) break;
421 int FFStream::write_packet(FFPacket &pkt)
424 av_packet_rescale_ts(pkt, st->codec->time_base, st->time_base);
425 pkt->stream_index = st->index;
426 return av_interleaved_write_frame(ffmpeg->fmt_ctx, pkt);
429 int FFStream::flush()
435 ret = encode_frame(pkt, 0, got_packet);
436 if( ret < 0 || !got_packet ) break;
437 ret = write_packet(pkt);
440 ff_err(ret, "FFStream::flush");
441 return ret >= 0 ? 0 : 1;
444 int FFStream::seek(int64_t no, double rate)
446 int64_t tstmp = -INT64_MAX+1;
447 // default ffmpeg native seek
449 int64_t pos = no, plmt = -1;
450 if( index_markers && index_markers->size() > 1 ) {
451 IndexMarks &marks = *index_markers;
452 int i = marks.find(pos);
453 int64_t n = i < 0 ? (i=0) : marks[i].no;
454 // if indexed seek point not too far away (<30 secs), use index
455 if( no-n < 30*rate ) {
458 if( i < marks.size() ) plmt = marks[i].pos;
463 double secs = pos / rate;
464 tstmp = secs * st->time_base.den / st->time_base.num;
465 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
467 int ret = avformat_seek_file(fmt_ctx, st->index,
468 -INT64_MAX, tstmp, INT64_MAX, AVSEEK_FLAG_ANY);
470 avcodec_flush_buffers(st->codec);
471 ipkt.finit(); ipkt.init();
472 need_packet = 0; flushed = 0;
473 seeked = 1; st_eof(0);
474 // read up to retry packets, limited to npkts in stream, and not past pkt.pos plmt
476 if( read_packet() <= 0 ) { ret = -1; break; }
477 if( plmt >= 0 && ipkt->pos >= plmt ) break;
478 if( ipkt->stream_index != st->index ) continue;
479 if( --npkts <= 0 ) break;
480 int64_t pkt_ts = ipkt->dts != AV_NOPTS_VALUE ? ipkt->dts : ipkt->pts;
481 if( pkt_ts == AV_NOPTS_VALUE ) continue;
482 if( pkt_ts >= tstmp ) break;
486 //printf("** seek fail %ld, %ld\n", pos, tstmp);
487 seeked = need_packet = 0;
491 //printf("seeked pos = %ld, %ld\n", pos, tstmp);
492 seek_pos = curr_pos = pos;
496 FFAudioStream::FFAudioStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
497 : FFStream(ffmpeg, strm, fidx)
500 channel0 = channels = 0;
504 resample_context = 0;
513 bfr = new float[bsz];
518 FFAudioStream::~FFAudioStream()
520 if( resample_context ) swr_free(&resample_context);
525 int FFAudioStream::get_samples(float *&samples, uint8_t **data, int len)
527 samples = *(float **)data;
528 if( resample_context ) {
529 if( len > aud_bfr_sz ) {
535 aud_bfr = new float[aud_bfr_sz*channels];
537 int ret = swr_convert(resample_context,
538 (uint8_t**)&aud_bfr, aud_bfr_sz, (const uint8_t**)data, len);
540 ff_err(ret, "FFAudioStream::get_samples: swr_convert failed\n");
549 int FFAudioStream::load_history(uint8_t **data, int len)
552 len = get_samples(samples, data, len);
554 // biggest user bfr since seek + frame
555 realloc(mbsz + len + 1, channels);
561 int FFAudioStream::decode_frame(AVPacket *pkt, AVFrame *frame, int &got_frame)
563 int first_frame = seeked; seeked = 0;
564 int ret = avcodec_decode_audio4(st->codec, frame, &got_frame, pkt);
566 if( first_frame ) return 0;
567 ff_err(ret, "FFAudioStream::decode_frame: Could not read audio frame\n");
571 int64_t pkt_ts = av_frame_get_best_effort_timestamp(frame);
572 if( pkt_ts != AV_NOPTS_VALUE )
573 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * sample_rate + 0.5;
578 int FFAudioStream::encode_activate()
580 if( writing >= 0 ) return writing;
581 AVCodecContext *ctx = st->codec;
582 frame_sz = ctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE ?
583 10000 : ctx->frame_size;
584 return FFStream::encode_activate();
587 int FFAudioStream::nb_samples()
589 AVCodecContext *ctx = st->codec;
590 return ctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE ?
591 10000 : ctx->frame_size;
594 int64_t FFAudioStream::load_buffer(double ** const sp, int len)
596 reserve(len+1, st->codec->channels);
597 for( int ch=0; ch<nch; ++ch )
598 write(sp[ch], len, ch);
602 int FFAudioStream::in_history(int64_t pos)
604 if( pos > curr_pos ) return 0;
606 if( len > sz ) len = sz;
607 if( pos < curr_pos - len ) return 0;
612 int FFAudioStream::init_frame(AVFrame *frame)
614 AVCodecContext *ctx = st->codec;
615 frame->nb_samples = frame_sz;
616 frame->format = ctx->sample_fmt;
617 frame->channel_layout = ctx->channel_layout;
618 frame->sample_rate = ctx->sample_rate;
619 int ret = av_frame_get_buffer(frame, 0);
621 ff_err(ret, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
625 int FFAudioStream::load(int64_t pos, int len)
627 if( audio_seek(pos) < 0 ) return -1;
628 if( !frame && !(frame=av_frame_alloc()) ) {
629 fprintf(stderr, "FFAudioStream::load: av_frame_alloc failed\n");
632 if( mbsz < len ) mbsz = len;
633 int64_t end_pos = pos + len;
635 for( int i=0; ret>=0 && !flushed && curr_pos<end_pos && i<MAX_RETRY; ++i ) {
636 ret = read_frame(frame);
638 load_history(&frame->extended_data[0], frame->nb_samples);
639 curr_pos += frame->nb_samples;
642 if( end_pos > curr_pos ) {
643 zero(end_pos - curr_pos);
646 len = curr_pos - pos;
651 int FFAudioStream::audio_seek(int64_t pos)
653 if( decode_activate() < 0 ) return -1;
654 if( !st->codec || !st->codec->codec ) return -1;
655 if( in_history(pos) ) return 0;
656 if( pos == curr_pos ) return 0;
657 reset_history(); mbsz = 0;
658 // guarentee preload > 1sec samples
659 if( seek(pos-sample_rate, sample_rate) < 0 ) return -1;
663 int FFAudioStream::encode(double **samples, int len)
665 if( encode_activate() <= 0 ) return -1;
668 int64_t count = load_buffer(samples, len);
671 while( ret >= 0 && count >= frame_sz ) {
672 frm = new FFrame(this);
673 if( (ret=frm->initted()) < 0 ) break;
674 AVFrame *frame = *frm;
675 float *bfrp = get_outp(frame_sz);
676 ret = swr_convert(resample_context,
677 (uint8_t **)frame->extended_data, frame_sz,
678 (const uint8_t **)&bfrp, frame_sz);
680 ff_err(ret, "FFAudioStream::encode: swr_convert failed\n");
683 frm->queue(curr_pos);
685 curr_pos += frame_sz;
690 return ret >= 0 ? 0 : 1;
693 int FFAudioStream::encode_frame(AVPacket *pkt, AVFrame *frame, int &got_packet)
695 int ret = avcodec_encode_audio2(st->codec, pkt, frame, &got_packet);
697 ff_err(ret, "FFAudioStream::encode_frame: encode audio failed\n");
703 void FFAudioStream::load_markers()
705 IndexState *index_state = ffmpeg->file_base->asset->index_state;
706 if( index_state->marker_status == MARKERS_NOTTESTED ) return;
707 if( !index_state || idx >= index_state->audio_markers.size() ) return;
708 FFStream::load_markers(*index_state->audio_markers[idx], sample_rate);
711 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
712 : FFStream(ffmpeg, strm, fidx)
721 FFVideoStream::~FFVideoStream()
725 int FFVideoStream::decode_frame(AVPacket *pkt, AVFrame *frame, int &got_frame)
727 int first_frame = seeked; seeked = 0;
728 int ret = avcodec_decode_video2(st->codec, frame, &got_frame, pkt);
730 if( first_frame ) return 0;
731 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame\n");
734 else // this is right out of ffplay, looks questionable ???
738 int64_t pkt_ts = av_frame_get_best_effort_timestamp(frame);
739 if( pkt_ts != AV_NOPTS_VALUE )
740 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * frame_rate + 0.5;
745 int FFVideoStream::load(VFrame *vframe, int64_t pos)
747 int ret = video_seek(pos);
748 if( ret < 0 ) return -1;
749 if( !frame && !(frame=av_frame_alloc()) ) {
750 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
753 for( int i=0; ret>=0 && !flushed && curr_pos<=pos && i<MAX_RETRY; ++i ) {
754 ret = read_frame(frame);
755 if( ret > 0 ) ++curr_pos;
758 AVCodecContext *ctx = st->codec;
759 ret = convert_cmodel(vframe, frame,
760 ctx->pix_fmt, ctx->width, ctx->height);
762 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
766 int FFVideoStream::video_seek(int64_t pos)
768 if( decode_activate() < 0 ) return -1;
769 if( !st->codec || !st->codec->codec ) return -1;
770 if( pos == curr_pos-1 && !seeked ) return 0;
771 // if close enough, just read up to current
772 int gop = st->codec->gop_size;
773 if( gop < 4 ) gop = 4;
774 if( gop > 64 ) gop = 64;
775 int read_limit = curr_pos + 3*gop;
776 if( pos >= curr_pos && pos <= read_limit ) return 0;
777 // guarentee preload more than 2*gop frames
778 if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
782 int FFVideoStream::init_frame(AVFrame *picture)
784 AVCodecContext *ctx = st->codec;
785 picture->format = ctx->pix_fmt;
786 picture->width = ctx->width;
787 picture->height = ctx->height;
788 int ret = av_frame_get_buffer(picture, 32);
792 int FFVideoStream::encode(VFrame *vframe)
794 if( encode_activate() <= 0 ) return -1;
796 FFrame *picture = new FFrame(this);
797 int ret = picture->initted();
799 AVFrame *frame = *picture;
800 frame->pts = curr_pos;
801 AVCodecContext *ctx = st->codec;
802 ret = convert_pixfmt(vframe, frame,
803 ctx->pix_fmt, ctx->width, ctx->height);
806 picture->queue(curr_pos);
810 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
813 return ret >= 0 ? 0 : 1;
816 int FFVideoStream::encode_frame(AVPacket *pkt, AVFrame *frame, int &got_packet)
818 int ret = avcodec_encode_video2(st->codec, pkt, frame, &got_packet);
820 ff_err(ret, "FFVideoStream::encode_frame: encode video failed\n");
826 AVPixelFormat FFVideoConvert::color_model_to_pix_fmt(int color_model)
828 switch( color_model ) {
829 case BC_YUV422: return AV_PIX_FMT_YUYV422;
830 case BC_RGB888: return AV_PIX_FMT_RGB24;
831 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
832 case BC_BGR8888: return AV_PIX_FMT_BGR0;
833 case BC_BGR888: return AV_PIX_FMT_BGR24;
834 case BC_ARGB8888: return AV_PIX_FMT_ARGB;
835 case BC_ABGR8888: return AV_PIX_FMT_ABGR;
836 case BC_RGB8: return AV_PIX_FMT_RGB8;
837 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
838 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
839 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
840 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
841 case BC_RGB565: return AV_PIX_FMT_RGB565;
842 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
843 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
847 return AV_PIX_FMT_NB;
850 int FFVideoConvert::pix_fmt_to_color_model(AVPixelFormat pix_fmt)
853 case AV_PIX_FMT_YUYV422: return BC_YUV422;
854 case AV_PIX_FMT_RGB24: return BC_RGB888;
855 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
856 case AV_PIX_FMT_BGR0: return BC_BGR8888;
857 case AV_PIX_FMT_BGR24: return BC_BGR888;
858 case AV_PIX_FMT_ARGB: return BC_ARGB8888;
859 case AV_PIX_FMT_ABGR: return BC_ABGR8888;
860 case AV_PIX_FMT_RGB8: return BC_RGB8;
861 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
862 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
863 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
864 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
865 case AV_PIX_FMT_RGB565: return BC_RGB565;
866 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
867 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
874 int FFVideoConvert::convert_picture_vframe(VFrame *frame,
875 AVFrame *ip, AVPixelFormat ifmt, int iw, int ih)
877 // try bc_xfer methods
878 int imodel = pix_fmt_to_color_model(ifmt);
880 long y_ofs = 0, u_ofs = 0, v_ofs = 0;
881 uint8_t *data = ip->data[0];
882 if( BC_CModels::is_yuv(imodel) ) {
883 u_ofs = ip->data[1] - data;
884 v_ofs = ip->data[2] - data;
886 VFrame iframe(data, -1, y_ofs, u_ofs, v_ofs, iw, ih, imodel, ip->linesize[0]);
887 frame->transfer_from(&iframe);
892 int cmodel = frame->get_color_model();
893 AVPixelFormat ofmt = color_model_to_pix_fmt(cmodel);
894 if( ofmt == AV_PIX_FMT_NB ) return -1;
895 int size = av_image_fill_arrays(opic.data, opic.linesize,
896 frame->get_data(), ofmt, frame->get_w(), frame->get_h(), 1);
897 if( size < 0 ) return -1;
899 // transfer line sizes must match also
900 int planar = BC_CModels::is_planar(cmodel);
901 int packed_width = !planar ? frame->get_bytes_per_line() :
902 BC_CModels::calculate_pixelsize(cmodel) * frame->get_w();
903 if( packed_width != opic.linesize[0] ) return -1;
906 // override av_image_fill_arrays() for planar types
907 opic.data[0] = frame->get_y();
908 opic.data[1] = frame->get_u();
909 opic.data[2] = frame->get_v();
912 convert_ctx = sws_getCachedContext(convert_ctx, iw, ih, ifmt,
913 frame->get_w(), frame->get_h(), ofmt, SWS_BICUBIC, NULL, NULL, NULL);
915 fprintf(stderr, "FFVideoConvert::convert_picture_frame:"
916 " sws_getCachedContext() failed\n");
919 int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ih,
920 opic.data, opic.linesize);
922 ff_err(ret, "FFVideoConvert::convert_picture_frame: sws_scale() failed\n");
928 int FFVideoConvert::convert_cmodel(VFrame *frame,
929 AVFrame *ip, AVPixelFormat ifmt, int iw, int ih)
931 // try direct transfer
932 if( !convert_picture_vframe(frame, ip, ifmt, iw, ih) ) return 1;
933 // use indirect transfer
934 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
936 for( int i = 0; i <desc->nb_components; ++i ) {
937 int bits = desc->comp[i].depth;
938 if( bits > max_bits ) max_bits = bits;
940 // from libavcodec/pixdesc.c
941 #define pixdesc_has_alpha(pixdesc) ((pixdesc)->nb_components == 2 || \
942 (pixdesc)->nb_components == 4 || (pixdesc)->flags & AV_PIX_FMT_FLAG_PAL)
943 int icolor_model = pixdesc_has_alpha(desc) ?
944 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
945 (max_bits > 8 ? BC_RGB161616 : BC_RGB888) ;
946 VFrame vframe(iw, ih, icolor_model);
947 if( convert_picture_vframe(&vframe, ip, ifmt, iw, ih) ) return -1;
948 frame->transfer_from(&vframe);
952 int FFVideoConvert::transfer_cmodel(VFrame *frame,
953 AVFrame *ifp, AVPixelFormat ifmt, int iw, int ih)
955 int ret = convert_cmodel(frame, ifp, ifmt, iw, ih);
957 const AVDictionary *src = av_frame_get_metadata(ifp);
958 AVDictionaryEntry *t = NULL;
959 BC_Hash *hp = frame->get_params();
961 while( (t=av_dict_get(src, "", t, AV_DICT_IGNORE_SUFFIX)) )
962 hp->update(t->key, t->value);
967 int FFVideoConvert::convert_vframe_picture(VFrame *frame,
968 AVFrame *op, AVPixelFormat ofmt, int ow, int oh)
971 int cmodel = frame->get_color_model();
972 AVPixelFormat ifmt = color_model_to_pix_fmt(cmodel);
973 if( ifmt == AV_PIX_FMT_NB ) return -1;
974 int size = av_image_fill_arrays(opic.data, opic.linesize,
975 frame->get_data(), ifmt, frame->get_w(), frame->get_h(), 1);
976 if( size < 0 ) return -1;
978 // transfer line sizes must match also
979 int planar = BC_CModels::is_planar(cmodel);
980 int packed_width = !planar ? frame->get_bytes_per_line() :
981 BC_CModels::calculate_pixelsize(cmodel) * frame->get_w();
982 if( packed_width != opic.linesize[0] ) return -1;
985 // override av_image_fill_arrays() for planar types
986 opic.data[0] = frame->get_y();
987 opic.data[1] = frame->get_u();
988 opic.data[2] = frame->get_v();
991 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(), ifmt,
992 ow, oh, ofmt, SWS_BICUBIC, NULL, NULL, NULL);
994 fprintf(stderr, "FFVideoConvert::convert_frame_picture:"
995 " sws_getCachedContext() failed\n");
998 int ret = sws_scale(convert_ctx, opic.data, opic.linesize, 0, frame->get_h(),
999 op->data, op->linesize);
1001 ff_err(ret, "FFVideoConvert::convert_frame_picture: sws_scale() failed\n");
1007 int FFVideoConvert::convert_pixfmt(VFrame *frame,
1008 AVFrame *op, AVPixelFormat ofmt, int ow, int oh)
1010 // try direct transfer
1011 if( !convert_vframe_picture(frame, op, ofmt, ow, oh) ) return 1;
1012 // use indirect transfer
1013 int colormodel = frame->get_color_model();
1014 int bits = BC_CModels::calculate_pixelsize(colormodel) * 8;
1015 bits /= BC_CModels::components(colormodel);
1016 int icolor_model = BC_CModels::has_alpha(colormodel) ?
1017 (bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1018 (bits > 8 ? BC_RGB161616: BC_RGB888) ;
1019 VFrame vframe(frame->get_w(), frame->get_h(), icolor_model);
1020 vframe.transfer_from(frame);
1021 if( !convert_vframe_picture(&vframe, op, ofmt, ow, oh) ) return 1;
1025 int FFVideoConvert::transfer_pixfmt(VFrame *frame,
1026 AVFrame *ofp, AVPixelFormat ofmt, int ow, int oh)
1028 int ret = convert_pixfmt(frame, ofp, ofmt, ow, oh);
1030 BC_Hash *hp = frame->get_params();
1031 AVDictionary **dict = avpriv_frame_get_metadatap(ofp);
1032 //av_dict_free(dict);
1033 for( int i=0; i<hp->size(); ++i ) {
1034 char *key = hp->get_key(i), *val = hp->get_value(i);
1035 av_dict_set(dict, key, val, 0);
1041 void FFVideoStream::load_markers()
1043 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1044 if( idx >= index_state->video_markers.size() ) return;
1045 FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
1049 FFMPEG::FFMPEG(FileBase *file_base)
1052 this->file_base = file_base;
1053 memset(file_format,0,sizeof(file_format));
1054 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
1055 flow_lock = new Condition(1,"FFStream::flow_lock",0);
1058 decoding = encoding = 0;
1059 has_audio = has_video = 0;
1062 opt_video_filter = 0;
1063 opt_audio_filter = 0;
1064 char option_path[BCTEXTLEN];
1065 set_option_path(option_path, "%s", "ffmpeg.opts");
1066 read_options(option_path, opts);
1071 ff_lock("FFMPEG::~FFMPEG()");
1073 ffaudio.remove_all_objects();
1074 ffvideo.remove_all_objects();
1075 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1079 av_dict_free(&opts);
1080 delete [] opt_video_filter;
1081 delete [] opt_audio_filter;
1084 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1086 const int *p = codec->supported_samplerates;
1087 if( !p ) return sample_rate;
1089 if( *p == sample_rate ) return *p;
1095 static inline AVRational std_frame_rate(int i)
1097 static const int m1 = 1001*12, m2 = 1000*12;
1098 static const int freqs[] = {
1099 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1100 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
1102 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1103 return (AVRational) { freq, 1001*12 };
1106 AVRational FFMPEG::check_frame_rate(AVCodec *codec, double frame_rate)
1108 const AVRational *p = codec->supported_framerates;
1109 AVRational rate, best_rate = (AVRational) { 0, 0 };
1110 double max_err = 1.; int i = 0;
1111 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1112 double framerate = (double) rate.num / rate.den;
1113 double err = fabs(frame_rate/framerate - 1.);
1114 if( err >= max_err ) continue;
1118 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1121 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1124 double display_aspect = asset->width / (double)asset->height;
1125 double sample_aspect = asset->aspect_ratio / display_aspect;
1126 int width = 1000000, height = width * sample_aspect + 0.5;
1128 MWindow::create_aspect_ratio(w, h, width, height);
1129 return (AVRational){(int)h, (int)w};
1132 return (AVRational){1, 1};
1136 AVRational FFMPEG::to_time_base(int sample_rate)
1138 return (AVRational){1, sample_rate};
1141 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
1143 char *ep = path + BCTEXTLEN-1;
1144 strncpy(path, File::get_cindat_path(), ep-path);
1145 strncat(path, "/ffmpeg/", ep-path);
1146 path += strlen(path);
1149 path += vsnprintf(path, ep-path, fmt, ap);
1154 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
1159 set_option_path(path, "%s/%s", type, spec);
1162 int FFMPEG::get_format(char *format, const char *path, const char *spec)
1164 char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
1165 get_option_path(option_path, path, spec);
1166 FILE *fp = fopen(option_path,"r");
1169 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1171 line[sizeof(line)-1] = 0;
1172 ret = scan_option_line(line, format, codec);
1178 int FFMPEG::get_codec(char *codec, const char *path, const char *spec)
1180 char option_path[BCTEXTLEN], line[BCTEXTLEN], format[BCTEXTLEN];
1181 get_option_path(option_path, path, spec);
1182 FILE *fp = fopen(option_path,"r");
1185 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1188 line[sizeof(line)-1] = 0;
1189 ret = scan_option_line(line, format, codec);
1192 char *vp = codec, *ep = vp+BCTEXTLEN-1;
1193 while( vp < ep && *vp && *vp != '|' ) ++vp;
1194 if( *vp == '|' ) --vp;
1195 while( vp > codec && (*vp==' ' || *vp=='\t') ) *vp-- = 0;
1200 int FFMPEG::get_file_format()
1203 char audio_format[BCSTRLEN], video_format[BCSTRLEN];
1204 file_format[0] = audio_format[0] = video_format[0] = 0;
1205 Asset *asset = file_base->asset;
1206 if( !ret && asset->audio_data )
1207 ret = get_format(audio_format, "audio", asset->acodec);
1208 if( !ret && asset->video_data )
1209 ret = get_format(video_format, "video", asset->vcodec);
1210 if( !ret && !audio_format[0] && !video_format[0] )
1212 if( !ret && audio_format[0] && video_format[0] &&
1213 strcmp(audio_format, video_format) ) ret = -1;
1215 strcpy(file_format, audio_format[0] ? audio_format : video_format);
1219 int FFMPEG::scan_option_line(char *cp, char *tag, char *val)
1221 while( *cp == ' ' || *cp == '\t' ) ++cp;
1223 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' ) ++cp;
1225 if( !len || len > BCSTRLEN-1 ) return 1;
1226 while( bp < cp ) *tag++ = *bp++;
1228 while( *cp == ' ' || *cp == '\t' ) ++cp;
1229 if( *cp == '=' ) ++cp;
1230 while( *cp == ' ' || *cp == '\t' ) ++cp;
1232 while( *cp && *cp != '\n' ) ++cp;
1234 if( len > BCTEXTLEN-1 ) return 1;
1235 while( bp < cp ) *val++ = *bp++;
1240 int FFMPEG::load_defaults(const char *path, const char *type,
1241 char *codec, char *codec_options, int len)
1243 char default_file[BCTEXTLEN];
1244 FFMPEG::set_option_path(default_file, "%s/%s.dfl", path, type);
1245 FILE *fp = fopen(default_file,"r");
1247 fgets(codec, BCSTRLEN, fp);
1249 while( *cp && *cp!='\n' ) ++cp;
1251 while( len > 0 && fgets(codec_options, len, fp) ) {
1252 int n = strlen(codec_options);
1253 codec_options += n; len -= n;
1256 FFMPEG::set_option_path(default_file, "%s/%s", path, codec);
1257 return FFMPEG::load_options(default_file, codec_options, len);
1260 void FFMPEG::set_asset_format(Asset *asset, const char *text)
1262 if( asset->format != FILE_FFMPEG ) return;
1263 strcpy(asset->fformat, text);
1264 if( !asset->ff_audio_options[0] ) {
1265 asset->audio_data = !load_defaults("audio", text, asset->acodec,
1266 asset->ff_audio_options, sizeof(asset->ff_audio_options));
1268 if( !asset->ff_video_options[0] ) {
1269 asset->video_data = !load_defaults("video", text, asset->vcodec,
1270 asset->ff_video_options, sizeof(asset->ff_video_options));
1274 int FFMPEG::get_encoder(const char *options,
1275 char *format, char *codec, char *bsfilter, char *bsargs)
1277 FILE *fp = fopen(options,"r");
1279 eprintf("FFMPEG::get_encoder: options open failed %s\n",options);
1282 if( get_encoder(fp, format, codec, bsfilter, bsargs) )
1283 eprintf(_("FFMPEG::get_encoder:"
1284 " err: format/codec not found %s\n"), options);
1289 int FFMPEG::get_encoder(FILE *fp,
1290 char *format, char *codec, char *bsfilter, char *bsargs)
1292 format[0] = codec[0] = bsfilter[0] = bsargs[0] = 0;
1293 char line[BCTEXTLEN];
1294 if( !fgets(line, sizeof(line), fp) ) return 1;
1295 line[sizeof(line)-1] = 0;
1296 if( scan_option_line(line, format, codec) ) return 1;
1298 while( *cp && *cp != '|' ) ++cp;
1299 if( !*cp ) return 0;
1300 if( scan_option_line(cp+1, bsfilter, bsargs) ) return 1;
1301 do { *cp-- = 0; } while( cp>=codec && (*cp==' ' || *cp == '\t' ) );
1305 int FFMPEG::read_options(const char *options, AVDictionary *&opts)
1307 FILE *fp = fopen(options,"r");
1309 int ret = read_options(fp, options, opts);
1314 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
1316 FILE *fp = fmemopen((void *)options,strlen(options),"r");
1318 int ret = read_options(fp, options, opts);
1320 AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
1321 if( tag ) st->id = strtol(tag->value,0,0);
1325 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
1327 int ret = 0, no = 0;
1328 char line[BCTEXTLEN];
1329 while( !ret && fgets(line, sizeof(line), fp) ) {
1330 line[sizeof(line)-1] = 0;
1332 if( line[0] == '#' ) continue;
1333 if( line[0] == '\n' ) continue;
1334 char key[BCSTRLEN], val[BCTEXTLEN];
1335 if( scan_option_line(line, key, val) ) {
1336 eprintf(_("FFMPEG::read_options:"
1337 " err reading %s: line %d\n"), options, no);
1341 if( !strcmp(key, "duration") )
1342 opt_duration = strtod(val, 0);
1343 else if( !strcmp(key, "video_filter") )
1344 opt_video_filter = cstrdup(val);
1345 else if( !strcmp(key, "audio_filter") )
1346 opt_audio_filter = cstrdup(val);
1347 else if( !strcmp(key, "loglevel") )
1350 av_dict_set(&opts, key, val, 0);
1356 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
1358 char option_path[BCTEXTLEN];
1359 set_option_path(option_path, "%s", options);
1360 return read_options(option_path, opts);
1363 int FFMPEG::load_options(const char *path, char *bfr, int len)
1366 FILE *fp = fopen(path, "r");
1368 fgets(bfr, len, fp); // skip hdr
1369 len = fread(bfr, 1, len-1, fp);
1370 if( len < 0 ) len = 0;
1376 void FFMPEG::set_loglevel(const char *ap)
1378 if( !ap || !*ap ) return;
1383 { "quiet" , AV_LOG_QUIET },
1384 { "panic" , AV_LOG_PANIC },
1385 { "fatal" , AV_LOG_FATAL },
1386 { "error" , AV_LOG_ERROR },
1387 { "warning", AV_LOG_WARNING },
1388 { "info" , AV_LOG_INFO },
1389 { "verbose", AV_LOG_VERBOSE },
1390 { "debug" , AV_LOG_DEBUG },
1392 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
1393 if( !strcmp(log_levels[i].name, ap) ) {
1394 av_log_set_level(log_levels[i].level);
1398 av_log_set_level(atoi(ap));
1401 double FFMPEG::to_secs(int64_t time, AVRational time_base)
1403 double base_time = time == AV_NOPTS_VALUE ? 0 :
1404 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
1405 return base_time / AV_TIME_BASE;
1408 int FFMPEG::info(char *text, int len)
1410 if( len <= 0 ) return 0;
1412 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
1414 if( ffvideo.size() > 0 )
1415 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
1416 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
1417 FFVideoStream *vid = ffvideo[vidx];
1418 AVStream *st = vid->st;
1419 AVCodecContext *avctx = st->codec;
1420 report(_("vid%d (%d), id 0x%06x:\n"), vid->idx, vid->fidx, avctx->codec_id);
1421 const AVCodecDescriptor *desc = avcodec_descriptor_get(avctx->codec_id);
1422 report(" video%d %s", vidx+1, desc ? desc->name : " (unkn)");
1423 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
1424 const char *pfn = av_get_pix_fmt_name(avctx->pix_fmt);
1425 report(" pix %s\n", pfn ? pfn : "(unkn)");
1426 double secs = to_secs(st->duration, st->time_base);
1427 int64_t length = secs * vid->frame_rate + 0.5;
1428 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
1429 int64_t nudge = ofs * vid->frame_rate;
1430 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1431 report(" %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
1432 int hrs = secs/3600; secs -= hrs*3600;
1433 int mins = secs/60; secs -= mins*60;
1434 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1436 if( ffaudio.size() > 0 )
1437 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
1438 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
1439 FFAudioStream *aud = ffaudio[aidx];
1440 AVStream *st = aud->st;
1441 AVCodecContext *avctx = st->codec;
1442 report(_("aud%d (%d), id 0x%06x:\n"), aud->idx, aud->fidx, avctx->codec_id);
1443 const AVCodecDescriptor *desc = avcodec_descriptor_get(avctx->codec_id);
1444 int nch = aud->channels, ch0 = aud->channel0+1;
1445 report(" audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
1446 const char *fmt = av_get_sample_fmt_name(avctx->sample_fmt);
1447 report(" %s %d", fmt, aud->sample_rate);
1448 int sample_bits = av_get_bits_per_sample(avctx->codec_id);
1449 report(" %dbits\n", sample_bits);
1450 double secs = to_secs(st->duration, st->time_base);
1451 int64_t length = secs * aud->sample_rate + 0.5;
1452 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
1453 int64_t nudge = ofs * aud->sample_rate;
1454 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1455 report(" %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
1456 int hrs = secs/3600; secs -= hrs*3600;
1457 int mins = secs/60; secs -= mins*60;
1458 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1460 if( fmt_ctx->nb_programs > 0 )
1461 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
1462 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
1463 report("program %d", i+1);
1464 AVProgram *pgrm = fmt_ctx->programs[i];
1465 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1466 int idx = pgrm->stream_index[j];
1467 int vidx = ffvideo.size();
1468 while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
1470 report(", vid%d", vidx);
1473 int aidx = ffaudio.size();
1474 while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
1476 report(", aud%d", aidx);
1479 report(", (%d)", pgrm->stream_index[j]);
1484 AVDictionaryEntry *tag = 0;
1485 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
1486 report("%s=%s\n", tag->key, tag->value);
1495 int FFMPEG::init_decoder(const char *filename)
1497 ff_lock("FFMPEG::init_decoder");
1499 char file_opts[BCTEXTLEN];
1500 char *bp = strrchr(strcpy(file_opts, filename), '/');
1501 char *sp = strrchr(!bp ? file_opts : bp, '.');
1504 strcpy(sp, ".opts");
1505 fp = fopen(file_opts, "r");
1508 read_options(fp, file_opts, opts);
1512 load_options("decode.opts", opts);
1513 AVDictionary *fopts = 0;
1514 av_dict_copy(&fopts, opts, 0);
1515 int ret = avformat_open_input(&fmt_ctx, filename, NULL, &fopts);
1516 av_dict_free(&fopts);
1518 ret = avformat_find_stream_info(fmt_ctx, NULL);
1523 return !ret ? 0 : 1;
1526 int FFMPEG::open_decoder()
1529 if( stat(fmt_ctx->filename, &st) < 0 ) {
1530 eprintf("FFMPEG::open_decoder: can't stat file: %s\n",
1535 int64_t file_bits = 8 * st.st_size;
1536 if( !fmt_ctx->bit_rate && opt_duration > 0 )
1537 fmt_ctx->bit_rate = file_bits / opt_duration;
1540 if( fmt_ctx->bit_rate > 0 ) {
1541 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1542 AVStream *st = fmt_ctx->streams[i];
1543 if( st->duration != AV_NOPTS_VALUE ) continue;
1544 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
1545 st->duration = av_rescale(file_bits, st->time_base.den,
1546 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
1551 printf("FFMPEG::open_decoder: some stream times estimated\n");
1553 ff_lock("FFMPEG::open_decoder");
1555 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1556 AVStream *st = fmt_ctx->streams[i];
1557 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
1558 AVCodecContext *avctx = st->codec;
1559 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avctx->codec_id);
1560 if( !codec_desc ) continue;
1561 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1562 if( avctx->width < 1 ) continue;
1563 if( avctx->height < 1 ) continue;
1564 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
1565 if( framerate.num < 1 ) continue;
1567 int vidx = ffvideo.size();
1568 FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
1569 vstrm_index.append(ffidx(vidx, 0));
1570 ffvideo.append(vid);
1571 vid->width = avctx->width;
1572 vid->height = avctx->height;
1573 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
1574 double secs = to_secs(st->duration, st->time_base);
1575 vid->length = secs * vid->frame_rate;
1576 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
1577 vid->nudge = st->start_time;
1579 if( opt_video_filter )
1580 vid->create_filter(opt_video_filter, avctx,avctx);
1582 else if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1583 if( avctx->channels < 1 ) continue;
1584 if( avctx->sample_rate < 1 ) continue;
1586 int aidx = ffaudio.size();
1587 FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
1588 ffaudio.append(aud);
1589 aud->channel0 = astrm_index.size();
1590 aud->channels = avctx->channels;
1591 for( int ch=0; ch<aud->channels; ++ch )
1592 astrm_index.append(ffidx(aidx, ch));
1593 aud->sample_rate = avctx->sample_rate;
1594 double secs = to_secs(st->duration, st->time_base);
1595 aud->length = secs * aud->sample_rate;
1596 if( avctx->sample_fmt != AV_SAMPLE_FMT_FLT ) {
1597 uint64_t layout = av_get_default_channel_layout(avctx->channels);
1598 if( !layout ) layout = ((uint64_t)1<<aud->channels) - 1;
1599 aud->resample_context = swr_alloc_set_opts(NULL,
1600 layout, AV_SAMPLE_FMT_FLT, avctx->sample_rate,
1601 layout, avctx->sample_fmt, avctx->sample_rate,
1603 swr_init(aud->resample_context);
1605 aud->nudge = st->start_time;
1607 if( opt_audio_filter )
1608 aud->create_filter(opt_audio_filter, avctx,avctx);
1612 printf("FFMPEG::open_decoder: some stream have bad times\n");
1618 int FFMPEG::init_encoder(const char *filename)
1620 int fd = ::open(filename,O_WRONLY);
1621 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
1623 eprintf("FFMPEG::init_encoder: bad file path: %s\n", filename);
1627 int ret = get_file_format();
1629 eprintf("FFMPEG::init_encoder: bad file format: %s\n", filename);
1633 eprintf("FFMPEG::init_encoder: mismatch audio/video file format: %s\n", filename);
1636 ff_lock("FFMPEG::init_encoder");
1638 avformat_alloc_output_context2(&fmt_ctx, 0, file_format, filename);
1640 eprintf("FFMPEG::init_encoder: failed: %s\n", filename);
1645 load_options("encode.opts", opts);
1651 int FFMPEG::open_encoder(const char *type, const char *spec)
1654 Asset *asset = file_base->asset;
1655 char *filename = asset->path;
1656 AVDictionary *sopts = 0;
1657 av_dict_copy(&sopts, opts, 0);
1658 char option_path[BCTEXTLEN];
1659 set_option_path(option_path, "%s/%s.opts", type, type);
1660 read_options(option_path, sopts);
1661 get_option_path(option_path, type, spec);
1662 char format_name[BCSTRLEN], codec_name[BCTEXTLEN];
1663 char bsfilter[BCSTRLEN], bsargs[BCTEXTLEN];
1664 if( get_encoder(option_path, format_name, codec_name, bsfilter, bsargs) ) {
1665 eprintf("FFMPEG::open_encoder: get_encoder failed %s:%s\n",
1666 option_path, filename);
1670 if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
1671 else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
1672 else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
1675 ff_lock("FFMPEG::open_encoder");
1679 const AVCodecDescriptor *codec_desc = 0;
1680 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
1682 eprintf("FFMPEG::open_encoder: cant find codec %s:%s\n",
1683 codec_name, filename);
1687 codec_desc = avcodec_descriptor_get(codec->id);
1689 eprintf("FFMPEG::open_encoder: unknown codec %s:%s\n",
1690 codec_name, filename);
1695 st = avformat_new_stream(fmt_ctx, 0);
1697 eprintf("FFMPEG::open_encoder: cant create stream %s:%s\n",
1698 codec_name, filename);
1703 AVCodecContext *ctx = st->codec;
1704 switch( codec_desc->type ) {
1705 case AVMEDIA_TYPE_AUDIO: {
1707 eprintf("FFMPEG::open_encoder: duplicate audio %s:%s\n",
1708 codec_name, filename);
1713 if( scan_options(asset->ff_audio_options, sopts, st) ) {
1714 eprintf("FFMPEG::open_encoder: bad audio options %s:%s\n",
1715 codec_name, filename);
1719 if( asset->ff_audio_bitrate > 0 ) {
1720 ctx->bit_rate = asset->ff_audio_bitrate;
1722 sprintf(arg, "%d", asset->ff_audio_bitrate);
1723 av_dict_set(&sopts, "b", arg, 0);
1725 int aidx = ffaudio.size();
1726 int fidx = aidx + ffvideo.size();
1727 FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
1728 ffaudio.append(aud); fst = aud;
1729 aud->sample_rate = asset->sample_rate;
1730 ctx->channels = aud->channels = asset->channels;
1731 for( int ch=0; ch<aud->channels; ++ch )
1732 astrm_index.append(ffidx(aidx, ch));
1733 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
1734 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
1735 if( !ctx->sample_rate ) {
1736 eprintf("FFMPEG::open_encoder:"
1737 " check_sample_rate failed %s\n", filename);
1741 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
1742 ctx->sample_fmt = codec->sample_fmts[0];
1743 uint64_t layout = av_get_default_channel_layout(ctx->channels);
1744 aud->resample_context = swr_alloc_set_opts(NULL,
1745 layout, ctx->sample_fmt, aud->sample_rate,
1746 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
1748 swr_init(aud->resample_context);
1751 case AVMEDIA_TYPE_VIDEO: {
1753 eprintf("FFMPEG::open_encoder: duplicate video %s:%s\n",
1754 codec_name, filename);
1759 if( scan_options(asset->ff_video_options, sopts, st) ) {
1760 eprintf("FFMPEG::open_encoder: bad video options %s:%s\n",
1761 codec_name, filename);
1765 if( asset->ff_video_bitrate > 0 ) {
1766 ctx->bit_rate = asset->ff_video_bitrate;
1768 sprintf(arg, "%d", asset->ff_video_bitrate);
1769 av_dict_set(&sopts, "b", arg, 0);
1771 else if( asset->ff_video_quality > 0 ) {
1772 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
1773 ctx->qmin = ctx->qmax = asset->ff_video_quality;
1774 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
1775 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
1776 ctx->flags |= CODEC_FLAG_QSCALE;
1778 av_dict_set(&sopts, "flags", "+qscale", 0);
1779 sprintf(arg, "%d", asset->ff_video_quality);
1780 av_dict_set(&sopts, "qscale", arg, 0);
1781 sprintf(arg, "%d", ctx->global_quality);
1782 av_dict_set(&sopts, "global_quality", arg, 0);
1784 int vidx = ffvideo.size();
1785 int fidx = vidx + ffaudio.size();
1786 FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
1787 vstrm_index.append(ffidx(vidx, 0));
1788 ffvideo.append(vid); fst = vid;
1789 vid->width = asset->width;
1790 ctx->width = (vid->width+3) & ~3;
1791 vid->height = asset->height;
1792 ctx->height = (vid->height+3) & ~3;
1793 vid->frame_rate = asset->frame_rate;
1794 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
1795 ctx->pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
1796 AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
1797 if( !frame_rate.num || !frame_rate.den ) {
1798 eprintf("FFMPEG::open_encoder:"
1799 " check_frame_rate failed %s\n", filename);
1803 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
1804 st->time_base = ctx->time_base;
1808 eprintf("FFMPEG::open_encoder: not audio/video, %s:%s\n",
1809 codec_name, filename);
1814 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
1815 st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
1817 ret = avcodec_open2(st->codec, codec, &sopts);
1819 ff_err(ret,"FFMPEG::open_encoder");
1820 eprintf("FFMPEG::open_encoder: open failed %s:%s\n",
1821 codec_name, filename);
1828 if( fst && bsfilter[0] )
1829 fst->add_bsfilter(bsfilter, !bsargs[0] ? 0 : bsargs);
1835 av_dict_free(&sopts);
1839 int FFMPEG::close_encoder()
1842 if( encoding > 0 ) {
1843 av_write_trailer(fmt_ctx);
1844 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
1845 avio_closep(&fmt_ctx->pb);
1851 int FFMPEG::decode_activate()
1853 if( decoding < 0 ) {
1855 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
1856 ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
1857 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
1858 ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
1859 // set nudges for each program stream set
1860 int npgrms = fmt_ctx->nb_programs;
1861 for( int i=0; i<npgrms; ++i ) {
1862 AVProgram *pgrm = fmt_ctx->programs[i];
1863 // first start time video stream
1864 int64_t vstart_time = -1, astart_time = -1;
1865 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1866 int fidx = pgrm->stream_index[j];
1867 AVStream *st = fmt_ctx->streams[fidx];
1868 AVCodecContext *avctx = st->codec;
1869 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1870 if( st->start_time == AV_NOPTS_VALUE ) continue;
1871 if( vstart_time > st->start_time ) continue;
1872 vstart_time = st->start_time;
1875 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1876 if( st->start_time == AV_NOPTS_VALUE ) continue;
1877 if( astart_time > st->start_time ) continue;
1878 astart_time = st->start_time;
1882 // match program streams to max start_time
1883 int64_t nudge = vstart_time > astart_time ? vstart_time : astart_time;
1884 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1885 int fidx = pgrm->stream_index[j];
1886 AVStream *st = fmt_ctx->streams[fidx];
1887 AVCodecContext *avctx = st->codec;
1888 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1889 for( int k=0; k<ffvideo.size(); ++k ) {
1890 if( ffvideo[k]->fidx != fidx ) continue;
1891 ffvideo[k]->nudge = nudge;
1895 if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1896 for( int k=0; k<ffaudio.size(); ++k ) {
1897 if( ffaudio[k]->fidx != fidx ) continue;
1898 ffaudio[k]->nudge = nudge;
1904 // set nudges for any streams not yet set
1905 int64_t vstart_time = 0, astart_time = 0;
1906 int nstreams = fmt_ctx->nb_streams;
1907 for( int i=0; i<nstreams; ++i ) {
1908 AVStream *st = fmt_ctx->streams[i];
1909 AVCodecContext *avctx = st->codec;
1910 switch( avctx->codec_type ) {
1911 case AVMEDIA_TYPE_VIDEO: {
1912 if( st->start_time == AV_NOPTS_VALUE ) continue;
1913 int vidx = ffvideo.size();
1914 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
1915 if( vidx >= 0 && ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
1916 if( vstart_time >= st->start_time ) continue;
1917 vstart_time = st->start_time;
1919 case AVMEDIA_TYPE_AUDIO: {
1920 if( st->start_time == AV_NOPTS_VALUE ) continue;
1921 int aidx = ffaudio.size();
1922 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
1923 if( aidx >= 0 && ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
1924 if( astart_time >= st->start_time ) continue;
1925 astart_time = st->start_time;
1930 int64_t nudge = vstart_time > astart_time ? vstart_time : astart_time;
1931 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
1932 if( ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
1933 ffvideo[vidx]->nudge = nudge;
1935 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
1936 if( ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
1937 ffaudio[aidx]->nudge = nudge;
1944 int FFMPEG::encode_activate()
1947 if( encoding < 0 ) {
1949 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
1950 (ret=avio_open(&fmt_ctx->pb, fmt_ctx->filename, AVIO_FLAG_WRITE)) < 0 ) {
1951 ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
1956 AVDictionary *fopts = 0;
1957 char option_path[BCTEXTLEN];
1958 set_option_path(option_path, "format/%s", file_format);
1959 read_options(option_path, fopts);
1960 ret = avformat_write_header(fmt_ctx, &fopts);
1961 av_dict_free(&fopts);
1963 ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
1973 int FFMPEG::audio_seek(int stream, int64_t pos)
1975 int aidx = astrm_index[stream].st_idx;
1976 FFAudioStream *aud = ffaudio[aidx];
1977 aud->audio_seek(pos);
1981 int FFMPEG::video_seek(int stream, int64_t pos)
1983 int vidx = vstrm_index[stream].st_idx;
1984 FFVideoStream *vid = ffvideo[vidx];
1985 vid->video_seek(pos);
1990 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
1992 if( !has_audio || chn >= astrm_index.size() ) return -1;
1993 int aidx = astrm_index[chn].st_idx;
1994 FFAudioStream *aud = ffaudio[aidx];
1995 if( aud->load(pos, len) < len ) return -1;
1996 int ch = astrm_index[chn].st_ch;
1997 int ret = aud->read(samples,len,ch);
2001 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
2003 if( !has_video || layer >= vstrm_index.size() ) return -1;
2004 int vidx = vstrm_index[layer].st_idx;
2005 FFVideoStream *vid = ffvideo[vidx];
2006 return vid->load(vframe, pos);
2010 int FFMPEG::encode(int stream, double **samples, int len)
2012 FFAudioStream *aud = ffaudio[stream];
2013 return aud->encode(samples, len);
2017 int FFMPEG::encode(int stream, VFrame *frame)
2019 FFVideoStream *vid = ffvideo[stream];
2020 return vid->encode(frame);
2023 void FFMPEG::start_muxer()
2031 void FFMPEG::stop_muxer()
2040 void FFMPEG::flow_off()
2043 flow_lock->lock("FFMPEG::flow_off");
2047 void FFMPEG::flow_on()
2051 flow_lock->unlock();
2054 void FFMPEG::flow_ctl()
2057 flow_lock->lock("FFMPEG::flow_ctl");
2058 flow_lock->unlock();
2062 int FFMPEG::mux_audio(FFrame *frm)
2065 FFStream *fst = frm->fst;
2066 AVCodecContext *ctx = fst->st->codec;
2067 AVFrame *frame = *frm;
2068 AVRational tick_rate = {1, ctx->sample_rate};
2069 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
2071 int ret = fst->encode_frame(pkt, frame, got_packet);
2072 if( ret >= 0 && got_packet )
2073 ret = fst->write_packet(pkt);
2075 ff_err(ret, "FFMPEG::mux_audio");
2076 return ret >= 0 ? 0 : 1;
2079 int FFMPEG::mux_video(FFrame *frm)
2082 FFStream *fst = frm->fst;
2083 AVFrame *frame = *frm;
2084 frame->pts = frm->position;
2086 int ret = fst->encode_frame(pkt, frame, got_packet);
2087 if( ret >= 0 && got_packet )
2088 ret = fst->write_packet(pkt);
2090 ff_err(ret, "FFMPEG::mux_video");
2091 return ret >= 0 ? 0 : 1;
2097 double atm = -1, vtm = -1;
2098 FFrame *afrm = 0, *vfrm = 0;
2100 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
2101 FFStream *fst = ffaudio[i];
2102 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
2103 FFrame *frm = fst->frms.first;
2104 if( !frm ) { if( !done ) return; continue; }
2105 double tm = to_secs(frm->position, fst->st->codec->time_base);
2106 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
2108 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
2109 FFStream *fst = ffvideo[i];
2110 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
2111 FFrame *frm = fst->frms.first;
2112 if( !frm ) { if( !done ) return; continue; }
2113 double tm = to_secs(frm->position, fst->st->codec->time_base);
2114 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
2116 if( !demand ) flow_off();
2117 if( !afrm && !vfrm ) break;
2118 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
2119 vfrm->position, vfrm->fst->st->codec->time_base,
2120 afrm->position, afrm->fst->st->codec->time_base);
2121 FFrame *frm = v <= 0 ? vfrm : afrm;
2122 if( frm == afrm ) mux_audio(frm);
2123 if( frm == vfrm ) mux_video(frm);
2132 mux_lock->lock("FFMPEG::run");
2136 for( int i=0; i<ffaudio.size(); ++i )
2137 ffaudio[i]->flush();
2138 for( int i=0; i<ffvideo.size(); ++i )
2139 ffvideo[i]->flush();
2143 int FFMPEG::ff_total_audio_channels()
2145 return astrm_index.size();
2148 int FFMPEG::ff_total_astreams()
2150 return ffaudio.size();
2153 int FFMPEG::ff_audio_channels(int stream)
2155 return ffaudio[stream]->channels;
2158 int FFMPEG::ff_sample_rate(int stream)
2160 return ffaudio[stream]->sample_rate;
2163 const char* FFMPEG::ff_audio_format(int stream)
2165 AVStream *st = ffaudio[stream]->st;
2166 AVCodecID id = st->codec->codec_id;
2167 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2168 return desc ? desc->name : "Unknown";
2171 int FFMPEG::ff_audio_pid(int stream)
2173 return ffaudio[stream]->st->id;
2176 int64_t FFMPEG::ff_audio_samples(int stream)
2178 return ffaudio[stream]->length;
2181 // find audio astream/channels with this program,
2182 // or all program audio channels (astream=-1)
2183 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
2187 int vidx = ffvideo[vstream]->fidx;
2188 // find first program with this video stream
2189 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
2190 AVProgram *pgrm = fmt_ctx->programs[i];
2191 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
2192 int st_idx = pgrm->stream_index[j];
2193 AVStream *st = fmt_ctx->streams[st_idx];
2194 if( st->codec->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
2195 if( st_idx == vidx ) pidx = i;
2198 if( pidx < 0 ) return -1;
2200 int64_t channels = 0;
2201 AVProgram *pgrm = fmt_ctx->programs[pidx];
2202 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2203 int aidx = pgrm->stream_index[j];
2204 AVStream *st = fmt_ctx->streams[aidx];
2205 if( st->codec->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
2206 if( astream > 0 ) { --astream; continue; }
2208 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
2209 if( ffaudio[i]->fidx == aidx ) astrm = i;
2211 if( ret < 0 ) ret = astrm;
2212 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
2213 channels |= mask << ffaudio[astrm]->channel0;
2215 if( !astream ) break;
2217 channel_mask = channels;
2222 int FFMPEG::ff_total_video_layers()
2224 return vstrm_index.size();
2227 int FFMPEG::ff_total_vstreams()
2229 return ffvideo.size();
2232 int FFMPEG::ff_video_width(int stream)
2234 return ffvideo[stream]->width;
2237 int FFMPEG::ff_video_height(int stream)
2239 return ffvideo[stream]->height;
2242 int FFMPEG::ff_set_video_width(int stream, int width)
2244 int w = ffvideo[stream]->width;
2245 ffvideo[stream]->width = width;
2249 int FFMPEG::ff_set_video_height(int stream, int height)
2251 int h = ffvideo[stream]->height;
2252 ffvideo[stream]->height = height;
2256 int FFMPEG::ff_coded_width(int stream)
2258 AVStream *st = ffvideo[stream]->st;
2259 return st->codec->coded_width;
2262 int FFMPEG::ff_coded_height(int stream)
2264 AVStream *st = ffvideo[stream]->st;
2265 return st->codec->coded_height;
2268 float FFMPEG::ff_aspect_ratio(int stream)
2270 return ffvideo[stream]->aspect_ratio;
2273 const char* FFMPEG::ff_video_format(int stream)
2275 AVStream *st = ffvideo[stream]->st;
2276 AVCodecID id = st->codec->codec_id;
2277 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2278 return desc ? desc->name : "Unknown";
2281 double FFMPEG::ff_frame_rate(int stream)
2283 return ffvideo[stream]->frame_rate;
2286 int64_t FFMPEG::ff_video_frames(int stream)
2288 return ffvideo[stream]->length;
2291 int FFMPEG::ff_video_pid(int stream)
2293 return ffvideo[stream]->st->id;
2297 int FFMPEG::ff_cpus()
2299 return file_base->file->cpus;
2302 int FFVideoStream::create_filter(const char *filter_spec,
2303 AVCodecContext *src_ctx, AVCodecContext *sink_ctx)
2305 avfilter_register_all();
2306 AVFilter *filter = avfilter_get_by_name(filter_spec);
2307 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_VIDEO ) {
2308 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
2311 filter_graph = avfilter_graph_alloc();
2312 AVFilter *buffersrc = avfilter_get_by_name("buffer");
2313 AVFilter *buffersink = avfilter_get_by_name("buffersink");
2315 int ret = 0; char args[BCTEXTLEN];
2316 snprintf(args, sizeof(args),
2317 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
2318 src_ctx->width, src_ctx->height, src_ctx->pix_fmt,
2319 src_ctx->time_base.num, src_ctx->time_base.den,
2320 src_ctx->sample_aspect_ratio.num, src_ctx->sample_aspect_ratio.den);
2322 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2323 args, NULL, filter_graph);
2325 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2326 NULL, NULL, filter_graph);
2328 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
2329 (uint8_t*)&sink_ctx->pix_fmt, sizeof(sink_ctx->pix_fmt),
2330 AV_OPT_SEARCH_CHILDREN);
2332 ff_err(ret, "FFVideoStream::create_filter");
2334 ret = FFStream::create_filter(filter_spec);
2335 return ret >= 0 ? 0 : 1;
2338 int FFAudioStream::create_filter(const char *filter_spec,
2339 AVCodecContext *src_ctx, AVCodecContext *sink_ctx)
2341 avfilter_register_all();
2342 AVFilter *filter = avfilter_get_by_name(filter_spec);
2343 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_AUDIO ) {
2344 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
2347 filter_graph = avfilter_graph_alloc();
2348 AVFilter *buffersrc = avfilter_get_by_name("abuffer");
2349 AVFilter *buffersink = avfilter_get_by_name("abuffersink");
2350 int ret = 0; char args[BCTEXTLEN];
2351 snprintf(args, sizeof(args),
2352 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
2353 src_ctx->time_base.num, src_ctx->time_base.den, src_ctx->sample_rate,
2354 av_get_sample_fmt_name(src_ctx->sample_fmt), src_ctx->channel_layout);
2356 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2357 args, NULL, filter_graph);
2359 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2360 NULL, NULL, filter_graph);
2362 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
2363 (uint8_t*)&sink_ctx->sample_fmt, sizeof(sink_ctx->sample_fmt),
2364 AV_OPT_SEARCH_CHILDREN);
2366 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
2367 (uint8_t*)&sink_ctx->channel_layout,
2368 sizeof(sink_ctx->channel_layout), AV_OPT_SEARCH_CHILDREN);
2370 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
2371 (uint8_t*)&sink_ctx->sample_rate, sizeof(sink_ctx->sample_rate),
2372 AV_OPT_SEARCH_CHILDREN);
2374 ff_err(ret, "FFAudioStream::create_filter");
2376 ret = FFStream::create_filter(filter_spec);
2377 return ret >= 0 ? 0 : 1;
2380 int FFStream::create_filter(const char *filter_spec)
2382 /* Endpoints for the filter graph. */
2383 AVFilterInOut *outputs = avfilter_inout_alloc();
2384 outputs->name = av_strdup("in");
2385 outputs->filter_ctx = buffersrc_ctx;
2386 outputs->pad_idx = 0;
2389 AVFilterInOut *inputs = avfilter_inout_alloc();
2390 inputs->name = av_strdup("out");
2391 inputs->filter_ctx = buffersink_ctx;
2392 inputs->pad_idx = 0;
2395 int ret = !outputs->name || !inputs->name ? -1 : 0;
2397 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
2398 &inputs, &outputs, NULL);
2400 ret = avfilter_graph_config(filter_graph, NULL);
2403 ff_err(ret, "FFStream::create_filter");
2404 avfilter_inout_free(&inputs);
2405 avfilter_inout_free(&outputs);
2409 void FFStream::add_bsfilter(const char *bsf, const char *ap)
2411 bsfilter.append(new BSFilter(bsf,ap));
2414 int FFStream::bs_filter(AVPacket *pkt)
2416 if( !bsfilter.size() ) return 0;
2417 av_packet_split_side_data(pkt);
2420 for( int i=0; i<bsfilter.size(); ++i ) {
2421 AVPacket bspkt = *pkt;
2422 ret = av_bitstream_filter_filter(bsfilter[i]->bsfc,
2423 st->codec, bsfilter[i]->args, &bspkt.data, &bspkt.size,
2424 pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY);
2425 if( ret < 0 ) break;
2426 int size = bspkt.size;
2427 uint8_t *data = bspkt.data;
2428 if( !ret && bspkt.data != pkt->data ) {
2430 data = (uint8_t *)av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
2431 if( !data ) { ret = AVERROR(ENOMEM); break; }
2432 memcpy(data, bspkt.data, size);
2433 memset(data+size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2437 pkt->side_data = 0; pkt->side_data_elems = 0;
2438 av_packet_unref(pkt);
2439 ret = av_packet_from_data(&bspkt, data, size);
2440 if( ret < 0 ) break;
2445 ff_err(ret,"FFStream::bs_filter");
2449 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
2452 av_init_packet(&pkt);
2453 AVFrame *frame = av_frame_alloc();
2455 fprintf(stderr, "FFMPEG::scan: av_frame_alloc failed\n");
2459 index_state->add_video_markers(ffvideo.size());
2460 index_state->add_audio_markers(ffaudio.size());
2462 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2463 AVDictionary *copts = 0;
2464 av_dict_copy(&copts, opts, 0);
2465 AVStream *st = fmt_ctx->streams[i];
2466 AVCodecID codec_id = st->codec->codec_id;
2467 AVCodec *decoder = avcodec_find_decoder(codec_id);
2468 if( avcodec_open2(st->codec, decoder, &copts) < 0 )
2469 fprintf(stderr, "FFMPEG::scan: codec open failed\n");
2470 av_dict_free(&copts);
2473 for( int64_t count=0; !*canceled; ++count ) {
2474 av_packet_unref(&pkt);
2475 pkt.data = 0; pkt.size = 0;
2477 int ret = av_read_frame(fmt_ctx, &pkt);
2479 if( ret == AVERROR_EOF ) break;
2480 if( ++errs > 100 ) {
2481 ff_err(ret, "over 100 read_frame errs\n");
2486 if( !pkt.data ) continue;
2487 int i = pkt.stream_index;
2488 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
2489 AVStream *st = fmt_ctx->streams[i];
2490 AVCodecContext *avctx = st->codec;
2491 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
2493 switch( avctx->codec_type ) {
2494 case AVMEDIA_TYPE_VIDEO: {
2495 int vidx = ffvideo.size();
2496 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
2497 if( vidx < 0 ) break;
2498 FFVideoStream *vid = ffvideo[vidx];
2499 int64_t tstmp = pkt.dts;
2500 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.pts;
2501 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
2502 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
2503 double secs = to_secs(tstmp, st->time_base);
2504 int64_t frm = secs * vid->frame_rate + 0.5;
2505 if( frm < 0 ) frm = 0;
2506 index_state->put_video_mark(vidx, frm, pkt.pos);
2509 while( pkt.size > 0 ) {
2510 av_frame_unref(frame);
2512 int ret = vid->decode_frame(&pkt, frame, got_frame);
2513 if( ret <= 0 ) break;
2514 // if( got_frame ) {}
2520 case AVMEDIA_TYPE_AUDIO: {
2521 int aidx = ffaudio.size();
2522 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
2523 if( aidx < 0 ) break;
2524 FFAudioStream *aud = ffaudio[aidx];
2525 int64_t tstmp = pkt.pts;
2526 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
2527 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
2528 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
2529 double secs = to_secs(tstmp, st->time_base);
2530 int64_t sample = secs * aud->sample_rate + 0.5;
2531 if( sample < 0 ) sample = 0;
2532 index_state->put_audio_mark(aidx, sample, pkt.pos);
2534 while( pkt.size > 0 ) {
2535 int ch = aud->channel0, nch = aud->channels;
2536 int64_t pos = index_state->pos(ch);
2537 if( pos != aud->curr_pos ) {
2538 if( abs(pos-aud->curr_pos) > 1 )
2539 printf("audio%d pad %ld %ld (%ld)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
2540 index_state->pad_data(ch, nch, aud->curr_pos);
2542 av_frame_unref(frame);
2544 int ret = aud->decode_frame(&pkt, frame, got_frame);
2545 if( ret <= 0 ) break;
2546 if( got_frame && frame->channels == nch ) {
2548 int len = aud->get_samples(samples,
2549 &frame->extended_data[0], frame->nb_samples);
2550 for( int i=0; i<nch; ++i )
2551 index_state->put_data(ch+i,nch,samples+i,len);
2552 aud->curr_pos += len;
2561 av_frame_free(&frame);
2565 void FFStream::load_markers(IndexMarks &marks, double rate)
2567 index_markers = &marks;
2569 int64_t sz = marks.size();
2570 int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
2571 int nb_ent = st->nb_index_entries;
2572 // some formats already have an index
2574 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
2575 int64_t tstmp = ep->timestamp;
2576 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
2577 double secs = ffmpeg->to_secs(tstmp, st->time_base);
2578 int64_t no = secs * rate;
2579 while( in < sz && marks[in].no <= no ) ++in;
2581 int64_t len = sz - in;
2582 int64_t count = max_entries - nb_ent;
2583 if( count > len ) count = len;
2584 for( int i=0; i<count; ++i ) {
2585 int k = in + i * len / count;
2586 int64_t no = marks[k].no, pos = marks[k].pos;
2587 double secs = (double)no / rate;
2588 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
2589 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
2590 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);