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);
57 av_packet_unref(&pkt);
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 ) need_packet = 1;
366 if( ret <= 0 || !ipkt->data ) break;
379 fprintf(stderr, "FFStream::decode: Retry limit\n");
383 fprintf(stderr, "FFStream::decode: failed\n");
388 int FFStream::load_filter(AVFrame *frame)
390 int ret = av_buffersrc_add_frame_flags(buffersrc_ctx,
391 frame, AV_BUFFERSRC_FLAG_KEEP_REF);
393 av_frame_unref(frame);
394 eprintf("FFStream::load_filter: av_buffersrc_add_frame_flags failed\n");
399 int FFStream::read_filter(AVFrame *frame)
401 int ret = av_buffersink_get_frame(buffersink_ctx, frame);
403 if( ret == AVERROR(EAGAIN) ) return 0;
404 if( ret == AVERROR_EOF ) { st_eof(1); return -1; }
405 ff_err(ret, "FFStream::read_filter: av_buffersink_get_frame failed\n");
411 int FFStream::read_frame(AVFrame *frame)
413 if( !filter_graph || !buffersrc_ctx || !buffersink_ctx )
414 return decode(frame);
415 if( !fframe && !(fframe=av_frame_alloc()) ) {
416 fprintf(stderr, "FFStream::read_frame: av_frame_alloc failed\n");
420 while( !flushed && !(ret=read_filter(frame)) ) {
421 if( (ret=decode(fframe)) < 0 ) break;
422 if( ret > 0 && (ret=load_filter(fframe)) < 0 ) break;
427 int FFStream::write_packet(FFPacket &pkt)
430 av_packet_rescale_ts(pkt, st->codec->time_base, st->time_base);
431 pkt->stream_index = st->index;
432 return av_interleaved_write_frame(ffmpeg->fmt_ctx, pkt);
435 int FFStream::flush()
441 ret = encode_frame(pkt, 0, got_packet);
442 if( ret < 0 || !got_packet ) break;
443 ret = write_packet(pkt);
446 ff_err(ret, "FFStream::flush");
447 return ret >= 0 ? 0 : 1;
450 int FFStream::seek(int64_t no, double rate)
453 // default ffmpeg native seek
455 int64_t pos = no, plmt = -1;
456 if( index_markers && index_markers->size() > 1 ) {
457 IndexMarks &marks = *index_markers;
458 int i = marks.find(pos);
459 int64_t n = i < 0 ? (i=0) : marks[i].no;
460 // if indexed seek point not too far away (<30 secs), use index
461 if( no-n < 30*rate ) {
464 if( ++i < marks.size() ) plmt = marks[i].pos;
468 double secs = pos / rate;
469 int64_t pkt_ts, tstmp = secs * st->time_base.den / st->time_base.num;
470 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
471 int ret = avformat_seek_file(fmt_ctx, st->index,
472 -INT64_MAX, tstmp, INT64_MAX, AVSEEK_FLAG_ANY);
474 avcodec_flush_buffers(st->codec);
475 need_packet = 0; flushed = 0;
476 seeked = 1; st_eof(0);
477 // read up to retry packets, limited to npkts in stream, and not past pkt.pos plmt
478 for( int retry=MAX_RETRY; ret>=0 && --retry>=0; ) {
479 if( read_packet() <= 0 ) { ret = -1; break; }
480 if( plmt >= 0 && ipkt->pos >= plmt ) break;
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->marker_status == MARKERS_NOTTESTED ) return;
710 if( !index_state || idx >= index_state->audio_markers.size() ) return;
711 FFStream::load_markers(*index_state->audio_markers[idx], sample_rate);
714 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
715 : FFStream(ffmpeg, strm, fidx)
724 FFVideoStream::~FFVideoStream()
728 int FFVideoStream::decode_frame(AVPacket *pkt, AVFrame *frame, int &got_frame)
730 int first_frame = seeked; seeked = 0;
731 int ret = avcodec_decode_video2(st->codec, frame, &got_frame, pkt);
733 if( first_frame ) return 0;
734 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame\n");
737 else // this is right out of ffplay, looks questionable ???
741 int64_t pkt_ts = av_frame_get_best_effort_timestamp(frame);
742 if( pkt_ts != AV_NOPTS_VALUE )
743 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * frame_rate + 0.5;
748 int FFVideoStream::load(VFrame *vframe, int64_t pos)
750 int ret = video_seek(pos);
751 if( ret < 0 ) return -1;
752 if( !frame && !(frame=av_frame_alloc()) ) {
753 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
756 for( int i=0; ret>=0 && !flushed && curr_pos<=pos && i<MAX_RETRY; ++i ) {
757 ret = read_frame(frame);
758 if( ret > 0 ) ++curr_pos;
761 AVCodecContext *ctx = st->codec;
762 ret = convert_cmodel(vframe, frame,
763 ctx->pix_fmt, ctx->width, ctx->height);
765 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
769 int FFVideoStream::video_seek(int64_t pos)
771 if( decode_activate() < 0 ) return -1;
772 if( !st->codec || !st->codec->codec ) return -1;
773 if( pos == curr_pos-1 && !seeked ) return 0;
774 // if close enough, just read up to current
775 int gop = st->codec->gop_size;
776 if( gop < 4 ) gop = 4;
777 if( gop > 64 ) gop = 64;
778 int read_limit = curr_pos + 3*gop;
779 if( pos >= curr_pos && pos <= read_limit ) return 0;
780 // guarentee preload more than 2*gop frames
781 if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
785 int FFVideoStream::init_frame(AVFrame *picture)
787 AVCodecContext *ctx = st->codec;
788 picture->format = ctx->pix_fmt;
789 picture->width = ctx->width;
790 picture->height = ctx->height;
791 int ret = av_frame_get_buffer(picture, 32);
795 int FFVideoStream::encode(VFrame *vframe)
797 if( encode_activate() <= 0 ) return -1;
799 FFrame *picture = new FFrame(this);
800 int ret = picture->initted();
802 AVFrame *frame = *picture;
803 frame->pts = curr_pos;
804 AVCodecContext *ctx = st->codec;
805 ret = convert_pixfmt(vframe, frame,
806 ctx->pix_fmt, ctx->width, ctx->height);
809 picture->queue(curr_pos);
813 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
816 return ret >= 0 ? 0 : 1;
819 int FFVideoStream::encode_frame(AVPacket *pkt, AVFrame *frame, int &got_packet)
821 int ret = avcodec_encode_video2(st->codec, pkt, frame, &got_packet);
823 ff_err(ret, "FFVideoStream::encode_frame: encode video failed\n");
829 AVPixelFormat FFVideoConvert::color_model_to_pix_fmt(int color_model)
831 switch( color_model ) {
832 case BC_YUV422: return AV_PIX_FMT_YUYV422;
833 case BC_RGB888: return AV_PIX_FMT_RGB24;
834 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
835 case BC_BGR8888: return AV_PIX_FMT_BGR0;
836 case BC_BGR888: return AV_PIX_FMT_BGR24;
837 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
838 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
839 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
840 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
841 case BC_RGB565: return AV_PIX_FMT_RGB565;
842 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
843 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
847 return AV_PIX_FMT_NB;
850 int FFVideoConvert::pix_fmt_to_color_model(AVPixelFormat pix_fmt)
853 case AV_PIX_FMT_YUYV422: return BC_YUV422;
854 case AV_PIX_FMT_RGB24: return BC_RGB888;
855 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
856 case AV_PIX_FMT_BGR0: return BC_BGR8888;
857 case AV_PIX_FMT_BGR24: return BC_BGR888;
858 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
859 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
860 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
861 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
862 case AV_PIX_FMT_RGB565: return BC_RGB565;
863 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
864 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
868 return BC_TRANSPARENCY;
871 int FFVideoConvert::convert_picture_vframe(VFrame *frame,
872 AVFrame *ip, AVPixelFormat ifmt, int iw, int ih)
875 int cmodel = frame->get_color_model();
876 AVPixelFormat ofmt = color_model_to_pix_fmt(cmodel);
877 if( ofmt == AV_PIX_FMT_NB ) return -1;
878 int size = av_image_fill_arrays(opic.data, opic.linesize,
879 frame->get_data(), ofmt, frame->get_w(), frame->get_h(), 1);
880 if( size < 0 ) return -1;
882 // transfer line sizes must match also
883 int planar = BC_CModels::is_planar(cmodel);
884 int packed_width = !planar ? frame->get_bytes_per_line() :
885 BC_CModels::calculate_pixelsize(cmodel) * frame->get_w();
886 if( packed_width != opic.linesize[0] ) return -1;
889 // override av_image_fill_arrays() for planar types
890 opic.data[0] = frame->get_y();
891 opic.data[1] = frame->get_u();
892 opic.data[2] = frame->get_v();
895 convert_ctx = sws_getCachedContext(convert_ctx, iw, ih, ifmt,
896 frame->get_w(), frame->get_h(), ofmt, SWS_BICUBIC, NULL, NULL, NULL);
898 fprintf(stderr, "FFVideoConvert::convert_picture_frame:"
899 " sws_getCachedContext() failed\n");
902 int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ih,
903 opic.data, opic.linesize);
905 ff_err(ret, "FFVideoConvert::convert_picture_frame: sws_scale() failed\n");
911 int FFVideoConvert::convert_cmodel(VFrame *frame,
912 AVFrame *ip, AVPixelFormat ifmt, int iw, int ih)
914 // try direct transfer
915 if( !convert_picture_vframe(frame, ip, ifmt, iw, ih) ) return 1;
916 // use indirect transfer
917 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
919 for( int i = 0; i <desc->nb_components; ++i ) {
920 int bits = desc->comp[i].depth;
921 if( bits > max_bits ) max_bits = bits;
923 // from libavcodec/pixdesc.c
924 #define pixdesc_has_alpha(pixdesc) ((pixdesc)->nb_components == 2 || \
925 (pixdesc)->nb_components == 4 || (pixdesc)->flags & AV_PIX_FMT_FLAG_PAL)
926 int icolor_model = pixdesc_has_alpha(desc) ?
927 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
928 (max_bits > 8 ? BC_RGB161616 : BC_RGB888) ;
929 VFrame vframe(iw, ih, icolor_model);
930 if( convert_picture_vframe(&vframe, ip, ifmt, iw, ih) ) return -1;
931 frame->transfer_from(&vframe);
935 int FFVideoConvert::transfer_cmodel(VFrame *frame,
936 AVFrame *ifp, AVPixelFormat ifmt, int iw, int ih)
938 int ret = convert_cmodel(frame, ifp, ifmt, iw, ih);
940 const AVDictionary *src = av_frame_get_metadata(ifp);
941 AVDictionaryEntry *t = NULL;
942 BC_Hash *hp = frame->get_params();
944 while( (t=av_dict_get(src, "", t, AV_DICT_IGNORE_SUFFIX)) )
945 hp->update(t->key, t->value);
950 int FFVideoConvert::convert_vframe_picture(VFrame *frame,
951 AVFrame *op, AVPixelFormat ofmt, int ow, int oh)
954 int cmodel = frame->get_color_model();
955 AVPixelFormat ifmt = color_model_to_pix_fmt(cmodel);
956 if( ifmt == AV_PIX_FMT_NB ) return -1;
957 int size = av_image_fill_arrays(opic.data, opic.linesize,
958 frame->get_data(), ifmt, frame->get_w(), frame->get_h(), 1);
959 if( size < 0 ) return -1;
961 // transfer line sizes must match also
962 int planar = BC_CModels::is_planar(cmodel);
963 int packed_width = !planar ? frame->get_bytes_per_line() :
964 BC_CModels::calculate_pixelsize(cmodel) * frame->get_w();
965 if( packed_width != opic.linesize[0] ) return -1;
968 // override av_image_fill_arrays() for planar types
969 opic.data[0] = frame->get_y();
970 opic.data[1] = frame->get_u();
971 opic.data[2] = frame->get_v();
974 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(), ifmt,
975 ow, oh, ofmt, SWS_BICUBIC, NULL, NULL, NULL);
977 fprintf(stderr, "FFVideoConvert::convert_frame_picture:"
978 " sws_getCachedContext() failed\n");
981 int ret = sws_scale(convert_ctx, opic.data, opic.linesize, 0, frame->get_h(),
982 op->data, op->linesize);
984 ff_err(ret, "FFVideoConvert::convert_frame_picture: sws_scale() failed\n");
990 int FFVideoConvert::convert_pixfmt(VFrame *frame,
991 AVFrame *op, AVPixelFormat ofmt, int ow, int oh)
993 // try direct transfer
994 if( !convert_vframe_picture(frame, op, ofmt, ow, oh) ) return 1;
995 // use indirect transfer
996 int colormodel = frame->get_color_model();
997 int bits = BC_CModels::calculate_pixelsize(colormodel) * 8;
998 bits /= BC_CModels::components(colormodel);
999 int icolor_model = BC_CModels::has_alpha(colormodel) ?
1000 (bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1001 (bits > 8 ? BC_RGB161616: BC_RGB888) ;
1002 VFrame vframe(frame->get_w(), frame->get_h(), icolor_model);
1003 vframe.transfer_from(frame);
1004 if( !convert_vframe_picture(&vframe, op, ofmt, ow, oh) ) return 1;
1008 int FFVideoConvert::transfer_pixfmt(VFrame *frame,
1009 AVFrame *ofp, AVPixelFormat ofmt, int ow, int oh)
1011 int ret = convert_pixfmt(frame, ofp, ofmt, ow, oh);
1013 BC_Hash *hp = frame->get_params();
1014 AVDictionary **dict = avpriv_frame_get_metadatap(ofp);
1015 //av_dict_free(dict);
1016 for( int i=0; i<hp->size(); ++i ) {
1017 char *key = hp->get_key(i), *val = hp->get_value(i);
1018 av_dict_set(dict, key, val, 0);
1024 void FFVideoStream::load_markers()
1026 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1027 if( idx >= index_state->video_markers.size() ) return;
1028 FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
1032 FFMPEG::FFMPEG(FileBase *file_base)
1035 this->file_base = file_base;
1036 memset(file_format,0,sizeof(file_format));
1037 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
1038 flow_lock = new Condition(1,"FFStream::flow_lock",0);
1041 decoding = encoding = 0;
1042 has_audio = has_video = 0;
1045 opt_video_filter = 0;
1046 opt_audio_filter = 0;
1047 char option_path[BCTEXTLEN];
1048 set_option_path(option_path, "%s", "ffmpeg.opts");
1049 read_options(option_path, opts);
1054 ff_lock("FFMPEG::~FFMPEG()");
1056 ffaudio.remove_all_objects();
1057 ffvideo.remove_all_objects();
1058 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1062 av_dict_free(&opts);
1063 delete [] opt_video_filter;
1064 delete [] opt_audio_filter;
1067 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1069 const int *p = codec->supported_samplerates;
1070 if( !p ) return sample_rate;
1072 if( *p == sample_rate ) return *p;
1078 static inline AVRational std_frame_rate(int i)
1080 static const int m1 = 1001*12, m2 = 1000*12;
1081 static const int freqs[] = {
1082 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1083 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
1085 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1086 return (AVRational) { freq, 1001*12 };
1089 AVRational FFMPEG::check_frame_rate(AVCodec *codec, double frame_rate)
1091 const AVRational *p = codec->supported_framerates;
1092 AVRational rate, best_rate = (AVRational) { 0, 0 };
1093 double max_err = 1.; int i = 0;
1094 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1095 double framerate = (double) rate.num / rate.den;
1096 double err = fabs(frame_rate/framerate - 1.);
1097 if( err >= max_err ) continue;
1101 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1104 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1107 double display_aspect = asset->width / (double)asset->height;
1108 double sample_aspect = asset->aspect_ratio / display_aspect;
1109 int width = 1000000, height = width * sample_aspect + 0.5;
1111 MWindow::create_aspect_ratio(w, h, width, height);
1112 return (AVRational){(int)h, (int)w};
1115 return (AVRational){1, 1};
1119 AVRational FFMPEG::to_time_base(int sample_rate)
1121 return (AVRational){1, sample_rate};
1124 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
1127 strcat(path, "/ffmpeg/");
1128 path += strlen(path);
1131 vsprintf(path, fmt, ap);
1135 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
1140 set_option_path(path, "%s/%s", type, spec);
1143 int FFMPEG::get_format(char *format, const char *path, char *spec)
1145 char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
1146 get_option_path(option_path, path, spec);
1147 FILE *fp = fopen(option_path,"r");
1150 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1152 line[sizeof(line)-1] = 0;
1153 ret = scan_option_line(line, format, codec);
1159 int FFMPEG::get_file_format()
1162 char audio_format[BCSTRLEN], video_format[BCSTRLEN];
1163 file_format[0] = audio_format[0] = video_format[0] = 0;
1164 Asset *asset = file_base->asset;
1165 if( !ret && asset->audio_data )
1166 ret = get_format(audio_format, "audio", asset->acodec);
1167 if( !ret && asset->video_data )
1168 ret = get_format(video_format, "video", asset->vcodec);
1169 if( !ret && !audio_format[0] && !video_format[0] )
1171 if( !ret && audio_format[0] && video_format[0] &&
1172 strcmp(audio_format, video_format) ) ret = -1;
1174 strcpy(file_format, audio_format[0] ? audio_format : video_format);
1178 int FFMPEG::scan_option_line(char *cp, char *tag, char *val)
1180 while( *cp == ' ' || *cp == '\t' ) ++cp;
1182 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' ) ++cp;
1184 if( !len || len > BCSTRLEN-1 ) return 1;
1185 while( bp < cp ) *tag++ = *bp++;
1187 while( *cp == ' ' || *cp == '\t' ) ++cp;
1188 if( *cp == '=' ) ++cp;
1189 while( *cp == ' ' || *cp == '\t' ) ++cp;
1191 while( *cp && *cp != '\n' ) ++cp;
1193 if( len > BCTEXTLEN-1 ) return 1;
1194 while( bp < cp ) *val++ = *bp++;
1199 int FFMPEG::load_defaults(const char *path, const char *type,
1200 char *codec, char *codec_options, int len)
1202 char default_file[BCTEXTLEN];
1203 FFMPEG::set_option_path(default_file, "%s/%s.dfl", path, type);
1204 FILE *fp = fopen(default_file,"r");
1206 fgets(codec, BCSTRLEN, fp);
1208 while( *cp && *cp!='\n' ) ++cp;
1210 while( len > 0 && fgets(codec_options, len, fp) ) {
1211 int n = strlen(codec_options);
1212 codec_options += n; len -= n;
1215 FFMPEG::set_option_path(default_file, "%s/%s", path, codec);
1216 return FFMPEG::load_options(default_file, codec_options, len);
1219 void FFMPEG::set_asset_format(Asset *asset, const char *text)
1221 if( asset->format != FILE_FFMPEG ) return;
1222 strcpy(asset->fformat, text);
1223 if( !asset->ff_audio_options[0] ) {
1224 asset->audio_data = !load_defaults("audio", text, asset->acodec,
1225 asset->ff_audio_options, sizeof(asset->ff_audio_options));
1227 if( !asset->ff_video_options[0] ) {
1228 asset->video_data = !load_defaults("video", text, asset->vcodec,
1229 asset->ff_video_options, sizeof(asset->ff_video_options));
1233 int FFMPEG::get_encoder(const char *options,
1234 char *format, char *codec, char *bsfilter, char *bsargs)
1236 FILE *fp = fopen(options,"r");
1238 eprintf("FFMPEG::get_encoder: options open failed %s\n",options);
1241 if( get_encoder(fp, format, codec, bsfilter, bsargs) )
1242 eprintf(_("FFMPEG::get_encoder:"
1243 " err: format/codec not found %s\n"), options);
1248 int FFMPEG::get_encoder(FILE *fp,
1249 char *format, char *codec, char *bsfilter, char *bsargs)
1251 format[0] = codec[0] = bsfilter[0] = bsargs[0] = 0;
1252 char line[BCTEXTLEN];
1253 if( !fgets(line, sizeof(line), fp) ) return 1;
1254 line[sizeof(line)-1] = 0;
1255 if( scan_option_line(line, format, codec) ) return 1;
1257 while( *cp && *cp != '|' ) ++cp;
1258 if( !*cp ) return 0;
1259 if( scan_option_line(cp+1, bsfilter, bsargs) ) return 1;
1260 do { *cp-- = 0; } while( cp>=codec && (*cp==' ' || *cp == '\t' ) );
1264 int FFMPEG::read_options(const char *options, AVDictionary *&opts)
1266 FILE *fp = fopen(options,"r");
1268 int ret = read_options(fp, options, opts);
1273 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
1275 FILE *fp = fmemopen((void *)options,strlen(options),"r");
1277 int ret = read_options(fp, options, opts);
1279 AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
1280 if( tag ) st->id = strtol(tag->value,0,0);
1284 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
1286 int ret = 0, no = 0;
1287 char line[BCTEXTLEN];
1288 while( !ret && fgets(line, sizeof(line), fp) ) {
1289 line[sizeof(line)-1] = 0;
1291 if( line[0] == '#' ) continue;
1292 if( line[0] == '\n' ) continue;
1293 char key[BCSTRLEN], val[BCTEXTLEN];
1294 if( scan_option_line(line, key, val) ) {
1295 eprintf(_("FFMPEG::read_options:"
1296 " err reading %s: line %d\n"), options, no);
1300 if( !strcmp(key, "duration") )
1301 opt_duration = strtod(val, 0);
1302 else if( !strcmp(key, "video_filter") )
1303 opt_video_filter = cstrdup(val);
1304 else if( !strcmp(key, "audio_filter") )
1305 opt_audio_filter = cstrdup(val);
1306 else if( !strcmp(key, "loglevel") )
1309 av_dict_set(&opts, key, val, 0);
1315 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
1317 char option_path[BCTEXTLEN];
1318 set_option_path(option_path, "%s", options);
1319 return read_options(option_path, opts);
1322 int FFMPEG::load_options(const char *path, char *bfr, int len)
1325 FILE *fp = fopen(path, "r");
1327 fgets(bfr, len, fp); // skip hdr
1328 len = fread(bfr, 1, len-1, fp);
1329 if( len < 0 ) len = 0;
1335 void FFMPEG::set_loglevel(const char *ap)
1337 if( !ap || !*ap ) return;
1342 { "quiet" , AV_LOG_QUIET },
1343 { "panic" , AV_LOG_PANIC },
1344 { "fatal" , AV_LOG_FATAL },
1345 { "error" , AV_LOG_ERROR },
1346 { "warning", AV_LOG_WARNING },
1347 { "info" , AV_LOG_INFO },
1348 { "verbose", AV_LOG_VERBOSE },
1349 { "debug" , AV_LOG_DEBUG },
1351 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
1352 if( !strcmp(log_levels[i].name, ap) ) {
1353 av_log_set_level(log_levels[i].level);
1357 av_log_set_level(atoi(ap));
1360 double FFMPEG::to_secs(int64_t time, AVRational time_base)
1362 double base_time = time == AV_NOPTS_VALUE ? 0 :
1363 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
1364 return base_time / AV_TIME_BASE;
1367 int FFMPEG::info(char *text, int len)
1369 if( len <= 0 ) return 0;
1371 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
1373 if( ffvideo.size() > 0 )
1374 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
1375 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
1376 FFVideoStream *vid = ffvideo[vidx];
1377 AVStream *st = vid->st;
1378 AVCodecContext *avctx = st->codec;
1379 report(_("vid%d (%d), id 0x%06x:\n"), vid->idx, vid->fidx, avctx->codec_id);
1380 const AVCodecDescriptor *desc = avcodec_descriptor_get(avctx->codec_id);
1381 report(" video%d %s", vidx+1, desc ? desc->name : " (unkn)");
1382 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
1383 const char *pfn = av_get_pix_fmt_name(avctx->pix_fmt);
1384 report(" pix %s\n", pfn ? pfn : "(unkn)");
1385 double secs = to_secs(st->duration, st->time_base);
1386 int64_t length = secs * vid->frame_rate + 0.5;
1387 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
1388 int64_t nudge = ofs * vid->frame_rate;
1389 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1390 report(" %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
1391 int hrs = secs/3600; secs -= hrs*3600;
1392 int mins = secs/60; secs -= mins*60;
1393 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1395 if( ffaudio.size() > 0 )
1396 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
1397 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
1398 FFAudioStream *aud = ffaudio[aidx];
1399 AVStream *st = aud->st;
1400 AVCodecContext *avctx = st->codec;
1401 report(_("aud%d (%d), id 0x%06x:\n"), aud->idx, aud->fidx, avctx->codec_id);
1402 const AVCodecDescriptor *desc = avcodec_descriptor_get(avctx->codec_id);
1403 int nch = aud->channels, ch0 = aud->channel0+1;
1404 report(" audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
1405 const char *fmt = av_get_sample_fmt_name(avctx->sample_fmt);
1406 report(" %s %d", fmt, aud->sample_rate);
1407 int sample_bits = av_get_bits_per_sample(avctx->codec_id);
1408 report(" %dbits\n", sample_bits);
1409 double secs = to_secs(st->duration, st->time_base);
1410 int64_t length = secs * aud->sample_rate + 0.5;
1411 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
1412 int64_t nudge = ofs * aud->sample_rate;
1413 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1414 report(" %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
1415 int hrs = secs/3600; secs -= hrs*3600;
1416 int mins = secs/60; secs -= mins*60;
1417 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1419 if( fmt_ctx->nb_programs > 0 )
1420 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
1421 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
1422 report("program %d", i+1);
1423 AVProgram *pgrm = fmt_ctx->programs[i];
1424 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1425 int idx = pgrm->stream_index[j];
1426 int vidx = ffvideo.size();
1427 while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
1429 report(", vid%d", vidx);
1432 int aidx = ffaudio.size();
1433 while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
1435 report(", aud%d", aidx);
1438 report(", (%d)", pgrm->stream_index[j]);
1443 AVDictionaryEntry *tag = 0;
1444 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
1445 report("%s=%s\n", tag->key, tag->value);
1454 int FFMPEG::init_decoder(const char *filename)
1456 ff_lock("FFMPEG::init_decoder");
1458 char file_opts[BCTEXTLEN];
1459 char *bp = strrchr(strcpy(file_opts, filename), '/');
1460 char *sp = strrchr(!bp ? file_opts : bp, '.');
1463 strcpy(sp, ".opts");
1464 fp = fopen(file_opts, "r");
1467 read_options(fp, file_opts, opts);
1471 load_options("decode.opts", opts);
1472 AVDictionary *fopts = 0;
1473 av_dict_copy(&fopts, opts, 0);
1474 int ret = avformat_open_input(&fmt_ctx, filename, NULL, &fopts);
1475 av_dict_free(&fopts);
1477 ret = avformat_find_stream_info(fmt_ctx, NULL);
1482 return !ret ? 0 : 1;
1485 int FFMPEG::open_decoder()
1488 if( stat(fmt_ctx->filename, &st) < 0 ) {
1489 eprintf("FFMPEG::open_decoder: can't stat file: %s\n",
1494 int64_t file_bits = 8 * st.st_size;
1495 if( !fmt_ctx->bit_rate && opt_duration > 0 )
1496 fmt_ctx->bit_rate = file_bits / opt_duration;
1499 if( fmt_ctx->bit_rate > 0 ) {
1500 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1501 AVStream *st = fmt_ctx->streams[i];
1502 if( st->duration != AV_NOPTS_VALUE ) continue;
1503 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
1504 st->duration = av_rescale(file_bits, st->time_base.den,
1505 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
1510 printf("FFMPEG::open_decoder: some stream times estimated\n");
1512 ff_lock("FFMPEG::open_decoder");
1514 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1515 AVStream *st = fmt_ctx->streams[i];
1516 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
1517 AVCodecContext *avctx = st->codec;
1518 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avctx->codec_id);
1519 if( !codec_desc ) continue;
1520 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1521 if( avctx->width < 1 ) continue;
1522 if( avctx->height < 1 ) continue;
1523 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
1524 if( framerate.num < 1 ) continue;
1526 int vidx = ffvideo.size();
1527 FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
1528 vstrm_index.append(ffidx(vidx, 0));
1529 ffvideo.append(vid);
1530 vid->width = avctx->width;
1531 vid->height = avctx->height;
1532 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
1533 double secs = to_secs(st->duration, st->time_base);
1534 vid->length = secs * vid->frame_rate;
1535 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
1536 vid->nudge = st->start_time;
1538 if( opt_video_filter )
1539 vid->create_filter(opt_video_filter, avctx,avctx);
1541 else if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1542 if( avctx->channels < 1 ) continue;
1543 if( avctx->sample_rate < 1 ) continue;
1545 int aidx = ffaudio.size();
1546 FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
1547 ffaudio.append(aud);
1548 aud->channel0 = astrm_index.size();
1549 aud->channels = avctx->channels;
1550 for( int ch=0; ch<aud->channels; ++ch )
1551 astrm_index.append(ffidx(aidx, ch));
1552 aud->sample_rate = avctx->sample_rate;
1553 double secs = to_secs(st->duration, st->time_base);
1554 aud->length = secs * aud->sample_rate;
1555 if( avctx->sample_fmt != AV_SAMPLE_FMT_FLT ) {
1556 uint64_t layout = av_get_default_channel_layout(avctx->channels);
1557 if( !layout ) layout = ((uint64_t)1<<aud->channels) - 1;
1558 aud->resample_context = swr_alloc_set_opts(NULL,
1559 layout, AV_SAMPLE_FMT_FLT, avctx->sample_rate,
1560 layout, avctx->sample_fmt, avctx->sample_rate,
1562 swr_init(aud->resample_context);
1564 aud->nudge = st->start_time;
1566 if( opt_audio_filter )
1567 aud->create_filter(opt_audio_filter, avctx,avctx);
1571 printf("FFMPEG::open_decoder: some stream have bad times\n");
1577 int FFMPEG::init_encoder(const char *filename)
1579 int fd = ::open(filename,O_WRONLY);
1580 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
1582 eprintf("FFMPEG::init_encoder: bad file path: %s\n", filename);
1586 int ret = get_file_format();
1588 eprintf("FFMPEG::init_encoder: bad file format: %s\n", filename);
1592 eprintf("FFMPEG::init_encoder: mismatch audio/video file format: %s\n", filename);
1595 ff_lock("FFMPEG::init_encoder");
1597 avformat_alloc_output_context2(&fmt_ctx, 0, file_format, filename);
1599 eprintf("FFMPEG::init_encoder: failed: %s\n", filename);
1604 load_options("encode.opts", opts);
1610 int FFMPEG::open_encoder(const char *type, const char *spec)
1613 Asset *asset = file_base->asset;
1614 char *filename = asset->path;
1615 AVDictionary *sopts = 0;
1616 av_dict_copy(&sopts, opts, 0);
1617 char option_path[BCTEXTLEN];
1618 set_option_path(option_path, "%s/%s.opts", type, type);
1619 read_options(option_path, sopts);
1620 get_option_path(option_path, type, spec);
1621 char format_name[BCSTRLEN], codec_name[BCTEXTLEN];
1622 char bsfilter[BCSTRLEN], bsargs[BCTEXTLEN];
1623 if( get_encoder(option_path, format_name, codec_name, bsfilter, bsargs) ) {
1624 eprintf("FFMPEG::open_encoder: get_encoder failed %s:%s\n",
1625 option_path, filename);
1629 if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
1630 else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
1631 else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
1634 ff_lock("FFMPEG::open_encoder");
1638 const AVCodecDescriptor *codec_desc = 0;
1639 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
1641 eprintf("FFMPEG::open_encoder: cant find codec %s:%s\n",
1642 codec_name, filename);
1646 codec_desc = avcodec_descriptor_get(codec->id);
1648 eprintf("FFMPEG::open_encoder: unknown codec %s:%s\n",
1649 codec_name, filename);
1654 st = avformat_new_stream(fmt_ctx, 0);
1656 eprintf("FFMPEG::open_encoder: cant create stream %s:%s\n",
1657 codec_name, filename);
1662 AVCodecContext *ctx = st->codec;
1663 switch( codec_desc->type ) {
1664 case AVMEDIA_TYPE_AUDIO: {
1666 eprintf("FFMPEG::open_encoder: duplicate audio %s:%s\n",
1667 codec_name, filename);
1672 if( scan_options(asset->ff_audio_options, sopts, st) ) {
1673 eprintf("FFMPEG::open_encoder: bad audio options %s:%s\n",
1674 codec_name, filename);
1678 if( asset->ff_audio_bitrate > 0 ) {
1679 ctx->bit_rate = asset->ff_audio_bitrate;
1681 sprintf(arg, "%d", asset->ff_audio_bitrate);
1682 av_dict_set(&sopts, "b", arg, 0);
1684 int aidx = ffaudio.size();
1685 int fidx = aidx + ffvideo.size();
1686 FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
1687 ffaudio.append(aud); fst = aud;
1688 aud->sample_rate = asset->sample_rate;
1689 ctx->channels = aud->channels = asset->channels;
1690 for( int ch=0; ch<aud->channels; ++ch )
1691 astrm_index.append(ffidx(aidx, ch));
1692 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
1693 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
1694 if( !ctx->sample_rate ) {
1695 eprintf("FFMPEG::open_encoder:"
1696 " check_sample_rate failed %s\n", filename);
1700 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
1701 ctx->sample_fmt = codec->sample_fmts[0];
1702 uint64_t layout = av_get_default_channel_layout(ctx->channels);
1703 aud->resample_context = swr_alloc_set_opts(NULL,
1704 layout, ctx->sample_fmt, aud->sample_rate,
1705 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
1707 swr_init(aud->resample_context);
1710 case AVMEDIA_TYPE_VIDEO: {
1712 eprintf("FFMPEG::open_encoder: duplicate video %s:%s\n",
1713 codec_name, filename);
1718 if( scan_options(asset->ff_video_options, sopts, st) ) {
1719 eprintf("FFMPEG::open_encoder: bad video options %s:%s\n",
1720 codec_name, filename);
1724 if( asset->ff_video_bitrate > 0 ) {
1725 ctx->bit_rate = asset->ff_video_bitrate;
1727 sprintf(arg, "%d", asset->ff_video_bitrate);
1728 av_dict_set(&sopts, "b", arg, 0);
1730 else if( asset->ff_video_quality > 0 ) {
1731 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
1732 ctx->qmin = ctx->qmax = asset->ff_video_quality;
1733 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
1734 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
1735 ctx->flags |= CODEC_FLAG_QSCALE;
1737 av_dict_set(&sopts, "flags", "+qscale", 0);
1738 sprintf(arg, "%d", asset->ff_video_quality);
1739 av_dict_set(&sopts, "qscale", arg, 0);
1740 sprintf(arg, "%d", ctx->global_quality);
1741 av_dict_set(&sopts, "global_quality", arg, 0);
1743 int vidx = ffvideo.size();
1744 int fidx = vidx + ffaudio.size();
1745 FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
1746 vstrm_index.append(ffidx(vidx, 0));
1747 ffvideo.append(vid); fst = vid;
1748 vid->width = asset->width;
1749 ctx->width = (vid->width+3) & ~3;
1750 vid->height = asset->height;
1751 ctx->height = (vid->height+3) & ~3;
1752 vid->frame_rate = asset->frame_rate;
1753 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
1754 ctx->pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
1755 AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
1756 if( !frame_rate.num || !frame_rate.den ) {
1757 eprintf("FFMPEG::open_encoder:"
1758 " check_frame_rate failed %s\n", filename);
1762 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
1763 st->time_base = ctx->time_base;
1767 eprintf("FFMPEG::open_encoder: not audio/video, %s:%s\n",
1768 codec_name, filename);
1773 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
1774 st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
1776 ret = avcodec_open2(st->codec, codec, &sopts);
1778 ff_err(ret,"FFMPEG::open_encoder");
1779 eprintf("FFMPEG::open_encoder: open failed %s:%s\n",
1780 codec_name, filename);
1787 if( fst && bsfilter[0] )
1788 fst->add_bsfilter(bsfilter, !bsargs[0] ? 0 : bsargs);
1794 av_dict_free(&sopts);
1798 int FFMPEG::close_encoder()
1801 if( encoding > 0 ) {
1802 av_write_trailer(fmt_ctx);
1803 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
1804 avio_closep(&fmt_ctx->pb);
1810 int FFMPEG::decode_activate()
1812 if( decoding < 0 ) {
1814 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
1815 ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
1816 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
1817 ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
1818 // set nudges for each program stream set
1819 int npgrms = fmt_ctx->nb_programs;
1820 for( int i=0; i<npgrms; ++i ) {
1821 AVProgram *pgrm = fmt_ctx->programs[i];
1822 // first start time video stream
1823 int64_t vstart_time = -1, astart_time = -1;
1824 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1825 int fidx = pgrm->stream_index[j];
1826 AVStream *st = fmt_ctx->streams[fidx];
1827 AVCodecContext *avctx = st->codec;
1828 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1829 if( st->start_time == AV_NOPTS_VALUE ) continue;
1830 if( vstart_time > st->start_time ) continue;
1831 vstart_time = st->start_time;
1834 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1835 if( st->start_time == AV_NOPTS_VALUE ) continue;
1836 if( astart_time > st->start_time ) continue;
1837 astart_time = st->start_time;
1841 // match program streams to max start_time
1842 int64_t nudge = vstart_time > astart_time ? vstart_time : astart_time;
1843 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1844 int fidx = pgrm->stream_index[j];
1845 AVStream *st = fmt_ctx->streams[fidx];
1846 AVCodecContext *avctx = st->codec;
1847 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1848 for( int k=0; k<ffvideo.size(); ++k ) {
1849 if( ffvideo[k]->fidx != fidx ) continue;
1850 ffvideo[k]->nudge = nudge;
1854 if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1855 for( int k=0; k<ffaudio.size(); ++k ) {
1856 if( ffaudio[k]->fidx != fidx ) continue;
1857 ffaudio[k]->nudge = nudge;
1863 // set nudges for any streams not yet set
1864 int64_t vstart_time = 0, astart_time = 0;
1865 int nstreams = fmt_ctx->nb_streams;
1866 for( int i=0; i<nstreams; ++i ) {
1867 AVStream *st = fmt_ctx->streams[i];
1868 AVCodecContext *avctx = st->codec;
1869 switch( avctx->codec_type ) {
1870 case AVMEDIA_TYPE_VIDEO: {
1871 if( st->start_time == AV_NOPTS_VALUE ) continue;
1872 int vidx = ffvideo.size();
1873 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
1874 if( vidx >= 0 && ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
1875 if( vstart_time >= st->start_time ) continue;
1876 vstart_time = st->start_time;
1878 case AVMEDIA_TYPE_AUDIO: {
1879 if( st->start_time == AV_NOPTS_VALUE ) continue;
1880 int aidx = ffaudio.size();
1881 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
1882 if( aidx >= 0 && ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
1883 if( astart_time >= st->start_time ) continue;
1884 astart_time = st->start_time;
1889 int64_t nudge = vstart_time > astart_time ? vstart_time : astart_time;
1890 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
1891 if( ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
1892 ffvideo[vidx]->nudge = nudge;
1894 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
1895 if( ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
1896 ffaudio[aidx]->nudge = nudge;
1903 int FFMPEG::encode_activate()
1906 if( encoding < 0 ) {
1908 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
1909 (ret=avio_open(&fmt_ctx->pb, fmt_ctx->filename, AVIO_FLAG_WRITE)) < 0 ) {
1910 ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
1915 AVDictionary *fopts = 0;
1916 char option_path[BCTEXTLEN];
1917 set_option_path(option_path, "format/%s", file_format);
1918 read_options(option_path, fopts);
1919 ret = avformat_write_header(fmt_ctx, &fopts);
1920 av_dict_free(&fopts);
1922 ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
1932 int FFMPEG::audio_seek(int stream, int64_t pos)
1934 int aidx = astrm_index[stream].st_idx;
1935 FFAudioStream *aud = ffaudio[aidx];
1936 aud->audio_seek(pos);
1940 int FFMPEG::video_seek(int stream, int64_t pos)
1942 int vidx = vstrm_index[stream].st_idx;
1943 FFVideoStream *vid = ffvideo[vidx];
1944 vid->video_seek(pos);
1949 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
1951 if( !has_audio || chn >= astrm_index.size() ) return -1;
1952 int aidx = astrm_index[chn].st_idx;
1953 FFAudioStream *aud = ffaudio[aidx];
1954 if( aud->load(pos, len) < len ) return -1;
1955 int ch = astrm_index[chn].st_ch;
1956 int ret = aud->read(samples,len,ch);
1960 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
1962 if( !has_video || layer >= vstrm_index.size() ) return -1;
1963 int vidx = vstrm_index[layer].st_idx;
1964 FFVideoStream *vid = ffvideo[vidx];
1965 return vid->load(vframe, pos);
1969 int FFMPEG::encode(int stream, double **samples, int len)
1971 FFAudioStream *aud = ffaudio[stream];
1972 return aud->encode(samples, len);
1976 int FFMPEG::encode(int stream, VFrame *frame)
1978 FFVideoStream *vid = ffvideo[stream];
1979 return vid->encode(frame);
1982 void FFMPEG::start_muxer()
1990 void FFMPEG::stop_muxer()
1999 void FFMPEG::flow_off()
2002 flow_lock->lock("FFMPEG::flow_off");
2006 void FFMPEG::flow_on()
2010 flow_lock->unlock();
2013 void FFMPEG::flow_ctl()
2016 flow_lock->lock("FFMPEG::flow_ctl");
2017 flow_lock->unlock();
2021 int FFMPEG::mux_audio(FFrame *frm)
2024 FFStream *fst = frm->fst;
2025 AVCodecContext *ctx = fst->st->codec;
2026 AVFrame *frame = *frm;
2027 AVRational tick_rate = {1, ctx->sample_rate};
2028 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
2030 int ret = fst->encode_frame(pkt, frame, got_packet);
2031 if( ret >= 0 && got_packet )
2032 ret = fst->write_packet(pkt);
2034 ff_err(ret, "FFMPEG::mux_audio");
2035 return ret >= 0 ? 0 : 1;
2038 int FFMPEG::mux_video(FFrame *frm)
2041 FFStream *fst = frm->fst;
2042 AVFrame *frame = *frm;
2043 frame->pts = frm->position;
2045 int ret = fst->encode_frame(pkt, frame, got_packet);
2046 if( ret >= 0 && got_packet )
2047 ret = fst->write_packet(pkt);
2049 ff_err(ret, "FFMPEG::mux_video");
2050 return ret >= 0 ? 0 : 1;
2056 double atm = -1, vtm = -1;
2057 FFrame *afrm = 0, *vfrm = 0;
2059 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
2060 FFStream *fst = ffaudio[i];
2061 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
2062 FFrame *frm = fst->frms.first;
2063 if( !frm ) { if( !done ) return; continue; }
2064 double tm = to_secs(frm->position, fst->st->codec->time_base);
2065 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
2067 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
2068 FFStream *fst = ffvideo[i];
2069 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
2070 FFrame *frm = fst->frms.first;
2071 if( !frm ) { if( !done ) return; continue; }
2072 double tm = to_secs(frm->position, fst->st->codec->time_base);
2073 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
2075 if( !demand ) flow_off();
2076 if( !afrm && !vfrm ) break;
2077 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
2078 vfrm->position, vfrm->fst->st->codec->time_base,
2079 afrm->position, afrm->fst->st->codec->time_base);
2080 FFrame *frm = v <= 0 ? vfrm : afrm;
2081 if( frm == afrm ) mux_audio(frm);
2082 if( frm == vfrm ) mux_video(frm);
2091 mux_lock->lock("FFMPEG::run");
2095 for( int i=0; i<ffaudio.size(); ++i )
2096 ffaudio[i]->flush();
2097 for( int i=0; i<ffvideo.size(); ++i )
2098 ffvideo[i]->flush();
2102 int FFMPEG::ff_total_audio_channels()
2104 return astrm_index.size();
2107 int FFMPEG::ff_total_astreams()
2109 return ffaudio.size();
2112 int FFMPEG::ff_audio_channels(int stream)
2114 return ffaudio[stream]->channels;
2117 int FFMPEG::ff_sample_rate(int stream)
2119 return ffaudio[stream]->sample_rate;
2122 const char* FFMPEG::ff_audio_format(int stream)
2124 AVStream *st = ffaudio[stream]->st;
2125 AVCodecID id = st->codec->codec_id;
2126 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2127 return desc ? desc->name : "Unknown";
2130 int FFMPEG::ff_audio_pid(int stream)
2132 return ffaudio[stream]->st->id;
2135 int64_t FFMPEG::ff_audio_samples(int stream)
2137 return ffaudio[stream]->length;
2140 // find audio astream/channels with this program,
2141 // or all program audio channels (astream=-1)
2142 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
2146 int vidx = ffvideo[vstream]->fidx;
2147 // find first program with this video stream
2148 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
2149 AVProgram *pgrm = fmt_ctx->programs[i];
2150 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
2151 int st_idx = pgrm->stream_index[j];
2152 AVStream *st = fmt_ctx->streams[st_idx];
2153 if( st->codec->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
2154 if( st_idx == vidx ) pidx = i;
2157 if( pidx < 0 ) return -1;
2159 int64_t channels = 0;
2160 AVProgram *pgrm = fmt_ctx->programs[pidx];
2161 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2162 int aidx = pgrm->stream_index[j];
2163 AVStream *st = fmt_ctx->streams[aidx];
2164 if( st->codec->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
2165 if( astream > 0 ) { --astream; continue; }
2167 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
2168 if( ffaudio[i]->fidx == aidx ) astrm = i;
2170 if( ret < 0 ) ret = astrm;
2171 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
2172 channels |= mask << ffaudio[astrm]->channel0;
2174 if( !astream ) break;
2176 channel_mask = channels;
2181 int FFMPEG::ff_total_video_layers()
2183 return vstrm_index.size();
2186 int FFMPEG::ff_total_vstreams()
2188 return ffvideo.size();
2191 int FFMPEG::ff_video_width(int stream)
2193 return ffvideo[stream]->width;
2196 int FFMPEG::ff_video_height(int stream)
2198 return ffvideo[stream]->height;
2201 int FFMPEG::ff_set_video_width(int stream, int width)
2203 int w = ffvideo[stream]->width;
2204 ffvideo[stream]->width = width;
2208 int FFMPEG::ff_set_video_height(int stream, int height)
2210 int h = ffvideo[stream]->height;
2211 ffvideo[stream]->height = height;
2215 int FFMPEG::ff_coded_width(int stream)
2217 AVStream *st = ffvideo[stream]->st;
2218 return st->codec->coded_width;
2221 int FFMPEG::ff_coded_height(int stream)
2223 AVStream *st = ffvideo[stream]->st;
2224 return st->codec->coded_height;
2227 float FFMPEG::ff_aspect_ratio(int stream)
2229 return ffvideo[stream]->aspect_ratio;
2232 const char* FFMPEG::ff_video_format(int stream)
2234 AVStream *st = ffvideo[stream]->st;
2235 AVCodecID id = st->codec->codec_id;
2236 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2237 return desc ? desc->name : "Unknown";
2240 double FFMPEG::ff_frame_rate(int stream)
2242 return ffvideo[stream]->frame_rate;
2245 int64_t FFMPEG::ff_video_frames(int stream)
2247 return ffvideo[stream]->length;
2250 int FFMPEG::ff_video_pid(int stream)
2252 return ffvideo[stream]->st->id;
2256 int FFMPEG::ff_cpus()
2258 return file_base->file->cpus;
2261 int FFVideoStream::create_filter(const char *filter_spec,
2262 AVCodecContext *src_ctx, AVCodecContext *sink_ctx)
2264 avfilter_register_all();
2265 AVFilter *filter = avfilter_get_by_name(filter_spec);
2266 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_VIDEO ) {
2267 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
2270 filter_graph = avfilter_graph_alloc();
2271 AVFilter *buffersrc = avfilter_get_by_name("buffer");
2272 AVFilter *buffersink = avfilter_get_by_name("buffersink");
2274 int ret = 0; char args[BCTEXTLEN];
2275 snprintf(args, sizeof(args),
2276 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
2277 src_ctx->width, src_ctx->height, src_ctx->pix_fmt,
2278 src_ctx->time_base.num, src_ctx->time_base.den,
2279 src_ctx->sample_aspect_ratio.num, src_ctx->sample_aspect_ratio.den);
2281 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2282 args, NULL, filter_graph);
2284 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2285 NULL, NULL, filter_graph);
2287 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
2288 (uint8_t*)&sink_ctx->pix_fmt, sizeof(sink_ctx->pix_fmt),
2289 AV_OPT_SEARCH_CHILDREN);
2291 ff_err(ret, "FFVideoStream::create_filter");
2293 ret = FFStream::create_filter(filter_spec);
2294 return ret >= 0 ? 0 : 1;
2297 int FFAudioStream::create_filter(const char *filter_spec,
2298 AVCodecContext *src_ctx, AVCodecContext *sink_ctx)
2300 avfilter_register_all();
2301 AVFilter *filter = avfilter_get_by_name(filter_spec);
2302 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_AUDIO ) {
2303 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
2306 filter_graph = avfilter_graph_alloc();
2307 AVFilter *buffersrc = avfilter_get_by_name("abuffer");
2308 AVFilter *buffersink = avfilter_get_by_name("abuffersink");
2309 int ret = 0; char args[BCTEXTLEN];
2310 snprintf(args, sizeof(args),
2311 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
2312 src_ctx->time_base.num, src_ctx->time_base.den, src_ctx->sample_rate,
2313 av_get_sample_fmt_name(src_ctx->sample_fmt), src_ctx->channel_layout);
2315 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2316 args, NULL, filter_graph);
2318 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2319 NULL, NULL, filter_graph);
2321 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
2322 (uint8_t*)&sink_ctx->sample_fmt, sizeof(sink_ctx->sample_fmt),
2323 AV_OPT_SEARCH_CHILDREN);
2325 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
2326 (uint8_t*)&sink_ctx->channel_layout,
2327 sizeof(sink_ctx->channel_layout), AV_OPT_SEARCH_CHILDREN);
2329 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
2330 (uint8_t*)&sink_ctx->sample_rate, sizeof(sink_ctx->sample_rate),
2331 AV_OPT_SEARCH_CHILDREN);
2333 ff_err(ret, "FFAudioStream::create_filter");
2335 ret = FFStream::create_filter(filter_spec);
2336 return ret >= 0 ? 0 : 1;
2339 int FFStream::create_filter(const char *filter_spec)
2341 /* Endpoints for the filter graph. */
2342 AVFilterInOut *outputs = avfilter_inout_alloc();
2343 outputs->name = av_strdup("in");
2344 outputs->filter_ctx = buffersrc_ctx;
2345 outputs->pad_idx = 0;
2348 AVFilterInOut *inputs = avfilter_inout_alloc();
2349 inputs->name = av_strdup("out");
2350 inputs->filter_ctx = buffersink_ctx;
2351 inputs->pad_idx = 0;
2354 int ret = !outputs->name || !inputs->name ? -1 : 0;
2356 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
2357 &inputs, &outputs, NULL);
2359 ret = avfilter_graph_config(filter_graph, NULL);
2362 ff_err(ret, "FFStream::create_filter");
2363 avfilter_inout_free(&inputs);
2364 avfilter_inout_free(&outputs);
2368 void FFStream::add_bsfilter(const char *bsf, const char *ap)
2370 bsfilter.append(new BSFilter(bsf,ap));
2373 int FFStream::bs_filter(AVPacket *pkt)
2375 if( !bsfilter.size() ) return 0;
2376 av_packet_split_side_data(pkt);
2379 for( int i=0; i<bsfilter.size(); ++i ) {
2380 AVPacket bspkt = *pkt;
2381 ret = av_bitstream_filter_filter(bsfilter[i]->bsfc,
2382 st->codec, bsfilter[i]->args, &bspkt.data, &bspkt.size,
2383 pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY);
2384 if( ret < 0 ) break;
2385 int size = bspkt.size;
2386 uint8_t *data = bspkt.data;
2387 if( !ret && bspkt.data != pkt->data ) {
2389 data = (uint8_t *)av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
2390 if( !data ) { ret = AVERROR(ENOMEM); break; }
2391 memcpy(data, bspkt.data, size);
2392 memset(data+size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2396 pkt->side_data = 0; pkt->side_data_elems = 0;
2397 av_packet_unref(pkt);
2398 ret = av_packet_from_data(&bspkt, data, size);
2399 if( ret < 0 ) break;
2404 ff_err(ret,"FFStream::bs_filter");
2408 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
2411 av_init_packet(&pkt);
2412 AVFrame *frame = av_frame_alloc();
2414 fprintf(stderr, "FFMPEG::scan: av_frame_alloc failed\n");
2418 index_state->add_video_markers(ffvideo.size());
2419 index_state->add_audio_markers(ffaudio.size());
2421 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2422 AVDictionary *copts = 0;
2423 av_dict_copy(&copts, opts, 0);
2424 AVStream *st = fmt_ctx->streams[i];
2425 AVCodecID codec_id = st->codec->codec_id;
2426 AVCodec *decoder = avcodec_find_decoder(codec_id);
2427 if( avcodec_open2(st->codec, decoder, &copts) < 0 )
2428 fprintf(stderr, "FFMPEG::scan: codec open failed\n");
2429 av_dict_free(&copts);
2432 for( int64_t count=0; !*canceled; ++count ) {
2433 av_packet_unref(&pkt);
2434 pkt.data = 0; pkt.size = 0;
2436 int ret = av_read_frame(fmt_ctx, &pkt);
2438 if( ret == AVERROR_EOF ) break;
2439 if( ++errs > 100 ) {
2440 ff_err(ret, "over 100 read_frame errs\n");
2445 if( !pkt.data ) continue;
2446 int i = pkt.stream_index;
2447 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
2448 AVStream *st = fmt_ctx->streams[i];
2449 AVCodecContext *avctx = st->codec;
2450 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
2452 switch( avctx->codec_type ) {
2453 case AVMEDIA_TYPE_VIDEO: {
2454 int vidx = ffvideo.size();
2455 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
2456 if( vidx < 0 ) break;
2457 FFVideoStream *vid = ffvideo[vidx];
2458 int64_t tstmp = pkt.dts;
2459 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.pts;
2460 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
2461 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
2462 double secs = to_secs(tstmp, st->time_base);
2463 int64_t frm = secs * vid->frame_rate + 0.5;
2464 if( frm < 0 ) frm = 0;
2465 index_state->put_video_mark(vidx, frm, pkt.pos);
2468 while( pkt.size > 0 ) {
2469 av_frame_unref(frame);
2471 int ret = vid->decode_frame(&pkt, frame, got_frame);
2472 if( ret <= 0 ) break;
2473 // if( got_frame ) {}
2479 case AVMEDIA_TYPE_AUDIO: {
2480 int aidx = ffaudio.size();
2481 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
2482 if( aidx < 0 ) break;
2483 FFAudioStream *aud = ffaudio[aidx];
2484 int64_t tstmp = pkt.pts;
2485 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
2486 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
2487 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
2488 double secs = to_secs(tstmp, st->time_base);
2489 int64_t sample = secs * aud->sample_rate + 0.5;
2490 if( sample < 0 ) sample = 0;
2491 index_state->put_audio_mark(aidx, sample, pkt.pos);
2493 while( pkt.size > 0 ) {
2494 int ch = aud->channel0, nch = aud->channels;
2495 int64_t pos = index_state->pos(ch);
2496 if( pos != aud->curr_pos ) {
2497 if( abs(pos-aud->curr_pos) > 1 )
2498 printf("audio%d pad %ld %ld (%ld)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
2499 index_state->pad_data(ch, nch, aud->curr_pos);
2501 av_frame_unref(frame);
2503 int ret = aud->decode_frame(&pkt, frame, got_frame);
2504 if( ret <= 0 ) break;
2505 if( got_frame && frame->channels == nch ) {
2507 int len = aud->get_samples(samples,
2508 &frame->extended_data[0], frame->nb_samples);
2509 for( int i=0; i<nch; ++i )
2510 index_state->put_data(ch+i,nch,samples+i,len);
2511 aud->curr_pos += len;
2520 av_frame_free(&frame);
2524 void FFStream::load_markers(IndexMarks &marks, double rate)
2526 index_markers = &marks;
2528 int64_t sz = marks.size();
2529 int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
2530 int nb_ent = st->nb_index_entries;
2531 // some formats already have an index
2533 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
2534 int64_t tstmp = ep->timestamp;
2535 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
2536 double secs = ffmpeg->to_secs(tstmp, st->time_base);
2537 int64_t no = secs * rate;
2538 while( in < sz && marks[in].no <= no ) ++in;
2540 int64_t len = sz - in;
2541 int64_t count = max_entries - nb_ent;
2542 if( count > len ) count = len;
2543 for( int i=0; i<count; ++i ) {
2544 int k = in + i * len / count;
2545 int64_t no = marks[k].no, pos = marks[k].pos;
2546 double secs = (double)no / rate;
2547 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
2548 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
2549 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);