10 // work arounds (centos)
13 #define INT64_MAX 9223372036854775807LL
15 #define MAX_RETRY 1000
18 #include "bccmodels.h"
20 #include "fileffmpeg.h"
23 #include "indexfile.h"
26 #include "mainerror.h"
31 #define VIDEO_INBUF_SIZE 0x10000
32 #define AUDIO_INBUF_SIZE 0x10000
33 #define VIDEO_REFILL_THRESH 0
34 #define AUDIO_REFILL_THRESH 0x1000
36 Mutex FFMPEG::fflock("FFMPEG::fflock");
38 static void ff_err(int ret, const char *fmt, ...)
43 vsnprintf(msg, sizeof(msg), fmt, ap);
45 char errmsg[BCSTRLEN];
46 av_strerror(ret, errmsg, sizeof(errmsg));
47 fprintf(stderr,_("%s err: %s\n"),msg, errmsg);
63 pkt.data = 0; pkt.size = 0;
66 FFrame::FFrame(FFStream *fst)
69 frm = av_frame_alloc();
70 init = fst->init_frame(frm);
78 void FFrame::queue(int64_t pos)
84 void FFrame::dequeue()
89 int FFAudioStream::read(float *fp, long len)
97 while( --k >= 0 ) *fp++ = *op++;
98 if( op >= lmt ) op = bfr;
103 void FFAudioStream::realloc(long nsz, int nch, long len)
105 long bsz = nsz * nch;
106 float *np = new float[bsz];
107 inp = np + read(np, len) * nch;
112 delete [] bfr; bfr = np;
115 void FFAudioStream::realloc(long nsz, int nch)
117 if( nsz > sz || this->nch != nch ) {
118 long len = this->nch != nch ? 0 : hpos;
119 if( len > sz ) len = sz;
121 realloc(nsz, nch, len);
125 void FFAudioStream::reserve(long nsz, int nch)
127 long len = (inp - outp) / nch;
129 if( nsz > sz || this->nch != nch ) {
130 if( this->nch != nch ) len = 0;
131 realloc(nsz, nch, len);
134 if( (len*=nch) > 0 && bfr != outp )
135 memmove(bfr, outp, len*sizeof(*bfr));
140 long FFAudioStream::used()
142 long len = inp>=outp ? inp-outp : inp-bfr + lmt-outp;
145 long FFAudioStream::avail()
148 if( in1 >= lmt ) in1 = bfr;
149 long len = outp >= in1 ? outp-in1 : outp-bfr + lmt-in1;
152 void FFAudioStream::reset_history()
158 void FFAudioStream::iseek(int64_t ofs)
160 outp = inp - ofs*nch;
161 if( outp < bfr ) outp += sz*nch;
164 float *FFAudioStream::get_outp(int ofs)
171 int64_t FFAudioStream::put_inp(int ofs)
174 return (inp-outp) / nch;
177 int FFAudioStream::write(const float *fp, long len)
185 while( --k >= 0 ) *ip++ = *fp++;
186 if( ip >= lmt ) ip = bfr;
193 int FFAudioStream::zero(long len)
201 while( --k >= 0 ) *ip++ = 0;
202 if( ip >= lmt ) ip = bfr;
209 // does not advance outp
210 int FFAudioStream::read(double *dp, long len, int ch)
213 float *op = outp + ch;
214 float *lmt1 = lmt + nch-1;
216 int k = (lmt1 - op) / nch;
219 while( --k >= 0 ) { *dp++ = *op; op += nch; }
220 if( op >= lmt ) op -= sz*nch;
225 // load linear buffer, no wrapping allowed, does not advance inp
226 int FFAudioStream::write(const double *dp, long len, int ch)
229 float *ip = inp + ch;
230 while( --n >= 0 ) { *ip = *dp++; ip += nch; }
235 FFStream::FFStream(FFMPEG *ffmpeg, AVStream *st, int fidx)
237 this->ffmpeg = ffmpeg;
240 frm_lock = new Mutex("FFStream::frm_lock");
246 nudge = AV_NOPTS_VALUE;
247 seek_pos = curr_pos = 0;
250 reading = writing = 0;
256 FFStream::~FFStream()
258 if( reading > 0 || writing > 0 ) avcodec_close(st->codec);
259 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
260 while( frms.first ) frms.remove(frms.first);
261 if( filter_graph ) avfilter_graph_free(&filter_graph);
262 if( frame ) av_frame_free(&frame);
263 if( fframe ) av_frame_free(&fframe);
264 bsfilter.remove_all_objects();
268 void FFStream::ff_lock(const char *cp)
270 FFMPEG::fflock.lock(cp);
273 void FFStream::ff_unlock()
275 FFMPEG::fflock.unlock();
278 void FFStream::queue(FFrame *frm)
280 frm_lock->lock("FFStream::queue");
284 ffmpeg->mux_lock->unlock();
287 void FFStream::dequeue(FFrame *frm)
289 frm_lock->lock("FFStream::dequeue");
291 frms.remove_pointer(frm);
295 int FFStream::encode_activate()
298 writing = ffmpeg->encode_activate();
302 int FFStream::decode_activate()
304 if( reading < 0 && (reading=ffmpeg->decode_activate()) > 0 ) {
305 ff_lock("FFStream::decode_activate");
307 AVDictionary *copts = 0;
308 av_dict_copy(&copts, ffmpeg->opts, 0);
310 // this should be avformat_copy_context(), but no copy avail
311 ret = avformat_open_input(&fmt_ctx, ffmpeg->fmt_ctx->filename, NULL, &copts);
313 ret = avformat_find_stream_info(fmt_ctx, 0);
314 st = fmt_ctx->streams[fidx];
318 AVCodecID codec_id = st->codec->codec_id;
319 AVCodec *decoder = avcodec_find_decoder(codec_id);
320 ret = avcodec_open2(st->codec, decoder, &copts);
324 eprintf("FFStream::decode_activate: open decoder failed\n");
327 eprintf("FFStream::decode_activate: can't clone input file\n");
328 av_dict_free(&copts);
334 int FFStream::read_packet()
336 av_packet_unref(ipkt);
337 int ret = av_read_frame(fmt_ctx, ipkt);
340 if( ret == AVERROR_EOF ) {
341 ipkt->stream_index = st->index;
344 ff_err(ret, "FFStream::read_packet: av_read_frame failed\n");
351 int FFStream::decode(AVFrame *frame)
354 int retries = MAX_RETRY;
357 while( ret >= 0 && !flushed && --retries >= 0 && !got_frame ) {
360 if( (ret=read_packet()) < 0 ) break;
362 if( ipkt->stream_index == st->index ) {
363 while( (ipkt->size > 0 || !ipkt->data) && !got_frame ) {
364 ret = decode_frame(ipkt, frame, got_frame);
365 if( ret <= 0 || !ipkt->data ) break;
378 fprintf(stderr, "FFStream::decode: Retry limit\n");
382 fprintf(stderr, "FFStream::decode: failed\n");
387 int FFStream::load_filter(AVFrame *frame)
389 int ret = av_buffersrc_add_frame_flags(buffersrc_ctx,
390 frame, AV_BUFFERSRC_FLAG_KEEP_REF);
392 av_frame_unref(frame);
393 eprintf("FFStream::load_filter: av_buffersrc_add_frame_flags failed\n");
398 int FFStream::read_filter(AVFrame *frame)
400 int ret = av_buffersink_get_frame(buffersink_ctx, frame);
402 if( ret == AVERROR(EAGAIN) ) return 0;
403 if( ret == AVERROR_EOF ) { st_eof(1); return -1; }
404 ff_err(ret, "FFStream::read_filter: av_buffersink_get_frame failed\n");
410 int FFStream::read_frame(AVFrame *frame)
412 if( !filter_graph || !buffersrc_ctx || !buffersink_ctx )
413 return decode(frame);
414 if( !fframe && !(fframe=av_frame_alloc()) ) {
415 fprintf(stderr, "FFStream::read_frame: av_frame_alloc failed\n");
419 while( !flushed && !(ret=read_filter(frame)) ) {
420 if( (ret=decode(fframe)) < 0 ) break;
421 if( ret > 0 && (ret=load_filter(fframe)) < 0 ) break;
426 int FFStream::write_packet(FFPacket &pkt)
429 av_packet_rescale_ts(pkt, st->codec->time_base, st->time_base);
430 pkt->stream_index = st->index;
431 return av_interleaved_write_frame(ffmpeg->fmt_ctx, pkt);
434 int FFStream::flush()
440 ret = encode_frame(pkt, 0, got_packet);
441 if( ret < 0 || !got_packet ) break;
442 ret = write_packet(pkt);
445 ff_err(ret, "FFStream::flush");
446 return ret >= 0 ? 0 : 1;
449 int FFStream::seek(int64_t no, double rate)
452 // default ffmpeg native seek
454 int64_t pos = no, plmt = -1;
455 if( index_markers && index_markers->size() > 1 ) {
456 IndexMarks &marks = *index_markers;
457 int i = marks.find(pos);
458 int64_t n = i < 0 ? (i=0) : marks[i].no;
459 // if indexed seek point not too far away (<30 secs), use index
460 if( no-n < 30*rate ) {
467 double secs = pos / rate;
468 int64_t pkt_ts, tstmp = secs * st->time_base.den / st->time_base.num;
469 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
470 int ret = avformat_seek_file(fmt_ctx, st->index,
471 -INT64_MAX, tstmp, INT64_MAX, AVSEEK_FLAG_ANY);
473 avcodec_flush_buffers(st->codec);
474 need_packet = 0; flushed = 0;
475 seeked = 1; st_eof(0);
476 // read up to retry packets, limited to npkts in stream, and not past pkt.pos plmt
477 for( int retry=MAX_RETRY; ret>=0 && --retry>=0; ) {
478 if( read_packet() <= 0 || ( plmt >= 0 && ipkt->pos > plmt ) ) {
481 if( ipkt->stream_index != st->index ) continue;
482 if( --npkts <= 0 ) break;
483 if( (pkt_ts=ipkt->dts) == AV_NOPTS_VALUE &&
484 (pkt_ts=ipkt->pts) == AV_NOPTS_VALUE ) continue;
485 if( pkt_ts >= tstmp ) break;
489 //printf("** seek fail %ld, %ld\n", pos, tstmp);
490 seeked = need_packet = 0;
494 //printf("seeked pos = %ld, %ld\n", pos, tstmp);
495 seek_pos = curr_pos = pos;
499 FFAudioStream::FFAudioStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
500 : FFStream(ffmpeg, strm, fidx)
503 channel0 = channels = 0;
507 resample_context = 0;
516 bfr = new float[bsz];
521 FFAudioStream::~FFAudioStream()
523 if( resample_context ) swr_free(&resample_context);
528 int FFAudioStream::get_samples(float *&samples, uint8_t **data, int len)
530 samples = *(float **)data;
531 if( resample_context ) {
532 if( len > aud_bfr_sz ) {
538 aud_bfr = new float[aud_bfr_sz*channels];
540 int ret = swr_convert(resample_context,
541 (uint8_t**)&aud_bfr, aud_bfr_sz, (const uint8_t**)data, len);
543 ff_err(ret, "FFAudioStream::get_samples: swr_convert failed\n");
552 int FFAudioStream::load_history(uint8_t **data, int len)
555 len = get_samples(samples, data, len);
557 // biggest user bfr since seek + frame
558 realloc(mbsz + len + 1, channels);
564 int FFAudioStream::decode_frame(AVPacket *pkt, AVFrame *frame, int &got_frame)
566 int first_frame = seeked; seeked = 0;
567 int ret = avcodec_decode_audio4(st->codec, frame, &got_frame, pkt);
569 if( first_frame ) return 0;
570 ff_err(ret, "FFAudioStream::decode_frame: Could not read audio frame\n");
574 int64_t pkt_ts = av_frame_get_best_effort_timestamp(frame);
575 if( pkt_ts != AV_NOPTS_VALUE )
576 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * sample_rate + 0.5;
581 int FFAudioStream::encode_activate()
583 if( writing >= 0 ) return writing;
584 AVCodecContext *ctx = st->codec;
585 frame_sz = ctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE ?
586 10000 : ctx->frame_size;
587 return FFStream::encode_activate();
590 int FFAudioStream::nb_samples()
592 AVCodecContext *ctx = st->codec;
593 return ctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE ?
594 10000 : ctx->frame_size;
597 int64_t FFAudioStream::load_buffer(double ** const sp, int len)
599 reserve(len+1, st->codec->channels);
600 for( int ch=0; ch<nch; ++ch )
601 write(sp[ch], len, ch);
605 int FFAudioStream::in_history(int64_t pos)
607 if( pos > curr_pos ) return 0;
609 if( len > sz ) len = sz;
610 if( pos < curr_pos - len ) return 0;
615 int FFAudioStream::init_frame(AVFrame *frame)
617 AVCodecContext *ctx = st->codec;
618 frame->nb_samples = frame_sz;
619 frame->format = ctx->sample_fmt;
620 frame->channel_layout = ctx->channel_layout;
621 frame->sample_rate = ctx->sample_rate;
622 int ret = av_frame_get_buffer(frame, 0);
624 ff_err(ret, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
628 int FFAudioStream::load(int64_t pos, int len)
630 if( audio_seek(pos) < 0 ) return -1;
631 if( !frame && !(frame=av_frame_alloc()) ) {
632 fprintf(stderr, "FFAudioStream::load: av_frame_alloc failed\n");
635 if( mbsz < len ) mbsz = len;
636 int64_t end_pos = pos + len;
638 for( int i=0; ret>=0 && !flushed && curr_pos<end_pos && i<MAX_RETRY; ++i ) {
639 ret = read_frame(frame);
641 load_history(&frame->extended_data[0], frame->nb_samples);
642 curr_pos += frame->nb_samples;
645 if( end_pos > curr_pos ) {
646 zero(end_pos - curr_pos);
649 len = curr_pos - pos;
654 int FFAudioStream::audio_seek(int64_t pos)
656 if( decode_activate() < 0 ) return -1;
657 if( !st->codec || !st->codec->codec ) return -1;
658 if( in_history(pos) ) return 0;
659 if( pos == curr_pos ) return 0;
660 reset_history(); mbsz = 0;
661 // guarentee preload > 1sec samples
662 if( seek(pos-sample_rate, sample_rate) < 0 ) return -1;
666 int FFAudioStream::encode(double **samples, int len)
668 if( encode_activate() <= 0 ) return -1;
671 int64_t count = load_buffer(samples, len);
674 while( ret >= 0 && count >= frame_sz ) {
675 frm = new FFrame(this);
676 if( (ret=frm->initted()) < 0 ) break;
677 AVFrame *frame = *frm;
678 float *bfrp = get_outp(frame_sz);
679 ret = swr_convert(resample_context,
680 (uint8_t **)frame->extended_data, frame_sz,
681 (const uint8_t **)&bfrp, frame_sz);
683 ff_err(ret, "FFAudioStream::encode: swr_convert failed\n");
686 frm->queue(curr_pos);
688 curr_pos += frame_sz;
693 return ret >= 0 ? 0 : 1;
696 int FFAudioStream::encode_frame(AVPacket *pkt, AVFrame *frame, int &got_packet)
698 int ret = avcodec_encode_audio2(st->codec, pkt, frame, &got_packet);
700 ff_err(ret, "FFAudioStream::encode_frame: encode audio failed\n");
706 void FFAudioStream::load_markers()
708 IndexState *index_state = ffmpeg->file_base->asset->index_state;
709 if( !index_state || idx >= index_state->audio_markers.size() ) return;
710 FFStream::load_markers(*index_state->audio_markers[idx], sample_rate);
713 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
714 : FFStream(ffmpeg, strm, fidx)
723 FFVideoStream::~FFVideoStream()
727 int FFVideoStream::decode_frame(AVPacket *pkt, AVFrame *frame, int &got_frame)
729 int first_frame = seeked; seeked = 0;
730 int ret = avcodec_decode_video2(st->codec, frame, &got_frame, pkt);
732 if( first_frame ) return 0;
733 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame\n");
737 int64_t pkt_ts = av_frame_get_best_effort_timestamp(frame);
738 if( pkt_ts != AV_NOPTS_VALUE )
739 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * frame_rate + 0.5;
744 int FFVideoStream::load(VFrame *vframe, int64_t pos)
746 int ret = video_seek(pos);
747 if( ret < 0 ) return -1;
748 if( !frame && !(frame=av_frame_alloc()) ) {
749 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
752 for( int i=0; ret>=0 && !flushed && curr_pos<=pos && i<MAX_RETRY; ++i ) {
753 ret = read_frame(frame);
754 if( ret > 0 ) ++curr_pos;
757 AVCodecContext *ctx = st->codec;
758 ret = convert_cmodel(vframe, (AVPicture *)frame,
759 ctx->pix_fmt, ctx->width, ctx->height);
761 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
765 int FFVideoStream::video_seek(int64_t pos)
767 if( decode_activate() < 0 ) return -1;
768 if( !st->codec || !st->codec->codec ) return -1;
769 if( pos == curr_pos-1 && !seeked ) return 0;
770 // if close enough, just read up to current
771 int gop = st->codec->gop_size;
772 if( gop < 4 ) gop = 4;
773 if( gop > 64 ) gop = 64;
774 int read_limit = curr_pos + 3*gop;
775 if( pos >= curr_pos && pos <= read_limit ) return 0;
776 // guarentee preload more than 2*gop frames
777 if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
781 int FFVideoStream::init_frame(AVFrame *picture)
783 AVCodecContext *ctx = st->codec;
784 picture->format = ctx->pix_fmt;
785 picture->width = ctx->width;
786 picture->height = ctx->height;
787 int ret = av_frame_get_buffer(picture, 32);
791 int FFVideoStream::encode(VFrame *vframe)
793 if( encode_activate() <= 0 ) return -1;
795 FFrame *picture = new FFrame(this);
796 int ret = picture->initted();
798 AVFrame *frame = *picture;
799 frame->pts = curr_pos;
800 AVCodecContext *ctx = st->codec;
801 ret = convert_pixfmt(vframe, (AVPicture*)frame,
802 ctx->pix_fmt, ctx->width, ctx->height);
805 picture->queue(curr_pos);
809 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
812 return ret >= 0 ? 0 : 1;
815 int FFVideoStream::encode_frame(AVPacket *pkt, AVFrame *frame, int &got_packet)
817 int ret = avcodec_encode_video2(st->codec, pkt, frame, &got_packet);
819 ff_err(ret, "FFVideoStream::encode_frame: encode video failed\n");
825 PixelFormat FFVideoConvert::color_model_to_pix_fmt(int color_model)
827 switch( color_model ) {
828 case BC_YUV422: return AV_PIX_FMT_YUYV422;
829 case BC_RGB888: return AV_PIX_FMT_RGB24;
830 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
831 case BC_BGR8888: return AV_PIX_FMT_BGR0;
832 case BC_BGR888: return AV_PIX_FMT_BGR24;
833 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
834 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
835 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
836 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
837 case BC_RGB565: return AV_PIX_FMT_RGB565;
838 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
839 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
843 return AV_PIX_FMT_NB;
846 int FFVideoConvert::pix_fmt_to_color_model(PixelFormat pix_fmt)
849 case AV_PIX_FMT_YUYV422: return BC_YUV422;
850 case AV_PIX_FMT_RGB24: return BC_RGB888;
851 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
852 case AV_PIX_FMT_BGR0: return BC_BGR8888;
853 case AV_PIX_FMT_BGR24: return BC_BGR888;
854 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
855 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
856 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
857 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
858 case AV_PIX_FMT_RGB565: return BC_RGB565;
859 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
860 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
864 return BC_TRANSPARENCY;
867 int FFVideoConvert::convert_picture_vframe(VFrame *frame,
868 AVPicture *ip, PixelFormat ifmt, int iw, int ih)
871 int cmodel = frame->get_color_model();
872 PixelFormat ofmt = color_model_to_pix_fmt(cmodel);
873 if( ofmt == AV_PIX_FMT_NB ) return -1;
874 int size = avpicture_fill(&opic, frame->get_data(), ofmt,
875 frame->get_w(), frame->get_h());
876 if( size < 0 ) return -1;
878 // transfer line sizes must match also
879 int planar = BC_CModels::is_planar(cmodel);
880 int packed_width = !planar ? frame->get_bytes_per_line() :
881 BC_CModels::calculate_pixelsize(cmodel) * frame->get_w();
882 if( packed_width != opic.linesize[0] ) return -1;
885 // override avpicture_fill() for planar types
886 opic.data[0] = frame->get_y();
887 opic.data[1] = frame->get_u();
888 opic.data[2] = frame->get_v();
891 convert_ctx = sws_getCachedContext(convert_ctx, iw, ih, ifmt,
892 frame->get_w(), frame->get_h(), ofmt, SWS_BICUBIC, NULL, NULL, NULL);
894 fprintf(stderr, "FFVideoConvert::convert_picture_frame:"
895 " sws_getCachedContext() failed\n");
898 int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ih,
899 opic.data, opic.linesize);
901 ff_err(ret, "FFVideoConvert::convert_picture_frame: sws_scale() failed\n");
907 int FFVideoConvert::convert_cmodel(VFrame *frame,
908 AVPicture *ip, PixelFormat ifmt, int iw, int ih)
910 // try direct transfer
911 if( !convert_picture_vframe(frame, ip, ifmt, iw, ih) ) return 1;
912 // use indirect transfer
913 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
915 for( int i = 0; i <desc->nb_components; ++i ) {
916 int bits = desc->comp[i].depth_minus1 + 1;
917 if( bits > max_bits ) max_bits = bits;
919 // from libavcodec/pixdesc.c
920 #define pixdesc_has_alpha(pixdesc) ((pixdesc)->nb_components == 2 || \
921 (pixdesc)->nb_components == 4 || (pixdesc)->flags & AV_PIX_FMT_FLAG_PAL)
922 int icolor_model = pixdesc_has_alpha(desc) ?
923 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
924 (max_bits > 8 ? BC_RGB161616 : BC_RGB888) ;
925 VFrame vframe(iw, ih, icolor_model);
926 if( convert_picture_vframe(&vframe, ip, ifmt, iw, ih) ) return -1;
927 frame->transfer_from(&vframe);
931 int FFVideoConvert::transfer_cmodel(VFrame *frame,
932 AVFrame *ifp, PixelFormat ifmt, int iw, int ih)
934 int ret = convert_cmodel(frame, (AVPicture *)ifp, ifmt, iw, ih);
936 const AVDictionary *src = av_frame_get_metadata(ifp);
937 AVDictionaryEntry *t = NULL;
938 BC_Hash *hp = frame->get_params();
940 while( (t=av_dict_get(src, "", t, AV_DICT_IGNORE_SUFFIX)) )
941 hp->update(t->key, t->value);
946 int FFVideoConvert::convert_vframe_picture(VFrame *frame,
947 AVPicture *op, PixelFormat ofmt, int ow, int oh)
950 int cmodel = frame->get_color_model();
951 PixelFormat ifmt = color_model_to_pix_fmt(cmodel);
952 if( ifmt == AV_PIX_FMT_NB ) return -1;
953 int size = avpicture_fill(&opic, frame->get_data(), ifmt,
954 frame->get_w(), frame->get_h());
955 if( size < 0 ) return -1;
957 // transfer line sizes must match also
958 int planar = BC_CModels::is_planar(cmodel);
959 int packed_width = !planar ? frame->get_bytes_per_line() :
960 BC_CModels::calculate_pixelsize(cmodel) * frame->get_w();
961 if( packed_width != opic.linesize[0] ) return -1;
964 // override avpicture_fill() for planar types
965 opic.data[0] = frame->get_y();
966 opic.data[1] = frame->get_u();
967 opic.data[2] = frame->get_v();
970 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(), ifmt,
971 ow, oh, ofmt, SWS_BICUBIC, NULL, NULL, NULL);
973 fprintf(stderr, "FFVideoConvert::convert_frame_picture:"
974 " sws_getCachedContext() failed\n");
977 int ret = sws_scale(convert_ctx, opic.data, opic.linesize, 0, frame->get_h(),
978 op->data, op->linesize);
980 ff_err(ret, "FFVideoConvert::convert_frame_picture: sws_scale() failed\n");
986 int FFVideoConvert::convert_pixfmt(VFrame *frame,
987 AVPicture *op, PixelFormat ofmt, int ow, int oh)
989 // try direct transfer
990 if( !convert_vframe_picture(frame, op, ofmt, ow, oh) ) return 1;
991 // use indirect transfer
992 int colormodel = frame->get_color_model();
993 int bits = BC_CModels::calculate_pixelsize(colormodel) * 8;
994 bits /= BC_CModels::components(colormodel);
995 int icolor_model = BC_CModels::has_alpha(colormodel) ?
996 (bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
997 (bits > 8 ? BC_RGB161616: BC_RGB888) ;
998 VFrame vframe(frame->get_w(), frame->get_h(), icolor_model);
999 vframe.transfer_from(frame);
1000 if( !convert_vframe_picture(&vframe, op, ofmt, ow, oh) ) return 1;
1004 int FFVideoConvert::transfer_pixfmt(VFrame *frame,
1005 AVFrame *ofp, PixelFormat ofmt, int ow, int oh)
1007 int ret = convert_pixfmt(frame, (AVPicture *)ofp, ofmt, ow, oh);
1009 BC_Hash *hp = frame->get_params();
1010 AVDictionary **dict = avpriv_frame_get_metadatap(ofp);
1011 //av_dict_free(dict);
1012 for( int i=0; i<hp->size(); ++i ) {
1013 char *key = hp->get_key(i), *val = hp->get_value(i);
1014 av_dict_set(dict, key, val, 0);
1020 void FFVideoStream::load_markers()
1022 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1023 if( idx >= index_state->video_markers.size() ) return;
1024 FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
1028 FFMPEG::FFMPEG(FileBase *file_base)
1031 this->file_base = file_base;
1032 memset(file_format,0,sizeof(file_format));
1033 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
1034 flow_lock = new Condition(1,"FFStream::flow_lock",0);
1037 decoding = encoding = 0;
1038 has_audio = has_video = 0;
1041 opt_video_filter = 0;
1042 opt_audio_filter = 0;
1043 char option_path[BCTEXTLEN];
1044 set_option_path(option_path, "%s", "ffmpeg.opts");
1045 read_options(option_path, opts);
1050 ff_lock("FFMPEG::~FFMPEG()");
1052 ffaudio.remove_all_objects();
1053 ffvideo.remove_all_objects();
1054 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1058 av_dict_free(&opts);
1059 delete [] opt_video_filter;
1060 delete [] opt_audio_filter;
1063 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1065 const int *p = codec->supported_samplerates;
1066 if( !p ) return sample_rate;
1068 if( *p == sample_rate ) return *p;
1074 static inline AVRational std_frame_rate(int i)
1076 static const int m1 = 1001*12, m2 = 1000*12;
1077 static const int freqs[] = {
1078 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1079 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
1081 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1082 return (AVRational) { freq, 1001*12 };
1085 AVRational FFMPEG::check_frame_rate(AVCodec *codec, double frame_rate)
1087 const AVRational *p = codec->supported_framerates;
1088 AVRational rate, best_rate = (AVRational) { 0, 0 };
1089 double max_err = 1.; int i = 0;
1090 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1091 double framerate = (double) rate.num / rate.den;
1092 double err = fabs(frame_rate/framerate - 1.);
1093 if( err >= max_err ) continue;
1097 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1100 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1103 double display_aspect = asset->width / (double)asset->height;
1104 double sample_aspect = asset->aspect_ratio / display_aspect;
1105 int width = 1000000, height = width * sample_aspect + 0.5;
1107 MWindow::create_aspect_ratio(w, h, width, height);
1108 return (AVRational){(int)h, (int)w};
1111 return (AVRational){1, 1};
1115 AVRational FFMPEG::to_time_base(int sample_rate)
1117 return (AVRational){1, sample_rate};
1120 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
1123 strcat(path, "/ffmpeg/");
1124 path += strlen(path);
1127 vsprintf(path, fmt, ap);
1131 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
1136 set_option_path(path, "%s/%s", type, spec);
1139 int FFMPEG::get_format(char *format, const char *path, char *spec)
1141 char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
1142 get_option_path(option_path, path, spec);
1143 FILE *fp = fopen(option_path,"r");
1146 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1148 line[sizeof(line)-1] = 0;
1149 ret = scan_option_line(line, format, codec);
1155 int FFMPEG::get_file_format()
1158 char audio_format[BCSTRLEN], video_format[BCSTRLEN];
1159 file_format[0] = audio_format[0] = video_format[0] = 0;
1160 Asset *asset = file_base->asset;
1161 if( !ret && asset->audio_data )
1162 ret = get_format(audio_format, "audio", asset->acodec);
1163 if( !ret && asset->video_data )
1164 ret = get_format(video_format, "video", asset->vcodec);
1165 if( !ret && !audio_format[0] && !video_format[0] )
1167 if( !ret && audio_format[0] && video_format[0] &&
1168 strcmp(audio_format, video_format) ) ret = -1;
1170 strcpy(file_format, audio_format[0] ? audio_format : video_format);
1174 int FFMPEG::scan_option_line(char *cp, char *tag, char *val)
1176 while( *cp == ' ' || *cp == '\t' ) ++cp;
1178 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' ) ++cp;
1180 if( !len || len > BCSTRLEN-1 ) return 1;
1181 while( bp < cp ) *tag++ = *bp++;
1183 while( *cp == ' ' || *cp == '\t' ) ++cp;
1184 if( *cp == '=' ) ++cp;
1185 while( *cp == ' ' || *cp == '\t' ) ++cp;
1187 while( *cp && *cp != '\n' ) ++cp;
1189 if( len > BCTEXTLEN-1 ) return 1;
1190 while( bp < cp ) *val++ = *bp++;
1195 int FFMPEG::get_encoder(const char *options,
1196 char *format, char *codec, char *bsfilter, char *bsargs)
1198 FILE *fp = fopen(options,"r");
1200 eprintf("FFMPEG::get_encoder: options open failed %s\n",options);
1203 if( get_encoder(fp, format, codec, bsfilter, bsargs) )
1204 eprintf(_("FFMPEG::get_encoder:"
1205 " err: format/codec not found %s\n"), options);
1210 int FFMPEG::get_encoder(FILE *fp,
1211 char *format, char *codec, char *bsfilter, char *bsargs)
1213 format[0] = codec[0] = bsfilter[0] = bsargs[0] = 0;
1214 char line[BCTEXTLEN];
1215 if( !fgets(line, sizeof(line), fp) ) return 1;
1216 line[sizeof(line)-1] = 0;
1217 if( scan_option_line(line, format, codec) ) return 1;
1219 while( *cp && *cp != '|' ) ++cp;
1220 if( !*cp ) return 0;
1221 if( scan_option_line(cp+1, bsfilter, bsargs) ) return 1;
1222 do { *cp-- = 0; } while( cp>=codec && (*cp==' ' || *cp == '\t' ) );
1226 int FFMPEG::read_options(const char *options, AVDictionary *&opts)
1228 FILE *fp = fopen(options,"r");
1230 int ret = read_options(fp, options, opts);
1235 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
1237 FILE *fp = fmemopen((void *)options,strlen(options),"r");
1239 int ret = read_options(fp, options, opts);
1241 AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
1242 if( tag ) st->id = strtol(tag->value,0,0);
1246 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
1248 int ret = 0, no = 0;
1249 char line[BCTEXTLEN];
1250 while( !ret && fgets(line, sizeof(line), fp) ) {
1251 line[sizeof(line)-1] = 0;
1253 if( line[0] == '#' ) continue;
1254 if( line[0] == '\n' ) continue;
1255 char key[BCSTRLEN], val[BCTEXTLEN];
1256 if( scan_option_line(line, key, val) ) {
1257 eprintf(_("FFMPEG::read_options:"
1258 " err reading %s: line %d\n"), options, no);
1262 if( !strcmp(key, "duration") )
1263 opt_duration = strtod(val, 0);
1264 else if( !strcmp(key, "video_filter") )
1265 opt_video_filter = cstrdup(val);
1266 else if( !strcmp(key, "audio_filter") )
1267 opt_audio_filter = cstrdup(val);
1268 else if( !strcmp(key, "loglevel") )
1271 av_dict_set(&opts, key, val, 0);
1277 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
1279 char option_path[BCTEXTLEN];
1280 set_option_path(option_path, "%s", options);
1281 return read_options(option_path, opts);
1284 int FFMPEG::load_options(const char *path, char *bfr, int len)
1287 FILE *fp = fopen(path, "r");
1289 fgets(bfr, len, fp); // skip hdr
1290 len = fread(bfr, 1, len-1, fp);
1291 if( len < 0 ) len = 0;
1297 void FFMPEG::set_loglevel(const char *ap)
1299 if( !ap || !*ap ) return;
1304 { "quiet" , AV_LOG_QUIET },
1305 { "panic" , AV_LOG_PANIC },
1306 { "fatal" , AV_LOG_FATAL },
1307 { "error" , AV_LOG_ERROR },
1308 { "warning", AV_LOG_WARNING },
1309 { "info" , AV_LOG_INFO },
1310 { "verbose", AV_LOG_VERBOSE },
1311 { "debug" , AV_LOG_DEBUG },
1313 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
1314 if( !strcmp(log_levels[i].name, ap) ) {
1315 av_log_set_level(log_levels[i].level);
1319 av_log_set_level(atoi(ap));
1322 double FFMPEG::to_secs(int64_t time, AVRational time_base)
1324 double base_time = time == AV_NOPTS_VALUE ? 0 :
1325 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
1326 return base_time / AV_TIME_BASE;
1329 int FFMPEG::info(char *text, int len)
1331 if( len <= 0 ) return 0;
1333 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
1335 if( ffvideo.size() > 0 )
1336 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
1337 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
1338 FFVideoStream *vid = ffvideo[vidx];
1339 AVStream *st = vid->st;
1340 AVCodecContext *avctx = st->codec;
1341 report(_("vid%d (%d), id 0x%06x:\n"), vid->idx, vid->fidx, avctx->codec_id);
1342 const AVCodecDescriptor *desc = avcodec_descriptor_get(avctx->codec_id);
1343 report(" video%d %s", vidx+1, desc ? desc->name : " (unkn)");
1344 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
1345 const char *pfn = av_get_pix_fmt_name(avctx->pix_fmt);
1346 report(" pix %s\n", pfn ? pfn : "(unkn)");
1347 double secs = to_secs(st->duration, st->time_base);
1348 int64_t length = secs * vid->frame_rate + 0.5;
1349 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
1350 int64_t nudge = ofs * vid->frame_rate;
1351 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1352 report(" %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
1353 int hrs = secs/3600; secs -= hrs*3600;
1354 int mins = secs/60; secs -= mins*60;
1355 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1357 if( ffaudio.size() > 0 )
1358 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
1359 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
1360 FFAudioStream *aud = ffaudio[aidx];
1361 AVStream *st = aud->st;
1362 AVCodecContext *avctx = st->codec;
1363 report(_("aud%d (%d), id 0x%06x:\n"), aud->idx, aud->fidx, avctx->codec_id);
1364 const AVCodecDescriptor *desc = avcodec_descriptor_get(avctx->codec_id);
1365 int nch = aud->channels, ch0 = aud->channel0+1;
1366 report(" audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
1367 const char *fmt = av_get_sample_fmt_name(avctx->sample_fmt);
1368 report(" %s %d", fmt, aud->sample_rate);
1369 int sample_bits = av_get_bits_per_sample(avctx->codec_id);
1370 report(" %dbits\n", sample_bits);
1371 double secs = to_secs(st->duration, st->time_base);
1372 int64_t length = secs * aud->sample_rate + 0.5;
1373 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
1374 int64_t nudge = ofs * aud->sample_rate;
1375 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1376 report(" %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
1377 int hrs = secs/3600; secs -= hrs*3600;
1378 int mins = secs/60; secs -= mins*60;
1379 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1381 if( fmt_ctx->nb_programs > 0 )
1382 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
1383 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
1384 report("program %d", i+1);
1385 AVProgram *pgrm = fmt_ctx->programs[i];
1386 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1387 int idx = pgrm->stream_index[j];
1388 int vidx = ffvideo.size();
1389 while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
1391 report(", vid%d", vidx);
1394 int aidx = ffaudio.size();
1395 while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
1397 report(", aud%d", aidx);
1400 report(", (%d)", pgrm->stream_index[j]);
1405 AVDictionaryEntry *tag = 0;
1406 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
1407 report("%s=%s\n", tag->key, tag->value);
1416 int FFMPEG::init_decoder(const char *filename)
1418 ff_lock("FFMPEG::init_decoder");
1420 char file_opts[BCTEXTLEN];
1421 char *bp = strrchr(strcpy(file_opts, filename), '/');
1422 char *sp = strrchr(!bp ? file_opts : bp, '.');
1425 strcpy(sp, ".opts");
1426 fp = fopen(file_opts, "r");
1429 read_options(fp, file_opts, opts);
1433 load_options("decode.opts", opts);
1434 AVDictionary *fopts = 0;
1435 av_dict_copy(&fopts, opts, 0);
1436 int ret = avformat_open_input(&fmt_ctx, filename, NULL, &fopts);
1437 av_dict_free(&fopts);
1439 ret = avformat_find_stream_info(fmt_ctx, NULL);
1444 return !ret ? 0 : 1;
1447 int FFMPEG::open_decoder()
1450 if( stat(fmt_ctx->filename, &st) < 0 ) {
1451 eprintf("FFMPEG::open_decoder: can't stat file: %s\n",
1456 int64_t file_bits = 8 * st.st_size;
1457 if( !fmt_ctx->bit_rate && opt_duration > 0 )
1458 fmt_ctx->bit_rate = file_bits / opt_duration;
1461 if( fmt_ctx->bit_rate > 0 ) {
1462 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1463 AVStream *st = fmt_ctx->streams[i];
1464 if( st->duration != AV_NOPTS_VALUE ) continue;
1465 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
1466 st->duration = av_rescale(file_bits, st->time_base.den,
1467 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
1472 printf("FFMPEG::open_decoder: some stream times estimated\n");
1474 ff_lock("FFMPEG::open_decoder");
1476 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1477 AVStream *st = fmt_ctx->streams[i];
1478 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
1479 AVCodecContext *avctx = st->codec;
1480 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avctx->codec_id);
1481 if( !codec_desc ) continue;
1482 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1483 if( avctx->width < 1 ) continue;
1484 if( avctx->height < 1 ) continue;
1485 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
1486 if( framerate.num < 1 ) continue;
1488 int vidx = ffvideo.size();
1489 FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
1490 vstrm_index.append(ffidx(vidx, 0));
1491 ffvideo.append(vid);
1492 vid->width = avctx->width;
1493 vid->height = avctx->height;
1494 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
1495 double secs = to_secs(st->duration, st->time_base);
1496 vid->length = secs * vid->frame_rate;
1497 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
1498 vid->nudge = st->start_time;
1500 if( opt_video_filter )
1501 vid->create_filter(opt_video_filter, avctx,avctx);
1503 else if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1504 if( avctx->channels < 1 ) continue;
1505 if( avctx->sample_rate < 1 ) continue;
1507 int aidx = ffaudio.size();
1508 FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
1509 ffaudio.append(aud);
1510 aud->channel0 = astrm_index.size();
1511 aud->channels = avctx->channels;
1512 for( int ch=0; ch<aud->channels; ++ch )
1513 astrm_index.append(ffidx(aidx, ch));
1514 aud->sample_rate = avctx->sample_rate;
1515 double secs = to_secs(st->duration, st->time_base);
1516 aud->length = secs * aud->sample_rate;
1517 if( avctx->sample_fmt != AV_SAMPLE_FMT_FLT ) {
1518 uint64_t layout = av_get_default_channel_layout(avctx->channels);
1519 if( !layout ) layout = ((uint64_t)1<<aud->channels) - 1;
1520 aud->resample_context = swr_alloc_set_opts(NULL,
1521 layout, AV_SAMPLE_FMT_FLT, avctx->sample_rate,
1522 layout, avctx->sample_fmt, avctx->sample_rate,
1524 swr_init(aud->resample_context);
1526 aud->nudge = st->start_time;
1528 if( opt_audio_filter )
1529 aud->create_filter(opt_audio_filter, avctx,avctx);
1533 printf("FFMPEG::open_decoder: some stream have bad times\n");
1539 int FFMPEG::init_encoder(const char *filename)
1541 int fd = ::open(filename,O_WRONLY);
1542 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
1544 eprintf("FFMPEG::init_encoder: bad file path: %s\n", filename);
1548 int ret = get_file_format();
1550 eprintf("FFMPEG::init_encoder: bad file format: %s\n", filename);
1554 eprintf("FFMPEG::init_encoder: mismatch audio/video file format: %s\n", filename);
1557 ff_lock("FFMPEG::init_encoder");
1559 avformat_alloc_output_context2(&fmt_ctx, 0, file_format, filename);
1561 eprintf("FFMPEG::init_encoder: failed: %s\n", filename);
1566 load_options("encode.opts", opts);
1573 int FFMPEG::open_encoder(const char *type, const char *spec)
1576 Asset *asset = file_base->asset;
1577 char *filename = asset->path;
1578 AVDictionary *sopts = 0;
1579 av_dict_copy(&sopts, opts, 0);
1580 char option_path[BCTEXTLEN];
1581 set_option_path(option_path, "%s/%s.opts", type, type);
1582 read_options(option_path, sopts);
1583 get_option_path(option_path, type, spec);
1584 char format_name[BCSTRLEN], codec_name[BCTEXTLEN];
1585 char bsfilter[BCSTRLEN], bsargs[BCTEXTLEN];
1586 if( get_encoder(option_path, format_name, codec_name, bsfilter, bsargs) ) {
1587 eprintf("FFMPEG::open_encoder: get_encoder failed %s:%s\n",
1588 option_path, filename);
1592 if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
1593 else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
1594 else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
1597 ff_lock("FFMPEG::open_encoder");
1601 const AVCodecDescriptor *codec_desc = 0;
1602 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
1604 eprintf("FFMPEG::open_encoder: cant find codec %s:%s\n",
1605 codec_name, filename);
1609 codec_desc = avcodec_descriptor_get(codec->id);
1611 eprintf("FFMPEG::open_encoder: unknown codec %s:%s\n",
1612 codec_name, filename);
1617 st = avformat_new_stream(fmt_ctx, 0);
1619 eprintf("FFMPEG::open_encoder: cant create stream %s:%s\n",
1620 codec_name, filename);
1625 AVCodecContext *ctx = st->codec;
1626 switch( codec_desc->type ) {
1627 case AVMEDIA_TYPE_AUDIO: {
1629 eprintf("FFMPEG::open_encoder: duplicate audio %s:%s\n",
1630 codec_name, filename);
1635 if( scan_options(asset->ff_audio_options, sopts, st) ) {
1636 eprintf("FFMPEG::open_encoder: bad audio options %s:%s\n",
1637 codec_name, filename);
1641 if( asset->ff_audio_bitrate > 0 ) {
1642 ctx->bit_rate = asset->ff_audio_bitrate;
1644 sprintf(arg, "%d", asset->ff_audio_bitrate);
1645 av_dict_set(&sopts, "b", arg, 0);
1647 int aidx = ffaudio.size();
1648 int fidx = aidx + ffvideo.size();
1649 FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
1650 ffaudio.append(aud); fst = aud;
1651 aud->sample_rate = asset->sample_rate;
1652 ctx->channels = aud->channels = asset->channels;
1653 for( int ch=0; ch<aud->channels; ++ch )
1654 astrm_index.append(ffidx(aidx, ch));
1655 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
1656 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
1657 if( !ctx->sample_rate ) {
1658 eprintf("FFMPEG::open_audio_encode:"
1659 " check_sample_rate failed %s\n", filename);
1663 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
1664 ctx->sample_fmt = codec->sample_fmts[0];
1665 uint64_t layout = av_get_default_channel_layout(ctx->channels);
1666 aud->resample_context = swr_alloc_set_opts(NULL,
1667 layout, ctx->sample_fmt, aud->sample_rate,
1668 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
1670 swr_init(aud->resample_context);
1673 case AVMEDIA_TYPE_VIDEO: {
1675 eprintf("FFMPEG::open_encoder: duplicate video %s:%s\n",
1676 codec_name, filename);
1681 if( scan_options(asset->ff_video_options, sopts, st) ) {
1682 eprintf("FFMPEG::open_encoder: bad video options %s:%s\n",
1683 codec_name, filename);
1687 if( asset->ff_video_bitrate > 0 ) {
1688 ctx->bit_rate = asset->ff_video_bitrate;
1690 sprintf(arg, "%d", asset->ff_video_bitrate);
1691 av_dict_set(&sopts, "b", arg, 0);
1693 else if( asset->ff_video_quality > 0 ) {
1694 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
1695 ctx->qmin = ctx->qmax = asset->ff_video_quality;
1696 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
1697 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
1698 ctx->flags |= CODEC_FLAG_QSCALE;
1700 av_dict_set(&sopts, "flags", "+qscale", 0);
1701 sprintf(arg, "%d", asset->ff_video_quality);
1702 av_dict_set(&sopts, "qscale", arg, 0);
1703 sprintf(arg, "%d", ctx->global_quality);
1704 av_dict_set(&sopts, "global_quality", arg, 0);
1706 int vidx = ffvideo.size();
1707 int fidx = vidx + ffaudio.size();
1708 FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
1709 vstrm_index.append(ffidx(vidx, 0));
1710 ffvideo.append(vid); fst = vid;
1711 vid->width = asset->width;
1712 ctx->width = (vid->width+3) & ~3;
1713 vid->height = asset->height;
1714 ctx->height = (vid->height+3) & ~3;
1715 vid->frame_rate = asset->frame_rate;
1716 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
1717 ctx->pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
1718 AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
1719 if( !frame_rate.num || !frame_rate.den ) {
1720 eprintf("FFMPEG::open_audio_encode:"
1721 " check_frame_rate failed %s\n", filename);
1725 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
1726 st->time_base = ctx->time_base;
1730 eprintf("FFMPEG::open_encoder: not audio/video, %s:%s\n",
1731 codec_name, filename);
1736 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
1737 st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
1739 ret = avcodec_open2(st->codec, codec, &sopts);
1741 ff_err(ret,"FFMPEG::open_encoder");
1742 eprintf("FFMPEG::open_encoder: open failed %s:%s\n",
1743 codec_name, filename);
1750 if( fst && bsfilter[0] )
1751 fst->add_bsfilter(bsfilter, !bsargs[0] ? 0 : bsargs);
1755 av_dict_free(&sopts);
1759 int FFMPEG::close_encoder()
1762 if( encoding > 0 ) {
1763 av_write_trailer(fmt_ctx);
1764 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
1765 avio_closep(&fmt_ctx->pb);
1771 int FFMPEG::decode_activate()
1773 if( decoding < 0 ) {
1775 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
1776 ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
1777 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
1778 ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
1779 // set nudges for each program stream set
1780 int npgrms = fmt_ctx->nb_programs;
1781 for( int i=0; i<npgrms; ++i ) {
1782 AVProgram *pgrm = fmt_ctx->programs[i];
1783 // first start time video stream
1784 int64_t vstart_time = -1, astart_time = -1;
1785 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1786 int fidx = pgrm->stream_index[j];
1787 AVStream *st = fmt_ctx->streams[fidx];
1788 AVCodecContext *avctx = st->codec;
1789 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1790 if( st->start_time == AV_NOPTS_VALUE ) continue;
1791 if( vstart_time > st->start_time ) continue;
1792 vstart_time = st->start_time;
1795 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1796 if( st->start_time == AV_NOPTS_VALUE ) continue;
1797 if( astart_time > st->start_time ) continue;
1798 astart_time = st->start_time;
1802 // match program streams to max start_time
1803 int64_t nudge = vstart_time > astart_time ? vstart_time : astart_time;
1804 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1805 int fidx = pgrm->stream_index[j];
1806 AVStream *st = fmt_ctx->streams[fidx];
1807 AVCodecContext *avctx = st->codec;
1808 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1809 for( int k=0; k<ffvideo.size(); ++k ) {
1810 if( ffvideo[k]->fidx != fidx ) continue;
1811 ffvideo[k]->nudge = nudge;
1815 if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1816 for( int k=0; k<ffaudio.size(); ++k ) {
1817 if( ffaudio[k]->fidx != fidx ) continue;
1818 ffaudio[k]->nudge = nudge;
1824 // set nudges for any streams not yet set
1825 int64_t vstart_time = 0, astart_time = 0;
1826 int nstreams = fmt_ctx->nb_streams;
1827 for( int i=0; i<nstreams; ++i ) {
1828 AVStream *st = fmt_ctx->streams[i];
1829 AVCodecContext *avctx = st->codec;
1830 switch( avctx->codec_type ) {
1831 case AVMEDIA_TYPE_VIDEO: {
1832 if( st->start_time == AV_NOPTS_VALUE ) continue;
1833 int vidx = ffvideo.size();
1834 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
1835 if( vidx >= 0 && ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
1836 if( vstart_time >= st->start_time ) continue;
1837 vstart_time = st->start_time;
1839 case AVMEDIA_TYPE_AUDIO: {
1840 if( st->start_time == AV_NOPTS_VALUE ) continue;
1841 int aidx = ffaudio.size();
1842 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
1843 if( aidx >= 0 && ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
1844 if( astart_time >= st->start_time ) continue;
1845 astart_time = st->start_time;
1850 int64_t nudge = vstart_time > astart_time ? vstart_time : astart_time;
1851 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
1852 if( ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
1853 ffvideo[vidx]->nudge = nudge;
1855 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
1856 if( ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
1857 ffaudio[aidx]->nudge = nudge;
1864 int FFMPEG::encode_activate()
1867 if( encoding < 0 ) {
1869 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
1870 (ret=avio_open(&fmt_ctx->pb, fmt_ctx->filename, AVIO_FLAG_WRITE)) < 0 ) {
1871 ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
1876 AVDictionary *fopts = 0;
1877 char option_path[BCTEXTLEN];
1878 set_option_path(option_path, "format/%s", file_format);
1879 read_options(option_path, fopts);
1880 ret = avformat_write_header(fmt_ctx, &fopts);
1881 av_dict_free(&fopts);
1883 ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
1893 int FFMPEG::audio_seek(int stream, int64_t pos)
1895 int aidx = astrm_index[stream].st_idx;
1896 FFAudioStream *aud = ffaudio[aidx];
1897 aud->audio_seek(pos);
1901 int FFMPEG::video_seek(int stream, int64_t pos)
1903 int vidx = vstrm_index[stream].st_idx;
1904 FFVideoStream *vid = ffvideo[vidx];
1905 vid->video_seek(pos);
1910 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
1912 if( !has_audio || chn >= astrm_index.size() ) return -1;
1913 int aidx = astrm_index[chn].st_idx;
1914 FFAudioStream *aud = ffaudio[aidx];
1915 if( aud->load(pos, len) < len ) return -1;
1916 int ch = astrm_index[chn].st_ch;
1917 int ret = aud->read(samples,len,ch);
1921 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
1923 if( !has_video || layer >= vstrm_index.size() ) return -1;
1924 int vidx = vstrm_index[layer].st_idx;
1925 FFVideoStream *vid = ffvideo[vidx];
1926 return vid->load(vframe, pos);
1930 int FFMPEG::encode(int stream, double **samples, int len)
1932 FFAudioStream *aud = ffaudio[stream];
1933 return aud->encode(samples, len);
1937 int FFMPEG::encode(int stream, VFrame *frame)
1939 FFVideoStream *vid = ffvideo[stream];
1940 return vid->encode(frame);
1943 void FFMPEG::start_muxer()
1951 void FFMPEG::stop_muxer()
1960 void FFMPEG::flow_off()
1963 flow_lock->lock("FFMPEG::flow_off");
1967 void FFMPEG::flow_on()
1971 flow_lock->unlock();
1974 void FFMPEG::flow_ctl()
1977 flow_lock->lock("FFMPEG::flow_ctl");
1978 flow_lock->unlock();
1982 int FFMPEG::mux_audio(FFrame *frm)
1985 FFStream *fst = frm->fst;
1986 AVCodecContext *ctx = fst->st->codec;
1987 AVFrame *frame = *frm;
1988 AVRational tick_rate = {1, ctx->sample_rate};
1989 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
1991 int ret = fst->encode_frame(pkt, frame, got_packet);
1992 if( ret >= 0 && got_packet )
1993 ret = fst->write_packet(pkt);
1995 ff_err(ret, "FFMPEG::mux_audio");
1996 return ret >= 0 ? 0 : 1;
1999 int FFMPEG::mux_video(FFrame *frm)
2002 FFStream *fst = frm->fst;
2003 AVFrame *frame = *frm;
2004 frame->pts = frm->position;
2005 int ret = 1, got_packet = 0;
2006 if( fmt_ctx->oformat->flags & AVFMT_RAWPICTURE ) {
2007 /* a hack to avoid data copy with some raw video muxers */
2008 pkt->flags |= AV_PKT_FLAG_KEY;
2009 pkt->stream_index = fst->st->index;
2010 AVPicture *picture = (AVPicture *)frame;
2011 pkt->data = (uint8_t *)picture;
2012 pkt->size = sizeof(AVPicture);
2013 pkt->pts = pkt->dts = frame->pts;
2017 ret = fst->encode_frame(pkt, frame, got_packet);
2018 if( ret >= 0 && got_packet )
2019 ret = fst->write_packet(pkt);
2021 ff_err(ret, "FFMPEG::mux_video");
2022 return ret >= 0 ? 0 : 1;
2028 double atm = -1, vtm = -1;
2029 FFrame *afrm = 0, *vfrm = 0;
2031 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
2032 FFStream *fst = ffaudio[i];
2033 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
2034 FFrame *frm = fst->frms.first;
2035 if( !frm ) { if( !done ) return; continue; }
2036 double tm = to_secs(frm->position, fst->st->codec->time_base);
2037 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
2039 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
2040 FFStream *fst = ffvideo[i];
2041 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
2042 FFrame *frm = fst->frms.first;
2043 if( !frm ) { if( !done ) return; continue; }
2044 double tm = to_secs(frm->position, fst->st->codec->time_base);
2045 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
2047 if( !demand ) flow_off();
2048 if( !afrm && !vfrm ) break;
2049 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
2050 vfrm->position, vfrm->fst->st->codec->time_base,
2051 afrm->position, afrm->fst->st->codec->time_base);
2052 FFrame *frm = v <= 0 ? vfrm : afrm;
2053 if( frm == afrm ) mux_audio(frm);
2054 if( frm == vfrm ) mux_video(frm);
2063 mux_lock->lock("FFMPEG::run");
2067 for( int i=0; i<ffaudio.size(); ++i )
2068 ffaudio[i]->flush();
2069 for( int i=0; i<ffvideo.size(); ++i )
2070 ffvideo[i]->flush();
2074 int FFMPEG::ff_total_audio_channels()
2076 return astrm_index.size();
2079 int FFMPEG::ff_total_astreams()
2081 return ffaudio.size();
2084 int FFMPEG::ff_audio_channels(int stream)
2086 return ffaudio[stream]->channels;
2089 int FFMPEG::ff_sample_rate(int stream)
2091 return ffaudio[stream]->sample_rate;
2094 const char* FFMPEG::ff_audio_format(int stream)
2096 AVStream *st = ffaudio[stream]->st;
2097 AVCodecID id = st->codec->codec_id;
2098 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2099 return desc ? desc->name : "Unknown";
2102 int FFMPEG::ff_audio_pid(int stream)
2104 return ffaudio[stream]->st->id;
2107 int64_t FFMPEG::ff_audio_samples(int stream)
2109 return ffaudio[stream]->length;
2112 // find audio astream/channels with this program,
2113 // or all program audio channels (astream=-1)
2114 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
2118 int vidx = ffvideo[vstream]->fidx;
2119 // find first program with this video stream
2120 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
2121 AVProgram *pgrm = fmt_ctx->programs[i];
2122 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
2123 int st_idx = pgrm->stream_index[j];
2124 AVStream *st = fmt_ctx->streams[st_idx];
2125 if( st->codec->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
2126 if( st_idx == vidx ) pidx = i;
2129 if( pidx < 0 ) return -1;
2131 int64_t channels = 0;
2132 AVProgram *pgrm = fmt_ctx->programs[pidx];
2133 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2134 int aidx = pgrm->stream_index[j];
2135 AVStream *st = fmt_ctx->streams[aidx];
2136 if( st->codec->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
2137 if( astream > 0 ) { --astream; continue; }
2139 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
2140 if( ffaudio[i]->fidx == aidx ) astrm = i;
2142 if( ret < 0 ) ret = astrm;
2143 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
2144 channels |= mask << ffaudio[astrm]->channel0;
2146 if( !astream ) break;
2148 channel_mask = channels;
2153 int FFMPEG::ff_total_video_layers()
2155 return vstrm_index.size();
2158 int FFMPEG::ff_total_vstreams()
2160 return ffvideo.size();
2163 int FFMPEG::ff_video_width(int stream)
2165 return ffvideo[stream]->width;
2168 int FFMPEG::ff_video_height(int stream)
2170 return ffvideo[stream]->height;
2173 int FFMPEG::ff_set_video_width(int stream, int width)
2175 int w = ffvideo[stream]->width;
2176 ffvideo[stream]->width = width;
2180 int FFMPEG::ff_set_video_height(int stream, int height)
2182 int h = ffvideo[stream]->height;
2183 ffvideo[stream]->height = height;
2187 int FFMPEG::ff_coded_width(int stream)
2189 AVStream *st = ffvideo[stream]->st;
2190 return st->codec->coded_width;
2193 int FFMPEG::ff_coded_height(int stream)
2195 AVStream *st = ffvideo[stream]->st;
2196 return st->codec->coded_height;
2199 float FFMPEG::ff_aspect_ratio(int stream)
2201 return ffvideo[stream]->aspect_ratio;
2204 const char* FFMPEG::ff_video_format(int stream)
2206 AVStream *st = ffvideo[stream]->st;
2207 AVCodecID id = st->codec->codec_id;
2208 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2209 return desc ? desc->name : "Unknown";
2212 double FFMPEG::ff_frame_rate(int stream)
2214 return ffvideo[stream]->frame_rate;
2217 int64_t FFMPEG::ff_video_frames(int stream)
2219 return ffvideo[stream]->length;
2222 int FFMPEG::ff_video_pid(int stream)
2224 return ffvideo[stream]->st->id;
2228 int FFMPEG::ff_cpus()
2230 return file_base->file->cpus;
2233 int FFVideoStream::create_filter(const char *filter_spec,
2234 AVCodecContext *src_ctx, AVCodecContext *sink_ctx)
2236 avfilter_register_all();
2237 AVFilter *filter = avfilter_get_by_name(filter_spec);
2238 if( !filter || filter->inputs->type != AVMEDIA_TYPE_VIDEO ) {
2239 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
2242 filter_graph = avfilter_graph_alloc();
2243 AVFilter *buffersrc = avfilter_get_by_name("buffer");
2244 AVFilter *buffersink = avfilter_get_by_name("buffersink");
2246 int ret = 0; char args[BCTEXTLEN];
2247 snprintf(args, sizeof(args),
2248 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
2249 src_ctx->width, src_ctx->height, src_ctx->pix_fmt,
2250 src_ctx->time_base.num, src_ctx->time_base.den,
2251 src_ctx->sample_aspect_ratio.num, src_ctx->sample_aspect_ratio.den);
2253 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2254 args, NULL, filter_graph);
2256 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2257 NULL, NULL, filter_graph);
2259 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
2260 (uint8_t*)&sink_ctx->pix_fmt, sizeof(sink_ctx->pix_fmt),
2261 AV_OPT_SEARCH_CHILDREN);
2263 ff_err(ret, "FFVideoStream::create_filter");
2265 ret = FFStream::create_filter(filter_spec);
2266 return ret >= 0 ? 0 : 1;
2269 int FFAudioStream::create_filter(const char *filter_spec,
2270 AVCodecContext *src_ctx, AVCodecContext *sink_ctx)
2272 avfilter_register_all();
2273 AVFilter *filter = avfilter_get_by_name(filter_spec);
2274 if( !filter || filter->inputs->type != AVMEDIA_TYPE_AUDIO ) {
2275 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
2278 filter_graph = avfilter_graph_alloc();
2279 AVFilter *buffersrc = avfilter_get_by_name("abuffer");
2280 AVFilter *buffersink = avfilter_get_by_name("abuffersink");
2281 int ret = 0; char args[BCTEXTLEN];
2282 snprintf(args, sizeof(args),
2283 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
2284 src_ctx->time_base.num, src_ctx->time_base.den, src_ctx->sample_rate,
2285 av_get_sample_fmt_name(src_ctx->sample_fmt), src_ctx->channel_layout);
2287 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2288 args, NULL, filter_graph);
2290 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2291 NULL, NULL, filter_graph);
2293 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
2294 (uint8_t*)&sink_ctx->sample_fmt, sizeof(sink_ctx->sample_fmt),
2295 AV_OPT_SEARCH_CHILDREN);
2297 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
2298 (uint8_t*)&sink_ctx->channel_layout,
2299 sizeof(sink_ctx->channel_layout), AV_OPT_SEARCH_CHILDREN);
2301 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
2302 (uint8_t*)&sink_ctx->sample_rate, sizeof(sink_ctx->sample_rate),
2303 AV_OPT_SEARCH_CHILDREN);
2305 ff_err(ret, "FFAudioStream::create_filter");
2307 ret = FFStream::create_filter(filter_spec);
2308 return ret >= 0 ? 0 : 1;
2311 int FFStream::create_filter(const char *filter_spec)
2313 /* Endpoints for the filter graph. */
2314 AVFilterInOut *outputs = avfilter_inout_alloc();
2315 outputs->name = av_strdup("in");
2316 outputs->filter_ctx = buffersrc_ctx;
2317 outputs->pad_idx = 0;
2320 AVFilterInOut *inputs = avfilter_inout_alloc();
2321 inputs->name = av_strdup("out");
2322 inputs->filter_ctx = buffersink_ctx;
2323 inputs->pad_idx = 0;
2326 int ret = !outputs->name || !inputs->name ? -1 : 0;
2328 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
2329 &inputs, &outputs, NULL);
2331 ret = avfilter_graph_config(filter_graph, NULL);
2334 ff_err(ret, "FFStream::create_filter");
2335 avfilter_inout_free(&inputs);
2336 avfilter_inout_free(&outputs);
2340 void FFStream::add_bsfilter(const char *bsf, const char *ap)
2342 bsfilter.append(new BSFilter(bsf,ap));
2345 int FFStream::bs_filter(AVPacket *pkt)
2347 if( !bsfilter.size() ) return 0;
2348 av_packet_split_side_data(pkt);
2351 for( int i=0; i<bsfilter.size(); ++i ) {
2352 AVPacket bspkt = *pkt;
2353 ret = av_bitstream_filter_filter(bsfilter[i]->bsfc,
2354 st->codec, bsfilter[i]->args, &bspkt.data, &bspkt.size,
2355 pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY);
2356 if( ret < 0 ) break;
2357 int size = bspkt.size;
2358 uint8_t *data = bspkt.data;
2359 if( !ret && bspkt.data != pkt->data ) {
2361 data = (uint8_t *)av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
2362 if( !data ) { ret = AVERROR(ENOMEM); break; }
2363 memcpy(data, bspkt.data, size);
2364 memset(data+size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2368 pkt->side_data = 0; pkt->side_data_elems = 0;
2369 av_free_packet(pkt);
2370 ret = av_packet_from_data(&bspkt, data, size);
2371 if( ret < 0 ) break;
2376 ff_err(ret,"FFStream::bs_filter");
2380 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
2383 av_init_packet(&pkt);
2384 AVFrame *frame = av_frame_alloc();
2386 fprintf(stderr, "FFMPEG::scan: av_frame_alloc failed\n");
2390 index_state->add_video_markers(ffvideo.size());
2391 index_state->add_audio_markers(ffaudio.size());
2393 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2394 AVDictionary *copts = 0;
2395 av_dict_copy(&copts, opts, 0);
2396 AVStream *st = fmt_ctx->streams[i];
2397 AVCodecID codec_id = st->codec->codec_id;
2398 AVCodec *decoder = avcodec_find_decoder(codec_id);
2399 if( avcodec_open2(st->codec, decoder, &copts) < 0 )
2400 fprintf(stderr, "FFMPEG::scan: codec open failed\n");
2401 av_dict_free(&copts);
2404 for( int64_t count=0; !*canceled; ++count ) {
2405 av_packet_unref(&pkt);
2406 pkt.data = 0; pkt.size = 0;
2408 int ret = av_read_frame(fmt_ctx, &pkt);
2410 if( ret == AVERROR_EOF ) break;
2411 if( ++errs > 100 ) {
2412 ff_err(ret, "over 100 read_frame errs\n");
2417 if( !pkt.data ) continue;
2418 int i = pkt.stream_index;
2419 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
2420 AVStream *st = fmt_ctx->streams[i];
2421 AVCodecContext *avctx = st->codec;
2422 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
2424 switch( avctx->codec_type ) {
2425 case AVMEDIA_TYPE_VIDEO: {
2426 int vidx = ffvideo.size();
2427 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
2428 if( vidx < 0 ) break;
2429 FFVideoStream *vid = ffvideo[vidx];
2430 int64_t tstmp = pkt.dts;
2431 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.pts;
2432 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
2433 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
2434 double secs = to_secs(tstmp, st->time_base);
2435 int64_t frm = secs * vid->frame_rate + 0.5;
2436 if( frm < 0 ) frm = 0;
2437 index_state->put_video_mark(vidx, frm, pkt.pos);
2440 while( pkt.size > 0 ) {
2441 av_frame_unref(frame);
2443 int ret = vid->decode_frame(&pkt, frame, got_frame);
2444 if( ret <= 0 ) break;
2445 // if( got_frame ) {}
2451 case AVMEDIA_TYPE_AUDIO: {
2452 int aidx = ffaudio.size();
2453 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
2454 if( aidx < 0 ) break;
2455 FFAudioStream *aud = ffaudio[aidx];
2456 int64_t tstmp = pkt.pts;
2457 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
2458 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
2459 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
2460 double secs = to_secs(tstmp, st->time_base);
2461 int64_t sample = secs * aud->sample_rate + 0.5;
2462 if( sample < 0 ) sample = 0;
2463 index_state->put_audio_mark(aidx, sample, pkt.pos);
2465 while( pkt.size > 0 ) {
2466 int ch = aud->channel0, nch = aud->channels;
2467 int64_t pos = index_state->pos(ch);
2468 if( pos != aud->curr_pos ) {
2469 if( abs(pos-aud->curr_pos) > 1 )
2470 printf("audio%d pad %ld %ld (%ld)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
2471 index_state->pad_data(ch, nch, aud->curr_pos);
2473 av_frame_unref(frame);
2475 int ret = aud->decode_frame(&pkt, frame, got_frame);
2476 if( ret <= 0 ) break;
2479 int len = aud->get_samples(samples,
2480 &frame->extended_data[0], frame->nb_samples);
2481 for( int i=0; i<nch; ++i )
2482 index_state->put_data(ch+i,nch,samples+i,len);
2483 aud->curr_pos += len;
2492 av_frame_free(&frame);
2496 void FFStream::load_markers(IndexMarks &marks, double rate)
2498 index_markers = &marks;
2500 int64_t sz = marks.size();
2501 int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
2502 int nb_ent = st->nb_index_entries;
2503 // some formats already have an index
2505 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
2506 int64_t tstmp = ep->timestamp;
2507 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
2508 double secs = ffmpeg->to_secs(tstmp, st->time_base);
2509 int64_t no = secs * rate;
2510 while( in < sz && marks[in].no <= no ) ++in;
2512 int64_t len = sz - in;
2513 int64_t count = max_entries - nb_ent;
2514 if( count > len ) count = len;
2515 for( int i=0; i<count; ++i ) {
2516 int k = in + i * len / count;
2517 int64_t no = marks[k].no, pos = marks[k].pos;
2518 double secs = (double)no / rate;
2519 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
2520 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
2521 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);