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"
24 #include "interlacemodes.h"
27 #include "mainerror.h"
32 #define VIDEO_INBUF_SIZE 0x10000
33 #define AUDIO_INBUF_SIZE 0x10000
34 #define VIDEO_REFILL_THRESH 0
35 #define AUDIO_REFILL_THRESH 0x1000
37 Mutex FFMPEG::fflock("FFMPEG::fflock");
39 static void ff_err(int ret, const char *fmt, ...)
44 vsnprintf(msg, sizeof(msg), fmt, ap);
46 char errmsg[BCSTRLEN];
47 av_strerror(ret, errmsg, sizeof(errmsg));
48 fprintf(stderr,_("%s err: %s\n"),msg, errmsg);
54 pkt.data = 0; pkt.size = 0;
56 void FFPacket::finit()
58 av_packet_unref(&pkt);
61 FFrame::FFrame(FFStream *fst)
64 frm = av_frame_alloc();
65 init = fst->init_frame(frm);
73 void FFrame::queue(int64_t pos)
79 void FFrame::dequeue()
84 int FFAudioStream::read(float *fp, long len)
92 while( --k >= 0 ) *fp++ = *op++;
93 if( op >= lmt ) op = bfr;
98 void FFAudioStream::realloc(long nsz, int nch, long len)
100 long bsz = nsz * nch;
101 float *np = new float[bsz];
102 inp = np + read(np, len) * nch;
107 delete [] bfr; bfr = np;
110 void FFAudioStream::realloc(long nsz, int nch)
112 if( nsz > sz || this->nch != nch ) {
113 long len = this->nch != nch ? 0 : hpos;
114 if( len > sz ) len = sz;
116 realloc(nsz, nch, len);
120 void FFAudioStream::reserve(long nsz, int nch)
122 long len = (inp - outp) / nch;
124 if( nsz > sz || this->nch != nch ) {
125 if( this->nch != nch ) len = 0;
126 realloc(nsz, nch, len);
129 if( (len*=nch) > 0 && bfr != outp )
130 memmove(bfr, outp, len*sizeof(*bfr));
135 long FFAudioStream::used()
137 long len = inp>=outp ? inp-outp : inp-bfr + lmt-outp;
140 long FFAudioStream::avail()
143 if( in1 >= lmt ) in1 = bfr;
144 long len = outp >= in1 ? outp-in1 : outp-bfr + lmt-in1;
147 void FFAudioStream::reset_history()
153 void FFAudioStream::iseek(int64_t ofs)
155 outp = inp - ofs*nch;
156 if( outp < bfr ) outp += sz*nch;
159 float *FFAudioStream::get_outp(int ofs)
166 int64_t FFAudioStream::put_inp(int ofs)
169 return (inp-outp) / nch;
172 int FFAudioStream::write(const float *fp, long len)
180 while( --k >= 0 ) *ip++ = *fp++;
181 if( ip >= lmt ) ip = bfr;
188 int FFAudioStream::zero(long len)
196 while( --k >= 0 ) *ip++ = 0;
197 if( ip >= lmt ) ip = bfr;
204 // does not advance outp
205 int FFAudioStream::read(double *dp, long len, int ch)
208 float *op = outp + ch;
209 float *lmt1 = lmt + nch-1;
211 int k = (lmt1 - op) / nch;
214 while( --k >= 0 ) { *dp++ = *op; op += nch; }
215 if( op >= lmt ) op -= sz*nch;
220 // load linear buffer, no wrapping allowed, does not advance inp
221 int FFAudioStream::write(const double *dp, long len, int ch)
224 float *ip = inp + ch;
225 while( --n >= 0 ) { *ip = *dp++; ip += nch; }
230 FFStream::FFStream(FFMPEG *ffmpeg, AVStream *st, int fidx)
232 this->ffmpeg = ffmpeg;
235 frm_lock = new Mutex("FFStream::frm_lock");
242 nudge = AV_NOPTS_VALUE;
243 seek_pos = curr_pos = 0;
245 reading = writing = 0;
252 FFStream::~FFStream()
254 if( reading > 0 || writing > 0 ) avcodec_close(avctx);
255 if( avctx ) avcodec_free_context(&avctx);
256 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
257 if( bsfc ) av_bsf_free(&bsfc);
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);
265 void FFStream::ff_lock(const char *cp)
267 FFMPEG::fflock.lock(cp);
270 void FFStream::ff_unlock()
272 FFMPEG::fflock.unlock();
275 void FFStream::queue(FFrame *frm)
277 frm_lock->lock("FFStream::queue");
281 ffmpeg->mux_lock->unlock();
284 void FFStream::dequeue(FFrame *frm)
286 frm_lock->lock("FFStream::dequeue");
288 frms.remove_pointer(frm);
292 int FFStream::encode_activate()
295 writing = ffmpeg->encode_activate();
299 int FFStream::decode_activate()
301 if( reading < 0 && (reading=ffmpeg->decode_activate()) > 0 ) {
302 ff_lock("FFStream::decode_activate");
304 AVDictionary *copts = 0;
305 av_dict_copy(&copts, ffmpeg->opts, 0);
307 // this should be avformat_copy_context(), but no copy avail
308 ret = avformat_open_input(&fmt_ctx, ffmpeg->fmt_ctx->filename, NULL, &copts);
310 ret = avformat_find_stream_info(fmt_ctx, 0);
311 st = fmt_ctx->streams[fidx];
314 if( ret >= 0 && st != 0 ) {
315 AVCodecID codec_id = st->codecpar->codec_id;
316 AVCodec *decoder = avcodec_find_decoder(codec_id);
317 avctx = avcodec_alloc_context3(decoder);
319 eprintf(_("cant allocate codec context\n"));
320 ret = AVERROR(ENOMEM);
323 avcodec_parameters_to_context(avctx, st->codecpar);
324 ret = avcodec_open2(avctx, decoder, &copts);
329 eprintf(_("open decoder failed\n"));
332 eprintf(_("can't clone input file\n"));
333 av_dict_free(&copts);
339 int FFStream::read_packet()
341 av_packet_unref(ipkt);
342 int ret = av_read_frame(fmt_ctx, ipkt);
345 if( ret == AVERROR_EOF ) return 0;
346 ff_err(ret, "FFStream::read_packet: av_read_frame failed\n");
353 int FFStream::decode(AVFrame *frame)
356 int retries = MAX_RETRY;
358 while( ret >= 0 && !flushed && --retries >= 0 ) {
360 if( (ret=read_packet()) < 0 ) break;
361 AVPacket *pkt = ret > 0 ? (AVPacket*)ipkt : 0;
363 if( pkt->stream_index != st->index ) continue;
364 if( !pkt->data | !pkt->size ) continue;
366 if( (ret=avcodec_send_packet(avctx, pkt)) < 0 ) {
367 ff_err(ret, "FFStream::decode: avcodec_send_packet failed\n");
373 if( (ret=decode_frame(frame)) > 0 ) break;
381 fprintf(stderr, "FFStream::decode: Retry limit\n");
385 fprintf(stderr, "FFStream::decode: failed\n");
389 int FFStream::load_filter(AVFrame *frame)
391 int ret = av_buffersrc_add_frame_flags(buffersrc_ctx,
392 frame, AV_BUFFERSRC_FLAG_KEEP_REF);
394 av_frame_unref(frame);
395 eprintf(_("av_buffersrc_add_frame_flags failed\n"));
400 int FFStream::read_filter(AVFrame *frame)
402 int ret = av_buffersink_get_frame(buffersink_ctx, frame);
404 if( ret == AVERROR(EAGAIN) ) return 0;
405 if( ret == AVERROR_EOF ) { st_eof(1); return -1; }
406 ff_err(ret, "FFStream::read_filter: av_buffersink_get_frame failed\n");
412 int FFStream::read_frame(AVFrame *frame)
414 if( !filter_graph || !buffersrc_ctx || !buffersink_ctx )
415 return decode(frame);
416 if( !fframe && !(fframe=av_frame_alloc()) ) {
417 fprintf(stderr, "FFStream::read_frame: av_frame_alloc failed\n");
421 while( !flushed && !(ret=read_filter(frame)) ) {
422 if( (ret=decode(fframe)) < 0 ) break;
423 if( ret > 0 && (ret=load_filter(fframe)) < 0 ) break;
428 int FFStream::write_packet(FFPacket &pkt)
432 av_packet_rescale_ts(pkt, avctx->time_base, st->time_base);
433 pkt->stream_index = st->index;
434 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, pkt);
437 ret = av_bsf_send_packet(bsfc, pkt);
440 if( (ret=av_bsf_receive_packet(bsfc, bs)) < 0 ) {
441 if( ret == AVERROR(EAGAIN) ) return 0;
442 if( ret == AVERROR_EOF ) return -1;
445 av_packet_rescale_ts(bs, avctx->time_base, st->time_base);
446 bs->stream_index = st->index;
447 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, bs);
451 ff_err(ret, "FFStream::write_packet: write packet failed\n");
455 int FFStream::encode_frame(AVFrame *frame)
457 int pkts = 0, ret = 0;
458 for( int retry=100; --retry>=0; ) {
460 ret = avcodec_send_frame(avctx, frame);
461 if( !ret && frame ) return pkts;
462 if( ret < 0 && ret != AVERROR(EAGAIN) ) break;
464 ret = avcodec_receive_packet(avctx, opkt);
465 if( !frame && ret == AVERROR_EOF ) return pkts;
467 ret = write_packet(opkt);
471 ff_err(ret, "FFStream::encode_frame: encode failed\n");
475 int FFStream::flush()
479 int ret = encode_frame(0);
481 ff_err(ret, "FFStream::flush");
482 return ret >= 0 ? 0 : 1;
485 int FFStream::seek(int64_t no, double rate)
487 int64_t tstmp = -INT64_MAX+1;
488 // default ffmpeg native seek
490 int64_t pos = no, pkt_pos = -1;
491 IndexMarks *index_markers = get_markers();
492 if( index_markers && index_markers->size() > 1 ) {
493 IndexMarks &marks = *index_markers;
494 int i = marks.find(pos);
495 int64_t n = i < 0 ? (i=0) : marks[i].no;
496 // if indexed seek point not too far away (<30 secs), use index
497 if( no-n < 30*rate ) {
500 if( i < marks.size() ) pkt_pos = marks[i].pos;
504 if( pos > 0 && st->time_base.num > 0 ) {
505 double secs = pos / rate;
506 tstmp = secs * st->time_base.den / st->time_base.num;
507 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
509 avcodec_flush_buffers(avctx);
510 avformat_flush(fmt_ctx);
512 int64_t seek = tstmp;
513 int flags = AVSEEK_FLAG_ANY;
514 if( !(fmt_ctx->iformat->flags & AVFMT_NO_BYTE_SEEK) && pkt_pos >= 0 ) {
516 flags = AVSEEK_FLAG_BYTE;
518 int ret = avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, seek, INT64_MAX, flags);
520 int ret = av_seek_frame(fmt_ctx, st->index, tstmp, AVSEEK_FLAG_ANY);
522 int retry = MAX_RETRY;
524 need_packet = 0; flushed = 0;
525 seeked = 1; st_eof(0);
526 // read up to retry packets, limited to npkts in stream, and not pkt.pos past pkt_pos
527 while( --retry >= 0 ) {
528 if( read_packet() <= 0 ) { ret = -1; break; }
529 if( ipkt->stream_index != st->index ) continue;
530 if( !ipkt->data || !ipkt->size ) continue;
531 if( pkt_pos >= 0 && ipkt->pos >= pkt_pos ) break;
532 if( --npkts <= 0 ) break;
533 int64_t pkt_ts = ipkt->dts != AV_NOPTS_VALUE ? ipkt->dts : ipkt->pts;
534 if( pkt_ts == AV_NOPTS_VALUE ) continue;
535 if( pkt_ts >= tstmp ) break;
538 fprintf(stderr,"FFStream::seek: retry limit, pos=%jd tstmp=%jd\n",pos,tstmp);
542 ret = avcodec_send_packet(avctx, ipkt);
544 //some codecs need more than one pkt to resync
545 if( ret == AVERROR_INVALIDDATA ) ret = 0;
547 ff_err(ret, "FFStream::avcodec_send_packet failed\n");
552 //printf("** seek fail %ld, %ld\n", pos, tstmp);
553 seeked = need_packet = 0;
557 //printf("seeked pos = %ld, %ld\n", pos, tstmp);
558 seek_pos = curr_pos = pos;
562 FFAudioStream::FFAudioStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
563 : FFStream(ffmpeg, strm, fidx)
566 channel0 = channels = 0;
570 resample_context = 0;
579 bfr = new float[bsz];
584 FFAudioStream::~FFAudioStream()
586 if( resample_context ) swr_free(&resample_context);
591 int FFAudioStream::get_samples(float *&samples, uint8_t **data, int len)
593 samples = *(float **)data;
594 if( resample_context ) {
595 if( len > aud_bfr_sz ) {
601 aud_bfr = new float[aud_bfr_sz*channels];
603 int ret = swr_convert(resample_context,
604 (uint8_t**)&aud_bfr, aud_bfr_sz, (const uint8_t**)data, len);
606 ff_err(ret, "FFAudioStream::get_samples: swr_convert failed\n");
615 int FFAudioStream::load_history(uint8_t **data, int len)
618 len = get_samples(samples, data, len);
620 // biggest user bfr since seek + frame
621 realloc(mbsz + len + 1, channels);
627 int FFAudioStream::decode_frame(AVFrame *frame)
629 int first_frame = seeked; seeked = 0;
630 int ret = avcodec_receive_frame(avctx, frame);
632 if( first_frame || ret == AVERROR(EAGAIN) ) return 0;
633 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
634 ff_err(ret, "FFAudioStream::decode_frame: Could not read audio frame\n");
637 int64_t pkt_ts = av_frame_get_best_effort_timestamp(frame);
638 if( pkt_ts != AV_NOPTS_VALUE )
639 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * sample_rate + 0.5;
643 int FFAudioStream::encode_activate()
645 if( writing >= 0 ) return writing;
646 frame_sz = avctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE ?
647 10000 : avctx->frame_size;
648 return FFStream::encode_activate();
651 int64_t FFAudioStream::load_buffer(double ** const sp, int len)
653 reserve(len+1, st->codecpar->channels);
654 for( int ch=0; ch<nch; ++ch )
655 write(sp[ch], len, ch);
659 int FFAudioStream::in_history(int64_t pos)
661 if( pos > curr_pos ) return 0;
663 if( len > sz ) len = sz;
664 if( pos < curr_pos - len ) return 0;
669 int FFAudioStream::init_frame(AVFrame *frame)
671 frame->nb_samples = frame_sz;
672 frame->format = avctx->sample_fmt;
673 frame->channel_layout = avctx->channel_layout;
674 frame->sample_rate = avctx->sample_rate;
675 int ret = av_frame_get_buffer(frame, 0);
677 ff_err(ret, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
681 int FFAudioStream::load(int64_t pos, int len)
683 if( audio_seek(pos) < 0 ) return -1;
684 if( !frame && !(frame=av_frame_alloc()) ) {
685 fprintf(stderr, "FFAudioStream::load: av_frame_alloc failed\n");
688 if( mbsz < len ) mbsz = len;
689 int64_t end_pos = pos + len;
691 for( int i=0; ret>=0 && !flushed && curr_pos<end_pos && i<MAX_RETRY; ++i ) {
692 ret = read_frame(frame);
694 load_history(&frame->extended_data[0], frame->nb_samples);
695 curr_pos += frame->nb_samples;
698 if( end_pos > curr_pos ) {
699 zero(end_pos - curr_pos);
702 len = curr_pos - pos;
707 int FFAudioStream::audio_seek(int64_t pos)
709 if( decode_activate() < 0 ) return -1;
710 if( !st->codecpar ) return -1;
711 if( in_history(pos) ) return 0;
712 if( pos == curr_pos ) return 0;
713 reset_history(); mbsz = 0;
714 // guarentee preload > 1sec samples
715 if( seek(pos-sample_rate, sample_rate) < 0 ) return -1;
719 int FFAudioStream::encode(double **samples, int len)
721 if( encode_activate() <= 0 ) return -1;
724 int64_t count = load_buffer(samples, len);
727 while( ret >= 0 && count >= frame_sz ) {
728 frm = new FFrame(this);
729 if( (ret=frm->initted()) < 0 ) break;
730 AVFrame *frame = *frm;
731 float *bfrp = get_outp(frame_sz);
732 ret = swr_convert(resample_context,
733 (uint8_t **)frame->extended_data, frame_sz,
734 (const uint8_t **)&bfrp, frame_sz);
736 ff_err(ret, "FFAudioStream::encode: swr_convert failed\n");
739 frm->queue(curr_pos);
741 curr_pos += frame_sz;
746 return ret >= 0 ? 0 : 1;
749 int FFAudioStream::encode_frame(AVFrame *frame)
751 return FFStream::encode_frame(frame);
754 void FFAudioStream::load_markers()
756 IndexState *index_state = ffmpeg->file_base->asset->index_state;
757 if( !index_state || idx >= index_state->audio_markers.size() ) return;
758 if( index_state->marker_status == MARKERS_NOTTESTED ) return;
759 FFStream::load_markers(*index_state->audio_markers[idx], sample_rate);
762 IndexMarks *FFAudioStream::get_markers()
764 IndexState *index_state = ffmpeg->file_base->asset->index_state;
765 if( !index_state || idx >= index_state->audio_markers.size() ) return 0;
766 return index_state->audio_markers[idx];
769 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
770 : FFStream(ffmpeg, strm, fidx)
781 FFVideoStream::~FFVideoStream()
785 int FFVideoStream::decode_frame(AVFrame *frame)
787 int first_frame = seeked; seeked = 0;
788 int ret = avcodec_receive_frame(avctx, frame);
790 if( first_frame || ret == AVERROR(EAGAIN) ) return 0;
791 if( ret == AVERROR(EAGAIN) ) return 0;
792 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
793 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame\n");
796 int64_t pkt_ts = av_frame_get_best_effort_timestamp(frame);
797 if( pkt_ts != AV_NOPTS_VALUE )
798 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * frame_rate + 0.5;
802 int FFVideoStream::load(VFrame *vframe, int64_t pos)
804 int ret = video_seek(pos);
805 if( ret < 0 ) return -1;
806 if( !frame && !(frame=av_frame_alloc()) ) {
807 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
810 for( int i=0; ret>=0 && !flushed && curr_pos<=pos && i<MAX_RETRY; ++i ) {
811 ret = read_frame(frame);
812 if( ret > 0 ) ++curr_pos;
814 if( frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0 )
817 ret = convert_cmodel(vframe, frame);
819 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
823 int FFVideoStream::video_seek(int64_t pos)
825 if( decode_activate() < 0 ) return -1;
826 if( !st->codecpar ) return -1;
827 if( pos == curr_pos-1 && !seeked ) return 0;
828 // if close enough, just read up to current
829 int gop = avctx->gop_size;
830 if( gop < 4 ) gop = 4;
831 if( gop > 64 ) gop = 64;
832 int read_limit = curr_pos + 3*gop;
833 if( pos >= curr_pos && pos <= read_limit ) return 0;
834 // guarentee preload more than 2*gop frames
835 if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
839 int FFVideoStream::init_frame(AVFrame *picture)
841 picture->format = avctx->pix_fmt;
842 picture->width = avctx->width;
843 picture->height = avctx->height;
844 int ret = av_frame_get_buffer(picture, 32);
848 int FFVideoStream::encode(VFrame *vframe)
850 if( encode_activate() <= 0 ) return -1;
852 FFrame *picture = new FFrame(this);
853 int ret = picture->initted();
855 AVFrame *frame = *picture;
856 frame->pts = curr_pos;
857 ret = convert_pixfmt(vframe, frame);
860 picture->queue(curr_pos);
864 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
867 return ret >= 0 ? 0 : 1;
870 int FFVideoStream::encode_frame(AVFrame *frame)
873 frame->interlaced_frame = interlaced;
874 frame->top_field_first = top_field_first;
876 return FFStream::encode_frame(frame);
879 AVPixelFormat FFVideoConvert::color_model_to_pix_fmt(int color_model)
881 switch( color_model ) {
882 case BC_YUV422: return AV_PIX_FMT_YUYV422;
883 case BC_RGB888: return AV_PIX_FMT_RGB24;
884 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
885 case BC_BGR8888: return AV_PIX_FMT_BGR0;
886 case BC_BGR888: return AV_PIX_FMT_BGR24;
887 case BC_ARGB8888: return AV_PIX_FMT_ARGB;
888 case BC_ABGR8888: return AV_PIX_FMT_ABGR;
889 case BC_RGB8: return AV_PIX_FMT_RGB8;
890 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
891 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
892 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
893 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
894 case BC_RGB565: return AV_PIX_FMT_RGB565;
895 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
896 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
897 case BC_AYUV16161616: return AV_PIX_FMT_AYUV64LE;
901 return AV_PIX_FMT_NB;
904 int FFVideoConvert::pix_fmt_to_color_model(AVPixelFormat pix_fmt)
907 case AV_PIX_FMT_YUYV422: return BC_YUV422;
908 case AV_PIX_FMT_RGB24: return BC_RGB888;
909 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
910 case AV_PIX_FMT_BGR0: return BC_BGR8888;
911 case AV_PIX_FMT_BGR24: return BC_BGR888;
912 case AV_PIX_FMT_ARGB: return BC_ARGB8888;
913 case AV_PIX_FMT_ABGR: return BC_ABGR8888;
914 case AV_PIX_FMT_RGB8: return BC_RGB8;
915 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
916 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
917 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
918 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
919 case AV_PIX_FMT_RGB565: return BC_RGB565;
920 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
921 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
922 case AV_PIX_FMT_AYUV64LE: return BC_AYUV16161616;
929 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip)
931 AVFrame *ipic = av_frame_alloc();
932 int ret = convert_picture_vframe(frame, ip, ipic);
933 av_frame_free(&ipic);
937 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip, AVFrame *ipic)
939 int cmodel = frame->get_color_model();
940 AVPixelFormat ofmt = color_model_to_pix_fmt(cmodel);
941 if( ofmt == AV_PIX_FMT_NB ) return -1;
942 int size = av_image_fill_arrays(ipic->data, ipic->linesize,
943 frame->get_data(), ofmt, frame->get_w(), frame->get_h(), 1);
944 if( size < 0 ) return -1;
946 int bpp = BC_CModels::calculate_pixelsize(cmodel);
947 int ysz = bpp * frame->get_w(), usz = ysz;
956 // override av_image_fill_arrays() for planar types
957 ipic->data[0] = frame->get_y(); ipic->linesize[0] = ysz;
958 ipic->data[1] = frame->get_u(); ipic->linesize[1] = usz;
959 ipic->data[2] = frame->get_v(); ipic->linesize[2] = usz;
962 ipic->data[0] = frame->get_data();
963 ipic->linesize[0] = frame->get_bytes_per_line();
967 AVPixelFormat pix_fmt = (AVPixelFormat)ip->format;
968 convert_ctx = sws_getCachedContext(convert_ctx, ip->width, ip->height, pix_fmt,
969 frame->get_w(), frame->get_h(), ofmt, SWS_POINT, NULL, NULL, NULL);
971 fprintf(stderr, "FFVideoConvert::convert_picture_frame:"
972 " sws_getCachedContext() failed\n");
975 int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ip->height,
976 ipic->data, ipic->linesize);
978 ff_err(ret, "FFVideoConvert::convert_picture_frame: sws_scale() failed\n");
984 int FFVideoConvert::convert_cmodel(VFrame *frame, AVFrame *ip)
986 // try direct transfer
987 if( !convert_picture_vframe(frame, ip) ) return 1;
988 // use indirect transfer
989 AVPixelFormat ifmt = (AVPixelFormat)ip->format;
990 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
992 for( int i = 0; i <desc->nb_components; ++i ) {
993 int bits = desc->comp[i].depth;
994 if( bits > max_bits ) max_bits = bits;
996 int imodel = pix_fmt_to_color_model(ifmt);
997 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
998 int cmodel = frame->get_color_model();
999 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1000 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1001 imodel = cmodel_is_yuv ?
1002 (BC_CModels::has_alpha(cmodel) ?
1004 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1005 (BC_CModels::has_alpha(cmodel) ?
1006 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1007 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1009 VFrame vframe(ip->width, ip->height, imodel);
1010 if( convert_picture_vframe(&vframe, ip) ) return -1;
1011 frame->transfer_from(&vframe);
1015 int FFVideoConvert::transfer_cmodel(VFrame *frame, AVFrame *ifp)
1017 int ret = convert_cmodel(frame, ifp);
1019 const AVDictionary *src = av_frame_get_metadata(ifp);
1020 AVDictionaryEntry *t = NULL;
1021 BC_Hash *hp = frame->get_params();
1023 while( (t=av_dict_get(src, "", t, AV_DICT_IGNORE_SUFFIX)) )
1024 hp->update(t->key, t->value);
1029 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op)
1031 AVFrame *opic = av_frame_alloc();
1032 int ret = convert_vframe_picture(frame, op, opic);
1033 av_frame_free(&opic);
1037 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op, AVFrame *opic)
1039 int cmodel = frame->get_color_model();
1040 AVPixelFormat ifmt = color_model_to_pix_fmt(cmodel);
1041 if( ifmt == AV_PIX_FMT_NB ) return -1;
1042 int size = av_image_fill_arrays(opic->data, opic->linesize,
1043 frame->get_data(), ifmt, frame->get_w(), frame->get_h(), 1);
1044 if( size < 0 ) return -1;
1046 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1047 int ysz = bpp * frame->get_w(), usz = ysz;
1056 // override av_image_fill_arrays() for planar types
1057 opic->data[0] = frame->get_y(); opic->linesize[0] = ysz;
1058 opic->data[1] = frame->get_u(); opic->linesize[1] = usz;
1059 opic->data[2] = frame->get_v(); opic->linesize[2] = usz;
1062 opic->data[0] = frame->get_data();
1063 opic->linesize[0] = frame->get_bytes_per_line();
1067 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1068 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(),
1069 ifmt, op->width, op->height, ofmt, SWS_POINT, NULL, NULL, NULL);
1070 if( !convert_ctx ) {
1071 fprintf(stderr, "FFVideoConvert::convert_frame_picture:"
1072 " sws_getCachedContext() failed\n");
1075 int ret = sws_scale(convert_ctx, opic->data, opic->linesize, 0, frame->get_h(),
1076 op->data, op->linesize);
1078 ff_err(ret, "FFVideoConvert::convert_frame_picture: sws_scale() failed\n");
1084 int FFVideoConvert::convert_pixfmt(VFrame *frame, AVFrame *op)
1086 // try direct transfer
1087 if( !convert_vframe_picture(frame, op) ) return 1;
1088 // use indirect transfer
1089 int cmodel = frame->get_color_model();
1090 int max_bits = BC_CModels::calculate_pixelsize(cmodel) * 8;
1091 max_bits /= BC_CModels::components(cmodel);
1092 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1093 int imodel = pix_fmt_to_color_model(ofmt);
1094 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1095 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1096 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1097 imodel = cmodel_is_yuv ?
1098 (BC_CModels::has_alpha(cmodel) ?
1100 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1101 (BC_CModels::has_alpha(cmodel) ?
1102 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1103 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1105 VFrame vframe(frame->get_w(), frame->get_h(), imodel);
1106 vframe.transfer_from(frame);
1107 if( !convert_vframe_picture(&vframe, op) ) return 1;
1111 int FFVideoConvert::transfer_pixfmt(VFrame *frame, AVFrame *ofp)
1113 int ret = convert_pixfmt(frame, ofp);
1115 BC_Hash *hp = frame->get_params();
1116 AVDictionary **dict = avpriv_frame_get_metadatap(ofp);
1117 //av_dict_free(dict);
1118 for( int i=0; i<hp->size(); ++i ) {
1119 char *key = hp->get_key(i), *val = hp->get_value(i);
1120 av_dict_set(dict, key, val, 0);
1126 void FFVideoStream::load_markers()
1128 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1129 if( !index_state || idx >= index_state->video_markers.size() ) return;
1130 FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
1133 IndexMarks *FFVideoStream::get_markers()
1135 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1136 if( !index_state || idx >= index_state->video_markers.size() ) return 0;
1137 return !index_state ? 0 : index_state->video_markers[idx];
1141 FFMPEG::FFMPEG(FileBase *file_base)
1144 this->file_base = file_base;
1145 memset(file_format,0,sizeof(file_format));
1146 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
1147 flow_lock = new Condition(1,"FFStream::flow_lock",0);
1150 decoding = encoding = 0;
1151 has_audio = has_video = 0;
1154 opt_video_filter = 0;
1155 opt_audio_filter = 0;
1156 char option_path[BCTEXTLEN];
1157 set_option_path(option_path, "%s", "ffmpeg.opts");
1158 read_options(option_path, opts);
1163 ff_lock("FFMPEG::~FFMPEG()");
1165 ffaudio.remove_all_objects();
1166 ffvideo.remove_all_objects();
1167 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1171 av_dict_free(&opts);
1172 delete [] opt_video_filter;
1173 delete [] opt_audio_filter;
1176 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1178 const int *p = codec->supported_samplerates;
1179 if( !p ) return sample_rate;
1181 if( *p == sample_rate ) return *p;
1187 static inline AVRational std_frame_rate(int i)
1189 static const int m1 = 1001*12, m2 = 1000*12;
1190 static const int freqs[] = {
1191 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1192 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
1194 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1195 return (AVRational) { freq, 1001*12 };
1198 AVRational FFMPEG::check_frame_rate(AVCodec *codec, double frame_rate)
1200 const AVRational *p = codec->supported_framerates;
1201 AVRational rate, best_rate = (AVRational) { 0, 0 };
1202 double max_err = 1.; int i = 0;
1203 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1204 double framerate = (double) rate.num / rate.den;
1205 double err = fabs(frame_rate/framerate - 1.);
1206 if( err >= max_err ) continue;
1210 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1213 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1216 double display_aspect = asset->width / (double)asset->height;
1217 double sample_aspect = asset->aspect_ratio / display_aspect;
1218 int width = 1000000, height = width * sample_aspect + 0.5;
1220 MWindow::create_aspect_ratio(w, h, width, height);
1221 return (AVRational){(int)w, (int)h};
1224 return (AVRational){1, 1};
1228 AVRational FFMPEG::to_time_base(int sample_rate)
1230 return (AVRational){1, sample_rate};
1233 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
1235 char *ep = path + BCTEXTLEN-1;
1236 strncpy(path, File::get_cindat_path(), ep-path);
1237 strncat(path, "/ffmpeg/", ep-path);
1238 path += strlen(path);
1241 path += vsnprintf(path, ep-path, fmt, ap);
1246 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
1251 set_option_path(path, "%s/%s", type, spec);
1254 int FFMPEG::get_format(char *format, const char *path, const char *spec)
1256 char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
1257 get_option_path(option_path, path, spec);
1258 FILE *fp = fopen(option_path,"r");
1261 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1263 line[sizeof(line)-1] = 0;
1264 ret = scan_option_line(line, format, codec);
1270 int FFMPEG::get_codec(char *codec, const char *path, const char *spec)
1272 char option_path[BCTEXTLEN], line[BCTEXTLEN], format[BCTEXTLEN];
1273 get_option_path(option_path, path, spec);
1274 FILE *fp = fopen(option_path,"r");
1277 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1280 line[sizeof(line)-1] = 0;
1281 ret = scan_option_line(line, format, codec);
1284 char *vp = codec, *ep = vp+BCTEXTLEN-1;
1285 while( vp < ep && *vp && *vp != '|' ) ++vp;
1286 if( *vp == '|' ) --vp;
1287 while( vp > codec && (*vp==' ' || *vp=='\t') ) *vp-- = 0;
1292 int FFMPEG::get_file_format()
1294 char audio_muxer[BCSTRLEN], video_muxer[BCSTRLEN];
1295 char audio_format[BCSTRLEN], video_format[BCSTRLEN];
1296 audio_muxer[0] = audio_format[0] = 0;
1297 video_muxer[0] = video_format[0] = 0;
1298 Asset *asset = file_base->asset;
1299 int ret = asset ? 0 : 1;
1300 if( !ret && asset->audio_data ) {
1301 if( !(ret=get_format(audio_format, "audio", asset->acodec)) ) {
1302 if( get_format(audio_muxer, "format", audio_format) ) {
1303 strcpy(audio_muxer, audio_format);
1304 audio_format[0] = 0;
1308 if( !ret && asset->video_data ) {
1309 if( !(ret=get_format(video_format, "video", asset->vcodec)) ) {
1310 if( get_format(video_muxer, "format", video_format) ) {
1311 strcpy(video_muxer, video_format);
1312 video_format[0] = 0;
1316 if( !ret && !audio_muxer[0] && !video_muxer[0] )
1318 if( !ret && audio_muxer[0] && video_muxer[0] &&
1319 strcmp(audio_muxer, video_muxer) ) ret = -1;
1320 if( !ret && audio_format[0] && video_format[0] &&
1321 strcmp(audio_format, video_format) ) ret = -1;
1323 strcpy(file_format, !audio_format[0] && !video_format[0] ?
1324 (audio_muxer[0] ? audio_muxer : video_muxer) :
1325 (audio_format[0] ? audio_format : video_format));
1329 int FFMPEG::scan_option_line(char *cp, char *tag, char *val)
1331 while( *cp == ' ' || *cp == '\t' ) ++cp;
1333 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' && *cp != '\n' ) ++cp;
1335 if( !len || len > BCSTRLEN-1 ) return 1;
1336 while( bp < cp ) *tag++ = *bp++;
1338 while( *cp == ' ' || *cp == '\t' ) ++cp;
1339 if( *cp == '=' ) ++cp;
1340 while( *cp == ' ' || *cp == '\t' ) ++cp;
1342 while( *cp && *cp != '\n' ) ++cp;
1344 if( len > BCTEXTLEN-1 ) return 1;
1345 while( bp < cp ) *val++ = *bp++;
1350 int FFMPEG::load_defaults(const char *path, const char *type,
1351 char *codec, char *codec_options, int len)
1353 char default_file[BCTEXTLEN];
1354 set_option_path(default_file, "%s/%s.dfl", path, type);
1355 FILE *fp = fopen(default_file,"r");
1357 fgets(codec, BCSTRLEN, fp);
1359 while( *cp && *cp!='\n' ) ++cp;
1361 while( len > 0 && fgets(codec_options, len, fp) ) {
1362 int n = strlen(codec_options);
1363 codec_options += n; len -= n;
1366 set_option_path(default_file, "%s/%s", path, codec);
1367 return load_options(default_file, codec_options, len);
1370 void FFMPEG::set_asset_format(Asset *asset, const char *text)
1372 if( asset->format != FILE_FFMPEG ) return;
1373 if( text != asset->fformat )
1374 strcpy(asset->fformat, text);
1375 if( !asset->ff_audio_options[0] ) {
1376 asset->audio_data = !load_defaults("audio", text, asset->acodec,
1377 asset->ff_audio_options, sizeof(asset->ff_audio_options));
1379 if( !asset->ff_video_options[0] ) {
1380 asset->video_data = !load_defaults("video", text, asset->vcodec,
1381 asset->ff_video_options, sizeof(asset->ff_video_options));
1385 int FFMPEG::get_encoder(const char *options,
1386 char *format, char *codec, char *bsfilter)
1388 FILE *fp = fopen(options,"r");
1390 eprintf(_("options open failed %s\n"),options);
1393 if( get_encoder(fp, format, codec, bsfilter) )
1394 eprintf(_("format/codec not found %s\n"), options);
1399 int FFMPEG::get_encoder(FILE *fp,
1400 char *format, char *codec, char *bsfilter)
1402 format[0] = codec[0] = bsfilter[0] = 0;
1403 char line[BCTEXTLEN];
1404 if( !fgets(line, sizeof(line), fp) ) return 1;
1405 line[sizeof(line)-1] = 0;
1406 if( scan_option_line(line, format, codec) ) return 1;
1408 while( *cp && *cp != '|' ) ++cp;
1409 if( !*cp ) return 0;
1411 do { *bp-- = 0; } while( bp>=codec && (*bp==' ' || *bp == '\t' ) );
1412 while( *++cp && (*cp==' ' || *cp == '\t') );
1414 for( int i=BCTEXTLEN; --i>0 && *cp; ) *bp++ = *cp++;
1419 int FFMPEG::read_options(const char *options, AVDictionary *&opts, int skip)
1421 FILE *fp = fopen(options,"r");
1424 while( !ret && --skip >= 0 ) {
1426 while( ch >= 0 && ch != '\n' ) ch = getc(fp);
1427 if( ch < 0 ) ret = 1;
1430 ret = read_options(fp, options, opts);
1435 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
1437 FILE *fp = fmemopen((void *)options,strlen(options),"r");
1439 int ret = read_options(fp, options, opts);
1441 AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
1442 if( tag ) st->id = strtol(tag->value,0,0);
1446 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
1448 int ret = 0, no = 0;
1449 char line[BCTEXTLEN];
1450 while( !ret && fgets(line, sizeof(line), fp) ) {
1451 line[sizeof(line)-1] = 0;
1452 if( line[0] == '#' ) continue;
1453 if( line[0] == '\n' ) continue;
1454 char key[BCSTRLEN], val[BCTEXTLEN];
1455 if( scan_option_line(line, key, val) ) {
1456 eprintf(_("err reading %s: line %d\n"), options, no);
1460 if( !strcmp(key, "duration") )
1461 opt_duration = strtod(val, 0);
1462 else if( !strcmp(key, "video_filter") )
1463 opt_video_filter = cstrdup(val);
1464 else if( !strcmp(key, "audio_filter") )
1465 opt_audio_filter = cstrdup(val);
1466 else if( !strcmp(key, "loglevel") )
1469 av_dict_set(&opts, key, val, 0);
1475 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
1477 char option_path[BCTEXTLEN];
1478 set_option_path(option_path, "%s", options);
1479 return read_options(option_path, opts);
1482 int FFMPEG::load_options(const char *path, char *bfr, int len)
1485 FILE *fp = fopen(path, "r");
1487 fgets(bfr, len, fp); // skip hdr
1488 len = fread(bfr, 1, len-1, fp);
1489 if( len < 0 ) len = 0;
1495 void FFMPEG::set_loglevel(const char *ap)
1497 if( !ap || !*ap ) return;
1502 { "quiet" , AV_LOG_QUIET },
1503 { "panic" , AV_LOG_PANIC },
1504 { "fatal" , AV_LOG_FATAL },
1505 { "error" , AV_LOG_ERROR },
1506 { "warning", AV_LOG_WARNING },
1507 { "info" , AV_LOG_INFO },
1508 { "verbose", AV_LOG_VERBOSE },
1509 { "debug" , AV_LOG_DEBUG },
1511 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
1512 if( !strcmp(log_levels[i].name, ap) ) {
1513 av_log_set_level(log_levels[i].level);
1517 av_log_set_level(atoi(ap));
1520 double FFMPEG::to_secs(int64_t time, AVRational time_base)
1522 double base_time = time == AV_NOPTS_VALUE ? 0 :
1523 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
1524 return base_time / AV_TIME_BASE;
1527 int FFMPEG::info(char *text, int len)
1529 if( len <= 0 ) return 0;
1531 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
1533 report("format: %s\n",fmt_ctx->iformat->name);
1534 if( ffvideo.size() > 0 )
1535 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
1536 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
1537 FFVideoStream *vid = ffvideo[vidx];
1538 AVStream *st = vid->st;
1539 AVCodecID codec_id = st->codecpar->codec_id;
1540 report(_("vid%d (%d), id 0x%06x:\n"), vid->idx, vid->fidx, codec_id);
1541 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
1542 report(" video%d %s", vidx+1, desc ? desc->name : " (unkn)");
1543 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
1544 AVPixelFormat pix_fmt = (AVPixelFormat)st->codecpar->format;
1545 const char *pfn = av_get_pix_fmt_name(pix_fmt);
1546 report(" pix %s\n", pfn ? pfn : "(unkn)");
1547 double secs = to_secs(st->duration, st->time_base);
1548 int64_t length = secs * vid->frame_rate + 0.5;
1549 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
1550 int64_t nudge = ofs * vid->frame_rate;
1551 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1552 report(" %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
1553 int hrs = secs/3600; secs -= hrs*3600;
1554 int mins = secs/60; secs -= mins*60;
1555 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1557 if( ffaudio.size() > 0 )
1558 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
1559 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
1560 FFAudioStream *aud = ffaudio[aidx];
1561 AVStream *st = aud->st;
1562 AVCodecID codec_id = st->codecpar->codec_id;
1563 report(_("aud%d (%d), id 0x%06x:\n"), aud->idx, aud->fidx, codec_id);
1564 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
1565 int nch = aud->channels, ch0 = aud->channel0+1;
1566 report(" audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
1567 AVSampleFormat sample_fmt = (AVSampleFormat)st->codecpar->format;
1568 const char *fmt = av_get_sample_fmt_name(sample_fmt);
1569 report(" %s %d", fmt, aud->sample_rate);
1570 int sample_bits = av_get_bits_per_sample(codec_id);
1571 report(" %dbits\n", sample_bits);
1572 double secs = to_secs(st->duration, st->time_base);
1573 int64_t length = secs * aud->sample_rate + 0.5;
1574 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
1575 int64_t nudge = ofs * aud->sample_rate;
1576 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1577 report(" %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
1578 int hrs = secs/3600; secs -= hrs*3600;
1579 int mins = secs/60; secs -= mins*60;
1580 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1582 if( fmt_ctx->nb_programs > 0 )
1583 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
1584 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
1585 report("program %d", i+1);
1586 AVProgram *pgrm = fmt_ctx->programs[i];
1587 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1588 int idx = pgrm->stream_index[j];
1589 int vidx = ffvideo.size();
1590 while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
1592 report(", vid%d", vidx);
1595 int aidx = ffaudio.size();
1596 while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
1598 report(", aud%d", aidx);
1601 report(", (%d)", pgrm->stream_index[j]);
1606 AVDictionaryEntry *tag = 0;
1607 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
1608 report("%s=%s\n", tag->key, tag->value);
1617 int FFMPEG::init_decoder(const char *filename)
1619 ff_lock("FFMPEG::init_decoder");
1621 char file_opts[BCTEXTLEN];
1622 char *bp = strrchr(strcpy(file_opts, filename), '/');
1623 char *sp = strrchr(!bp ? file_opts : bp, '.');
1626 strcpy(sp, ".opts");
1627 fp = fopen(file_opts, "r");
1630 read_options(fp, file_opts, opts);
1634 load_options("decode.opts", opts);
1635 AVDictionary *fopts = 0;
1636 av_dict_copy(&fopts, opts, 0);
1637 int ret = avformat_open_input(&fmt_ctx, filename, NULL, &fopts);
1638 av_dict_free(&fopts);
1640 ret = avformat_find_stream_info(fmt_ctx, NULL);
1645 return !ret ? 0 : 1;
1648 int FFMPEG::open_decoder()
1651 if( stat(fmt_ctx->filename, &st) < 0 ) {
1652 eprintf(_("can't stat file: %s\n"), fmt_ctx->filename);
1656 int64_t file_bits = 8 * st.st_size;
1657 if( !fmt_ctx->bit_rate && opt_duration > 0 )
1658 fmt_ctx->bit_rate = file_bits / opt_duration;
1661 if( fmt_ctx->bit_rate > 0 ) {
1662 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1663 AVStream *st = fmt_ctx->streams[i];
1664 if( st->duration != AV_NOPTS_VALUE ) continue;
1665 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
1666 st->duration = av_rescale(file_bits, st->time_base.den,
1667 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
1672 printf("FFMPEG::open_decoder: some stream times estimated\n");
1674 ff_lock("FFMPEG::open_decoder");
1675 int ret = 0, bad_time = 0;
1676 for( int i=0; !ret && i<(int)fmt_ctx->nb_streams; ++i ) {
1677 AVStream *st = fmt_ctx->streams[i];
1678 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
1679 AVCodecParameters *avpar = st->codecpar;
1680 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avpar->codec_id);
1681 if( !codec_desc ) continue;
1682 switch( avpar->codec_type ) {
1683 case AVMEDIA_TYPE_VIDEO: {
1684 if( avpar->width < 1 ) continue;
1685 if( avpar->height < 1 ) continue;
1686 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
1687 if( framerate.num < 1 ) continue;
1689 int vidx = ffvideo.size();
1690 FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
1691 vstrm_index.append(ffidx(vidx, 0));
1692 ffvideo.append(vid);
1693 vid->width = avpar->width;
1694 vid->height = avpar->height;
1695 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
1696 double secs = to_secs(st->duration, st->time_base);
1697 vid->length = secs * vid->frame_rate;
1698 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
1699 vid->nudge = st->start_time;
1701 if( opt_video_filter )
1702 ret = vid->create_filter(opt_video_filter, avpar);
1704 case AVMEDIA_TYPE_AUDIO: {
1705 if( avpar->channels < 1 ) continue;
1706 if( avpar->sample_rate < 1 ) continue;
1708 int aidx = ffaudio.size();
1709 FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
1710 ffaudio.append(aud);
1711 aud->channel0 = astrm_index.size();
1712 aud->channels = avpar->channels;
1713 for( int ch=0; ch<aud->channels; ++ch )
1714 astrm_index.append(ffidx(aidx, ch));
1715 aud->sample_rate = avpar->sample_rate;
1716 double secs = to_secs(st->duration, st->time_base);
1717 aud->length = secs * aud->sample_rate;
1718 if( avpar->format != AV_SAMPLE_FMT_FLT ) {
1719 uint64_t layout = av_get_default_channel_layout(avpar->channels);
1720 if( !layout ) layout = ((uint64_t)1<<aud->channels) - 1;
1721 AVSampleFormat sample_format = (AVSampleFormat)avpar->format;
1722 aud->resample_context = swr_alloc_set_opts(NULL,
1723 layout, AV_SAMPLE_FMT_FLT, avpar->sample_rate,
1724 layout, sample_format, avpar->sample_rate,
1726 swr_init(aud->resample_context);
1728 aud->nudge = st->start_time;
1730 if( opt_audio_filter )
1731 ret = aud->create_filter(opt_audio_filter, avpar);
1737 printf("FFMPEG::open_decoder: some stream have bad times\n");
1739 return ret < 0 ? -1 : 0;
1743 int FFMPEG::init_encoder(const char *filename)
1745 int fd = ::open(filename,O_WRONLY);
1746 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
1748 eprintf(_("bad file path: %s\n"), filename);
1752 int ret = get_file_format();
1754 eprintf(_("bad file format: %s\n"), filename);
1758 eprintf(_("mismatch audio/video file format: %s\n"), filename);
1761 ff_lock("FFMPEG::init_encoder");
1763 char format[BCSTRLEN];
1764 if( get_format(format, "format", file_format) )
1765 strcpy(format, file_format);
1766 avformat_alloc_output_context2(&fmt_ctx, 0, format, filename);
1768 eprintf(_("failed: %s\n"), filename);
1773 load_options("encode.opts", opts);
1779 int FFMPEG::open_encoder(const char *type, const char *spec)
1782 Asset *asset = file_base->asset;
1783 char *filename = asset->path;
1784 AVDictionary *sopts = 0;
1785 av_dict_copy(&sopts, opts, 0);
1786 char option_path[BCTEXTLEN];
1787 set_option_path(option_path, "%s/%s.opts", type, type);
1788 read_options(option_path, sopts);
1789 get_option_path(option_path, type, spec);
1790 char format_name[BCSTRLEN], codec_name[BCTEXTLEN], bsfilter[BCTEXTLEN];
1791 if( get_encoder(option_path, format_name, codec_name, bsfilter) ) {
1792 eprintf(_("get_encoder failed %s:%s\n"), option_path, filename);
1796 if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
1797 else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
1798 else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
1801 ff_lock("FFMPEG::open_encoder");
1804 AVCodecContext *ctx = 0;
1806 const AVCodecDescriptor *codec_desc = 0;
1807 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
1809 eprintf(_("cant find codec %s:%s\n"), codec_name, filename);
1813 codec_desc = avcodec_descriptor_get(codec->id);
1815 eprintf(_("unknown codec %s:%s\n"), codec_name, filename);
1820 st = avformat_new_stream(fmt_ctx, 0);
1822 eprintf(_("cant create stream %s:%s\n"), codec_name, filename);
1827 switch( codec_desc->type ) {
1828 case AVMEDIA_TYPE_AUDIO: {
1830 eprintf(_("duplicate audio %s:%s\n"), codec_name, filename);
1834 if( scan_options(asset->ff_audio_options, sopts, st) ) {
1835 eprintf(_("bad audio options %s:%s\n"), codec_name, filename);
1840 ctx = avcodec_alloc_context3(codec);
1841 if( asset->ff_audio_bitrate > 0 ) {
1842 ctx->bit_rate = asset->ff_audio_bitrate;
1844 sprintf(arg, "%d", asset->ff_audio_bitrate);
1845 av_dict_set(&sopts, "b", arg, 0);
1847 int aidx = ffaudio.size();
1848 int fidx = aidx + ffvideo.size();
1849 FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
1850 aud->avctx = ctx; ffaudio.append(aud); fst = aud;
1851 aud->sample_rate = asset->sample_rate;
1852 ctx->channels = aud->channels = asset->channels;
1853 for( int ch=0; ch<aud->channels; ++ch )
1854 astrm_index.append(ffidx(aidx, ch));
1855 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
1856 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
1857 if( !ctx->sample_rate ) {
1858 eprintf(_("check_sample_rate failed %s\n"), filename);
1862 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
1863 ctx->sample_fmt = codec->sample_fmts[0];
1864 uint64_t layout = av_get_default_channel_layout(ctx->channels);
1865 aud->resample_context = swr_alloc_set_opts(NULL,
1866 layout, ctx->sample_fmt, aud->sample_rate,
1867 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
1869 swr_init(aud->resample_context);
1872 case AVMEDIA_TYPE_VIDEO: {
1874 eprintf(_("duplicate video %s:%s\n"), codec_name, filename);
1878 if( scan_options(asset->ff_video_options, sopts, st) ) {
1879 eprintf(_("bad video options %s:%s\n"), codec_name, filename);
1884 ctx = avcodec_alloc_context3(codec);
1885 if( asset->ff_video_bitrate > 0 ) {
1886 ctx->bit_rate = asset->ff_video_bitrate;
1888 sprintf(arg, "%d", asset->ff_video_bitrate);
1889 av_dict_set(&sopts, "b", arg, 0);
1891 else if( asset->ff_video_quality >= 0 ) {
1892 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
1893 ctx->qmin = ctx->qmax = asset->ff_video_quality;
1894 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
1895 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
1896 ctx->flags |= CODEC_FLAG_QSCALE;
1898 av_dict_set(&sopts, "flags", "+qscale", 0);
1899 sprintf(arg, "%d", asset->ff_video_quality);
1900 av_dict_set(&sopts, "qscale", arg, 0);
1901 sprintf(arg, "%d", ctx->global_quality);
1902 av_dict_set(&sopts, "global_quality", arg, 0);
1904 int vidx = ffvideo.size();
1905 int fidx = vidx + ffaudio.size();
1906 FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
1907 vstrm_index.append(ffidx(vidx, 0));
1908 vid->avctx = ctx; ffvideo.append(vid); fst = vid;
1909 vid->width = asset->width;
1910 ctx->width = (vid->width+3) & ~3;
1911 vid->height = asset->height;
1912 ctx->height = (vid->height+3) & ~3;
1913 vid->frame_rate = asset->frame_rate;
1914 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
1915 ctx->pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
1916 AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
1917 if( !frame_rate.num || !frame_rate.den ) {
1918 eprintf(_("check_frame_rate failed %s\n"), filename);
1922 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
1923 st->time_base = ctx->time_base;
1925 vid->interlaced = asset->interlace_mode == ILACE_MODE_TOP_FIRST ||
1926 asset->interlace_mode == ILACE_MODE_BOTTOM_FIRST ? 1 : 0;
1927 vid->top_field_first = asset->interlace_mode == ILACE_MODE_TOP_FIRST ? 1 : 0;
1930 eprintf(_("not audio/video, %s:%s\n"), codec_name, filename);
1935 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
1936 ctx->flags |= CODEC_FLAG_GLOBAL_HEADER;
1938 av_dict_set(&sopts, "cin_bitrate", 0, 0);
1939 av_dict_set(&sopts, "cin_quality", 0, 0);
1941 ret = avcodec_open2(ctx, codec, &sopts);
1943 ret = avcodec_parameters_from_context(st->codecpar, ctx);
1945 fprintf(stderr, "Could not copy the stream parameters\n");
1948 ff_err(ret,"FFMPEG::open_encoder");
1949 eprintf(_("open failed %s:%s\n"), codec_name, filename);
1955 if( !ret && fst && bsfilter[0] ) {
1956 ret = av_bsf_list_parse_str(bsfilter, &fst->bsfc);
1958 ff_err(ret,"FFMPEG::open_encoder");
1959 eprintf(_("bitstream filter failed %s:\n%s\n"), filename, bsfilter);
1970 av_dict_free(&sopts);
1974 int FFMPEG::close_encoder()
1977 if( encoding > 0 ) {
1978 av_write_trailer(fmt_ctx);
1979 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
1980 avio_closep(&fmt_ctx->pb);
1986 int FFMPEG::decode_activate()
1988 if( decoding < 0 ) {
1990 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
1991 ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
1992 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
1993 ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
1994 // set nudges for each program stream set
1995 const int64_t min_nudge = INT64_MIN+1;
1996 int npgrms = fmt_ctx->nb_programs;
1997 for( int i=0; i<npgrms; ++i ) {
1998 AVProgram *pgrm = fmt_ctx->programs[i];
1999 // first start time video stream
2000 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2001 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2002 int fidx = pgrm->stream_index[j];
2003 AVStream *st = fmt_ctx->streams[fidx];
2004 AVCodecParameters *avpar = st->codecpar;
2005 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2006 if( st->start_time == AV_NOPTS_VALUE ) continue;
2007 if( vstart_time < st->start_time )
2008 vstart_time = st->start_time;
2011 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2012 if( st->start_time == AV_NOPTS_VALUE ) continue;
2013 if( astart_time < st->start_time )
2014 astart_time = st->start_time;
2018 //since frame rate is much more grainy than sample rate, it is better to
2019 // align using video, so that total absolute error is minimized.
2020 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2021 astart_time > min_nudge ? astart_time : AV_NOPTS_VALUE;
2022 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2023 int fidx = pgrm->stream_index[j];
2024 AVStream *st = fmt_ctx->streams[fidx];
2025 AVCodecParameters *avpar = st->codecpar;
2026 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2027 for( int k=0; k<ffvideo.size(); ++k ) {
2028 if( ffvideo[k]->fidx != fidx ) continue;
2029 ffvideo[k]->nudge = nudge;
2033 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2034 for( int k=0; k<ffaudio.size(); ++k ) {
2035 if( ffaudio[k]->fidx != fidx ) continue;
2036 ffaudio[k]->nudge = nudge;
2042 // set nudges for any streams not yet set
2043 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2044 int nstreams = fmt_ctx->nb_streams;
2045 for( int i=0; i<nstreams; ++i ) {
2046 AVStream *st = fmt_ctx->streams[i];
2047 AVCodecParameters *avpar = st->codecpar;
2048 switch( avpar->codec_type ) {
2049 case AVMEDIA_TYPE_VIDEO: {
2050 if( st->start_time == AV_NOPTS_VALUE ) continue;
2051 int vidx = ffvideo.size();
2052 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
2053 if( vidx >= 0 && ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
2054 if( vstart_time < st->start_time )
2055 vstart_time = st->start_time;
2057 case AVMEDIA_TYPE_AUDIO: {
2058 if( st->start_time == AV_NOPTS_VALUE ) continue;
2059 int aidx = ffaudio.size();
2060 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
2061 if( aidx >= 0 && ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
2062 if( astart_time < st->start_time )
2063 astart_time = st->start_time;
2068 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2069 astart_time > min_nudge ? astart_time : AV_NOPTS_VALUE;
2070 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
2071 if( ffvideo[vidx]->nudge == AV_NOPTS_VALUE )
2072 ffvideo[vidx]->nudge = nudge;
2074 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2075 if( ffaudio[aidx]->nudge == AV_NOPTS_VALUE )
2076 ffaudio[aidx]->nudge = nudge;
2083 int FFMPEG::encode_activate()
2086 if( encoding < 0 ) {
2088 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
2089 (ret=avio_open(&fmt_ctx->pb, fmt_ctx->filename, AVIO_FLAG_WRITE)) < 0 ) {
2090 ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
2096 AVProgram *prog = av_new_program(fmt_ctx, prog_id);
2097 for( int i=0; i< ffvideo.size(); ++i )
2098 av_program_add_stream_index(fmt_ctx, prog_id, ffvideo[i]->fidx);
2099 for( int i=0; i< ffaudio.size(); ++i )
2100 av_program_add_stream_index(fmt_ctx, prog_id, ffaudio[i]->fidx);
2101 int pi = fmt_ctx->nb_programs;
2102 while( --pi >= 0 && fmt_ctx->programs[pi]->id != prog_id );
2103 AVDictionary **meta = &prog->metadata;
2104 av_dict_set(meta, "service_provider", "cin5", 0);
2105 const char *path = fmt_ctx->filename, *bp = strrchr(path,'/');
2106 if( bp ) path = bp + 1;
2107 av_dict_set(meta, "title", path, 0);
2109 if( ffaudio.size() ) {
2110 const char *ep = getenv("CIN_AUDIO_LANG"), *lp = 0;
2111 if( !ep && (lp=getenv("LANG")) ) { // some are guesses
2112 static struct { const char lc[3], lng[4]; } lcode[] = {
2113 { "en", "eng" }, { "de", "ger" }, { "es", "spa" },
2114 { "eu", "bas" }, { "fr", "fre" }, { "el", "gre" },
2115 { "hi", "hin" }, { "it", "ita" }, { "ja", "jap" },
2116 { "ko", "kor" }, { "du", "dut" }, { "pl", "pol" },
2117 { "pt", "por" }, { "ru", "rus" }, { "sl", "slv" },
2118 { "uk", "ukr" }, { "vi", "vie" }, { "zh", "chi" },
2120 for( int i=sizeof(lcode)/sizeof(lcode[0]); --i>=0 && !ep; )
2121 if( !strncmp(lcode[i].lc,lp,2) ) ep = lcode[i].lng;
2123 if( !ep ) ep = "und";
2125 strncpy(lang,ep,3); lang[3] = 0;
2126 AVStream *st = ffaudio[0]->st;
2127 av_dict_set(&st->metadata,"language",lang,0);
2130 AVDictionary *fopts = 0;
2131 char option_path[BCTEXTLEN];
2132 set_option_path(option_path, "format/%s", file_format);
2133 read_options(option_path, fopts, 1);
2134 ret = avformat_write_header(fmt_ctx, &fopts);
2136 ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
2140 av_dict_free(&fopts);
2147 int FFMPEG::audio_seek(int stream, int64_t pos)
2149 int aidx = astrm_index[stream].st_idx;
2150 FFAudioStream *aud = ffaudio[aidx];
2151 aud->audio_seek(pos);
2155 int FFMPEG::video_seek(int stream, int64_t pos)
2157 int vidx = vstrm_index[stream].st_idx;
2158 FFVideoStream *vid = ffvideo[vidx];
2159 vid->video_seek(pos);
2164 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
2166 if( !has_audio || chn >= astrm_index.size() ) return -1;
2167 int aidx = astrm_index[chn].st_idx;
2168 FFAudioStream *aud = ffaudio[aidx];
2169 if( aud->load(pos, len) < len ) return -1;
2170 int ch = astrm_index[chn].st_ch;
2171 int ret = aud->read(samples,len,ch);
2175 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
2177 if( !has_video || layer >= vstrm_index.size() ) return -1;
2178 int vidx = vstrm_index[layer].st_idx;
2179 FFVideoStream *vid = ffvideo[vidx];
2180 return vid->load(vframe, pos);
2184 int FFMPEG::encode(int stream, double **samples, int len)
2186 FFAudioStream *aud = ffaudio[stream];
2187 return aud->encode(samples, len);
2191 int FFMPEG::encode(int stream, VFrame *frame)
2193 FFVideoStream *vid = ffvideo[stream];
2194 return vid->encode(frame);
2197 void FFMPEG::start_muxer()
2205 void FFMPEG::stop_muxer()
2214 void FFMPEG::flow_off()
2217 flow_lock->lock("FFMPEG::flow_off");
2221 void FFMPEG::flow_on()
2225 flow_lock->unlock();
2228 void FFMPEG::flow_ctl()
2231 flow_lock->lock("FFMPEG::flow_ctl");
2232 flow_lock->unlock();
2236 int FFMPEG::mux_audio(FFrame *frm)
2238 FFStream *fst = frm->fst;
2239 AVCodecContext *ctx = fst->avctx;
2240 AVFrame *frame = *frm;
2241 AVRational tick_rate = {1, ctx->sample_rate};
2242 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
2243 int ret = fst->encode_frame(frame);
2245 ff_err(ret, "FFMPEG::mux_audio");
2246 return ret >= 0 ? 0 : 1;
2249 int FFMPEG::mux_video(FFrame *frm)
2251 FFStream *fst = frm->fst;
2252 AVFrame *frame = *frm;
2253 frame->pts = frm->position;
2254 int ret = fst->encode_frame(frame);
2256 ff_err(ret, "FFMPEG::mux_video");
2257 return ret >= 0 ? 0 : 1;
2263 double atm = -1, vtm = -1;
2264 FFrame *afrm = 0, *vfrm = 0;
2266 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
2267 FFStream *fst = ffaudio[i];
2268 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
2269 FFrame *frm = fst->frms.first;
2270 if( !frm ) { if( !done ) return; continue; }
2271 double tm = to_secs(frm->position, fst->avctx->time_base);
2272 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
2274 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
2275 FFStream *fst = ffvideo[i];
2276 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
2277 FFrame *frm = fst->frms.first;
2278 if( !frm ) { if( !done ) return; continue; }
2279 double tm = to_secs(frm->position, fst->avctx->time_base);
2280 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
2282 if( !demand ) flow_off();
2283 if( !afrm && !vfrm ) break;
2284 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
2285 vfrm->position, vfrm->fst->avctx->time_base,
2286 afrm->position, afrm->fst->avctx->time_base);
2287 FFrame *frm = v <= 0 ? vfrm : afrm;
2288 if( frm == afrm ) mux_audio(frm);
2289 if( frm == vfrm ) mux_video(frm);
2298 mux_lock->lock("FFMPEG::run");
2302 for( int i=0; i<ffaudio.size(); ++i )
2303 ffaudio[i]->flush();
2304 for( int i=0; i<ffvideo.size(); ++i )
2305 ffvideo[i]->flush();
2309 int FFMPEG::ff_total_audio_channels()
2311 return astrm_index.size();
2314 int FFMPEG::ff_total_astreams()
2316 return ffaudio.size();
2319 int FFMPEG::ff_audio_channels(int stream)
2321 return ffaudio[stream]->channels;
2324 int FFMPEG::ff_sample_rate(int stream)
2326 return ffaudio[stream]->sample_rate;
2329 const char* FFMPEG::ff_audio_format(int stream)
2331 AVStream *st = ffaudio[stream]->st;
2332 AVCodecID id = st->codecpar->codec_id;
2333 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2334 return desc ? desc->name : _("Unknown");
2337 int FFMPEG::ff_audio_pid(int stream)
2339 return ffaudio[stream]->st->id;
2342 int64_t FFMPEG::ff_audio_samples(int stream)
2344 return ffaudio[stream]->length;
2347 // find audio astream/channels with this program,
2348 // or all program audio channels (astream=-1)
2349 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
2353 int vidx = ffvideo[vstream]->fidx;
2354 // find first program with this video stream
2355 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
2356 AVProgram *pgrm = fmt_ctx->programs[i];
2357 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
2358 int st_idx = pgrm->stream_index[j];
2359 AVStream *st = fmt_ctx->streams[st_idx];
2360 if( st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
2361 if( st_idx == vidx ) pidx = i;
2364 if( pidx < 0 ) return -1;
2366 int64_t channels = 0;
2367 AVProgram *pgrm = fmt_ctx->programs[pidx];
2368 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2369 int aidx = pgrm->stream_index[j];
2370 AVStream *st = fmt_ctx->streams[aidx];
2371 if( st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
2372 if( astream > 0 ) { --astream; continue; }
2374 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
2375 if( ffaudio[i]->fidx == aidx ) astrm = i;
2377 if( ret < 0 ) ret = astrm;
2378 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
2379 channels |= mask << ffaudio[astrm]->channel0;
2381 if( !astream ) break;
2383 channel_mask = channels;
2388 int FFMPEG::ff_total_video_layers()
2390 return vstrm_index.size();
2393 int FFMPEG::ff_total_vstreams()
2395 return ffvideo.size();
2398 int FFMPEG::ff_video_width(int stream)
2400 return ffvideo[stream]->width;
2403 int FFMPEG::ff_video_height(int stream)
2405 return ffvideo[stream]->height;
2408 int FFMPEG::ff_set_video_width(int stream, int width)
2410 int w = ffvideo[stream]->width;
2411 ffvideo[stream]->width = width;
2415 int FFMPEG::ff_set_video_height(int stream, int height)
2417 int h = ffvideo[stream]->height;
2418 ffvideo[stream]->height = height;
2422 int FFMPEG::ff_coded_width(int stream)
2424 return ffvideo[stream]->avctx->coded_width;
2427 int FFMPEG::ff_coded_height(int stream)
2429 return ffvideo[stream]->avctx->coded_height;
2432 float FFMPEG::ff_aspect_ratio(int stream)
2434 return ffvideo[stream]->aspect_ratio;
2437 const char* FFMPEG::ff_video_format(int stream)
2439 AVStream *st = ffvideo[stream]->st;
2440 AVCodecID id = st->codecpar->codec_id;
2441 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2442 return desc ? desc->name : _("Unknown");
2445 double FFMPEG::ff_frame_rate(int stream)
2447 return ffvideo[stream]->frame_rate;
2450 int64_t FFMPEG::ff_video_frames(int stream)
2452 return ffvideo[stream]->length;
2455 int FFMPEG::ff_video_pid(int stream)
2457 return ffvideo[stream]->st->id;
2461 int FFMPEG::ff_cpus()
2463 return file_base->file->cpus;
2466 int FFVideoStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
2468 avfilter_register_all();
2469 const char *sp = filter_spec;
2470 char filter_name[BCSTRLEN], *np = filter_name;
2471 int i = sizeof(filter_name);
2472 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
2474 AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
2475 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_VIDEO ) {
2476 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
2479 filter_graph = avfilter_graph_alloc();
2480 AVFilter *buffersrc = avfilter_get_by_name("buffer");
2481 AVFilter *buffersink = avfilter_get_by_name("buffersink");
2483 int ret = 0; char args[BCTEXTLEN];
2484 AVPixelFormat pix_fmt = (AVPixelFormat)avpar->format;
2485 snprintf(args, sizeof(args),
2486 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
2487 avpar->width, avpar->height, (int)pix_fmt,
2488 st->time_base.num, st->time_base.den,
2489 avpar->sample_aspect_ratio.num, avpar->sample_aspect_ratio.den);
2491 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2492 args, NULL, filter_graph);
2494 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2495 NULL, NULL, filter_graph);
2497 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
2498 (uint8_t*)&pix_fmt, sizeof(pix_fmt),
2499 AV_OPT_SEARCH_CHILDREN);
2501 ff_err(ret, "FFVideoStream::create_filter");
2503 ret = FFStream::create_filter(filter_spec);
2504 return ret >= 0 ? 0 : -1;
2507 int FFAudioStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
2509 avfilter_register_all();
2510 const char *sp = filter_spec;
2511 char filter_name[BCSTRLEN], *np = filter_name;
2512 int i = sizeof(filter_name);
2513 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
2515 AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
2516 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_AUDIO ) {
2517 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
2520 filter_graph = avfilter_graph_alloc();
2521 AVFilter *buffersrc = avfilter_get_by_name("abuffer");
2522 AVFilter *buffersink = avfilter_get_by_name("abuffersink");
2523 int ret = 0; char args[BCTEXTLEN];
2524 AVSampleFormat sample_fmt = (AVSampleFormat)avpar->format;
2525 snprintf(args, sizeof(args),
2526 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
2527 st->time_base.num, st->time_base.den, avpar->sample_rate,
2528 av_get_sample_fmt_name(sample_fmt), avpar->channel_layout);
2530 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2531 args, NULL, filter_graph);
2533 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2534 NULL, NULL, filter_graph);
2536 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
2537 (uint8_t*)&sample_fmt, sizeof(sample_fmt),
2538 AV_OPT_SEARCH_CHILDREN);
2540 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
2541 (uint8_t*)&avpar->channel_layout,
2542 sizeof(avpar->channel_layout), AV_OPT_SEARCH_CHILDREN);
2544 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
2545 (uint8_t*)&sample_rate, sizeof(sample_rate),
2546 AV_OPT_SEARCH_CHILDREN);
2548 ff_err(ret, "FFAudioStream::create_filter");
2550 ret = FFStream::create_filter(filter_spec);
2551 return ret >= 0 ? 0 : -1;
2554 int FFStream::create_filter(const char *filter_spec)
2556 /* Endpoints for the filter graph. */
2557 AVFilterInOut *outputs = avfilter_inout_alloc();
2558 outputs->name = av_strdup("in");
2559 outputs->filter_ctx = buffersrc_ctx;
2560 outputs->pad_idx = 0;
2563 AVFilterInOut *inputs = avfilter_inout_alloc();
2564 inputs->name = av_strdup("out");
2565 inputs->filter_ctx = buffersink_ctx;
2566 inputs->pad_idx = 0;
2569 int ret = !outputs->name || !inputs->name ? -1 : 0;
2571 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
2572 &inputs, &outputs, NULL);
2574 ret = avfilter_graph_config(filter_graph, NULL);
2577 ff_err(ret, "FFStream::create_filter");
2578 avfilter_graph_free(&filter_graph);
2581 avfilter_inout_free(&inputs);
2582 avfilter_inout_free(&outputs);
2586 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
2589 av_init_packet(&pkt);
2590 AVFrame *frame = av_frame_alloc();
2592 fprintf(stderr,"FFMPEG::scan: ");
2593 fprintf(stderr,_("av_frame_alloc failed\n"));
2597 index_state->add_video_markers(ffvideo.size());
2598 index_state->add_audio_markers(ffaudio.size());
2600 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2602 AVDictionary *copts = 0;
2603 av_dict_copy(&copts, opts, 0);
2604 AVStream *st = fmt_ctx->streams[i];
2605 AVCodecID codec_id = st->codecpar->codec_id;
2606 AVCodec *decoder = avcodec_find_decoder(codec_id);
2607 AVCodecContext *avctx = avcodec_alloc_context3(decoder);
2609 eprintf(_("cant allocate codec context\n"));
2610 ret = AVERROR(ENOMEM);
2613 avcodec_parameters_to_context(avctx, st->codecpar);
2614 ret = avcodec_open2(avctx, decoder, &copts);
2616 av_dict_free(&copts);
2618 fprintf(stderr,"FFMPEG::scan: ");
2619 fprintf(stderr,_("codec open failed\n"));
2622 AVCodecParameters *avpar = st->codecpar;
2623 switch( avpar->codec_type ) {
2624 case AVMEDIA_TYPE_VIDEO: {
2625 int vidx = ffvideo.size();
2626 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
2627 if( vidx < 0 ) break;
2628 ffvideo[vidx]->avctx = avctx;
2630 case AVMEDIA_TYPE_AUDIO: {
2631 int aidx = ffaudio.size();
2632 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
2633 if( aidx < 0 ) continue;
2634 ffaudio[aidx]->avctx = avctx;
2641 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2642 AVStream *st = fmt_ctx->streams[i];
2643 AVCodecParameters *avpar = st->codecpar;
2644 if( avpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
2645 int64_t tstmp = st->start_time;
2646 if( tstmp == AV_NOPTS_VALUE ) continue;
2647 int aidx = ffaudio.size();
2648 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
2649 if( aidx < 0 ) continue;
2650 FFAudioStream *aud = ffaudio[aidx];
2651 tstmp -= aud->nudge;
2652 double secs = to_secs(tstmp, st->time_base);
2653 aud->curr_pos = secs * aud->sample_rate + 0.5;
2657 for( int64_t count=0; !*canceled; ++count ) {
2658 av_packet_unref(&pkt);
2659 pkt.data = 0; pkt.size = 0;
2661 int ret = av_read_frame(fmt_ctx, &pkt);
2663 if( ret == AVERROR_EOF ) break;
2664 if( ++errs > 100 ) {
2665 ff_err(ret,_("over 100 read_frame errs\n"));
2670 if( !pkt.data ) continue;
2671 int i = pkt.stream_index;
2672 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
2673 AVStream *st = fmt_ctx->streams[i];
2674 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
2676 AVCodecParameters *avpar = st->codecpar;
2677 switch( avpar->codec_type ) {
2678 case AVMEDIA_TYPE_VIDEO: {
2679 int vidx = ffvideo.size();
2680 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
2681 if( vidx < 0 ) break;
2682 FFVideoStream *vid = ffvideo[vidx];
2683 int64_t tstmp = pkt.dts;
2684 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.pts;
2685 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
2686 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
2687 double secs = to_secs(tstmp, st->time_base);
2688 int64_t frm = secs * vid->frame_rate + 0.5;
2689 if( frm < 0 ) frm = 0;
2690 index_state->put_video_mark(vidx, frm, pkt.pos);
2693 ret = avcodec_send_packet(vid->avctx, pkt);
2694 if( ret < 0 ) break;
2695 while( (ret=vid->decode_frame(frame)) > 0 ) {}
2698 case AVMEDIA_TYPE_AUDIO: {
2699 int aidx = ffaudio.size();
2700 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
2701 if( aidx < 0 ) break;
2702 FFAudioStream *aud = ffaudio[aidx];
2703 int64_t tstmp = pkt.pts;
2704 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
2705 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
2706 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
2707 double secs = to_secs(tstmp, st->time_base);
2708 int64_t sample = secs * aud->sample_rate + 0.5;
2710 index_state->put_audio_mark(aidx, sample, pkt.pos);
2712 ret = avcodec_send_packet(aud->avctx, &pkt);
2713 if( ret < 0 ) break;
2714 int ch = aud->channel0, nch = aud->channels;
2715 int64_t pos = index_state->pos(ch);
2716 if( pos != aud->curr_pos ) {
2717 if( abs(pos-aud->curr_pos) > 1 )
2718 printf("audio%d pad %jd %jd (%jd)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
2719 index_state->pad_data(ch, nch, aud->curr_pos);
2721 while( (ret=aud->decode_frame(frame)) > 0 ) {
2722 if( frame->channels != nch ) break;
2724 int len = aud->get_samples(samples,
2725 &frame->extended_data[0], frame->nb_samples);
2726 pos = aud->curr_pos;
2727 if( (aud->curr_pos += len) >= 0 ) {
2729 samples += -pos * nch;
2730 len = aud->curr_pos;
2732 for( int i=0; i<nch; ++i )
2733 index_state->put_data(ch+i,nch,samples+i,len);
2740 av_frame_free(&frame);
2744 void FFStream::load_markers(IndexMarks &marks, double rate)
2747 int64_t sz = marks.size();
2748 int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
2749 int nb_ent = st->nb_index_entries;
2750 // some formats already have an index
2752 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
2753 int64_t tstmp = ep->timestamp;
2754 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
2755 double secs = ffmpeg->to_secs(tstmp, st->time_base);
2756 int64_t no = secs * rate;
2757 while( in < sz && marks[in].no <= no ) ++in;
2759 int64_t len = sz - in;
2760 int64_t count = max_entries - nb_ent;
2761 if( count > len ) count = len;
2762 for( int i=0; i<count; ++i ) {
2763 int k = in + i * len / count;
2764 int64_t no = marks[k].no, pos = marks[k].pos;
2765 double secs = (double)no / rate;
2766 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
2767 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
2768 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);