10 // work arounds (centos)
13 #define INT64_MAX 9223372036854775807LL
15 #define MAX_RETRY 1000
18 #include "bccmodels.h"
20 #include "fileffmpeg.h"
23 #include "indexfile.h"
24 #include "interlacemodes.h"
27 #include "mainerror.h"
32 #define VIDEO_INBUF_SIZE 0x10000
33 #define AUDIO_INBUF_SIZE 0x10000
34 #define VIDEO_REFILL_THRESH 0
35 #define AUDIO_REFILL_THRESH 0x1000
37 Mutex FFMPEG::fflock("FFMPEG::fflock");
39 static void ff_err(int ret, const char *fmt, ...)
44 vsnprintf(msg, sizeof(msg), fmt, ap);
46 char errmsg[BCSTRLEN];
47 av_strerror(ret, errmsg, sizeof(errmsg));
48 fprintf(stderr,_("%s err: %s\n"),msg, errmsg);
54 pkt.data = 0; pkt.size = 0;
56 void FFPacket::finit()
58 av_packet_unref(&pkt);
61 FFrame::FFrame(FFStream *fst)
64 frm = av_frame_alloc();
65 init = fst->init_frame(frm);
73 void FFrame::queue(int64_t pos)
79 void FFrame::dequeue()
84 int FFAudioStream::read(float *fp, long len)
92 while( --k >= 0 ) *fp++ = *op++;
93 if( op >= lmt ) op = bfr;
98 void FFAudioStream::realloc(long nsz, int nch, long len)
100 long bsz = nsz * nch;
101 float *np = new float[bsz];
102 inp = np + read(np, len) * nch;
107 delete [] bfr; bfr = np;
110 void FFAudioStream::realloc(long nsz, int nch)
112 if( nsz > sz || this->nch != nch ) {
113 long len = this->nch != nch ? 0 : hpos;
114 if( len > sz ) len = sz;
116 realloc(nsz, nch, len);
120 void FFAudioStream::reserve(long nsz, int nch)
122 long len = (inp - outp) / nch;
124 if( nsz > sz || this->nch != nch ) {
125 if( this->nch != nch ) len = 0;
126 realloc(nsz, nch, len);
129 if( (len*=nch) > 0 && bfr != outp )
130 memmove(bfr, outp, len*sizeof(*bfr));
135 long FFAudioStream::used()
137 long len = inp>=outp ? inp-outp : inp-bfr + lmt-outp;
140 long FFAudioStream::avail()
143 if( in1 >= lmt ) in1 = bfr;
144 long len = outp >= in1 ? outp-in1 : outp-bfr + lmt-in1;
147 void FFAudioStream::reset_history()
153 void FFAudioStream::iseek(int64_t ofs)
155 outp = inp - ofs*nch;
156 if( outp < bfr ) outp += sz*nch;
159 float *FFAudioStream::get_outp(int ofs)
166 int64_t FFAudioStream::put_inp(int ofs)
169 return (inp-outp) / nch;
172 int FFAudioStream::write(const float *fp, long len)
180 while( --k >= 0 ) *ip++ = *fp++;
181 if( ip >= lmt ) ip = bfr;
188 int FFAudioStream::zero(long len)
196 while( --k >= 0 ) *ip++ = 0;
197 if( ip >= lmt ) ip = bfr;
204 // does not advance outp
205 int FFAudioStream::read(double *dp, long len, int ch)
208 float *op = outp + ch;
209 float *lmt1 = lmt + nch-1;
211 int k = (lmt1 - op) / nch;
214 while( --k >= 0 ) { *dp++ = *op; op += nch; }
215 if( op >= lmt ) op -= sz*nch;
220 // load linear buffer, no wrapping allowed, does not advance inp
221 int FFAudioStream::write(const double *dp, long len, int ch)
224 float *ip = inp + ch;
225 while( --n >= 0 ) { *ip = *dp++; ip += nch; }
230 FFStream::FFStream(FFMPEG *ffmpeg, AVStream *st, int fidx)
232 this->ffmpeg = ffmpeg;
235 frm_lock = new Mutex("FFStream::frm_lock");
242 nudge = AV_NOPTS_VALUE;
243 seek_pos = curr_pos = 0;
245 reading = writing = 0;
252 FFStream::~FFStream()
254 if( reading > 0 || writing > 0 ) avcodec_close(avctx);
255 if( avctx ) avcodec_free_context(&avctx);
256 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
257 if( bsfc ) av_bsf_free(&bsfc);
258 while( frms.first ) frms.remove(frms.first);
259 if( filter_graph ) avfilter_graph_free(&filter_graph);
260 if( frame ) av_frame_free(&frame);
261 if( fframe ) av_frame_free(&fframe);
265 void FFStream::ff_lock(const char *cp)
267 FFMPEG::fflock.lock(cp);
270 void FFStream::ff_unlock()
272 FFMPEG::fflock.unlock();
275 void FFStream::queue(FFrame *frm)
277 frm_lock->lock("FFStream::queue");
281 ffmpeg->mux_lock->unlock();
284 void FFStream::dequeue(FFrame *frm)
286 frm_lock->lock("FFStream::dequeue");
288 frms.remove_pointer(frm);
292 int FFStream::encode_activate()
295 writing = ffmpeg->encode_activate();
299 int FFStream::decode_activate()
301 if( reading < 0 && (reading=ffmpeg->decode_activate()) > 0 ) {
302 ff_lock("FFStream::decode_activate");
304 AVDictionary *copts = 0;
305 av_dict_copy(&copts, ffmpeg->opts, 0);
307 // this should be avformat_copy_context(), but no copy avail
308 ret = avformat_open_input(&fmt_ctx, ffmpeg->fmt_ctx->filename, NULL, &copts);
310 ret = avformat_find_stream_info(fmt_ctx, 0);
311 st = fmt_ctx->streams[fidx];
314 if( ret >= 0 && st != 0 ) {
315 AVCodecID codec_id = st->codecpar->codec_id;
316 AVCodec *decoder = avcodec_find_decoder(codec_id);
317 avctx = avcodec_alloc_context3(decoder);
319 eprintf(_("cant allocate codec context\n"));
320 ret = AVERROR(ENOMEM);
323 av_codec_set_pkt_timebase(avctx, st->time_base);
324 if( decoder->capabilities & AV_CODEC_CAP_DR1 )
325 avctx->flags |= CODEC_FLAG_EMU_EDGE;
326 avcodec_parameters_to_context(avctx, st->codecpar);
327 ret = avcodec_open2(avctx, decoder, &copts);
333 eprintf(_("open decoder failed\n"));
336 eprintf(_("can't clone input file\n"));
337 av_dict_free(&copts);
343 int FFStream::read_packet()
345 av_packet_unref(ipkt);
346 int ret = av_read_frame(fmt_ctx, ipkt);
349 if( ret == AVERROR_EOF ) return 0;
350 ff_err(ret, "FFStream::read_packet: av_read_frame failed\n");
357 int FFStream::decode(AVFrame *frame)
360 int retries = MAX_RETRY;
362 while( ret >= 0 && !flushed && --retries >= 0 ) {
364 if( (ret=read_packet()) < 0 ) break;
365 AVPacket *pkt = ret > 0 ? (AVPacket*)ipkt : 0;
367 if( pkt->stream_index != st->index ) continue;
368 if( !pkt->data | !pkt->size ) continue;
370 if( (ret=avcodec_send_packet(avctx, pkt)) < 0 ) {
371 ff_err(ret, "FFStream::decode: avcodec_send_packet failed\n");
377 if( (ret=decode_frame(frame)) > 0 ) break;
385 fprintf(stderr, "FFStream::decode: Retry limit\n");
389 fprintf(stderr, "FFStream::decode: failed\n");
393 int FFStream::load_filter(AVFrame *frame)
395 int ret = av_buffersrc_add_frame_flags(buffersrc_ctx,
396 frame, AV_BUFFERSRC_FLAG_KEEP_REF);
398 av_frame_unref(frame);
399 eprintf(_("av_buffersrc_add_frame_flags failed\n"));
404 int FFStream::read_filter(AVFrame *frame)
406 int ret = av_buffersink_get_frame(buffersink_ctx, frame);
408 if( ret == AVERROR(EAGAIN) ) return 0;
409 if( ret == AVERROR_EOF ) { st_eof(1); return -1; }
410 ff_err(ret, "FFStream::read_filter: av_buffersink_get_frame failed\n");
416 int FFStream::read_frame(AVFrame *frame)
418 if( !filter_graph || !buffersrc_ctx || !buffersink_ctx )
419 return decode(frame);
420 if( !fframe && !(fframe=av_frame_alloc()) ) {
421 fprintf(stderr, "FFStream::read_frame: av_frame_alloc failed\n");
425 while( !flushed && !(ret=read_filter(frame)) ) {
426 if( (ret=decode(fframe)) < 0 ) break;
427 if( ret > 0 && (ret=load_filter(fframe)) < 0 ) break;
432 int FFStream::write_packet(FFPacket &pkt)
436 av_packet_rescale_ts(pkt, avctx->time_base, st->time_base);
437 pkt->stream_index = st->index;
438 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, pkt);
441 ret = av_bsf_send_packet(bsfc, pkt);
444 if( (ret=av_bsf_receive_packet(bsfc, bs)) < 0 ) {
445 if( ret == AVERROR(EAGAIN) ) return 0;
446 if( ret == AVERROR_EOF ) return -1;
449 av_packet_rescale_ts(bs, avctx->time_base, st->time_base);
450 bs->stream_index = st->index;
451 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, bs);
455 ff_err(ret, "FFStream::write_packet: write packet failed\n");
459 int FFStream::encode_frame(AVFrame *frame)
461 int pkts = 0, ret = 0;
462 for( int retry=100; --retry>=0; ) {
464 ret = avcodec_send_frame(avctx, frame);
465 if( !ret && frame ) return pkts;
466 if( ret < 0 && ret != AVERROR(EAGAIN) ) break;
468 ret = avcodec_receive_packet(avctx, opkt);
469 if( !frame && ret == AVERROR_EOF ) return pkts;
471 ret = write_packet(opkt);
475 ff_err(ret, "FFStream::encode_frame: encode failed\n");
479 int FFStream::flush()
483 int ret = encode_frame(0);
485 ff_err(ret, "FFStream::flush");
486 return ret >= 0 ? 0 : 1;
489 int FFStream::seek(int64_t no, double rate)
491 int64_t tstmp = -INT64_MAX+1;
492 // default ffmpeg native seek
494 int64_t pos = no, pkt_pos = -1;
495 IndexMarks *index_markers = get_markers();
496 if( index_markers && index_markers->size() > 1 ) {
497 IndexMarks &marks = *index_markers;
498 int i = marks.find(pos);
499 int64_t n = i < 0 ? (i=0) : marks[i].no;
500 // if indexed seek point not too far away (<30 secs), use index
501 if( no-n < 30*rate ) {
504 if( i < marks.size() ) pkt_pos = marks[i].pos;
508 if( pos > 0 && st->time_base.num > 0 ) {
509 double secs = pos / rate;
510 tstmp = secs * st->time_base.den / st->time_base.num;
511 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
513 avcodec_flush_buffers(avctx);
514 avformat_flush(fmt_ctx);
516 int64_t seek = tstmp;
517 int flags = AVSEEK_FLAG_ANY;
518 if( !(fmt_ctx->iformat->flags & AVFMT_NO_BYTE_SEEK) && pkt_pos >= 0 ) {
520 flags = AVSEEK_FLAG_BYTE;
522 int ret = avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, seek, INT64_MAX, flags);
524 int ret = av_seek_frame(fmt_ctx, st->index, tstmp, AVSEEK_FLAG_ANY);
526 int retry = MAX_RETRY;
528 need_packet = 0; flushed = 0;
529 seeked = 1; st_eof(0);
530 // read up to retry packets, limited to npkts in stream, and not pkt.pos past pkt_pos
531 while( --retry >= 0 ) {
532 if( read_packet() <= 0 ) { ret = -1; break; }
533 if( ipkt->stream_index != st->index ) continue;
534 if( !ipkt->data || !ipkt->size ) continue;
535 if( pkt_pos >= 0 && ipkt->pos >= pkt_pos ) break;
536 if( --npkts <= 0 ) break;
537 int64_t pkt_ts = ipkt->dts != AV_NOPTS_VALUE ? ipkt->dts : ipkt->pts;
538 if( pkt_ts == AV_NOPTS_VALUE ) continue;
539 if( pkt_ts >= tstmp ) break;
542 fprintf(stderr,"FFStream::seek: retry limit, pos=%jd tstmp=%jd\n",pos,tstmp);
546 ret = avcodec_send_packet(avctx, ipkt);
548 //some codecs need more than one pkt to resync
549 if( ret == AVERROR_INVALIDDATA ) ret = 0;
551 ff_err(ret, "FFStream::avcodec_send_packet failed\n");
556 printf("** seek fail %ld, %ld\n", pos, tstmp);
557 seeked = need_packet = 0;
561 //printf("seeked pos = %ld, %ld\n", pos, tstmp);
562 seek_pos = curr_pos = pos;
566 FFAudioStream::FFAudioStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
567 : FFStream(ffmpeg, strm, fidx)
570 channel0 = channels = 0;
574 resample_context = 0;
575 swr_ichs = swr_ifmt = swr_irate = 0;
584 bfr = new float[bsz];
589 FFAudioStream::~FFAudioStream()
591 if( resample_context ) swr_free(&resample_context);
596 void FFAudioStream::init_swr(int ichs, int ifmt, int irate)
598 if( resample_context ) {
599 if( swr_ichs == ichs && swr_ifmt == ifmt && swr_irate == irate )
601 swr_free(&resample_context);
603 swr_ichs = ichs; swr_ifmt = ifmt; swr_irate = irate;
604 if( ichs == channels && ifmt == AV_SAMPLE_FMT_FLT && irate == sample_rate )
606 uint64_t ilayout = av_get_default_channel_layout(ichs);
607 if( !ilayout ) ilayout = ((uint64_t)1<<ichs) - 1;
608 uint64_t olayout = av_get_default_channel_layout(channels);
609 if( !olayout ) olayout = ((uint64_t)1<<channels) - 1;
610 resample_context = swr_alloc_set_opts(NULL,
611 olayout, AV_SAMPLE_FMT_FLT, sample_rate,
612 ilayout, (AVSampleFormat)ifmt, irate,
614 if( resample_context )
615 swr_init(resample_context);
618 int FFAudioStream::get_samples(float *&samples, uint8_t **data, int len)
620 samples = *(float **)data;
621 if( resample_context ) {
622 if( len > aud_bfr_sz ) {
628 aud_bfr = new float[aud_bfr_sz*channels];
630 int ret = swr_convert(resample_context,
631 (uint8_t**)&aud_bfr, aud_bfr_sz, (const uint8_t**)data, len);
633 ff_err(ret, "FFAudioStream::get_samples: swr_convert failed\n");
642 int FFAudioStream::load_history(uint8_t **data, int len)
645 len = get_samples(samples, data, len);
647 // biggest user bfr since seek + frame
648 realloc(mbsz + len + 1, channels);
654 int FFAudioStream::decode_frame(AVFrame *frame)
656 int first_frame = seeked; seeked = 0;
657 int ret = avcodec_receive_frame(avctx, frame);
659 if( first_frame || ret == AVERROR(EAGAIN) ) return 0;
660 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
661 ff_err(ret, "FFAudioStream::decode_frame: Could not read audio frame\n");
664 int64_t pkt_ts = av_frame_get_best_effort_timestamp(frame);
665 if( pkt_ts != AV_NOPTS_VALUE )
666 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * sample_rate + 0.5;
670 int FFAudioStream::encode_activate()
672 if( writing >= 0 ) return writing;
673 frame_sz = avctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE ?
674 10000 : avctx->frame_size;
675 return FFStream::encode_activate();
678 int64_t FFAudioStream::load_buffer(double ** const sp, int len)
680 reserve(len+1, st->codecpar->channels);
681 for( int ch=0; ch<nch; ++ch )
682 write(sp[ch], len, ch);
686 int FFAudioStream::in_history(int64_t pos)
688 if( pos > curr_pos ) return 0;
690 if( len > sz ) len = sz;
691 if( pos < curr_pos - len ) return 0;
696 int FFAudioStream::init_frame(AVFrame *frame)
698 frame->nb_samples = frame_sz;
699 frame->format = avctx->sample_fmt;
700 frame->channel_layout = avctx->channel_layout;
701 frame->sample_rate = avctx->sample_rate;
702 int ret = av_frame_get_buffer(frame, 0);
704 ff_err(ret, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
708 int FFAudioStream::load(int64_t pos, int len)
710 if( audio_seek(pos) < 0 ) return -1;
711 if( !frame && !(frame=av_frame_alloc()) ) {
712 fprintf(stderr, "FFAudioStream::load: av_frame_alloc failed\n");
715 if( mbsz < len ) mbsz = len;
716 int64_t end_pos = pos + len;
718 for( int i=0; ret>=0 && !flushed && curr_pos<end_pos && i<MAX_RETRY; ++i ) {
719 ret = read_frame(frame);
721 init_swr(frame->channels, frame->format, frame->sample_rate);
722 load_history(&frame->extended_data[0], frame->nb_samples);
723 curr_pos += frame->nb_samples;
726 if( end_pos > curr_pos ) {
727 zero(end_pos - curr_pos);
730 len = curr_pos - pos;
735 int FFAudioStream::audio_seek(int64_t pos)
737 if( decode_activate() <= 0 ) return -1;
738 if( !st->codecpar ) return -1;
739 if( in_history(pos) ) return 0;
740 if( pos == curr_pos ) return 0;
741 reset_history(); mbsz = 0;
742 // guarentee preload > 1sec samples
743 if( seek(pos-sample_rate, sample_rate) < 0 ) return -1;
747 int FFAudioStream::encode(double **samples, int len)
749 if( encode_activate() <= 0 ) return -1;
752 int64_t count = samples ? load_buffer(samples, len) : used();
753 int frame_sz1 = samples ? frame_sz-1 : 0;
756 while( ret >= 0 && count > frame_sz1 ) {
757 frm = new FFrame(this);
758 if( (ret=frm->initted()) < 0 ) break;
759 AVFrame *frame = *frm;
760 len = count >= frame_sz ? frame_sz : count;
761 float *bfrp = get_outp(len);
762 ret = swr_convert(resample_context,
763 (uint8_t **)frame->extended_data, len,
764 (const uint8_t **)&bfrp, len);
766 ff_err(ret, "FFAudioStream::encode: swr_convert failed\n");
769 frame->nb_samples = len;
770 frm->queue(curr_pos);
777 return ret >= 0 ? 0 : 1;
780 int FFAudioStream::drain()
785 int FFAudioStream::encode_frame(AVFrame *frame)
787 return FFStream::encode_frame(frame);
790 void FFAudioStream::load_markers()
792 IndexState *index_state = ffmpeg->file_base->asset->index_state;
793 if( !index_state || idx >= index_state->audio_markers.size() ) return;
794 if( index_state->marker_status == MARKERS_NOTTESTED ) return;
795 FFStream::load_markers(*index_state->audio_markers[idx], sample_rate);
798 IndexMarks *FFAudioStream::get_markers()
800 IndexState *index_state = ffmpeg->file_base->asset->index_state;
801 if( !index_state || idx >= index_state->audio_markers.size() ) return 0;
802 return index_state->audio_markers[idx];
805 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
806 : FFStream(ffmpeg, strm, fidx)
817 FFVideoStream::~FFVideoStream()
821 int FFVideoStream::decode_frame(AVFrame *frame)
823 int first_frame = seeked; seeked = 0;
824 int ret = avcodec_receive_frame(avctx, frame);
826 if( first_frame || ret == AVERROR(EAGAIN) ) return 0;
827 if( ret == AVERROR(EAGAIN) ) return 0;
828 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
829 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame\n");
832 int64_t pkt_ts = av_frame_get_best_effort_timestamp(frame);
833 if( pkt_ts != AV_NOPTS_VALUE )
834 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * frame_rate + 0.5;
838 int FFVideoStream::load(VFrame *vframe, int64_t pos)
840 int ret = video_seek(pos);
841 if( ret < 0 ) return -1;
842 if( !frame && !(frame=av_frame_alloc()) ) {
843 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
846 for( int i=0; ret>=0 && !flushed && curr_pos<=pos && i<MAX_RETRY; ++i ) {
847 ret = read_frame(frame);
848 if( ret > 0 ) ++curr_pos;
850 if( frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0 )
853 ret = convert_cmodel(vframe, frame);
855 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
859 int FFVideoStream::video_seek(int64_t pos)
861 if( decode_activate() <= 0 ) return -1;
862 if( !st->codecpar ) return -1;
863 if( pos == curr_pos-1 && !seeked ) return 0;
864 // if close enough, just read up to current
865 int gop = avctx->gop_size;
866 if( gop < 4 ) gop = 4;
867 if( gop > 64 ) gop = 64;
868 int read_limit = curr_pos + 3*gop;
869 if( pos >= curr_pos && pos <= read_limit ) return 0;
870 // guarentee preload more than 2*gop frames
871 if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
875 int FFVideoStream::init_frame(AVFrame *picture)
877 picture->format = avctx->pix_fmt;
878 picture->width = avctx->width;
879 picture->height = avctx->height;
880 int ret = av_frame_get_buffer(picture, 32);
884 int FFVideoStream::encode(VFrame *vframe)
886 if( encode_activate() <= 0 ) return -1;
888 FFrame *picture = new FFrame(this);
889 int ret = picture->initted();
891 AVFrame *frame = *picture;
892 frame->pts = curr_pos;
893 ret = convert_pixfmt(vframe, frame);
896 picture->queue(curr_pos);
900 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
903 return ret >= 0 ? 0 : 1;
906 int FFVideoStream::drain()
911 int FFVideoStream::encode_frame(AVFrame *frame)
914 frame->interlaced_frame = interlaced;
915 frame->top_field_first = top_field_first;
917 return FFStream::encode_frame(frame);
920 AVPixelFormat FFVideoConvert::color_model_to_pix_fmt(int color_model)
922 switch( color_model ) {
923 case BC_YUV422: return AV_PIX_FMT_YUYV422;
924 case BC_RGB888: return AV_PIX_FMT_RGB24;
925 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
926 case BC_BGR8888: return AV_PIX_FMT_BGR0;
927 case BC_BGR888: return AV_PIX_FMT_BGR24;
928 case BC_ARGB8888: return AV_PIX_FMT_ARGB;
929 case BC_ABGR8888: return AV_PIX_FMT_ABGR;
930 case BC_RGB8: return AV_PIX_FMT_RGB8;
931 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
932 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
933 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
934 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
935 case BC_RGB565: return AV_PIX_FMT_RGB565;
936 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
937 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
938 case BC_AYUV16161616: return AV_PIX_FMT_AYUV64LE;
942 return AV_PIX_FMT_NB;
945 int FFVideoConvert::pix_fmt_to_color_model(AVPixelFormat pix_fmt)
948 case AV_PIX_FMT_YUYV422: return BC_YUV422;
949 case AV_PIX_FMT_RGB24: return BC_RGB888;
950 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
951 case AV_PIX_FMT_BGR0: return BC_BGR8888;
952 case AV_PIX_FMT_BGR24: return BC_BGR888;
953 case AV_PIX_FMT_ARGB: return BC_ARGB8888;
954 case AV_PIX_FMT_ABGR: return BC_ABGR8888;
955 case AV_PIX_FMT_RGB8: return BC_RGB8;
956 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
957 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
958 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
959 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
960 case AV_PIX_FMT_RGB565: return BC_RGB565;
961 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
962 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
963 case AV_PIX_FMT_AYUV64LE: return BC_AYUV16161616;
970 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip)
972 AVFrame *ipic = av_frame_alloc();
973 int ret = convert_picture_vframe(frame, ip, ipic);
974 av_frame_free(&ipic);
978 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip, AVFrame *ipic)
980 int cmodel = frame->get_color_model();
981 AVPixelFormat ofmt = color_model_to_pix_fmt(cmodel);
982 if( ofmt == AV_PIX_FMT_NB ) return -1;
983 int size = av_image_fill_arrays(ipic->data, ipic->linesize,
984 frame->get_data(), ofmt, frame->get_w(), frame->get_h(), 1);
985 if( size < 0 ) return -1;
987 int bpp = BC_CModels::calculate_pixelsize(cmodel);
988 int ysz = bpp * frame->get_w(), usz = ysz;
997 // override av_image_fill_arrays() for planar types
998 ipic->data[0] = frame->get_y(); ipic->linesize[0] = ysz;
999 ipic->data[1] = frame->get_u(); ipic->linesize[1] = usz;
1000 ipic->data[2] = frame->get_v(); ipic->linesize[2] = usz;
1003 ipic->data[0] = frame->get_data();
1004 ipic->linesize[0] = frame->get_bytes_per_line();
1008 AVPixelFormat pix_fmt = (AVPixelFormat)ip->format;
1009 convert_ctx = sws_getCachedContext(convert_ctx, ip->width, ip->height, pix_fmt,
1010 frame->get_w(), frame->get_h(), ofmt, SWS_POINT, NULL, NULL, NULL);
1011 if( !convert_ctx ) {
1012 fprintf(stderr, "FFVideoConvert::convert_picture_frame:"
1013 " sws_getCachedContext() failed\n");
1016 int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ip->height,
1017 ipic->data, ipic->linesize);
1019 ff_err(ret, "FFVideoConvert::convert_picture_frame: sws_scale() failed\n");
1025 int FFVideoConvert::convert_cmodel(VFrame *frame, AVFrame *ip)
1027 // try direct transfer
1028 if( !convert_picture_vframe(frame, ip) ) return 1;
1029 // use indirect transfer
1030 AVPixelFormat ifmt = (AVPixelFormat)ip->format;
1031 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
1033 for( int i = 0; i <desc->nb_components; ++i ) {
1034 int bits = desc->comp[i].depth;
1035 if( bits > max_bits ) max_bits = bits;
1037 int imodel = pix_fmt_to_color_model(ifmt);
1038 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1039 int cmodel = frame->get_color_model();
1040 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1041 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1042 imodel = cmodel_is_yuv ?
1043 (BC_CModels::has_alpha(cmodel) ?
1045 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1046 (BC_CModels::has_alpha(cmodel) ?
1047 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1048 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1050 VFrame vframe(ip->width, ip->height, imodel);
1051 if( convert_picture_vframe(&vframe, ip) ) return -1;
1052 frame->transfer_from(&vframe);
1056 int FFVideoConvert::transfer_cmodel(VFrame *frame, AVFrame *ifp)
1058 int ret = convert_cmodel(frame, ifp);
1060 const AVDictionary *src = av_frame_get_metadata(ifp);
1061 AVDictionaryEntry *t = NULL;
1062 BC_Hash *hp = frame->get_params();
1064 while( (t=av_dict_get(src, "", t, AV_DICT_IGNORE_SUFFIX)) )
1065 hp->update(t->key, t->value);
1070 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op)
1072 AVFrame *opic = av_frame_alloc();
1073 int ret = convert_vframe_picture(frame, op, opic);
1074 av_frame_free(&opic);
1078 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op, AVFrame *opic)
1080 int cmodel = frame->get_color_model();
1081 AVPixelFormat ifmt = color_model_to_pix_fmt(cmodel);
1082 if( ifmt == AV_PIX_FMT_NB ) return -1;
1083 int size = av_image_fill_arrays(opic->data, opic->linesize,
1084 frame->get_data(), ifmt, frame->get_w(), frame->get_h(), 1);
1085 if( size < 0 ) return -1;
1087 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1088 int ysz = bpp * frame->get_w(), usz = ysz;
1097 // override av_image_fill_arrays() for planar types
1098 opic->data[0] = frame->get_y(); opic->linesize[0] = ysz;
1099 opic->data[1] = frame->get_u(); opic->linesize[1] = usz;
1100 opic->data[2] = frame->get_v(); opic->linesize[2] = usz;
1103 opic->data[0] = frame->get_data();
1104 opic->linesize[0] = frame->get_bytes_per_line();
1108 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1109 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(),
1110 ifmt, op->width, op->height, ofmt, SWS_POINT, NULL, NULL, NULL);
1111 if( !convert_ctx ) {
1112 fprintf(stderr, "FFVideoConvert::convert_frame_picture:"
1113 " sws_getCachedContext() failed\n");
1116 int ret = sws_scale(convert_ctx, opic->data, opic->linesize, 0, frame->get_h(),
1117 op->data, op->linesize);
1119 ff_err(ret, "FFVideoConvert::convert_frame_picture: sws_scale() failed\n");
1125 int FFVideoConvert::convert_pixfmt(VFrame *frame, AVFrame *op)
1127 // try direct transfer
1128 if( !convert_vframe_picture(frame, op) ) return 1;
1129 // use indirect transfer
1130 int cmodel = frame->get_color_model();
1131 int max_bits = BC_CModels::calculate_pixelsize(cmodel) * 8;
1132 max_bits /= BC_CModels::components(cmodel);
1133 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1134 int imodel = pix_fmt_to_color_model(ofmt);
1135 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1136 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1137 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1138 imodel = cmodel_is_yuv ?
1139 (BC_CModels::has_alpha(cmodel) ?
1141 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1142 (BC_CModels::has_alpha(cmodel) ?
1143 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1144 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1146 VFrame vframe(frame->get_w(), frame->get_h(), imodel);
1147 vframe.transfer_from(frame);
1148 if( !convert_vframe_picture(&vframe, op) ) return 1;
1152 int FFVideoConvert::transfer_pixfmt(VFrame *frame, AVFrame *ofp)
1154 int ret = convert_pixfmt(frame, ofp);
1156 BC_Hash *hp = frame->get_params();
1157 AVDictionary **dict = avpriv_frame_get_metadatap(ofp);
1158 //av_dict_free(dict);
1159 for( int i=0; i<hp->size(); ++i ) {
1160 char *key = hp->get_key(i), *val = hp->get_value(i);
1161 av_dict_set(dict, key, val, 0);
1167 void FFVideoStream::load_markers()
1169 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1170 if( !index_state || idx >= index_state->video_markers.size() ) return;
1171 FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
1174 IndexMarks *FFVideoStream::get_markers()
1176 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1177 if( !index_state || idx >= index_state->video_markers.size() ) return 0;
1178 return !index_state ? 0 : index_state->video_markers[idx];
1182 FFMPEG::FFMPEG(FileBase *file_base)
1185 this->file_base = file_base;
1186 memset(file_format,0,sizeof(file_format));
1187 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
1188 flow_lock = new Condition(1,"FFStream::flow_lock",0);
1191 decoding = encoding = 0;
1192 has_audio = has_video = 0;
1195 opt_video_filter = 0;
1196 opt_audio_filter = 0;
1197 char option_path[BCTEXTLEN];
1198 set_option_path(option_path, "%s", "ffmpeg.opts");
1199 read_options(option_path, opts);
1204 ff_lock("FFMPEG::~FFMPEG()");
1206 ffaudio.remove_all_objects();
1207 ffvideo.remove_all_objects();
1208 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1212 av_dict_free(&opts);
1213 delete [] opt_video_filter;
1214 delete [] opt_audio_filter;
1217 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1219 const int *p = codec->supported_samplerates;
1220 if( !p ) return sample_rate;
1222 if( *p == sample_rate ) return *p;
1228 static inline AVRational std_frame_rate(int i)
1230 static const int m1 = 1001*12, m2 = 1000*12;
1231 static const int freqs[] = {
1232 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1233 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
1235 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1236 return (AVRational) { freq, 1001*12 };
1239 AVRational FFMPEG::check_frame_rate(AVCodec *codec, double frame_rate)
1241 const AVRational *p = codec->supported_framerates;
1242 AVRational rate, best_rate = (AVRational) { 0, 0 };
1243 double max_err = 1.; int i = 0;
1244 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1245 double framerate = (double) rate.num / rate.den;
1246 double err = fabs(frame_rate/framerate - 1.);
1247 if( err >= max_err ) continue;
1251 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1254 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1257 double display_aspect = asset->width / (double)asset->height;
1258 double sample_aspect = display_aspect / asset->aspect_ratio;
1259 int width = 1000000, height = width * sample_aspect + 0.5;
1261 MWindow::create_aspect_ratio(w, h, width, height);
1262 return (AVRational){(int)w, (int)h};
1265 return (AVRational){1, 1};
1269 AVRational FFMPEG::to_time_base(int sample_rate)
1271 return (AVRational){1, sample_rate};
1274 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
1276 char *ep = path + BCTEXTLEN-1;
1277 strncpy(path, File::get_cindat_path(), ep-path);
1278 strncat(path, "/ffmpeg/", ep-path);
1279 path += strlen(path);
1282 path += vsnprintf(path, ep-path, fmt, ap);
1287 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
1292 set_option_path(path, "%s/%s", type, spec);
1295 int FFMPEG::get_format(char *format, const char *path, const char *spec)
1297 char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
1298 get_option_path(option_path, path, spec);
1299 FILE *fp = fopen(option_path,"r");
1302 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1304 line[sizeof(line)-1] = 0;
1305 ret = scan_option_line(line, format, codec);
1311 int FFMPEG::get_codec(char *codec, const char *path, const char *spec)
1313 char option_path[BCTEXTLEN], line[BCTEXTLEN], format[BCTEXTLEN];
1314 get_option_path(option_path, path, spec);
1315 FILE *fp = fopen(option_path,"r");
1318 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1321 line[sizeof(line)-1] = 0;
1322 ret = scan_option_line(line, format, codec);
1325 char *vp = codec, *ep = vp+BCTEXTLEN-1;
1326 while( vp < ep && *vp && *vp != '|' ) ++vp;
1327 if( *vp == '|' ) --vp;
1328 while( vp > codec && (*vp==' ' || *vp=='\t') ) *vp-- = 0;
1333 int FFMPEG::get_file_format()
1335 char audio_muxer[BCSTRLEN], video_muxer[BCSTRLEN];
1336 char audio_format[BCSTRLEN], video_format[BCSTRLEN];
1337 audio_muxer[0] = audio_format[0] = 0;
1338 video_muxer[0] = video_format[0] = 0;
1339 Asset *asset = file_base->asset;
1340 int ret = asset ? 0 : 1;
1341 if( !ret && asset->audio_data ) {
1342 if( !(ret=get_format(audio_format, "audio", asset->acodec)) ) {
1343 if( get_format(audio_muxer, "format", audio_format) ) {
1344 strcpy(audio_muxer, audio_format);
1345 audio_format[0] = 0;
1349 if( !ret && asset->video_data ) {
1350 if( !(ret=get_format(video_format, "video", asset->vcodec)) ) {
1351 if( get_format(video_muxer, "format", video_format) ) {
1352 strcpy(video_muxer, video_format);
1353 video_format[0] = 0;
1357 if( !ret && !audio_muxer[0] && !video_muxer[0] )
1359 if( !ret && audio_muxer[0] && video_muxer[0] &&
1360 strcmp(audio_muxer, video_muxer) ) ret = -1;
1361 if( !ret && audio_format[0] && video_format[0] &&
1362 strcmp(audio_format, video_format) ) ret = -1;
1364 strcpy(file_format, !audio_format[0] && !video_format[0] ?
1365 (audio_muxer[0] ? audio_muxer : video_muxer) :
1366 (audio_format[0] ? audio_format : video_format));
1370 int FFMPEG::scan_option_line(char *cp, char *tag, char *val)
1372 while( *cp == ' ' || *cp == '\t' ) ++cp;
1374 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' && *cp != '\n' ) ++cp;
1376 if( !len || len > BCSTRLEN-1 ) return 1;
1377 while( bp < cp ) *tag++ = *bp++;
1379 while( *cp == ' ' || *cp == '\t' ) ++cp;
1380 if( *cp == '=' ) ++cp;
1381 while( *cp == ' ' || *cp == '\t' ) ++cp;
1383 while( *cp && *cp != '\n' ) ++cp;
1385 if( len > BCTEXTLEN-1 ) return 1;
1386 while( bp < cp ) *val++ = *bp++;
1391 int FFMPEG::load_defaults(const char *path, const char *type,
1392 char *codec, char *codec_options, int len)
1394 char default_file[BCTEXTLEN];
1395 set_option_path(default_file, "%s/%s.dfl", path, type);
1396 FILE *fp = fopen(default_file,"r");
1398 fgets(codec, BCSTRLEN, fp);
1400 while( *cp && *cp!='\n' ) ++cp;
1402 while( len > 0 && fgets(codec_options, len, fp) ) {
1403 int n = strlen(codec_options);
1404 codec_options += n; len -= n;
1407 set_option_path(default_file, "%s/%s", path, codec);
1408 return load_options(default_file, codec_options, len);
1411 void FFMPEG::set_asset_format(Asset *asset, const char *text)
1413 if( asset->format != FILE_FFMPEG ) return;
1414 if( text != asset->fformat )
1415 strcpy(asset->fformat, text);
1416 if( !asset->ff_audio_options[0] ) {
1417 asset->audio_data = !load_defaults("audio", text, asset->acodec,
1418 asset->ff_audio_options, sizeof(asset->ff_audio_options));
1420 if( !asset->ff_video_options[0] ) {
1421 asset->video_data = !load_defaults("video", text, asset->vcodec,
1422 asset->ff_video_options, sizeof(asset->ff_video_options));
1426 int FFMPEG::get_encoder(const char *options,
1427 char *format, char *codec, char *bsfilter)
1429 FILE *fp = fopen(options,"r");
1431 eprintf(_("options open failed %s\n"),options);
1434 if( get_encoder(fp, format, codec, bsfilter) )
1435 eprintf(_("format/codec not found %s\n"), options);
1440 int FFMPEG::get_encoder(FILE *fp,
1441 char *format, char *codec, char *bsfilter)
1443 format[0] = codec[0] = bsfilter[0] = 0;
1444 char line[BCTEXTLEN];
1445 if( !fgets(line, sizeof(line), fp) ) return 1;
1446 line[sizeof(line)-1] = 0;
1447 if( scan_option_line(line, format, codec) ) return 1;
1449 while( *cp && *cp != '|' ) ++cp;
1450 if( !*cp ) return 0;
1452 do { *bp-- = 0; } while( bp>=codec && (*bp==' ' || *bp == '\t' ) );
1453 while( *++cp && (*cp==' ' || *cp == '\t') );
1455 for( int i=BCTEXTLEN; --i>0 && *cp; ) *bp++ = *cp++;
1460 int FFMPEG::read_options(const char *options, AVDictionary *&opts, int skip)
1462 FILE *fp = fopen(options,"r");
1465 while( !ret && --skip >= 0 ) {
1467 while( ch >= 0 && ch != '\n' ) ch = getc(fp);
1468 if( ch < 0 ) ret = 1;
1471 ret = read_options(fp, options, opts);
1476 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
1478 FILE *fp = fmemopen((void *)options,strlen(options),"r");
1480 int ret = read_options(fp, options, opts);
1482 AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
1483 if( tag ) st->id = strtol(tag->value,0,0);
1487 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
1489 int ret = 0, no = 0;
1490 char line[BCTEXTLEN];
1491 while( !ret && fgets(line, sizeof(line), fp) ) {
1492 line[sizeof(line)-1] = 0;
1493 if( line[0] == '#' ) continue;
1494 if( line[0] == '\n' ) continue;
1495 char key[BCSTRLEN], val[BCTEXTLEN];
1496 if( scan_option_line(line, key, val) ) {
1497 eprintf(_("err reading %s: line %d\n"), options, no);
1501 if( !strcmp(key, "duration") )
1502 opt_duration = strtod(val, 0);
1503 else if( !strcmp(key, "video_filter") )
1504 opt_video_filter = cstrdup(val);
1505 else if( !strcmp(key, "audio_filter") )
1506 opt_audio_filter = cstrdup(val);
1507 else if( !strcmp(key, "loglevel") )
1510 av_dict_set(&opts, key, val, 0);
1516 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
1518 char option_path[BCTEXTLEN];
1519 set_option_path(option_path, "%s", options);
1520 return read_options(option_path, opts);
1523 int FFMPEG::load_options(const char *path, char *bfr, int len)
1526 FILE *fp = fopen(path, "r");
1528 fgets(bfr, len, fp); // skip hdr
1529 len = fread(bfr, 1, len-1, fp);
1530 if( len < 0 ) len = 0;
1536 void FFMPEG::set_loglevel(const char *ap)
1538 if( !ap || !*ap ) return;
1543 { "quiet" , AV_LOG_QUIET },
1544 { "panic" , AV_LOG_PANIC },
1545 { "fatal" , AV_LOG_FATAL },
1546 { "error" , AV_LOG_ERROR },
1547 { "warning", AV_LOG_WARNING },
1548 { "info" , AV_LOG_INFO },
1549 { "verbose", AV_LOG_VERBOSE },
1550 { "debug" , AV_LOG_DEBUG },
1552 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
1553 if( !strcmp(log_levels[i].name, ap) ) {
1554 av_log_set_level(log_levels[i].level);
1558 av_log_set_level(atoi(ap));
1561 double FFMPEG::to_secs(int64_t time, AVRational time_base)
1563 double base_time = time == AV_NOPTS_VALUE ? 0 :
1564 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
1565 return base_time / AV_TIME_BASE;
1568 int FFMPEG::info(char *text, int len)
1570 if( len <= 0 ) return 0;
1572 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
1574 report("format: %s\n",fmt_ctx->iformat->name);
1575 if( ffvideo.size() > 0 )
1576 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
1577 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
1578 FFVideoStream *vid = ffvideo[vidx];
1579 AVStream *st = vid->st;
1580 AVCodecID codec_id = st->codecpar->codec_id;
1581 report(_("vid%d (%d), id 0x%06x:\n"), vid->idx, vid->fidx, codec_id);
1582 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
1583 report(" video%d %s", vidx+1, desc ? desc->name : " (unkn)");
1584 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
1585 AVPixelFormat pix_fmt = (AVPixelFormat)st->codecpar->format;
1586 const char *pfn = av_get_pix_fmt_name(pix_fmt);
1587 report(" pix %s\n", pfn ? pfn : "(unkn)");
1588 double secs = to_secs(st->duration, st->time_base);
1589 int64_t length = secs * vid->frame_rate + 0.5;
1590 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
1591 int64_t nudge = ofs * vid->frame_rate;
1592 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1593 report(" %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
1594 int hrs = secs/3600; secs -= hrs*3600;
1595 int mins = secs/60; secs -= mins*60;
1596 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1598 if( ffaudio.size() > 0 )
1599 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
1600 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
1601 FFAudioStream *aud = ffaudio[aidx];
1602 AVStream *st = aud->st;
1603 AVCodecID codec_id = st->codecpar->codec_id;
1604 report(_("aud%d (%d), id 0x%06x:\n"), aud->idx, aud->fidx, codec_id);
1605 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
1606 int nch = aud->channels, ch0 = aud->channel0+1;
1607 report(" audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
1608 AVSampleFormat sample_fmt = (AVSampleFormat)st->codecpar->format;
1609 const char *fmt = av_get_sample_fmt_name(sample_fmt);
1610 report(" %s %d", fmt, aud->sample_rate);
1611 int sample_bits = av_get_bits_per_sample(codec_id);
1612 report(" %dbits\n", sample_bits);
1613 double secs = to_secs(st->duration, st->time_base);
1614 int64_t length = secs * aud->sample_rate + 0.5;
1615 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
1616 int64_t nudge = ofs * aud->sample_rate;
1617 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1618 report(" %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
1619 int hrs = secs/3600; secs -= hrs*3600;
1620 int mins = secs/60; secs -= mins*60;
1621 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1623 if( fmt_ctx->nb_programs > 0 )
1624 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
1625 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
1626 report("program %d", i+1);
1627 AVProgram *pgrm = fmt_ctx->programs[i];
1628 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1629 int idx = pgrm->stream_index[j];
1630 int vidx = ffvideo.size();
1631 while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
1633 report(", vid%d", vidx);
1636 int aidx = ffaudio.size();
1637 while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
1639 report(", aud%d", aidx);
1642 report(", (%d)", pgrm->stream_index[j]);
1647 AVDictionaryEntry *tag = 0;
1648 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
1649 report("%s=%s\n", tag->key, tag->value);
1658 int FFMPEG::init_decoder(const char *filename)
1660 ff_lock("FFMPEG::init_decoder");
1662 char file_opts[BCTEXTLEN];
1663 char *bp = strrchr(strcpy(file_opts, filename), '/');
1664 char *sp = strrchr(!bp ? file_opts : bp, '.');
1667 strcpy(sp, ".opts");
1668 fp = fopen(file_opts, "r");
1671 read_options(fp, file_opts, opts);
1675 load_options("decode.opts", opts);
1676 AVDictionary *fopts = 0;
1677 av_dict_copy(&fopts, opts, 0);
1678 int ret = avformat_open_input(&fmt_ctx, filename, NULL, &fopts);
1679 av_dict_free(&fopts);
1681 ret = avformat_find_stream_info(fmt_ctx, NULL);
1686 return !ret ? 0 : 1;
1689 int FFMPEG::open_decoder()
1692 if( stat(fmt_ctx->filename, &st) < 0 ) {
1693 eprintf(_("can't stat file: %s\n"), fmt_ctx->filename);
1697 int64_t file_bits = 8 * st.st_size;
1698 if( !fmt_ctx->bit_rate && opt_duration > 0 )
1699 fmt_ctx->bit_rate = file_bits / opt_duration;
1702 if( fmt_ctx->bit_rate > 0 ) {
1703 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1704 AVStream *st = fmt_ctx->streams[i];
1705 if( st->duration != AV_NOPTS_VALUE ) continue;
1706 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
1707 st->duration = av_rescale(file_bits, st->time_base.den,
1708 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
1713 printf("FFMPEG::open_decoder: some stream times estimated\n");
1715 ff_lock("FFMPEG::open_decoder");
1716 int ret = 0, bad_time = 0;
1717 for( int i=0; !ret && i<(int)fmt_ctx->nb_streams; ++i ) {
1718 AVStream *st = fmt_ctx->streams[i];
1719 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
1720 AVCodecParameters *avpar = st->codecpar;
1721 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avpar->codec_id);
1722 if( !codec_desc ) continue;
1723 switch( avpar->codec_type ) {
1724 case AVMEDIA_TYPE_VIDEO: {
1725 if( avpar->width < 1 ) continue;
1726 if( avpar->height < 1 ) continue;
1727 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
1728 if( framerate.num < 1 ) continue;
1730 int vidx = ffvideo.size();
1731 FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
1732 vstrm_index.append(ffidx(vidx, 0));
1733 ffvideo.append(vid);
1734 vid->width = avpar->width;
1735 vid->height = avpar->height;
1736 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
1737 double secs = to_secs(st->duration, st->time_base);
1738 vid->length = secs * vid->frame_rate;
1739 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
1740 vid->nudge = st->start_time;
1742 if( opt_video_filter )
1743 ret = vid->create_filter(opt_video_filter, avpar);
1745 case AVMEDIA_TYPE_AUDIO: {
1746 if( avpar->channels < 1 ) continue;
1747 if( avpar->sample_rate < 1 ) continue;
1749 int aidx = ffaudio.size();
1750 FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
1751 ffaudio.append(aud);
1752 aud->channel0 = astrm_index.size();
1753 aud->channels = avpar->channels;
1754 for( int ch=0; ch<aud->channels; ++ch )
1755 astrm_index.append(ffidx(aidx, ch));
1756 aud->sample_rate = avpar->sample_rate;
1757 double secs = to_secs(st->duration, st->time_base);
1758 aud->length = secs * aud->sample_rate;
1759 aud->init_swr(aud->channels, avpar->format, aud->sample_rate);
1760 aud->nudge = st->start_time;
1762 if( opt_audio_filter )
1763 ret = aud->create_filter(opt_audio_filter, avpar);
1769 printf("FFMPEG::open_decoder: some stream have bad times\n");
1771 return ret < 0 ? -1 : 0;
1775 int FFMPEG::init_encoder(const char *filename)
1777 int fd = ::open(filename,O_WRONLY);
1778 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
1780 eprintf(_("bad file path: %s\n"), filename);
1784 int ret = get_file_format();
1786 eprintf(_("bad file format: %s\n"), filename);
1790 eprintf(_("mismatch audio/video file format: %s\n"), filename);
1793 ff_lock("FFMPEG::init_encoder");
1795 char format[BCSTRLEN];
1796 if( get_format(format, "format", file_format) )
1797 strcpy(format, file_format);
1798 avformat_alloc_output_context2(&fmt_ctx, 0, format, filename);
1800 eprintf(_("failed: %s\n"), filename);
1805 load_options("encode.opts", opts);
1811 int FFMPEG::open_encoder(const char *type, const char *spec)
1814 Asset *asset = file_base->asset;
1815 char *filename = asset->path;
1816 AVDictionary *sopts = 0;
1817 av_dict_copy(&sopts, opts, 0);
1818 char option_path[BCTEXTLEN];
1819 set_option_path(option_path, "%s/%s.opts", type, type);
1820 read_options(option_path, sopts);
1821 get_option_path(option_path, type, spec);
1822 char format_name[BCSTRLEN], codec_name[BCTEXTLEN], bsfilter[BCTEXTLEN];
1823 if( get_encoder(option_path, format_name, codec_name, bsfilter) ) {
1824 eprintf(_("get_encoder failed %s:%s\n"), option_path, filename);
1828 if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
1829 else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
1830 else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
1833 ff_lock("FFMPEG::open_encoder");
1836 AVCodecContext *ctx = 0;
1838 const AVCodecDescriptor *codec_desc = 0;
1839 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
1841 eprintf(_("cant find codec %s:%s\n"), codec_name, filename);
1845 codec_desc = avcodec_descriptor_get(codec->id);
1847 eprintf(_("unknown codec %s:%s\n"), codec_name, filename);
1852 st = avformat_new_stream(fmt_ctx, 0);
1854 eprintf(_("cant create stream %s:%s\n"), codec_name, filename);
1859 switch( codec_desc->type ) {
1860 case AVMEDIA_TYPE_AUDIO: {
1862 eprintf(_("duplicate audio %s:%s\n"), codec_name, filename);
1866 if( scan_options(asset->ff_audio_options, sopts, st) ) {
1867 eprintf(_("bad audio options %s:%s\n"), codec_name, filename);
1872 ctx = avcodec_alloc_context3(codec);
1873 if( asset->ff_audio_bitrate > 0 ) {
1874 ctx->bit_rate = asset->ff_audio_bitrate;
1876 sprintf(arg, "%d", asset->ff_audio_bitrate);
1877 av_dict_set(&sopts, "b", arg, 0);
1879 int aidx = ffaudio.size();
1880 int fidx = aidx + ffvideo.size();
1881 FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
1882 aud->avctx = ctx; ffaudio.append(aud); fst = aud;
1883 aud->sample_rate = asset->sample_rate;
1884 ctx->channels = aud->channels = asset->channels;
1885 for( int ch=0; ch<aud->channels; ++ch )
1886 astrm_index.append(ffidx(aidx, ch));
1887 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
1888 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
1889 if( !ctx->sample_rate ) {
1890 eprintf(_("check_sample_rate failed %s\n"), filename);
1894 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
1895 ctx->sample_fmt = codec->sample_fmts[0];
1896 uint64_t layout = av_get_default_channel_layout(ctx->channels);
1897 aud->resample_context = swr_alloc_set_opts(NULL,
1898 layout, ctx->sample_fmt, aud->sample_rate,
1899 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
1901 swr_init(aud->resample_context);
1904 case AVMEDIA_TYPE_VIDEO: {
1906 eprintf(_("duplicate video %s:%s\n"), codec_name, filename);
1910 if( scan_options(asset->ff_video_options, sopts, st) ) {
1911 eprintf(_("bad video options %s:%s\n"), codec_name, filename);
1916 ctx = avcodec_alloc_context3(codec);
1917 if( asset->ff_video_bitrate > 0 ) {
1918 ctx->bit_rate = asset->ff_video_bitrate;
1920 sprintf(arg, "%d", asset->ff_video_bitrate);
1921 av_dict_set(&sopts, "b", arg, 0);
1923 else if( asset->ff_video_quality >= 0 ) {
1924 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
1925 ctx->qmin = ctx->qmax = asset->ff_video_quality;
1926 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
1927 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
1928 ctx->flags |= CODEC_FLAG_QSCALE;
1930 av_dict_set(&sopts, "flags", "+qscale", 0);
1931 sprintf(arg, "%d", asset->ff_video_quality);
1932 av_dict_set(&sopts, "qscale", arg, 0);
1933 sprintf(arg, "%d", ctx->global_quality);
1934 av_dict_set(&sopts, "global_quality", arg, 0);
1936 int vidx = ffvideo.size();
1937 int fidx = vidx + ffaudio.size();
1938 FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
1939 vstrm_index.append(ffidx(vidx, 0));
1940 vid->avctx = ctx; ffvideo.append(vid); fst = vid;
1941 vid->width = asset->width;
1942 ctx->width = (vid->width+3) & ~3;
1943 vid->height = asset->height;
1944 ctx->height = (vid->height+3) & ~3;
1945 vid->frame_rate = asset->frame_rate;
1946 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
1947 ctx->pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
1948 AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
1949 if( !frame_rate.num || !frame_rate.den ) {
1950 eprintf(_("check_frame_rate failed %s\n"), filename);
1954 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
1955 st->time_base = ctx->time_base;
1957 vid->interlaced = asset->interlace_mode == ILACE_MODE_TOP_FIRST ||
1958 asset->interlace_mode == ILACE_MODE_BOTTOM_FIRST ? 1 : 0;
1959 vid->top_field_first = asset->interlace_mode == ILACE_MODE_TOP_FIRST ? 1 : 0;
1962 eprintf(_("not audio/video, %s:%s\n"), codec_name, filename);
1967 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
1968 ctx->flags |= CODEC_FLAG_GLOBAL_HEADER;
1970 av_dict_set(&sopts, "cin_bitrate", 0, 0);
1971 av_dict_set(&sopts, "cin_quality", 0, 0);
1973 ret = avcodec_open2(ctx, codec, &sopts);
1975 ret = avcodec_parameters_from_context(st->codecpar, ctx);
1977 fprintf(stderr, "Could not copy the stream parameters\n");
1980 ff_err(ret,"FFMPEG::open_encoder");
1981 eprintf(_("open failed %s:%s\n"), codec_name, filename);
1987 if( !ret && fst && bsfilter[0] ) {
1988 ret = av_bsf_list_parse_str(bsfilter, &fst->bsfc);
1990 ff_err(ret,"FFMPEG::open_encoder");
1991 eprintf(_("bitstream filter failed %s:\n%s\n"), filename, bsfilter);
2002 av_dict_free(&sopts);
2006 int FFMPEG::close_encoder()
2009 if( encoding > 0 ) {
2010 av_write_trailer(fmt_ctx);
2011 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
2012 avio_closep(&fmt_ctx->pb);
2018 int FFMPEG::decode_activate()
2020 if( decoding < 0 ) {
2022 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
2023 ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
2024 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
2025 ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
2026 // set nudges for each program stream set
2027 const int64_t min_nudge = INT64_MIN+1;
2028 int npgrms = fmt_ctx->nb_programs;
2029 for( int i=0; i<npgrms; ++i ) {
2030 AVProgram *pgrm = fmt_ctx->programs[i];
2031 // first start time video stream
2032 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2033 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2034 int fidx = pgrm->stream_index[j];
2035 AVStream *st = fmt_ctx->streams[fidx];
2036 AVCodecParameters *avpar = st->codecpar;
2037 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2038 if( st->start_time == AV_NOPTS_VALUE ) continue;
2039 if( vstart_time < st->start_time )
2040 vstart_time = st->start_time;
2043 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2044 if( st->start_time == AV_NOPTS_VALUE ) continue;
2045 if( astart_time < st->start_time )
2046 astart_time = st->start_time;
2050 //since frame rate is much more grainy than sample rate, it is better to
2051 // align using video, so that total absolute error is minimized.
2052 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2053 astart_time > min_nudge ? astart_time : AV_NOPTS_VALUE;
2054 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2055 int fidx = pgrm->stream_index[j];
2056 AVStream *st = fmt_ctx->streams[fidx];
2057 AVCodecParameters *avpar = st->codecpar;
2058 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2059 for( int k=0; k<ffvideo.size(); ++k ) {
2060 if( ffvideo[k]->fidx != fidx ) continue;
2061 ffvideo[k]->nudge = nudge;
2065 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2066 for( int k=0; k<ffaudio.size(); ++k ) {
2067 if( ffaudio[k]->fidx != fidx ) continue;
2068 ffaudio[k]->nudge = nudge;
2074 // set nudges for any streams not yet set
2075 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2076 int nstreams = fmt_ctx->nb_streams;
2077 for( int i=0; i<nstreams; ++i ) {
2078 AVStream *st = fmt_ctx->streams[i];
2079 AVCodecParameters *avpar = st->codecpar;
2080 switch( avpar->codec_type ) {
2081 case AVMEDIA_TYPE_VIDEO: {
2082 if( st->start_time == AV_NOPTS_VALUE ) continue;
2083 int vidx = ffvideo.size();
2084 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
2085 if( vidx >= 0 && ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
2086 if( vstart_time < st->start_time )
2087 vstart_time = st->start_time;
2089 case AVMEDIA_TYPE_AUDIO: {
2090 if( st->start_time == AV_NOPTS_VALUE ) continue;
2091 int aidx = ffaudio.size();
2092 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
2093 if( aidx >= 0 && ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
2094 if( astart_time < st->start_time )
2095 astart_time = st->start_time;
2100 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2101 astart_time > min_nudge ? astart_time : 0;
2102 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
2103 if( ffvideo[vidx]->nudge == AV_NOPTS_VALUE )
2104 ffvideo[vidx]->nudge = nudge;
2106 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2107 if( ffaudio[aidx]->nudge == AV_NOPTS_VALUE )
2108 ffaudio[aidx]->nudge = nudge;
2115 int FFMPEG::encode_activate()
2118 if( encoding < 0 ) {
2120 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
2121 (ret=avio_open(&fmt_ctx->pb, fmt_ctx->filename, AVIO_FLAG_WRITE)) < 0 ) {
2122 ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
2128 AVProgram *prog = av_new_program(fmt_ctx, prog_id);
2129 for( int i=0; i< ffvideo.size(); ++i )
2130 av_program_add_stream_index(fmt_ctx, prog_id, ffvideo[i]->fidx);
2131 for( int i=0; i< ffaudio.size(); ++i )
2132 av_program_add_stream_index(fmt_ctx, prog_id, ffaudio[i]->fidx);
2133 int pi = fmt_ctx->nb_programs;
2134 while( --pi >= 0 && fmt_ctx->programs[pi]->id != prog_id );
2135 AVDictionary **meta = &prog->metadata;
2136 av_dict_set(meta, "service_provider", "cin5", 0);
2137 const char *path = fmt_ctx->filename, *bp = strrchr(path,'/');
2138 if( bp ) path = bp + 1;
2139 av_dict_set(meta, "title", path, 0);
2141 if( ffaudio.size() ) {
2142 const char *ep = getenv("CIN_AUDIO_LANG"), *lp = 0;
2143 if( !ep && (lp=getenv("LANG")) ) { // some are guesses
2144 static struct { const char lc[3], lng[4]; } lcode[] = {
2145 { "en", "eng" }, { "de", "ger" }, { "es", "spa" },
2146 { "eu", "bas" }, { "fr", "fre" }, { "el", "gre" },
2147 { "hi", "hin" }, { "it", "ita" }, { "ja", "jap" },
2148 { "ko", "kor" }, { "du", "dut" }, { "pl", "pol" },
2149 { "pt", "por" }, { "ru", "rus" }, { "sl", "slv" },
2150 { "uk", "ukr" }, { "vi", "vie" }, { "zh", "chi" },
2152 for( int i=sizeof(lcode)/sizeof(lcode[0]); --i>=0 && !ep; )
2153 if( !strncmp(lcode[i].lc,lp,2) ) ep = lcode[i].lng;
2155 if( !ep ) ep = "und";
2157 strncpy(lang,ep,3); lang[3] = 0;
2158 AVStream *st = ffaudio[0]->st;
2159 av_dict_set(&st->metadata,"language",lang,0);
2162 AVDictionary *fopts = 0;
2163 char option_path[BCTEXTLEN];
2164 set_option_path(option_path, "format/%s", file_format);
2165 read_options(option_path, fopts, 1);
2166 ret = avformat_write_header(fmt_ctx, &fopts);
2168 ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
2172 av_dict_free(&fopts);
2179 int FFMPEG::audio_seek(int stream, int64_t pos)
2181 int aidx = astrm_index[stream].st_idx;
2182 FFAudioStream *aud = ffaudio[aidx];
2183 aud->audio_seek(pos);
2187 int FFMPEG::video_seek(int stream, int64_t pos)
2189 int vidx = vstrm_index[stream].st_idx;
2190 FFVideoStream *vid = ffvideo[vidx];
2191 vid->video_seek(pos);
2196 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
2198 if( !has_audio || chn >= astrm_index.size() ) return -1;
2199 int aidx = astrm_index[chn].st_idx;
2200 FFAudioStream *aud = ffaudio[aidx];
2201 if( aud->load(pos, len) < len ) return -1;
2202 int ch = astrm_index[chn].st_ch;
2203 int ret = aud->read(samples,len,ch);
2207 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
2209 if( !has_video || layer >= vstrm_index.size() ) return -1;
2210 int vidx = vstrm_index[layer].st_idx;
2211 FFVideoStream *vid = ffvideo[vidx];
2212 return vid->load(vframe, pos);
2216 int FFMPEG::encode(int stream, double **samples, int len)
2218 FFAudioStream *aud = ffaudio[stream];
2219 return aud->encode(samples, len);
2223 int FFMPEG::encode(int stream, VFrame *frame)
2225 FFVideoStream *vid = ffvideo[stream];
2226 return vid->encode(frame);
2229 void FFMPEG::start_muxer()
2237 void FFMPEG::stop_muxer()
2246 void FFMPEG::flow_off()
2249 flow_lock->lock("FFMPEG::flow_off");
2253 void FFMPEG::flow_on()
2257 flow_lock->unlock();
2260 void FFMPEG::flow_ctl()
2263 flow_lock->lock("FFMPEG::flow_ctl");
2264 flow_lock->unlock();
2268 int FFMPEG::mux_audio(FFrame *frm)
2270 FFStream *fst = frm->fst;
2271 AVCodecContext *ctx = fst->avctx;
2272 AVFrame *frame = *frm;
2273 AVRational tick_rate = {1, ctx->sample_rate};
2274 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
2275 int ret = fst->encode_frame(frame);
2277 ff_err(ret, "FFMPEG::mux_audio");
2278 return ret >= 0 ? 0 : 1;
2281 int FFMPEG::mux_video(FFrame *frm)
2283 FFStream *fst = frm->fst;
2284 AVFrame *frame = *frm;
2285 frame->pts = frm->position;
2286 int ret = fst->encode_frame(frame);
2288 ff_err(ret, "FFMPEG::mux_video");
2289 return ret >= 0 ? 0 : 1;
2295 double atm = -1, vtm = -1;
2296 FFrame *afrm = 0, *vfrm = 0;
2298 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
2299 FFStream *fst = ffaudio[i];
2300 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
2301 FFrame *frm = fst->frms.first;
2302 if( !frm ) { if( !done ) return; continue; }
2303 double tm = to_secs(frm->position, fst->avctx->time_base);
2304 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
2306 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
2307 FFStream *fst = ffvideo[i];
2308 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
2309 FFrame *frm = fst->frms.first;
2310 if( !frm ) { if( !done ) return; continue; }
2311 double tm = to_secs(frm->position, fst->avctx->time_base);
2312 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
2314 if( !demand ) flow_off();
2315 if( !afrm && !vfrm ) break;
2316 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
2317 vfrm->position, vfrm->fst->avctx->time_base,
2318 afrm->position, afrm->fst->avctx->time_base);
2319 FFrame *frm = v <= 0 ? vfrm : afrm;
2320 if( frm == afrm ) mux_audio(frm);
2321 if( frm == vfrm ) mux_video(frm);
2330 mux_lock->lock("FFMPEG::run");
2333 for( int i=0; i<ffaudio.size(); ++i )
2334 ffaudio[i]->drain();
2335 for( int i=0; i<ffvideo.size(); ++i )
2336 ffvideo[i]->drain();
2338 for( int i=0; i<ffaudio.size(); ++i )
2339 ffaudio[i]->flush();
2340 for( int i=0; i<ffvideo.size(); ++i )
2341 ffvideo[i]->flush();
2345 int FFMPEG::ff_total_audio_channels()
2347 return astrm_index.size();
2350 int FFMPEG::ff_total_astreams()
2352 return ffaudio.size();
2355 int FFMPEG::ff_audio_channels(int stream)
2357 return ffaudio[stream]->channels;
2360 int FFMPEG::ff_sample_rate(int stream)
2362 return ffaudio[stream]->sample_rate;
2365 const char* FFMPEG::ff_audio_format(int stream)
2367 AVStream *st = ffaudio[stream]->st;
2368 AVCodecID id = st->codecpar->codec_id;
2369 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2370 return desc ? desc->name : _("Unknown");
2373 int FFMPEG::ff_audio_pid(int stream)
2375 return ffaudio[stream]->st->id;
2378 int64_t FFMPEG::ff_audio_samples(int stream)
2380 return ffaudio[stream]->length;
2383 // find audio astream/channels with this program,
2384 // or all program audio channels (astream=-1)
2385 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
2389 int vidx = ffvideo[vstream]->fidx;
2390 // find first program with this video stream
2391 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
2392 AVProgram *pgrm = fmt_ctx->programs[i];
2393 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
2394 int st_idx = pgrm->stream_index[j];
2395 AVStream *st = fmt_ctx->streams[st_idx];
2396 if( st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
2397 if( st_idx == vidx ) pidx = i;
2400 if( pidx < 0 ) return -1;
2402 int64_t channels = 0;
2403 AVProgram *pgrm = fmt_ctx->programs[pidx];
2404 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2405 int aidx = pgrm->stream_index[j];
2406 AVStream *st = fmt_ctx->streams[aidx];
2407 if( st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
2408 if( astream > 0 ) { --astream; continue; }
2410 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
2411 if( ffaudio[i]->fidx == aidx ) astrm = i;
2413 if( ret < 0 ) ret = astrm;
2414 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
2415 channels |= mask << ffaudio[astrm]->channel0;
2417 if( !astream ) break;
2419 channel_mask = channels;
2424 int FFMPEG::ff_total_video_layers()
2426 return vstrm_index.size();
2429 int FFMPEG::ff_total_vstreams()
2431 return ffvideo.size();
2434 int FFMPEG::ff_video_width(int stream)
2436 return ffvideo[stream]->width;
2439 int FFMPEG::ff_video_height(int stream)
2441 return ffvideo[stream]->height;
2444 int FFMPEG::ff_set_video_width(int stream, int width)
2446 int w = ffvideo[stream]->width;
2447 ffvideo[stream]->width = width;
2451 int FFMPEG::ff_set_video_height(int stream, int height)
2453 int h = ffvideo[stream]->height;
2454 ffvideo[stream]->height = height;
2458 int FFMPEG::ff_coded_width(int stream)
2460 return ffvideo[stream]->avctx->coded_width;
2463 int FFMPEG::ff_coded_height(int stream)
2465 return ffvideo[stream]->avctx->coded_height;
2468 float FFMPEG::ff_aspect_ratio(int stream)
2470 return ffvideo[stream]->aspect_ratio;
2473 const char* FFMPEG::ff_video_format(int stream)
2475 AVStream *st = ffvideo[stream]->st;
2476 AVCodecID id = st->codecpar->codec_id;
2477 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2478 return desc ? desc->name : _("Unknown");
2481 double FFMPEG::ff_frame_rate(int stream)
2483 return ffvideo[stream]->frame_rate;
2486 int64_t FFMPEG::ff_video_frames(int stream)
2488 return ffvideo[stream]->length;
2491 int FFMPEG::ff_video_pid(int stream)
2493 return ffvideo[stream]->st->id;
2497 int FFMPEG::ff_cpus()
2499 return file_base->file->cpus;
2502 int FFVideoStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
2504 avfilter_register_all();
2505 const char *sp = filter_spec;
2506 char filter_name[BCSTRLEN], *np = filter_name;
2507 int i = sizeof(filter_name);
2508 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
2510 AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
2511 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_VIDEO ) {
2512 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
2515 filter_graph = avfilter_graph_alloc();
2516 AVFilter *buffersrc = avfilter_get_by_name("buffer");
2517 AVFilter *buffersink = avfilter_get_by_name("buffersink");
2519 int ret = 0; char args[BCTEXTLEN];
2520 AVPixelFormat pix_fmt = (AVPixelFormat)avpar->format;
2521 snprintf(args, sizeof(args),
2522 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
2523 avpar->width, avpar->height, (int)pix_fmt,
2524 st->time_base.num, st->time_base.den,
2525 avpar->sample_aspect_ratio.num, avpar->sample_aspect_ratio.den);
2527 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2528 args, NULL, filter_graph);
2530 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2531 NULL, NULL, filter_graph);
2533 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
2534 (uint8_t*)&pix_fmt, sizeof(pix_fmt),
2535 AV_OPT_SEARCH_CHILDREN);
2537 ff_err(ret, "FFVideoStream::create_filter");
2539 ret = FFStream::create_filter(filter_spec);
2540 return ret >= 0 ? 0 : -1;
2543 int FFAudioStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
2545 avfilter_register_all();
2546 const char *sp = filter_spec;
2547 char filter_name[BCSTRLEN], *np = filter_name;
2548 int i = sizeof(filter_name);
2549 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
2551 AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
2552 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_AUDIO ) {
2553 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
2556 filter_graph = avfilter_graph_alloc();
2557 AVFilter *buffersrc = avfilter_get_by_name("abuffer");
2558 AVFilter *buffersink = avfilter_get_by_name("abuffersink");
2559 int ret = 0; char args[BCTEXTLEN];
2560 AVSampleFormat sample_fmt = (AVSampleFormat)avpar->format;
2561 snprintf(args, sizeof(args),
2562 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
2563 st->time_base.num, st->time_base.den, avpar->sample_rate,
2564 av_get_sample_fmt_name(sample_fmt), avpar->channel_layout);
2566 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2567 args, NULL, filter_graph);
2569 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2570 NULL, NULL, filter_graph);
2572 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
2573 (uint8_t*)&sample_fmt, sizeof(sample_fmt),
2574 AV_OPT_SEARCH_CHILDREN);
2576 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
2577 (uint8_t*)&avpar->channel_layout,
2578 sizeof(avpar->channel_layout), AV_OPT_SEARCH_CHILDREN);
2580 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
2581 (uint8_t*)&sample_rate, sizeof(sample_rate),
2582 AV_OPT_SEARCH_CHILDREN);
2584 ff_err(ret, "FFAudioStream::create_filter");
2586 ret = FFStream::create_filter(filter_spec);
2587 return ret >= 0 ? 0 : -1;
2590 int FFStream::create_filter(const char *filter_spec)
2592 /* Endpoints for the filter graph. */
2593 AVFilterInOut *outputs = avfilter_inout_alloc();
2594 outputs->name = av_strdup("in");
2595 outputs->filter_ctx = buffersrc_ctx;
2596 outputs->pad_idx = 0;
2599 AVFilterInOut *inputs = avfilter_inout_alloc();
2600 inputs->name = av_strdup("out");
2601 inputs->filter_ctx = buffersink_ctx;
2602 inputs->pad_idx = 0;
2605 int ret = !outputs->name || !inputs->name ? -1 : 0;
2607 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
2608 &inputs, &outputs, NULL);
2610 ret = avfilter_graph_config(filter_graph, NULL);
2613 ff_err(ret, "FFStream::create_filter");
2614 avfilter_graph_free(&filter_graph);
2617 avfilter_inout_free(&inputs);
2618 avfilter_inout_free(&outputs);
2622 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
2625 av_init_packet(&pkt);
2626 AVFrame *frame = av_frame_alloc();
2628 fprintf(stderr,"FFMPEG::scan: ");
2629 fprintf(stderr,_("av_frame_alloc failed\n"));
2633 index_state->add_video_markers(ffvideo.size());
2634 index_state->add_audio_markers(ffaudio.size());
2636 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2638 AVDictionary *copts = 0;
2639 av_dict_copy(&copts, opts, 0);
2640 AVStream *st = fmt_ctx->streams[i];
2641 AVCodecID codec_id = st->codecpar->codec_id;
2642 AVCodec *decoder = avcodec_find_decoder(codec_id);
2643 AVCodecContext *avctx = avcodec_alloc_context3(decoder);
2645 eprintf(_("cant allocate codec context\n"));
2646 ret = AVERROR(ENOMEM);
2649 avcodec_parameters_to_context(avctx, st->codecpar);
2650 ret = avcodec_open2(avctx, decoder, &copts);
2652 av_dict_free(&copts);
2654 AVCodecParameters *avpar = st->codecpar;
2655 switch( avpar->codec_type ) {
2656 case AVMEDIA_TYPE_VIDEO: {
2657 int vidx = ffvideo.size();
2658 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
2659 if( vidx < 0 ) break;
2660 ffvideo[vidx]->avctx = avctx;
2662 case AVMEDIA_TYPE_AUDIO: {
2663 int aidx = ffaudio.size();
2664 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
2665 if( aidx < 0 ) break;
2666 ffaudio[aidx]->avctx = avctx;
2671 fprintf(stderr,"FFMPEG::scan: ");
2672 fprintf(stderr,_("codec open failed\n"));
2673 avcodec_free_context(&avctx);
2677 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2678 AVStream *st = fmt_ctx->streams[i];
2679 AVCodecParameters *avpar = st->codecpar;
2680 if( avpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
2681 int64_t tstmp = st->start_time;
2682 if( tstmp == AV_NOPTS_VALUE ) continue;
2683 int aidx = ffaudio.size();
2684 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
2685 if( aidx < 0 ) continue;
2686 FFAudioStream *aud = ffaudio[aidx];
2687 tstmp -= aud->nudge;
2688 double secs = to_secs(tstmp, st->time_base);
2689 aud->curr_pos = secs * aud->sample_rate + 0.5;
2693 for( int64_t count=0; !*canceled; ++count ) {
2694 av_packet_unref(&pkt);
2695 pkt.data = 0; pkt.size = 0;
2697 int ret = av_read_frame(fmt_ctx, &pkt);
2699 if( ret == AVERROR_EOF ) break;
2700 if( ++errs > 100 ) {
2701 ff_err(ret,_("over 100 read_frame errs\n"));
2706 if( !pkt.data ) continue;
2707 int i = pkt.stream_index;
2708 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
2709 AVStream *st = fmt_ctx->streams[i];
2710 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
2712 AVCodecParameters *avpar = st->codecpar;
2713 switch( avpar->codec_type ) {
2714 case AVMEDIA_TYPE_VIDEO: {
2715 int vidx = ffvideo.size();
2716 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
2717 if( vidx < 0 ) break;
2718 FFVideoStream *vid = ffvideo[vidx];
2719 if( !vid->avctx ) break;
2720 int64_t tstmp = pkt.dts;
2721 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.pts;
2722 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
2723 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
2724 double secs = to_secs(tstmp, st->time_base);
2725 int64_t frm = secs * vid->frame_rate + 0.5;
2726 if( frm < 0 ) frm = 0;
2727 index_state->put_video_mark(vidx, frm, pkt.pos);
2730 ret = avcodec_send_packet(vid->avctx, pkt);
2731 if( ret < 0 ) break;
2732 while( (ret=vid->decode_frame(frame)) > 0 ) {}
2735 case AVMEDIA_TYPE_AUDIO: {
2736 int aidx = ffaudio.size();
2737 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
2738 if( aidx < 0 ) break;
2739 FFAudioStream *aud = ffaudio[aidx];
2740 if( !aud->avctx ) break;
2741 int64_t tstmp = pkt.pts;
2742 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
2743 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
2744 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
2745 double secs = to_secs(tstmp, st->time_base);
2746 int64_t sample = secs * aud->sample_rate + 0.5;
2748 index_state->put_audio_mark(aidx, sample, pkt.pos);
2750 ret = avcodec_send_packet(aud->avctx, &pkt);
2751 if( ret < 0 ) break;
2752 int ch = aud->channel0, nch = aud->channels;
2753 int64_t pos = index_state->pos(ch);
2754 if( pos != aud->curr_pos ) {
2755 if( abs(pos-aud->curr_pos) > 1 )
2756 printf("audio%d pad %jd %jd (%jd)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
2757 index_state->pad_data(ch, nch, aud->curr_pos);
2759 while( (ret=aud->decode_frame(frame)) > 0 ) {
2760 //if( frame->channels != nch ) break;
2761 aud->init_swr(frame->channels, frame->format, frame->sample_rate);
2763 int len = aud->get_samples(samples,
2764 &frame->extended_data[0], frame->nb_samples);
2765 pos = aud->curr_pos;
2766 if( (aud->curr_pos += len) >= 0 ) {
2768 samples += -pos * nch;
2769 len = aud->curr_pos;
2771 for( int i=0; i<nch; ++i )
2772 index_state->put_data(ch+i,nch,samples+i,len);
2779 av_frame_free(&frame);
2783 void FFStream::load_markers(IndexMarks &marks, double rate)
2786 int64_t sz = marks.size();
2787 int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
2788 int nb_ent = st->nb_index_entries;
2789 // some formats already have an index
2791 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
2792 int64_t tstmp = ep->timestamp;
2793 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
2794 double secs = ffmpeg->to_secs(tstmp, st->time_base);
2795 int64_t no = secs * rate;
2796 while( in < sz && marks[in].no <= no ) ++in;
2798 int64_t len = sz - in;
2799 int64_t count = max_entries - nb_ent;
2800 if( count > len ) count = len;
2801 for( int i=0; i<count; ++i ) {
2802 int k = in + i * len / count;
2803 int64_t no = marks[k].no, pos = marks[k].pos;
2804 double secs = (double)no / rate;
2805 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
2806 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
2807 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);