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_YUV420P: return AV_PIX_FMT_YUV420P;
835 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
836 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
837 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
838 case BC_RGB565: return AV_PIX_FMT_RGB565;
839 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
840 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
844 return AV_PIX_FMT_NB;
847 int FFVideoConvert::pix_fmt_to_color_model(AVPixelFormat pix_fmt)
850 case AV_PIX_FMT_YUYV422: return BC_YUV422;
851 case AV_PIX_FMT_RGB24: return BC_RGB888;
852 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
853 case AV_PIX_FMT_BGR0: return BC_BGR8888;
854 case AV_PIX_FMT_BGR24: return BC_BGR888;
855 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
856 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
857 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
858 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
859 case AV_PIX_FMT_RGB565: return BC_RGB565;
860 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
861 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
868 int FFVideoConvert::convert_picture_vframe(VFrame *frame,
869 AVFrame *ip, AVPixelFormat ifmt, int iw, int ih)
871 // try bc_xfer methods
872 int imodel = pix_fmt_to_color_model(ifmt);
874 long y_ofs = 0, u_ofs = 0, v_ofs = 0;
875 uint8_t *data = ip->data[0];
876 if( BC_CModels::is_yuv(imodel) ) {
877 u_ofs = ip->data[1] - data;
878 v_ofs = ip->data[2] - data;
880 VFrame iframe(data, -1, y_ofs, u_ofs, v_ofs, iw, ih, imodel, ip->linesize[0]);
881 frame->transfer_from(&iframe);
886 int cmodel = frame->get_color_model();
887 AVPixelFormat ofmt = color_model_to_pix_fmt(cmodel);
888 if( ofmt == AV_PIX_FMT_NB ) return -1;
889 int size = av_image_fill_arrays(opic.data, opic.linesize,
890 frame->get_data(), ofmt, frame->get_w(), frame->get_h(), 1);
891 if( size < 0 ) return -1;
893 // transfer line sizes must match also
894 int planar = BC_CModels::is_planar(cmodel);
895 int packed_width = !planar ? frame->get_bytes_per_line() :
896 BC_CModels::calculate_pixelsize(cmodel) * frame->get_w();
897 if( packed_width != opic.linesize[0] ) return -1;
900 // override av_image_fill_arrays() for planar types
901 opic.data[0] = frame->get_y();
902 opic.data[1] = frame->get_u();
903 opic.data[2] = frame->get_v();
906 convert_ctx = sws_getCachedContext(convert_ctx, iw, ih, ifmt,
907 frame->get_w(), frame->get_h(), ofmt, SWS_BICUBIC, NULL, NULL, NULL);
909 fprintf(stderr, "FFVideoConvert::convert_picture_frame:"
910 " sws_getCachedContext() failed\n");
913 int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ih,
914 opic.data, opic.linesize);
916 ff_err(ret, "FFVideoConvert::convert_picture_frame: sws_scale() failed\n");
922 int FFVideoConvert::convert_cmodel(VFrame *frame,
923 AVFrame *ip, AVPixelFormat ifmt, int iw, int ih)
925 // try direct transfer
926 if( !convert_picture_vframe(frame, ip, ifmt, iw, ih) ) return 1;
927 // use indirect transfer
928 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
930 for( int i = 0; i <desc->nb_components; ++i ) {
931 int bits = desc->comp[i].depth;
932 if( bits > max_bits ) max_bits = bits;
934 // from libavcodec/pixdesc.c
935 #define pixdesc_has_alpha(pixdesc) ((pixdesc)->nb_components == 2 || \
936 (pixdesc)->nb_components == 4 || (pixdesc)->flags & AV_PIX_FMT_FLAG_PAL)
937 int icolor_model = pixdesc_has_alpha(desc) ?
938 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
939 (max_bits > 8 ? BC_RGB161616 : BC_RGB888) ;
940 VFrame vframe(iw, ih, icolor_model);
941 if( convert_picture_vframe(&vframe, ip, ifmt, iw, ih) ) return -1;
942 frame->transfer_from(&vframe);
946 int FFVideoConvert::transfer_cmodel(VFrame *frame,
947 AVFrame *ifp, AVPixelFormat ifmt, int iw, int ih)
949 int ret = convert_cmodel(frame, ifp, ifmt, iw, ih);
951 const AVDictionary *src = av_frame_get_metadata(ifp);
952 AVDictionaryEntry *t = NULL;
953 BC_Hash *hp = frame->get_params();
955 while( (t=av_dict_get(src, "", t, AV_DICT_IGNORE_SUFFIX)) )
956 hp->update(t->key, t->value);
961 int FFVideoConvert::convert_vframe_picture(VFrame *frame,
962 AVFrame *op, AVPixelFormat ofmt, int ow, int oh)
965 int cmodel = frame->get_color_model();
966 AVPixelFormat ifmt = color_model_to_pix_fmt(cmodel);
967 if( ifmt == AV_PIX_FMT_NB ) return -1;
968 int size = av_image_fill_arrays(opic.data, opic.linesize,
969 frame->get_data(), ifmt, frame->get_w(), frame->get_h(), 1);
970 if( size < 0 ) return -1;
972 // transfer line sizes must match also
973 int planar = BC_CModels::is_planar(cmodel);
974 int packed_width = !planar ? frame->get_bytes_per_line() :
975 BC_CModels::calculate_pixelsize(cmodel) * frame->get_w();
976 if( packed_width != opic.linesize[0] ) return -1;
979 // override av_image_fill_arrays() for planar types
980 opic.data[0] = frame->get_y();
981 opic.data[1] = frame->get_u();
982 opic.data[2] = frame->get_v();
985 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(), ifmt,
986 ow, oh, ofmt, SWS_BICUBIC, NULL, NULL, NULL);
988 fprintf(stderr, "FFVideoConvert::convert_frame_picture:"
989 " sws_getCachedContext() failed\n");
992 int ret = sws_scale(convert_ctx, opic.data, opic.linesize, 0, frame->get_h(),
993 op->data, op->linesize);
995 ff_err(ret, "FFVideoConvert::convert_frame_picture: sws_scale() failed\n");
1001 int FFVideoConvert::convert_pixfmt(VFrame *frame,
1002 AVFrame *op, AVPixelFormat ofmt, int ow, int oh)
1004 // try direct transfer
1005 if( !convert_vframe_picture(frame, op, ofmt, ow, oh) ) return 1;
1006 // use indirect transfer
1007 int colormodel = frame->get_color_model();
1008 int bits = BC_CModels::calculate_pixelsize(colormodel) * 8;
1009 bits /= BC_CModels::components(colormodel);
1010 int icolor_model = BC_CModels::has_alpha(colormodel) ?
1011 (bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1012 (bits > 8 ? BC_RGB161616: BC_RGB888) ;
1013 VFrame vframe(frame->get_w(), frame->get_h(), icolor_model);
1014 vframe.transfer_from(frame);
1015 if( !convert_vframe_picture(&vframe, op, ofmt, ow, oh) ) return 1;
1019 int FFVideoConvert::transfer_pixfmt(VFrame *frame,
1020 AVFrame *ofp, AVPixelFormat ofmt, int ow, int oh)
1022 int ret = convert_pixfmt(frame, ofp, ofmt, ow, oh);
1024 BC_Hash *hp = frame->get_params();
1025 AVDictionary **dict = avpriv_frame_get_metadatap(ofp);
1026 //av_dict_free(dict);
1027 for( int i=0; i<hp->size(); ++i ) {
1028 char *key = hp->get_key(i), *val = hp->get_value(i);
1029 av_dict_set(dict, key, val, 0);
1035 void FFVideoStream::load_markers()
1037 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1038 if( idx >= index_state->video_markers.size() ) return;
1039 FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
1043 FFMPEG::FFMPEG(FileBase *file_base)
1046 this->file_base = file_base;
1047 memset(file_format,0,sizeof(file_format));
1048 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
1049 flow_lock = new Condition(1,"FFStream::flow_lock",0);
1052 decoding = encoding = 0;
1053 has_audio = has_video = 0;
1056 opt_video_filter = 0;
1057 opt_audio_filter = 0;
1058 char option_path[BCTEXTLEN];
1059 set_option_path(option_path, "%s", "ffmpeg.opts");
1060 read_options(option_path, opts);
1065 ff_lock("FFMPEG::~FFMPEG()");
1067 ffaudio.remove_all_objects();
1068 ffvideo.remove_all_objects();
1069 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1073 av_dict_free(&opts);
1074 delete [] opt_video_filter;
1075 delete [] opt_audio_filter;
1078 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1080 const int *p = codec->supported_samplerates;
1081 if( !p ) return sample_rate;
1083 if( *p == sample_rate ) return *p;
1089 static inline AVRational std_frame_rate(int i)
1091 static const int m1 = 1001*12, m2 = 1000*12;
1092 static const int freqs[] = {
1093 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1094 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
1096 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1097 return (AVRational) { freq, 1001*12 };
1100 AVRational FFMPEG::check_frame_rate(AVCodec *codec, double frame_rate)
1102 const AVRational *p = codec->supported_framerates;
1103 AVRational rate, best_rate = (AVRational) { 0, 0 };
1104 double max_err = 1.; int i = 0;
1105 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1106 double framerate = (double) rate.num / rate.den;
1107 double err = fabs(frame_rate/framerate - 1.);
1108 if( err >= max_err ) continue;
1112 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1115 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1118 double display_aspect = asset->width / (double)asset->height;
1119 double sample_aspect = asset->aspect_ratio / display_aspect;
1120 int width = 1000000, height = width * sample_aspect + 0.5;
1122 MWindow::create_aspect_ratio(w, h, width, height);
1123 return (AVRational){(int)h, (int)w};
1126 return (AVRational){1, 1};
1130 AVRational FFMPEG::to_time_base(int sample_rate)
1132 return (AVRational){1, sample_rate};
1135 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
1138 strcat(path, "/ffmpeg/");
1139 path += strlen(path);
1142 vsprintf(path, fmt, ap);
1146 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
1151 set_option_path(path, "%s/%s", type, spec);
1154 int FFMPEG::get_format(char *format, const char *path, const char *spec)
1156 char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
1157 get_option_path(option_path, path, spec);
1158 FILE *fp = fopen(option_path,"r");
1161 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1163 line[sizeof(line)-1] = 0;
1164 ret = scan_option_line(line, format, codec);
1170 int FFMPEG::get_codec(char *codec, const char *path, const char *spec)
1172 char option_path[BCTEXTLEN], line[BCTEXTLEN], format[BCTEXTLEN];
1173 get_option_path(option_path, path, spec);
1174 FILE *fp = fopen(option_path,"r");
1177 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1180 line[sizeof(line)-1] = 0;
1181 ret = scan_option_line(line, format, codec);
1184 char *vp = codec, *ep = vp+BCTEXTLEN-1;
1185 while( vp < ep && *vp && *vp != '|' ) ++vp;
1186 if( *vp == '|' ) --vp;
1187 while( vp > codec && (*vp==' ' || *vp=='\t') ) *vp-- = 0;
1192 int FFMPEG::get_file_format()
1195 char audio_format[BCSTRLEN], video_format[BCSTRLEN];
1196 file_format[0] = audio_format[0] = video_format[0] = 0;
1197 Asset *asset = file_base->asset;
1198 if( !ret && asset->audio_data )
1199 ret = get_format(audio_format, "audio", asset->acodec);
1200 if( !ret && asset->video_data )
1201 ret = get_format(video_format, "video", asset->vcodec);
1202 if( !ret && !audio_format[0] && !video_format[0] )
1204 if( !ret && audio_format[0] && video_format[0] &&
1205 strcmp(audio_format, video_format) ) ret = -1;
1207 strcpy(file_format, audio_format[0] ? audio_format : video_format);
1211 int FFMPEG::scan_option_line(char *cp, char *tag, char *val)
1213 while( *cp == ' ' || *cp == '\t' ) ++cp;
1215 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' ) ++cp;
1217 if( !len || len > BCSTRLEN-1 ) return 1;
1218 while( bp < cp ) *tag++ = *bp++;
1220 while( *cp == ' ' || *cp == '\t' ) ++cp;
1221 if( *cp == '=' ) ++cp;
1222 while( *cp == ' ' || *cp == '\t' ) ++cp;
1224 while( *cp && *cp != '\n' ) ++cp;
1226 if( len > BCTEXTLEN-1 ) return 1;
1227 while( bp < cp ) *val++ = *bp++;
1232 int FFMPEG::load_defaults(const char *path, const char *type,
1233 char *codec, char *codec_options, int len)
1235 char default_file[BCTEXTLEN];
1236 FFMPEG::set_option_path(default_file, "%s/%s.dfl", path, type);
1237 FILE *fp = fopen(default_file,"r");
1239 fgets(codec, BCSTRLEN, fp);
1241 while( *cp && *cp!='\n' ) ++cp;
1243 while( len > 0 && fgets(codec_options, len, fp) ) {
1244 int n = strlen(codec_options);
1245 codec_options += n; len -= n;
1248 FFMPEG::set_option_path(default_file, "%s/%s", path, codec);
1249 return FFMPEG::load_options(default_file, codec_options, len);
1252 void FFMPEG::set_asset_format(Asset *asset, const char *text)
1254 if( asset->format != FILE_FFMPEG ) return;
1255 strcpy(asset->fformat, text);
1256 if( !asset->ff_audio_options[0] ) {
1257 asset->audio_data = !load_defaults("audio", text, asset->acodec,
1258 asset->ff_audio_options, sizeof(asset->ff_audio_options));
1260 if( !asset->ff_video_options[0] ) {
1261 asset->video_data = !load_defaults("video", text, asset->vcodec,
1262 asset->ff_video_options, sizeof(asset->ff_video_options));
1266 int FFMPEG::get_encoder(const char *options,
1267 char *format, char *codec, char *bsfilter, char *bsargs)
1269 FILE *fp = fopen(options,"r");
1271 eprintf("FFMPEG::get_encoder: options open failed %s\n",options);
1274 if( get_encoder(fp, format, codec, bsfilter, bsargs) )
1275 eprintf(_("FFMPEG::get_encoder:"
1276 " err: format/codec not found %s\n"), options);
1281 int FFMPEG::get_encoder(FILE *fp,
1282 char *format, char *codec, char *bsfilter, char *bsargs)
1284 format[0] = codec[0] = bsfilter[0] = bsargs[0] = 0;
1285 char line[BCTEXTLEN];
1286 if( !fgets(line, sizeof(line), fp) ) return 1;
1287 line[sizeof(line)-1] = 0;
1288 if( scan_option_line(line, format, codec) ) return 1;
1290 while( *cp && *cp != '|' ) ++cp;
1291 if( !*cp ) return 0;
1292 if( scan_option_line(cp+1, bsfilter, bsargs) ) return 1;
1293 do { *cp-- = 0; } while( cp>=codec && (*cp==' ' || *cp == '\t' ) );
1297 int FFMPEG::read_options(const char *options, AVDictionary *&opts)
1299 FILE *fp = fopen(options,"r");
1301 int ret = read_options(fp, options, opts);
1306 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
1308 FILE *fp = fmemopen((void *)options,strlen(options),"r");
1310 int ret = read_options(fp, options, opts);
1312 AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
1313 if( tag ) st->id = strtol(tag->value,0,0);
1317 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
1319 int ret = 0, no = 0;
1320 char line[BCTEXTLEN];
1321 while( !ret && fgets(line, sizeof(line), fp) ) {
1322 line[sizeof(line)-1] = 0;
1324 if( line[0] == '#' ) continue;
1325 if( line[0] == '\n' ) continue;
1326 char key[BCSTRLEN], val[BCTEXTLEN];
1327 if( scan_option_line(line, key, val) ) {
1328 eprintf(_("FFMPEG::read_options:"
1329 " err reading %s: line %d\n"), options, no);
1333 if( !strcmp(key, "duration") )
1334 opt_duration = strtod(val, 0);
1335 else if( !strcmp(key, "video_filter") )
1336 opt_video_filter = cstrdup(val);
1337 else if( !strcmp(key, "audio_filter") )
1338 opt_audio_filter = cstrdup(val);
1339 else if( !strcmp(key, "loglevel") )
1342 av_dict_set(&opts, key, val, 0);
1348 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
1350 char option_path[BCTEXTLEN];
1351 set_option_path(option_path, "%s", options);
1352 return read_options(option_path, opts);
1355 int FFMPEG::load_options(const char *path, char *bfr, int len)
1358 FILE *fp = fopen(path, "r");
1360 fgets(bfr, len, fp); // skip hdr
1361 len = fread(bfr, 1, len-1, fp);
1362 if( len < 0 ) len = 0;
1368 void FFMPEG::set_loglevel(const char *ap)
1370 if( !ap || !*ap ) return;
1375 { "quiet" , AV_LOG_QUIET },
1376 { "panic" , AV_LOG_PANIC },
1377 { "fatal" , AV_LOG_FATAL },
1378 { "error" , AV_LOG_ERROR },
1379 { "warning", AV_LOG_WARNING },
1380 { "info" , AV_LOG_INFO },
1381 { "verbose", AV_LOG_VERBOSE },
1382 { "debug" , AV_LOG_DEBUG },
1384 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
1385 if( !strcmp(log_levels[i].name, ap) ) {
1386 av_log_set_level(log_levels[i].level);
1390 av_log_set_level(atoi(ap));
1393 double FFMPEG::to_secs(int64_t time, AVRational time_base)
1395 double base_time = time == AV_NOPTS_VALUE ? 0 :
1396 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
1397 return base_time / AV_TIME_BASE;
1400 int FFMPEG::info(char *text, int len)
1402 if( len <= 0 ) return 0;
1404 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
1406 if( ffvideo.size() > 0 )
1407 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
1408 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
1409 FFVideoStream *vid = ffvideo[vidx];
1410 AVStream *st = vid->st;
1411 AVCodecContext *avctx = st->codec;
1412 report(_("vid%d (%d), id 0x%06x:\n"), vid->idx, vid->fidx, avctx->codec_id);
1413 const AVCodecDescriptor *desc = avcodec_descriptor_get(avctx->codec_id);
1414 report(" video%d %s", vidx+1, desc ? desc->name : " (unkn)");
1415 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
1416 const char *pfn = av_get_pix_fmt_name(avctx->pix_fmt);
1417 report(" pix %s\n", pfn ? pfn : "(unkn)");
1418 double secs = to_secs(st->duration, st->time_base);
1419 int64_t length = secs * vid->frame_rate + 0.5;
1420 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
1421 int64_t nudge = ofs * vid->frame_rate;
1422 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1423 report(" %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
1424 int hrs = secs/3600; secs -= hrs*3600;
1425 int mins = secs/60; secs -= mins*60;
1426 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1428 if( ffaudio.size() > 0 )
1429 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
1430 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
1431 FFAudioStream *aud = ffaudio[aidx];
1432 AVStream *st = aud->st;
1433 AVCodecContext *avctx = st->codec;
1434 report(_("aud%d (%d), id 0x%06x:\n"), aud->idx, aud->fidx, avctx->codec_id);
1435 const AVCodecDescriptor *desc = avcodec_descriptor_get(avctx->codec_id);
1436 int nch = aud->channels, ch0 = aud->channel0+1;
1437 report(" audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
1438 const char *fmt = av_get_sample_fmt_name(avctx->sample_fmt);
1439 report(" %s %d", fmt, aud->sample_rate);
1440 int sample_bits = av_get_bits_per_sample(avctx->codec_id);
1441 report(" %dbits\n", sample_bits);
1442 double secs = to_secs(st->duration, st->time_base);
1443 int64_t length = secs * aud->sample_rate + 0.5;
1444 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
1445 int64_t nudge = ofs * aud->sample_rate;
1446 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1447 report(" %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
1448 int hrs = secs/3600; secs -= hrs*3600;
1449 int mins = secs/60; secs -= mins*60;
1450 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1452 if( fmt_ctx->nb_programs > 0 )
1453 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
1454 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
1455 report("program %d", i+1);
1456 AVProgram *pgrm = fmt_ctx->programs[i];
1457 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1458 int idx = pgrm->stream_index[j];
1459 int vidx = ffvideo.size();
1460 while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
1462 report(", vid%d", vidx);
1465 int aidx = ffaudio.size();
1466 while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
1468 report(", aud%d", aidx);
1471 report(", (%d)", pgrm->stream_index[j]);
1476 AVDictionaryEntry *tag = 0;
1477 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
1478 report("%s=%s\n", tag->key, tag->value);
1487 int FFMPEG::init_decoder(const char *filename)
1489 ff_lock("FFMPEG::init_decoder");
1491 char file_opts[BCTEXTLEN];
1492 char *bp = strrchr(strcpy(file_opts, filename), '/');
1493 char *sp = strrchr(!bp ? file_opts : bp, '.');
1496 strcpy(sp, ".opts");
1497 fp = fopen(file_opts, "r");
1500 read_options(fp, file_opts, opts);
1504 load_options("decode.opts", opts);
1505 AVDictionary *fopts = 0;
1506 av_dict_copy(&fopts, opts, 0);
1507 int ret = avformat_open_input(&fmt_ctx, filename, NULL, &fopts);
1508 av_dict_free(&fopts);
1510 ret = avformat_find_stream_info(fmt_ctx, NULL);
1515 return !ret ? 0 : 1;
1518 int FFMPEG::open_decoder()
1521 if( stat(fmt_ctx->filename, &st) < 0 ) {
1522 eprintf("FFMPEG::open_decoder: can't stat file: %s\n",
1527 int64_t file_bits = 8 * st.st_size;
1528 if( !fmt_ctx->bit_rate && opt_duration > 0 )
1529 fmt_ctx->bit_rate = file_bits / opt_duration;
1532 if( fmt_ctx->bit_rate > 0 ) {
1533 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1534 AVStream *st = fmt_ctx->streams[i];
1535 if( st->duration != AV_NOPTS_VALUE ) continue;
1536 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
1537 st->duration = av_rescale(file_bits, st->time_base.den,
1538 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
1543 printf("FFMPEG::open_decoder: some stream times estimated\n");
1545 ff_lock("FFMPEG::open_decoder");
1547 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1548 AVStream *st = fmt_ctx->streams[i];
1549 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
1550 AVCodecContext *avctx = st->codec;
1551 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avctx->codec_id);
1552 if( !codec_desc ) continue;
1553 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1554 if( avctx->width < 1 ) continue;
1555 if( avctx->height < 1 ) continue;
1556 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
1557 if( framerate.num < 1 ) continue;
1559 int vidx = ffvideo.size();
1560 FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
1561 vstrm_index.append(ffidx(vidx, 0));
1562 ffvideo.append(vid);
1563 vid->width = avctx->width;
1564 vid->height = avctx->height;
1565 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
1566 double secs = to_secs(st->duration, st->time_base);
1567 vid->length = secs * vid->frame_rate;
1568 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
1569 vid->nudge = st->start_time;
1571 if( opt_video_filter )
1572 vid->create_filter(opt_video_filter, avctx,avctx);
1574 else if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1575 if( avctx->channels < 1 ) continue;
1576 if( avctx->sample_rate < 1 ) continue;
1578 int aidx = ffaudio.size();
1579 FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
1580 ffaudio.append(aud);
1581 aud->channel0 = astrm_index.size();
1582 aud->channels = avctx->channels;
1583 for( int ch=0; ch<aud->channels; ++ch )
1584 astrm_index.append(ffidx(aidx, ch));
1585 aud->sample_rate = avctx->sample_rate;
1586 double secs = to_secs(st->duration, st->time_base);
1587 aud->length = secs * aud->sample_rate;
1588 if( avctx->sample_fmt != AV_SAMPLE_FMT_FLT ) {
1589 uint64_t layout = av_get_default_channel_layout(avctx->channels);
1590 if( !layout ) layout = ((uint64_t)1<<aud->channels) - 1;
1591 aud->resample_context = swr_alloc_set_opts(NULL,
1592 layout, AV_SAMPLE_FMT_FLT, avctx->sample_rate,
1593 layout, avctx->sample_fmt, avctx->sample_rate,
1595 swr_init(aud->resample_context);
1597 aud->nudge = st->start_time;
1599 if( opt_audio_filter )
1600 aud->create_filter(opt_audio_filter, avctx,avctx);
1604 printf("FFMPEG::open_decoder: some stream have bad times\n");
1610 int FFMPEG::init_encoder(const char *filename)
1612 int fd = ::open(filename,O_WRONLY);
1613 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
1615 eprintf("FFMPEG::init_encoder: bad file path: %s\n", filename);
1619 int ret = get_file_format();
1621 eprintf("FFMPEG::init_encoder: bad file format: %s\n", filename);
1625 eprintf("FFMPEG::init_encoder: mismatch audio/video file format: %s\n", filename);
1628 ff_lock("FFMPEG::init_encoder");
1630 avformat_alloc_output_context2(&fmt_ctx, 0, file_format, filename);
1632 eprintf("FFMPEG::init_encoder: failed: %s\n", filename);
1637 load_options("encode.opts", opts);
1643 int FFMPEG::open_encoder(const char *type, const char *spec)
1646 Asset *asset = file_base->asset;
1647 char *filename = asset->path;
1648 AVDictionary *sopts = 0;
1649 av_dict_copy(&sopts, opts, 0);
1650 char option_path[BCTEXTLEN];
1651 set_option_path(option_path, "%s/%s.opts", type, type);
1652 read_options(option_path, sopts);
1653 get_option_path(option_path, type, spec);
1654 char format_name[BCSTRLEN], codec_name[BCTEXTLEN];
1655 char bsfilter[BCSTRLEN], bsargs[BCTEXTLEN];
1656 if( get_encoder(option_path, format_name, codec_name, bsfilter, bsargs) ) {
1657 eprintf("FFMPEG::open_encoder: get_encoder failed %s:%s\n",
1658 option_path, filename);
1662 if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
1663 else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
1664 else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
1667 ff_lock("FFMPEG::open_encoder");
1671 const AVCodecDescriptor *codec_desc = 0;
1672 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
1674 eprintf("FFMPEG::open_encoder: cant find codec %s:%s\n",
1675 codec_name, filename);
1679 codec_desc = avcodec_descriptor_get(codec->id);
1681 eprintf("FFMPEG::open_encoder: unknown codec %s:%s\n",
1682 codec_name, filename);
1687 st = avformat_new_stream(fmt_ctx, 0);
1689 eprintf("FFMPEG::open_encoder: cant create stream %s:%s\n",
1690 codec_name, filename);
1695 AVCodecContext *ctx = st->codec;
1696 switch( codec_desc->type ) {
1697 case AVMEDIA_TYPE_AUDIO: {
1699 eprintf("FFMPEG::open_encoder: duplicate audio %s:%s\n",
1700 codec_name, filename);
1705 if( scan_options(asset->ff_audio_options, sopts, st) ) {
1706 eprintf("FFMPEG::open_encoder: bad audio options %s:%s\n",
1707 codec_name, filename);
1711 if( asset->ff_audio_bitrate > 0 ) {
1712 ctx->bit_rate = asset->ff_audio_bitrate;
1714 sprintf(arg, "%d", asset->ff_audio_bitrate);
1715 av_dict_set(&sopts, "b", arg, 0);
1717 int aidx = ffaudio.size();
1718 int fidx = aidx + ffvideo.size();
1719 FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
1720 ffaudio.append(aud); fst = aud;
1721 aud->sample_rate = asset->sample_rate;
1722 ctx->channels = aud->channels = asset->channels;
1723 for( int ch=0; ch<aud->channels; ++ch )
1724 astrm_index.append(ffidx(aidx, ch));
1725 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
1726 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
1727 if( !ctx->sample_rate ) {
1728 eprintf("FFMPEG::open_encoder:"
1729 " check_sample_rate failed %s\n", filename);
1733 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
1734 ctx->sample_fmt = codec->sample_fmts[0];
1735 uint64_t layout = av_get_default_channel_layout(ctx->channels);
1736 aud->resample_context = swr_alloc_set_opts(NULL,
1737 layout, ctx->sample_fmt, aud->sample_rate,
1738 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
1740 swr_init(aud->resample_context);
1743 case AVMEDIA_TYPE_VIDEO: {
1745 eprintf("FFMPEG::open_encoder: duplicate video %s:%s\n",
1746 codec_name, filename);
1751 if( scan_options(asset->ff_video_options, sopts, st) ) {
1752 eprintf("FFMPEG::open_encoder: bad video options %s:%s\n",
1753 codec_name, filename);
1757 if( asset->ff_video_bitrate > 0 ) {
1758 ctx->bit_rate = asset->ff_video_bitrate;
1760 sprintf(arg, "%d", asset->ff_video_bitrate);
1761 av_dict_set(&sopts, "b", arg, 0);
1763 else if( asset->ff_video_quality > 0 ) {
1764 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
1765 ctx->qmin = ctx->qmax = asset->ff_video_quality;
1766 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
1767 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
1768 ctx->flags |= CODEC_FLAG_QSCALE;
1770 av_dict_set(&sopts, "flags", "+qscale", 0);
1771 sprintf(arg, "%d", asset->ff_video_quality);
1772 av_dict_set(&sopts, "qscale", arg, 0);
1773 sprintf(arg, "%d", ctx->global_quality);
1774 av_dict_set(&sopts, "global_quality", arg, 0);
1776 int vidx = ffvideo.size();
1777 int fidx = vidx + ffaudio.size();
1778 FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
1779 vstrm_index.append(ffidx(vidx, 0));
1780 ffvideo.append(vid); fst = vid;
1781 vid->width = asset->width;
1782 ctx->width = (vid->width+3) & ~3;
1783 vid->height = asset->height;
1784 ctx->height = (vid->height+3) & ~3;
1785 vid->frame_rate = asset->frame_rate;
1786 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
1787 ctx->pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
1788 AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
1789 if( !frame_rate.num || !frame_rate.den ) {
1790 eprintf("FFMPEG::open_encoder:"
1791 " check_frame_rate failed %s\n", filename);
1795 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
1796 st->time_base = ctx->time_base;
1800 eprintf("FFMPEG::open_encoder: not audio/video, %s:%s\n",
1801 codec_name, filename);
1806 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
1807 st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
1809 ret = avcodec_open2(st->codec, codec, &sopts);
1811 ff_err(ret,"FFMPEG::open_encoder");
1812 eprintf("FFMPEG::open_encoder: open failed %s:%s\n",
1813 codec_name, filename);
1820 if( fst && bsfilter[0] )
1821 fst->add_bsfilter(bsfilter, !bsargs[0] ? 0 : bsargs);
1827 av_dict_free(&sopts);
1831 int FFMPEG::close_encoder()
1834 if( encoding > 0 ) {
1835 av_write_trailer(fmt_ctx);
1836 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
1837 avio_closep(&fmt_ctx->pb);
1843 int FFMPEG::decode_activate()
1845 if( decoding < 0 ) {
1847 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
1848 ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
1849 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
1850 ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
1851 // set nudges for each program stream set
1852 int npgrms = fmt_ctx->nb_programs;
1853 for( int i=0; i<npgrms; ++i ) {
1854 AVProgram *pgrm = fmt_ctx->programs[i];
1855 // first start time video stream
1856 int64_t vstart_time = -1, astart_time = -1;
1857 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1858 int fidx = pgrm->stream_index[j];
1859 AVStream *st = fmt_ctx->streams[fidx];
1860 AVCodecContext *avctx = st->codec;
1861 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1862 if( st->start_time == AV_NOPTS_VALUE ) continue;
1863 if( vstart_time > st->start_time ) continue;
1864 vstart_time = st->start_time;
1867 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1868 if( st->start_time == AV_NOPTS_VALUE ) continue;
1869 if( astart_time > st->start_time ) continue;
1870 astart_time = st->start_time;
1874 // match program streams to max start_time
1875 int64_t nudge = vstart_time > astart_time ? vstart_time : astart_time;
1876 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1877 int fidx = pgrm->stream_index[j];
1878 AVStream *st = fmt_ctx->streams[fidx];
1879 AVCodecContext *avctx = st->codec;
1880 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1881 for( int k=0; k<ffvideo.size(); ++k ) {
1882 if( ffvideo[k]->fidx != fidx ) continue;
1883 ffvideo[k]->nudge = nudge;
1887 if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1888 for( int k=0; k<ffaudio.size(); ++k ) {
1889 if( ffaudio[k]->fidx != fidx ) continue;
1890 ffaudio[k]->nudge = nudge;
1896 // set nudges for any streams not yet set
1897 int64_t vstart_time = 0, astart_time = 0;
1898 int nstreams = fmt_ctx->nb_streams;
1899 for( int i=0; i<nstreams; ++i ) {
1900 AVStream *st = fmt_ctx->streams[i];
1901 AVCodecContext *avctx = st->codec;
1902 switch( avctx->codec_type ) {
1903 case AVMEDIA_TYPE_VIDEO: {
1904 if( st->start_time == AV_NOPTS_VALUE ) continue;
1905 int vidx = ffvideo.size();
1906 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
1907 if( vidx >= 0 && ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
1908 if( vstart_time >= st->start_time ) continue;
1909 vstart_time = st->start_time;
1911 case AVMEDIA_TYPE_AUDIO: {
1912 if( st->start_time == AV_NOPTS_VALUE ) continue;
1913 int aidx = ffaudio.size();
1914 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
1915 if( aidx >= 0 && ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
1916 if( astart_time >= st->start_time ) continue;
1917 astart_time = st->start_time;
1922 int64_t nudge = vstart_time > astart_time ? vstart_time : astart_time;
1923 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
1924 if( ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
1925 ffvideo[vidx]->nudge = nudge;
1927 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
1928 if( ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
1929 ffaudio[aidx]->nudge = nudge;
1936 int FFMPEG::encode_activate()
1939 if( encoding < 0 ) {
1941 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
1942 (ret=avio_open(&fmt_ctx->pb, fmt_ctx->filename, AVIO_FLAG_WRITE)) < 0 ) {
1943 ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
1948 AVDictionary *fopts = 0;
1949 char option_path[BCTEXTLEN];
1950 set_option_path(option_path, "format/%s", file_format);
1951 read_options(option_path, fopts);
1952 ret = avformat_write_header(fmt_ctx, &fopts);
1953 av_dict_free(&fopts);
1955 ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
1965 int FFMPEG::audio_seek(int stream, int64_t pos)
1967 int aidx = astrm_index[stream].st_idx;
1968 FFAudioStream *aud = ffaudio[aidx];
1969 aud->audio_seek(pos);
1973 int FFMPEG::video_seek(int stream, int64_t pos)
1975 int vidx = vstrm_index[stream].st_idx;
1976 FFVideoStream *vid = ffvideo[vidx];
1977 vid->video_seek(pos);
1982 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
1984 if( !has_audio || chn >= astrm_index.size() ) return -1;
1985 int aidx = astrm_index[chn].st_idx;
1986 FFAudioStream *aud = ffaudio[aidx];
1987 if( aud->load(pos, len) < len ) return -1;
1988 int ch = astrm_index[chn].st_ch;
1989 int ret = aud->read(samples,len,ch);
1993 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
1995 if( !has_video || layer >= vstrm_index.size() ) return -1;
1996 int vidx = vstrm_index[layer].st_idx;
1997 FFVideoStream *vid = ffvideo[vidx];
1998 return vid->load(vframe, pos);
2002 int FFMPEG::encode(int stream, double **samples, int len)
2004 FFAudioStream *aud = ffaudio[stream];
2005 return aud->encode(samples, len);
2009 int FFMPEG::encode(int stream, VFrame *frame)
2011 FFVideoStream *vid = ffvideo[stream];
2012 return vid->encode(frame);
2015 void FFMPEG::start_muxer()
2023 void FFMPEG::stop_muxer()
2032 void FFMPEG::flow_off()
2035 flow_lock->lock("FFMPEG::flow_off");
2039 void FFMPEG::flow_on()
2043 flow_lock->unlock();
2046 void FFMPEG::flow_ctl()
2049 flow_lock->lock("FFMPEG::flow_ctl");
2050 flow_lock->unlock();
2054 int FFMPEG::mux_audio(FFrame *frm)
2057 FFStream *fst = frm->fst;
2058 AVCodecContext *ctx = fst->st->codec;
2059 AVFrame *frame = *frm;
2060 AVRational tick_rate = {1, ctx->sample_rate};
2061 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
2063 int ret = fst->encode_frame(pkt, frame, got_packet);
2064 if( ret >= 0 && got_packet )
2065 ret = fst->write_packet(pkt);
2067 ff_err(ret, "FFMPEG::mux_audio");
2068 return ret >= 0 ? 0 : 1;
2071 int FFMPEG::mux_video(FFrame *frm)
2074 FFStream *fst = frm->fst;
2075 AVFrame *frame = *frm;
2076 frame->pts = frm->position;
2078 int ret = fst->encode_frame(pkt, frame, got_packet);
2079 if( ret >= 0 && got_packet )
2080 ret = fst->write_packet(pkt);
2082 ff_err(ret, "FFMPEG::mux_video");
2083 return ret >= 0 ? 0 : 1;
2089 double atm = -1, vtm = -1;
2090 FFrame *afrm = 0, *vfrm = 0;
2092 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
2093 FFStream *fst = ffaudio[i];
2094 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
2095 FFrame *frm = fst->frms.first;
2096 if( !frm ) { if( !done ) return; continue; }
2097 double tm = to_secs(frm->position, fst->st->codec->time_base);
2098 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
2100 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
2101 FFStream *fst = ffvideo[i];
2102 if( fst->frm_count < 2 ) { 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( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
2108 if( !demand ) flow_off();
2109 if( !afrm && !vfrm ) break;
2110 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
2111 vfrm->position, vfrm->fst->st->codec->time_base,
2112 afrm->position, afrm->fst->st->codec->time_base);
2113 FFrame *frm = v <= 0 ? vfrm : afrm;
2114 if( frm == afrm ) mux_audio(frm);
2115 if( frm == vfrm ) mux_video(frm);
2124 mux_lock->lock("FFMPEG::run");
2128 for( int i=0; i<ffaudio.size(); ++i )
2129 ffaudio[i]->flush();
2130 for( int i=0; i<ffvideo.size(); ++i )
2131 ffvideo[i]->flush();
2135 int FFMPEG::ff_total_audio_channels()
2137 return astrm_index.size();
2140 int FFMPEG::ff_total_astreams()
2142 return ffaudio.size();
2145 int FFMPEG::ff_audio_channels(int stream)
2147 return ffaudio[stream]->channels;
2150 int FFMPEG::ff_sample_rate(int stream)
2152 return ffaudio[stream]->sample_rate;
2155 const char* FFMPEG::ff_audio_format(int stream)
2157 AVStream *st = ffaudio[stream]->st;
2158 AVCodecID id = st->codec->codec_id;
2159 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2160 return desc ? desc->name : "Unknown";
2163 int FFMPEG::ff_audio_pid(int stream)
2165 return ffaudio[stream]->st->id;
2168 int64_t FFMPEG::ff_audio_samples(int stream)
2170 return ffaudio[stream]->length;
2173 // find audio astream/channels with this program,
2174 // or all program audio channels (astream=-1)
2175 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
2179 int vidx = ffvideo[vstream]->fidx;
2180 // find first program with this video stream
2181 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
2182 AVProgram *pgrm = fmt_ctx->programs[i];
2183 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
2184 int st_idx = pgrm->stream_index[j];
2185 AVStream *st = fmt_ctx->streams[st_idx];
2186 if( st->codec->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
2187 if( st_idx == vidx ) pidx = i;
2190 if( pidx < 0 ) return -1;
2192 int64_t channels = 0;
2193 AVProgram *pgrm = fmt_ctx->programs[pidx];
2194 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2195 int aidx = pgrm->stream_index[j];
2196 AVStream *st = fmt_ctx->streams[aidx];
2197 if( st->codec->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
2198 if( astream > 0 ) { --astream; continue; }
2200 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
2201 if( ffaudio[i]->fidx == aidx ) astrm = i;
2203 if( ret < 0 ) ret = astrm;
2204 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
2205 channels |= mask << ffaudio[astrm]->channel0;
2207 if( !astream ) break;
2209 channel_mask = channels;
2214 int FFMPEG::ff_total_video_layers()
2216 return vstrm_index.size();
2219 int FFMPEG::ff_total_vstreams()
2221 return ffvideo.size();
2224 int FFMPEG::ff_video_width(int stream)
2226 return ffvideo[stream]->width;
2229 int FFMPEG::ff_video_height(int stream)
2231 return ffvideo[stream]->height;
2234 int FFMPEG::ff_set_video_width(int stream, int width)
2236 int w = ffvideo[stream]->width;
2237 ffvideo[stream]->width = width;
2241 int FFMPEG::ff_set_video_height(int stream, int height)
2243 int h = ffvideo[stream]->height;
2244 ffvideo[stream]->height = height;
2248 int FFMPEG::ff_coded_width(int stream)
2250 AVStream *st = ffvideo[stream]->st;
2251 return st->codec->coded_width;
2254 int FFMPEG::ff_coded_height(int stream)
2256 AVStream *st = ffvideo[stream]->st;
2257 return st->codec->coded_height;
2260 float FFMPEG::ff_aspect_ratio(int stream)
2262 return ffvideo[stream]->aspect_ratio;
2265 const char* FFMPEG::ff_video_format(int stream)
2267 AVStream *st = ffvideo[stream]->st;
2268 AVCodecID id = st->codec->codec_id;
2269 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2270 return desc ? desc->name : "Unknown";
2273 double FFMPEG::ff_frame_rate(int stream)
2275 return ffvideo[stream]->frame_rate;
2278 int64_t FFMPEG::ff_video_frames(int stream)
2280 return ffvideo[stream]->length;
2283 int FFMPEG::ff_video_pid(int stream)
2285 return ffvideo[stream]->st->id;
2289 int FFMPEG::ff_cpus()
2291 return file_base->file->cpus;
2294 int FFVideoStream::create_filter(const char *filter_spec,
2295 AVCodecContext *src_ctx, AVCodecContext *sink_ctx)
2297 avfilter_register_all();
2298 AVFilter *filter = avfilter_get_by_name(filter_spec);
2299 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_VIDEO ) {
2300 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
2303 filter_graph = avfilter_graph_alloc();
2304 AVFilter *buffersrc = avfilter_get_by_name("buffer");
2305 AVFilter *buffersink = avfilter_get_by_name("buffersink");
2307 int ret = 0; char args[BCTEXTLEN];
2308 snprintf(args, sizeof(args),
2309 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
2310 src_ctx->width, src_ctx->height, src_ctx->pix_fmt,
2311 src_ctx->time_base.num, src_ctx->time_base.den,
2312 src_ctx->sample_aspect_ratio.num, src_ctx->sample_aspect_ratio.den);
2314 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2315 args, NULL, filter_graph);
2317 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2318 NULL, NULL, filter_graph);
2320 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
2321 (uint8_t*)&sink_ctx->pix_fmt, sizeof(sink_ctx->pix_fmt),
2322 AV_OPT_SEARCH_CHILDREN);
2324 ff_err(ret, "FFVideoStream::create_filter");
2326 ret = FFStream::create_filter(filter_spec);
2327 return ret >= 0 ? 0 : 1;
2330 int FFAudioStream::create_filter(const char *filter_spec,
2331 AVCodecContext *src_ctx, AVCodecContext *sink_ctx)
2333 avfilter_register_all();
2334 AVFilter *filter = avfilter_get_by_name(filter_spec);
2335 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_AUDIO ) {
2336 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
2339 filter_graph = avfilter_graph_alloc();
2340 AVFilter *buffersrc = avfilter_get_by_name("abuffer");
2341 AVFilter *buffersink = avfilter_get_by_name("abuffersink");
2342 int ret = 0; char args[BCTEXTLEN];
2343 snprintf(args, sizeof(args),
2344 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
2345 src_ctx->time_base.num, src_ctx->time_base.den, src_ctx->sample_rate,
2346 av_get_sample_fmt_name(src_ctx->sample_fmt), src_ctx->channel_layout);
2348 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2349 args, NULL, filter_graph);
2351 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2352 NULL, NULL, filter_graph);
2354 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
2355 (uint8_t*)&sink_ctx->sample_fmt, sizeof(sink_ctx->sample_fmt),
2356 AV_OPT_SEARCH_CHILDREN);
2358 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
2359 (uint8_t*)&sink_ctx->channel_layout,
2360 sizeof(sink_ctx->channel_layout), AV_OPT_SEARCH_CHILDREN);
2362 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
2363 (uint8_t*)&sink_ctx->sample_rate, sizeof(sink_ctx->sample_rate),
2364 AV_OPT_SEARCH_CHILDREN);
2366 ff_err(ret, "FFAudioStream::create_filter");
2368 ret = FFStream::create_filter(filter_spec);
2369 return ret >= 0 ? 0 : 1;
2372 int FFStream::create_filter(const char *filter_spec)
2374 /* Endpoints for the filter graph. */
2375 AVFilterInOut *outputs = avfilter_inout_alloc();
2376 outputs->name = av_strdup("in");
2377 outputs->filter_ctx = buffersrc_ctx;
2378 outputs->pad_idx = 0;
2381 AVFilterInOut *inputs = avfilter_inout_alloc();
2382 inputs->name = av_strdup("out");
2383 inputs->filter_ctx = buffersink_ctx;
2384 inputs->pad_idx = 0;
2387 int ret = !outputs->name || !inputs->name ? -1 : 0;
2389 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
2390 &inputs, &outputs, NULL);
2392 ret = avfilter_graph_config(filter_graph, NULL);
2395 ff_err(ret, "FFStream::create_filter");
2396 avfilter_inout_free(&inputs);
2397 avfilter_inout_free(&outputs);
2401 void FFStream::add_bsfilter(const char *bsf, const char *ap)
2403 bsfilter.append(new BSFilter(bsf,ap));
2406 int FFStream::bs_filter(AVPacket *pkt)
2408 if( !bsfilter.size() ) return 0;
2409 av_packet_split_side_data(pkt);
2412 for( int i=0; i<bsfilter.size(); ++i ) {
2413 AVPacket bspkt = *pkt;
2414 ret = av_bitstream_filter_filter(bsfilter[i]->bsfc,
2415 st->codec, bsfilter[i]->args, &bspkt.data, &bspkt.size,
2416 pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY);
2417 if( ret < 0 ) break;
2418 int size = bspkt.size;
2419 uint8_t *data = bspkt.data;
2420 if( !ret && bspkt.data != pkt->data ) {
2422 data = (uint8_t *)av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
2423 if( !data ) { ret = AVERROR(ENOMEM); break; }
2424 memcpy(data, bspkt.data, size);
2425 memset(data+size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2429 pkt->side_data = 0; pkt->side_data_elems = 0;
2430 av_packet_unref(pkt);
2431 ret = av_packet_from_data(&bspkt, data, size);
2432 if( ret < 0 ) break;
2437 ff_err(ret,"FFStream::bs_filter");
2441 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
2444 av_init_packet(&pkt);
2445 AVFrame *frame = av_frame_alloc();
2447 fprintf(stderr, "FFMPEG::scan: av_frame_alloc failed\n");
2451 index_state->add_video_markers(ffvideo.size());
2452 index_state->add_audio_markers(ffaudio.size());
2454 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2455 AVDictionary *copts = 0;
2456 av_dict_copy(&copts, opts, 0);
2457 AVStream *st = fmt_ctx->streams[i];
2458 AVCodecID codec_id = st->codec->codec_id;
2459 AVCodec *decoder = avcodec_find_decoder(codec_id);
2460 if( avcodec_open2(st->codec, decoder, &copts) < 0 )
2461 fprintf(stderr, "FFMPEG::scan: codec open failed\n");
2462 av_dict_free(&copts);
2465 for( int64_t count=0; !*canceled; ++count ) {
2466 av_packet_unref(&pkt);
2467 pkt.data = 0; pkt.size = 0;
2469 int ret = av_read_frame(fmt_ctx, &pkt);
2471 if( ret == AVERROR_EOF ) break;
2472 if( ++errs > 100 ) {
2473 ff_err(ret, "over 100 read_frame errs\n");
2478 if( !pkt.data ) continue;
2479 int i = pkt.stream_index;
2480 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
2481 AVStream *st = fmt_ctx->streams[i];
2482 AVCodecContext *avctx = st->codec;
2483 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
2485 switch( avctx->codec_type ) {
2486 case AVMEDIA_TYPE_VIDEO: {
2487 int vidx = ffvideo.size();
2488 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
2489 if( vidx < 0 ) break;
2490 FFVideoStream *vid = ffvideo[vidx];
2491 int64_t tstmp = pkt.dts;
2492 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.pts;
2493 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
2494 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
2495 double secs = to_secs(tstmp, st->time_base);
2496 int64_t frm = secs * vid->frame_rate + 0.5;
2497 if( frm < 0 ) frm = 0;
2498 index_state->put_video_mark(vidx, frm, pkt.pos);
2501 while( pkt.size > 0 ) {
2502 av_frame_unref(frame);
2504 int ret = vid->decode_frame(&pkt, frame, got_frame);
2505 if( ret <= 0 ) break;
2506 // if( got_frame ) {}
2512 case AVMEDIA_TYPE_AUDIO: {
2513 int aidx = ffaudio.size();
2514 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
2515 if( aidx < 0 ) break;
2516 FFAudioStream *aud = ffaudio[aidx];
2517 int64_t tstmp = pkt.pts;
2518 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
2519 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
2520 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
2521 double secs = to_secs(tstmp, st->time_base);
2522 int64_t sample = secs * aud->sample_rate + 0.5;
2523 if( sample < 0 ) sample = 0;
2524 index_state->put_audio_mark(aidx, sample, pkt.pos);
2526 while( pkt.size > 0 ) {
2527 int ch = aud->channel0, nch = aud->channels;
2528 int64_t pos = index_state->pos(ch);
2529 if( pos != aud->curr_pos ) {
2530 if( abs(pos-aud->curr_pos) > 1 )
2531 printf("audio%d pad %ld %ld (%ld)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
2532 index_state->pad_data(ch, nch, aud->curr_pos);
2534 av_frame_unref(frame);
2536 int ret = aud->decode_frame(&pkt, frame, got_frame);
2537 if( ret <= 0 ) break;
2538 if( got_frame && frame->channels == nch ) {
2540 int len = aud->get_samples(samples,
2541 &frame->extended_data[0], frame->nb_samples);
2542 for( int i=0; i<nch; ++i )
2543 index_state->put_data(ch+i,nch,samples+i,len);
2544 aud->curr_pos += len;
2553 av_frame_free(&frame);
2557 void FFStream::load_markers(IndexMarks &marks, double rate)
2559 index_markers = &marks;
2561 int64_t sz = marks.size();
2562 int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
2563 int nb_ent = st->nb_index_entries;
2564 // some formats already have an index
2566 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
2567 int64_t tstmp = ep->timestamp;
2568 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
2569 double secs = ffmpeg->to_secs(tstmp, st->time_base);
2570 int64_t no = secs * rate;
2571 while( in < sz && marks[in].no <= no ) ++in;
2573 int64_t len = sz - in;
2574 int64_t count = max_entries - nb_ent;
2575 if( count > len ) count = len;
2576 for( int i=0; i<count; ++i ) {
2577 int k = in + i * len / count;
2578 int64_t no = marks[k].no, pos = marks[k].pos;
2579 double secs = (double)no / rate;
2580 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
2581 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
2582 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);