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 if( !st->codec || !st->codec->codec ) return -1;
552 avcodec_flush_buffers(st->codec);
553 double secs = (double)pos / sample_rate;
554 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
555 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
556 avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, tstmp, INT64_MAX, 0);
557 seek_pos = curr_pos = pos;
559 mbsz = 0; flushed = 0; need_packet = 1;
563 int FFAudioStream::encode(double **samples, int len)
565 if( encode_activate() <= 0 ) return -1;
568 int64_t count = load_buffer(samples, len);
571 while( ret >= 0 && count >= frame_sz ) {
572 frm = new FFrame(this);
573 if( (ret=frm->initted()) < 0 ) break;
574 AVFrame *frame = *frm;
575 float *bfrp = get_outp(frame_sz);
576 ret = swr_convert(resample_context,
577 (uint8_t **)frame->extended_data, frame_sz,
578 (const uint8_t **)&bfrp, frame_sz);
580 fprintf(stderr, "FFAudioStream::encode: swr_convert failed\n");
583 frm->queue(curr_pos);
585 curr_pos += frame_sz;
590 return ret >= 0 ? 0 : 1;
593 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx)
594 : FFStream(ffmpeg, strm, idx)
599 seek_pos = curr_pos = 0;
604 FFVideoStream::~FFVideoStream()
606 if( convert_ctx ) sws_freeContext(convert_ctx);
609 int FFVideoStream::decode_frame(AVFrame *frame, int &got_frame)
611 int ret = avcodec_decode_video2(st->codec, frame, &got_frame, ipkt);
613 fprintf(stderr, "FFVideoStream::decode_frame: Could not read video frame\n");
621 int FFVideoStream::load(VFrame *vframe, int64_t pos)
623 if( video_seek(pos) < 0 ) return -1;
624 if( !frame && !(frame=av_frame_alloc()) ) {
625 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
629 for( int i=0; ret>=0 && !flushed && curr_pos<=pos && i<1000; ++i ) {
630 ret = read_frame(frame);
633 AVCodecContext *ctx = st->codec;
634 ret = convert_cmodel(vframe, (AVPicture *)frame,
635 ctx->pix_fmt, ctx->width, ctx->height);
637 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
641 int FFVideoStream::video_seek(int64_t pos)
643 if( decode_activate() < 0 ) return -1;
644 // if close enough, just read up to current
645 // 3*gop_size seems excessive, but less causes tears
646 int gop = 3*st->codec->gop_size;
647 if( gop < 4 ) gop = 4;
648 if( gop > 64 ) gop = 64;
649 if( pos >= curr_pos && pos <= curr_pos + gop ) return 0;
650 if( !st->codec || !st->codec->codec ) return -1;
651 avcodec_flush_buffers(st->codec);
652 // back up a few frames to read up to current to help repair damages
653 if( (pos-=gop) < 0 ) pos = 0;
654 double secs = (double)pos / frame_rate;
655 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
656 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
657 avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, tstmp, INT64_MAX, 0);
658 seek_pos = curr_pos = pos;
660 flushed = 0; need_packet = 1;
664 int FFVideoStream::init_frame(AVFrame *picture)
666 AVCodecContext *ctx = st->codec;
667 picture->format = ctx->pix_fmt;
668 picture->width = ctx->width;
669 picture->height = ctx->height;
670 int ret = av_frame_get_buffer(picture, 32);
674 int FFVideoStream::encode(VFrame *vframe)
676 if( encode_activate() <= 0 ) return -1;
678 FFrame *picture = new FFrame(this);
679 int ret = picture->initted();
681 AVFrame *frame = *picture;
682 frame->pts = curr_pos;
683 AVCodecContext *ctx = st->codec;
684 ret = convert_pixfmt(vframe, (AVPicture*)frame,
685 ctx->pix_fmt, ctx->width, ctx->height);
688 picture->queue(curr_pos);
692 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
695 return ret >= 0 ? 0 : 1;
699 PixelFormat FFVideoStream::color_model_to_pix_fmt(int color_model)
701 switch( color_model ) {
702 case BC_YUV422: return AV_PIX_FMT_YUYV422;
703 case BC_RGB888: return AV_PIX_FMT_RGB24;
704 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
705 case BC_BGR8888: return AV_PIX_FMT_BGR0;
706 case BC_BGR888: return AV_PIX_FMT_BGR24;
707 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
708 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
709 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
710 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
711 case BC_RGB565: return AV_PIX_FMT_RGB565;
712 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
713 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
717 return AV_PIX_FMT_NB;
720 int FFVideoStream::pix_fmt_to_color_model(PixelFormat pix_fmt)
723 case AV_PIX_FMT_YUYV422: return BC_YUV422;
724 case AV_PIX_FMT_RGB24: return BC_RGB888;
725 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
726 case AV_PIX_FMT_BGR0: return BC_BGR8888;
727 case AV_PIX_FMT_BGR24: return BC_BGR888;
728 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
729 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
730 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
731 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
732 case AV_PIX_FMT_RGB565: return BC_RGB565;
733 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
734 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
738 return BC_TRANSPARENCY;
741 int FFVideoStream::convert_picture_vframe(VFrame *frame,
742 AVPicture *ip, PixelFormat ifmt, int iw, int ih)
745 int cmodel = frame->get_color_model();
746 PixelFormat ofmt = color_model_to_pix_fmt(cmodel);
747 if( ofmt == AV_PIX_FMT_NB ) return -1;
748 int size = avpicture_fill(&opic, frame->get_data(), ofmt,
749 frame->get_w(), frame->get_h());
750 if( size < 0 ) return -1;
752 // transfer line sizes must match also
753 int planar = BC_CModels::is_planar(cmodel);
754 int packed_width = !planar ? frame->get_bytes_per_line() :
755 BC_CModels::calculate_pixelsize(cmodel) * frame->get_w();
756 if( packed_width != opic.linesize[0] ) return -1;
759 // override avpicture_fill() for planar types
760 opic.data[0] = frame->get_y();
761 opic.data[1] = frame->get_u();
762 opic.data[2] = frame->get_v();
765 convert_ctx = sws_getCachedContext(convert_ctx, iw, ih, ifmt,
766 frame->get_w(), frame->get_h(), ofmt, SWS_BICUBIC, NULL, NULL, NULL);
768 fprintf(stderr, "FFVideoStream::convert_picture_frame:"
769 " sws_getCachedContext() failed\n");
772 if( sws_scale(convert_ctx, ip->data, ip->linesize, 0, ih,
773 opic.data, opic.linesize) < 0 ) {
774 fprintf(stderr, "FFVideoStream::convert_picture_frame: sws_scale() failed\n");
780 int FFVideoStream::convert_cmodel(VFrame *frame,
781 AVPicture *ip, PixelFormat ifmt, int iw, int ih)
783 // try direct transfer
784 if( !convert_picture_vframe(frame, ip, ifmt, iw, ih) ) return 1;
785 // use indirect transfer
786 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
788 for( int i = 0; i <desc->nb_components; ++i ) {
789 int bits = desc->comp[i].depth_minus1 + 1;
790 if( bits > max_bits ) max_bits = bits;
792 // from libavcodec/pixdesc.c
793 #define pixdesc_has_alpha(pixdesc) ((pixdesc)->nb_components == 2 || \
794 (pixdesc)->nb_components == 4 || (pixdesc)->flags & AV_PIX_FMT_FLAG_PAL)
795 int icolor_model = pixdesc_has_alpha(desc) ?
796 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
797 (max_bits > 8 ? BC_RGB161616 : BC_RGB888) ;
798 VFrame vframe(iw, ih, icolor_model);
799 if( convert_picture_vframe(&vframe, ip, ifmt, iw, ih) ) return -1;
800 frame->transfer_from(&vframe);
804 int FFVideoStream::convert_vframe_picture(VFrame *frame,
805 AVPicture *op, PixelFormat ofmt, int ow, int oh)
808 int cmodel = frame->get_color_model();
809 PixelFormat ifmt = color_model_to_pix_fmt(cmodel);
810 if( ifmt == AV_PIX_FMT_NB ) return -1;
811 int size = avpicture_fill(&opic, frame->get_data(), ifmt,
812 frame->get_w(), frame->get_h());
813 if( size < 0 ) return -1;
815 // transfer line sizes must match also
816 int planar = BC_CModels::is_planar(cmodel);
817 int packed_width = !planar ? frame->get_bytes_per_line() :
818 BC_CModels::calculate_pixelsize(cmodel) * frame->get_w();
819 if( packed_width != opic.linesize[0] ) return -1;
822 // override avpicture_fill() for planar types
823 opic.data[0] = frame->get_y();
824 opic.data[1] = frame->get_u();
825 opic.data[2] = frame->get_v();
828 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(), ifmt,
829 ow, oh, ofmt, SWS_BICUBIC, NULL, NULL, NULL);
831 fprintf(stderr, "FFVideoStream::convert_frame_picture:"
832 " sws_getCachedContext() failed\n");
835 if( sws_scale(convert_ctx, opic.data, opic.linesize, 0, frame->get_h(),
836 op->data, op->linesize) < 0 ) {
837 fprintf(stderr, "FFVideoStream::convert_frame_picture: sws_scale() failed\n");
843 int FFVideoStream::convert_pixfmt(VFrame *frame,
844 AVPicture *op, PixelFormat ofmt, int ow, int oh)
846 // try direct transfer
847 if( !convert_vframe_picture(frame, op, ofmt, ow, oh) ) return 0;
848 // use indirect transfer
849 int colormodel = frame->get_color_model();
850 int bits = BC_CModels::calculate_pixelsize(colormodel) * 8;
851 bits /= BC_CModels::components(colormodel);
852 int icolor_model = BC_CModels::has_alpha(colormodel) ?
853 (bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
854 (bits > 8 ? BC_RGB161616: BC_RGB888) ;
855 VFrame vframe(frame->get_w(), frame->get_h(), icolor_model);
856 vframe.transfer_from(frame);
857 if( convert_vframe_picture(&vframe, op, ofmt, ow, oh) ) return 1;
862 FFMPEG::FFMPEG(FileBase *file_base)
865 this->file_base = file_base;
866 memset(file_format,0,sizeof(file_format));
867 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
868 flow_lock = new Condition(1,"FFStream::flow_lock",0);
871 decoding = encoding = 0;
872 has_audio = has_video = 0;
875 opt_video_filter = 0;
876 opt_audio_filter = 0;
877 char option_path[BCTEXTLEN];
878 set_option_path(option_path, "%s", "ffmpeg.opts");
879 read_options(option_path, opts);
884 ff_lock("FFMPEG::~FFMPEG()");
886 ffaudio.remove_all_objects();
887 ffvideo.remove_all_objects();
888 if( encoding ) avformat_free_context(fmt_ctx);
893 delete opt_video_filter;
894 delete opt_audio_filter;
897 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
899 const int *p = codec->supported_samplerates;
900 if( !p ) return sample_rate;
902 if( *p == sample_rate ) return *p;
908 static inline AVRational std_frame_rate(int i)
910 static const int m1 = 1001*12, m2 = 1000*12;
911 static const int freqs[] = {
912 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
913 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
915 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
916 return (AVRational) { freq, 1001*12 };
919 AVRational FFMPEG::check_frame_rate(AVCodec *codec, double frame_rate)
921 const AVRational *p = codec->supported_framerates;
922 AVRational rate, best_rate = (AVRational) { 0, 0 };
923 double max_err = 1.; int i = 0;
924 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
925 double framerate = (double) rate.num / rate.den;
926 double err = fabs(frame_rate/framerate - 1.);
927 if( err >= max_err ) continue;
931 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
934 AVRational FFMPEG::to_sample_aspect_ratio(double aspect_ratio)
937 int height = 1000000, width = height * aspect_ratio;
939 MWindow::create_aspect_ratio(w, h, width, height);
940 return (AVRational){(int)w, (int)h};
943 return (AVRational){1, 1};
947 AVRational FFMPEG::to_time_base(int sample_rate)
949 return (AVRational){1, sample_rate};
952 extern void get_exe_path(char *result); // from main.C
954 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
957 strcat(path, "/ffmpeg/");
958 path += strlen(path);
961 vsprintf(path, fmt, ap);
965 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
970 set_option_path(path, "%s/%s", type, spec);
973 int FFMPEG::get_format(char *format, const char *path, char *spec)
975 char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
976 get_option_path(option_path, path, spec);
977 FILE *fp = fopen(option_path,"r");
980 if( !fgets(line, sizeof(line), fp) ) ret = 1;
982 line[sizeof(line)-1] = 0;
983 ret = scan_option_line(line, format, codec);
989 int FFMPEG::get_file_format()
992 char audio_format[BCSTRLEN], video_format[BCSTRLEN];
993 file_format[0] = audio_format[0] = video_format[0] = 0;
994 Asset *asset = file_base->asset;
995 if( !ret && asset->audio_data )
996 ret = get_format(audio_format, "audio", asset->acodec);
997 if( !ret && asset->video_data )
998 ret = get_format(video_format, "video", asset->vcodec);
999 if( !ret && !audio_format[0] && !video_format[0] )
1001 if( !ret && audio_format[0] && video_format[0] &&
1002 strcmp(audio_format, video_format) ) ret = -1;
1004 strcpy(file_format, audio_format[0] ? audio_format : video_format);
1008 int FFMPEG::scan_option_line(char *cp, char *tag, char *val)
1010 while( *cp == ' ' || *cp == '\t' ) ++cp;
1012 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' ) ++cp;
1014 if( !len || len > BCSTRLEN-1 ) return 1;
1015 while( bp < cp ) *tag++ = *bp++;
1017 while( *cp == ' ' || *cp == '\t' ) ++cp;
1018 if( *cp == '=' ) ++cp;
1019 while( *cp == ' ' || *cp == '\t' ) ++cp;
1021 while( *cp && *cp != '\n' ) ++cp;
1023 if( len > BCTEXTLEN-1 ) return 1;
1024 while( bp < cp ) *val++ = *bp++;
1029 int FFMPEG::get_encoder(const char *options,
1030 char *format, char *codec, char *bsfilter, char *bsargs)
1032 FILE *fp = fopen(options,"r");
1034 eprintf("FFMPEG::get_encoder: options open failed %s\n",options);
1037 if( get_encoder(fp, format, codec, bsfilter, bsargs) )
1038 eprintf("FFMPEG::get_encoder:"
1039 " err: format/codec not found %s\n", options);
1044 int FFMPEG::get_encoder(FILE *fp,
1045 char *format, char *codec, char *bsfilter, char *bsargs)
1047 format[0] = codec[0] = bsfilter[0] = bsargs[0] = 0;
1048 char line[BCTEXTLEN];
1049 if( !fgets(line, sizeof(line), fp) ) return 1;
1050 line[sizeof(line)-1] = 0;
1051 if( scan_option_line(line, format, codec) ) return 1;
1053 while( *cp && *cp != '|' ) ++cp;
1054 if( !*cp ) return 0;
1055 if( scan_option_line(cp+1, bsfilter, bsargs) ) return 1;
1056 do { *cp-- = 0; } while( cp>=codec && (*cp==' ' || *cp == '\t' ) );
1060 int FFMPEG::read_options(const char *options, AVDictionary *&opts)
1062 FILE *fp = fopen(options,"r");
1064 int ret = read_options(fp, options, opts);
1069 int FFMPEG::scan_options(const char *options, AVDictionary *&opts)
1071 FILE *fp = fmemopen((void *)options,strlen(options),"r");
1073 int ret = read_options(fp, options, opts);
1078 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
1080 int ret = 0, no = 0;
1081 char line[BCTEXTLEN];
1082 while( !ret && fgets(line, sizeof(line), fp) ) {
1083 line[sizeof(line)-1] = 0;
1085 if( line[0] == '#' ) continue;
1086 if( line[0] == '\n' ) continue;
1087 char key[BCSTRLEN], val[BCTEXTLEN];
1088 if( scan_option_line(line, key, val) ) {
1089 eprintf("FFMPEG::read_options:"
1090 " err reading %s: line %d\n", options, no);
1094 if( !strcmp(key, "duration") )
1095 opt_duration = strtod(val, 0);
1096 if( !strcmp(key, "video_filter") )
1097 opt_video_filter = cstrdup(val);
1098 if( !strcmp(key, "audio_filter") )
1099 opt_audio_filter = cstrdup(val);
1100 else if( !strcmp(key, "loglevel") )
1103 av_dict_set(&opts, key, val, 0);
1109 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
1111 char option_path[BCTEXTLEN];
1112 set_option_path(option_path, "%s", options);
1113 return read_options(option_path, opts);
1116 int FFMPEG::load_options(const char *path, char *bfr, int len)
1119 FILE *fp = fopen(path, "r");
1121 fgets(bfr, len, fp); // skip hdr
1122 len = fread(bfr, 1, len-1, fp);
1123 if( len < 0 ) len = 0;
1129 void FFMPEG::set_loglevel(const char *ap)
1131 if( !ap || !*ap ) return;
1136 { "quiet" , AV_LOG_QUIET },
1137 { "panic" , AV_LOG_PANIC },
1138 { "fatal" , AV_LOG_FATAL },
1139 { "error" , AV_LOG_ERROR },
1140 { "warning", AV_LOG_WARNING },
1141 { "info" , AV_LOG_INFO },
1142 { "verbose", AV_LOG_VERBOSE },
1143 { "debug" , AV_LOG_DEBUG },
1145 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
1146 if( !strcmp(log_levels[i].name, ap) ) {
1147 av_log_set_level(log_levels[i].level);
1151 av_log_set_level(atoi(ap));
1154 double FFMPEG::to_secs(int64_t time, AVRational time_base)
1156 double base_time = time == AV_NOPTS_VALUE ? 0 :
1157 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
1158 return base_time / AV_TIME_BASE;
1161 int FFMPEG::info(char *text, int len)
1163 if( len <= 0 ) return 0;
1164 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
1166 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1167 AVStream *st = fmt_ctx->streams[i];
1168 AVCodecContext *avctx = st->codec;
1169 report("stream %d, id 0x%06x:\n", i, avctx->codec_id);
1170 const AVCodecDescriptor *desc = avcodec_descriptor_get(avctx->codec_id);
1171 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1172 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
1173 double frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
1174 report(" video %s",desc ? desc->name : " (unkn)");
1175 report(" %dx%d %5.2f", avctx->width, avctx->height, frame_rate);
1176 const char *pfn = av_get_pix_fmt_name(avctx->pix_fmt);
1177 report(" pix %s\n", pfn ? pfn : "(unkn)");
1178 double secs = to_secs(st->duration, st->time_base);
1179 int64_t length = secs * frame_rate + 0.5;
1180 report(" %jd frms %0.2f secs", length, secs);
1181 int hrs = secs/3600; secs -= hrs*3600;
1182 int mins = secs/60; secs -= mins*60;
1183 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1186 else if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1187 int sample_rate = avctx->sample_rate;
1188 const char *fmt = av_get_sample_fmt_name(avctx->sample_fmt);
1189 report(" audio %s",desc ? desc->name : " (unkn)");
1190 report(" %dch %s %d",avctx->channels, fmt, sample_rate);
1191 int sample_bits = av_get_bits_per_sample(avctx->codec_id);
1192 report(" %dbits\n", sample_bits);
1193 double secs = to_secs(st->duration, st->time_base);
1194 int64_t length = secs * sample_rate + 0.5;
1195 report(" %jd smpl %0.2f secs", length, secs);
1196 int hrs = secs/3600; secs -= hrs*3600;
1197 int mins = secs/60; secs -= mins*60;
1198 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1201 report(" codec_type unknown\n");
1204 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
1205 report("program %d", i+1);
1206 AVProgram *pgrm = fmt_ctx->programs[i];
1207 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j )
1208 report(", %d", pgrm->stream_index[j]);
1212 AVDictionaryEntry *tag = 0;
1213 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
1214 report("%s=%s\n", tag->key, tag->value);
1223 int FFMPEG::init_decoder(const char *filename)
1225 ff_lock("FFMPEG::init_decoder");
1227 char file_opts[BCTEXTLEN];
1228 char *bp = strrchr(strcpy(file_opts, filename), '/');
1229 char *sp = strrchr(!bp ? file_opts : bp, '.');
1232 strcpy(sp, ".opts");
1233 fp = fopen(file_opts, "r");
1236 read_options(fp, file_opts, opts);
1240 load_options("decode.opts", opts);
1241 AVDictionary *fopts = 0;
1242 av_dict_copy(&fopts, opts, 0);
1243 int ret = avformat_open_input(&fmt_ctx, filename, NULL, &fopts);
1244 av_dict_free(&fopts);
1246 ret = avformat_find_stream_info(fmt_ctx, NULL);
1251 return !ret ? 0 : 1;
1254 int FFMPEG::open_decoder()
1257 if( stat(fmt_ctx->filename, &st) < 0 ) {
1258 eprintf("FFMPEG::open_decoder: can't stat file: %s\n",
1263 int64_t file_bits = 8 * st.st_size;
1264 if( !fmt_ctx->bit_rate && opt_duration > 0 )
1265 fmt_ctx->bit_rate = file_bits / opt_duration;
1268 if( fmt_ctx->bit_rate > 0 ) {
1269 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1270 AVStream *st = fmt_ctx->streams[i];
1271 if( st->duration != AV_NOPTS_VALUE ) continue;
1272 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
1273 st->duration = av_rescale(file_bits, st->time_base.den,
1274 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
1279 printf("FFMPEG::open_decoder: some stream times estimated\n");
1281 ff_lock("FFMPEG::open_decoder");
1283 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1284 AVStream *st = fmt_ctx->streams[i];
1285 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
1286 AVCodecContext *avctx = st->codec;
1287 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1289 FFVideoStream *vid = new FFVideoStream(this, st, i);
1290 int vidx = ffvideo.size();
1291 vstrm_index.append(ffidx(vidx, 0));
1292 ffvideo.append(vid);
1293 vid->width = avctx->width;
1294 vid->height = avctx->height;
1295 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
1296 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
1297 double secs = to_secs(st->duration, st->time_base);
1298 vid->length = secs * vid->frame_rate;
1299 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
1300 vid->nudge = st->start_time;
1302 if( opt_video_filter )
1303 vid->create_filter(opt_video_filter, avctx,avctx);
1305 else if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1307 FFAudioStream *aud = new FFAudioStream(this, st, i);
1308 int aidx = ffaudio.size();
1309 ffaudio.append(aud);
1310 aud->channel0 = astrm_index.size();
1311 aud->channels = avctx->channels;
1312 for( int ch=0; ch<aud->channels; ++ch )
1313 astrm_index.append(ffidx(aidx, ch));
1314 aud->sample_rate = avctx->sample_rate;
1315 double secs = to_secs(st->duration, st->time_base);
1316 aud->length = secs * aud->sample_rate;
1317 if( avctx->sample_fmt != AV_SAMPLE_FMT_FLT ) {
1318 uint64_t layout = av_get_default_channel_layout(avctx->channels);
1319 if( !layout ) layout = ((uint64_t)1<<aud->channels) - 1;
1320 aud->resample_context = swr_alloc_set_opts(NULL,
1321 layout, AV_SAMPLE_FMT_FLT, avctx->sample_rate,
1322 layout, avctx->sample_fmt, avctx->sample_rate,
1324 swr_init(aud->resample_context);
1326 aud->nudge = st->start_time;
1328 if( opt_audio_filter )
1329 aud->create_filter(opt_audio_filter, avctx,avctx);
1333 printf("FFMPEG::open_decoder: some stream have bad times\n");
1339 int FFMPEG::init_encoder(const char *filename)
1341 int fd = ::open(filename,O_WRONLY);
1342 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
1344 eprintf("FFMPEG::init_encoder: bad file path: %s\n", filename);
1348 int ret = get_file_format();
1350 eprintf("FFMPEG::init_encoder: bad file format: %s\n", filename);
1354 eprintf("FFMPEG::init_encoder: mismatch audio/video file format: %s\n", filename);
1357 ff_lock("FFMPEG::init_encoder");
1359 avformat_alloc_output_context2(&fmt_ctx, 0, file_format, filename);
1361 eprintf("FFMPEG::init_encoder: failed: %s\n", filename);
1366 load_options("encode.opts", opts);
1373 int FFMPEG::open_encoder(const char *type, const char *spec)
1376 Asset *asset = file_base->asset;
1377 char *filename = asset->path;
1378 AVDictionary *sopts = 0;
1379 av_dict_copy(&sopts, opts, 0);
1380 char option_path[BCTEXTLEN];
1381 set_option_path(option_path, "%s/%s.opts", type, type);
1382 read_options(option_path, sopts);
1383 get_option_path(option_path, type, spec);
1384 char format_name[BCSTRLEN], codec_name[BCTEXTLEN];
1385 char bsfilter[BCSTRLEN], bsargs[BCTEXTLEN];
1386 if( get_encoder(option_path, format_name, codec_name, bsfilter, bsargs) ) {
1387 eprintf("FFMPEG::open_encoder: get_encoder failed %s:%s\n",
1388 option_path, filename);
1393 ff_lock("FFMPEG::open_encoder");
1397 const AVCodecDescriptor *codec_desc = 0;
1398 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
1400 eprintf("FFMPEG::open_encoder: cant find codec %s:%s\n",
1401 codec_name, filename);
1405 codec_desc = avcodec_descriptor_get(codec->id);
1407 eprintf("FFMPEG::open_encoder: unknown codec %s:%s\n",
1408 codec_name, filename);
1413 st = avformat_new_stream(fmt_ctx, 0);
1415 eprintf("FFMPEG::open_encoder: cant create stream %s:%s\n",
1416 codec_name, filename);
1421 AVCodecContext *ctx = st->codec;
1422 switch( codec_desc->type ) {
1423 case AVMEDIA_TYPE_AUDIO: {
1425 eprintf("FFMPEG::open_encoder: duplicate audio %s:%s\n",
1426 codec_name, filename);
1431 if( scan_options(asset->ff_audio_options, sopts) ) {
1432 eprintf("FFMPEG::open_encoder: bad audio options %s:%s\n",
1433 codec_name, filename);
1437 if( asset->ff_audio_bitrate > 0 ) {
1438 ctx->bit_rate = asset->ff_audio_bitrate;
1440 sprintf(arg, "%d", asset->ff_audio_bitrate);
1441 av_dict_set(&sopts, "b", arg, 0);
1443 int aidx = ffaudio.size();
1444 int idx = aidx + ffvideo.size();
1445 FFAudioStream *aud = new FFAudioStream(this, st, idx);
1446 ffaudio.append(aud); fst = aud;
1447 aud->sample_rate = asset->sample_rate;
1448 ctx->channels = aud->channels = asset->channels;
1449 for( int ch=0; ch<aud->channels; ++ch )
1450 astrm_index.append(ffidx(aidx, ch));
1451 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
1452 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
1453 if( !ctx->sample_rate ) {
1454 eprintf("FFMPEG::open_audio_encode:"
1455 " check_sample_rate failed %s\n", filename);
1459 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
1460 ctx->sample_fmt = codec->sample_fmts[0];
1461 uint64_t layout = av_get_default_channel_layout(ctx->channels);
1462 aud->resample_context = swr_alloc_set_opts(NULL,
1463 layout, ctx->sample_fmt, aud->sample_rate,
1464 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
1466 swr_init(aud->resample_context);
1469 case AVMEDIA_TYPE_VIDEO: {
1471 eprintf("FFMPEG::open_encoder: duplicate video %s:%s\n",
1472 codec_name, filename);
1477 if( scan_options(asset->ff_video_options, sopts) ) {
1478 eprintf("FFMPEG::open_encoder: bad video options %s:%s\n",
1479 codec_name, filename);
1483 if( asset->ff_video_bitrate > 0 ) {
1484 ctx->bit_rate = asset->ff_video_bitrate;
1486 sprintf(arg, "%d", asset->ff_video_bitrate);
1487 av_dict_set(&sopts, "b", arg, 0);
1489 else if( asset->ff_video_quality > 0 ) {
1490 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
1491 ctx->qmin = ctx->qmax = asset->ff_video_quality;
1492 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
1493 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
1494 ctx->flags |= CODEC_FLAG_QSCALE;
1496 av_dict_set(&sopts, "flags", "+qscale", 0);
1497 sprintf(arg, "%d", asset->ff_video_quality);
1498 av_dict_set(&sopts, "qscale", arg, 0);
1499 sprintf(arg, "%d", ctx->global_quality);
1500 av_dict_set(&sopts, "global_quality", arg, 0);
1502 int vidx = ffvideo.size();
1503 int idx = vidx + ffaudio.size();
1504 FFVideoStream *vid = new FFVideoStream(this, st, idx);
1505 vstrm_index.append(ffidx(vidx, 0));
1506 ffvideo.append(vid); fst = vid;
1507 vid->width = asset->width;
1508 ctx->width = (vid->width+3) & ~3;
1509 vid->height = asset->height;
1510 ctx->height = (vid->height+3) & ~3;
1511 vid->frame_rate = asset->frame_rate;
1512 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset->aspect_ratio);
1513 ctx->pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
1514 AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
1515 if( !frame_rate.num || !frame_rate.den ) {
1516 eprintf("FFMPEG::open_audio_encode:"
1517 " check_frame_rate failed %s\n", filename);
1521 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
1522 st->time_base = ctx->time_base;
1526 eprintf("FFMPEG::open_encoder: not audio/video, %s:%s\n",
1527 codec_name, filename);
1532 ret = avcodec_open2(st->codec, codec, &sopts);
1534 ff_err(ret,"FFMPEG::open_encoder");
1535 eprintf("FFMPEG::open_encoder: open failed %s:%s\n",
1536 codec_name, filename);
1543 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
1544 st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
1545 if( fst && bsfilter[0] )
1546 fst->add_bsfilter(bsfilter, !bsargs[0] ? 0 : bsargs);
1550 av_dict_free(&sopts);
1554 int FFMPEG::close_encoder()
1557 if( encoding > 0 ) {
1558 av_write_trailer(fmt_ctx);
1559 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
1560 avio_closep(&fmt_ctx->pb);
1566 int FFMPEG::decode_activate()
1568 if( decoding < 0 ) {
1570 int npgrms = fmt_ctx->nb_programs;
1571 for( int i=0; i<npgrms; ++i ) {
1572 AVProgram *pgrm = fmt_ctx->programs[i];
1573 // first start time video stream
1574 int64_t vstart_time = -1;
1575 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1576 int st_idx = pgrm->stream_index[j];
1577 AVStream *st = fmt_ctx->streams[st_idx];
1578 AVCodecContext *avctx = st->codec;
1579 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1580 if( st->start_time == AV_NOPTS_VALUE ) continue;
1581 vstart_time = st->start_time;
1585 // max start time audio stream
1586 int64_t astart_time = -1;
1587 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1588 int st_idx = pgrm->stream_index[j];
1589 AVStream *st = fmt_ctx->streams[st_idx];
1590 AVCodecContext *avctx = st->codec;
1591 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1592 if( st->start_time == AV_NOPTS_VALUE ) continue;
1593 if( astart_time > st->start_time ) continue;
1594 astart_time = st->start_time;
1597 if( astart_time < 0 || vstart_time < 0 ) continue;
1598 // match program streams to max start_time
1599 int64_t nudge = vstart_time > astart_time ? vstart_time : astart_time;
1600 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1601 int st_idx = pgrm->stream_index[j];
1602 AVStream *st = fmt_ctx->streams[st_idx];
1603 AVCodecContext *avctx = st->codec;
1604 if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1605 for( int k=0; k<ffaudio.size(); ++k ) {
1606 if( ffaudio[k]->idx == st_idx )
1607 ffaudio[k]->nudge = nudge;
1610 else if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1611 for( int k=0; k<ffvideo.size(); ++k ) {
1612 if( ffvideo[k]->idx == st_idx )
1613 ffvideo[k]->nudge = nudge;
1618 int64_t vstart_time = 0, astart_time = 0;
1619 int nstreams = fmt_ctx->nb_streams;
1620 for( int i=0; i<nstreams; ++i ) {
1621 AVStream *st = fmt_ctx->streams[i];
1622 AVCodecContext *avctx = st->codec;
1623 switch( avctx->codec_type ) {
1624 case AVMEDIA_TYPE_VIDEO:
1625 if( st->start_time == AV_NOPTS_VALUE ) continue;
1626 if( vstart_time >= st->start_time ) continue;
1627 vstart_time = st->start_time;
1629 case AVMEDIA_TYPE_AUDIO:
1630 if( st->start_time == AV_NOPTS_VALUE ) continue;
1631 if( astart_time >= st->start_time ) continue;
1632 astart_time = st->start_time;
1636 int64_t nudge = vstart_time > astart_time ? vstart_time : astart_time;
1637 for( int k=0; k<ffvideo.size(); ++k ) {
1638 if( ffvideo[k]->nudge != AV_NOPTS_VALUE ) continue;
1639 ffvideo[k]->nudge = nudge;
1641 for( int k=0; k<ffaudio.size(); ++k ) {
1642 if( ffaudio[k]->nudge != AV_NOPTS_VALUE ) continue;
1643 ffaudio[k]->nudge = nudge;
1650 int FFMPEG::encode_activate()
1652 if( encoding < 0 ) {
1654 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
1655 avio_open(&fmt_ctx->pb, fmt_ctx->filename, AVIO_FLAG_WRITE) < 0 ) {
1656 fprintf(stderr, "FFMPEG::encode_activate: err opening : %s\n",
1661 AVDictionary *fopts = 0;
1662 char option_path[BCTEXTLEN];
1663 set_option_path(option_path, "format/%s", file_format);
1664 read_options(option_path, fopts);
1665 int ret = avformat_write_header(fmt_ctx, &fopts);
1666 av_dict_free(&fopts);
1668 fprintf(stderr, "FFMPEG::encode_activate: write header failed %s\n",
1677 int FFMPEG::audio_seek(int stream, int64_t pos)
1679 int aidx = astrm_index[stream].st_idx;
1680 FFAudioStream *aud = ffaudio[aidx];
1681 aud->audio_seek(pos);
1682 aud->seek_pos = aud->curr_pos = pos;
1686 int FFMPEG::video_seek(int stream, int64_t pos)
1688 int vidx = vstrm_index[stream].st_idx;
1689 FFVideoStream *vid = ffvideo[vidx];
1690 vid->video_seek(pos);
1691 vid->seek_pos = vid->curr_pos = pos;
1696 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
1698 if( !has_audio || chn >= astrm_index.size() ) return -1;
1699 int aidx = astrm_index[chn].st_idx;
1700 FFAudioStream *aud = ffaudio[aidx];
1701 if( aud->load(pos, len) < len ) return -1;
1702 int ch = astrm_index[chn].st_ch;
1703 return aud->read(samples,len,ch);
1706 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
1708 if( !has_video || layer >= vstrm_index.size() ) return -1;
1709 int vidx = vstrm_index[layer].st_idx;
1710 FFVideoStream *vid = ffvideo[vidx];
1711 return vid->load(vframe, pos);
1714 int FFMPEG::encode(int stream, double **samples, int len)
1716 FFAudioStream *aud = ffaudio[stream];
1717 return aud->encode(samples, len);
1721 int FFMPEG::encode(int stream, VFrame *frame)
1723 FFVideoStream *vid = ffvideo[stream];
1724 return vid->encode(frame);
1727 void FFMPEG::start_muxer()
1735 void FFMPEG::stop_muxer()
1744 void FFMPEG::flow_off()
1747 flow_lock->lock("FFMPEG::flow_off");
1751 void FFMPEG::flow_on()
1755 flow_lock->unlock();
1758 void FFMPEG::flow_ctl()
1761 flow_lock->lock("FFMPEG::flow_ctl");
1762 flow_lock->unlock();
1766 int FFMPEG::mux_audio(FFrame *frm)
1769 AVStream *st = frm->fst->st;
1770 AVCodecContext *ctx = st->codec;
1771 AVFrame *frame = *frm;
1772 AVRational tick_rate = {1, ctx->sample_rate};
1773 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
1775 int ret = avcodec_encode_audio2(ctx, pkt, frame, &got_packet);
1776 if( ret >= 0 && got_packet ) {
1777 frm->fst->bs_filter(pkt);
1778 av_packet_rescale_ts(pkt, ctx->time_base, st->time_base);
1779 pkt->stream_index = st->index;
1780 ret = av_interleaved_write_frame(fmt_ctx, pkt);
1783 ff_err(ret, "FFMPEG::mux_audio");
1784 return ret >= 0 ? 0 : 1;
1787 int FFMPEG::mux_video(FFrame *frm)
1790 AVStream *st = frm->fst->st;
1791 AVFrame *frame = *frm;
1792 frame->pts = frm->position;
1793 int ret = 1, got_packet = 0;
1794 if( fmt_ctx->oformat->flags & AVFMT_RAWPICTURE ) {
1795 /* a hack to avoid data copy with some raw video muxers */
1796 pkt->flags |= AV_PKT_FLAG_KEY;
1797 pkt->stream_index = st->index;
1798 AVPicture *picture = (AVPicture *)frame;
1799 pkt->data = (uint8_t *)picture;
1800 pkt->size = sizeof(AVPicture);
1801 pkt->pts = pkt->dts = frame->pts;
1805 ret = avcodec_encode_video2(st->codec, pkt, frame, &got_packet);
1806 if( ret >= 0 && got_packet ) {
1807 frm->fst->bs_filter(pkt);
1808 av_packet_rescale_ts(pkt, st->codec->time_base, st->time_base);
1809 pkt->stream_index = st->index;
1810 ret = av_interleaved_write_frame(fmt_ctx, pkt);
1813 ff_err(ret, "FFMPEG::mux_video");
1814 return ret >= 0 ? 0 : 1;
1820 double atm = -1, vtm = -1;
1821 FFrame *afrm = 0, *vfrm = 0;
1823 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
1824 FFStream *fst = ffaudio[i];
1825 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
1826 FFrame *frm = fst->frms.first;
1827 if( !frm ) { if( !done ) return; continue; }
1828 double tm = to_secs(frm->position, fst->st->codec->time_base);
1829 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
1831 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
1832 FFStream *fst = ffvideo[i];
1833 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
1834 FFrame *frm = fst->frms.first;
1835 if( !frm ) { if( !done ) return; continue; }
1836 double tm = to_secs(frm->position, fst->st->codec->time_base);
1837 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
1839 if( !demand ) flow_off();
1840 if( !afrm && !vfrm ) break;
1841 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
1842 vfrm->position, vfrm->fst->st->codec->time_base,
1843 afrm->position, afrm->fst->st->codec->time_base);
1844 FFrame *frm = v <= 0 ? vfrm : afrm;
1845 if( frm == afrm ) mux_audio(frm);
1846 if( frm == vfrm ) mux_video(frm);
1855 mux_lock->lock("FFMPEG::run");
1862 int FFMPEG::ff_total_audio_channels()
1864 return astrm_index.size();
1867 int FFMPEG::ff_total_astreams()
1869 return ffaudio.size();
1872 int FFMPEG::ff_audio_channels(int stream)
1874 return ffaudio[stream]->channels;
1877 int FFMPEG::ff_sample_rate(int stream)
1879 return ffaudio[stream]->sample_rate;
1882 const char* FFMPEG::ff_audio_format(int stream)
1884 AVStream *st = ffaudio[stream]->st;
1885 AVCodecID id = st->codec->codec_id;
1886 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
1887 return desc ? desc->name : "Unknown";
1890 int FFMPEG::ff_audio_pid(int stream)
1892 return ffaudio[stream]->st->id;
1895 int64_t FFMPEG::ff_audio_samples(int stream)
1897 return ffaudio[stream]->length;
1900 // find audio astream/channels with this program,
1901 // or all program audio channels (astream=-1)
1902 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
1906 int vidx = ffvideo[vstream]->idx;
1907 // find first program with this video stream
1908 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
1909 AVProgram *pgrm = fmt_ctx->programs[i];
1910 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
1911 int st_idx = pgrm->stream_index[j];
1912 AVStream *st = fmt_ctx->streams[st_idx];
1913 if( st->codec->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
1914 if( st_idx == vidx ) pidx = i;
1917 if( pidx < 0 ) return -1;
1919 int64_t channels = 0;
1920 AVProgram *pgrm = fmt_ctx->programs[pidx];
1921 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1922 int aidx = pgrm->stream_index[j];
1923 AVStream *st = fmt_ctx->streams[aidx];
1924 if( st->codec->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
1925 if( astream > 0 ) { --astream; continue; }
1927 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
1928 if( ffaudio[i]->idx == aidx ) astrm = i;
1930 if( ret < 0 ) ret = astrm;
1931 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
1932 channels |= mask << ffaudio[astrm]->channel0;
1934 if( !astream ) break;
1936 channel_mask = channels;
1941 int FFMPEG::ff_total_video_layers()
1943 return vstrm_index.size();
1946 int FFMPEG::ff_total_vstreams()
1948 return ffvideo.size();
1951 int FFMPEG::ff_video_width(int stream)
1953 return ffvideo[stream]->width;
1956 int FFMPEG::ff_video_height(int stream)
1958 return ffvideo[stream]->height;
1961 int FFMPEG::ff_set_video_width(int stream, int width)
1963 int w = ffvideo[stream]->width;
1964 ffvideo[stream]->width = width;
1968 int FFMPEG::ff_set_video_height(int stream, int height)
1970 int h = ffvideo[stream]->height;
1971 ffvideo[stream]->height = height;
1975 int FFMPEG::ff_coded_width(int stream)
1977 AVStream *st = ffvideo[stream]->st;
1978 return st->codec->coded_width;
1981 int FFMPEG::ff_coded_height(int stream)
1983 AVStream *st = ffvideo[stream]->st;
1984 return st->codec->coded_height;
1987 float FFMPEG::ff_aspect_ratio(int stream)
1989 return ffvideo[stream]->aspect_ratio;
1992 const char* FFMPEG::ff_video_format(int stream)
1994 AVStream *st = ffvideo[stream]->st;
1995 AVCodecID id = st->codec->codec_id;
1996 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
1997 return desc ? desc->name : "Unknown";
2000 double FFMPEG::ff_frame_rate(int stream)
2002 return ffvideo[stream]->frame_rate;
2005 int64_t FFMPEG::ff_video_frames(int stream)
2007 return ffvideo[stream]->length;
2010 int FFMPEG::ff_video_pid(int stream)
2012 return ffvideo[stream]->st->id;
2016 int FFMPEG::ff_cpus()
2018 return file_base->file->cpus;
2021 int FFVideoStream::create_filter(const char *filter_spec,
2022 AVCodecContext *src_ctx, AVCodecContext *sink_ctx)
2024 avfilter_register_all();
2025 filter_graph = avfilter_graph_alloc();
2026 AVFilter *buffersrc = avfilter_get_by_name("buffer");
2027 AVFilter *buffersink = avfilter_get_by_name("buffersink");
2029 int ret = 0; char args[BCTEXTLEN];
2030 snprintf(args, sizeof(args),
2031 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
2032 src_ctx->width, src_ctx->height, src_ctx->pix_fmt,
2033 st->time_base.num, st->time_base.den,
2034 src_ctx->sample_aspect_ratio.num, src_ctx->sample_aspect_ratio.den);
2036 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2037 args, NULL, filter_graph);
2039 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2040 NULL, NULL, filter_graph);
2042 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
2043 (uint8_t*)&sink_ctx->pix_fmt, sizeof(sink_ctx->pix_fmt),
2044 AV_OPT_SEARCH_CHILDREN);
2046 ff_err(ret, "FFVideoStream::create_filter");
2048 ret = FFStream::create_filter(filter_spec);
2049 return ret >= 0 ? 0 : 1;
2052 int FFAudioStream::create_filter(const char *filter_spec,
2053 AVCodecContext *src_ctx, AVCodecContext *sink_ctx)
2055 avfilter_register_all();
2056 filter_graph = avfilter_graph_alloc();
2057 AVFilter *buffersrc = avfilter_get_by_name("abuffer");
2058 AVFilter *buffersink = avfilter_get_by_name("abuffersink");
2059 int ret = 0; char args[BCTEXTLEN];
2060 snprintf(args, sizeof(args),
2061 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
2062 st->time_base.num, st->time_base.den, src_ctx->sample_rate,
2063 av_get_sample_fmt_name(src_ctx->sample_fmt), src_ctx->channel_layout);
2065 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2066 args, NULL, filter_graph);
2068 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2069 NULL, NULL, filter_graph);
2071 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
2072 (uint8_t*)&sink_ctx->sample_fmt, sizeof(sink_ctx->sample_fmt),
2073 AV_OPT_SEARCH_CHILDREN);
2075 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
2076 (uint8_t*)&sink_ctx->channel_layout,
2077 sizeof(sink_ctx->channel_layout), AV_OPT_SEARCH_CHILDREN);
2079 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
2080 (uint8_t*)&sink_ctx->sample_rate, sizeof(sink_ctx->sample_rate),
2081 AV_OPT_SEARCH_CHILDREN);
2083 ff_err(ret, "FFAudioStream::create_filter");
2085 ret = FFStream::create_filter(filter_spec);
2086 return ret >= 0 ? 0 : 1;
2089 int FFStream::create_filter(const char *filter_spec)
2091 /* Endpoints for the filter graph. */
2092 AVFilterInOut *outputs = avfilter_inout_alloc();
2093 outputs->name = av_strdup("in");
2094 outputs->filter_ctx = buffersrc_ctx;
2095 outputs->pad_idx = 0;
2098 AVFilterInOut *inputs = avfilter_inout_alloc();
2099 inputs->name = av_strdup("out");
2100 inputs->filter_ctx = buffersink_ctx;
2101 inputs->pad_idx = 0;
2104 int ret = !outputs->name || !inputs->name ? -1 : 0;
2106 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
2107 &inputs, &outputs, NULL);
2109 ret = avfilter_graph_config(filter_graph, NULL);
2112 ff_err(ret, "FFStream::create_filter");
2113 avfilter_inout_free(&inputs);
2114 avfilter_inout_free(&outputs);
2118 void FFStream::add_bsfilter(const char *bsf, const char *ap)
2120 bsfilter.append(new BSFilter(bsf,ap));
2123 int FFStream::bs_filter(AVPacket *pkt)
2125 if( !bsfilter.size() ) return 0;
2126 av_packet_split_side_data(pkt);
2129 for( int i=0; i<bsfilter.size(); ++i ) {
2130 AVPacket bspkt = *pkt;
2131 ret = av_bitstream_filter_filter(bsfilter[i]->bsfc,
2132 st->codec, bsfilter[i]->args, &bspkt.data, &bspkt.size,
2133 pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY);
2134 if( ret < 0 ) break;
2135 int size = bspkt.size;
2136 uint8_t *data = bspkt.data;
2137 if( !ret && bspkt.data != pkt->data ) {
2139 data = (uint8_t *)av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
2140 if( !data ) { ret = AVERROR(ENOMEM); break; }
2141 memcpy(data, bspkt.data, size);
2142 memset(data+size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2146 pkt->side_data = 0; pkt->side_data_elems = 0;
2147 av_free_packet(pkt);
2148 ret = av_packet_from_data(&bspkt, data, size);
2149 if( ret < 0 ) break;
2154 ff_err(ret,"FFStream::bs_filter");