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
36 #define AUDIO_MIN_FRAME_SZ 128
38 Mutex FFMPEG::fflock("FFMPEG::fflock");
40 static void ff_err(int ret, const char *fmt, ...)
45 vsnprintf(msg, sizeof(msg), fmt, ap);
47 char errmsg[BCSTRLEN];
48 av_strerror(ret, errmsg, sizeof(errmsg));
49 fprintf(stderr,_("%s err: %s\n"),msg, errmsg);
55 pkt.data = 0; pkt.size = 0;
57 void FFPacket::finit()
59 av_packet_unref(&pkt);
62 FFrame::FFrame(FFStream *fst)
65 frm = av_frame_alloc();
66 init = fst->init_frame(frm);
74 void FFrame::queue(int64_t pos)
80 void FFrame::dequeue()
85 int FFAudioStream::read(float *fp, long len)
93 while( --k >= 0 ) *fp++ = *op++;
94 if( op >= lmt ) op = bfr;
99 void FFAudioStream::realloc(long nsz, int nch, long len)
101 long bsz = nsz * nch;
102 float *np = new float[bsz];
103 inp = np + read(np, len) * nch;
108 delete [] bfr; bfr = np;
111 void FFAudioStream::realloc(long nsz, int nch)
113 if( nsz > sz || this->nch != nch ) {
114 long len = this->nch != nch ? 0 : hpos;
115 if( len > sz ) len = sz;
117 realloc(nsz, nch, len);
121 void FFAudioStream::reserve(long nsz, int nch)
123 long len = (inp - outp) / nch;
125 if( nsz > sz || this->nch != nch ) {
126 if( this->nch != nch ) len = 0;
127 realloc(nsz, nch, len);
130 if( (len*=nch) > 0 && bfr != outp )
131 memmove(bfr, outp, len*sizeof(*bfr));
136 long FFAudioStream::used()
138 long len = inp>=outp ? inp-outp : inp-bfr + lmt-outp;
141 long FFAudioStream::avail()
144 if( in1 >= lmt ) in1 = bfr;
145 long len = outp >= in1 ? outp-in1 : outp-bfr + lmt-in1;
148 void FFAudioStream::reset_history()
152 memset(bfr, 0, lmt-bfr);
155 void FFAudioStream::iseek(int64_t ofs)
157 if( ofs > hpos ) ofs = hpos;
158 if( ofs > sz ) ofs = sz;
159 outp = inp - ofs*nch;
160 if( outp < bfr ) outp += sz*nch;
163 float *FFAudioStream::get_outp(int ofs)
170 int64_t FFAudioStream::put_inp(int ofs)
173 return (inp-outp) / nch;
176 int FFAudioStream::write(const float *fp, long len)
184 while( --k >= 0 ) *ip++ = *fp++;
185 if( ip >= lmt ) ip = bfr;
192 int FFAudioStream::zero(long len)
200 while( --k >= 0 ) *ip++ = 0;
201 if( ip >= lmt ) ip = bfr;
208 // does not advance outp
209 int FFAudioStream::read(double *dp, long len, int ch)
212 float *op = outp + ch;
213 float *lmt1 = lmt + nch-1;
215 int k = (lmt1 - op) / nch;
218 while( --k >= 0 ) { *dp++ = *op; op += nch; }
219 if( op >= lmt ) op -= sz*nch;
224 // load linear buffer, no wrapping allowed, does not advance inp
225 int FFAudioStream::write(const double *dp, long len, int ch)
228 float *ip = inp + ch;
229 while( --n >= 0 ) { *ip = *dp++; ip += nch; }
234 FFStream::FFStream(FFMPEG *ffmpeg, AVStream *st, int fidx)
236 this->ffmpeg = ffmpeg;
239 frm_lock = new Mutex("FFStream::frm_lock");
246 nudge = AV_NOPTS_VALUE;
247 seek_pos = curr_pos = 0;
249 reading = writing = 0;
256 FFStream::~FFStream()
258 if( reading > 0 || writing > 0 ) avcodec_close(avctx);
259 if( avctx ) avcodec_free_context(&avctx);
260 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
261 if( bsfc ) av_bsf_free(&bsfc);
262 while( frms.first ) frms.remove(frms.first);
263 if( filter_graph ) avfilter_graph_free(&filter_graph);
264 if( frame ) av_frame_free(&frame);
265 if( fframe ) av_frame_free(&fframe);
269 void FFStream::ff_lock(const char *cp)
271 FFMPEG::fflock.lock(cp);
274 void FFStream::ff_unlock()
276 FFMPEG::fflock.unlock();
279 void FFStream::queue(FFrame *frm)
281 frm_lock->lock("FFStream::queue");
285 ffmpeg->mux_lock->unlock();
288 void FFStream::dequeue(FFrame *frm)
290 frm_lock->lock("FFStream::dequeue");
292 frms.remove_pointer(frm);
296 int FFStream::encode_activate()
299 writing = ffmpeg->encode_activate();
303 int FFStream::decode_activate()
305 if( reading < 0 && (reading=ffmpeg->decode_activate()) > 0 ) {
306 ff_lock("FFStream::decode_activate");
308 AVDictionary *copts = 0;
309 av_dict_copy(&copts, ffmpeg->opts, 0);
311 // this should be avformat_copy_context(), but no copy avail
312 ret = avformat_open_input(&fmt_ctx, ffmpeg->fmt_ctx->filename, NULL, &copts);
314 ret = avformat_find_stream_info(fmt_ctx, 0);
315 st = fmt_ctx->streams[fidx];
318 if( ret >= 0 && st != 0 ) {
319 AVCodecID codec_id = st->codecpar->codec_id;
320 AVCodec *decoder = avcodec_find_decoder(codec_id);
321 avctx = avcodec_alloc_context3(decoder);
323 eprintf(_("cant allocate codec context\n"));
324 ret = AVERROR(ENOMEM);
327 av_codec_set_pkt_timebase(avctx, st->time_base);
328 if( decoder->capabilities & AV_CODEC_CAP_DR1 )
329 avctx->flags |= CODEC_FLAG_EMU_EDGE;
330 avcodec_parameters_to_context(avctx, st->codecpar);
331 ret = avcodec_open2(avctx, decoder, &copts);
337 eprintf(_("open decoder failed\n"));
340 eprintf(_("can't clone input file\n"));
341 av_dict_free(&copts);
347 int FFStream::read_packet()
349 av_packet_unref(ipkt);
350 int ret = av_read_frame(fmt_ctx, ipkt);
353 if( ret == AVERROR_EOF ) return 0;
354 ff_err(ret, "FFStream::read_packet: av_read_frame failed\n");
361 int FFStream::decode(AVFrame *frame)
364 int retries = MAX_RETRY;
366 while( ret >= 0 && !flushed && --retries >= 0 ) {
368 if( (ret=read_packet()) < 0 ) break;
369 AVPacket *pkt = ret > 0 ? (AVPacket*)ipkt : 0;
371 if( pkt->stream_index != st->index ) continue;
372 if( !pkt->data | !pkt->size ) continue;
374 if( (ret=avcodec_send_packet(avctx, pkt)) < 0 ) {
375 ff_err(ret, "FFStream::decode: avcodec_send_packet failed\n");
381 if( (ret=decode_frame(frame)) > 0 ) break;
389 fprintf(stderr, "FFStream::decode: Retry limit\n");
393 fprintf(stderr, "FFStream::decode: failed\n");
397 int FFStream::load_filter(AVFrame *frame)
399 int ret = av_buffersrc_add_frame_flags(buffersrc_ctx, frame, 0);
401 eprintf(_("av_buffersrc_add_frame_flags failed\n"));
405 int FFStream::read_filter(AVFrame *frame)
407 int ret = av_buffersink_get_frame(buffersink_ctx, frame);
409 if( ret == AVERROR(EAGAIN) ) return 0;
410 if( ret == AVERROR_EOF ) { st_eof(1); return -1; }
411 ff_err(ret, "FFStream::read_filter: av_buffersink_get_frame failed\n");
417 int FFStream::read_frame(AVFrame *frame)
419 av_frame_unref(frame);
420 if( !filter_graph || !buffersrc_ctx || !buffersink_ctx )
421 return decode(frame);
422 if( !fframe && !(fframe=av_frame_alloc()) ) {
423 fprintf(stderr, "FFStream::read_frame: av_frame_alloc failed\n");
427 while( !flushed && !(ret=read_filter(frame)) ) {
428 if( (ret=decode(fframe)) < 0 ) break;
429 if( ret > 0 && (ret=load_filter(fframe)) < 0 ) break;
434 int FFStream::write_packet(FFPacket &pkt)
438 av_packet_rescale_ts(pkt, avctx->time_base, st->time_base);
439 pkt->stream_index = st->index;
440 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, pkt);
443 ret = av_bsf_send_packet(bsfc, pkt);
446 if( (ret=av_bsf_receive_packet(bsfc, bs)) < 0 ) {
447 if( ret == AVERROR(EAGAIN) ) return 0;
448 if( ret == AVERROR_EOF ) return -1;
451 av_packet_rescale_ts(bs, avctx->time_base, st->time_base);
452 bs->stream_index = st->index;
453 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, bs);
457 ff_err(ret, "FFStream::write_packet: write packet failed\n");
461 int FFStream::encode_frame(AVFrame *frame)
463 int pkts = 0, ret = 0;
464 for( int retry=100; --retry>=0; ) {
466 ret = avcodec_send_frame(avctx, frame);
467 if( !ret && frame ) return pkts;
468 if( ret < 0 && ret != AVERROR(EAGAIN) ) break;
470 ret = avcodec_receive_packet(avctx, opkt);
471 if( !frame && ret == AVERROR_EOF ) return pkts;
473 ret = write_packet(opkt);
477 ff_err(ret, "FFStream::encode_frame: encode failed\n");
481 int FFStream::flush()
485 int ret = encode_frame(0);
487 ff_err(ret, "FFStream::flush");
488 return ret >= 0 ? 0 : 1;
491 int FFStream::seek(int64_t no, double rate)
493 // default ffmpeg native seek
495 int64_t pos = no, pkt_pos = -1;
496 IndexMarks *index_markers = get_markers();
497 if( index_markers && index_markers->size() > 1 ) {
498 IndexMarks &marks = *index_markers;
499 int i = marks.find(pos);
500 int64_t n = i < 0 ? (i=0) : marks[i].no;
501 // if indexed seek point not too far away (<30 secs), use index
502 if( no-n < 30*rate ) {
505 if( i < marks.size() ) pkt_pos = marks[i].pos;
509 if( pos == curr_pos ) return 0;
510 double secs = pos < 0 ? 0. : pos / rate;
511 AVRational time_base = st->time_base;
512 int64_t tstmp = time_base.num > 0 ? secs * time_base.den/time_base.num : 0;
514 if( st->nb_index_entries > 0 ) tstmp = st->index_entries[0].timestamp;
515 else if( st->start_time != AV_NOPTS_VALUE ) tstmp = st->start_time;
516 else if( st->first_dts != AV_NOPTS_VALUE ) tstmp = st->first_dts;
517 else tstmp = INT64_MIN+1;
519 else if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
522 // seek all streams using the default timebase.
523 // this is how ffmpeg and ffplay work. stream seeks are less tested.
524 tstmp = av_rescale_q(tstmp, time_base, AV_TIME_BASE_Q);
528 avcodec_flush_buffers(avctx);
529 avformat_flush(fmt_ctx);
531 int64_t seek = tstmp;
532 int flags = AVSEEK_FLAG_ANY;
533 if( !(fmt_ctx->iformat->flags & AVFMT_NO_BYTE_SEEK) && pkt_pos >= 0 ) {
535 flags = AVSEEK_FLAG_BYTE;
537 int ret = avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, seek, INT64_MAX, flags);
539 // finds the first index frame below the target time
540 int flags = AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_ANY;
541 int ret = av_seek_frame(fmt_ctx, idx, tstmp, flags);
543 int retry = MAX_RETRY;
545 need_packet = 0; flushed = 0;
546 seeked = 1; st_eof(0);
547 // read up to retry packets, limited to npkts in stream, and not pkt.pos past pkt_pos
548 while( --retry >= 0 ) {
549 if( read_packet() <= 0 ) { ret = -1; break; }
550 if( ipkt->stream_index != st->index ) continue;
551 if( !ipkt->data || !ipkt->size ) continue;
552 if( pkt_pos >= 0 && ipkt->pos >= pkt_pos ) break;
553 if( --npkts <= 0 ) break;
554 int64_t pkt_ts = ipkt->dts != AV_NOPTS_VALUE ? ipkt->dts : ipkt->pts;
555 if( pkt_ts == AV_NOPTS_VALUE ) continue;
556 if( pkt_ts >= tstmp ) break;
559 fprintf(stderr,"FFStream::seek: retry limit, pos=%jd tstmp=%jd\n",pos,tstmp);
563 ret = avcodec_send_packet(avctx, ipkt);
565 //some codecs need more than one pkt to resync
566 if( ret == AVERROR_INVALIDDATA ) ret = 0;
568 ff_err(ret, "FFStream::avcodec_send_packet failed\n");
573 printf("** seek fail %jd, %jd\n", pos, tstmp);
574 seeked = need_packet = 0;
578 //printf("seeked pos = %ld, %ld\n", pos, tstmp);
579 seek_pos = curr_pos = pos;
583 FFAudioStream::FFAudioStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
584 : FFStream(ffmpeg, strm, fidx)
587 channel0 = channels = 0;
590 frame_sz = AUDIO_MIN_FRAME_SZ;
592 resample_context = 0;
593 swr_ichs = swr_ifmt = swr_irate = 0;
602 bfr = new float[bsz];
607 FFAudioStream::~FFAudioStream()
609 if( resample_context ) swr_free(&resample_context);
614 void FFAudioStream::init_swr(int ichs, int ifmt, int irate)
616 if( resample_context ) {
617 if( swr_ichs == ichs && swr_ifmt == ifmt && swr_irate == irate )
619 swr_free(&resample_context);
621 swr_ichs = ichs; swr_ifmt = ifmt; swr_irate = irate;
622 if( ichs == channels && ifmt == AV_SAMPLE_FMT_FLT && irate == sample_rate )
624 uint64_t ilayout = av_get_default_channel_layout(ichs);
625 if( !ilayout ) ilayout = ((uint64_t)1<<ichs) - 1;
626 uint64_t olayout = av_get_default_channel_layout(channels);
627 if( !olayout ) olayout = ((uint64_t)1<<channels) - 1;
628 resample_context = swr_alloc_set_opts(NULL,
629 olayout, AV_SAMPLE_FMT_FLT, sample_rate,
630 ilayout, (AVSampleFormat)ifmt, irate,
632 if( resample_context )
633 swr_init(resample_context);
636 int FFAudioStream::get_samples(float *&samples, uint8_t **data, int len)
638 samples = *(float **)data;
639 if( resample_context ) {
640 if( len > aud_bfr_sz ) {
646 aud_bfr = new float[aud_bfr_sz*channels];
648 int ret = swr_convert(resample_context,
649 (uint8_t**)&aud_bfr, aud_bfr_sz, (const uint8_t**)data, len);
651 ff_err(ret, "FFAudioStream::get_samples: swr_convert failed\n");
660 int FFAudioStream::load_history(uint8_t **data, int len)
663 len = get_samples(samples, data, len);
665 // biggest user bfr since seek + frame
666 realloc(mbsz + len + 1, channels);
672 int FFAudioStream::decode_frame(AVFrame *frame)
674 int first_frame = seeked; seeked = 0;
675 int ret = avcodec_receive_frame(avctx, frame);
677 if( first_frame || ret == AVERROR(EAGAIN) ) return 0;
678 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
679 ff_err(ret, "FFAudioStream::decode_frame: Could not read audio frame\n");
682 int64_t pkt_ts = av_frame_get_best_effort_timestamp(frame);
683 if( pkt_ts != AV_NOPTS_VALUE )
684 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * sample_rate + 0.5;
688 int FFAudioStream::encode_activate()
690 if( writing >= 0 ) return writing;
691 frame_sz = avctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE ?
692 10000 : avctx->frame_size;
693 return FFStream::encode_activate();
696 int64_t FFAudioStream::load_buffer(double ** const sp, int len)
698 reserve(len+1, st->codecpar->channels);
699 for( int ch=0; ch<nch; ++ch )
700 write(sp[ch], len, ch);
704 int FFAudioStream::in_history(int64_t pos)
706 if( pos > curr_pos ) return 0;
708 if( len > sz ) len = sz;
709 if( pos < curr_pos - len ) return 0;
714 int FFAudioStream::init_frame(AVFrame *frame)
716 frame->nb_samples = frame_sz;
717 frame->format = avctx->sample_fmt;
718 frame->channel_layout = avctx->channel_layout;
719 frame->sample_rate = avctx->sample_rate;
720 int ret = av_frame_get_buffer(frame, 0);
722 ff_err(ret, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
726 int FFAudioStream::load(int64_t pos, int len)
728 if( audio_seek(pos) < 0 ) return -1;
729 if( !frame && !(frame=av_frame_alloc()) ) {
730 fprintf(stderr, "FFAudioStream::load: av_frame_alloc failed\n");
733 if( mbsz < len ) mbsz = len;
734 int64_t end_pos = pos + len;
735 int ret = 0, i = len / frame_sz + MAX_RETRY;
736 while( ret>=0 && !flushed && curr_pos<end_pos && --i>=0 ) {
737 ret = read_frame(frame);
738 if( ret > 0 && frame->nb_samples > 0 ) {
739 init_swr(frame->channels, frame->format, frame->sample_rate);
740 load_history(&frame->extended_data[0], frame->nb_samples);
741 curr_pos += frame->nb_samples;
744 if( end_pos > curr_pos ) {
745 zero(end_pos - curr_pos);
748 len = curr_pos - pos;
753 int FFAudioStream::audio_seek(int64_t pos)
755 if( decode_activate() <= 0 ) return -1;
756 if( !st->codecpar ) return -1;
757 if( in_history(pos) ) return 0;
758 if( pos == curr_pos ) return 0;
759 reset_history(); mbsz = 0;
760 // guarentee preload > 1sec samples
761 if( seek(pos-sample_rate, sample_rate) < 0 ) return -1;
765 int FFAudioStream::encode(double **samples, int len)
767 if( encode_activate() <= 0 ) return -1;
770 int64_t count = samples ? load_buffer(samples, len) : used();
771 int frame_sz1 = samples ? frame_sz-1 : 0;
774 while( ret >= 0 && count > frame_sz1 ) {
775 frm = new FFrame(this);
776 if( (ret=frm->initted()) < 0 ) break;
777 AVFrame *frame = *frm;
778 len = count >= frame_sz ? frame_sz : count;
779 float *bfrp = get_outp(len);
780 ret = swr_convert(resample_context,
781 (uint8_t **)frame->extended_data, len,
782 (const uint8_t **)&bfrp, len);
784 ff_err(ret, "FFAudioStream::encode: swr_convert failed\n");
787 frame->nb_samples = len;
788 frm->queue(curr_pos);
795 return ret >= 0 ? 0 : 1;
798 int FFAudioStream::drain()
803 int FFAudioStream::encode_frame(AVFrame *frame)
805 return FFStream::encode_frame(frame);
808 int FFAudioStream::write_packet(FFPacket &pkt)
810 return FFStream::write_packet(pkt);
813 void FFAudioStream::load_markers()
815 IndexState *index_state = ffmpeg->file_base->asset->index_state;
816 if( !index_state || idx >= index_state->audio_markers.size() ) return;
817 if( index_state->marker_status == MARKERS_NOTTESTED ) return;
818 FFStream::load_markers(*index_state->audio_markers[idx], sample_rate);
821 IndexMarks *FFAudioStream::get_markers()
823 IndexState *index_state = ffmpeg->file_base->asset->index_state;
824 if( !index_state || idx >= index_state->audio_markers.size() ) return 0;
825 return index_state->audio_markers[idx];
828 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
829 : FFStream(ffmpeg, strm, fidx)
840 FFVideoStream::~FFVideoStream()
844 int FFVideoStream::decode_frame(AVFrame *frame)
846 int first_frame = seeked; seeked = 0;
847 int ret = avcodec_receive_frame(avctx, frame);
849 if( first_frame || ret == AVERROR(EAGAIN) ) return 0;
850 if( ret == AVERROR(EAGAIN) ) return 0;
851 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
852 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame\n");
855 int64_t pkt_ts = av_frame_get_best_effort_timestamp(frame);
856 if( pkt_ts != AV_NOPTS_VALUE )
857 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * frame_rate + 0.5;
861 int FFVideoStream::load(VFrame *vframe, int64_t pos)
863 int ret = video_seek(pos);
864 if( ret < 0 ) return -1;
865 if( !frame && !(frame=av_frame_alloc()) ) {
866 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
869 int i = MAX_RETRY + pos - curr_pos;
870 while( ret>=0 && !flushed && curr_pos<=pos && --i>=0 ) {
871 ret = read_frame(frame);
872 if( ret > 0 ) ++curr_pos;
874 if( frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0 )
877 ret = convert_cmodel(vframe, frame);
879 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
883 int FFVideoStream::video_seek(int64_t pos)
885 if( decode_activate() <= 0 ) return -1;
886 if( !st->codecpar ) return -1;
887 if( pos == curr_pos-1 && !seeked ) return 0;
888 // if close enough, just read up to current
889 int gop = avctx->gop_size;
890 if( gop < 4 ) gop = 4;
891 if( gop > 64 ) gop = 64;
892 int read_limit = curr_pos + 3*gop;
893 if( pos >= curr_pos && pos <= read_limit ) return 0;
894 // guarentee preload more than 2*gop frames
895 if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
899 int FFVideoStream::init_frame(AVFrame *picture)
901 picture->format = avctx->pix_fmt;
902 picture->width = avctx->width;
903 picture->height = avctx->height;
904 int ret = av_frame_get_buffer(picture, 32);
908 int FFVideoStream::encode(VFrame *vframe)
910 if( encode_activate() <= 0 ) return -1;
912 FFrame *picture = new FFrame(this);
913 int ret = picture->initted();
915 AVFrame *frame = *picture;
916 frame->pts = curr_pos;
917 ret = convert_pixfmt(vframe, frame);
920 picture->queue(curr_pos);
924 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
927 return ret >= 0 ? 0 : 1;
930 int FFVideoStream::drain()
935 int FFVideoStream::encode_frame(AVFrame *frame)
938 frame->interlaced_frame = interlaced;
939 frame->top_field_first = top_field_first;
941 return FFStream::encode_frame(frame);
944 int FFVideoStream::write_packet(FFPacket &pkt)
946 if( !(ffmpeg->fmt_ctx->oformat->flags & AVFMT_VARIABLE_FPS) )
948 return FFStream::write_packet(pkt);
951 AVPixelFormat FFVideoConvert::color_model_to_pix_fmt(int color_model)
953 switch( color_model ) {
954 case BC_YUV422: return AV_PIX_FMT_YUYV422;
955 case BC_RGB888: return AV_PIX_FMT_RGB24;
956 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
957 case BC_BGR8888: return AV_PIX_FMT_BGR0;
958 case BC_BGR888: return AV_PIX_FMT_BGR24;
959 case BC_ARGB8888: return AV_PIX_FMT_ARGB;
960 case BC_ABGR8888: return AV_PIX_FMT_ABGR;
961 case BC_RGB8: return AV_PIX_FMT_RGB8;
962 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
963 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
964 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
965 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
966 case BC_RGB565: return AV_PIX_FMT_RGB565;
967 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
968 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
969 case BC_AYUV16161616: return AV_PIX_FMT_AYUV64LE;
973 return AV_PIX_FMT_NB;
976 int FFVideoConvert::pix_fmt_to_color_model(AVPixelFormat pix_fmt)
979 case AV_PIX_FMT_YUYV422: return BC_YUV422;
980 case AV_PIX_FMT_RGB24: return BC_RGB888;
981 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
982 case AV_PIX_FMT_BGR0: return BC_BGR8888;
983 case AV_PIX_FMT_BGR24: return BC_BGR888;
984 case AV_PIX_FMT_ARGB: return BC_ARGB8888;
985 case AV_PIX_FMT_ABGR: return BC_ABGR8888;
986 case AV_PIX_FMT_RGB8: return BC_RGB8;
987 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
988 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
989 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
990 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
991 case AV_PIX_FMT_RGB565: return BC_RGB565;
992 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
993 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
994 case AV_PIX_FMT_AYUV64LE: return BC_AYUV16161616;
1001 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip)
1003 AVFrame *ipic = av_frame_alloc();
1004 int ret = convert_picture_vframe(frame, ip, ipic);
1005 av_frame_free(&ipic);
1009 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip, AVFrame *ipic)
1011 int cmodel = frame->get_color_model();
1012 AVPixelFormat ofmt = color_model_to_pix_fmt(cmodel);
1013 if( ofmt == AV_PIX_FMT_NB ) return -1;
1014 int size = av_image_fill_arrays(ipic->data, ipic->linesize,
1015 frame->get_data(), ofmt, frame->get_w(), frame->get_h(), 1);
1016 if( size < 0 ) return -1;
1018 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1019 int ysz = bpp * frame->get_w(), usz = ysz;
1028 // override av_image_fill_arrays() for planar types
1029 ipic->data[0] = frame->get_y(); ipic->linesize[0] = ysz;
1030 ipic->data[1] = frame->get_u(); ipic->linesize[1] = usz;
1031 ipic->data[2] = frame->get_v(); ipic->linesize[2] = usz;
1034 ipic->data[0] = frame->get_data();
1035 ipic->linesize[0] = frame->get_bytes_per_line();
1039 AVPixelFormat pix_fmt = (AVPixelFormat)ip->format;
1040 convert_ctx = sws_getCachedContext(convert_ctx, ip->width, ip->height, pix_fmt,
1041 frame->get_w(), frame->get_h(), ofmt, SWS_POINT, NULL, NULL, NULL);
1042 if( !convert_ctx ) {
1043 fprintf(stderr, "FFVideoConvert::convert_picture_frame:"
1044 " sws_getCachedContext() failed\n");
1047 int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ip->height,
1048 ipic->data, ipic->linesize);
1050 ff_err(ret, "FFVideoConvert::convert_picture_frame: sws_scale() failed\n");
1056 int FFVideoConvert::convert_cmodel(VFrame *frame, AVFrame *ip)
1058 // try direct transfer
1059 if( !convert_picture_vframe(frame, ip) ) return 1;
1060 // use indirect transfer
1061 AVPixelFormat ifmt = (AVPixelFormat)ip->format;
1062 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
1064 for( int i = 0; i <desc->nb_components; ++i ) {
1065 int bits = desc->comp[i].depth;
1066 if( bits > max_bits ) max_bits = bits;
1068 int imodel = pix_fmt_to_color_model(ifmt);
1069 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1070 int cmodel = frame->get_color_model();
1071 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1072 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1073 imodel = cmodel_is_yuv ?
1074 (BC_CModels::has_alpha(cmodel) ?
1076 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1077 (BC_CModels::has_alpha(cmodel) ?
1078 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1079 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1081 VFrame vframe(ip->width, ip->height, imodel);
1082 if( convert_picture_vframe(&vframe, ip) ) return -1;
1083 frame->transfer_from(&vframe);
1087 int FFVideoConvert::transfer_cmodel(VFrame *frame, AVFrame *ifp)
1089 int ret = convert_cmodel(frame, ifp);
1091 const AVDictionary *src = av_frame_get_metadata(ifp);
1092 AVDictionaryEntry *t = NULL;
1093 BC_Hash *hp = frame->get_params();
1095 while( (t=av_dict_get(src, "", t, AV_DICT_IGNORE_SUFFIX)) )
1096 hp->update(t->key, t->value);
1101 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op)
1103 AVFrame *opic = av_frame_alloc();
1104 int ret = convert_vframe_picture(frame, op, opic);
1105 av_frame_free(&opic);
1109 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op, AVFrame *opic)
1111 int cmodel = frame->get_color_model();
1112 AVPixelFormat ifmt = color_model_to_pix_fmt(cmodel);
1113 if( ifmt == AV_PIX_FMT_NB ) return -1;
1114 int size = av_image_fill_arrays(opic->data, opic->linesize,
1115 frame->get_data(), ifmt, frame->get_w(), frame->get_h(), 1);
1116 if( size < 0 ) return -1;
1118 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1119 int ysz = bpp * frame->get_w(), usz = ysz;
1128 // override av_image_fill_arrays() for planar types
1129 opic->data[0] = frame->get_y(); opic->linesize[0] = ysz;
1130 opic->data[1] = frame->get_u(); opic->linesize[1] = usz;
1131 opic->data[2] = frame->get_v(); opic->linesize[2] = usz;
1134 opic->data[0] = frame->get_data();
1135 opic->linesize[0] = frame->get_bytes_per_line();
1139 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1140 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(),
1141 ifmt, op->width, op->height, ofmt, SWS_POINT, NULL, NULL, NULL);
1142 if( !convert_ctx ) {
1143 fprintf(stderr, "FFVideoConvert::convert_frame_picture:"
1144 " sws_getCachedContext() failed\n");
1147 int ret = sws_scale(convert_ctx, opic->data, opic->linesize, 0, frame->get_h(),
1148 op->data, op->linesize);
1150 ff_err(ret, "FFVideoConvert::convert_frame_picture: sws_scale() failed\n");
1156 int FFVideoConvert::convert_pixfmt(VFrame *frame, AVFrame *op)
1158 // try direct transfer
1159 if( !convert_vframe_picture(frame, op) ) return 1;
1160 // use indirect transfer
1161 int cmodel = frame->get_color_model();
1162 int max_bits = BC_CModels::calculate_pixelsize(cmodel) * 8;
1163 max_bits /= BC_CModels::components(cmodel);
1164 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1165 int imodel = pix_fmt_to_color_model(ofmt);
1166 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1167 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1168 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1169 imodel = cmodel_is_yuv ?
1170 (BC_CModels::has_alpha(cmodel) ?
1172 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1173 (BC_CModels::has_alpha(cmodel) ?
1174 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1175 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1177 VFrame vframe(frame->get_w(), frame->get_h(), imodel);
1178 vframe.transfer_from(frame);
1179 if( !convert_vframe_picture(&vframe, op) ) return 1;
1183 int FFVideoConvert::transfer_pixfmt(VFrame *frame, AVFrame *ofp)
1185 int ret = convert_pixfmt(frame, ofp);
1187 BC_Hash *hp = frame->get_params();
1188 AVDictionary **dict = avpriv_frame_get_metadatap(ofp);
1189 //av_dict_free(dict);
1190 for( int i=0; i<hp->size(); ++i ) {
1191 char *key = hp->get_key(i), *val = hp->get_value(i);
1192 av_dict_set(dict, key, val, 0);
1198 void FFVideoStream::load_markers()
1200 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1201 if( !index_state || idx >= index_state->video_markers.size() ) return;
1202 FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
1205 IndexMarks *FFVideoStream::get_markers()
1207 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1208 if( !index_state || idx >= index_state->video_markers.size() ) return 0;
1209 return !index_state ? 0 : index_state->video_markers[idx];
1213 FFMPEG::FFMPEG(FileBase *file_base)
1216 this->file_base = file_base;
1217 memset(file_format,0,sizeof(file_format));
1218 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
1219 flow_lock = new Condition(1,"FFStream::flow_lock",0);
1222 decoding = encoding = 0;
1223 has_audio = has_video = 0;
1226 opt_video_filter = 0;
1227 opt_audio_filter = 0;
1228 char option_path[BCTEXTLEN];
1229 set_option_path(option_path, "%s", "ffmpeg.opts");
1230 read_options(option_path, opts);
1235 ff_lock("FFMPEG::~FFMPEG()");
1237 ffaudio.remove_all_objects();
1238 ffvideo.remove_all_objects();
1239 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1243 av_dict_free(&opts);
1244 delete [] opt_video_filter;
1245 delete [] opt_audio_filter;
1248 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1250 const int *p = codec->supported_samplerates;
1251 if( !p ) return sample_rate;
1253 if( *p == sample_rate ) return *p;
1259 static inline AVRational std_frame_rate(int i)
1261 static const int m1 = 1001*12, m2 = 1000*12;
1262 static const int freqs[] = {
1263 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1264 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
1266 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1267 return (AVRational) { freq, 1001*12 };
1270 AVRational FFMPEG::check_frame_rate(AVCodec *codec, double frame_rate)
1272 const AVRational *p = codec->supported_framerates;
1273 AVRational rate, best_rate = (AVRational) { 0, 0 };
1274 double max_err = 1.; int i = 0;
1275 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1276 double framerate = (double) rate.num / rate.den;
1277 double err = fabs(frame_rate/framerate - 1.);
1278 if( err >= max_err ) continue;
1282 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1285 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1288 double display_aspect = asset->width / (double)asset->height;
1289 double sample_aspect = display_aspect / asset->aspect_ratio;
1290 int width = 1000000, height = width * sample_aspect + 0.5;
1292 MWindow::create_aspect_ratio(w, h, width, height);
1293 return (AVRational){(int)w, (int)h};
1296 return (AVRational){1, 1};
1300 AVRational FFMPEG::to_time_base(int sample_rate)
1302 return (AVRational){1, sample_rate};
1305 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
1307 char *ep = path + BCTEXTLEN-1;
1308 strncpy(path, File::get_cindat_path(), ep-path);
1309 strncat(path, "/ffmpeg/", ep-path);
1310 path += strlen(path);
1313 path += vsnprintf(path, ep-path, fmt, ap);
1318 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
1323 set_option_path(path, "%s/%s", type, spec);
1326 int FFMPEG::get_format(char *format, const char *path, const char *spec)
1328 char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
1329 get_option_path(option_path, path, spec);
1330 FILE *fp = fopen(option_path,"r");
1333 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1335 line[sizeof(line)-1] = 0;
1336 ret = scan_option_line(line, format, codec);
1342 int FFMPEG::get_codec(char *codec, const char *path, const char *spec)
1344 char option_path[BCTEXTLEN], line[BCTEXTLEN], format[BCTEXTLEN];
1345 get_option_path(option_path, path, spec);
1346 FILE *fp = fopen(option_path,"r");
1349 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1352 line[sizeof(line)-1] = 0;
1353 ret = scan_option_line(line, format, codec);
1356 char *vp = codec, *ep = vp+BCTEXTLEN-1;
1357 while( vp < ep && *vp && *vp != '|' ) ++vp;
1358 if( *vp == '|' ) --vp;
1359 while( vp > codec && (*vp==' ' || *vp=='\t') ) *vp-- = 0;
1364 int FFMPEG::get_file_format()
1366 char audio_muxer[BCSTRLEN], video_muxer[BCSTRLEN];
1367 char audio_format[BCSTRLEN], video_format[BCSTRLEN];
1368 audio_muxer[0] = audio_format[0] = 0;
1369 video_muxer[0] = video_format[0] = 0;
1370 Asset *asset = file_base->asset;
1371 int ret = asset ? 0 : 1;
1372 if( !ret && asset->audio_data ) {
1373 if( !(ret=get_format(audio_format, "audio", asset->acodec)) ) {
1374 if( get_format(audio_muxer, "format", audio_format) ) {
1375 strcpy(audio_muxer, audio_format);
1376 audio_format[0] = 0;
1380 if( !ret && asset->video_data ) {
1381 if( !(ret=get_format(video_format, "video", asset->vcodec)) ) {
1382 if( get_format(video_muxer, "format", video_format) ) {
1383 strcpy(video_muxer, video_format);
1384 video_format[0] = 0;
1388 if( !ret && !audio_muxer[0] && !video_muxer[0] )
1390 if( !ret && audio_muxer[0] && video_muxer[0] &&
1391 strcmp(audio_muxer, video_muxer) ) ret = -1;
1392 if( !ret && audio_format[0] && video_format[0] &&
1393 strcmp(audio_format, video_format) ) ret = -1;
1395 strcpy(file_format, !audio_format[0] && !video_format[0] ?
1396 (audio_muxer[0] ? audio_muxer : video_muxer) :
1397 (audio_format[0] ? audio_format : video_format));
1401 int FFMPEG::scan_option_line(char *cp, char *tag, char *val)
1403 while( *cp == ' ' || *cp == '\t' ) ++cp;
1405 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' && *cp != '\n' ) ++cp;
1407 if( !len || len > BCSTRLEN-1 ) return 1;
1408 while( bp < cp ) *tag++ = *bp++;
1410 while( *cp == ' ' || *cp == '\t' ) ++cp;
1411 if( *cp == '=' ) ++cp;
1412 while( *cp == ' ' || *cp == '\t' ) ++cp;
1414 while( *cp && *cp != '\n' ) ++cp;
1416 if( len > BCTEXTLEN-1 ) return 1;
1417 while( bp < cp ) *val++ = *bp++;
1422 int FFMPEG::load_defaults(const char *path, const char *type,
1423 char *codec, char *codec_options, int len)
1425 char default_file[BCTEXTLEN];
1426 set_option_path(default_file, "%s/%s.dfl", path, type);
1427 FILE *fp = fopen(default_file,"r");
1429 fgets(codec, BCSTRLEN, fp);
1431 while( *cp && *cp!='\n' ) ++cp;
1433 while( len > 0 && fgets(codec_options, len, fp) ) {
1434 int n = strlen(codec_options);
1435 codec_options += n; len -= n;
1438 set_option_path(default_file, "%s/%s", path, codec);
1439 return load_options(default_file, codec_options, len);
1442 void FFMPEG::set_asset_format(Asset *asset, const char *text)
1444 if( asset->format != FILE_FFMPEG ) return;
1445 if( text != asset->fformat )
1446 strcpy(asset->fformat, text);
1447 if( !asset->ff_audio_options[0] ) {
1448 asset->audio_data = !load_defaults("audio", text, asset->acodec,
1449 asset->ff_audio_options, sizeof(asset->ff_audio_options));
1451 if( !asset->ff_video_options[0] ) {
1452 asset->video_data = !load_defaults("video", text, asset->vcodec,
1453 asset->ff_video_options, sizeof(asset->ff_video_options));
1457 int FFMPEG::get_encoder(const char *options,
1458 char *format, char *codec, char *bsfilter)
1460 FILE *fp = fopen(options,"r");
1462 eprintf(_("options open failed %s\n"),options);
1465 if( get_encoder(fp, format, codec, bsfilter) )
1466 eprintf(_("format/codec not found %s\n"), options);
1471 int FFMPEG::get_encoder(FILE *fp,
1472 char *format, char *codec, char *bsfilter)
1474 format[0] = codec[0] = bsfilter[0] = 0;
1475 char line[BCTEXTLEN];
1476 if( !fgets(line, sizeof(line), fp) ) return 1;
1477 line[sizeof(line)-1] = 0;
1478 if( scan_option_line(line, format, codec) ) return 1;
1480 while( *cp && *cp != '|' ) ++cp;
1481 if( !*cp ) return 0;
1483 do { *bp-- = 0; } while( bp>=codec && (*bp==' ' || *bp == '\t' ) );
1484 while( *++cp && (*cp==' ' || *cp == '\t') );
1486 for( int i=BCTEXTLEN; --i>0 && *cp; ) *bp++ = *cp++;
1491 int FFMPEG::read_options(const char *options, AVDictionary *&opts, int skip)
1493 FILE *fp = fopen(options,"r");
1496 while( !ret && --skip >= 0 ) {
1498 while( ch >= 0 && ch != '\n' ) ch = getc(fp);
1499 if( ch < 0 ) ret = 1;
1502 ret = read_options(fp, options, opts);
1507 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
1509 FILE *fp = fmemopen((void *)options,strlen(options),"r");
1511 int ret = read_options(fp, options, opts);
1513 AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
1514 if( tag ) st->id = strtol(tag->value,0,0);
1518 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
1520 int ret = 0, no = 0;
1521 char line[BCTEXTLEN];
1522 while( !ret && fgets(line, sizeof(line), fp) ) {
1523 line[sizeof(line)-1] = 0;
1524 if( line[0] == '#' ) continue;
1525 if( line[0] == '\n' ) continue;
1526 char key[BCSTRLEN], val[BCTEXTLEN];
1527 if( scan_option_line(line, key, val) ) {
1528 eprintf(_("err reading %s: line %d\n"), options, no);
1532 if( !strcmp(key, "duration") )
1533 opt_duration = strtod(val, 0);
1534 else if( !strcmp(key, "video_filter") )
1535 opt_video_filter = cstrdup(val);
1536 else if( !strcmp(key, "audio_filter") )
1537 opt_audio_filter = cstrdup(val);
1538 else if( !strcmp(key, "loglevel") )
1541 av_dict_set(&opts, key, val, 0);
1547 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
1549 char option_path[BCTEXTLEN];
1550 set_option_path(option_path, "%s", options);
1551 return read_options(option_path, opts);
1554 int FFMPEG::load_options(const char *path, char *bfr, int len)
1557 FILE *fp = fopen(path, "r");
1559 fgets(bfr, len, fp); // skip hdr
1560 len = fread(bfr, 1, len-1, fp);
1561 if( len < 0 ) len = 0;
1567 void FFMPEG::set_loglevel(const char *ap)
1569 if( !ap || !*ap ) return;
1574 { "quiet" , AV_LOG_QUIET },
1575 { "panic" , AV_LOG_PANIC },
1576 { "fatal" , AV_LOG_FATAL },
1577 { "error" , AV_LOG_ERROR },
1578 { "warning", AV_LOG_WARNING },
1579 { "info" , AV_LOG_INFO },
1580 { "verbose", AV_LOG_VERBOSE },
1581 { "debug" , AV_LOG_DEBUG },
1583 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
1584 if( !strcmp(log_levels[i].name, ap) ) {
1585 av_log_set_level(log_levels[i].level);
1589 av_log_set_level(atoi(ap));
1592 double FFMPEG::to_secs(int64_t time, AVRational time_base)
1594 double base_time = time == AV_NOPTS_VALUE ? 0 :
1595 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
1596 return base_time / AV_TIME_BASE;
1599 int FFMPEG::info(char *text, int len)
1601 if( len <= 0 ) return 0;
1603 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
1605 report("format: %s\n",fmt_ctx->iformat->name);
1606 if( ffvideo.size() > 0 )
1607 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
1608 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
1609 FFVideoStream *vid = ffvideo[vidx];
1610 AVStream *st = vid->st;
1611 AVCodecID codec_id = st->codecpar->codec_id;
1612 report(_("vid%d (%d), id 0x%06x:\n"), vid->idx, vid->fidx, codec_id);
1613 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
1614 report(" video%d %s", vidx+1, desc ? desc->name : " (unkn)");
1615 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
1616 AVPixelFormat pix_fmt = (AVPixelFormat)st->codecpar->format;
1617 const char *pfn = av_get_pix_fmt_name(pix_fmt);
1618 report(" pix %s\n", pfn ? pfn : "(unkn)");
1619 double secs = to_secs(st->duration, st->time_base);
1620 int64_t length = secs * vid->frame_rate + 0.5;
1621 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
1622 int64_t nudge = ofs * vid->frame_rate;
1623 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1624 report(" %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
1625 int hrs = secs/3600; secs -= hrs*3600;
1626 int mins = secs/60; secs -= mins*60;
1627 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1629 if( ffaudio.size() > 0 )
1630 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
1631 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
1632 FFAudioStream *aud = ffaudio[aidx];
1633 AVStream *st = aud->st;
1634 AVCodecID codec_id = st->codecpar->codec_id;
1635 report(_("aud%d (%d), id 0x%06x:\n"), aud->idx, aud->fidx, codec_id);
1636 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
1637 int nch = aud->channels, ch0 = aud->channel0+1;
1638 report(" audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
1639 AVSampleFormat sample_fmt = (AVSampleFormat)st->codecpar->format;
1640 const char *fmt = av_get_sample_fmt_name(sample_fmt);
1641 report(" %s %d", fmt, aud->sample_rate);
1642 int sample_bits = av_get_bits_per_sample(codec_id);
1643 report(" %dbits\n", sample_bits);
1644 double secs = to_secs(st->duration, st->time_base);
1645 int64_t length = secs * aud->sample_rate + 0.5;
1646 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
1647 int64_t nudge = ofs * aud->sample_rate;
1648 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1649 report(" %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
1650 int hrs = secs/3600; secs -= hrs*3600;
1651 int mins = secs/60; secs -= mins*60;
1652 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1654 if( fmt_ctx->nb_programs > 0 )
1655 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
1656 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
1657 report("program %d", i+1);
1658 AVProgram *pgrm = fmt_ctx->programs[i];
1659 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1660 int idx = pgrm->stream_index[j];
1661 int vidx = ffvideo.size();
1662 while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
1664 report(", vid%d", vidx);
1667 int aidx = ffaudio.size();
1668 while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
1670 report(", aud%d", aidx);
1673 report(", (%d)", pgrm->stream_index[j]);
1678 AVDictionaryEntry *tag = 0;
1679 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
1680 report("%s=%s\n", tag->key, tag->value);
1689 int FFMPEG::init_decoder(const char *filename)
1691 ff_lock("FFMPEG::init_decoder");
1693 char file_opts[BCTEXTLEN];
1694 char *bp = strrchr(strcpy(file_opts, filename), '/');
1695 char *sp = strrchr(!bp ? file_opts : bp, '.');
1698 strcpy(sp, ".opts");
1699 fp = fopen(file_opts, "r");
1702 read_options(fp, file_opts, opts);
1706 load_options("decode.opts", opts);
1707 AVDictionary *fopts = 0;
1708 av_dict_copy(&fopts, opts, 0);
1709 int ret = avformat_open_input(&fmt_ctx, filename, NULL, &fopts);
1710 av_dict_free(&fopts);
1712 ret = avformat_find_stream_info(fmt_ctx, NULL);
1717 return !ret ? 0 : 1;
1720 int FFMPEG::open_decoder()
1723 if( stat(fmt_ctx->filename, &st) < 0 ) {
1724 eprintf(_("can't stat file: %s\n"), fmt_ctx->filename);
1728 int64_t file_bits = 8 * st.st_size;
1729 if( !fmt_ctx->bit_rate && opt_duration > 0 )
1730 fmt_ctx->bit_rate = file_bits / opt_duration;
1733 if( fmt_ctx->bit_rate > 0 ) {
1734 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1735 AVStream *st = fmt_ctx->streams[i];
1736 if( st->duration != AV_NOPTS_VALUE ) continue;
1737 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
1738 st->duration = av_rescale(file_bits, st->time_base.den,
1739 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
1744 printf("FFMPEG::open_decoder: some stream times estimated\n");
1746 ff_lock("FFMPEG::open_decoder");
1747 int ret = 0, bad_time = 0;
1748 for( int i=0; !ret && i<(int)fmt_ctx->nb_streams; ++i ) {
1749 AVStream *st = fmt_ctx->streams[i];
1750 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
1751 AVCodecParameters *avpar = st->codecpar;
1752 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avpar->codec_id);
1753 if( !codec_desc ) continue;
1754 switch( avpar->codec_type ) {
1755 case AVMEDIA_TYPE_VIDEO: {
1756 if( avpar->width < 1 ) continue;
1757 if( avpar->height < 1 ) continue;
1758 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
1759 if( framerate.num < 1 ) continue;
1761 int vidx = ffvideo.size();
1762 FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
1763 vstrm_index.append(ffidx(vidx, 0));
1764 ffvideo.append(vid);
1765 vid->width = avpar->width;
1766 vid->height = avpar->height;
1767 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
1768 double secs = to_secs(st->duration, st->time_base);
1769 vid->length = secs * vid->frame_rate;
1770 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
1771 vid->nudge = st->start_time;
1773 if( opt_video_filter )
1774 ret = vid->create_filter(opt_video_filter, avpar);
1776 case AVMEDIA_TYPE_AUDIO: {
1777 if( avpar->channels < 1 ) continue;
1778 if( avpar->sample_rate < 1 ) continue;
1780 int aidx = ffaudio.size();
1781 FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
1782 ffaudio.append(aud);
1783 aud->channel0 = astrm_index.size();
1784 aud->channels = avpar->channels;
1785 for( int ch=0; ch<aud->channels; ++ch )
1786 astrm_index.append(ffidx(aidx, ch));
1787 aud->sample_rate = avpar->sample_rate;
1788 double secs = to_secs(st->duration, st->time_base);
1789 aud->length = secs * aud->sample_rate;
1790 aud->init_swr(aud->channels, avpar->format, aud->sample_rate);
1791 aud->nudge = st->start_time;
1793 if( opt_audio_filter )
1794 ret = aud->create_filter(opt_audio_filter, avpar);
1800 printf("FFMPEG::open_decoder: some stream have bad times\n");
1802 return ret < 0 ? -1 : 0;
1806 int FFMPEG::init_encoder(const char *filename)
1808 int fd = ::open(filename,O_WRONLY);
1809 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
1811 eprintf(_("bad file path: %s\n"), filename);
1815 int ret = get_file_format();
1817 eprintf(_("bad file format: %s\n"), filename);
1821 eprintf(_("mismatch audio/video file format: %s\n"), filename);
1824 ff_lock("FFMPEG::init_encoder");
1826 char format[BCSTRLEN];
1827 if( get_format(format, "format", file_format) )
1828 strcpy(format, file_format);
1829 avformat_alloc_output_context2(&fmt_ctx, 0, format, filename);
1831 eprintf(_("failed: %s\n"), filename);
1836 load_options("encode.opts", opts);
1842 int FFMPEG::open_encoder(const char *type, const char *spec)
1845 Asset *asset = file_base->asset;
1846 char *filename = asset->path;
1847 AVDictionary *sopts = 0;
1848 av_dict_copy(&sopts, opts, 0);
1849 char option_path[BCTEXTLEN];
1850 set_option_path(option_path, "%s/%s.opts", type, type);
1851 read_options(option_path, sopts);
1852 get_option_path(option_path, type, spec);
1853 char format_name[BCSTRLEN], codec_name[BCTEXTLEN], bsfilter[BCTEXTLEN];
1854 if( get_encoder(option_path, format_name, codec_name, bsfilter) ) {
1855 eprintf(_("get_encoder failed %s:%s\n"), option_path, filename);
1859 if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
1860 else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
1861 else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
1864 ff_lock("FFMPEG::open_encoder");
1867 AVCodecContext *ctx = 0;
1869 const AVCodecDescriptor *codec_desc = 0;
1870 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
1872 eprintf(_("cant find codec %s:%s\n"), codec_name, filename);
1876 codec_desc = avcodec_descriptor_get(codec->id);
1878 eprintf(_("unknown codec %s:%s\n"), codec_name, filename);
1883 st = avformat_new_stream(fmt_ctx, 0);
1885 eprintf(_("cant create stream %s:%s\n"), codec_name, filename);
1890 switch( codec_desc->type ) {
1891 case AVMEDIA_TYPE_AUDIO: {
1893 eprintf(_("duplicate audio %s:%s\n"), codec_name, filename);
1897 if( scan_options(asset->ff_audio_options, sopts, st) ) {
1898 eprintf(_("bad audio options %s:%s\n"), codec_name, filename);
1903 ctx = avcodec_alloc_context3(codec);
1904 if( asset->ff_audio_bitrate > 0 ) {
1905 ctx->bit_rate = asset->ff_audio_bitrate;
1907 sprintf(arg, "%d", asset->ff_audio_bitrate);
1908 av_dict_set(&sopts, "b", arg, 0);
1910 int aidx = ffaudio.size();
1911 int fidx = aidx + ffvideo.size();
1912 FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
1913 aud->avctx = ctx; ffaudio.append(aud); fst = aud;
1914 aud->sample_rate = asset->sample_rate;
1915 ctx->channels = aud->channels = asset->channels;
1916 for( int ch=0; ch<aud->channels; ++ch )
1917 astrm_index.append(ffidx(aidx, ch));
1918 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
1919 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
1920 if( !ctx->sample_rate ) {
1921 eprintf(_("check_sample_rate failed %s\n"), filename);
1925 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
1926 ctx->sample_fmt = codec->sample_fmts[0];
1927 uint64_t layout = av_get_default_channel_layout(ctx->channels);
1928 aud->resample_context = swr_alloc_set_opts(NULL,
1929 layout, ctx->sample_fmt, aud->sample_rate,
1930 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
1932 swr_init(aud->resample_context);
1935 case AVMEDIA_TYPE_VIDEO: {
1937 eprintf(_("duplicate video %s:%s\n"), codec_name, filename);
1941 if( scan_options(asset->ff_video_options, sopts, st) ) {
1942 eprintf(_("bad video options %s:%s\n"), codec_name, filename);
1947 ctx = avcodec_alloc_context3(codec);
1948 if( asset->ff_video_bitrate > 0 ) {
1949 ctx->bit_rate = asset->ff_video_bitrate;
1951 sprintf(arg, "%d", asset->ff_video_bitrate);
1952 av_dict_set(&sopts, "b", arg, 0);
1954 else if( asset->ff_video_quality >= 0 ) {
1955 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
1956 ctx->qmin = ctx->qmax = asset->ff_video_quality;
1957 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
1958 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
1959 ctx->flags |= CODEC_FLAG_QSCALE;
1961 av_dict_set(&sopts, "flags", "+qscale", 0);
1962 sprintf(arg, "%d", asset->ff_video_quality);
1963 av_dict_set(&sopts, "qscale", arg, 0);
1964 sprintf(arg, "%d", ctx->global_quality);
1965 av_dict_set(&sopts, "global_quality", arg, 0);
1967 int vidx = ffvideo.size();
1968 int fidx = vidx + ffaudio.size();
1969 FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
1970 vstrm_index.append(ffidx(vidx, 0));
1971 vid->avctx = ctx; ffvideo.append(vid); fst = vid;
1972 vid->width = asset->width;
1973 ctx->width = (vid->width+3) & ~3;
1974 vid->height = asset->height;
1975 ctx->height = (vid->height+3) & ~3;
1976 vid->frame_rate = asset->frame_rate;
1977 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
1978 ctx->pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
1979 AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
1980 if( !frame_rate.num || !frame_rate.den ) {
1981 eprintf(_("check_frame_rate failed %s\n"), filename);
1985 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
1986 st->time_base = ctx->time_base;
1988 vid->interlaced = asset->interlace_mode == ILACE_MODE_TOP_FIRST ||
1989 asset->interlace_mode == ILACE_MODE_BOTTOM_FIRST ? 1 : 0;
1990 vid->top_field_first = asset->interlace_mode == ILACE_MODE_TOP_FIRST ? 1 : 0;
1993 eprintf(_("not audio/video, %s:%s\n"), codec_name, filename);
1998 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
1999 ctx->flags |= CODEC_FLAG_GLOBAL_HEADER;
2001 av_dict_set(&sopts, "cin_bitrate", 0, 0);
2002 av_dict_set(&sopts, "cin_quality", 0, 0);
2004 ret = avcodec_open2(ctx, codec, &sopts);
2006 ret = avcodec_parameters_from_context(st->codecpar, ctx);
2008 fprintf(stderr, "Could not copy the stream parameters\n");
2011 ff_err(ret,"FFMPEG::open_encoder");
2012 eprintf(_("open failed %s:%s\n"), codec_name, filename);
2018 if( !ret && fst && bsfilter[0] ) {
2019 ret = av_bsf_list_parse_str(bsfilter, &fst->bsfc);
2021 ff_err(ret,"FFMPEG::open_encoder");
2022 eprintf(_("bitstream filter failed %s:\n%s\n"), filename, bsfilter);
2033 av_dict_free(&sopts);
2037 int FFMPEG::close_encoder()
2040 if( encoding > 0 ) {
2041 av_write_trailer(fmt_ctx);
2042 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
2043 avio_closep(&fmt_ctx->pb);
2049 int FFMPEG::decode_activate()
2051 if( decoding < 0 ) {
2053 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
2054 ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
2055 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
2056 ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
2057 // set nudges for each program stream set
2058 const int64_t min_nudge = INT64_MIN+1;
2059 int npgrms = fmt_ctx->nb_programs;
2060 for( int i=0; i<npgrms; ++i ) {
2061 AVProgram *pgrm = fmt_ctx->programs[i];
2062 // first start time video stream
2063 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2064 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2065 int fidx = pgrm->stream_index[j];
2066 AVStream *st = fmt_ctx->streams[fidx];
2067 AVCodecParameters *avpar = st->codecpar;
2068 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2069 if( st->start_time == AV_NOPTS_VALUE ) continue;
2070 if( vstart_time < st->start_time )
2071 vstart_time = st->start_time;
2074 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2075 if( st->start_time == AV_NOPTS_VALUE ) continue;
2076 if( astart_time < st->start_time )
2077 astart_time = st->start_time;
2081 //since frame rate is much more grainy than sample rate, it is better to
2082 // align using video, so that total absolute error is minimized.
2083 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2084 astart_time > min_nudge ? astart_time : AV_NOPTS_VALUE;
2085 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2086 int fidx = pgrm->stream_index[j];
2087 AVStream *st = fmt_ctx->streams[fidx];
2088 AVCodecParameters *avpar = st->codecpar;
2089 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2090 for( int k=0; k<ffvideo.size(); ++k ) {
2091 if( ffvideo[k]->fidx != fidx ) continue;
2092 ffvideo[k]->nudge = nudge;
2096 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2097 for( int k=0; k<ffaudio.size(); ++k ) {
2098 if( ffaudio[k]->fidx != fidx ) continue;
2099 ffaudio[k]->nudge = nudge;
2105 // set nudges for any streams not yet set
2106 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2107 int nstreams = fmt_ctx->nb_streams;
2108 for( int i=0; i<nstreams; ++i ) {
2109 AVStream *st = fmt_ctx->streams[i];
2110 AVCodecParameters *avpar = st->codecpar;
2111 switch( avpar->codec_type ) {
2112 case AVMEDIA_TYPE_VIDEO: {
2113 if( st->start_time == AV_NOPTS_VALUE ) continue;
2114 int vidx = ffvideo.size();
2115 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
2116 if( vidx < 0 ) continue;
2117 if( ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
2118 if( vstart_time < st->start_time )
2119 vstart_time = st->start_time;
2121 case AVMEDIA_TYPE_AUDIO: {
2122 if( st->start_time == AV_NOPTS_VALUE ) continue;
2123 int aidx = ffaudio.size();
2124 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
2125 if( aidx < 0 ) continue;
2126 if( ffaudio[aidx]->frame_sz < avpar->frame_size )
2127 ffaudio[aidx]->frame_sz = avpar->frame_size;
2128 if( ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
2129 if( astart_time < st->start_time )
2130 astart_time = st->start_time;
2135 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2136 astart_time > min_nudge ? astart_time : 0;
2137 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
2138 if( ffvideo[vidx]->nudge == AV_NOPTS_VALUE )
2139 ffvideo[vidx]->nudge = nudge;
2141 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2142 if( ffaudio[aidx]->nudge == AV_NOPTS_VALUE )
2143 ffaudio[aidx]->nudge = nudge;
2150 int FFMPEG::encode_activate()
2153 if( encoding < 0 ) {
2155 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
2156 (ret=avio_open(&fmt_ctx->pb, fmt_ctx->filename, AVIO_FLAG_WRITE)) < 0 ) {
2157 ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
2163 AVProgram *prog = av_new_program(fmt_ctx, prog_id);
2164 for( int i=0; i< ffvideo.size(); ++i )
2165 av_program_add_stream_index(fmt_ctx, prog_id, ffvideo[i]->fidx);
2166 for( int i=0; i< ffaudio.size(); ++i )
2167 av_program_add_stream_index(fmt_ctx, prog_id, ffaudio[i]->fidx);
2168 int pi = fmt_ctx->nb_programs;
2169 while( --pi >= 0 && fmt_ctx->programs[pi]->id != prog_id );
2170 AVDictionary **meta = &prog->metadata;
2171 av_dict_set(meta, "service_provider", "cin5", 0);
2172 const char *path = fmt_ctx->filename, *bp = strrchr(path,'/');
2173 if( bp ) path = bp + 1;
2174 av_dict_set(meta, "title", path, 0);
2176 if( ffaudio.size() ) {
2177 const char *ep = getenv("CIN_AUDIO_LANG"), *lp = 0;
2178 if( !ep && (lp=getenv("LANG")) ) { // some are guesses
2179 static struct { const char lc[3], lng[4]; } lcode[] = {
2180 { "en", "eng" }, { "de", "ger" }, { "es", "spa" },
2181 { "eu", "bas" }, { "fr", "fre" }, { "el", "gre" },
2182 { "hi", "hin" }, { "it", "ita" }, { "ja", "jap" },
2183 { "ko", "kor" }, { "du", "dut" }, { "pl", "pol" },
2184 { "pt", "por" }, { "ru", "rus" }, { "sl", "slv" },
2185 { "uk", "ukr" }, { "vi", "vie" }, { "zh", "chi" },
2187 for( int i=sizeof(lcode)/sizeof(lcode[0]); --i>=0 && !ep; )
2188 if( !strncmp(lcode[i].lc,lp,2) ) ep = lcode[i].lng;
2190 if( !ep ) ep = "und";
2192 strncpy(lang,ep,3); lang[3] = 0;
2193 AVStream *st = ffaudio[0]->st;
2194 av_dict_set(&st->metadata,"language",lang,0);
2197 AVDictionary *fopts = 0;
2198 char option_path[BCTEXTLEN];
2199 set_option_path(option_path, "format/%s", file_format);
2200 read_options(option_path, fopts, 1);
2201 ret = avformat_write_header(fmt_ctx, &fopts);
2203 ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
2207 av_dict_free(&fopts);
2214 int FFMPEG::audio_seek(int stream, int64_t pos)
2216 int aidx = astrm_index[stream].st_idx;
2217 FFAudioStream *aud = ffaudio[aidx];
2218 aud->audio_seek(pos);
2222 int FFMPEG::video_seek(int stream, int64_t pos)
2224 int vidx = vstrm_index[stream].st_idx;
2225 FFVideoStream *vid = ffvideo[vidx];
2226 vid->video_seek(pos);
2231 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
2233 if( !has_audio || chn >= astrm_index.size() ) return -1;
2234 int aidx = astrm_index[chn].st_idx;
2235 FFAudioStream *aud = ffaudio[aidx];
2236 if( aud->load(pos, len) < len ) return -1;
2237 int ch = astrm_index[chn].st_ch;
2238 int ret = aud->read(samples,len,ch);
2242 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
2244 if( !has_video || layer >= vstrm_index.size() ) return -1;
2245 int vidx = vstrm_index[layer].st_idx;
2246 FFVideoStream *vid = ffvideo[vidx];
2247 return vid->load(vframe, pos);
2251 int FFMPEG::encode(int stream, double **samples, int len)
2253 FFAudioStream *aud = ffaudio[stream];
2254 return aud->encode(samples, len);
2258 int FFMPEG::encode(int stream, VFrame *frame)
2260 FFVideoStream *vid = ffvideo[stream];
2261 return vid->encode(frame);
2264 void FFMPEG::start_muxer()
2272 void FFMPEG::stop_muxer()
2281 void FFMPEG::flow_off()
2284 flow_lock->lock("FFMPEG::flow_off");
2288 void FFMPEG::flow_on()
2292 flow_lock->unlock();
2295 void FFMPEG::flow_ctl()
2298 flow_lock->lock("FFMPEG::flow_ctl");
2299 flow_lock->unlock();
2303 int FFMPEG::mux_audio(FFrame *frm)
2305 FFStream *fst = frm->fst;
2306 AVCodecContext *ctx = fst->avctx;
2307 AVFrame *frame = *frm;
2308 AVRational tick_rate = {1, ctx->sample_rate};
2309 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
2310 int ret = fst->encode_frame(frame);
2312 ff_err(ret, "FFMPEG::mux_audio");
2313 return ret >= 0 ? 0 : 1;
2316 int FFMPEG::mux_video(FFrame *frm)
2318 FFStream *fst = frm->fst;
2319 AVFrame *frame = *frm;
2320 frame->pts = frm->position;
2321 int ret = fst->encode_frame(frame);
2323 ff_err(ret, "FFMPEG::mux_video");
2324 return ret >= 0 ? 0 : 1;
2330 double atm = -1, vtm = -1;
2331 FFrame *afrm = 0, *vfrm = 0;
2333 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
2334 FFStream *fst = ffaudio[i];
2335 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
2336 FFrame *frm = fst->frms.first;
2337 if( !frm ) { if( !done ) return; continue; }
2338 double tm = to_secs(frm->position, fst->avctx->time_base);
2339 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
2341 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
2342 FFStream *fst = ffvideo[i];
2343 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
2344 FFrame *frm = fst->frms.first;
2345 if( !frm ) { if( !done ) return; continue; }
2346 double tm = to_secs(frm->position, fst->avctx->time_base);
2347 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
2349 if( !demand ) flow_off();
2350 if( !afrm && !vfrm ) break;
2351 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
2352 vfrm->position, vfrm->fst->avctx->time_base,
2353 afrm->position, afrm->fst->avctx->time_base);
2354 FFrame *frm = v <= 0 ? vfrm : afrm;
2355 if( frm == afrm ) mux_audio(frm);
2356 if( frm == vfrm ) mux_video(frm);
2365 mux_lock->lock("FFMPEG::run");
2368 for( int i=0; i<ffaudio.size(); ++i )
2369 ffaudio[i]->drain();
2370 for( int i=0; i<ffvideo.size(); ++i )
2371 ffvideo[i]->drain();
2373 for( int i=0; i<ffaudio.size(); ++i )
2374 ffaudio[i]->flush();
2375 for( int i=0; i<ffvideo.size(); ++i )
2376 ffvideo[i]->flush();
2380 int FFMPEG::ff_total_audio_channels()
2382 return astrm_index.size();
2385 int FFMPEG::ff_total_astreams()
2387 return ffaudio.size();
2390 int FFMPEG::ff_audio_channels(int stream)
2392 return ffaudio[stream]->channels;
2395 int FFMPEG::ff_sample_rate(int stream)
2397 return ffaudio[stream]->sample_rate;
2400 const char* FFMPEG::ff_audio_format(int stream)
2402 AVStream *st = ffaudio[stream]->st;
2403 AVCodecID id = st->codecpar->codec_id;
2404 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2405 return desc ? desc->name : _("Unknown");
2408 int FFMPEG::ff_audio_pid(int stream)
2410 return ffaudio[stream]->st->id;
2413 int64_t FFMPEG::ff_audio_samples(int stream)
2415 return ffaudio[stream]->length;
2418 // find audio astream/channels with this program,
2419 // or all program audio channels (astream=-1)
2420 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
2424 int vidx = ffvideo[vstream]->fidx;
2425 // find first program with this video stream
2426 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
2427 AVProgram *pgrm = fmt_ctx->programs[i];
2428 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
2429 int st_idx = pgrm->stream_index[j];
2430 AVStream *st = fmt_ctx->streams[st_idx];
2431 if( st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
2432 if( st_idx == vidx ) pidx = i;
2435 if( pidx < 0 ) return -1;
2437 int64_t channels = 0;
2438 AVProgram *pgrm = fmt_ctx->programs[pidx];
2439 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2440 int aidx = pgrm->stream_index[j];
2441 AVStream *st = fmt_ctx->streams[aidx];
2442 if( st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
2443 if( astream > 0 ) { --astream; continue; }
2445 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
2446 if( ffaudio[i]->fidx == aidx ) astrm = i;
2448 if( ret < 0 ) ret = astrm;
2449 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
2450 channels |= mask << ffaudio[astrm]->channel0;
2452 if( !astream ) break;
2454 channel_mask = channels;
2459 int FFMPEG::ff_total_video_layers()
2461 return vstrm_index.size();
2464 int FFMPEG::ff_total_vstreams()
2466 return ffvideo.size();
2469 int FFMPEG::ff_video_width(int stream)
2471 return ffvideo[stream]->width;
2474 int FFMPEG::ff_video_height(int stream)
2476 return ffvideo[stream]->height;
2479 int FFMPEG::ff_set_video_width(int stream, int width)
2481 int w = ffvideo[stream]->width;
2482 ffvideo[stream]->width = width;
2486 int FFMPEG::ff_set_video_height(int stream, int height)
2488 int h = ffvideo[stream]->height;
2489 ffvideo[stream]->height = height;
2493 int FFMPEG::ff_coded_width(int stream)
2495 return ffvideo[stream]->avctx->coded_width;
2498 int FFMPEG::ff_coded_height(int stream)
2500 return ffvideo[stream]->avctx->coded_height;
2503 float FFMPEG::ff_aspect_ratio(int stream)
2505 return ffvideo[stream]->aspect_ratio;
2508 const char* FFMPEG::ff_video_format(int stream)
2510 AVStream *st = ffvideo[stream]->st;
2511 AVCodecID id = st->codecpar->codec_id;
2512 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2513 return desc ? desc->name : _("Unknown");
2516 double FFMPEG::ff_frame_rate(int stream)
2518 return ffvideo[stream]->frame_rate;
2521 int64_t FFMPEG::ff_video_frames(int stream)
2523 return ffvideo[stream]->length;
2526 int FFMPEG::ff_video_pid(int stream)
2528 return ffvideo[stream]->st->id;
2532 int FFMPEG::ff_cpus()
2534 return file_base->file->cpus;
2537 int FFVideoStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
2539 avfilter_register_all();
2540 const char *sp = filter_spec;
2541 char filter_name[BCSTRLEN], *np = filter_name;
2542 int i = sizeof(filter_name);
2543 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
2545 AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
2546 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_VIDEO ) {
2547 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
2550 filter_graph = avfilter_graph_alloc();
2551 AVFilter *buffersrc = avfilter_get_by_name("buffer");
2552 AVFilter *buffersink = avfilter_get_by_name("buffersink");
2554 int ret = 0; char args[BCTEXTLEN];
2555 AVPixelFormat pix_fmt = (AVPixelFormat)avpar->format;
2556 snprintf(args, sizeof(args),
2557 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
2558 avpar->width, avpar->height, (int)pix_fmt,
2559 st->time_base.num, st->time_base.den,
2560 avpar->sample_aspect_ratio.num, avpar->sample_aspect_ratio.den);
2562 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2563 args, NULL, filter_graph);
2565 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2566 NULL, NULL, filter_graph);
2568 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
2569 (uint8_t*)&pix_fmt, sizeof(pix_fmt),
2570 AV_OPT_SEARCH_CHILDREN);
2572 ff_err(ret, "FFVideoStream::create_filter");
2574 ret = FFStream::create_filter(filter_spec);
2575 return ret >= 0 ? 0 : -1;
2578 int FFAudioStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
2580 avfilter_register_all();
2581 const char *sp = filter_spec;
2582 char filter_name[BCSTRLEN], *np = filter_name;
2583 int i = sizeof(filter_name);
2584 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
2586 AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
2587 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_AUDIO ) {
2588 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
2591 filter_graph = avfilter_graph_alloc();
2592 AVFilter *buffersrc = avfilter_get_by_name("abuffer");
2593 AVFilter *buffersink = avfilter_get_by_name("abuffersink");
2594 int ret = 0; char args[BCTEXTLEN];
2595 AVSampleFormat sample_fmt = (AVSampleFormat)avpar->format;
2596 snprintf(args, sizeof(args),
2597 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
2598 st->time_base.num, st->time_base.den, avpar->sample_rate,
2599 av_get_sample_fmt_name(sample_fmt), avpar->channel_layout);
2601 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2602 args, NULL, filter_graph);
2604 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2605 NULL, NULL, filter_graph);
2607 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
2608 (uint8_t*)&sample_fmt, sizeof(sample_fmt),
2609 AV_OPT_SEARCH_CHILDREN);
2611 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
2612 (uint8_t*)&avpar->channel_layout,
2613 sizeof(avpar->channel_layout), AV_OPT_SEARCH_CHILDREN);
2615 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
2616 (uint8_t*)&sample_rate, sizeof(sample_rate),
2617 AV_OPT_SEARCH_CHILDREN);
2619 ff_err(ret, "FFAudioStream::create_filter");
2621 ret = FFStream::create_filter(filter_spec);
2622 return ret >= 0 ? 0 : -1;
2625 int FFStream::create_filter(const char *filter_spec)
2627 /* Endpoints for the filter graph. */
2628 AVFilterInOut *outputs = avfilter_inout_alloc();
2629 outputs->name = av_strdup("in");
2630 outputs->filter_ctx = buffersrc_ctx;
2631 outputs->pad_idx = 0;
2634 AVFilterInOut *inputs = avfilter_inout_alloc();
2635 inputs->name = av_strdup("out");
2636 inputs->filter_ctx = buffersink_ctx;
2637 inputs->pad_idx = 0;
2640 int ret = !outputs->name || !inputs->name ? -1 : 0;
2642 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
2643 &inputs, &outputs, NULL);
2645 ret = avfilter_graph_config(filter_graph, NULL);
2648 ff_err(ret, "FFStream::create_filter");
2649 avfilter_graph_free(&filter_graph);
2652 avfilter_inout_free(&inputs);
2653 avfilter_inout_free(&outputs);
2657 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
2660 av_init_packet(&pkt);
2661 AVFrame *frame = av_frame_alloc();
2663 fprintf(stderr,"FFMPEG::scan: ");
2664 fprintf(stderr,_("av_frame_alloc failed\n"));
2668 index_state->add_video_markers(ffvideo.size());
2669 index_state->add_audio_markers(ffaudio.size());
2671 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2673 AVDictionary *copts = 0;
2674 av_dict_copy(&copts, opts, 0);
2675 AVStream *st = fmt_ctx->streams[i];
2676 AVCodecID codec_id = st->codecpar->codec_id;
2677 AVCodec *decoder = avcodec_find_decoder(codec_id);
2678 AVCodecContext *avctx = avcodec_alloc_context3(decoder);
2680 eprintf(_("cant allocate codec context\n"));
2681 ret = AVERROR(ENOMEM);
2684 avcodec_parameters_to_context(avctx, st->codecpar);
2685 ret = avcodec_open2(avctx, decoder, &copts);
2687 av_dict_free(&copts);
2689 AVCodecParameters *avpar = st->codecpar;
2690 switch( avpar->codec_type ) {
2691 case AVMEDIA_TYPE_VIDEO: {
2692 int vidx = ffvideo.size();
2693 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
2694 if( vidx < 0 ) break;
2695 ffvideo[vidx]->avctx = avctx;
2697 case AVMEDIA_TYPE_AUDIO: {
2698 int aidx = ffaudio.size();
2699 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
2700 if( aidx < 0 ) break;
2701 ffaudio[aidx]->avctx = avctx;
2706 fprintf(stderr,"FFMPEG::scan: ");
2707 fprintf(stderr,_("codec open failed\n"));
2708 avcodec_free_context(&avctx);
2712 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2713 AVStream *st = fmt_ctx->streams[i];
2714 AVCodecParameters *avpar = st->codecpar;
2715 if( avpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
2716 int64_t tstmp = st->start_time;
2717 if( tstmp == AV_NOPTS_VALUE ) continue;
2718 int aidx = ffaudio.size();
2719 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
2720 if( aidx < 0 ) continue;
2721 FFAudioStream *aud = ffaudio[aidx];
2722 tstmp -= aud->nudge;
2723 double secs = to_secs(tstmp, st->time_base);
2724 aud->curr_pos = secs * aud->sample_rate + 0.5;
2728 for( int64_t count=0; !*canceled; ++count ) {
2729 av_packet_unref(&pkt);
2730 pkt.data = 0; pkt.size = 0;
2732 int ret = av_read_frame(fmt_ctx, &pkt);
2734 if( ret == AVERROR_EOF ) break;
2735 if( ++errs > 100 ) {
2736 ff_err(ret,_("over 100 read_frame errs\n"));
2741 if( !pkt.data ) continue;
2742 int i = pkt.stream_index;
2743 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
2744 AVStream *st = fmt_ctx->streams[i];
2745 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
2747 AVCodecParameters *avpar = st->codecpar;
2748 switch( avpar->codec_type ) {
2749 case AVMEDIA_TYPE_VIDEO: {
2750 int vidx = ffvideo.size();
2751 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
2752 if( vidx < 0 ) break;
2753 FFVideoStream *vid = ffvideo[vidx];
2754 if( !vid->avctx ) break;
2755 int64_t tstmp = pkt.dts;
2756 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.pts;
2757 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
2758 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
2759 double secs = to_secs(tstmp, st->time_base);
2760 int64_t frm = secs * vid->frame_rate + 0.5;
2761 if( frm < 0 ) frm = 0;
2762 index_state->put_video_mark(vidx, frm, pkt.pos);
2765 ret = avcodec_send_packet(vid->avctx, pkt);
2766 if( ret < 0 ) break;
2767 while( (ret=vid->decode_frame(frame)) > 0 ) {}
2770 case AVMEDIA_TYPE_AUDIO: {
2771 int aidx = ffaudio.size();
2772 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
2773 if( aidx < 0 ) break;
2774 FFAudioStream *aud = ffaudio[aidx];
2775 if( !aud->avctx ) break;
2776 int64_t tstmp = pkt.pts;
2777 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
2778 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
2779 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
2780 double secs = to_secs(tstmp, st->time_base);
2781 int64_t sample = secs * aud->sample_rate + 0.5;
2783 index_state->put_audio_mark(aidx, sample, pkt.pos);
2785 ret = avcodec_send_packet(aud->avctx, &pkt);
2786 if( ret < 0 ) break;
2787 int ch = aud->channel0, nch = aud->channels;
2788 int64_t pos = index_state->pos(ch);
2789 if( pos != aud->curr_pos ) {
2790 if( abs(pos-aud->curr_pos) > 1 )
2791 printf("audio%d pad %jd %jd (%jd)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
2792 index_state->pad_data(ch, nch, aud->curr_pos);
2794 while( (ret=aud->decode_frame(frame)) > 0 ) {
2795 //if( frame->channels != nch ) break;
2796 aud->init_swr(frame->channels, frame->format, frame->sample_rate);
2798 int len = aud->get_samples(samples,
2799 &frame->extended_data[0], frame->nb_samples);
2800 pos = aud->curr_pos;
2801 if( (aud->curr_pos += len) >= 0 ) {
2803 samples += -pos * nch;
2804 len = aud->curr_pos;
2806 for( int i=0; i<nch; ++i )
2807 index_state->put_data(ch+i,nch,samples+i,len);
2814 av_frame_free(&frame);
2818 void FFStream::load_markers(IndexMarks &marks, double rate)
2821 int64_t sz = marks.size();
2822 int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
2823 int nb_ent = st->nb_index_entries;
2824 // some formats already have an index
2826 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
2827 int64_t tstmp = ep->timestamp;
2828 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
2829 double secs = ffmpeg->to_secs(tstmp, st->time_base);
2830 int64_t no = secs * rate;
2831 while( in < sz && marks[in].no <= no ) ++in;
2833 int64_t len = sz - in;
2834 int64_t count = max_entries - nb_ent;
2835 if( count > len ) count = len;
2836 for( int i=0; i<count; ++i ) {
2837 int k = in + i * len / count;
2838 int64_t no = marks[k].no, pos = marks[k].pos;
2839 double secs = (double)no / rate;
2840 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
2841 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
2842 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);