10 // work arounds (centos)
13 #define INT64_MAX 9223372036854775807LL
17 #include "bccmodels.h"
18 #include "fileffmpeg.h"
21 #include "mainerror.h"
26 #define VIDEO_INBUF_SIZE 0x10000
27 #define AUDIO_INBUF_SIZE 0x10000
28 #define VIDEO_REFILL_THRESH 0
29 #define AUDIO_REFILL_THRESH 0x1000
31 Mutex FFMPEG::fflock("FFMPEG::fflock");
33 static void ff_err(int ret, const char *msg)
35 char errmsg[BCSTRLEN]; av_strerror(ret, errmsg, sizeof(errmsg));
36 fprintf(stderr,"%s: %s\n",msg, errmsg);
52 pkt.data = 0; pkt.size = 0;
55 FFrame::FFrame(FFStream *fst)
58 frm = av_frame_alloc();
59 init = fst->init_frame(frm);
67 void FFrame::queue(int64_t pos)
73 void FFrame::dequeue()
78 int FFAudioStream::read(float *fp, long len)
86 while( --k >= 0 ) *fp++ = *op++;
87 if( op >= lmt ) op = bfr;
92 void FFAudioStream::realloc(long sz, int nch, long len)
95 float *np = new float[bsz];
96 inp = np + read(np, len) * nch;
101 delete [] bfr; bfr = np;
104 void FFAudioStream::realloc(long sz, int nch)
106 if( sz > this->sz || this->nch != nch ) {
107 long len = this->nch != nch ? 0 : curr_pos - seek_pos;
108 if( len > this->sz ) len = this->sz;
110 realloc(sz, nch, len);
114 void FFAudioStream::reserve(long sz, int nch)
116 long len = (inp - outp) / nch;
118 if( sz > this->sz || this->nch != nch ) {
119 if( this->nch != nch ) len = 0;
120 realloc(sz, nch, len);
123 if( (len*=nch) > 0 && bfr != outp )
124 memmove(bfr, outp, len*sizeof(*bfr));
129 long FFAudioStream::used()
131 long len = inp>=outp ? inp-outp : inp-bfr + lmt-outp;
134 long FFAudioStream::avail()
137 if( in1 >= lmt ) in1 = bfr;
138 long len = outp >= in1 ? outp-in1 : outp-bfr + lmt-in1;
141 void FFAudioStream::reset() // clear bfr
146 void FFAudioStream::iseek(int64_t ofs)
148 outp = inp - ofs*nch;
149 if( outp < bfr ) outp += sz*nch;
152 float *FFAudioStream::get_outp(int ofs)
159 int64_t FFAudioStream::put_inp(int ofs)
162 return (inp-outp) / nch;
165 int FFAudioStream::write(const float *fp, long len)
173 while( --k >= 0 ) *ip++ = *fp++;
174 if( ip >= lmt ) ip = bfr;
180 int FFAudioStream::zero(long len)
188 while( --k >= 0 ) *ip++ = 0;
189 if( ip >= lmt ) ip = bfr;
195 // does not advance outp
196 int FFAudioStream::read(double *dp, long len, int ch)
199 float *op = outp + ch;
200 float *lmt1 = lmt + nch-1;
202 int k = (lmt1 - op) / nch;
205 while( --k >= 0 ) { *dp++ = *op; op += nch; }
206 if( op >= lmt ) op -= sz*nch;
211 // load linear buffer, no wrapping allowed, does not advance inp
212 int FFAudioStream::write(const double *dp, long len, int ch)
215 float *ip = inp + ch;
216 while( --n >= 0 ) { *ip = *dp++; ip += nch; }
221 FFStream::FFStream(FFMPEG *ffmpeg, AVStream *st, int idx)
223 this->ffmpeg = ffmpeg;
226 frm_lock = new Mutex("FFStream::frm_lock");
232 nudge = AV_NOPTS_VALUE;
234 reading = writing = 0;
240 FFStream::~FFStream()
242 if( reading > 0 || writing > 0 ) avcodec_close(st->codec);
243 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
244 while( frms.first ) frms.remove(frms.first);
245 if( filter_graph ) avfilter_graph_free(&filter_graph);
246 if( frame ) av_frame_free(&frame);
247 if( fframe ) av_frame_free(&fframe);
248 bsfilter.remove_all_objects();
252 void FFStream::ff_lock(const char *cp)
254 FFMPEG::fflock.lock(cp);
257 void FFStream::ff_unlock()
259 FFMPEG::fflock.unlock();
262 void FFStream::queue(FFrame *frm)
264 frm_lock->lock("FFStream::queue");
268 ffmpeg->mux_lock->unlock();
271 void FFStream::dequeue(FFrame *frm)
273 frm_lock->lock("FFStream::dequeue");
275 frms.remove_pointer(frm);
279 int FFStream::encode_activate()
282 writing = ffmpeg->encode_activate();
286 int FFStream::decode_activate()
288 if( reading < 0 && (reading=ffmpeg->decode_activate()) > 0 ) {
289 ff_lock("FFStream::decode_activate");
291 AVDictionary *copts = 0;
292 av_dict_copy(&copts, ffmpeg->opts, 0);
294 // this should be avformat_copy_context(), but no copy avail
295 ret = avformat_open_input(&fmt_ctx, ffmpeg->fmt_ctx->filename, NULL, &copts);
297 ret = avformat_find_stream_info(fmt_ctx, 0);
298 st = fmt_ctx->streams[idx];
301 AVCodecID codec_id = st->codec->codec_id;
302 AVCodec *decoder = avcodec_find_decoder(codec_id);
303 ret = avcodec_open2(st->codec, decoder, &copts);
307 eprintf("FFStream::decode_activate: open decoder failed\n");
310 eprintf("FFStream::decode_activate: can't clone input file\n");
311 av_dict_free(&copts);
317 int FFStream::read_packet()
319 av_packet_unref(ipkt);
320 int ret = av_read_frame(fmt_ctx, ipkt);
321 if( ret >= 0 ) return 1;
323 if( ret == AVERROR_EOF ) return 0;
324 fprintf(stderr, "FFStream::read_packet: av_read_frame failed\n");
329 int FFStream::decode(AVFrame *frame)
335 while( ret >= 0 && !flushed && --retries >= 0 && !got_frame ) {
340 if( !ret ) ipkt->stream_index = st->index;
342 if( ipkt->stream_index == st->index ) {
343 while( (ipkt->size > 0 || !ipkt->data) && !got_frame ) {
344 ret = decode_frame(frame, got_frame);
345 if( ret < 0 || !ipkt->data ) break;
358 fprintf(stderr, "FFStream::decode: Retry limit\n");
362 fprintf(stderr, "FFStream::decode: failed\n");
367 int FFStream::load_filter(AVFrame *frame)
369 int ret = av_buffersrc_add_frame_flags(buffersrc_ctx,
370 frame, AV_BUFFERSRC_FLAG_KEEP_REF);
372 av_frame_unref(frame);
373 eprintf("FFStream::load_filter: av_buffersrc_add_frame_flags failed\n");
378 int FFStream::read_filter(AVFrame *frame)
380 int ret = av_buffersink_get_frame(buffersink_ctx, frame);
382 if( ret == AVERROR(EAGAIN) ) return 0;
383 if( ret == AVERROR_EOF ) { st_eof(1); return -1; }
384 fprintf(stderr, "FFStream::read_filter: av_buffersink_get_frame failed\n");
390 int FFStream::read_frame(AVFrame *frame)
392 if( !filter_graph || !buffersrc_ctx || !buffersink_ctx )
393 return decode(frame);
394 if( !fframe && !(fframe=av_frame_alloc()) ) {
395 fprintf(stderr, "FFStream::read_frame: av_frame_alloc failed\n");
399 while( !flushed && !(ret=read_filter(frame)) ) {
400 if( (ret=decode(fframe)) < 0 ) break;
401 if( ret > 0 && (ret=load_filter(fframe)) < 0 ) break;
406 FFAudioStream::FFAudioStream(FFMPEG *ffmpeg, AVStream *strm, int idx)
407 : FFStream(ffmpeg, strm, idx)
409 channel0 = channels = 0;
412 seek_pos = curr_pos = 0;
414 resample_context = 0;
423 bfr = new float[bsz];
428 FFAudioStream::~FFAudioStream()
430 if( resample_context ) swr_free(&resample_context);
435 int FFAudioStream::load_history(uint8_t **data, int len)
437 float *samples = *(float **)data;
438 if( resample_context ) {
439 if( len > aud_bfr_sz ) {
445 aud_bfr = new float[aud_bfr_sz*channels];
447 int ret = swr_convert(resample_context,
448 (uint8_t**)&aud_bfr, aud_bfr_sz, (const uint8_t**)data, len);
450 fprintf(stderr, "FFAudioStream::load_history: swr_convert failed\n");
456 // biggest user bfr since seek + frame
457 realloc(mbsz + len + 1, channels);
462 int FFAudioStream::decode_frame(AVFrame *frame, int &got_frame)
464 int ret = avcodec_decode_audio4(st->codec, frame, &got_frame, ipkt);
466 fprintf(stderr, "FFAudioStream::decode_frame: Could not read audio frame\n");
472 int FFAudioStream::encode_activate()
474 if( writing >= 0 ) return writing;
475 AVCodecContext *ctx = st->codec;
476 frame_sz = ctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE ?
477 10000 : ctx->frame_size;
478 return FFStream::encode_activate();
481 int FFAudioStream::nb_samples()
483 AVCodecContext *ctx = st->codec;
484 return ctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE ?
485 10000 : ctx->frame_size;
488 int64_t FFAudioStream::load_buffer(double ** const sp, int len)
490 reserve(len+1, st->codec->channels);
491 for( int ch=0; ch<nch; ++ch )
492 write(sp[ch], len, ch);
496 int FFAudioStream::in_history(int64_t pos)
498 if( pos > curr_pos ) return 0;
499 int64_t len = curr_pos - seek_pos;
500 if( len > sz ) len = sz;
501 if( pos < curr_pos - len ) return 0;
506 int FFAudioStream::init_frame(AVFrame *frame)
508 AVCodecContext *ctx = st->codec;
509 frame->nb_samples = frame_sz;
510 frame->format = ctx->sample_fmt;
511 frame->channel_layout = ctx->channel_layout;
512 frame->sample_rate = ctx->sample_rate;
513 int ret = av_frame_get_buffer(frame, 0);
515 fprintf(stderr, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
519 int FFAudioStream::load(int64_t pos, int len)
521 if( audio_seek(pos) < 0 ) return -1;
522 if( mbsz < len ) mbsz = len;
524 int64_t end_pos = pos + len;
525 if( !frame && !(frame=av_frame_alloc()) ) {
526 fprintf(stderr, "FFAudioStream::load: av_frame_alloc failed\n");
529 for( int i=0; ret>=0 && !flushed && curr_pos<end_pos && i<1000; ++i ) {
530 ret = read_frame(frame);
532 load_history(&frame->extended_data[0], frame->nb_samples);
533 curr_pos += frame->nb_samples;
536 if( flushed && end_pos > curr_pos ) {
537 zero(end_pos - curr_pos);
540 return curr_pos - pos;
543 int FFAudioStream::audio_seek(int64_t pos)
545 if( decode_activate() < 0 ) return -1;
546 if( in_history(pos) ) {
547 iseek(curr_pos - pos);
550 if( pos == curr_pos ) return 0;
551 avcodec_flush_buffers(st->codec);
552 double secs = (double)pos / sample_rate;
553 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
554 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
555 avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, tstmp, INT64_MAX, 0);
556 seek_pos = curr_pos = pos;
558 mbsz = 0; flushed = 0; need_packet = 1;
562 int FFAudioStream::encode(double **samples, int len)
564 if( encode_activate() <= 0 ) return -1;
567 int64_t count = load_buffer(samples, len);
570 while( ret >= 0 && count >= frame_sz ) {
571 frm = new FFrame(this);
572 if( (ret=frm->initted()) < 0 ) break;
573 AVFrame *frame = *frm;
574 float *bfrp = get_outp(frame_sz);
575 ret = swr_convert(resample_context,
576 (uint8_t **)frame->extended_data, frame_sz,
577 (const uint8_t **)&bfrp, frame_sz);
579 fprintf(stderr, "FFAudioStream::encode: swr_convert failed\n");
582 frm->queue(curr_pos);
584 curr_pos += frame_sz;
589 return ret >= 0 ? 0 : 1;
592 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx)
593 : FFStream(ffmpeg, strm, idx)
598 seek_pos = curr_pos = 0;
603 FFVideoStream::~FFVideoStream()
605 if( convert_ctx ) sws_freeContext(convert_ctx);
608 int FFVideoStream::decode_frame(AVFrame *frame, int &got_frame)
610 int ret = avcodec_decode_video2(st->codec, frame, &got_frame, ipkt);
612 fprintf(stderr, "FFVideoStream::decode_frame: Could not read video frame\n");
620 int FFVideoStream::load(VFrame *vframe, int64_t pos)
622 if( video_seek(pos) < 0 ) return -1;
623 if( !frame && !(frame=av_frame_alloc()) ) {
624 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
628 for( int i=0; ret>=0 && !flushed && curr_pos<=pos && i<1000; ++i ) {
629 ret = read_frame(frame);
632 AVCodecContext *ctx = st->codec;
633 ret = convert_cmodel(vframe, (AVPicture *)frame,
634 ctx->pix_fmt, ctx->width, ctx->height);
636 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
640 int FFVideoStream::video_seek(int64_t pos)
642 if( decode_activate() < 0 ) return -1;
643 // if close enough, just read up to current
644 // 3*gop_size seems excessive, but less causes tears
645 int gop = 3*st->codec->gop_size;
646 if( gop < 4 ) gop = 4;
647 if( gop > 64 ) gop = 64;
648 if( pos >= curr_pos && pos <= curr_pos + gop ) return 0;
649 avcodec_flush_buffers(st->codec);
650 // back up a few frames to read up to current to help repair damages
651 if( (pos-=gop) < 0 ) pos = 0;
652 double secs = (double)pos / frame_rate;
653 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
654 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
655 avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, tstmp, INT64_MAX, 0);
656 seek_pos = curr_pos = pos;
658 flushed = 0; need_packet = 1;
662 int FFVideoStream::init_frame(AVFrame *picture)
664 AVCodecContext *ctx = st->codec;
665 picture->format = ctx->pix_fmt;
666 picture->width = ctx->width;
667 picture->height = ctx->height;
668 int ret = av_frame_get_buffer(picture, 32);
672 int FFVideoStream::encode(VFrame *vframe)
674 if( encode_activate() <= 0 ) return -1;
676 FFrame *picture = new FFrame(this);
677 int ret = picture->initted();
679 AVFrame *frame = *picture;
680 frame->pts = curr_pos;
681 AVCodecContext *ctx = st->codec;
682 ret = convert_pixfmt(vframe, (AVPicture*)frame,
683 ctx->pix_fmt, ctx->width, ctx->height);
686 picture->queue(curr_pos);
690 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
693 return ret >= 0 ? 0 : 1;
697 PixelFormat FFVideoStream::color_model_to_pix_fmt(int color_model)
699 switch( color_model ) {
700 case BC_YUV422: return AV_PIX_FMT_YUYV422;
701 case BC_RGB888: return AV_PIX_FMT_RGB24;
702 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
703 case BC_BGR8888: return AV_PIX_FMT_BGR0;
704 case BC_BGR888: return AV_PIX_FMT_BGR24;
705 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
706 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
707 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
708 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
709 case BC_RGB565: return AV_PIX_FMT_RGB565;
710 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
711 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
715 return AV_PIX_FMT_NB;
718 int FFVideoStream::pix_fmt_to_color_model(PixelFormat pix_fmt)
721 case AV_PIX_FMT_YUYV422: return BC_YUV422;
722 case AV_PIX_FMT_RGB24: return BC_RGB888;
723 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
724 case AV_PIX_FMT_BGR0: return BC_BGR8888;
725 case AV_PIX_FMT_BGR24: return BC_BGR888;
726 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
727 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
728 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
729 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
730 case AV_PIX_FMT_RGB565: return BC_RGB565;
731 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
732 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
736 return BC_TRANSPARENCY;
739 int FFVideoStream::convert_picture_vframe(VFrame *frame,
740 AVPicture *ip, PixelFormat ifmt, int iw, int ih)
743 int cmodel = frame->get_color_model();
744 PixelFormat ofmt = color_model_to_pix_fmt(cmodel);
745 if( ofmt == AV_PIX_FMT_NB ) return -1;
746 int size = avpicture_fill(&opic, frame->get_data(), ofmt,
747 frame->get_w(), frame->get_h());
748 if( size < 0 ) return -1;
750 // transfer line sizes must match also
751 int planar = BC_CModels::is_planar(cmodel);
752 int packed_width = !planar ? frame->get_bytes_per_line() :
753 BC_CModels::calculate_pixelsize(cmodel) * frame->get_w();
754 if( packed_width != opic.linesize[0] ) return -1;
757 // override avpicture_fill() for planar types
758 opic.data[0] = frame->get_y();
759 opic.data[1] = frame->get_u();
760 opic.data[2] = frame->get_v();
763 convert_ctx = sws_getCachedContext(convert_ctx, iw, ih, ifmt,
764 frame->get_w(), frame->get_h(), ofmt, SWS_BICUBIC, NULL, NULL, NULL);
766 fprintf(stderr, "FFVideoStream::convert_picture_frame:"
767 " sws_getCachedContext() failed\n");
770 if( sws_scale(convert_ctx, ip->data, ip->linesize, 0, ih,
771 opic.data, opic.linesize) < 0 ) {
772 fprintf(stderr, "FFVideoStream::convert_picture_frame: sws_scale() failed\n");
778 int FFVideoStream::convert_cmodel(VFrame *frame,
779 AVPicture *ip, PixelFormat ifmt, int iw, int ih)
781 // try direct transfer
782 if( !convert_picture_vframe(frame, ip, ifmt, iw, ih) ) return 1;
783 // use indirect transfer
784 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
786 for( int i = 0; i <desc->nb_components; ++i ) {
787 int bits = desc->comp[i].depth_minus1 + 1;
788 if( bits > max_bits ) max_bits = bits;
790 // from libavcodec/pixdesc.c
791 #define pixdesc_has_alpha(pixdesc) ((pixdesc)->nb_components == 2 || \
792 (pixdesc)->nb_components == 4 || (pixdesc)->flags & AV_PIX_FMT_FLAG_PAL)
793 int icolor_model = pixdesc_has_alpha(desc) ?
794 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
795 (max_bits > 8 ? BC_RGB161616 : BC_RGB888) ;
796 VFrame vframe(iw, ih, icolor_model);
797 if( convert_picture_vframe(&vframe, ip, ifmt, iw, ih) ) return -1;
798 frame->transfer_from(&vframe);
802 int FFVideoStream::convert_vframe_picture(VFrame *frame,
803 AVPicture *op, PixelFormat ofmt, int ow, int oh)
806 int cmodel = frame->get_color_model();
807 PixelFormat ifmt = color_model_to_pix_fmt(cmodel);
808 if( ifmt == AV_PIX_FMT_NB ) return -1;
809 int size = avpicture_fill(&opic, frame->get_data(), ifmt,
810 frame->get_w(), frame->get_h());
811 if( size < 0 ) return -1;
813 // transfer line sizes must match also
814 int planar = BC_CModels::is_planar(cmodel);
815 int packed_width = !planar ? frame->get_bytes_per_line() :
816 BC_CModels::calculate_pixelsize(cmodel) * frame->get_w();
817 if( packed_width != opic.linesize[0] ) return -1;
820 // override avpicture_fill() for planar types
821 opic.data[0] = frame->get_y();
822 opic.data[1] = frame->get_u();
823 opic.data[2] = frame->get_v();
826 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(), ifmt,
827 ow, oh, ofmt, SWS_BICUBIC, NULL, NULL, NULL);
829 fprintf(stderr, "FFVideoStream::convert_frame_picture:"
830 " sws_getCachedContext() failed\n");
833 if( sws_scale(convert_ctx, opic.data, opic.linesize, 0, frame->get_h(),
834 op->data, op->linesize) < 0 ) {
835 fprintf(stderr, "FFVideoStream::convert_frame_picture: sws_scale() failed\n");
841 int FFVideoStream::convert_pixfmt(VFrame *frame,
842 AVPicture *op, PixelFormat ofmt, int ow, int oh)
844 // try direct transfer
845 if( !convert_vframe_picture(frame, op, ofmt, ow, oh) ) return 0;
846 // use indirect transfer
847 int colormodel = frame->get_color_model();
848 int bits = BC_CModels::calculate_pixelsize(colormodel) * 8;
849 bits /= BC_CModels::components(colormodel);
850 int icolor_model = BC_CModels::has_alpha(colormodel) ?
851 (bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
852 (bits > 8 ? BC_RGB161616: BC_RGB888) ;
853 VFrame vframe(frame->get_w(), frame->get_h(), icolor_model);
854 vframe.transfer_from(frame);
855 if( convert_vframe_picture(&vframe, op, ofmt, ow, oh) ) return 1;
860 FFMPEG::FFMPEG(FileBase *file_base)
863 this->file_base = file_base;
864 memset(file_format,0,sizeof(file_format));
865 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
866 flow_lock = new Condition(1,"FFStream::flow_lock",0);
869 decoding = encoding = 0;
870 has_audio = has_video = 0;
873 opt_video_filter = 0;
874 opt_audio_filter = 0;
875 char option_path[BCTEXTLEN];
876 set_option_path(option_path, "%s", "ffmpeg.opts");
877 read_options(option_path, opts);
882 ff_lock("FFMPEG::~FFMPEG()");
884 ffaudio.remove_all_objects();
885 ffvideo.remove_all_objects();
886 if( encoding ) avformat_free_context(fmt_ctx);
891 delete opt_video_filter;
892 delete opt_audio_filter;
895 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
897 const int *p = codec->supported_samplerates;
898 if( !p ) return sample_rate;
900 if( *p == sample_rate ) return *p;
906 static inline AVRational std_frame_rate(int i)
908 static const int m1 = 1001*12, m2 = 1000*12;
909 static const int freqs[] = {
910 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
911 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
913 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
914 return (AVRational) { freq, 1001*12 };
917 AVRational FFMPEG::check_frame_rate(AVCodec *codec, double frame_rate)
919 const AVRational *p = codec->supported_framerates;
920 AVRational rate, best_rate = (AVRational) { 0, 0 };
921 double max_err = 1.; int i = 0;
922 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
923 double framerate = (double) rate.num / rate.den;
924 double err = fabs(frame_rate/framerate - 1.);
925 if( err >= max_err ) continue;
929 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
932 AVRational FFMPEG::to_sample_aspect_ratio(double aspect_ratio)
934 int height = 1000000, width = height * aspect_ratio;
936 MWindow::create_aspect_ratio(w, h, width, height);
937 return (AVRational){(int)w, (int)h};
940 AVRational FFMPEG::to_time_base(int sample_rate)
942 return (AVRational){1, sample_rate};
945 extern void get_exe_path(char *result); // from main.C
947 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
950 strcat(path, "/ffmpeg/");
951 path += strlen(path);
954 vsprintf(path, fmt, ap);
958 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
963 set_option_path(path, "%s/%s", type, spec);
966 int FFMPEG::get_format(char *format, const char *path, char *spec)
968 char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
969 get_option_path(option_path, path, spec);
970 FILE *fp = fopen(option_path,"r");
973 if( !fgets(line, sizeof(line), fp) ) ret = 1;
975 line[sizeof(line)-1] = 0;
976 ret = scan_option_line(line, format, codec);
982 int FFMPEG::get_file_format()
985 char audio_format[BCSTRLEN], video_format[BCSTRLEN];
986 file_format[0] = audio_format[0] = video_format[0] = 0;
987 Asset *asset = file_base->asset;
988 if( !ret && asset->audio_data )
989 ret = get_format(audio_format, "audio", asset->acodec);
990 if( !ret && asset->video_data )
991 ret = get_format(video_format, "video", asset->vcodec);
992 if( !ret && !audio_format[0] && !video_format[0] )
994 if( !ret && audio_format[0] && video_format[0] &&
995 strcmp(audio_format, video_format) ) ret = -1;
997 strcpy(file_format, audio_format[0] ? audio_format : video_format);
1001 int FFMPEG::scan_option_line(char *cp, char *tag, char *val)
1003 while( *cp == ' ' || *cp == '\t' ) ++cp;
1005 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' ) ++cp;
1007 if( !len || len > BCSTRLEN-1 ) return 1;
1008 while( bp < cp ) *tag++ = *bp++;
1010 while( *cp == ' ' || *cp == '\t' ) ++cp;
1011 if( *cp == '=' ) ++cp;
1012 while( *cp == ' ' || *cp == '\t' ) ++cp;
1014 while( *cp && *cp != '\n' ) ++cp;
1016 if( len > BCTEXTLEN-1 ) return 1;
1017 while( bp < cp ) *val++ = *bp++;
1022 int FFMPEG::get_encoder(const char *options,
1023 char *format, char *codec, char *bsfilter, char *bsargs)
1025 FILE *fp = fopen(options,"r");
1027 eprintf("FFMPEG::get_encoder: options open failed %s\n",options);
1030 if( get_encoder(fp, format, codec, bsfilter, bsargs) )
1031 eprintf("FFMPEG::get_encoder:"
1032 " err: format/codec not found %s\n", options);
1037 int FFMPEG::get_encoder(FILE *fp,
1038 char *format, char *codec, char *bsfilter, char *bsargs)
1040 format[0] = codec[0] = bsfilter[0] = bsargs[0] = 0;
1041 char line[BCTEXTLEN];
1042 if( !fgets(line, sizeof(line), fp) ) return 1;
1043 line[sizeof(line)-1] = 0;
1044 if( scan_option_line(line, format, codec) ) return 1;
1046 while( *cp && *cp != '|' ) ++cp;
1047 if( !*cp ) return 0;
1048 if( scan_option_line(cp+1, bsfilter, bsargs) ) return 1;
1049 do { *cp-- = 0; } while( cp>=codec && (*cp==' ' || *cp == '\t' ) );
1053 int FFMPEG::read_options(const char *options, AVDictionary *&opts)
1055 FILE *fp = fopen(options,"r");
1057 int ret = read_options(fp, options, opts);
1062 int FFMPEG::scan_options(const char *options, AVDictionary *&opts)
1064 FILE *fp = fmemopen((void *)options,strlen(options),"r");
1066 int ret = read_options(fp, options, opts);
1071 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
1073 int ret = 0, no = 0;
1074 char line[BCTEXTLEN];
1075 while( !ret && fgets(line, sizeof(line), fp) ) {
1076 line[sizeof(line)-1] = 0;
1078 if( line[0] == '#' ) continue;
1079 if( line[0] == '\n' ) continue;
1080 char key[BCSTRLEN], val[BCTEXTLEN];
1081 if( scan_option_line(line, key, val) ) {
1082 eprintf("FFMPEG::read_options:"
1083 " err reading %s: line %d\n", options, no);
1087 if( !strcmp(key, "duration") )
1088 opt_duration = strtod(val, 0);
1089 if( !strcmp(key, "video_filter") )
1090 opt_video_filter = cstrdup(val);
1091 if( !strcmp(key, "audio_filter") )
1092 opt_audio_filter = cstrdup(val);
1093 else if( !strcmp(key, "loglevel") )
1096 av_dict_set(&opts, key, val, 0);
1102 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
1104 char option_path[BCTEXTLEN];
1105 set_option_path(option_path, "%s", options);
1106 return read_options(option_path, opts);
1109 int FFMPEG::load_options(const char *path, char *bfr, int len)
1112 FILE *fp = fopen(path, "r");
1114 fgets(bfr, len, fp); // skip hdr
1115 len = fread(bfr, 1, len-1, fp);
1116 if( len < 0 ) len = 0;
1122 void FFMPEG::set_loglevel(const char *ap)
1124 if( !ap || !*ap ) return;
1129 { "quiet" , AV_LOG_QUIET },
1130 { "panic" , AV_LOG_PANIC },
1131 { "fatal" , AV_LOG_FATAL },
1132 { "error" , AV_LOG_ERROR },
1133 { "warning", AV_LOG_WARNING },
1134 { "info" , AV_LOG_INFO },
1135 { "verbose", AV_LOG_VERBOSE },
1136 { "debug" , AV_LOG_DEBUG },
1138 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
1139 if( !strcmp(log_levels[i].name, ap) ) {
1140 av_log_set_level(log_levels[i].level);
1144 av_log_set_level(atoi(ap));
1147 double FFMPEG::to_secs(int64_t time, AVRational time_base)
1149 double base_time = time == AV_NOPTS_VALUE ? 0 :
1150 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
1151 return base_time / AV_TIME_BASE;
1154 int FFMPEG::info(char *text, int len)
1156 if( len <= 0 ) return 0;
1157 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
1159 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1160 AVStream *st = fmt_ctx->streams[i];
1161 AVCodecContext *avctx = st->codec;
1162 report("stream %d, id 0x%06x:\n", i, avctx->codec_id);
1163 const AVCodecDescriptor *desc = avcodec_descriptor_get(avctx->codec_id);
1164 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1165 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
1166 double frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
1167 report(" video %s",desc ? desc->name : " (unkn)");
1168 report(" %dx%d %5.2f", avctx->width, avctx->height, frame_rate);
1169 const char *pfn = av_get_pix_fmt_name(avctx->pix_fmt);
1170 report(" pix %s\n", pfn ? pfn : "(unkn)");
1171 double secs = to_secs(st->duration, st->time_base);
1172 int64_t length = secs * frame_rate + 0.5;
1173 report(" %jd frms %0.2f secs", length, secs);
1174 int hrs = secs/3600; secs -= hrs*3600;
1175 int mins = secs/60; secs -= mins*60;
1176 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1179 else if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1180 int sample_rate = avctx->sample_rate;
1181 const char *fmt = av_get_sample_fmt_name(avctx->sample_fmt);
1182 report(" audio %s",desc ? desc->name : " (unkn)");
1183 report(" %dch %s %d",avctx->channels, fmt, sample_rate);
1184 int sample_bits = av_get_bits_per_sample(avctx->codec_id);
1185 report(" %dbits\n", sample_bits);
1186 double secs = to_secs(st->duration, st->time_base);
1187 int64_t length = secs * sample_rate + 0.5;
1188 report(" %jd smpl %0.2f secs", length, secs);
1189 int hrs = secs/3600; secs -= hrs*3600;
1190 int mins = secs/60; secs -= mins*60;
1191 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1194 report(" codec_type unknown\n");
1197 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
1198 report("program %d", i+1);
1199 AVProgram *pgrm = fmt_ctx->programs[i];
1200 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j )
1201 report(", %d", pgrm->stream_index[j]);
1205 AVDictionaryEntry *tag = 0;
1206 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
1207 report("%s=%s\n", tag->key, tag->value);
1216 int FFMPEG::init_decoder(const char *filename)
1218 ff_lock("FFMPEG::init_decoder");
1220 char file_opts[BCTEXTLEN];
1221 char *bp = strrchr(strcpy(file_opts, filename), '/');
1222 char *sp = strrchr(!bp ? file_opts : bp, '.');
1225 strcpy(sp, ".opts");
1226 fp = fopen(file_opts, "r");
1229 read_options(fp, file_opts, opts);
1233 load_options("decode.opts", opts);
1234 AVDictionary *fopts = 0;
1235 av_dict_copy(&fopts, opts, 0);
1236 int ret = avformat_open_input(&fmt_ctx, filename, NULL, &fopts);
1237 av_dict_free(&fopts);
1239 ret = avformat_find_stream_info(fmt_ctx, NULL);
1244 return !ret ? 0 : 1;
1247 int FFMPEG::open_decoder()
1250 if( stat(fmt_ctx->filename, &st) < 0 ) {
1251 eprintf("FFMPEG::open_decoder: can't stat file: %s\n",
1256 int64_t file_bits = 8 * st.st_size;
1257 if( !fmt_ctx->bit_rate && opt_duration > 0 )
1258 fmt_ctx->bit_rate = file_bits / opt_duration;
1261 if( fmt_ctx->bit_rate > 0 ) {
1262 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1263 AVStream *st = fmt_ctx->streams[i];
1264 if( st->duration != AV_NOPTS_VALUE ) continue;
1265 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
1266 st->duration = av_rescale(file_bits, st->time_base.den,
1267 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
1272 printf("FFMPEG::open_decoder: some stream times estimated\n");
1274 ff_lock("FFMPEG::open_decoder");
1276 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1277 AVStream *st = fmt_ctx->streams[i];
1278 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
1279 AVCodecContext *avctx = st->codec;
1280 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1282 FFVideoStream *vid = new FFVideoStream(this, st, i);
1283 int vidx = ffvideo.size();
1284 vstrm_index.append(ffidx(vidx, 0));
1285 ffvideo.append(vid);
1286 vid->width = avctx->width;
1287 vid->height = avctx->height;
1288 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
1289 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
1290 double secs = to_secs(st->duration, st->time_base);
1291 vid->length = secs * vid->frame_rate;
1292 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
1293 vid->nudge = st->start_time;
1295 if( opt_video_filter )
1296 vid->create_filter(opt_video_filter, avctx,avctx);
1298 else if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1300 FFAudioStream *aud = new FFAudioStream(this, st, i);
1301 int aidx = ffaudio.size();
1302 ffaudio.append(aud);
1303 aud->channel0 = astrm_index.size();
1304 aud->channels = avctx->channels;
1305 for( int ch=0; ch<aud->channels; ++ch )
1306 astrm_index.append(ffidx(aidx, ch));
1307 aud->sample_rate = avctx->sample_rate;
1308 double secs = to_secs(st->duration, st->time_base);
1309 aud->length = secs * aud->sample_rate;
1310 if( avctx->sample_fmt != AV_SAMPLE_FMT_FLT ) {
1311 uint64_t layout = av_get_default_channel_layout(avctx->channels);
1312 if( !layout ) layout = ((uint64_t)1<<aud->channels) - 1;
1313 aud->resample_context = swr_alloc_set_opts(NULL,
1314 layout, AV_SAMPLE_FMT_FLT, avctx->sample_rate,
1315 layout, avctx->sample_fmt, avctx->sample_rate,
1317 swr_init(aud->resample_context);
1319 aud->nudge = st->start_time;
1321 if( opt_audio_filter )
1322 aud->create_filter(opt_audio_filter, avctx,avctx);
1326 printf("FFMPEG::open_decoder: some stream have bad times\n");
1332 int FFMPEG::init_encoder(const char *filename)
1334 int fd = ::open(filename,O_WRONLY);
1335 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
1337 eprintf("FFMPEG::init_encoder: bad file path: %s\n", filename);
1341 int ret = get_file_format();
1343 eprintf("FFMPEG::init_encoder: bad file format: %s\n", filename);
1347 eprintf("FFMPEG::init_encoder: mismatch audio/video file format: %s\n", filename);
1350 ff_lock("FFMPEG::init_encoder");
1352 avformat_alloc_output_context2(&fmt_ctx, 0, file_format, filename);
1354 eprintf("FFMPEG::init_encoder: failed: %s\n", filename);
1359 load_options("encode.opts", opts);
1366 int FFMPEG::open_encoder(const char *type, const char *spec)
1369 Asset *asset = file_base->asset;
1370 char *filename = asset->path;
1371 AVDictionary *sopts = 0;
1372 av_dict_copy(&sopts, opts, 0);
1373 char option_path[BCTEXTLEN];
1374 set_option_path(option_path, "%s/%s.opts", type, type);
1375 read_options(option_path, sopts);
1376 get_option_path(option_path, type, spec);
1377 char format_name[BCSTRLEN], codec_name[BCTEXTLEN];
1378 char bsfilter[BCSTRLEN], bsargs[BCTEXTLEN];
1379 if( get_encoder(option_path, format_name, codec_name, bsfilter, bsargs) ) {
1380 eprintf("FFMPEG::open_encoder: get_encoder failed %s:%s\n",
1381 option_path, filename);
1386 ff_lock("FFMPEG::open_encoder");
1390 const AVCodecDescriptor *codec_desc = 0;
1391 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
1393 eprintf("FFMPEG::open_encoder: cant find codec %s:%s\n",
1394 codec_name, filename);
1398 codec_desc = avcodec_descriptor_get(codec->id);
1400 eprintf("FFMPEG::open_encoder: unknown codec %s:%s\n",
1401 codec_name, filename);
1406 st = avformat_new_stream(fmt_ctx, 0);
1408 eprintf("FFMPEG::open_encoder: cant create stream %s:%s\n",
1409 codec_name, filename);
1414 AVCodecContext *ctx = st->codec;
1415 switch( codec_desc->type ) {
1416 case AVMEDIA_TYPE_AUDIO: {
1418 eprintf("FFMPEG::open_encoder: duplicate audio %s:%s\n",
1419 codec_name, filename);
1424 if( scan_options(asset->ff_audio_options, sopts) ) {
1425 eprintf("FFMPEG::open_encoder: bad audio options %s:%s\n",
1426 codec_name, filename);
1430 if( asset->ff_audio_bitrate > 0 ) {
1432 sprintf(arg, "%d", asset->ff_audio_bitrate);
1433 av_dict_set(&sopts, "b", arg, 0);
1435 int aidx = ffaudio.size();
1436 int idx = aidx + ffvideo.size();
1437 FFAudioStream *aud = new FFAudioStream(this, st, idx);
1438 ffaudio.append(aud); fst = aud;
1439 aud->sample_rate = asset->sample_rate;
1440 ctx->channels = aud->channels = asset->channels;
1441 for( int ch=0; ch<aud->channels; ++ch )
1442 astrm_index.append(ffidx(aidx, ch));
1443 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
1444 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
1445 if( !ctx->sample_rate ) {
1446 eprintf("FFMPEG::open_audio_encode:"
1447 " check_sample_rate failed %s\n", filename);
1451 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
1452 ctx->sample_fmt = codec->sample_fmts[0];
1453 uint64_t layout = av_get_default_channel_layout(ctx->channels);
1454 aud->resample_context = swr_alloc_set_opts(NULL,
1455 layout, ctx->sample_fmt, aud->sample_rate,
1456 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
1458 swr_init(aud->resample_context);
1461 case AVMEDIA_TYPE_VIDEO: {
1463 eprintf("FFMPEG::open_encoder: duplicate video %s:%s\n",
1464 codec_name, filename);
1469 if( scan_options(asset->ff_video_options, sopts) ) {
1470 eprintf("FFMPEG::open_encoder: bad video options %s:%s\n",
1471 codec_name, filename);
1475 if( asset->ff_video_bitrate > 0 ) {
1477 sprintf(arg, "%d", asset->ff_video_bitrate);
1478 av_dict_set(&sopts, "b", arg, 0);
1480 else if( asset->ff_video_quality > 0 ) {
1481 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
1482 ctx->qmin = ctx->qmax = asset->ff_video_quality;
1483 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
1484 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
1485 ctx->flags |= CODEC_FLAG_QSCALE;
1487 av_dict_set(&sopts, "flags", "+qscale", 0);
1488 sprintf(arg, "%d", asset->ff_video_quality);
1489 av_dict_set(&sopts, "qscale", arg, 0);
1490 sprintf(arg, "%d", ctx->global_quality);
1491 av_dict_set(&sopts, "global_quality", arg, 0);
1493 int vidx = ffvideo.size();
1494 int idx = vidx + ffaudio.size();
1495 FFVideoStream *vid = new FFVideoStream(this, st, idx);
1496 vstrm_index.append(ffidx(vidx, 0));
1497 ffvideo.append(vid); fst = vid;
1498 vid->width = asset->width;
1499 ctx->width = (vid->width+3) & ~3;
1500 vid->height = asset->height;
1501 ctx->height = (vid->height+3) & ~3;
1502 vid->frame_rate = asset->frame_rate;
1503 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset->aspect_ratio);
1504 ctx->pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
1505 AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
1506 if( !frame_rate.num || !frame_rate.den ) {
1507 eprintf("FFMPEG::open_audio_encode:"
1508 " check_frame_rate failed %s\n", filename);
1512 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
1513 st->time_base = ctx->time_base;
1517 eprintf("FFMPEG::open_encoder: not audio/video, %s:%s\n",
1518 codec_name, filename);
1523 ret = avcodec_open2(st->codec, codec, &sopts);
1525 ff_err(ret,"FFMPEG::open_encoder");
1526 eprintf("FFMPEG::open_encoder: open failed %s:%s\n",
1527 codec_name, filename);
1534 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
1535 st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
1536 if( fst && bsfilter[0] )
1537 fst->add_bsfilter(bsfilter, !bsargs[0] ? 0 : bsargs);
1541 av_dict_free(&sopts);
1545 int FFMPEG::close_encoder()
1548 if( encoding > 0 ) {
1549 av_write_trailer(fmt_ctx);
1550 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
1551 avio_closep(&fmt_ctx->pb);
1557 int FFMPEG::decode_activate()
1559 if( decoding < 0 ) {
1561 int npgrms = fmt_ctx->nb_programs;
1562 for( int i=0; i<npgrms; ++i ) {
1563 AVProgram *pgrm = fmt_ctx->programs[i];
1564 // first start time video stream
1565 int64_t vstart_time = -1;
1566 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1567 int st_idx = pgrm->stream_index[j];
1568 AVStream *st = fmt_ctx->streams[st_idx];
1569 AVCodecContext *avctx = st->codec;
1570 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1571 if( st->start_time == AV_NOPTS_VALUE ) continue;
1572 vstart_time = st->start_time;
1576 // max start time audio stream
1577 int64_t astart_time = -1;
1578 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1579 int st_idx = pgrm->stream_index[j];
1580 AVStream *st = fmt_ctx->streams[st_idx];
1581 AVCodecContext *avctx = st->codec;
1582 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1583 if( st->start_time == AV_NOPTS_VALUE ) continue;
1584 if( astart_time > st->start_time ) continue;
1585 astart_time = st->start_time;
1588 if( astart_time < 0 || vstart_time < 0 ) continue;
1589 // match program streams to max start_time
1590 int64_t nudge = vstart_time > astart_time ? vstart_time : astart_time;
1591 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1592 int st_idx = pgrm->stream_index[j];
1593 AVStream *st = fmt_ctx->streams[st_idx];
1594 AVCodecContext *avctx = st->codec;
1595 if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1596 for( int k=0; k<ffaudio.size(); ++k ) {
1597 if( ffaudio[k]->idx == st_idx )
1598 ffaudio[k]->nudge = nudge;
1601 else if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1602 for( int k=0; k<ffvideo.size(); ++k ) {
1603 if( ffvideo[k]->idx == st_idx )
1604 ffvideo[k]->nudge = nudge;
1609 int64_t vstart_time = 0, astart_time = 0;
1610 int nstreams = fmt_ctx->nb_streams;
1611 for( int i=0; i<nstreams; ++i ) {
1612 AVStream *st = fmt_ctx->streams[i];
1613 AVCodecContext *avctx = st->codec;
1614 switch( avctx->codec_type ) {
1615 case AVMEDIA_TYPE_VIDEO:
1616 if( st->start_time == AV_NOPTS_VALUE ) continue;
1617 if( vstart_time >= st->start_time ) continue;
1618 vstart_time = st->start_time;
1620 case AVMEDIA_TYPE_AUDIO:
1621 if( st->start_time == AV_NOPTS_VALUE ) continue;
1622 if( astart_time >= st->start_time ) continue;
1623 astart_time = st->start_time;
1627 int64_t nudge = vstart_time > astart_time ? vstart_time : astart_time;
1628 for( int k=0; k<ffvideo.size(); ++k ) {
1629 if( ffvideo[k]->nudge != AV_NOPTS_VALUE ) continue;
1630 ffvideo[k]->nudge = nudge;
1632 for( int k=0; k<ffaudio.size(); ++k ) {
1633 if( ffaudio[k]->nudge != AV_NOPTS_VALUE ) continue;
1634 ffaudio[k]->nudge = nudge;
1641 int FFMPEG::encode_activate()
1643 if( encoding < 0 ) {
1645 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
1646 avio_open(&fmt_ctx->pb, fmt_ctx->filename, AVIO_FLAG_WRITE) < 0 ) {
1647 fprintf(stderr, "FFMPEG::encode_activate: err opening : %s\n",
1652 AVDictionary *fopts = 0;
1653 char option_path[BCTEXTLEN];
1654 set_option_path(option_path, "format/%s", file_format);
1655 read_options(option_path, fopts);
1656 int ret = avformat_write_header(fmt_ctx, &fopts);
1657 av_dict_free(&fopts);
1659 fprintf(stderr, "FFMPEG::encode_activate: write header failed %s\n",
1668 int FFMPEG::audio_seek(int stream, int64_t pos)
1670 int aidx = astrm_index[stream].st_idx;
1671 FFAudioStream *aud = ffaudio[aidx];
1672 aud->audio_seek(pos);
1673 aud->seek_pos = aud->curr_pos = pos;
1677 int FFMPEG::video_seek(int stream, int64_t pos)
1679 int vidx = vstrm_index[stream].st_idx;
1680 FFVideoStream *vid = ffvideo[vidx];
1681 vid->video_seek(pos);
1682 vid->seek_pos = vid->curr_pos = pos;
1687 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
1689 if( !has_audio || chn >= astrm_index.size() ) return -1;
1690 int aidx = astrm_index[chn].st_idx;
1691 FFAudioStream *aud = ffaudio[aidx];
1692 if( aud->load(pos, len) < len ) return -1;
1693 int ch = astrm_index[chn].st_ch;
1694 return aud->read(samples,len,ch);
1697 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
1699 if( !has_video || layer >= vstrm_index.size() ) return -1;
1700 int vidx = vstrm_index[layer].st_idx;
1701 FFVideoStream *vid = ffvideo[vidx];
1702 return vid->load(vframe, pos);
1705 int FFMPEG::encode(int stream, double **samples, int len)
1707 FFAudioStream *aud = ffaudio[stream];
1708 return aud->encode(samples, len);
1712 int FFMPEG::encode(int stream, VFrame *frame)
1714 FFVideoStream *vid = ffvideo[stream];
1715 return vid->encode(frame);
1718 void FFMPEG::start_muxer()
1726 void FFMPEG::stop_muxer()
1735 void FFMPEG::flow_off()
1738 flow_lock->lock("FFMPEG::flow_off");
1742 void FFMPEG::flow_on()
1746 flow_lock->unlock();
1749 void FFMPEG::flow_ctl()
1752 flow_lock->lock("FFMPEG::flow_ctl");
1753 flow_lock->unlock();
1757 int FFMPEG::mux_audio(FFrame *frm)
1760 AVStream *st = frm->fst->st;
1761 AVCodecContext *ctx = st->codec;
1762 AVFrame *frame = *frm;
1763 AVRational tick_rate = {1, ctx->sample_rate};
1764 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
1766 int ret = avcodec_encode_audio2(ctx, pkt, frame, &got_packet);
1767 if( ret >= 0 && got_packet ) {
1768 frm->fst->bs_filter(pkt);
1769 av_packet_rescale_ts(pkt, ctx->time_base, st->time_base);
1770 pkt->stream_index = st->index;
1771 ret = av_interleaved_write_frame(fmt_ctx, pkt);
1774 ff_err(ret, "FFMPEG::mux_audio");
1775 return ret >= 0 ? 0 : 1;
1778 int FFMPEG::mux_video(FFrame *frm)
1781 AVStream *st = frm->fst->st;
1782 AVFrame *frame = *frm;
1783 frame->pts = frm->position;
1784 int ret = 1, got_packet = 0;
1785 if( fmt_ctx->oformat->flags & AVFMT_RAWPICTURE ) {
1786 /* a hack to avoid data copy with some raw video muxers */
1787 pkt->flags |= AV_PKT_FLAG_KEY;
1788 pkt->stream_index = st->index;
1789 AVPicture *picture = (AVPicture *)frame;
1790 pkt->data = (uint8_t *)picture;
1791 pkt->size = sizeof(AVPicture);
1792 pkt->pts = pkt->dts = frame->pts;
1796 ret = avcodec_encode_video2(st->codec, pkt, frame, &got_packet);
1797 if( ret >= 0 && got_packet ) {
1798 frm->fst->bs_filter(pkt);
1799 av_packet_rescale_ts(pkt, st->codec->time_base, st->time_base);
1800 pkt->stream_index = st->index;
1801 ret = av_interleaved_write_frame(fmt_ctx, pkt);
1804 ff_err(ret, "FFMPEG::mux_video");
1805 return ret >= 0 ? 0 : 1;
1811 double atm = -1, vtm = -1;
1812 FFrame *afrm = 0, *vfrm = 0;
1814 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
1815 FFStream *fst = ffaudio[i];
1816 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
1817 FFrame *frm = fst->frms.first;
1818 if( !frm ) { if( !done ) return; continue; }
1819 double tm = to_secs(frm->position, fst->st->codec->time_base);
1820 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
1822 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
1823 FFStream *fst = ffvideo[i];
1824 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
1825 FFrame *frm = fst->frms.first;
1826 if( !frm ) { if( !done ) return; continue; }
1827 double tm = to_secs(frm->position, fst->st->codec->time_base);
1828 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
1830 if( !demand ) flow_off();
1831 if( !afrm && !vfrm ) break;
1832 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
1833 vfrm->position, vfrm->fst->st->codec->time_base,
1834 afrm->position, afrm->fst->st->codec->time_base);
1835 FFrame *frm = v <= 0 ? vfrm : afrm;
1836 if( frm == afrm ) mux_audio(frm);
1837 if( frm == vfrm ) mux_video(frm);
1846 mux_lock->lock("FFMPEG::run");
1853 int FFMPEG::ff_total_audio_channels()
1855 return astrm_index.size();
1858 int FFMPEG::ff_total_astreams()
1860 return ffaudio.size();
1863 int FFMPEG::ff_audio_channels(int stream)
1865 return ffaudio[stream]->channels;
1868 int FFMPEG::ff_sample_rate(int stream)
1870 return ffaudio[stream]->sample_rate;
1873 const char* FFMPEG::ff_audio_format(int stream)
1875 AVStream *st = ffaudio[stream]->st;
1876 AVCodecID id = st->codec->codec_id;
1877 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
1878 return desc ? desc->name : "Unknown";
1881 int FFMPEG::ff_audio_pid(int stream)
1883 return ffaudio[stream]->st->id;
1886 int64_t FFMPEG::ff_audio_samples(int stream)
1888 return ffaudio[stream]->length;
1891 // find audio astream/channels with this program,
1892 // or all program audio channels (astream=-1)
1893 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
1897 int vidx = ffvideo[vstream]->idx;
1898 // find first program with this video stream
1899 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
1900 AVProgram *pgrm = fmt_ctx->programs[i];
1901 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
1902 int st_idx = pgrm->stream_index[j];
1903 AVStream *st = fmt_ctx->streams[st_idx];
1904 if( st->codec->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
1905 if( st_idx == vidx ) pidx = i;
1908 if( pidx < 0 ) return -1;
1910 int64_t channels = 0;
1911 AVProgram *pgrm = fmt_ctx->programs[pidx];
1912 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1913 int aidx = pgrm->stream_index[j];
1914 AVStream *st = fmt_ctx->streams[aidx];
1915 if( st->codec->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
1916 if( astream > 0 ) { --astream; continue; }
1918 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
1919 if( ffaudio[i]->idx == aidx ) astrm = i;
1921 if( ret < 0 ) ret = astrm;
1922 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
1923 channels |= mask << ffaudio[astrm]->channel0;
1925 if( !astream ) break;
1927 channel_mask = channels;
1932 int FFMPEG::ff_total_video_layers()
1934 return vstrm_index.size();
1937 int FFMPEG::ff_total_vstreams()
1939 return ffvideo.size();
1942 int FFMPEG::ff_video_width(int stream)
1944 return ffvideo[stream]->width;
1947 int FFMPEG::ff_video_height(int stream)
1949 return ffvideo[stream]->height;
1952 int FFMPEG::ff_set_video_width(int stream, int width)
1954 int w = ffvideo[stream]->width;
1955 ffvideo[stream]->width = width;
1959 int FFMPEG::ff_set_video_height(int stream, int height)
1961 int h = ffvideo[stream]->height;
1962 ffvideo[stream]->height = height;
1966 int FFMPEG::ff_coded_width(int stream)
1968 AVStream *st = ffvideo[stream]->st;
1969 return st->codec->coded_width;
1972 int FFMPEG::ff_coded_height(int stream)
1974 AVStream *st = ffvideo[stream]->st;
1975 return st->codec->coded_height;
1978 float FFMPEG::ff_aspect_ratio(int stream)
1980 return ffvideo[stream]->aspect_ratio;
1983 const char* FFMPEG::ff_video_format(int stream)
1985 AVStream *st = ffvideo[stream]->st;
1986 AVCodecID id = st->codec->codec_id;
1987 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
1988 return desc ? desc->name : "Unknown";
1991 double FFMPEG::ff_frame_rate(int stream)
1993 return ffvideo[stream]->frame_rate;
1996 int64_t FFMPEG::ff_video_frames(int stream)
1998 return ffvideo[stream]->length;
2001 int FFMPEG::ff_video_pid(int stream)
2003 return ffvideo[stream]->st->id;
2007 int FFMPEG::ff_cpus()
2009 return file_base->file->cpus;
2012 int FFVideoStream::create_filter(const char *filter_spec,
2013 AVCodecContext *src_ctx, AVCodecContext *sink_ctx)
2015 avfilter_register_all();
2016 filter_graph = avfilter_graph_alloc();
2017 AVFilter *buffersrc = avfilter_get_by_name("buffer");
2018 AVFilter *buffersink = avfilter_get_by_name("buffersink");
2020 int ret = 0; char args[BCTEXTLEN];
2021 snprintf(args, sizeof(args),
2022 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
2023 src_ctx->width, src_ctx->height, src_ctx->pix_fmt,
2024 st->time_base.num, st->time_base.den,
2025 src_ctx->sample_aspect_ratio.num, src_ctx->sample_aspect_ratio.den);
2027 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2028 args, NULL, filter_graph);
2030 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2031 NULL, NULL, filter_graph);
2033 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
2034 (uint8_t*)&sink_ctx->pix_fmt, sizeof(sink_ctx->pix_fmt),
2035 AV_OPT_SEARCH_CHILDREN);
2037 ff_err(ret, "FFVideoStream::create_filter");
2039 ret = FFStream::create_filter(filter_spec);
2040 return ret >= 0 ? 0 : 1;
2043 int FFAudioStream::create_filter(const char *filter_spec,
2044 AVCodecContext *src_ctx, AVCodecContext *sink_ctx)
2046 avfilter_register_all();
2047 filter_graph = avfilter_graph_alloc();
2048 AVFilter *buffersrc = avfilter_get_by_name("abuffer");
2049 AVFilter *buffersink = avfilter_get_by_name("abuffersink");
2050 int ret = 0; char args[BCTEXTLEN];
2051 snprintf(args, sizeof(args),
2052 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
2053 st->time_base.num, st->time_base.den, src_ctx->sample_rate,
2054 av_get_sample_fmt_name(src_ctx->sample_fmt), src_ctx->channel_layout);
2056 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2057 args, NULL, filter_graph);
2059 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2060 NULL, NULL, filter_graph);
2062 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
2063 (uint8_t*)&sink_ctx->sample_fmt, sizeof(sink_ctx->sample_fmt),
2064 AV_OPT_SEARCH_CHILDREN);
2066 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
2067 (uint8_t*)&sink_ctx->channel_layout,
2068 sizeof(sink_ctx->channel_layout), AV_OPT_SEARCH_CHILDREN);
2070 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
2071 (uint8_t*)&sink_ctx->sample_rate, sizeof(sink_ctx->sample_rate),
2072 AV_OPT_SEARCH_CHILDREN);
2074 ff_err(ret, "FFAudioStream::create_filter");
2076 ret = FFStream::create_filter(filter_spec);
2077 return ret >= 0 ? 0 : 1;
2080 int FFStream::create_filter(const char *filter_spec)
2082 /* Endpoints for the filter graph. */
2083 AVFilterInOut *outputs = avfilter_inout_alloc();
2084 outputs->name = av_strdup("in");
2085 outputs->filter_ctx = buffersrc_ctx;
2086 outputs->pad_idx = 0;
2089 AVFilterInOut *inputs = avfilter_inout_alloc();
2090 inputs->name = av_strdup("out");
2091 inputs->filter_ctx = buffersink_ctx;
2092 inputs->pad_idx = 0;
2095 int ret = !outputs->name || !inputs->name ? -1 : 0;
2097 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
2098 &inputs, &outputs, NULL);
2100 ret = avfilter_graph_config(filter_graph, NULL);
2103 ff_err(ret, "FFStream::create_filter");
2104 avfilter_inout_free(&inputs);
2105 avfilter_inout_free(&outputs);
2109 void FFStream::add_bsfilter(const char *bsf, const char *ap)
2111 bsfilter.append(new BSFilter(bsf,ap));
2114 int FFStream::bs_filter(AVPacket *pkt)
2116 if( !bsfilter.size() ) return 0;
2117 av_packet_split_side_data(pkt);
2120 for( int i=0; i<bsfilter.size(); ++i ) {
2121 AVPacket bspkt = *pkt;
2122 ret = av_bitstream_filter_filter(bsfilter[i]->bsfc,
2123 st->codec, bsfilter[i]->args, &bspkt.data, &bspkt.size,
2124 pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY);
2125 if( ret < 0 ) break;
2126 int size = bspkt.size;
2127 uint8_t *data = bspkt.data;
2128 if( !ret && bspkt.data != pkt->data ) {
2130 data = (uint8_t *)av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
2131 if( !data ) { ret = AVERROR(ENOMEM); break; }
2132 memcpy(data, bspkt.data, size);
2133 memset(data+size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2137 pkt->side_data = 0; pkt->side_data_elems = 0;
2138 av_free_packet(pkt);
2139 ret = av_packet_from_data(&bspkt, data, size);
2140 if( ret < 0 ) break;
2145 ff_err(ret,"FFStream::bs_filter");