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 av_frame_unref(frame);
400 int ret = av_buffersrc_add_frame_flags(buffersrc_ctx,
401 frame, AV_BUFFERSRC_FLAG_KEEP_REF);
403 eprintf(_("av_buffersrc_add_frame_flags failed\n"));
407 int FFStream::read_filter(AVFrame *frame)
409 int ret = av_buffersink_get_frame(buffersink_ctx, frame);
411 if( ret == AVERROR(EAGAIN) ) return 0;
412 if( ret == AVERROR_EOF ) { st_eof(1); return -1; }
413 ff_err(ret, "FFStream::read_filter: av_buffersink_get_frame failed\n");
419 int FFStream::read_frame(AVFrame *frame)
421 av_frame_unref(frame);
422 if( !filter_graph || !buffersrc_ctx || !buffersink_ctx )
423 return decode(frame);
424 if( !fframe && !(fframe=av_frame_alloc()) ) {
425 fprintf(stderr, "FFStream::read_frame: av_frame_alloc failed\n");
429 while( !flushed && !(ret=read_filter(frame)) ) {
430 if( (ret=decode(fframe)) < 0 ) break;
431 if( ret > 0 && (ret=load_filter(fframe)) < 0 ) break;
436 int FFStream::write_packet(FFPacket &pkt)
440 av_packet_rescale_ts(pkt, avctx->time_base, st->time_base);
441 pkt->stream_index = st->index;
442 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, pkt);
445 ret = av_bsf_send_packet(bsfc, pkt);
448 if( (ret=av_bsf_receive_packet(bsfc, bs)) < 0 ) {
449 if( ret == AVERROR(EAGAIN) ) return 0;
450 if( ret == AVERROR_EOF ) return -1;
453 av_packet_rescale_ts(bs, avctx->time_base, st->time_base);
454 bs->stream_index = st->index;
455 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, bs);
459 ff_err(ret, "FFStream::write_packet: write packet failed\n");
463 int FFStream::encode_frame(AVFrame *frame)
465 int pkts = 0, ret = 0;
466 for( int retry=100; --retry>=0; ) {
468 ret = avcodec_send_frame(avctx, frame);
469 if( !ret && frame ) return pkts;
470 if( ret < 0 && ret != AVERROR(EAGAIN) ) break;
472 ret = avcodec_receive_packet(avctx, opkt);
473 if( !frame && ret == AVERROR_EOF ) return pkts;
475 ret = write_packet(opkt);
479 ff_err(ret, "FFStream::encode_frame: encode failed\n");
483 int FFStream::flush()
487 int ret = encode_frame(0);
489 ff_err(ret, "FFStream::flush");
490 return ret >= 0 ? 0 : 1;
493 int FFStream::seek(int64_t no, double rate)
495 // default ffmpeg native seek
497 int64_t pos = no, pkt_pos = -1;
498 IndexMarks *index_markers = get_markers();
499 if( index_markers && index_markers->size() > 1 ) {
500 IndexMarks &marks = *index_markers;
501 int i = marks.find(pos);
502 int64_t n = i < 0 ? (i=0) : marks[i].no;
503 // if indexed seek point not too far away (<30 secs), use index
504 if( no-n < 30*rate ) {
507 if( i < marks.size() ) pkt_pos = marks[i].pos;
511 if( pos == curr_pos ) return 0;
512 double secs = pos < 0 ? 0. : pos / rate;
513 AVRational time_base = st->time_base;
514 int64_t tstmp = time_base.num > 0 ? secs * time_base.den/time_base.num : 0;
516 if( st->nb_index_entries > 0 ) tstmp = st->index_entries[0].timestamp;
517 else if( st->start_time != AV_NOPTS_VALUE ) tstmp = st->start_time;
518 else if( st->first_dts != AV_NOPTS_VALUE ) tstmp = st->first_dts;
519 else tstmp = INT64_MIN+1;
521 else if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
524 // seek all streams using the default timebase.
525 // this is how ffmpeg and ffplay work. stream seeks are less tested.
526 tstmp = av_rescale_q(tstmp, time_base, AV_TIME_BASE_Q);
530 avcodec_flush_buffers(avctx);
531 avformat_flush(fmt_ctx);
533 int64_t seek = tstmp;
534 int flags = AVSEEK_FLAG_ANY;
535 if( !(fmt_ctx->iformat->flags & AVFMT_NO_BYTE_SEEK) && pkt_pos >= 0 ) {
537 flags = AVSEEK_FLAG_BYTE;
539 int ret = avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, seek, INT64_MAX, flags);
541 // finds the first index frame below the target time
542 int flags = AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_ANY;
543 int ret = av_seek_frame(fmt_ctx, idx, tstmp, flags);
545 int retry = MAX_RETRY;
547 need_packet = 0; flushed = 0;
548 seeked = 1; st_eof(0);
549 // read up to retry packets, limited to npkts in stream, and not pkt.pos past pkt_pos
550 while( --retry >= 0 ) {
551 if( read_packet() <= 0 ) { ret = -1; break; }
552 if( ipkt->stream_index != st->index ) continue;
553 if( !ipkt->data || !ipkt->size ) continue;
554 if( pkt_pos >= 0 && ipkt->pos >= pkt_pos ) break;
555 if( --npkts <= 0 ) break;
556 int64_t pkt_ts = ipkt->dts != AV_NOPTS_VALUE ? ipkt->dts : ipkt->pts;
557 if( pkt_ts == AV_NOPTS_VALUE ) continue;
558 if( pkt_ts >= tstmp ) break;
561 fprintf(stderr,"FFStream::seek: retry limit, pos=%jd tstmp=%jd\n",pos,tstmp);
565 ret = avcodec_send_packet(avctx, ipkt);
567 //some codecs need more than one pkt to resync
568 if( ret == AVERROR_INVALIDDATA ) ret = 0;
570 ff_err(ret, "FFStream::avcodec_send_packet failed\n");
575 printf("** seek fail %jd, %jd\n", pos, tstmp);
576 seeked = need_packet = 0;
580 //printf("seeked pos = %ld, %ld\n", pos, tstmp);
581 seek_pos = curr_pos = pos;
585 FFAudioStream::FFAudioStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
586 : FFStream(ffmpeg, strm, fidx)
589 channel0 = channels = 0;
592 frame_sz = AUDIO_MIN_FRAME_SZ;
594 resample_context = 0;
595 swr_ichs = swr_ifmt = swr_irate = 0;
604 bfr = new float[bsz];
609 FFAudioStream::~FFAudioStream()
611 if( resample_context ) swr_free(&resample_context);
616 void FFAudioStream::init_swr(int ichs, int ifmt, int irate)
618 if( resample_context ) {
619 if( swr_ichs == ichs && swr_ifmt == ifmt && swr_irate == irate )
621 swr_free(&resample_context);
623 swr_ichs = ichs; swr_ifmt = ifmt; swr_irate = irate;
624 if( ichs == channels && ifmt == AV_SAMPLE_FMT_FLT && irate == sample_rate )
626 uint64_t ilayout = av_get_default_channel_layout(ichs);
627 if( !ilayout ) ilayout = ((uint64_t)1<<ichs) - 1;
628 uint64_t olayout = av_get_default_channel_layout(channels);
629 if( !olayout ) olayout = ((uint64_t)1<<channels) - 1;
630 resample_context = swr_alloc_set_opts(NULL,
631 olayout, AV_SAMPLE_FMT_FLT, sample_rate,
632 ilayout, (AVSampleFormat)ifmt, irate,
634 if( resample_context )
635 swr_init(resample_context);
638 int FFAudioStream::get_samples(float *&samples, uint8_t **data, int len)
640 samples = *(float **)data;
641 if( resample_context ) {
642 if( len > aud_bfr_sz ) {
648 aud_bfr = new float[aud_bfr_sz*channels];
650 int ret = swr_convert(resample_context,
651 (uint8_t**)&aud_bfr, aud_bfr_sz, (const uint8_t**)data, len);
653 ff_err(ret, "FFAudioStream::get_samples: swr_convert failed\n");
662 int FFAudioStream::load_history(uint8_t **data, int len)
665 len = get_samples(samples, data, len);
667 // biggest user bfr since seek + frame
668 realloc(mbsz + len + 1, channels);
674 int FFAudioStream::decode_frame(AVFrame *frame)
676 int first_frame = seeked; seeked = 0;
677 int ret = avcodec_receive_frame(avctx, frame);
679 if( first_frame || ret == AVERROR(EAGAIN) ) return 0;
680 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
681 ff_err(ret, "FFAudioStream::decode_frame: Could not read audio frame\n");
684 int64_t pkt_ts = av_frame_get_best_effort_timestamp(frame);
685 if( pkt_ts != AV_NOPTS_VALUE )
686 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * sample_rate + 0.5;
690 int FFAudioStream::encode_activate()
692 if( writing >= 0 ) return writing;
693 frame_sz = avctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE ?
694 10000 : avctx->frame_size;
695 return FFStream::encode_activate();
698 int64_t FFAudioStream::load_buffer(double ** const sp, int len)
700 reserve(len+1, st->codecpar->channels);
701 for( int ch=0; ch<nch; ++ch )
702 write(sp[ch], len, ch);
706 int FFAudioStream::in_history(int64_t pos)
708 if( pos > curr_pos ) return 0;
710 if( len > sz ) len = sz;
711 if( pos < curr_pos - len ) return 0;
716 int FFAudioStream::init_frame(AVFrame *frame)
718 frame->nb_samples = frame_sz;
719 frame->format = avctx->sample_fmt;
720 frame->channel_layout = avctx->channel_layout;
721 frame->sample_rate = avctx->sample_rate;
722 int ret = av_frame_get_buffer(frame, 0);
724 ff_err(ret, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
728 int FFAudioStream::load(int64_t pos, int len)
730 if( audio_seek(pos) < 0 ) return -1;
731 if( !frame && !(frame=av_frame_alloc()) ) {
732 fprintf(stderr, "FFAudioStream::load: av_frame_alloc failed\n");
735 if( mbsz < len ) mbsz = len;
736 int64_t end_pos = pos + len;
737 int ret = 0, i = len / frame_sz + MAX_RETRY;
738 while( ret>=0 && !flushed && curr_pos<end_pos && --i>=0 ) {
739 ret = read_frame(frame);
740 if( ret > 0 && frame->nb_samples > 0 ) {
741 init_swr(frame->channels, frame->format, frame->sample_rate);
742 load_history(&frame->extended_data[0], frame->nb_samples);
743 curr_pos += frame->nb_samples;
746 if( end_pos > curr_pos ) {
747 zero(end_pos - curr_pos);
750 len = curr_pos - pos;
755 int FFAudioStream::audio_seek(int64_t pos)
757 if( decode_activate() <= 0 ) return -1;
758 if( !st->codecpar ) return -1;
759 if( in_history(pos) ) return 0;
760 if( pos == curr_pos ) return 0;
761 reset_history(); mbsz = 0;
762 // guarentee preload > 1sec samples
763 if( seek(pos-sample_rate, sample_rate) < 0 ) return -1;
767 int FFAudioStream::encode(double **samples, int len)
769 if( encode_activate() <= 0 ) return -1;
772 int64_t count = samples ? load_buffer(samples, len) : used();
773 int frame_sz1 = samples ? frame_sz-1 : 0;
776 while( ret >= 0 && count > frame_sz1 ) {
777 frm = new FFrame(this);
778 if( (ret=frm->initted()) < 0 ) break;
779 AVFrame *frame = *frm;
780 len = count >= frame_sz ? frame_sz : count;
781 float *bfrp = get_outp(len);
782 ret = swr_convert(resample_context,
783 (uint8_t **)frame->extended_data, len,
784 (const uint8_t **)&bfrp, len);
786 ff_err(ret, "FFAudioStream::encode: swr_convert failed\n");
789 frame->nb_samples = len;
790 frm->queue(curr_pos);
797 return ret >= 0 ? 0 : 1;
800 int FFAudioStream::drain()
805 int FFAudioStream::encode_frame(AVFrame *frame)
807 return FFStream::encode_frame(frame);
810 int FFAudioStream::write_packet(FFPacket &pkt)
812 return FFStream::write_packet(pkt);
815 void FFAudioStream::load_markers()
817 IndexState *index_state = ffmpeg->file_base->asset->index_state;
818 if( !index_state || idx >= index_state->audio_markers.size() ) return;
819 if( index_state->marker_status == MARKERS_NOTTESTED ) return;
820 FFStream::load_markers(*index_state->audio_markers[idx], sample_rate);
823 IndexMarks *FFAudioStream::get_markers()
825 IndexState *index_state = ffmpeg->file_base->asset->index_state;
826 if( !index_state || idx >= index_state->audio_markers.size() ) return 0;
827 return index_state->audio_markers[idx];
830 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
831 : FFStream(ffmpeg, strm, fidx)
842 FFVideoStream::~FFVideoStream()
846 int FFVideoStream::decode_frame(AVFrame *frame)
848 int first_frame = seeked; seeked = 0;
849 int ret = avcodec_receive_frame(avctx, frame);
851 if( first_frame || ret == AVERROR(EAGAIN) ) return 0;
852 if( ret == AVERROR(EAGAIN) ) return 0;
853 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
854 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame\n");
857 int64_t pkt_ts = av_frame_get_best_effort_timestamp(frame);
858 if( pkt_ts != AV_NOPTS_VALUE )
859 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * frame_rate + 0.5;
863 int FFVideoStream::load(VFrame *vframe, int64_t pos)
865 int ret = video_seek(pos);
866 if( ret < 0 ) return -1;
867 if( !frame && !(frame=av_frame_alloc()) ) {
868 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
871 int i = MAX_RETRY + pos - curr_pos;
872 while( ret>=0 && !flushed && curr_pos<=pos && --i>=0 ) {
873 ret = read_frame(frame);
874 if( ret > 0 ) ++curr_pos;
876 if( frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0 )
879 ret = convert_cmodel(vframe, frame);
881 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
885 int FFVideoStream::video_seek(int64_t pos)
887 if( decode_activate() <= 0 ) return -1;
888 if( !st->codecpar ) return -1;
889 if( pos == curr_pos-1 && !seeked ) return 0;
890 // if close enough, just read up to current
891 int gop = avctx->gop_size;
892 if( gop < 4 ) gop = 4;
893 if( gop > 64 ) gop = 64;
894 int read_limit = curr_pos + 3*gop;
895 if( pos >= curr_pos && pos <= read_limit ) return 0;
896 // guarentee preload more than 2*gop frames
897 if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
901 int FFVideoStream::init_frame(AVFrame *picture)
903 picture->format = avctx->pix_fmt;
904 picture->width = avctx->width;
905 picture->height = avctx->height;
906 int ret = av_frame_get_buffer(picture, 32);
910 int FFVideoStream::encode(VFrame *vframe)
912 if( encode_activate() <= 0 ) return -1;
914 FFrame *picture = new FFrame(this);
915 int ret = picture->initted();
917 AVFrame *frame = *picture;
918 frame->pts = curr_pos;
919 ret = convert_pixfmt(vframe, frame);
922 picture->queue(curr_pos);
926 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
929 return ret >= 0 ? 0 : 1;
932 int FFVideoStream::drain()
937 int FFVideoStream::encode_frame(AVFrame *frame)
940 frame->interlaced_frame = interlaced;
941 frame->top_field_first = top_field_first;
943 return FFStream::encode_frame(frame);
946 int FFVideoStream::write_packet(FFPacket &pkt)
948 if( !(ffmpeg->fmt_ctx->oformat->flags & AVFMT_VARIABLE_FPS) )
950 return FFStream::write_packet(pkt);
953 AVPixelFormat FFVideoConvert::color_model_to_pix_fmt(int color_model)
955 switch( color_model ) {
956 case BC_YUV422: return AV_PIX_FMT_YUYV422;
957 case BC_RGB888: return AV_PIX_FMT_RGB24;
958 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
959 case BC_BGR8888: return AV_PIX_FMT_BGR0;
960 case BC_BGR888: return AV_PIX_FMT_BGR24;
961 case BC_ARGB8888: return AV_PIX_FMT_ARGB;
962 case BC_ABGR8888: return AV_PIX_FMT_ABGR;
963 case BC_RGB8: return AV_PIX_FMT_RGB8;
964 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
965 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
966 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
967 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
968 case BC_RGB565: return AV_PIX_FMT_RGB565;
969 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
970 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
971 case BC_AYUV16161616: return AV_PIX_FMT_AYUV64LE;
975 return AV_PIX_FMT_NB;
978 int FFVideoConvert::pix_fmt_to_color_model(AVPixelFormat pix_fmt)
981 case AV_PIX_FMT_YUYV422: return BC_YUV422;
982 case AV_PIX_FMT_RGB24: return BC_RGB888;
983 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
984 case AV_PIX_FMT_BGR0: return BC_BGR8888;
985 case AV_PIX_FMT_BGR24: return BC_BGR888;
986 case AV_PIX_FMT_ARGB: return BC_ARGB8888;
987 case AV_PIX_FMT_ABGR: return BC_ABGR8888;
988 case AV_PIX_FMT_RGB8: return BC_RGB8;
989 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
990 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
991 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
992 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
993 case AV_PIX_FMT_RGB565: return BC_RGB565;
994 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
995 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
996 case AV_PIX_FMT_AYUV64LE: return BC_AYUV16161616;
1003 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip)
1005 AVFrame *ipic = av_frame_alloc();
1006 int ret = convert_picture_vframe(frame, ip, ipic);
1007 av_frame_free(&ipic);
1011 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip, AVFrame *ipic)
1013 int cmodel = frame->get_color_model();
1014 AVPixelFormat ofmt = color_model_to_pix_fmt(cmodel);
1015 if( ofmt == AV_PIX_FMT_NB ) return -1;
1016 int size = av_image_fill_arrays(ipic->data, ipic->linesize,
1017 frame->get_data(), ofmt, frame->get_w(), frame->get_h(), 1);
1018 if( size < 0 ) return -1;
1020 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1021 int ysz = bpp * frame->get_w(), usz = ysz;
1030 // override av_image_fill_arrays() for planar types
1031 ipic->data[0] = frame->get_y(); ipic->linesize[0] = ysz;
1032 ipic->data[1] = frame->get_u(); ipic->linesize[1] = usz;
1033 ipic->data[2] = frame->get_v(); ipic->linesize[2] = usz;
1036 ipic->data[0] = frame->get_data();
1037 ipic->linesize[0] = frame->get_bytes_per_line();
1041 AVPixelFormat pix_fmt = (AVPixelFormat)ip->format;
1042 convert_ctx = sws_getCachedContext(convert_ctx, ip->width, ip->height, pix_fmt,
1043 frame->get_w(), frame->get_h(), ofmt, SWS_POINT, NULL, NULL, NULL);
1044 if( !convert_ctx ) {
1045 fprintf(stderr, "FFVideoConvert::convert_picture_frame:"
1046 " sws_getCachedContext() failed\n");
1049 int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ip->height,
1050 ipic->data, ipic->linesize);
1052 ff_err(ret, "FFVideoConvert::convert_picture_frame: sws_scale() failed\n");
1058 int FFVideoConvert::convert_cmodel(VFrame *frame, AVFrame *ip)
1060 // try direct transfer
1061 if( !convert_picture_vframe(frame, ip) ) return 1;
1062 // use indirect transfer
1063 AVPixelFormat ifmt = (AVPixelFormat)ip->format;
1064 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
1066 for( int i = 0; i <desc->nb_components; ++i ) {
1067 int bits = desc->comp[i].depth;
1068 if( bits > max_bits ) max_bits = bits;
1070 int imodel = pix_fmt_to_color_model(ifmt);
1071 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1072 int cmodel = frame->get_color_model();
1073 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1074 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1075 imodel = cmodel_is_yuv ?
1076 (BC_CModels::has_alpha(cmodel) ?
1078 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1079 (BC_CModels::has_alpha(cmodel) ?
1080 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1081 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1083 VFrame vframe(ip->width, ip->height, imodel);
1084 if( convert_picture_vframe(&vframe, ip) ) return -1;
1085 frame->transfer_from(&vframe);
1089 int FFVideoConvert::transfer_cmodel(VFrame *frame, AVFrame *ifp)
1091 int ret = convert_cmodel(frame, ifp);
1093 const AVDictionary *src = av_frame_get_metadata(ifp);
1094 AVDictionaryEntry *t = NULL;
1095 BC_Hash *hp = frame->get_params();
1097 while( (t=av_dict_get(src, "", t, AV_DICT_IGNORE_SUFFIX)) )
1098 hp->update(t->key, t->value);
1103 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op)
1105 AVFrame *opic = av_frame_alloc();
1106 int ret = convert_vframe_picture(frame, op, opic);
1107 av_frame_free(&opic);
1111 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op, AVFrame *opic)
1113 int cmodel = frame->get_color_model();
1114 AVPixelFormat ifmt = color_model_to_pix_fmt(cmodel);
1115 if( ifmt == AV_PIX_FMT_NB ) return -1;
1116 int size = av_image_fill_arrays(opic->data, opic->linesize,
1117 frame->get_data(), ifmt, frame->get_w(), frame->get_h(), 1);
1118 if( size < 0 ) return -1;
1120 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1121 int ysz = bpp * frame->get_w(), usz = ysz;
1130 // override av_image_fill_arrays() for planar types
1131 opic->data[0] = frame->get_y(); opic->linesize[0] = ysz;
1132 opic->data[1] = frame->get_u(); opic->linesize[1] = usz;
1133 opic->data[2] = frame->get_v(); opic->linesize[2] = usz;
1136 opic->data[0] = frame->get_data();
1137 opic->linesize[0] = frame->get_bytes_per_line();
1141 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1142 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(),
1143 ifmt, op->width, op->height, ofmt, SWS_POINT, NULL, NULL, NULL);
1144 if( !convert_ctx ) {
1145 fprintf(stderr, "FFVideoConvert::convert_frame_picture:"
1146 " sws_getCachedContext() failed\n");
1149 int ret = sws_scale(convert_ctx, opic->data, opic->linesize, 0, frame->get_h(),
1150 op->data, op->linesize);
1152 ff_err(ret, "FFVideoConvert::convert_frame_picture: sws_scale() failed\n");
1158 int FFVideoConvert::convert_pixfmt(VFrame *frame, AVFrame *op)
1160 // try direct transfer
1161 if( !convert_vframe_picture(frame, op) ) return 1;
1162 // use indirect transfer
1163 int cmodel = frame->get_color_model();
1164 int max_bits = BC_CModels::calculate_pixelsize(cmodel) * 8;
1165 max_bits /= BC_CModels::components(cmodel);
1166 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1167 int imodel = pix_fmt_to_color_model(ofmt);
1168 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1169 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1170 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1171 imodel = cmodel_is_yuv ?
1172 (BC_CModels::has_alpha(cmodel) ?
1174 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1175 (BC_CModels::has_alpha(cmodel) ?
1176 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1177 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1179 VFrame vframe(frame->get_w(), frame->get_h(), imodel);
1180 vframe.transfer_from(frame);
1181 if( !convert_vframe_picture(&vframe, op) ) return 1;
1185 int FFVideoConvert::transfer_pixfmt(VFrame *frame, AVFrame *ofp)
1187 int ret = convert_pixfmt(frame, ofp);
1189 BC_Hash *hp = frame->get_params();
1190 AVDictionary **dict = avpriv_frame_get_metadatap(ofp);
1191 //av_dict_free(dict);
1192 for( int i=0; i<hp->size(); ++i ) {
1193 char *key = hp->get_key(i), *val = hp->get_value(i);
1194 av_dict_set(dict, key, val, 0);
1200 void FFVideoStream::load_markers()
1202 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1203 if( !index_state || idx >= index_state->video_markers.size() ) return;
1204 FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
1207 IndexMarks *FFVideoStream::get_markers()
1209 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1210 if( !index_state || idx >= index_state->video_markers.size() ) return 0;
1211 return !index_state ? 0 : index_state->video_markers[idx];
1215 FFMPEG::FFMPEG(FileBase *file_base)
1218 this->file_base = file_base;
1219 memset(file_format,0,sizeof(file_format));
1220 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
1221 flow_lock = new Condition(1,"FFStream::flow_lock",0);
1224 decoding = encoding = 0;
1225 has_audio = has_video = 0;
1228 opt_video_filter = 0;
1229 opt_audio_filter = 0;
1230 char option_path[BCTEXTLEN];
1231 set_option_path(option_path, "%s", "ffmpeg.opts");
1232 read_options(option_path, opts);
1237 ff_lock("FFMPEG::~FFMPEG()");
1239 ffaudio.remove_all_objects();
1240 ffvideo.remove_all_objects();
1241 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1245 av_dict_free(&opts);
1246 delete [] opt_video_filter;
1247 delete [] opt_audio_filter;
1250 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1252 const int *p = codec->supported_samplerates;
1253 if( !p ) return sample_rate;
1255 if( *p == sample_rate ) return *p;
1261 static inline AVRational std_frame_rate(int i)
1263 static const int m1 = 1001*12, m2 = 1000*12;
1264 static const int freqs[] = {
1265 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1266 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
1268 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1269 return (AVRational) { freq, 1001*12 };
1272 AVRational FFMPEG::check_frame_rate(AVCodec *codec, double frame_rate)
1274 const AVRational *p = codec->supported_framerates;
1275 AVRational rate, best_rate = (AVRational) { 0, 0 };
1276 double max_err = 1.; int i = 0;
1277 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1278 double framerate = (double) rate.num / rate.den;
1279 double err = fabs(frame_rate/framerate - 1.);
1280 if( err >= max_err ) continue;
1284 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1287 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1290 double display_aspect = asset->width / (double)asset->height;
1291 double sample_aspect = display_aspect / asset->aspect_ratio;
1292 int width = 1000000, height = width * sample_aspect + 0.5;
1294 MWindow::create_aspect_ratio(w, h, width, height);
1295 return (AVRational){(int)w, (int)h};
1298 return (AVRational){1, 1};
1302 AVRational FFMPEG::to_time_base(int sample_rate)
1304 return (AVRational){1, sample_rate};
1307 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
1309 char *ep = path + BCTEXTLEN-1;
1310 strncpy(path, File::get_cindat_path(), ep-path);
1311 strncat(path, "/ffmpeg/", ep-path);
1312 path += strlen(path);
1315 path += vsnprintf(path, ep-path, fmt, ap);
1320 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
1325 set_option_path(path, "%s/%s", type, spec);
1328 int FFMPEG::get_format(char *format, const char *path, const char *spec)
1330 char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
1331 get_option_path(option_path, path, spec);
1332 FILE *fp = fopen(option_path,"r");
1335 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1337 line[sizeof(line)-1] = 0;
1338 ret = scan_option_line(line, format, codec);
1344 int FFMPEG::get_codec(char *codec, const char *path, const char *spec)
1346 char option_path[BCTEXTLEN], line[BCTEXTLEN], format[BCTEXTLEN];
1347 get_option_path(option_path, path, spec);
1348 FILE *fp = fopen(option_path,"r");
1351 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1354 line[sizeof(line)-1] = 0;
1355 ret = scan_option_line(line, format, codec);
1358 char *vp = codec, *ep = vp+BCTEXTLEN-1;
1359 while( vp < ep && *vp && *vp != '|' ) ++vp;
1360 if( *vp == '|' ) --vp;
1361 while( vp > codec && (*vp==' ' || *vp=='\t') ) *vp-- = 0;
1366 int FFMPEG::get_file_format()
1368 char audio_muxer[BCSTRLEN], video_muxer[BCSTRLEN];
1369 char audio_format[BCSTRLEN], video_format[BCSTRLEN];
1370 audio_muxer[0] = audio_format[0] = 0;
1371 video_muxer[0] = video_format[0] = 0;
1372 Asset *asset = file_base->asset;
1373 int ret = asset ? 0 : 1;
1374 if( !ret && asset->audio_data ) {
1375 if( !(ret=get_format(audio_format, "audio", asset->acodec)) ) {
1376 if( get_format(audio_muxer, "format", audio_format) ) {
1377 strcpy(audio_muxer, audio_format);
1378 audio_format[0] = 0;
1382 if( !ret && asset->video_data ) {
1383 if( !(ret=get_format(video_format, "video", asset->vcodec)) ) {
1384 if( get_format(video_muxer, "format", video_format) ) {
1385 strcpy(video_muxer, video_format);
1386 video_format[0] = 0;
1390 if( !ret && !audio_muxer[0] && !video_muxer[0] )
1392 if( !ret && audio_muxer[0] && video_muxer[0] &&
1393 strcmp(audio_muxer, video_muxer) ) ret = -1;
1394 if( !ret && audio_format[0] && video_format[0] &&
1395 strcmp(audio_format, video_format) ) ret = -1;
1397 strcpy(file_format, !audio_format[0] && !video_format[0] ?
1398 (audio_muxer[0] ? audio_muxer : video_muxer) :
1399 (audio_format[0] ? audio_format : video_format));
1403 int FFMPEG::scan_option_line(char *cp, char *tag, char *val)
1405 while( *cp == ' ' || *cp == '\t' ) ++cp;
1407 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' && *cp != '\n' ) ++cp;
1409 if( !len || len > BCSTRLEN-1 ) return 1;
1410 while( bp < cp ) *tag++ = *bp++;
1412 while( *cp == ' ' || *cp == '\t' ) ++cp;
1413 if( *cp == '=' ) ++cp;
1414 while( *cp == ' ' || *cp == '\t' ) ++cp;
1416 while( *cp && *cp != '\n' ) ++cp;
1418 if( len > BCTEXTLEN-1 ) return 1;
1419 while( bp < cp ) *val++ = *bp++;
1424 int FFMPEG::load_defaults(const char *path, const char *type,
1425 char *codec, char *codec_options, int len)
1427 char default_file[BCTEXTLEN];
1428 set_option_path(default_file, "%s/%s.dfl", path, type);
1429 FILE *fp = fopen(default_file,"r");
1431 fgets(codec, BCSTRLEN, fp);
1433 while( *cp && *cp!='\n' ) ++cp;
1435 while( len > 0 && fgets(codec_options, len, fp) ) {
1436 int n = strlen(codec_options);
1437 codec_options += n; len -= n;
1440 set_option_path(default_file, "%s/%s", path, codec);
1441 return load_options(default_file, codec_options, len);
1444 void FFMPEG::set_asset_format(Asset *asset, const char *text)
1446 if( asset->format != FILE_FFMPEG ) return;
1447 if( text != asset->fformat )
1448 strcpy(asset->fformat, text);
1449 if( !asset->ff_audio_options[0] ) {
1450 asset->audio_data = !load_defaults("audio", text, asset->acodec,
1451 asset->ff_audio_options, sizeof(asset->ff_audio_options));
1453 if( !asset->ff_video_options[0] ) {
1454 asset->video_data = !load_defaults("video", text, asset->vcodec,
1455 asset->ff_video_options, sizeof(asset->ff_video_options));
1459 int FFMPEG::get_encoder(const char *options,
1460 char *format, char *codec, char *bsfilter)
1462 FILE *fp = fopen(options,"r");
1464 eprintf(_("options open failed %s\n"),options);
1467 if( get_encoder(fp, format, codec, bsfilter) )
1468 eprintf(_("format/codec not found %s\n"), options);
1473 int FFMPEG::get_encoder(FILE *fp,
1474 char *format, char *codec, char *bsfilter)
1476 format[0] = codec[0] = bsfilter[0] = 0;
1477 char line[BCTEXTLEN];
1478 if( !fgets(line, sizeof(line), fp) ) return 1;
1479 line[sizeof(line)-1] = 0;
1480 if( scan_option_line(line, format, codec) ) return 1;
1482 while( *cp && *cp != '|' ) ++cp;
1483 if( !*cp ) return 0;
1485 do { *bp-- = 0; } while( bp>=codec && (*bp==' ' || *bp == '\t' ) );
1486 while( *++cp && (*cp==' ' || *cp == '\t') );
1488 for( int i=BCTEXTLEN; --i>0 && *cp; ) *bp++ = *cp++;
1493 int FFMPEG::read_options(const char *options, AVDictionary *&opts, int skip)
1495 FILE *fp = fopen(options,"r");
1498 while( !ret && --skip >= 0 ) {
1500 while( ch >= 0 && ch != '\n' ) ch = getc(fp);
1501 if( ch < 0 ) ret = 1;
1504 ret = read_options(fp, options, opts);
1509 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
1511 FILE *fp = fmemopen((void *)options,strlen(options),"r");
1513 int ret = read_options(fp, options, opts);
1515 AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
1516 if( tag ) st->id = strtol(tag->value,0,0);
1520 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
1522 int ret = 0, no = 0;
1523 char line[BCTEXTLEN];
1524 while( !ret && fgets(line, sizeof(line), fp) ) {
1525 line[sizeof(line)-1] = 0;
1526 if( line[0] == '#' ) continue;
1527 if( line[0] == '\n' ) continue;
1528 char key[BCSTRLEN], val[BCTEXTLEN];
1529 if( scan_option_line(line, key, val) ) {
1530 eprintf(_("err reading %s: line %d\n"), options, no);
1534 if( !strcmp(key, "duration") )
1535 opt_duration = strtod(val, 0);
1536 else if( !strcmp(key, "video_filter") )
1537 opt_video_filter = cstrdup(val);
1538 else if( !strcmp(key, "audio_filter") )
1539 opt_audio_filter = cstrdup(val);
1540 else if( !strcmp(key, "loglevel") )
1543 av_dict_set(&opts, key, val, 0);
1549 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
1551 char option_path[BCTEXTLEN];
1552 set_option_path(option_path, "%s", options);
1553 return read_options(option_path, opts);
1556 int FFMPEG::load_options(const char *path, char *bfr, int len)
1559 FILE *fp = fopen(path, "r");
1561 fgets(bfr, len, fp); // skip hdr
1562 len = fread(bfr, 1, len-1, fp);
1563 if( len < 0 ) len = 0;
1569 void FFMPEG::set_loglevel(const char *ap)
1571 if( !ap || !*ap ) return;
1576 { "quiet" , AV_LOG_QUIET },
1577 { "panic" , AV_LOG_PANIC },
1578 { "fatal" , AV_LOG_FATAL },
1579 { "error" , AV_LOG_ERROR },
1580 { "warning", AV_LOG_WARNING },
1581 { "info" , AV_LOG_INFO },
1582 { "verbose", AV_LOG_VERBOSE },
1583 { "debug" , AV_LOG_DEBUG },
1585 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
1586 if( !strcmp(log_levels[i].name, ap) ) {
1587 av_log_set_level(log_levels[i].level);
1591 av_log_set_level(atoi(ap));
1594 double FFMPEG::to_secs(int64_t time, AVRational time_base)
1596 double base_time = time == AV_NOPTS_VALUE ? 0 :
1597 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
1598 return base_time / AV_TIME_BASE;
1601 int FFMPEG::info(char *text, int len)
1603 if( len <= 0 ) return 0;
1605 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
1607 report("format: %s\n",fmt_ctx->iformat->name);
1608 if( ffvideo.size() > 0 )
1609 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
1610 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
1611 FFVideoStream *vid = ffvideo[vidx];
1612 AVStream *st = vid->st;
1613 AVCodecID codec_id = st->codecpar->codec_id;
1614 report(_("vid%d (%d), id 0x%06x:\n"), vid->idx, vid->fidx, codec_id);
1615 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
1616 report(" video%d %s", vidx+1, desc ? desc->name : " (unkn)");
1617 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
1618 AVPixelFormat pix_fmt = (AVPixelFormat)st->codecpar->format;
1619 const char *pfn = av_get_pix_fmt_name(pix_fmt);
1620 report(" pix %s\n", pfn ? pfn : "(unkn)");
1621 double secs = to_secs(st->duration, st->time_base);
1622 int64_t length = secs * vid->frame_rate + 0.5;
1623 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
1624 int64_t nudge = ofs * vid->frame_rate;
1625 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1626 report(" %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
1627 int hrs = secs/3600; secs -= hrs*3600;
1628 int mins = secs/60; secs -= mins*60;
1629 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1631 if( ffaudio.size() > 0 )
1632 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
1633 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
1634 FFAudioStream *aud = ffaudio[aidx];
1635 AVStream *st = aud->st;
1636 AVCodecID codec_id = st->codecpar->codec_id;
1637 report(_("aud%d (%d), id 0x%06x:\n"), aud->idx, aud->fidx, codec_id);
1638 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
1639 int nch = aud->channels, ch0 = aud->channel0+1;
1640 report(" audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
1641 AVSampleFormat sample_fmt = (AVSampleFormat)st->codecpar->format;
1642 const char *fmt = av_get_sample_fmt_name(sample_fmt);
1643 report(" %s %d", fmt, aud->sample_rate);
1644 int sample_bits = av_get_bits_per_sample(codec_id);
1645 report(" %dbits\n", sample_bits);
1646 double secs = to_secs(st->duration, st->time_base);
1647 int64_t length = secs * aud->sample_rate + 0.5;
1648 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
1649 int64_t nudge = ofs * aud->sample_rate;
1650 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1651 report(" %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
1652 int hrs = secs/3600; secs -= hrs*3600;
1653 int mins = secs/60; secs -= mins*60;
1654 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1656 if( fmt_ctx->nb_programs > 0 )
1657 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
1658 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
1659 report("program %d", i+1);
1660 AVProgram *pgrm = fmt_ctx->programs[i];
1661 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1662 int idx = pgrm->stream_index[j];
1663 int vidx = ffvideo.size();
1664 while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
1666 report(", vid%d", vidx);
1669 int aidx = ffaudio.size();
1670 while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
1672 report(", aud%d", aidx);
1675 report(", (%d)", pgrm->stream_index[j]);
1680 AVDictionaryEntry *tag = 0;
1681 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
1682 report("%s=%s\n", tag->key, tag->value);
1691 int FFMPEG::init_decoder(const char *filename)
1693 ff_lock("FFMPEG::init_decoder");
1695 char file_opts[BCTEXTLEN];
1696 char *bp = strrchr(strcpy(file_opts, filename), '/');
1697 char *sp = strrchr(!bp ? file_opts : bp, '.');
1700 strcpy(sp, ".opts");
1701 fp = fopen(file_opts, "r");
1704 read_options(fp, file_opts, opts);
1708 load_options("decode.opts", opts);
1709 AVDictionary *fopts = 0;
1710 av_dict_copy(&fopts, opts, 0);
1711 int ret = avformat_open_input(&fmt_ctx, filename, NULL, &fopts);
1712 av_dict_free(&fopts);
1714 ret = avformat_find_stream_info(fmt_ctx, NULL);
1719 return !ret ? 0 : 1;
1722 int FFMPEG::open_decoder()
1725 if( stat(fmt_ctx->filename, &st) < 0 ) {
1726 eprintf(_("can't stat file: %s\n"), fmt_ctx->filename);
1730 int64_t file_bits = 8 * st.st_size;
1731 if( !fmt_ctx->bit_rate && opt_duration > 0 )
1732 fmt_ctx->bit_rate = file_bits / opt_duration;
1735 if( fmt_ctx->bit_rate > 0 ) {
1736 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1737 AVStream *st = fmt_ctx->streams[i];
1738 if( st->duration != AV_NOPTS_VALUE ) continue;
1739 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
1740 st->duration = av_rescale(file_bits, st->time_base.den,
1741 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
1746 printf("FFMPEG::open_decoder: some stream times estimated\n");
1748 ff_lock("FFMPEG::open_decoder");
1749 int ret = 0, bad_time = 0;
1750 for( int i=0; !ret && i<(int)fmt_ctx->nb_streams; ++i ) {
1751 AVStream *st = fmt_ctx->streams[i];
1752 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
1753 AVCodecParameters *avpar = st->codecpar;
1754 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avpar->codec_id);
1755 if( !codec_desc ) continue;
1756 switch( avpar->codec_type ) {
1757 case AVMEDIA_TYPE_VIDEO: {
1758 if( avpar->width < 1 ) continue;
1759 if( avpar->height < 1 ) continue;
1760 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
1761 if( framerate.num < 1 ) continue;
1763 int vidx = ffvideo.size();
1764 FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
1765 vstrm_index.append(ffidx(vidx, 0));
1766 ffvideo.append(vid);
1767 vid->width = avpar->width;
1768 vid->height = avpar->height;
1769 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
1770 double secs = to_secs(st->duration, st->time_base);
1771 vid->length = secs * vid->frame_rate;
1772 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
1773 vid->nudge = st->start_time;
1775 if( opt_video_filter )
1776 ret = vid->create_filter(opt_video_filter, avpar);
1778 case AVMEDIA_TYPE_AUDIO: {
1779 if( avpar->channels < 1 ) continue;
1780 if( avpar->sample_rate < 1 ) continue;
1782 int aidx = ffaudio.size();
1783 FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
1784 ffaudio.append(aud);
1785 aud->channel0 = astrm_index.size();
1786 aud->channels = avpar->channels;
1787 for( int ch=0; ch<aud->channels; ++ch )
1788 astrm_index.append(ffidx(aidx, ch));
1789 aud->sample_rate = avpar->sample_rate;
1790 double secs = to_secs(st->duration, st->time_base);
1791 aud->length = secs * aud->sample_rate;
1792 aud->init_swr(aud->channels, avpar->format, aud->sample_rate);
1793 aud->nudge = st->start_time;
1795 if( opt_audio_filter )
1796 ret = aud->create_filter(opt_audio_filter, avpar);
1802 printf("FFMPEG::open_decoder: some stream have bad times\n");
1804 return ret < 0 ? -1 : 0;
1808 int FFMPEG::init_encoder(const char *filename)
1810 int fd = ::open(filename,O_WRONLY);
1811 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
1813 eprintf(_("bad file path: %s\n"), filename);
1817 int ret = get_file_format();
1819 eprintf(_("bad file format: %s\n"), filename);
1823 eprintf(_("mismatch audio/video file format: %s\n"), filename);
1826 ff_lock("FFMPEG::init_encoder");
1828 char format[BCSTRLEN];
1829 if( get_format(format, "format", file_format) )
1830 strcpy(format, file_format);
1831 avformat_alloc_output_context2(&fmt_ctx, 0, format, filename);
1833 eprintf(_("failed: %s\n"), filename);
1838 load_options("encode.opts", opts);
1844 int FFMPEG::open_encoder(const char *type, const char *spec)
1847 Asset *asset = file_base->asset;
1848 char *filename = asset->path;
1849 AVDictionary *sopts = 0;
1850 av_dict_copy(&sopts, opts, 0);
1851 char option_path[BCTEXTLEN];
1852 set_option_path(option_path, "%s/%s.opts", type, type);
1853 read_options(option_path, sopts);
1854 get_option_path(option_path, type, spec);
1855 char format_name[BCSTRLEN], codec_name[BCTEXTLEN], bsfilter[BCTEXTLEN];
1856 if( get_encoder(option_path, format_name, codec_name, bsfilter) ) {
1857 eprintf(_("get_encoder failed %s:%s\n"), option_path, filename);
1861 if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
1862 else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
1863 else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
1866 ff_lock("FFMPEG::open_encoder");
1869 AVCodecContext *ctx = 0;
1871 const AVCodecDescriptor *codec_desc = 0;
1872 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
1874 eprintf(_("cant find codec %s:%s\n"), codec_name, filename);
1878 codec_desc = avcodec_descriptor_get(codec->id);
1880 eprintf(_("unknown codec %s:%s\n"), codec_name, filename);
1885 st = avformat_new_stream(fmt_ctx, 0);
1887 eprintf(_("cant create stream %s:%s\n"), codec_name, filename);
1892 switch( codec_desc->type ) {
1893 case AVMEDIA_TYPE_AUDIO: {
1895 eprintf(_("duplicate audio %s:%s\n"), codec_name, filename);
1899 if( scan_options(asset->ff_audio_options, sopts, st) ) {
1900 eprintf(_("bad audio options %s:%s\n"), codec_name, filename);
1905 ctx = avcodec_alloc_context3(codec);
1906 if( asset->ff_audio_bitrate > 0 ) {
1907 ctx->bit_rate = asset->ff_audio_bitrate;
1909 sprintf(arg, "%d", asset->ff_audio_bitrate);
1910 av_dict_set(&sopts, "b", arg, 0);
1912 int aidx = ffaudio.size();
1913 int fidx = aidx + ffvideo.size();
1914 FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
1915 aud->avctx = ctx; ffaudio.append(aud); fst = aud;
1916 aud->sample_rate = asset->sample_rate;
1917 ctx->channels = aud->channels = asset->channels;
1918 for( int ch=0; ch<aud->channels; ++ch )
1919 astrm_index.append(ffidx(aidx, ch));
1920 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
1921 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
1922 if( !ctx->sample_rate ) {
1923 eprintf(_("check_sample_rate failed %s\n"), filename);
1927 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
1928 ctx->sample_fmt = codec->sample_fmts[0];
1929 uint64_t layout = av_get_default_channel_layout(ctx->channels);
1930 aud->resample_context = swr_alloc_set_opts(NULL,
1931 layout, ctx->sample_fmt, aud->sample_rate,
1932 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
1934 swr_init(aud->resample_context);
1937 case AVMEDIA_TYPE_VIDEO: {
1939 eprintf(_("duplicate video %s:%s\n"), codec_name, filename);
1943 if( scan_options(asset->ff_video_options, sopts, st) ) {
1944 eprintf(_("bad video options %s:%s\n"), codec_name, filename);
1949 ctx = avcodec_alloc_context3(codec);
1950 if( asset->ff_video_bitrate > 0 ) {
1951 ctx->bit_rate = asset->ff_video_bitrate;
1953 sprintf(arg, "%d", asset->ff_video_bitrate);
1954 av_dict_set(&sopts, "b", arg, 0);
1956 else if( asset->ff_video_quality >= 0 ) {
1957 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
1958 ctx->qmin = ctx->qmax = asset->ff_video_quality;
1959 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
1960 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
1961 ctx->flags |= CODEC_FLAG_QSCALE;
1963 av_dict_set(&sopts, "flags", "+qscale", 0);
1964 sprintf(arg, "%d", asset->ff_video_quality);
1965 av_dict_set(&sopts, "qscale", arg, 0);
1966 sprintf(arg, "%d", ctx->global_quality);
1967 av_dict_set(&sopts, "global_quality", arg, 0);
1969 int vidx = ffvideo.size();
1970 int fidx = vidx + ffaudio.size();
1971 FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
1972 vstrm_index.append(ffidx(vidx, 0));
1973 vid->avctx = ctx; ffvideo.append(vid); fst = vid;
1974 vid->width = asset->width;
1975 ctx->width = (vid->width+3) & ~3;
1976 vid->height = asset->height;
1977 ctx->height = (vid->height+3) & ~3;
1978 vid->frame_rate = asset->frame_rate;
1979 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
1980 ctx->pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
1981 AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
1982 if( !frame_rate.num || !frame_rate.den ) {
1983 eprintf(_("check_frame_rate failed %s\n"), filename);
1987 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
1988 st->time_base = ctx->time_base;
1990 vid->interlaced = asset->interlace_mode == ILACE_MODE_TOP_FIRST ||
1991 asset->interlace_mode == ILACE_MODE_BOTTOM_FIRST ? 1 : 0;
1992 vid->top_field_first = asset->interlace_mode == ILACE_MODE_TOP_FIRST ? 1 : 0;
1995 eprintf(_("not audio/video, %s:%s\n"), codec_name, filename);
2000 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
2001 ctx->flags |= CODEC_FLAG_GLOBAL_HEADER;
2003 av_dict_set(&sopts, "cin_bitrate", 0, 0);
2004 av_dict_set(&sopts, "cin_quality", 0, 0);
2006 ret = avcodec_open2(ctx, codec, &sopts);
2008 ret = avcodec_parameters_from_context(st->codecpar, ctx);
2010 fprintf(stderr, "Could not copy the stream parameters\n");
2013 ff_err(ret,"FFMPEG::open_encoder");
2014 eprintf(_("open failed %s:%s\n"), codec_name, filename);
2020 if( !ret && fst && bsfilter[0] ) {
2021 ret = av_bsf_list_parse_str(bsfilter, &fst->bsfc);
2023 ff_err(ret,"FFMPEG::open_encoder");
2024 eprintf(_("bitstream filter failed %s:\n%s\n"), filename, bsfilter);
2035 av_dict_free(&sopts);
2039 int FFMPEG::close_encoder()
2042 if( encoding > 0 ) {
2043 av_write_trailer(fmt_ctx);
2044 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
2045 avio_closep(&fmt_ctx->pb);
2051 int FFMPEG::decode_activate()
2053 if( decoding < 0 ) {
2055 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
2056 ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
2057 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
2058 ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
2059 // set nudges for each program stream set
2060 const int64_t min_nudge = INT64_MIN+1;
2061 int npgrms = fmt_ctx->nb_programs;
2062 for( int i=0; i<npgrms; ++i ) {
2063 AVProgram *pgrm = fmt_ctx->programs[i];
2064 // first start time video stream
2065 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2066 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2067 int fidx = pgrm->stream_index[j];
2068 AVStream *st = fmt_ctx->streams[fidx];
2069 AVCodecParameters *avpar = st->codecpar;
2070 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2071 if( st->start_time == AV_NOPTS_VALUE ) continue;
2072 if( vstart_time < st->start_time )
2073 vstart_time = st->start_time;
2076 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2077 if( st->start_time == AV_NOPTS_VALUE ) continue;
2078 if( astart_time < st->start_time )
2079 astart_time = st->start_time;
2083 //since frame rate is much more grainy than sample rate, it is better to
2084 // align using video, so that total absolute error is minimized.
2085 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2086 astart_time > min_nudge ? astart_time : AV_NOPTS_VALUE;
2087 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2088 int fidx = pgrm->stream_index[j];
2089 AVStream *st = fmt_ctx->streams[fidx];
2090 AVCodecParameters *avpar = st->codecpar;
2091 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2092 for( int k=0; k<ffvideo.size(); ++k ) {
2093 if( ffvideo[k]->fidx != fidx ) continue;
2094 ffvideo[k]->nudge = nudge;
2098 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2099 for( int k=0; k<ffaudio.size(); ++k ) {
2100 if( ffaudio[k]->fidx != fidx ) continue;
2101 ffaudio[k]->nudge = nudge;
2107 // set nudges for any streams not yet set
2108 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2109 int nstreams = fmt_ctx->nb_streams;
2110 for( int i=0; i<nstreams; ++i ) {
2111 AVStream *st = fmt_ctx->streams[i];
2112 AVCodecParameters *avpar = st->codecpar;
2113 switch( avpar->codec_type ) {
2114 case AVMEDIA_TYPE_VIDEO: {
2115 if( st->start_time == AV_NOPTS_VALUE ) continue;
2116 int vidx = ffvideo.size();
2117 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
2118 if( vidx < 0 ) continue;
2119 if( ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
2120 if( vstart_time < st->start_time )
2121 vstart_time = st->start_time;
2123 case AVMEDIA_TYPE_AUDIO: {
2124 if( st->start_time == AV_NOPTS_VALUE ) continue;
2125 int aidx = ffaudio.size();
2126 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
2127 if( aidx < 0 ) continue;
2128 if( ffaudio[aidx]->frame_sz < avpar->frame_size )
2129 ffaudio[aidx]->frame_sz = avpar->frame_size;
2130 if( ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
2131 if( astart_time < st->start_time )
2132 astart_time = st->start_time;
2137 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2138 astart_time > min_nudge ? astart_time : 0;
2139 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
2140 if( ffvideo[vidx]->nudge == AV_NOPTS_VALUE )
2141 ffvideo[vidx]->nudge = nudge;
2143 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2144 if( ffaudio[aidx]->nudge == AV_NOPTS_VALUE )
2145 ffaudio[aidx]->nudge = nudge;
2152 int FFMPEG::encode_activate()
2155 if( encoding < 0 ) {
2157 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
2158 (ret=avio_open(&fmt_ctx->pb, fmt_ctx->filename, AVIO_FLAG_WRITE)) < 0 ) {
2159 ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
2165 AVProgram *prog = av_new_program(fmt_ctx, prog_id);
2166 for( int i=0; i< ffvideo.size(); ++i )
2167 av_program_add_stream_index(fmt_ctx, prog_id, ffvideo[i]->fidx);
2168 for( int i=0; i< ffaudio.size(); ++i )
2169 av_program_add_stream_index(fmt_ctx, prog_id, ffaudio[i]->fidx);
2170 int pi = fmt_ctx->nb_programs;
2171 while( --pi >= 0 && fmt_ctx->programs[pi]->id != prog_id );
2172 AVDictionary **meta = &prog->metadata;
2173 av_dict_set(meta, "service_provider", "cin5", 0);
2174 const char *path = fmt_ctx->filename, *bp = strrchr(path,'/');
2175 if( bp ) path = bp + 1;
2176 av_dict_set(meta, "title", path, 0);
2178 if( ffaudio.size() ) {
2179 const char *ep = getenv("CIN_AUDIO_LANG"), *lp = 0;
2180 if( !ep && (lp=getenv("LANG")) ) { // some are guesses
2181 static struct { const char lc[3], lng[4]; } lcode[] = {
2182 { "en", "eng" }, { "de", "ger" }, { "es", "spa" },
2183 { "eu", "bas" }, { "fr", "fre" }, { "el", "gre" },
2184 { "hi", "hin" }, { "it", "ita" }, { "ja", "jap" },
2185 { "ko", "kor" }, { "du", "dut" }, { "pl", "pol" },
2186 { "pt", "por" }, { "ru", "rus" }, { "sl", "slv" },
2187 { "uk", "ukr" }, { "vi", "vie" }, { "zh", "chi" },
2189 for( int i=sizeof(lcode)/sizeof(lcode[0]); --i>=0 && !ep; )
2190 if( !strncmp(lcode[i].lc,lp,2) ) ep = lcode[i].lng;
2192 if( !ep ) ep = "und";
2194 strncpy(lang,ep,3); lang[3] = 0;
2195 AVStream *st = ffaudio[0]->st;
2196 av_dict_set(&st->metadata,"language",lang,0);
2199 AVDictionary *fopts = 0;
2200 char option_path[BCTEXTLEN];
2201 set_option_path(option_path, "format/%s", file_format);
2202 read_options(option_path, fopts, 1);
2203 ret = avformat_write_header(fmt_ctx, &fopts);
2205 ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
2209 av_dict_free(&fopts);
2216 int FFMPEG::audio_seek(int stream, int64_t pos)
2218 int aidx = astrm_index[stream].st_idx;
2219 FFAudioStream *aud = ffaudio[aidx];
2220 aud->audio_seek(pos);
2224 int FFMPEG::video_seek(int stream, int64_t pos)
2226 int vidx = vstrm_index[stream].st_idx;
2227 FFVideoStream *vid = ffvideo[vidx];
2228 vid->video_seek(pos);
2233 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
2235 if( !has_audio || chn >= astrm_index.size() ) return -1;
2236 int aidx = astrm_index[chn].st_idx;
2237 FFAudioStream *aud = ffaudio[aidx];
2238 if( aud->load(pos, len) < len ) return -1;
2239 int ch = astrm_index[chn].st_ch;
2240 int ret = aud->read(samples,len,ch);
2244 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
2246 if( !has_video || layer >= vstrm_index.size() ) return -1;
2247 int vidx = vstrm_index[layer].st_idx;
2248 FFVideoStream *vid = ffvideo[vidx];
2249 return vid->load(vframe, pos);
2253 int FFMPEG::encode(int stream, double **samples, int len)
2255 FFAudioStream *aud = ffaudio[stream];
2256 return aud->encode(samples, len);
2260 int FFMPEG::encode(int stream, VFrame *frame)
2262 FFVideoStream *vid = ffvideo[stream];
2263 return vid->encode(frame);
2266 void FFMPEG::start_muxer()
2274 void FFMPEG::stop_muxer()
2283 void FFMPEG::flow_off()
2286 flow_lock->lock("FFMPEG::flow_off");
2290 void FFMPEG::flow_on()
2294 flow_lock->unlock();
2297 void FFMPEG::flow_ctl()
2300 flow_lock->lock("FFMPEG::flow_ctl");
2301 flow_lock->unlock();
2305 int FFMPEG::mux_audio(FFrame *frm)
2307 FFStream *fst = frm->fst;
2308 AVCodecContext *ctx = fst->avctx;
2309 AVFrame *frame = *frm;
2310 AVRational tick_rate = {1, ctx->sample_rate};
2311 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
2312 int ret = fst->encode_frame(frame);
2314 ff_err(ret, "FFMPEG::mux_audio");
2315 return ret >= 0 ? 0 : 1;
2318 int FFMPEG::mux_video(FFrame *frm)
2320 FFStream *fst = frm->fst;
2321 AVFrame *frame = *frm;
2322 frame->pts = frm->position;
2323 int ret = fst->encode_frame(frame);
2325 ff_err(ret, "FFMPEG::mux_video");
2326 return ret >= 0 ? 0 : 1;
2332 double atm = -1, vtm = -1;
2333 FFrame *afrm = 0, *vfrm = 0;
2335 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
2336 FFStream *fst = ffaudio[i];
2337 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
2338 FFrame *frm = fst->frms.first;
2339 if( !frm ) { if( !done ) return; continue; }
2340 double tm = to_secs(frm->position, fst->avctx->time_base);
2341 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
2343 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
2344 FFStream *fst = ffvideo[i];
2345 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
2346 FFrame *frm = fst->frms.first;
2347 if( !frm ) { if( !done ) return; continue; }
2348 double tm = to_secs(frm->position, fst->avctx->time_base);
2349 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
2351 if( !demand ) flow_off();
2352 if( !afrm && !vfrm ) break;
2353 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
2354 vfrm->position, vfrm->fst->avctx->time_base,
2355 afrm->position, afrm->fst->avctx->time_base);
2356 FFrame *frm = v <= 0 ? vfrm : afrm;
2357 if( frm == afrm ) mux_audio(frm);
2358 if( frm == vfrm ) mux_video(frm);
2367 mux_lock->lock("FFMPEG::run");
2370 for( int i=0; i<ffaudio.size(); ++i )
2371 ffaudio[i]->drain();
2372 for( int i=0; i<ffvideo.size(); ++i )
2373 ffvideo[i]->drain();
2375 for( int i=0; i<ffaudio.size(); ++i )
2376 ffaudio[i]->flush();
2377 for( int i=0; i<ffvideo.size(); ++i )
2378 ffvideo[i]->flush();
2382 int FFMPEG::ff_total_audio_channels()
2384 return astrm_index.size();
2387 int FFMPEG::ff_total_astreams()
2389 return ffaudio.size();
2392 int FFMPEG::ff_audio_channels(int stream)
2394 return ffaudio[stream]->channels;
2397 int FFMPEG::ff_sample_rate(int stream)
2399 return ffaudio[stream]->sample_rate;
2402 const char* FFMPEG::ff_audio_format(int stream)
2404 AVStream *st = ffaudio[stream]->st;
2405 AVCodecID id = st->codecpar->codec_id;
2406 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2407 return desc ? desc->name : _("Unknown");
2410 int FFMPEG::ff_audio_pid(int stream)
2412 return ffaudio[stream]->st->id;
2415 int64_t FFMPEG::ff_audio_samples(int stream)
2417 return ffaudio[stream]->length;
2420 // find audio astream/channels with this program,
2421 // or all program audio channels (astream=-1)
2422 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
2426 int vidx = ffvideo[vstream]->fidx;
2427 // find first program with this video stream
2428 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
2429 AVProgram *pgrm = fmt_ctx->programs[i];
2430 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
2431 int st_idx = pgrm->stream_index[j];
2432 AVStream *st = fmt_ctx->streams[st_idx];
2433 if( st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
2434 if( st_idx == vidx ) pidx = i;
2437 if( pidx < 0 ) return -1;
2439 int64_t channels = 0;
2440 AVProgram *pgrm = fmt_ctx->programs[pidx];
2441 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2442 int aidx = pgrm->stream_index[j];
2443 AVStream *st = fmt_ctx->streams[aidx];
2444 if( st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
2445 if( astream > 0 ) { --astream; continue; }
2447 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
2448 if( ffaudio[i]->fidx == aidx ) astrm = i;
2450 if( ret < 0 ) ret = astrm;
2451 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
2452 channels |= mask << ffaudio[astrm]->channel0;
2454 if( !astream ) break;
2456 channel_mask = channels;
2461 int FFMPEG::ff_total_video_layers()
2463 return vstrm_index.size();
2466 int FFMPEG::ff_total_vstreams()
2468 return ffvideo.size();
2471 int FFMPEG::ff_video_width(int stream)
2473 return ffvideo[stream]->width;
2476 int FFMPEG::ff_video_height(int stream)
2478 return ffvideo[stream]->height;
2481 int FFMPEG::ff_set_video_width(int stream, int width)
2483 int w = ffvideo[stream]->width;
2484 ffvideo[stream]->width = width;
2488 int FFMPEG::ff_set_video_height(int stream, int height)
2490 int h = ffvideo[stream]->height;
2491 ffvideo[stream]->height = height;
2495 int FFMPEG::ff_coded_width(int stream)
2497 return ffvideo[stream]->avctx->coded_width;
2500 int FFMPEG::ff_coded_height(int stream)
2502 return ffvideo[stream]->avctx->coded_height;
2505 float FFMPEG::ff_aspect_ratio(int stream)
2507 return ffvideo[stream]->aspect_ratio;
2510 const char* FFMPEG::ff_video_format(int stream)
2512 AVStream *st = ffvideo[stream]->st;
2513 AVCodecID id = st->codecpar->codec_id;
2514 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2515 return desc ? desc->name : _("Unknown");
2518 double FFMPEG::ff_frame_rate(int stream)
2520 return ffvideo[stream]->frame_rate;
2523 int64_t FFMPEG::ff_video_frames(int stream)
2525 return ffvideo[stream]->length;
2528 int FFMPEG::ff_video_pid(int stream)
2530 return ffvideo[stream]->st->id;
2534 int FFMPEG::ff_cpus()
2536 return file_base->file->cpus;
2539 int FFVideoStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
2541 avfilter_register_all();
2542 const char *sp = filter_spec;
2543 char filter_name[BCSTRLEN], *np = filter_name;
2544 int i = sizeof(filter_name);
2545 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
2547 AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
2548 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_VIDEO ) {
2549 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
2552 filter_graph = avfilter_graph_alloc();
2553 AVFilter *buffersrc = avfilter_get_by_name("buffer");
2554 AVFilter *buffersink = avfilter_get_by_name("buffersink");
2556 int ret = 0; char args[BCTEXTLEN];
2557 AVPixelFormat pix_fmt = (AVPixelFormat)avpar->format;
2558 snprintf(args, sizeof(args),
2559 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
2560 avpar->width, avpar->height, (int)pix_fmt,
2561 st->time_base.num, st->time_base.den,
2562 avpar->sample_aspect_ratio.num, avpar->sample_aspect_ratio.den);
2564 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2565 args, NULL, filter_graph);
2567 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2568 NULL, NULL, filter_graph);
2570 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
2571 (uint8_t*)&pix_fmt, sizeof(pix_fmt),
2572 AV_OPT_SEARCH_CHILDREN);
2574 ff_err(ret, "FFVideoStream::create_filter");
2576 ret = FFStream::create_filter(filter_spec);
2577 return ret >= 0 ? 0 : -1;
2580 int FFAudioStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
2582 avfilter_register_all();
2583 const char *sp = filter_spec;
2584 char filter_name[BCSTRLEN], *np = filter_name;
2585 int i = sizeof(filter_name);
2586 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
2588 AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
2589 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_AUDIO ) {
2590 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
2593 filter_graph = avfilter_graph_alloc();
2594 AVFilter *buffersrc = avfilter_get_by_name("abuffer");
2595 AVFilter *buffersink = avfilter_get_by_name("abuffersink");
2596 int ret = 0; char args[BCTEXTLEN];
2597 AVSampleFormat sample_fmt = (AVSampleFormat)avpar->format;
2598 snprintf(args, sizeof(args),
2599 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
2600 st->time_base.num, st->time_base.den, avpar->sample_rate,
2601 av_get_sample_fmt_name(sample_fmt), avpar->channel_layout);
2603 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2604 args, NULL, filter_graph);
2606 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2607 NULL, NULL, filter_graph);
2609 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
2610 (uint8_t*)&sample_fmt, sizeof(sample_fmt),
2611 AV_OPT_SEARCH_CHILDREN);
2613 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
2614 (uint8_t*)&avpar->channel_layout,
2615 sizeof(avpar->channel_layout), AV_OPT_SEARCH_CHILDREN);
2617 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
2618 (uint8_t*)&sample_rate, sizeof(sample_rate),
2619 AV_OPT_SEARCH_CHILDREN);
2621 ff_err(ret, "FFAudioStream::create_filter");
2623 ret = FFStream::create_filter(filter_spec);
2624 return ret >= 0 ? 0 : -1;
2627 int FFStream::create_filter(const char *filter_spec)
2629 /* Endpoints for the filter graph. */
2630 AVFilterInOut *outputs = avfilter_inout_alloc();
2631 outputs->name = av_strdup("in");
2632 outputs->filter_ctx = buffersrc_ctx;
2633 outputs->pad_idx = 0;
2636 AVFilterInOut *inputs = avfilter_inout_alloc();
2637 inputs->name = av_strdup("out");
2638 inputs->filter_ctx = buffersink_ctx;
2639 inputs->pad_idx = 0;
2642 int ret = !outputs->name || !inputs->name ? -1 : 0;
2644 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
2645 &inputs, &outputs, NULL);
2647 ret = avfilter_graph_config(filter_graph, NULL);
2650 ff_err(ret, "FFStream::create_filter");
2651 avfilter_graph_free(&filter_graph);
2654 avfilter_inout_free(&inputs);
2655 avfilter_inout_free(&outputs);
2659 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
2662 av_init_packet(&pkt);
2663 AVFrame *frame = av_frame_alloc();
2665 fprintf(stderr,"FFMPEG::scan: ");
2666 fprintf(stderr,_("av_frame_alloc failed\n"));
2670 index_state->add_video_markers(ffvideo.size());
2671 index_state->add_audio_markers(ffaudio.size());
2673 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2675 AVDictionary *copts = 0;
2676 av_dict_copy(&copts, opts, 0);
2677 AVStream *st = fmt_ctx->streams[i];
2678 AVCodecID codec_id = st->codecpar->codec_id;
2679 AVCodec *decoder = avcodec_find_decoder(codec_id);
2680 AVCodecContext *avctx = avcodec_alloc_context3(decoder);
2682 eprintf(_("cant allocate codec context\n"));
2683 ret = AVERROR(ENOMEM);
2686 avcodec_parameters_to_context(avctx, st->codecpar);
2687 ret = avcodec_open2(avctx, decoder, &copts);
2689 av_dict_free(&copts);
2691 AVCodecParameters *avpar = st->codecpar;
2692 switch( avpar->codec_type ) {
2693 case AVMEDIA_TYPE_VIDEO: {
2694 int vidx = ffvideo.size();
2695 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
2696 if( vidx < 0 ) break;
2697 ffvideo[vidx]->avctx = avctx;
2699 case AVMEDIA_TYPE_AUDIO: {
2700 int aidx = ffaudio.size();
2701 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
2702 if( aidx < 0 ) break;
2703 ffaudio[aidx]->avctx = avctx;
2708 fprintf(stderr,"FFMPEG::scan: ");
2709 fprintf(stderr,_("codec open failed\n"));
2710 avcodec_free_context(&avctx);
2714 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2715 AVStream *st = fmt_ctx->streams[i];
2716 AVCodecParameters *avpar = st->codecpar;
2717 if( avpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
2718 int64_t tstmp = st->start_time;
2719 if( tstmp == AV_NOPTS_VALUE ) continue;
2720 int aidx = ffaudio.size();
2721 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
2722 if( aidx < 0 ) continue;
2723 FFAudioStream *aud = ffaudio[aidx];
2724 tstmp -= aud->nudge;
2725 double secs = to_secs(tstmp, st->time_base);
2726 aud->curr_pos = secs * aud->sample_rate + 0.5;
2730 for( int64_t count=0; !*canceled; ++count ) {
2731 av_packet_unref(&pkt);
2732 pkt.data = 0; pkt.size = 0;
2734 int ret = av_read_frame(fmt_ctx, &pkt);
2736 if( ret == AVERROR_EOF ) break;
2737 if( ++errs > 100 ) {
2738 ff_err(ret,_("over 100 read_frame errs\n"));
2743 if( !pkt.data ) continue;
2744 int i = pkt.stream_index;
2745 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
2746 AVStream *st = fmt_ctx->streams[i];
2747 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
2749 AVCodecParameters *avpar = st->codecpar;
2750 switch( avpar->codec_type ) {
2751 case AVMEDIA_TYPE_VIDEO: {
2752 int vidx = ffvideo.size();
2753 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
2754 if( vidx < 0 ) break;
2755 FFVideoStream *vid = ffvideo[vidx];
2756 if( !vid->avctx ) break;
2757 int64_t tstmp = pkt.dts;
2758 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.pts;
2759 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
2760 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
2761 double secs = to_secs(tstmp, st->time_base);
2762 int64_t frm = secs * vid->frame_rate + 0.5;
2763 if( frm < 0 ) frm = 0;
2764 index_state->put_video_mark(vidx, frm, pkt.pos);
2767 ret = avcodec_send_packet(vid->avctx, pkt);
2768 if( ret < 0 ) break;
2769 while( (ret=vid->decode_frame(frame)) > 0 ) {}
2772 case AVMEDIA_TYPE_AUDIO: {
2773 int aidx = ffaudio.size();
2774 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
2775 if( aidx < 0 ) break;
2776 FFAudioStream *aud = ffaudio[aidx];
2777 if( !aud->avctx ) break;
2778 int64_t tstmp = pkt.pts;
2779 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
2780 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
2781 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
2782 double secs = to_secs(tstmp, st->time_base);
2783 int64_t sample = secs * aud->sample_rate + 0.5;
2785 index_state->put_audio_mark(aidx, sample, pkt.pos);
2787 ret = avcodec_send_packet(aud->avctx, &pkt);
2788 if( ret < 0 ) break;
2789 int ch = aud->channel0, nch = aud->channels;
2790 int64_t pos = index_state->pos(ch);
2791 if( pos != aud->curr_pos ) {
2792 if( abs(pos-aud->curr_pos) > 1 )
2793 printf("audio%d pad %jd %jd (%jd)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
2794 index_state->pad_data(ch, nch, aud->curr_pos);
2796 while( (ret=aud->decode_frame(frame)) > 0 ) {
2797 //if( frame->channels != nch ) break;
2798 aud->init_swr(frame->channels, frame->format, frame->sample_rate);
2800 int len = aud->get_samples(samples,
2801 &frame->extended_data[0], frame->nb_samples);
2802 pos = aud->curr_pos;
2803 if( (aud->curr_pos += len) >= 0 ) {
2805 samples += -pos * nch;
2806 len = aud->curr_pos;
2808 for( int i=0; i<nch; ++i )
2809 index_state->put_data(ch+i,nch,samples+i,len);
2816 av_frame_free(&frame);
2820 void FFStream::load_markers(IndexMarks &marks, double rate)
2823 int64_t sz = marks.size();
2824 int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
2825 int nb_ent = st->nb_index_entries;
2826 // some formats already have an index
2828 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
2829 int64_t tstmp = ep->timestamp;
2830 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
2831 double secs = ffmpeg->to_secs(tstmp, st->time_base);
2832 int64_t no = secs * rate;
2833 while( in < sz && marks[in].no <= no ) ++in;
2835 int64_t len = sz - in;
2836 int64_t count = max_entries - nb_ent;
2837 if( count > len ) count = len;
2838 for( int i=0; i<count; ++i ) {
2839 int k = in + i * len / count;
2840 int64_t no = marks[k].no, pos = marks[k].pos;
2841 double secs = (double)no / rate;
2842 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
2843 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
2844 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);