10 // work arounds (centos)
13 #define INT64_MAX 9223372036854775807LL
15 #define MAX_RETRY 1000
18 #include "bccmodels.h"
20 #include "fileffmpeg.h"
23 #include "indexfile.h"
24 #include "interlacemodes.h"
27 #include "mainerror.h"
32 #define VIDEO_INBUF_SIZE 0x10000
33 #define AUDIO_INBUF_SIZE 0x10000
34 #define VIDEO_REFILL_THRESH 0
35 #define AUDIO_REFILL_THRESH 0x1000
37 Mutex FFMPEG::fflock("FFMPEG::fflock");
39 static void ff_err(int ret, const char *fmt, ...)
44 vsnprintf(msg, sizeof(msg), fmt, ap);
46 char errmsg[BCSTRLEN];
47 av_strerror(ret, errmsg, sizeof(errmsg));
48 fprintf(stderr,_("%s err: %s\n"),msg, errmsg);
54 pkt.data = 0; pkt.size = 0;
56 void FFPacket::finit()
58 av_packet_unref(&pkt);
61 FFrame::FFrame(FFStream *fst)
64 frm = av_frame_alloc();
65 init = fst->init_frame(frm);
73 void FFrame::queue(int64_t pos)
79 void FFrame::dequeue()
84 int FFAudioStream::read(float *fp, long len)
92 while( --k >= 0 ) *fp++ = *op++;
93 if( op >= lmt ) op = bfr;
98 void FFAudioStream::realloc(long nsz, int nch, long len)
100 long bsz = nsz * nch;
101 float *np = new float[bsz];
102 inp = np + read(np, len) * nch;
107 delete [] bfr; bfr = np;
110 void FFAudioStream::realloc(long nsz, int nch)
112 if( nsz > sz || this->nch != nch ) {
113 long len = this->nch != nch ? 0 : hpos;
114 if( len > sz ) len = sz;
116 realloc(nsz, nch, len);
120 void FFAudioStream::reserve(long nsz, int nch)
122 long len = (inp - outp) / nch;
124 if( nsz > sz || this->nch != nch ) {
125 if( this->nch != nch ) len = 0;
126 realloc(nsz, nch, len);
129 if( (len*=nch) > 0 && bfr != outp )
130 memmove(bfr, outp, len*sizeof(*bfr));
135 long FFAudioStream::used()
137 long len = inp>=outp ? inp-outp : inp-bfr + lmt-outp;
140 long FFAudioStream::avail()
143 if( in1 >= lmt ) in1 = bfr;
144 long len = outp >= in1 ? outp-in1 : outp-bfr + lmt-in1;
147 void FFAudioStream::reset_history()
153 void FFAudioStream::iseek(int64_t ofs)
155 outp = inp - ofs*nch;
156 if( outp < bfr ) outp += sz*nch;
159 float *FFAudioStream::get_outp(int ofs)
166 int64_t FFAudioStream::put_inp(int ofs)
169 return (inp-outp) / nch;
172 int FFAudioStream::write(const float *fp, long len)
180 while( --k >= 0 ) *ip++ = *fp++;
181 if( ip >= lmt ) ip = bfr;
188 int FFAudioStream::zero(long len)
196 while( --k >= 0 ) *ip++ = 0;
197 if( ip >= lmt ) ip = bfr;
204 // does not advance outp
205 int FFAudioStream::read(double *dp, long len, int ch)
208 float *op = outp + ch;
209 float *lmt1 = lmt + nch-1;
211 int k = (lmt1 - op) / nch;
214 while( --k >= 0 ) { *dp++ = *op; op += nch; }
215 if( op >= lmt ) op -= sz*nch;
220 // load linear buffer, no wrapping allowed, does not advance inp
221 int FFAudioStream::write(const double *dp, long len, int ch)
224 float *ip = inp + ch;
225 while( --n >= 0 ) { *ip = *dp++; ip += nch; }
230 FFStream::FFStream(FFMPEG *ffmpeg, AVStream *st, int fidx)
232 this->ffmpeg = ffmpeg;
235 frm_lock = new Mutex("FFStream::frm_lock");
241 nudge = AV_NOPTS_VALUE;
242 seek_pos = curr_pos = 0;
244 reading = writing = 0;
250 FFStream::~FFStream()
252 if( reading > 0 || writing > 0 ) avcodec_close(st->codec);
253 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
254 while( frms.first ) frms.remove(frms.first);
255 if( filter_graph ) avfilter_graph_free(&filter_graph);
256 if( frame ) av_frame_free(&frame);
257 if( fframe ) av_frame_free(&fframe);
258 bsfilter.remove_all_objects();
262 void FFStream::ff_lock(const char *cp)
264 FFMPEG::fflock.lock(cp);
267 void FFStream::ff_unlock()
269 FFMPEG::fflock.unlock();
272 void FFStream::queue(FFrame *frm)
274 frm_lock->lock("FFStream::queue");
278 ffmpeg->mux_lock->unlock();
281 void FFStream::dequeue(FFrame *frm)
283 frm_lock->lock("FFStream::dequeue");
285 frms.remove_pointer(frm);
289 int FFStream::encode_activate()
292 writing = ffmpeg->encode_activate();
296 int FFStream::decode_activate()
298 if( reading < 0 && (reading=ffmpeg->decode_activate()) > 0 ) {
299 ff_lock("FFStream::decode_activate");
301 AVDictionary *copts = 0;
302 av_dict_copy(&copts, ffmpeg->opts, 0);
304 // this should be avformat_copy_context(), but no copy avail
305 ret = avformat_open_input(&fmt_ctx, ffmpeg->fmt_ctx->filename, NULL, &copts);
307 ret = avformat_find_stream_info(fmt_ctx, 0);
308 st = fmt_ctx->streams[fidx];
312 AVCodecID codec_id = st->codec->codec_id;
313 AVCodec *decoder = avcodec_find_decoder(codec_id);
314 ret = avcodec_open2(st->codec, decoder, &copts);
318 eprintf(_("open decoder failed\n"));
321 eprintf(_("can't clone input file\n"));
322 av_dict_free(&copts);
328 int FFStream::read_packet()
330 av_packet_unref(ipkt);
331 int ret = av_read_frame(fmt_ctx, ipkt);
334 if( ret == AVERROR_EOF ) {
335 ipkt->stream_index = st->index;
338 ff_err(ret, "FFStream::read_packet: av_read_frame failed\n");
345 int FFStream::decode(AVFrame *frame)
348 int retries = MAX_RETRY;
351 while( ret >= 0 && !flushed && --retries >= 0 && !got_frame ) {
354 if( (ret=read_packet()) < 0 ) break;
356 if( ipkt->stream_index == st->index ) {
357 while( (ipkt->size > 0 || !ipkt->data) && !got_frame ) {
358 ret = decode_frame(ipkt, frame, got_frame);
359 if( ret < 0 ) need_packet = 1;
360 if( ret <= 0 || !ipkt->data ) break;
373 fprintf(stderr, "FFStream::decode: Retry limit\n");
377 fprintf(stderr, "FFStream::decode: failed\n");
382 int FFStream::load_filter(AVFrame *frame)
384 int ret = av_buffersrc_add_frame_flags(buffersrc_ctx,
385 frame, AV_BUFFERSRC_FLAG_KEEP_REF);
387 av_frame_unref(frame);
388 eprintf(_("av_buffersrc_add_frame_flags failed\n"));
393 int FFStream::read_filter(AVFrame *frame)
395 int ret = av_buffersink_get_frame(buffersink_ctx, frame);
397 if( ret == AVERROR(EAGAIN) ) return 0;
398 if( ret == AVERROR_EOF ) { st_eof(1); return -1; }
399 ff_err(ret, "FFStream::read_filter: av_buffersink_get_frame failed\n");
405 int FFStream::read_frame(AVFrame *frame)
407 if( !filter_graph || !buffersrc_ctx || !buffersink_ctx )
408 return decode(frame);
409 if( !fframe && !(fframe=av_frame_alloc()) ) {
410 fprintf(stderr, "FFStream::read_frame: av_frame_alloc failed\n");
414 while( !flushed && !(ret=read_filter(frame)) ) {
415 if( (ret=decode(fframe)) < 0 ) break;
416 if( ret > 0 && (ret=load_filter(fframe)) < 0 ) break;
421 int FFStream::write_packet(FFPacket &pkt)
424 av_packet_rescale_ts(pkt, st->codec->time_base, st->time_base);
425 pkt->stream_index = st->index;
426 return av_interleaved_write_frame(ffmpeg->fmt_ctx, pkt);
429 int FFStream::flush()
437 ret = encode_frame(pkt, 0, got_packet);
438 if( ret < 0 || !got_packet ) break;
439 ret = write_packet(pkt);
442 ff_err(ret, "FFStream::flush");
443 return ret >= 0 ? 0 : 1;
446 int FFStream::seek(int64_t no, double rate)
448 int64_t tstmp = -INT64_MAX+1;
449 // default ffmpeg native seek
451 int64_t pos = no, plmt = -1;
452 IndexMarks *index_markers = get_markers();
453 if( index_markers && index_markers->size() > 1 ) {
454 IndexMarks &marks = *index_markers;
455 int i = marks.find(pos);
456 int64_t n = i < 0 ? (i=0) : marks[i].no;
457 // if indexed seek point not too far away (<30 secs), use index
458 if( no-n < 30*rate ) {
461 if( i < marks.size() ) plmt = marks[i].pos;
466 double secs = pos / rate;
467 tstmp = secs * st->time_base.den / st->time_base.num;
468 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
470 int ret = avformat_seek_file(fmt_ctx, st->index,
471 -INT64_MAX, tstmp, INT64_MAX, AVSEEK_FLAG_ANY);
473 avcodec_flush_buffers(st->codec);
474 ipkt.finit(); ipkt.init();
475 need_packet = 0; flushed = 0;
476 seeked = 1; st_eof(0);
477 // read up to retry packets, limited to npkts in stream, and not past pkt.pos plmt
479 if( read_packet() <= 0 ) { ret = -1; break; }
480 if( plmt >= 0 && ipkt->pos >= plmt ) break;
481 if( ipkt->stream_index != st->index ) continue;
482 if( --npkts <= 0 ) break;
483 int64_t pkt_ts = ipkt->dts != AV_NOPTS_VALUE ? ipkt->dts : ipkt->pts;
484 if( pkt_ts == AV_NOPTS_VALUE ) continue;
485 if( pkt_ts >= tstmp ) break;
489 //printf("** seek fail %ld, %ld\n", pos, tstmp);
490 seeked = need_packet = 0;
494 //printf("seeked pos = %ld, %ld\n", pos, tstmp);
495 seek_pos = curr_pos = pos;
499 FFAudioStream::FFAudioStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
500 : FFStream(ffmpeg, strm, fidx)
503 channel0 = channels = 0;
507 resample_context = 0;
516 bfr = new float[bsz];
521 FFAudioStream::~FFAudioStream()
523 if( resample_context ) swr_free(&resample_context);
528 int FFAudioStream::get_samples(float *&samples, uint8_t **data, int len)
530 samples = *(float **)data;
531 if( resample_context ) {
532 if( len > aud_bfr_sz ) {
538 aud_bfr = new float[aud_bfr_sz*channels];
540 int ret = swr_convert(resample_context,
541 (uint8_t**)&aud_bfr, aud_bfr_sz, (const uint8_t**)data, len);
543 ff_err(ret, "FFAudioStream::get_samples: swr_convert failed\n");
552 int FFAudioStream::load_history(uint8_t **data, int len)
555 len = get_samples(samples, data, len);
557 // biggest user bfr since seek + frame
558 realloc(mbsz + len + 1, channels);
564 int FFAudioStream::decode_frame(AVPacket *pkt, AVFrame *frame, int &got_frame)
566 int first_frame = seeked; seeked = 0;
567 int ret = avcodec_decode_audio4(st->codec, frame, &got_frame, pkt);
569 if( first_frame ) return 0;
570 ff_err(ret, "FFAudioStream::decode_frame: Could not read audio frame\n");
574 int64_t pkt_ts = av_frame_get_best_effort_timestamp(frame);
575 if( pkt_ts != AV_NOPTS_VALUE )
576 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * sample_rate + 0.5;
581 int FFAudioStream::encode_activate()
583 if( writing >= 0 ) return writing;
584 AVCodecContext *ctx = st->codec;
585 frame_sz = ctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE ?
586 10000 : ctx->frame_size;
587 return FFStream::encode_activate();
590 int FFAudioStream::nb_samples()
592 AVCodecContext *ctx = st->codec;
593 return ctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE ?
594 10000 : ctx->frame_size;
597 int64_t FFAudioStream::load_buffer(double ** const sp, int len)
599 reserve(len+1, st->codec->channels);
600 for( int ch=0; ch<nch; ++ch )
601 write(sp[ch], len, ch);
605 int FFAudioStream::in_history(int64_t pos)
607 if( pos > curr_pos ) return 0;
609 if( len > sz ) len = sz;
610 if( pos < curr_pos - len ) return 0;
615 int FFAudioStream::init_frame(AVFrame *frame)
617 AVCodecContext *ctx = st->codec;
618 frame->nb_samples = frame_sz;
619 frame->format = ctx->sample_fmt;
620 frame->channel_layout = ctx->channel_layout;
621 frame->sample_rate = ctx->sample_rate;
622 int ret = av_frame_get_buffer(frame, 0);
624 ff_err(ret, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
628 int FFAudioStream::load(int64_t pos, int len)
630 if( audio_seek(pos) < 0 ) return -1;
631 if( !frame && !(frame=av_frame_alloc()) ) {
632 fprintf(stderr, "FFAudioStream::load: av_frame_alloc failed\n");
635 if( mbsz < len ) mbsz = len;
636 int64_t end_pos = pos + len;
638 for( int i=0; ret>=0 && !flushed && curr_pos<end_pos && i<MAX_RETRY; ++i ) {
639 ret = read_frame(frame);
641 load_history(&frame->extended_data[0], frame->nb_samples);
642 curr_pos += frame->nb_samples;
645 if( end_pos > curr_pos ) {
646 zero(end_pos - curr_pos);
649 len = curr_pos - pos;
654 int FFAudioStream::audio_seek(int64_t pos)
656 if( decode_activate() < 0 ) return -1;
657 if( !st->codec || !st->codec->codec ) return -1;
658 if( in_history(pos) ) return 0;
659 if( pos == curr_pos ) return 0;
660 reset_history(); mbsz = 0;
661 // guarentee preload > 1sec samples
662 if( seek(pos-sample_rate, sample_rate) < 0 ) return -1;
666 int FFAudioStream::encode(double **samples, int len)
668 if( encode_activate() <= 0 ) return -1;
671 int64_t count = load_buffer(samples, len);
674 while( ret >= 0 && count >= frame_sz ) {
675 frm = new FFrame(this);
676 if( (ret=frm->initted()) < 0 ) break;
677 AVFrame *frame = *frm;
678 float *bfrp = get_outp(frame_sz);
679 ret = swr_convert(resample_context,
680 (uint8_t **)frame->extended_data, frame_sz,
681 (const uint8_t **)&bfrp, frame_sz);
683 ff_err(ret, "FFAudioStream::encode: swr_convert failed\n");
686 frm->queue(curr_pos);
688 curr_pos += frame_sz;
693 return ret >= 0 ? 0 : 1;
696 int FFAudioStream::encode_frame(AVPacket *pkt, AVFrame *frame, int &got_packet)
698 int ret = avcodec_encode_audio2(st->codec, pkt, frame, &got_packet);
700 ff_err(ret, "FFAudioStream::encode_frame: encode audio failed\n");
706 void FFAudioStream::load_markers()
708 IndexState *index_state = ffmpeg->file_base->asset->index_state;
709 if( !index_state || idx >= index_state->audio_markers.size() ) return;
710 if( index_state->marker_status == MARKERS_NOTTESTED ) return;
711 FFStream::load_markers(*index_state->audio_markers[idx], sample_rate);
714 IndexMarks *FFAudioStream::get_markers()
716 IndexState *index_state = ffmpeg->file_base->asset->index_state;
717 if( !index_state || idx >= index_state->audio_markers.size() ) return 0;
718 return index_state->audio_markers[idx];
721 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
722 : FFStream(ffmpeg, strm, fidx)
733 FFVideoStream::~FFVideoStream()
737 int FFVideoStream::decode_frame(AVPacket *pkt, AVFrame *frame, int &got_frame)
739 int first_frame = seeked; seeked = 0;
740 int ret = avcodec_decode_video2(st->codec, frame, &got_frame, pkt);
742 if( first_frame ) return 0;
743 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame\n");
746 else // this is right out of ffplay, looks questionable ???
750 int64_t pkt_ts = av_frame_get_best_effort_timestamp(frame);
751 if( pkt_ts != AV_NOPTS_VALUE )
752 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * frame_rate + 0.5;
757 int FFVideoStream::load(VFrame *vframe, int64_t pos)
759 int ret = video_seek(pos);
760 if( ret < 0 ) return -1;
761 if( !frame && !(frame=av_frame_alloc()) ) {
762 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
765 for( int i=0; ret>=0 && !flushed && curr_pos<=pos && i<MAX_RETRY; ++i ) {
766 ret = read_frame(frame);
767 if( ret > 0 ) ++curr_pos;
769 if( frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0 )
772 ret = convert_cmodel(vframe, frame);
774 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
778 int FFVideoStream::video_seek(int64_t pos)
780 if( decode_activate() < 0 ) return -1;
781 if( !st->codec || !st->codec->codec ) return -1;
782 if( pos == curr_pos-1 && !seeked ) return 0;
783 // if close enough, just read up to current
784 int gop = st->codec->gop_size;
785 if( gop < 4 ) gop = 4;
786 if( gop > 64 ) gop = 64;
787 int read_limit = curr_pos + 3*gop;
788 if( pos >= curr_pos && pos <= read_limit ) return 0;
789 // guarentee preload more than 2*gop frames
790 if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
794 int FFVideoStream::init_frame(AVFrame *picture)
796 AVCodecContext *ctx = st->codec;
797 picture->format = ctx->pix_fmt;
798 picture->width = ctx->width;
799 picture->height = ctx->height;
800 int ret = av_frame_get_buffer(picture, 32);
804 int FFVideoStream::encode(VFrame *vframe)
806 if( encode_activate() <= 0 ) return -1;
808 FFrame *picture = new FFrame(this);
809 int ret = picture->initted();
811 AVFrame *frame = *picture;
812 frame->pts = curr_pos;
813 ret = convert_pixfmt(vframe, frame);
816 picture->queue(curr_pos);
820 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
823 return ret >= 0 ? 0 : 1;
826 int FFVideoStream::encode_frame(AVPacket *pkt, AVFrame *frame, int &got_packet)
829 frame->interlaced_frame = interlaced;
830 frame->top_field_first = top_field_first;
832 int ret = avcodec_encode_video2(st->codec, pkt, frame, &got_packet);
834 ff_err(ret, "FFVideoStream::encode_frame: encode video failed\n");
840 AVPixelFormat FFVideoConvert::color_model_to_pix_fmt(int color_model)
842 switch( color_model ) {
843 case BC_YUV422: return AV_PIX_FMT_YUYV422;
844 case BC_RGB888: return AV_PIX_FMT_RGB24;
845 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
846 case BC_BGR8888: return AV_PIX_FMT_BGR0;
847 case BC_BGR888: return AV_PIX_FMT_BGR24;
848 case BC_ARGB8888: return AV_PIX_FMT_ARGB;
849 case BC_ABGR8888: return AV_PIX_FMT_ABGR;
850 case BC_RGB8: return AV_PIX_FMT_RGB8;
851 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
852 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
853 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
854 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
855 case BC_RGB565: return AV_PIX_FMT_RGB565;
856 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
857 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
858 case BC_AYUV16161616: return AV_PIX_FMT_AYUV64LE;
862 return AV_PIX_FMT_NB;
865 int FFVideoConvert::pix_fmt_to_color_model(AVPixelFormat pix_fmt)
868 case AV_PIX_FMT_YUYV422: return BC_YUV422;
869 case AV_PIX_FMT_RGB24: return BC_RGB888;
870 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
871 case AV_PIX_FMT_BGR0: return BC_BGR8888;
872 case AV_PIX_FMT_BGR24: return BC_BGR888;
873 case AV_PIX_FMT_ARGB: return BC_ARGB8888;
874 case AV_PIX_FMT_ABGR: return BC_ABGR8888;
875 case AV_PIX_FMT_RGB8: return BC_RGB8;
876 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
877 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
878 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
879 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
880 case AV_PIX_FMT_RGB565: return BC_RGB565;
881 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
882 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
883 case AV_PIX_FMT_AYUV64LE: return BC_AYUV16161616;
890 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip)
892 AVFrame *ipic = av_frame_alloc();
893 int ret = convert_picture_vframe(frame, ip, ipic);
894 av_frame_free(&ipic);
898 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip, AVFrame *ipic)
900 int cmodel = frame->get_color_model();
901 AVPixelFormat ofmt = color_model_to_pix_fmt(cmodel);
902 if( ofmt == AV_PIX_FMT_NB ) return -1;
903 int size = av_image_fill_arrays(ipic->data, ipic->linesize,
904 frame->get_data(), ofmt, frame->get_w(), frame->get_h(), 1);
905 if( size < 0 ) return -1;
907 int bpp = BC_CModels::calculate_pixelsize(cmodel);
908 int ysz = bpp * frame->get_w(), usz = ysz;
917 // override av_image_fill_arrays() for planar types
918 ipic->data[0] = frame->get_y(); ipic->linesize[0] = ysz;
919 ipic->data[1] = frame->get_u(); ipic->linesize[1] = usz;
920 ipic->data[2] = frame->get_v(); ipic->linesize[2] = usz;
923 ipic->data[0] = frame->get_data();
924 ipic->linesize[0] = frame->get_bytes_per_line();
928 AVPixelFormat pix_fmt = (AVPixelFormat)ip->format;
929 convert_ctx = sws_getCachedContext(convert_ctx, ip->width, ip->height, pix_fmt,
930 frame->get_w(), frame->get_h(), ofmt, SWS_POINT, NULL, NULL, NULL);
932 fprintf(stderr, "FFVideoConvert::convert_picture_frame:"
933 " sws_getCachedContext() failed\n");
936 int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ip->height,
937 ipic->data, ipic->linesize);
939 ff_err(ret, "FFVideoConvert::convert_picture_frame: sws_scale() failed\n");
945 int FFVideoConvert::convert_cmodel(VFrame *frame, AVFrame *ip)
947 // try direct transfer
948 if( !convert_picture_vframe(frame, ip) ) return 1;
949 // use indirect transfer
950 AVPixelFormat ifmt = (AVPixelFormat)ip->format;
951 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
953 for( int i = 0; i <desc->nb_components; ++i ) {
954 int bits = desc->comp[i].depth;
955 if( bits > max_bits ) max_bits = bits;
957 int imodel = pix_fmt_to_color_model(ifmt);
958 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
959 int cmodel = frame->get_color_model();
960 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
961 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
962 imodel = cmodel_is_yuv ?
963 (BC_CModels::has_alpha(cmodel) ?
965 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
966 (BC_CModels::has_alpha(cmodel) ?
967 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
968 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
970 VFrame vframe(ip->width, ip->height, imodel);
971 if( convert_picture_vframe(&vframe, ip) ) return -1;
972 frame->transfer_from(&vframe);
976 int FFVideoConvert::transfer_cmodel(VFrame *frame, AVFrame *ifp)
978 int ret = convert_cmodel(frame, ifp);
980 const AVDictionary *src = av_frame_get_metadata(ifp);
981 AVDictionaryEntry *t = NULL;
982 BC_Hash *hp = frame->get_params();
984 while( (t=av_dict_get(src, "", t, AV_DICT_IGNORE_SUFFIX)) )
985 hp->update(t->key, t->value);
990 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op)
992 AVFrame *opic = av_frame_alloc();
993 int ret = convert_vframe_picture(frame, op, opic);
994 av_frame_free(&opic);
998 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op, AVFrame *opic)
1000 int cmodel = frame->get_color_model();
1001 AVPixelFormat ifmt = color_model_to_pix_fmt(cmodel);
1002 if( ifmt == AV_PIX_FMT_NB ) return -1;
1003 int size = av_image_fill_arrays(opic->data, opic->linesize,
1004 frame->get_data(), ifmt, frame->get_w(), frame->get_h(), 1);
1005 if( size < 0 ) return -1;
1007 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1008 int ysz = bpp * frame->get_w(), usz = ysz;
1017 // override av_image_fill_arrays() for planar types
1018 opic->data[0] = frame->get_y(); opic->linesize[0] = ysz;
1019 opic->data[1] = frame->get_u(); opic->linesize[1] = usz;
1020 opic->data[2] = frame->get_v(); opic->linesize[2] = usz;
1023 opic->data[0] = frame->get_data();
1024 opic->linesize[0] = frame->get_bytes_per_line();
1028 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1029 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(),
1030 ifmt, op->width, op->height, ofmt, SWS_POINT, NULL, NULL, NULL);
1031 if( !convert_ctx ) {
1032 fprintf(stderr, "FFVideoConvert::convert_frame_picture:"
1033 " sws_getCachedContext() failed\n");
1036 int ret = sws_scale(convert_ctx, opic->data, opic->linesize, 0, frame->get_h(),
1037 op->data, op->linesize);
1039 ff_err(ret, "FFVideoConvert::convert_frame_picture: sws_scale() failed\n");
1045 int FFVideoConvert::convert_pixfmt(VFrame *frame, AVFrame *op)
1047 // try direct transfer
1048 if( !convert_vframe_picture(frame, op) ) return 1;
1049 // use indirect transfer
1050 int cmodel = frame->get_color_model();
1051 int max_bits = BC_CModels::calculate_pixelsize(cmodel) * 8;
1052 max_bits /= BC_CModels::components(cmodel);
1053 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1054 int imodel = pix_fmt_to_color_model(ofmt);
1055 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1056 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1057 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1058 imodel = cmodel_is_yuv ?
1059 (BC_CModels::has_alpha(cmodel) ?
1061 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1062 (BC_CModels::has_alpha(cmodel) ?
1063 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1064 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1066 VFrame vframe(frame->get_w(), frame->get_h(), imodel);
1067 vframe.transfer_from(frame);
1068 if( !convert_vframe_picture(&vframe, op) ) return 1;
1072 int FFVideoConvert::transfer_pixfmt(VFrame *frame, AVFrame *ofp)
1074 int ret = convert_pixfmt(frame, ofp);
1076 BC_Hash *hp = frame->get_params();
1077 AVDictionary **dict = avpriv_frame_get_metadatap(ofp);
1078 //av_dict_free(dict);
1079 for( int i=0; i<hp->size(); ++i ) {
1080 char *key = hp->get_key(i), *val = hp->get_value(i);
1081 av_dict_set(dict, key, val, 0);
1087 void FFVideoStream::load_markers()
1089 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1090 if( !index_state || idx >= index_state->video_markers.size() ) return;
1091 FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
1094 IndexMarks *FFVideoStream::get_markers()
1096 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1097 if( !index_state || idx >= index_state->video_markers.size() ) return 0;
1098 return !index_state ? 0 : index_state->video_markers[idx];
1102 FFMPEG::FFMPEG(FileBase *file_base)
1105 this->file_base = file_base;
1106 memset(file_format,0,sizeof(file_format));
1107 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
1108 flow_lock = new Condition(1,"FFStream::flow_lock",0);
1111 decoding = encoding = 0;
1112 has_audio = has_video = 0;
1115 opt_video_filter = 0;
1116 opt_audio_filter = 0;
1117 char option_path[BCTEXTLEN];
1118 set_option_path(option_path, "%s", "ffmpeg.opts");
1119 read_options(option_path, opts);
1124 ff_lock("FFMPEG::~FFMPEG()");
1126 ffaudio.remove_all_objects();
1127 ffvideo.remove_all_objects();
1128 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1132 av_dict_free(&opts);
1133 delete [] opt_video_filter;
1134 delete [] opt_audio_filter;
1137 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1139 const int *p = codec->supported_samplerates;
1140 if( !p ) return sample_rate;
1142 if( *p == sample_rate ) return *p;
1148 static inline AVRational std_frame_rate(int i)
1150 static const int m1 = 1001*12, m2 = 1000*12;
1151 static const int freqs[] = {
1152 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1153 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
1155 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1156 return (AVRational) { freq, 1001*12 };
1159 AVRational FFMPEG::check_frame_rate(AVCodec *codec, double frame_rate)
1161 const AVRational *p = codec->supported_framerates;
1162 AVRational rate, best_rate = (AVRational) { 0, 0 };
1163 double max_err = 1.; int i = 0;
1164 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1165 double framerate = (double) rate.num / rate.den;
1166 double err = fabs(frame_rate/framerate - 1.);
1167 if( err >= max_err ) continue;
1171 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1174 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1177 double display_aspect = asset->width / (double)asset->height;
1178 double sample_aspect = asset->aspect_ratio / display_aspect;
1179 int width = 1000000, height = width * sample_aspect + 0.5;
1181 MWindow::create_aspect_ratio(w, h, width, height);
1182 return (AVRational){(int)w, (int)h};
1185 return (AVRational){1, 1};
1189 AVRational FFMPEG::to_time_base(int sample_rate)
1191 return (AVRational){1, sample_rate};
1194 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
1196 char *ep = path + BCTEXTLEN-1;
1197 strncpy(path, File::get_cindat_path(), ep-path);
1198 strncat(path, "/ffmpeg/", ep-path);
1199 path += strlen(path);
1202 path += vsnprintf(path, ep-path, fmt, ap);
1207 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
1212 set_option_path(path, "%s/%s", type, spec);
1215 int FFMPEG::get_format(char *format, const char *path, const char *spec)
1217 char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
1218 get_option_path(option_path, path, spec);
1219 FILE *fp = fopen(option_path,"r");
1222 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1224 line[sizeof(line)-1] = 0;
1225 ret = scan_option_line(line, format, codec);
1231 int FFMPEG::get_codec(char *codec, const char *path, const char *spec)
1233 char option_path[BCTEXTLEN], line[BCTEXTLEN], format[BCTEXTLEN];
1234 get_option_path(option_path, path, spec);
1235 FILE *fp = fopen(option_path,"r");
1238 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1241 line[sizeof(line)-1] = 0;
1242 ret = scan_option_line(line, format, codec);
1245 char *vp = codec, *ep = vp+BCTEXTLEN-1;
1246 while( vp < ep && *vp && *vp != '|' ) ++vp;
1247 if( *vp == '|' ) --vp;
1248 while( vp > codec && (*vp==' ' || *vp=='\t') ) *vp-- = 0;
1253 int FFMPEG::get_file_format()
1255 char audio_muxer[BCSTRLEN], video_muxer[BCSTRLEN];
1256 char audio_format[BCSTRLEN], video_format[BCSTRLEN];
1257 audio_muxer[0] = audio_format[0] = 0;
1258 video_muxer[0] = video_format[0] = 0;
1259 Asset *asset = file_base->asset;
1260 int ret = asset ? 0 : 1;
1261 if( !ret && asset->audio_data ) {
1262 if( !(ret=get_format(audio_format, "audio", asset->acodec)) ) {
1263 if( get_format(audio_muxer, "format", audio_format) ) {
1264 strcpy(audio_muxer, audio_format);
1265 audio_format[0] = 0;
1269 if( !ret && asset->video_data ) {
1270 if( !(ret=get_format(video_format, "video", asset->vcodec)) ) {
1271 if( get_format(video_muxer, "format", video_format) ) {
1272 strcpy(video_muxer, video_format);
1273 video_format[0] = 0;
1277 if( !ret && !audio_muxer[0] && !video_muxer[0] )
1279 if( !ret && audio_muxer[0] && video_muxer[0] &&
1280 strcmp(audio_muxer, video_muxer) ) ret = -1;
1281 if( !ret && audio_format[0] && video_format[0] &&
1282 strcmp(audio_format, video_format) ) ret = -1;
1284 strcpy(file_format, !audio_format[0] && !video_format[0] ?
1285 (audio_muxer[0] ? audio_muxer : video_muxer) :
1286 (audio_format[0] ? audio_format : video_format));
1290 int FFMPEG::scan_option_line(char *cp, char *tag, char *val)
1292 while( *cp == ' ' || *cp == '\t' ) ++cp;
1294 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' && *cp != '\n' ) ++cp;
1296 if( !len || len > BCSTRLEN-1 ) return 1;
1297 while( bp < cp ) *tag++ = *bp++;
1299 while( *cp == ' ' || *cp == '\t' ) ++cp;
1300 if( *cp == '=' ) ++cp;
1301 while( *cp == ' ' || *cp == '\t' ) ++cp;
1303 while( *cp && *cp != '\n' ) ++cp;
1305 if( len > BCTEXTLEN-1 ) return 1;
1306 while( bp < cp ) *val++ = *bp++;
1311 int FFMPEG::load_defaults(const char *path, const char *type,
1312 char *codec, char *codec_options, int len)
1314 char default_file[BCTEXTLEN];
1315 set_option_path(default_file, "%s/%s.dfl", path, type);
1316 FILE *fp = fopen(default_file,"r");
1318 fgets(codec, BCSTRLEN, fp);
1320 while( *cp && *cp!='\n' ) ++cp;
1322 while( len > 0 && fgets(codec_options, len, fp) ) {
1323 int n = strlen(codec_options);
1324 codec_options += n; len -= n;
1327 set_option_path(default_file, "%s/%s", path, codec);
1328 return load_options(default_file, codec_options, len);
1331 void FFMPEG::set_asset_format(Asset *asset, const char *text)
1333 if( asset->format != FILE_FFMPEG ) return;
1334 if( text != asset->fformat )
1335 strcpy(asset->fformat, text);
1336 if( !asset->ff_audio_options[0] ) {
1337 asset->audio_data = !load_defaults("audio", text, asset->acodec,
1338 asset->ff_audio_options, sizeof(asset->ff_audio_options));
1340 if( !asset->ff_video_options[0] ) {
1341 asset->video_data = !load_defaults("video", text, asset->vcodec,
1342 asset->ff_video_options, sizeof(asset->ff_video_options));
1346 int FFMPEG::get_encoder(const char *options,
1347 char *format, char *codec, char *bsfilter, char *bsargs)
1349 FILE *fp = fopen(options,"r");
1351 eprintf(_("options open failed %s\n"),options);
1354 if( get_encoder(fp, format, codec, bsfilter, bsargs) )
1355 eprintf(_("format/codec not found %s\n"), options);
1360 int FFMPEG::get_encoder(FILE *fp,
1361 char *format, char *codec, char *bsfilter, char *bsargs)
1363 format[0] = codec[0] = bsfilter[0] = bsargs[0] = 0;
1364 char line[BCTEXTLEN];
1365 if( !fgets(line, sizeof(line), fp) ) return 1;
1366 line[sizeof(line)-1] = 0;
1367 if( scan_option_line(line, format, codec) ) return 1;
1369 while( *cp && *cp != '|' ) ++cp;
1370 if( !*cp ) return 0;
1371 if( scan_option_line(cp+1, bsfilter, bsargs) ) return 1;
1372 do { *cp-- = 0; } while( cp>=codec && (*cp==' ' || *cp == '\t' ) );
1376 int FFMPEG::read_options(const char *options, AVDictionary *&opts, int skip)
1378 FILE *fp = fopen(options,"r");
1381 while( !ret && --skip >= 0 ) {
1383 while( ch >= 0 && ch != '\n' ) ch = getc(fp);
1384 if( ch < 0 ) ret = 1;
1387 ret = read_options(fp, options, opts);
1392 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
1394 FILE *fp = fmemopen((void *)options,strlen(options),"r");
1396 int ret = read_options(fp, options, opts);
1398 AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
1399 if( tag ) st->id = strtol(tag->value,0,0);
1403 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
1405 int ret = 0, no = 0;
1406 char line[BCTEXTLEN];
1407 while( !ret && fgets(line, sizeof(line), fp) ) {
1408 line[sizeof(line)-1] = 0;
1409 if( line[0] == '#' ) continue;
1410 if( line[0] == '\n' ) continue;
1411 char key[BCSTRLEN], val[BCTEXTLEN];
1412 if( scan_option_line(line, key, val) ) {
1413 eprintf(_("err reading %s: line %d\n"), options, no);
1417 if( !strcmp(key, "duration") )
1418 opt_duration = strtod(val, 0);
1419 else if( !strcmp(key, "video_filter") )
1420 opt_video_filter = cstrdup(val);
1421 else if( !strcmp(key, "audio_filter") )
1422 opt_audio_filter = cstrdup(val);
1423 else if( !strcmp(key, "loglevel") )
1426 av_dict_set(&opts, key, val, 0);
1432 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
1434 char option_path[BCTEXTLEN];
1435 set_option_path(option_path, "%s", options);
1436 return read_options(option_path, opts);
1439 int FFMPEG::load_options(const char *path, char *bfr, int len)
1442 FILE *fp = fopen(path, "r");
1444 fgets(bfr, len, fp); // skip hdr
1445 len = fread(bfr, 1, len-1, fp);
1446 if( len < 0 ) len = 0;
1452 void FFMPEG::set_loglevel(const char *ap)
1454 if( !ap || !*ap ) return;
1459 { "quiet" , AV_LOG_QUIET },
1460 { "panic" , AV_LOG_PANIC },
1461 { "fatal" , AV_LOG_FATAL },
1462 { "error" , AV_LOG_ERROR },
1463 { "warning", AV_LOG_WARNING },
1464 { "info" , AV_LOG_INFO },
1465 { "verbose", AV_LOG_VERBOSE },
1466 { "debug" , AV_LOG_DEBUG },
1468 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
1469 if( !strcmp(log_levels[i].name, ap) ) {
1470 av_log_set_level(log_levels[i].level);
1474 av_log_set_level(atoi(ap));
1477 double FFMPEG::to_secs(int64_t time, AVRational time_base)
1479 double base_time = time == AV_NOPTS_VALUE ? 0 :
1480 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
1481 return base_time / AV_TIME_BASE;
1484 int FFMPEG::info(char *text, int len)
1486 if( len <= 0 ) return 0;
1488 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
1490 if( ffvideo.size() > 0 )
1491 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
1492 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
1493 FFVideoStream *vid = ffvideo[vidx];
1494 AVStream *st = vid->st;
1495 AVCodecContext *avctx = st->codec;
1496 report(_("vid%d (%d), id 0x%06x:\n"), vid->idx, vid->fidx, avctx->codec_id);
1497 const AVCodecDescriptor *desc = avcodec_descriptor_get(avctx->codec_id);
1498 report(" video%d %s", vidx+1, desc ? desc->name : " (unkn)");
1499 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
1500 const char *pfn = av_get_pix_fmt_name(avctx->pix_fmt);
1501 report(" pix %s\n", pfn ? pfn : "(unkn)");
1502 double secs = to_secs(st->duration, st->time_base);
1503 int64_t length = secs * vid->frame_rate + 0.5;
1504 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
1505 int64_t nudge = ofs * vid->frame_rate;
1506 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1507 report(" %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
1508 int hrs = secs/3600; secs -= hrs*3600;
1509 int mins = secs/60; secs -= mins*60;
1510 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1512 if( ffaudio.size() > 0 )
1513 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
1514 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
1515 FFAudioStream *aud = ffaudio[aidx];
1516 AVStream *st = aud->st;
1517 AVCodecContext *avctx = st->codec;
1518 report(_("aud%d (%d), id 0x%06x:\n"), aud->idx, aud->fidx, avctx->codec_id);
1519 const AVCodecDescriptor *desc = avcodec_descriptor_get(avctx->codec_id);
1520 int nch = aud->channels, ch0 = aud->channel0+1;
1521 report(" audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
1522 const char *fmt = av_get_sample_fmt_name(avctx->sample_fmt);
1523 report(" %s %d", fmt, aud->sample_rate);
1524 int sample_bits = av_get_bits_per_sample(avctx->codec_id);
1525 report(" %dbits\n", sample_bits);
1526 double secs = to_secs(st->duration, st->time_base);
1527 int64_t length = secs * aud->sample_rate + 0.5;
1528 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
1529 int64_t nudge = ofs * aud->sample_rate;
1530 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1531 report(" %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
1532 int hrs = secs/3600; secs -= hrs*3600;
1533 int mins = secs/60; secs -= mins*60;
1534 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1536 if( fmt_ctx->nb_programs > 0 )
1537 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
1538 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
1539 report("program %d", i+1);
1540 AVProgram *pgrm = fmt_ctx->programs[i];
1541 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1542 int idx = pgrm->stream_index[j];
1543 int vidx = ffvideo.size();
1544 while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
1546 report(", vid%d", vidx);
1549 int aidx = ffaudio.size();
1550 while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
1552 report(", aud%d", aidx);
1555 report(", (%d)", pgrm->stream_index[j]);
1560 AVDictionaryEntry *tag = 0;
1561 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
1562 report("%s=%s\n", tag->key, tag->value);
1571 int FFMPEG::init_decoder(const char *filename)
1573 ff_lock("FFMPEG::init_decoder");
1575 char file_opts[BCTEXTLEN];
1576 char *bp = strrchr(strcpy(file_opts, filename), '/');
1577 char *sp = strrchr(!bp ? file_opts : bp, '.');
1580 strcpy(sp, ".opts");
1581 fp = fopen(file_opts, "r");
1584 read_options(fp, file_opts, opts);
1588 load_options("decode.opts", opts);
1589 AVDictionary *fopts = 0;
1590 av_dict_copy(&fopts, opts, 0);
1591 int ret = avformat_open_input(&fmt_ctx, filename, NULL, &fopts);
1592 av_dict_free(&fopts);
1594 ret = avformat_find_stream_info(fmt_ctx, NULL);
1599 return !ret ? 0 : 1;
1602 int FFMPEG::open_decoder()
1605 if( stat(fmt_ctx->filename, &st) < 0 ) {
1606 eprintf(_("can't stat file: %s\n"), fmt_ctx->filename);
1610 int64_t file_bits = 8 * st.st_size;
1611 if( !fmt_ctx->bit_rate && opt_duration > 0 )
1612 fmt_ctx->bit_rate = file_bits / opt_duration;
1615 if( fmt_ctx->bit_rate > 0 ) {
1616 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1617 AVStream *st = fmt_ctx->streams[i];
1618 if( st->duration != AV_NOPTS_VALUE ) continue;
1619 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
1620 st->duration = av_rescale(file_bits, st->time_base.den,
1621 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
1626 printf("FFMPEG::open_decoder: some stream times estimated\n");
1628 ff_lock("FFMPEG::open_decoder");
1629 int ret = 0, bad_time = 0;
1630 for( int i=0; !ret && i<(int)fmt_ctx->nb_streams; ++i ) {
1631 AVStream *st = fmt_ctx->streams[i];
1632 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
1633 AVCodecContext *avctx = st->codec;
1634 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avctx->codec_id);
1635 if( !codec_desc ) continue;
1636 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1637 if( avctx->width < 1 ) continue;
1638 if( avctx->height < 1 ) continue;
1639 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
1640 if( framerate.num < 1 ) continue;
1642 int vidx = ffvideo.size();
1643 FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
1644 vstrm_index.append(ffidx(vidx, 0));
1645 ffvideo.append(vid);
1646 vid->width = avctx->width;
1647 vid->height = avctx->height;
1648 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
1649 double secs = to_secs(st->duration, st->time_base);
1650 vid->length = secs * vid->frame_rate;
1651 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
1652 vid->nudge = st->start_time;
1654 if( opt_video_filter )
1655 ret = vid->create_filter(opt_video_filter, avctx,avctx);
1657 else if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1658 if( avctx->channels < 1 ) continue;
1659 if( avctx->sample_rate < 1 ) continue;
1661 int aidx = ffaudio.size();
1662 FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
1663 ffaudio.append(aud);
1664 aud->channel0 = astrm_index.size();
1665 aud->channels = avctx->channels;
1666 for( int ch=0; ch<aud->channels; ++ch )
1667 astrm_index.append(ffidx(aidx, ch));
1668 aud->sample_rate = avctx->sample_rate;
1669 double secs = to_secs(st->duration, st->time_base);
1670 aud->length = secs * aud->sample_rate;
1671 if( avctx->sample_fmt != AV_SAMPLE_FMT_FLT ) {
1672 uint64_t layout = av_get_default_channel_layout(avctx->channels);
1673 if( !layout ) layout = ((uint64_t)1<<aud->channels) - 1;
1674 aud->resample_context = swr_alloc_set_opts(NULL,
1675 layout, AV_SAMPLE_FMT_FLT, avctx->sample_rate,
1676 layout, avctx->sample_fmt, avctx->sample_rate,
1678 swr_init(aud->resample_context);
1680 aud->nudge = st->start_time;
1682 if( opt_audio_filter )
1683 ret = aud->create_filter(opt_audio_filter, avctx,avctx);
1687 printf("FFMPEG::open_decoder: some stream have bad times\n");
1689 return ret < 0 ? -1 : 0;
1693 int FFMPEG::init_encoder(const char *filename)
1695 int fd = ::open(filename,O_WRONLY);
1696 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
1698 eprintf(_("bad file path: %s\n"), filename);
1702 int ret = get_file_format();
1704 eprintf(_("bad file format: %s\n"), filename);
1708 eprintf(_("mismatch audio/video file format: %s\n"), filename);
1711 ff_lock("FFMPEG::init_encoder");
1713 char format[BCSTRLEN];
1714 if( get_format(format, "format", file_format) )
1715 strcpy(format, file_format);
1716 avformat_alloc_output_context2(&fmt_ctx, 0, format, filename);
1718 eprintf(_("failed: %s\n"), filename);
1723 load_options("encode.opts", opts);
1729 int FFMPEG::open_encoder(const char *type, const char *spec)
1732 Asset *asset = file_base->asset;
1733 char *filename = asset->path;
1734 AVDictionary *sopts = 0;
1735 av_dict_copy(&sopts, opts, 0);
1736 char option_path[BCTEXTLEN];
1737 set_option_path(option_path, "%s/%s.opts", type, type);
1738 read_options(option_path, sopts);
1739 get_option_path(option_path, type, spec);
1740 char format_name[BCSTRLEN], codec_name[BCTEXTLEN];
1741 char bsfilter[BCSTRLEN], bsargs[BCTEXTLEN];
1742 if( get_encoder(option_path, format_name, codec_name, bsfilter, bsargs) ) {
1743 eprintf(_("get_encoder failed %s:%s\n"), option_path, filename);
1747 if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
1748 else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
1749 else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
1752 ff_lock("FFMPEG::open_encoder");
1756 const AVCodecDescriptor *codec_desc = 0;
1757 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
1759 eprintf(_("cant find codec %s:%s\n"), codec_name, filename);
1763 codec_desc = avcodec_descriptor_get(codec->id);
1765 eprintf(_("unknown codec %s:%s\n"), codec_name, filename);
1770 st = avformat_new_stream(fmt_ctx, 0);
1772 eprintf(_("cant create stream %s:%s\n"), codec_name, filename);
1777 AVCodecContext *ctx = st->codec;
1778 switch( codec_desc->type ) {
1779 case AVMEDIA_TYPE_AUDIO: {
1781 eprintf(_("duplicate audio %s:%s\n"), codec_name, filename);
1786 if( scan_options(asset->ff_audio_options, sopts, st) ) {
1787 eprintf(_("bad audio options %s:%s\n"), codec_name, filename);
1791 if( asset->ff_audio_bitrate > 0 ) {
1792 ctx->bit_rate = asset->ff_audio_bitrate;
1794 sprintf(arg, "%d", asset->ff_audio_bitrate);
1795 av_dict_set(&sopts, "b", arg, 0);
1797 int aidx = ffaudio.size();
1798 int fidx = aidx + ffvideo.size();
1799 FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
1800 ffaudio.append(aud); fst = aud;
1801 aud->sample_rate = asset->sample_rate;
1802 ctx->channels = aud->channels = asset->channels;
1803 for( int ch=0; ch<aud->channels; ++ch )
1804 astrm_index.append(ffidx(aidx, ch));
1805 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
1806 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
1807 if( !ctx->sample_rate ) {
1808 eprintf(_("check_sample_rate failed %s\n"), filename);
1812 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
1813 ctx->sample_fmt = codec->sample_fmts[0];
1814 uint64_t layout = av_get_default_channel_layout(ctx->channels);
1815 aud->resample_context = swr_alloc_set_opts(NULL,
1816 layout, ctx->sample_fmt, aud->sample_rate,
1817 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
1819 swr_init(aud->resample_context);
1822 case AVMEDIA_TYPE_VIDEO: {
1824 eprintf(_("duplicate video %s:%s\n"), codec_name, filename);
1829 if( scan_options(asset->ff_video_options, sopts, st) ) {
1830 eprintf(_("bad video options %s:%s\n"), codec_name, filename);
1834 if( asset->ff_video_bitrate > 0 ) {
1835 ctx->bit_rate = asset->ff_video_bitrate;
1837 sprintf(arg, "%d", asset->ff_video_bitrate);
1838 av_dict_set(&sopts, "b", arg, 0);
1840 else if( asset->ff_video_quality >= 0 ) {
1841 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
1842 ctx->qmin = ctx->qmax = asset->ff_video_quality;
1843 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
1844 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
1845 ctx->flags |= CODEC_FLAG_QSCALE;
1847 av_dict_set(&sopts, "flags", "+qscale", 0);
1848 sprintf(arg, "%d", asset->ff_video_quality);
1849 av_dict_set(&sopts, "qscale", arg, 0);
1850 sprintf(arg, "%d", ctx->global_quality);
1851 av_dict_set(&sopts, "global_quality", arg, 0);
1853 int vidx = ffvideo.size();
1854 int fidx = vidx + ffaudio.size();
1855 FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
1856 vstrm_index.append(ffidx(vidx, 0));
1857 ffvideo.append(vid); fst = vid;
1858 vid->width = asset->width;
1859 ctx->width = (vid->width+3) & ~3;
1860 vid->height = asset->height;
1861 ctx->height = (vid->height+3) & ~3;
1862 vid->frame_rate = asset->frame_rate;
1863 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
1864 ctx->pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
1865 AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
1866 if( !frame_rate.num || !frame_rate.den ) {
1867 eprintf(_("check_frame_rate failed %s\n"), filename);
1871 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
1872 st->time_base = ctx->time_base;
1874 vid->interlaced = asset->interlace_mode == ILACE_MODE_TOP_FIRST ||
1875 asset->interlace_mode == ILACE_MODE_BOTTOM_FIRST ? 1 : 0;
1876 vid->top_field_first = asset->interlace_mode == ILACE_MODE_TOP_FIRST ? 1 : 0;
1879 eprintf(_("not audio/video, %s:%s\n"), codec_name, filename);
1884 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
1885 st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
1887 av_dict_set(&sopts, "cin_bitrate", 0, 0);
1888 av_dict_set(&sopts, "cin_quality", 0, 0);
1890 ret = avcodec_open2(st->codec, codec, &sopts);
1892 ff_err(ret,"FFMPEG::open_encoder");
1893 eprintf(_("open failed %s:%s\n"), codec_name, filename);
1900 if( fst && bsfilter[0] )
1901 fst->add_bsfilter(bsfilter, !bsargs[0] ? 0 : bsargs);
1908 av_dict_free(&sopts);
1912 int FFMPEG::close_encoder()
1915 if( encoding > 0 ) {
1916 av_write_trailer(fmt_ctx);
1917 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
1918 avio_closep(&fmt_ctx->pb);
1924 int FFMPEG::decode_activate()
1926 if( decoding < 0 ) {
1928 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
1929 ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
1930 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
1931 ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
1932 // set nudges for each program stream set
1933 int npgrms = fmt_ctx->nb_programs;
1934 for( int i=0; i<npgrms; ++i ) {
1935 AVProgram *pgrm = fmt_ctx->programs[i];
1936 // first start time video stream
1937 int64_t vstart_time = -1, astart_time = -1;
1938 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1939 int fidx = pgrm->stream_index[j];
1940 AVStream *st = fmt_ctx->streams[fidx];
1941 AVCodecContext *avctx = st->codec;
1942 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1943 if( st->start_time == AV_NOPTS_VALUE ) continue;
1944 if( vstart_time > st->start_time ) continue;
1945 vstart_time = st->start_time;
1948 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1949 if( st->start_time == AV_NOPTS_VALUE ) continue;
1950 if( astart_time > st->start_time ) continue;
1951 astart_time = st->start_time;
1955 // match program streams to max start_time
1956 int64_t nudge = vstart_time > astart_time ? vstart_time : astart_time;
1957 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1958 int fidx = pgrm->stream_index[j];
1959 AVStream *st = fmt_ctx->streams[fidx];
1960 AVCodecContext *avctx = st->codec;
1961 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1962 for( int k=0; k<ffvideo.size(); ++k ) {
1963 if( ffvideo[k]->fidx != fidx ) continue;
1964 ffvideo[k]->nudge = nudge;
1968 if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1969 for( int k=0; k<ffaudio.size(); ++k ) {
1970 if( ffaudio[k]->fidx != fidx ) continue;
1971 ffaudio[k]->nudge = nudge;
1977 // set nudges for any streams not yet set
1978 int64_t vstart_time = 0, astart_time = 0;
1979 int nstreams = fmt_ctx->nb_streams;
1980 for( int i=0; i<nstreams; ++i ) {
1981 AVStream *st = fmt_ctx->streams[i];
1982 AVCodecContext *avctx = st->codec;
1983 switch( avctx->codec_type ) {
1984 case AVMEDIA_TYPE_VIDEO: {
1985 if( st->start_time == AV_NOPTS_VALUE ) continue;
1986 int vidx = ffvideo.size();
1987 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
1988 if( vidx >= 0 && ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
1989 if( vstart_time >= st->start_time ) continue;
1990 vstart_time = st->start_time;
1992 case AVMEDIA_TYPE_AUDIO: {
1993 if( st->start_time == AV_NOPTS_VALUE ) continue;
1994 int aidx = ffaudio.size();
1995 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
1996 if( aidx >= 0 && ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
1997 if( astart_time >= st->start_time ) continue;
1998 astart_time = st->start_time;
2003 int64_t nudge = vstart_time > astart_time ? vstart_time : astart_time;
2004 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
2005 if( ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
2006 ffvideo[vidx]->nudge = nudge;
2008 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2009 if( ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
2010 ffaudio[aidx]->nudge = nudge;
2017 int FFMPEG::encode_activate()
2020 if( encoding < 0 ) {
2022 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
2023 (ret=avio_open(&fmt_ctx->pb, fmt_ctx->filename, AVIO_FLAG_WRITE)) < 0 ) {
2024 ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
2030 AVProgram *prog = av_new_program(fmt_ctx, prog_id);
2031 for( int i=0; i< ffvideo.size(); ++i )
2032 av_program_add_stream_index(fmt_ctx, prog_id, ffvideo[i]->fidx);
2033 for( int i=0; i< ffaudio.size(); ++i )
2034 av_program_add_stream_index(fmt_ctx, prog_id, ffaudio[i]->fidx);
2035 int pi = fmt_ctx->nb_programs;
2036 while( --pi >= 0 && fmt_ctx->programs[pi]->id != prog_id );
2037 AVDictionary **meta = &prog->metadata;
2038 av_dict_set(meta, "service_provider", "cin5", 0);
2039 const char *path = fmt_ctx->filename, *bp = strrchr(path,'/');
2040 if( bp ) path = bp + 1;
2041 av_dict_set(meta, "title", path, 0);
2043 if( ffaudio.size() ) {
2044 const char *ep = getenv("CIN_AUDIO_LANG"), *lp = 0;
2045 if( !ep && (lp=getenv("LANG")) ) { // some are guesses
2046 static struct { const char lc[3], lng[4]; } lcode[] = {
2047 { "en", "eng" }, { "de", "ger" }, { "es", "spa" },
2048 { "eu", "bas" }, { "fr", "fre" }, { "el", "gre" },
2049 { "hi", "hin" }, { "it", "ita" }, { "ja", "jap" },
2050 { "ko", "kor" }, { "du", "dut" }, { "pl", "pol" },
2051 { "pt", "por" }, { "ru", "rus" }, { "sl", "slv" },
2052 { "uk", "ukr" }, { "vi", "vie" }, { "zh", "chi" },
2054 for( int i=sizeof(lcode)/sizeof(lcode[0]); --i>=0 && !ep; )
2055 if( !strncmp(lcode[i].lc,lp,2) ) ep = lcode[i].lng;
2057 if( !ep ) ep = "und";
2059 strncpy(lang,ep,3); lang[3] = 0;
2060 AVStream *st = ffaudio[0]->st;
2061 av_dict_set(&st->metadata,"language",lang,0);
2064 AVDictionary *fopts = 0;
2065 char option_path[BCTEXTLEN];
2066 set_option_path(option_path, "format/%s", file_format);
2067 read_options(option_path, fopts, 1);
2068 ret = avformat_write_header(fmt_ctx, &fopts);
2070 ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
2074 av_dict_free(&fopts);
2081 int FFMPEG::audio_seek(int stream, int64_t pos)
2083 int aidx = astrm_index[stream].st_idx;
2084 FFAudioStream *aud = ffaudio[aidx];
2085 aud->audio_seek(pos);
2089 int FFMPEG::video_seek(int stream, int64_t pos)
2091 int vidx = vstrm_index[stream].st_idx;
2092 FFVideoStream *vid = ffvideo[vidx];
2093 vid->video_seek(pos);
2098 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
2100 if( !has_audio || chn >= astrm_index.size() ) return -1;
2101 int aidx = astrm_index[chn].st_idx;
2102 FFAudioStream *aud = ffaudio[aidx];
2103 if( aud->load(pos, len) < len ) return -1;
2104 int ch = astrm_index[chn].st_ch;
2105 int ret = aud->read(samples,len,ch);
2109 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
2111 if( !has_video || layer >= vstrm_index.size() ) return -1;
2112 int vidx = vstrm_index[layer].st_idx;
2113 FFVideoStream *vid = ffvideo[vidx];
2114 return vid->load(vframe, pos);
2118 int FFMPEG::encode(int stream, double **samples, int len)
2120 FFAudioStream *aud = ffaudio[stream];
2121 return aud->encode(samples, len);
2125 int FFMPEG::encode(int stream, VFrame *frame)
2127 FFVideoStream *vid = ffvideo[stream];
2128 return vid->encode(frame);
2131 void FFMPEG::start_muxer()
2139 void FFMPEG::stop_muxer()
2148 void FFMPEG::flow_off()
2151 flow_lock->lock("FFMPEG::flow_off");
2155 void FFMPEG::flow_on()
2159 flow_lock->unlock();
2162 void FFMPEG::flow_ctl()
2165 flow_lock->lock("FFMPEG::flow_ctl");
2166 flow_lock->unlock();
2170 int FFMPEG::mux_audio(FFrame *frm)
2173 FFStream *fst = frm->fst;
2174 AVCodecContext *ctx = fst->st->codec;
2175 AVFrame *frame = *frm;
2176 AVRational tick_rate = {1, ctx->sample_rate};
2177 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
2179 int ret = fst->encode_frame(pkt, frame, got_packet);
2180 if( ret >= 0 && got_packet )
2181 ret = fst->write_packet(pkt);
2183 ff_err(ret, "FFMPEG::mux_audio");
2184 return ret >= 0 ? 0 : 1;
2187 int FFMPEG::mux_video(FFrame *frm)
2190 FFStream *fst = frm->fst;
2191 AVFrame *frame = *frm;
2192 frame->pts = frm->position;
2194 int ret = fst->encode_frame(pkt, frame, got_packet);
2195 if( ret >= 0 && got_packet )
2196 ret = fst->write_packet(pkt);
2198 ff_err(ret, "FFMPEG::mux_video");
2199 return ret >= 0 ? 0 : 1;
2205 double atm = -1, vtm = -1;
2206 FFrame *afrm = 0, *vfrm = 0;
2208 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
2209 FFStream *fst = ffaudio[i];
2210 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
2211 FFrame *frm = fst->frms.first;
2212 if( !frm ) { if( !done ) return; continue; }
2213 double tm = to_secs(frm->position, fst->st->codec->time_base);
2214 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
2216 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
2217 FFStream *fst = ffvideo[i];
2218 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
2219 FFrame *frm = fst->frms.first;
2220 if( !frm ) { if( !done ) return; continue; }
2221 double tm = to_secs(frm->position, fst->st->codec->time_base);
2222 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
2224 if( !demand ) flow_off();
2225 if( !afrm && !vfrm ) break;
2226 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
2227 vfrm->position, vfrm->fst->st->codec->time_base,
2228 afrm->position, afrm->fst->st->codec->time_base);
2229 FFrame *frm = v <= 0 ? vfrm : afrm;
2230 if( frm == afrm ) mux_audio(frm);
2231 if( frm == vfrm ) mux_video(frm);
2240 mux_lock->lock("FFMPEG::run");
2244 for( int i=0; i<ffaudio.size(); ++i )
2245 ffaudio[i]->flush();
2246 for( int i=0; i<ffvideo.size(); ++i )
2247 ffvideo[i]->flush();
2251 int FFMPEG::ff_total_audio_channels()
2253 return astrm_index.size();
2256 int FFMPEG::ff_total_astreams()
2258 return ffaudio.size();
2261 int FFMPEG::ff_audio_channels(int stream)
2263 return ffaudio[stream]->channels;
2266 int FFMPEG::ff_sample_rate(int stream)
2268 return ffaudio[stream]->sample_rate;
2271 const char* FFMPEG::ff_audio_format(int stream)
2273 AVStream *st = ffaudio[stream]->st;
2274 AVCodecID id = st->codec->codec_id;
2275 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2276 return desc ? desc->name : _("Unknown");
2279 int FFMPEG::ff_audio_pid(int stream)
2281 return ffaudio[stream]->st->id;
2284 int64_t FFMPEG::ff_audio_samples(int stream)
2286 return ffaudio[stream]->length;
2289 // find audio astream/channels with this program,
2290 // or all program audio channels (astream=-1)
2291 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
2295 int vidx = ffvideo[vstream]->fidx;
2296 // find first program with this video stream
2297 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
2298 AVProgram *pgrm = fmt_ctx->programs[i];
2299 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
2300 int st_idx = pgrm->stream_index[j];
2301 AVStream *st = fmt_ctx->streams[st_idx];
2302 if( st->codec->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
2303 if( st_idx == vidx ) pidx = i;
2306 if( pidx < 0 ) return -1;
2308 int64_t channels = 0;
2309 AVProgram *pgrm = fmt_ctx->programs[pidx];
2310 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2311 int aidx = pgrm->stream_index[j];
2312 AVStream *st = fmt_ctx->streams[aidx];
2313 if( st->codec->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
2314 if( astream > 0 ) { --astream; continue; }
2316 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
2317 if( ffaudio[i]->fidx == aidx ) astrm = i;
2319 if( ret < 0 ) ret = astrm;
2320 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
2321 channels |= mask << ffaudio[astrm]->channel0;
2323 if( !astream ) break;
2325 channel_mask = channels;
2330 int FFMPEG::ff_total_video_layers()
2332 return vstrm_index.size();
2335 int FFMPEG::ff_total_vstreams()
2337 return ffvideo.size();
2340 int FFMPEG::ff_video_width(int stream)
2342 return ffvideo[stream]->width;
2345 int FFMPEG::ff_video_height(int stream)
2347 return ffvideo[stream]->height;
2350 int FFMPEG::ff_set_video_width(int stream, int width)
2352 int w = ffvideo[stream]->width;
2353 ffvideo[stream]->width = width;
2357 int FFMPEG::ff_set_video_height(int stream, int height)
2359 int h = ffvideo[stream]->height;
2360 ffvideo[stream]->height = height;
2364 int FFMPEG::ff_coded_width(int stream)
2366 AVStream *st = ffvideo[stream]->st;
2367 return st->codec->coded_width;
2370 int FFMPEG::ff_coded_height(int stream)
2372 AVStream *st = ffvideo[stream]->st;
2373 return st->codec->coded_height;
2376 float FFMPEG::ff_aspect_ratio(int stream)
2378 return ffvideo[stream]->aspect_ratio;
2381 const char* FFMPEG::ff_video_format(int stream)
2383 AVStream *st = ffvideo[stream]->st;
2384 AVCodecID id = st->codec->codec_id;
2385 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2386 return desc ? desc->name : _("Unknown");
2389 double FFMPEG::ff_frame_rate(int stream)
2391 return ffvideo[stream]->frame_rate;
2394 int64_t FFMPEG::ff_video_frames(int stream)
2396 return ffvideo[stream]->length;
2399 int FFMPEG::ff_video_pid(int stream)
2401 return ffvideo[stream]->st->id;
2405 int FFMPEG::ff_cpus()
2407 return file_base->file->cpus;
2410 int FFVideoStream::create_filter(const char *filter_spec,
2411 AVCodecContext *src_ctx, AVCodecContext *sink_ctx)
2413 avfilter_register_all();
2414 const char *sp = filter_spec;
2415 char filter_name[BCSTRLEN], *np = filter_name;
2416 int i = sizeof(filter_name);
2417 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
2419 AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
2420 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_VIDEO ) {
2421 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
2424 filter_graph = avfilter_graph_alloc();
2425 AVFilter *buffersrc = avfilter_get_by_name("buffer");
2426 AVFilter *buffersink = avfilter_get_by_name("buffersink");
2428 int ret = 0; char args[BCTEXTLEN];
2429 snprintf(args, sizeof(args),
2430 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
2431 src_ctx->width, src_ctx->height, src_ctx->pix_fmt,
2432 src_ctx->time_base.num, src_ctx->time_base.den,
2433 src_ctx->sample_aspect_ratio.num, src_ctx->sample_aspect_ratio.den);
2435 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2436 args, NULL, filter_graph);
2438 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2439 NULL, NULL, filter_graph);
2441 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
2442 (uint8_t*)&sink_ctx->pix_fmt, sizeof(sink_ctx->pix_fmt),
2443 AV_OPT_SEARCH_CHILDREN);
2445 ff_err(ret, "FFVideoStream::create_filter");
2447 ret = FFStream::create_filter(filter_spec);
2448 return ret >= 0 ? 0 : -1;
2451 int FFAudioStream::create_filter(const char *filter_spec,
2452 AVCodecContext *src_ctx, AVCodecContext *sink_ctx)
2454 avfilter_register_all();
2455 const char *sp = filter_spec;
2456 char filter_name[BCSTRLEN], *np = filter_name;
2457 int i = sizeof(filter_name);
2458 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
2460 AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
2461 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_AUDIO ) {
2462 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
2465 filter_graph = avfilter_graph_alloc();
2466 AVFilter *buffersrc = avfilter_get_by_name("abuffer");
2467 AVFilter *buffersink = avfilter_get_by_name("abuffersink");
2468 int ret = 0; char args[BCTEXTLEN];
2469 snprintf(args, sizeof(args),
2470 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
2471 src_ctx->time_base.num, src_ctx->time_base.den, src_ctx->sample_rate,
2472 av_get_sample_fmt_name(src_ctx->sample_fmt), src_ctx->channel_layout);
2474 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2475 args, NULL, filter_graph);
2477 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2478 NULL, NULL, filter_graph);
2480 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
2481 (uint8_t*)&sink_ctx->sample_fmt, sizeof(sink_ctx->sample_fmt),
2482 AV_OPT_SEARCH_CHILDREN);
2484 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
2485 (uint8_t*)&sink_ctx->channel_layout,
2486 sizeof(sink_ctx->channel_layout), AV_OPT_SEARCH_CHILDREN);
2488 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
2489 (uint8_t*)&sink_ctx->sample_rate, sizeof(sink_ctx->sample_rate),
2490 AV_OPT_SEARCH_CHILDREN);
2492 ff_err(ret, "FFAudioStream::create_filter");
2494 ret = FFStream::create_filter(filter_spec);
2495 return ret >= 0 ? 0 : -1;
2498 int FFStream::create_filter(const char *filter_spec)
2500 /* Endpoints for the filter graph. */
2501 AVFilterInOut *outputs = avfilter_inout_alloc();
2502 outputs->name = av_strdup("in");
2503 outputs->filter_ctx = buffersrc_ctx;
2504 outputs->pad_idx = 0;
2507 AVFilterInOut *inputs = avfilter_inout_alloc();
2508 inputs->name = av_strdup("out");
2509 inputs->filter_ctx = buffersink_ctx;
2510 inputs->pad_idx = 0;
2513 int ret = !outputs->name || !inputs->name ? -1 : 0;
2515 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
2516 &inputs, &outputs, NULL);
2518 ret = avfilter_graph_config(filter_graph, NULL);
2521 ff_err(ret, "FFStream::create_filter");
2522 avfilter_graph_free(&filter_graph);
2525 avfilter_inout_free(&inputs);
2526 avfilter_inout_free(&outputs);
2530 void FFStream::add_bsfilter(const char *bsf, const char *ap)
2532 bsfilter.append(new BSFilter(bsf,ap));
2535 int FFStream::bs_filter(AVPacket *pkt)
2537 if( !bsfilter.size() ) return 0;
2538 av_packet_split_side_data(pkt);
2541 for( int i=0; i<bsfilter.size(); ++i ) {
2542 AVPacket bspkt = *pkt;
2543 ret = av_bitstream_filter_filter(bsfilter[i]->bsfc,
2544 st->codec, bsfilter[i]->args, &bspkt.data, &bspkt.size,
2545 pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY);
2546 if( ret < 0 ) break;
2547 int size = bspkt.size;
2548 uint8_t *data = bspkt.data;
2549 if( !ret && bspkt.data != pkt->data ) {
2551 data = (uint8_t *)av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
2552 if( !data ) { ret = AVERROR(ENOMEM); break; }
2553 memcpy(data, bspkt.data, size);
2554 memset(data+size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2558 pkt->side_data = 0; pkt->side_data_elems = 0;
2559 av_packet_unref(pkt);
2560 ret = av_packet_from_data(&bspkt, data, size);
2561 if( ret < 0 ) break;
2566 ff_err(ret,"FFStream::bs_filter");
2570 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
2573 av_init_packet(&pkt);
2574 AVFrame *frame = av_frame_alloc();
2576 fprintf(stderr,"FFMPEG::scan: ");
2577 fprintf(stderr,_("av_frame_alloc failed\n"));
2581 index_state->add_video_markers(ffvideo.size());
2582 index_state->add_audio_markers(ffaudio.size());
2584 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2585 AVDictionary *copts = 0;
2586 av_dict_copy(&copts, opts, 0);
2587 AVStream *st = fmt_ctx->streams[i];
2588 AVCodecID codec_id = st->codec->codec_id;
2589 AVCodec *decoder = avcodec_find_decoder(codec_id);
2590 if( avcodec_open2(st->codec, decoder, &copts) < 0 ) {
2591 fprintf(stderr,"FFMPEG::scan: ");
2592 fprintf(stderr,_("codec open failed\n"));
2594 av_dict_free(&copts);
2597 for( int64_t count=0; !*canceled; ++count ) {
2598 av_packet_unref(&pkt);
2599 pkt.data = 0; pkt.size = 0;
2601 int ret = av_read_frame(fmt_ctx, &pkt);
2603 if( ret == AVERROR_EOF ) break;
2604 if( ++errs > 100 ) {
2605 ff_err(ret,_("over 100 read_frame errs\n"));
2610 if( !pkt.data ) continue;
2611 int i = pkt.stream_index;
2612 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
2613 AVStream *st = fmt_ctx->streams[i];
2614 AVCodecContext *avctx = st->codec;
2615 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
2617 switch( avctx->codec_type ) {
2618 case AVMEDIA_TYPE_VIDEO: {
2619 int vidx = ffvideo.size();
2620 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
2621 if( vidx < 0 ) break;
2622 FFVideoStream *vid = ffvideo[vidx];
2623 int64_t tstmp = pkt.dts;
2624 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.pts;
2625 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
2626 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
2627 double secs = to_secs(tstmp, st->time_base);
2628 int64_t frm = secs * vid->frame_rate + 0.5;
2629 if( frm < 0 ) frm = 0;
2630 index_state->put_video_mark(vidx, frm, pkt.pos);
2633 while( pkt.size > 0 ) {
2634 av_frame_unref(frame);
2636 int ret = vid->decode_frame(&pkt, frame, got_frame);
2637 if( ret <= 0 ) break;
2638 // if( got_frame ) {}
2644 case AVMEDIA_TYPE_AUDIO: {
2645 int aidx = ffaudio.size();
2646 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
2647 if( aidx < 0 ) break;
2648 FFAudioStream *aud = ffaudio[aidx];
2649 int64_t tstmp = pkt.pts;
2650 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
2651 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
2652 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
2653 double secs = to_secs(tstmp, st->time_base);
2654 int64_t sample = secs * aud->sample_rate + 0.5;
2655 if( sample < 0 ) sample = 0;
2656 index_state->put_audio_mark(aidx, sample, pkt.pos);
2658 while( pkt.size > 0 ) {
2659 int ch = aud->channel0, nch = aud->channels;
2660 int64_t pos = index_state->pos(ch);
2661 if( pos != aud->curr_pos ) {
2662 if( abs(pos-aud->curr_pos) > 1 )
2663 printf("audio%d pad %jd %jd (%jd)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
2664 index_state->pad_data(ch, nch, aud->curr_pos);
2666 av_frame_unref(frame);
2668 int ret = aud->decode_frame(&pkt, frame, got_frame);
2669 if( ret <= 0 ) break;
2670 if( got_frame && frame->channels == nch ) {
2672 int len = aud->get_samples(samples,
2673 &frame->extended_data[0], frame->nb_samples);
2674 for( int i=0; i<nch; ++i )
2675 index_state->put_data(ch+i,nch,samples+i,len);
2676 aud->curr_pos += len;
2685 av_frame_free(&frame);
2689 void FFStream::load_markers(IndexMarks &marks, double rate)
2692 int64_t sz = marks.size();
2693 int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
2694 int nb_ent = st->nb_index_entries;
2695 // some formats already have an index
2697 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
2698 int64_t tstmp = ep->timestamp;
2699 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
2700 double secs = ffmpeg->to_secs(tstmp, st->time_base);
2701 int64_t no = secs * rate;
2702 while( in < sz && marks[in].no <= no ) ++in;
2704 int64_t len = sz - in;
2705 int64_t count = max_entries - nb_ent;
2706 if( count > len ) count = len;
2707 for( int i=0; i<count; ++i ) {
2708 int k = in + i * len / count;
2709 int64_t no = marks[k].no, pos = marks[k].pos;
2710 double secs = (double)no / rate;
2711 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
2712 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
2713 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);