10 // work arounds (centos)
13 #define INT64_MAX 9223372036854775807LL
17 #include "bccmodels.h"
18 #include "fileffmpeg.h"
21 #include "indexfile.h"
24 #include "mainerror.h"
29 #define VIDEO_INBUF_SIZE 0x10000
30 #define AUDIO_INBUF_SIZE 0x10000
31 #define VIDEO_REFILL_THRESH 0
32 #define AUDIO_REFILL_THRESH 0x1000
34 Mutex FFMPEG::fflock("FFMPEG::fflock");
36 static void ff_err(int ret, const char *fmt, ...)
41 vsnprintf(msg, sizeof(msg), fmt, ap);
43 char errmsg[BCSTRLEN];
44 av_strerror(ret, errmsg, sizeof(errmsg));
45 fprintf(stderr,_("%s err: %s\n"),msg, errmsg);
61 pkt.data = 0; pkt.size = 0;
64 FFrame::FFrame(FFStream *fst)
67 frm = av_frame_alloc();
68 init = fst->init_frame(frm);
76 void FFrame::queue(int64_t pos)
82 void FFrame::dequeue()
87 int FFAudioStream::read(float *fp, long len)
95 while( --k >= 0 ) *fp++ = *op++;
96 if( op >= lmt ) op = bfr;
101 void FFAudioStream::realloc(long nsz, int nch, long len)
103 long bsz = nsz * nch;
104 float *np = new float[bsz];
105 inp = np + read(np, len) * nch;
110 delete [] bfr; bfr = np;
113 void FFAudioStream::realloc(long nsz, int nch)
115 if( nsz > sz || this->nch != nch ) {
116 long len = this->nch != nch ? 0 : hpos;
117 if( len > sz ) len = sz;
119 realloc(nsz, nch, len);
123 void FFAudioStream::reserve(long nsz, int nch)
125 long len = (inp - outp) / nch;
127 if( nsz > sz || this->nch != nch ) {
128 if( this->nch != nch ) len = 0;
129 realloc(nsz, nch, len);
132 if( (len*=nch) > 0 && bfr != outp )
133 memmove(bfr, outp, len*sizeof(*bfr));
138 long FFAudioStream::used()
140 long len = inp>=outp ? inp-outp : inp-bfr + lmt-outp;
143 long FFAudioStream::avail()
146 if( in1 >= lmt ) in1 = bfr;
147 long len = outp >= in1 ? outp-in1 : outp-bfr + lmt-in1;
150 void FFAudioStream::reset_history()
156 void FFAudioStream::iseek(int64_t ofs)
158 outp = inp - ofs*nch;
159 if( outp < bfr ) outp += sz*nch;
162 float *FFAudioStream::get_outp(int ofs)
169 int64_t FFAudioStream::put_inp(int ofs)
172 return (inp-outp) / nch;
175 int FFAudioStream::write(const float *fp, long len)
183 while( --k >= 0 ) *ip++ = *fp++;
184 if( ip >= lmt ) ip = bfr;
191 int FFAudioStream::zero(long len)
199 while( --k >= 0 ) *ip++ = 0;
200 if( ip >= lmt ) ip = bfr;
207 // does not advance outp
208 int FFAudioStream::read(double *dp, long len, int ch)
211 float *op = outp + ch;
212 float *lmt1 = lmt + nch-1;
214 int k = (lmt1 - op) / nch;
217 while( --k >= 0 ) { *dp++ = *op; op += nch; }
218 if( op >= lmt ) op -= sz*nch;
223 // load linear buffer, no wrapping allowed, does not advance inp
224 int FFAudioStream::write(const double *dp, long len, int ch)
227 float *ip = inp + ch;
228 while( --n >= 0 ) { *ip = *dp++; ip += nch; }
233 FFStream::FFStream(FFMPEG *ffmpeg, AVStream *st, int fidx)
235 this->ffmpeg = ffmpeg;
238 frm_lock = new Mutex("FFStream::frm_lock");
244 nudge = AV_NOPTS_VALUE;
245 seek_pos = curr_pos = 0;
248 reading = writing = 0;
254 FFStream::~FFStream()
256 if( reading > 0 || writing > 0 ) avcodec_close(st->codec);
257 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
258 while( frms.first ) frms.remove(frms.first);
259 if( filter_graph ) avfilter_graph_free(&filter_graph);
260 if( frame ) av_frame_free(&frame);
261 if( fframe ) av_frame_free(&fframe);
262 bsfilter.remove_all_objects();
266 void FFStream::ff_lock(const char *cp)
268 FFMPEG::fflock.lock(cp);
271 void FFStream::ff_unlock()
273 FFMPEG::fflock.unlock();
276 void FFStream::queue(FFrame *frm)
278 frm_lock->lock("FFStream::queue");
282 ffmpeg->mux_lock->unlock();
285 void FFStream::dequeue(FFrame *frm)
287 frm_lock->lock("FFStream::dequeue");
289 frms.remove_pointer(frm);
293 int FFStream::encode_activate()
296 writing = ffmpeg->encode_activate();
300 int FFStream::decode_activate()
302 if( reading < 0 && (reading=ffmpeg->decode_activate()) > 0 ) {
303 ff_lock("FFStream::decode_activate");
305 AVDictionary *copts = 0;
306 av_dict_copy(&copts, ffmpeg->opts, 0);
308 // this should be avformat_copy_context(), but no copy avail
309 ret = avformat_open_input(&fmt_ctx, ffmpeg->fmt_ctx->filename, NULL, &copts);
311 ret = avformat_find_stream_info(fmt_ctx, 0);
312 st = fmt_ctx->streams[fidx];
316 AVCodecID codec_id = st->codec->codec_id;
317 AVCodec *decoder = avcodec_find_decoder(codec_id);
318 ret = avcodec_open2(st->codec, decoder, &copts);
322 eprintf("FFStream::decode_activate: open decoder failed\n");
325 eprintf("FFStream::decode_activate: can't clone input file\n");
326 av_dict_free(&copts);
332 int FFStream::read_packet()
334 av_packet_unref(ipkt);
335 int ret = av_read_frame(fmt_ctx, ipkt);
338 if( ret == AVERROR_EOF ) {
339 ipkt->stream_index = st->index;
342 ff_err(ret, "FFStream::read_packet: av_read_frame failed\n");
349 int FFStream::decode(AVFrame *frame)
355 while( ret >= 0 && !flushed && --retries >= 0 && !got_frame ) {
358 if( (ret=read_packet()) < 0 ) break;
360 if( ipkt->stream_index == st->index ) {
361 while( (ipkt->size > 0 || !ipkt->data) && !got_frame ) {
362 ret = decode_frame(ipkt, frame, got_frame);
363 if( ret <= 0 || !ipkt->data ) break;
376 fprintf(stderr, "FFStream::decode: Retry limit\n");
380 fprintf(stderr, "FFStream::decode: failed\n");
385 int FFStream::load_filter(AVFrame *frame)
387 int ret = av_buffersrc_add_frame_flags(buffersrc_ctx,
388 frame, AV_BUFFERSRC_FLAG_KEEP_REF);
390 av_frame_unref(frame);
391 eprintf("FFStream::load_filter: av_buffersrc_add_frame_flags failed\n");
396 int FFStream::read_filter(AVFrame *frame)
398 int ret = av_buffersink_get_frame(buffersink_ctx, frame);
400 if( ret == AVERROR(EAGAIN) ) return 0;
401 if( ret == AVERROR_EOF ) { st_eof(1); return -1; }
402 ff_err(ret, "FFStream::read_filter: av_buffersink_get_frame failed\n");
408 int FFStream::read_frame(AVFrame *frame)
410 if( !filter_graph || !buffersrc_ctx || !buffersink_ctx )
411 return decode(frame);
412 if( !fframe && !(fframe=av_frame_alloc()) ) {
413 fprintf(stderr, "FFStream::read_frame: av_frame_alloc failed\n");
417 while( !flushed && !(ret=read_filter(frame)) ) {
418 if( (ret=decode(fframe)) < 0 ) break;
419 if( ret > 0 && (ret=load_filter(fframe)) < 0 ) break;
424 int FFStream::write_packet(FFPacket &pkt)
427 av_packet_rescale_ts(pkt, st->codec->time_base, st->time_base);
428 pkt->stream_index = st->index;
429 return av_interleaved_write_frame(ffmpeg->fmt_ctx, pkt);
432 int FFStream::flush()
438 ret = encode_frame(pkt, 0, got_packet);
439 if( ret < 0 || !got_packet ) break;
440 ret = write_packet(pkt);
443 ff_err(ret, "FFStream::flush");
444 return ret >= 0 ? 0 : 1;
447 int FFStream::seek(int64_t no, double rate)
450 // default ffmpeg native seek
452 int64_t pos = no, plmt = -1;
453 if( index_markers && index_markers->size() > 1 ) {
454 IndexMarks &marks = *index_markers;
455 int i = marks.find(pos);
456 int64_t n = i < 0 ? (i=0) : marks[i].no;
457 // if indexed seek point not too far away (<30 secs), use index
458 if( no-n < 30*rate ) {
465 double secs = pos / rate;
466 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
467 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
468 if( avformat_seek_file(fmt_ctx, st->index,
469 -INT64_MAX, tstmp, INT64_MAX, AVSEEK_FLAG_ANY) < 0 ) return -1;
470 avcodec_flush_buffers(st->codec);
471 need_packet = 0; flushed = 0;
472 seeked = 1; st_eof(0);
473 int64_t pkt_ts = AV_NOPTS_VALUE;
474 int ret = 1, retry = 1000;
476 // read up to retry packets, limited to npkts in stream, and not past pkt.pos plmt
477 while( ret > 0 && npkts > 0 && --retry >= 0 ) {
478 if( (ret=read_packet()) <= 0 ) break;
479 if( ipkt->stream_index != st->index ) continue;
480 if( (pkt_ts=ipkt->dts) == AV_NOPTS_VALUE ) pkt_ts = ipkt->pts;
481 if( pkt_ts != AV_NOPTS_VALUE && pkt_ts >= tstmp ) break;
482 if( plmt >= 0 && ipkt->pos >= plmt ) break;
486 if( ret <= 0 || retry < 0 ) return -1;
487 seek_pos = curr_pos = pos;
488 return npkts > 0 ? 1 : 0;
491 FFAudioStream::FFAudioStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
492 : FFStream(ffmpeg, strm, fidx)
495 channel0 = channels = 0;
499 resample_context = 0;
508 bfr = new float[bsz];
513 FFAudioStream::~FFAudioStream()
515 if( resample_context ) swr_free(&resample_context);
520 int FFAudioStream::get_samples(float *&samples, uint8_t **data, int len)
522 samples = *(float **)data;
523 if( resample_context ) {
524 if( len > aud_bfr_sz ) {
530 aud_bfr = new float[aud_bfr_sz*channels];
532 int ret = swr_convert(resample_context,
533 (uint8_t**)&aud_bfr, aud_bfr_sz, (const uint8_t**)data, len);
535 ff_err(ret, "FFAudioStream::get_samples: swr_convert failed\n");
544 int FFAudioStream::load_history(uint8_t **data, int len)
547 len = get_samples(samples, data, len);
549 // biggest user bfr since seek + frame
550 realloc(mbsz + len + 1, channels);
556 int FFAudioStream::decode_frame(AVPacket *pkt, AVFrame *frame, int &got_frame)
558 int first_frame = seeked; seeked = 0;
559 int ret = avcodec_decode_audio4(st->codec, frame, &got_frame, pkt);
561 if( first_frame ) return 0;
562 ff_err(ret, "FFAudioStream::decode_frame: Could not read audio frame\n");
566 int64_t pkt_ts = av_frame_get_best_effort_timestamp(frame);
567 if( pkt_ts != AV_NOPTS_VALUE )
568 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * sample_rate + 0.5;
573 int FFAudioStream::encode_activate()
575 if( writing >= 0 ) return writing;
576 AVCodecContext *ctx = st->codec;
577 frame_sz = ctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE ?
578 10000 : ctx->frame_size;
579 return FFStream::encode_activate();
582 int FFAudioStream::nb_samples()
584 AVCodecContext *ctx = st->codec;
585 return ctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE ?
586 10000 : ctx->frame_size;
589 int64_t FFAudioStream::load_buffer(double ** const sp, int len)
591 reserve(len+1, st->codec->channels);
592 for( int ch=0; ch<nch; ++ch )
593 write(sp[ch], len, ch);
597 int FFAudioStream::in_history(int64_t pos)
599 if( pos > curr_pos ) return 0;
601 if( len > sz ) len = sz;
602 if( pos < curr_pos - len ) return 0;
607 int FFAudioStream::init_frame(AVFrame *frame)
609 AVCodecContext *ctx = st->codec;
610 frame->nb_samples = frame_sz;
611 frame->format = ctx->sample_fmt;
612 frame->channel_layout = ctx->channel_layout;
613 frame->sample_rate = ctx->sample_rate;
614 int ret = av_frame_get_buffer(frame, 0);
616 ff_err(ret, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
620 int FFAudioStream::load(int64_t pos, int len)
622 if( audio_seek(pos) < 0 ) return -1;
623 if( !frame && !(frame=av_frame_alloc()) ) {
624 fprintf(stderr, "FFAudioStream::load: av_frame_alloc failed\n");
627 if( mbsz < len ) mbsz = len;
628 int64_t end_pos = pos + len;
630 for( int i=0; ret>=0 && !flushed && curr_pos<end_pos && i<1000; ++i ) {
631 ret = read_frame(frame);
633 load_history(&frame->extended_data[0], frame->nb_samples);
634 curr_pos += frame->nb_samples;
637 if( end_pos > curr_pos ) {
638 zero(end_pos - curr_pos);
641 len = curr_pos - pos;
646 int FFAudioStream::audio_seek(int64_t pos)
648 if( decode_activate() < 0 ) return -1;
649 if( !st->codec || !st->codec->codec ) return -1;
650 if( in_history(pos) ) return 0;
651 if( pos == curr_pos ) return 0;
652 reset_history(); mbsz = 0;
653 // guarentee preload > 1sec samples
654 if( seek(pos-sample_rate, sample_rate) < 0 ) return -1;
658 int FFAudioStream::encode(double **samples, int len)
660 if( encode_activate() <= 0 ) return -1;
663 int64_t count = load_buffer(samples, len);
666 while( ret >= 0 && count >= frame_sz ) {
667 frm = new FFrame(this);
668 if( (ret=frm->initted()) < 0 ) break;
669 AVFrame *frame = *frm;
670 float *bfrp = get_outp(frame_sz);
671 ret = swr_convert(resample_context,
672 (uint8_t **)frame->extended_data, frame_sz,
673 (const uint8_t **)&bfrp, frame_sz);
675 ff_err(ret, "FFAudioStream::encode: swr_convert failed\n");
678 frm->queue(curr_pos);
680 curr_pos += frame_sz;
685 return ret >= 0 ? 0 : 1;
688 int FFAudioStream::encode_frame(AVPacket *pkt, AVFrame *frame, int &got_packet)
690 int ret = avcodec_encode_audio2(st->codec, pkt, frame, &got_packet);
692 ff_err(ret, "FFAudioStream::encode_frame: encode audio failed\n");
698 void FFAudioStream::load_markers()
700 IndexState *index_state = ffmpeg->file_base->asset->index_state;
701 if( !index_state || idx >= index_state->audio_markers.size() ) return;
702 FFStream::load_markers(*index_state->audio_markers[idx], sample_rate);
705 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
706 : FFStream(ffmpeg, strm, fidx)
716 FFVideoStream::~FFVideoStream()
718 if( convert_ctx ) sws_freeContext(convert_ctx);
721 int FFVideoStream::decode_frame(AVPacket *pkt, AVFrame *frame, int &got_frame)
723 int first_frame = seeked; seeked = 0;
724 int ret = avcodec_decode_video2(st->codec, frame, &got_frame, pkt);
726 if( first_frame ) return 0;
727 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame\n");
731 int64_t pkt_ts = av_frame_get_best_effort_timestamp(frame);
732 if( pkt_ts != AV_NOPTS_VALUE )
733 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * frame_rate + 0.5;
738 int FFVideoStream::load(VFrame *vframe, int64_t pos)
740 int ret = video_seek(pos);
741 if( ret < 0 ) return -1;
742 if( !frame && !(frame=av_frame_alloc()) ) {
743 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
746 for( int i=0; ret>=0 && !flushed && curr_pos<=pos && i<1000; ++i ) {
747 ret = read_frame(frame);
748 if( ret > 0 ) ++curr_pos;
751 AVCodecContext *ctx = st->codec;
752 ret = convert_cmodel(vframe, (AVPicture *)frame,
753 ctx->pix_fmt, ctx->width, ctx->height);
755 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
759 int FFVideoStream::video_seek(int64_t pos)
761 if( decode_activate() < 0 ) return -1;
762 if( !st->codec || !st->codec->codec ) return -1;
763 if( pos == curr_pos-1 && !seeked ) return 0;
764 // if close enough, just read up to current
765 int gop = st->codec->gop_size;
766 if( gop < 4 ) gop = 4;
767 if( gop > 64 ) gop = 64;
768 int read_limit = curr_pos + 3*gop;
769 if( pos >= curr_pos && pos <= read_limit ) return 0;
770 // guarentee preload more than 2*gop frames
771 if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
775 int FFVideoStream::init_frame(AVFrame *picture)
777 AVCodecContext *ctx = st->codec;
778 picture->format = ctx->pix_fmt;
779 picture->width = ctx->width;
780 picture->height = ctx->height;
781 int ret = av_frame_get_buffer(picture, 32);
785 int FFVideoStream::encode(VFrame *vframe)
787 if( encode_activate() <= 0 ) return -1;
789 FFrame *picture = new FFrame(this);
790 int ret = picture->initted();
792 AVFrame *frame = *picture;
793 frame->pts = curr_pos;
794 AVCodecContext *ctx = st->codec;
795 ret = convert_pixfmt(vframe, (AVPicture*)frame,
796 ctx->pix_fmt, ctx->width, ctx->height);
799 picture->queue(curr_pos);
803 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
806 return ret >= 0 ? 0 : 1;
809 int FFVideoStream::encode_frame(AVPacket *pkt, AVFrame *frame, int &got_packet)
811 int ret = avcodec_encode_video2(st->codec, pkt, frame, &got_packet);
813 ff_err(ret, "FFVideoStream::encode_frame: encode video failed\n");
819 PixelFormat FFVideoStream::color_model_to_pix_fmt(int color_model)
821 switch( color_model ) {
822 case BC_YUV422: return AV_PIX_FMT_YUYV422;
823 case BC_RGB888: return AV_PIX_FMT_RGB24;
824 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
825 case BC_BGR8888: return AV_PIX_FMT_BGR0;
826 case BC_BGR888: return AV_PIX_FMT_BGR24;
827 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
828 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
829 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
830 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
831 case BC_RGB565: return AV_PIX_FMT_RGB565;
832 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
833 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
837 return AV_PIX_FMT_NB;
840 int FFVideoStream::pix_fmt_to_color_model(PixelFormat pix_fmt)
843 case AV_PIX_FMT_YUYV422: return BC_YUV422;
844 case AV_PIX_FMT_RGB24: return BC_RGB888;
845 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
846 case AV_PIX_FMT_BGR0: return BC_BGR8888;
847 case AV_PIX_FMT_BGR24: return BC_BGR888;
848 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
849 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
850 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
851 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
852 case AV_PIX_FMT_RGB565: return BC_RGB565;
853 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
854 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
858 return BC_TRANSPARENCY;
861 int FFVideoStream::convert_picture_vframe(VFrame *frame,
862 AVPicture *ip, PixelFormat ifmt, int iw, int ih)
865 int cmodel = frame->get_color_model();
866 PixelFormat ofmt = color_model_to_pix_fmt(cmodel);
867 if( ofmt == AV_PIX_FMT_NB ) return -1;
868 int size = avpicture_fill(&opic, frame->get_data(), ofmt,
869 frame->get_w(), frame->get_h());
870 if( size < 0 ) return -1;
872 // transfer line sizes must match also
873 int planar = BC_CModels::is_planar(cmodel);
874 int packed_width = !planar ? frame->get_bytes_per_line() :
875 BC_CModels::calculate_pixelsize(cmodel) * frame->get_w();
876 if( packed_width != opic.linesize[0] ) return -1;
879 // override avpicture_fill() for planar types
880 opic.data[0] = frame->get_y();
881 opic.data[1] = frame->get_u();
882 opic.data[2] = frame->get_v();
885 convert_ctx = sws_getCachedContext(convert_ctx, iw, ih, ifmt,
886 frame->get_w(), frame->get_h(), ofmt, SWS_BICUBIC, NULL, NULL, NULL);
888 fprintf(stderr, "FFVideoStream::convert_picture_frame:"
889 " sws_getCachedContext() failed\n");
892 int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ih,
893 opic.data, opic.linesize);
895 ff_err(ret, "FFVideoStream::convert_picture_frame: sws_scale() failed\n");
901 int FFVideoStream::convert_cmodel(VFrame *frame,
902 AVPicture *ip, PixelFormat ifmt, int iw, int ih)
904 // try direct transfer
905 if( !convert_picture_vframe(frame, ip, ifmt, iw, ih) ) return 1;
906 // use indirect transfer
907 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
909 for( int i = 0; i <desc->nb_components; ++i ) {
910 int bits = desc->comp[i].depth_minus1 + 1;
911 if( bits > max_bits ) max_bits = bits;
913 // from libavcodec/pixdesc.c
914 #define pixdesc_has_alpha(pixdesc) ((pixdesc)->nb_components == 2 || \
915 (pixdesc)->nb_components == 4 || (pixdesc)->flags & AV_PIX_FMT_FLAG_PAL)
916 int icolor_model = pixdesc_has_alpha(desc) ?
917 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
918 (max_bits > 8 ? BC_RGB161616 : BC_RGB888) ;
919 VFrame vframe(iw, ih, icolor_model);
920 if( convert_picture_vframe(&vframe, ip, ifmt, iw, ih) ) return -1;
921 frame->transfer_from(&vframe);
925 int FFVideoStream::convert_vframe_picture(VFrame *frame,
926 AVPicture *op, PixelFormat ofmt, int ow, int oh)
929 int cmodel = frame->get_color_model();
930 PixelFormat ifmt = color_model_to_pix_fmt(cmodel);
931 if( ifmt == AV_PIX_FMT_NB ) return -1;
932 int size = avpicture_fill(&opic, frame->get_data(), ifmt,
933 frame->get_w(), frame->get_h());
934 if( size < 0 ) return -1;
936 // transfer line sizes must match also
937 int planar = BC_CModels::is_planar(cmodel);
938 int packed_width = !planar ? frame->get_bytes_per_line() :
939 BC_CModels::calculate_pixelsize(cmodel) * frame->get_w();
940 if( packed_width != opic.linesize[0] ) return -1;
943 // override avpicture_fill() for planar types
944 opic.data[0] = frame->get_y();
945 opic.data[1] = frame->get_u();
946 opic.data[2] = frame->get_v();
949 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(), ifmt,
950 ow, oh, ofmt, SWS_BICUBIC, NULL, NULL, NULL);
952 fprintf(stderr, "FFVideoStream::convert_frame_picture:"
953 " sws_getCachedContext() failed\n");
956 int ret = sws_scale(convert_ctx, opic.data, opic.linesize, 0, frame->get_h(),
957 op->data, op->linesize);
959 ff_err(ret, "FFVideoStream::convert_frame_picture: sws_scale() failed\n");
965 int FFVideoStream::convert_pixfmt(VFrame *frame,
966 AVPicture *op, PixelFormat ofmt, int ow, int oh)
968 // try direct transfer
969 if( !convert_vframe_picture(frame, op, ofmt, ow, oh) ) return 0;
970 // use indirect transfer
971 int colormodel = frame->get_color_model();
972 int bits = BC_CModels::calculate_pixelsize(colormodel) * 8;
973 bits /= BC_CModels::components(colormodel);
974 int icolor_model = BC_CModels::has_alpha(colormodel) ?
975 (bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
976 (bits > 8 ? BC_RGB161616: BC_RGB888) ;
977 VFrame vframe(frame->get_w(), frame->get_h(), icolor_model);
978 vframe.transfer_from(frame);
979 if( convert_vframe_picture(&vframe, op, ofmt, ow, oh) ) return 1;
983 void FFVideoStream::load_markers()
985 IndexState *index_state = ffmpeg->file_base->asset->index_state;
986 if( idx >= index_state->video_markers.size() ) return;
987 FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
991 FFMPEG::FFMPEG(FileBase *file_base)
994 this->file_base = file_base;
995 memset(file_format,0,sizeof(file_format));
996 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
997 flow_lock = new Condition(1,"FFStream::flow_lock",0);
1000 decoding = encoding = 0;
1001 has_audio = has_video = 0;
1004 opt_video_filter = 0;
1005 opt_audio_filter = 0;
1006 char option_path[BCTEXTLEN];
1007 set_option_path(option_path, "%s", "ffmpeg.opts");
1008 read_options(option_path, opts);
1013 ff_lock("FFMPEG::~FFMPEG()");
1015 ffaudio.remove_all_objects();
1016 ffvideo.remove_all_objects();
1017 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1021 av_dict_free(&opts);
1022 delete [] opt_video_filter;
1023 delete [] opt_audio_filter;
1026 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1028 const int *p = codec->supported_samplerates;
1029 if( !p ) return sample_rate;
1031 if( *p == sample_rate ) return *p;
1037 static inline AVRational std_frame_rate(int i)
1039 static const int m1 = 1001*12, m2 = 1000*12;
1040 static const int freqs[] = {
1041 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1042 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
1044 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1045 return (AVRational) { freq, 1001*12 };
1048 AVRational FFMPEG::check_frame_rate(AVCodec *codec, double frame_rate)
1050 const AVRational *p = codec->supported_framerates;
1051 AVRational rate, best_rate = (AVRational) { 0, 0 };
1052 double max_err = 1.; int i = 0;
1053 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1054 double framerate = (double) rate.num / rate.den;
1055 double err = fabs(frame_rate/framerate - 1.);
1056 if( err >= max_err ) continue;
1060 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1063 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1066 double display_aspect = asset->width / (double)asset->height;
1067 double sample_aspect = asset->aspect_ratio / display_aspect;
1068 int width = 1000000, height = width * sample_aspect + 0.5;
1070 MWindow::create_aspect_ratio(w, h, width, height);
1071 return (AVRational){(int)h, (int)w};
1074 return (AVRational){1, 1};
1078 AVRational FFMPEG::to_time_base(int sample_rate)
1080 return (AVRational){1, sample_rate};
1083 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
1086 strcat(path, "/ffmpeg/");
1087 path += strlen(path);
1090 vsprintf(path, fmt, ap);
1094 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
1099 set_option_path(path, "%s/%s", type, spec);
1102 int FFMPEG::get_format(char *format, const char *path, char *spec)
1104 char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
1105 get_option_path(option_path, path, spec);
1106 FILE *fp = fopen(option_path,"r");
1109 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1111 line[sizeof(line)-1] = 0;
1112 ret = scan_option_line(line, format, codec);
1118 int FFMPEG::get_file_format()
1121 char audio_format[BCSTRLEN], video_format[BCSTRLEN];
1122 file_format[0] = audio_format[0] = video_format[0] = 0;
1123 Asset *asset = file_base->asset;
1124 if( !ret && asset->audio_data )
1125 ret = get_format(audio_format, "audio", asset->acodec);
1126 if( !ret && asset->video_data )
1127 ret = get_format(video_format, "video", asset->vcodec);
1128 if( !ret && !audio_format[0] && !video_format[0] )
1130 if( !ret && audio_format[0] && video_format[0] &&
1131 strcmp(audio_format, video_format) ) ret = -1;
1133 strcpy(file_format, audio_format[0] ? audio_format : video_format);
1137 int FFMPEG::scan_option_line(char *cp, char *tag, char *val)
1139 while( *cp == ' ' || *cp == '\t' ) ++cp;
1141 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' ) ++cp;
1143 if( !len || len > BCSTRLEN-1 ) return 1;
1144 while( bp < cp ) *tag++ = *bp++;
1146 while( *cp == ' ' || *cp == '\t' ) ++cp;
1147 if( *cp == '=' ) ++cp;
1148 while( *cp == ' ' || *cp == '\t' ) ++cp;
1150 while( *cp && *cp != '\n' ) ++cp;
1152 if( len > BCTEXTLEN-1 ) return 1;
1153 while( bp < cp ) *val++ = *bp++;
1158 int FFMPEG::get_encoder(const char *options,
1159 char *format, char *codec, char *bsfilter, char *bsargs)
1161 FILE *fp = fopen(options,"r");
1163 eprintf("FFMPEG::get_encoder: options open failed %s\n",options);
1166 if( get_encoder(fp, format, codec, bsfilter, bsargs) )
1167 eprintf(_("FFMPEG::get_encoder:"
1168 " err: format/codec not found %s\n"), options);
1173 int FFMPEG::get_encoder(FILE *fp,
1174 char *format, char *codec, char *bsfilter, char *bsargs)
1176 format[0] = codec[0] = bsfilter[0] = bsargs[0] = 0;
1177 char line[BCTEXTLEN];
1178 if( !fgets(line, sizeof(line), fp) ) return 1;
1179 line[sizeof(line)-1] = 0;
1180 if( scan_option_line(line, format, codec) ) return 1;
1182 while( *cp && *cp != '|' ) ++cp;
1183 if( !*cp ) return 0;
1184 if( scan_option_line(cp+1, bsfilter, bsargs) ) return 1;
1185 do { *cp-- = 0; } while( cp>=codec && (*cp==' ' || *cp == '\t' ) );
1189 int FFMPEG::read_options(const char *options, AVDictionary *&opts)
1191 FILE *fp = fopen(options,"r");
1193 int ret = read_options(fp, options, opts);
1198 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
1200 FILE *fp = fmemopen((void *)options,strlen(options),"r");
1202 int ret = read_options(fp, options, opts);
1204 AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
1205 if( tag ) st->id = strtol(tag->value,0,0);
1209 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
1211 int ret = 0, no = 0;
1212 char line[BCTEXTLEN];
1213 while( !ret && fgets(line, sizeof(line), fp) ) {
1214 line[sizeof(line)-1] = 0;
1216 if( line[0] == '#' ) continue;
1217 if( line[0] == '\n' ) continue;
1218 char key[BCSTRLEN], val[BCTEXTLEN];
1219 if( scan_option_line(line, key, val) ) {
1220 eprintf(_("FFMPEG::read_options:"
1221 " err reading %s: line %d\n"), options, no);
1225 if( !strcmp(key, "duration") )
1226 opt_duration = strtod(val, 0);
1227 if( !strcmp(key, "video_filter") )
1228 opt_video_filter = cstrdup(val);
1229 if( !strcmp(key, "audio_filter") )
1230 opt_audio_filter = cstrdup(val);
1231 else if( !strcmp(key, "loglevel") )
1234 av_dict_set(&opts, key, val, 0);
1240 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
1242 char option_path[BCTEXTLEN];
1243 set_option_path(option_path, "%s", options);
1244 return read_options(option_path, opts);
1247 int FFMPEG::load_options(const char *path, char *bfr, int len)
1250 FILE *fp = fopen(path, "r");
1252 fgets(bfr, len, fp); // skip hdr
1253 len = fread(bfr, 1, len-1, fp);
1254 if( len < 0 ) len = 0;
1260 void FFMPEG::set_loglevel(const char *ap)
1262 if( !ap || !*ap ) return;
1267 { "quiet" , AV_LOG_QUIET },
1268 { "panic" , AV_LOG_PANIC },
1269 { "fatal" , AV_LOG_FATAL },
1270 { "error" , AV_LOG_ERROR },
1271 { "warning", AV_LOG_WARNING },
1272 { "info" , AV_LOG_INFO },
1273 { "verbose", AV_LOG_VERBOSE },
1274 { "debug" , AV_LOG_DEBUG },
1276 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
1277 if( !strcmp(log_levels[i].name, ap) ) {
1278 av_log_set_level(log_levels[i].level);
1282 av_log_set_level(atoi(ap));
1285 double FFMPEG::to_secs(int64_t time, AVRational time_base)
1287 double base_time = time == AV_NOPTS_VALUE ? 0 :
1288 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
1289 return base_time / AV_TIME_BASE;
1292 int FFMPEG::info(char *text, int len)
1294 if( len <= 0 ) return 0;
1296 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
1298 if( ffvideo.size() > 0 )
1299 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
1300 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
1301 FFVideoStream *vid = ffvideo[vidx];
1302 AVStream *st = vid->st;
1303 AVCodecContext *avctx = st->codec;
1304 report(_("vid%d (%d), id 0x%06x:\n"), vid->idx, vid->fidx, avctx->codec_id);
1305 const AVCodecDescriptor *desc = avcodec_descriptor_get(avctx->codec_id);
1306 report(" video%d %s", vidx+1, desc ? desc->name : " (unkn)");
1307 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
1308 const char *pfn = av_get_pix_fmt_name(avctx->pix_fmt);
1309 report(" pix %s\n", pfn ? pfn : "(unkn)");
1310 double secs = to_secs(st->duration, st->time_base);
1311 int64_t length = secs * vid->frame_rate + 0.5;
1312 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
1313 int64_t nudge = ofs * vid->frame_rate;
1314 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1315 report(" %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
1316 int hrs = secs/3600; secs -= hrs*3600;
1317 int mins = secs/60; secs -= mins*60;
1318 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1320 if( ffaudio.size() > 0 )
1321 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
1322 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
1323 FFAudioStream *aud = ffaudio[aidx];
1324 AVStream *st = aud->st;
1325 AVCodecContext *avctx = st->codec;
1326 report(_("aud%d (%d), id 0x%06x:\n"), aud->idx, aud->fidx, avctx->codec_id);
1327 const AVCodecDescriptor *desc = avcodec_descriptor_get(avctx->codec_id);
1328 int nch = aud->channels, ch0 = aud->channel0+1;
1329 report(" audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
1330 const char *fmt = av_get_sample_fmt_name(avctx->sample_fmt);
1331 report(" %s %d", fmt, aud->sample_rate);
1332 int sample_bits = av_get_bits_per_sample(avctx->codec_id);
1333 report(" %dbits\n", sample_bits);
1334 double secs = to_secs(st->duration, st->time_base);
1335 int64_t length = secs * aud->sample_rate + 0.5;
1336 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
1337 int64_t nudge = ofs * aud->sample_rate;
1338 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1339 report(" %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
1340 int hrs = secs/3600; secs -= hrs*3600;
1341 int mins = secs/60; secs -= mins*60;
1342 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1344 if( fmt_ctx->nb_programs > 0 )
1345 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
1346 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
1347 report("program %d", i+1);
1348 AVProgram *pgrm = fmt_ctx->programs[i];
1349 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1350 int idx = pgrm->stream_index[j];
1351 int vidx = ffvideo.size();
1352 while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
1354 report(", vid%d", vidx);
1357 int aidx = ffaudio.size();
1358 while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
1360 report(", aud%d", aidx);
1363 report(", (%d)", pgrm->stream_index[j]);
1368 AVDictionaryEntry *tag = 0;
1369 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
1370 report("%s=%s\n", tag->key, tag->value);
1379 int FFMPEG::init_decoder(const char *filename)
1381 ff_lock("FFMPEG::init_decoder");
1383 char file_opts[BCTEXTLEN];
1384 char *bp = strrchr(strcpy(file_opts, filename), '/');
1385 char *sp = strrchr(!bp ? file_opts : bp, '.');
1388 strcpy(sp, ".opts");
1389 fp = fopen(file_opts, "r");
1392 read_options(fp, file_opts, opts);
1396 load_options("decode.opts", opts);
1397 AVDictionary *fopts = 0;
1398 av_dict_copy(&fopts, opts, 0);
1399 int ret = avformat_open_input(&fmt_ctx, filename, NULL, &fopts);
1400 av_dict_free(&fopts);
1402 ret = avformat_find_stream_info(fmt_ctx, NULL);
1407 return !ret ? 0 : 1;
1410 int FFMPEG::open_decoder()
1413 if( stat(fmt_ctx->filename, &st) < 0 ) {
1414 eprintf("FFMPEG::open_decoder: can't stat file: %s\n",
1419 int64_t file_bits = 8 * st.st_size;
1420 if( !fmt_ctx->bit_rate && opt_duration > 0 )
1421 fmt_ctx->bit_rate = file_bits / opt_duration;
1424 if( fmt_ctx->bit_rate > 0 ) {
1425 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1426 AVStream *st = fmt_ctx->streams[i];
1427 if( st->duration != AV_NOPTS_VALUE ) continue;
1428 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
1429 st->duration = av_rescale(file_bits, st->time_base.den,
1430 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
1435 printf("FFMPEG::open_decoder: some stream times estimated\n");
1437 ff_lock("FFMPEG::open_decoder");
1439 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1440 AVStream *st = fmt_ctx->streams[i];
1441 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
1442 AVCodecContext *avctx = st->codec;
1443 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avctx->codec_id);
1444 if( !codec_desc ) continue;
1445 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1446 if( avctx->width < 1 ) continue;
1447 if( avctx->height < 1 ) continue;
1448 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
1449 if( framerate.num < 1 ) continue;
1451 int vidx = ffvideo.size();
1452 FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
1453 vstrm_index.append(ffidx(vidx, 0));
1454 ffvideo.append(vid);
1455 vid->width = avctx->width;
1456 vid->height = avctx->height;
1457 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
1458 double secs = to_secs(st->duration, st->time_base);
1459 vid->length = secs * vid->frame_rate;
1460 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
1461 vid->nudge = st->start_time;
1463 if( opt_video_filter )
1464 vid->create_filter(opt_video_filter, avctx,avctx);
1466 else if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1467 if( avctx->channels < 1 ) continue;
1468 if( avctx->sample_rate < 1 ) continue;
1470 int aidx = ffaudio.size();
1471 FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
1472 ffaudio.append(aud);
1473 aud->channel0 = astrm_index.size();
1474 aud->channels = avctx->channels;
1475 for( int ch=0; ch<aud->channels; ++ch )
1476 astrm_index.append(ffidx(aidx, ch));
1477 aud->sample_rate = avctx->sample_rate;
1478 double secs = to_secs(st->duration, st->time_base);
1479 aud->length = secs * aud->sample_rate;
1480 if( avctx->sample_fmt != AV_SAMPLE_FMT_FLT ) {
1481 uint64_t layout = av_get_default_channel_layout(avctx->channels);
1482 if( !layout ) layout = ((uint64_t)1<<aud->channels) - 1;
1483 aud->resample_context = swr_alloc_set_opts(NULL,
1484 layout, AV_SAMPLE_FMT_FLT, avctx->sample_rate,
1485 layout, avctx->sample_fmt, avctx->sample_rate,
1487 swr_init(aud->resample_context);
1489 aud->nudge = st->start_time;
1491 if( opt_audio_filter )
1492 aud->create_filter(opt_audio_filter, avctx,avctx);
1496 printf("FFMPEG::open_decoder: some stream have bad times\n");
1502 int FFMPEG::init_encoder(const char *filename)
1504 int fd = ::open(filename,O_WRONLY);
1505 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
1507 eprintf("FFMPEG::init_encoder: bad file path: %s\n", filename);
1511 int ret = get_file_format();
1513 eprintf("FFMPEG::init_encoder: bad file format: %s\n", filename);
1517 eprintf("FFMPEG::init_encoder: mismatch audio/video file format: %s\n", filename);
1520 ff_lock("FFMPEG::init_encoder");
1522 avformat_alloc_output_context2(&fmt_ctx, 0, file_format, filename);
1524 eprintf("FFMPEG::init_encoder: failed: %s\n", filename);
1529 load_options("encode.opts", opts);
1536 int FFMPEG::open_encoder(const char *type, const char *spec)
1539 Asset *asset = file_base->asset;
1540 char *filename = asset->path;
1541 AVDictionary *sopts = 0;
1542 av_dict_copy(&sopts, opts, 0);
1543 char option_path[BCTEXTLEN];
1544 set_option_path(option_path, "%s/%s.opts", type, type);
1545 read_options(option_path, sopts);
1546 get_option_path(option_path, type, spec);
1547 char format_name[BCSTRLEN], codec_name[BCTEXTLEN];
1548 char bsfilter[BCSTRLEN], bsargs[BCTEXTLEN];
1549 if( get_encoder(option_path, format_name, codec_name, bsfilter, bsargs) ) {
1550 eprintf("FFMPEG::open_encoder: get_encoder failed %s:%s\n",
1551 option_path, filename);
1555 if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
1556 else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
1557 else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
1560 ff_lock("FFMPEG::open_encoder");
1564 const AVCodecDescriptor *codec_desc = 0;
1565 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
1567 eprintf("FFMPEG::open_encoder: cant find codec %s:%s\n",
1568 codec_name, filename);
1572 codec_desc = avcodec_descriptor_get(codec->id);
1574 eprintf("FFMPEG::open_encoder: unknown codec %s:%s\n",
1575 codec_name, filename);
1580 st = avformat_new_stream(fmt_ctx, 0);
1582 eprintf("FFMPEG::open_encoder: cant create stream %s:%s\n",
1583 codec_name, filename);
1588 AVCodecContext *ctx = st->codec;
1589 switch( codec_desc->type ) {
1590 case AVMEDIA_TYPE_AUDIO: {
1592 eprintf("FFMPEG::open_encoder: duplicate audio %s:%s\n",
1593 codec_name, filename);
1598 if( scan_options(asset->ff_audio_options, sopts, st) ) {
1599 eprintf("FFMPEG::open_encoder: bad audio options %s:%s\n",
1600 codec_name, filename);
1604 if( asset->ff_audio_bitrate > 0 ) {
1605 ctx->bit_rate = asset->ff_audio_bitrate;
1607 sprintf(arg, "%d", asset->ff_audio_bitrate);
1608 av_dict_set(&sopts, "b", arg, 0);
1610 int aidx = ffaudio.size();
1611 int fidx = aidx + ffvideo.size();
1612 FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
1613 ffaudio.append(aud); fst = aud;
1614 aud->sample_rate = asset->sample_rate;
1615 ctx->channels = aud->channels = asset->channels;
1616 for( int ch=0; ch<aud->channels; ++ch )
1617 astrm_index.append(ffidx(aidx, ch));
1618 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
1619 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
1620 if( !ctx->sample_rate ) {
1621 eprintf("FFMPEG::open_audio_encode:"
1622 " check_sample_rate failed %s\n", filename);
1626 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
1627 ctx->sample_fmt = codec->sample_fmts[0];
1628 uint64_t layout = av_get_default_channel_layout(ctx->channels);
1629 aud->resample_context = swr_alloc_set_opts(NULL,
1630 layout, ctx->sample_fmt, aud->sample_rate,
1631 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
1633 swr_init(aud->resample_context);
1636 case AVMEDIA_TYPE_VIDEO: {
1638 eprintf("FFMPEG::open_encoder: duplicate video %s:%s\n",
1639 codec_name, filename);
1644 if( scan_options(asset->ff_video_options, sopts, st) ) {
1645 eprintf("FFMPEG::open_encoder: bad video options %s:%s\n",
1646 codec_name, filename);
1650 if( asset->ff_video_bitrate > 0 ) {
1651 ctx->bit_rate = asset->ff_video_bitrate;
1653 sprintf(arg, "%d", asset->ff_video_bitrate);
1654 av_dict_set(&sopts, "b", arg, 0);
1656 else if( asset->ff_video_quality > 0 ) {
1657 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
1658 ctx->qmin = ctx->qmax = asset->ff_video_quality;
1659 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
1660 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
1661 ctx->flags |= CODEC_FLAG_QSCALE;
1663 av_dict_set(&sopts, "flags", "+qscale", 0);
1664 sprintf(arg, "%d", asset->ff_video_quality);
1665 av_dict_set(&sopts, "qscale", arg, 0);
1666 sprintf(arg, "%d", ctx->global_quality);
1667 av_dict_set(&sopts, "global_quality", arg, 0);
1669 int vidx = ffvideo.size();
1670 int fidx = vidx + ffaudio.size();
1671 FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
1672 vstrm_index.append(ffidx(vidx, 0));
1673 ffvideo.append(vid); fst = vid;
1674 vid->width = asset->width;
1675 ctx->width = (vid->width+3) & ~3;
1676 vid->height = asset->height;
1677 ctx->height = (vid->height+3) & ~3;
1678 vid->frame_rate = asset->frame_rate;
1679 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
1680 ctx->pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
1681 AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
1682 if( !frame_rate.num || !frame_rate.den ) {
1683 eprintf("FFMPEG::open_audio_encode:"
1684 " check_frame_rate failed %s\n", filename);
1688 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
1689 st->time_base = ctx->time_base;
1693 eprintf("FFMPEG::open_encoder: not audio/video, %s:%s\n",
1694 codec_name, filename);
1699 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
1700 st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
1702 ret = avcodec_open2(st->codec, codec, &sopts);
1704 ff_err(ret,"FFMPEG::open_encoder");
1705 eprintf("FFMPEG::open_encoder: open failed %s:%s\n",
1706 codec_name, filename);
1713 if( fst && bsfilter[0] )
1714 fst->add_bsfilter(bsfilter, !bsargs[0] ? 0 : bsargs);
1718 av_dict_free(&sopts);
1722 int FFMPEG::close_encoder()
1725 if( encoding > 0 ) {
1726 av_write_trailer(fmt_ctx);
1727 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
1728 avio_closep(&fmt_ctx->pb);
1734 int FFMPEG::decode_activate()
1736 if( decoding < 0 ) {
1738 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
1739 ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
1740 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
1741 ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
1742 // set nudges for each program stream set
1743 int npgrms = fmt_ctx->nb_programs;
1744 for( int i=0; i<npgrms; ++i ) {
1745 AVProgram *pgrm = fmt_ctx->programs[i];
1746 // first start time video stream
1747 int64_t vstart_time = -1, astart_time = -1;
1748 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1749 int fidx = pgrm->stream_index[j];
1750 AVStream *st = fmt_ctx->streams[fidx];
1751 AVCodecContext *avctx = st->codec;
1752 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1753 if( st->start_time == AV_NOPTS_VALUE ) continue;
1754 if( vstart_time > st->start_time ) continue;
1755 vstart_time = st->start_time;
1758 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1759 if( st->start_time == AV_NOPTS_VALUE ) continue;
1760 if( astart_time > st->start_time ) continue;
1761 astart_time = st->start_time;
1765 // match program streams to max start_time
1766 int64_t nudge = vstart_time > astart_time ? vstart_time : astart_time;
1767 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1768 int fidx = pgrm->stream_index[j];
1769 AVStream *st = fmt_ctx->streams[fidx];
1770 AVCodecContext *avctx = st->codec;
1771 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1772 for( int k=0; k<ffvideo.size(); ++k ) {
1773 if( ffvideo[k]->fidx != fidx ) continue;
1774 ffvideo[k]->nudge = nudge;
1778 if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1779 for( int k=0; k<ffaudio.size(); ++k ) {
1780 if( ffaudio[k]->fidx != fidx ) continue;
1781 ffaudio[k]->nudge = nudge;
1787 // set nudges for any streams not yet set
1788 int64_t vstart_time = 0, astart_time = 0;
1789 int nstreams = fmt_ctx->nb_streams;
1790 for( int i=0; i<nstreams; ++i ) {
1791 AVStream *st = fmt_ctx->streams[i];
1792 AVCodecContext *avctx = st->codec;
1793 switch( avctx->codec_type ) {
1794 case AVMEDIA_TYPE_VIDEO: {
1795 if( st->start_time == AV_NOPTS_VALUE ) continue;
1796 int vidx = ffvideo.size();
1797 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
1798 if( vidx >= 0 && ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
1799 if( vstart_time >= st->start_time ) continue;
1800 vstart_time = st->start_time;
1802 case AVMEDIA_TYPE_AUDIO: {
1803 if( st->start_time == AV_NOPTS_VALUE ) continue;
1804 int aidx = ffaudio.size();
1805 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
1806 if( aidx >= 0 && ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
1807 if( astart_time >= st->start_time ) continue;
1808 astart_time = st->start_time;
1813 int64_t nudge = vstart_time > astart_time ? vstart_time : astart_time;
1814 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
1815 if( ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
1816 ffvideo[vidx]->nudge = nudge;
1818 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
1819 if( ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
1820 ffaudio[aidx]->nudge = nudge;
1827 int FFMPEG::encode_activate()
1830 if( encoding < 0 ) {
1832 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
1833 (ret=avio_open(&fmt_ctx->pb, fmt_ctx->filename, AVIO_FLAG_WRITE)) < 0 ) {
1834 ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
1839 AVDictionary *fopts = 0;
1840 char option_path[BCTEXTLEN];
1841 set_option_path(option_path, "format/%s", file_format);
1842 read_options(option_path, fopts);
1843 ret = avformat_write_header(fmt_ctx, &fopts);
1844 av_dict_free(&fopts);
1846 ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
1856 int FFMPEG::audio_seek(int stream, int64_t pos)
1858 int aidx = astrm_index[stream].st_idx;
1859 FFAudioStream *aud = ffaudio[aidx];
1860 pos = pos * aud->sample_rate / file_base->asset->sample_rate + 0.5;
1861 aud->audio_seek(pos);
1865 int FFMPEG::video_seek(int stream, int64_t pos)
1867 int vidx = vstrm_index[stream].st_idx;
1868 FFVideoStream *vid = ffvideo[vidx];
1869 pos = pos * vid->frame_rate / file_base->asset->frame_rate + 0.5;
1870 vid->video_seek(pos);
1875 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
1877 if( !has_audio || chn >= astrm_index.size() ) return -1;
1878 int aidx = astrm_index[chn].st_idx;
1879 FFAudioStream *aud = ffaudio[aidx];
1880 pos = pos * aud->sample_rate / file_base->asset->sample_rate + 0.5;
1881 if( aud->load(pos, len) < len ) return -1;
1882 int ch = astrm_index[chn].st_ch;
1883 int ret = aud->read(samples,len,ch);
1887 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
1889 if( !has_video || layer >= vstrm_index.size() ) return -1;
1890 int vidx = vstrm_index[layer].st_idx;
1891 FFVideoStream *vid = ffvideo[vidx];
1892 pos = pos * vid->frame_rate / file_base->asset->frame_rate + 0.5;
1893 return vid->load(vframe, pos);
1897 int FFMPEG::encode(int stream, double **samples, int len)
1899 FFAudioStream *aud = ffaudio[stream];
1900 return aud->encode(samples, len);
1904 int FFMPEG::encode(int stream, VFrame *frame)
1906 FFVideoStream *vid = ffvideo[stream];
1907 return vid->encode(frame);
1910 void FFMPEG::start_muxer()
1918 void FFMPEG::stop_muxer()
1927 void FFMPEG::flow_off()
1930 flow_lock->lock("FFMPEG::flow_off");
1934 void FFMPEG::flow_on()
1938 flow_lock->unlock();
1941 void FFMPEG::flow_ctl()
1944 flow_lock->lock("FFMPEG::flow_ctl");
1945 flow_lock->unlock();
1949 int FFMPEG::mux_audio(FFrame *frm)
1952 FFStream *fst = frm->fst;
1953 AVCodecContext *ctx = fst->st->codec;
1954 AVFrame *frame = *frm;
1955 AVRational tick_rate = {1, ctx->sample_rate};
1956 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
1958 int ret = fst->encode_frame(pkt, frame, got_packet);
1959 if( ret >= 0 && got_packet )
1960 ret = fst->write_packet(pkt);
1962 ff_err(ret, "FFMPEG::mux_audio");
1963 return ret >= 0 ? 0 : 1;
1966 int FFMPEG::mux_video(FFrame *frm)
1969 FFStream *fst = frm->fst;
1970 AVFrame *frame = *frm;
1971 frame->pts = frm->position;
1972 int ret = 1, got_packet = 0;
1973 if( fmt_ctx->oformat->flags & AVFMT_RAWPICTURE ) {
1974 /* a hack to avoid data copy with some raw video muxers */
1975 pkt->flags |= AV_PKT_FLAG_KEY;
1976 pkt->stream_index = fst->st->index;
1977 AVPicture *picture = (AVPicture *)frame;
1978 pkt->data = (uint8_t *)picture;
1979 pkt->size = sizeof(AVPicture);
1980 pkt->pts = pkt->dts = frame->pts;
1984 ret = fst->encode_frame(pkt, frame, got_packet);
1985 if( ret >= 0 && got_packet )
1986 ret = fst->write_packet(pkt);
1988 ff_err(ret, "FFMPEG::mux_video");
1989 return ret >= 0 ? 0 : 1;
1995 double atm = -1, vtm = -1;
1996 FFrame *afrm = 0, *vfrm = 0;
1998 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
1999 FFStream *fst = ffaudio[i];
2000 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
2001 FFrame *frm = fst->frms.first;
2002 if( !frm ) { if( !done ) return; continue; }
2003 double tm = to_secs(frm->position, fst->st->codec->time_base);
2004 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
2006 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
2007 FFStream *fst = ffvideo[i];
2008 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
2009 FFrame *frm = fst->frms.first;
2010 if( !frm ) { if( !done ) return; continue; }
2011 double tm = to_secs(frm->position, fst->st->codec->time_base);
2012 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
2014 if( !demand ) flow_off();
2015 if( !afrm && !vfrm ) break;
2016 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
2017 vfrm->position, vfrm->fst->st->codec->time_base,
2018 afrm->position, afrm->fst->st->codec->time_base);
2019 FFrame *frm = v <= 0 ? vfrm : afrm;
2020 if( frm == afrm ) mux_audio(frm);
2021 if( frm == vfrm ) mux_video(frm);
2030 mux_lock->lock("FFMPEG::run");
2034 for( int i=0; i<ffaudio.size(); ++i )
2035 ffaudio[i]->flush();
2036 for( int i=0; i<ffvideo.size(); ++i )
2037 ffvideo[i]->flush();
2041 int FFMPEG::ff_total_audio_channels()
2043 return astrm_index.size();
2046 int FFMPEG::ff_total_astreams()
2048 return ffaudio.size();
2051 int FFMPEG::ff_audio_channels(int stream)
2053 return ffaudio[stream]->channels;
2056 int FFMPEG::ff_sample_rate(int stream)
2058 return ffaudio[stream]->sample_rate;
2061 const char* FFMPEG::ff_audio_format(int stream)
2063 AVStream *st = ffaudio[stream]->st;
2064 AVCodecID id = st->codec->codec_id;
2065 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2066 return desc ? desc->name : "Unknown";
2069 int FFMPEG::ff_audio_pid(int stream)
2071 return ffaudio[stream]->st->id;
2074 int64_t FFMPEG::ff_audio_samples(int stream)
2076 return ffaudio[stream]->length;
2079 // find audio astream/channels with this program,
2080 // or all program audio channels (astream=-1)
2081 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
2085 int vidx = ffvideo[vstream]->fidx;
2086 // find first program with this video stream
2087 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
2088 AVProgram *pgrm = fmt_ctx->programs[i];
2089 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
2090 int st_idx = pgrm->stream_index[j];
2091 AVStream *st = fmt_ctx->streams[st_idx];
2092 if( st->codec->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
2093 if( st_idx == vidx ) pidx = i;
2096 if( pidx < 0 ) return -1;
2098 int64_t channels = 0;
2099 AVProgram *pgrm = fmt_ctx->programs[pidx];
2100 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2101 int aidx = pgrm->stream_index[j];
2102 AVStream *st = fmt_ctx->streams[aidx];
2103 if( st->codec->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
2104 if( astream > 0 ) { --astream; continue; }
2106 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
2107 if( ffaudio[i]->fidx == aidx ) astrm = i;
2109 if( ret < 0 ) ret = astrm;
2110 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
2111 channels |= mask << ffaudio[astrm]->channel0;
2113 if( !astream ) break;
2115 channel_mask = channels;
2120 int FFMPEG::ff_total_video_layers()
2122 return vstrm_index.size();
2125 int FFMPEG::ff_total_vstreams()
2127 return ffvideo.size();
2130 int FFMPEG::ff_video_width(int stream)
2132 return ffvideo[stream]->width;
2135 int FFMPEG::ff_video_height(int stream)
2137 return ffvideo[stream]->height;
2140 int FFMPEG::ff_set_video_width(int stream, int width)
2142 int w = ffvideo[stream]->width;
2143 ffvideo[stream]->width = width;
2147 int FFMPEG::ff_set_video_height(int stream, int height)
2149 int h = ffvideo[stream]->height;
2150 ffvideo[stream]->height = height;
2154 int FFMPEG::ff_coded_width(int stream)
2156 AVStream *st = ffvideo[stream]->st;
2157 return st->codec->coded_width;
2160 int FFMPEG::ff_coded_height(int stream)
2162 AVStream *st = ffvideo[stream]->st;
2163 return st->codec->coded_height;
2166 float FFMPEG::ff_aspect_ratio(int stream)
2168 return ffvideo[stream]->aspect_ratio;
2171 const char* FFMPEG::ff_video_format(int stream)
2173 AVStream *st = ffvideo[stream]->st;
2174 AVCodecID id = st->codec->codec_id;
2175 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2176 return desc ? desc->name : "Unknown";
2179 double FFMPEG::ff_frame_rate(int stream)
2181 return ffvideo[stream]->frame_rate;
2184 int64_t FFMPEG::ff_video_frames(int stream)
2186 return ffvideo[stream]->length;
2189 int FFMPEG::ff_video_pid(int stream)
2191 return ffvideo[stream]->st->id;
2195 int FFMPEG::ff_cpus()
2197 return file_base->file->cpus;
2200 int FFVideoStream::create_filter(const char *filter_spec,
2201 AVCodecContext *src_ctx, AVCodecContext *sink_ctx)
2203 avfilter_register_all();
2204 AVFilter *filter = avfilter_get_by_name(filter_spec);
2205 if( !filter || filter->inputs->type != AVMEDIA_TYPE_VIDEO ) {
2206 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
2209 filter_graph = avfilter_graph_alloc();
2210 AVFilter *buffersrc = avfilter_get_by_name("buffer");
2211 AVFilter *buffersink = avfilter_get_by_name("buffersink");
2213 int ret = 0; char args[BCTEXTLEN];
2214 snprintf(args, sizeof(args),
2215 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
2216 src_ctx->width, src_ctx->height, src_ctx->pix_fmt,
2217 st->time_base.num, st->time_base.den,
2218 src_ctx->sample_aspect_ratio.num, src_ctx->sample_aspect_ratio.den);
2220 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2221 args, NULL, filter_graph);
2223 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2224 NULL, NULL, filter_graph);
2226 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
2227 (uint8_t*)&sink_ctx->pix_fmt, sizeof(sink_ctx->pix_fmt),
2228 AV_OPT_SEARCH_CHILDREN);
2230 ff_err(ret, "FFVideoStream::create_filter");
2232 ret = FFStream::create_filter(filter_spec);
2233 return ret >= 0 ? 0 : 1;
2236 int FFAudioStream::create_filter(const char *filter_spec,
2237 AVCodecContext *src_ctx, AVCodecContext *sink_ctx)
2239 avfilter_register_all();
2240 AVFilter *filter = avfilter_get_by_name(filter_spec);
2241 if( !filter || filter->inputs->type != AVMEDIA_TYPE_AUDIO ) {
2242 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
2245 filter_graph = avfilter_graph_alloc();
2246 AVFilter *buffersrc = avfilter_get_by_name("abuffer");
2247 AVFilter *buffersink = avfilter_get_by_name("abuffersink");
2248 int ret = 0; char args[BCTEXTLEN];
2249 snprintf(args, sizeof(args),
2250 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
2251 st->time_base.num, st->time_base.den, src_ctx->sample_rate,
2252 av_get_sample_fmt_name(src_ctx->sample_fmt), src_ctx->channel_layout);
2254 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2255 args, NULL, filter_graph);
2257 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2258 NULL, NULL, filter_graph);
2260 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
2261 (uint8_t*)&sink_ctx->sample_fmt, sizeof(sink_ctx->sample_fmt),
2262 AV_OPT_SEARCH_CHILDREN);
2264 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
2265 (uint8_t*)&sink_ctx->channel_layout,
2266 sizeof(sink_ctx->channel_layout), AV_OPT_SEARCH_CHILDREN);
2268 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
2269 (uint8_t*)&sink_ctx->sample_rate, sizeof(sink_ctx->sample_rate),
2270 AV_OPT_SEARCH_CHILDREN);
2272 ff_err(ret, "FFAudioStream::create_filter");
2274 ret = FFStream::create_filter(filter_spec);
2275 return ret >= 0 ? 0 : 1;
2278 int FFStream::create_filter(const char *filter_spec)
2280 /* Endpoints for the filter graph. */
2281 AVFilterInOut *outputs = avfilter_inout_alloc();
2282 outputs->name = av_strdup("in");
2283 outputs->filter_ctx = buffersrc_ctx;
2284 outputs->pad_idx = 0;
2287 AVFilterInOut *inputs = avfilter_inout_alloc();
2288 inputs->name = av_strdup("out");
2289 inputs->filter_ctx = buffersink_ctx;
2290 inputs->pad_idx = 0;
2293 int ret = !outputs->name || !inputs->name ? -1 : 0;
2295 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
2296 &inputs, &outputs, NULL);
2298 ret = avfilter_graph_config(filter_graph, NULL);
2301 ff_err(ret, "FFStream::create_filter");
2302 avfilter_inout_free(&inputs);
2303 avfilter_inout_free(&outputs);
2307 void FFStream::add_bsfilter(const char *bsf, const char *ap)
2309 bsfilter.append(new BSFilter(bsf,ap));
2312 int FFStream::bs_filter(AVPacket *pkt)
2314 if( !bsfilter.size() ) return 0;
2315 av_packet_split_side_data(pkt);
2318 for( int i=0; i<bsfilter.size(); ++i ) {
2319 AVPacket bspkt = *pkt;
2320 ret = av_bitstream_filter_filter(bsfilter[i]->bsfc,
2321 st->codec, bsfilter[i]->args, &bspkt.data, &bspkt.size,
2322 pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY);
2323 if( ret < 0 ) break;
2324 int size = bspkt.size;
2325 uint8_t *data = bspkt.data;
2326 if( !ret && bspkt.data != pkt->data ) {
2328 data = (uint8_t *)av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
2329 if( !data ) { ret = AVERROR(ENOMEM); break; }
2330 memcpy(data, bspkt.data, size);
2331 memset(data+size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2335 pkt->side_data = 0; pkt->side_data_elems = 0;
2336 av_free_packet(pkt);
2337 ret = av_packet_from_data(&bspkt, data, size);
2338 if( ret < 0 ) break;
2343 ff_err(ret,"FFStream::bs_filter");
2347 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
2350 av_init_packet(&pkt);
2351 AVFrame *frame = av_frame_alloc();
2353 fprintf(stderr, "FFMPEG::scan: av_frame_alloc failed\n");
2357 index_state->add_video_markers(ffvideo.size());
2358 index_state->add_audio_markers(ffaudio.size());
2360 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2361 AVDictionary *copts = 0;
2362 av_dict_copy(&copts, opts, 0);
2363 AVStream *st = fmt_ctx->streams[i];
2364 AVCodecID codec_id = st->codec->codec_id;
2365 AVCodec *decoder = avcodec_find_decoder(codec_id);
2366 if( avcodec_open2(st->codec, decoder, &copts) < 0 )
2367 fprintf(stderr, "FFMPEG::scan: codec open failed\n");
2368 av_dict_free(&copts);
2371 for( int64_t count=0; !*canceled; ++count ) {
2372 av_packet_unref(&pkt);
2373 pkt.data = 0; pkt.size = 0;
2375 int ret = av_read_frame(fmt_ctx, &pkt);
2377 if( ret == AVERROR_EOF ) break;
2378 if( ++errs > 100 ) {
2379 ff_err(ret, "over 100 read_frame errs\n");
2384 if( !pkt.data ) continue;
2385 int i = pkt.stream_index;
2386 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
2387 AVStream *st = fmt_ctx->streams[i];
2388 AVCodecContext *avctx = st->codec;
2389 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
2391 switch( avctx->codec_type ) {
2392 case AVMEDIA_TYPE_VIDEO: {
2393 int vidx = ffvideo.size();
2394 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
2395 if( vidx < 0 ) break;
2396 FFVideoStream *vid = ffvideo[vidx];
2397 int64_t tstmp = pkt.dts;
2398 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.pts;
2399 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
2400 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
2401 double secs = to_secs(tstmp, st->time_base);
2402 int64_t frm = secs * vid->frame_rate + 0.5;
2403 if( frm < 0 ) frm = 0;
2404 index_state->put_video_mark(vidx, frm, pkt.pos);
2407 while( pkt.size > 0 ) {
2408 av_frame_unref(frame);
2410 int ret = vid->decode_frame(&pkt, frame, got_frame);
2411 if( ret <= 0 ) break;
2412 // if( got_frame ) {}
2418 case AVMEDIA_TYPE_AUDIO: {
2419 int aidx = ffaudio.size();
2420 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
2421 if( aidx < 0 ) break;
2422 FFAudioStream *aud = ffaudio[aidx];
2423 int64_t tstmp = pkt.pts;
2424 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
2425 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
2426 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
2427 double secs = to_secs(tstmp, st->time_base);
2428 int64_t sample = secs * aud->sample_rate + 0.5;
2429 if( sample < 0 ) sample = 0;
2430 index_state->put_audio_mark(aidx, sample, pkt.pos);
2432 while( pkt.size > 0 ) {
2433 int ch = aud->channel0, nch = aud->channels;
2434 int64_t pos = index_state->pos(ch);
2435 if( pos != aud->curr_pos ) {
2436 if( abs(pos-aud->curr_pos) > 1 )
2437 printf("audio%d pad %ld %ld (%ld)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
2438 index_state->pad_data(ch, nch, aud->curr_pos);
2440 av_frame_unref(frame);
2442 int ret = aud->decode_frame(&pkt, frame, got_frame);
2443 if( ret <= 0 ) break;
2446 int len = aud->get_samples(samples,
2447 &frame->extended_data[0], frame->nb_samples);
2448 for( int i=0; i<nch; ++i )
2449 index_state->put_data(ch+i,nch,samples+i,len);
2450 aud->curr_pos += len;
2459 av_frame_free(&frame);
2463 void FFStream::load_markers(IndexMarks &marks, double rate)
2465 index_markers = &marks;
2467 int64_t sz = marks.size();
2468 int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
2469 int nb_ent = st->nb_index_entries;
2470 // some formats already have an index
2472 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
2473 int64_t tstmp = ep->timestamp;
2474 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
2475 double secs = ffmpeg->to_secs(tstmp, st->time_base);
2476 int64_t no = secs * rate;
2477 while( in < sz && marks[in].no <= no ) ++in;
2479 int64_t len = sz - in;
2480 int64_t count = max_entries - nb_ent;
2481 if( count > len ) count = len;
2482 for( int i=0; i<count; ++i ) {
2483 int k = in + i * len / count;
2484 int64_t no = marks[k].no, pos = marks[k].pos;
2485 double secs = (double)no / rate;
2486 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
2487 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
2488 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);