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 = samples ? load_buffer(samples, len) : used();
725 int frame_sz1 = samples ? frame_sz-1 : 0;
728 while( ret >= 0 && count > frame_sz1 ) {
729 frm = new FFrame(this);
730 if( (ret=frm->initted()) < 0 ) break;
731 AVFrame *frame = *frm;
732 len = count >= frame_sz ? frame_sz : count;
733 float *bfrp = get_outp(len);
734 ret = swr_convert(resample_context,
735 (uint8_t **)frame->extended_data, len,
736 (const uint8_t **)&bfrp, len);
738 ff_err(ret, "FFAudioStream::encode: swr_convert failed\n");
741 frame->nb_samples = len;
742 frm->queue(curr_pos);
749 return ret >= 0 ? 0 : 1;
752 int FFAudioStream::drain()
757 int FFAudioStream::encode_frame(AVFrame *frame)
759 return FFStream::encode_frame(frame);
762 void FFAudioStream::load_markers()
764 IndexState *index_state = ffmpeg->file_base->asset->index_state;
765 if( !index_state || idx >= index_state->audio_markers.size() ) return;
766 if( index_state->marker_status == MARKERS_NOTTESTED ) return;
767 FFStream::load_markers(*index_state->audio_markers[idx], sample_rate);
770 IndexMarks *FFAudioStream::get_markers()
772 IndexState *index_state = ffmpeg->file_base->asset->index_state;
773 if( !index_state || idx >= index_state->audio_markers.size() ) return 0;
774 return index_state->audio_markers[idx];
777 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
778 : FFStream(ffmpeg, strm, fidx)
789 FFVideoStream::~FFVideoStream()
793 int FFVideoStream::decode_frame(AVFrame *frame)
795 int first_frame = seeked; seeked = 0;
796 int ret = avcodec_receive_frame(avctx, frame);
798 if( first_frame || ret == AVERROR(EAGAIN) ) return 0;
799 if( ret == AVERROR(EAGAIN) ) return 0;
800 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
801 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame\n");
804 int64_t pkt_ts = av_frame_get_best_effort_timestamp(frame);
805 if( pkt_ts != AV_NOPTS_VALUE )
806 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * frame_rate + 0.5;
810 int FFVideoStream::load(VFrame *vframe, int64_t pos)
812 int ret = video_seek(pos);
813 if( ret < 0 ) return -1;
814 if( !frame && !(frame=av_frame_alloc()) ) {
815 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
818 for( int i=0; ret>=0 && !flushed && curr_pos<=pos && i<MAX_RETRY; ++i ) {
819 ret = read_frame(frame);
820 if( ret > 0 ) ++curr_pos;
822 if( frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0 )
825 ret = convert_cmodel(vframe, frame);
827 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
831 int FFVideoStream::video_seek(int64_t pos)
833 if( decode_activate() < 0 ) return -1;
834 if( !st->codecpar ) return -1;
835 if( pos == curr_pos-1 && !seeked ) return 0;
836 // if close enough, just read up to current
837 int gop = avctx->gop_size;
838 if( gop < 4 ) gop = 4;
839 if( gop > 64 ) gop = 64;
840 int read_limit = curr_pos + 3*gop;
841 if( pos >= curr_pos && pos <= read_limit ) return 0;
842 // guarentee preload more than 2*gop frames
843 if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
847 int FFVideoStream::init_frame(AVFrame *picture)
849 picture->format = avctx->pix_fmt;
850 picture->width = avctx->width;
851 picture->height = avctx->height;
852 int ret = av_frame_get_buffer(picture, 32);
856 int FFVideoStream::encode(VFrame *vframe)
858 if( encode_activate() <= 0 ) return -1;
860 FFrame *picture = new FFrame(this);
861 int ret = picture->initted();
863 AVFrame *frame = *picture;
864 frame->pts = curr_pos;
865 ret = convert_pixfmt(vframe, frame);
868 picture->queue(curr_pos);
872 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
875 return ret >= 0 ? 0 : 1;
878 int FFVideoStream::drain()
883 int FFVideoStream::encode_frame(AVFrame *frame)
886 frame->interlaced_frame = interlaced;
887 frame->top_field_first = top_field_first;
889 return FFStream::encode_frame(frame);
892 AVPixelFormat FFVideoConvert::color_model_to_pix_fmt(int color_model)
894 switch( color_model ) {
895 case BC_YUV422: return AV_PIX_FMT_YUYV422;
896 case BC_RGB888: return AV_PIX_FMT_RGB24;
897 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
898 case BC_BGR8888: return AV_PIX_FMT_BGR0;
899 case BC_BGR888: return AV_PIX_FMT_BGR24;
900 case BC_ARGB8888: return AV_PIX_FMT_ARGB;
901 case BC_ABGR8888: return AV_PIX_FMT_ABGR;
902 case BC_RGB8: return AV_PIX_FMT_RGB8;
903 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
904 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
905 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
906 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
907 case BC_RGB565: return AV_PIX_FMT_RGB565;
908 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
909 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
910 case BC_AYUV16161616: return AV_PIX_FMT_AYUV64LE;
914 return AV_PIX_FMT_NB;
917 int FFVideoConvert::pix_fmt_to_color_model(AVPixelFormat pix_fmt)
920 case AV_PIX_FMT_YUYV422: return BC_YUV422;
921 case AV_PIX_FMT_RGB24: return BC_RGB888;
922 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
923 case AV_PIX_FMT_BGR0: return BC_BGR8888;
924 case AV_PIX_FMT_BGR24: return BC_BGR888;
925 case AV_PIX_FMT_ARGB: return BC_ARGB8888;
926 case AV_PIX_FMT_ABGR: return BC_ABGR8888;
927 case AV_PIX_FMT_RGB8: return BC_RGB8;
928 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
929 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
930 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
931 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
932 case AV_PIX_FMT_RGB565: return BC_RGB565;
933 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
934 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
935 case AV_PIX_FMT_AYUV64LE: return BC_AYUV16161616;
942 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip)
944 AVFrame *ipic = av_frame_alloc();
945 int ret = convert_picture_vframe(frame, ip, ipic);
946 av_frame_free(&ipic);
950 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip, AVFrame *ipic)
952 int cmodel = frame->get_color_model();
953 AVPixelFormat ofmt = color_model_to_pix_fmt(cmodel);
954 if( ofmt == AV_PIX_FMT_NB ) return -1;
955 int size = av_image_fill_arrays(ipic->data, ipic->linesize,
956 frame->get_data(), ofmt, frame->get_w(), frame->get_h(), 1);
957 if( size < 0 ) return -1;
959 int bpp = BC_CModels::calculate_pixelsize(cmodel);
960 int ysz = bpp * frame->get_w(), usz = ysz;
969 // override av_image_fill_arrays() for planar types
970 ipic->data[0] = frame->get_y(); ipic->linesize[0] = ysz;
971 ipic->data[1] = frame->get_u(); ipic->linesize[1] = usz;
972 ipic->data[2] = frame->get_v(); ipic->linesize[2] = usz;
975 ipic->data[0] = frame->get_data();
976 ipic->linesize[0] = frame->get_bytes_per_line();
980 AVPixelFormat pix_fmt = (AVPixelFormat)ip->format;
981 convert_ctx = sws_getCachedContext(convert_ctx, ip->width, ip->height, pix_fmt,
982 frame->get_w(), frame->get_h(), ofmt, SWS_POINT, NULL, NULL, NULL);
984 fprintf(stderr, "FFVideoConvert::convert_picture_frame:"
985 " sws_getCachedContext() failed\n");
988 int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ip->height,
989 ipic->data, ipic->linesize);
991 ff_err(ret, "FFVideoConvert::convert_picture_frame: sws_scale() failed\n");
997 int FFVideoConvert::convert_cmodel(VFrame *frame, AVFrame *ip)
999 // try direct transfer
1000 if( !convert_picture_vframe(frame, ip) ) return 1;
1001 // use indirect transfer
1002 AVPixelFormat ifmt = (AVPixelFormat)ip->format;
1003 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
1005 for( int i = 0; i <desc->nb_components; ++i ) {
1006 int bits = desc->comp[i].depth;
1007 if( bits > max_bits ) max_bits = bits;
1009 int imodel = pix_fmt_to_color_model(ifmt);
1010 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1011 int cmodel = frame->get_color_model();
1012 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1013 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1014 imodel = cmodel_is_yuv ?
1015 (BC_CModels::has_alpha(cmodel) ?
1017 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1018 (BC_CModels::has_alpha(cmodel) ?
1019 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1020 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1022 VFrame vframe(ip->width, ip->height, imodel);
1023 if( convert_picture_vframe(&vframe, ip) ) return -1;
1024 frame->transfer_from(&vframe);
1028 int FFVideoConvert::transfer_cmodel(VFrame *frame, AVFrame *ifp)
1030 int ret = convert_cmodel(frame, ifp);
1032 const AVDictionary *src = av_frame_get_metadata(ifp);
1033 AVDictionaryEntry *t = NULL;
1034 BC_Hash *hp = frame->get_params();
1036 while( (t=av_dict_get(src, "", t, AV_DICT_IGNORE_SUFFIX)) )
1037 hp->update(t->key, t->value);
1042 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op)
1044 AVFrame *opic = av_frame_alloc();
1045 int ret = convert_vframe_picture(frame, op, opic);
1046 av_frame_free(&opic);
1050 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op, AVFrame *opic)
1052 int cmodel = frame->get_color_model();
1053 AVPixelFormat ifmt = color_model_to_pix_fmt(cmodel);
1054 if( ifmt == AV_PIX_FMT_NB ) return -1;
1055 int size = av_image_fill_arrays(opic->data, opic->linesize,
1056 frame->get_data(), ifmt, frame->get_w(), frame->get_h(), 1);
1057 if( size < 0 ) return -1;
1059 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1060 int ysz = bpp * frame->get_w(), usz = ysz;
1069 // override av_image_fill_arrays() for planar types
1070 opic->data[0] = frame->get_y(); opic->linesize[0] = ysz;
1071 opic->data[1] = frame->get_u(); opic->linesize[1] = usz;
1072 opic->data[2] = frame->get_v(); opic->linesize[2] = usz;
1075 opic->data[0] = frame->get_data();
1076 opic->linesize[0] = frame->get_bytes_per_line();
1080 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1081 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(),
1082 ifmt, op->width, op->height, ofmt, SWS_POINT, NULL, NULL, NULL);
1083 if( !convert_ctx ) {
1084 fprintf(stderr, "FFVideoConvert::convert_frame_picture:"
1085 " sws_getCachedContext() failed\n");
1088 int ret = sws_scale(convert_ctx, opic->data, opic->linesize, 0, frame->get_h(),
1089 op->data, op->linesize);
1091 ff_err(ret, "FFVideoConvert::convert_frame_picture: sws_scale() failed\n");
1097 int FFVideoConvert::convert_pixfmt(VFrame *frame, AVFrame *op)
1099 // try direct transfer
1100 if( !convert_vframe_picture(frame, op) ) return 1;
1101 // use indirect transfer
1102 int cmodel = frame->get_color_model();
1103 int max_bits = BC_CModels::calculate_pixelsize(cmodel) * 8;
1104 max_bits /= BC_CModels::components(cmodel);
1105 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1106 int imodel = pix_fmt_to_color_model(ofmt);
1107 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1108 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1109 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1110 imodel = cmodel_is_yuv ?
1111 (BC_CModels::has_alpha(cmodel) ?
1113 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1114 (BC_CModels::has_alpha(cmodel) ?
1115 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1116 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1118 VFrame vframe(frame->get_w(), frame->get_h(), imodel);
1119 vframe.transfer_from(frame);
1120 if( !convert_vframe_picture(&vframe, op) ) return 1;
1124 int FFVideoConvert::transfer_pixfmt(VFrame *frame, AVFrame *ofp)
1126 int ret = convert_pixfmt(frame, ofp);
1128 BC_Hash *hp = frame->get_params();
1129 AVDictionary **dict = avpriv_frame_get_metadatap(ofp);
1130 //av_dict_free(dict);
1131 for( int i=0; i<hp->size(); ++i ) {
1132 char *key = hp->get_key(i), *val = hp->get_value(i);
1133 av_dict_set(dict, key, val, 0);
1139 void FFVideoStream::load_markers()
1141 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1142 if( !index_state || idx >= index_state->video_markers.size() ) return;
1143 FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
1146 IndexMarks *FFVideoStream::get_markers()
1148 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1149 if( !index_state || idx >= index_state->video_markers.size() ) return 0;
1150 return !index_state ? 0 : index_state->video_markers[idx];
1154 FFMPEG::FFMPEG(FileBase *file_base)
1157 this->file_base = file_base;
1158 memset(file_format,0,sizeof(file_format));
1159 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
1160 flow_lock = new Condition(1,"FFStream::flow_lock",0);
1163 decoding = encoding = 0;
1164 has_audio = has_video = 0;
1167 opt_video_filter = 0;
1168 opt_audio_filter = 0;
1169 char option_path[BCTEXTLEN];
1170 set_option_path(option_path, "%s", "ffmpeg.opts");
1171 read_options(option_path, opts);
1176 ff_lock("FFMPEG::~FFMPEG()");
1178 ffaudio.remove_all_objects();
1179 ffvideo.remove_all_objects();
1180 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1184 av_dict_free(&opts);
1185 delete [] opt_video_filter;
1186 delete [] opt_audio_filter;
1189 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1191 const int *p = codec->supported_samplerates;
1192 if( !p ) return sample_rate;
1194 if( *p == sample_rate ) return *p;
1200 static inline AVRational std_frame_rate(int i)
1202 static const int m1 = 1001*12, m2 = 1000*12;
1203 static const int freqs[] = {
1204 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1205 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
1207 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1208 return (AVRational) { freq, 1001*12 };
1211 AVRational FFMPEG::check_frame_rate(AVCodec *codec, double frame_rate)
1213 const AVRational *p = codec->supported_framerates;
1214 AVRational rate, best_rate = (AVRational) { 0, 0 };
1215 double max_err = 1.; int i = 0;
1216 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1217 double framerate = (double) rate.num / rate.den;
1218 double err = fabs(frame_rate/framerate - 1.);
1219 if( err >= max_err ) continue;
1223 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1226 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1229 double display_aspect = asset->width / (double)asset->height;
1230 double sample_aspect = display_aspect / asset->aspect_ratio;
1231 int width = 1000000, height = width * sample_aspect + 0.5;
1233 MWindow::create_aspect_ratio(w, h, width, height);
1234 return (AVRational){(int)w, (int)h};
1237 return (AVRational){1, 1};
1241 AVRational FFMPEG::to_time_base(int sample_rate)
1243 return (AVRational){1, sample_rate};
1246 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
1248 char *ep = path + BCTEXTLEN-1;
1249 strncpy(path, File::get_cindat_path(), ep-path);
1250 strncat(path, "/ffmpeg/", ep-path);
1251 path += strlen(path);
1254 path += vsnprintf(path, ep-path, fmt, ap);
1259 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
1264 set_option_path(path, "%s/%s", type, spec);
1267 int FFMPEG::get_format(char *format, const char *path, const char *spec)
1269 char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
1270 get_option_path(option_path, path, spec);
1271 FILE *fp = fopen(option_path,"r");
1274 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1276 line[sizeof(line)-1] = 0;
1277 ret = scan_option_line(line, format, codec);
1283 int FFMPEG::get_codec(char *codec, const char *path, const char *spec)
1285 char option_path[BCTEXTLEN], line[BCTEXTLEN], format[BCTEXTLEN];
1286 get_option_path(option_path, path, spec);
1287 FILE *fp = fopen(option_path,"r");
1290 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1293 line[sizeof(line)-1] = 0;
1294 ret = scan_option_line(line, format, codec);
1297 char *vp = codec, *ep = vp+BCTEXTLEN-1;
1298 while( vp < ep && *vp && *vp != '|' ) ++vp;
1299 if( *vp == '|' ) --vp;
1300 while( vp > codec && (*vp==' ' || *vp=='\t') ) *vp-- = 0;
1305 int FFMPEG::get_file_format()
1307 char audio_muxer[BCSTRLEN], video_muxer[BCSTRLEN];
1308 char audio_format[BCSTRLEN], video_format[BCSTRLEN];
1309 audio_muxer[0] = audio_format[0] = 0;
1310 video_muxer[0] = video_format[0] = 0;
1311 Asset *asset = file_base->asset;
1312 int ret = asset ? 0 : 1;
1313 if( !ret && asset->audio_data ) {
1314 if( !(ret=get_format(audio_format, "audio", asset->acodec)) ) {
1315 if( get_format(audio_muxer, "format", audio_format) ) {
1316 strcpy(audio_muxer, audio_format);
1317 audio_format[0] = 0;
1321 if( !ret && asset->video_data ) {
1322 if( !(ret=get_format(video_format, "video", asset->vcodec)) ) {
1323 if( get_format(video_muxer, "format", video_format) ) {
1324 strcpy(video_muxer, video_format);
1325 video_format[0] = 0;
1329 if( !ret && !audio_muxer[0] && !video_muxer[0] )
1331 if( !ret && audio_muxer[0] && video_muxer[0] &&
1332 strcmp(audio_muxer, video_muxer) ) ret = -1;
1333 if( !ret && audio_format[0] && video_format[0] &&
1334 strcmp(audio_format, video_format) ) ret = -1;
1336 strcpy(file_format, !audio_format[0] && !video_format[0] ?
1337 (audio_muxer[0] ? audio_muxer : video_muxer) :
1338 (audio_format[0] ? audio_format : video_format));
1342 int FFMPEG::scan_option_line(char *cp, char *tag, char *val)
1344 while( *cp == ' ' || *cp == '\t' ) ++cp;
1346 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' && *cp != '\n' ) ++cp;
1348 if( !len || len > BCSTRLEN-1 ) return 1;
1349 while( bp < cp ) *tag++ = *bp++;
1351 while( *cp == ' ' || *cp == '\t' ) ++cp;
1352 if( *cp == '=' ) ++cp;
1353 while( *cp == ' ' || *cp == '\t' ) ++cp;
1355 while( *cp && *cp != '\n' ) ++cp;
1357 if( len > BCTEXTLEN-1 ) return 1;
1358 while( bp < cp ) *val++ = *bp++;
1363 int FFMPEG::load_defaults(const char *path, const char *type,
1364 char *codec, char *codec_options, int len)
1366 char default_file[BCTEXTLEN];
1367 set_option_path(default_file, "%s/%s.dfl", path, type);
1368 FILE *fp = fopen(default_file,"r");
1370 fgets(codec, BCSTRLEN, fp);
1372 while( *cp && *cp!='\n' ) ++cp;
1374 while( len > 0 && fgets(codec_options, len, fp) ) {
1375 int n = strlen(codec_options);
1376 codec_options += n; len -= n;
1379 set_option_path(default_file, "%s/%s", path, codec);
1380 return load_options(default_file, codec_options, len);
1383 void FFMPEG::set_asset_format(Asset *asset, const char *text)
1385 if( asset->format != FILE_FFMPEG ) return;
1386 if( text != asset->fformat )
1387 strcpy(asset->fformat, text);
1388 if( !asset->ff_audio_options[0] ) {
1389 asset->audio_data = !load_defaults("audio", text, asset->acodec,
1390 asset->ff_audio_options, sizeof(asset->ff_audio_options));
1392 if( !asset->ff_video_options[0] ) {
1393 asset->video_data = !load_defaults("video", text, asset->vcodec,
1394 asset->ff_video_options, sizeof(asset->ff_video_options));
1398 int FFMPEG::get_encoder(const char *options,
1399 char *format, char *codec, char *bsfilter)
1401 FILE *fp = fopen(options,"r");
1403 eprintf(_("options open failed %s\n"),options);
1406 if( get_encoder(fp, format, codec, bsfilter) )
1407 eprintf(_("format/codec not found %s\n"), options);
1412 int FFMPEG::get_encoder(FILE *fp,
1413 char *format, char *codec, char *bsfilter)
1415 format[0] = codec[0] = bsfilter[0] = 0;
1416 char line[BCTEXTLEN];
1417 if( !fgets(line, sizeof(line), fp) ) return 1;
1418 line[sizeof(line)-1] = 0;
1419 if( scan_option_line(line, format, codec) ) return 1;
1421 while( *cp && *cp != '|' ) ++cp;
1422 if( !*cp ) return 0;
1424 do { *bp-- = 0; } while( bp>=codec && (*bp==' ' || *bp == '\t' ) );
1425 while( *++cp && (*cp==' ' || *cp == '\t') );
1427 for( int i=BCTEXTLEN; --i>0 && *cp; ) *bp++ = *cp++;
1432 int FFMPEG::read_options(const char *options, AVDictionary *&opts, int skip)
1434 FILE *fp = fopen(options,"r");
1437 while( !ret && --skip >= 0 ) {
1439 while( ch >= 0 && ch != '\n' ) ch = getc(fp);
1440 if( ch < 0 ) ret = 1;
1443 ret = read_options(fp, options, opts);
1448 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
1450 FILE *fp = fmemopen((void *)options,strlen(options),"r");
1452 int ret = read_options(fp, options, opts);
1454 AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
1455 if( tag ) st->id = strtol(tag->value,0,0);
1459 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
1461 int ret = 0, no = 0;
1462 char line[BCTEXTLEN];
1463 while( !ret && fgets(line, sizeof(line), fp) ) {
1464 line[sizeof(line)-1] = 0;
1465 if( line[0] == '#' ) continue;
1466 if( line[0] == '\n' ) continue;
1467 char key[BCSTRLEN], val[BCTEXTLEN];
1468 if( scan_option_line(line, key, val) ) {
1469 eprintf(_("err reading %s: line %d\n"), options, no);
1473 if( !strcmp(key, "duration") )
1474 opt_duration = strtod(val, 0);
1475 else if( !strcmp(key, "video_filter") )
1476 opt_video_filter = cstrdup(val);
1477 else if( !strcmp(key, "audio_filter") )
1478 opt_audio_filter = cstrdup(val);
1479 else if( !strcmp(key, "loglevel") )
1482 av_dict_set(&opts, key, val, 0);
1488 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
1490 char option_path[BCTEXTLEN];
1491 set_option_path(option_path, "%s", options);
1492 return read_options(option_path, opts);
1495 int FFMPEG::load_options(const char *path, char *bfr, int len)
1498 FILE *fp = fopen(path, "r");
1500 fgets(bfr, len, fp); // skip hdr
1501 len = fread(bfr, 1, len-1, fp);
1502 if( len < 0 ) len = 0;
1508 void FFMPEG::set_loglevel(const char *ap)
1510 if( !ap || !*ap ) return;
1515 { "quiet" , AV_LOG_QUIET },
1516 { "panic" , AV_LOG_PANIC },
1517 { "fatal" , AV_LOG_FATAL },
1518 { "error" , AV_LOG_ERROR },
1519 { "warning", AV_LOG_WARNING },
1520 { "info" , AV_LOG_INFO },
1521 { "verbose", AV_LOG_VERBOSE },
1522 { "debug" , AV_LOG_DEBUG },
1524 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
1525 if( !strcmp(log_levels[i].name, ap) ) {
1526 av_log_set_level(log_levels[i].level);
1530 av_log_set_level(atoi(ap));
1533 double FFMPEG::to_secs(int64_t time, AVRational time_base)
1535 double base_time = time == AV_NOPTS_VALUE ? 0 :
1536 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
1537 return base_time / AV_TIME_BASE;
1540 int FFMPEG::info(char *text, int len)
1542 if( len <= 0 ) return 0;
1544 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
1546 report("format: %s\n",fmt_ctx->iformat->name);
1547 if( ffvideo.size() > 0 )
1548 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
1549 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
1550 FFVideoStream *vid = ffvideo[vidx];
1551 AVStream *st = vid->st;
1552 AVCodecID codec_id = st->codecpar->codec_id;
1553 report(_("vid%d (%d), id 0x%06x:\n"), vid->idx, vid->fidx, codec_id);
1554 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
1555 report(" video%d %s", vidx+1, desc ? desc->name : " (unkn)");
1556 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
1557 AVPixelFormat pix_fmt = (AVPixelFormat)st->codecpar->format;
1558 const char *pfn = av_get_pix_fmt_name(pix_fmt);
1559 report(" pix %s\n", pfn ? pfn : "(unkn)");
1560 double secs = to_secs(st->duration, st->time_base);
1561 int64_t length = secs * vid->frame_rate + 0.5;
1562 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
1563 int64_t nudge = ofs * vid->frame_rate;
1564 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1565 report(" %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
1566 int hrs = secs/3600; secs -= hrs*3600;
1567 int mins = secs/60; secs -= mins*60;
1568 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1570 if( ffaudio.size() > 0 )
1571 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
1572 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
1573 FFAudioStream *aud = ffaudio[aidx];
1574 AVStream *st = aud->st;
1575 AVCodecID codec_id = st->codecpar->codec_id;
1576 report(_("aud%d (%d), id 0x%06x:\n"), aud->idx, aud->fidx, codec_id);
1577 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
1578 int nch = aud->channels, ch0 = aud->channel0+1;
1579 report(" audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
1580 AVSampleFormat sample_fmt = (AVSampleFormat)st->codecpar->format;
1581 const char *fmt = av_get_sample_fmt_name(sample_fmt);
1582 report(" %s %d", fmt, aud->sample_rate);
1583 int sample_bits = av_get_bits_per_sample(codec_id);
1584 report(" %dbits\n", sample_bits);
1585 double secs = to_secs(st->duration, st->time_base);
1586 int64_t length = secs * aud->sample_rate + 0.5;
1587 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
1588 int64_t nudge = ofs * aud->sample_rate;
1589 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1590 report(" %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
1591 int hrs = secs/3600; secs -= hrs*3600;
1592 int mins = secs/60; secs -= mins*60;
1593 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1595 if( fmt_ctx->nb_programs > 0 )
1596 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
1597 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
1598 report("program %d", i+1);
1599 AVProgram *pgrm = fmt_ctx->programs[i];
1600 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1601 int idx = pgrm->stream_index[j];
1602 int vidx = ffvideo.size();
1603 while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
1605 report(", vid%d", vidx);
1608 int aidx = ffaudio.size();
1609 while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
1611 report(", aud%d", aidx);
1614 report(", (%d)", pgrm->stream_index[j]);
1619 AVDictionaryEntry *tag = 0;
1620 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
1621 report("%s=%s\n", tag->key, tag->value);
1630 int FFMPEG::init_decoder(const char *filename)
1632 ff_lock("FFMPEG::init_decoder");
1634 char file_opts[BCTEXTLEN];
1635 char *bp = strrchr(strcpy(file_opts, filename), '/');
1636 char *sp = strrchr(!bp ? file_opts : bp, '.');
1639 strcpy(sp, ".opts");
1640 fp = fopen(file_opts, "r");
1643 read_options(fp, file_opts, opts);
1647 load_options("decode.opts", opts);
1648 AVDictionary *fopts = 0;
1649 av_dict_copy(&fopts, opts, 0);
1650 int ret = avformat_open_input(&fmt_ctx, filename, NULL, &fopts);
1651 av_dict_free(&fopts);
1653 ret = avformat_find_stream_info(fmt_ctx, NULL);
1658 return !ret ? 0 : 1;
1661 int FFMPEG::open_decoder()
1664 if( stat(fmt_ctx->filename, &st) < 0 ) {
1665 eprintf(_("can't stat file: %s\n"), fmt_ctx->filename);
1669 int64_t file_bits = 8 * st.st_size;
1670 if( !fmt_ctx->bit_rate && opt_duration > 0 )
1671 fmt_ctx->bit_rate = file_bits / opt_duration;
1674 if( fmt_ctx->bit_rate > 0 ) {
1675 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1676 AVStream *st = fmt_ctx->streams[i];
1677 if( st->duration != AV_NOPTS_VALUE ) continue;
1678 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
1679 st->duration = av_rescale(file_bits, st->time_base.den,
1680 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
1685 printf("FFMPEG::open_decoder: some stream times estimated\n");
1687 ff_lock("FFMPEG::open_decoder");
1688 int ret = 0, bad_time = 0;
1689 for( int i=0; !ret && i<(int)fmt_ctx->nb_streams; ++i ) {
1690 AVStream *st = fmt_ctx->streams[i];
1691 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
1692 AVCodecParameters *avpar = st->codecpar;
1693 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avpar->codec_id);
1694 if( !codec_desc ) continue;
1695 switch( avpar->codec_type ) {
1696 case AVMEDIA_TYPE_VIDEO: {
1697 if( avpar->width < 1 ) continue;
1698 if( avpar->height < 1 ) continue;
1699 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
1700 if( framerate.num < 1 ) continue;
1702 int vidx = ffvideo.size();
1703 FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
1704 vstrm_index.append(ffidx(vidx, 0));
1705 ffvideo.append(vid);
1706 vid->width = avpar->width;
1707 vid->height = avpar->height;
1708 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
1709 double secs = to_secs(st->duration, st->time_base);
1710 vid->length = secs * vid->frame_rate;
1711 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
1712 vid->nudge = st->start_time;
1714 if( opt_video_filter )
1715 ret = vid->create_filter(opt_video_filter, avpar);
1717 case AVMEDIA_TYPE_AUDIO: {
1718 if( avpar->channels < 1 ) continue;
1719 if( avpar->sample_rate < 1 ) continue;
1721 int aidx = ffaudio.size();
1722 FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
1723 ffaudio.append(aud);
1724 aud->channel0 = astrm_index.size();
1725 aud->channels = avpar->channels;
1726 for( int ch=0; ch<aud->channels; ++ch )
1727 astrm_index.append(ffidx(aidx, ch));
1728 aud->sample_rate = avpar->sample_rate;
1729 double secs = to_secs(st->duration, st->time_base);
1730 aud->length = secs * aud->sample_rate;
1731 if( avpar->format != AV_SAMPLE_FMT_FLT ) {
1732 uint64_t layout = av_get_default_channel_layout(avpar->channels);
1733 if( !layout ) layout = ((uint64_t)1<<aud->channels) - 1;
1734 AVSampleFormat sample_format = (AVSampleFormat)avpar->format;
1735 aud->resample_context = swr_alloc_set_opts(NULL,
1736 layout, AV_SAMPLE_FMT_FLT, avpar->sample_rate,
1737 layout, sample_format, avpar->sample_rate,
1739 swr_init(aud->resample_context);
1741 aud->nudge = st->start_time;
1743 if( opt_audio_filter )
1744 ret = aud->create_filter(opt_audio_filter, avpar);
1750 printf("FFMPEG::open_decoder: some stream have bad times\n");
1752 return ret < 0 ? -1 : 0;
1756 int FFMPEG::init_encoder(const char *filename)
1758 int fd = ::open(filename,O_WRONLY);
1759 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
1761 eprintf(_("bad file path: %s\n"), filename);
1765 int ret = get_file_format();
1767 eprintf(_("bad file format: %s\n"), filename);
1771 eprintf(_("mismatch audio/video file format: %s\n"), filename);
1774 ff_lock("FFMPEG::init_encoder");
1776 char format[BCSTRLEN];
1777 if( get_format(format, "format", file_format) )
1778 strcpy(format, file_format);
1779 avformat_alloc_output_context2(&fmt_ctx, 0, format, filename);
1781 eprintf(_("failed: %s\n"), filename);
1786 load_options("encode.opts", opts);
1792 int FFMPEG::open_encoder(const char *type, const char *spec)
1795 Asset *asset = file_base->asset;
1796 char *filename = asset->path;
1797 AVDictionary *sopts = 0;
1798 av_dict_copy(&sopts, opts, 0);
1799 char option_path[BCTEXTLEN];
1800 set_option_path(option_path, "%s/%s.opts", type, type);
1801 read_options(option_path, sopts);
1802 get_option_path(option_path, type, spec);
1803 char format_name[BCSTRLEN], codec_name[BCTEXTLEN], bsfilter[BCTEXTLEN];
1804 if( get_encoder(option_path, format_name, codec_name, bsfilter) ) {
1805 eprintf(_("get_encoder failed %s:%s\n"), option_path, filename);
1809 if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
1810 else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
1811 else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
1814 ff_lock("FFMPEG::open_encoder");
1817 AVCodecContext *ctx = 0;
1819 const AVCodecDescriptor *codec_desc = 0;
1820 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
1822 eprintf(_("cant find codec %s:%s\n"), codec_name, filename);
1826 codec_desc = avcodec_descriptor_get(codec->id);
1828 eprintf(_("unknown codec %s:%s\n"), codec_name, filename);
1833 st = avformat_new_stream(fmt_ctx, 0);
1835 eprintf(_("cant create stream %s:%s\n"), codec_name, filename);
1840 switch( codec_desc->type ) {
1841 case AVMEDIA_TYPE_AUDIO: {
1843 eprintf(_("duplicate audio %s:%s\n"), codec_name, filename);
1847 if( scan_options(asset->ff_audio_options, sopts, st) ) {
1848 eprintf(_("bad audio options %s:%s\n"), codec_name, filename);
1853 ctx = avcodec_alloc_context3(codec);
1854 if( asset->ff_audio_bitrate > 0 ) {
1855 ctx->bit_rate = asset->ff_audio_bitrate;
1857 sprintf(arg, "%d", asset->ff_audio_bitrate);
1858 av_dict_set(&sopts, "b", arg, 0);
1860 int aidx = ffaudio.size();
1861 int fidx = aidx + ffvideo.size();
1862 FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
1863 aud->avctx = ctx; ffaudio.append(aud); fst = aud;
1864 aud->sample_rate = asset->sample_rate;
1865 ctx->channels = aud->channels = asset->channels;
1866 for( int ch=0; ch<aud->channels; ++ch )
1867 astrm_index.append(ffidx(aidx, ch));
1868 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
1869 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
1870 if( !ctx->sample_rate ) {
1871 eprintf(_("check_sample_rate failed %s\n"), filename);
1875 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
1876 ctx->sample_fmt = codec->sample_fmts[0];
1877 uint64_t layout = av_get_default_channel_layout(ctx->channels);
1878 aud->resample_context = swr_alloc_set_opts(NULL,
1879 layout, ctx->sample_fmt, aud->sample_rate,
1880 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
1882 swr_init(aud->resample_context);
1885 case AVMEDIA_TYPE_VIDEO: {
1887 eprintf(_("duplicate video %s:%s\n"), codec_name, filename);
1891 if( scan_options(asset->ff_video_options, sopts, st) ) {
1892 eprintf(_("bad video options %s:%s\n"), codec_name, filename);
1897 ctx = avcodec_alloc_context3(codec);
1898 if( asset->ff_video_bitrate > 0 ) {
1899 ctx->bit_rate = asset->ff_video_bitrate;
1901 sprintf(arg, "%d", asset->ff_video_bitrate);
1902 av_dict_set(&sopts, "b", arg, 0);
1904 else if( asset->ff_video_quality >= 0 ) {
1905 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
1906 ctx->qmin = ctx->qmax = asset->ff_video_quality;
1907 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
1908 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
1909 ctx->flags |= CODEC_FLAG_QSCALE;
1911 av_dict_set(&sopts, "flags", "+qscale", 0);
1912 sprintf(arg, "%d", asset->ff_video_quality);
1913 av_dict_set(&sopts, "qscale", arg, 0);
1914 sprintf(arg, "%d", ctx->global_quality);
1915 av_dict_set(&sopts, "global_quality", arg, 0);
1917 int vidx = ffvideo.size();
1918 int fidx = vidx + ffaudio.size();
1919 FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
1920 vstrm_index.append(ffidx(vidx, 0));
1921 vid->avctx = ctx; ffvideo.append(vid); fst = vid;
1922 vid->width = asset->width;
1923 ctx->width = (vid->width+3) & ~3;
1924 vid->height = asset->height;
1925 ctx->height = (vid->height+3) & ~3;
1926 vid->frame_rate = asset->frame_rate;
1927 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
1928 ctx->pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
1929 AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
1930 if( !frame_rate.num || !frame_rate.den ) {
1931 eprintf(_("check_frame_rate failed %s\n"), filename);
1935 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
1936 st->time_base = ctx->time_base;
1938 vid->interlaced = asset->interlace_mode == ILACE_MODE_TOP_FIRST ||
1939 asset->interlace_mode == ILACE_MODE_BOTTOM_FIRST ? 1 : 0;
1940 vid->top_field_first = asset->interlace_mode == ILACE_MODE_TOP_FIRST ? 1 : 0;
1943 eprintf(_("not audio/video, %s:%s\n"), codec_name, filename);
1948 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
1949 ctx->flags |= CODEC_FLAG_GLOBAL_HEADER;
1951 av_dict_set(&sopts, "cin_bitrate", 0, 0);
1952 av_dict_set(&sopts, "cin_quality", 0, 0);
1954 ret = avcodec_open2(ctx, codec, &sopts);
1956 ret = avcodec_parameters_from_context(st->codecpar, ctx);
1958 fprintf(stderr, "Could not copy the stream parameters\n");
1961 ff_err(ret,"FFMPEG::open_encoder");
1962 eprintf(_("open failed %s:%s\n"), codec_name, filename);
1968 if( !ret && fst && bsfilter[0] ) {
1969 ret = av_bsf_list_parse_str(bsfilter, &fst->bsfc);
1971 ff_err(ret,"FFMPEG::open_encoder");
1972 eprintf(_("bitstream filter failed %s:\n%s\n"), filename, bsfilter);
1983 av_dict_free(&sopts);
1987 int FFMPEG::close_encoder()
1990 if( encoding > 0 ) {
1991 av_write_trailer(fmt_ctx);
1992 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
1993 avio_closep(&fmt_ctx->pb);
1999 int FFMPEG::decode_activate()
2001 if( decoding < 0 ) {
2003 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
2004 ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
2005 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
2006 ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
2007 // set nudges for each program stream set
2008 const int64_t min_nudge = INT64_MIN+1;
2009 int npgrms = fmt_ctx->nb_programs;
2010 for( int i=0; i<npgrms; ++i ) {
2011 AVProgram *pgrm = fmt_ctx->programs[i];
2012 // first start time video stream
2013 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2014 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2015 int fidx = pgrm->stream_index[j];
2016 AVStream *st = fmt_ctx->streams[fidx];
2017 AVCodecParameters *avpar = st->codecpar;
2018 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2019 if( st->start_time == AV_NOPTS_VALUE ) continue;
2020 if( vstart_time < st->start_time )
2021 vstart_time = st->start_time;
2024 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2025 if( st->start_time == AV_NOPTS_VALUE ) continue;
2026 if( astart_time < st->start_time )
2027 astart_time = st->start_time;
2031 //since frame rate is much more grainy than sample rate, it is better to
2032 // align using video, so that total absolute error is minimized.
2033 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2034 astart_time > min_nudge ? astart_time : AV_NOPTS_VALUE;
2035 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2036 int fidx = pgrm->stream_index[j];
2037 AVStream *st = fmt_ctx->streams[fidx];
2038 AVCodecParameters *avpar = st->codecpar;
2039 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2040 for( int k=0; k<ffvideo.size(); ++k ) {
2041 if( ffvideo[k]->fidx != fidx ) continue;
2042 ffvideo[k]->nudge = nudge;
2046 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2047 for( int k=0; k<ffaudio.size(); ++k ) {
2048 if( ffaudio[k]->fidx != fidx ) continue;
2049 ffaudio[k]->nudge = nudge;
2055 // set nudges for any streams not yet set
2056 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2057 int nstreams = fmt_ctx->nb_streams;
2058 for( int i=0; i<nstreams; ++i ) {
2059 AVStream *st = fmt_ctx->streams[i];
2060 AVCodecParameters *avpar = st->codecpar;
2061 switch( avpar->codec_type ) {
2062 case AVMEDIA_TYPE_VIDEO: {
2063 if( st->start_time == AV_NOPTS_VALUE ) continue;
2064 int vidx = ffvideo.size();
2065 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
2066 if( vidx >= 0 && ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
2067 if( vstart_time < st->start_time )
2068 vstart_time = st->start_time;
2070 case AVMEDIA_TYPE_AUDIO: {
2071 if( st->start_time == AV_NOPTS_VALUE ) continue;
2072 int aidx = ffaudio.size();
2073 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
2074 if( aidx >= 0 && ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
2075 if( astart_time < st->start_time )
2076 astart_time = st->start_time;
2081 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2082 astart_time > min_nudge ? astart_time : AV_NOPTS_VALUE;
2083 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
2084 if( ffvideo[vidx]->nudge == AV_NOPTS_VALUE )
2085 ffvideo[vidx]->nudge = nudge;
2087 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2088 if( ffaudio[aidx]->nudge == AV_NOPTS_VALUE )
2089 ffaudio[aidx]->nudge = nudge;
2096 int FFMPEG::encode_activate()
2099 if( encoding < 0 ) {
2101 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
2102 (ret=avio_open(&fmt_ctx->pb, fmt_ctx->filename, AVIO_FLAG_WRITE)) < 0 ) {
2103 ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
2109 AVProgram *prog = av_new_program(fmt_ctx, prog_id);
2110 for( int i=0; i< ffvideo.size(); ++i )
2111 av_program_add_stream_index(fmt_ctx, prog_id, ffvideo[i]->fidx);
2112 for( int i=0; i< ffaudio.size(); ++i )
2113 av_program_add_stream_index(fmt_ctx, prog_id, ffaudio[i]->fidx);
2114 int pi = fmt_ctx->nb_programs;
2115 while( --pi >= 0 && fmt_ctx->programs[pi]->id != prog_id );
2116 AVDictionary **meta = &prog->metadata;
2117 av_dict_set(meta, "service_provider", "cin5", 0);
2118 const char *path = fmt_ctx->filename, *bp = strrchr(path,'/');
2119 if( bp ) path = bp + 1;
2120 av_dict_set(meta, "title", path, 0);
2122 if( ffaudio.size() ) {
2123 const char *ep = getenv("CIN_AUDIO_LANG"), *lp = 0;
2124 if( !ep && (lp=getenv("LANG")) ) { // some are guesses
2125 static struct { const char lc[3], lng[4]; } lcode[] = {
2126 { "en", "eng" }, { "de", "ger" }, { "es", "spa" },
2127 { "eu", "bas" }, { "fr", "fre" }, { "el", "gre" },
2128 { "hi", "hin" }, { "it", "ita" }, { "ja", "jap" },
2129 { "ko", "kor" }, { "du", "dut" }, { "pl", "pol" },
2130 { "pt", "por" }, { "ru", "rus" }, { "sl", "slv" },
2131 { "uk", "ukr" }, { "vi", "vie" }, { "zh", "chi" },
2133 for( int i=sizeof(lcode)/sizeof(lcode[0]); --i>=0 && !ep; )
2134 if( !strncmp(lcode[i].lc,lp,2) ) ep = lcode[i].lng;
2136 if( !ep ) ep = "und";
2138 strncpy(lang,ep,3); lang[3] = 0;
2139 AVStream *st = ffaudio[0]->st;
2140 av_dict_set(&st->metadata,"language",lang,0);
2143 AVDictionary *fopts = 0;
2144 char option_path[BCTEXTLEN];
2145 set_option_path(option_path, "format/%s", file_format);
2146 read_options(option_path, fopts, 1);
2147 ret = avformat_write_header(fmt_ctx, &fopts);
2149 ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
2153 av_dict_free(&fopts);
2160 int FFMPEG::audio_seek(int stream, int64_t pos)
2162 int aidx = astrm_index[stream].st_idx;
2163 FFAudioStream *aud = ffaudio[aidx];
2164 aud->audio_seek(pos);
2168 int FFMPEG::video_seek(int stream, int64_t pos)
2170 int vidx = vstrm_index[stream].st_idx;
2171 FFVideoStream *vid = ffvideo[vidx];
2172 vid->video_seek(pos);
2177 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
2179 if( !has_audio || chn >= astrm_index.size() ) return -1;
2180 int aidx = astrm_index[chn].st_idx;
2181 FFAudioStream *aud = ffaudio[aidx];
2182 if( aud->load(pos, len) < len ) return -1;
2183 int ch = astrm_index[chn].st_ch;
2184 int ret = aud->read(samples,len,ch);
2188 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
2190 if( !has_video || layer >= vstrm_index.size() ) return -1;
2191 int vidx = vstrm_index[layer].st_idx;
2192 FFVideoStream *vid = ffvideo[vidx];
2193 return vid->load(vframe, pos);
2197 int FFMPEG::encode(int stream, double **samples, int len)
2199 FFAudioStream *aud = ffaudio[stream];
2200 return aud->encode(samples, len);
2204 int FFMPEG::encode(int stream, VFrame *frame)
2206 FFVideoStream *vid = ffvideo[stream];
2207 return vid->encode(frame);
2210 void FFMPEG::start_muxer()
2218 void FFMPEG::stop_muxer()
2227 void FFMPEG::flow_off()
2230 flow_lock->lock("FFMPEG::flow_off");
2234 void FFMPEG::flow_on()
2238 flow_lock->unlock();
2241 void FFMPEG::flow_ctl()
2244 flow_lock->lock("FFMPEG::flow_ctl");
2245 flow_lock->unlock();
2249 int FFMPEG::mux_audio(FFrame *frm)
2251 FFStream *fst = frm->fst;
2252 AVCodecContext *ctx = fst->avctx;
2253 AVFrame *frame = *frm;
2254 AVRational tick_rate = {1, ctx->sample_rate};
2255 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
2256 int ret = fst->encode_frame(frame);
2258 ff_err(ret, "FFMPEG::mux_audio");
2259 return ret >= 0 ? 0 : 1;
2262 int FFMPEG::mux_video(FFrame *frm)
2264 FFStream *fst = frm->fst;
2265 AVFrame *frame = *frm;
2266 frame->pts = frm->position;
2267 int ret = fst->encode_frame(frame);
2269 ff_err(ret, "FFMPEG::mux_video");
2270 return ret >= 0 ? 0 : 1;
2276 double atm = -1, vtm = -1;
2277 FFrame *afrm = 0, *vfrm = 0;
2279 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
2280 FFStream *fst = ffaudio[i];
2281 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
2282 FFrame *frm = fst->frms.first;
2283 if( !frm ) { if( !done ) return; continue; }
2284 double tm = to_secs(frm->position, fst->avctx->time_base);
2285 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
2287 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
2288 FFStream *fst = ffvideo[i];
2289 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
2290 FFrame *frm = fst->frms.first;
2291 if( !frm ) { if( !done ) return; continue; }
2292 double tm = to_secs(frm->position, fst->avctx->time_base);
2293 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
2295 if( !demand ) flow_off();
2296 if( !afrm && !vfrm ) break;
2297 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
2298 vfrm->position, vfrm->fst->avctx->time_base,
2299 afrm->position, afrm->fst->avctx->time_base);
2300 FFrame *frm = v <= 0 ? vfrm : afrm;
2301 if( frm == afrm ) mux_audio(frm);
2302 if( frm == vfrm ) mux_video(frm);
2311 mux_lock->lock("FFMPEG::run");
2314 for( int i=0; i<ffaudio.size(); ++i )
2315 ffaudio[i]->drain();
2316 for( int i=0; i<ffvideo.size(); ++i )
2317 ffvideo[i]->drain();
2319 for( int i=0; i<ffaudio.size(); ++i )
2320 ffaudio[i]->flush();
2321 for( int i=0; i<ffvideo.size(); ++i )
2322 ffvideo[i]->flush();
2326 int FFMPEG::ff_total_audio_channels()
2328 return astrm_index.size();
2331 int FFMPEG::ff_total_astreams()
2333 return ffaudio.size();
2336 int FFMPEG::ff_audio_channels(int stream)
2338 return ffaudio[stream]->channels;
2341 int FFMPEG::ff_sample_rate(int stream)
2343 return ffaudio[stream]->sample_rate;
2346 const char* FFMPEG::ff_audio_format(int stream)
2348 AVStream *st = ffaudio[stream]->st;
2349 AVCodecID id = st->codecpar->codec_id;
2350 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2351 return desc ? desc->name : _("Unknown");
2354 int FFMPEG::ff_audio_pid(int stream)
2356 return ffaudio[stream]->st->id;
2359 int64_t FFMPEG::ff_audio_samples(int stream)
2361 return ffaudio[stream]->length;
2364 // find audio astream/channels with this program,
2365 // or all program audio channels (astream=-1)
2366 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
2370 int vidx = ffvideo[vstream]->fidx;
2371 // find first program with this video stream
2372 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
2373 AVProgram *pgrm = fmt_ctx->programs[i];
2374 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
2375 int st_idx = pgrm->stream_index[j];
2376 AVStream *st = fmt_ctx->streams[st_idx];
2377 if( st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
2378 if( st_idx == vidx ) pidx = i;
2381 if( pidx < 0 ) return -1;
2383 int64_t channels = 0;
2384 AVProgram *pgrm = fmt_ctx->programs[pidx];
2385 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2386 int aidx = pgrm->stream_index[j];
2387 AVStream *st = fmt_ctx->streams[aidx];
2388 if( st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
2389 if( astream > 0 ) { --astream; continue; }
2391 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
2392 if( ffaudio[i]->fidx == aidx ) astrm = i;
2394 if( ret < 0 ) ret = astrm;
2395 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
2396 channels |= mask << ffaudio[astrm]->channel0;
2398 if( !astream ) break;
2400 channel_mask = channels;
2405 int FFMPEG::ff_total_video_layers()
2407 return vstrm_index.size();
2410 int FFMPEG::ff_total_vstreams()
2412 return ffvideo.size();
2415 int FFMPEG::ff_video_width(int stream)
2417 return ffvideo[stream]->width;
2420 int FFMPEG::ff_video_height(int stream)
2422 return ffvideo[stream]->height;
2425 int FFMPEG::ff_set_video_width(int stream, int width)
2427 int w = ffvideo[stream]->width;
2428 ffvideo[stream]->width = width;
2432 int FFMPEG::ff_set_video_height(int stream, int height)
2434 int h = ffvideo[stream]->height;
2435 ffvideo[stream]->height = height;
2439 int FFMPEG::ff_coded_width(int stream)
2441 return ffvideo[stream]->avctx->coded_width;
2444 int FFMPEG::ff_coded_height(int stream)
2446 return ffvideo[stream]->avctx->coded_height;
2449 float FFMPEG::ff_aspect_ratio(int stream)
2451 return ffvideo[stream]->aspect_ratio;
2454 const char* FFMPEG::ff_video_format(int stream)
2456 AVStream *st = ffvideo[stream]->st;
2457 AVCodecID id = st->codecpar->codec_id;
2458 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2459 return desc ? desc->name : _("Unknown");
2462 double FFMPEG::ff_frame_rate(int stream)
2464 return ffvideo[stream]->frame_rate;
2467 int64_t FFMPEG::ff_video_frames(int stream)
2469 return ffvideo[stream]->length;
2472 int FFMPEG::ff_video_pid(int stream)
2474 return ffvideo[stream]->st->id;
2478 int FFMPEG::ff_cpus()
2480 return file_base->file->cpus;
2483 int FFVideoStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
2485 avfilter_register_all();
2486 const char *sp = filter_spec;
2487 char filter_name[BCSTRLEN], *np = filter_name;
2488 int i = sizeof(filter_name);
2489 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
2491 AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
2492 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_VIDEO ) {
2493 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
2496 filter_graph = avfilter_graph_alloc();
2497 AVFilter *buffersrc = avfilter_get_by_name("buffer");
2498 AVFilter *buffersink = avfilter_get_by_name("buffersink");
2500 int ret = 0; char args[BCTEXTLEN];
2501 AVPixelFormat pix_fmt = (AVPixelFormat)avpar->format;
2502 snprintf(args, sizeof(args),
2503 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
2504 avpar->width, avpar->height, (int)pix_fmt,
2505 st->time_base.num, st->time_base.den,
2506 avpar->sample_aspect_ratio.num, avpar->sample_aspect_ratio.den);
2508 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2509 args, NULL, filter_graph);
2511 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2512 NULL, NULL, filter_graph);
2514 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
2515 (uint8_t*)&pix_fmt, sizeof(pix_fmt),
2516 AV_OPT_SEARCH_CHILDREN);
2518 ff_err(ret, "FFVideoStream::create_filter");
2520 ret = FFStream::create_filter(filter_spec);
2521 return ret >= 0 ? 0 : -1;
2524 int FFAudioStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
2526 avfilter_register_all();
2527 const char *sp = filter_spec;
2528 char filter_name[BCSTRLEN], *np = filter_name;
2529 int i = sizeof(filter_name);
2530 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
2532 AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
2533 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_AUDIO ) {
2534 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
2537 filter_graph = avfilter_graph_alloc();
2538 AVFilter *buffersrc = avfilter_get_by_name("abuffer");
2539 AVFilter *buffersink = avfilter_get_by_name("abuffersink");
2540 int ret = 0; char args[BCTEXTLEN];
2541 AVSampleFormat sample_fmt = (AVSampleFormat)avpar->format;
2542 snprintf(args, sizeof(args),
2543 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
2544 st->time_base.num, st->time_base.den, avpar->sample_rate,
2545 av_get_sample_fmt_name(sample_fmt), avpar->channel_layout);
2547 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2548 args, NULL, filter_graph);
2550 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2551 NULL, NULL, filter_graph);
2553 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
2554 (uint8_t*)&sample_fmt, sizeof(sample_fmt),
2555 AV_OPT_SEARCH_CHILDREN);
2557 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
2558 (uint8_t*)&avpar->channel_layout,
2559 sizeof(avpar->channel_layout), AV_OPT_SEARCH_CHILDREN);
2561 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
2562 (uint8_t*)&sample_rate, sizeof(sample_rate),
2563 AV_OPT_SEARCH_CHILDREN);
2565 ff_err(ret, "FFAudioStream::create_filter");
2567 ret = FFStream::create_filter(filter_spec);
2568 return ret >= 0 ? 0 : -1;
2571 int FFStream::create_filter(const char *filter_spec)
2573 /* Endpoints for the filter graph. */
2574 AVFilterInOut *outputs = avfilter_inout_alloc();
2575 outputs->name = av_strdup("in");
2576 outputs->filter_ctx = buffersrc_ctx;
2577 outputs->pad_idx = 0;
2580 AVFilterInOut *inputs = avfilter_inout_alloc();
2581 inputs->name = av_strdup("out");
2582 inputs->filter_ctx = buffersink_ctx;
2583 inputs->pad_idx = 0;
2586 int ret = !outputs->name || !inputs->name ? -1 : 0;
2588 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
2589 &inputs, &outputs, NULL);
2591 ret = avfilter_graph_config(filter_graph, NULL);
2594 ff_err(ret, "FFStream::create_filter");
2595 avfilter_graph_free(&filter_graph);
2598 avfilter_inout_free(&inputs);
2599 avfilter_inout_free(&outputs);
2603 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
2606 av_init_packet(&pkt);
2607 AVFrame *frame = av_frame_alloc();
2609 fprintf(stderr,"FFMPEG::scan: ");
2610 fprintf(stderr,_("av_frame_alloc failed\n"));
2614 index_state->add_video_markers(ffvideo.size());
2615 index_state->add_audio_markers(ffaudio.size());
2617 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2619 AVDictionary *copts = 0;
2620 av_dict_copy(&copts, opts, 0);
2621 AVStream *st = fmt_ctx->streams[i];
2622 AVCodecID codec_id = st->codecpar->codec_id;
2623 AVCodec *decoder = avcodec_find_decoder(codec_id);
2624 AVCodecContext *avctx = avcodec_alloc_context3(decoder);
2626 eprintf(_("cant allocate codec context\n"));
2627 ret = AVERROR(ENOMEM);
2630 avcodec_parameters_to_context(avctx, st->codecpar);
2631 ret = avcodec_open2(avctx, decoder, &copts);
2633 av_dict_free(&copts);
2635 fprintf(stderr,"FFMPEG::scan: ");
2636 fprintf(stderr,_("codec open failed\n"));
2639 AVCodecParameters *avpar = st->codecpar;
2640 switch( avpar->codec_type ) {
2641 case AVMEDIA_TYPE_VIDEO: {
2642 int vidx = ffvideo.size();
2643 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
2644 if( vidx < 0 ) break;
2645 ffvideo[vidx]->avctx = avctx;
2647 case AVMEDIA_TYPE_AUDIO: {
2648 int aidx = ffaudio.size();
2649 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
2650 if( aidx < 0 ) continue;
2651 ffaudio[aidx]->avctx = avctx;
2658 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2659 AVStream *st = fmt_ctx->streams[i];
2660 AVCodecParameters *avpar = st->codecpar;
2661 if( avpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
2662 int64_t tstmp = st->start_time;
2663 if( tstmp == AV_NOPTS_VALUE ) continue;
2664 int aidx = ffaudio.size();
2665 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
2666 if( aidx < 0 ) continue;
2667 FFAudioStream *aud = ffaudio[aidx];
2668 tstmp -= aud->nudge;
2669 double secs = to_secs(tstmp, st->time_base);
2670 aud->curr_pos = secs * aud->sample_rate + 0.5;
2674 for( int64_t count=0; !*canceled; ++count ) {
2675 av_packet_unref(&pkt);
2676 pkt.data = 0; pkt.size = 0;
2678 int ret = av_read_frame(fmt_ctx, &pkt);
2680 if( ret == AVERROR_EOF ) break;
2681 if( ++errs > 100 ) {
2682 ff_err(ret,_("over 100 read_frame errs\n"));
2687 if( !pkt.data ) continue;
2688 int i = pkt.stream_index;
2689 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
2690 AVStream *st = fmt_ctx->streams[i];
2691 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
2693 AVCodecParameters *avpar = st->codecpar;
2694 switch( avpar->codec_type ) {
2695 case AVMEDIA_TYPE_VIDEO: {
2696 int vidx = ffvideo.size();
2697 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
2698 if( vidx < 0 ) break;
2699 FFVideoStream *vid = ffvideo[vidx];
2700 int64_t tstmp = pkt.dts;
2701 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.pts;
2702 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
2703 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
2704 double secs = to_secs(tstmp, st->time_base);
2705 int64_t frm = secs * vid->frame_rate + 0.5;
2706 if( frm < 0 ) frm = 0;
2707 index_state->put_video_mark(vidx, frm, pkt.pos);
2710 ret = avcodec_send_packet(vid->avctx, pkt);
2711 if( ret < 0 ) break;
2712 while( (ret=vid->decode_frame(frame)) > 0 ) {}
2715 case AVMEDIA_TYPE_AUDIO: {
2716 int aidx = ffaudio.size();
2717 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
2718 if( aidx < 0 ) break;
2719 FFAudioStream *aud = ffaudio[aidx];
2720 int64_t tstmp = pkt.pts;
2721 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
2722 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
2723 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
2724 double secs = to_secs(tstmp, st->time_base);
2725 int64_t sample = secs * aud->sample_rate + 0.5;
2727 index_state->put_audio_mark(aidx, sample, pkt.pos);
2729 ret = avcodec_send_packet(aud->avctx, &pkt);
2730 if( ret < 0 ) break;
2731 int ch = aud->channel0, nch = aud->channels;
2732 int64_t pos = index_state->pos(ch);
2733 if( pos != aud->curr_pos ) {
2734 if( abs(pos-aud->curr_pos) > 1 )
2735 printf("audio%d pad %jd %jd (%jd)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
2736 index_state->pad_data(ch, nch, aud->curr_pos);
2738 while( (ret=aud->decode_frame(frame)) > 0 ) {
2739 if( frame->channels != nch ) break;
2741 int len = aud->get_samples(samples,
2742 &frame->extended_data[0], frame->nb_samples);
2743 pos = aud->curr_pos;
2744 if( (aud->curr_pos += len) >= 0 ) {
2746 samples += -pos * nch;
2747 len = aud->curr_pos;
2749 for( int i=0; i<nch; ++i )
2750 index_state->put_data(ch+i,nch,samples+i,len);
2757 av_frame_free(&frame);
2761 void FFStream::load_markers(IndexMarks &marks, double rate)
2764 int64_t sz = marks.size();
2765 int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
2766 int nb_ent = st->nb_index_entries;
2767 // some formats already have an index
2769 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
2770 int64_t tstmp = ep->timestamp;
2771 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
2772 double secs = ffmpeg->to_secs(tstmp, st->time_base);
2773 int64_t no = secs * rate;
2774 while( in < sz && marks[in].no <= no ) ++in;
2776 int64_t len = sz - in;
2777 int64_t count = max_entries - nb_ent;
2778 if( count > len ) count = len;
2779 for( int i=0; i<count; ++i ) {
2780 int k = in + i * len / count;
2781 int64_t no = marks[k].no, pos = marks[k].pos;
2782 double secs = (double)no / rate;
2783 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
2784 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
2785 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);