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()
151 memset(bfr, 0, lmt-bfr);
154 void FFAudioStream::iseek(int64_t ofs)
156 if( ofs > hpos ) ofs = hpos;
157 if( ofs > sz ) ofs = sz;
158 outp = inp - ofs*nch;
159 if( outp < bfr ) outp += sz*nch;
162 float *FFAudioStream::get_outp(int ofs)
169 int64_t FFAudioStream::put_inp(int ofs)
172 return (inp-outp) / nch;
175 int FFAudioStream::write(const float *fp, long len)
183 while( --k >= 0 ) *ip++ = *fp++;
184 if( ip >= lmt ) ip = bfr;
191 int FFAudioStream::zero(long len)
199 while( --k >= 0 ) *ip++ = 0;
200 if( ip >= lmt ) ip = bfr;
207 // does not advance outp
208 int FFAudioStream::read(double *dp, long len, int ch)
211 float *op = outp + ch;
212 float *lmt1 = lmt + nch-1;
214 int k = (lmt1 - op) / nch;
217 while( --k >= 0 ) { *dp++ = *op; op += nch; }
218 if( op >= lmt ) op -= sz*nch;
223 // load linear buffer, no wrapping allowed, does not advance inp
224 int FFAudioStream::write(const double *dp, long len, int ch)
227 float *ip = inp + ch;
228 while( --n >= 0 ) { *ip = *dp++; ip += nch; }
233 FFStream::FFStream(FFMPEG *ffmpeg, AVStream *st, int fidx)
235 this->ffmpeg = ffmpeg;
238 frm_lock = new Mutex("FFStream::frm_lock");
245 nudge = AV_NOPTS_VALUE;
246 seek_pos = curr_pos = 0;
248 reading = writing = 0;
255 FFStream::~FFStream()
257 if( reading > 0 || writing > 0 ) avcodec_close(avctx);
258 if( avctx ) avcodec_free_context(&avctx);
259 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
260 if( bsfc ) av_bsf_free(&bsfc);
261 while( frms.first ) frms.remove(frms.first);
262 if( filter_graph ) avfilter_graph_free(&filter_graph);
263 if( frame ) av_frame_free(&frame);
264 if( fframe ) av_frame_free(&fframe);
268 void FFStream::ff_lock(const char *cp)
270 FFMPEG::fflock.lock(cp);
273 void FFStream::ff_unlock()
275 FFMPEG::fflock.unlock();
278 void FFStream::queue(FFrame *frm)
280 frm_lock->lock("FFStream::queue");
284 ffmpeg->mux_lock->unlock();
287 void FFStream::dequeue(FFrame *frm)
289 frm_lock->lock("FFStream::dequeue");
291 frms.remove_pointer(frm);
295 int FFStream::encode_activate()
298 writing = ffmpeg->encode_activate();
302 int FFStream::decode_activate()
304 if( reading < 0 && (reading=ffmpeg->decode_activate()) > 0 ) {
305 ff_lock("FFStream::decode_activate");
307 AVDictionary *copts = 0;
308 av_dict_copy(&copts, ffmpeg->opts, 0);
310 // this should be avformat_copy_context(), but no copy avail
311 ret = avformat_open_input(&fmt_ctx, ffmpeg->fmt_ctx->filename, NULL, &copts);
313 ret = avformat_find_stream_info(fmt_ctx, 0);
314 st = fmt_ctx->streams[fidx];
317 if( ret >= 0 && st != 0 ) {
318 AVCodecID codec_id = st->codecpar->codec_id;
319 AVCodec *decoder = avcodec_find_decoder(codec_id);
320 avctx = avcodec_alloc_context3(decoder);
322 eprintf(_("cant allocate codec context\n"));
323 ret = AVERROR(ENOMEM);
326 av_codec_set_pkt_timebase(avctx, st->time_base);
327 if( decoder->capabilities & AV_CODEC_CAP_DR1 )
328 avctx->flags |= CODEC_FLAG_EMU_EDGE;
329 avcodec_parameters_to_context(avctx, st->codecpar);
330 ret = avcodec_open2(avctx, decoder, &copts);
336 eprintf(_("open decoder failed\n"));
339 eprintf(_("can't clone input file\n"));
340 av_dict_free(&copts);
346 int FFStream::read_packet()
348 av_packet_unref(ipkt);
349 int ret = av_read_frame(fmt_ctx, ipkt);
352 if( ret == AVERROR_EOF ) return 0;
353 ff_err(ret, "FFStream::read_packet: av_read_frame failed\n");
360 int FFStream::decode(AVFrame *frame)
363 int retries = MAX_RETRY;
365 while( ret >= 0 && !flushed && --retries >= 0 ) {
367 if( (ret=read_packet()) < 0 ) break;
368 AVPacket *pkt = ret > 0 ? (AVPacket*)ipkt : 0;
370 if( pkt->stream_index != st->index ) continue;
371 if( !pkt->data | !pkt->size ) continue;
373 if( (ret=avcodec_send_packet(avctx, pkt)) < 0 ) {
374 ff_err(ret, "FFStream::decode: avcodec_send_packet failed\n");
380 if( (ret=decode_frame(frame)) > 0 ) break;
388 fprintf(stderr, "FFStream::decode: Retry limit\n");
392 fprintf(stderr, "FFStream::decode: failed\n");
396 int FFStream::load_filter(AVFrame *frame)
398 av_frame_unref(frame);
399 int ret = av_buffersrc_add_frame_flags(buffersrc_ctx,
400 frame, AV_BUFFERSRC_FLAG_KEEP_REF);
402 eprintf(_("av_buffersrc_add_frame_flags failed\n"));
406 int FFStream::read_filter(AVFrame *frame)
408 int ret = av_buffersink_get_frame(buffersink_ctx, frame);
410 if( ret == AVERROR(EAGAIN) ) return 0;
411 if( ret == AVERROR_EOF ) { st_eof(1); return -1; }
412 ff_err(ret, "FFStream::read_filter: av_buffersink_get_frame failed\n");
418 int FFStream::read_frame(AVFrame *frame)
420 av_frame_unref(frame);
421 if( !filter_graph || !buffersrc_ctx || !buffersink_ctx )
422 return decode(frame);
423 if( !fframe && !(fframe=av_frame_alloc()) ) {
424 fprintf(stderr, "FFStream::read_frame: av_frame_alloc failed\n");
428 while( !flushed && !(ret=read_filter(frame)) ) {
429 if( (ret=decode(fframe)) < 0 ) break;
430 if( ret > 0 && (ret=load_filter(fframe)) < 0 ) break;
435 int FFStream::write_packet(FFPacket &pkt)
439 av_packet_rescale_ts(pkt, avctx->time_base, st->time_base);
440 pkt->stream_index = st->index;
441 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, pkt);
444 ret = av_bsf_send_packet(bsfc, pkt);
447 if( (ret=av_bsf_receive_packet(bsfc, bs)) < 0 ) {
448 if( ret == AVERROR(EAGAIN) ) return 0;
449 if( ret == AVERROR_EOF ) return -1;
452 av_packet_rescale_ts(bs, avctx->time_base, st->time_base);
453 bs->stream_index = st->index;
454 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, bs);
458 ff_err(ret, "FFStream::write_packet: write packet failed\n");
462 int FFStream::encode_frame(AVFrame *frame)
464 int pkts = 0, ret = 0;
465 for( int retry=100; --retry>=0; ) {
467 ret = avcodec_send_frame(avctx, frame);
468 if( !ret && frame ) return pkts;
469 if( ret < 0 && ret != AVERROR(EAGAIN) ) break;
471 ret = avcodec_receive_packet(avctx, opkt);
472 if( !frame && ret == AVERROR_EOF ) return pkts;
474 ret = write_packet(opkt);
478 ff_err(ret, "FFStream::encode_frame: encode failed\n");
482 int FFStream::flush()
486 int ret = encode_frame(0);
488 ff_err(ret, "FFStream::flush");
489 return ret >= 0 ? 0 : 1;
492 int FFStream::seek(int64_t no, double rate)
494 // default ffmpeg native seek
496 int64_t pos = no, pkt_pos = -1;
497 IndexMarks *index_markers = get_markers();
498 if( index_markers && index_markers->size() > 1 ) {
499 IndexMarks &marks = *index_markers;
500 int i = marks.find(pos);
501 int64_t n = i < 0 ? (i=0) : marks[i].no;
502 // if indexed seek point not too far away (<30 secs), use index
503 if( no-n < 30*rate ) {
506 if( i < marks.size() ) pkt_pos = marks[i].pos;
510 if( pos == curr_pos ) return 0;
511 double secs = pos < 0 ? 0. : pos / rate;
512 AVRational time_base = st->time_base;
513 int64_t tstmp = time_base.num > 0 ? secs * time_base.den/time_base.num : 0;
514 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
517 // seek all streams using the default timebase.
518 // this is how ffmpeg and ffplay work. stream seeks are less tested.
519 tstmp = av_rescale_q(tstmp, time_base, AV_TIME_BASE_Q);
523 avcodec_flush_buffers(avctx);
524 avformat_flush(fmt_ctx);
526 int64_t seek = tstmp;
527 int flags = AVSEEK_FLAG_ANY;
528 if( !(fmt_ctx->iformat->flags & AVFMT_NO_BYTE_SEEK) && pkt_pos >= 0 ) {
530 flags = AVSEEK_FLAG_BYTE;
532 int ret = avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, seek, INT64_MAX, flags);
534 int ret = av_seek_frame(fmt_ctx, idx, tstmp, AVSEEK_FLAG_ANY);
536 int retry = MAX_RETRY;
538 need_packet = 0; flushed = 0;
539 seeked = 1; st_eof(0);
540 // read up to retry packets, limited to npkts in stream, and not pkt.pos past pkt_pos
541 while( --retry >= 0 ) {
542 if( read_packet() <= 0 ) { ret = -1; break; }
543 if( ipkt->stream_index != st->index ) continue;
544 if( !ipkt->data || !ipkt->size ) continue;
545 if( pkt_pos >= 0 && ipkt->pos >= pkt_pos ) break;
546 if( --npkts <= 0 ) break;
547 int64_t pkt_ts = ipkt->dts != AV_NOPTS_VALUE ? ipkt->dts : ipkt->pts;
548 if( pkt_ts == AV_NOPTS_VALUE ) continue;
549 if( pkt_ts >= tstmp ) break;
552 fprintf(stderr,"FFStream::seek: retry limit, pos=%jd tstmp=%jd\n",pos,tstmp);
556 ret = avcodec_send_packet(avctx, ipkt);
558 //some codecs need more than one pkt to resync
559 if( ret == AVERROR_INVALIDDATA ) ret = 0;
561 ff_err(ret, "FFStream::avcodec_send_packet failed\n");
566 printf("** seek fail %jd, %jd\n", pos, tstmp);
567 seeked = need_packet = 0;
571 //printf("seeked pos = %ld, %ld\n", pos, tstmp);
572 seek_pos = curr_pos = pos;
576 FFAudioStream::FFAudioStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
577 : FFStream(ffmpeg, strm, fidx)
580 channel0 = channels = 0;
584 resample_context = 0;
585 swr_ichs = swr_ifmt = swr_irate = 0;
594 bfr = new float[bsz];
599 FFAudioStream::~FFAudioStream()
601 if( resample_context ) swr_free(&resample_context);
606 void FFAudioStream::init_swr(int ichs, int ifmt, int irate)
608 if( resample_context ) {
609 if( swr_ichs == ichs && swr_ifmt == ifmt && swr_irate == irate )
611 swr_free(&resample_context);
613 swr_ichs = ichs; swr_ifmt = ifmt; swr_irate = irate;
614 if( ichs == channels && ifmt == AV_SAMPLE_FMT_FLT && irate == sample_rate )
616 uint64_t ilayout = av_get_default_channel_layout(ichs);
617 if( !ilayout ) ilayout = ((uint64_t)1<<ichs) - 1;
618 uint64_t olayout = av_get_default_channel_layout(channels);
619 if( !olayout ) olayout = ((uint64_t)1<<channels) - 1;
620 resample_context = swr_alloc_set_opts(NULL,
621 olayout, AV_SAMPLE_FMT_FLT, sample_rate,
622 ilayout, (AVSampleFormat)ifmt, irate,
624 if( resample_context )
625 swr_init(resample_context);
628 int FFAudioStream::get_samples(float *&samples, uint8_t **data, int len)
630 samples = *(float **)data;
631 if( resample_context ) {
632 if( len > aud_bfr_sz ) {
638 aud_bfr = new float[aud_bfr_sz*channels];
640 int ret = swr_convert(resample_context,
641 (uint8_t**)&aud_bfr, aud_bfr_sz, (const uint8_t**)data, len);
643 ff_err(ret, "FFAudioStream::get_samples: swr_convert failed\n");
652 int FFAudioStream::load_history(uint8_t **data, int len)
655 len = get_samples(samples, data, len);
657 // biggest user bfr since seek + frame
658 realloc(mbsz + len + 1, channels);
664 int FFAudioStream::decode_frame(AVFrame *frame)
666 int first_frame = seeked; seeked = 0;
667 int ret = avcodec_receive_frame(avctx, frame);
669 if( first_frame || ret == AVERROR(EAGAIN) ) return 0;
670 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
671 ff_err(ret, "FFAudioStream::decode_frame: Could not read audio frame\n");
674 int64_t pkt_ts = av_frame_get_best_effort_timestamp(frame);
675 if( pkt_ts != AV_NOPTS_VALUE )
676 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * sample_rate + 0.5;
680 int FFAudioStream::encode_activate()
682 if( writing >= 0 ) return writing;
683 frame_sz = avctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE ?
684 10000 : avctx->frame_size;
685 return FFStream::encode_activate();
688 int64_t FFAudioStream::load_buffer(double ** const sp, int len)
690 reserve(len+1, st->codecpar->channels);
691 for( int ch=0; ch<nch; ++ch )
692 write(sp[ch], len, ch);
696 int FFAudioStream::in_history(int64_t pos)
698 if( pos > curr_pos ) return 0;
700 if( len > sz ) len = sz;
701 if( pos < curr_pos - len ) return 0;
706 int FFAudioStream::init_frame(AVFrame *frame)
708 frame->nb_samples = frame_sz;
709 frame->format = avctx->sample_fmt;
710 frame->channel_layout = avctx->channel_layout;
711 frame->sample_rate = avctx->sample_rate;
712 int ret = av_frame_get_buffer(frame, 0);
714 ff_err(ret, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
718 int FFAudioStream::load(int64_t pos, int len)
720 if( audio_seek(pos) < 0 ) return -1;
721 if( !frame && !(frame=av_frame_alloc()) ) {
722 fprintf(stderr, "FFAudioStream::load: av_frame_alloc failed\n");
725 if( mbsz < len ) mbsz = len;
726 int64_t end_pos = pos + len;
728 for( int i=0; ret>=0 && !flushed && curr_pos<end_pos && i<MAX_RETRY; ++i ) {
729 ret = read_frame(frame);
731 init_swr(frame->channels, frame->format, frame->sample_rate);
732 load_history(&frame->extended_data[0], frame->nb_samples);
733 curr_pos += frame->nb_samples;
736 if( end_pos > curr_pos ) {
737 zero(end_pos - curr_pos);
740 len = curr_pos - pos;
745 int FFAudioStream::audio_seek(int64_t pos)
747 if( decode_activate() <= 0 ) return -1;
748 if( !st->codecpar ) return -1;
749 if( in_history(pos) ) return 0;
750 if( pos == curr_pos ) return 0;
751 reset_history(); mbsz = 0;
752 // guarentee preload > 1sec samples
753 if( seek(pos-sample_rate, sample_rate) < 0 ) return -1;
757 int FFAudioStream::encode(double **samples, int len)
759 if( encode_activate() <= 0 ) return -1;
762 int64_t count = samples ? load_buffer(samples, len) : used();
763 int frame_sz1 = samples ? frame_sz-1 : 0;
766 while( ret >= 0 && count > frame_sz1 ) {
767 frm = new FFrame(this);
768 if( (ret=frm->initted()) < 0 ) break;
769 AVFrame *frame = *frm;
770 len = count >= frame_sz ? frame_sz : count;
771 float *bfrp = get_outp(len);
772 ret = swr_convert(resample_context,
773 (uint8_t **)frame->extended_data, len,
774 (const uint8_t **)&bfrp, len);
776 ff_err(ret, "FFAudioStream::encode: swr_convert failed\n");
779 frame->nb_samples = len;
780 frm->queue(curr_pos);
787 return ret >= 0 ? 0 : 1;
790 int FFAudioStream::drain()
795 int FFAudioStream::encode_frame(AVFrame *frame)
797 return FFStream::encode_frame(frame);
800 int FFAudioStream::write_packet(FFPacket &pkt)
802 return FFStream::write_packet(pkt);
805 void FFAudioStream::load_markers()
807 IndexState *index_state = ffmpeg->file_base->asset->index_state;
808 if( !index_state || idx >= index_state->audio_markers.size() ) return;
809 if( index_state->marker_status == MARKERS_NOTTESTED ) return;
810 FFStream::load_markers(*index_state->audio_markers[idx], sample_rate);
813 IndexMarks *FFAudioStream::get_markers()
815 IndexState *index_state = ffmpeg->file_base->asset->index_state;
816 if( !index_state || idx >= index_state->audio_markers.size() ) return 0;
817 return index_state->audio_markers[idx];
820 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
821 : FFStream(ffmpeg, strm, fidx)
832 FFVideoStream::~FFVideoStream()
836 int FFVideoStream::decode_frame(AVFrame *frame)
838 int first_frame = seeked; seeked = 0;
839 int ret = avcodec_receive_frame(avctx, frame);
841 if( first_frame || ret == AVERROR(EAGAIN) ) return 0;
842 if( ret == AVERROR(EAGAIN) ) return 0;
843 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
844 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame\n");
847 int64_t pkt_ts = av_frame_get_best_effort_timestamp(frame);
848 if( pkt_ts != AV_NOPTS_VALUE )
849 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * frame_rate + 0.5;
853 int FFVideoStream::load(VFrame *vframe, int64_t pos)
855 int ret = video_seek(pos);
856 if( ret < 0 ) return -1;
857 if( !frame && !(frame=av_frame_alloc()) ) {
858 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
861 for( int i=0; ret>=0 && !flushed && curr_pos<=pos && i<MAX_RETRY; ++i ) {
862 ret = read_frame(frame);
863 if( ret > 0 ) ++curr_pos;
865 if( frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0 )
868 ret = convert_cmodel(vframe, frame);
870 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
874 int FFVideoStream::video_seek(int64_t pos)
876 if( decode_activate() <= 0 ) return -1;
877 if( !st->codecpar ) return -1;
878 if( pos == curr_pos-1 && !seeked ) return 0;
879 // if close enough, just read up to current
880 int gop = avctx->gop_size;
881 if( gop < 4 ) gop = 4;
882 if( gop > 64 ) gop = 64;
883 int read_limit = curr_pos + 3*gop;
884 if( pos >= curr_pos && pos <= read_limit ) return 0;
885 // guarentee preload more than 2*gop frames
886 if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
890 int FFVideoStream::init_frame(AVFrame *picture)
892 picture->format = avctx->pix_fmt;
893 picture->width = avctx->width;
894 picture->height = avctx->height;
895 int ret = av_frame_get_buffer(picture, 32);
899 int FFVideoStream::encode(VFrame *vframe)
901 if( encode_activate() <= 0 ) return -1;
903 FFrame *picture = new FFrame(this);
904 int ret = picture->initted();
906 AVFrame *frame = *picture;
907 frame->pts = curr_pos;
908 ret = convert_pixfmt(vframe, frame);
911 picture->queue(curr_pos);
915 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
918 return ret >= 0 ? 0 : 1;
921 int FFVideoStream::drain()
926 int FFVideoStream::encode_frame(AVFrame *frame)
929 frame->interlaced_frame = interlaced;
930 frame->top_field_first = top_field_first;
932 return FFStream::encode_frame(frame);
935 int FFVideoStream::write_packet(FFPacket &pkt)
937 if( !(ffmpeg->fmt_ctx->oformat->flags & AVFMT_VARIABLE_FPS) )
939 return FFStream::write_packet(pkt);
942 AVPixelFormat FFVideoConvert::color_model_to_pix_fmt(int color_model)
944 switch( color_model ) {
945 case BC_YUV422: return AV_PIX_FMT_YUYV422;
946 case BC_RGB888: return AV_PIX_FMT_RGB24;
947 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
948 case BC_BGR8888: return AV_PIX_FMT_BGR0;
949 case BC_BGR888: return AV_PIX_FMT_BGR24;
950 case BC_ARGB8888: return AV_PIX_FMT_ARGB;
951 case BC_ABGR8888: return AV_PIX_FMT_ABGR;
952 case BC_RGB8: return AV_PIX_FMT_RGB8;
953 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
954 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
955 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
956 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
957 case BC_RGB565: return AV_PIX_FMT_RGB565;
958 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
959 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
960 case BC_AYUV16161616: return AV_PIX_FMT_AYUV64LE;
964 return AV_PIX_FMT_NB;
967 int FFVideoConvert::pix_fmt_to_color_model(AVPixelFormat pix_fmt)
970 case AV_PIX_FMT_YUYV422: return BC_YUV422;
971 case AV_PIX_FMT_RGB24: return BC_RGB888;
972 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
973 case AV_PIX_FMT_BGR0: return BC_BGR8888;
974 case AV_PIX_FMT_BGR24: return BC_BGR888;
975 case AV_PIX_FMT_ARGB: return BC_ARGB8888;
976 case AV_PIX_FMT_ABGR: return BC_ABGR8888;
977 case AV_PIX_FMT_RGB8: return BC_RGB8;
978 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
979 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
980 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
981 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
982 case AV_PIX_FMT_RGB565: return BC_RGB565;
983 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
984 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
985 case AV_PIX_FMT_AYUV64LE: return BC_AYUV16161616;
992 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip)
994 AVFrame *ipic = av_frame_alloc();
995 int ret = convert_picture_vframe(frame, ip, ipic);
996 av_frame_free(&ipic);
1000 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip, AVFrame *ipic)
1002 int cmodel = frame->get_color_model();
1003 AVPixelFormat ofmt = color_model_to_pix_fmt(cmodel);
1004 if( ofmt == AV_PIX_FMT_NB ) return -1;
1005 int size = av_image_fill_arrays(ipic->data, ipic->linesize,
1006 frame->get_data(), ofmt, frame->get_w(), frame->get_h(), 1);
1007 if( size < 0 ) return -1;
1009 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1010 int ysz = bpp * frame->get_w(), usz = ysz;
1019 // override av_image_fill_arrays() for planar types
1020 ipic->data[0] = frame->get_y(); ipic->linesize[0] = ysz;
1021 ipic->data[1] = frame->get_u(); ipic->linesize[1] = usz;
1022 ipic->data[2] = frame->get_v(); ipic->linesize[2] = usz;
1025 ipic->data[0] = frame->get_data();
1026 ipic->linesize[0] = frame->get_bytes_per_line();
1030 AVPixelFormat pix_fmt = (AVPixelFormat)ip->format;
1031 convert_ctx = sws_getCachedContext(convert_ctx, ip->width, ip->height, pix_fmt,
1032 frame->get_w(), frame->get_h(), ofmt, SWS_POINT, NULL, NULL, NULL);
1033 if( !convert_ctx ) {
1034 fprintf(stderr, "FFVideoConvert::convert_picture_frame:"
1035 " sws_getCachedContext() failed\n");
1038 int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ip->height,
1039 ipic->data, ipic->linesize);
1041 ff_err(ret, "FFVideoConvert::convert_picture_frame: sws_scale() failed\n");
1047 int FFVideoConvert::convert_cmodel(VFrame *frame, AVFrame *ip)
1049 // try direct transfer
1050 if( !convert_picture_vframe(frame, ip) ) return 1;
1051 // use indirect transfer
1052 AVPixelFormat ifmt = (AVPixelFormat)ip->format;
1053 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
1055 for( int i = 0; i <desc->nb_components; ++i ) {
1056 int bits = desc->comp[i].depth;
1057 if( bits > max_bits ) max_bits = bits;
1059 int imodel = pix_fmt_to_color_model(ifmt);
1060 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1061 int cmodel = frame->get_color_model();
1062 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1063 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1064 imodel = cmodel_is_yuv ?
1065 (BC_CModels::has_alpha(cmodel) ?
1067 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1068 (BC_CModels::has_alpha(cmodel) ?
1069 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1070 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1072 VFrame vframe(ip->width, ip->height, imodel);
1073 if( convert_picture_vframe(&vframe, ip) ) return -1;
1074 frame->transfer_from(&vframe);
1078 int FFVideoConvert::transfer_cmodel(VFrame *frame, AVFrame *ifp)
1080 int ret = convert_cmodel(frame, ifp);
1082 const AVDictionary *src = av_frame_get_metadata(ifp);
1083 AVDictionaryEntry *t = NULL;
1084 BC_Hash *hp = frame->get_params();
1086 while( (t=av_dict_get(src, "", t, AV_DICT_IGNORE_SUFFIX)) )
1087 hp->update(t->key, t->value);
1092 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op)
1094 AVFrame *opic = av_frame_alloc();
1095 int ret = convert_vframe_picture(frame, op, opic);
1096 av_frame_free(&opic);
1100 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op, AVFrame *opic)
1102 int cmodel = frame->get_color_model();
1103 AVPixelFormat ifmt = color_model_to_pix_fmt(cmodel);
1104 if( ifmt == AV_PIX_FMT_NB ) return -1;
1105 int size = av_image_fill_arrays(opic->data, opic->linesize,
1106 frame->get_data(), ifmt, frame->get_w(), frame->get_h(), 1);
1107 if( size < 0 ) return -1;
1109 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1110 int ysz = bpp * frame->get_w(), usz = ysz;
1119 // override av_image_fill_arrays() for planar types
1120 opic->data[0] = frame->get_y(); opic->linesize[0] = ysz;
1121 opic->data[1] = frame->get_u(); opic->linesize[1] = usz;
1122 opic->data[2] = frame->get_v(); opic->linesize[2] = usz;
1125 opic->data[0] = frame->get_data();
1126 opic->linesize[0] = frame->get_bytes_per_line();
1130 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1131 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(),
1132 ifmt, op->width, op->height, ofmt, SWS_POINT, NULL, NULL, NULL);
1133 if( !convert_ctx ) {
1134 fprintf(stderr, "FFVideoConvert::convert_frame_picture:"
1135 " sws_getCachedContext() failed\n");
1138 int ret = sws_scale(convert_ctx, opic->data, opic->linesize, 0, frame->get_h(),
1139 op->data, op->linesize);
1141 ff_err(ret, "FFVideoConvert::convert_frame_picture: sws_scale() failed\n");
1147 int FFVideoConvert::convert_pixfmt(VFrame *frame, AVFrame *op)
1149 // try direct transfer
1150 if( !convert_vframe_picture(frame, op) ) return 1;
1151 // use indirect transfer
1152 int cmodel = frame->get_color_model();
1153 int max_bits = BC_CModels::calculate_pixelsize(cmodel) * 8;
1154 max_bits /= BC_CModels::components(cmodel);
1155 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1156 int imodel = pix_fmt_to_color_model(ofmt);
1157 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1158 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1159 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1160 imodel = cmodel_is_yuv ?
1161 (BC_CModels::has_alpha(cmodel) ?
1163 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1164 (BC_CModels::has_alpha(cmodel) ?
1165 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1166 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1168 VFrame vframe(frame->get_w(), frame->get_h(), imodel);
1169 vframe.transfer_from(frame);
1170 if( !convert_vframe_picture(&vframe, op) ) return 1;
1174 int FFVideoConvert::transfer_pixfmt(VFrame *frame, AVFrame *ofp)
1176 int ret = convert_pixfmt(frame, ofp);
1178 BC_Hash *hp = frame->get_params();
1179 AVDictionary **dict = avpriv_frame_get_metadatap(ofp);
1180 //av_dict_free(dict);
1181 for( int i=0; i<hp->size(); ++i ) {
1182 char *key = hp->get_key(i), *val = hp->get_value(i);
1183 av_dict_set(dict, key, val, 0);
1189 void FFVideoStream::load_markers()
1191 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1192 if( !index_state || idx >= index_state->video_markers.size() ) return;
1193 FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
1196 IndexMarks *FFVideoStream::get_markers()
1198 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1199 if( !index_state || idx >= index_state->video_markers.size() ) return 0;
1200 return !index_state ? 0 : index_state->video_markers[idx];
1204 FFMPEG::FFMPEG(FileBase *file_base)
1207 this->file_base = file_base;
1208 memset(file_format,0,sizeof(file_format));
1209 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
1210 flow_lock = new Condition(1,"FFStream::flow_lock",0);
1213 decoding = encoding = 0;
1214 has_audio = has_video = 0;
1217 opt_video_filter = 0;
1218 opt_audio_filter = 0;
1219 char option_path[BCTEXTLEN];
1220 set_option_path(option_path, "%s", "ffmpeg.opts");
1221 read_options(option_path, opts);
1226 ff_lock("FFMPEG::~FFMPEG()");
1228 ffaudio.remove_all_objects();
1229 ffvideo.remove_all_objects();
1230 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1234 av_dict_free(&opts);
1235 delete [] opt_video_filter;
1236 delete [] opt_audio_filter;
1239 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1241 const int *p = codec->supported_samplerates;
1242 if( !p ) return sample_rate;
1244 if( *p == sample_rate ) return *p;
1250 static inline AVRational std_frame_rate(int i)
1252 static const int m1 = 1001*12, m2 = 1000*12;
1253 static const int freqs[] = {
1254 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1255 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
1257 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1258 return (AVRational) { freq, 1001*12 };
1261 AVRational FFMPEG::check_frame_rate(AVCodec *codec, double frame_rate)
1263 const AVRational *p = codec->supported_framerates;
1264 AVRational rate, best_rate = (AVRational) { 0, 0 };
1265 double max_err = 1.; int i = 0;
1266 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1267 double framerate = (double) rate.num / rate.den;
1268 double err = fabs(frame_rate/framerate - 1.);
1269 if( err >= max_err ) continue;
1273 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1276 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1279 double display_aspect = asset->width / (double)asset->height;
1280 double sample_aspect = display_aspect / asset->aspect_ratio;
1281 int width = 1000000, height = width * sample_aspect + 0.5;
1283 MWindow::create_aspect_ratio(w, h, width, height);
1284 return (AVRational){(int)w, (int)h};
1287 return (AVRational){1, 1};
1291 AVRational FFMPEG::to_time_base(int sample_rate)
1293 return (AVRational){1, sample_rate};
1296 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
1298 char *ep = path + BCTEXTLEN-1;
1299 strncpy(path, File::get_cindat_path(), ep-path);
1300 strncat(path, "/ffmpeg/", ep-path);
1301 path += strlen(path);
1304 path += vsnprintf(path, ep-path, fmt, ap);
1309 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
1314 set_option_path(path, "%s/%s", type, spec);
1317 int FFMPEG::get_format(char *format, const char *path, const char *spec)
1319 char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
1320 get_option_path(option_path, path, spec);
1321 FILE *fp = fopen(option_path,"r");
1324 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1326 line[sizeof(line)-1] = 0;
1327 ret = scan_option_line(line, format, codec);
1333 int FFMPEG::get_codec(char *codec, const char *path, const char *spec)
1335 char option_path[BCTEXTLEN], line[BCTEXTLEN], format[BCTEXTLEN];
1336 get_option_path(option_path, path, spec);
1337 FILE *fp = fopen(option_path,"r");
1340 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1343 line[sizeof(line)-1] = 0;
1344 ret = scan_option_line(line, format, codec);
1347 char *vp = codec, *ep = vp+BCTEXTLEN-1;
1348 while( vp < ep && *vp && *vp != '|' ) ++vp;
1349 if( *vp == '|' ) --vp;
1350 while( vp > codec && (*vp==' ' || *vp=='\t') ) *vp-- = 0;
1355 int FFMPEG::get_file_format()
1357 char audio_muxer[BCSTRLEN], video_muxer[BCSTRLEN];
1358 char audio_format[BCSTRLEN], video_format[BCSTRLEN];
1359 audio_muxer[0] = audio_format[0] = 0;
1360 video_muxer[0] = video_format[0] = 0;
1361 Asset *asset = file_base->asset;
1362 int ret = asset ? 0 : 1;
1363 if( !ret && asset->audio_data ) {
1364 if( !(ret=get_format(audio_format, "audio", asset->acodec)) ) {
1365 if( get_format(audio_muxer, "format", audio_format) ) {
1366 strcpy(audio_muxer, audio_format);
1367 audio_format[0] = 0;
1371 if( !ret && asset->video_data ) {
1372 if( !(ret=get_format(video_format, "video", asset->vcodec)) ) {
1373 if( get_format(video_muxer, "format", video_format) ) {
1374 strcpy(video_muxer, video_format);
1375 video_format[0] = 0;
1379 if( !ret && !audio_muxer[0] && !video_muxer[0] )
1381 if( !ret && audio_muxer[0] && video_muxer[0] &&
1382 strcmp(audio_muxer, video_muxer) ) ret = -1;
1383 if( !ret && audio_format[0] && video_format[0] &&
1384 strcmp(audio_format, video_format) ) ret = -1;
1386 strcpy(file_format, !audio_format[0] && !video_format[0] ?
1387 (audio_muxer[0] ? audio_muxer : video_muxer) :
1388 (audio_format[0] ? audio_format : video_format));
1392 int FFMPEG::scan_option_line(char *cp, char *tag, char *val)
1394 while( *cp == ' ' || *cp == '\t' ) ++cp;
1396 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' && *cp != '\n' ) ++cp;
1398 if( !len || len > BCSTRLEN-1 ) return 1;
1399 while( bp < cp ) *tag++ = *bp++;
1401 while( *cp == ' ' || *cp == '\t' ) ++cp;
1402 if( *cp == '=' ) ++cp;
1403 while( *cp == ' ' || *cp == '\t' ) ++cp;
1405 while( *cp && *cp != '\n' ) ++cp;
1407 if( len > BCTEXTLEN-1 ) return 1;
1408 while( bp < cp ) *val++ = *bp++;
1413 int FFMPEG::load_defaults(const char *path, const char *type,
1414 char *codec, char *codec_options, int len)
1416 char default_file[BCTEXTLEN];
1417 set_option_path(default_file, "%s/%s.dfl", path, type);
1418 FILE *fp = fopen(default_file,"r");
1420 fgets(codec, BCSTRLEN, fp);
1422 while( *cp && *cp!='\n' ) ++cp;
1424 while( len > 0 && fgets(codec_options, len, fp) ) {
1425 int n = strlen(codec_options);
1426 codec_options += n; len -= n;
1429 set_option_path(default_file, "%s/%s", path, codec);
1430 return load_options(default_file, codec_options, len);
1433 void FFMPEG::set_asset_format(Asset *asset, const char *text)
1435 if( asset->format != FILE_FFMPEG ) return;
1436 if( text != asset->fformat )
1437 strcpy(asset->fformat, text);
1438 if( !asset->ff_audio_options[0] ) {
1439 asset->audio_data = !load_defaults("audio", text, asset->acodec,
1440 asset->ff_audio_options, sizeof(asset->ff_audio_options));
1442 if( !asset->ff_video_options[0] ) {
1443 asset->video_data = !load_defaults("video", text, asset->vcodec,
1444 asset->ff_video_options, sizeof(asset->ff_video_options));
1448 int FFMPEG::get_encoder(const char *options,
1449 char *format, char *codec, char *bsfilter)
1451 FILE *fp = fopen(options,"r");
1453 eprintf(_("options open failed %s\n"),options);
1456 if( get_encoder(fp, format, codec, bsfilter) )
1457 eprintf(_("format/codec not found %s\n"), options);
1462 int FFMPEG::get_encoder(FILE *fp,
1463 char *format, char *codec, char *bsfilter)
1465 format[0] = codec[0] = bsfilter[0] = 0;
1466 char line[BCTEXTLEN];
1467 if( !fgets(line, sizeof(line), fp) ) return 1;
1468 line[sizeof(line)-1] = 0;
1469 if( scan_option_line(line, format, codec) ) return 1;
1471 while( *cp && *cp != '|' ) ++cp;
1472 if( !*cp ) return 0;
1474 do { *bp-- = 0; } while( bp>=codec && (*bp==' ' || *bp == '\t' ) );
1475 while( *++cp && (*cp==' ' || *cp == '\t') );
1477 for( int i=BCTEXTLEN; --i>0 && *cp; ) *bp++ = *cp++;
1482 int FFMPEG::read_options(const char *options, AVDictionary *&opts, int skip)
1484 FILE *fp = fopen(options,"r");
1487 while( !ret && --skip >= 0 ) {
1489 while( ch >= 0 && ch != '\n' ) ch = getc(fp);
1490 if( ch < 0 ) ret = 1;
1493 ret = read_options(fp, options, opts);
1498 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
1500 FILE *fp = fmemopen((void *)options,strlen(options),"r");
1502 int ret = read_options(fp, options, opts);
1504 AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
1505 if( tag ) st->id = strtol(tag->value,0,0);
1509 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
1511 int ret = 0, no = 0;
1512 char line[BCTEXTLEN];
1513 while( !ret && fgets(line, sizeof(line), fp) ) {
1514 line[sizeof(line)-1] = 0;
1515 if( line[0] == '#' ) continue;
1516 if( line[0] == '\n' ) continue;
1517 char key[BCSTRLEN], val[BCTEXTLEN];
1518 if( scan_option_line(line, key, val) ) {
1519 eprintf(_("err reading %s: line %d\n"), options, no);
1523 if( !strcmp(key, "duration") )
1524 opt_duration = strtod(val, 0);
1525 else if( !strcmp(key, "video_filter") )
1526 opt_video_filter = cstrdup(val);
1527 else if( !strcmp(key, "audio_filter") )
1528 opt_audio_filter = cstrdup(val);
1529 else if( !strcmp(key, "loglevel") )
1532 av_dict_set(&opts, key, val, 0);
1538 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
1540 char option_path[BCTEXTLEN];
1541 set_option_path(option_path, "%s", options);
1542 return read_options(option_path, opts);
1545 int FFMPEG::load_options(const char *path, char *bfr, int len)
1548 FILE *fp = fopen(path, "r");
1550 fgets(bfr, len, fp); // skip hdr
1551 len = fread(bfr, 1, len-1, fp);
1552 if( len < 0 ) len = 0;
1558 void FFMPEG::set_loglevel(const char *ap)
1560 if( !ap || !*ap ) return;
1565 { "quiet" , AV_LOG_QUIET },
1566 { "panic" , AV_LOG_PANIC },
1567 { "fatal" , AV_LOG_FATAL },
1568 { "error" , AV_LOG_ERROR },
1569 { "warning", AV_LOG_WARNING },
1570 { "info" , AV_LOG_INFO },
1571 { "verbose", AV_LOG_VERBOSE },
1572 { "debug" , AV_LOG_DEBUG },
1574 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
1575 if( !strcmp(log_levels[i].name, ap) ) {
1576 av_log_set_level(log_levels[i].level);
1580 av_log_set_level(atoi(ap));
1583 double FFMPEG::to_secs(int64_t time, AVRational time_base)
1585 double base_time = time == AV_NOPTS_VALUE ? 0 :
1586 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
1587 return base_time / AV_TIME_BASE;
1590 int FFMPEG::info(char *text, int len)
1592 if( len <= 0 ) return 0;
1594 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
1596 report("format: %s\n",fmt_ctx->iformat->name);
1597 if( ffvideo.size() > 0 )
1598 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
1599 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
1600 FFVideoStream *vid = ffvideo[vidx];
1601 AVStream *st = vid->st;
1602 AVCodecID codec_id = st->codecpar->codec_id;
1603 report(_("vid%d (%d), id 0x%06x:\n"), vid->idx, vid->fidx, codec_id);
1604 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
1605 report(" video%d %s", vidx+1, desc ? desc->name : " (unkn)");
1606 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
1607 AVPixelFormat pix_fmt = (AVPixelFormat)st->codecpar->format;
1608 const char *pfn = av_get_pix_fmt_name(pix_fmt);
1609 report(" pix %s\n", pfn ? pfn : "(unkn)");
1610 double secs = to_secs(st->duration, st->time_base);
1611 int64_t length = secs * vid->frame_rate + 0.5;
1612 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
1613 int64_t nudge = ofs * vid->frame_rate;
1614 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1615 report(" %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
1616 int hrs = secs/3600; secs -= hrs*3600;
1617 int mins = secs/60; secs -= mins*60;
1618 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1620 if( ffaudio.size() > 0 )
1621 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
1622 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
1623 FFAudioStream *aud = ffaudio[aidx];
1624 AVStream *st = aud->st;
1625 AVCodecID codec_id = st->codecpar->codec_id;
1626 report(_("aud%d (%d), id 0x%06x:\n"), aud->idx, aud->fidx, codec_id);
1627 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
1628 int nch = aud->channels, ch0 = aud->channel0+1;
1629 report(" audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
1630 AVSampleFormat sample_fmt = (AVSampleFormat)st->codecpar->format;
1631 const char *fmt = av_get_sample_fmt_name(sample_fmt);
1632 report(" %s %d", fmt, aud->sample_rate);
1633 int sample_bits = av_get_bits_per_sample(codec_id);
1634 report(" %dbits\n", sample_bits);
1635 double secs = to_secs(st->duration, st->time_base);
1636 int64_t length = secs * aud->sample_rate + 0.5;
1637 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
1638 int64_t nudge = ofs * aud->sample_rate;
1639 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1640 report(" %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
1641 int hrs = secs/3600; secs -= hrs*3600;
1642 int mins = secs/60; secs -= mins*60;
1643 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1645 if( fmt_ctx->nb_programs > 0 )
1646 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
1647 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
1648 report("program %d", i+1);
1649 AVProgram *pgrm = fmt_ctx->programs[i];
1650 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1651 int idx = pgrm->stream_index[j];
1652 int vidx = ffvideo.size();
1653 while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
1655 report(", vid%d", vidx);
1658 int aidx = ffaudio.size();
1659 while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
1661 report(", aud%d", aidx);
1664 report(", (%d)", pgrm->stream_index[j]);
1669 AVDictionaryEntry *tag = 0;
1670 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
1671 report("%s=%s\n", tag->key, tag->value);
1680 int FFMPEG::init_decoder(const char *filename)
1682 ff_lock("FFMPEG::init_decoder");
1684 char file_opts[BCTEXTLEN];
1685 char *bp = strrchr(strcpy(file_opts, filename), '/');
1686 char *sp = strrchr(!bp ? file_opts : bp, '.');
1689 strcpy(sp, ".opts");
1690 fp = fopen(file_opts, "r");
1693 read_options(fp, file_opts, opts);
1697 load_options("decode.opts", opts);
1698 AVDictionary *fopts = 0;
1699 av_dict_copy(&fopts, opts, 0);
1700 int ret = avformat_open_input(&fmt_ctx, filename, NULL, &fopts);
1701 av_dict_free(&fopts);
1703 ret = avformat_find_stream_info(fmt_ctx, NULL);
1708 return !ret ? 0 : 1;
1711 int FFMPEG::open_decoder()
1714 if( stat(fmt_ctx->filename, &st) < 0 ) {
1715 eprintf(_("can't stat file: %s\n"), fmt_ctx->filename);
1719 int64_t file_bits = 8 * st.st_size;
1720 if( !fmt_ctx->bit_rate && opt_duration > 0 )
1721 fmt_ctx->bit_rate = file_bits / opt_duration;
1724 if( fmt_ctx->bit_rate > 0 ) {
1725 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1726 AVStream *st = fmt_ctx->streams[i];
1727 if( st->duration != AV_NOPTS_VALUE ) continue;
1728 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
1729 st->duration = av_rescale(file_bits, st->time_base.den,
1730 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
1735 printf("FFMPEG::open_decoder: some stream times estimated\n");
1737 ff_lock("FFMPEG::open_decoder");
1738 int ret = 0, bad_time = 0;
1739 for( int i=0; !ret && i<(int)fmt_ctx->nb_streams; ++i ) {
1740 AVStream *st = fmt_ctx->streams[i];
1741 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
1742 AVCodecParameters *avpar = st->codecpar;
1743 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avpar->codec_id);
1744 if( !codec_desc ) continue;
1745 switch( avpar->codec_type ) {
1746 case AVMEDIA_TYPE_VIDEO: {
1747 if( avpar->width < 1 ) continue;
1748 if( avpar->height < 1 ) continue;
1749 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
1750 if( framerate.num < 1 ) continue;
1752 int vidx = ffvideo.size();
1753 FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
1754 vstrm_index.append(ffidx(vidx, 0));
1755 ffvideo.append(vid);
1756 vid->width = avpar->width;
1757 vid->height = avpar->height;
1758 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
1759 double secs = to_secs(st->duration, st->time_base);
1760 vid->length = secs * vid->frame_rate;
1761 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
1762 vid->nudge = st->start_time;
1764 if( opt_video_filter )
1765 ret = vid->create_filter(opt_video_filter, avpar);
1767 case AVMEDIA_TYPE_AUDIO: {
1768 if( avpar->channels < 1 ) continue;
1769 if( avpar->sample_rate < 1 ) continue;
1771 int aidx = ffaudio.size();
1772 FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
1773 ffaudio.append(aud);
1774 aud->channel0 = astrm_index.size();
1775 aud->channels = avpar->channels;
1776 for( int ch=0; ch<aud->channels; ++ch )
1777 astrm_index.append(ffidx(aidx, ch));
1778 aud->sample_rate = avpar->sample_rate;
1779 double secs = to_secs(st->duration, st->time_base);
1780 aud->length = secs * aud->sample_rate;
1781 aud->init_swr(aud->channels, avpar->format, aud->sample_rate);
1782 aud->nudge = st->start_time;
1784 if( opt_audio_filter )
1785 ret = aud->create_filter(opt_audio_filter, avpar);
1791 printf("FFMPEG::open_decoder: some stream have bad times\n");
1793 return ret < 0 ? -1 : 0;
1797 int FFMPEG::init_encoder(const char *filename)
1799 int fd = ::open(filename,O_WRONLY);
1800 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
1802 eprintf(_("bad file path: %s\n"), filename);
1806 int ret = get_file_format();
1808 eprintf(_("bad file format: %s\n"), filename);
1812 eprintf(_("mismatch audio/video file format: %s\n"), filename);
1815 ff_lock("FFMPEG::init_encoder");
1817 char format[BCSTRLEN];
1818 if( get_format(format, "format", file_format) )
1819 strcpy(format, file_format);
1820 avformat_alloc_output_context2(&fmt_ctx, 0, format, filename);
1822 eprintf(_("failed: %s\n"), filename);
1827 load_options("encode.opts", opts);
1833 int FFMPEG::open_encoder(const char *type, const char *spec)
1836 Asset *asset = file_base->asset;
1837 char *filename = asset->path;
1838 AVDictionary *sopts = 0;
1839 av_dict_copy(&sopts, opts, 0);
1840 char option_path[BCTEXTLEN];
1841 set_option_path(option_path, "%s/%s.opts", type, type);
1842 read_options(option_path, sopts);
1843 get_option_path(option_path, type, spec);
1844 char format_name[BCSTRLEN], codec_name[BCTEXTLEN], bsfilter[BCTEXTLEN];
1845 if( get_encoder(option_path, format_name, codec_name, bsfilter) ) {
1846 eprintf(_("get_encoder failed %s:%s\n"), option_path, filename);
1850 if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
1851 else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
1852 else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
1855 ff_lock("FFMPEG::open_encoder");
1858 AVCodecContext *ctx = 0;
1860 const AVCodecDescriptor *codec_desc = 0;
1861 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
1863 eprintf(_("cant find codec %s:%s\n"), codec_name, filename);
1867 codec_desc = avcodec_descriptor_get(codec->id);
1869 eprintf(_("unknown codec %s:%s\n"), codec_name, filename);
1874 st = avformat_new_stream(fmt_ctx, 0);
1876 eprintf(_("cant create stream %s:%s\n"), codec_name, filename);
1881 switch( codec_desc->type ) {
1882 case AVMEDIA_TYPE_AUDIO: {
1884 eprintf(_("duplicate audio %s:%s\n"), codec_name, filename);
1888 if( scan_options(asset->ff_audio_options, sopts, st) ) {
1889 eprintf(_("bad audio options %s:%s\n"), codec_name, filename);
1894 ctx = avcodec_alloc_context3(codec);
1895 if( asset->ff_audio_bitrate > 0 ) {
1896 ctx->bit_rate = asset->ff_audio_bitrate;
1898 sprintf(arg, "%d", asset->ff_audio_bitrate);
1899 av_dict_set(&sopts, "b", arg, 0);
1901 int aidx = ffaudio.size();
1902 int fidx = aidx + ffvideo.size();
1903 FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
1904 aud->avctx = ctx; ffaudio.append(aud); fst = aud;
1905 aud->sample_rate = asset->sample_rate;
1906 ctx->channels = aud->channels = asset->channels;
1907 for( int ch=0; ch<aud->channels; ++ch )
1908 astrm_index.append(ffidx(aidx, ch));
1909 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
1910 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
1911 if( !ctx->sample_rate ) {
1912 eprintf(_("check_sample_rate failed %s\n"), filename);
1916 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
1917 ctx->sample_fmt = codec->sample_fmts[0];
1918 uint64_t layout = av_get_default_channel_layout(ctx->channels);
1919 aud->resample_context = swr_alloc_set_opts(NULL,
1920 layout, ctx->sample_fmt, aud->sample_rate,
1921 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
1923 swr_init(aud->resample_context);
1926 case AVMEDIA_TYPE_VIDEO: {
1928 eprintf(_("duplicate video %s:%s\n"), codec_name, filename);
1932 if( scan_options(asset->ff_video_options, sopts, st) ) {
1933 eprintf(_("bad video options %s:%s\n"), codec_name, filename);
1938 ctx = avcodec_alloc_context3(codec);
1939 if( asset->ff_video_bitrate > 0 ) {
1940 ctx->bit_rate = asset->ff_video_bitrate;
1942 sprintf(arg, "%d", asset->ff_video_bitrate);
1943 av_dict_set(&sopts, "b", arg, 0);
1945 else if( asset->ff_video_quality >= 0 ) {
1946 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
1947 ctx->qmin = ctx->qmax = asset->ff_video_quality;
1948 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
1949 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
1950 ctx->flags |= CODEC_FLAG_QSCALE;
1952 av_dict_set(&sopts, "flags", "+qscale", 0);
1953 sprintf(arg, "%d", asset->ff_video_quality);
1954 av_dict_set(&sopts, "qscale", arg, 0);
1955 sprintf(arg, "%d", ctx->global_quality);
1956 av_dict_set(&sopts, "global_quality", arg, 0);
1958 int vidx = ffvideo.size();
1959 int fidx = vidx + ffaudio.size();
1960 FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
1961 vstrm_index.append(ffidx(vidx, 0));
1962 vid->avctx = ctx; ffvideo.append(vid); fst = vid;
1963 vid->width = asset->width;
1964 ctx->width = (vid->width+3) & ~3;
1965 vid->height = asset->height;
1966 ctx->height = (vid->height+3) & ~3;
1967 vid->frame_rate = asset->frame_rate;
1968 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
1969 ctx->pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
1970 AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
1971 if( !frame_rate.num || !frame_rate.den ) {
1972 eprintf(_("check_frame_rate failed %s\n"), filename);
1976 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
1977 st->time_base = ctx->time_base;
1979 vid->interlaced = asset->interlace_mode == ILACE_MODE_TOP_FIRST ||
1980 asset->interlace_mode == ILACE_MODE_BOTTOM_FIRST ? 1 : 0;
1981 vid->top_field_first = asset->interlace_mode == ILACE_MODE_TOP_FIRST ? 1 : 0;
1984 eprintf(_("not audio/video, %s:%s\n"), codec_name, filename);
1989 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
1990 ctx->flags |= CODEC_FLAG_GLOBAL_HEADER;
1992 av_dict_set(&sopts, "cin_bitrate", 0, 0);
1993 av_dict_set(&sopts, "cin_quality", 0, 0);
1995 ret = avcodec_open2(ctx, codec, &sopts);
1997 ret = avcodec_parameters_from_context(st->codecpar, ctx);
1999 fprintf(stderr, "Could not copy the stream parameters\n");
2002 ff_err(ret,"FFMPEG::open_encoder");
2003 eprintf(_("open failed %s:%s\n"), codec_name, filename);
2009 if( !ret && fst && bsfilter[0] ) {
2010 ret = av_bsf_list_parse_str(bsfilter, &fst->bsfc);
2012 ff_err(ret,"FFMPEG::open_encoder");
2013 eprintf(_("bitstream filter failed %s:\n%s\n"), filename, bsfilter);
2024 av_dict_free(&sopts);
2028 int FFMPEG::close_encoder()
2031 if( encoding > 0 ) {
2032 av_write_trailer(fmt_ctx);
2033 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
2034 avio_closep(&fmt_ctx->pb);
2040 int FFMPEG::decode_activate()
2042 if( decoding < 0 ) {
2044 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
2045 ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
2046 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
2047 ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
2048 // set nudges for each program stream set
2049 const int64_t min_nudge = INT64_MIN+1;
2050 int npgrms = fmt_ctx->nb_programs;
2051 for( int i=0; i<npgrms; ++i ) {
2052 AVProgram *pgrm = fmt_ctx->programs[i];
2053 // first start time video stream
2054 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2055 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2056 int fidx = pgrm->stream_index[j];
2057 AVStream *st = fmt_ctx->streams[fidx];
2058 AVCodecParameters *avpar = st->codecpar;
2059 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2060 if( st->start_time == AV_NOPTS_VALUE ) continue;
2061 if( vstart_time < st->start_time )
2062 vstart_time = st->start_time;
2065 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2066 if( st->start_time == AV_NOPTS_VALUE ) continue;
2067 if( astart_time < st->start_time )
2068 astart_time = st->start_time;
2072 //since frame rate is much more grainy than sample rate, it is better to
2073 // align using video, so that total absolute error is minimized.
2074 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2075 astart_time > min_nudge ? astart_time : AV_NOPTS_VALUE;
2076 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2077 int fidx = pgrm->stream_index[j];
2078 AVStream *st = fmt_ctx->streams[fidx];
2079 AVCodecParameters *avpar = st->codecpar;
2080 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2081 for( int k=0; k<ffvideo.size(); ++k ) {
2082 if( ffvideo[k]->fidx != fidx ) continue;
2083 ffvideo[k]->nudge = nudge;
2087 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2088 for( int k=0; k<ffaudio.size(); ++k ) {
2089 if( ffaudio[k]->fidx != fidx ) continue;
2090 ffaudio[k]->nudge = nudge;
2096 // set nudges for any streams not yet set
2097 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2098 int nstreams = fmt_ctx->nb_streams;
2099 for( int i=0; i<nstreams; ++i ) {
2100 AVStream *st = fmt_ctx->streams[i];
2101 AVCodecParameters *avpar = st->codecpar;
2102 switch( avpar->codec_type ) {
2103 case AVMEDIA_TYPE_VIDEO: {
2104 if( st->start_time == AV_NOPTS_VALUE ) continue;
2105 int vidx = ffvideo.size();
2106 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
2107 if( vidx >= 0 && ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
2108 if( vstart_time < st->start_time )
2109 vstart_time = st->start_time;
2111 case AVMEDIA_TYPE_AUDIO: {
2112 if( st->start_time == AV_NOPTS_VALUE ) continue;
2113 int aidx = ffaudio.size();
2114 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
2115 if( aidx >= 0 && ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
2116 if( astart_time < st->start_time )
2117 astart_time = st->start_time;
2122 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2123 astart_time > min_nudge ? astart_time : 0;
2124 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
2125 if( ffvideo[vidx]->nudge == AV_NOPTS_VALUE )
2126 ffvideo[vidx]->nudge = nudge;
2128 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2129 if( ffaudio[aidx]->nudge == AV_NOPTS_VALUE )
2130 ffaudio[aidx]->nudge = nudge;
2137 int FFMPEG::encode_activate()
2140 if( encoding < 0 ) {
2142 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
2143 (ret=avio_open(&fmt_ctx->pb, fmt_ctx->filename, AVIO_FLAG_WRITE)) < 0 ) {
2144 ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
2150 AVProgram *prog = av_new_program(fmt_ctx, prog_id);
2151 for( int i=0; i< ffvideo.size(); ++i )
2152 av_program_add_stream_index(fmt_ctx, prog_id, ffvideo[i]->fidx);
2153 for( int i=0; i< ffaudio.size(); ++i )
2154 av_program_add_stream_index(fmt_ctx, prog_id, ffaudio[i]->fidx);
2155 int pi = fmt_ctx->nb_programs;
2156 while( --pi >= 0 && fmt_ctx->programs[pi]->id != prog_id );
2157 AVDictionary **meta = &prog->metadata;
2158 av_dict_set(meta, "service_provider", "cin5", 0);
2159 const char *path = fmt_ctx->filename, *bp = strrchr(path,'/');
2160 if( bp ) path = bp + 1;
2161 av_dict_set(meta, "title", path, 0);
2163 if( ffaudio.size() ) {
2164 const char *ep = getenv("CIN_AUDIO_LANG"), *lp = 0;
2165 if( !ep && (lp=getenv("LANG")) ) { // some are guesses
2166 static struct { const char lc[3], lng[4]; } lcode[] = {
2167 { "en", "eng" }, { "de", "ger" }, { "es", "spa" },
2168 { "eu", "bas" }, { "fr", "fre" }, { "el", "gre" },
2169 { "hi", "hin" }, { "it", "ita" }, { "ja", "jap" },
2170 { "ko", "kor" }, { "du", "dut" }, { "pl", "pol" },
2171 { "pt", "por" }, { "ru", "rus" }, { "sl", "slv" },
2172 { "uk", "ukr" }, { "vi", "vie" }, { "zh", "chi" },
2174 for( int i=sizeof(lcode)/sizeof(lcode[0]); --i>=0 && !ep; )
2175 if( !strncmp(lcode[i].lc,lp,2) ) ep = lcode[i].lng;
2177 if( !ep ) ep = "und";
2179 strncpy(lang,ep,3); lang[3] = 0;
2180 AVStream *st = ffaudio[0]->st;
2181 av_dict_set(&st->metadata,"language",lang,0);
2184 AVDictionary *fopts = 0;
2185 char option_path[BCTEXTLEN];
2186 set_option_path(option_path, "format/%s", file_format);
2187 read_options(option_path, fopts, 1);
2188 ret = avformat_write_header(fmt_ctx, &fopts);
2190 ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
2194 av_dict_free(&fopts);
2201 int FFMPEG::audio_seek(int stream, int64_t pos)
2203 int aidx = astrm_index[stream].st_idx;
2204 FFAudioStream *aud = ffaudio[aidx];
2205 aud->audio_seek(pos);
2209 int FFMPEG::video_seek(int stream, int64_t pos)
2211 int vidx = vstrm_index[stream].st_idx;
2212 FFVideoStream *vid = ffvideo[vidx];
2213 vid->video_seek(pos);
2218 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
2220 if( !has_audio || chn >= astrm_index.size() ) return -1;
2221 int aidx = astrm_index[chn].st_idx;
2222 FFAudioStream *aud = ffaudio[aidx];
2223 if( aud->load(pos, len) < len ) return -1;
2224 int ch = astrm_index[chn].st_ch;
2225 int ret = aud->read(samples,len,ch);
2229 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
2231 if( !has_video || layer >= vstrm_index.size() ) return -1;
2232 int vidx = vstrm_index[layer].st_idx;
2233 FFVideoStream *vid = ffvideo[vidx];
2234 return vid->load(vframe, pos);
2238 int FFMPEG::encode(int stream, double **samples, int len)
2240 FFAudioStream *aud = ffaudio[stream];
2241 return aud->encode(samples, len);
2245 int FFMPEG::encode(int stream, VFrame *frame)
2247 FFVideoStream *vid = ffvideo[stream];
2248 return vid->encode(frame);
2251 void FFMPEG::start_muxer()
2259 void FFMPEG::stop_muxer()
2268 void FFMPEG::flow_off()
2271 flow_lock->lock("FFMPEG::flow_off");
2275 void FFMPEG::flow_on()
2279 flow_lock->unlock();
2282 void FFMPEG::flow_ctl()
2285 flow_lock->lock("FFMPEG::flow_ctl");
2286 flow_lock->unlock();
2290 int FFMPEG::mux_audio(FFrame *frm)
2292 FFStream *fst = frm->fst;
2293 AVCodecContext *ctx = fst->avctx;
2294 AVFrame *frame = *frm;
2295 AVRational tick_rate = {1, ctx->sample_rate};
2296 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
2297 int ret = fst->encode_frame(frame);
2299 ff_err(ret, "FFMPEG::mux_audio");
2300 return ret >= 0 ? 0 : 1;
2303 int FFMPEG::mux_video(FFrame *frm)
2305 FFStream *fst = frm->fst;
2306 AVFrame *frame = *frm;
2307 frame->pts = frm->position;
2308 int ret = fst->encode_frame(frame);
2310 ff_err(ret, "FFMPEG::mux_video");
2311 return ret >= 0 ? 0 : 1;
2317 double atm = -1, vtm = -1;
2318 FFrame *afrm = 0, *vfrm = 0;
2320 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
2321 FFStream *fst = ffaudio[i];
2322 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
2323 FFrame *frm = fst->frms.first;
2324 if( !frm ) { if( !done ) return; continue; }
2325 double tm = to_secs(frm->position, fst->avctx->time_base);
2326 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
2328 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
2329 FFStream *fst = ffvideo[i];
2330 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
2331 FFrame *frm = fst->frms.first;
2332 if( !frm ) { if( !done ) return; continue; }
2333 double tm = to_secs(frm->position, fst->avctx->time_base);
2334 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
2336 if( !demand ) flow_off();
2337 if( !afrm && !vfrm ) break;
2338 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
2339 vfrm->position, vfrm->fst->avctx->time_base,
2340 afrm->position, afrm->fst->avctx->time_base);
2341 FFrame *frm = v <= 0 ? vfrm : afrm;
2342 if( frm == afrm ) mux_audio(frm);
2343 if( frm == vfrm ) mux_video(frm);
2352 mux_lock->lock("FFMPEG::run");
2355 for( int i=0; i<ffaudio.size(); ++i )
2356 ffaudio[i]->drain();
2357 for( int i=0; i<ffvideo.size(); ++i )
2358 ffvideo[i]->drain();
2360 for( int i=0; i<ffaudio.size(); ++i )
2361 ffaudio[i]->flush();
2362 for( int i=0; i<ffvideo.size(); ++i )
2363 ffvideo[i]->flush();
2367 int FFMPEG::ff_total_audio_channels()
2369 return astrm_index.size();
2372 int FFMPEG::ff_total_astreams()
2374 return ffaudio.size();
2377 int FFMPEG::ff_audio_channels(int stream)
2379 return ffaudio[stream]->channels;
2382 int FFMPEG::ff_sample_rate(int stream)
2384 return ffaudio[stream]->sample_rate;
2387 const char* FFMPEG::ff_audio_format(int stream)
2389 AVStream *st = ffaudio[stream]->st;
2390 AVCodecID id = st->codecpar->codec_id;
2391 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2392 return desc ? desc->name : _("Unknown");
2395 int FFMPEG::ff_audio_pid(int stream)
2397 return ffaudio[stream]->st->id;
2400 int64_t FFMPEG::ff_audio_samples(int stream)
2402 return ffaudio[stream]->length;
2405 // find audio astream/channels with this program,
2406 // or all program audio channels (astream=-1)
2407 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
2411 int vidx = ffvideo[vstream]->fidx;
2412 // find first program with this video stream
2413 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
2414 AVProgram *pgrm = fmt_ctx->programs[i];
2415 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
2416 int st_idx = pgrm->stream_index[j];
2417 AVStream *st = fmt_ctx->streams[st_idx];
2418 if( st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
2419 if( st_idx == vidx ) pidx = i;
2422 if( pidx < 0 ) return -1;
2424 int64_t channels = 0;
2425 AVProgram *pgrm = fmt_ctx->programs[pidx];
2426 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2427 int aidx = pgrm->stream_index[j];
2428 AVStream *st = fmt_ctx->streams[aidx];
2429 if( st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
2430 if( astream > 0 ) { --astream; continue; }
2432 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
2433 if( ffaudio[i]->fidx == aidx ) astrm = i;
2435 if( ret < 0 ) ret = astrm;
2436 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
2437 channels |= mask << ffaudio[astrm]->channel0;
2439 if( !astream ) break;
2441 channel_mask = channels;
2446 int FFMPEG::ff_total_video_layers()
2448 return vstrm_index.size();
2451 int FFMPEG::ff_total_vstreams()
2453 return ffvideo.size();
2456 int FFMPEG::ff_video_width(int stream)
2458 return ffvideo[stream]->width;
2461 int FFMPEG::ff_video_height(int stream)
2463 return ffvideo[stream]->height;
2466 int FFMPEG::ff_set_video_width(int stream, int width)
2468 int w = ffvideo[stream]->width;
2469 ffvideo[stream]->width = width;
2473 int FFMPEG::ff_set_video_height(int stream, int height)
2475 int h = ffvideo[stream]->height;
2476 ffvideo[stream]->height = height;
2480 int FFMPEG::ff_coded_width(int stream)
2482 return ffvideo[stream]->avctx->coded_width;
2485 int FFMPEG::ff_coded_height(int stream)
2487 return ffvideo[stream]->avctx->coded_height;
2490 float FFMPEG::ff_aspect_ratio(int stream)
2492 return ffvideo[stream]->aspect_ratio;
2495 const char* FFMPEG::ff_video_format(int stream)
2497 AVStream *st = ffvideo[stream]->st;
2498 AVCodecID id = st->codecpar->codec_id;
2499 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2500 return desc ? desc->name : _("Unknown");
2503 double FFMPEG::ff_frame_rate(int stream)
2505 return ffvideo[stream]->frame_rate;
2508 int64_t FFMPEG::ff_video_frames(int stream)
2510 return ffvideo[stream]->length;
2513 int FFMPEG::ff_video_pid(int stream)
2515 return ffvideo[stream]->st->id;
2519 int FFMPEG::ff_cpus()
2521 return file_base->file->cpus;
2524 int FFVideoStream::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_VIDEO ) {
2534 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
2537 filter_graph = avfilter_graph_alloc();
2538 AVFilter *buffersrc = avfilter_get_by_name("buffer");
2539 AVFilter *buffersink = avfilter_get_by_name("buffersink");
2541 int ret = 0; char args[BCTEXTLEN];
2542 AVPixelFormat pix_fmt = (AVPixelFormat)avpar->format;
2543 snprintf(args, sizeof(args),
2544 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
2545 avpar->width, avpar->height, (int)pix_fmt,
2546 st->time_base.num, st->time_base.den,
2547 avpar->sample_aspect_ratio.num, avpar->sample_aspect_ratio.den);
2549 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2550 args, NULL, filter_graph);
2552 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2553 NULL, NULL, filter_graph);
2555 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
2556 (uint8_t*)&pix_fmt, sizeof(pix_fmt),
2557 AV_OPT_SEARCH_CHILDREN);
2559 ff_err(ret, "FFVideoStream::create_filter");
2561 ret = FFStream::create_filter(filter_spec);
2562 return ret >= 0 ? 0 : -1;
2565 int FFAudioStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
2567 avfilter_register_all();
2568 const char *sp = filter_spec;
2569 char filter_name[BCSTRLEN], *np = filter_name;
2570 int i = sizeof(filter_name);
2571 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
2573 AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
2574 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_AUDIO ) {
2575 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
2578 filter_graph = avfilter_graph_alloc();
2579 AVFilter *buffersrc = avfilter_get_by_name("abuffer");
2580 AVFilter *buffersink = avfilter_get_by_name("abuffersink");
2581 int ret = 0; char args[BCTEXTLEN];
2582 AVSampleFormat sample_fmt = (AVSampleFormat)avpar->format;
2583 snprintf(args, sizeof(args),
2584 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
2585 st->time_base.num, st->time_base.den, avpar->sample_rate,
2586 av_get_sample_fmt_name(sample_fmt), avpar->channel_layout);
2588 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2589 args, NULL, filter_graph);
2591 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2592 NULL, NULL, filter_graph);
2594 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
2595 (uint8_t*)&sample_fmt, sizeof(sample_fmt),
2596 AV_OPT_SEARCH_CHILDREN);
2598 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
2599 (uint8_t*)&avpar->channel_layout,
2600 sizeof(avpar->channel_layout), AV_OPT_SEARCH_CHILDREN);
2602 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
2603 (uint8_t*)&sample_rate, sizeof(sample_rate),
2604 AV_OPT_SEARCH_CHILDREN);
2606 ff_err(ret, "FFAudioStream::create_filter");
2608 ret = FFStream::create_filter(filter_spec);
2609 return ret >= 0 ? 0 : -1;
2612 int FFStream::create_filter(const char *filter_spec)
2614 /* Endpoints for the filter graph. */
2615 AVFilterInOut *outputs = avfilter_inout_alloc();
2616 outputs->name = av_strdup("in");
2617 outputs->filter_ctx = buffersrc_ctx;
2618 outputs->pad_idx = 0;
2621 AVFilterInOut *inputs = avfilter_inout_alloc();
2622 inputs->name = av_strdup("out");
2623 inputs->filter_ctx = buffersink_ctx;
2624 inputs->pad_idx = 0;
2627 int ret = !outputs->name || !inputs->name ? -1 : 0;
2629 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
2630 &inputs, &outputs, NULL);
2632 ret = avfilter_graph_config(filter_graph, NULL);
2635 ff_err(ret, "FFStream::create_filter");
2636 avfilter_graph_free(&filter_graph);
2639 avfilter_inout_free(&inputs);
2640 avfilter_inout_free(&outputs);
2644 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
2647 av_init_packet(&pkt);
2648 AVFrame *frame = av_frame_alloc();
2650 fprintf(stderr,"FFMPEG::scan: ");
2651 fprintf(stderr,_("av_frame_alloc failed\n"));
2655 index_state->add_video_markers(ffvideo.size());
2656 index_state->add_audio_markers(ffaudio.size());
2658 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2660 AVDictionary *copts = 0;
2661 av_dict_copy(&copts, opts, 0);
2662 AVStream *st = fmt_ctx->streams[i];
2663 AVCodecID codec_id = st->codecpar->codec_id;
2664 AVCodec *decoder = avcodec_find_decoder(codec_id);
2665 AVCodecContext *avctx = avcodec_alloc_context3(decoder);
2667 eprintf(_("cant allocate codec context\n"));
2668 ret = AVERROR(ENOMEM);
2671 avcodec_parameters_to_context(avctx, st->codecpar);
2672 ret = avcodec_open2(avctx, decoder, &copts);
2674 av_dict_free(&copts);
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 ffvideo[vidx]->avctx = avctx;
2684 case AVMEDIA_TYPE_AUDIO: {
2685 int aidx = ffaudio.size();
2686 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
2687 if( aidx < 0 ) break;
2688 ffaudio[aidx]->avctx = avctx;
2693 fprintf(stderr,"FFMPEG::scan: ");
2694 fprintf(stderr,_("codec open failed\n"));
2695 avcodec_free_context(&avctx);
2699 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2700 AVStream *st = fmt_ctx->streams[i];
2701 AVCodecParameters *avpar = st->codecpar;
2702 if( avpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
2703 int64_t tstmp = st->start_time;
2704 if( tstmp == AV_NOPTS_VALUE ) continue;
2705 int aidx = ffaudio.size();
2706 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
2707 if( aidx < 0 ) continue;
2708 FFAudioStream *aud = ffaudio[aidx];
2709 tstmp -= aud->nudge;
2710 double secs = to_secs(tstmp, st->time_base);
2711 aud->curr_pos = secs * aud->sample_rate + 0.5;
2715 for( int64_t count=0; !*canceled; ++count ) {
2716 av_packet_unref(&pkt);
2717 pkt.data = 0; pkt.size = 0;
2719 int ret = av_read_frame(fmt_ctx, &pkt);
2721 if( ret == AVERROR_EOF ) break;
2722 if( ++errs > 100 ) {
2723 ff_err(ret,_("over 100 read_frame errs\n"));
2728 if( !pkt.data ) continue;
2729 int i = pkt.stream_index;
2730 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
2731 AVStream *st = fmt_ctx->streams[i];
2732 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
2734 AVCodecParameters *avpar = st->codecpar;
2735 switch( avpar->codec_type ) {
2736 case AVMEDIA_TYPE_VIDEO: {
2737 int vidx = ffvideo.size();
2738 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
2739 if( vidx < 0 ) break;
2740 FFVideoStream *vid = ffvideo[vidx];
2741 if( !vid->avctx ) break;
2742 int64_t tstmp = pkt.dts;
2743 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.pts;
2744 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
2745 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
2746 double secs = to_secs(tstmp, st->time_base);
2747 int64_t frm = secs * vid->frame_rate + 0.5;
2748 if( frm < 0 ) frm = 0;
2749 index_state->put_video_mark(vidx, frm, pkt.pos);
2752 ret = avcodec_send_packet(vid->avctx, pkt);
2753 if( ret < 0 ) break;
2754 while( (ret=vid->decode_frame(frame)) > 0 ) {}
2757 case AVMEDIA_TYPE_AUDIO: {
2758 int aidx = ffaudio.size();
2759 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
2760 if( aidx < 0 ) break;
2761 FFAudioStream *aud = ffaudio[aidx];
2762 if( !aud->avctx ) break;
2763 int64_t tstmp = pkt.pts;
2764 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
2765 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
2766 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
2767 double secs = to_secs(tstmp, st->time_base);
2768 int64_t sample = secs * aud->sample_rate + 0.5;
2770 index_state->put_audio_mark(aidx, sample, pkt.pos);
2772 ret = avcodec_send_packet(aud->avctx, &pkt);
2773 if( ret < 0 ) break;
2774 int ch = aud->channel0, nch = aud->channels;
2775 int64_t pos = index_state->pos(ch);
2776 if( pos != aud->curr_pos ) {
2777 if( abs(pos-aud->curr_pos) > 1 )
2778 printf("audio%d pad %jd %jd (%jd)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
2779 index_state->pad_data(ch, nch, aud->curr_pos);
2781 while( (ret=aud->decode_frame(frame)) > 0 ) {
2782 //if( frame->channels != nch ) break;
2783 aud->init_swr(frame->channels, frame->format, frame->sample_rate);
2785 int len = aud->get_samples(samples,
2786 &frame->extended_data[0], frame->nb_samples);
2787 pos = aud->curr_pos;
2788 if( (aud->curr_pos += len) >= 0 ) {
2790 samples += -pos * nch;
2791 len = aud->curr_pos;
2793 for( int i=0; i<nch; ++i )
2794 index_state->put_data(ch+i,nch,samples+i,len);
2801 av_frame_free(&frame);
2805 void FFStream::load_markers(IndexMarks &marks, double rate)
2808 int64_t sz = marks.size();
2809 int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
2810 int nb_ent = st->nb_index_entries;
2811 // some formats already have an index
2813 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
2814 int64_t tstmp = ep->timestamp;
2815 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
2816 double secs = ffmpeg->to_secs(tstmp, st->time_base);
2817 int64_t no = secs * rate;
2818 while( in < sz && marks[in].no <= no ) ++in;
2820 int64_t len = sz - in;
2821 int64_t count = max_entries - nb_ent;
2822 if( count > len ) count = len;
2823 for( int i=0; i<count; ++i ) {
2824 int k = in + i * len / count;
2825 int64_t no = marks[k].no, pos = marks[k].pos;
2826 double secs = (double)no / rate;
2827 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
2828 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
2829 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);