10 // work arounds (centos)
13 #define INT64_MAX 9223372036854775807LL
17 #include "bccmodels.h"
18 #include "fileffmpeg.h"
23 #include "mainerror.h"
28 #define VIDEO_INBUF_SIZE 0x10000
29 #define AUDIO_INBUF_SIZE 0x10000
30 #define VIDEO_REFILL_THRESH 0
31 #define AUDIO_REFILL_THRESH 0x1000
33 Mutex FFMPEG::fflock("FFMPEG::fflock");
35 static void ff_err(int ret, const char *fmt, ...)
40 vsnprintf(msg, sizeof(msg), fmt, ap);
42 char errmsg[BCSTRLEN];
43 av_strerror(ret, errmsg, sizeof(errmsg));
44 fprintf(stderr,_("%s err: %s\n"),msg, errmsg);
60 pkt.data = 0; pkt.size = 0;
63 FFrame::FFrame(FFStream *fst)
66 frm = av_frame_alloc();
67 init = fst->init_frame(frm);
75 void FFrame::queue(int64_t pos)
81 void FFrame::dequeue()
86 int FFAudioStream::read(float *fp, long len)
94 while( --k >= 0 ) *fp++ = *op++;
95 if( op >= lmt ) op = bfr;
100 void FFAudioStream::realloc(long sz, int nch, long len)
103 float *np = new float[bsz];
104 inp = np + read(np, len) * nch;
109 delete [] bfr; bfr = np;
112 void FFAudioStream::realloc(long sz, int nch)
114 if( sz > this->sz || this->nch != nch ) {
115 long len = this->nch != nch ? 0 : curr_pos - seek_pos;
116 if( len > this->sz ) len = this->sz;
118 realloc(sz, nch, len);
122 void FFAudioStream::reserve(long sz, int nch)
124 long len = (inp - outp) / nch;
126 if( sz > this->sz || this->nch != nch ) {
127 if( this->nch != nch ) len = 0;
128 realloc(sz, nch, len);
131 if( (len*=nch) > 0 && bfr != outp )
132 memmove(bfr, outp, len*sizeof(*bfr));
137 long FFAudioStream::used()
139 long len = inp>=outp ? inp-outp : inp-bfr + lmt-outp;
142 long FFAudioStream::avail()
145 if( in1 >= lmt ) in1 = bfr;
146 long len = outp >= in1 ? outp-in1 : outp-bfr + lmt-in1;
149 void FFAudioStream::reset() // clear bfr
154 void FFAudioStream::iseek(int64_t ofs)
156 outp = inp - ofs*nch;
157 if( outp < bfr ) outp += sz*nch;
160 float *FFAudioStream::get_outp(int ofs)
167 int64_t FFAudioStream::put_inp(int ofs)
170 return (inp-outp) / nch;
173 int FFAudioStream::write(const float *fp, long len)
181 while( --k >= 0 ) *ip++ = *fp++;
182 if( ip >= lmt ) ip = bfr;
188 int FFAudioStream::zero(long len)
196 while( --k >= 0 ) *ip++ = 0;
197 if( ip >= lmt ) ip = bfr;
203 // does not advance outp
204 int FFAudioStream::read(double *dp, long len, int ch)
207 float *op = outp + ch;
208 float *lmt1 = lmt + nch-1;
210 int k = (lmt1 - op) / nch;
213 while( --k >= 0 ) { *dp++ = *op; op += nch; }
214 if( op >= lmt ) op -= sz*nch;
219 // load linear buffer, no wrapping allowed, does not advance inp
220 int FFAudioStream::write(const double *dp, long len, int ch)
223 float *ip = inp + ch;
224 while( --n >= 0 ) { *ip = *dp++; ip += nch; }
229 FFStream::FFStream(FFMPEG *ffmpeg, AVStream *st, int idx)
231 this->ffmpeg = ffmpeg;
234 frm_lock = new Mutex("FFStream::frm_lock");
240 nudge = AV_NOPTS_VALUE;
242 reading = writing = 0;
248 FFStream::~FFStream()
250 if( reading > 0 || writing > 0 ) avcodec_close(st->codec);
251 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
252 while( frms.first ) frms.remove(frms.first);
253 if( filter_graph ) avfilter_graph_free(&filter_graph);
254 if( frame ) av_frame_free(&frame);
255 if( fframe ) av_frame_free(&fframe);
256 bsfilter.remove_all_objects();
260 void FFStream::ff_lock(const char *cp)
262 FFMPEG::fflock.lock(cp);
265 void FFStream::ff_unlock()
267 FFMPEG::fflock.unlock();
270 void FFStream::queue(FFrame *frm)
272 frm_lock->lock("FFStream::queue");
276 ffmpeg->mux_lock->unlock();
279 void FFStream::dequeue(FFrame *frm)
281 frm_lock->lock("FFStream::dequeue");
283 frms.remove_pointer(frm);
287 int FFStream::encode_activate()
290 writing = ffmpeg->encode_activate();
294 int FFStream::decode_activate()
296 if( reading < 0 && (reading=ffmpeg->decode_activate()) > 0 ) {
297 ff_lock("FFStream::decode_activate");
299 AVDictionary *copts = 0;
300 av_dict_copy(&copts, ffmpeg->opts, 0);
302 // this should be avformat_copy_context(), but no copy avail
303 ret = avformat_open_input(&fmt_ctx, ffmpeg->fmt_ctx->filename, NULL, &copts);
305 ret = avformat_find_stream_info(fmt_ctx, 0);
306 st = fmt_ctx->streams[idx];
309 AVCodecID codec_id = st->codec->codec_id;
310 AVCodec *decoder = avcodec_find_decoder(codec_id);
311 ret = avcodec_open2(st->codec, decoder, &copts);
315 eprintf("FFStream::decode_activate: open decoder failed\n");
318 eprintf("FFStream::decode_activate: can't clone input file\n");
319 av_dict_free(&copts);
325 int FFStream::read_packet()
327 av_packet_unref(ipkt);
328 int ret = av_read_frame(fmt_ctx, ipkt);
329 if( ret >= 0 ) return 1;
331 if( ret == AVERROR_EOF ) return 0;
332 ff_err(ret, "FFStream::read_packet: av_read_frame failed\n");
337 int FFStream::decode(AVFrame *frame)
343 while( ret >= 0 && !flushed && --retries >= 0 && !got_frame ) {
348 if( !ret ) ipkt->stream_index = st->index;
350 if( ipkt->stream_index == st->index ) {
351 while( (ipkt->size > 0 || !ipkt->data) && !got_frame ) {
352 ret = decode_frame(frame, got_frame);
353 if( ret < 0 || !ipkt->data ) break;
366 fprintf(stderr, "FFStream::decode: Retry limit\n");
370 fprintf(stderr, "FFStream::decode: failed\n");
375 int FFStream::load_filter(AVFrame *frame)
377 int ret = av_buffersrc_add_frame_flags(buffersrc_ctx,
378 frame, AV_BUFFERSRC_FLAG_KEEP_REF);
380 av_frame_unref(frame);
381 eprintf("FFStream::load_filter: av_buffersrc_add_frame_flags failed\n");
386 int FFStream::read_filter(AVFrame *frame)
388 int ret = av_buffersink_get_frame(buffersink_ctx, frame);
390 if( ret == AVERROR(EAGAIN) ) return 0;
391 if( ret == AVERROR_EOF ) { st_eof(1); return -1; }
392 ff_err(ret, "FFStream::read_filter: av_buffersink_get_frame failed\n");
398 int FFStream::read_frame(AVFrame *frame)
400 if( !filter_graph || !buffersrc_ctx || !buffersink_ctx )
401 return decode(frame);
402 if( !fframe && !(fframe=av_frame_alloc()) ) {
403 fprintf(stderr, "FFStream::read_frame: av_frame_alloc failed\n");
407 while( !flushed && !(ret=read_filter(frame)) ) {
408 if( (ret=decode(fframe)) < 0 ) break;
409 if( ret > 0 && (ret=load_filter(fframe)) < 0 ) break;
414 int FFStream::write_packet(FFPacket &pkt)
417 av_packet_rescale_ts(pkt, st->codec->time_base, st->time_base);
418 pkt->stream_index = st->index;
419 return av_interleaved_write_frame(ffmpeg->fmt_ctx, pkt);
422 int FFStream::flush()
428 ret = encode_frame(pkt, 0, got_packet);
429 if( ret < 0 || !got_packet ) break;
430 ret = write_packet(pkt);
433 ff_err(ret, "FFStream::flush");
434 return ret >= 0 ? 0 : 1;
437 FFAudioStream::FFAudioStream(FFMPEG *ffmpeg, AVStream *strm, int idx)
438 : FFStream(ffmpeg, strm, idx)
440 channel0 = channels = 0;
443 seek_pos = curr_pos = 0;
445 resample_context = 0;
454 bfr = new float[bsz];
459 FFAudioStream::~FFAudioStream()
461 if( resample_context ) swr_free(&resample_context);
466 int FFAudioStream::load_history(uint8_t **data, int len)
468 float *samples = *(float **)data;
469 if( resample_context ) {
470 if( len > aud_bfr_sz ) {
476 aud_bfr = new float[aud_bfr_sz*channels];
478 int ret = swr_convert(resample_context,
479 (uint8_t**)&aud_bfr, aud_bfr_sz, (const uint8_t**)data, len);
481 ff_err(ret, "FFAudioStream::load_history: swr_convert failed\n");
487 // biggest user bfr since seek + frame
488 realloc(mbsz + len + 1, channels);
493 int FFAudioStream::decode_frame(AVFrame *frame, int &got_frame)
495 int ret = avcodec_decode_audio4(st->codec, frame, &got_frame, ipkt);
497 ff_err(ret, "FFAudioStream::decode_frame: Could not read audio frame\n");
503 int FFAudioStream::encode_activate()
505 if( writing >= 0 ) return writing;
506 AVCodecContext *ctx = st->codec;
507 frame_sz = ctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE ?
508 10000 : ctx->frame_size;
509 return FFStream::encode_activate();
512 int FFAudioStream::nb_samples()
514 AVCodecContext *ctx = st->codec;
515 return ctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE ?
516 10000 : ctx->frame_size;
519 int64_t FFAudioStream::load_buffer(double ** const sp, int len)
521 reserve(len+1, st->codec->channels);
522 for( int ch=0; ch<nch; ++ch )
523 write(sp[ch], len, ch);
527 int FFAudioStream::in_history(int64_t pos)
529 if( pos > curr_pos ) return 0;
530 int64_t len = curr_pos - seek_pos;
531 if( len > sz ) len = sz;
532 if( pos < curr_pos - len ) return 0;
537 int FFAudioStream::init_frame(AVFrame *frame)
539 AVCodecContext *ctx = st->codec;
540 frame->nb_samples = frame_sz;
541 frame->format = ctx->sample_fmt;
542 frame->channel_layout = ctx->channel_layout;
543 frame->sample_rate = ctx->sample_rate;
544 int ret = av_frame_get_buffer(frame, 0);
546 ff_err(ret, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
550 int FFAudioStream::load(int64_t pos, int len)
552 if( audio_seek(pos) < 0 ) return -1;
553 if( mbsz < len ) mbsz = len;
555 int64_t end_pos = pos + len;
556 if( !frame && !(frame=av_frame_alloc()) ) {
557 fprintf(stderr, "FFAudioStream::load: av_frame_alloc failed\n");
560 for( int i=0; ret>=0 && !flushed && curr_pos<end_pos && i<1000; ++i ) {
561 ret = read_frame(frame);
563 load_history(&frame->extended_data[0], frame->nb_samples);
564 curr_pos += frame->nb_samples;
567 if( end_pos > curr_pos ) {
568 zero(end_pos - curr_pos);
571 return curr_pos - pos;
574 int FFAudioStream::audio_seek(int64_t pos)
576 if( decode_activate() < 0 ) return -1;
577 if( in_history(pos) ) {
578 iseek(curr_pos - pos);
581 if( pos == curr_pos ) return 0;
582 if( !st->codec || !st->codec->codec ) return -1;
583 avcodec_flush_buffers(st->codec);
584 double secs = (double)pos / sample_rate;
585 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
586 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
587 avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, tstmp, INT64_MAX, 0);
588 seek_pos = curr_pos = pos;
590 mbsz = 0; flushed = 0; need_packet = 1;
594 int FFAudioStream::encode(double **samples, int len)
596 if( encode_activate() <= 0 ) return -1;
599 int64_t count = load_buffer(samples, len);
602 while( ret >= 0 && count >= frame_sz ) {
603 frm = new FFrame(this);
604 if( (ret=frm->initted()) < 0 ) break;
605 AVFrame *frame = *frm;
606 float *bfrp = get_outp(frame_sz);
607 ret = swr_convert(resample_context,
608 (uint8_t **)frame->extended_data, frame_sz,
609 (const uint8_t **)&bfrp, frame_sz);
611 ff_err(ret, "FFAudioStream::encode: swr_convert failed\n");
614 frm->queue(curr_pos);
616 curr_pos += frame_sz;
621 return ret >= 0 ? 0 : 1;
624 int FFAudioStream::encode_frame(FFPacket &pkt, AVFrame *frame, int &got_packet)
626 int ret = avcodec_encode_audio2(st->codec, pkt, frame, &got_packet);
628 ff_err(ret, "FFAudioStream::encode_frame: encode audio failed\n");
634 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx)
635 : FFStream(ffmpeg, strm, idx)
640 seek_pos = curr_pos = 0;
645 FFVideoStream::~FFVideoStream()
647 if( convert_ctx ) sws_freeContext(convert_ctx);
650 int FFVideoStream::decode_frame(AVFrame *frame, int &got_frame)
652 int ret = avcodec_decode_video2(st->codec, frame, &got_frame, ipkt);
654 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame\n");
662 int FFVideoStream::load(VFrame *vframe, int64_t pos)
664 int ret = video_seek(pos);
665 if( ret < 0 ) return -1;
666 if( !frame && !(frame=av_frame_alloc()) ) {
667 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
670 for( int i=0; ret>=0 && !flushed && curr_pos<=pos && i<1000; ++i ) {
671 ret = read_frame(frame);
674 AVCodecContext *ctx = st->codec;
675 ret = convert_cmodel(vframe, (AVPicture *)frame,
676 ctx->pix_fmt, ctx->width, ctx->height);
678 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
682 int FFVideoStream::video_seek(int64_t pos)
684 if( decode_activate() < 0 ) return -1;
685 // if close enough, just read up to current
686 // 3*gop_size seems excessive, but less causes tears
687 int gop = 3*st->codec->gop_size;
688 if( gop < 4 ) gop = 4;
689 if( gop > 64 ) gop = 64;
690 if( pos >= curr_pos && pos <= curr_pos + gop ) return 0;
691 if( pos == curr_pos-1 && curr_pos > seek_pos ) return 1;
692 if( !st->codec || !st->codec->codec ) return -1;
693 avcodec_flush_buffers(st->codec);
694 // back up a few frames to read up to current to help repair damages
695 if( (pos-=gop) < 0 ) pos = 0;
696 double secs = (double)pos / frame_rate;
697 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
698 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
699 avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, tstmp, INT64_MAX, 0);
700 seek_pos = curr_pos = pos;
702 flushed = 0; need_packet = 1;
706 int FFVideoStream::init_frame(AVFrame *picture)
708 AVCodecContext *ctx = st->codec;
709 picture->format = ctx->pix_fmt;
710 picture->width = ctx->width;
711 picture->height = ctx->height;
712 int ret = av_frame_get_buffer(picture, 32);
716 int FFVideoStream::encode(VFrame *vframe)
718 if( encode_activate() <= 0 ) return -1;
720 FFrame *picture = new FFrame(this);
721 int ret = picture->initted();
723 AVFrame *frame = *picture;
724 frame->pts = curr_pos;
725 AVCodecContext *ctx = st->codec;
726 ret = convert_pixfmt(vframe, (AVPicture*)frame,
727 ctx->pix_fmt, ctx->width, ctx->height);
730 picture->queue(curr_pos);
734 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
737 return ret >= 0 ? 0 : 1;
740 int FFVideoStream::encode_frame(FFPacket &pkt, AVFrame *frame, int &got_packet)
742 int ret = avcodec_encode_video2(st->codec, pkt, frame, &got_packet);
744 ff_err(ret, "FFVideoStream::encode_frame: encode video failed\n");
750 PixelFormat FFVideoStream::color_model_to_pix_fmt(int color_model)
752 switch( color_model ) {
753 case BC_YUV422: return AV_PIX_FMT_YUYV422;
754 case BC_RGB888: return AV_PIX_FMT_RGB24;
755 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
756 case BC_BGR8888: return AV_PIX_FMT_BGR0;
757 case BC_BGR888: return AV_PIX_FMT_BGR24;
758 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
759 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
760 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
761 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
762 case BC_RGB565: return AV_PIX_FMT_RGB565;
763 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
764 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
768 return AV_PIX_FMT_NB;
771 int FFVideoStream::pix_fmt_to_color_model(PixelFormat pix_fmt)
774 case AV_PIX_FMT_YUYV422: return BC_YUV422;
775 case AV_PIX_FMT_RGB24: return BC_RGB888;
776 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
777 case AV_PIX_FMT_BGR0: return BC_BGR8888;
778 case AV_PIX_FMT_BGR24: return BC_BGR888;
779 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
780 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
781 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
782 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
783 case AV_PIX_FMT_RGB565: return BC_RGB565;
784 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
785 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
789 return BC_TRANSPARENCY;
792 int FFVideoStream::convert_picture_vframe(VFrame *frame,
793 AVPicture *ip, PixelFormat ifmt, int iw, int ih)
796 int cmodel = frame->get_color_model();
797 PixelFormat ofmt = color_model_to_pix_fmt(cmodel);
798 if( ofmt == AV_PIX_FMT_NB ) return -1;
799 int size = avpicture_fill(&opic, frame->get_data(), ofmt,
800 frame->get_w(), frame->get_h());
801 if( size < 0 ) return -1;
803 // transfer line sizes must match also
804 int planar = BC_CModels::is_planar(cmodel);
805 int packed_width = !planar ? frame->get_bytes_per_line() :
806 BC_CModels::calculate_pixelsize(cmodel) * frame->get_w();
807 if( packed_width != opic.linesize[0] ) return -1;
810 // override avpicture_fill() for planar types
811 opic.data[0] = frame->get_y();
812 opic.data[1] = frame->get_u();
813 opic.data[2] = frame->get_v();
816 convert_ctx = sws_getCachedContext(convert_ctx, iw, ih, ifmt,
817 frame->get_w(), frame->get_h(), ofmt, SWS_BICUBIC, NULL, NULL, NULL);
819 fprintf(stderr, "FFVideoStream::convert_picture_frame:"
820 " sws_getCachedContext() failed\n");
823 int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ih,
824 opic.data, opic.linesize);
826 ff_err(ret, "FFVideoStream::convert_picture_frame: sws_scale() failed\n");
832 int FFVideoStream::convert_cmodel(VFrame *frame,
833 AVPicture *ip, PixelFormat ifmt, int iw, int ih)
835 // try direct transfer
836 if( !convert_picture_vframe(frame, ip, ifmt, iw, ih) ) return 1;
837 // use indirect transfer
838 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
840 for( int i = 0; i <desc->nb_components; ++i ) {
841 int bits = desc->comp[i].depth_minus1 + 1;
842 if( bits > max_bits ) max_bits = bits;
844 // from libavcodec/pixdesc.c
845 #define pixdesc_has_alpha(pixdesc) ((pixdesc)->nb_components == 2 || \
846 (pixdesc)->nb_components == 4 || (pixdesc)->flags & AV_PIX_FMT_FLAG_PAL)
847 int icolor_model = pixdesc_has_alpha(desc) ?
848 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
849 (max_bits > 8 ? BC_RGB161616 : BC_RGB888) ;
850 VFrame vframe(iw, ih, icolor_model);
851 if( convert_picture_vframe(&vframe, ip, ifmt, iw, ih) ) return -1;
852 frame->transfer_from(&vframe);
856 int FFVideoStream::convert_vframe_picture(VFrame *frame,
857 AVPicture *op, PixelFormat ofmt, int ow, int oh)
860 int cmodel = frame->get_color_model();
861 PixelFormat ifmt = color_model_to_pix_fmt(cmodel);
862 if( ifmt == AV_PIX_FMT_NB ) return -1;
863 int size = avpicture_fill(&opic, frame->get_data(), ifmt,
864 frame->get_w(), frame->get_h());
865 if( size < 0 ) return -1;
867 // transfer line sizes must match also
868 int planar = BC_CModels::is_planar(cmodel);
869 int packed_width = !planar ? frame->get_bytes_per_line() :
870 BC_CModels::calculate_pixelsize(cmodel) * frame->get_w();
871 if( packed_width != opic.linesize[0] ) return -1;
874 // override avpicture_fill() for planar types
875 opic.data[0] = frame->get_y();
876 opic.data[1] = frame->get_u();
877 opic.data[2] = frame->get_v();
880 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(), ifmt,
881 ow, oh, ofmt, SWS_BICUBIC, NULL, NULL, NULL);
883 fprintf(stderr, "FFVideoStream::convert_frame_picture:"
884 " sws_getCachedContext() failed\n");
887 int ret = sws_scale(convert_ctx, opic.data, opic.linesize, 0, frame->get_h(),
888 op->data, op->linesize);
890 ff_err(ret, "FFVideoStream::convert_frame_picture: sws_scale() failed\n");
896 int FFVideoStream::convert_pixfmt(VFrame *frame,
897 AVPicture *op, PixelFormat ofmt, int ow, int oh)
899 // try direct transfer
900 if( !convert_vframe_picture(frame, op, ofmt, ow, oh) ) return 0;
901 // use indirect transfer
902 int colormodel = frame->get_color_model();
903 int bits = BC_CModels::calculate_pixelsize(colormodel) * 8;
904 bits /= BC_CModels::components(colormodel);
905 int icolor_model = BC_CModels::has_alpha(colormodel) ?
906 (bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
907 (bits > 8 ? BC_RGB161616: BC_RGB888) ;
908 VFrame vframe(frame->get_w(), frame->get_h(), icolor_model);
909 vframe.transfer_from(frame);
910 if( convert_vframe_picture(&vframe, op, ofmt, ow, oh) ) return 1;
915 FFMPEG::FFMPEG(FileBase *file_base)
918 this->file_base = file_base;
919 memset(file_format,0,sizeof(file_format));
920 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
921 flow_lock = new Condition(1,"FFStream::flow_lock",0);
924 decoding = encoding = 0;
925 has_audio = has_video = 0;
928 opt_video_filter = 0;
929 opt_audio_filter = 0;
930 char option_path[BCTEXTLEN];
931 set_option_path(option_path, "%s", "ffmpeg.opts");
932 read_options(option_path, opts);
937 ff_lock("FFMPEG::~FFMPEG()");
939 ffaudio.remove_all_objects();
940 ffvideo.remove_all_objects();
941 if( encoding ) avformat_free_context(fmt_ctx);
946 delete [] opt_video_filter;
947 delete [] opt_audio_filter;
950 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
952 const int *p = codec->supported_samplerates;
953 if( !p ) return sample_rate;
955 if( *p == sample_rate ) return *p;
961 static inline AVRational std_frame_rate(int i)
963 static const int m1 = 1001*12, m2 = 1000*12;
964 static const int freqs[] = {
965 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
966 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
968 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
969 return (AVRational) { freq, 1001*12 };
972 AVRational FFMPEG::check_frame_rate(AVCodec *codec, double frame_rate)
974 const AVRational *p = codec->supported_framerates;
975 AVRational rate, best_rate = (AVRational) { 0, 0 };
976 double max_err = 1.; int i = 0;
977 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
978 double framerate = (double) rate.num / rate.den;
979 double err = fabs(frame_rate/framerate - 1.);
980 if( err >= max_err ) continue;
984 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
987 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
990 double display_aspect = asset->width / (double)asset->height;
991 double sample_aspect = asset->aspect_ratio / display_aspect;
992 int width = 1000000, height = width * sample_aspect + 0.5;
994 MWindow::create_aspect_ratio(w, h, width, height);
995 return (AVRational){(int)h, (int)w};
998 return (AVRational){1, 1};
1002 AVRational FFMPEG::to_time_base(int sample_rate)
1004 return (AVRational){1, sample_rate};
1007 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
1010 strcat(path, "/ffmpeg/");
1011 path += strlen(path);
1014 vsprintf(path, fmt, ap);
1018 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
1023 set_option_path(path, "%s/%s", type, spec);
1026 int FFMPEG::get_format(char *format, const char *path, char *spec)
1028 char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
1029 get_option_path(option_path, path, spec);
1030 FILE *fp = fopen(option_path,"r");
1033 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1035 line[sizeof(line)-1] = 0;
1036 ret = scan_option_line(line, format, codec);
1042 int FFMPEG::get_file_format()
1045 char audio_format[BCSTRLEN], video_format[BCSTRLEN];
1046 file_format[0] = audio_format[0] = video_format[0] = 0;
1047 Asset *asset = file_base->asset;
1048 if( !ret && asset->audio_data )
1049 ret = get_format(audio_format, "audio", asset->acodec);
1050 if( !ret && asset->video_data )
1051 ret = get_format(video_format, "video", asset->vcodec);
1052 if( !ret && !audio_format[0] && !video_format[0] )
1054 if( !ret && audio_format[0] && video_format[0] &&
1055 strcmp(audio_format, video_format) ) ret = -1;
1057 strcpy(file_format, audio_format[0] ? audio_format : video_format);
1061 int FFMPEG::scan_option_line(char *cp, char *tag, char *val)
1063 while( *cp == ' ' || *cp == '\t' ) ++cp;
1065 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' ) ++cp;
1067 if( !len || len > BCSTRLEN-1 ) return 1;
1068 while( bp < cp ) *tag++ = *bp++;
1070 while( *cp == ' ' || *cp == '\t' ) ++cp;
1071 if( *cp == '=' ) ++cp;
1072 while( *cp == ' ' || *cp == '\t' ) ++cp;
1074 while( *cp && *cp != '\n' ) ++cp;
1076 if( len > BCTEXTLEN-1 ) return 1;
1077 while( bp < cp ) *val++ = *bp++;
1082 int FFMPEG::get_encoder(const char *options,
1083 char *format, char *codec, char *bsfilter, char *bsargs)
1085 FILE *fp = fopen(options,"r");
1087 eprintf("FFMPEG::get_encoder: options open failed %s\n",options);
1090 if( get_encoder(fp, format, codec, bsfilter, bsargs) )
1091 eprintf(_("FFMPEG::get_encoder:"
1092 " err: format/codec not found %s\n"), options);
1097 int FFMPEG::get_encoder(FILE *fp,
1098 char *format, char *codec, char *bsfilter, char *bsargs)
1100 format[0] = codec[0] = bsfilter[0] = bsargs[0] = 0;
1101 char line[BCTEXTLEN];
1102 if( !fgets(line, sizeof(line), fp) ) return 1;
1103 line[sizeof(line)-1] = 0;
1104 if( scan_option_line(line, format, codec) ) return 1;
1106 while( *cp && *cp != '|' ) ++cp;
1107 if( !*cp ) return 0;
1108 if( scan_option_line(cp+1, bsfilter, bsargs) ) return 1;
1109 do { *cp-- = 0; } while( cp>=codec && (*cp==' ' || *cp == '\t' ) );
1113 int FFMPEG::read_options(const char *options, AVDictionary *&opts)
1115 FILE *fp = fopen(options,"r");
1117 int ret = read_options(fp, options, opts);
1122 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
1124 FILE *fp = fmemopen((void *)options,strlen(options),"r");
1126 int ret = read_options(fp, options, opts);
1128 AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
1129 if( tag ) st->id = strtol(tag->value,0,0);
1133 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
1135 int ret = 0, no = 0;
1136 char line[BCTEXTLEN];
1137 while( !ret && fgets(line, sizeof(line), fp) ) {
1138 line[sizeof(line)-1] = 0;
1140 if( line[0] == '#' ) continue;
1141 if( line[0] == '\n' ) continue;
1142 char key[BCSTRLEN], val[BCTEXTLEN];
1143 if( scan_option_line(line, key, val) ) {
1144 eprintf(_("FFMPEG::read_options:"
1145 " err reading %s: line %d\n"), options, no);
1149 if( !strcmp(key, "duration") )
1150 opt_duration = strtod(val, 0);
1151 if( !strcmp(key, "video_filter") )
1152 opt_video_filter = cstrdup(val);
1153 if( !strcmp(key, "audio_filter") )
1154 opt_audio_filter = cstrdup(val);
1155 else if( !strcmp(key, "loglevel") )
1158 av_dict_set(&opts, key, val, 0);
1164 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
1166 char option_path[BCTEXTLEN];
1167 set_option_path(option_path, "%s", options);
1168 return read_options(option_path, opts);
1171 int FFMPEG::load_options(const char *path, char *bfr, int len)
1174 FILE *fp = fopen(path, "r");
1176 fgets(bfr, len, fp); // skip hdr
1177 len = fread(bfr, 1, len-1, fp);
1178 if( len < 0 ) len = 0;
1184 void FFMPEG::set_loglevel(const char *ap)
1186 if( !ap || !*ap ) return;
1191 { "quiet" , AV_LOG_QUIET },
1192 { "panic" , AV_LOG_PANIC },
1193 { "fatal" , AV_LOG_FATAL },
1194 { "error" , AV_LOG_ERROR },
1195 { "warning", AV_LOG_WARNING },
1196 { "info" , AV_LOG_INFO },
1197 { "verbose", AV_LOG_VERBOSE },
1198 { "debug" , AV_LOG_DEBUG },
1200 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
1201 if( !strcmp(log_levels[i].name, ap) ) {
1202 av_log_set_level(log_levels[i].level);
1206 av_log_set_level(atoi(ap));
1209 double FFMPEG::to_secs(int64_t time, AVRational time_base)
1211 double base_time = time == AV_NOPTS_VALUE ? 0 :
1212 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
1213 return base_time / AV_TIME_BASE;
1216 int FFMPEG::info(char *text, int len)
1218 if( len <= 0 ) return 0;
1219 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
1221 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1222 AVStream *st = fmt_ctx->streams[i];
1223 AVCodecContext *avctx = st->codec;
1224 report(_("stream %d, id 0x%06x:\n"), i, avctx->codec_id);
1225 const AVCodecDescriptor *desc = avcodec_descriptor_get(avctx->codec_id);
1226 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1227 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
1228 double frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
1229 report(" video %s",desc ? desc->name : " (unkn)");
1230 report(" %dx%d %5.2f", avctx->width, avctx->height, frame_rate);
1231 const char *pfn = av_get_pix_fmt_name(avctx->pix_fmt);
1232 report(" pix %s\n", pfn ? pfn : "(unkn)");
1233 double secs = to_secs(st->duration, st->time_base);
1234 int64_t length = secs * frame_rate + 0.5;
1235 report(" %jd frms %0.2f secs", length, secs);
1236 int hrs = secs/3600; secs -= hrs*3600;
1237 int mins = secs/60; secs -= mins*60;
1238 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1241 else if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1242 int sample_rate = avctx->sample_rate;
1243 const char *fmt = av_get_sample_fmt_name(avctx->sample_fmt);
1244 report(" audio %s",desc ? desc->name : " (unkn)");
1245 report(" %dch %s %d",avctx->channels, fmt, sample_rate);
1246 int sample_bits = av_get_bits_per_sample(avctx->codec_id);
1247 report(" %dbits\n", sample_bits);
1248 double secs = to_secs(st->duration, st->time_base);
1249 int64_t length = secs * sample_rate + 0.5;
1250 report(" %jd smpl %0.2f secs", length, secs);
1251 int hrs = secs/3600; secs -= hrs*3600;
1252 int mins = secs/60; secs -= mins*60;
1253 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1256 report(_(" codec_type unknown\n"));
1259 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
1260 report("program %d", i+1);
1261 AVProgram *pgrm = fmt_ctx->programs[i];
1262 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j )
1263 report(", %d", pgrm->stream_index[j]);
1267 AVDictionaryEntry *tag = 0;
1268 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
1269 report("%s=%s\n", tag->key, tag->value);
1278 int FFMPEG::init_decoder(const char *filename)
1280 ff_lock("FFMPEG::init_decoder");
1282 char file_opts[BCTEXTLEN];
1283 char *bp = strrchr(strcpy(file_opts, filename), '/');
1284 char *sp = strrchr(!bp ? file_opts : bp, '.');
1287 strcpy(sp, ".opts");
1288 fp = fopen(file_opts, "r");
1291 read_options(fp, file_opts, opts);
1295 load_options("decode.opts", opts);
1296 AVDictionary *fopts = 0;
1297 av_dict_copy(&fopts, opts, 0);
1298 int ret = avformat_open_input(&fmt_ctx, filename, NULL, &fopts);
1299 av_dict_free(&fopts);
1301 ret = avformat_find_stream_info(fmt_ctx, NULL);
1306 return !ret ? 0 : 1;
1309 int FFMPEG::open_decoder()
1312 if( stat(fmt_ctx->filename, &st) < 0 ) {
1313 eprintf("FFMPEG::open_decoder: can't stat file: %s\n",
1318 int64_t file_bits = 8 * st.st_size;
1319 if( !fmt_ctx->bit_rate && opt_duration > 0 )
1320 fmt_ctx->bit_rate = file_bits / opt_duration;
1323 if( fmt_ctx->bit_rate > 0 ) {
1324 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1325 AVStream *st = fmt_ctx->streams[i];
1326 if( st->duration != AV_NOPTS_VALUE ) continue;
1327 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
1328 st->duration = av_rescale(file_bits, st->time_base.den,
1329 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
1334 printf("FFMPEG::open_decoder: some stream times estimated\n");
1336 ff_lock("FFMPEG::open_decoder");
1338 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1339 AVStream *st = fmt_ctx->streams[i];
1340 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
1341 AVCodecContext *avctx = st->codec;
1342 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avctx->codec_id);
1343 if( !codec_desc ) continue;
1344 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1345 if( avctx->width < 1 ) continue;
1346 if( avctx->height < 1 ) continue;
1347 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
1348 if( framerate.num < 1 ) continue;
1350 FFVideoStream *vid = new FFVideoStream(this, st, i);
1351 int vidx = ffvideo.size();
1352 vstrm_index.append(ffidx(vidx, 0));
1353 ffvideo.append(vid);
1354 vid->width = avctx->width;
1355 vid->height = avctx->height;
1356 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
1357 double secs = to_secs(st->duration, st->time_base);
1358 vid->length = secs * vid->frame_rate;
1359 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
1360 vid->nudge = st->start_time;
1362 if( opt_video_filter )
1363 vid->create_filter(opt_video_filter, avctx,avctx);
1365 else if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1366 if( avctx->channels < 1 ) continue;
1367 if( avctx->sample_rate < 1 ) continue;
1369 FFAudioStream *aud = new FFAudioStream(this, st, i);
1370 int aidx = ffaudio.size();
1371 ffaudio.append(aud);
1372 aud->channel0 = astrm_index.size();
1373 aud->channels = avctx->channels;
1374 for( int ch=0; ch<aud->channels; ++ch )
1375 astrm_index.append(ffidx(aidx, ch));
1376 aud->sample_rate = avctx->sample_rate;
1377 double secs = to_secs(st->duration, st->time_base);
1378 aud->length = secs * aud->sample_rate;
1379 if( avctx->sample_fmt != AV_SAMPLE_FMT_FLT ) {
1380 uint64_t layout = av_get_default_channel_layout(avctx->channels);
1381 if( !layout ) layout = ((uint64_t)1<<aud->channels) - 1;
1382 aud->resample_context = swr_alloc_set_opts(NULL,
1383 layout, AV_SAMPLE_FMT_FLT, avctx->sample_rate,
1384 layout, avctx->sample_fmt, avctx->sample_rate,
1386 swr_init(aud->resample_context);
1388 aud->nudge = st->start_time;
1390 if( opt_audio_filter )
1391 aud->create_filter(opt_audio_filter, avctx,avctx);
1395 printf("FFMPEG::open_decoder: some stream have bad times\n");
1401 int FFMPEG::init_encoder(const char *filename)
1403 int fd = ::open(filename,O_WRONLY);
1404 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
1406 eprintf("FFMPEG::init_encoder: bad file path: %s\n", filename);
1410 int ret = get_file_format();
1412 eprintf("FFMPEG::init_encoder: bad file format: %s\n", filename);
1416 eprintf("FFMPEG::init_encoder: mismatch audio/video file format: %s\n", filename);
1419 ff_lock("FFMPEG::init_encoder");
1421 avformat_alloc_output_context2(&fmt_ctx, 0, file_format, filename);
1423 eprintf("FFMPEG::init_encoder: failed: %s\n", filename);
1428 load_options("encode.opts", opts);
1435 int FFMPEG::open_encoder(const char *type, const char *spec)
1438 Asset *asset = file_base->asset;
1439 char *filename = asset->path;
1440 AVDictionary *sopts = 0;
1441 av_dict_copy(&sopts, opts, 0);
1442 char option_path[BCTEXTLEN];
1443 set_option_path(option_path, "%s/%s.opts", type, type);
1444 read_options(option_path, sopts);
1445 get_option_path(option_path, type, spec);
1446 char format_name[BCSTRLEN], codec_name[BCTEXTLEN];
1447 char bsfilter[BCSTRLEN], bsargs[BCTEXTLEN];
1448 if( get_encoder(option_path, format_name, codec_name, bsfilter, bsargs) ) {
1449 eprintf("FFMPEG::open_encoder: get_encoder failed %s:%s\n",
1450 option_path, filename);
1454 if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
1455 else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
1456 else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
1459 ff_lock("FFMPEG::open_encoder");
1463 const AVCodecDescriptor *codec_desc = 0;
1464 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
1466 eprintf("FFMPEG::open_encoder: cant find codec %s:%s\n",
1467 codec_name, filename);
1471 codec_desc = avcodec_descriptor_get(codec->id);
1473 eprintf("FFMPEG::open_encoder: unknown codec %s:%s\n",
1474 codec_name, filename);
1479 st = avformat_new_stream(fmt_ctx, 0);
1481 eprintf("FFMPEG::open_encoder: cant create stream %s:%s\n",
1482 codec_name, filename);
1487 AVCodecContext *ctx = st->codec;
1488 switch( codec_desc->type ) {
1489 case AVMEDIA_TYPE_AUDIO: {
1491 eprintf("FFMPEG::open_encoder: duplicate audio %s:%s\n",
1492 codec_name, filename);
1497 if( scan_options(asset->ff_audio_options, sopts, st) ) {
1498 eprintf("FFMPEG::open_encoder: bad audio options %s:%s\n",
1499 codec_name, filename);
1503 if( asset->ff_audio_bitrate > 0 ) {
1504 ctx->bit_rate = asset->ff_audio_bitrate;
1506 sprintf(arg, "%d", asset->ff_audio_bitrate);
1507 av_dict_set(&sopts, "b", arg, 0);
1509 int aidx = ffaudio.size();
1510 int idx = aidx + ffvideo.size();
1511 FFAudioStream *aud = new FFAudioStream(this, st, idx);
1512 ffaudio.append(aud); fst = aud;
1513 aud->sample_rate = asset->sample_rate;
1514 ctx->channels = aud->channels = asset->channels;
1515 for( int ch=0; ch<aud->channels; ++ch )
1516 astrm_index.append(ffidx(aidx, ch));
1517 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
1518 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
1519 if( !ctx->sample_rate ) {
1520 eprintf("FFMPEG::open_audio_encode:"
1521 " check_sample_rate failed %s\n", filename);
1525 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
1526 ctx->sample_fmt = codec->sample_fmts[0];
1527 uint64_t layout = av_get_default_channel_layout(ctx->channels);
1528 aud->resample_context = swr_alloc_set_opts(NULL,
1529 layout, ctx->sample_fmt, aud->sample_rate,
1530 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
1532 swr_init(aud->resample_context);
1535 case AVMEDIA_TYPE_VIDEO: {
1537 eprintf("FFMPEG::open_encoder: duplicate video %s:%s\n",
1538 codec_name, filename);
1543 if( scan_options(asset->ff_video_options, sopts, st) ) {
1544 eprintf("FFMPEG::open_encoder: bad video options %s:%s\n",
1545 codec_name, filename);
1549 if( asset->ff_video_bitrate > 0 ) {
1550 ctx->bit_rate = asset->ff_video_bitrate;
1552 sprintf(arg, "%d", asset->ff_video_bitrate);
1553 av_dict_set(&sopts, "b", arg, 0);
1555 else if( asset->ff_video_quality > 0 ) {
1556 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
1557 ctx->qmin = ctx->qmax = asset->ff_video_quality;
1558 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
1559 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
1560 ctx->flags |= CODEC_FLAG_QSCALE;
1562 av_dict_set(&sopts, "flags", "+qscale", 0);
1563 sprintf(arg, "%d", asset->ff_video_quality);
1564 av_dict_set(&sopts, "qscale", arg, 0);
1565 sprintf(arg, "%d", ctx->global_quality);
1566 av_dict_set(&sopts, "global_quality", arg, 0);
1568 int vidx = ffvideo.size();
1569 int idx = vidx + ffaudio.size();
1570 FFVideoStream *vid = new FFVideoStream(this, st, idx);
1571 vstrm_index.append(ffidx(vidx, 0));
1572 ffvideo.append(vid); fst = vid;
1573 vid->width = asset->width;
1574 ctx->width = (vid->width+3) & ~3;
1575 vid->height = asset->height;
1576 ctx->height = (vid->height+3) & ~3;
1577 vid->frame_rate = asset->frame_rate;
1578 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
1579 ctx->pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
1580 AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
1581 if( !frame_rate.num || !frame_rate.den ) {
1582 eprintf("FFMPEG::open_audio_encode:"
1583 " check_frame_rate failed %s\n", filename);
1587 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
1588 st->time_base = ctx->time_base;
1592 eprintf("FFMPEG::open_encoder: not audio/video, %s:%s\n",
1593 codec_name, filename);
1598 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
1599 st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
1601 ret = avcodec_open2(st->codec, codec, &sopts);
1603 ff_err(ret,"FFMPEG::open_encoder");
1604 eprintf("FFMPEG::open_encoder: open failed %s:%s\n",
1605 codec_name, filename);
1612 if( fst && bsfilter[0] )
1613 fst->add_bsfilter(bsfilter, !bsargs[0] ? 0 : bsargs);
1617 av_dict_free(&sopts);
1621 int FFMPEG::close_encoder()
1624 if( encoding > 0 ) {
1625 av_write_trailer(fmt_ctx);
1626 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
1627 avio_closep(&fmt_ctx->pb);
1633 int FFMPEG::decode_activate()
1635 if( decoding < 0 ) {
1637 int npgrms = fmt_ctx->nb_programs;
1638 for( int i=0; i<npgrms; ++i ) {
1639 AVProgram *pgrm = fmt_ctx->programs[i];
1640 // first start time video stream
1641 int64_t vstart_time = -1;
1642 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1643 int st_idx = pgrm->stream_index[j];
1644 AVStream *st = fmt_ctx->streams[st_idx];
1645 AVCodecContext *avctx = st->codec;
1646 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1647 if( st->start_time == AV_NOPTS_VALUE ) continue;
1648 vstart_time = st->start_time;
1652 // max start time audio stream
1653 int64_t astart_time = -1;
1654 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1655 int st_idx = pgrm->stream_index[j];
1656 AVStream *st = fmt_ctx->streams[st_idx];
1657 AVCodecContext *avctx = st->codec;
1658 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1659 if( st->start_time == AV_NOPTS_VALUE ) continue;
1660 if( astart_time > st->start_time ) continue;
1661 astart_time = st->start_time;
1664 if( astart_time < 0 || vstart_time < 0 ) continue;
1665 // match program streams to max start_time
1666 int64_t nudge = vstart_time > astart_time ? vstart_time : astart_time;
1667 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1668 int st_idx = pgrm->stream_index[j];
1669 AVStream *st = fmt_ctx->streams[st_idx];
1670 AVCodecContext *avctx = st->codec;
1671 if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1672 for( int k=0; k<ffaudio.size(); ++k ) {
1673 if( ffaudio[k]->idx == st_idx )
1674 ffaudio[k]->nudge = nudge;
1677 else if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1678 for( int k=0; k<ffvideo.size(); ++k ) {
1679 if( ffvideo[k]->idx == st_idx )
1680 ffvideo[k]->nudge = nudge;
1685 int64_t vstart_time = 0, astart_time = 0;
1686 int nstreams = fmt_ctx->nb_streams;
1687 for( int i=0; i<nstreams; ++i ) {
1688 AVStream *st = fmt_ctx->streams[i];
1689 AVCodecContext *avctx = st->codec;
1690 switch( avctx->codec_type ) {
1691 case AVMEDIA_TYPE_VIDEO:
1692 if( st->start_time == AV_NOPTS_VALUE ) continue;
1693 if( vstart_time >= st->start_time ) continue;
1694 vstart_time = st->start_time;
1696 case AVMEDIA_TYPE_AUDIO:
1697 if( st->start_time == AV_NOPTS_VALUE ) continue;
1698 if( astart_time >= st->start_time ) continue;
1699 astart_time = st->start_time;
1703 int64_t nudge = vstart_time > astart_time ? vstart_time : astart_time;
1704 for( int k=0; k<ffvideo.size(); ++k ) {
1705 if( ffvideo[k]->nudge != AV_NOPTS_VALUE ) continue;
1706 ffvideo[k]->nudge = nudge;
1708 for( int k=0; k<ffaudio.size(); ++k ) {
1709 if( ffaudio[k]->nudge != AV_NOPTS_VALUE ) continue;
1710 ffaudio[k]->nudge = nudge;
1717 int FFMPEG::encode_activate()
1720 if( encoding < 0 ) {
1722 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
1723 (ret=avio_open(&fmt_ctx->pb, fmt_ctx->filename, AVIO_FLAG_WRITE)) < 0 ) {
1724 ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
1729 AVDictionary *fopts = 0;
1730 char option_path[BCTEXTLEN];
1731 set_option_path(option_path, "format/%s", file_format);
1732 read_options(option_path, fopts);
1733 ret = avformat_write_header(fmt_ctx, &fopts);
1734 av_dict_free(&fopts);
1736 ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
1745 int FFMPEG::audio_seek(int stream, int64_t pos)
1747 int aidx = astrm_index[stream].st_idx;
1748 FFAudioStream *aud = ffaudio[aidx];
1749 aud->audio_seek(pos);
1750 aud->seek_pos = aud->curr_pos = pos;
1754 int FFMPEG::video_seek(int stream, int64_t pos)
1756 int vidx = vstrm_index[stream].st_idx;
1757 FFVideoStream *vid = ffvideo[vidx];
1758 vid->video_seek(pos);
1759 vid->seek_pos = vid->curr_pos = pos;
1764 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
1766 if( !has_audio || chn >= astrm_index.size() ) return -1;
1767 int aidx = astrm_index[chn].st_idx;
1768 FFAudioStream *aud = ffaudio[aidx];
1769 if( aud->load(pos, len) < len ) return -1;
1770 int ch = astrm_index[chn].st_ch;
1771 return aud->read(samples,len,ch);
1774 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
1776 if( !has_video || layer >= vstrm_index.size() ) return -1;
1777 int vidx = vstrm_index[layer].st_idx;
1778 FFVideoStream *vid = ffvideo[vidx];
1779 return vid->load(vframe, pos);
1782 int FFMPEG::encode(int stream, double **samples, int len)
1784 FFAudioStream *aud = ffaudio[stream];
1785 return aud->encode(samples, len);
1789 int FFMPEG::encode(int stream, VFrame *frame)
1791 FFVideoStream *vid = ffvideo[stream];
1792 return vid->encode(frame);
1795 void FFMPEG::start_muxer()
1803 void FFMPEG::stop_muxer()
1812 void FFMPEG::flow_off()
1815 flow_lock->lock("FFMPEG::flow_off");
1819 void FFMPEG::flow_on()
1823 flow_lock->unlock();
1826 void FFMPEG::flow_ctl()
1829 flow_lock->lock("FFMPEG::flow_ctl");
1830 flow_lock->unlock();
1834 int FFMPEG::mux_audio(FFrame *frm)
1837 FFStream *fst = frm->fst;
1838 AVCodecContext *ctx = fst->st->codec;
1839 AVFrame *frame = *frm;
1840 AVRational tick_rate = {1, ctx->sample_rate};
1841 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
1843 int ret = fst->encode_frame(pkt, frame, got_packet);
1844 if( ret >= 0 && got_packet )
1845 ret = fst->write_packet(pkt);
1847 ff_err(ret, "FFMPEG::mux_audio");
1848 return ret >= 0 ? 0 : 1;
1851 int FFMPEG::mux_video(FFrame *frm)
1854 FFStream *fst = frm->fst;
1855 AVFrame *frame = *frm;
1856 frame->pts = frm->position;
1857 int ret = 1, got_packet = 0;
1858 if( fmt_ctx->oformat->flags & AVFMT_RAWPICTURE ) {
1859 /* a hack to avoid data copy with some raw video muxers */
1860 pkt->flags |= AV_PKT_FLAG_KEY;
1861 pkt->stream_index = fst->st->index;
1862 AVPicture *picture = (AVPicture *)frame;
1863 pkt->data = (uint8_t *)picture;
1864 pkt->size = sizeof(AVPicture);
1865 pkt->pts = pkt->dts = frame->pts;
1869 ret = fst->encode_frame(pkt, frame, got_packet);
1870 if( ret >= 0 && got_packet )
1871 ret = fst->write_packet(pkt);
1873 ff_err(ret, "FFMPEG::mux_video");
1874 return ret >= 0 ? 0 : 1;
1880 double atm = -1, vtm = -1;
1881 FFrame *afrm = 0, *vfrm = 0;
1883 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
1884 FFStream *fst = ffaudio[i];
1885 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
1886 FFrame *frm = fst->frms.first;
1887 if( !frm ) { if( !done ) return; continue; }
1888 double tm = to_secs(frm->position, fst->st->codec->time_base);
1889 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
1891 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
1892 FFStream *fst = ffvideo[i];
1893 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
1894 FFrame *frm = fst->frms.first;
1895 if( !frm ) { if( !done ) return; continue; }
1896 double tm = to_secs(frm->position, fst->st->codec->time_base);
1897 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
1899 if( !demand ) flow_off();
1900 if( !afrm && !vfrm ) break;
1901 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
1902 vfrm->position, vfrm->fst->st->codec->time_base,
1903 afrm->position, afrm->fst->st->codec->time_base);
1904 FFrame *frm = v <= 0 ? vfrm : afrm;
1905 if( frm == afrm ) mux_audio(frm);
1906 if( frm == vfrm ) mux_video(frm);
1915 mux_lock->lock("FFMPEG::run");
1919 for( int i=0; i<ffaudio.size(); ++i )
1920 ffaudio[i]->flush();
1921 for( int i=0; i<ffvideo.size(); ++i )
1922 ffvideo[i]->flush();
1926 int FFMPEG::ff_total_audio_channels()
1928 return astrm_index.size();
1931 int FFMPEG::ff_total_astreams()
1933 return ffaudio.size();
1936 int FFMPEG::ff_audio_channels(int stream)
1938 return ffaudio[stream]->channels;
1941 int FFMPEG::ff_sample_rate(int stream)
1943 return ffaudio[stream]->sample_rate;
1946 const char* FFMPEG::ff_audio_format(int stream)
1948 AVStream *st = ffaudio[stream]->st;
1949 AVCodecID id = st->codec->codec_id;
1950 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
1951 return desc ? desc->name : "Unknown";
1954 int FFMPEG::ff_audio_pid(int stream)
1956 return ffaudio[stream]->st->id;
1959 int64_t FFMPEG::ff_audio_samples(int stream)
1961 return ffaudio[stream]->length;
1964 // find audio astream/channels with this program,
1965 // or all program audio channels (astream=-1)
1966 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
1970 int vidx = ffvideo[vstream]->idx;
1971 // find first program with this video stream
1972 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
1973 AVProgram *pgrm = fmt_ctx->programs[i];
1974 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
1975 int st_idx = pgrm->stream_index[j];
1976 AVStream *st = fmt_ctx->streams[st_idx];
1977 if( st->codec->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
1978 if( st_idx == vidx ) pidx = i;
1981 if( pidx < 0 ) return -1;
1983 int64_t channels = 0;
1984 AVProgram *pgrm = fmt_ctx->programs[pidx];
1985 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1986 int aidx = pgrm->stream_index[j];
1987 AVStream *st = fmt_ctx->streams[aidx];
1988 if( st->codec->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
1989 if( astream > 0 ) { --astream; continue; }
1991 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
1992 if( ffaudio[i]->idx == aidx ) astrm = i;
1994 if( ret < 0 ) ret = astrm;
1995 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
1996 channels |= mask << ffaudio[astrm]->channel0;
1998 if( !astream ) break;
2000 channel_mask = channels;
2005 int FFMPEG::ff_total_video_layers()
2007 return vstrm_index.size();
2010 int FFMPEG::ff_total_vstreams()
2012 return ffvideo.size();
2015 int FFMPEG::ff_video_width(int stream)
2017 return ffvideo[stream]->width;
2020 int FFMPEG::ff_video_height(int stream)
2022 return ffvideo[stream]->height;
2025 int FFMPEG::ff_set_video_width(int stream, int width)
2027 int w = ffvideo[stream]->width;
2028 ffvideo[stream]->width = width;
2032 int FFMPEG::ff_set_video_height(int stream, int height)
2034 int h = ffvideo[stream]->height;
2035 ffvideo[stream]->height = height;
2039 int FFMPEG::ff_coded_width(int stream)
2041 AVStream *st = ffvideo[stream]->st;
2042 return st->codec->coded_width;
2045 int FFMPEG::ff_coded_height(int stream)
2047 AVStream *st = ffvideo[stream]->st;
2048 return st->codec->coded_height;
2051 float FFMPEG::ff_aspect_ratio(int stream)
2053 return ffvideo[stream]->aspect_ratio;
2056 const char* FFMPEG::ff_video_format(int stream)
2058 AVStream *st = ffvideo[stream]->st;
2059 AVCodecID id = st->codec->codec_id;
2060 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2061 return desc ? desc->name : "Unknown";
2064 double FFMPEG::ff_frame_rate(int stream)
2066 return ffvideo[stream]->frame_rate;
2069 int64_t FFMPEG::ff_video_frames(int stream)
2071 return ffvideo[stream]->length;
2074 int FFMPEG::ff_video_pid(int stream)
2076 return ffvideo[stream]->st->id;
2080 int FFMPEG::ff_cpus()
2082 return file_base->file->cpus;
2085 int FFVideoStream::create_filter(const char *filter_spec,
2086 AVCodecContext *src_ctx, AVCodecContext *sink_ctx)
2088 avfilter_register_all();
2089 AVFilter *filter = avfilter_get_by_name(filter_spec);
2090 if( !filter || filter->inputs->type != AVMEDIA_TYPE_VIDEO ) {
2091 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
2094 filter_graph = avfilter_graph_alloc();
2095 AVFilter *buffersrc = avfilter_get_by_name("buffer");
2096 AVFilter *buffersink = avfilter_get_by_name("buffersink");
2098 int ret = 0; char args[BCTEXTLEN];
2099 snprintf(args, sizeof(args),
2100 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
2101 src_ctx->width, src_ctx->height, src_ctx->pix_fmt,
2102 st->time_base.num, st->time_base.den,
2103 src_ctx->sample_aspect_ratio.num, src_ctx->sample_aspect_ratio.den);
2105 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2106 args, NULL, filter_graph);
2108 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2109 NULL, NULL, filter_graph);
2111 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
2112 (uint8_t*)&sink_ctx->pix_fmt, sizeof(sink_ctx->pix_fmt),
2113 AV_OPT_SEARCH_CHILDREN);
2115 ff_err(ret, "FFVideoStream::create_filter");
2117 ret = FFStream::create_filter(filter_spec);
2118 return ret >= 0 ? 0 : 1;
2121 int FFAudioStream::create_filter(const char *filter_spec,
2122 AVCodecContext *src_ctx, AVCodecContext *sink_ctx)
2124 avfilter_register_all();
2125 AVFilter *filter = avfilter_get_by_name(filter_spec);
2126 if( !filter || filter->inputs->type != AVMEDIA_TYPE_AUDIO ) {
2127 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
2130 filter_graph = avfilter_graph_alloc();
2131 AVFilter *buffersrc = avfilter_get_by_name("abuffer");
2132 AVFilter *buffersink = avfilter_get_by_name("abuffersink");
2133 int ret = 0; char args[BCTEXTLEN];
2134 snprintf(args, sizeof(args),
2135 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
2136 st->time_base.num, st->time_base.den, src_ctx->sample_rate,
2137 av_get_sample_fmt_name(src_ctx->sample_fmt), src_ctx->channel_layout);
2139 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2140 args, NULL, filter_graph);
2142 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2143 NULL, NULL, filter_graph);
2145 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
2146 (uint8_t*)&sink_ctx->sample_fmt, sizeof(sink_ctx->sample_fmt),
2147 AV_OPT_SEARCH_CHILDREN);
2149 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
2150 (uint8_t*)&sink_ctx->channel_layout,
2151 sizeof(sink_ctx->channel_layout), AV_OPT_SEARCH_CHILDREN);
2153 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
2154 (uint8_t*)&sink_ctx->sample_rate, sizeof(sink_ctx->sample_rate),
2155 AV_OPT_SEARCH_CHILDREN);
2157 ff_err(ret, "FFAudioStream::create_filter");
2159 ret = FFStream::create_filter(filter_spec);
2160 return ret >= 0 ? 0 : 1;
2163 int FFStream::create_filter(const char *filter_spec)
2165 /* Endpoints for the filter graph. */
2166 AVFilterInOut *outputs = avfilter_inout_alloc();
2167 outputs->name = av_strdup("in");
2168 outputs->filter_ctx = buffersrc_ctx;
2169 outputs->pad_idx = 0;
2172 AVFilterInOut *inputs = avfilter_inout_alloc();
2173 inputs->name = av_strdup("out");
2174 inputs->filter_ctx = buffersink_ctx;
2175 inputs->pad_idx = 0;
2178 int ret = !outputs->name || !inputs->name ? -1 : 0;
2180 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
2181 &inputs, &outputs, NULL);
2183 ret = avfilter_graph_config(filter_graph, NULL);
2186 ff_err(ret, "FFStream::create_filter");
2187 avfilter_inout_free(&inputs);
2188 avfilter_inout_free(&outputs);
2192 void FFStream::add_bsfilter(const char *bsf, const char *ap)
2194 bsfilter.append(new BSFilter(bsf,ap));
2197 int FFStream::bs_filter(AVPacket *pkt)
2199 if( !bsfilter.size() ) return 0;
2200 av_packet_split_side_data(pkt);
2203 for( int i=0; i<bsfilter.size(); ++i ) {
2204 AVPacket bspkt = *pkt;
2205 ret = av_bitstream_filter_filter(bsfilter[i]->bsfc,
2206 st->codec, bsfilter[i]->args, &bspkt.data, &bspkt.size,
2207 pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY);
2208 if( ret < 0 ) break;
2209 int size = bspkt.size;
2210 uint8_t *data = bspkt.data;
2211 if( !ret && bspkt.data != pkt->data ) {
2213 data = (uint8_t *)av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
2214 if( !data ) { ret = AVERROR(ENOMEM); break; }
2215 memcpy(data, bspkt.data, size);
2216 memset(data+size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2220 pkt->side_data = 0; pkt->side_data_elems = 0;
2221 av_free_packet(pkt);
2222 ret = av_packet_from_data(&bspkt, data, size);
2223 if( ret < 0 ) break;
2228 ff_err(ret,"FFStream::bs_filter");