9 // work arounds (centos)
12 #define INT64_MAX 9223372036854775807LL
16 #include "bccmodels.h"
17 #include "fileffmpeg.h"
24 #define VIDEO_INBUF_SIZE 0x10000
25 #define AUDIO_INBUF_SIZE 0x10000
26 #define VIDEO_REFILL_THRESH 0
27 #define AUDIO_REFILL_THRESH 0x1000
29 Mutex FFMPEG::fflock("FFMPEG::fflock");
31 static void ff_err(int ret, const char *msg)
33 char errmsg[BCSTRLEN]; av_strerror(ret, errmsg, sizeof(errmsg));
34 fprintf(stderr,"%s: %s\n",msg, errmsg);
50 pkt.data = 0; pkt.size = 0;
53 FFrame::FFrame(FFStream *fst)
56 frm = av_frame_alloc();
57 init = fst->init_frame(frm);
65 void FFrame::queue(int64_t pos)
71 void FFrame::dequeue()
76 FFAudioHistory::FFAudioHistory()
86 FFAudioHistory::~FFAudioHistory()
92 void FFAudioHistory::reserve(long sz, int nch)
94 long isz = inp - outp;
96 if( this->sz < sz || this->nch != nch ) {
101 memmove(bfr, outp, isz*sizeof(*bfr));
106 void FFAudioHistory::realloc(long sz, int nch)
108 if( this->nch != nch )
110 else if( this->sz >= sz )
115 float *np = new float[bsz];
116 inp = np + copy(np, used());
119 delete [] bfr; bfr = np;
122 long FFAudioHistory::used()
124 long len = inp>=outp ? inp-outp : inp-bfr + lmt-outp;
127 long FFAudioHistory::avail()
130 if( in1 >= lmt ) in1 = bfr;
131 long len = outp >= in1 ? outp-in1 : outp-bfr + lmt-in1;
134 void FFAudioHistory::reset() // clear bfr
139 void FFAudioHistory::iseek(int64_t ofs)
141 outp = inp - ofs*nch;
142 if( outp < bfr ) outp += bsz;
145 float *FFAudioHistory::get_outp(int ofs)
152 int64_t FFAudioHistory::get_inp(int ofs)
155 return (inp-bfr) / nch;
158 int FFAudioHistory::write(const float *fp, long len)
166 while( --k >= 0 ) *ip++ = *fp++;
167 if( ip >= lmt ) ip = bfr;
173 int FFAudioHistory::copy(float *fp, long len)
181 while( --k >= 0 ) *fp++ = *op++;
182 if( op >= lmt ) op = bfr;
188 int FFAudioHistory::zero(long len)
196 while( --k >= 0 ) *ip++ = 0;
197 if( ip >= lmt ) ip = bfr;
203 // does not advance outp
204 int FFAudioHistory::read(double *dp, long len, int ch)
208 if( len > sz ) len = sz;
210 float *op = outp + ch;
211 float *lmt1 = lmt + nch-1;
213 int k = (lmt1 - op) / nch;
216 while( --k >= 0 ) { *dp++ = *op; op += nch; }
217 if( op >= lmt ) op -= bsz;
222 // load linear buffer, no wrapping allowed, does not advance inp
223 int FFAudioHistory::write(const double *dp, long len, int ch)
226 if( !osz || !len ) return 0;
227 if( len > osz ) len = osz;
229 float *ip = inp + ch;
230 while( --n >= 0 ) { *ip = *dp++; ip += nch; }
235 FFStream::FFStream(FFMPEG *ffmpeg, AVStream *st, int idx)
237 this->ffmpeg = ffmpeg;
240 frm_lock = new Mutex("FFStream::frm_lock");
246 nudge = AV_NOPTS_VALUE;
248 reading = writing = 0;
254 FFStream::~FFStream()
256 if( reading > 0 || writing > 0 ) avcodec_close(st->codec);
257 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
258 while( frms.first ) frms.remove(frms.first);
259 if( filter_graph ) avfilter_graph_free(&filter_graph);
260 if( frame ) av_frame_free(&frame);
261 if( fframe ) av_frame_free(&fframe);
262 bsfilter.remove_all_objects();
266 void FFStream::ff_lock(const char *cp)
268 FFMPEG::fflock.lock(cp);
271 void FFStream::ff_unlock()
273 FFMPEG::fflock.unlock();
276 void FFStream::queue(FFrame *frm)
278 frm_lock->lock("FFStream::queue");
282 ffmpeg->mux_lock->unlock();
285 void FFStream::dequeue(FFrame *frm)
287 frm_lock->lock("FFStream::dequeue");
289 frms.remove_pointer(frm);
293 int FFStream::encode_activate()
296 writing = ffmpeg->encode_activate();
300 int FFStream::decode_activate()
302 if( reading < 0 && (reading=ffmpeg->decode_activate()) > 0 ) {
303 ff_lock("FFStream::decode_activate");
305 AVDictionary *copts = 0;
306 av_dict_copy(&copts, ffmpeg->opts, 0);
308 // this should be avformat_copy_context(), but no copy avail
309 ret = avformat_open_input(&fmt_ctx, ffmpeg->fmt_ctx->filename, NULL, &copts);
311 ret = avformat_find_stream_info(fmt_ctx, 0);
312 st = fmt_ctx->streams[idx];
315 AVCodecID codec_id = st->codec->codec_id;
316 AVCodec *decoder = avcodec_find_decoder(codec_id);
317 ret = avcodec_open2(st->codec, decoder, &copts);
321 fprintf(stderr, "FFStream::decode_activate: open decoder failed\n");
324 fprintf(stderr, "FFStream::decode_activate: can't clone input file\n");
325 av_dict_free(&copts);
331 int FFStream::read_packet()
333 av_packet_unref(ipkt);
334 int ret = av_read_frame(fmt_ctx, ipkt);
335 if( ret >= 0 ) return 1;
337 if( ret == AVERROR_EOF ) return 0;
338 fprintf(stderr, "FFStream::read_packet: av_read_frame failed\n");
343 int FFStream::decode(AVFrame *frame)
349 while( ret >= 0 && !flushed && --retries >= 0 && !got_frame ) {
354 if( !ret ) ipkt->stream_index = st->index;
356 if( ipkt->stream_index == st->index ) {
357 while( (ipkt->size > 0 || !ipkt->data) && !got_frame ) {
358 ret = decode_frame(frame, got_frame);
359 if( ret < 0 || !ipkt->data ) break;
372 fprintf(stderr, "FFStream::decode: Retry limit\n");
376 fprintf(stderr, "FFStream::decode: failed\n");
381 int FFStream::load_filter(AVFrame *frame)
383 int ret = av_buffersrc_add_frame_flags(buffersrc_ctx,
384 frame, AV_BUFFERSRC_FLAG_KEEP_REF);
386 av_frame_unref(frame);
387 fprintf(stderr, "FFStream::load_filter: av_buffersrc_add_frame_flags failed\n");
392 int FFStream::read_filter(AVFrame *frame)
394 int ret = av_buffersink_get_frame(buffersink_ctx, frame);
396 if( ret == AVERROR(EAGAIN) ) return 0;
397 if( ret == AVERROR_EOF ) { st_eof(1); return -1; }
398 fprintf(stderr, "FFStream::read_filter: av_buffersink_get_frame failed\n");
404 int FFStream::read_frame(AVFrame *frame)
406 if( !filter_graph || !buffersrc_ctx || !buffersink_ctx )
407 return decode(frame);
408 if( !fframe && !(fframe=av_frame_alloc()) ) {
409 fprintf(stderr, "FFStream::read_frame: av_frame_alloc failed\n");
413 while( !flushed && !(ret=read_filter(frame)) ) {
414 if( (ret=decode(fframe)) < 0 ) break;
415 if( ret > 0 && (ret=load_filter(fframe)) < 0 ) break;
420 FFAudioStream::FFAudioStream(FFMPEG *ffmpeg, AVStream *strm, int idx)
421 : FFStream(ffmpeg, strm, idx)
423 channel0 = channels = 0;
426 seek_pos = curr_pos = 0;
428 resample_context = 0;
434 FFAudioStream::~FFAudioStream()
436 if( resample_context ) swr_free(&resample_context);
440 int FFAudioStream::load_history(float *&bfr, int len)
442 if( resample_context ) {
443 if( len > aud_bfr_sz ) {
449 aud_bfr = new float[aud_bfr_sz*channels];
451 int ret = swr_convert(resample_context,
452 (uint8_t**)&aud_bfr, aud_bfr_sz,
453 (const uint8_t**)&bfr, len);
455 fprintf(stderr, "FFAudioStream::load_history: swr_convert failed\n");
461 append_history(bfr, len);
465 int FFAudioStream::decode_frame(AVFrame *frame, int &got_frame)
467 int ret = avcodec_decode_audio4(st->codec, frame, &got_frame, ipkt);
469 fprintf(stderr, "FFAudioStream::decode_frame: Could not read audio frame\n");
475 int FFAudioStream::encode_activate()
477 if( writing >= 0 ) return writing;
478 AVCodecContext *ctx = st->codec;
479 frame_sz = ctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE ?
480 10000 : ctx->frame_size;
481 return FFStream::encode_activate();
484 int FFAudioStream::nb_samples()
486 AVCodecContext *ctx = st->codec;
487 return ctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE ?
488 10000 : ctx->frame_size;
491 void FFAudioStream::alloc_history(int len)
493 history.realloc(len+1, channels);
496 void FFAudioStream::reserve_history(int len)
498 history.reserve(len+1, st->codec->channels);
501 void FFAudioStream::append_history(const float *fp, int len)
503 // biggest user bfr since seek + length this frame
504 int hsz = mbsz + len;
506 history.write(fp, len);
509 int64_t FFAudioStream::load_buffer(double ** const sp, int len)
511 reserve_history(len);
512 int nch = st->codec->channels;
513 for( int ch=0; ch<nch; ++ch )
514 history.write(sp[ch], len, ch);
515 return history.get_inp(len);
518 void FFAudioStream::zero_history(int len)
523 float* FFAudioStream::get_history(int len)
525 return history.get_outp(len);
528 int FFAudioStream::in_history(int64_t pos)
530 if( pos > curr_pos ) return 0;
531 int64_t len = curr_pos - seek_pos;
532 if( len > history.sz ) len = history.sz;
533 if( pos < curr_pos - len ) return 0;
538 int FFAudioStream::init_frame(AVFrame *frame)
540 AVCodecContext *ctx = st->codec;
541 frame->nb_samples = frame_sz;
542 frame->format = ctx->sample_fmt;
543 frame->channel_layout = ctx->channel_layout;
544 frame->sample_rate = ctx->sample_rate;
545 int ret = av_frame_get_buffer(frame, 0);
547 fprintf(stderr, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
551 int FFAudioStream::load(int64_t pos, int len)
553 if( audio_seek(pos) < 0 ) return -1;
554 if( mbsz < len ) mbsz = len;
556 int64_t end_pos = pos + len;
557 if( !frame && !(frame=av_frame_alloc()) ) {
558 fprintf(stderr, "FFAudioStream::load: av_frame_alloc failed\n");
561 for( int i=0; ret>=0 && !flushed && curr_pos<end_pos && i<1000; ++i ) {
562 ret = read_frame(frame);
564 load_history((float *&)frame->extended_data[0], frame->nb_samples);
565 curr_pos += frame->nb_samples;
568 if( flushed && end_pos > curr_pos ) {
569 zero_history(end_pos - curr_pos);
572 return curr_pos - pos;
575 int FFAudioStream::audio_seek(int64_t pos)
577 if( decode_activate() < 0 ) return -1;
578 if( in_history(pos) ) {
579 history.iseek(curr_pos - pos);
582 if( pos == curr_pos ) return 0;
583 double secs = (double)pos / sample_rate;
584 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
585 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
586 avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, tstmp, INT64_MAX, 0);
587 seek_pos = curr_pos = pos;
594 int FFAudioStream::encode(double **samples, int len)
596 if( encode_activate() <= 0 ) return -1;
599 int64_t count = load_buffer(samples, len);
602 while( ret >= 0 && count >= frame_sz ) {
603 frm = new FFrame(this);
604 if( (ret=frm->initted()) < 0 ) break;
605 AVFrame *frame = *frm;
606 float *bfrp = get_history(frame_sz);
607 ret = swr_convert(resample_context,
608 (uint8_t **)frame->extended_data, frame_sz,
609 (const uint8_t **)&bfrp, frame_sz);
611 fprintf(stderr, "FFAudioStream::encode: swr_convert failed\n");
614 frm->queue(curr_pos);
616 curr_pos += frame_sz;
621 return ret >= 0 ? 0 : 1;
624 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx)
625 : FFStream(ffmpeg, strm, idx)
630 seek_pos = curr_pos = 0;
635 FFVideoStream::~FFVideoStream()
637 if( convert_ctx ) sws_freeContext(convert_ctx);
640 int FFVideoStream::decode_frame(AVFrame *frame, int &got_frame)
642 int ret = avcodec_decode_video2(st->codec, frame, &got_frame, ipkt);
644 fprintf(stderr, "FFVideoStream::decode_frame: Could not read video frame\n");
652 int FFVideoStream::load(VFrame *vframe, int64_t pos)
654 if( video_seek(pos) < 0 ) return -1;
655 if( !frame && !(frame=av_frame_alloc()) ) {
656 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
660 for( int i=0; ret>=0 && !flushed && curr_pos<=pos && i<1000; ++i ) {
661 ret = read_frame(frame);
664 AVCodecContext *ctx = st->codec;
665 ret = convert_cmodel(vframe, (AVPicture *)frame,
666 ctx->pix_fmt, ctx->width, ctx->height);
668 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
672 int FFVideoStream::video_seek(int64_t pos)
674 if( decode_activate() < 0 ) return -1;
675 // if close enough, just read up to current
676 // 3*gop_size seems excessive, but less causes tears
677 int gop = 3*st->codec->gop_size;
678 if( gop < 4 ) gop = 4;
679 if( gop > 64 ) gop = 64;
680 if( pos >= curr_pos && pos <= curr_pos + gop ) return 0;
681 // back up a few frames to read up to current to help repair damages
682 if( (pos-=gop) < 0 ) pos = 0;
683 double secs = (double)pos / frame_rate;
684 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
685 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
686 avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, tstmp, INT64_MAX, 0);
687 seek_pos = curr_pos = pos;
692 int FFVideoStream::init_frame(AVFrame *picture)
694 AVCodecContext *ctx = st->codec;
695 picture->format = ctx->pix_fmt;
696 picture->width = ctx->width;
697 picture->height = ctx->height;
698 int ret = av_frame_get_buffer(picture, 32);
702 int FFVideoStream::encode(VFrame *vframe)
704 if( encode_activate() <= 0 ) return -1;
706 FFrame *picture = new FFrame(this);
707 int ret = picture->initted();
709 AVFrame *frame = *picture;
710 frame->pts = curr_pos;
711 AVCodecContext *ctx = st->codec;
712 ret = convert_pixfmt(vframe, (AVPicture*)frame,
713 ctx->pix_fmt, ctx->width, ctx->height);
716 picture->queue(curr_pos);
720 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
723 return ret >= 0 ? 0 : 1;
727 PixelFormat FFVideoStream::color_model_to_pix_fmt(int color_model)
729 switch( color_model ) {
730 case BC_YUV422: return AV_PIX_FMT_YUYV422;
731 case BC_RGB888: return AV_PIX_FMT_RGB24;
732 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
733 case BC_BGR8888: return AV_PIX_FMT_BGR0;
734 case BC_BGR888: return AV_PIX_FMT_BGR24;
735 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
736 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
737 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
738 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
739 case BC_RGB565: return AV_PIX_FMT_RGB565;
740 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
741 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
745 return AV_PIX_FMT_NB;
748 int FFVideoStream::pix_fmt_to_color_model(PixelFormat pix_fmt)
751 case AV_PIX_FMT_YUYV422: return BC_YUV422;
752 case AV_PIX_FMT_RGB24: return BC_RGB888;
753 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
754 case AV_PIX_FMT_BGR0: return BC_BGR8888;
755 case AV_PIX_FMT_BGR24: return BC_BGR888;
756 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
757 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
758 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
759 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
760 case AV_PIX_FMT_RGB565: return BC_RGB565;
761 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
762 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
766 return BC_TRANSPARENCY;
769 int FFVideoStream::convert_picture_vframe(VFrame *frame,
770 AVPicture *ip, PixelFormat ifmt, int iw, int ih)
773 int cmodel = frame->get_color_model();
774 PixelFormat ofmt = color_model_to_pix_fmt(cmodel);
775 if( ofmt == AV_PIX_FMT_NB ) return -1;
776 int size = avpicture_fill(&opic, frame->get_data(), ofmt,
777 frame->get_w(), frame->get_h());
778 if( size < 0 ) return -1;
780 // transfer line sizes must match also
781 int planar = BC_CModels::is_planar(cmodel);
782 int packed_width = !planar ? frame->get_bytes_per_line() :
783 BC_CModels::calculate_pixelsize(cmodel) * frame->get_w();
784 if( packed_width != opic.linesize[0] ) return -1;
787 // override avpicture_fill() for planar types
788 opic.data[0] = frame->get_y();
789 opic.data[1] = frame->get_u();
790 opic.data[2] = frame->get_v();
793 convert_ctx = sws_getCachedContext(convert_ctx, iw, ih, ifmt,
794 frame->get_w(), frame->get_h(), ofmt, SWS_BICUBIC, NULL, NULL, NULL);
796 fprintf(stderr, "FFVideoStream::convert_picture_frame:"
797 " sws_getCachedContext() failed\n");
800 if( sws_scale(convert_ctx, ip->data, ip->linesize, 0, ih,
801 opic.data, opic.linesize) < 0 ) {
802 fprintf(stderr, "FFVideoStream::convert_picture_frame: sws_scale() failed\n");
808 int FFVideoStream::convert_cmodel(VFrame *frame,
809 AVPicture *ip, PixelFormat ifmt, int iw, int ih)
811 // try direct transfer
812 if( !convert_picture_vframe(frame, ip, ifmt, iw, ih) ) return 1;
813 // use indirect transfer
814 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
816 for( int i = 0; i <desc->nb_components; ++i ) {
817 int bits = desc->comp[i].depth_minus1 + 1;
818 if( bits > max_bits ) max_bits = bits;
820 // from libavcodec/pixdesc.c
821 #define pixdesc_has_alpha(pixdesc) ((pixdesc)->nb_components == 2 || \
822 (pixdesc)->nb_components == 4 || (pixdesc)->flags & AV_PIX_FMT_FLAG_PAL)
823 int icolor_model = pixdesc_has_alpha(desc) ?
824 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
825 (max_bits > 8 ? BC_RGB161616 : BC_RGB888) ;
826 VFrame vframe(iw, ih, icolor_model);
827 if( convert_picture_vframe(&vframe, ip, ifmt, iw, ih) ) return -1;
828 frame->transfer_from(&vframe);
832 int FFVideoStream::convert_vframe_picture(VFrame *frame,
833 AVPicture *op, PixelFormat ofmt, int ow, int oh)
836 int cmodel = frame->get_color_model();
837 PixelFormat ifmt = color_model_to_pix_fmt(cmodel);
838 if( ifmt == AV_PIX_FMT_NB ) return -1;
839 int size = avpicture_fill(&opic, frame->get_data(), ifmt,
840 frame->get_w(), frame->get_h());
841 if( size < 0 ) return -1;
843 // transfer line sizes must match also
844 int planar = BC_CModels::is_planar(cmodel);
845 int packed_width = !planar ? frame->get_bytes_per_line() :
846 BC_CModels::calculate_pixelsize(cmodel) * frame->get_w();
847 if( packed_width != opic.linesize[0] ) return -1;
850 // override avpicture_fill() for planar types
851 opic.data[0] = frame->get_y();
852 opic.data[1] = frame->get_u();
853 opic.data[2] = frame->get_v();
856 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(), ifmt,
857 ow, oh, ofmt, SWS_BICUBIC, NULL, NULL, NULL);
859 fprintf(stderr, "FFVideoStream::convert_frame_picture:"
860 " sws_getCachedContext() failed\n");
863 if( sws_scale(convert_ctx, opic.data, opic.linesize, 0, frame->get_h(),
864 op->data, op->linesize) < 0 ) {
865 fprintf(stderr, "FFVideoStream::convert_frame_picture: sws_scale() failed\n");
871 int FFVideoStream::convert_pixfmt(VFrame *frame,
872 AVPicture *op, PixelFormat ofmt, int ow, int oh)
874 // try direct transfer
875 if( !convert_vframe_picture(frame, op, ofmt, ow, oh) ) return 0;
876 // use indirect transfer
877 int colormodel = frame->get_color_model();
878 int bits = BC_CModels::calculate_pixelsize(colormodel) * 8;
879 bits /= BC_CModels::components(colormodel);
880 int icolor_model = BC_CModels::has_alpha(colormodel) ?
881 (bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
882 (bits > 8 ? BC_RGB161616: BC_RGB888) ;
883 VFrame vframe(frame->get_w(), frame->get_h(), icolor_model);
884 vframe.transfer_from(frame);
885 if( convert_vframe_picture(&vframe, op, ofmt, ow, oh) ) return 1;
890 FFMPEG::FFMPEG(FileBase *file_base)
893 this->file_base = file_base;
894 memset(file_format,0,sizeof(file_format));
895 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
896 flow_lock = new Condition(1,"FFStream::flow_lock",0);
899 decoding = encoding = 0;
900 has_audio = has_video = 0;
903 opt_video_filter = 0;
904 opt_audio_filter = 0;
905 char option_path[BCTEXTLEN];
906 set_option_path(option_path, "%s", "ffmpeg.opts");
907 read_options(option_path, opts);
912 ff_lock("FFMPEG::~FFMPEG()");
914 ffaudio.remove_all_objects();
915 ffvideo.remove_all_objects();
916 if( encoding ) avformat_free_context(fmt_ctx);
921 delete opt_video_filter;
922 delete opt_audio_filter;
925 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
927 const int *p = codec->supported_samplerates;
928 if( !p ) return sample_rate;
930 if( *p == sample_rate ) return *p;
936 static inline AVRational std_frame_rate(int i)
938 static const int m1 = 1001*12, m2 = 1000*12;
939 static const int freqs[] = {
940 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
941 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
943 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
944 return (AVRational) { freq, 1001*12 };
947 AVRational FFMPEG::check_frame_rate(AVCodec *codec, double frame_rate)
949 const AVRational *p = codec->supported_framerates;
950 AVRational rate, best_rate = (AVRational) { 0, 0 };
951 double max_err = 1.; int i = 0;
952 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
953 double framerate = (double) rate.num / rate.den;
954 double err = fabs(frame_rate/framerate - 1.);
955 if( err >= max_err ) continue;
959 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
962 AVRational FFMPEG::to_sample_aspect_ratio(double aspect_ratio)
964 int height = 1000000, width = height * aspect_ratio;
966 MWindow::create_aspect_ratio(w, h, width, height);
967 return (AVRational){(int)w, (int)h};
970 AVRational FFMPEG::to_time_base(int sample_rate)
972 return (AVRational){1, sample_rate};
975 extern void get_exe_path(char *result); // from main.C
977 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
980 strcat(path, "/ffmpeg/");
981 path += strlen(path);
984 vsprintf(path, fmt, ap);
988 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
993 set_option_path(path, "%s/%s", type, spec);
996 int FFMPEG::check_option(const char *path, char *spec)
998 char option_path[BCTEXTLEN], line[BCTEXTLEN];
999 char format[BCSTRLEN], codec[BCSTRLEN];
1000 get_option_path(option_path, path, spec);
1001 FILE *fp = fopen(option_path,"r");
1004 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1006 line[sizeof(line)-1] = 0;
1007 ret = scan_option_line(line, format, codec);
1010 if( !file_format[0] ) strcpy(file_format, format);
1011 else if( strcmp(file_format, format) ) ret = 1;
1017 const char *FFMPEG::get_file_format()
1021 Asset *asset = file_base->asset;
1022 if( !ret && asset->audio_data )
1023 ret = check_option("audio", asset->acodec);
1024 if( !ret && asset->video_data )
1025 ret = check_option("video", asset->vcodec);
1026 if( !ret && !file_format[0] ) ret = 1;
1027 return !ret ? file_format : 0;
1030 int FFMPEG::scan_option_line(char *cp, char *tag, char *val)
1032 while( *cp == ' ' || *cp == '\t' ) ++cp;
1034 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' ) ++cp;
1036 if( !len || len > BCSTRLEN-1 ) return 1;
1037 while( bp < cp ) *tag++ = *bp++;
1039 while( *cp == ' ' || *cp == '\t' ) ++cp;
1040 if( *cp == '=' ) ++cp;
1041 while( *cp == ' ' || *cp == '\t' ) ++cp;
1043 while( *cp && *cp != '\n' ) ++cp;
1045 if( len > BCTEXTLEN-1 ) return 1;
1046 while( bp < cp ) *val++ = *bp++;
1051 int FFMPEG::read_options(const char *options, char *format, char *codec,
1052 char *bsfilter, char *bsargs, AVDictionary *&opts)
1054 FILE *fp = fopen(options,"r");
1056 fprintf(stderr, "FFMPEG::read_options: options open failed %s\n",options);
1059 int ret = read_options(fp, options, format, codec, opts);
1061 while( *cp && *cp != '|' ) ++cp;
1062 if( *cp == '|' && !scan_option_line(cp+1, bsfilter, bsargs) ) {
1063 do { *cp-- = 0; } while( cp>=codec && (*cp==' ' || *cp == '\t' ) );
1066 bsfilter[0] = bsargs[0] = 0;
1071 int FFMPEG::read_options(FILE *fp, const char *options,
1072 char *format, char *codec, AVDictionary *&opts)
1074 char line[BCTEXTLEN];
1075 if( !fgets(line, sizeof(line), fp) ) {
1076 fprintf(stderr, "FFMPEG::read_options:"
1077 " options file empty %s\n",options);
1080 line[sizeof(line)-1] = 0;
1081 if( scan_option_line(line, format, codec) ) {
1082 fprintf(stderr, "FFMPEG::read_options:"
1083 " err: format/codec not found %s\n", options);
1086 return read_options(fp, options, opts, 1);
1089 int FFMPEG::read_options(const char *options, AVDictionary *&opts)
1091 FILE *fp = fopen(options,"r");
1093 int ret = read_options(fp, options, opts);
1098 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts, int no)
1101 char line[BCTEXTLEN];
1102 while( !ret && fgets(line, sizeof(line), fp) ) {
1103 line[sizeof(line)-1] = 0;
1105 if( line[0] == '#' ) continue;
1106 char key[BCSTRLEN], val[BCTEXTLEN];
1107 if( scan_option_line(line, key, val) ) {
1108 fprintf(stderr, "FFMPEG::read_options:"
1109 " err reading %s: line %d\n", options, no);
1113 if( !strcmp(key, "duration") )
1114 opt_duration = strtod(val, 0);
1115 if( !strcmp(key, "video_filter") )
1116 opt_video_filter = cstrdup(val);
1117 if( !strcmp(key, "audio_filter") )
1118 opt_audio_filter = cstrdup(val);
1119 else if( !strcmp(key, "loglevel") )
1122 av_dict_set(&opts, key, val, 0);
1128 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
1130 char option_path[BCTEXTLEN];
1131 set_option_path(option_path, "%s", options);
1132 return read_options(option_path, opts);
1135 void FFMPEG::set_loglevel(const char *ap)
1137 if( !ap || !*ap ) return;
1142 { "quiet" , AV_LOG_QUIET },
1143 { "panic" , AV_LOG_PANIC },
1144 { "fatal" , AV_LOG_FATAL },
1145 { "error" , AV_LOG_ERROR },
1146 { "warning", AV_LOG_WARNING },
1147 { "info" , AV_LOG_INFO },
1148 { "verbose", AV_LOG_VERBOSE },
1149 { "debug" , AV_LOG_DEBUG },
1151 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
1152 if( !strcmp(log_levels[i].name, ap) ) {
1153 av_log_set_level(log_levels[i].level);
1157 av_log_set_level(atoi(ap));
1160 double FFMPEG::to_secs(int64_t time, AVRational time_base)
1162 double base_time = time == AV_NOPTS_VALUE ? 0 :
1163 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
1164 return base_time / AV_TIME_BASE;
1167 int FFMPEG::info(char *text, int len)
1169 if( len <= 0 ) return 0;
1170 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
1172 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1173 AVStream *st = fmt_ctx->streams[i];
1174 AVCodecContext *avctx = st->codec;
1175 report("stream %d, id 0x%06x:\n", i, avctx->codec_id);
1176 const AVCodecDescriptor *desc = avcodec_descriptor_get(avctx->codec_id);
1177 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1178 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
1179 double frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
1180 report(" video %s",desc ? desc->name : " (unkn)");
1181 report(" %dx%d %5.2f", avctx->width, avctx->height, frame_rate);
1182 const char *pfn = av_get_pix_fmt_name(avctx->pix_fmt);
1183 report(" pix %s\n", pfn ? pfn : "(unkn)");
1184 double secs = to_secs(st->duration, st->time_base);
1185 int64_t length = secs * frame_rate + 0.5;
1186 report(" %jd frms %0.2f secs", length, secs);
1187 int hrs = secs/3600; secs -= hrs*3600;
1188 int mins = secs/60; secs -= mins*60;
1189 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1192 else if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1193 int sample_rate = avctx->sample_rate;
1194 const char *fmt = av_get_sample_fmt_name(avctx->sample_fmt);
1195 report(" audio %s",desc ? desc->name : " (unkn)");
1196 report(" %dch %s %d",avctx->channels, fmt, sample_rate);
1197 int sample_bits = av_get_bits_per_sample(avctx->codec_id);
1198 report(" %dbits\n", sample_bits);
1199 double secs = to_secs(st->duration, st->time_base);
1200 int64_t length = secs * sample_rate + 0.5;
1201 report(" %jd smpl %0.2f secs", length, secs);
1202 int hrs = secs/3600; secs -= hrs*3600;
1203 int mins = secs/60; secs -= mins*60;
1204 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1207 report(" codec_type unknown\n");
1210 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
1211 report("program %d", i+1);
1212 AVProgram *pgrm = fmt_ctx->programs[i];
1213 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j )
1214 report(", %d", pgrm->stream_index[j]);
1218 AVDictionaryEntry *tag = 0;
1219 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
1220 report("%s=%s\n", tag->key, tag->value);
1229 int FFMPEG::init_decoder(const char *filename)
1231 ff_lock("FFMPEG::init_decoder");
1233 char file_opts[BCTEXTLEN];
1234 char *bp = strrchr(strcpy(file_opts, filename), '/');
1235 char *sp = strrchr(!bp ? file_opts : bp, '.');
1238 strcpy(sp, ".opts");
1239 fp = fopen(file_opts, "r");
1242 read_options(fp, file_opts, opts, 0);
1246 load_options("decode.opts", opts);
1247 AVDictionary *fopts = 0;
1248 av_dict_copy(&fopts, opts, 0);
1249 int ret = avformat_open_input(&fmt_ctx, filename, NULL, &fopts);
1250 av_dict_free(&fopts);
1252 ret = avformat_find_stream_info(fmt_ctx, NULL);
1257 return !ret ? 0 : 1;
1260 int FFMPEG::open_decoder()
1263 if( stat(fmt_ctx->filename, &st) < 0 ) {
1264 fprintf(stderr,"FFMPEG::open_decoder: can't stat file: %s\n",
1269 int64_t file_bits = 8 * st.st_size;
1270 if( !fmt_ctx->bit_rate && opt_duration > 0 )
1271 fmt_ctx->bit_rate = file_bits / opt_duration;
1274 if( fmt_ctx->bit_rate > 0 ) {
1275 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1276 AVStream *st = fmt_ctx->streams[i];
1277 if( st->duration != AV_NOPTS_VALUE ) continue;
1278 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
1279 st->duration = av_rescale(file_bits, st->time_base.den,
1280 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
1285 printf("FFMPEG::open_decoder: some stream times estimated\n");
1287 ff_lock("FFMPEG::open_decoder");
1289 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1290 AVStream *st = fmt_ctx->streams[i];
1291 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
1292 AVCodecContext *avctx = st->codec;
1293 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1295 FFVideoStream *vid = new FFVideoStream(this, st, i);
1296 int vidx = ffvideo.size();
1297 vstrm_index.append(ffidx(vidx, 0));
1298 ffvideo.append(vid);
1299 vid->width = avctx->width;
1300 vid->height = avctx->height;
1301 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
1302 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
1303 double secs = to_secs(st->duration, st->time_base);
1304 vid->length = secs * vid->frame_rate;
1305 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
1306 vid->nudge = st->start_time;
1308 if( opt_video_filter )
1309 vid->create_filter(opt_video_filter, avctx,avctx);
1311 else if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1313 FFAudioStream *aud = new FFAudioStream(this, st, i);
1314 int aidx = ffaudio.size();
1315 ffaudio.append(aud);
1316 aud->channel0 = astrm_index.size();
1317 aud->channels = avctx->channels;
1318 for( int ch=0; ch<aud->channels; ++ch )
1319 astrm_index.append(ffidx(aidx, ch));
1320 aud->sample_rate = avctx->sample_rate;
1321 double secs = to_secs(st->duration, st->time_base);
1322 aud->length = secs * aud->sample_rate;
1323 if( avctx->sample_fmt != AV_SAMPLE_FMT_FLT ) {
1324 uint64_t layout = av_get_default_channel_layout(avctx->channels);
1325 if( !layout ) layout = ((uint64_t)1<<aud->channels) - 1;
1326 aud->resample_context = swr_alloc_set_opts(NULL,
1327 layout, AV_SAMPLE_FMT_FLT, avctx->sample_rate,
1328 layout, avctx->sample_fmt, avctx->sample_rate,
1330 swr_init(aud->resample_context);
1332 aud->nudge = st->start_time;
1334 if( opt_audio_filter )
1335 aud->create_filter(opt_audio_filter, avctx,avctx);
1339 printf("FFMPEG::open_decoder: some stream have bad times\n");
1345 int FFMPEG::init_encoder(const char *filename)
1347 const char *format = get_file_format();
1349 fprintf(stderr, "FFMPEG::init_encoder: invalid file format for %s\n", filename);
1353 ff_lock("FFMPEG::init_encoder");
1355 avformat_alloc_output_context2(&fmt_ctx, 0, format, filename);
1357 fprintf(stderr, "FFMPEG::init_encoder: failed: %s\n", filename);
1362 load_options("encode.opts", opts);
1369 int FFMPEG::open_encoder(const char *path, const char *spec)
1372 Asset *asset = file_base->asset;
1373 char *filename = asset->path;
1374 AVDictionary *sopts = 0;
1375 av_dict_copy(&sopts, opts, 0);
1376 char option_path[BCTEXTLEN];
1377 set_option_path(option_path, "%s/%s.opts", path, path);
1378 read_options(option_path, sopts);
1379 get_option_path(option_path, path, spec);
1380 char format_name[BCSTRLEN], codec_name[BCTEXTLEN];
1381 char bsfilter[BCSTRLEN], bsargs[BCTEXTLEN];
1382 if( read_options(option_path, format_name, codec_name, bsfilter, bsargs, sopts) ) {
1383 fprintf(stderr, "FFMPEG::open_encoder: read options failed %s:%s\n",
1384 option_path, filename);
1389 ff_lock("FFMPEG::open_encoder");
1393 const AVCodecDescriptor *codec_desc = 0;
1394 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
1396 fprintf(stderr, "FFMPEG::open_encoder: cant find codec %s:%s\n",
1397 codec_name, filename);
1401 codec_desc = avcodec_descriptor_get(codec->id);
1403 fprintf(stderr, "FFMPEG::open_encoder: unknown codec %s:%s\n",
1404 codec_name, filename);
1409 st = avformat_new_stream(fmt_ctx, 0);
1411 fprintf(stderr, "FFMPEG::open_encoder: cant create stream %s:%s\n",
1412 codec_name, filename);
1417 AVCodecContext *ctx = st->codec;
1418 switch( codec_desc->type ) {
1419 case AVMEDIA_TYPE_AUDIO: {
1421 fprintf(stderr, "FFMPEG::open_encoder: duplicate audio %s:%s\n",
1422 codec_name, filename);
1427 int aidx = ffaudio.size();
1428 int idx = aidx + ffvideo.size();
1429 FFAudioStream *aud = new FFAudioStream(this, st, idx);
1430 ffaudio.append(aud); fst = aud;
1431 aud->sample_rate = asset->sample_rate;
1432 ctx->channels = aud->channels = asset->channels;
1433 for( int ch=0; ch<aud->channels; ++ch )
1434 astrm_index.append(ffidx(aidx, ch));
1435 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
1436 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
1437 if( !ctx->sample_rate ) {
1438 fprintf(stderr, "FFMPEG::open_audio_encode:"
1439 " check_sample_rate failed %s\n", filename);
1443 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
1444 ctx->sample_fmt = codec->sample_fmts[0];
1445 uint64_t layout = av_get_default_channel_layout(ctx->channels);
1446 aud->resample_context = swr_alloc_set_opts(NULL,
1447 layout, ctx->sample_fmt, aud->sample_rate,
1448 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
1450 swr_init(aud->resample_context);
1453 case AVMEDIA_TYPE_VIDEO: {
1455 fprintf(stderr, "FFMPEG::open_encoder: duplicate video %s:%s\n",
1456 codec_name, filename);
1461 int vidx = ffvideo.size();
1462 int idx = vidx + ffaudio.size();
1463 FFVideoStream *vid = new FFVideoStream(this, st, idx);
1464 vstrm_index.append(ffidx(vidx, 0));
1465 ffvideo.append(vid); fst = vid;
1466 vid->width = asset->width;
1467 ctx->width = (vid->width+3) & ~3;
1468 vid->height = asset->height;
1469 ctx->height = (vid->height+3) & ~3;
1470 vid->frame_rate = asset->frame_rate;
1471 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset->aspect_ratio);
1472 ctx->pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
1473 AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
1474 if( !frame_rate.num || !frame_rate.den ) {
1475 fprintf(stderr, "FFMPEG::open_audio_encode:"
1476 " check_frame_rate failed %s\n", filename);
1480 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
1481 st->time_base = ctx->time_base;
1485 fprintf(stderr, "FFMPEG::open_encoder: not audio/video, %s:%s\n",
1486 codec_name, filename);
1491 ret = avcodec_open2(st->codec, codec, &sopts);
1493 ff_err(ret,"FFMPEG::open_encoder");
1494 fprintf(stderr, "FFMPEG::open_encoder: open failed %s:%s\n",
1495 codec_name, filename);
1502 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
1503 st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
1504 if( fst && bsfilter[0] )
1505 fst->add_bsfilter(bsfilter, !bsargs[0] ? 0 : bsargs);
1509 av_dict_free(&sopts);
1513 int FFMPEG::close_encoder()
1516 if( encoding > 0 ) {
1517 av_write_trailer(fmt_ctx);
1518 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
1519 avio_closep(&fmt_ctx->pb);
1525 int FFMPEG::decode_activate()
1527 if( decoding < 0 ) {
1529 int npgrms = fmt_ctx->nb_programs;
1530 for( int i=0; i<npgrms; ++i ) {
1531 AVProgram *pgrm = fmt_ctx->programs[i];
1532 // first start time video stream
1533 int64_t vstart_time = -1;
1534 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1535 int st_idx = pgrm->stream_index[j];
1536 AVStream *st = fmt_ctx->streams[st_idx];
1537 AVCodecContext *avctx = st->codec;
1538 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1539 if( st->start_time == AV_NOPTS_VALUE ) continue;
1540 vstart_time = st->start_time;
1544 // max start time audio stream
1545 int64_t astart_time = -1;
1546 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1547 int st_idx = pgrm->stream_index[j];
1548 AVStream *st = fmt_ctx->streams[st_idx];
1549 AVCodecContext *avctx = st->codec;
1550 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1551 if( st->start_time == AV_NOPTS_VALUE ) continue;
1552 if( astart_time > st->start_time ) continue;
1553 astart_time = st->start_time;
1556 if( astart_time < 0 || vstart_time < 0 ) continue;
1557 // match program streams to max start_time
1558 int64_t nudge = vstart_time > astart_time ? vstart_time : astart_time;
1559 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1560 int st_idx = pgrm->stream_index[j];
1561 AVStream *st = fmt_ctx->streams[st_idx];
1562 AVCodecContext *avctx = st->codec;
1563 if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1564 for( int k=0; k<ffaudio.size(); ++k ) {
1565 if( ffaudio[k]->idx == st_idx )
1566 ffaudio[k]->nudge = nudge;
1569 else if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1570 for( int k=0; k<ffvideo.size(); ++k ) {
1571 if( ffvideo[k]->idx == st_idx )
1572 ffvideo[k]->nudge = nudge;
1577 int64_t vstart_time = 0, astart_time = 0;
1578 int nstreams = fmt_ctx->nb_streams;
1579 for( int i=0; i<nstreams; ++i ) {
1580 AVStream *st = fmt_ctx->streams[i];
1581 AVCodecContext *avctx = st->codec;
1582 switch( avctx->codec_type ) {
1583 case AVMEDIA_TYPE_VIDEO:
1584 if( st->start_time == AV_NOPTS_VALUE ) continue;
1585 if( vstart_time >= st->start_time ) continue;
1586 vstart_time = st->start_time;
1588 case AVMEDIA_TYPE_AUDIO:
1589 if( st->start_time == AV_NOPTS_VALUE ) continue;
1590 if( astart_time >= st->start_time ) continue;
1591 astart_time = st->start_time;
1595 int64_t nudge = vstart_time > astart_time ? vstart_time : astart_time;
1596 for( int k=0; k<ffvideo.size(); ++k ) {
1597 if( ffvideo[k]->nudge != AV_NOPTS_VALUE ) continue;
1598 ffvideo[k]->nudge = nudge;
1600 for( int k=0; k<ffaudio.size(); ++k ) {
1601 if( ffaudio[k]->nudge != AV_NOPTS_VALUE ) continue;
1602 ffaudio[k]->nudge = nudge;
1609 int FFMPEG::encode_activate()
1611 if( encoding < 0 ) {
1613 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
1614 avio_open(&fmt_ctx->pb, fmt_ctx->filename, AVIO_FLAG_WRITE) < 0 ) {
1615 fprintf(stderr, "FFMPEG::encode_activate: err opening : %s\n",
1620 AVDictionary *fopts = 0;
1621 char option_path[BCTEXTLEN];
1622 set_option_path(option_path, "format/%s", file_format);
1623 read_options(option_path, fopts);
1624 int ret = avformat_write_header(fmt_ctx, &fopts);
1625 av_dict_free(&fopts);
1627 fprintf(stderr, "FFMPEG::encode_activate: write header failed %s\n",
1636 int FFMPEG::audio_seek(int stream, int64_t pos)
1638 int aidx = astrm_index[stream].st_idx;
1639 FFAudioStream *aud = ffaudio[aidx];
1640 aud->audio_seek(pos);
1641 aud->seek_pos = aud->curr_pos = pos;
1645 int FFMPEG::video_seek(int stream, int64_t pos)
1647 int vidx = vstrm_index[stream].st_idx;
1648 FFVideoStream *vid = ffvideo[vidx];
1649 vid->video_seek(pos);
1650 vid->seek_pos = vid->curr_pos = pos;
1655 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
1657 if( !has_audio || chn >= astrm_index.size() ) return -1;
1658 int aidx = astrm_index[chn].st_idx;
1659 FFAudioStream *aud = ffaudio[aidx];
1660 if( aud->load(pos, len) < len ) return -1;
1661 int ch = astrm_index[chn].st_ch;
1662 return aud->history.read(samples,len,ch);
1665 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
1667 if( !has_video || layer >= vstrm_index.size() ) return -1;
1668 int vidx = vstrm_index[layer].st_idx;
1669 FFVideoStream *vid = ffvideo[vidx];
1670 return vid->load(vframe, pos);
1673 int FFMPEG::encode(int stream, double **samples, int len)
1675 FFAudioStream *aud = ffaudio[stream];
1676 return aud->encode(samples, len);
1680 int FFMPEG::encode(int stream, VFrame *frame)
1682 FFVideoStream *vid = ffvideo[stream];
1683 return vid->encode(frame);
1686 void FFMPEG::start_muxer()
1694 void FFMPEG::stop_muxer()
1703 void FFMPEG::flow_off()
1706 flow_lock->lock("FFMPEG::flow_off");
1710 void FFMPEG::flow_on()
1714 flow_lock->unlock();
1717 void FFMPEG::flow_ctl()
1720 flow_lock->lock("FFMPEG::flow_ctl");
1721 flow_lock->unlock();
1725 int FFMPEG::mux_audio(FFrame *frm)
1728 AVStream *st = frm->fst->st;
1729 AVCodecContext *ctx = st->codec;
1730 AVFrame *frame = *frm;
1731 AVRational tick_rate = {1, ctx->sample_rate};
1732 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
1734 int ret = avcodec_encode_audio2(ctx, pkt, frame, &got_packet);
1735 if( ret >= 0 && got_packet ) {
1736 frm->fst->bs_filter(pkt);
1737 av_packet_rescale_ts(pkt, ctx->time_base, st->time_base);
1738 pkt->stream_index = st->index;
1739 ret = av_interleaved_write_frame(fmt_ctx, pkt);
1742 ff_err(ret, "FFMPEG::mux_audio");
1743 return ret >= 0 ? 0 : 1;
1746 int FFMPEG::mux_video(FFrame *frm)
1749 AVStream *st = frm->fst->st;
1750 AVFrame *frame = *frm;
1751 frame->pts = frm->position;
1752 int ret = 1, got_packet = 0;
1753 if( fmt_ctx->oformat->flags & AVFMT_RAWPICTURE ) {
1754 /* a hack to avoid data copy with some raw video muxers */
1755 pkt->flags |= AV_PKT_FLAG_KEY;
1756 pkt->stream_index = st->index;
1757 AVPicture *picture = (AVPicture *)frame;
1758 pkt->data = (uint8_t *)picture;
1759 pkt->size = sizeof(AVPicture);
1760 pkt->pts = pkt->dts = frame->pts;
1764 ret = avcodec_encode_video2(st->codec, pkt, frame, &got_packet);
1765 if( ret >= 0 && got_packet ) {
1766 frm->fst->bs_filter(pkt);
1767 av_packet_rescale_ts(pkt, st->codec->time_base, st->time_base);
1768 pkt->stream_index = st->index;
1769 ret = av_interleaved_write_frame(fmt_ctx, pkt);
1772 ff_err(ret, "FFMPEG::mux_video");
1773 return ret >= 0 ? 0 : 1;
1779 double atm = -1, vtm = -1;
1780 FFrame *afrm = 0, *vfrm = 0;
1782 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
1783 FFStream *fst = ffaudio[i];
1784 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
1785 FFrame *frm = fst->frms.first;
1786 if( !frm ) { if( !done ) return; continue; }
1787 double tm = to_secs(frm->position, fst->st->codec->time_base);
1788 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
1790 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
1791 FFStream *fst = ffvideo[i];
1792 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
1793 FFrame *frm = fst->frms.first;
1794 if( !frm ) { if( !done ) return; continue; }
1795 double tm = to_secs(frm->position, fst->st->codec->time_base);
1796 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
1798 if( !demand ) flow_off();
1799 if( !afrm && !vfrm ) break;
1800 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
1801 vfrm->position, vfrm->fst->st->codec->time_base,
1802 afrm->position, afrm->fst->st->codec->time_base);
1803 FFrame *frm = v <= 0 ? vfrm : afrm;
1804 if( frm == afrm ) mux_audio(frm);
1805 if( frm == vfrm ) mux_video(frm);
1814 mux_lock->lock("FFMPEG::run");
1821 int FFMPEG::ff_total_audio_channels()
1823 return astrm_index.size();
1826 int FFMPEG::ff_total_astreams()
1828 return ffaudio.size();
1831 int FFMPEG::ff_audio_channels(int stream)
1833 return ffaudio[stream]->channels;
1836 int FFMPEG::ff_sample_rate(int stream)
1838 return ffaudio[stream]->sample_rate;
1841 const char* FFMPEG::ff_audio_format(int stream)
1843 AVStream *st = ffaudio[stream]->st;
1844 AVCodecID id = st->codec->codec_id;
1845 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
1846 return desc ? desc->name : "Unknown";
1849 int FFMPEG::ff_audio_pid(int stream)
1851 return ffaudio[stream]->st->id;
1854 int64_t FFMPEG::ff_audio_samples(int stream)
1856 return ffaudio[stream]->length;
1859 // find audio astream/channels with this program,
1860 // or all program audio channels (astream=-1)
1861 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
1865 int vidx = ffvideo[vstream]->idx;
1866 // find first program with this video stream
1867 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
1868 AVProgram *pgrm = fmt_ctx->programs[i];
1869 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
1870 int st_idx = pgrm->stream_index[j];
1871 AVStream *st = fmt_ctx->streams[st_idx];
1872 if( st->codec->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
1873 if( st_idx == vidx ) pidx = i;
1876 if( pidx < 0 ) return -1;
1878 int64_t channels = 0;
1879 AVProgram *pgrm = fmt_ctx->programs[pidx];
1880 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1881 int aidx = pgrm->stream_index[j];
1882 AVStream *st = fmt_ctx->streams[aidx];
1883 if( st->codec->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
1884 if( astream > 0 ) { --astream; continue; }
1886 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
1887 if( ffaudio[i]->idx == aidx ) astrm = i;
1889 if( ret < 0 ) ret = astrm;
1890 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
1891 channels |= mask << ffaudio[astrm]->channel0;
1893 if( !astream ) break;
1895 channel_mask = channels;
1900 int FFMPEG::ff_total_video_layers()
1902 return vstrm_index.size();
1905 int FFMPEG::ff_total_vstreams()
1907 return ffvideo.size();
1910 int FFMPEG::ff_video_width(int stream)
1912 return ffvideo[stream]->width;
1915 int FFMPEG::ff_video_height(int stream)
1917 return ffvideo[stream]->height;
1920 int FFMPEG::ff_set_video_width(int stream, int width)
1922 int w = ffvideo[stream]->width;
1923 ffvideo[stream]->width = width;
1927 int FFMPEG::ff_set_video_height(int stream, int height)
1929 int h = ffvideo[stream]->height;
1930 ffvideo[stream]->height = height;
1934 int FFMPEG::ff_coded_width(int stream)
1936 AVStream *st = ffvideo[stream]->st;
1937 return st->codec->coded_width;
1940 int FFMPEG::ff_coded_height(int stream)
1942 AVStream *st = ffvideo[stream]->st;
1943 return st->codec->coded_height;
1946 float FFMPEG::ff_aspect_ratio(int stream)
1948 return ffvideo[stream]->aspect_ratio;
1951 const char* FFMPEG::ff_video_format(int stream)
1953 AVStream *st = ffvideo[stream]->st;
1954 AVCodecID id = st->codec->codec_id;
1955 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
1956 return desc ? desc->name : "Unknown";
1959 double FFMPEG::ff_frame_rate(int stream)
1961 return ffvideo[stream]->frame_rate;
1964 int64_t FFMPEG::ff_video_frames(int stream)
1966 return ffvideo[stream]->length;
1969 int FFMPEG::ff_video_pid(int stream)
1971 return ffvideo[stream]->st->id;
1975 int FFMPEG::ff_cpus()
1977 return file_base->file->cpus;
1980 int FFVideoStream::create_filter(const char *filter_spec,
1981 AVCodecContext *src_ctx, AVCodecContext *sink_ctx)
1983 avfilter_register_all();
1984 filter_graph = avfilter_graph_alloc();
1985 AVFilter *buffersrc = avfilter_get_by_name("buffer");
1986 AVFilter *buffersink = avfilter_get_by_name("buffersink");
1988 int ret = 0; char args[BCTEXTLEN];
1989 snprintf(args, sizeof(args),
1990 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
1991 src_ctx->width, src_ctx->height, src_ctx->pix_fmt,
1992 st->time_base.num, st->time_base.den,
1993 src_ctx->sample_aspect_ratio.num, src_ctx->sample_aspect_ratio.den);
1995 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
1996 args, NULL, filter_graph);
1998 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
1999 NULL, NULL, filter_graph);
2001 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
2002 (uint8_t*)&sink_ctx->pix_fmt, sizeof(sink_ctx->pix_fmt),
2003 AV_OPT_SEARCH_CHILDREN);
2005 ff_err(ret, "FFVideoStream::create_filter");
2007 ret = FFStream::create_filter(filter_spec);
2008 return ret >= 0 ? 0 : 1;
2011 int FFAudioStream::create_filter(const char *filter_spec,
2012 AVCodecContext *src_ctx, AVCodecContext *sink_ctx)
2014 avfilter_register_all();
2015 filter_graph = avfilter_graph_alloc();
2016 AVFilter *buffersrc = avfilter_get_by_name("abuffer");
2017 AVFilter *buffersink = avfilter_get_by_name("abuffersink");
2018 int ret = 0; char args[BCTEXTLEN];
2019 snprintf(args, sizeof(args),
2020 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
2021 st->time_base.num, st->time_base.den, src_ctx->sample_rate,
2022 av_get_sample_fmt_name(src_ctx->sample_fmt), src_ctx->channel_layout);
2024 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2025 args, NULL, filter_graph);
2027 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2028 NULL, NULL, filter_graph);
2030 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
2031 (uint8_t*)&sink_ctx->sample_fmt, sizeof(sink_ctx->sample_fmt),
2032 AV_OPT_SEARCH_CHILDREN);
2034 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
2035 (uint8_t*)&sink_ctx->channel_layout,
2036 sizeof(sink_ctx->channel_layout), AV_OPT_SEARCH_CHILDREN);
2038 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
2039 (uint8_t*)&sink_ctx->sample_rate, sizeof(sink_ctx->sample_rate),
2040 AV_OPT_SEARCH_CHILDREN);
2042 ff_err(ret, "FFAudioStream::create_filter");
2044 ret = FFStream::create_filter(filter_spec);
2045 return ret >= 0 ? 0 : 1;
2048 int FFStream::create_filter(const char *filter_spec)
2050 /* Endpoints for the filter graph. */
2051 AVFilterInOut *outputs = avfilter_inout_alloc();
2052 outputs->name = av_strdup("in");
2053 outputs->filter_ctx = buffersrc_ctx;
2054 outputs->pad_idx = 0;
2057 AVFilterInOut *inputs = avfilter_inout_alloc();
2058 inputs->name = av_strdup("out");
2059 inputs->filter_ctx = buffersink_ctx;
2060 inputs->pad_idx = 0;
2063 int ret = !outputs->name || !inputs->name ? -1 : 0;
2065 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
2066 &inputs, &outputs, NULL);
2068 ret = avfilter_graph_config(filter_graph, NULL);
2071 ff_err(ret, "FFStream::create_filter");
2072 avfilter_inout_free(&inputs);
2073 avfilter_inout_free(&outputs);
2077 void FFStream::add_bsfilter(const char *bsf, const char *ap)
2079 bsfilter.append(new BSFilter(bsf,ap));
2082 int FFStream::bs_filter(AVPacket *pkt)
2084 if( !bsfilter.size() ) return 0;
2085 av_packet_split_side_data(pkt);
2088 for( int i=0; i<bsfilter.size(); ++i ) {
2089 AVPacket bspkt = *pkt;
2090 ret = av_bitstream_filter_filter(bsfilter[i]->bsfc,
2091 st->codec, bsfilter[i]->args, &bspkt.data, &bspkt.size,
2092 pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY);
2093 if( ret < 0 ) break;
2094 int size = bspkt.size;
2095 uint8_t *data = bspkt.data;
2096 if( !ret && bspkt.data != pkt->data ) {
2098 data = (uint8_t *)av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
2099 if( !data ) { ret = AVERROR(ENOMEM); break; }
2100 memcpy(data, bspkt.data, size);
2101 memset(data+size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2105 pkt->side_data = 0; pkt->side_data_elems = 0;
2106 av_free_packet(pkt);
2107 ret = av_packet_from_data(&bspkt, data, size);
2108 if( ret < 0 ) break;
2113 ff_err(ret,"FFStream::bs_filter");