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 int ret = av_buffersrc_add_frame_flags(buffersrc_ctx,
399 frame, AV_BUFFERSRC_FLAG_KEEP_REF);
401 av_frame_unref(frame);
402 eprintf(_("av_buffersrc_add_frame_flags failed\n"));
407 int FFStream::read_filter(AVFrame *frame)
409 int ret = av_buffersink_get_frame(buffersink_ctx, frame);
411 if( ret == AVERROR(EAGAIN) ) return 0;
412 if( ret == AVERROR_EOF ) { st_eof(1); return -1; }
413 ff_err(ret, "FFStream::read_filter: av_buffersink_get_frame failed\n");
419 int FFStream::read_frame(AVFrame *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 int64_t tstmp = -INT64_MAX+1;
495 // default ffmpeg native seek
497 int64_t pos = no, pkt_pos = -1;
498 IndexMarks *index_markers = get_markers();
499 if( index_markers && index_markers->size() > 1 ) {
500 IndexMarks &marks = *index_markers;
501 int i = marks.find(pos);
502 int64_t n = i < 0 ? (i=0) : marks[i].no;
503 // if indexed seek point not too far away (<30 secs), use index
504 if( no-n < 30*rate ) {
507 if( i < marks.size() ) pkt_pos = marks[i].pos;
511 if( pos == curr_pos ) return 0;
512 if( pos > 0 && st->time_base.num > 0 ) {
513 double secs = pos / rate;
514 tstmp = secs * st->time_base.den / st->time_base.num;
515 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
517 avcodec_flush_buffers(avctx);
518 avformat_flush(fmt_ctx);
520 int64_t seek = tstmp;
521 int flags = AVSEEK_FLAG_ANY;
522 if( !(fmt_ctx->iformat->flags & AVFMT_NO_BYTE_SEEK) && pkt_pos >= 0 ) {
524 flags = AVSEEK_FLAG_BYTE;
526 int ret = avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, seek, INT64_MAX, flags);
528 int ret = av_seek_frame(fmt_ctx, st->index, tstmp, AVSEEK_FLAG_ANY);
530 int retry = MAX_RETRY;
532 need_packet = 0; flushed = 0;
533 seeked = 1; st_eof(0);
534 // read up to retry packets, limited to npkts in stream, and not pkt.pos past pkt_pos
535 while( --retry >= 0 ) {
536 if( read_packet() <= 0 ) { ret = -1; break; }
537 if( ipkt->stream_index != st->index ) continue;
538 if( !ipkt->data || !ipkt->size ) continue;
539 if( pkt_pos >= 0 && ipkt->pos >= pkt_pos ) break;
540 if( --npkts <= 0 ) break;
541 int64_t pkt_ts = ipkt->dts != AV_NOPTS_VALUE ? ipkt->dts : ipkt->pts;
542 if( pkt_ts == AV_NOPTS_VALUE ) continue;
543 if( pkt_ts >= tstmp ) break;
546 fprintf(stderr,"FFStream::seek: retry limit, pos=%jd tstmp=%jd\n",pos,tstmp);
550 ret = avcodec_send_packet(avctx, ipkt);
552 //some codecs need more than one pkt to resync
553 if( ret == AVERROR_INVALIDDATA ) ret = 0;
555 ff_err(ret, "FFStream::avcodec_send_packet failed\n");
560 printf("** seek fail %ld, %ld\n", pos, tstmp);
561 seeked = need_packet = 0;
565 //printf("seeked pos = %ld, %ld\n", pos, tstmp);
566 seek_pos = curr_pos = pos;
570 FFAudioStream::FFAudioStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
571 : FFStream(ffmpeg, strm, fidx)
574 channel0 = channels = 0;
578 resample_context = 0;
579 swr_ichs = swr_ifmt = swr_irate = 0;
588 bfr = new float[bsz];
593 FFAudioStream::~FFAudioStream()
595 if( resample_context ) swr_free(&resample_context);
600 void FFAudioStream::init_swr(int ichs, int ifmt, int irate)
602 if( resample_context ) {
603 if( swr_ichs == ichs && swr_ifmt == ifmt && swr_irate == irate )
605 swr_free(&resample_context);
607 swr_ichs = ichs; swr_ifmt = ifmt; swr_irate = irate;
608 if( ichs == channels && ifmt == AV_SAMPLE_FMT_FLT && irate == sample_rate )
610 uint64_t ilayout = av_get_default_channel_layout(ichs);
611 if( !ilayout ) ilayout = ((uint64_t)1<<ichs) - 1;
612 uint64_t olayout = av_get_default_channel_layout(channels);
613 if( !olayout ) olayout = ((uint64_t)1<<channels) - 1;
614 resample_context = swr_alloc_set_opts(NULL,
615 olayout, AV_SAMPLE_FMT_FLT, sample_rate,
616 ilayout, (AVSampleFormat)ifmt, irate,
618 if( resample_context )
619 swr_init(resample_context);
622 int FFAudioStream::get_samples(float *&samples, uint8_t **data, int len)
624 samples = *(float **)data;
625 if( resample_context ) {
626 if( len > aud_bfr_sz ) {
632 aud_bfr = new float[aud_bfr_sz*channels];
634 int ret = swr_convert(resample_context,
635 (uint8_t**)&aud_bfr, aud_bfr_sz, (const uint8_t**)data, len);
637 ff_err(ret, "FFAudioStream::get_samples: swr_convert failed\n");
646 int FFAudioStream::load_history(uint8_t **data, int len)
649 len = get_samples(samples, data, len);
651 // biggest user bfr since seek + frame
652 realloc(mbsz + len + 1, channels);
658 int FFAudioStream::decode_frame(AVFrame *frame)
660 int first_frame = seeked; seeked = 0;
661 int ret = avcodec_receive_frame(avctx, frame);
663 if( first_frame || ret == AVERROR(EAGAIN) ) return 0;
664 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
665 ff_err(ret, "FFAudioStream::decode_frame: Could not read audio frame\n");
668 int64_t pkt_ts = av_frame_get_best_effort_timestamp(frame);
669 if( pkt_ts != AV_NOPTS_VALUE )
670 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * sample_rate + 0.5;
674 int FFAudioStream::encode_activate()
676 if( writing >= 0 ) return writing;
677 frame_sz = avctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE ?
678 10000 : avctx->frame_size;
679 return FFStream::encode_activate();
682 int64_t FFAudioStream::load_buffer(double ** const sp, int len)
684 reserve(len+1, st->codecpar->channels);
685 for( int ch=0; ch<nch; ++ch )
686 write(sp[ch], len, ch);
690 int FFAudioStream::in_history(int64_t pos)
692 if( pos > curr_pos ) return 0;
694 if( len > sz ) len = sz;
695 if( pos < curr_pos - len ) return 0;
700 int FFAudioStream::init_frame(AVFrame *frame)
702 frame->nb_samples = frame_sz;
703 frame->format = avctx->sample_fmt;
704 frame->channel_layout = avctx->channel_layout;
705 frame->sample_rate = avctx->sample_rate;
706 int ret = av_frame_get_buffer(frame, 0);
708 ff_err(ret, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
712 int FFAudioStream::load(int64_t pos, int len)
714 if( audio_seek(pos) < 0 ) return -1;
715 if( !frame && !(frame=av_frame_alloc()) ) {
716 fprintf(stderr, "FFAudioStream::load: av_frame_alloc failed\n");
719 if( mbsz < len ) mbsz = len;
720 int64_t end_pos = pos + len;
722 for( int i=0; ret>=0 && !flushed && curr_pos<end_pos && i<MAX_RETRY; ++i ) {
723 ret = read_frame(frame);
725 init_swr(frame->channels, frame->format, frame->sample_rate);
726 load_history(&frame->extended_data[0], frame->nb_samples);
727 curr_pos += frame->nb_samples;
730 if( end_pos > curr_pos ) {
731 zero(end_pos - curr_pos);
734 len = curr_pos - pos;
739 int FFAudioStream::audio_seek(int64_t pos)
741 if( decode_activate() <= 0 ) return -1;
742 if( !st->codecpar ) return -1;
743 if( in_history(pos) ) return 0;
744 if( pos == curr_pos ) return 0;
745 reset_history(); mbsz = 0;
746 // guarentee preload > 1sec samples
747 if( seek(pos-sample_rate, sample_rate) < 0 ) return -1;
751 int FFAudioStream::encode(double **samples, int len)
753 if( encode_activate() <= 0 ) return -1;
756 int64_t count = samples ? load_buffer(samples, len) : used();
757 int frame_sz1 = samples ? frame_sz-1 : 0;
760 while( ret >= 0 && count > frame_sz1 ) {
761 frm = new FFrame(this);
762 if( (ret=frm->initted()) < 0 ) break;
763 AVFrame *frame = *frm;
764 len = count >= frame_sz ? frame_sz : count;
765 float *bfrp = get_outp(len);
766 ret = swr_convert(resample_context,
767 (uint8_t **)frame->extended_data, len,
768 (const uint8_t **)&bfrp, len);
770 ff_err(ret, "FFAudioStream::encode: swr_convert failed\n");
773 frame->nb_samples = len;
774 frm->queue(curr_pos);
781 return ret >= 0 ? 0 : 1;
784 int FFAudioStream::drain()
789 int FFAudioStream::encode_frame(AVFrame *frame)
791 return FFStream::encode_frame(frame);
794 void FFAudioStream::load_markers()
796 IndexState *index_state = ffmpeg->file_base->asset->index_state;
797 if( !index_state || idx >= index_state->audio_markers.size() ) return;
798 if( index_state->marker_status == MARKERS_NOTTESTED ) return;
799 FFStream::load_markers(*index_state->audio_markers[idx], sample_rate);
802 IndexMarks *FFAudioStream::get_markers()
804 IndexState *index_state = ffmpeg->file_base->asset->index_state;
805 if( !index_state || idx >= index_state->audio_markers.size() ) return 0;
806 return index_state->audio_markers[idx];
809 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
810 : FFStream(ffmpeg, strm, fidx)
821 FFVideoStream::~FFVideoStream()
825 int FFVideoStream::decode_frame(AVFrame *frame)
827 int first_frame = seeked; seeked = 0;
828 int ret = avcodec_receive_frame(avctx, frame);
830 if( first_frame || ret == AVERROR(EAGAIN) ) return 0;
831 if( ret == AVERROR(EAGAIN) ) return 0;
832 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
833 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame\n");
836 int64_t pkt_ts = av_frame_get_best_effort_timestamp(frame);
837 if( pkt_ts != AV_NOPTS_VALUE )
838 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * frame_rate + 0.5;
842 int FFVideoStream::load(VFrame *vframe, int64_t pos)
844 int ret = video_seek(pos);
845 if( ret < 0 ) return -1;
846 if( !frame && !(frame=av_frame_alloc()) ) {
847 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
850 for( int i=0; ret>=0 && !flushed && curr_pos<=pos && i<MAX_RETRY; ++i ) {
851 ret = read_frame(frame);
852 if( ret > 0 ) ++curr_pos;
854 if( frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0 )
857 ret = convert_cmodel(vframe, frame);
859 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
863 int FFVideoStream::video_seek(int64_t pos)
865 if( decode_activate() <= 0 ) return -1;
866 if( !st->codecpar ) return -1;
867 if( pos == curr_pos-1 && !seeked ) return 0;
868 // if close enough, just read up to current
869 int gop = avctx->gop_size;
870 if( gop < 4 ) gop = 4;
871 if( gop > 64 ) gop = 64;
872 int read_limit = curr_pos + 3*gop;
873 if( pos >= curr_pos && pos <= read_limit ) return 0;
874 // guarentee preload more than 2*gop frames
875 if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
879 int FFVideoStream::init_frame(AVFrame *picture)
881 picture->format = avctx->pix_fmt;
882 picture->width = avctx->width;
883 picture->height = avctx->height;
884 int ret = av_frame_get_buffer(picture, 32);
888 int FFVideoStream::encode(VFrame *vframe)
890 if( encode_activate() <= 0 ) return -1;
892 FFrame *picture = new FFrame(this);
893 int ret = picture->initted();
895 AVFrame *frame = *picture;
896 frame->pts = curr_pos;
897 ret = convert_pixfmt(vframe, frame);
900 picture->queue(curr_pos);
904 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
907 return ret >= 0 ? 0 : 1;
910 int FFVideoStream::drain()
915 int FFVideoStream::encode_frame(AVFrame *frame)
918 frame->interlaced_frame = interlaced;
919 frame->top_field_first = top_field_first;
921 return FFStream::encode_frame(frame);
924 AVPixelFormat FFVideoConvert::color_model_to_pix_fmt(int color_model)
926 switch( color_model ) {
927 case BC_YUV422: return AV_PIX_FMT_YUYV422;
928 case BC_RGB888: return AV_PIX_FMT_RGB24;
929 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
930 case BC_BGR8888: return AV_PIX_FMT_BGR0;
931 case BC_BGR888: return AV_PIX_FMT_BGR24;
932 case BC_ARGB8888: return AV_PIX_FMT_ARGB;
933 case BC_ABGR8888: return AV_PIX_FMT_ABGR;
934 case BC_RGB8: return AV_PIX_FMT_RGB8;
935 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
936 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
937 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
938 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
939 case BC_RGB565: return AV_PIX_FMT_RGB565;
940 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
941 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
942 case BC_AYUV16161616: return AV_PIX_FMT_AYUV64LE;
946 return AV_PIX_FMT_NB;
949 int FFVideoConvert::pix_fmt_to_color_model(AVPixelFormat pix_fmt)
952 case AV_PIX_FMT_YUYV422: return BC_YUV422;
953 case AV_PIX_FMT_RGB24: return BC_RGB888;
954 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
955 case AV_PIX_FMT_BGR0: return BC_BGR8888;
956 case AV_PIX_FMT_BGR24: return BC_BGR888;
957 case AV_PIX_FMT_ARGB: return BC_ARGB8888;
958 case AV_PIX_FMT_ABGR: return BC_ABGR8888;
959 case AV_PIX_FMT_RGB8: return BC_RGB8;
960 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
961 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
962 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
963 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
964 case AV_PIX_FMT_RGB565: return BC_RGB565;
965 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
966 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
967 case AV_PIX_FMT_AYUV64LE: return BC_AYUV16161616;
974 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip)
976 AVFrame *ipic = av_frame_alloc();
977 int ret = convert_picture_vframe(frame, ip, ipic);
978 av_frame_free(&ipic);
982 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip, AVFrame *ipic)
984 int cmodel = frame->get_color_model();
985 AVPixelFormat ofmt = color_model_to_pix_fmt(cmodel);
986 if( ofmt == AV_PIX_FMT_NB ) return -1;
987 int size = av_image_fill_arrays(ipic->data, ipic->linesize,
988 frame->get_data(), ofmt, frame->get_w(), frame->get_h(), 1);
989 if( size < 0 ) return -1;
991 int bpp = BC_CModels::calculate_pixelsize(cmodel);
992 int ysz = bpp * frame->get_w(), usz = ysz;
1001 // override av_image_fill_arrays() for planar types
1002 ipic->data[0] = frame->get_y(); ipic->linesize[0] = ysz;
1003 ipic->data[1] = frame->get_u(); ipic->linesize[1] = usz;
1004 ipic->data[2] = frame->get_v(); ipic->linesize[2] = usz;
1007 ipic->data[0] = frame->get_data();
1008 ipic->linesize[0] = frame->get_bytes_per_line();
1012 AVPixelFormat pix_fmt = (AVPixelFormat)ip->format;
1013 convert_ctx = sws_getCachedContext(convert_ctx, ip->width, ip->height, pix_fmt,
1014 frame->get_w(), frame->get_h(), ofmt, SWS_POINT, NULL, NULL, NULL);
1015 if( !convert_ctx ) {
1016 fprintf(stderr, "FFVideoConvert::convert_picture_frame:"
1017 " sws_getCachedContext() failed\n");
1020 int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ip->height,
1021 ipic->data, ipic->linesize);
1023 ff_err(ret, "FFVideoConvert::convert_picture_frame: sws_scale() failed\n");
1029 int FFVideoConvert::convert_cmodel(VFrame *frame, AVFrame *ip)
1031 // try direct transfer
1032 if( !convert_picture_vframe(frame, ip) ) return 1;
1033 // use indirect transfer
1034 AVPixelFormat ifmt = (AVPixelFormat)ip->format;
1035 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
1037 for( int i = 0; i <desc->nb_components; ++i ) {
1038 int bits = desc->comp[i].depth;
1039 if( bits > max_bits ) max_bits = bits;
1041 int imodel = pix_fmt_to_color_model(ifmt);
1042 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1043 int cmodel = frame->get_color_model();
1044 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1045 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1046 imodel = cmodel_is_yuv ?
1047 (BC_CModels::has_alpha(cmodel) ?
1049 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1050 (BC_CModels::has_alpha(cmodel) ?
1051 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1052 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1054 VFrame vframe(ip->width, ip->height, imodel);
1055 if( convert_picture_vframe(&vframe, ip) ) return -1;
1056 frame->transfer_from(&vframe);
1060 int FFVideoConvert::transfer_cmodel(VFrame *frame, AVFrame *ifp)
1062 int ret = convert_cmodel(frame, ifp);
1064 const AVDictionary *src = av_frame_get_metadata(ifp);
1065 AVDictionaryEntry *t = NULL;
1066 BC_Hash *hp = frame->get_params();
1068 while( (t=av_dict_get(src, "", t, AV_DICT_IGNORE_SUFFIX)) )
1069 hp->update(t->key, t->value);
1074 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op)
1076 AVFrame *opic = av_frame_alloc();
1077 int ret = convert_vframe_picture(frame, op, opic);
1078 av_frame_free(&opic);
1082 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op, AVFrame *opic)
1084 int cmodel = frame->get_color_model();
1085 AVPixelFormat ifmt = color_model_to_pix_fmt(cmodel);
1086 if( ifmt == AV_PIX_FMT_NB ) return -1;
1087 int size = av_image_fill_arrays(opic->data, opic->linesize,
1088 frame->get_data(), ifmt, frame->get_w(), frame->get_h(), 1);
1089 if( size < 0 ) return -1;
1091 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1092 int ysz = bpp * frame->get_w(), usz = ysz;
1101 // override av_image_fill_arrays() for planar types
1102 opic->data[0] = frame->get_y(); opic->linesize[0] = ysz;
1103 opic->data[1] = frame->get_u(); opic->linesize[1] = usz;
1104 opic->data[2] = frame->get_v(); opic->linesize[2] = usz;
1107 opic->data[0] = frame->get_data();
1108 opic->linesize[0] = frame->get_bytes_per_line();
1112 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1113 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(),
1114 ifmt, op->width, op->height, ofmt, SWS_POINT, NULL, NULL, NULL);
1115 if( !convert_ctx ) {
1116 fprintf(stderr, "FFVideoConvert::convert_frame_picture:"
1117 " sws_getCachedContext() failed\n");
1120 int ret = sws_scale(convert_ctx, opic->data, opic->linesize, 0, frame->get_h(),
1121 op->data, op->linesize);
1123 ff_err(ret, "FFVideoConvert::convert_frame_picture: sws_scale() failed\n");
1129 int FFVideoConvert::convert_pixfmt(VFrame *frame, AVFrame *op)
1131 // try direct transfer
1132 if( !convert_vframe_picture(frame, op) ) return 1;
1133 // use indirect transfer
1134 int cmodel = frame->get_color_model();
1135 int max_bits = BC_CModels::calculate_pixelsize(cmodel) * 8;
1136 max_bits /= BC_CModels::components(cmodel);
1137 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1138 int imodel = pix_fmt_to_color_model(ofmt);
1139 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1140 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1141 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1142 imodel = cmodel_is_yuv ?
1143 (BC_CModels::has_alpha(cmodel) ?
1145 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1146 (BC_CModels::has_alpha(cmodel) ?
1147 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1148 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1150 VFrame vframe(frame->get_w(), frame->get_h(), imodel);
1151 vframe.transfer_from(frame);
1152 if( !convert_vframe_picture(&vframe, op) ) return 1;
1156 int FFVideoConvert::transfer_pixfmt(VFrame *frame, AVFrame *ofp)
1158 int ret = convert_pixfmt(frame, ofp);
1160 BC_Hash *hp = frame->get_params();
1161 AVDictionary **dict = avpriv_frame_get_metadatap(ofp);
1162 //av_dict_free(dict);
1163 for( int i=0; i<hp->size(); ++i ) {
1164 char *key = hp->get_key(i), *val = hp->get_value(i);
1165 av_dict_set(dict, key, val, 0);
1171 void FFVideoStream::load_markers()
1173 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1174 if( !index_state || idx >= index_state->video_markers.size() ) return;
1175 FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
1178 IndexMarks *FFVideoStream::get_markers()
1180 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1181 if( !index_state || idx >= index_state->video_markers.size() ) return 0;
1182 return !index_state ? 0 : index_state->video_markers[idx];
1186 FFMPEG::FFMPEG(FileBase *file_base)
1189 this->file_base = file_base;
1190 memset(file_format,0,sizeof(file_format));
1191 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
1192 flow_lock = new Condition(1,"FFStream::flow_lock",0);
1195 decoding = encoding = 0;
1196 has_audio = has_video = 0;
1199 opt_video_filter = 0;
1200 opt_audio_filter = 0;
1201 char option_path[BCTEXTLEN];
1202 set_option_path(option_path, "%s", "ffmpeg.opts");
1203 read_options(option_path, opts);
1208 ff_lock("FFMPEG::~FFMPEG()");
1210 ffaudio.remove_all_objects();
1211 ffvideo.remove_all_objects();
1212 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1216 av_dict_free(&opts);
1217 delete [] opt_video_filter;
1218 delete [] opt_audio_filter;
1221 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1223 const int *p = codec->supported_samplerates;
1224 if( !p ) return sample_rate;
1226 if( *p == sample_rate ) return *p;
1232 static inline AVRational std_frame_rate(int i)
1234 static const int m1 = 1001*12, m2 = 1000*12;
1235 static const int freqs[] = {
1236 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1237 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
1239 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1240 return (AVRational) { freq, 1001*12 };
1243 AVRational FFMPEG::check_frame_rate(AVCodec *codec, double frame_rate)
1245 const AVRational *p = codec->supported_framerates;
1246 AVRational rate, best_rate = (AVRational) { 0, 0 };
1247 double max_err = 1.; int i = 0;
1248 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1249 double framerate = (double) rate.num / rate.den;
1250 double err = fabs(frame_rate/framerate - 1.);
1251 if( err >= max_err ) continue;
1255 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1258 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1261 double display_aspect = asset->width / (double)asset->height;
1262 double sample_aspect = display_aspect / asset->aspect_ratio;
1263 int width = 1000000, height = width * sample_aspect + 0.5;
1265 MWindow::create_aspect_ratio(w, h, width, height);
1266 return (AVRational){(int)w, (int)h};
1269 return (AVRational){1, 1};
1273 AVRational FFMPEG::to_time_base(int sample_rate)
1275 return (AVRational){1, sample_rate};
1278 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
1280 char *ep = path + BCTEXTLEN-1;
1281 strncpy(path, File::get_cindat_path(), ep-path);
1282 strncat(path, "/ffmpeg/", ep-path);
1283 path += strlen(path);
1286 path += vsnprintf(path, ep-path, fmt, ap);
1291 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
1296 set_option_path(path, "%s/%s", type, spec);
1299 int FFMPEG::get_format(char *format, const char *path, const char *spec)
1301 char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
1302 get_option_path(option_path, path, spec);
1303 FILE *fp = fopen(option_path,"r");
1306 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1308 line[sizeof(line)-1] = 0;
1309 ret = scan_option_line(line, format, codec);
1315 int FFMPEG::get_codec(char *codec, const char *path, const char *spec)
1317 char option_path[BCTEXTLEN], line[BCTEXTLEN], format[BCTEXTLEN];
1318 get_option_path(option_path, path, spec);
1319 FILE *fp = fopen(option_path,"r");
1322 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1325 line[sizeof(line)-1] = 0;
1326 ret = scan_option_line(line, format, codec);
1329 char *vp = codec, *ep = vp+BCTEXTLEN-1;
1330 while( vp < ep && *vp && *vp != '|' ) ++vp;
1331 if( *vp == '|' ) --vp;
1332 while( vp > codec && (*vp==' ' || *vp=='\t') ) *vp-- = 0;
1337 int FFMPEG::get_file_format()
1339 char audio_muxer[BCSTRLEN], video_muxer[BCSTRLEN];
1340 char audio_format[BCSTRLEN], video_format[BCSTRLEN];
1341 audio_muxer[0] = audio_format[0] = 0;
1342 video_muxer[0] = video_format[0] = 0;
1343 Asset *asset = file_base->asset;
1344 int ret = asset ? 0 : 1;
1345 if( !ret && asset->audio_data ) {
1346 if( !(ret=get_format(audio_format, "audio", asset->acodec)) ) {
1347 if( get_format(audio_muxer, "format", audio_format) ) {
1348 strcpy(audio_muxer, audio_format);
1349 audio_format[0] = 0;
1353 if( !ret && asset->video_data ) {
1354 if( !(ret=get_format(video_format, "video", asset->vcodec)) ) {
1355 if( get_format(video_muxer, "format", video_format) ) {
1356 strcpy(video_muxer, video_format);
1357 video_format[0] = 0;
1361 if( !ret && !audio_muxer[0] && !video_muxer[0] )
1363 if( !ret && audio_muxer[0] && video_muxer[0] &&
1364 strcmp(audio_muxer, video_muxer) ) ret = -1;
1365 if( !ret && audio_format[0] && video_format[0] &&
1366 strcmp(audio_format, video_format) ) ret = -1;
1368 strcpy(file_format, !audio_format[0] && !video_format[0] ?
1369 (audio_muxer[0] ? audio_muxer : video_muxer) :
1370 (audio_format[0] ? audio_format : video_format));
1374 int FFMPEG::scan_option_line(char *cp, char *tag, char *val)
1376 while( *cp == ' ' || *cp == '\t' ) ++cp;
1378 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' && *cp != '\n' ) ++cp;
1380 if( !len || len > BCSTRLEN-1 ) return 1;
1381 while( bp < cp ) *tag++ = *bp++;
1383 while( *cp == ' ' || *cp == '\t' ) ++cp;
1384 if( *cp == '=' ) ++cp;
1385 while( *cp == ' ' || *cp == '\t' ) ++cp;
1387 while( *cp && *cp != '\n' ) ++cp;
1389 if( len > BCTEXTLEN-1 ) return 1;
1390 while( bp < cp ) *val++ = *bp++;
1395 int FFMPEG::load_defaults(const char *path, const char *type,
1396 char *codec, char *codec_options, int len)
1398 char default_file[BCTEXTLEN];
1399 set_option_path(default_file, "%s/%s.dfl", path, type);
1400 FILE *fp = fopen(default_file,"r");
1402 fgets(codec, BCSTRLEN, fp);
1404 while( *cp && *cp!='\n' ) ++cp;
1406 while( len > 0 && fgets(codec_options, len, fp) ) {
1407 int n = strlen(codec_options);
1408 codec_options += n; len -= n;
1411 set_option_path(default_file, "%s/%s", path, codec);
1412 return load_options(default_file, codec_options, len);
1415 void FFMPEG::set_asset_format(Asset *asset, const char *text)
1417 if( asset->format != FILE_FFMPEG ) return;
1418 if( text != asset->fformat )
1419 strcpy(asset->fformat, text);
1420 if( !asset->ff_audio_options[0] ) {
1421 asset->audio_data = !load_defaults("audio", text, asset->acodec,
1422 asset->ff_audio_options, sizeof(asset->ff_audio_options));
1424 if( !asset->ff_video_options[0] ) {
1425 asset->video_data = !load_defaults("video", text, asset->vcodec,
1426 asset->ff_video_options, sizeof(asset->ff_video_options));
1430 int FFMPEG::get_encoder(const char *options,
1431 char *format, char *codec, char *bsfilter)
1433 FILE *fp = fopen(options,"r");
1435 eprintf(_("options open failed %s\n"),options);
1438 if( get_encoder(fp, format, codec, bsfilter) )
1439 eprintf(_("format/codec not found %s\n"), options);
1444 int FFMPEG::get_encoder(FILE *fp,
1445 char *format, char *codec, char *bsfilter)
1447 format[0] = codec[0] = bsfilter[0] = 0;
1448 char line[BCTEXTLEN];
1449 if( !fgets(line, sizeof(line), fp) ) return 1;
1450 line[sizeof(line)-1] = 0;
1451 if( scan_option_line(line, format, codec) ) return 1;
1453 while( *cp && *cp != '|' ) ++cp;
1454 if( !*cp ) return 0;
1456 do { *bp-- = 0; } while( bp>=codec && (*bp==' ' || *bp == '\t' ) );
1457 while( *++cp && (*cp==' ' || *cp == '\t') );
1459 for( int i=BCTEXTLEN; --i>0 && *cp; ) *bp++ = *cp++;
1464 int FFMPEG::read_options(const char *options, AVDictionary *&opts, int skip)
1466 FILE *fp = fopen(options,"r");
1469 while( !ret && --skip >= 0 ) {
1471 while( ch >= 0 && ch != '\n' ) ch = getc(fp);
1472 if( ch < 0 ) ret = 1;
1475 ret = read_options(fp, options, opts);
1480 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
1482 FILE *fp = fmemopen((void *)options,strlen(options),"r");
1484 int ret = read_options(fp, options, opts);
1486 AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
1487 if( tag ) st->id = strtol(tag->value,0,0);
1491 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
1493 int ret = 0, no = 0;
1494 char line[BCTEXTLEN];
1495 while( !ret && fgets(line, sizeof(line), fp) ) {
1496 line[sizeof(line)-1] = 0;
1497 if( line[0] == '#' ) continue;
1498 if( line[0] == '\n' ) continue;
1499 char key[BCSTRLEN], val[BCTEXTLEN];
1500 if( scan_option_line(line, key, val) ) {
1501 eprintf(_("err reading %s: line %d\n"), options, no);
1505 if( !strcmp(key, "duration") )
1506 opt_duration = strtod(val, 0);
1507 else if( !strcmp(key, "video_filter") )
1508 opt_video_filter = cstrdup(val);
1509 else if( !strcmp(key, "audio_filter") )
1510 opt_audio_filter = cstrdup(val);
1511 else if( !strcmp(key, "loglevel") )
1514 av_dict_set(&opts, key, val, 0);
1520 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
1522 char option_path[BCTEXTLEN];
1523 set_option_path(option_path, "%s", options);
1524 return read_options(option_path, opts);
1527 int FFMPEG::load_options(const char *path, char *bfr, int len)
1530 FILE *fp = fopen(path, "r");
1532 fgets(bfr, len, fp); // skip hdr
1533 len = fread(bfr, 1, len-1, fp);
1534 if( len < 0 ) len = 0;
1540 void FFMPEG::set_loglevel(const char *ap)
1542 if( !ap || !*ap ) return;
1547 { "quiet" , AV_LOG_QUIET },
1548 { "panic" , AV_LOG_PANIC },
1549 { "fatal" , AV_LOG_FATAL },
1550 { "error" , AV_LOG_ERROR },
1551 { "warning", AV_LOG_WARNING },
1552 { "info" , AV_LOG_INFO },
1553 { "verbose", AV_LOG_VERBOSE },
1554 { "debug" , AV_LOG_DEBUG },
1556 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
1557 if( !strcmp(log_levels[i].name, ap) ) {
1558 av_log_set_level(log_levels[i].level);
1562 av_log_set_level(atoi(ap));
1565 double FFMPEG::to_secs(int64_t time, AVRational time_base)
1567 double base_time = time == AV_NOPTS_VALUE ? 0 :
1568 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
1569 return base_time / AV_TIME_BASE;
1572 int FFMPEG::info(char *text, int len)
1574 if( len <= 0 ) return 0;
1576 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
1578 report("format: %s\n",fmt_ctx->iformat->name);
1579 if( ffvideo.size() > 0 )
1580 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
1581 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
1582 FFVideoStream *vid = ffvideo[vidx];
1583 AVStream *st = vid->st;
1584 AVCodecID codec_id = st->codecpar->codec_id;
1585 report(_("vid%d (%d), id 0x%06x:\n"), vid->idx, vid->fidx, codec_id);
1586 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
1587 report(" video%d %s", vidx+1, desc ? desc->name : " (unkn)");
1588 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
1589 AVPixelFormat pix_fmt = (AVPixelFormat)st->codecpar->format;
1590 const char *pfn = av_get_pix_fmt_name(pix_fmt);
1591 report(" pix %s\n", pfn ? pfn : "(unkn)");
1592 double secs = to_secs(st->duration, st->time_base);
1593 int64_t length = secs * vid->frame_rate + 0.5;
1594 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
1595 int64_t nudge = ofs * vid->frame_rate;
1596 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1597 report(" %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
1598 int hrs = secs/3600; secs -= hrs*3600;
1599 int mins = secs/60; secs -= mins*60;
1600 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1602 if( ffaudio.size() > 0 )
1603 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
1604 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
1605 FFAudioStream *aud = ffaudio[aidx];
1606 AVStream *st = aud->st;
1607 AVCodecID codec_id = st->codecpar->codec_id;
1608 report(_("aud%d (%d), id 0x%06x:\n"), aud->idx, aud->fidx, codec_id);
1609 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
1610 int nch = aud->channels, ch0 = aud->channel0+1;
1611 report(" audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
1612 AVSampleFormat sample_fmt = (AVSampleFormat)st->codecpar->format;
1613 const char *fmt = av_get_sample_fmt_name(sample_fmt);
1614 report(" %s %d", fmt, aud->sample_rate);
1615 int sample_bits = av_get_bits_per_sample(codec_id);
1616 report(" %dbits\n", sample_bits);
1617 double secs = to_secs(st->duration, st->time_base);
1618 int64_t length = secs * aud->sample_rate + 0.5;
1619 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
1620 int64_t nudge = ofs * aud->sample_rate;
1621 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1622 report(" %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
1623 int hrs = secs/3600; secs -= hrs*3600;
1624 int mins = secs/60; secs -= mins*60;
1625 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1627 if( fmt_ctx->nb_programs > 0 )
1628 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
1629 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
1630 report("program %d", i+1);
1631 AVProgram *pgrm = fmt_ctx->programs[i];
1632 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1633 int idx = pgrm->stream_index[j];
1634 int vidx = ffvideo.size();
1635 while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
1637 report(", vid%d", vidx);
1640 int aidx = ffaudio.size();
1641 while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
1643 report(", aud%d", aidx);
1646 report(", (%d)", pgrm->stream_index[j]);
1651 AVDictionaryEntry *tag = 0;
1652 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
1653 report("%s=%s\n", tag->key, tag->value);
1662 int FFMPEG::init_decoder(const char *filename)
1664 ff_lock("FFMPEG::init_decoder");
1666 char file_opts[BCTEXTLEN];
1667 char *bp = strrchr(strcpy(file_opts, filename), '/');
1668 char *sp = strrchr(!bp ? file_opts : bp, '.');
1671 strcpy(sp, ".opts");
1672 fp = fopen(file_opts, "r");
1675 read_options(fp, file_opts, opts);
1679 load_options("decode.opts", opts);
1680 AVDictionary *fopts = 0;
1681 av_dict_copy(&fopts, opts, 0);
1682 int ret = avformat_open_input(&fmt_ctx, filename, NULL, &fopts);
1683 av_dict_free(&fopts);
1685 ret = avformat_find_stream_info(fmt_ctx, NULL);
1690 return !ret ? 0 : 1;
1693 int FFMPEG::open_decoder()
1696 if( stat(fmt_ctx->filename, &st) < 0 ) {
1697 eprintf(_("can't stat file: %s\n"), fmt_ctx->filename);
1701 int64_t file_bits = 8 * st.st_size;
1702 if( !fmt_ctx->bit_rate && opt_duration > 0 )
1703 fmt_ctx->bit_rate = file_bits / opt_duration;
1706 if( fmt_ctx->bit_rate > 0 ) {
1707 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1708 AVStream *st = fmt_ctx->streams[i];
1709 if( st->duration != AV_NOPTS_VALUE ) continue;
1710 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
1711 st->duration = av_rescale(file_bits, st->time_base.den,
1712 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
1717 printf("FFMPEG::open_decoder: some stream times estimated\n");
1719 ff_lock("FFMPEG::open_decoder");
1720 int ret = 0, bad_time = 0;
1721 for( int i=0; !ret && i<(int)fmt_ctx->nb_streams; ++i ) {
1722 AVStream *st = fmt_ctx->streams[i];
1723 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
1724 AVCodecParameters *avpar = st->codecpar;
1725 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avpar->codec_id);
1726 if( !codec_desc ) continue;
1727 switch( avpar->codec_type ) {
1728 case AVMEDIA_TYPE_VIDEO: {
1729 if( avpar->width < 1 ) continue;
1730 if( avpar->height < 1 ) continue;
1731 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
1732 if( framerate.num < 1 ) continue;
1734 int vidx = ffvideo.size();
1735 FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
1736 vstrm_index.append(ffidx(vidx, 0));
1737 ffvideo.append(vid);
1738 vid->width = avpar->width;
1739 vid->height = avpar->height;
1740 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
1741 double secs = to_secs(st->duration, st->time_base);
1742 vid->length = secs * vid->frame_rate;
1743 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
1744 vid->nudge = st->start_time;
1746 if( opt_video_filter )
1747 ret = vid->create_filter(opt_video_filter, avpar);
1749 case AVMEDIA_TYPE_AUDIO: {
1750 if( avpar->channels < 1 ) continue;
1751 if( avpar->sample_rate < 1 ) continue;
1753 int aidx = ffaudio.size();
1754 FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
1755 ffaudio.append(aud);
1756 aud->channel0 = astrm_index.size();
1757 aud->channels = avpar->channels;
1758 for( int ch=0; ch<aud->channels; ++ch )
1759 astrm_index.append(ffidx(aidx, ch));
1760 aud->sample_rate = avpar->sample_rate;
1761 double secs = to_secs(st->duration, st->time_base);
1762 aud->length = secs * aud->sample_rate;
1763 aud->init_swr(aud->channels, avpar->format, aud->sample_rate);
1764 aud->nudge = st->start_time;
1766 if( opt_audio_filter )
1767 ret = aud->create_filter(opt_audio_filter, avpar);
1773 printf("FFMPEG::open_decoder: some stream have bad times\n");
1775 return ret < 0 ? -1 : 0;
1779 int FFMPEG::init_encoder(const char *filename)
1781 int fd = ::open(filename,O_WRONLY);
1782 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
1784 eprintf(_("bad file path: %s\n"), filename);
1788 int ret = get_file_format();
1790 eprintf(_("bad file format: %s\n"), filename);
1794 eprintf(_("mismatch audio/video file format: %s\n"), filename);
1797 ff_lock("FFMPEG::init_encoder");
1799 char format[BCSTRLEN];
1800 if( get_format(format, "format", file_format) )
1801 strcpy(format, file_format);
1802 avformat_alloc_output_context2(&fmt_ctx, 0, format, filename);
1804 eprintf(_("failed: %s\n"), filename);
1809 load_options("encode.opts", opts);
1815 int FFMPEG::open_encoder(const char *type, const char *spec)
1818 Asset *asset = file_base->asset;
1819 char *filename = asset->path;
1820 AVDictionary *sopts = 0;
1821 av_dict_copy(&sopts, opts, 0);
1822 char option_path[BCTEXTLEN];
1823 set_option_path(option_path, "%s/%s.opts", type, type);
1824 read_options(option_path, sopts);
1825 get_option_path(option_path, type, spec);
1826 char format_name[BCSTRLEN], codec_name[BCTEXTLEN], bsfilter[BCTEXTLEN];
1827 if( get_encoder(option_path, format_name, codec_name, bsfilter) ) {
1828 eprintf(_("get_encoder failed %s:%s\n"), option_path, filename);
1832 if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
1833 else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
1834 else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
1837 ff_lock("FFMPEG::open_encoder");
1840 AVCodecContext *ctx = 0;
1842 const AVCodecDescriptor *codec_desc = 0;
1843 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
1845 eprintf(_("cant find codec %s:%s\n"), codec_name, filename);
1849 codec_desc = avcodec_descriptor_get(codec->id);
1851 eprintf(_("unknown codec %s:%s\n"), codec_name, filename);
1856 st = avformat_new_stream(fmt_ctx, 0);
1858 eprintf(_("cant create stream %s:%s\n"), codec_name, filename);
1863 switch( codec_desc->type ) {
1864 case AVMEDIA_TYPE_AUDIO: {
1866 eprintf(_("duplicate audio %s:%s\n"), codec_name, filename);
1870 if( scan_options(asset->ff_audio_options, sopts, st) ) {
1871 eprintf(_("bad audio options %s:%s\n"), codec_name, filename);
1876 ctx = avcodec_alloc_context3(codec);
1877 if( asset->ff_audio_bitrate > 0 ) {
1878 ctx->bit_rate = asset->ff_audio_bitrate;
1880 sprintf(arg, "%d", asset->ff_audio_bitrate);
1881 av_dict_set(&sopts, "b", arg, 0);
1883 int aidx = ffaudio.size();
1884 int fidx = aidx + ffvideo.size();
1885 FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
1886 aud->avctx = ctx; ffaudio.append(aud); fst = aud;
1887 aud->sample_rate = asset->sample_rate;
1888 ctx->channels = aud->channels = asset->channels;
1889 for( int ch=0; ch<aud->channels; ++ch )
1890 astrm_index.append(ffidx(aidx, ch));
1891 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
1892 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
1893 if( !ctx->sample_rate ) {
1894 eprintf(_("check_sample_rate failed %s\n"), filename);
1898 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
1899 ctx->sample_fmt = codec->sample_fmts[0];
1900 uint64_t layout = av_get_default_channel_layout(ctx->channels);
1901 aud->resample_context = swr_alloc_set_opts(NULL,
1902 layout, ctx->sample_fmt, aud->sample_rate,
1903 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
1905 swr_init(aud->resample_context);
1908 case AVMEDIA_TYPE_VIDEO: {
1910 eprintf(_("duplicate video %s:%s\n"), codec_name, filename);
1914 if( scan_options(asset->ff_video_options, sopts, st) ) {
1915 eprintf(_("bad video options %s:%s\n"), codec_name, filename);
1920 ctx = avcodec_alloc_context3(codec);
1921 if( asset->ff_video_bitrate > 0 ) {
1922 ctx->bit_rate = asset->ff_video_bitrate;
1924 sprintf(arg, "%d", asset->ff_video_bitrate);
1925 av_dict_set(&sopts, "b", arg, 0);
1927 else if( asset->ff_video_quality >= 0 ) {
1928 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
1929 ctx->qmin = ctx->qmax = asset->ff_video_quality;
1930 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
1931 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
1932 ctx->flags |= CODEC_FLAG_QSCALE;
1934 av_dict_set(&sopts, "flags", "+qscale", 0);
1935 sprintf(arg, "%d", asset->ff_video_quality);
1936 av_dict_set(&sopts, "qscale", arg, 0);
1937 sprintf(arg, "%d", ctx->global_quality);
1938 av_dict_set(&sopts, "global_quality", arg, 0);
1940 int vidx = ffvideo.size();
1941 int fidx = vidx + ffaudio.size();
1942 FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
1943 vstrm_index.append(ffidx(vidx, 0));
1944 vid->avctx = ctx; ffvideo.append(vid); fst = vid;
1945 vid->width = asset->width;
1946 ctx->width = (vid->width+3) & ~3;
1947 vid->height = asset->height;
1948 ctx->height = (vid->height+3) & ~3;
1949 vid->frame_rate = asset->frame_rate;
1950 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
1951 ctx->pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
1952 AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
1953 if( !frame_rate.num || !frame_rate.den ) {
1954 eprintf(_("check_frame_rate failed %s\n"), filename);
1958 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
1959 st->time_base = ctx->time_base;
1961 vid->interlaced = asset->interlace_mode == ILACE_MODE_TOP_FIRST ||
1962 asset->interlace_mode == ILACE_MODE_BOTTOM_FIRST ? 1 : 0;
1963 vid->top_field_first = asset->interlace_mode == ILACE_MODE_TOP_FIRST ? 1 : 0;
1966 eprintf(_("not audio/video, %s:%s\n"), codec_name, filename);
1971 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
1972 ctx->flags |= CODEC_FLAG_GLOBAL_HEADER;
1974 av_dict_set(&sopts, "cin_bitrate", 0, 0);
1975 av_dict_set(&sopts, "cin_quality", 0, 0);
1977 ret = avcodec_open2(ctx, codec, &sopts);
1979 ret = avcodec_parameters_from_context(st->codecpar, ctx);
1981 fprintf(stderr, "Could not copy the stream parameters\n");
1984 ff_err(ret,"FFMPEG::open_encoder");
1985 eprintf(_("open failed %s:%s\n"), codec_name, filename);
1991 if( !ret && fst && bsfilter[0] ) {
1992 ret = av_bsf_list_parse_str(bsfilter, &fst->bsfc);
1994 ff_err(ret,"FFMPEG::open_encoder");
1995 eprintf(_("bitstream filter failed %s:\n%s\n"), filename, bsfilter);
2006 av_dict_free(&sopts);
2010 int FFMPEG::close_encoder()
2013 if( encoding > 0 ) {
2014 av_write_trailer(fmt_ctx);
2015 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
2016 avio_closep(&fmt_ctx->pb);
2022 int FFMPEG::decode_activate()
2024 if( decoding < 0 ) {
2026 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
2027 ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
2028 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
2029 ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
2030 // set nudges for each program stream set
2031 const int64_t min_nudge = INT64_MIN+1;
2032 int npgrms = fmt_ctx->nb_programs;
2033 for( int i=0; i<npgrms; ++i ) {
2034 AVProgram *pgrm = fmt_ctx->programs[i];
2035 // first start time video stream
2036 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2037 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2038 int fidx = pgrm->stream_index[j];
2039 AVStream *st = fmt_ctx->streams[fidx];
2040 AVCodecParameters *avpar = st->codecpar;
2041 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2042 if( st->start_time == AV_NOPTS_VALUE ) continue;
2043 if( vstart_time < st->start_time )
2044 vstart_time = st->start_time;
2047 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2048 if( st->start_time == AV_NOPTS_VALUE ) continue;
2049 if( astart_time < st->start_time )
2050 astart_time = st->start_time;
2054 //since frame rate is much more grainy than sample rate, it is better to
2055 // align using video, so that total absolute error is minimized.
2056 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2057 astart_time > min_nudge ? astart_time : AV_NOPTS_VALUE;
2058 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2059 int fidx = pgrm->stream_index[j];
2060 AVStream *st = fmt_ctx->streams[fidx];
2061 AVCodecParameters *avpar = st->codecpar;
2062 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2063 for( int k=0; k<ffvideo.size(); ++k ) {
2064 if( ffvideo[k]->fidx != fidx ) continue;
2065 ffvideo[k]->nudge = nudge;
2069 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2070 for( int k=0; k<ffaudio.size(); ++k ) {
2071 if( ffaudio[k]->fidx != fidx ) continue;
2072 ffaudio[k]->nudge = nudge;
2078 // set nudges for any streams not yet set
2079 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2080 int nstreams = fmt_ctx->nb_streams;
2081 for( int i=0; i<nstreams; ++i ) {
2082 AVStream *st = fmt_ctx->streams[i];
2083 AVCodecParameters *avpar = st->codecpar;
2084 switch( avpar->codec_type ) {
2085 case AVMEDIA_TYPE_VIDEO: {
2086 if( st->start_time == AV_NOPTS_VALUE ) continue;
2087 int vidx = ffvideo.size();
2088 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
2089 if( vidx >= 0 && ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
2090 if( vstart_time < st->start_time )
2091 vstart_time = st->start_time;
2093 case AVMEDIA_TYPE_AUDIO: {
2094 if( st->start_time == AV_NOPTS_VALUE ) continue;
2095 int aidx = ffaudio.size();
2096 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
2097 if( aidx >= 0 && ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
2098 if( astart_time < st->start_time )
2099 astart_time = st->start_time;
2104 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2105 astart_time > min_nudge ? astart_time : 0;
2106 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
2107 if( ffvideo[vidx]->nudge == AV_NOPTS_VALUE )
2108 ffvideo[vidx]->nudge = nudge;
2110 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2111 if( ffaudio[aidx]->nudge == AV_NOPTS_VALUE )
2112 ffaudio[aidx]->nudge = nudge;
2119 int FFMPEG::encode_activate()
2122 if( encoding < 0 ) {
2124 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
2125 (ret=avio_open(&fmt_ctx->pb, fmt_ctx->filename, AVIO_FLAG_WRITE)) < 0 ) {
2126 ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
2132 AVProgram *prog = av_new_program(fmt_ctx, prog_id);
2133 for( int i=0; i< ffvideo.size(); ++i )
2134 av_program_add_stream_index(fmt_ctx, prog_id, ffvideo[i]->fidx);
2135 for( int i=0; i< ffaudio.size(); ++i )
2136 av_program_add_stream_index(fmt_ctx, prog_id, ffaudio[i]->fidx);
2137 int pi = fmt_ctx->nb_programs;
2138 while( --pi >= 0 && fmt_ctx->programs[pi]->id != prog_id );
2139 AVDictionary **meta = &prog->metadata;
2140 av_dict_set(meta, "service_provider", "cin5", 0);
2141 const char *path = fmt_ctx->filename, *bp = strrchr(path,'/');
2142 if( bp ) path = bp + 1;
2143 av_dict_set(meta, "title", path, 0);
2145 if( ffaudio.size() ) {
2146 const char *ep = getenv("CIN_AUDIO_LANG"), *lp = 0;
2147 if( !ep && (lp=getenv("LANG")) ) { // some are guesses
2148 static struct { const char lc[3], lng[4]; } lcode[] = {
2149 { "en", "eng" }, { "de", "ger" }, { "es", "spa" },
2150 { "eu", "bas" }, { "fr", "fre" }, { "el", "gre" },
2151 { "hi", "hin" }, { "it", "ita" }, { "ja", "jap" },
2152 { "ko", "kor" }, { "du", "dut" }, { "pl", "pol" },
2153 { "pt", "por" }, { "ru", "rus" }, { "sl", "slv" },
2154 { "uk", "ukr" }, { "vi", "vie" }, { "zh", "chi" },
2156 for( int i=sizeof(lcode)/sizeof(lcode[0]); --i>=0 && !ep; )
2157 if( !strncmp(lcode[i].lc,lp,2) ) ep = lcode[i].lng;
2159 if( !ep ) ep = "und";
2161 strncpy(lang,ep,3); lang[3] = 0;
2162 AVStream *st = ffaudio[0]->st;
2163 av_dict_set(&st->metadata,"language",lang,0);
2166 AVDictionary *fopts = 0;
2167 char option_path[BCTEXTLEN];
2168 set_option_path(option_path, "format/%s", file_format);
2169 read_options(option_path, fopts, 1);
2170 ret = avformat_write_header(fmt_ctx, &fopts);
2172 ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
2176 av_dict_free(&fopts);
2183 int FFMPEG::audio_seek(int stream, int64_t pos)
2185 int aidx = astrm_index[stream].st_idx;
2186 FFAudioStream *aud = ffaudio[aidx];
2187 aud->audio_seek(pos);
2191 int FFMPEG::video_seek(int stream, int64_t pos)
2193 int vidx = vstrm_index[stream].st_idx;
2194 FFVideoStream *vid = ffvideo[vidx];
2195 vid->video_seek(pos);
2200 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
2202 if( !has_audio || chn >= astrm_index.size() ) return -1;
2203 int aidx = astrm_index[chn].st_idx;
2204 FFAudioStream *aud = ffaudio[aidx];
2205 if( aud->load(pos, len) < len ) return -1;
2206 int ch = astrm_index[chn].st_ch;
2207 int ret = aud->read(samples,len,ch);
2211 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
2213 if( !has_video || layer >= vstrm_index.size() ) return -1;
2214 int vidx = vstrm_index[layer].st_idx;
2215 FFVideoStream *vid = ffvideo[vidx];
2216 return vid->load(vframe, pos);
2220 int FFMPEG::encode(int stream, double **samples, int len)
2222 FFAudioStream *aud = ffaudio[stream];
2223 return aud->encode(samples, len);
2227 int FFMPEG::encode(int stream, VFrame *frame)
2229 FFVideoStream *vid = ffvideo[stream];
2230 return vid->encode(frame);
2233 void FFMPEG::start_muxer()
2241 void FFMPEG::stop_muxer()
2250 void FFMPEG::flow_off()
2253 flow_lock->lock("FFMPEG::flow_off");
2257 void FFMPEG::flow_on()
2261 flow_lock->unlock();
2264 void FFMPEG::flow_ctl()
2267 flow_lock->lock("FFMPEG::flow_ctl");
2268 flow_lock->unlock();
2272 int FFMPEG::mux_audio(FFrame *frm)
2274 FFStream *fst = frm->fst;
2275 AVCodecContext *ctx = fst->avctx;
2276 AVFrame *frame = *frm;
2277 AVRational tick_rate = {1, ctx->sample_rate};
2278 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
2279 int ret = fst->encode_frame(frame);
2281 ff_err(ret, "FFMPEG::mux_audio");
2282 return ret >= 0 ? 0 : 1;
2285 int FFMPEG::mux_video(FFrame *frm)
2287 FFStream *fst = frm->fst;
2288 AVFrame *frame = *frm;
2289 frame->pts = frm->position;
2290 int ret = fst->encode_frame(frame);
2292 ff_err(ret, "FFMPEG::mux_video");
2293 return ret >= 0 ? 0 : 1;
2299 double atm = -1, vtm = -1;
2300 FFrame *afrm = 0, *vfrm = 0;
2302 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
2303 FFStream *fst = ffaudio[i];
2304 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
2305 FFrame *frm = fst->frms.first;
2306 if( !frm ) { if( !done ) return; continue; }
2307 double tm = to_secs(frm->position, fst->avctx->time_base);
2308 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
2310 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
2311 FFStream *fst = ffvideo[i];
2312 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
2313 FFrame *frm = fst->frms.first;
2314 if( !frm ) { if( !done ) return; continue; }
2315 double tm = to_secs(frm->position, fst->avctx->time_base);
2316 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
2318 if( !demand ) flow_off();
2319 if( !afrm && !vfrm ) break;
2320 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
2321 vfrm->position, vfrm->fst->avctx->time_base,
2322 afrm->position, afrm->fst->avctx->time_base);
2323 FFrame *frm = v <= 0 ? vfrm : afrm;
2324 if( frm == afrm ) mux_audio(frm);
2325 if( frm == vfrm ) mux_video(frm);
2334 mux_lock->lock("FFMPEG::run");
2337 for( int i=0; i<ffaudio.size(); ++i )
2338 ffaudio[i]->drain();
2339 for( int i=0; i<ffvideo.size(); ++i )
2340 ffvideo[i]->drain();
2342 for( int i=0; i<ffaudio.size(); ++i )
2343 ffaudio[i]->flush();
2344 for( int i=0; i<ffvideo.size(); ++i )
2345 ffvideo[i]->flush();
2349 int FFMPEG::ff_total_audio_channels()
2351 return astrm_index.size();
2354 int FFMPEG::ff_total_astreams()
2356 return ffaudio.size();
2359 int FFMPEG::ff_audio_channels(int stream)
2361 return ffaudio[stream]->channels;
2364 int FFMPEG::ff_sample_rate(int stream)
2366 return ffaudio[stream]->sample_rate;
2369 const char* FFMPEG::ff_audio_format(int stream)
2371 AVStream *st = ffaudio[stream]->st;
2372 AVCodecID id = st->codecpar->codec_id;
2373 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2374 return desc ? desc->name : _("Unknown");
2377 int FFMPEG::ff_audio_pid(int stream)
2379 return ffaudio[stream]->st->id;
2382 int64_t FFMPEG::ff_audio_samples(int stream)
2384 return ffaudio[stream]->length;
2387 // find audio astream/channels with this program,
2388 // or all program audio channels (astream=-1)
2389 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
2393 int vidx = ffvideo[vstream]->fidx;
2394 // find first program with this video stream
2395 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
2396 AVProgram *pgrm = fmt_ctx->programs[i];
2397 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
2398 int st_idx = pgrm->stream_index[j];
2399 AVStream *st = fmt_ctx->streams[st_idx];
2400 if( st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
2401 if( st_idx == vidx ) pidx = i;
2404 if( pidx < 0 ) return -1;
2406 int64_t channels = 0;
2407 AVProgram *pgrm = fmt_ctx->programs[pidx];
2408 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2409 int aidx = pgrm->stream_index[j];
2410 AVStream *st = fmt_ctx->streams[aidx];
2411 if( st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
2412 if( astream > 0 ) { --astream; continue; }
2414 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
2415 if( ffaudio[i]->fidx == aidx ) astrm = i;
2417 if( ret < 0 ) ret = astrm;
2418 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
2419 channels |= mask << ffaudio[astrm]->channel0;
2421 if( !astream ) break;
2423 channel_mask = channels;
2428 int FFMPEG::ff_total_video_layers()
2430 return vstrm_index.size();
2433 int FFMPEG::ff_total_vstreams()
2435 return ffvideo.size();
2438 int FFMPEG::ff_video_width(int stream)
2440 return ffvideo[stream]->width;
2443 int FFMPEG::ff_video_height(int stream)
2445 return ffvideo[stream]->height;
2448 int FFMPEG::ff_set_video_width(int stream, int width)
2450 int w = ffvideo[stream]->width;
2451 ffvideo[stream]->width = width;
2455 int FFMPEG::ff_set_video_height(int stream, int height)
2457 int h = ffvideo[stream]->height;
2458 ffvideo[stream]->height = height;
2462 int FFMPEG::ff_coded_width(int stream)
2464 return ffvideo[stream]->avctx->coded_width;
2467 int FFMPEG::ff_coded_height(int stream)
2469 return ffvideo[stream]->avctx->coded_height;
2472 float FFMPEG::ff_aspect_ratio(int stream)
2474 return ffvideo[stream]->aspect_ratio;
2477 const char* FFMPEG::ff_video_format(int stream)
2479 AVStream *st = ffvideo[stream]->st;
2480 AVCodecID id = st->codecpar->codec_id;
2481 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2482 return desc ? desc->name : _("Unknown");
2485 double FFMPEG::ff_frame_rate(int stream)
2487 return ffvideo[stream]->frame_rate;
2490 int64_t FFMPEG::ff_video_frames(int stream)
2492 return ffvideo[stream]->length;
2495 int FFMPEG::ff_video_pid(int stream)
2497 return ffvideo[stream]->st->id;
2501 int FFMPEG::ff_cpus()
2503 return file_base->file->cpus;
2506 int FFVideoStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
2508 avfilter_register_all();
2509 const char *sp = filter_spec;
2510 char filter_name[BCSTRLEN], *np = filter_name;
2511 int i = sizeof(filter_name);
2512 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
2514 AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
2515 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_VIDEO ) {
2516 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
2519 filter_graph = avfilter_graph_alloc();
2520 AVFilter *buffersrc = avfilter_get_by_name("buffer");
2521 AVFilter *buffersink = avfilter_get_by_name("buffersink");
2523 int ret = 0; char args[BCTEXTLEN];
2524 AVPixelFormat pix_fmt = (AVPixelFormat)avpar->format;
2525 snprintf(args, sizeof(args),
2526 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
2527 avpar->width, avpar->height, (int)pix_fmt,
2528 st->time_base.num, st->time_base.den,
2529 avpar->sample_aspect_ratio.num, avpar->sample_aspect_ratio.den);
2531 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2532 args, NULL, filter_graph);
2534 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2535 NULL, NULL, filter_graph);
2537 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
2538 (uint8_t*)&pix_fmt, sizeof(pix_fmt),
2539 AV_OPT_SEARCH_CHILDREN);
2541 ff_err(ret, "FFVideoStream::create_filter");
2543 ret = FFStream::create_filter(filter_spec);
2544 return ret >= 0 ? 0 : -1;
2547 int FFAudioStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
2549 avfilter_register_all();
2550 const char *sp = filter_spec;
2551 char filter_name[BCSTRLEN], *np = filter_name;
2552 int i = sizeof(filter_name);
2553 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
2555 AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
2556 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_AUDIO ) {
2557 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
2560 filter_graph = avfilter_graph_alloc();
2561 AVFilter *buffersrc = avfilter_get_by_name("abuffer");
2562 AVFilter *buffersink = avfilter_get_by_name("abuffersink");
2563 int ret = 0; char args[BCTEXTLEN];
2564 AVSampleFormat sample_fmt = (AVSampleFormat)avpar->format;
2565 snprintf(args, sizeof(args),
2566 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
2567 st->time_base.num, st->time_base.den, avpar->sample_rate,
2568 av_get_sample_fmt_name(sample_fmt), avpar->channel_layout);
2570 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2571 args, NULL, filter_graph);
2573 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2574 NULL, NULL, filter_graph);
2576 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
2577 (uint8_t*)&sample_fmt, sizeof(sample_fmt),
2578 AV_OPT_SEARCH_CHILDREN);
2580 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
2581 (uint8_t*)&avpar->channel_layout,
2582 sizeof(avpar->channel_layout), AV_OPT_SEARCH_CHILDREN);
2584 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
2585 (uint8_t*)&sample_rate, sizeof(sample_rate),
2586 AV_OPT_SEARCH_CHILDREN);
2588 ff_err(ret, "FFAudioStream::create_filter");
2590 ret = FFStream::create_filter(filter_spec);
2591 return ret >= 0 ? 0 : -1;
2594 int FFStream::create_filter(const char *filter_spec)
2596 /* Endpoints for the filter graph. */
2597 AVFilterInOut *outputs = avfilter_inout_alloc();
2598 outputs->name = av_strdup("in");
2599 outputs->filter_ctx = buffersrc_ctx;
2600 outputs->pad_idx = 0;
2603 AVFilterInOut *inputs = avfilter_inout_alloc();
2604 inputs->name = av_strdup("out");
2605 inputs->filter_ctx = buffersink_ctx;
2606 inputs->pad_idx = 0;
2609 int ret = !outputs->name || !inputs->name ? -1 : 0;
2611 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
2612 &inputs, &outputs, NULL);
2614 ret = avfilter_graph_config(filter_graph, NULL);
2617 ff_err(ret, "FFStream::create_filter");
2618 avfilter_graph_free(&filter_graph);
2621 avfilter_inout_free(&inputs);
2622 avfilter_inout_free(&outputs);
2626 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
2629 av_init_packet(&pkt);
2630 AVFrame *frame = av_frame_alloc();
2632 fprintf(stderr,"FFMPEG::scan: ");
2633 fprintf(stderr,_("av_frame_alloc failed\n"));
2637 index_state->add_video_markers(ffvideo.size());
2638 index_state->add_audio_markers(ffaudio.size());
2640 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2642 AVDictionary *copts = 0;
2643 av_dict_copy(&copts, opts, 0);
2644 AVStream *st = fmt_ctx->streams[i];
2645 AVCodecID codec_id = st->codecpar->codec_id;
2646 AVCodec *decoder = avcodec_find_decoder(codec_id);
2647 AVCodecContext *avctx = avcodec_alloc_context3(decoder);
2649 eprintf(_("cant allocate codec context\n"));
2650 ret = AVERROR(ENOMEM);
2653 avcodec_parameters_to_context(avctx, st->codecpar);
2654 ret = avcodec_open2(avctx, decoder, &copts);
2656 av_dict_free(&copts);
2658 AVCodecParameters *avpar = st->codecpar;
2659 switch( avpar->codec_type ) {
2660 case AVMEDIA_TYPE_VIDEO: {
2661 int vidx = ffvideo.size();
2662 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
2663 if( vidx < 0 ) break;
2664 ffvideo[vidx]->avctx = avctx;
2666 case AVMEDIA_TYPE_AUDIO: {
2667 int aidx = ffaudio.size();
2668 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
2669 if( aidx < 0 ) break;
2670 ffaudio[aidx]->avctx = avctx;
2675 fprintf(stderr,"FFMPEG::scan: ");
2676 fprintf(stderr,_("codec open failed\n"));
2677 avcodec_free_context(&avctx);
2681 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2682 AVStream *st = fmt_ctx->streams[i];
2683 AVCodecParameters *avpar = st->codecpar;
2684 if( avpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
2685 int64_t tstmp = st->start_time;
2686 if( tstmp == AV_NOPTS_VALUE ) continue;
2687 int aidx = ffaudio.size();
2688 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
2689 if( aidx < 0 ) continue;
2690 FFAudioStream *aud = ffaudio[aidx];
2691 tstmp -= aud->nudge;
2692 double secs = to_secs(tstmp, st->time_base);
2693 aud->curr_pos = secs * aud->sample_rate + 0.5;
2697 for( int64_t count=0; !*canceled; ++count ) {
2698 av_packet_unref(&pkt);
2699 pkt.data = 0; pkt.size = 0;
2701 int ret = av_read_frame(fmt_ctx, &pkt);
2703 if( ret == AVERROR_EOF ) break;
2704 if( ++errs > 100 ) {
2705 ff_err(ret,_("over 100 read_frame errs\n"));
2710 if( !pkt.data ) continue;
2711 int i = pkt.stream_index;
2712 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
2713 AVStream *st = fmt_ctx->streams[i];
2714 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
2716 AVCodecParameters *avpar = st->codecpar;
2717 switch( avpar->codec_type ) {
2718 case AVMEDIA_TYPE_VIDEO: {
2719 int vidx = ffvideo.size();
2720 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
2721 if( vidx < 0 ) break;
2722 FFVideoStream *vid = ffvideo[vidx];
2723 if( !vid->avctx ) break;
2724 int64_t tstmp = pkt.dts;
2725 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.pts;
2726 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
2727 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
2728 double secs = to_secs(tstmp, st->time_base);
2729 int64_t frm = secs * vid->frame_rate + 0.5;
2730 if( frm < 0 ) frm = 0;
2731 index_state->put_video_mark(vidx, frm, pkt.pos);
2734 ret = avcodec_send_packet(vid->avctx, pkt);
2735 if( ret < 0 ) break;
2736 while( (ret=vid->decode_frame(frame)) > 0 ) {}
2739 case AVMEDIA_TYPE_AUDIO: {
2740 int aidx = ffaudio.size();
2741 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
2742 if( aidx < 0 ) break;
2743 FFAudioStream *aud = ffaudio[aidx];
2744 if( !aud->avctx ) break;
2745 int64_t tstmp = pkt.pts;
2746 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
2747 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
2748 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
2749 double secs = to_secs(tstmp, st->time_base);
2750 int64_t sample = secs * aud->sample_rate + 0.5;
2752 index_state->put_audio_mark(aidx, sample, pkt.pos);
2754 ret = avcodec_send_packet(aud->avctx, &pkt);
2755 if( ret < 0 ) break;
2756 int ch = aud->channel0, nch = aud->channels;
2757 int64_t pos = index_state->pos(ch);
2758 if( pos != aud->curr_pos ) {
2759 if( abs(pos-aud->curr_pos) > 1 )
2760 printf("audio%d pad %jd %jd (%jd)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
2761 index_state->pad_data(ch, nch, aud->curr_pos);
2763 while( (ret=aud->decode_frame(frame)) > 0 ) {
2764 //if( frame->channels != nch ) break;
2765 aud->init_swr(frame->channels, frame->format, frame->sample_rate);
2767 int len = aud->get_samples(samples,
2768 &frame->extended_data[0], frame->nb_samples);
2769 pos = aud->curr_pos;
2770 if( (aud->curr_pos += len) >= 0 ) {
2772 samples += -pos * nch;
2773 len = aud->curr_pos;
2775 for( int i=0; i<nch; ++i )
2776 index_state->put_data(ch+i,nch,samples+i,len);
2783 av_frame_free(&frame);
2787 void FFStream::load_markers(IndexMarks &marks, double rate)
2790 int64_t sz = marks.size();
2791 int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
2792 int nb_ent = st->nb_index_entries;
2793 // some formats already have an index
2795 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
2796 int64_t tstmp = ep->timestamp;
2797 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
2798 double secs = ffmpeg->to_secs(tstmp, st->time_base);
2799 int64_t no = secs * rate;
2800 while( in < sz && marks[in].no <= no ) ++in;
2802 int64_t len = sz - in;
2803 int64_t count = max_entries - nb_ent;
2804 if( count > len ) count = len;
2805 for( int i=0; i<count; ++i ) {
2806 int k = in + i * len / count;
2807 int64_t no = marks[k].no, pos = marks[k].pos;
2808 double secs = (double)no / rate;
2809 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
2810 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
2811 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);