9 // work arounds (centos)
12 #define INT64_MAX 9223372036854775807LL
16 #include "bccmodels.h"
17 #include "fileffmpeg.h"
24 #define VIDEO_INBUF_SIZE 0x10000
25 #define AUDIO_INBUF_SIZE 0x10000
26 #define VIDEO_REFILL_THRESH 0
27 #define AUDIO_REFILL_THRESH 0x1000
29 Mutex FFMPEG::fflock("FFMPEG::fflock");
31 static void ff_err(int ret, const char *msg)
33 char errmsg[BCSTRLEN]; av_strerror(ret, errmsg, sizeof(errmsg));
34 fprintf(stderr,"%s: %s\n",msg, errmsg);
50 pkt.data = 0; pkt.size = 0;
53 FFrame::FFrame(FFStream *fst)
56 frm = av_frame_alloc();
57 init = fst->init_frame(frm);
65 void FFrame::queue(int64_t pos)
71 void FFrame::dequeue()
76 FFAudioHistory::FFAudioHistory()
86 FFAudioHistory::~FFAudioHistory()
92 void FFAudioHistory::reserve(long sz, int nch)
94 long isz = inp - outp;
96 if( this->sz < sz || this->nch != nch ) {
101 memmove(bfr, outp, isz*sizeof(*bfr));
106 void FFAudioHistory::realloc(long sz, int nch)
108 if( this->sz >= sz && this->nch == nch ) return;
109 long isz = used() * nch;
113 float *np = new float[bsz];
114 if( isz > 0 ) copy(np, isz);
118 delete [] bfr; bfr = np;
121 long FFAudioHistory::used()
123 long len = inp>=outp ? inp-outp : inp-bfr + lmt-outp;
126 long FFAudioHistory::avail()
129 if( in1 >= lmt ) in1 = bfr;
130 long len = outp >= in1 ? outp-in1 : outp-bfr + lmt-in1;
133 void FFAudioHistory::reset() // clear bfr
138 void FFAudioHistory::iseek(int64_t ofs)
140 outp = inp - ofs*nch;
141 if( outp < bfr ) outp += bsz;
144 float *FFAudioHistory::get_outp(int ofs)
151 int64_t FFAudioHistory::get_inp(int ofs)
154 return (inp-bfr) / nch;
157 int FFAudioHistory::write(const float *fp, long len)
164 while( --k >= 0 ) *inp++ = *fp++;
165 if( inp >= lmt ) inp -= bsz;
170 int FFAudioHistory::copy(float *fp, long len)
177 while( --k >= 0 ) *fp++ = *outp++;
178 if( outp >= lmt ) outp -= bsz;
183 int FFAudioHistory::zero(long len)
190 while( --k >= 0 ) *inp++ = 0;
191 if( inp >= lmt ) inp -= bsz;
196 int FFAudioHistory::read(double *dp, long len, int ch)
200 if( len > sz ) len = sz;
202 float *op = outp + ch;
204 int k = (lmt - outp) / nch;
207 while( --k >= 0 ) { *dp++ = *op; op += nch; }
208 if( op >= lmt ) op -= bsz;
213 // load linear buffer, no wrapping allowed, does not advance inp
214 int FFAudioHistory::write(const double *dp, long len, int ch)
217 if( !osz || !len ) return 0;
218 if( len > osz ) len = osz;
220 float *ip = inp + ch;
221 while( --n >= 0 ) { *ip = *dp++; ip += nch; }
226 FFStream::FFStream(FFMPEG *ffmpeg, AVStream *st, int idx)
228 this->ffmpeg = ffmpeg;
231 frm_lock = new Mutex("FFStream::frm_lock");
237 nudge = AV_NOPTS_VALUE;
239 reading = writing = 0;
245 FFStream::~FFStream()
247 if( reading > 0 || writing > 0 ) avcodec_close(st->codec);
248 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
249 while( frms.first ) frms.remove(frms.first);
250 if( filter_graph ) avfilter_graph_free(&filter_graph);
251 if( frame ) av_frame_free(&frame);
252 if( fframe ) av_frame_free(&fframe);
253 bsfilter.remove_all_objects();
257 void FFStream::ff_lock(const char *cp)
259 FFMPEG::fflock.lock(cp);
262 void FFStream::ff_unlock()
264 FFMPEG::fflock.unlock();
267 void FFStream::queue(FFrame *frm)
269 frm_lock->lock("FFStream::queue");
273 ffmpeg->mux_lock->unlock();
276 void FFStream::dequeue(FFrame *frm)
278 frm_lock->lock("FFStream::dequeue");
280 frms.remove_pointer(frm);
284 int FFStream::encode_activate()
287 writing = ffmpeg->encode_activate();
291 int FFStream::decode_activate()
293 if( reading < 0 && (reading=ffmpeg->decode_activate()) > 0 ) {
294 ff_lock("FFStream::decode_activate");
296 AVDictionary *copts = 0;
297 av_dict_copy(&copts, ffmpeg->opts, 0);
299 // this should be avformat_copy_context(), but no copy avail
300 ret = avformat_open_input(&fmt_ctx, ffmpeg->fmt_ctx->filename, NULL, &copts);
302 ret = avformat_find_stream_info(fmt_ctx, 0);
303 st = fmt_ctx->streams[idx];
306 AVCodecID codec_id = st->codec->codec_id;
307 AVCodec *decoder = avcodec_find_decoder(codec_id);
308 ret = avcodec_open2(st->codec, decoder, &copts);
312 fprintf(stderr, "FFStream::decode_activate: open decoder failed\n");
315 fprintf(stderr, "FFStream::decode_activate: can't clone input file\n");
316 av_dict_free(&copts);
322 int FFStream::read_packet()
324 av_packet_unref(ipkt);
325 int ret = av_read_frame(fmt_ctx, ipkt);
326 if( ret >= 0 ) return 1;
328 if( ret == AVERROR_EOF ) return 0;
329 fprintf(stderr, "FFStream::read_packet: av_read_frame failed\n");
334 int FFStream::decode(AVFrame *frame)
340 while( ret >= 0 && !flushed && --retries >= 0 && !got_frame ) {
345 if( !ret ) ipkt->stream_index = st->index;
347 if( ipkt->stream_index == st->index ) {
348 while( ipkt->size > 0 && !got_frame ) {
349 ret = decode_frame(frame, got_frame);
363 fprintf(stderr, "FFStream::decode: Retry limit\n");
367 fprintf(stderr, "FFStream::decode: failed\n");
372 int FFStream::load_filter(AVFrame *frame)
374 int ret = av_buffersrc_add_frame_flags(buffersrc_ctx,
375 frame, AV_BUFFERSRC_FLAG_KEEP_REF);
377 av_frame_unref(frame);
378 fprintf(stderr, "FFStream::load_filter: av_buffersrc_add_frame_flags failed\n");
383 int FFStream::read_filter(AVFrame *frame)
385 int ret = av_buffersink_get_frame(buffersink_ctx, frame);
387 if( ret == AVERROR(EAGAIN) ) return 0;
388 if( ret == AVERROR_EOF ) { st_eof(1); return -1; }
389 fprintf(stderr, "FFStream::read_filter: av_buffersink_get_frame failed\n");
395 int FFStream::read_frame(AVFrame *frame)
397 if( !filter_graph || !buffersrc_ctx || !buffersink_ctx )
398 return decode(frame);
399 if( !fframe && !(fframe=av_frame_alloc()) ) {
400 fprintf(stderr, "FFStream::read_frame: av_frame_alloc failed\n");
404 while( !flushed && !(ret=read_filter(frame)) ) {
405 if( (ret=decode(fframe)) < 0 ) break;
406 if( ret > 0 && (ret=load_filter(fframe)) < 0 ) break;
411 FFAudioStream::FFAudioStream(FFMPEG *ffmpeg, AVStream *strm, int idx)
412 : FFStream(ffmpeg, strm, idx)
414 channel0 = channels = 0;
417 seek_pos = curr_pos = 0;
419 resample_context = 0;
425 FFAudioStream::~FFAudioStream()
427 if( resample_context ) swr_free(&resample_context);
431 int FFAudioStream::load_history(float *&bfr, int len)
433 if( resample_context ) {
434 if( len > aud_bfr_sz ) {
440 aud_bfr = new float[aud_bfr_sz*channels];
442 int ret = swr_convert(resample_context,
443 (uint8_t**)&aud_bfr, aud_bfr_sz,
444 (const uint8_t**)&bfr, len);
446 fprintf(stderr, "FFAudioStream::load_history: swr_convert failed\n");
452 append_history(bfr, len);
456 int FFAudioStream::decode_frame(AVFrame *frame, int &got_frame)
458 int ret = avcodec_decode_audio4(st->codec, frame, &got_frame, ipkt);
460 fprintf(stderr, "FFAudioStream::decode_frame: Could not read audio frame\n");
466 int FFAudioStream::encode_activate()
468 if( writing >= 0 ) return writing;
469 AVCodecContext *ctx = st->codec;
470 frame_sz = ctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE ?
471 10000 : ctx->frame_size;
472 return FFStream::encode_activate();
475 int FFAudioStream::nb_samples()
477 AVCodecContext *ctx = st->codec;
478 return ctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE ?
479 10000 : ctx->frame_size;
482 void FFAudioStream::alloc_history(int len)
484 history.realloc(len+1, channels);
487 void FFAudioStream::reserve_history(int len)
489 history.reserve(len+1, st->codec->channels);
492 void FFAudioStream::append_history(const float *fp, int len)
494 // biggest user bfr since seek + length this frame
495 int hsz = mbsz + len;
497 history.write(fp, len);
500 int64_t FFAudioStream::load_buffer(double ** const sp, int len)
502 reserve_history(len);
503 int nch = st->codec->channels;
504 for( int ch=0; ch<nch; ++ch )
505 history.write(sp[ch], len, ch);
506 return history.get_inp(len);
509 void FFAudioStream::zero_history(int len)
514 float* FFAudioStream::get_history(int len)
516 return history.get_outp(len);
519 int FFAudioStream::in_history(int64_t pos)
521 if( pos > curr_pos ) return 0;
522 int64_t len = curr_pos - seek_pos;
523 if( len > history.sz ) len = history.sz;
524 if( pos < curr_pos - len ) return 0;
529 int FFAudioStream::init_frame(AVFrame *frame)
531 AVCodecContext *ctx = st->codec;
532 frame->nb_samples = frame_sz;
533 frame->format = ctx->sample_fmt;
534 frame->channel_layout = ctx->channel_layout;
535 frame->sample_rate = ctx->sample_rate;
536 int ret = av_frame_get_buffer(frame, 0);
538 fprintf(stderr, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
542 int FFAudioStream::load(int64_t pos, int len)
544 if( audio_seek(pos) < 0 ) return -1;
545 if( mbsz < len ) mbsz = len;
547 int64_t end_pos = pos + len;
548 if( !frame && !(frame=av_frame_alloc()) ) {
549 fprintf(stderr, "FFAudioStream::load: av_frame_alloc failed\n");
552 for( int i=0; ret>=0 && !flushed && curr_pos<end_pos && i<1000; ++i ) {
553 ret = read_frame(frame);
555 load_history((float *&)frame->extended_data[0], frame->nb_samples);
556 curr_pos += frame->nb_samples;
559 if( flushed && end_pos > curr_pos ) {
560 zero_history(end_pos - curr_pos);
563 return curr_pos - pos;
566 int FFAudioStream::audio_seek(int64_t pos)
568 if( decode_activate() < 0 ) return -1;
569 if( in_history(pos) ) {
570 history.iseek(curr_pos - pos);
573 if( pos == curr_pos ) return 0;
574 double secs = (double)pos / sample_rate;
575 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
576 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
577 avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, tstmp, INT64_MAX, 0);
578 seek_pos = curr_pos = pos;
585 int FFAudioStream::encode(double **samples, int len)
587 if( encode_activate() <= 0 ) return -1;
590 int64_t count = load_buffer(samples, len);
593 while( ret >= 0 && count >= frame_sz ) {
594 frm = new FFrame(this);
595 if( (ret=frm->initted()) < 0 ) break;
596 AVFrame *frame = *frm;
597 float *bfrp = get_history(frame_sz);
598 ret = swr_convert(resample_context,
599 (uint8_t **)frame->extended_data, frame_sz,
600 (const uint8_t **)&bfrp, frame_sz);
602 fprintf(stderr, "FFAudioStream::encode: swr_convert failed\n");
605 frm->queue(curr_pos);
607 curr_pos += frame_sz;
612 return ret >= 0 ? 0 : 1;
615 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx)
616 : FFStream(ffmpeg, strm, idx)
621 seek_pos = curr_pos = 0;
626 FFVideoStream::~FFVideoStream()
628 if( convert_ctx ) sws_freeContext(convert_ctx);
631 int FFVideoStream::decode_frame(AVFrame *frame, int &got_frame)
633 int ret = avcodec_decode_video2(st->codec, frame, &got_frame, ipkt);
635 fprintf(stderr, "FFVideoStream::decode_frame: Could not read video frame\n");
643 int FFVideoStream::load(VFrame *vframe, int64_t pos)
645 if( video_seek(pos) < 0 ) return -1;
646 if( !frame && !(frame=av_frame_alloc()) ) {
647 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
651 for( int i=0; ret>=0 && !flushed && curr_pos<=pos && i<1000; ++i ) {
652 ret = read_frame(frame);
655 AVCodecContext *ctx = st->codec;
656 ret = convert_cmodel(vframe, (AVPicture *)frame,
657 ctx->pix_fmt, ctx->width, ctx->height);
659 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
663 int FFVideoStream::video_seek(int64_t pos)
665 if( decode_activate() < 0 ) return -1;
666 // if close enough, just read up to current
667 // 3*gop_size seems excessive, but less causes tears
668 int gop = 3*st->codec->gop_size;
669 if( gop < 4 ) gop = 4;
670 if( gop > 64 ) gop = 64;
671 if( pos >= curr_pos && pos <= curr_pos + gop ) return 0;
672 // back up a few frames to read up to current to help repair damages
673 if( (pos-=gop) < 0 ) pos = 0;
674 double secs = (double)pos / frame_rate;
675 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
676 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
677 avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, tstmp, INT64_MAX, 0);
678 seek_pos = curr_pos = pos;
683 int FFVideoStream::init_frame(AVFrame *picture)
685 AVCodecContext *ctx = st->codec;
686 picture->format = ctx->pix_fmt;
687 picture->width = ctx->width;
688 picture->height = ctx->height;
689 int ret = av_frame_get_buffer(picture, 32);
693 int FFVideoStream::encode(VFrame *vframe)
695 if( encode_activate() <= 0 ) return -1;
697 FFrame *picture = new FFrame(this);
698 int ret = picture->initted();
700 AVFrame *frame = *picture;
701 frame->pts = curr_pos;
702 AVCodecContext *ctx = st->codec;
703 ret = convert_pixfmt(vframe, (AVPicture*)frame,
704 ctx->pix_fmt, ctx->width, ctx->height);
707 picture->queue(curr_pos);
711 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
714 return ret >= 0 ? 0 : 1;
718 PixelFormat FFVideoStream::color_model_to_pix_fmt(int color_model)
720 switch( color_model ) {
721 case BC_YUV422: return AV_PIX_FMT_YUYV422;
722 case BC_RGB888: return AV_PIX_FMT_RGB24;
723 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
724 case BC_BGR8888: return AV_PIX_FMT_BGR0;
725 case BC_BGR888: return AV_PIX_FMT_BGR24;
726 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
727 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
728 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
729 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
730 case BC_RGB565: return AV_PIX_FMT_RGB565;
731 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
732 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
736 return AV_PIX_FMT_NB;
739 int FFVideoStream::pix_fmt_to_color_model(PixelFormat pix_fmt)
742 case AV_PIX_FMT_YUYV422: return BC_YUV422;
743 case AV_PIX_FMT_RGB24: return BC_RGB888;
744 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
745 case AV_PIX_FMT_BGR0: return BC_BGR8888;
746 case AV_PIX_FMT_BGR24: return BC_BGR888;
747 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
748 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
749 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
750 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
751 case AV_PIX_FMT_RGB565: return BC_RGB565;
752 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
753 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
757 return BC_TRANSPARENCY;
760 int FFVideoStream::convert_picture_vframe(VFrame *frame,
761 AVPicture *ip, PixelFormat ifmt, int iw, int ih)
764 int cmodel = frame->get_color_model();
765 PixelFormat ofmt = color_model_to_pix_fmt(cmodel);
766 if( ofmt == AV_PIX_FMT_NB ) return -1;
767 int size = avpicture_fill(&opic, frame->get_data(), ofmt,
768 frame->get_w(), frame->get_h());
769 if( size < 0 ) return -1;
771 // transfer line sizes must match also
772 int planar = BC_CModels::is_planar(cmodel);
773 int packed_width = !planar ? frame->get_bytes_per_line() :
774 BC_CModels::calculate_pixelsize(cmodel) * frame->get_w();
775 if( packed_width != opic.linesize[0] ) return -1;
778 // override avpicture_fill() for planar types
779 opic.data[0] = frame->get_y();
780 opic.data[1] = frame->get_u();
781 opic.data[2] = frame->get_v();
784 convert_ctx = sws_getCachedContext(convert_ctx, iw, ih, ifmt,
785 frame->get_w(), frame->get_h(), ofmt, SWS_BICUBIC, NULL, NULL, NULL);
787 fprintf(stderr, "FFVideoStream::convert_picture_frame:"
788 " sws_getCachedContext() failed\n");
791 if( sws_scale(convert_ctx, ip->data, ip->linesize, 0, ih,
792 opic.data, opic.linesize) < 0 ) {
793 fprintf(stderr, "FFVideoStream::convert_picture_frame: sws_scale() failed\n");
799 int FFVideoStream::convert_cmodel(VFrame *frame,
800 AVPicture *ip, PixelFormat ifmt, int iw, int ih)
802 // try direct transfer
803 if( !convert_picture_vframe(frame, ip, ifmt, iw, ih) ) return 1;
804 // use indirect transfer
805 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
807 for( int i = 0; i <desc->nb_components; ++i ) {
808 int bits = desc->comp[i].depth_minus1 + 1;
809 if( bits > max_bits ) max_bits = bits;
811 // from libavcodec/pixdesc.c
812 #define pixdesc_has_alpha(pixdesc) ((pixdesc)->nb_components == 2 || \
813 (pixdesc)->nb_components == 4 || (pixdesc)->flags & AV_PIX_FMT_FLAG_PAL)
814 int icolor_model = pixdesc_has_alpha(desc) ?
815 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
816 (max_bits > 8 ? BC_RGB161616 : BC_RGB888) ;
817 VFrame vframe(iw, ih, icolor_model);
818 if( convert_picture_vframe(&vframe, ip, ifmt, iw, ih) ) return -1;
819 frame->transfer_from(&vframe);
823 int FFVideoStream::convert_vframe_picture(VFrame *frame,
824 AVPicture *op, PixelFormat ofmt, int ow, int oh)
827 int cmodel = frame->get_color_model();
828 PixelFormat ifmt = color_model_to_pix_fmt(cmodel);
829 if( ifmt == AV_PIX_FMT_NB ) return -1;
830 int size = avpicture_fill(&opic, frame->get_data(), ifmt,
831 frame->get_w(), frame->get_h());
832 if( size < 0 ) return -1;
834 // transfer line sizes must match also
835 int planar = BC_CModels::is_planar(cmodel);
836 int packed_width = !planar ? frame->get_bytes_per_line() :
837 BC_CModels::calculate_pixelsize(cmodel) * frame->get_w();
838 if( packed_width != opic.linesize[0] ) return -1;
841 // override avpicture_fill() for planar types
842 opic.data[0] = frame->get_y();
843 opic.data[1] = frame->get_u();
844 opic.data[2] = frame->get_v();
847 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(), ifmt,
848 ow, oh, ofmt, SWS_BICUBIC, NULL, NULL, NULL);
850 fprintf(stderr, "FFVideoStream::convert_frame_picture:"
851 " sws_getCachedContext() failed\n");
854 if( sws_scale(convert_ctx, opic.data, opic.linesize, 0, frame->get_h(),
855 op->data, op->linesize) < 0 ) {
856 fprintf(stderr, "FFVideoStream::convert_frame_picture: sws_scale() failed\n");
862 int FFVideoStream::convert_pixfmt(VFrame *frame,
863 AVPicture *op, PixelFormat ofmt, int ow, int oh)
865 // try direct transfer
866 if( !convert_vframe_picture(frame, op, ofmt, ow, oh) ) return 0;
867 // use indirect transfer
868 int colormodel = frame->get_color_model();
869 int bits = BC_CModels::calculate_pixelsize(colormodel) * 8;
870 bits /= BC_CModels::components(colormodel);
871 int icolor_model = BC_CModels::has_alpha(colormodel) ?
872 (bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
873 (bits > 8 ? BC_RGB161616: BC_RGB888) ;
874 VFrame vframe(frame->get_w(), frame->get_h(), icolor_model);
875 vframe.transfer_from(frame);
876 if( convert_vframe_picture(&vframe, op, ofmt, ow, oh) ) return 1;
881 FFMPEG::FFMPEG(FileBase *file_base)
884 this->file_base = file_base;
885 memset(file_format,0,sizeof(file_format));
886 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
887 flow_lock = new Condition(1,"FFStream::flow_lock",0);
890 decoding = encoding = 0;
891 has_audio = has_video = 0;
894 opt_video_filter = 0;
895 opt_audio_filter = 0;
896 char option_path[BCTEXTLEN];
897 set_option_path(option_path, "%s", "ffmpeg.opts");
898 read_options(option_path, opts);
903 ff_lock("FFMPEG::~FFMPEG()");
905 ffaudio.remove_all_objects();
906 ffvideo.remove_all_objects();
907 if( encoding ) avformat_free_context(fmt_ctx);
912 delete opt_video_filter;
913 delete opt_audio_filter;
916 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
918 const int *p = codec->supported_samplerates;
919 if( !p ) return sample_rate;
921 if( *p == sample_rate ) return *p;
927 static inline AVRational std_frame_rate(int i)
929 static const int m1 = 1001*12, m2 = 1000*12;
930 static const int freqs[] = {
931 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
932 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
934 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
935 return (AVRational) { freq, 1001*12 };
938 AVRational FFMPEG::check_frame_rate(AVCodec *codec, double frame_rate)
940 const AVRational *p = codec->supported_framerates;
941 AVRational rate, best_rate = (AVRational) { 0, 0 };
942 double max_err = 1.; int i = 0;
943 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
944 double framerate = (double) rate.num / rate.den;
945 double err = fabs(frame_rate/framerate - 1.);
946 if( err >= max_err ) continue;
950 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
953 AVRational FFMPEG::to_sample_aspect_ratio(double aspect_ratio)
955 int height = 1000000, width = height * aspect_ratio;
957 MWindow::create_aspect_ratio(w, h, width, height);
958 return (AVRational){(int)w, (int)h};
961 AVRational FFMPEG::to_time_base(int sample_rate)
963 return (AVRational){1, sample_rate};
966 extern void get_exe_path(char *result); // from main.C
968 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
971 strcat(path, "/ffmpeg/");
972 path += strlen(path);
975 vsprintf(path, fmt, ap);
979 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
984 set_option_path(path, "%s/%s", type, spec);
987 int FFMPEG::check_option(const char *path, char *spec)
989 char option_path[BCTEXTLEN], line[BCTEXTLEN];
990 char format[BCSTRLEN], codec[BCSTRLEN];
991 get_option_path(option_path, path, spec);
992 FILE *fp = fopen(option_path,"r");
995 if( !fgets(line, sizeof(line), fp) ) ret = 1;
997 line[sizeof(line)-1] = 0;
998 ret = scan_option_line(line, format, codec);
1001 if( !file_format[0] ) strcpy(file_format, format);
1002 else if( strcmp(file_format, format) ) ret = 1;
1008 const char *FFMPEG::get_file_format()
1012 Asset *asset = file_base->asset;
1013 if( !ret && asset->audio_data )
1014 ret = check_option("audio", asset->acodec);
1015 if( !ret && asset->video_data )
1016 ret = check_option("video", asset->vcodec);
1017 if( !ret && !file_format[0] ) ret = 1;
1018 return !ret ? file_format : 0;
1021 int FFMPEG::scan_option_line(char *cp, char *tag, char *val)
1023 while( *cp == ' ' || *cp == '\t' ) ++cp;
1025 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' ) ++cp;
1027 if( !len || len > BCSTRLEN-1 ) return 1;
1028 while( bp < cp ) *tag++ = *bp++;
1030 while( *cp == ' ' || *cp == '\t' ) ++cp;
1031 if( *cp == '=' ) ++cp;
1032 while( *cp == ' ' || *cp == '\t' ) ++cp;
1034 while( *cp && *cp != '\n' ) ++cp;
1036 if( len > BCTEXTLEN-1 ) return 1;
1037 while( bp < cp ) *val++ = *bp++;
1042 int FFMPEG::read_options(const char *options, char *format, char *codec,
1043 char *bsfilter, char *bsargs, AVDictionary *&opts)
1045 FILE *fp = fopen(options,"r");
1047 fprintf(stderr, "FFMPEG::read_options: options open failed %s\n",options);
1050 int ret = read_options(fp, options, format, codec, opts);
1052 while( *cp && *cp != '|' ) ++cp;
1053 if( *cp == '|' && !scan_option_line(cp+1, bsfilter, bsargs) ) {
1054 do { *cp-- = 0; } while( cp>=codec && (*cp==' ' || *cp == '\t' ) );
1057 bsfilter[0] = bsargs[0] = 0;
1062 int FFMPEG::read_options(FILE *fp, const char *options,
1063 char *format, char *codec, AVDictionary *&opts)
1065 char line[BCTEXTLEN];
1066 if( !fgets(line, sizeof(line), fp) ) {
1067 fprintf(stderr, "FFMPEG::read_options:"
1068 " options file empty %s\n",options);
1071 line[sizeof(line)-1] = 0;
1072 if( scan_option_line(line, format, codec) ) {
1073 fprintf(stderr, "FFMPEG::read_options:"
1074 " err: format/codec not found %s\n", options);
1077 return read_options(fp, options, opts, 1);
1080 int FFMPEG::read_options(const char *options, AVDictionary *&opts)
1082 FILE *fp = fopen(options,"r");
1084 int ret = read_options(fp, options, opts);
1089 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts, int no)
1092 char line[BCTEXTLEN];
1093 while( !ret && fgets(line, sizeof(line), fp) ) {
1094 line[sizeof(line)-1] = 0;
1096 if( line[0] == '#' ) continue;
1097 char key[BCSTRLEN], val[BCTEXTLEN];
1098 if( scan_option_line(line, key, val) ) {
1099 fprintf(stderr, "FFMPEG::read_options:"
1100 " err reading %s: line %d\n", options, no);
1104 if( !strcmp(key, "duration") )
1105 opt_duration = strtod(val, 0);
1106 if( !strcmp(key, "video_filter") )
1107 opt_video_filter = cstrdup(val);
1108 if( !strcmp(key, "audio_filter") )
1109 opt_audio_filter = cstrdup(val);
1110 else if( !strcmp(key, "loglevel") )
1113 av_dict_set(&opts, key, val, 0);
1119 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
1121 char option_path[BCTEXTLEN];
1122 set_option_path(option_path, "%s", options);
1123 return read_options(option_path, opts);
1126 void FFMPEG::set_loglevel(const char *ap)
1128 if( !ap || !*ap ) return;
1133 { "quiet" , AV_LOG_QUIET },
1134 { "panic" , AV_LOG_PANIC },
1135 { "fatal" , AV_LOG_FATAL },
1136 { "error" , AV_LOG_ERROR },
1137 { "warning", AV_LOG_WARNING },
1138 { "info" , AV_LOG_INFO },
1139 { "verbose", AV_LOG_VERBOSE },
1140 { "debug" , AV_LOG_DEBUG },
1142 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
1143 if( !strcmp(log_levels[i].name, ap) ) {
1144 av_log_set_level(log_levels[i].level);
1148 av_log_set_level(atoi(ap));
1151 double FFMPEG::to_secs(int64_t time, AVRational time_base)
1153 double base_time = time == AV_NOPTS_VALUE ? 0 :
1154 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
1155 return base_time / AV_TIME_BASE;
1158 int FFMPEG::info(char *text, int len)
1160 if( len <= 0 ) return 0;
1161 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
1163 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1164 AVStream *st = fmt_ctx->streams[i];
1165 AVCodecContext *avctx = st->codec;
1166 report("stream %d, id 0x%06x:\n", i, avctx->codec_id);
1167 const AVCodecDescriptor *desc = avcodec_descriptor_get(avctx->codec_id);
1168 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1169 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
1170 double frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
1171 report(" video %s",desc ? desc->name : " (unkn)");
1172 report(" %dx%d %5.2f", avctx->width, avctx->height, frame_rate);
1173 const char *pfn = av_get_pix_fmt_name(avctx->pix_fmt);
1174 report(" pix %s\n", pfn ? pfn : "(unkn)");
1175 double secs = to_secs(st->duration, st->time_base);
1176 int64_t length = secs * frame_rate + 0.5;
1177 report(" %jd frms %0.2f secs", length, secs);
1178 int hrs = secs/3600; secs -= hrs*3600;
1179 int mins = secs/60; secs -= mins*60;
1180 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1183 else if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1184 int sample_rate = avctx->sample_rate;
1185 const char *fmt = av_get_sample_fmt_name(avctx->sample_fmt);
1186 report(" audio %s",desc ? desc->name : " (unkn)");
1187 report(" %dch %s %d",avctx->channels, fmt, sample_rate);
1188 int sample_bits = av_get_bits_per_sample(avctx->codec_id);
1189 report(" %dbits\n", sample_bits);
1190 double secs = to_secs(st->duration, st->time_base);
1191 int64_t length = secs * sample_rate + 0.5;
1192 report(" %jd smpl %0.2f secs", length, secs);
1193 int hrs = secs/3600; secs -= hrs*3600;
1194 int mins = secs/60; secs -= mins*60;
1195 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1198 report(" codec_type unknown\n");
1201 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
1202 report("program %d", i+1);
1203 AVProgram *pgrm = fmt_ctx->programs[i];
1204 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j )
1205 report(", %d", pgrm->stream_index[j]);
1209 AVDictionaryEntry *tag = 0;
1210 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
1211 report("%s=%s\n", tag->key, tag->value);
1220 int FFMPEG::init_decoder(const char *filename)
1222 ff_lock("FFMPEG::init_decoder");
1224 char file_opts[BCTEXTLEN];
1225 char *bp = strrchr(strcpy(file_opts, filename), '/');
1226 char *sp = strrchr(!bp ? file_opts : bp, '.');
1229 strcpy(sp, ".opts");
1230 fp = fopen(file_opts, "r");
1233 read_options(fp, file_opts, opts, 0);
1237 load_options("decode.opts", opts);
1238 AVDictionary *fopts = 0;
1239 av_dict_copy(&fopts, opts, 0);
1240 int ret = avformat_open_input(&fmt_ctx, filename, NULL, &fopts);
1241 av_dict_free(&fopts);
1243 ret = avformat_find_stream_info(fmt_ctx, NULL);
1248 return !ret ? 0 : 1;
1251 int FFMPEG::open_decoder()
1254 if( stat(fmt_ctx->filename, &st) < 0 ) {
1255 fprintf(stderr,"FFMPEG::open_decoder: can't stat file: %s\n",
1260 int64_t file_bits = 8 * st.st_size;
1261 if( !fmt_ctx->bit_rate && opt_duration > 0 )
1262 fmt_ctx->bit_rate = file_bits / opt_duration;
1265 if( fmt_ctx->bit_rate > 0 ) {
1266 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1267 AVStream *st = fmt_ctx->streams[i];
1268 if( st->duration != AV_NOPTS_VALUE ) continue;
1269 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
1270 st->duration = av_rescale(file_bits, st->time_base.den,
1271 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
1276 printf("FFMPEG::open_decoder: some stream times estimated\n");
1278 ff_lock("FFMPEG::open_decoder");
1280 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1281 AVStream *st = fmt_ctx->streams[i];
1282 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
1283 AVCodecContext *avctx = st->codec;
1284 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1286 FFVideoStream *vid = new FFVideoStream(this, st, i);
1287 int vidx = ffvideo.size();
1288 vstrm_index.append(ffidx(vidx, 0));
1289 ffvideo.append(vid);
1290 vid->width = avctx->width;
1291 vid->height = avctx->height;
1292 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
1293 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
1294 double secs = to_secs(st->duration, st->time_base);
1295 vid->length = secs * vid->frame_rate;
1296 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
1297 vid->nudge = st->start_time;
1299 if( opt_video_filter )
1300 vid->create_filter(opt_video_filter, avctx,avctx);
1302 else if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1304 FFAudioStream *aud = new FFAudioStream(this, st, i);
1305 int aidx = ffaudio.size();
1306 ffaudio.append(aud);
1307 aud->channel0 = astrm_index.size();
1308 aud->channels = avctx->channels;
1309 for( int ch=0; ch<aud->channels; ++ch )
1310 astrm_index.append(ffidx(aidx, ch));
1311 aud->sample_rate = avctx->sample_rate;
1312 double secs = to_secs(st->duration, st->time_base);
1313 aud->length = secs * aud->sample_rate;
1314 if( avctx->sample_fmt != AV_SAMPLE_FMT_FLT ) {
1315 uint64_t layout = av_get_default_channel_layout(avctx->channels);
1316 if( !layout ) layout = ((uint64_t)1<<aud->channels) - 1;
1317 aud->resample_context = swr_alloc_set_opts(NULL,
1318 layout, AV_SAMPLE_FMT_FLT, avctx->sample_rate,
1319 layout, avctx->sample_fmt, avctx->sample_rate,
1321 swr_init(aud->resample_context);
1323 aud->nudge = st->start_time;
1325 if( opt_audio_filter )
1326 aud->create_filter(opt_audio_filter, avctx,avctx);
1330 printf("FFMPEG::open_decoder: some stream have bad times\n");
1336 int FFMPEG::init_encoder(const char *filename)
1338 const char *format = get_file_format();
1340 fprintf(stderr, "FFMPEG::init_encoder: invalid file format for %s\n", filename);
1344 ff_lock("FFMPEG::init_encoder");
1346 avformat_alloc_output_context2(&fmt_ctx, 0, format, filename);
1348 fprintf(stderr, "FFMPEG::init_encoder: failed: %s\n", filename);
1353 load_options("encode.opts", opts);
1360 int FFMPEG::open_encoder(const char *path, const char *spec)
1363 Asset *asset = file_base->asset;
1364 char *filename = asset->path;
1365 AVDictionary *sopts = 0;
1366 av_dict_copy(&sopts, opts, 0);
1367 char option_path[BCTEXTLEN];
1368 set_option_path(option_path, "%s/%s.opts", path, path);
1369 read_options(option_path, sopts);
1370 get_option_path(option_path, path, spec);
1371 char format_name[BCSTRLEN], codec_name[BCTEXTLEN];
1372 char bsfilter[BCSTRLEN], bsargs[BCTEXTLEN];
1373 if( read_options(option_path, format_name, codec_name, bsfilter, bsargs, sopts) ) {
1374 fprintf(stderr, "FFMPEG::open_encoder: read options failed %s:%s\n",
1375 option_path, filename);
1380 ff_lock("FFMPEG::open_encoder");
1384 const AVCodecDescriptor *codec_desc = 0;
1385 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
1387 fprintf(stderr, "FFMPEG::open_encoder: cant find codec %s:%s\n",
1388 codec_name, filename);
1392 codec_desc = avcodec_descriptor_get(codec->id);
1394 fprintf(stderr, "FFMPEG::open_encoder: unknown codec %s:%s\n",
1395 codec_name, filename);
1400 st = avformat_new_stream(fmt_ctx, 0);
1402 fprintf(stderr, "FFMPEG::open_encoder: cant create stream %s:%s\n",
1403 codec_name, filename);
1408 AVCodecContext *ctx = st->codec;
1409 switch( codec_desc->type ) {
1410 case AVMEDIA_TYPE_AUDIO: {
1412 fprintf(stderr, "FFMPEG::open_encoder: duplicate audio %s:%s\n",
1413 codec_name, filename);
1418 int aidx = ffaudio.size();
1419 int idx = aidx + ffvideo.size();
1420 FFAudioStream *aud = new FFAudioStream(this, st, idx);
1421 ffaudio.append(aud); fst = aud;
1422 aud->sample_rate = asset->sample_rate;
1423 ctx->channels = aud->channels = asset->channels;
1424 for( int ch=0; ch<aud->channels; ++ch )
1425 astrm_index.append(ffidx(aidx, ch));
1426 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
1427 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
1428 if( !ctx->sample_rate ) {
1429 fprintf(stderr, "FFMPEG::open_audio_encode:"
1430 " check_sample_rate failed %s\n", filename);
1434 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
1435 ctx->sample_fmt = codec->sample_fmts[0];
1436 uint64_t layout = av_get_default_channel_layout(ctx->channels);
1437 aud->resample_context = swr_alloc_set_opts(NULL,
1438 layout, ctx->sample_fmt, aud->sample_rate,
1439 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
1441 swr_init(aud->resample_context);
1444 case AVMEDIA_TYPE_VIDEO: {
1446 fprintf(stderr, "FFMPEG::open_encoder: duplicate video %s:%s\n",
1447 codec_name, filename);
1452 int vidx = ffvideo.size();
1453 int idx = vidx + ffaudio.size();
1454 FFVideoStream *vid = new FFVideoStream(this, st, idx);
1455 vstrm_index.append(ffidx(vidx, 0));
1456 ffvideo.append(vid); fst = vid;
1457 vid->width = asset->width;
1458 ctx->width = (vid->width+3) & ~3;
1459 vid->height = asset->height;
1460 ctx->height = (vid->height+3) & ~3;
1461 vid->frame_rate = asset->frame_rate;
1462 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset->aspect_ratio);
1463 ctx->pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
1464 AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
1465 if( !frame_rate.num || !frame_rate.den ) {
1466 fprintf(stderr, "FFMPEG::open_audio_encode:"
1467 " check_frame_rate failed %s\n", filename);
1471 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
1472 st->time_base = ctx->time_base;
1476 fprintf(stderr, "FFMPEG::open_encoder: not audio/video, %s:%s\n",
1477 codec_name, filename);
1482 ret = avcodec_open2(st->codec, codec, &sopts);
1484 ff_err(ret,"FFMPEG::open_encoder");
1485 fprintf(stderr, "FFMPEG::open_encoder: open failed %s:%s\n",
1486 codec_name, filename);
1493 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
1494 st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
1495 if( fst && bsfilter[0] )
1496 fst->add_bsfilter(bsfilter, !bsargs[0] ? 0 : bsargs);
1500 av_dict_free(&sopts);
1504 int FFMPEG::close_encoder()
1507 if( encoding > 0 ) {
1508 av_write_trailer(fmt_ctx);
1509 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
1510 avio_closep(&fmt_ctx->pb);
1516 int FFMPEG::decode_activate()
1518 if( decoding < 0 ) {
1520 int npgrms = fmt_ctx->nb_programs;
1521 for( int i=0; i<npgrms; ++i ) {
1522 AVProgram *pgrm = fmt_ctx->programs[i];
1523 // first start time video stream
1524 int64_t vstart_time = -1;
1525 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1526 int st_idx = pgrm->stream_index[j];
1527 AVStream *st = fmt_ctx->streams[st_idx];
1528 AVCodecContext *avctx = st->codec;
1529 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1530 if( st->start_time == AV_NOPTS_VALUE ) continue;
1531 vstart_time = st->start_time;
1535 // max start time audio stream
1536 int64_t astart_time = -1;
1537 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1538 int st_idx = pgrm->stream_index[j];
1539 AVStream *st = fmt_ctx->streams[st_idx];
1540 AVCodecContext *avctx = st->codec;
1541 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1542 if( st->start_time == AV_NOPTS_VALUE ) continue;
1543 if( astart_time > st->start_time ) continue;
1544 astart_time = st->start_time;
1547 if( astart_time < 0 || vstart_time < 0 ) continue;
1548 // match program streams to max start_time
1549 int64_t nudge = vstart_time > astart_time ? vstart_time : astart_time;
1550 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1551 int st_idx = pgrm->stream_index[j];
1552 AVStream *st = fmt_ctx->streams[st_idx];
1553 AVCodecContext *avctx = st->codec;
1554 if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1555 for( int k=0; k<ffaudio.size(); ++k ) {
1556 if( ffaudio[k]->idx == st_idx )
1557 ffaudio[k]->nudge = nudge;
1560 else if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1561 for( int k=0; k<ffvideo.size(); ++k ) {
1562 if( ffvideo[k]->idx == st_idx )
1563 ffvideo[k]->nudge = nudge;
1568 int64_t vstart_time = 0, astart_time = 0;
1569 int nstreams = fmt_ctx->nb_streams;
1570 for( int i=0; i<nstreams; ++i ) {
1571 AVStream *st = fmt_ctx->streams[i];
1572 AVCodecContext *avctx = st->codec;
1573 switch( avctx->codec_type ) {
1574 case AVMEDIA_TYPE_VIDEO:
1575 if( st->start_time == AV_NOPTS_VALUE ) continue;
1576 if( vstart_time >= st->start_time ) continue;
1577 vstart_time = st->start_time;
1579 case AVMEDIA_TYPE_AUDIO:
1580 if( st->start_time == AV_NOPTS_VALUE ) continue;
1581 if( astart_time >= st->start_time ) continue;
1582 astart_time = st->start_time;
1586 int64_t nudge = vstart_time > astart_time ? vstart_time : astart_time;
1587 for( int k=0; k<ffvideo.size(); ++k ) {
1588 if( ffvideo[k]->nudge != AV_NOPTS_VALUE ) continue;
1589 ffvideo[k]->nudge = nudge;
1591 for( int k=0; k<ffaudio.size(); ++k ) {
1592 if( ffaudio[k]->nudge != AV_NOPTS_VALUE ) continue;
1593 ffaudio[k]->nudge = nudge;
1600 int FFMPEG::encode_activate()
1602 if( encoding < 0 ) {
1604 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
1605 avio_open(&fmt_ctx->pb, fmt_ctx->filename, AVIO_FLAG_WRITE) < 0 ) {
1606 fprintf(stderr, "FFMPEG::encode_activate: err opening : %s\n",
1611 AVDictionary *fopts = 0;
1612 char option_path[BCTEXTLEN];
1613 set_option_path(option_path, "format/%s", file_format);
1614 read_options(option_path, fopts);
1615 int ret = avformat_write_header(fmt_ctx, &fopts);
1616 av_dict_free(&fopts);
1618 fprintf(stderr, "FFMPEG::encode_activate: write header failed %s\n",
1627 int FFMPEG::audio_seek(int stream, int64_t pos)
1629 int aidx = astrm_index[stream].st_idx;
1630 FFAudioStream *aud = ffaudio[aidx];
1631 aud->audio_seek(pos);
1632 aud->seek_pos = aud->curr_pos = pos;
1636 int FFMPEG::video_seek(int stream, int64_t pos)
1638 int vidx = vstrm_index[stream].st_idx;
1639 FFVideoStream *vid = ffvideo[vidx];
1640 vid->video_seek(pos);
1641 vid->seek_pos = vid->curr_pos = pos;
1646 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
1648 if( !has_audio || chn >= astrm_index.size() ) return -1;
1649 int aidx = astrm_index[chn].st_idx;
1650 FFAudioStream *aud = ffaudio[aidx];
1651 if( aud->load(pos, len) < len ) return -1;
1652 int ch = astrm_index[chn].st_ch;
1653 return aud->history.read(samples,len,ch);
1656 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
1658 if( !has_video || layer >= vstrm_index.size() ) return -1;
1659 int vidx = vstrm_index[layer].st_idx;
1660 FFVideoStream *vid = ffvideo[vidx];
1661 return vid->load(vframe, pos);
1664 int FFMPEG::encode(int stream, double **samples, int len)
1666 FFAudioStream *aud = ffaudio[stream];
1667 return aud->encode(samples, len);
1671 int FFMPEG::encode(int stream, VFrame *frame)
1673 FFVideoStream *vid = ffvideo[stream];
1674 return vid->encode(frame);
1677 void FFMPEG::start_muxer()
1685 void FFMPEG::stop_muxer()
1694 void FFMPEG::flow_off()
1697 flow_lock->lock("FFMPEG::flow_off");
1701 void FFMPEG::flow_on()
1705 flow_lock->unlock();
1708 void FFMPEG::flow_ctl()
1711 flow_lock->lock("FFMPEG::flow_ctl");
1712 flow_lock->unlock();
1716 int FFMPEG::mux_audio(FFrame *frm)
1719 AVStream *st = frm->fst->st;
1720 AVCodecContext *ctx = st->codec;
1721 AVFrame *frame = *frm;
1722 AVRational tick_rate = {1, ctx->sample_rate};
1723 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
1725 int ret = avcodec_encode_audio2(ctx, pkt, frame, &got_packet);
1726 if( ret >= 0 && got_packet ) {
1727 frm->fst->bs_filter(pkt);
1728 av_packet_rescale_ts(pkt, ctx->time_base, st->time_base);
1729 pkt->stream_index = st->index;
1730 ret = av_interleaved_write_frame(fmt_ctx, pkt);
1733 ff_err(ret, "FFMPEG::mux_audio");
1734 return ret >= 0 ? 0 : 1;
1737 int FFMPEG::mux_video(FFrame *frm)
1740 AVStream *st = frm->fst->st;
1741 AVFrame *frame = *frm;
1742 frame->pts = frm->position;
1743 int ret = 1, got_packet = 0;
1744 if( fmt_ctx->oformat->flags & AVFMT_RAWPICTURE ) {
1745 /* a hack to avoid data copy with some raw video muxers */
1746 pkt->flags |= AV_PKT_FLAG_KEY;
1747 pkt->stream_index = st->index;
1748 AVPicture *picture = (AVPicture *)frame;
1749 pkt->data = (uint8_t *)picture;
1750 pkt->size = sizeof(AVPicture);
1751 pkt->pts = pkt->dts = frame->pts;
1755 ret = avcodec_encode_video2(st->codec, pkt, frame, &got_packet);
1756 if( ret >= 0 && got_packet ) {
1757 frm->fst->bs_filter(pkt);
1758 av_packet_rescale_ts(pkt, st->codec->time_base, st->time_base);
1759 pkt->stream_index = st->index;
1760 ret = av_interleaved_write_frame(fmt_ctx, pkt);
1763 ff_err(ret, "FFMPEG::mux_video");
1764 return ret >= 0 ? 0 : 1;
1770 double atm = -1, vtm = -1;
1771 FFrame *afrm = 0, *vfrm = 0;
1773 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
1774 FFStream *fst = ffaudio[i];
1775 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
1776 FFrame *frm = fst->frms.first;
1777 if( !frm ) { if( !done ) return; continue; }
1778 double tm = to_secs(frm->position, fst->st->codec->time_base);
1779 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
1781 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
1782 FFStream *fst = ffvideo[i];
1783 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
1784 FFrame *frm = fst->frms.first;
1785 if( !frm ) { if( !done ) return; continue; }
1786 double tm = to_secs(frm->position, fst->st->codec->time_base);
1787 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
1789 if( !demand ) flow_off();
1790 if( !afrm && !vfrm ) break;
1791 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
1792 vfrm->position, vfrm->fst->st->codec->time_base,
1793 afrm->position, afrm->fst->st->codec->time_base);
1794 FFrame *frm = v <= 0 ? vfrm : afrm;
1795 if( frm == afrm ) mux_audio(frm);
1796 if( frm == vfrm ) mux_video(frm);
1805 mux_lock->lock("FFMPEG::run");
1812 int FFMPEG::ff_total_audio_channels()
1814 return astrm_index.size();
1817 int FFMPEG::ff_total_astreams()
1819 return ffaudio.size();
1822 int FFMPEG::ff_audio_channels(int stream)
1824 return ffaudio[stream]->channels;
1827 int FFMPEG::ff_sample_rate(int stream)
1829 return ffaudio[stream]->sample_rate;
1832 const char* FFMPEG::ff_audio_format(int stream)
1834 AVStream *st = ffaudio[stream]->st;
1835 AVCodecID id = st->codec->codec_id;
1836 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
1837 return desc ? desc->name : "Unknown";
1840 int FFMPEG::ff_audio_pid(int stream)
1842 return ffaudio[stream]->st->id;
1845 int64_t FFMPEG::ff_audio_samples(int stream)
1847 return ffaudio[stream]->length;
1850 // find audio astream/channels with this program,
1851 // or all program audio channels (astream=-1)
1852 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
1856 int vidx = ffvideo[vstream]->idx;
1857 // find first program with this video stream
1858 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
1859 AVProgram *pgrm = fmt_ctx->programs[i];
1860 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
1861 int st_idx = pgrm->stream_index[j];
1862 AVStream *st = fmt_ctx->streams[st_idx];
1863 if( st->codec->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
1864 if( st_idx == vidx ) pidx = i;
1867 if( pidx < 0 ) return -1;
1869 int64_t channels = 0;
1870 AVProgram *pgrm = fmt_ctx->programs[pidx];
1871 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1872 int aidx = pgrm->stream_index[j];
1873 AVStream *st = fmt_ctx->streams[aidx];
1874 if( st->codec->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
1875 if( astream > 0 ) { --astream; continue; }
1877 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
1878 if( ffaudio[i]->idx == aidx ) astrm = i;
1880 if( ret < 0 ) ret = astrm;
1881 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
1882 channels |= mask << ffaudio[astrm]->channel0;
1884 if( !astream ) break;
1886 channel_mask = channels;
1891 int FFMPEG::ff_total_video_layers()
1893 return vstrm_index.size();
1896 int FFMPEG::ff_total_vstreams()
1898 return ffvideo.size();
1901 int FFMPEG::ff_video_width(int stream)
1903 return ffvideo[stream]->width;
1906 int FFMPEG::ff_video_height(int stream)
1908 return ffvideo[stream]->height;
1911 int FFMPEG::ff_set_video_width(int stream, int width)
1913 int w = ffvideo[stream]->width;
1914 ffvideo[stream]->width = width;
1918 int FFMPEG::ff_set_video_height(int stream, int height)
1920 int h = ffvideo[stream]->height;
1921 ffvideo[stream]->height = height;
1925 int FFMPEG::ff_coded_width(int stream)
1927 AVStream *st = ffvideo[stream]->st;
1928 return st->codec->coded_width;
1931 int FFMPEG::ff_coded_height(int stream)
1933 AVStream *st = ffvideo[stream]->st;
1934 return st->codec->coded_height;
1937 float FFMPEG::ff_aspect_ratio(int stream)
1939 return ffvideo[stream]->aspect_ratio;
1942 const char* FFMPEG::ff_video_format(int stream)
1944 AVStream *st = ffvideo[stream]->st;
1945 AVCodecID id = st->codec->codec_id;
1946 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
1947 return desc ? desc->name : "Unknown";
1950 double FFMPEG::ff_frame_rate(int stream)
1952 return ffvideo[stream]->frame_rate;
1955 int64_t FFMPEG::ff_video_frames(int stream)
1957 return ffvideo[stream]->length;
1960 int FFMPEG::ff_video_pid(int stream)
1962 return ffvideo[stream]->st->id;
1966 int FFMPEG::ff_cpus()
1968 return file_base->file->cpus;
1971 int FFVideoStream::create_filter(const char *filter_spec,
1972 AVCodecContext *src_ctx, AVCodecContext *sink_ctx)
1974 avfilter_register_all();
1975 filter_graph = avfilter_graph_alloc();
1976 AVFilter *buffersrc = avfilter_get_by_name("buffer");
1977 AVFilter *buffersink = avfilter_get_by_name("buffersink");
1979 int ret = 0; char args[BCTEXTLEN];
1980 snprintf(args, sizeof(args),
1981 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
1982 src_ctx->width, src_ctx->height, src_ctx->pix_fmt,
1983 st->time_base.num, st->time_base.den,
1984 src_ctx->sample_aspect_ratio.num, src_ctx->sample_aspect_ratio.den);
1986 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
1987 args, NULL, filter_graph);
1989 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
1990 NULL, NULL, filter_graph);
1992 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
1993 (uint8_t*)&sink_ctx->pix_fmt, sizeof(sink_ctx->pix_fmt),
1994 AV_OPT_SEARCH_CHILDREN);
1996 ff_err(ret, "FFVideoStream::create_filter");
1998 ret = FFStream::create_filter(filter_spec);
1999 return ret >= 0 ? 0 : 1;
2002 int FFAudioStream::create_filter(const char *filter_spec,
2003 AVCodecContext *src_ctx, AVCodecContext *sink_ctx)
2005 avfilter_register_all();
2006 filter_graph = avfilter_graph_alloc();
2007 AVFilter *buffersrc = avfilter_get_by_name("abuffer");
2008 AVFilter *buffersink = avfilter_get_by_name("abuffersink");
2009 int ret = 0; char args[BCTEXTLEN];
2010 snprintf(args, sizeof(args),
2011 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
2012 st->time_base.num, st->time_base.den, src_ctx->sample_rate,
2013 av_get_sample_fmt_name(src_ctx->sample_fmt), src_ctx->channel_layout);
2015 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2016 args, NULL, filter_graph);
2018 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2019 NULL, NULL, filter_graph);
2021 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
2022 (uint8_t*)&sink_ctx->sample_fmt, sizeof(sink_ctx->sample_fmt),
2023 AV_OPT_SEARCH_CHILDREN);
2025 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
2026 (uint8_t*)&sink_ctx->channel_layout,
2027 sizeof(sink_ctx->channel_layout), AV_OPT_SEARCH_CHILDREN);
2029 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
2030 (uint8_t*)&sink_ctx->sample_rate, sizeof(sink_ctx->sample_rate),
2031 AV_OPT_SEARCH_CHILDREN);
2033 ff_err(ret, "FFAudioStream::create_filter");
2035 ret = FFStream::create_filter(filter_spec);
2036 return ret >= 0 ? 0 : 1;
2039 int FFStream::create_filter(const char *filter_spec)
2041 /* Endpoints for the filter graph. */
2042 AVFilterInOut *outputs = avfilter_inout_alloc();
2043 outputs->name = av_strdup("in");
2044 outputs->filter_ctx = buffersrc_ctx;
2045 outputs->pad_idx = 0;
2048 AVFilterInOut *inputs = avfilter_inout_alloc();
2049 inputs->name = av_strdup("out");
2050 inputs->filter_ctx = buffersink_ctx;
2051 inputs->pad_idx = 0;
2054 int ret = !outputs->name || !inputs->name ? -1 : 0;
2056 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
2057 &inputs, &outputs, NULL);
2059 ret = avfilter_graph_config(filter_graph, NULL);
2062 ff_err(ret, "FFStream::create_filter");
2063 avfilter_inout_free(&inputs);
2064 avfilter_inout_free(&outputs);
2068 void FFStream::add_bsfilter(const char *bsf, const char *ap)
2070 bsfilter.append(new BSFilter(bsf,ap));
2073 int FFStream::bs_filter(AVPacket *pkt)
2075 if( !bsfilter.size() ) return 0;
2076 av_packet_split_side_data(pkt);
2079 for( int i=0; i<bsfilter.size(); ++i ) {
2080 AVPacket bspkt = *pkt;
2081 ret = av_bitstream_filter_filter(bsfilter[i]->bsfc,
2082 st->codec, bsfilter[i]->args, &bspkt.data, &bspkt.size,
2083 pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY);
2084 if( ret < 0 ) break;
2085 int size = bspkt.size;
2086 uint8_t *data = bspkt.data;
2087 if( !ret && bspkt.data != pkt->data ) {
2089 data = (uint8_t *)av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
2090 if( !data ) { ret = AVERROR(ENOMEM); break; }
2091 memcpy(data, bspkt.data, size);
2092 memset(data+size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2096 pkt->side_data = 0; pkt->side_data_elems = 0;
2097 av_free_packet(pkt);
2098 ret = av_packet_from_data(&bspkt, data, size);
2099 if( ret < 0 ) break;
2104 ff_err(ret,"FFStream::bs_filter");