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);
53 pkt.data = 0; pkt.size = 0;
55 void FFPacket::finit()
57 av_packet_unref(&pkt);
60 FFrame::FFrame(FFStream *fst)
63 frm = av_frame_alloc();
64 init = fst->init_frame(frm);
72 void FFrame::queue(int64_t pos)
78 void FFrame::dequeue()
83 int FFAudioStream::read(float *fp, long len)
91 while( --k >= 0 ) *fp++ = *op++;
92 if( op >= lmt ) op = bfr;
97 void FFAudioStream::realloc(long nsz, int nch, long len)
100 float *np = new float[bsz];
101 inp = np + read(np, len) * nch;
106 delete [] bfr; bfr = np;
109 void FFAudioStream::realloc(long nsz, int nch)
111 if( nsz > sz || this->nch != nch ) {
112 long len = this->nch != nch ? 0 : hpos;
113 if( len > sz ) len = sz;
115 realloc(nsz, nch, len);
119 void FFAudioStream::reserve(long nsz, int nch)
121 long len = (inp - outp) / nch;
123 if( nsz > sz || this->nch != nch ) {
124 if( this->nch != nch ) len = 0;
125 realloc(nsz, nch, len);
128 if( (len*=nch) > 0 && bfr != outp )
129 memmove(bfr, outp, len*sizeof(*bfr));
134 long FFAudioStream::used()
136 long len = inp>=outp ? inp-outp : inp-bfr + lmt-outp;
139 long FFAudioStream::avail()
142 if( in1 >= lmt ) in1 = bfr;
143 long len = outp >= in1 ? outp-in1 : outp-bfr + lmt-in1;
146 void FFAudioStream::reset_history()
152 void FFAudioStream::iseek(int64_t ofs)
154 outp = inp - ofs*nch;
155 if( outp < bfr ) outp += sz*nch;
158 float *FFAudioStream::get_outp(int ofs)
165 int64_t FFAudioStream::put_inp(int ofs)
168 return (inp-outp) / nch;
171 int FFAudioStream::write(const float *fp, long len)
179 while( --k >= 0 ) *ip++ = *fp++;
180 if( ip >= lmt ) ip = bfr;
187 int FFAudioStream::zero(long len)
195 while( --k >= 0 ) *ip++ = 0;
196 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 fidx)
231 this->ffmpeg = ffmpeg;
234 frm_lock = new Mutex("FFStream::frm_lock");
240 nudge = AV_NOPTS_VALUE;
241 seek_pos = curr_pos = 0;
243 reading = writing = 0;
249 FFStream::~FFStream()
251 if( reading > 0 || writing > 0 ) avcodec_close(st->codec);
252 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
253 while( frms.first ) frms.remove(frms.first);
254 if( filter_graph ) avfilter_graph_free(&filter_graph);
255 if( frame ) av_frame_free(&frame);
256 if( fframe ) av_frame_free(&fframe);
257 bsfilter.remove_all_objects();
261 void FFStream::ff_lock(const char *cp)
263 FFMPEG::fflock.lock(cp);
266 void FFStream::ff_unlock()
268 FFMPEG::fflock.unlock();
271 void FFStream::queue(FFrame *frm)
273 frm_lock->lock("FFStream::queue");
277 ffmpeg->mux_lock->unlock();
280 void FFStream::dequeue(FFrame *frm)
282 frm_lock->lock("FFStream::dequeue");
284 frms.remove_pointer(frm);
288 int FFStream::encode_activate()
291 writing = ffmpeg->encode_activate();
295 int FFStream::decode_activate()
297 if( reading < 0 && (reading=ffmpeg->decode_activate()) > 0 ) {
298 ff_lock("FFStream::decode_activate");
300 AVDictionary *copts = 0;
301 av_dict_copy(&copts, ffmpeg->opts, 0);
303 // this should be avformat_copy_context(), but no copy avail
304 ret = avformat_open_input(&fmt_ctx, ffmpeg->fmt_ctx->filename, NULL, &copts);
306 ret = avformat_find_stream_info(fmt_ctx, 0);
307 st = fmt_ctx->streams[fidx];
311 AVCodecID codec_id = st->codec->codec_id;
312 AVCodec *decoder = avcodec_find_decoder(codec_id);
313 ret = avcodec_open2(st->codec, decoder, &copts);
317 eprintf(_("open decoder failed\n"));
320 eprintf(_("can't clone input file\n"));
321 av_dict_free(&copts);
327 int FFStream::read_packet()
329 av_packet_unref(ipkt);
330 int ret = av_read_frame(fmt_ctx, ipkt);
333 if( ret == AVERROR_EOF ) {
334 ipkt->stream_index = st->index;
337 ff_err(ret, "FFStream::read_packet: av_read_frame failed\n");
344 int FFStream::decode(AVFrame *frame)
347 int retries = MAX_RETRY;
350 while( ret >= 0 && !flushed && --retries >= 0 && !got_frame ) {
353 if( (ret=read_packet()) < 0 ) break;
355 if( ipkt->stream_index == st->index ) {
356 while( (ipkt->size > 0 || !ipkt->data) && !got_frame ) {
357 ret = decode_frame(ipkt, frame, got_frame);
358 if( ret < 0 ) need_packet = 1;
359 if( ret <= 0 || !ipkt->data ) break;
372 fprintf(stderr, "FFStream::decode: Retry limit\n");
376 fprintf(stderr, "FFStream::decode: failed\n");
381 int FFStream::load_filter(AVFrame *frame)
383 int ret = av_buffersrc_add_frame_flags(buffersrc_ctx,
384 frame, AV_BUFFERSRC_FLAG_KEEP_REF);
386 av_frame_unref(frame);
387 eprintf(_("av_buffersrc_add_frame_flags failed\n"));
392 int FFStream::read_filter(AVFrame *frame)
394 int ret = av_buffersink_get_frame(buffersink_ctx, frame);
396 if( ret == AVERROR(EAGAIN) ) return 0;
397 if( ret == AVERROR_EOF ) { st_eof(1); return -1; }
398 ff_err(ret, "FFStream::read_filter: av_buffersink_get_frame failed\n");
404 int FFStream::read_frame(AVFrame *frame)
406 if( !filter_graph || !buffersrc_ctx || !buffersink_ctx )
407 return decode(frame);
408 if( !fframe && !(fframe=av_frame_alloc()) ) {
409 fprintf(stderr, "FFStream::read_frame: av_frame_alloc failed\n");
413 while( !flushed && !(ret=read_filter(frame)) ) {
414 if( (ret=decode(fframe)) < 0 ) break;
415 if( ret > 0 && (ret=load_filter(fframe)) < 0 ) break;
420 int FFStream::write_packet(FFPacket &pkt)
423 av_packet_rescale_ts(pkt, st->codec->time_base, st->time_base);
424 pkt->stream_index = st->index;
425 return av_interleaved_write_frame(ffmpeg->fmt_ctx, pkt);
428 int FFStream::flush()
434 ret = encode_frame(pkt, 0, got_packet);
435 if( ret < 0 || !got_packet ) break;
436 ret = write_packet(pkt);
439 ff_err(ret, "FFStream::flush");
440 return ret >= 0 ? 0 : 1;
443 int FFStream::seek(int64_t no, double rate)
445 int64_t tstmp = -INT64_MAX+1;
446 // default ffmpeg native seek
448 int64_t pos = no, plmt = -1;
449 IndexMarks *index_markers = get_markers();
450 if( index_markers && index_markers->size() > 1 ) {
451 IndexMarks &marks = *index_markers;
452 int i = marks.find(pos);
453 int64_t n = i < 0 ? (i=0) : marks[i].no;
454 // if indexed seek point not too far away (<30 secs), use index
455 if( no-n < 30*rate ) {
458 if( i < marks.size() ) plmt = marks[i].pos;
463 double secs = pos / rate;
464 tstmp = secs * st->time_base.den / st->time_base.num;
465 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
467 int ret = avformat_seek_file(fmt_ctx, st->index,
468 -INT64_MAX, tstmp, INT64_MAX, AVSEEK_FLAG_ANY);
470 avcodec_flush_buffers(st->codec);
471 ipkt.finit(); ipkt.init();
472 need_packet = 0; flushed = 0;
473 seeked = 1; st_eof(0);
474 // read up to retry packets, limited to npkts in stream, and not past pkt.pos plmt
476 if( read_packet() <= 0 ) { ret = -1; break; }
477 if( plmt >= 0 && ipkt->pos >= plmt ) break;
478 if( ipkt->stream_index != st->index ) continue;
479 if( --npkts <= 0 ) break;
480 int64_t pkt_ts = ipkt->dts != AV_NOPTS_VALUE ? ipkt->dts : ipkt->pts;
481 if( pkt_ts == AV_NOPTS_VALUE ) continue;
482 if( pkt_ts >= tstmp ) break;
486 //printf("** seek fail %ld, %ld\n", pos, tstmp);
487 seeked = need_packet = 0;
491 //printf("seeked pos = %ld, %ld\n", pos, tstmp);
492 seek_pos = curr_pos = pos;
496 FFAudioStream::FFAudioStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
497 : FFStream(ffmpeg, strm, fidx)
500 channel0 = channels = 0;
504 resample_context = 0;
513 bfr = new float[bsz];
518 FFAudioStream::~FFAudioStream()
520 if( resample_context ) swr_free(&resample_context);
525 int FFAudioStream::get_samples(float *&samples, uint8_t **data, int len)
527 samples = *(float **)data;
528 if( resample_context ) {
529 if( len > aud_bfr_sz ) {
535 aud_bfr = new float[aud_bfr_sz*channels];
537 int ret = swr_convert(resample_context,
538 (uint8_t**)&aud_bfr, aud_bfr_sz, (const uint8_t**)data, len);
540 ff_err(ret, "FFAudioStream::get_samples: swr_convert failed\n");
549 int FFAudioStream::load_history(uint8_t **data, int len)
552 len = get_samples(samples, data, len);
554 // biggest user bfr since seek + frame
555 realloc(mbsz + len + 1, channels);
561 int FFAudioStream::decode_frame(AVPacket *pkt, AVFrame *frame, int &got_frame)
563 int first_frame = seeked; seeked = 0;
564 int ret = avcodec_decode_audio4(st->codec, frame, &got_frame, pkt);
566 if( first_frame ) return 0;
567 ff_err(ret, "FFAudioStream::decode_frame: Could not read audio frame\n");
571 int64_t pkt_ts = av_frame_get_best_effort_timestamp(frame);
572 if( pkt_ts != AV_NOPTS_VALUE )
573 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * sample_rate + 0.5;
578 int FFAudioStream::encode_activate()
580 if( writing >= 0 ) return writing;
581 AVCodecContext *ctx = st->codec;
582 frame_sz = ctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE ?
583 10000 : ctx->frame_size;
584 return FFStream::encode_activate();
587 int FFAudioStream::nb_samples()
589 AVCodecContext *ctx = st->codec;
590 return ctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE ?
591 10000 : ctx->frame_size;
594 int64_t FFAudioStream::load_buffer(double ** const sp, int len)
596 reserve(len+1, st->codec->channels);
597 for( int ch=0; ch<nch; ++ch )
598 write(sp[ch], len, ch);
602 int FFAudioStream::in_history(int64_t pos)
604 if( pos > curr_pos ) return 0;
606 if( len > sz ) len = sz;
607 if( pos < curr_pos - len ) return 0;
612 int FFAudioStream::init_frame(AVFrame *frame)
614 AVCodecContext *ctx = st->codec;
615 frame->nb_samples = frame_sz;
616 frame->format = ctx->sample_fmt;
617 frame->channel_layout = ctx->channel_layout;
618 frame->sample_rate = ctx->sample_rate;
619 int ret = av_frame_get_buffer(frame, 0);
621 ff_err(ret, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
625 int FFAudioStream::load(int64_t pos, int len)
627 if( audio_seek(pos) < 0 ) return -1;
628 if( !frame && !(frame=av_frame_alloc()) ) {
629 fprintf(stderr, "FFAudioStream::load: av_frame_alloc failed\n");
632 if( mbsz < len ) mbsz = len;
633 int64_t end_pos = pos + len;
635 for( int i=0; ret>=0 && !flushed && curr_pos<end_pos && i<MAX_RETRY; ++i ) {
636 ret = read_frame(frame);
638 load_history(&frame->extended_data[0], frame->nb_samples);
639 curr_pos += frame->nb_samples;
642 if( end_pos > curr_pos ) {
643 zero(end_pos - curr_pos);
646 len = curr_pos - pos;
651 int FFAudioStream::audio_seek(int64_t pos)
653 if( decode_activate() < 0 ) return -1;
654 if( !st->codec || !st->codec->codec ) return -1;
655 if( in_history(pos) ) return 0;
656 if( pos == curr_pos ) return 0;
657 reset_history(); mbsz = 0;
658 // guarentee preload > 1sec samples
659 if( seek(pos-sample_rate, sample_rate) < 0 ) return -1;
663 int FFAudioStream::encode(double **samples, int len)
665 if( encode_activate() <= 0 ) return -1;
668 int64_t count = load_buffer(samples, len);
671 while( ret >= 0 && count >= frame_sz ) {
672 frm = new FFrame(this);
673 if( (ret=frm->initted()) < 0 ) break;
674 AVFrame *frame = *frm;
675 float *bfrp = get_outp(frame_sz);
676 ret = swr_convert(resample_context,
677 (uint8_t **)frame->extended_data, frame_sz,
678 (const uint8_t **)&bfrp, frame_sz);
680 ff_err(ret, "FFAudioStream::encode: swr_convert failed\n");
683 frm->queue(curr_pos);
685 curr_pos += frame_sz;
690 return ret >= 0 ? 0 : 1;
693 int FFAudioStream::encode_frame(AVPacket *pkt, AVFrame *frame, int &got_packet)
695 int ret = avcodec_encode_audio2(st->codec, pkt, frame, &got_packet);
697 ff_err(ret, "FFAudioStream::encode_frame: encode audio failed\n");
703 void FFAudioStream::load_markers()
705 IndexState *index_state = ffmpeg->file_base->asset->index_state;
706 if( !index_state || idx >= index_state->audio_markers.size() ) return;
707 if( index_state->marker_status == MARKERS_NOTTESTED ) return;
708 FFStream::load_markers(*index_state->audio_markers[idx], sample_rate);
711 IndexMarks *FFAudioStream::get_markers()
713 IndexState *index_state = ffmpeg->file_base->asset->index_state;
714 if( !index_state || idx >= index_state->audio_markers.size() ) return 0;
715 return index_state->audio_markers[idx];
718 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
719 : FFStream(ffmpeg, strm, fidx)
728 FFVideoStream::~FFVideoStream()
732 int FFVideoStream::decode_frame(AVPacket *pkt, AVFrame *frame, int &got_frame)
734 int first_frame = seeked; seeked = 0;
735 int ret = avcodec_decode_video2(st->codec, frame, &got_frame, pkt);
737 if( first_frame ) return 0;
738 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame\n");
741 else // this is right out of ffplay, looks questionable ???
745 int64_t pkt_ts = av_frame_get_best_effort_timestamp(frame);
746 if( pkt_ts != AV_NOPTS_VALUE )
747 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * frame_rate + 0.5;
752 int FFVideoStream::load(VFrame *vframe, int64_t pos)
754 int ret = video_seek(pos);
755 if( ret < 0 ) return -1;
756 if( !frame && !(frame=av_frame_alloc()) ) {
757 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
760 for( int i=0; ret>=0 && !flushed && curr_pos<=pos && i<MAX_RETRY; ++i ) {
761 ret = read_frame(frame);
762 if( ret > 0 ) ++curr_pos;
765 AVCodecContext *ctx = st->codec;
766 ret = convert_cmodel(vframe, frame,
767 ctx->pix_fmt, ctx->width, ctx->height);
769 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
773 int FFVideoStream::video_seek(int64_t pos)
775 if( decode_activate() < 0 ) return -1;
776 if( !st->codec || !st->codec->codec ) return -1;
777 if( pos == curr_pos-1 && !seeked ) return 0;
778 // if close enough, just read up to current
779 int gop = st->codec->gop_size;
780 if( gop < 4 ) gop = 4;
781 if( gop > 64 ) gop = 64;
782 int read_limit = curr_pos + 3*gop;
783 if( pos >= curr_pos && pos <= read_limit ) return 0;
784 // guarentee preload more than 2*gop frames
785 if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
789 int FFVideoStream::init_frame(AVFrame *picture)
791 AVCodecContext *ctx = st->codec;
792 picture->format = ctx->pix_fmt;
793 picture->width = ctx->width;
794 picture->height = ctx->height;
795 int ret = av_frame_get_buffer(picture, 32);
799 int FFVideoStream::encode(VFrame *vframe)
801 if( encode_activate() <= 0 ) return -1;
803 FFrame *picture = new FFrame(this);
804 int ret = picture->initted();
806 AVFrame *frame = *picture;
807 frame->pts = curr_pos;
808 AVCodecContext *ctx = st->codec;
809 ret = convert_pixfmt(vframe, frame,
810 ctx->pix_fmt, ctx->width, ctx->height);
813 picture->queue(curr_pos);
817 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
820 return ret >= 0 ? 0 : 1;
823 int FFVideoStream::encode_frame(AVPacket *pkt, AVFrame *frame, int &got_packet)
825 int ret = avcodec_encode_video2(st->codec, pkt, frame, &got_packet);
827 ff_err(ret, "FFVideoStream::encode_frame: encode video failed\n");
833 AVPixelFormat FFVideoConvert::color_model_to_pix_fmt(int color_model)
835 switch( color_model ) {
836 case BC_YUV422: return AV_PIX_FMT_YUYV422;
837 case BC_RGB888: return AV_PIX_FMT_RGB24;
838 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
839 case BC_BGR8888: return AV_PIX_FMT_BGR0;
840 case BC_BGR888: return AV_PIX_FMT_BGR24;
841 case BC_ARGB8888: return AV_PIX_FMT_ARGB;
842 case BC_ABGR8888: return AV_PIX_FMT_ABGR;
843 case BC_RGB8: return AV_PIX_FMT_RGB8;
844 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
845 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
846 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
847 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
848 case BC_RGB565: return AV_PIX_FMT_RGB565;
849 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
850 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
854 return AV_PIX_FMT_NB;
857 int FFVideoConvert::pix_fmt_to_color_model(AVPixelFormat pix_fmt)
860 case AV_PIX_FMT_YUYV422: return BC_YUV422;
861 case AV_PIX_FMT_RGB24: return BC_RGB888;
862 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
863 case AV_PIX_FMT_BGR0: return BC_BGR8888;
864 case AV_PIX_FMT_BGR24: return BC_BGR888;
865 case AV_PIX_FMT_ARGB: return BC_ARGB8888;
866 case AV_PIX_FMT_ABGR: return BC_ABGR8888;
867 case AV_PIX_FMT_RGB8: return BC_RGB8;
868 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
869 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
870 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
871 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
872 case AV_PIX_FMT_RGB565: return BC_RGB565;
873 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
874 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
881 int FFVideoConvert::convert_picture_vframe(VFrame *frame,
882 AVFrame *ip, AVPixelFormat ifmt, int iw, int ih)
884 // try bc_xfer methods
885 int imodel = pix_fmt_to_color_model(ifmt);
887 long y_ofs = 0, u_ofs = 0, v_ofs = 0;
888 uint8_t *data = ip->data[0];
889 if( BC_CModels::is_yuv(imodel) ) {
890 u_ofs = ip->data[1] - data;
891 v_ofs = ip->data[2] - data;
893 VFrame iframe(data, -1, y_ofs, u_ofs, v_ofs, iw, ih, imodel, ip->linesize[0]);
894 frame->transfer_from(&iframe);
899 int cmodel = frame->get_color_model();
900 AVPixelFormat ofmt = color_model_to_pix_fmt(cmodel);
901 if( ofmt == AV_PIX_FMT_NB ) return -1;
902 int size = av_image_fill_arrays(opic.data, opic.linesize,
903 frame->get_data(), ofmt, frame->get_w(), frame->get_h(), 1);
904 if( size < 0 ) return -1;
906 // transfer line sizes must match also
907 int planar = BC_CModels::is_planar(cmodel);
908 int packed_width = !planar ? frame->get_bytes_per_line() :
909 BC_CModels::calculate_pixelsize(cmodel) * frame->get_w();
910 if( packed_width != opic.linesize[0] ) return -1;
913 // override av_image_fill_arrays() for planar types
914 opic.data[0] = frame->get_y();
915 opic.data[1] = frame->get_u();
916 opic.data[2] = frame->get_v();
919 convert_ctx = sws_getCachedContext(convert_ctx, iw, ih, ifmt,
920 frame->get_w(), frame->get_h(), ofmt, SWS_BICUBIC, NULL, NULL, NULL);
922 fprintf(stderr, "FFVideoConvert::convert_picture_frame:"
923 " sws_getCachedContext() failed\n");
926 int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ih,
927 opic.data, opic.linesize);
929 ff_err(ret, "FFVideoConvert::convert_picture_frame: sws_scale() failed\n");
935 int FFVideoConvert::convert_cmodel(VFrame *frame,
936 AVFrame *ip, AVPixelFormat ifmt, int iw, int ih)
938 // try direct transfer
939 if( !convert_picture_vframe(frame, ip, ifmt, iw, ih) ) return 1;
940 // use indirect transfer
941 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
943 for( int i = 0; i <desc->nb_components; ++i ) {
944 int bits = desc->comp[i].depth;
945 if( bits > max_bits ) max_bits = bits;
947 // from libavcodec/pixdesc.c
948 #define pixdesc_has_alpha(pixdesc) ((pixdesc)->nb_components == 2 || \
949 (pixdesc)->nb_components == 4 || (pixdesc)->flags & AV_PIX_FMT_FLAG_PAL)
950 int icolor_model = pixdesc_has_alpha(desc) ?
951 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
952 (max_bits > 8 ? BC_RGB161616 : BC_RGB888) ;
953 VFrame vframe(iw, ih, icolor_model);
954 if( convert_picture_vframe(&vframe, ip, ifmt, iw, ih) ) return -1;
955 frame->transfer_from(&vframe);
959 int FFVideoConvert::transfer_cmodel(VFrame *frame,
960 AVFrame *ifp, AVPixelFormat ifmt, int iw, int ih)
962 int ret = convert_cmodel(frame, ifp, ifmt, iw, ih);
964 const AVDictionary *src = av_frame_get_metadata(ifp);
965 AVDictionaryEntry *t = NULL;
966 BC_Hash *hp = frame->get_params();
968 while( (t=av_dict_get(src, "", t, AV_DICT_IGNORE_SUFFIX)) )
969 hp->update(t->key, t->value);
974 int FFVideoConvert::convert_vframe_picture(VFrame *frame,
975 AVFrame *op, AVPixelFormat ofmt, int ow, int oh)
978 int cmodel = frame->get_color_model();
979 AVPixelFormat ifmt = color_model_to_pix_fmt(cmodel);
980 if( ifmt == AV_PIX_FMT_NB ) return -1;
981 int size = av_image_fill_arrays(opic.data, opic.linesize,
982 frame->get_data(), ifmt, frame->get_w(), frame->get_h(), 1);
983 if( size < 0 ) return -1;
985 // transfer line sizes must match also
986 int planar = BC_CModels::is_planar(cmodel);
987 int packed_width = !planar ? frame->get_bytes_per_line() :
988 BC_CModels::calculate_pixelsize(cmodel) * frame->get_w();
989 if( packed_width != opic.linesize[0] ) return -1;
992 // override av_image_fill_arrays() for planar types
993 opic.data[0] = frame->get_y();
994 opic.data[1] = frame->get_u();
995 opic.data[2] = frame->get_v();
998 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(), ifmt,
999 ow, oh, ofmt, SWS_BICUBIC, NULL, NULL, NULL);
1000 if( !convert_ctx ) {
1001 fprintf(stderr, "FFVideoConvert::convert_frame_picture:"
1002 " sws_getCachedContext() failed\n");
1005 int ret = sws_scale(convert_ctx, opic.data, opic.linesize, 0, frame->get_h(),
1006 op->data, op->linesize);
1008 ff_err(ret, "FFVideoConvert::convert_frame_picture: sws_scale() failed\n");
1014 int FFVideoConvert::convert_pixfmt(VFrame *frame,
1015 AVFrame *op, AVPixelFormat ofmt, int ow, int oh)
1017 // try direct transfer
1018 if( !convert_vframe_picture(frame, op, ofmt, ow, oh) ) return 1;
1019 // use indirect transfer
1020 int colormodel = frame->get_color_model();
1021 int bits = BC_CModels::calculate_pixelsize(colormodel) * 8;
1022 bits /= BC_CModels::components(colormodel);
1023 int icolor_model = BC_CModels::has_alpha(colormodel) ?
1024 (bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1025 (bits > 8 ? BC_RGB161616: BC_RGB888) ;
1026 VFrame vframe(frame->get_w(), frame->get_h(), icolor_model);
1027 vframe.transfer_from(frame);
1028 if( !convert_vframe_picture(&vframe, op, ofmt, ow, oh) ) return 1;
1032 int FFVideoConvert::transfer_pixfmt(VFrame *frame,
1033 AVFrame *ofp, AVPixelFormat ofmt, int ow, int oh)
1035 int ret = convert_pixfmt(frame, ofp, ofmt, ow, oh);
1037 BC_Hash *hp = frame->get_params();
1038 AVDictionary **dict = avpriv_frame_get_metadatap(ofp);
1039 //av_dict_free(dict);
1040 for( int i=0; i<hp->size(); ++i ) {
1041 char *key = hp->get_key(i), *val = hp->get_value(i);
1042 av_dict_set(dict, key, val, 0);
1048 void FFVideoStream::load_markers()
1050 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1051 if( !index_state || idx >= index_state->video_markers.size() ) return;
1052 FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
1055 IndexMarks *FFVideoStream::get_markers()
1057 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1058 if( !index_state || idx >= index_state->video_markers.size() ) return 0;
1059 return !index_state ? 0 : index_state->video_markers[idx];
1063 FFMPEG::FFMPEG(FileBase *file_base)
1066 this->file_base = file_base;
1067 memset(file_format,0,sizeof(file_format));
1068 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
1069 flow_lock = new Condition(1,"FFStream::flow_lock",0);
1072 decoding = encoding = 0;
1073 has_audio = has_video = 0;
1076 opt_video_filter = 0;
1077 opt_audio_filter = 0;
1078 char option_path[BCTEXTLEN];
1079 set_option_path(option_path, "%s", "ffmpeg.opts");
1080 read_options(option_path, opts);
1085 ff_lock("FFMPEG::~FFMPEG()");
1087 ffaudio.remove_all_objects();
1088 ffvideo.remove_all_objects();
1089 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1093 av_dict_free(&opts);
1094 delete [] opt_video_filter;
1095 delete [] opt_audio_filter;
1098 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1100 const int *p = codec->supported_samplerates;
1101 if( !p ) return sample_rate;
1103 if( *p == sample_rate ) return *p;
1109 static inline AVRational std_frame_rate(int i)
1111 static const int m1 = 1001*12, m2 = 1000*12;
1112 static const int freqs[] = {
1113 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1114 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
1116 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1117 return (AVRational) { freq, 1001*12 };
1120 AVRational FFMPEG::check_frame_rate(AVCodec *codec, double frame_rate)
1122 const AVRational *p = codec->supported_framerates;
1123 AVRational rate, best_rate = (AVRational) { 0, 0 };
1124 double max_err = 1.; int i = 0;
1125 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1126 double framerate = (double) rate.num / rate.den;
1127 double err = fabs(frame_rate/framerate - 1.);
1128 if( err >= max_err ) continue;
1132 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1135 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1138 double display_aspect = asset->width / (double)asset->height;
1139 double sample_aspect = asset->aspect_ratio / display_aspect;
1140 int width = 1000000, height = width * sample_aspect + 0.5;
1142 MWindow::create_aspect_ratio(w, h, width, height);
1143 return (AVRational){(int)h, (int)w};
1146 return (AVRational){1, 1};
1150 AVRational FFMPEG::to_time_base(int sample_rate)
1152 return (AVRational){1, sample_rate};
1155 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
1157 char *ep = path + BCTEXTLEN-1;
1158 strncpy(path, File::get_cindat_path(), ep-path);
1159 strncat(path, "/ffmpeg/", ep-path);
1160 path += strlen(path);
1163 path += vsnprintf(path, ep-path, fmt, ap);
1168 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
1173 set_option_path(path, "%s/%s", type, spec);
1176 int FFMPEG::get_format(char *format, const char *path, const char *spec)
1178 char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
1179 get_option_path(option_path, path, spec);
1180 FILE *fp = fopen(option_path,"r");
1183 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1185 line[sizeof(line)-1] = 0;
1186 ret = scan_option_line(line, format, codec);
1192 int FFMPEG::get_codec(char *codec, const char *path, const char *spec)
1194 char option_path[BCTEXTLEN], line[BCTEXTLEN], format[BCTEXTLEN];
1195 get_option_path(option_path, path, spec);
1196 FILE *fp = fopen(option_path,"r");
1199 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1202 line[sizeof(line)-1] = 0;
1203 ret = scan_option_line(line, format, codec);
1206 char *vp = codec, *ep = vp+BCTEXTLEN-1;
1207 while( vp < ep && *vp && *vp != '|' ) ++vp;
1208 if( *vp == '|' ) --vp;
1209 while( vp > codec && (*vp==' ' || *vp=='\t') ) *vp-- = 0;
1214 int FFMPEG::get_file_format()
1217 char audio_format[BCSTRLEN], video_format[BCSTRLEN];
1218 file_format[0] = audio_format[0] = video_format[0] = 0;
1219 Asset *asset = file_base->asset;
1220 if( !ret && asset->audio_data )
1221 ret = get_format(audio_format, "audio", asset->acodec);
1222 if( !ret && asset->video_data )
1223 ret = get_format(video_format, "video", asset->vcodec);
1224 if( !ret && !audio_format[0] && !video_format[0] )
1226 if( !ret && audio_format[0] && video_format[0] &&
1227 strcmp(audio_format, video_format) ) ret = -1;
1229 strcpy(file_format, audio_format[0] ? audio_format : video_format);
1233 int FFMPEG::scan_option_line(char *cp, char *tag, char *val)
1235 while( *cp == ' ' || *cp == '\t' ) ++cp;
1237 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' ) ++cp;
1239 if( !len || len > BCSTRLEN-1 ) return 1;
1240 while( bp < cp ) *tag++ = *bp++;
1242 while( *cp == ' ' || *cp == '\t' ) ++cp;
1243 if( *cp == '=' ) ++cp;
1244 while( *cp == ' ' || *cp == '\t' ) ++cp;
1246 while( *cp && *cp != '\n' ) ++cp;
1248 if( len > BCTEXTLEN-1 ) return 1;
1249 while( bp < cp ) *val++ = *bp++;
1254 int FFMPEG::load_defaults(const char *path, const char *type,
1255 char *codec, char *codec_options, int len)
1257 char default_file[BCTEXTLEN];
1258 FFMPEG::set_option_path(default_file, "%s/%s.dfl", path, type);
1259 FILE *fp = fopen(default_file,"r");
1261 fgets(codec, BCSTRLEN, fp);
1263 while( *cp && *cp!='\n' ) ++cp;
1265 while( len > 0 && fgets(codec_options, len, fp) ) {
1266 int n = strlen(codec_options);
1267 codec_options += n; len -= n;
1270 FFMPEG::set_option_path(default_file, "%s/%s", path, codec);
1271 return FFMPEG::load_options(default_file, codec_options, len);
1274 void FFMPEG::set_asset_format(Asset *asset, const char *text)
1276 if( asset->format != FILE_FFMPEG ) return;
1277 strcpy(asset->fformat, text);
1278 if( !asset->ff_audio_options[0] ) {
1279 asset->audio_data = !load_defaults("audio", text, asset->acodec,
1280 asset->ff_audio_options, sizeof(asset->ff_audio_options));
1282 if( !asset->ff_video_options[0] ) {
1283 asset->video_data = !load_defaults("video", text, asset->vcodec,
1284 asset->ff_video_options, sizeof(asset->ff_video_options));
1288 int FFMPEG::get_encoder(const char *options,
1289 char *format, char *codec, char *bsfilter, char *bsargs)
1291 FILE *fp = fopen(options,"r");
1293 eprintf(_("options open failed %s\n"),options);
1296 if( get_encoder(fp, format, codec, bsfilter, bsargs) )
1297 eprintf(_("format/codec not found %s\n"), options);
1302 int FFMPEG::get_encoder(FILE *fp,
1303 char *format, char *codec, char *bsfilter, char *bsargs)
1305 format[0] = codec[0] = bsfilter[0] = bsargs[0] = 0;
1306 char line[BCTEXTLEN];
1307 if( !fgets(line, sizeof(line), fp) ) return 1;
1308 line[sizeof(line)-1] = 0;
1309 if( scan_option_line(line, format, codec) ) return 1;
1311 while( *cp && *cp != '|' ) ++cp;
1312 if( !*cp ) return 0;
1313 if( scan_option_line(cp+1, bsfilter, bsargs) ) return 1;
1314 do { *cp-- = 0; } while( cp>=codec && (*cp==' ' || *cp == '\t' ) );
1318 int FFMPEG::read_options(const char *options, AVDictionary *&opts)
1320 FILE *fp = fopen(options,"r");
1322 int ret = read_options(fp, options, opts);
1327 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
1329 FILE *fp = fmemopen((void *)options,strlen(options),"r");
1331 int ret = read_options(fp, options, opts);
1333 AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
1334 if( tag ) st->id = strtol(tag->value,0,0);
1338 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
1340 int ret = 0, no = 0;
1341 char line[BCTEXTLEN];
1342 while( !ret && fgets(line, sizeof(line), fp) ) {
1343 line[sizeof(line)-1] = 0;
1345 if( line[0] == '#' ) continue;
1346 if( line[0] == '\n' ) continue;
1347 char key[BCSTRLEN], val[BCTEXTLEN];
1348 if( scan_option_line(line, key, val) ) {
1349 eprintf(_("err reading %s: line %d\n"), options, no);
1353 if( !strcmp(key, "duration") )
1354 opt_duration = strtod(val, 0);
1355 else if( !strcmp(key, "video_filter") )
1356 opt_video_filter = cstrdup(val);
1357 else if( !strcmp(key, "audio_filter") )
1358 opt_audio_filter = cstrdup(val);
1359 else if( !strcmp(key, "loglevel") )
1362 av_dict_set(&opts, key, val, 0);
1368 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
1370 char option_path[BCTEXTLEN];
1371 set_option_path(option_path, "%s", options);
1372 return read_options(option_path, opts);
1375 int FFMPEG::load_options(const char *path, char *bfr, int len)
1378 FILE *fp = fopen(path, "r");
1380 fgets(bfr, len, fp); // skip hdr
1381 len = fread(bfr, 1, len-1, fp);
1382 if( len < 0 ) len = 0;
1388 void FFMPEG::set_loglevel(const char *ap)
1390 if( !ap || !*ap ) return;
1395 { "quiet" , AV_LOG_QUIET },
1396 { "panic" , AV_LOG_PANIC },
1397 { "fatal" , AV_LOG_FATAL },
1398 { "error" , AV_LOG_ERROR },
1399 { "warning", AV_LOG_WARNING },
1400 { "info" , AV_LOG_INFO },
1401 { "verbose", AV_LOG_VERBOSE },
1402 { "debug" , AV_LOG_DEBUG },
1404 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
1405 if( !strcmp(log_levels[i].name, ap) ) {
1406 av_log_set_level(log_levels[i].level);
1410 av_log_set_level(atoi(ap));
1413 double FFMPEG::to_secs(int64_t time, AVRational time_base)
1415 double base_time = time == AV_NOPTS_VALUE ? 0 :
1416 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
1417 return base_time / AV_TIME_BASE;
1420 int FFMPEG::info(char *text, int len)
1422 if( len <= 0 ) return 0;
1424 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
1426 if( ffvideo.size() > 0 )
1427 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
1428 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
1429 FFVideoStream *vid = ffvideo[vidx];
1430 AVStream *st = vid->st;
1431 AVCodecContext *avctx = st->codec;
1432 report(_("vid%d (%d), id 0x%06x:\n"), vid->idx, vid->fidx, avctx->codec_id);
1433 const AVCodecDescriptor *desc = avcodec_descriptor_get(avctx->codec_id);
1434 report(" video%d %s", vidx+1, desc ? desc->name : " (unkn)");
1435 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
1436 const char *pfn = av_get_pix_fmt_name(avctx->pix_fmt);
1437 report(" pix %s\n", pfn ? pfn : "(unkn)");
1438 double secs = to_secs(st->duration, st->time_base);
1439 int64_t length = secs * vid->frame_rate + 0.5;
1440 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
1441 int64_t nudge = ofs * vid->frame_rate;
1442 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1443 report(" %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
1444 int hrs = secs/3600; secs -= hrs*3600;
1445 int mins = secs/60; secs -= mins*60;
1446 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1448 if( ffaudio.size() > 0 )
1449 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
1450 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
1451 FFAudioStream *aud = ffaudio[aidx];
1452 AVStream *st = aud->st;
1453 AVCodecContext *avctx = st->codec;
1454 report(_("aud%d (%d), id 0x%06x:\n"), aud->idx, aud->fidx, avctx->codec_id);
1455 const AVCodecDescriptor *desc = avcodec_descriptor_get(avctx->codec_id);
1456 int nch = aud->channels, ch0 = aud->channel0+1;
1457 report(" audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
1458 const char *fmt = av_get_sample_fmt_name(avctx->sample_fmt);
1459 report(" %s %d", fmt, aud->sample_rate);
1460 int sample_bits = av_get_bits_per_sample(avctx->codec_id);
1461 report(" %dbits\n", sample_bits);
1462 double secs = to_secs(st->duration, st->time_base);
1463 int64_t length = secs * aud->sample_rate + 0.5;
1464 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
1465 int64_t nudge = ofs * aud->sample_rate;
1466 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1467 report(" %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
1468 int hrs = secs/3600; secs -= hrs*3600;
1469 int mins = secs/60; secs -= mins*60;
1470 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1472 if( fmt_ctx->nb_programs > 0 )
1473 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
1474 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
1475 report("program %d", i+1);
1476 AVProgram *pgrm = fmt_ctx->programs[i];
1477 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1478 int idx = pgrm->stream_index[j];
1479 int vidx = ffvideo.size();
1480 while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
1482 report(", vid%d", vidx);
1485 int aidx = ffaudio.size();
1486 while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
1488 report(", aud%d", aidx);
1491 report(", (%d)", pgrm->stream_index[j]);
1496 AVDictionaryEntry *tag = 0;
1497 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
1498 report("%s=%s\n", tag->key, tag->value);
1507 int FFMPEG::init_decoder(const char *filename)
1509 ff_lock("FFMPEG::init_decoder");
1511 char file_opts[BCTEXTLEN];
1512 char *bp = strrchr(strcpy(file_opts, filename), '/');
1513 char *sp = strrchr(!bp ? file_opts : bp, '.');
1516 strcpy(sp, ".opts");
1517 fp = fopen(file_opts, "r");
1520 read_options(fp, file_opts, opts);
1524 load_options("decode.opts", opts);
1525 AVDictionary *fopts = 0;
1526 av_dict_copy(&fopts, opts, 0);
1527 int ret = avformat_open_input(&fmt_ctx, filename, NULL, &fopts);
1528 av_dict_free(&fopts);
1530 ret = avformat_find_stream_info(fmt_ctx, NULL);
1535 return !ret ? 0 : 1;
1538 int FFMPEG::open_decoder()
1541 if( stat(fmt_ctx->filename, &st) < 0 ) {
1542 eprintf(_("can't stat file: %s\n"), fmt_ctx->filename);
1546 int64_t file_bits = 8 * st.st_size;
1547 if( !fmt_ctx->bit_rate && opt_duration > 0 )
1548 fmt_ctx->bit_rate = file_bits / opt_duration;
1551 if( fmt_ctx->bit_rate > 0 ) {
1552 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1553 AVStream *st = fmt_ctx->streams[i];
1554 if( st->duration != AV_NOPTS_VALUE ) continue;
1555 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
1556 st->duration = av_rescale(file_bits, st->time_base.den,
1557 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
1562 printf("FFMPEG::open_decoder: some stream times estimated\n");
1564 ff_lock("FFMPEG::open_decoder");
1566 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1567 AVStream *st = fmt_ctx->streams[i];
1568 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
1569 AVCodecContext *avctx = st->codec;
1570 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avctx->codec_id);
1571 if( !codec_desc ) continue;
1572 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1573 if( avctx->width < 1 ) continue;
1574 if( avctx->height < 1 ) continue;
1575 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
1576 if( framerate.num < 1 ) continue;
1578 int vidx = ffvideo.size();
1579 FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
1580 vstrm_index.append(ffidx(vidx, 0));
1581 ffvideo.append(vid);
1582 vid->width = avctx->width;
1583 vid->height = avctx->height;
1584 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
1585 double secs = to_secs(st->duration, st->time_base);
1586 vid->length = secs * vid->frame_rate;
1587 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
1588 vid->nudge = st->start_time;
1590 if( opt_video_filter )
1591 vid->create_filter(opt_video_filter, avctx,avctx);
1593 else if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1594 if( avctx->channels < 1 ) continue;
1595 if( avctx->sample_rate < 1 ) continue;
1597 int aidx = ffaudio.size();
1598 FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
1599 ffaudio.append(aud);
1600 aud->channel0 = astrm_index.size();
1601 aud->channels = avctx->channels;
1602 for( int ch=0; ch<aud->channels; ++ch )
1603 astrm_index.append(ffidx(aidx, ch));
1604 aud->sample_rate = avctx->sample_rate;
1605 double secs = to_secs(st->duration, st->time_base);
1606 aud->length = secs * aud->sample_rate;
1607 if( avctx->sample_fmt != AV_SAMPLE_FMT_FLT ) {
1608 uint64_t layout = av_get_default_channel_layout(avctx->channels);
1609 if( !layout ) layout = ((uint64_t)1<<aud->channels) - 1;
1610 aud->resample_context = swr_alloc_set_opts(NULL,
1611 layout, AV_SAMPLE_FMT_FLT, avctx->sample_rate,
1612 layout, avctx->sample_fmt, avctx->sample_rate,
1614 swr_init(aud->resample_context);
1616 aud->nudge = st->start_time;
1618 if( opt_audio_filter )
1619 aud->create_filter(opt_audio_filter, avctx,avctx);
1623 printf("FFMPEG::open_decoder: some stream have bad times\n");
1629 int FFMPEG::init_encoder(const char *filename)
1631 int fd = ::open(filename,O_WRONLY);
1632 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
1634 eprintf(_("bad file path: %s\n"), filename);
1638 int ret = get_file_format();
1640 eprintf(_("bad file format: %s\n"), filename);
1644 eprintf(_("mismatch audio/video file format: %s\n"), filename);
1647 ff_lock("FFMPEG::init_encoder");
1649 avformat_alloc_output_context2(&fmt_ctx, 0, file_format, filename);
1651 eprintf(_("failed: %s\n"), filename);
1656 load_options("encode.opts", opts);
1662 int FFMPEG::open_encoder(const char *type, const char *spec)
1665 Asset *asset = file_base->asset;
1666 char *filename = asset->path;
1667 AVDictionary *sopts = 0;
1668 av_dict_copy(&sopts, opts, 0);
1669 char option_path[BCTEXTLEN];
1670 set_option_path(option_path, "%s/%s.opts", type, type);
1671 read_options(option_path, sopts);
1672 get_option_path(option_path, type, spec);
1673 char format_name[BCSTRLEN], codec_name[BCTEXTLEN];
1674 char bsfilter[BCSTRLEN], bsargs[BCTEXTLEN];
1675 if( get_encoder(option_path, format_name, codec_name, bsfilter, bsargs) ) {
1676 eprintf(_("get_encoder failed %s:%s\n"), option_path, filename);
1680 if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
1681 else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
1682 else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
1685 ff_lock("FFMPEG::open_encoder");
1689 const AVCodecDescriptor *codec_desc = 0;
1690 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
1692 eprintf(_("cant find codec %s:%s\n"), codec_name, filename);
1696 codec_desc = avcodec_descriptor_get(codec->id);
1698 eprintf(_("unknown codec %s:%s\n"), codec_name, filename);
1703 st = avformat_new_stream(fmt_ctx, 0);
1705 eprintf(_("cant create stream %s:%s\n"), codec_name, filename);
1710 AVCodecContext *ctx = st->codec;
1711 switch( codec_desc->type ) {
1712 case AVMEDIA_TYPE_AUDIO: {
1714 eprintf(_("duplicate audio %s:%s\n"), codec_name, filename);
1719 if( scan_options(asset->ff_audio_options, sopts, st) ) {
1720 eprintf(_("bad audio options %s:%s\n"), codec_name, filename);
1724 if( asset->ff_audio_bitrate > 0 ) {
1725 ctx->bit_rate = asset->ff_audio_bitrate;
1727 sprintf(arg, "%d", asset->ff_audio_bitrate);
1728 av_dict_set(&sopts, "b", arg, 0);
1730 int aidx = ffaudio.size();
1731 int fidx = aidx + ffvideo.size();
1732 FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
1733 ffaudio.append(aud); fst = aud;
1734 aud->sample_rate = asset->sample_rate;
1735 ctx->channels = aud->channels = asset->channels;
1736 for( int ch=0; ch<aud->channels; ++ch )
1737 astrm_index.append(ffidx(aidx, ch));
1738 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
1739 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
1740 if( !ctx->sample_rate ) {
1741 eprintf(_("check_sample_rate failed %s\n"), filename);
1745 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
1746 ctx->sample_fmt = codec->sample_fmts[0];
1747 uint64_t layout = av_get_default_channel_layout(ctx->channels);
1748 aud->resample_context = swr_alloc_set_opts(NULL,
1749 layout, ctx->sample_fmt, aud->sample_rate,
1750 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
1752 swr_init(aud->resample_context);
1755 case AVMEDIA_TYPE_VIDEO: {
1757 eprintf(_("duplicate video %s:%s\n"), codec_name, filename);
1762 if( scan_options(asset->ff_video_options, sopts, st) ) {
1763 eprintf(_("bad video options %s:%s\n"), codec_name, filename);
1767 if( asset->ff_video_bitrate > 0 ) {
1768 ctx->bit_rate = asset->ff_video_bitrate;
1770 sprintf(arg, "%d", asset->ff_video_bitrate);
1771 av_dict_set(&sopts, "b", arg, 0);
1773 else if( asset->ff_video_quality > 0 ) {
1774 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
1775 ctx->qmin = ctx->qmax = asset->ff_video_quality;
1776 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
1777 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
1778 ctx->flags |= CODEC_FLAG_QSCALE;
1780 av_dict_set(&sopts, "flags", "+qscale", 0);
1781 sprintf(arg, "%d", asset->ff_video_quality);
1782 av_dict_set(&sopts, "qscale", arg, 0);
1783 sprintf(arg, "%d", ctx->global_quality);
1784 av_dict_set(&sopts, "global_quality", arg, 0);
1786 int vidx = ffvideo.size();
1787 int fidx = vidx + ffaudio.size();
1788 FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
1789 vstrm_index.append(ffidx(vidx, 0));
1790 ffvideo.append(vid); fst = vid;
1791 vid->width = asset->width;
1792 ctx->width = (vid->width+3) & ~3;
1793 vid->height = asset->height;
1794 ctx->height = (vid->height+3) & ~3;
1795 vid->frame_rate = asset->frame_rate;
1796 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
1797 ctx->pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
1798 AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
1799 if( !frame_rate.num || !frame_rate.den ) {
1800 eprintf(_("check_frame_rate failed %s\n"), filename);
1804 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
1805 st->time_base = ctx->time_base;
1809 eprintf(_("not audio/video, %s:%s\n"), codec_name, filename);
1814 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
1815 st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
1817 ret = avcodec_open2(st->codec, codec, &sopts);
1819 ff_err(ret,"FFMPEG::open_encoder");
1820 eprintf(_("open failed %s:%s\n"), codec_name, filename);
1827 if( fst && bsfilter[0] )
1828 fst->add_bsfilter(bsfilter, !bsargs[0] ? 0 : bsargs);
1834 av_dict_free(&sopts);
1838 int FFMPEG::close_encoder()
1841 if( encoding > 0 ) {
1842 av_write_trailer(fmt_ctx);
1843 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
1844 avio_closep(&fmt_ctx->pb);
1850 int FFMPEG::decode_activate()
1852 if( decoding < 0 ) {
1854 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
1855 ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
1856 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
1857 ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
1858 // set nudges for each program stream set
1859 int npgrms = fmt_ctx->nb_programs;
1860 for( int i=0; i<npgrms; ++i ) {
1861 AVProgram *pgrm = fmt_ctx->programs[i];
1862 // first start time video stream
1863 int64_t vstart_time = -1, astart_time = -1;
1864 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1865 int fidx = pgrm->stream_index[j];
1866 AVStream *st = fmt_ctx->streams[fidx];
1867 AVCodecContext *avctx = st->codec;
1868 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1869 if( st->start_time == AV_NOPTS_VALUE ) continue;
1870 if( vstart_time > st->start_time ) continue;
1871 vstart_time = st->start_time;
1874 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1875 if( st->start_time == AV_NOPTS_VALUE ) continue;
1876 if( astart_time > st->start_time ) continue;
1877 astart_time = st->start_time;
1881 // match program streams to max start_time
1882 int64_t nudge = vstart_time > astart_time ? vstart_time : astart_time;
1883 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1884 int fidx = pgrm->stream_index[j];
1885 AVStream *st = fmt_ctx->streams[fidx];
1886 AVCodecContext *avctx = st->codec;
1887 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1888 for( int k=0; k<ffvideo.size(); ++k ) {
1889 if( ffvideo[k]->fidx != fidx ) continue;
1890 ffvideo[k]->nudge = nudge;
1894 if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1895 for( int k=0; k<ffaudio.size(); ++k ) {
1896 if( ffaudio[k]->fidx != fidx ) continue;
1897 ffaudio[k]->nudge = nudge;
1903 // set nudges for any streams not yet set
1904 int64_t vstart_time = 0, astart_time = 0;
1905 int nstreams = fmt_ctx->nb_streams;
1906 for( int i=0; i<nstreams; ++i ) {
1907 AVStream *st = fmt_ctx->streams[i];
1908 AVCodecContext *avctx = st->codec;
1909 switch( avctx->codec_type ) {
1910 case AVMEDIA_TYPE_VIDEO: {
1911 if( st->start_time == AV_NOPTS_VALUE ) continue;
1912 int vidx = ffvideo.size();
1913 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
1914 if( vidx >= 0 && ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
1915 if( vstart_time >= st->start_time ) continue;
1916 vstart_time = st->start_time;
1918 case AVMEDIA_TYPE_AUDIO: {
1919 if( st->start_time == AV_NOPTS_VALUE ) continue;
1920 int aidx = ffaudio.size();
1921 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
1922 if( aidx >= 0 && ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
1923 if( astart_time >= st->start_time ) continue;
1924 astart_time = st->start_time;
1929 int64_t nudge = vstart_time > astart_time ? vstart_time : astart_time;
1930 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
1931 if( ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
1932 ffvideo[vidx]->nudge = nudge;
1934 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
1935 if( ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
1936 ffaudio[aidx]->nudge = nudge;
1943 int FFMPEG::encode_activate()
1946 if( encoding < 0 ) {
1948 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
1949 (ret=avio_open(&fmt_ctx->pb, fmt_ctx->filename, AVIO_FLAG_WRITE)) < 0 ) {
1950 ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
1955 AVDictionary *fopts = 0;
1956 char option_path[BCTEXTLEN];
1957 set_option_path(option_path, "format/%s", file_format);
1958 read_options(option_path, fopts);
1959 ret = avformat_write_header(fmt_ctx, &fopts);
1960 av_dict_free(&fopts);
1962 ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
1972 int FFMPEG::audio_seek(int stream, int64_t pos)
1974 int aidx = astrm_index[stream].st_idx;
1975 FFAudioStream *aud = ffaudio[aidx];
1976 aud->audio_seek(pos);
1980 int FFMPEG::video_seek(int stream, int64_t pos)
1982 int vidx = vstrm_index[stream].st_idx;
1983 FFVideoStream *vid = ffvideo[vidx];
1984 vid->video_seek(pos);
1989 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
1991 if( !has_audio || chn >= astrm_index.size() ) return -1;
1992 int aidx = astrm_index[chn].st_idx;
1993 FFAudioStream *aud = ffaudio[aidx];
1994 if( aud->load(pos, len) < len ) return -1;
1995 int ch = astrm_index[chn].st_ch;
1996 int ret = aud->read(samples,len,ch);
2000 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
2002 if( !has_video || layer >= vstrm_index.size() ) return -1;
2003 int vidx = vstrm_index[layer].st_idx;
2004 FFVideoStream *vid = ffvideo[vidx];
2005 return vid->load(vframe, pos);
2009 int FFMPEG::encode(int stream, double **samples, int len)
2011 FFAudioStream *aud = ffaudio[stream];
2012 return aud->encode(samples, len);
2016 int FFMPEG::encode(int stream, VFrame *frame)
2018 FFVideoStream *vid = ffvideo[stream];
2019 return vid->encode(frame);
2022 void FFMPEG::start_muxer()
2030 void FFMPEG::stop_muxer()
2039 void FFMPEG::flow_off()
2042 flow_lock->lock("FFMPEG::flow_off");
2046 void FFMPEG::flow_on()
2050 flow_lock->unlock();
2053 void FFMPEG::flow_ctl()
2056 flow_lock->lock("FFMPEG::flow_ctl");
2057 flow_lock->unlock();
2061 int FFMPEG::mux_audio(FFrame *frm)
2064 FFStream *fst = frm->fst;
2065 AVCodecContext *ctx = fst->st->codec;
2066 AVFrame *frame = *frm;
2067 AVRational tick_rate = {1, ctx->sample_rate};
2068 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
2070 int ret = fst->encode_frame(pkt, frame, got_packet);
2071 if( ret >= 0 && got_packet )
2072 ret = fst->write_packet(pkt);
2074 ff_err(ret, "FFMPEG::mux_audio");
2075 return ret >= 0 ? 0 : 1;
2078 int FFMPEG::mux_video(FFrame *frm)
2081 FFStream *fst = frm->fst;
2082 AVFrame *frame = *frm;
2083 frame->pts = frm->position;
2085 int ret = fst->encode_frame(pkt, frame, got_packet);
2086 if( ret >= 0 && got_packet )
2087 ret = fst->write_packet(pkt);
2089 ff_err(ret, "FFMPEG::mux_video");
2090 return ret >= 0 ? 0 : 1;
2096 double atm = -1, vtm = -1;
2097 FFrame *afrm = 0, *vfrm = 0;
2099 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
2100 FFStream *fst = ffaudio[i];
2101 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
2102 FFrame *frm = fst->frms.first;
2103 if( !frm ) { if( !done ) return; continue; }
2104 double tm = to_secs(frm->position, fst->st->codec->time_base);
2105 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
2107 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
2108 FFStream *fst = ffvideo[i];
2109 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
2110 FFrame *frm = fst->frms.first;
2111 if( !frm ) { if( !done ) return; continue; }
2112 double tm = to_secs(frm->position, fst->st->codec->time_base);
2113 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
2115 if( !demand ) flow_off();
2116 if( !afrm && !vfrm ) break;
2117 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
2118 vfrm->position, vfrm->fst->st->codec->time_base,
2119 afrm->position, afrm->fst->st->codec->time_base);
2120 FFrame *frm = v <= 0 ? vfrm : afrm;
2121 if( frm == afrm ) mux_audio(frm);
2122 if( frm == vfrm ) mux_video(frm);
2131 mux_lock->lock("FFMPEG::run");
2135 for( int i=0; i<ffaudio.size(); ++i )
2136 ffaudio[i]->flush();
2137 for( int i=0; i<ffvideo.size(); ++i )
2138 ffvideo[i]->flush();
2142 int FFMPEG::ff_total_audio_channels()
2144 return astrm_index.size();
2147 int FFMPEG::ff_total_astreams()
2149 return ffaudio.size();
2152 int FFMPEG::ff_audio_channels(int stream)
2154 return ffaudio[stream]->channels;
2157 int FFMPEG::ff_sample_rate(int stream)
2159 return ffaudio[stream]->sample_rate;
2162 const char* FFMPEG::ff_audio_format(int stream)
2164 AVStream *st = ffaudio[stream]->st;
2165 AVCodecID id = st->codec->codec_id;
2166 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2167 return desc ? desc->name : _("Unknown");
2170 int FFMPEG::ff_audio_pid(int stream)
2172 return ffaudio[stream]->st->id;
2175 int64_t FFMPEG::ff_audio_samples(int stream)
2177 return ffaudio[stream]->length;
2180 // find audio astream/channels with this program,
2181 // or all program audio channels (astream=-1)
2182 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
2186 int vidx = ffvideo[vstream]->fidx;
2187 // find first program with this video stream
2188 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
2189 AVProgram *pgrm = fmt_ctx->programs[i];
2190 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
2191 int st_idx = pgrm->stream_index[j];
2192 AVStream *st = fmt_ctx->streams[st_idx];
2193 if( st->codec->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
2194 if( st_idx == vidx ) pidx = i;
2197 if( pidx < 0 ) return -1;
2199 int64_t channels = 0;
2200 AVProgram *pgrm = fmt_ctx->programs[pidx];
2201 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2202 int aidx = pgrm->stream_index[j];
2203 AVStream *st = fmt_ctx->streams[aidx];
2204 if( st->codec->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
2205 if( astream > 0 ) { --astream; continue; }
2207 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
2208 if( ffaudio[i]->fidx == aidx ) astrm = i;
2210 if( ret < 0 ) ret = astrm;
2211 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
2212 channels |= mask << ffaudio[astrm]->channel0;
2214 if( !astream ) break;
2216 channel_mask = channels;
2221 int FFMPEG::ff_total_video_layers()
2223 return vstrm_index.size();
2226 int FFMPEG::ff_total_vstreams()
2228 return ffvideo.size();
2231 int FFMPEG::ff_video_width(int stream)
2233 return ffvideo[stream]->width;
2236 int FFMPEG::ff_video_height(int stream)
2238 return ffvideo[stream]->height;
2241 int FFMPEG::ff_set_video_width(int stream, int width)
2243 int w = ffvideo[stream]->width;
2244 ffvideo[stream]->width = width;
2248 int FFMPEG::ff_set_video_height(int stream, int height)
2250 int h = ffvideo[stream]->height;
2251 ffvideo[stream]->height = height;
2255 int FFMPEG::ff_coded_width(int stream)
2257 AVStream *st = ffvideo[stream]->st;
2258 return st->codec->coded_width;
2261 int FFMPEG::ff_coded_height(int stream)
2263 AVStream *st = ffvideo[stream]->st;
2264 return st->codec->coded_height;
2267 float FFMPEG::ff_aspect_ratio(int stream)
2269 return ffvideo[stream]->aspect_ratio;
2272 const char* FFMPEG::ff_video_format(int stream)
2274 AVStream *st = ffvideo[stream]->st;
2275 AVCodecID id = st->codec->codec_id;
2276 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2277 return desc ? desc->name : _("Unknown");
2280 double FFMPEG::ff_frame_rate(int stream)
2282 return ffvideo[stream]->frame_rate;
2285 int64_t FFMPEG::ff_video_frames(int stream)
2287 return ffvideo[stream]->length;
2290 int FFMPEG::ff_video_pid(int stream)
2292 return ffvideo[stream]->st->id;
2296 int FFMPEG::ff_cpus()
2298 return file_base->file->cpus;
2301 int FFVideoStream::create_filter(const char *filter_spec,
2302 AVCodecContext *src_ctx, AVCodecContext *sink_ctx)
2304 avfilter_register_all();
2305 AVFilter *filter = avfilter_get_by_name(filter_spec);
2306 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_VIDEO ) {
2307 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
2310 filter_graph = avfilter_graph_alloc();
2311 AVFilter *buffersrc = avfilter_get_by_name("buffer");
2312 AVFilter *buffersink = avfilter_get_by_name("buffersink");
2314 int ret = 0; char args[BCTEXTLEN];
2315 snprintf(args, sizeof(args),
2316 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
2317 src_ctx->width, src_ctx->height, src_ctx->pix_fmt,
2318 src_ctx->time_base.num, src_ctx->time_base.den,
2319 src_ctx->sample_aspect_ratio.num, src_ctx->sample_aspect_ratio.den);
2321 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2322 args, NULL, filter_graph);
2324 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2325 NULL, NULL, filter_graph);
2327 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
2328 (uint8_t*)&sink_ctx->pix_fmt, sizeof(sink_ctx->pix_fmt),
2329 AV_OPT_SEARCH_CHILDREN);
2331 ff_err(ret, "FFVideoStream::create_filter");
2333 ret = FFStream::create_filter(filter_spec);
2334 return ret >= 0 ? 0 : 1;
2337 int FFAudioStream::create_filter(const char *filter_spec,
2338 AVCodecContext *src_ctx, AVCodecContext *sink_ctx)
2340 avfilter_register_all();
2341 AVFilter *filter = avfilter_get_by_name(filter_spec);
2342 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_AUDIO ) {
2343 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
2346 filter_graph = avfilter_graph_alloc();
2347 AVFilter *buffersrc = avfilter_get_by_name("abuffer");
2348 AVFilter *buffersink = avfilter_get_by_name("abuffersink");
2349 int ret = 0; char args[BCTEXTLEN];
2350 snprintf(args, sizeof(args),
2351 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
2352 src_ctx->time_base.num, src_ctx->time_base.den, src_ctx->sample_rate,
2353 av_get_sample_fmt_name(src_ctx->sample_fmt), src_ctx->channel_layout);
2355 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2356 args, NULL, filter_graph);
2358 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2359 NULL, NULL, filter_graph);
2361 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
2362 (uint8_t*)&sink_ctx->sample_fmt, sizeof(sink_ctx->sample_fmt),
2363 AV_OPT_SEARCH_CHILDREN);
2365 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
2366 (uint8_t*)&sink_ctx->channel_layout,
2367 sizeof(sink_ctx->channel_layout), AV_OPT_SEARCH_CHILDREN);
2369 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
2370 (uint8_t*)&sink_ctx->sample_rate, sizeof(sink_ctx->sample_rate),
2371 AV_OPT_SEARCH_CHILDREN);
2373 ff_err(ret, "FFAudioStream::create_filter");
2375 ret = FFStream::create_filter(filter_spec);
2376 return ret >= 0 ? 0 : 1;
2379 int FFStream::create_filter(const char *filter_spec)
2381 /* Endpoints for the filter graph. */
2382 AVFilterInOut *outputs = avfilter_inout_alloc();
2383 outputs->name = av_strdup("in");
2384 outputs->filter_ctx = buffersrc_ctx;
2385 outputs->pad_idx = 0;
2388 AVFilterInOut *inputs = avfilter_inout_alloc();
2389 inputs->name = av_strdup("out");
2390 inputs->filter_ctx = buffersink_ctx;
2391 inputs->pad_idx = 0;
2394 int ret = !outputs->name || !inputs->name ? -1 : 0;
2396 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
2397 &inputs, &outputs, NULL);
2399 ret = avfilter_graph_config(filter_graph, NULL);
2402 ff_err(ret, "FFStream::create_filter");
2403 avfilter_inout_free(&inputs);
2404 avfilter_inout_free(&outputs);
2408 void FFStream::add_bsfilter(const char *bsf, const char *ap)
2410 bsfilter.append(new BSFilter(bsf,ap));
2413 int FFStream::bs_filter(AVPacket *pkt)
2415 if( !bsfilter.size() ) return 0;
2416 av_packet_split_side_data(pkt);
2419 for( int i=0; i<bsfilter.size(); ++i ) {
2420 AVPacket bspkt = *pkt;
2421 ret = av_bitstream_filter_filter(bsfilter[i]->bsfc,
2422 st->codec, bsfilter[i]->args, &bspkt.data, &bspkt.size,
2423 pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY);
2424 if( ret < 0 ) break;
2425 int size = bspkt.size;
2426 uint8_t *data = bspkt.data;
2427 if( !ret && bspkt.data != pkt->data ) {
2429 data = (uint8_t *)av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
2430 if( !data ) { ret = AVERROR(ENOMEM); break; }
2431 memcpy(data, bspkt.data, size);
2432 memset(data+size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2436 pkt->side_data = 0; pkt->side_data_elems = 0;
2437 av_packet_unref(pkt);
2438 ret = av_packet_from_data(&bspkt, data, size);
2439 if( ret < 0 ) break;
2444 ff_err(ret,"FFStream::bs_filter");
2448 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
2451 av_init_packet(&pkt);
2452 AVFrame *frame = av_frame_alloc();
2454 fprintf(stderr,"FFMPEG::scan: ");
2455 fprintf(stderr,_("av_frame_alloc failed\n"));
2459 index_state->add_video_markers(ffvideo.size());
2460 index_state->add_audio_markers(ffaudio.size());
2462 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2463 AVDictionary *copts = 0;
2464 av_dict_copy(&copts, opts, 0);
2465 AVStream *st = fmt_ctx->streams[i];
2466 AVCodecID codec_id = st->codec->codec_id;
2467 AVCodec *decoder = avcodec_find_decoder(codec_id);
2468 if( avcodec_open2(st->codec, decoder, &copts) < 0 ) {
2469 fprintf(stderr,"FFMPEG::scan: ");
2470 fprintf(stderr,_("codec open failed\n"));
2472 av_dict_free(&copts);
2475 for( int64_t count=0; !*canceled; ++count ) {
2476 av_packet_unref(&pkt);
2477 pkt.data = 0; pkt.size = 0;
2479 int ret = av_read_frame(fmt_ctx, &pkt);
2481 if( ret == AVERROR_EOF ) break;
2482 if( ++errs > 100 ) {
2483 ff_err(ret,_("over 100 read_frame errs\n"));
2488 if( !pkt.data ) continue;
2489 int i = pkt.stream_index;
2490 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
2491 AVStream *st = fmt_ctx->streams[i];
2492 AVCodecContext *avctx = st->codec;
2493 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
2495 switch( avctx->codec_type ) {
2496 case AVMEDIA_TYPE_VIDEO: {
2497 int vidx = ffvideo.size();
2498 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
2499 if( vidx < 0 ) break;
2500 FFVideoStream *vid = ffvideo[vidx];
2501 int64_t tstmp = pkt.dts;
2502 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.pts;
2503 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
2504 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
2505 double secs = to_secs(tstmp, st->time_base);
2506 int64_t frm = secs * vid->frame_rate + 0.5;
2507 if( frm < 0 ) frm = 0;
2508 index_state->put_video_mark(vidx, frm, pkt.pos);
2511 while( pkt.size > 0 ) {
2512 av_frame_unref(frame);
2514 int ret = vid->decode_frame(&pkt, frame, got_frame);
2515 if( ret <= 0 ) break;
2516 // if( got_frame ) {}
2522 case AVMEDIA_TYPE_AUDIO: {
2523 int aidx = ffaudio.size();
2524 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
2525 if( aidx < 0 ) break;
2526 FFAudioStream *aud = ffaudio[aidx];
2527 int64_t tstmp = pkt.pts;
2528 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
2529 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
2530 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
2531 double secs = to_secs(tstmp, st->time_base);
2532 int64_t sample = secs * aud->sample_rate + 0.5;
2533 if( sample < 0 ) sample = 0;
2534 index_state->put_audio_mark(aidx, sample, pkt.pos);
2536 while( pkt.size > 0 ) {
2537 int ch = aud->channel0, nch = aud->channels;
2538 int64_t pos = index_state->pos(ch);
2539 if( pos != aud->curr_pos ) {
2540 if( abs(pos-aud->curr_pos) > 1 )
2541 printf("audio%d pad %ld %ld (%ld)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
2542 index_state->pad_data(ch, nch, aud->curr_pos);
2544 av_frame_unref(frame);
2546 int ret = aud->decode_frame(&pkt, frame, got_frame);
2547 if( ret <= 0 ) break;
2548 if( got_frame && frame->channels == nch ) {
2550 int len = aud->get_samples(samples,
2551 &frame->extended_data[0], frame->nb_samples);
2552 for( int i=0; i<nch; ++i )
2553 index_state->put_data(ch+i,nch,samples+i,len);
2554 aud->curr_pos += len;
2563 av_frame_free(&frame);
2567 void FFStream::load_markers(IndexMarks &marks, double rate)
2570 int64_t sz = marks.size();
2571 int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
2572 int nb_ent = st->nb_index_entries;
2573 // some formats already have an index
2575 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
2576 int64_t tstmp = ep->timestamp;
2577 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
2578 double secs = ffmpeg->to_secs(tstmp, st->time_base);
2579 int64_t no = secs * rate;
2580 while( in < sz && marks[in].no <= no ) ++in;
2582 int64_t len = sz - in;
2583 int64_t count = max_entries - nb_ent;
2584 if( count > len ) count = len;
2585 for( int i=0; i<count; ++i ) {
2586 int k = in + i * len / count;
2587 int64_t no = marks[k].no, pos = marks[k].pos;
2588 double secs = (double)no / rate;
2589 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
2590 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
2591 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);