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 ret = avcodec_open2(st->codec, codec, &sopts);
1889 ff_err(ret,"FFMPEG::open_encoder");
1890 eprintf(_("open failed %s:%s\n"), codec_name, filename);
1897 if( fst && bsfilter[0] )
1898 fst->add_bsfilter(bsfilter, !bsargs[0] ? 0 : bsargs);
1905 av_dict_free(&sopts);
1909 int FFMPEG::close_encoder()
1912 if( encoding > 0 ) {
1913 av_write_trailer(fmt_ctx);
1914 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
1915 avio_closep(&fmt_ctx->pb);
1921 int FFMPEG::decode_activate()
1923 if( decoding < 0 ) {
1925 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
1926 ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
1927 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
1928 ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
1929 // set nudges for each program stream set
1930 int npgrms = fmt_ctx->nb_programs;
1931 for( int i=0; i<npgrms; ++i ) {
1932 AVProgram *pgrm = fmt_ctx->programs[i];
1933 // first start time video stream
1934 int64_t vstart_time = -1, astart_time = -1;
1935 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1936 int fidx = pgrm->stream_index[j];
1937 AVStream *st = fmt_ctx->streams[fidx];
1938 AVCodecContext *avctx = st->codec;
1939 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1940 if( st->start_time == AV_NOPTS_VALUE ) continue;
1941 if( vstart_time > st->start_time ) continue;
1942 vstart_time = st->start_time;
1945 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1946 if( st->start_time == AV_NOPTS_VALUE ) continue;
1947 if( astart_time > st->start_time ) continue;
1948 astart_time = st->start_time;
1952 // match program streams to max start_time
1953 int64_t nudge = vstart_time > astart_time ? vstart_time : astart_time;
1954 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1955 int fidx = pgrm->stream_index[j];
1956 AVStream *st = fmt_ctx->streams[fidx];
1957 AVCodecContext *avctx = st->codec;
1958 if( avctx->codec_type == AVMEDIA_TYPE_VIDEO ) {
1959 for( int k=0; k<ffvideo.size(); ++k ) {
1960 if( ffvideo[k]->fidx != fidx ) continue;
1961 ffvideo[k]->nudge = nudge;
1965 if( avctx->codec_type == AVMEDIA_TYPE_AUDIO ) {
1966 for( int k=0; k<ffaudio.size(); ++k ) {
1967 if( ffaudio[k]->fidx != fidx ) continue;
1968 ffaudio[k]->nudge = nudge;
1974 // set nudges for any streams not yet set
1975 int64_t vstart_time = 0, astart_time = 0;
1976 int nstreams = fmt_ctx->nb_streams;
1977 for( int i=0; i<nstreams; ++i ) {
1978 AVStream *st = fmt_ctx->streams[i];
1979 AVCodecContext *avctx = st->codec;
1980 switch( avctx->codec_type ) {
1981 case AVMEDIA_TYPE_VIDEO: {
1982 if( st->start_time == AV_NOPTS_VALUE ) continue;
1983 int vidx = ffvideo.size();
1984 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
1985 if( vidx >= 0 && ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
1986 if( vstart_time >= st->start_time ) continue;
1987 vstart_time = st->start_time;
1989 case AVMEDIA_TYPE_AUDIO: {
1990 if( st->start_time == AV_NOPTS_VALUE ) continue;
1991 int aidx = ffaudio.size();
1992 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
1993 if( aidx >= 0 && ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
1994 if( astart_time >= st->start_time ) continue;
1995 astart_time = st->start_time;
2000 int64_t nudge = vstart_time > astart_time ? vstart_time : astart_time;
2001 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
2002 if( ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
2003 ffvideo[vidx]->nudge = nudge;
2005 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2006 if( ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
2007 ffaudio[aidx]->nudge = nudge;
2014 int FFMPEG::encode_activate()
2017 if( encoding < 0 ) {
2019 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
2020 (ret=avio_open(&fmt_ctx->pb, fmt_ctx->filename, AVIO_FLAG_WRITE)) < 0 ) {
2021 ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
2027 AVProgram *prog = av_new_program(fmt_ctx, prog_id);
2028 for( int i=0; i< ffvideo.size(); ++i )
2029 av_program_add_stream_index(fmt_ctx, prog_id, ffvideo[i]->fidx);
2030 for( int i=0; i< ffaudio.size(); ++i )
2031 av_program_add_stream_index(fmt_ctx, prog_id, ffaudio[i]->fidx);
2032 int pi = fmt_ctx->nb_programs;
2033 while( --pi >= 0 && fmt_ctx->programs[pi]->id != prog_id );
2034 AVDictionary **meta = &prog->metadata;
2035 av_dict_set(meta, "service_provider", "cin5", 0);
2036 const char *path = fmt_ctx->filename, *bp = strrchr(path,'/');
2037 if( bp ) path = bp + 1;
2038 av_dict_set(meta, "title", path, 0);
2040 if( ffaudio.size() ) {
2041 const char *ep = getenv("CIN_AUDIO_LANG"), *lp = 0;
2042 if( !ep && (lp=getenv("LANG")) ) { // some are guesses
2043 static struct { const char lc[3], lng[4]; } lcode[] = {
2044 { "en", "eng" }, { "de", "ger" }, { "es", "spa" },
2045 { "eu", "bas" }, { "fr", "fre" }, { "el", "gre" },
2046 { "hi", "hin" }, { "it", "ita" }, { "ja", "jap" },
2047 { "ko", "kor" }, { "du", "dut" }, { "pl", "pol" },
2048 { "pt", "por" }, { "ru", "rus" }, { "sl", "slv" },
2049 { "uk", "ukr" }, { "vi", "vie" }, { "zh", "chi" },
2051 for( int i=sizeof(lcode)/sizeof(lcode[0]); --i>=0 && !ep; )
2052 if( !strncmp(lcode[i].lc,lp,2) ) ep = lcode[i].lng;
2055 strncpy(lang,ep,3); lang[3] = 0;
2056 AVStream *st = ffaudio[0]->st;
2057 av_dict_set(&st->metadata,"language",lang,0);
2060 AVDictionary *fopts = 0;
2061 char option_path[BCTEXTLEN];
2062 set_option_path(option_path, "format/%s", file_format);
2063 read_options(option_path, fopts, 1);
2064 ret = avformat_write_header(fmt_ctx, &fopts);
2066 ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
2070 av_dict_free(&fopts);
2077 int FFMPEG::audio_seek(int stream, int64_t pos)
2079 int aidx = astrm_index[stream].st_idx;
2080 FFAudioStream *aud = ffaudio[aidx];
2081 aud->audio_seek(pos);
2085 int FFMPEG::video_seek(int stream, int64_t pos)
2087 int vidx = vstrm_index[stream].st_idx;
2088 FFVideoStream *vid = ffvideo[vidx];
2089 vid->video_seek(pos);
2094 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
2096 if( !has_audio || chn >= astrm_index.size() ) return -1;
2097 int aidx = astrm_index[chn].st_idx;
2098 FFAudioStream *aud = ffaudio[aidx];
2099 if( aud->load(pos, len) < len ) return -1;
2100 int ch = astrm_index[chn].st_ch;
2101 int ret = aud->read(samples,len,ch);
2105 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
2107 if( !has_video || layer >= vstrm_index.size() ) return -1;
2108 int vidx = vstrm_index[layer].st_idx;
2109 FFVideoStream *vid = ffvideo[vidx];
2110 return vid->load(vframe, pos);
2114 int FFMPEG::encode(int stream, double **samples, int len)
2116 FFAudioStream *aud = ffaudio[stream];
2117 return aud->encode(samples, len);
2121 int FFMPEG::encode(int stream, VFrame *frame)
2123 FFVideoStream *vid = ffvideo[stream];
2124 return vid->encode(frame);
2127 void FFMPEG::start_muxer()
2135 void FFMPEG::stop_muxer()
2144 void FFMPEG::flow_off()
2147 flow_lock->lock("FFMPEG::flow_off");
2151 void FFMPEG::flow_on()
2155 flow_lock->unlock();
2158 void FFMPEG::flow_ctl()
2161 flow_lock->lock("FFMPEG::flow_ctl");
2162 flow_lock->unlock();
2166 int FFMPEG::mux_audio(FFrame *frm)
2169 FFStream *fst = frm->fst;
2170 AVCodecContext *ctx = fst->st->codec;
2171 AVFrame *frame = *frm;
2172 AVRational tick_rate = {1, ctx->sample_rate};
2173 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
2175 int ret = fst->encode_frame(pkt, frame, got_packet);
2176 if( ret >= 0 && got_packet )
2177 ret = fst->write_packet(pkt);
2179 ff_err(ret, "FFMPEG::mux_audio");
2180 return ret >= 0 ? 0 : 1;
2183 int FFMPEG::mux_video(FFrame *frm)
2186 FFStream *fst = frm->fst;
2187 AVFrame *frame = *frm;
2188 frame->pts = frm->position;
2190 int ret = fst->encode_frame(pkt, frame, got_packet);
2191 if( ret >= 0 && got_packet )
2192 ret = fst->write_packet(pkt);
2194 ff_err(ret, "FFMPEG::mux_video");
2195 return ret >= 0 ? 0 : 1;
2201 double atm = -1, vtm = -1;
2202 FFrame *afrm = 0, *vfrm = 0;
2204 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
2205 FFStream *fst = ffaudio[i];
2206 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
2207 FFrame *frm = fst->frms.first;
2208 if( !frm ) { if( !done ) return; continue; }
2209 double tm = to_secs(frm->position, fst->st->codec->time_base);
2210 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
2212 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
2213 FFStream *fst = ffvideo[i];
2214 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
2215 FFrame *frm = fst->frms.first;
2216 if( !frm ) { if( !done ) return; continue; }
2217 double tm = to_secs(frm->position, fst->st->codec->time_base);
2218 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
2220 if( !demand ) flow_off();
2221 if( !afrm && !vfrm ) break;
2222 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
2223 vfrm->position, vfrm->fst->st->codec->time_base,
2224 afrm->position, afrm->fst->st->codec->time_base);
2225 FFrame *frm = v <= 0 ? vfrm : afrm;
2226 if( frm == afrm ) mux_audio(frm);
2227 if( frm == vfrm ) mux_video(frm);
2236 mux_lock->lock("FFMPEG::run");
2240 for( int i=0; i<ffaudio.size(); ++i )
2241 ffaudio[i]->flush();
2242 for( int i=0; i<ffvideo.size(); ++i )
2243 ffvideo[i]->flush();
2247 int FFMPEG::ff_total_audio_channels()
2249 return astrm_index.size();
2252 int FFMPEG::ff_total_astreams()
2254 return ffaudio.size();
2257 int FFMPEG::ff_audio_channels(int stream)
2259 return ffaudio[stream]->channels;
2262 int FFMPEG::ff_sample_rate(int stream)
2264 return ffaudio[stream]->sample_rate;
2267 const char* FFMPEG::ff_audio_format(int stream)
2269 AVStream *st = ffaudio[stream]->st;
2270 AVCodecID id = st->codec->codec_id;
2271 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2272 return desc ? desc->name : _("Unknown");
2275 int FFMPEG::ff_audio_pid(int stream)
2277 return ffaudio[stream]->st->id;
2280 int64_t FFMPEG::ff_audio_samples(int stream)
2282 return ffaudio[stream]->length;
2285 // find audio astream/channels with this program,
2286 // or all program audio channels (astream=-1)
2287 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
2291 int vidx = ffvideo[vstream]->fidx;
2292 // find first program with this video stream
2293 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
2294 AVProgram *pgrm = fmt_ctx->programs[i];
2295 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
2296 int st_idx = pgrm->stream_index[j];
2297 AVStream *st = fmt_ctx->streams[st_idx];
2298 if( st->codec->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
2299 if( st_idx == vidx ) pidx = i;
2302 if( pidx < 0 ) return -1;
2304 int64_t channels = 0;
2305 AVProgram *pgrm = fmt_ctx->programs[pidx];
2306 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2307 int aidx = pgrm->stream_index[j];
2308 AVStream *st = fmt_ctx->streams[aidx];
2309 if( st->codec->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
2310 if( astream > 0 ) { --astream; continue; }
2312 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
2313 if( ffaudio[i]->fidx == aidx ) astrm = i;
2315 if( ret < 0 ) ret = astrm;
2316 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
2317 channels |= mask << ffaudio[astrm]->channel0;
2319 if( !astream ) break;
2321 channel_mask = channels;
2326 int FFMPEG::ff_total_video_layers()
2328 return vstrm_index.size();
2331 int FFMPEG::ff_total_vstreams()
2333 return ffvideo.size();
2336 int FFMPEG::ff_video_width(int stream)
2338 return ffvideo[stream]->width;
2341 int FFMPEG::ff_video_height(int stream)
2343 return ffvideo[stream]->height;
2346 int FFMPEG::ff_set_video_width(int stream, int width)
2348 int w = ffvideo[stream]->width;
2349 ffvideo[stream]->width = width;
2353 int FFMPEG::ff_set_video_height(int stream, int height)
2355 int h = ffvideo[stream]->height;
2356 ffvideo[stream]->height = height;
2360 int FFMPEG::ff_coded_width(int stream)
2362 AVStream *st = ffvideo[stream]->st;
2363 return st->codec->coded_width;
2366 int FFMPEG::ff_coded_height(int stream)
2368 AVStream *st = ffvideo[stream]->st;
2369 return st->codec->coded_height;
2372 float FFMPEG::ff_aspect_ratio(int stream)
2374 return ffvideo[stream]->aspect_ratio;
2377 const char* FFMPEG::ff_video_format(int stream)
2379 AVStream *st = ffvideo[stream]->st;
2380 AVCodecID id = st->codec->codec_id;
2381 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2382 return desc ? desc->name : _("Unknown");
2385 double FFMPEG::ff_frame_rate(int stream)
2387 return ffvideo[stream]->frame_rate;
2390 int64_t FFMPEG::ff_video_frames(int stream)
2392 return ffvideo[stream]->length;
2395 int FFMPEG::ff_video_pid(int stream)
2397 return ffvideo[stream]->st->id;
2401 int FFMPEG::ff_cpus()
2403 return file_base->file->cpus;
2406 int FFVideoStream::create_filter(const char *filter_spec,
2407 AVCodecContext *src_ctx, AVCodecContext *sink_ctx)
2409 avfilter_register_all();
2410 const char *sp = filter_spec;
2411 char filter_name[BCSTRLEN], *np = filter_name;
2412 int i = sizeof(filter_name);
2413 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
2415 AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
2416 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_VIDEO ) {
2417 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
2420 filter_graph = avfilter_graph_alloc();
2421 AVFilter *buffersrc = avfilter_get_by_name("buffer");
2422 AVFilter *buffersink = avfilter_get_by_name("buffersink");
2424 int ret = 0; char args[BCTEXTLEN];
2425 snprintf(args, sizeof(args),
2426 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
2427 src_ctx->width, src_ctx->height, src_ctx->pix_fmt,
2428 src_ctx->time_base.num, src_ctx->time_base.den,
2429 src_ctx->sample_aspect_ratio.num, src_ctx->sample_aspect_ratio.den);
2431 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2432 args, NULL, filter_graph);
2434 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2435 NULL, NULL, filter_graph);
2437 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
2438 (uint8_t*)&sink_ctx->pix_fmt, sizeof(sink_ctx->pix_fmt),
2439 AV_OPT_SEARCH_CHILDREN);
2441 ff_err(ret, "FFVideoStream::create_filter");
2443 ret = FFStream::create_filter(filter_spec);
2444 return ret >= 0 ? 0 : -1;
2447 int FFAudioStream::create_filter(const char *filter_spec,
2448 AVCodecContext *src_ctx, AVCodecContext *sink_ctx)
2450 avfilter_register_all();
2451 const char *sp = filter_spec;
2452 char filter_name[BCSTRLEN], *np = filter_name;
2453 int i = sizeof(filter_name);
2454 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
2456 AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
2457 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_AUDIO ) {
2458 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
2461 filter_graph = avfilter_graph_alloc();
2462 AVFilter *buffersrc = avfilter_get_by_name("abuffer");
2463 AVFilter *buffersink = avfilter_get_by_name("abuffersink");
2464 int ret = 0; char args[BCTEXTLEN];
2465 snprintf(args, sizeof(args),
2466 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
2467 src_ctx->time_base.num, src_ctx->time_base.den, src_ctx->sample_rate,
2468 av_get_sample_fmt_name(src_ctx->sample_fmt), src_ctx->channel_layout);
2470 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2471 args, NULL, filter_graph);
2473 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2474 NULL, NULL, filter_graph);
2476 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
2477 (uint8_t*)&sink_ctx->sample_fmt, sizeof(sink_ctx->sample_fmt),
2478 AV_OPT_SEARCH_CHILDREN);
2480 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
2481 (uint8_t*)&sink_ctx->channel_layout,
2482 sizeof(sink_ctx->channel_layout), AV_OPT_SEARCH_CHILDREN);
2484 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
2485 (uint8_t*)&sink_ctx->sample_rate, sizeof(sink_ctx->sample_rate),
2486 AV_OPT_SEARCH_CHILDREN);
2488 ff_err(ret, "FFAudioStream::create_filter");
2490 ret = FFStream::create_filter(filter_spec);
2491 return ret >= 0 ? 0 : -1;
2494 int FFStream::create_filter(const char *filter_spec)
2496 /* Endpoints for the filter graph. */
2497 AVFilterInOut *outputs = avfilter_inout_alloc();
2498 outputs->name = av_strdup("in");
2499 outputs->filter_ctx = buffersrc_ctx;
2500 outputs->pad_idx = 0;
2503 AVFilterInOut *inputs = avfilter_inout_alloc();
2504 inputs->name = av_strdup("out");
2505 inputs->filter_ctx = buffersink_ctx;
2506 inputs->pad_idx = 0;
2509 int ret = !outputs->name || !inputs->name ? -1 : 0;
2511 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
2512 &inputs, &outputs, NULL);
2514 ret = avfilter_graph_config(filter_graph, NULL);
2517 ff_err(ret, "FFStream::create_filter");
2518 avfilter_graph_free(&filter_graph);
2521 avfilter_inout_free(&inputs);
2522 avfilter_inout_free(&outputs);
2526 void FFStream::add_bsfilter(const char *bsf, const char *ap)
2528 bsfilter.append(new BSFilter(bsf,ap));
2531 int FFStream::bs_filter(AVPacket *pkt)
2533 if( !bsfilter.size() ) return 0;
2534 av_packet_split_side_data(pkt);
2537 for( int i=0; i<bsfilter.size(); ++i ) {
2538 AVPacket bspkt = *pkt;
2539 ret = av_bitstream_filter_filter(bsfilter[i]->bsfc,
2540 st->codec, bsfilter[i]->args, &bspkt.data, &bspkt.size,
2541 pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY);
2542 if( ret < 0 ) break;
2543 int size = bspkt.size;
2544 uint8_t *data = bspkt.data;
2545 if( !ret && bspkt.data != pkt->data ) {
2547 data = (uint8_t *)av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
2548 if( !data ) { ret = AVERROR(ENOMEM); break; }
2549 memcpy(data, bspkt.data, size);
2550 memset(data+size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2554 pkt->side_data = 0; pkt->side_data_elems = 0;
2555 av_packet_unref(pkt);
2556 ret = av_packet_from_data(&bspkt, data, size);
2557 if( ret < 0 ) break;
2562 ff_err(ret,"FFStream::bs_filter");
2566 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
2569 av_init_packet(&pkt);
2570 AVFrame *frame = av_frame_alloc();
2572 fprintf(stderr,"FFMPEG::scan: ");
2573 fprintf(stderr,_("av_frame_alloc failed\n"));
2577 index_state->add_video_markers(ffvideo.size());
2578 index_state->add_audio_markers(ffaudio.size());
2580 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2581 AVDictionary *copts = 0;
2582 av_dict_copy(&copts, opts, 0);
2583 AVStream *st = fmt_ctx->streams[i];
2584 AVCodecID codec_id = st->codec->codec_id;
2585 AVCodec *decoder = avcodec_find_decoder(codec_id);
2586 if( avcodec_open2(st->codec, decoder, &copts) < 0 ) {
2587 fprintf(stderr,"FFMPEG::scan: ");
2588 fprintf(stderr,_("codec open failed\n"));
2590 av_dict_free(&copts);
2593 for( int64_t count=0; !*canceled; ++count ) {
2594 av_packet_unref(&pkt);
2595 pkt.data = 0; pkt.size = 0;
2597 int ret = av_read_frame(fmt_ctx, &pkt);
2599 if( ret == AVERROR_EOF ) break;
2600 if( ++errs > 100 ) {
2601 ff_err(ret,_("over 100 read_frame errs\n"));
2606 if( !pkt.data ) continue;
2607 int i = pkt.stream_index;
2608 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
2609 AVStream *st = fmt_ctx->streams[i];
2610 AVCodecContext *avctx = st->codec;
2611 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
2613 switch( avctx->codec_type ) {
2614 case AVMEDIA_TYPE_VIDEO: {
2615 int vidx = ffvideo.size();
2616 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
2617 if( vidx < 0 ) break;
2618 FFVideoStream *vid = ffvideo[vidx];
2619 int64_t tstmp = pkt.dts;
2620 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.pts;
2621 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
2622 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
2623 double secs = to_secs(tstmp, st->time_base);
2624 int64_t frm = secs * vid->frame_rate + 0.5;
2625 if( frm < 0 ) frm = 0;
2626 index_state->put_video_mark(vidx, frm, pkt.pos);
2629 while( pkt.size > 0 ) {
2630 av_frame_unref(frame);
2632 int ret = vid->decode_frame(&pkt, frame, got_frame);
2633 if( ret <= 0 ) break;
2634 // if( got_frame ) {}
2640 case AVMEDIA_TYPE_AUDIO: {
2641 int aidx = ffaudio.size();
2642 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
2643 if( aidx < 0 ) break;
2644 FFAudioStream *aud = ffaudio[aidx];
2645 int64_t tstmp = pkt.pts;
2646 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
2647 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
2648 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
2649 double secs = to_secs(tstmp, st->time_base);
2650 int64_t sample = secs * aud->sample_rate + 0.5;
2651 if( sample < 0 ) sample = 0;
2652 index_state->put_audio_mark(aidx, sample, pkt.pos);
2654 while( pkt.size > 0 ) {
2655 int ch = aud->channel0, nch = aud->channels;
2656 int64_t pos = index_state->pos(ch);
2657 if( pos != aud->curr_pos ) {
2658 if( abs(pos-aud->curr_pos) > 1 )
2659 printf("audio%d pad %jd %jd (%jd)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
2660 index_state->pad_data(ch, nch, aud->curr_pos);
2662 av_frame_unref(frame);
2664 int ret = aud->decode_frame(&pkt, frame, got_frame);
2665 if( ret <= 0 ) break;
2666 if( got_frame && frame->channels == nch ) {
2668 int len = aud->get_samples(samples,
2669 &frame->extended_data[0], frame->nb_samples);
2670 for( int i=0; i<nch; ++i )
2671 index_state->put_data(ch+i,nch,samples+i,len);
2672 aud->curr_pos += len;
2681 av_frame_free(&frame);
2685 void FFStream::load_markers(IndexMarks &marks, double rate)
2688 int64_t sz = marks.size();
2689 int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
2690 int nb_ent = st->nb_index_entries;
2691 // some formats already have an index
2693 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
2694 int64_t tstmp = ep->timestamp;
2695 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
2696 double secs = ffmpeg->to_secs(tstmp, st->time_base);
2697 int64_t no = secs * rate;
2698 while( in < sz && marks[in].no <= no ) ++in;
2700 int64_t len = sz - in;
2701 int64_t count = max_entries - nb_ent;
2702 if( count > len ) count = len;
2703 for( int i=0; i<count; ++i ) {
2704 int k = in + i * len / count;
2705 int64_t no = marks[k].no, pos = marks[k].pos;
2706 double secs = (double)no / rate;
2707 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
2708 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
2709 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);