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 *fmt, ...)
38 vsnprintf(msg, sizeof(msg), fmt, ap);
40 char errmsg[BCSTRLEN];
41 av_strerror(ret, errmsg, sizeof(errmsg));
42 fprintf(stderr,_("%s err: %s\n"),msg, errmsg);
58 pkt.data = 0; pkt.size = 0;
61 FFrame::FFrame(FFStream *fst)
64 frm = av_frame_alloc();
65 init = fst->init_frame(frm);
73 void FFrame::queue(int64_t pos)
79 void FFrame::dequeue()
84 int FFAudioStream::read(float *fp, long len)
92 while( --k >= 0 ) *fp++ = *op++;
93 if( op >= lmt ) op = bfr;
98 void FFAudioStream::realloc(long sz, int nch, long len)
101 float *np = new float[bsz];
102 inp = np + read(np, len) * nch;
107 delete [] bfr; bfr = np;
110 void FFAudioStream::realloc(long sz, int nch)
112 if( sz > this->sz || this->nch != nch ) {
113 long len = this->nch != nch ? 0 : curr_pos - seek_pos;
114 if( len > this->sz ) len = this->sz;
116 realloc(sz, nch, len);
120 void FFAudioStream::reserve(long sz, int nch)
122 long len = (inp - outp) / nch;
124 if( sz > this->sz || this->nch != nch ) {
125 if( this->nch != nch ) len = 0;
126 realloc(sz, nch, len);
129 if( (len*=nch) > 0 && bfr != outp )
130 memmove(bfr, outp, len*sizeof(*bfr));
135 long FFAudioStream::used()
137 long len = inp>=outp ? inp-outp : inp-bfr + lmt-outp;
140 long FFAudioStream::avail()
143 if( in1 >= lmt ) in1 = bfr;
144 long len = outp >= in1 ? outp-in1 : outp-bfr + lmt-in1;
147 void FFAudioStream::reset() // clear bfr
152 void FFAudioStream::iseek(int64_t ofs)
154 outp = inp - ofs*nch;
155 if( outp < bfr ) outp += sz*nch;
158 float *FFAudioStream::get_outp(int ofs)
165 int64_t FFAudioStream::put_inp(int ofs)
168 return (inp-outp) / nch;
171 int FFAudioStream::write(const float *fp, long len)
179 while( --k >= 0 ) *ip++ = *fp++;
180 if( ip >= lmt ) ip = bfr;
186 int FFAudioStream::zero(long len)
194 while( --k >= 0 ) *ip++ = 0;
195 if( ip >= lmt ) ip = bfr;
201 // does not advance outp
202 int FFAudioStream::read(double *dp, long len, int ch)
205 float *op = outp + ch;
206 float *lmt1 = lmt + nch-1;
208 int k = (lmt1 - op) / nch;
211 while( --k >= 0 ) { *dp++ = *op; op += nch; }
212 if( op >= lmt ) op -= sz*nch;
217 // load linear buffer, no wrapping allowed, does not advance inp
218 int FFAudioStream::write(const double *dp, long len, int ch)
221 float *ip = inp + ch;
222 while( --n >= 0 ) { *ip = *dp++; ip += nch; }
227 FFStream::FFStream(FFMPEG *ffmpeg, AVStream *st, int idx)
229 this->ffmpeg = ffmpeg;
232 frm_lock = new Mutex("FFStream::frm_lock");
238 nudge = AV_NOPTS_VALUE;
240 reading = writing = 0;
246 FFStream::~FFStream()
248 if( reading > 0 || writing > 0 ) avcodec_close(st->codec);
249 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
250 while( frms.first ) frms.remove(frms.first);
251 if( filter_graph ) avfilter_graph_free(&filter_graph);
252 if( frame ) av_frame_free(&frame);
253 if( fframe ) av_frame_free(&fframe);
254 bsfilter.remove_all_objects();
258 void FFStream::ff_lock(const char *cp)
260 FFMPEG::fflock.lock(cp);
263 void FFStream::ff_unlock()
265 FFMPEG::fflock.unlock();
268 void FFStream::queue(FFrame *frm)
270 frm_lock->lock("FFStream::queue");
274 ffmpeg->mux_lock->unlock();
277 void FFStream::dequeue(FFrame *frm)
279 frm_lock->lock("FFStream::dequeue");
281 frms.remove_pointer(frm);
285 int FFStream::encode_activate()
288 writing = ffmpeg->encode_activate();
292 int FFStream::decode_activate()
294 if( reading < 0 && (reading=ffmpeg->decode_activate()) > 0 ) {
295 ff_lock("FFStream::decode_activate");
297 AVDictionary *copts = 0;
298 av_dict_copy(&copts, ffmpeg->opts, 0);
300 // this should be avformat_copy_context(), but no copy avail
301 ret = avformat_open_input(&fmt_ctx, ffmpeg->fmt_ctx->filename, NULL, &copts);
303 ret = avformat_find_stream_info(fmt_ctx, 0);
304 st = fmt_ctx->streams[idx];
307 AVCodecID codec_id = st->codec->codec_id;
308 AVCodec *decoder = avcodec_find_decoder(codec_id);
309 ret = avcodec_open2(st->codec, decoder, &copts);
313 eprintf("FFStream::decode_activate: open decoder failed\n");
316 eprintf("FFStream::decode_activate: can't clone input file\n");
317 av_dict_free(&copts);
323 int FFStream::read_packet()
325 av_packet_unref(ipkt);
326 int ret = av_read_frame(fmt_ctx, ipkt);
327 if( ret >= 0 ) return 1;
329 if( ret == AVERROR_EOF ) return 0;
330 ff_err(ret, "FFStream::read_packet: av_read_frame failed\n");
335 int FFStream::decode(AVFrame *frame)
341 while( ret >= 0 && !flushed && --retries >= 0 && !got_frame ) {
346 if( !ret ) ipkt->stream_index = st->index;
348 if( ipkt->stream_index == st->index ) {
349 while( (ipkt->size > 0 || !ipkt->data) && !got_frame ) {
350 ret = decode_frame(frame, got_frame);
351 if( ret < 0 || !ipkt->data ) break;
364 fprintf(stderr, "FFStream::decode: Retry limit\n");
368 fprintf(stderr, "FFStream::decode: failed\n");
373 int FFStream::load_filter(AVFrame *frame)
375 int ret = av_buffersrc_add_frame_flags(buffersrc_ctx,
376 frame, AV_BUFFERSRC_FLAG_KEEP_REF);
378 av_frame_unref(frame);
379 eprintf("FFStream::load_filter: av_buffersrc_add_frame_flags failed\n");
384 int FFStream::read_filter(AVFrame *frame)
386 int ret = av_buffersink_get_frame(buffersink_ctx, frame);
388 if( ret == AVERROR(EAGAIN) ) return 0;
389 if( ret == AVERROR_EOF ) { st_eof(1); return -1; }
390 ff_err(ret, "FFStream::read_filter: av_buffersink_get_frame failed\n");
396 int FFStream::read_frame(AVFrame *frame)
398 if( !filter_graph || !buffersrc_ctx || !buffersink_ctx )
399 return decode(frame);
400 if( !fframe && !(fframe=av_frame_alloc()) ) {
401 fprintf(stderr, "FFStream::read_frame: av_frame_alloc failed\n");
405 while( !flushed && !(ret=read_filter(frame)) ) {
406 if( (ret=decode(fframe)) < 0 ) break;
407 if( ret > 0 && (ret=load_filter(fframe)) < 0 ) break;
412 FFAudioStream::FFAudioStream(FFMPEG *ffmpeg, AVStream *strm, int idx)
413 : FFStream(ffmpeg, strm, idx)
415 channel0 = channels = 0;
418 seek_pos = curr_pos = 0;
420 resample_context = 0;
429 bfr = new float[bsz];
434 FFAudioStream::~FFAudioStream()
436 if( resample_context ) swr_free(&resample_context);
441 int FFAudioStream::load_history(uint8_t **data, int len)
443 float *samples = *(float **)data;
444 if( resample_context ) {
445 if( len > aud_bfr_sz ) {
451 aud_bfr = new float[aud_bfr_sz*channels];
453 int ret = swr_convert(resample_context,
454 (uint8_t**)&aud_bfr, aud_bfr_sz, (const uint8_t**)data, len);
456 ff_err(ret, "FFAudioStream::load_history: swr_convert failed\n");
462 // biggest user bfr since seek + frame
463 realloc(mbsz + len + 1, channels);
468 int FFAudioStream::decode_frame(AVFrame *frame, int &got_frame)
470 int ret = avcodec_decode_audio4(st->codec, frame, &got_frame, ipkt);
472 ff_err(ret, "FFAudioStream::decode_frame: Could not read audio frame\n");
478 int FFAudioStream::encode_activate()
480 if( writing >= 0 ) return writing;
481 AVCodecContext *ctx = st->codec;
482 frame_sz = ctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE ?
483 10000 : ctx->frame_size;
484 return FFStream::encode_activate();
487 int FFAudioStream::nb_samples()
489 AVCodecContext *ctx = st->codec;
490 return ctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE ?
491 10000 : ctx->frame_size;
494 int64_t FFAudioStream::load_buffer(double ** const sp, int len)
496 reserve(len+1, st->codec->channels);
497 for( int ch=0; ch<nch; ++ch )
498 write(sp[ch], len, ch);
502 int FFAudioStream::in_history(int64_t pos)
504 if( pos > curr_pos ) return 0;
505 int64_t len = curr_pos - seek_pos;
506 if( len > sz ) len = sz;
507 if( pos < curr_pos - len ) return 0;
512 int FFAudioStream::init_frame(AVFrame *frame)
514 AVCodecContext *ctx = st->codec;
515 frame->nb_samples = frame_sz;
516 frame->format = ctx->sample_fmt;
517 frame->channel_layout = ctx->channel_layout;
518 frame->sample_rate = ctx->sample_rate;
519 int ret = av_frame_get_buffer(frame, 0);
521 ff_err(ret, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
525 int FFAudioStream::load(int64_t pos, int len)
527 if( audio_seek(pos) < 0 ) return -1;
528 if( mbsz < len ) mbsz = len;
530 int64_t end_pos = pos + len;
531 if( !frame && !(frame=av_frame_alloc()) ) {
532 fprintf(stderr, "FFAudioStream::load: av_frame_alloc failed\n");
535 for( int i=0; ret>=0 && !flushed && curr_pos<end_pos && i<1000; ++i ) {
536 ret = read_frame(frame);
538 load_history(&frame->extended_data[0], frame->nb_samples);
539 curr_pos += frame->nb_samples;
542 if( end_pos > curr_pos ) {
543 zero(end_pos - curr_pos);
546 return curr_pos - pos;
549 int FFAudioStream::audio_seek(int64_t pos)
551 if( decode_activate() < 0 ) return -1;
552 if( in_history(pos) ) {
553 iseek(curr_pos - pos);
556 if( pos == curr_pos ) return 0;
557 if( !st->codec || !st->codec->codec ) return -1;
558 avcodec_flush_buffers(st->codec);
559 double secs = (double)pos / sample_rate;
560 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
561 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
562 avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, tstmp, INT64_MAX, 0);
563 seek_pos = curr_pos = pos;
565 mbsz = 0; flushed = 0; need_packet = 1;
569 int FFAudioStream::encode(double **samples, int len)
571 if( encode_activate() <= 0 ) return -1;
574 int64_t count = load_buffer(samples, len);
577 while( ret >= 0 && count >= frame_sz ) {
578 frm = new FFrame(this);
579 if( (ret=frm->initted()) < 0 ) break;
580 AVFrame *frame = *frm;
581 float *bfrp = get_outp(frame_sz);
582 ret = swr_convert(resample_context,
583 (uint8_t **)frame->extended_data, frame_sz,
584 (const uint8_t **)&bfrp, frame_sz);
586 ff_err(ret, "FFAudioStream::encode: swr_convert failed\n");
589 frm->queue(curr_pos);
591 curr_pos += frame_sz;
596 return ret >= 0 ? 0 : 1;
599 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx)
600 : FFStream(ffmpeg, strm, idx)
605 seek_pos = curr_pos = 0;
610 FFVideoStream::~FFVideoStream()
612 if( convert_ctx ) sws_freeContext(convert_ctx);
615 int FFVideoStream::decode_frame(AVFrame *frame, int &got_frame)
617 int ret = avcodec_decode_video2(st->codec, frame, &got_frame, ipkt);
619 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame\n");
627 int FFVideoStream::load(VFrame *vframe, int64_t pos)
629 if( video_seek(pos) < 0 ) return -1;
630 if( !frame && !(frame=av_frame_alloc()) ) {
631 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
635 for( int i=0; ret>=0 && !flushed && curr_pos<=pos && i<1000; ++i ) {
636 ret = read_frame(frame);
639 AVCodecContext *ctx = st->codec;
640 ret = convert_cmodel(vframe, (AVPicture *)frame,
641 ctx->pix_fmt, ctx->width, ctx->height);
643 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
647 int FFVideoStream::video_seek(int64_t pos)
649 if( decode_activate() < 0 ) return -1;
650 // if close enough, just read up to current
651 // 3*gop_size seems excessive, but less causes tears
652 int gop = 3*st->codec->gop_size;
653 if( gop < 4 ) gop = 4;
654 if( gop > 64 ) gop = 64;
655 if( pos >= curr_pos && pos <= curr_pos + gop ) return 0;
656 if( !st->codec || !st->codec->codec ) return -1;
657 avcodec_flush_buffers(st->codec);
658 // back up a few frames to read up to current to help repair damages
659 if( (pos-=gop) < 0 ) pos = 0;
660 double secs = (double)pos / frame_rate;
661 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
662 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
663 avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, tstmp, INT64_MAX, 0);
664 seek_pos = curr_pos = pos;
666 flushed = 0; need_packet = 1;
670 int FFVideoStream::init_frame(AVFrame *picture)
672 AVCodecContext *ctx = st->codec;
673 picture->format = ctx->pix_fmt;
674 picture->width = ctx->width;
675 picture->height = ctx->height;
676 int ret = av_frame_get_buffer(picture, 32);
680 int FFVideoStream::encode(VFrame *vframe)
682 if( encode_activate() <= 0 ) return -1;
684 FFrame *picture = new FFrame(this);
685 int ret = picture->initted();
687 AVFrame *frame = *picture;
688 frame->pts = curr_pos;
689 AVCodecContext *ctx = st->codec;
690 ret = convert_pixfmt(vframe, (AVPicture*)frame,
691 ctx->pix_fmt, ctx->width, ctx->height);
694 picture->queue(curr_pos);
698 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
701 return ret >= 0 ? 0 : 1;
705 PixelFormat FFVideoStream::color_model_to_pix_fmt(int color_model)
707 switch( color_model ) {
708 case BC_YUV422: return AV_PIX_FMT_YUYV422;
709 case BC_RGB888: return AV_PIX_FMT_RGB24;
710 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
711 case BC_BGR8888: return AV_PIX_FMT_BGR0;
712 case BC_BGR888: return AV_PIX_FMT_BGR24;
713 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
714 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
715 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
716 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
717 case BC_RGB565: return AV_PIX_FMT_RGB565;
718 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
719 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
723 return AV_PIX_FMT_NB;
726 int FFVideoStream::pix_fmt_to_color_model(PixelFormat pix_fmt)
729 case AV_PIX_FMT_YUYV422: return BC_YUV422;
730 case AV_PIX_FMT_RGB24: return BC_RGB888;
731 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
732 case AV_PIX_FMT_BGR0: return BC_BGR8888;
733 case AV_PIX_FMT_BGR24: return BC_BGR888;
734 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
735 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
736 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
737 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
738 case AV_PIX_FMT_RGB565: return BC_RGB565;
739 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
740 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
744 return BC_TRANSPARENCY;
747 int FFVideoStream::convert_picture_vframe(VFrame *frame,
748 AVPicture *ip, PixelFormat ifmt, int iw, int ih)
751 int cmodel = frame->get_color_model();
752 PixelFormat ofmt = color_model_to_pix_fmt(cmodel);
753 if( ofmt == AV_PIX_FMT_NB ) return -1;
754 int size = avpicture_fill(&opic, frame->get_data(), ofmt,
755 frame->get_w(), frame->get_h());
756 if( size < 0 ) return -1;
758 // transfer line sizes must match also
759 int planar = BC_CModels::is_planar(cmodel);
760 int packed_width = !planar ? frame->get_bytes_per_line() :
761 BC_CModels::calculate_pixelsize(cmodel) * frame->get_w();
762 if( packed_width != opic.linesize[0] ) return -1;
765 // override avpicture_fill() for planar types
766 opic.data[0] = frame->get_y();
767 opic.data[1] = frame->get_u();
768 opic.data[2] = frame->get_v();
771 convert_ctx = sws_getCachedContext(convert_ctx, iw, ih, ifmt,
772 frame->get_w(), frame->get_h(), ofmt, SWS_BICUBIC, NULL, NULL, NULL);
774 fprintf(stderr, "FFVideoStream::convert_picture_frame:"
775 " sws_getCachedContext() failed\n");
778 int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ih,
779 opic.data, opic.linesize);
781 ff_err(ret, "FFVideoStream::convert_picture_frame: sws_scale() failed\n");
787 int FFVideoStream::convert_cmodel(VFrame *frame,
788 AVPicture *ip, PixelFormat ifmt, int iw, int ih)
790 // try direct transfer
791 if( !convert_picture_vframe(frame, ip, ifmt, iw, ih) ) return 1;
792 // use indirect transfer
793 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
795 for( int i = 0; i <desc->nb_components; ++i ) {
796 int bits = desc->comp[i].depth_minus1 + 1;
797 if( bits > max_bits ) max_bits = bits;
799 // from libavcodec/pixdesc.c
800 #define pixdesc_has_alpha(pixdesc) ((pixdesc)->nb_components == 2 || \
801 (pixdesc)->nb_components == 4 || (pixdesc)->flags & AV_PIX_FMT_FLAG_PAL)
802 int icolor_model = pixdesc_has_alpha(desc) ?
803 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
804 (max_bits > 8 ? BC_RGB161616 : BC_RGB888) ;
805 VFrame vframe(iw, ih, icolor_model);
806 if( convert_picture_vframe(&vframe, ip, ifmt, iw, ih) ) return -1;
807 frame->transfer_from(&vframe);
811 int FFVideoStream::convert_vframe_picture(VFrame *frame,
812 AVPicture *op, PixelFormat ofmt, int ow, int oh)
815 int cmodel = frame->get_color_model();
816 PixelFormat ifmt = color_model_to_pix_fmt(cmodel);
817 if( ifmt == AV_PIX_FMT_NB ) return -1;
818 int size = avpicture_fill(&opic, frame->get_data(), ifmt,
819 frame->get_w(), frame->get_h());
820 if( size < 0 ) return -1;
822 // transfer line sizes must match also
823 int planar = BC_CModels::is_planar(cmodel);
824 int packed_width = !planar ? frame->get_bytes_per_line() :
825 BC_CModels::calculate_pixelsize(cmodel) * frame->get_w();
826 if( packed_width != opic.linesize[0] ) return -1;
829 // override avpicture_fill() for planar types
830 opic.data[0] = frame->get_y();
831 opic.data[1] = frame->get_u();
832 opic.data[2] = frame->get_v();
835 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(), ifmt,
836 ow, oh, ofmt, SWS_BICUBIC, NULL, NULL, NULL);
838 fprintf(stderr, "FFVideoStream::convert_frame_picture:"
839 " sws_getCachedContext() failed\n");
842 int ret = sws_scale(convert_ctx, opic.data, opic.linesize, 0, frame->get_h(),
843 op->data, op->linesize);
845 ff_err(ret, "FFVideoStream::convert_frame_picture: sws_scale() failed\n");
851 int FFVideoStream::convert_pixfmt(VFrame *frame,
852 AVPicture *op, PixelFormat ofmt, int ow, int oh)
854 // try direct transfer
855 if( !convert_vframe_picture(frame, op, ofmt, ow, oh) ) return 0;
856 // use indirect transfer
857 int colormodel = frame->get_color_model();
858 int bits = BC_CModels::calculate_pixelsize(colormodel) * 8;
859 bits /= BC_CModels::components(colormodel);
860 int icolor_model = BC_CModels::has_alpha(colormodel) ?
861 (bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
862 (bits > 8 ? BC_RGB161616: BC_RGB888) ;
863 VFrame vframe(frame->get_w(), frame->get_h(), icolor_model);
864 vframe.transfer_from(frame);
865 if( convert_vframe_picture(&vframe, op, ofmt, ow, oh) ) return 1;
870 FFMPEG::FFMPEG(FileBase *file_base)
873 this->file_base = file_base;
874 memset(file_format,0,sizeof(file_format));
875 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
876 flow_lock = new Condition(1,"FFStream::flow_lock",0);
879 decoding = encoding = 0;
880 has_audio = has_video = 0;
883 opt_video_filter = 0;
884 opt_audio_filter = 0;
885 char option_path[BCTEXTLEN];
886 set_option_path(option_path, "%s", "ffmpeg.opts");
887 read_options(option_path, opts);
892 ff_lock("FFMPEG::~FFMPEG()");
894 ffaudio.remove_all_objects();
895 ffvideo.remove_all_objects();
896 if( encoding ) avformat_free_context(fmt_ctx);
901 delete opt_video_filter;
902 delete opt_audio_filter;
905 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
907 const int *p = codec->supported_samplerates;
908 if( !p ) return sample_rate;
910 if( *p == sample_rate ) return *p;
916 static inline AVRational std_frame_rate(int i)
918 static const int m1 = 1001*12, m2 = 1000*12;
919 static const int freqs[] = {
920 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
921 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
923 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
924 return (AVRational) { freq, 1001*12 };
927 AVRational FFMPEG::check_frame_rate(AVCodec *codec, double frame_rate)
929 const AVRational *p = codec->supported_framerates;
930 AVRational rate, best_rate = (AVRational) { 0, 0 };
931 double max_err = 1.; int i = 0;
932 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
933 double framerate = (double) rate.num / rate.den;
934 double err = fabs(frame_rate/framerate - 1.);
935 if( err >= max_err ) continue;
939 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
942 AVRational FFMPEG::to_sample_aspect_ratio(double aspect_ratio)
945 int height = 1000000, width = height * aspect_ratio;
947 MWindow::create_aspect_ratio(w, h, width, height);
948 return (AVRational){(int)w, (int)h};
951 return (AVRational){1, 1};
955 AVRational FFMPEG::to_time_base(int sample_rate)
957 return (AVRational){1, sample_rate};
960 extern void get_exe_path(char *result); // from main.C
962 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
965 strcat(path, "/ffmpeg/");
966 path += strlen(path);
969 vsprintf(path, fmt, ap);
973 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
978 set_option_path(path, "%s/%s", type, spec);
981 int FFMPEG::get_format(char *format, const char *path, char *spec)
983 char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
984 get_option_path(option_path, path, spec);
985 FILE *fp = fopen(option_path,"r");
988 if( !fgets(line, sizeof(line), fp) ) ret = 1;
990 line[sizeof(line)-1] = 0;
991 ret = scan_option_line(line, format, codec);
997 int FFMPEG::get_file_format()
1000 char audio_format[BCSTRLEN], video_format[BCSTRLEN];
1001 file_format[0] = audio_format[0] = video_format[0] = 0;
1002 Asset *asset = file_base->asset;
1003 if( !ret && asset->audio_data )
1004 ret = get_format(audio_format, "audio", asset->acodec);
1005 if( !ret && asset->video_data )
1006 ret = get_format(video_format, "video", asset->vcodec);
1007 if( !ret && !audio_format[0] && !video_format[0] )
1009 if( !ret && audio_format[0] && video_format[0] &&
1010 strcmp(audio_format, video_format) ) ret = -1;
1012 strcpy(file_format, audio_format[0] ? audio_format : video_format);
1016 int FFMPEG::scan_option_line(char *cp, char *tag, char *val)
1018 while( *cp == ' ' || *cp == '\t' ) ++cp;
1020 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' ) ++cp;
1022 if( !len || len > BCSTRLEN-1 ) return 1;
1023 while( bp < cp ) *tag++ = *bp++;
1025 while( *cp == ' ' || *cp == '\t' ) ++cp;
1026 if( *cp == '=' ) ++cp;
1027 while( *cp == ' ' || *cp == '\t' ) ++cp;
1029 while( *cp && *cp != '\n' ) ++cp;
1031 if( len > BCTEXTLEN-1 ) return 1;
1032 while( bp < cp ) *val++ = *bp++;
1037 int FFMPEG::get_encoder(const char *options,
1038 char *format, char *codec, char *bsfilter, char *bsargs)
1040 FILE *fp = fopen(options,"r");
1042 eprintf("FFMPEG::get_encoder: options open failed %s\n",options);
1045 if( get_encoder(fp, format, codec, bsfilter, bsargs) )
1046 eprintf(_("FFMPEG::get_encoder:"
1047 " err: format/codec not found %s\n"), options);
1052 int FFMPEG::get_encoder(FILE *fp,
1053 char *format, char *codec, char *bsfilter, char *bsargs)
1055 format[0] = codec[0] = bsfilter[0] = bsargs[0] = 0;
1056 char line[BCTEXTLEN];
1057 if( !fgets(line, sizeof(line), fp) ) return 1;
1058 line[sizeof(line)-1] = 0;
1059 if( scan_option_line(line, format, codec) ) return 1;
1061 while( *cp && *cp != '|' ) ++cp;
1062 if( !*cp ) return 0;
1063 if( scan_option_line(cp+1, bsfilter, bsargs) ) return 1;
1064 do { *cp-- = 0; } while( cp>=codec && (*cp==' ' || *cp == '\t' ) );
1068 int FFMPEG::read_options(const char *options, AVDictionary *&opts)
1070 FILE *fp = fopen(options,"r");
1072 int ret = read_options(fp, options, opts);
1077 int FFMPEG::scan_options(const char *options, AVDictionary *&opts)
1079 FILE *fp = fmemopen((void *)options,strlen(options),"r");
1081 int ret = read_options(fp, options, opts);
1086 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
1088 int ret = 0, no = 0;
1089 char line[BCTEXTLEN];
1090 while( !ret && fgets(line, sizeof(line), fp) ) {
1091 line[sizeof(line)-1] = 0;
1093 if( line[0] == '#' ) continue;
1094 if( line[0] == '\n' ) continue;
1095 char key[BCSTRLEN], val[BCTEXTLEN];
1096 if( scan_option_line(line, key, val) ) {
1097 eprintf(_("FFMPEG::read_options:"
1098 " err reading %s: line %d\n"), options, no);
1102 if( !strcmp(key, "duration") )
1103 opt_duration = strtod(val, 0);
1104 if( !strcmp(key, "video_filter") )
1105 opt_video_filter = cstrdup(val);
1106 if( !strcmp(key, "audio_filter") )
1107 opt_audio_filter = cstrdup(val);
1108 else if( !strcmp(key, "loglevel") )
1111 av_dict_set(&opts, key, val, 0);
1117 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
1119 char option_path[BCTEXTLEN];
1120 set_option_path(option_path, "%s", options);
1121 return read_options(option_path, opts);
1124 int FFMPEG::load_options(const char *path, char *bfr, int len)
1127 FILE *fp = fopen(path, "r");
1129 fgets(bfr, len, fp); // skip hdr
1130 len = fread(bfr, 1, len-1, fp);
1131 if( len < 0 ) len = 0;
1137 void FFMPEG::set_loglevel(const char *ap)
1139 if( !ap || !*ap ) return;
1144 { "quiet" , AV_LOG_QUIET },
1145 { "panic" , AV_LOG_PANIC },
1146 { "fatal" , AV_LOG_FATAL },
1147 { "error" , AV_LOG_ERROR },
1148 { "warning", AV_LOG_WARNING },
1149 { "info" , AV_LOG_INFO },
1150 { "verbose", AV_LOG_VERBOSE },
1151 { "debug" , AV_LOG_DEBUG },
1153 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
1154 if( !strcmp(log_levels[i].name, ap) ) {
1155 av_log_set_level(log_levels[i].level);
1159 av_log_set_level(atoi(ap));
1162 double FFMPEG::to_secs(int64_t time, AVRational time_base)
1164 double base_time = time == AV_NOPTS_VALUE ? 0 :
1165 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
1166 return base_time / AV_TIME_BASE;
1169 int FFMPEG::info(char *text, int len)
1171 if( len <= 0 ) return 0;
1172 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
1174 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1175 AVStream *st = fmt_ctx->streams[i];
1176 AVCodecContext *avctx = st->codec;
1177 report(_("stream %d, id 0x%06x:\n"), i, avctx->codec_id);
1178 const AVCodecDescriptor *desc = avcodec_descriptor_get(avctx->codec_id);
1179 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1180 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
1181 double frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
1182 report(" video %s",desc ? desc->name : " (unkn)");
1183 report(" %dx%d %5.2f", avctx->width, avctx->height, frame_rate);
1184 const char *pfn = av_get_pix_fmt_name(avctx->pix_fmt);
1185 report(" pix %s\n", pfn ? pfn : "(unkn)");
1186 double secs = to_secs(st->duration, st->time_base);
1187 int64_t length = secs * frame_rate + 0.5;
1188 report(" %jd frms %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 else if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1195 int sample_rate = avctx->sample_rate;
1196 const char *fmt = av_get_sample_fmt_name(avctx->sample_fmt);
1197 report(" audio %s",desc ? desc->name : " (unkn)");
1198 report(" %dch %s %d",avctx->channels, fmt, sample_rate);
1199 int sample_bits = av_get_bits_per_sample(avctx->codec_id);
1200 report(" %dbits\n", sample_bits);
1201 double secs = to_secs(st->duration, st->time_base);
1202 int64_t length = secs * sample_rate + 0.5;
1203 report(" %jd smpl %0.2f secs", length, secs);
1204 int hrs = secs/3600; secs -= hrs*3600;
1205 int mins = secs/60; secs -= mins*60;
1206 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1209 report(_(" codec_type unknown\n"));
1212 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
1213 report("program %d", i+1);
1214 AVProgram *pgrm = fmt_ctx->programs[i];
1215 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j )
1216 report(", %d", pgrm->stream_index[j]);
1220 AVDictionaryEntry *tag = 0;
1221 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
1222 report("%s=%s\n", tag->key, tag->value);
1231 int FFMPEG::init_decoder(const char *filename)
1233 ff_lock("FFMPEG::init_decoder");
1235 char file_opts[BCTEXTLEN];
1236 char *bp = strrchr(strcpy(file_opts, filename), '/');
1237 char *sp = strrchr(!bp ? file_opts : bp, '.');
1240 strcpy(sp, ".opts");
1241 fp = fopen(file_opts, "r");
1244 read_options(fp, file_opts, opts);
1248 load_options("decode.opts", opts);
1249 AVDictionary *fopts = 0;
1250 av_dict_copy(&fopts, opts, 0);
1251 int ret = avformat_open_input(&fmt_ctx, filename, NULL, &fopts);
1252 av_dict_free(&fopts);
1254 ret = avformat_find_stream_info(fmt_ctx, NULL);
1259 return !ret ? 0 : 1;
1262 int FFMPEG::open_decoder()
1265 if( stat(fmt_ctx->filename, &st) < 0 ) {
1266 eprintf("FFMPEG::open_decoder: can't stat file: %s\n",
1271 int64_t file_bits = 8 * st.st_size;
1272 if( !fmt_ctx->bit_rate && opt_duration > 0 )
1273 fmt_ctx->bit_rate = file_bits / opt_duration;
1276 if( fmt_ctx->bit_rate > 0 ) {
1277 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1278 AVStream *st = fmt_ctx->streams[i];
1279 if( st->duration != AV_NOPTS_VALUE ) continue;
1280 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
1281 st->duration = av_rescale(file_bits, st->time_base.den,
1282 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
1287 printf("FFMPEG::open_decoder: some stream times estimated\n");
1289 ff_lock("FFMPEG::open_decoder");
1291 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1292 AVStream *st = fmt_ctx->streams[i];
1293 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
1294 AVCodecContext *avctx = st->codec;
1295 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1297 FFVideoStream *vid = new FFVideoStream(this, st, i);
1298 int vidx = ffvideo.size();
1299 vstrm_index.append(ffidx(vidx, 0));
1300 ffvideo.append(vid);
1301 vid->width = avctx->width;
1302 vid->height = avctx->height;
1303 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
1304 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
1305 double secs = to_secs(st->duration, st->time_base);
1306 vid->length = secs * vid->frame_rate;
1307 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
1308 vid->nudge = st->start_time;
1310 if( opt_video_filter )
1311 vid->create_filter(opt_video_filter, avctx,avctx);
1313 else if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1315 FFAudioStream *aud = new FFAudioStream(this, st, i);
1316 int aidx = ffaudio.size();
1317 ffaudio.append(aud);
1318 aud->channel0 = astrm_index.size();
1319 aud->channels = avctx->channels;
1320 for( int ch=0; ch<aud->channels; ++ch )
1321 astrm_index.append(ffidx(aidx, ch));
1322 aud->sample_rate = avctx->sample_rate;
1323 double secs = to_secs(st->duration, st->time_base);
1324 aud->length = secs * aud->sample_rate;
1325 if( avctx->sample_fmt != AV_SAMPLE_FMT_FLT ) {
1326 uint64_t layout = av_get_default_channel_layout(avctx->channels);
1327 if( !layout ) layout = ((uint64_t)1<<aud->channels) - 1;
1328 aud->resample_context = swr_alloc_set_opts(NULL,
1329 layout, AV_SAMPLE_FMT_FLT, avctx->sample_rate,
1330 layout, avctx->sample_fmt, avctx->sample_rate,
1332 swr_init(aud->resample_context);
1334 aud->nudge = st->start_time;
1336 if( opt_audio_filter )
1337 aud->create_filter(opt_audio_filter, avctx,avctx);
1341 printf("FFMPEG::open_decoder: some stream have bad times\n");
1347 int FFMPEG::init_encoder(const char *filename)
1349 int fd = ::open(filename,O_WRONLY);
1350 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
1352 eprintf("FFMPEG::init_encoder: bad file path: %s\n", filename);
1356 int ret = get_file_format();
1358 eprintf("FFMPEG::init_encoder: bad file format: %s\n", filename);
1362 eprintf("FFMPEG::init_encoder: mismatch audio/video file format: %s\n", filename);
1365 ff_lock("FFMPEG::init_encoder");
1367 avformat_alloc_output_context2(&fmt_ctx, 0, file_format, filename);
1369 eprintf("FFMPEG::init_encoder: failed: %s\n", filename);
1374 load_options("encode.opts", opts);
1381 int FFMPEG::open_encoder(const char *type, const char *spec)
1384 Asset *asset = file_base->asset;
1385 char *filename = asset->path;
1386 AVDictionary *sopts = 0;
1387 av_dict_copy(&sopts, opts, 0);
1388 char option_path[BCTEXTLEN];
1389 set_option_path(option_path, "%s/%s.opts", type, type);
1390 read_options(option_path, sopts);
1391 get_option_path(option_path, type, spec);
1392 char format_name[BCSTRLEN], codec_name[BCTEXTLEN];
1393 char bsfilter[BCSTRLEN], bsargs[BCTEXTLEN];
1394 if( get_encoder(option_path, format_name, codec_name, bsfilter, bsargs) ) {
1395 eprintf("FFMPEG::open_encoder: get_encoder failed %s:%s\n",
1396 option_path, filename);
1401 ff_lock("FFMPEG::open_encoder");
1405 const AVCodecDescriptor *codec_desc = 0;
1406 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
1408 eprintf("FFMPEG::open_encoder: cant find codec %s:%s\n",
1409 codec_name, filename);
1413 codec_desc = avcodec_descriptor_get(codec->id);
1415 eprintf("FFMPEG::open_encoder: unknown codec %s:%s\n",
1416 codec_name, filename);
1421 st = avformat_new_stream(fmt_ctx, 0);
1423 eprintf("FFMPEG::open_encoder: cant create stream %s:%s\n",
1424 codec_name, filename);
1429 AVCodecContext *ctx = st->codec;
1430 switch( codec_desc->type ) {
1431 case AVMEDIA_TYPE_AUDIO: {
1433 eprintf("FFMPEG::open_encoder: duplicate audio %s:%s\n",
1434 codec_name, filename);
1439 if( scan_options(asset->ff_audio_options, sopts) ) {
1440 eprintf("FFMPEG::open_encoder: bad audio options %s:%s\n",
1441 codec_name, filename);
1445 if( asset->ff_audio_bitrate > 0 ) {
1446 ctx->bit_rate = asset->ff_audio_bitrate;
1448 sprintf(arg, "%d", asset->ff_audio_bitrate);
1449 av_dict_set(&sopts, "b", arg, 0);
1451 int aidx = ffaudio.size();
1452 int idx = aidx + ffvideo.size();
1453 FFAudioStream *aud = new FFAudioStream(this, st, idx);
1454 ffaudio.append(aud); fst = aud;
1455 aud->sample_rate = asset->sample_rate;
1456 ctx->channels = aud->channels = asset->channels;
1457 for( int ch=0; ch<aud->channels; ++ch )
1458 astrm_index.append(ffidx(aidx, ch));
1459 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
1460 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
1461 if( !ctx->sample_rate ) {
1462 eprintf("FFMPEG::open_audio_encode:"
1463 " check_sample_rate failed %s\n", filename);
1467 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
1468 ctx->sample_fmt = codec->sample_fmts[0];
1469 uint64_t layout = av_get_default_channel_layout(ctx->channels);
1470 aud->resample_context = swr_alloc_set_opts(NULL,
1471 layout, ctx->sample_fmt, aud->sample_rate,
1472 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
1474 swr_init(aud->resample_context);
1477 case AVMEDIA_TYPE_VIDEO: {
1479 eprintf("FFMPEG::open_encoder: duplicate video %s:%s\n",
1480 codec_name, filename);
1485 if( scan_options(asset->ff_video_options, sopts) ) {
1486 eprintf("FFMPEG::open_encoder: bad video options %s:%s\n",
1487 codec_name, filename);
1491 if( asset->ff_video_bitrate > 0 ) {
1492 ctx->bit_rate = asset->ff_video_bitrate;
1494 sprintf(arg, "%d", asset->ff_video_bitrate);
1495 av_dict_set(&sopts, "b", arg, 0);
1497 else if( asset->ff_video_quality > 0 ) {
1498 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
1499 ctx->qmin = ctx->qmax = asset->ff_video_quality;
1500 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
1501 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
1502 ctx->flags |= CODEC_FLAG_QSCALE;
1504 av_dict_set(&sopts, "flags", "+qscale", 0);
1505 sprintf(arg, "%d", asset->ff_video_quality);
1506 av_dict_set(&sopts, "qscale", arg, 0);
1507 sprintf(arg, "%d", ctx->global_quality);
1508 av_dict_set(&sopts, "global_quality", arg, 0);
1510 int vidx = ffvideo.size();
1511 int idx = vidx + ffaudio.size();
1512 FFVideoStream *vid = new FFVideoStream(this, st, idx);
1513 vstrm_index.append(ffidx(vidx, 0));
1514 ffvideo.append(vid); fst = vid;
1515 vid->width = asset->width;
1516 ctx->width = (vid->width+3) & ~3;
1517 vid->height = asset->height;
1518 ctx->height = (vid->height+3) & ~3;
1519 vid->frame_rate = asset->frame_rate;
1520 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset->aspect_ratio);
1521 ctx->pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
1522 AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
1523 if( !frame_rate.num || !frame_rate.den ) {
1524 eprintf("FFMPEG::open_audio_encode:"
1525 " check_frame_rate failed %s\n", filename);
1529 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
1530 st->time_base = ctx->time_base;
1534 eprintf("FFMPEG::open_encoder: not audio/video, %s:%s\n",
1535 codec_name, filename);
1540 ret = avcodec_open2(st->codec, codec, &sopts);
1542 ff_err(ret,"FFMPEG::open_encoder");
1543 eprintf("FFMPEG::open_encoder: open failed %s:%s\n",
1544 codec_name, filename);
1551 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
1552 st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
1553 if( fst && bsfilter[0] )
1554 fst->add_bsfilter(bsfilter, !bsargs[0] ? 0 : bsargs);
1558 av_dict_free(&sopts);
1562 int FFMPEG::close_encoder()
1565 if( encoding > 0 ) {
1566 av_write_trailer(fmt_ctx);
1567 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
1568 avio_closep(&fmt_ctx->pb);
1574 int FFMPEG::decode_activate()
1576 if( decoding < 0 ) {
1578 int npgrms = fmt_ctx->nb_programs;
1579 for( int i=0; i<npgrms; ++i ) {
1580 AVProgram *pgrm = fmt_ctx->programs[i];
1581 // first start time video stream
1582 int64_t vstart_time = -1;
1583 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1584 int st_idx = pgrm->stream_index[j];
1585 AVStream *st = fmt_ctx->streams[st_idx];
1586 AVCodecContext *avctx = st->codec;
1587 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1588 if( st->start_time == AV_NOPTS_VALUE ) continue;
1589 vstart_time = st->start_time;
1593 // max start time audio stream
1594 int64_t astart_time = -1;
1595 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1596 int st_idx = pgrm->stream_index[j];
1597 AVStream *st = fmt_ctx->streams[st_idx];
1598 AVCodecContext *avctx = st->codec;
1599 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1600 if( st->start_time == AV_NOPTS_VALUE ) continue;
1601 if( astart_time > st->start_time ) continue;
1602 astart_time = st->start_time;
1605 if( astart_time < 0 || vstart_time < 0 ) continue;
1606 // match program streams to max start_time
1607 int64_t nudge = vstart_time > astart_time ? vstart_time : astart_time;
1608 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1609 int st_idx = pgrm->stream_index[j];
1610 AVStream *st = fmt_ctx->streams[st_idx];
1611 AVCodecContext *avctx = st->codec;
1612 if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1613 for( int k=0; k<ffaudio.size(); ++k ) {
1614 if( ffaudio[k]->idx == st_idx )
1615 ffaudio[k]->nudge = nudge;
1618 else if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1619 for( int k=0; k<ffvideo.size(); ++k ) {
1620 if( ffvideo[k]->idx == st_idx )
1621 ffvideo[k]->nudge = nudge;
1626 int64_t vstart_time = 0, astart_time = 0;
1627 int nstreams = fmt_ctx->nb_streams;
1628 for( int i=0; i<nstreams; ++i ) {
1629 AVStream *st = fmt_ctx->streams[i];
1630 AVCodecContext *avctx = st->codec;
1631 switch( avctx->codec_type ) {
1632 case AVMEDIA_TYPE_VIDEO:
1633 if( st->start_time == AV_NOPTS_VALUE ) continue;
1634 if( vstart_time >= st->start_time ) continue;
1635 vstart_time = st->start_time;
1637 case AVMEDIA_TYPE_AUDIO:
1638 if( st->start_time == AV_NOPTS_VALUE ) continue;
1639 if( astart_time >= st->start_time ) continue;
1640 astart_time = st->start_time;
1644 int64_t nudge = vstart_time > astart_time ? vstart_time : astart_time;
1645 for( int k=0; k<ffvideo.size(); ++k ) {
1646 if( ffvideo[k]->nudge != AV_NOPTS_VALUE ) continue;
1647 ffvideo[k]->nudge = nudge;
1649 for( int k=0; k<ffaudio.size(); ++k ) {
1650 if( ffaudio[k]->nudge != AV_NOPTS_VALUE ) continue;
1651 ffaudio[k]->nudge = nudge;
1658 int FFMPEG::encode_activate()
1661 if( encoding < 0 ) {
1663 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
1664 (ret=avio_open(&fmt_ctx->pb, fmt_ctx->filename, AVIO_FLAG_WRITE)) < 0 ) {
1665 ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
1670 AVDictionary *fopts = 0;
1671 char option_path[BCTEXTLEN];
1672 set_option_path(option_path, "format/%s", file_format);
1673 read_options(option_path, fopts);
1674 ret = avformat_write_header(fmt_ctx, &fopts);
1675 av_dict_free(&fopts);
1677 ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
1686 int FFMPEG::audio_seek(int stream, int64_t pos)
1688 int aidx = astrm_index[stream].st_idx;
1689 FFAudioStream *aud = ffaudio[aidx];
1690 aud->audio_seek(pos);
1691 aud->seek_pos = aud->curr_pos = pos;
1695 int FFMPEG::video_seek(int stream, int64_t pos)
1697 int vidx = vstrm_index[stream].st_idx;
1698 FFVideoStream *vid = ffvideo[vidx];
1699 vid->video_seek(pos);
1700 vid->seek_pos = vid->curr_pos = pos;
1705 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
1707 if( !has_audio || chn >= astrm_index.size() ) return -1;
1708 int aidx = astrm_index[chn].st_idx;
1709 FFAudioStream *aud = ffaudio[aidx];
1710 if( aud->load(pos, len) < len ) return -1;
1711 int ch = astrm_index[chn].st_ch;
1712 return aud->read(samples,len,ch);
1715 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
1717 if( !has_video || layer >= vstrm_index.size() ) return -1;
1718 int vidx = vstrm_index[layer].st_idx;
1719 FFVideoStream *vid = ffvideo[vidx];
1720 return vid->load(vframe, pos);
1723 int FFMPEG::encode(int stream, double **samples, int len)
1725 FFAudioStream *aud = ffaudio[stream];
1726 return aud->encode(samples, len);
1730 int FFMPEG::encode(int stream, VFrame *frame)
1732 FFVideoStream *vid = ffvideo[stream];
1733 return vid->encode(frame);
1736 void FFMPEG::start_muxer()
1744 void FFMPEG::stop_muxer()
1753 void FFMPEG::flow_off()
1756 flow_lock->lock("FFMPEG::flow_off");
1760 void FFMPEG::flow_on()
1764 flow_lock->unlock();
1767 void FFMPEG::flow_ctl()
1770 flow_lock->lock("FFMPEG::flow_ctl");
1771 flow_lock->unlock();
1775 int FFMPEG::mux_audio(FFrame *frm)
1778 AVStream *st = frm->fst->st;
1779 AVCodecContext *ctx = st->codec;
1780 AVFrame *frame = *frm;
1781 AVRational tick_rate = {1, ctx->sample_rate};
1782 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
1784 int ret = avcodec_encode_audio2(ctx, pkt, frame, &got_packet);
1785 if( ret >= 0 && got_packet ) {
1786 frm->fst->bs_filter(pkt);
1787 av_packet_rescale_ts(pkt, ctx->time_base, st->time_base);
1788 pkt->stream_index = st->index;
1789 ret = av_interleaved_write_frame(fmt_ctx, pkt);
1792 ff_err(ret, "FFMPEG::mux_audio");
1793 return ret >= 0 ? 0 : 1;
1796 int FFMPEG::mux_video(FFrame *frm)
1799 AVStream *st = frm->fst->st;
1800 AVFrame *frame = *frm;
1801 frame->pts = frm->position;
1802 int ret = 1, got_packet = 0;
1803 if( fmt_ctx->oformat->flags & AVFMT_RAWPICTURE ) {
1804 /* a hack to avoid data copy with some raw video muxers */
1805 pkt->flags |= AV_PKT_FLAG_KEY;
1806 pkt->stream_index = st->index;
1807 AVPicture *picture = (AVPicture *)frame;
1808 pkt->data = (uint8_t *)picture;
1809 pkt->size = sizeof(AVPicture);
1810 pkt->pts = pkt->dts = frame->pts;
1814 ret = avcodec_encode_video2(st->codec, pkt, frame, &got_packet);
1815 if( ret >= 0 && got_packet ) {
1816 frm->fst->bs_filter(pkt);
1817 av_packet_rescale_ts(pkt, st->codec->time_base, st->time_base);
1818 pkt->stream_index = st->index;
1819 ret = av_interleaved_write_frame(fmt_ctx, pkt);
1822 ff_err(ret, "FFMPEG::mux_video");
1823 return ret >= 0 ? 0 : 1;
1829 double atm = -1, vtm = -1;
1830 FFrame *afrm = 0, *vfrm = 0;
1832 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
1833 FFStream *fst = ffaudio[i];
1834 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
1835 FFrame *frm = fst->frms.first;
1836 if( !frm ) { if( !done ) return; continue; }
1837 double tm = to_secs(frm->position, fst->st->codec->time_base);
1838 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
1840 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
1841 FFStream *fst = ffvideo[i];
1842 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
1843 FFrame *frm = fst->frms.first;
1844 if( !frm ) { if( !done ) return; continue; }
1845 double tm = to_secs(frm->position, fst->st->codec->time_base);
1846 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
1848 if( !demand ) flow_off();
1849 if( !afrm && !vfrm ) break;
1850 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
1851 vfrm->position, vfrm->fst->st->codec->time_base,
1852 afrm->position, afrm->fst->st->codec->time_base);
1853 FFrame *frm = v <= 0 ? vfrm : afrm;
1854 if( frm == afrm ) mux_audio(frm);
1855 if( frm == vfrm ) mux_video(frm);
1864 mux_lock->lock("FFMPEG::run");
1871 int FFMPEG::ff_total_audio_channels()
1873 return astrm_index.size();
1876 int FFMPEG::ff_total_astreams()
1878 return ffaudio.size();
1881 int FFMPEG::ff_audio_channels(int stream)
1883 return ffaudio[stream]->channels;
1886 int FFMPEG::ff_sample_rate(int stream)
1888 return ffaudio[stream]->sample_rate;
1891 const char* FFMPEG::ff_audio_format(int stream)
1893 AVStream *st = ffaudio[stream]->st;
1894 AVCodecID id = st->codec->codec_id;
1895 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
1896 return desc ? desc->name : "Unknown";
1899 int FFMPEG::ff_audio_pid(int stream)
1901 return ffaudio[stream]->st->id;
1904 int64_t FFMPEG::ff_audio_samples(int stream)
1906 return ffaudio[stream]->length;
1909 // find audio astream/channels with this program,
1910 // or all program audio channels (astream=-1)
1911 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
1915 int vidx = ffvideo[vstream]->idx;
1916 // find first program with this video stream
1917 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
1918 AVProgram *pgrm = fmt_ctx->programs[i];
1919 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
1920 int st_idx = pgrm->stream_index[j];
1921 AVStream *st = fmt_ctx->streams[st_idx];
1922 if( st->codec->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
1923 if( st_idx == vidx ) pidx = i;
1926 if( pidx < 0 ) return -1;
1928 int64_t channels = 0;
1929 AVProgram *pgrm = fmt_ctx->programs[pidx];
1930 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1931 int aidx = pgrm->stream_index[j];
1932 AVStream *st = fmt_ctx->streams[aidx];
1933 if( st->codec->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
1934 if( astream > 0 ) { --astream; continue; }
1936 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
1937 if( ffaudio[i]->idx == aidx ) astrm = i;
1939 if( ret < 0 ) ret = astrm;
1940 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
1941 channels |= mask << ffaudio[astrm]->channel0;
1943 if( !astream ) break;
1945 channel_mask = channels;
1950 int FFMPEG::ff_total_video_layers()
1952 return vstrm_index.size();
1955 int FFMPEG::ff_total_vstreams()
1957 return ffvideo.size();
1960 int FFMPEG::ff_video_width(int stream)
1962 return ffvideo[stream]->width;
1965 int FFMPEG::ff_video_height(int stream)
1967 return ffvideo[stream]->height;
1970 int FFMPEG::ff_set_video_width(int stream, int width)
1972 int w = ffvideo[stream]->width;
1973 ffvideo[stream]->width = width;
1977 int FFMPEG::ff_set_video_height(int stream, int height)
1979 int h = ffvideo[stream]->height;
1980 ffvideo[stream]->height = height;
1984 int FFMPEG::ff_coded_width(int stream)
1986 AVStream *st = ffvideo[stream]->st;
1987 return st->codec->coded_width;
1990 int FFMPEG::ff_coded_height(int stream)
1992 AVStream *st = ffvideo[stream]->st;
1993 return st->codec->coded_height;
1996 float FFMPEG::ff_aspect_ratio(int stream)
1998 return ffvideo[stream]->aspect_ratio;
2001 const char* FFMPEG::ff_video_format(int stream)
2003 AVStream *st = ffvideo[stream]->st;
2004 AVCodecID id = st->codec->codec_id;
2005 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2006 return desc ? desc->name : "Unknown";
2009 double FFMPEG::ff_frame_rate(int stream)
2011 return ffvideo[stream]->frame_rate;
2014 int64_t FFMPEG::ff_video_frames(int stream)
2016 return ffvideo[stream]->length;
2019 int FFMPEG::ff_video_pid(int stream)
2021 return ffvideo[stream]->st->id;
2025 int FFMPEG::ff_cpus()
2027 return file_base->file->cpus;
2030 int FFVideoStream::create_filter(const char *filter_spec,
2031 AVCodecContext *src_ctx, AVCodecContext *sink_ctx)
2033 avfilter_register_all();
2034 filter_graph = avfilter_graph_alloc();
2035 AVFilter *buffersrc = avfilter_get_by_name("buffer");
2036 AVFilter *buffersink = avfilter_get_by_name("buffersink");
2038 int ret = 0; char args[BCTEXTLEN];
2039 snprintf(args, sizeof(args),
2040 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
2041 src_ctx->width, src_ctx->height, src_ctx->pix_fmt,
2042 st->time_base.num, st->time_base.den,
2043 src_ctx->sample_aspect_ratio.num, src_ctx->sample_aspect_ratio.den);
2045 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2046 args, NULL, filter_graph);
2048 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2049 NULL, NULL, filter_graph);
2051 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
2052 (uint8_t*)&sink_ctx->pix_fmt, sizeof(sink_ctx->pix_fmt),
2053 AV_OPT_SEARCH_CHILDREN);
2055 ff_err(ret, "FFVideoStream::create_filter");
2057 ret = FFStream::create_filter(filter_spec);
2058 return ret >= 0 ? 0 : 1;
2061 int FFAudioStream::create_filter(const char *filter_spec,
2062 AVCodecContext *src_ctx, AVCodecContext *sink_ctx)
2064 avfilter_register_all();
2065 filter_graph = avfilter_graph_alloc();
2066 AVFilter *buffersrc = avfilter_get_by_name("abuffer");
2067 AVFilter *buffersink = avfilter_get_by_name("abuffersink");
2068 int ret = 0; char args[BCTEXTLEN];
2069 snprintf(args, sizeof(args),
2070 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
2071 st->time_base.num, st->time_base.den, src_ctx->sample_rate,
2072 av_get_sample_fmt_name(src_ctx->sample_fmt), src_ctx->channel_layout);
2074 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2075 args, NULL, filter_graph);
2077 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2078 NULL, NULL, filter_graph);
2080 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
2081 (uint8_t*)&sink_ctx->sample_fmt, sizeof(sink_ctx->sample_fmt),
2082 AV_OPT_SEARCH_CHILDREN);
2084 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
2085 (uint8_t*)&sink_ctx->channel_layout,
2086 sizeof(sink_ctx->channel_layout), AV_OPT_SEARCH_CHILDREN);
2088 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
2089 (uint8_t*)&sink_ctx->sample_rate, sizeof(sink_ctx->sample_rate),
2090 AV_OPT_SEARCH_CHILDREN);
2092 ff_err(ret, "FFAudioStream::create_filter");
2094 ret = FFStream::create_filter(filter_spec);
2095 return ret >= 0 ? 0 : 1;
2098 int FFStream::create_filter(const char *filter_spec)
2100 /* Endpoints for the filter graph. */
2101 AVFilterInOut *outputs = avfilter_inout_alloc();
2102 outputs->name = av_strdup("in");
2103 outputs->filter_ctx = buffersrc_ctx;
2104 outputs->pad_idx = 0;
2107 AVFilterInOut *inputs = avfilter_inout_alloc();
2108 inputs->name = av_strdup("out");
2109 inputs->filter_ctx = buffersink_ctx;
2110 inputs->pad_idx = 0;
2113 int ret = !outputs->name || !inputs->name ? -1 : 0;
2115 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
2116 &inputs, &outputs, NULL);
2118 ret = avfilter_graph_config(filter_graph, NULL);
2121 ff_err(ret, "FFStream::create_filter");
2122 avfilter_inout_free(&inputs);
2123 avfilter_inout_free(&outputs);
2127 void FFStream::add_bsfilter(const char *bsf, const char *ap)
2129 bsfilter.append(new BSFilter(bsf,ap));
2132 int FFStream::bs_filter(AVPacket *pkt)
2134 if( !bsfilter.size() ) return 0;
2135 av_packet_split_side_data(pkt);
2138 for( int i=0; i<bsfilter.size(); ++i ) {
2139 AVPacket bspkt = *pkt;
2140 ret = av_bitstream_filter_filter(bsfilter[i]->bsfc,
2141 st->codec, bsfilter[i]->args, &bspkt.data, &bspkt.size,
2142 pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY);
2143 if( ret < 0 ) break;
2144 int size = bspkt.size;
2145 uint8_t *data = bspkt.data;
2146 if( !ret && bspkt.data != pkt->data ) {
2148 data = (uint8_t *)av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
2149 if( !data ) { ret = AVERROR(ENOMEM); break; }
2150 memcpy(data, bspkt.data, size);
2151 memset(data+size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2155 pkt->side_data = 0; pkt->side_data_elems = 0;
2156 av_free_packet(pkt);
2157 ret = av_packet_from_data(&bspkt, data, size);
2158 if( ret < 0 ) break;
2163 ff_err(ret,"FFStream::bs_filter");