10 // work arounds (centos)
13 #define INT64_MAX 9223372036854775807LL
15 #define MAX_RETRY 1000
18 #include "bccmodels.h"
20 #include "fileffmpeg.h"
23 #include "indexfile.h"
24 #include "interlacemodes.h"
27 #include "mainerror.h"
32 #define VIDEO_INBUF_SIZE 0x10000
33 #define AUDIO_INBUF_SIZE 0x10000
34 #define VIDEO_REFILL_THRESH 0
35 #define AUDIO_REFILL_THRESH 0x1000
36 #define AUDIO_MIN_FRAME_SZ 128
38 Mutex FFMPEG::fflock("FFMPEG::fflock");
40 static void ff_err(int ret, const char *fmt, ...)
45 vsnprintf(msg, sizeof(msg), fmt, ap);
47 char errmsg[BCSTRLEN];
48 av_strerror(ret, errmsg, sizeof(errmsg));
49 fprintf(stderr,_("%s err: %s\n"),msg, errmsg);
55 pkt.data = 0; pkt.size = 0;
57 void FFPacket::finit()
59 av_packet_unref(&pkt);
62 FFrame::FFrame(FFStream *fst)
65 frm = av_frame_alloc();
66 init = fst->init_frame(frm);
74 void FFrame::queue(int64_t pos)
80 void FFrame::dequeue()
85 int FFAudioStream::read(float *fp, long len)
93 while( --k >= 0 ) *fp++ = *op++;
94 if( op >= lmt ) op = bfr;
99 void FFAudioStream::realloc(long nsz, int nch, long len)
101 long bsz = nsz * nch;
102 float *np = new float[bsz];
103 inp = np + read(np, len) * nch;
108 delete [] bfr; bfr = np;
111 void FFAudioStream::realloc(long nsz, int nch)
113 if( nsz > sz || this->nch != nch ) {
114 long len = this->nch != nch ? 0 : hpos;
115 if( len > sz ) len = sz;
117 realloc(nsz, nch, len);
121 void FFAudioStream::reserve(long nsz, int nch)
123 long len = (inp - outp) / nch;
125 if( nsz > sz || this->nch != nch ) {
126 if( this->nch != nch ) len = 0;
127 realloc(nsz, nch, len);
130 if( (len*=nch) > 0 && bfr != outp )
131 memmove(bfr, outp, len*sizeof(*bfr));
136 long FFAudioStream::used()
138 long len = inp>=outp ? inp-outp : inp-bfr + lmt-outp;
141 long FFAudioStream::avail()
144 if( in1 >= lmt ) in1 = bfr;
145 long len = outp >= in1 ? outp-in1 : outp-bfr + lmt-in1;
148 void FFAudioStream::reset_history()
152 memset(bfr, 0, lmt-bfr);
155 void FFAudioStream::iseek(int64_t ofs)
157 if( ofs > hpos ) ofs = hpos;
158 if( ofs > sz ) ofs = sz;
159 outp = inp - ofs*nch;
160 if( outp < bfr ) outp += sz*nch;
163 float *FFAudioStream::get_outp(int ofs)
170 int64_t FFAudioStream::put_inp(int ofs)
173 return (inp-outp) / nch;
176 int FFAudioStream::write(const float *fp, long len)
184 while( --k >= 0 ) *ip++ = *fp++;
185 if( ip >= lmt ) ip = bfr;
192 int FFAudioStream::zero(long len)
200 while( --k >= 0 ) *ip++ = 0;
201 if( ip >= lmt ) ip = bfr;
208 // does not advance outp
209 int FFAudioStream::read(double *dp, long len, int ch)
212 float *op = outp + ch;
213 float *lmt1 = lmt + nch-1;
215 int k = (lmt1 - op) / nch;
218 while( --k >= 0 ) { *dp++ = *op; op += nch; }
219 if( op >= lmt ) op -= sz*nch;
224 // load linear buffer, no wrapping allowed, does not advance inp
225 int FFAudioStream::write(const double *dp, long len, int ch)
228 float *ip = inp + ch;
229 while( --n >= 0 ) { *ip = *dp++; ip += nch; }
234 FFStream::FFStream(FFMPEG *ffmpeg, AVStream *st, int fidx)
236 this->ffmpeg = ffmpeg;
239 frm_lock = new Mutex("FFStream::frm_lock");
246 nudge = AV_NOPTS_VALUE;
247 seek_pos = curr_pos = 0;
249 reading = writing = 0;
256 FFStream::~FFStream()
258 if( reading > 0 || writing > 0 ) avcodec_close(avctx);
259 if( avctx ) avcodec_free_context(&avctx);
260 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
261 if( bsfc ) av_bsf_free(&bsfc);
262 while( frms.first ) frms.remove(frms.first);
263 if( filter_graph ) avfilter_graph_free(&filter_graph);
264 if( frame ) av_frame_free(&frame);
265 if( fframe ) av_frame_free(&fframe);
269 void FFStream::ff_lock(const char *cp)
271 FFMPEG::fflock.lock(cp);
274 void FFStream::ff_unlock()
276 FFMPEG::fflock.unlock();
279 void FFStream::queue(FFrame *frm)
281 frm_lock->lock("FFStream::queue");
285 ffmpeg->mux_lock->unlock();
288 void FFStream::dequeue(FFrame *frm)
290 frm_lock->lock("FFStream::dequeue");
292 frms.remove_pointer(frm);
296 int FFStream::encode_activate()
299 writing = ffmpeg->encode_activate();
303 int FFStream::decode_activate()
305 if( reading < 0 && (reading=ffmpeg->decode_activate()) > 0 ) {
306 ff_lock("FFStream::decode_activate");
308 AVDictionary *copts = 0;
309 av_dict_copy(&copts, ffmpeg->opts, 0);
311 // this should be avformat_copy_context(), but no copy avail
312 ret = avformat_open_input(&fmt_ctx, ffmpeg->fmt_ctx->filename, NULL, &copts);
314 ret = avformat_find_stream_info(fmt_ctx, 0);
315 st = fmt_ctx->streams[fidx];
318 if( ret >= 0 && st != 0 ) {
319 AVCodecID codec_id = st->codecpar->codec_id;
320 AVCodec *decoder = avcodec_find_decoder(codec_id);
321 avctx = avcodec_alloc_context3(decoder);
323 eprintf(_("cant allocate codec context\n"));
324 ret = AVERROR(ENOMEM);
327 av_codec_set_pkt_timebase(avctx, st->time_base);
328 if( decoder->capabilities & AV_CODEC_CAP_DR1 )
329 avctx->flags |= CODEC_FLAG_EMU_EDGE;
330 avcodec_parameters_to_context(avctx, st->codecpar);
331 if( !av_dict_get(copts, "threads", NULL, 0) )
332 avctx->thread_count = ffmpeg->ff_cpus();
333 ret = avcodec_open2(avctx, decoder, &copts);
339 eprintf(_("open decoder failed\n"));
342 eprintf(_("can't clone input file\n"));
343 av_dict_free(&copts);
349 int FFStream::read_packet()
351 av_packet_unref(ipkt);
352 int ret = av_read_frame(fmt_ctx, ipkt);
355 if( ret == AVERROR_EOF ) return 0;
356 ff_err(ret, "FFStream::read_packet: av_read_frame failed\n");
363 int FFStream::decode(AVFrame *frame)
366 int retries = MAX_RETRY;
368 while( ret >= 0 && !flushed && --retries >= 0 ) {
370 if( (ret=read_packet()) < 0 ) break;
371 AVPacket *pkt = ret > 0 ? (AVPacket*)ipkt : 0;
373 if( pkt->stream_index != st->index ) continue;
374 if( !pkt->data | !pkt->size ) continue;
376 if( (ret=avcodec_send_packet(avctx, pkt)) < 0 ) {
377 ff_err(ret, "FFStream::decode: avcodec_send_packet failed\n");
383 if( (ret=decode_frame(frame)) > 0 ) break;
391 fprintf(stderr, "FFStream::decode: Retry limit\n");
395 fprintf(stderr, "FFStream::decode: failed\n");
399 int FFStream::load_filter(AVFrame *frame)
401 int ret = av_buffersrc_add_frame_flags(buffersrc_ctx, frame, 0);
403 eprintf(_("av_buffersrc_add_frame_flags failed\n"));
407 int FFStream::read_filter(AVFrame *frame)
409 int ret = av_buffersink_get_frame(buffersink_ctx, frame);
411 if( ret == AVERROR(EAGAIN) ) return 0;
412 if( ret == AVERROR_EOF ) { st_eof(1); return -1; }
413 ff_err(ret, "FFStream::read_filter: av_buffersink_get_frame failed\n");
419 int FFStream::read_frame(AVFrame *frame)
421 av_frame_unref(frame);
422 if( !filter_graph || !buffersrc_ctx || !buffersink_ctx )
423 return decode(frame);
424 if( !fframe && !(fframe=av_frame_alloc()) ) {
425 fprintf(stderr, "FFStream::read_frame: av_frame_alloc failed\n");
429 while( !flushed && !(ret=read_filter(frame)) ) {
430 if( (ret=decode(fframe)) < 0 ) break;
431 if( ret > 0 && (ret=load_filter(fframe)) < 0 ) break;
436 int FFStream::write_packet(FFPacket &pkt)
440 av_packet_rescale_ts(pkt, avctx->time_base, st->time_base);
441 pkt->stream_index = st->index;
442 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, pkt);
445 ret = av_bsf_send_packet(bsfc, pkt);
448 if( (ret=av_bsf_receive_packet(bsfc, bs)) < 0 ) {
449 if( ret == AVERROR(EAGAIN) ) return 0;
450 if( ret == AVERROR_EOF ) return -1;
453 av_packet_rescale_ts(bs, avctx->time_base, st->time_base);
454 bs->stream_index = st->index;
455 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, bs);
459 ff_err(ret, "FFStream::write_packet: write packet failed\n");
463 int FFStream::encode_frame(AVFrame *frame)
465 int pkts = 0, ret = 0;
466 for( int retry=100; --retry>=0; ) {
468 ret = avcodec_send_frame(avctx, frame);
469 if( !ret && frame ) return pkts;
470 if( ret < 0 && ret != AVERROR(EAGAIN) ) break;
472 ret = avcodec_receive_packet(avctx, opkt);
473 if( !frame && ret == AVERROR_EOF ) return pkts;
475 ret = write_packet(opkt);
479 ff_err(ret, "FFStream::encode_frame: encode failed\n");
483 int FFStream::flush()
487 int ret = encode_frame(0);
489 ff_err(ret, "FFStream::flush");
490 return ret >= 0 ? 0 : 1;
493 int FFStream::seek(int64_t no, double rate)
495 // default ffmpeg native seek
497 int64_t pos = no, pkt_pos = -1;
498 IndexMarks *index_markers = get_markers();
499 if( index_markers && index_markers->size() > 1 ) {
500 IndexMarks &marks = *index_markers;
501 int i = marks.find(pos);
502 int64_t n = i < 0 ? (i=0) : marks[i].no;
503 // if indexed seek point not too far away (<30 secs), use index
504 if( no-n < 30*rate ) {
507 if( i < marks.size() ) pkt_pos = marks[i].pos;
511 if( pos == curr_pos ) return 0;
512 double secs = pos < 0 ? 0. : pos / rate;
513 AVRational time_base = st->time_base;
514 int64_t tstmp = time_base.num > 0 ? secs * time_base.den/time_base.num : 0;
516 if( st->nb_index_entries > 0 ) tstmp = st->index_entries[0].timestamp;
517 else if( st->start_time != AV_NOPTS_VALUE ) tstmp = st->start_time;
518 else if( st->first_dts != AV_NOPTS_VALUE ) tstmp = st->first_dts;
519 else tstmp = INT64_MIN+1;
521 else if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
524 // seek all streams using the default timebase.
525 // this is how ffmpeg and ffplay work. stream seeks are less tested.
526 tstmp = av_rescale_q(tstmp, time_base, AV_TIME_BASE_Q);
530 avcodec_flush_buffers(avctx);
531 avformat_flush(fmt_ctx);
533 int64_t seek = tstmp;
534 int flags = AVSEEK_FLAG_ANY;
535 if( !(fmt_ctx->iformat->flags & AVFMT_NO_BYTE_SEEK) && pkt_pos >= 0 ) {
537 flags = AVSEEK_FLAG_BYTE;
539 int ret = avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, seek, INT64_MAX, flags);
541 // finds the first index frame below the target time
542 int flags = AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_ANY;
543 int ret = av_seek_frame(fmt_ctx, idx, tstmp, flags);
545 int retry = MAX_RETRY;
547 need_packet = 0; flushed = 0;
548 seeked = 1; st_eof(0);
549 // read up to retry packets, limited to npkts in stream, and not pkt.pos past pkt_pos
550 while( --retry >= 0 ) {
551 if( read_packet() <= 0 ) { ret = -1; break; }
552 if( ipkt->stream_index != st->index ) continue;
553 if( !ipkt->data || !ipkt->size ) continue;
554 if( pkt_pos >= 0 && ipkt->pos >= pkt_pos ) break;
555 if( --npkts <= 0 ) break;
556 int64_t pkt_ts = ipkt->dts != AV_NOPTS_VALUE ? ipkt->dts : ipkt->pts;
557 if( pkt_ts == AV_NOPTS_VALUE ) continue;
558 if( pkt_ts >= tstmp ) break;
561 fprintf(stderr,"FFStream::seek: retry limit, pos=%jd tstmp=%jd\n",pos,tstmp);
565 ret = avcodec_send_packet(avctx, ipkt);
567 //some codecs need more than one pkt to resync
568 if( ret == AVERROR_INVALIDDATA ) ret = 0;
570 ff_err(ret, "FFStream::avcodec_send_packet failed\n");
575 printf("** seek fail %jd, %jd\n", pos, tstmp);
576 seeked = need_packet = 0;
580 //printf("seeked pos = %ld, %ld\n", pos, tstmp);
581 seek_pos = curr_pos = pos;
585 FFAudioStream::FFAudioStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
586 : FFStream(ffmpeg, strm, fidx)
589 channel0 = channels = 0;
592 frame_sz = AUDIO_MIN_FRAME_SZ;
594 resample_context = 0;
595 swr_ichs = swr_ifmt = swr_irate = 0;
604 bfr = new float[bsz];
609 FFAudioStream::~FFAudioStream()
611 if( resample_context ) swr_free(&resample_context);
616 void FFAudioStream::init_swr(int ichs, int ifmt, int irate)
618 if( resample_context ) {
619 if( swr_ichs == ichs && swr_ifmt == ifmt && swr_irate == irate )
621 swr_free(&resample_context);
623 swr_ichs = ichs; swr_ifmt = ifmt; swr_irate = irate;
624 if( ichs == channels && ifmt == AV_SAMPLE_FMT_FLT && irate == sample_rate )
626 uint64_t ilayout = av_get_default_channel_layout(ichs);
627 if( !ilayout ) ilayout = ((uint64_t)1<<ichs) - 1;
628 uint64_t olayout = av_get_default_channel_layout(channels);
629 if( !olayout ) olayout = ((uint64_t)1<<channels) - 1;
630 resample_context = swr_alloc_set_opts(NULL,
631 olayout, AV_SAMPLE_FMT_FLT, sample_rate,
632 ilayout, (AVSampleFormat)ifmt, irate,
634 if( resample_context )
635 swr_init(resample_context);
638 int FFAudioStream::get_samples(float *&samples, uint8_t **data, int len)
640 samples = *(float **)data;
641 if( resample_context ) {
642 if( len > aud_bfr_sz ) {
648 aud_bfr = new float[aud_bfr_sz*channels];
650 int ret = swr_convert(resample_context,
651 (uint8_t**)&aud_bfr, aud_bfr_sz, (const uint8_t**)data, len);
653 ff_err(ret, "FFAudioStream::get_samples: swr_convert failed\n");
662 int FFAudioStream::load_history(uint8_t **data, int len)
665 len = get_samples(samples, data, len);
667 // biggest user bfr since seek + frame
668 realloc(mbsz + len + 1, channels);
674 int FFAudioStream::decode_frame(AVFrame *frame)
676 int first_frame = seeked; seeked = 0;
677 int ret = avcodec_receive_frame(avctx, frame);
679 if( first_frame || ret == AVERROR(EAGAIN) ) return 0;
680 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
681 ff_err(ret, "FFAudioStream::decode_frame: Could not read audio frame\n");
684 int64_t pkt_ts = av_frame_get_best_effort_timestamp(frame);
685 if( pkt_ts != AV_NOPTS_VALUE )
686 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * sample_rate + 0.5;
690 int FFAudioStream::encode_activate()
692 if( writing >= 0 ) return writing;
693 if( !avctx->codec ) return writing = 0;
694 frame_sz = avctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE ?
695 10000 : avctx->frame_size;
696 return FFStream::encode_activate();
699 int64_t FFAudioStream::load_buffer(double ** const sp, int len)
701 reserve(len+1, st->codecpar->channels);
702 for( int ch=0; ch<nch; ++ch )
703 write(sp[ch], len, ch);
707 int FFAudioStream::in_history(int64_t pos)
709 if( pos > curr_pos ) return 0;
711 if( len > sz ) len = sz;
712 if( pos < curr_pos - len ) return 0;
717 int FFAudioStream::init_frame(AVFrame *frame)
719 frame->nb_samples = frame_sz;
720 frame->format = avctx->sample_fmt;
721 frame->channel_layout = avctx->channel_layout;
722 frame->sample_rate = avctx->sample_rate;
723 int ret = av_frame_get_buffer(frame, 0);
725 ff_err(ret, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
729 int FFAudioStream::load(int64_t pos, int len)
731 if( audio_seek(pos) < 0 ) return -1;
732 if( !frame && !(frame=av_frame_alloc()) ) {
733 fprintf(stderr, "FFAudioStream::load: av_frame_alloc failed\n");
736 if( mbsz < len ) mbsz = len;
737 int64_t end_pos = pos + len;
738 int ret = 0, i = len / frame_sz + MAX_RETRY;
739 while( ret>=0 && !flushed && curr_pos<end_pos && --i>=0 ) {
740 ret = read_frame(frame);
741 if( ret > 0 && frame->nb_samples > 0 ) {
742 init_swr(frame->channels, frame->format, frame->sample_rate);
743 load_history(&frame->extended_data[0], frame->nb_samples);
744 curr_pos += frame->nb_samples;
747 if( end_pos > curr_pos ) {
748 zero(end_pos - curr_pos);
751 len = curr_pos - pos;
756 int FFAudioStream::audio_seek(int64_t pos)
758 if( decode_activate() <= 0 ) return -1;
759 if( !st->codecpar ) return -1;
760 if( in_history(pos) ) return 0;
761 if( pos == curr_pos ) return 0;
762 reset_history(); mbsz = 0;
763 // guarentee preload > 1sec samples
764 if( seek(pos-sample_rate, sample_rate) < 0 ) return -1;
768 int FFAudioStream::encode(double **samples, int len)
770 if( encode_activate() <= 0 ) return -1;
773 int64_t count = samples ? load_buffer(samples, len) : used();
774 int frame_sz1 = samples ? frame_sz-1 : 0;
777 while( ret >= 0 && count > frame_sz1 ) {
778 frm = new FFrame(this);
779 if( (ret=frm->initted()) < 0 ) break;
780 AVFrame *frame = *frm;
781 len = count >= frame_sz ? frame_sz : count;
782 float *bfrp = get_outp(len);
783 ret = swr_convert(resample_context,
784 (uint8_t **)frame->extended_data, len,
785 (const uint8_t **)&bfrp, len);
787 ff_err(ret, "FFAudioStream::encode: swr_convert failed\n");
790 frame->nb_samples = len;
791 frm->queue(curr_pos);
798 return ret >= 0 ? 0 : 1;
801 int FFAudioStream::drain()
806 int FFAudioStream::encode_frame(AVFrame *frame)
808 return FFStream::encode_frame(frame);
811 int FFAudioStream::write_packet(FFPacket &pkt)
813 return FFStream::write_packet(pkt);
816 void FFAudioStream::load_markers()
818 IndexState *index_state = ffmpeg->file_base->asset->index_state;
819 if( !index_state || idx >= index_state->audio_markers.size() ) return;
820 if( index_state->marker_status == MARKERS_NOTTESTED ) return;
821 FFStream::load_markers(*index_state->audio_markers[idx], sample_rate);
824 IndexMarks *FFAudioStream::get_markers()
826 IndexState *index_state = ffmpeg->file_base->asset->index_state;
827 if( !index_state || idx >= index_state->audio_markers.size() ) return 0;
828 return index_state->audio_markers[idx];
831 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
832 : FFStream(ffmpeg, strm, fidx)
843 FFVideoStream::~FFVideoStream()
847 int FFVideoStream::decode_frame(AVFrame *frame)
849 int first_frame = seeked; seeked = 0;
850 int ret = avcodec_receive_frame(avctx, frame);
852 if( first_frame || ret == AVERROR(EAGAIN) ) return 0;
853 if( ret == AVERROR(EAGAIN) ) return 0;
854 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
855 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame\n");
858 int64_t pkt_ts = av_frame_get_best_effort_timestamp(frame);
859 if( pkt_ts != AV_NOPTS_VALUE )
860 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * frame_rate + 0.5;
864 int FFVideoStream::load(VFrame *vframe, int64_t pos)
866 int ret = video_seek(pos);
867 if( ret < 0 ) return -1;
868 if( !frame && !(frame=av_frame_alloc()) ) {
869 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
872 int i = MAX_RETRY + pos - curr_pos;
873 while( ret>=0 && !flushed && curr_pos<=pos && --i>=0 ) {
874 ret = read_frame(frame);
875 if( ret > 0 ) ++curr_pos;
877 if( frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0 )
880 ret = convert_cmodel(vframe, frame);
882 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
886 int FFVideoStream::video_seek(int64_t pos)
888 if( decode_activate() <= 0 ) return -1;
889 if( !st->codecpar ) return -1;
890 if( pos == curr_pos-1 && !seeked ) return 0;
891 // if close enough, just read up to current
892 int gop = avctx->gop_size;
893 if( gop < 4 ) gop = 4;
894 if( gop > 64 ) gop = 64;
895 int read_limit = curr_pos + 3*gop;
896 if( pos >= curr_pos && pos <= read_limit ) return 0;
897 // guarentee preload more than 2*gop frames
898 if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
902 int FFVideoStream::init_frame(AVFrame *picture)
904 picture->format = avctx->pix_fmt;
905 picture->width = avctx->width;
906 picture->height = avctx->height;
907 int ret = av_frame_get_buffer(picture, 32);
911 int FFVideoStream::encode(VFrame *vframe)
913 if( encode_activate() <= 0 ) return -1;
915 FFrame *picture = new FFrame(this);
916 int ret = picture->initted();
918 AVFrame *frame = *picture;
919 frame->pts = curr_pos;
920 ret = convert_pixfmt(vframe, frame);
923 picture->queue(curr_pos);
927 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
930 return ret >= 0 ? 0 : 1;
933 int FFVideoStream::drain()
938 int FFVideoStream::encode_frame(AVFrame *frame)
941 frame->interlaced_frame = interlaced;
942 frame->top_field_first = top_field_first;
944 return FFStream::encode_frame(frame);
947 int FFVideoStream::write_packet(FFPacket &pkt)
949 if( !(ffmpeg->fmt_ctx->oformat->flags & AVFMT_VARIABLE_FPS) )
951 return FFStream::write_packet(pkt);
954 AVPixelFormat FFVideoConvert::color_model_to_pix_fmt(int color_model)
956 switch( color_model ) {
957 case BC_YUV422: return AV_PIX_FMT_YUYV422;
958 case BC_RGB888: return AV_PIX_FMT_RGB24;
959 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
960 case BC_BGR8888: return AV_PIX_FMT_BGR0;
961 case BC_BGR888: return AV_PIX_FMT_BGR24;
962 case BC_ARGB8888: return AV_PIX_FMT_ARGB;
963 case BC_ABGR8888: return AV_PIX_FMT_ABGR;
964 case BC_RGB8: return AV_PIX_FMT_RGB8;
965 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
966 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
967 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
968 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
969 case BC_RGB565: return AV_PIX_FMT_RGB565;
970 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
971 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
972 case BC_AYUV16161616: return AV_PIX_FMT_AYUV64LE;
976 return AV_PIX_FMT_NB;
979 int FFVideoConvert::pix_fmt_to_color_model(AVPixelFormat pix_fmt)
982 case AV_PIX_FMT_YUYV422: return BC_YUV422;
983 case AV_PIX_FMT_RGB24: return BC_RGB888;
984 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
985 case AV_PIX_FMT_BGR0: return BC_BGR8888;
986 case AV_PIX_FMT_BGR24: return BC_BGR888;
987 case AV_PIX_FMT_ARGB: return BC_ARGB8888;
988 case AV_PIX_FMT_ABGR: return BC_ABGR8888;
989 case AV_PIX_FMT_RGB8: return BC_RGB8;
990 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
991 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
992 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
993 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
994 case AV_PIX_FMT_RGB565: return BC_RGB565;
995 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
996 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
997 case AV_PIX_FMT_AYUV64LE: return BC_AYUV16161616;
1004 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip)
1006 AVFrame *ipic = av_frame_alloc();
1007 int ret = convert_picture_vframe(frame, ip, ipic);
1008 av_frame_free(&ipic);
1012 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip, AVFrame *ipic)
1014 int cmodel = frame->get_color_model();
1015 AVPixelFormat ofmt = color_model_to_pix_fmt(cmodel);
1016 if( ofmt == AV_PIX_FMT_NB ) return -1;
1017 int size = av_image_fill_arrays(ipic->data, ipic->linesize,
1018 frame->get_data(), ofmt, frame->get_w(), frame->get_h(), 1);
1019 if( size < 0 ) return -1;
1021 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1022 int ysz = bpp * frame->get_w(), usz = ysz;
1031 // override av_image_fill_arrays() for planar types
1032 ipic->data[0] = frame->get_y(); ipic->linesize[0] = ysz;
1033 ipic->data[1] = frame->get_u(); ipic->linesize[1] = usz;
1034 ipic->data[2] = frame->get_v(); ipic->linesize[2] = usz;
1037 ipic->data[0] = frame->get_data();
1038 ipic->linesize[0] = frame->get_bytes_per_line();
1042 AVPixelFormat pix_fmt = (AVPixelFormat)ip->format;
1043 convert_ctx = sws_getCachedContext(convert_ctx, ip->width, ip->height, pix_fmt,
1044 frame->get_w(), frame->get_h(), ofmt, SWS_POINT, NULL, NULL, NULL);
1045 if( !convert_ctx ) {
1046 fprintf(stderr, "FFVideoConvert::convert_picture_frame:"
1047 " sws_getCachedContext() failed\n");
1050 int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ip->height,
1051 ipic->data, ipic->linesize);
1053 ff_err(ret, "FFVideoConvert::convert_picture_frame: sws_scale() failed\n");
1059 int FFVideoConvert::convert_cmodel(VFrame *frame, AVFrame *ip)
1061 // try direct transfer
1062 if( !convert_picture_vframe(frame, ip) ) return 1;
1063 // use indirect transfer
1064 AVPixelFormat ifmt = (AVPixelFormat)ip->format;
1065 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
1067 for( int i = 0; i <desc->nb_components; ++i ) {
1068 int bits = desc->comp[i].depth;
1069 if( bits > max_bits ) max_bits = bits;
1071 int imodel = pix_fmt_to_color_model(ifmt);
1072 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1073 int cmodel = frame->get_color_model();
1074 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1075 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1076 imodel = cmodel_is_yuv ?
1077 (BC_CModels::has_alpha(cmodel) ?
1079 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1080 (BC_CModels::has_alpha(cmodel) ?
1081 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1082 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1084 VFrame vframe(ip->width, ip->height, imodel);
1085 if( convert_picture_vframe(&vframe, ip) ) return -1;
1086 frame->transfer_from(&vframe);
1090 int FFVideoConvert::transfer_cmodel(VFrame *frame, AVFrame *ifp)
1092 int ret = convert_cmodel(frame, ifp);
1094 const AVDictionary *src = av_frame_get_metadata(ifp);
1095 AVDictionaryEntry *t = NULL;
1096 BC_Hash *hp = frame->get_params();
1098 while( (t=av_dict_get(src, "", t, AV_DICT_IGNORE_SUFFIX)) )
1099 hp->update(t->key, t->value);
1104 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op)
1106 AVFrame *opic = av_frame_alloc();
1107 int ret = convert_vframe_picture(frame, op, opic);
1108 av_frame_free(&opic);
1112 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op, AVFrame *opic)
1114 int cmodel = frame->get_color_model();
1115 AVPixelFormat ifmt = color_model_to_pix_fmt(cmodel);
1116 if( ifmt == AV_PIX_FMT_NB ) return -1;
1117 int size = av_image_fill_arrays(opic->data, opic->linesize,
1118 frame->get_data(), ifmt, frame->get_w(), frame->get_h(), 1);
1119 if( size < 0 ) return -1;
1121 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1122 int ysz = bpp * frame->get_w(), usz = ysz;
1131 // override av_image_fill_arrays() for planar types
1132 opic->data[0] = frame->get_y(); opic->linesize[0] = ysz;
1133 opic->data[1] = frame->get_u(); opic->linesize[1] = usz;
1134 opic->data[2] = frame->get_v(); opic->linesize[2] = usz;
1137 opic->data[0] = frame->get_data();
1138 opic->linesize[0] = frame->get_bytes_per_line();
1142 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1143 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(),
1144 ifmt, op->width, op->height, ofmt, SWS_POINT, NULL, NULL, NULL);
1145 if( !convert_ctx ) {
1146 fprintf(stderr, "FFVideoConvert::convert_frame_picture:"
1147 " sws_getCachedContext() failed\n");
1150 int ret = sws_scale(convert_ctx, opic->data, opic->linesize, 0, frame->get_h(),
1151 op->data, op->linesize);
1153 ff_err(ret, "FFVideoConvert::convert_frame_picture: sws_scale() failed\n");
1159 int FFVideoConvert::convert_pixfmt(VFrame *frame, AVFrame *op)
1161 // try direct transfer
1162 if( !convert_vframe_picture(frame, op) ) return 1;
1163 // use indirect transfer
1164 int cmodel = frame->get_color_model();
1165 int max_bits = BC_CModels::calculate_pixelsize(cmodel) * 8;
1166 max_bits /= BC_CModels::components(cmodel);
1167 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1168 int imodel = pix_fmt_to_color_model(ofmt);
1169 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1170 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1171 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1172 imodel = cmodel_is_yuv ?
1173 (BC_CModels::has_alpha(cmodel) ?
1175 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1176 (BC_CModels::has_alpha(cmodel) ?
1177 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1178 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1180 VFrame vframe(frame->get_w(), frame->get_h(), imodel);
1181 vframe.transfer_from(frame);
1182 if( !convert_vframe_picture(&vframe, op) ) return 1;
1186 int FFVideoConvert::transfer_pixfmt(VFrame *frame, AVFrame *ofp)
1188 int ret = convert_pixfmt(frame, ofp);
1190 BC_Hash *hp = frame->get_params();
1191 AVDictionary **dict = avpriv_frame_get_metadatap(ofp);
1192 //av_dict_free(dict);
1193 for( int i=0; i<hp->size(); ++i ) {
1194 char *key = hp->get_key(i), *val = hp->get_value(i);
1195 av_dict_set(dict, key, val, 0);
1201 void FFVideoStream::load_markers()
1203 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1204 if( !index_state || idx >= index_state->video_markers.size() ) return;
1205 FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
1208 IndexMarks *FFVideoStream::get_markers()
1210 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1211 if( !index_state || idx >= index_state->video_markers.size() ) return 0;
1212 return !index_state ? 0 : index_state->video_markers[idx];
1216 FFMPEG::FFMPEG(FileBase *file_base)
1219 this->file_base = file_base;
1220 memset(file_format,0,sizeof(file_format));
1221 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
1222 flow_lock = new Condition(1,"FFStream::flow_lock",0);
1225 decoding = encoding = 0;
1226 has_audio = has_video = 0;
1229 opt_video_filter = 0;
1230 opt_audio_filter = 0;
1231 char option_path[BCTEXTLEN];
1232 set_option_path(option_path, "%s", "ffmpeg.opts");
1233 read_options(option_path, opts);
1238 ff_lock("FFMPEG::~FFMPEG()");
1240 ffaudio.remove_all_objects();
1241 ffvideo.remove_all_objects();
1242 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1246 av_dict_free(&opts);
1247 delete [] opt_video_filter;
1248 delete [] opt_audio_filter;
1251 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1253 const int *p = codec->supported_samplerates;
1254 if( !p ) return sample_rate;
1256 if( *p == sample_rate ) return *p;
1262 static inline AVRational std_frame_rate(int i)
1264 static const int m1 = 1001*12, m2 = 1000*12;
1265 static const int freqs[] = {
1266 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1267 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
1269 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1270 return (AVRational) { freq, 1001*12 };
1273 AVRational FFMPEG::check_frame_rate(AVCodec *codec, double frame_rate)
1275 const AVRational *p = codec->supported_framerates;
1276 AVRational rate, best_rate = (AVRational) { 0, 0 };
1277 double max_err = 1.; int i = 0;
1278 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1279 double framerate = (double) rate.num / rate.den;
1280 double err = fabs(frame_rate/framerate - 1.);
1281 if( err >= max_err ) continue;
1285 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1288 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1291 double display_aspect = asset->width / (double)asset->height;
1292 double sample_aspect = display_aspect / asset->aspect_ratio;
1293 int width = 1000000, height = width * sample_aspect + 0.5;
1295 MWindow::create_aspect_ratio(w, h, width, height);
1296 return (AVRational){(int)w, (int)h};
1299 return (AVRational){1, 1};
1303 AVRational FFMPEG::to_time_base(int sample_rate)
1305 return (AVRational){1, sample_rate};
1308 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
1310 char *ep = path + BCTEXTLEN-1;
1311 strncpy(path, File::get_cindat_path(), ep-path);
1312 strncat(path, "/ffmpeg/", ep-path);
1313 path += strlen(path);
1316 path += vsnprintf(path, ep-path, fmt, ap);
1321 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
1326 set_option_path(path, "%s/%s", type, spec);
1329 int FFMPEG::get_format(char *format, const char *path, const char *spec)
1331 char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
1332 get_option_path(option_path, path, spec);
1333 FILE *fp = fopen(option_path,"r");
1336 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1338 line[sizeof(line)-1] = 0;
1339 ret = scan_option_line(line, format, codec);
1345 int FFMPEG::get_codec(char *codec, const char *path, const char *spec)
1347 char option_path[BCTEXTLEN], line[BCTEXTLEN], format[BCTEXTLEN];
1348 get_option_path(option_path, path, spec);
1349 FILE *fp = fopen(option_path,"r");
1352 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1355 line[sizeof(line)-1] = 0;
1356 ret = scan_option_line(line, format, codec);
1359 char *vp = codec, *ep = vp+BCTEXTLEN-1;
1360 while( vp < ep && *vp && *vp != '|' ) ++vp;
1361 if( *vp == '|' ) --vp;
1362 while( vp > codec && (*vp==' ' || *vp=='\t') ) *vp-- = 0;
1367 int FFMPEG::get_file_format()
1369 char audio_muxer[BCSTRLEN], video_muxer[BCSTRLEN];
1370 char audio_format[BCSTRLEN], video_format[BCSTRLEN];
1371 audio_muxer[0] = audio_format[0] = 0;
1372 video_muxer[0] = video_format[0] = 0;
1373 Asset *asset = file_base->asset;
1374 int ret = asset ? 0 : 1;
1375 if( !ret && asset->audio_data ) {
1376 if( !(ret=get_format(audio_format, "audio", asset->acodec)) ) {
1377 if( get_format(audio_muxer, "format", audio_format) ) {
1378 strcpy(audio_muxer, audio_format);
1379 audio_format[0] = 0;
1383 if( !ret && asset->video_data ) {
1384 if( !(ret=get_format(video_format, "video", asset->vcodec)) ) {
1385 if( get_format(video_muxer, "format", video_format) ) {
1386 strcpy(video_muxer, video_format);
1387 video_format[0] = 0;
1391 if( !ret && !audio_muxer[0] && !video_muxer[0] )
1393 if( !ret && audio_muxer[0] && video_muxer[0] &&
1394 strcmp(audio_muxer, video_muxer) ) ret = -1;
1395 if( !ret && audio_format[0] && video_format[0] &&
1396 strcmp(audio_format, video_format) ) ret = -1;
1398 strcpy(file_format, !audio_format[0] && !video_format[0] ?
1399 (audio_muxer[0] ? audio_muxer : video_muxer) :
1400 (audio_format[0] ? audio_format : video_format));
1404 int FFMPEG::scan_option_line(char *cp, char *tag, char *val)
1406 while( *cp == ' ' || *cp == '\t' ) ++cp;
1408 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' && *cp != '\n' ) ++cp;
1410 if( !len || len > BCSTRLEN-1 ) return 1;
1411 while( bp < cp ) *tag++ = *bp++;
1413 while( *cp == ' ' || *cp == '\t' ) ++cp;
1414 if( *cp == '=' ) ++cp;
1415 while( *cp == ' ' || *cp == '\t' ) ++cp;
1417 while( *cp && *cp != '\n' ) ++cp;
1419 if( len > BCTEXTLEN-1 ) return 1;
1420 while( bp < cp ) *val++ = *bp++;
1425 int FFMPEG::load_defaults(const char *path, const char *type,
1426 char *codec, char *codec_options, int len)
1428 char default_file[BCTEXTLEN];
1429 set_option_path(default_file, "%s/%s.dfl", path, type);
1430 FILE *fp = fopen(default_file,"r");
1432 fgets(codec, BCSTRLEN, fp);
1434 while( *cp && *cp!='\n' ) ++cp;
1436 while( len > 0 && fgets(codec_options, len, fp) ) {
1437 int n = strlen(codec_options);
1438 codec_options += n; len -= n;
1441 set_option_path(default_file, "%s/%s", path, codec);
1442 return load_options(default_file, codec_options, len);
1445 void FFMPEG::set_asset_format(Asset *asset, const char *text)
1447 if( asset->format != FILE_FFMPEG ) return;
1448 if( text != asset->fformat )
1449 strcpy(asset->fformat, text);
1450 if( !asset->ff_audio_options[0] ) {
1451 asset->audio_data = !load_defaults("audio", text, asset->acodec,
1452 asset->ff_audio_options, sizeof(asset->ff_audio_options));
1454 if( !asset->ff_video_options[0] ) {
1455 asset->video_data = !load_defaults("video", text, asset->vcodec,
1456 asset->ff_video_options, sizeof(asset->ff_video_options));
1460 int FFMPEG::get_encoder(const char *options,
1461 char *format, char *codec, char *bsfilter)
1463 FILE *fp = fopen(options,"r");
1465 eprintf(_("options open failed %s\n"),options);
1468 if( get_encoder(fp, format, codec, bsfilter) )
1469 eprintf(_("format/codec not found %s\n"), options);
1474 int FFMPEG::get_encoder(FILE *fp,
1475 char *format, char *codec, char *bsfilter)
1477 format[0] = codec[0] = bsfilter[0] = 0;
1478 char line[BCTEXTLEN];
1479 if( !fgets(line, sizeof(line), fp) ) return 1;
1480 line[sizeof(line)-1] = 0;
1481 if( scan_option_line(line, format, codec) ) return 1;
1483 while( *cp && *cp != '|' ) ++cp;
1484 if( !*cp ) return 0;
1486 do { *bp-- = 0; } while( bp>=codec && (*bp==' ' || *bp == '\t' ) );
1487 while( *++cp && (*cp==' ' || *cp == '\t') );
1489 for( int i=BCTEXTLEN; --i>0 && *cp; ) *bp++ = *cp++;
1494 int FFMPEG::read_options(const char *options, AVDictionary *&opts, int skip)
1496 FILE *fp = fopen(options,"r");
1499 while( !ret && --skip >= 0 ) {
1501 while( ch >= 0 && ch != '\n' ) ch = getc(fp);
1502 if( ch < 0 ) ret = 1;
1505 ret = read_options(fp, options, opts);
1510 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
1512 FILE *fp = fmemopen((void *)options,strlen(options),"r");
1514 int ret = read_options(fp, options, opts);
1516 AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
1517 if( tag ) st->id = strtol(tag->value,0,0);
1521 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
1523 int ret = 0, no = 0;
1524 char line[BCTEXTLEN];
1525 while( !ret && fgets(line, sizeof(line), fp) ) {
1526 line[sizeof(line)-1] = 0;
1527 if( line[0] == '#' ) continue;
1528 if( line[0] == '\n' ) continue;
1529 char key[BCSTRLEN], val[BCTEXTLEN];
1530 if( scan_option_line(line, key, val) ) {
1531 eprintf(_("err reading %s: line %d\n"), options, no);
1535 if( !strcmp(key, "duration") )
1536 opt_duration = strtod(val, 0);
1537 else if( !strcmp(key, "video_filter") )
1538 opt_video_filter = cstrdup(val);
1539 else if( !strcmp(key, "audio_filter") )
1540 opt_audio_filter = cstrdup(val);
1541 else if( !strcmp(key, "loglevel") )
1544 av_dict_set(&opts, key, val, 0);
1550 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
1552 char option_path[BCTEXTLEN];
1553 set_option_path(option_path, "%s", options);
1554 return read_options(option_path, opts);
1557 int FFMPEG::load_options(const char *path, char *bfr, int len)
1560 FILE *fp = fopen(path, "r");
1562 fgets(bfr, len, fp); // skip hdr
1563 len = fread(bfr, 1, len-1, fp);
1564 if( len < 0 ) len = 0;
1570 void FFMPEG::set_loglevel(const char *ap)
1572 if( !ap || !*ap ) return;
1577 { "quiet" , AV_LOG_QUIET },
1578 { "panic" , AV_LOG_PANIC },
1579 { "fatal" , AV_LOG_FATAL },
1580 { "error" , AV_LOG_ERROR },
1581 { "warning", AV_LOG_WARNING },
1582 { "info" , AV_LOG_INFO },
1583 { "verbose", AV_LOG_VERBOSE },
1584 { "debug" , AV_LOG_DEBUG },
1586 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
1587 if( !strcmp(log_levels[i].name, ap) ) {
1588 av_log_set_level(log_levels[i].level);
1592 av_log_set_level(atoi(ap));
1595 double FFMPEG::to_secs(int64_t time, AVRational time_base)
1597 double base_time = time == AV_NOPTS_VALUE ? 0 :
1598 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
1599 return base_time / AV_TIME_BASE;
1602 int FFMPEG::info(char *text, int len)
1604 if( len <= 0 ) return 0;
1606 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
1608 report("format: %s\n",fmt_ctx->iformat->name);
1609 if( ffvideo.size() > 0 )
1610 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
1611 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
1612 FFVideoStream *vid = ffvideo[vidx];
1613 AVStream *st = vid->st;
1614 AVCodecID codec_id = st->codecpar->codec_id;
1615 report(_("vid%d (%d), id 0x%06x:\n"), vid->idx, vid->fidx, codec_id);
1616 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
1617 report(" video%d %s", vidx+1, desc ? desc->name : " (unkn)");
1618 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
1619 AVPixelFormat pix_fmt = (AVPixelFormat)st->codecpar->format;
1620 const char *pfn = av_get_pix_fmt_name(pix_fmt);
1621 report(" pix %s\n", pfn ? pfn : "(unkn)");
1622 double secs = to_secs(st->duration, st->time_base);
1623 int64_t length = secs * vid->frame_rate + 0.5;
1624 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
1625 int64_t nudge = ofs * vid->frame_rate;
1626 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1627 report(" %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
1628 int hrs = secs/3600; secs -= hrs*3600;
1629 int mins = secs/60; secs -= mins*60;
1630 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1632 if( ffaudio.size() > 0 )
1633 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
1634 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
1635 FFAudioStream *aud = ffaudio[aidx];
1636 AVStream *st = aud->st;
1637 AVCodecID codec_id = st->codecpar->codec_id;
1638 report(_("aud%d (%d), id 0x%06x:\n"), aud->idx, aud->fidx, codec_id);
1639 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
1640 int nch = aud->channels, ch0 = aud->channel0+1;
1641 report(" audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
1642 AVSampleFormat sample_fmt = (AVSampleFormat)st->codecpar->format;
1643 const char *fmt = av_get_sample_fmt_name(sample_fmt);
1644 report(" %s %d", fmt, aud->sample_rate);
1645 int sample_bits = av_get_bits_per_sample(codec_id);
1646 report(" %dbits\n", sample_bits);
1647 double secs = to_secs(st->duration, st->time_base);
1648 int64_t length = secs * aud->sample_rate + 0.5;
1649 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
1650 int64_t nudge = ofs * aud->sample_rate;
1651 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1652 report(" %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
1653 int hrs = secs/3600; secs -= hrs*3600;
1654 int mins = secs/60; secs -= mins*60;
1655 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1657 if( fmt_ctx->nb_programs > 0 )
1658 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
1659 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
1660 report("program %d", i+1);
1661 AVProgram *pgrm = fmt_ctx->programs[i];
1662 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1663 int idx = pgrm->stream_index[j];
1664 int vidx = ffvideo.size();
1665 while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
1667 report(", vid%d", vidx);
1670 int aidx = ffaudio.size();
1671 while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
1673 report(", aud%d", aidx);
1676 report(", (%d)", pgrm->stream_index[j]);
1681 AVDictionaryEntry *tag = 0;
1682 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
1683 report("%s=%s\n", tag->key, tag->value);
1692 int FFMPEG::init_decoder(const char *filename)
1694 ff_lock("FFMPEG::init_decoder");
1696 char file_opts[BCTEXTLEN];
1697 char *bp = strrchr(strcpy(file_opts, filename), '/');
1698 char *sp = strrchr(!bp ? file_opts : bp, '.');
1701 strcpy(sp, ".opts");
1702 fp = fopen(file_opts, "r");
1705 read_options(fp, file_opts, opts);
1709 load_options("decode.opts", opts);
1710 AVDictionary *fopts = 0;
1711 av_dict_copy(&fopts, opts, 0);
1712 int ret = avformat_open_input(&fmt_ctx, filename, NULL, &fopts);
1713 av_dict_free(&fopts);
1715 ret = avformat_find_stream_info(fmt_ctx, NULL);
1720 return !ret ? 0 : 1;
1723 int FFMPEG::open_decoder()
1726 if( stat(fmt_ctx->filename, &st) < 0 ) {
1727 eprintf(_("can't stat file: %s\n"), fmt_ctx->filename);
1731 int64_t file_bits = 8 * st.st_size;
1732 if( !fmt_ctx->bit_rate && opt_duration > 0 )
1733 fmt_ctx->bit_rate = file_bits / opt_duration;
1736 if( fmt_ctx->bit_rate > 0 ) {
1737 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1738 AVStream *st = fmt_ctx->streams[i];
1739 if( st->duration != AV_NOPTS_VALUE ) continue;
1740 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
1741 st->duration = av_rescale(file_bits, st->time_base.den,
1742 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
1747 printf("FFMPEG::open_decoder: some stream times estimated\n");
1749 ff_lock("FFMPEG::open_decoder");
1750 int ret = 0, bad_time = 0;
1751 for( int i=0; !ret && i<(int)fmt_ctx->nb_streams; ++i ) {
1752 AVStream *st = fmt_ctx->streams[i];
1753 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
1754 AVCodecParameters *avpar = st->codecpar;
1755 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avpar->codec_id);
1756 if( !codec_desc ) continue;
1757 switch( avpar->codec_type ) {
1758 case AVMEDIA_TYPE_VIDEO: {
1759 if( avpar->width < 1 ) continue;
1760 if( avpar->height < 1 ) continue;
1761 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
1762 if( framerate.num < 1 ) continue;
1764 int vidx = ffvideo.size();
1765 FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
1766 vstrm_index.append(ffidx(vidx, 0));
1767 ffvideo.append(vid);
1768 vid->width = avpar->width;
1769 vid->height = avpar->height;
1770 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
1771 double secs = to_secs(st->duration, st->time_base);
1772 vid->length = secs * vid->frame_rate;
1773 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
1774 vid->nudge = st->start_time;
1776 if( opt_video_filter )
1777 ret = vid->create_filter(opt_video_filter, avpar);
1779 case AVMEDIA_TYPE_AUDIO: {
1780 if( avpar->channels < 1 ) continue;
1781 if( avpar->sample_rate < 1 ) continue;
1783 int aidx = ffaudio.size();
1784 FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
1785 ffaudio.append(aud);
1786 aud->channel0 = astrm_index.size();
1787 aud->channels = avpar->channels;
1788 for( int ch=0; ch<aud->channels; ++ch )
1789 astrm_index.append(ffidx(aidx, ch));
1790 aud->sample_rate = avpar->sample_rate;
1791 double secs = to_secs(st->duration, st->time_base);
1792 aud->length = secs * aud->sample_rate;
1793 aud->init_swr(aud->channels, avpar->format, aud->sample_rate);
1794 aud->nudge = st->start_time;
1796 if( opt_audio_filter )
1797 ret = aud->create_filter(opt_audio_filter, avpar);
1803 printf("FFMPEG::open_decoder: some stream have bad times\n");
1805 return ret < 0 ? -1 : 0;
1809 int FFMPEG::init_encoder(const char *filename)
1811 int fd = ::open(filename,O_WRONLY);
1812 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
1814 eprintf(_("bad file path: %s\n"), filename);
1818 int ret = get_file_format();
1820 eprintf(_("bad file format: %s\n"), filename);
1824 eprintf(_("mismatch audio/video file format: %s\n"), filename);
1827 ff_lock("FFMPEG::init_encoder");
1829 char format[BCSTRLEN];
1830 if( get_format(format, "format", file_format) )
1831 strcpy(format, file_format);
1832 avformat_alloc_output_context2(&fmt_ctx, 0, format, filename);
1834 eprintf(_("failed: %s\n"), filename);
1839 load_options("encode.opts", opts);
1845 int FFMPEG::open_encoder(const char *type, const char *spec)
1848 Asset *asset = file_base->asset;
1849 char *filename = asset->path;
1850 AVDictionary *sopts = 0;
1851 av_dict_copy(&sopts, opts, 0);
1852 char option_path[BCTEXTLEN];
1853 set_option_path(option_path, "%s/%s.opts", type, type);
1854 read_options(option_path, sopts);
1855 get_option_path(option_path, type, spec);
1856 char format_name[BCSTRLEN], codec_name[BCTEXTLEN], bsfilter[BCTEXTLEN];
1857 if( get_encoder(option_path, format_name, codec_name, bsfilter) ) {
1858 eprintf(_("get_encoder failed %s:%s\n"), option_path, filename);
1862 if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
1863 else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
1864 else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
1867 ff_lock("FFMPEG::open_encoder");
1870 AVCodecContext *ctx = 0;
1872 const AVCodecDescriptor *codec_desc = 0;
1873 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
1875 eprintf(_("cant find codec %s:%s\n"), codec_name, filename);
1879 codec_desc = avcodec_descriptor_get(codec->id);
1881 eprintf(_("unknown codec %s:%s\n"), codec_name, filename);
1886 st = avformat_new_stream(fmt_ctx, 0);
1888 eprintf(_("cant create stream %s:%s\n"), codec_name, filename);
1893 switch( codec_desc->type ) {
1894 case AVMEDIA_TYPE_AUDIO: {
1896 eprintf(_("duplicate audio %s:%s\n"), codec_name, filename);
1900 if( scan_options(asset->ff_audio_options, sopts, st) ) {
1901 eprintf(_("bad audio options %s:%s\n"), codec_name, filename);
1906 ctx = avcodec_alloc_context3(codec);
1907 if( asset->ff_audio_bitrate > 0 ) {
1908 ctx->bit_rate = asset->ff_audio_bitrate;
1910 sprintf(arg, "%d", asset->ff_audio_bitrate);
1911 av_dict_set(&sopts, "b", arg, 0);
1913 int aidx = ffaudio.size();
1914 int fidx = aidx + ffvideo.size();
1915 FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
1916 aud->avctx = ctx; ffaudio.append(aud); fst = aud;
1917 aud->sample_rate = asset->sample_rate;
1918 ctx->channels = aud->channels = asset->channels;
1919 for( int ch=0; ch<aud->channels; ++ch )
1920 astrm_index.append(ffidx(aidx, ch));
1921 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
1922 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
1923 if( !ctx->sample_rate ) {
1924 eprintf(_("check_sample_rate failed %s\n"), filename);
1928 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
1929 ctx->sample_fmt = codec->sample_fmts[0];
1930 uint64_t layout = av_get_default_channel_layout(ctx->channels);
1931 aud->resample_context = swr_alloc_set_opts(NULL,
1932 layout, ctx->sample_fmt, aud->sample_rate,
1933 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
1935 swr_init(aud->resample_context);
1938 case AVMEDIA_TYPE_VIDEO: {
1940 eprintf(_("duplicate video %s:%s\n"), codec_name, filename);
1944 if( scan_options(asset->ff_video_options, sopts, st) ) {
1945 eprintf(_("bad video options %s:%s\n"), codec_name, filename);
1950 ctx = avcodec_alloc_context3(codec);
1951 if( asset->ff_video_bitrate > 0 ) {
1952 ctx->bit_rate = asset->ff_video_bitrate;
1954 sprintf(arg, "%d", asset->ff_video_bitrate);
1955 av_dict_set(&sopts, "b", arg, 0);
1957 else if( asset->ff_video_quality >= 0 ) {
1958 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
1959 ctx->qmin = ctx->qmax = asset->ff_video_quality;
1960 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
1961 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
1962 ctx->flags |= CODEC_FLAG_QSCALE;
1964 av_dict_set(&sopts, "flags", "+qscale", 0);
1965 sprintf(arg, "%d", asset->ff_video_quality);
1966 av_dict_set(&sopts, "qscale", arg, 0);
1967 sprintf(arg, "%d", ctx->global_quality);
1968 av_dict_set(&sopts, "global_quality", arg, 0);
1970 int vidx = ffvideo.size();
1971 int fidx = vidx + ffaudio.size();
1972 FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
1973 vstrm_index.append(ffidx(vidx, 0));
1974 vid->avctx = ctx; ffvideo.append(vid); fst = vid;
1975 vid->width = asset->width;
1976 ctx->width = (vid->width+3) & ~3;
1977 vid->height = asset->height;
1978 ctx->height = (vid->height+3) & ~3;
1979 vid->frame_rate = asset->frame_rate;
1980 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
1981 ctx->pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
1982 AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
1983 if( !frame_rate.num || !frame_rate.den ) {
1984 eprintf(_("check_frame_rate failed %s\n"), filename);
1988 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
1989 st->time_base = ctx->time_base;
1991 vid->interlaced = asset->interlace_mode == ILACE_MODE_TOP_FIRST ||
1992 asset->interlace_mode == ILACE_MODE_BOTTOM_FIRST ? 1 : 0;
1993 vid->top_field_first = asset->interlace_mode == ILACE_MODE_TOP_FIRST ? 1 : 0;
1996 eprintf(_("not audio/video, %s:%s\n"), codec_name, filename);
2001 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
2002 ctx->flags |= CODEC_FLAG_GLOBAL_HEADER;
2004 av_dict_set(&sopts, "cin_bitrate", 0, 0);
2005 av_dict_set(&sopts, "cin_quality", 0, 0);
2007 if( !av_dict_get(sopts, "threads", NULL, 0) )
2008 ctx->thread_count = ff_cpus();
2009 ret = avcodec_open2(ctx, codec, &sopts);
2011 ret = avcodec_parameters_from_context(st->codecpar, ctx);
2013 fprintf(stderr, "Could not copy the stream parameters\n");
2016 ff_err(ret,"FFMPEG::open_encoder");
2017 eprintf(_("open failed %s:%s\n"), codec_name, filename);
2023 if( !ret && fst && bsfilter[0] ) {
2024 ret = av_bsf_list_parse_str(bsfilter, &fst->bsfc);
2026 ff_err(ret,"FFMPEG::open_encoder");
2027 eprintf(_("bitstream filter failed %s:\n%s\n"), filename, bsfilter);
2038 av_dict_free(&sopts);
2042 int FFMPEG::close_encoder()
2045 if( encoding > 0 ) {
2046 av_write_trailer(fmt_ctx);
2047 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
2048 avio_closep(&fmt_ctx->pb);
2054 int FFMPEG::decode_activate()
2056 if( decoding < 0 ) {
2058 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
2059 ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
2060 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
2061 ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
2062 // set nudges for each program stream set
2063 const int64_t min_nudge = INT64_MIN+1;
2064 int npgrms = fmt_ctx->nb_programs;
2065 for( int i=0; i<npgrms; ++i ) {
2066 AVProgram *pgrm = fmt_ctx->programs[i];
2067 // first start time video stream
2068 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2069 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2070 int fidx = pgrm->stream_index[j];
2071 AVStream *st = fmt_ctx->streams[fidx];
2072 AVCodecParameters *avpar = st->codecpar;
2073 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2074 if( st->start_time == AV_NOPTS_VALUE ) continue;
2075 if( vstart_time < st->start_time )
2076 vstart_time = st->start_time;
2079 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2080 if( st->start_time == AV_NOPTS_VALUE ) continue;
2081 if( astart_time < st->start_time )
2082 astart_time = st->start_time;
2086 //since frame rate is much more grainy than sample rate, it is better to
2087 // align using video, so that total absolute error is minimized.
2088 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2089 astart_time > min_nudge ? astart_time : AV_NOPTS_VALUE;
2090 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2091 int fidx = pgrm->stream_index[j];
2092 AVStream *st = fmt_ctx->streams[fidx];
2093 AVCodecParameters *avpar = st->codecpar;
2094 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2095 for( int k=0; k<ffvideo.size(); ++k ) {
2096 if( ffvideo[k]->fidx != fidx ) continue;
2097 ffvideo[k]->nudge = nudge;
2101 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2102 for( int k=0; k<ffaudio.size(); ++k ) {
2103 if( ffaudio[k]->fidx != fidx ) continue;
2104 ffaudio[k]->nudge = nudge;
2110 // set nudges for any streams not yet set
2111 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2112 int nstreams = fmt_ctx->nb_streams;
2113 for( int i=0; i<nstreams; ++i ) {
2114 AVStream *st = fmt_ctx->streams[i];
2115 AVCodecParameters *avpar = st->codecpar;
2116 switch( avpar->codec_type ) {
2117 case AVMEDIA_TYPE_VIDEO: {
2118 if( st->start_time == AV_NOPTS_VALUE ) continue;
2119 int vidx = ffvideo.size();
2120 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
2121 if( vidx < 0 ) continue;
2122 if( ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
2123 if( vstart_time < st->start_time )
2124 vstart_time = st->start_time;
2126 case AVMEDIA_TYPE_AUDIO: {
2127 if( st->start_time == AV_NOPTS_VALUE ) continue;
2128 int aidx = ffaudio.size();
2129 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
2130 if( aidx < 0 ) continue;
2131 if( ffaudio[aidx]->frame_sz < avpar->frame_size )
2132 ffaudio[aidx]->frame_sz = avpar->frame_size;
2133 if( ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
2134 if( astart_time < st->start_time )
2135 astart_time = st->start_time;
2140 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2141 astart_time > min_nudge ? astart_time : 0;
2142 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
2143 if( ffvideo[vidx]->nudge == AV_NOPTS_VALUE )
2144 ffvideo[vidx]->nudge = nudge;
2146 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2147 if( ffaudio[aidx]->nudge == AV_NOPTS_VALUE )
2148 ffaudio[aidx]->nudge = nudge;
2155 int FFMPEG::encode_activate()
2158 if( encoding < 0 ) {
2160 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
2161 (ret=avio_open(&fmt_ctx->pb, fmt_ctx->filename, AVIO_FLAG_WRITE)) < 0 ) {
2162 ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
2168 AVProgram *prog = av_new_program(fmt_ctx, prog_id);
2169 for( int i=0; i< ffvideo.size(); ++i )
2170 av_program_add_stream_index(fmt_ctx, prog_id, ffvideo[i]->fidx);
2171 for( int i=0; i< ffaudio.size(); ++i )
2172 av_program_add_stream_index(fmt_ctx, prog_id, ffaudio[i]->fidx);
2173 int pi = fmt_ctx->nb_programs;
2174 while( --pi >= 0 && fmt_ctx->programs[pi]->id != prog_id );
2175 AVDictionary **meta = &prog->metadata;
2176 av_dict_set(meta, "service_provider", "cin5", 0);
2177 const char *path = fmt_ctx->filename, *bp = strrchr(path,'/');
2178 if( bp ) path = bp + 1;
2179 av_dict_set(meta, "title", path, 0);
2181 if( ffaudio.size() ) {
2182 const char *ep = getenv("CIN_AUDIO_LANG"), *lp = 0;
2183 if( !ep && (lp=getenv("LANG")) ) { // some are guesses
2184 static struct { const char lc[3], lng[4]; } lcode[] = {
2185 { "en", "eng" }, { "de", "ger" }, { "es", "spa" },
2186 { "eu", "bas" }, { "fr", "fre" }, { "el", "gre" },
2187 { "hi", "hin" }, { "it", "ita" }, { "ja", "jap" },
2188 { "ko", "kor" }, { "du", "dut" }, { "pl", "pol" },
2189 { "pt", "por" }, { "ru", "rus" }, { "sl", "slv" },
2190 { "uk", "ukr" }, { "vi", "vie" }, { "zh", "chi" },
2192 for( int i=sizeof(lcode)/sizeof(lcode[0]); --i>=0 && !ep; )
2193 if( !strncmp(lcode[i].lc,lp,2) ) ep = lcode[i].lng;
2195 if( !ep ) ep = "und";
2197 strncpy(lang,ep,3); lang[3] = 0;
2198 AVStream *st = ffaudio[0]->st;
2199 av_dict_set(&st->metadata,"language",lang,0);
2202 AVDictionary *fopts = 0;
2203 char option_path[BCTEXTLEN];
2204 set_option_path(option_path, "format/%s", file_format);
2205 read_options(option_path, fopts, 1);
2206 ret = avformat_write_header(fmt_ctx, &fopts);
2208 ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
2212 av_dict_free(&fopts);
2219 int FFMPEG::audio_seek(int stream, int64_t pos)
2221 int aidx = astrm_index[stream].st_idx;
2222 FFAudioStream *aud = ffaudio[aidx];
2223 aud->audio_seek(pos);
2227 int FFMPEG::video_seek(int stream, int64_t pos)
2229 int vidx = vstrm_index[stream].st_idx;
2230 FFVideoStream *vid = ffvideo[vidx];
2231 vid->video_seek(pos);
2236 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
2238 if( !has_audio || chn >= astrm_index.size() ) return -1;
2239 int aidx = astrm_index[chn].st_idx;
2240 FFAudioStream *aud = ffaudio[aidx];
2241 if( aud->load(pos, len) < len ) return -1;
2242 int ch = astrm_index[chn].st_ch;
2243 int ret = aud->read(samples,len,ch);
2247 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
2249 if( !has_video || layer >= vstrm_index.size() ) return -1;
2250 int vidx = vstrm_index[layer].st_idx;
2251 FFVideoStream *vid = ffvideo[vidx];
2252 return vid->load(vframe, pos);
2256 int FFMPEG::encode(int stream, double **samples, int len)
2258 FFAudioStream *aud = ffaudio[stream];
2259 return aud->encode(samples, len);
2263 int FFMPEG::encode(int stream, VFrame *frame)
2265 FFVideoStream *vid = ffvideo[stream];
2266 return vid->encode(frame);
2269 void FFMPEG::start_muxer()
2277 void FFMPEG::stop_muxer()
2286 void FFMPEG::flow_off()
2289 flow_lock->lock("FFMPEG::flow_off");
2293 void FFMPEG::flow_on()
2297 flow_lock->unlock();
2300 void FFMPEG::flow_ctl()
2303 flow_lock->lock("FFMPEG::flow_ctl");
2304 flow_lock->unlock();
2308 int FFMPEG::mux_audio(FFrame *frm)
2310 FFStream *fst = frm->fst;
2311 AVCodecContext *ctx = fst->avctx;
2312 AVFrame *frame = *frm;
2313 AVRational tick_rate = {1, ctx->sample_rate};
2314 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
2315 int ret = fst->encode_frame(frame);
2317 ff_err(ret, "FFMPEG::mux_audio");
2318 return ret >= 0 ? 0 : 1;
2321 int FFMPEG::mux_video(FFrame *frm)
2323 FFStream *fst = frm->fst;
2324 AVFrame *frame = *frm;
2325 frame->pts = frm->position;
2326 int ret = fst->encode_frame(frame);
2328 ff_err(ret, "FFMPEG::mux_video");
2329 return ret >= 0 ? 0 : 1;
2335 double atm = -1, vtm = -1;
2336 FFrame *afrm = 0, *vfrm = 0;
2338 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
2339 FFStream *fst = ffaudio[i];
2340 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
2341 FFrame *frm = fst->frms.first;
2342 if( !frm ) { if( !done ) return; continue; }
2343 double tm = to_secs(frm->position, fst->avctx->time_base);
2344 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
2346 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
2347 FFStream *fst = ffvideo[i];
2348 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
2349 FFrame *frm = fst->frms.first;
2350 if( !frm ) { if( !done ) return; continue; }
2351 double tm = to_secs(frm->position, fst->avctx->time_base);
2352 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
2354 if( !demand ) flow_off();
2355 if( !afrm && !vfrm ) break;
2356 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
2357 vfrm->position, vfrm->fst->avctx->time_base,
2358 afrm->position, afrm->fst->avctx->time_base);
2359 FFrame *frm = v <= 0 ? vfrm : afrm;
2360 if( frm == afrm ) mux_audio(frm);
2361 if( frm == vfrm ) mux_video(frm);
2370 mux_lock->lock("FFMPEG::run");
2373 for( int i=0; i<ffaudio.size(); ++i )
2374 ffaudio[i]->drain();
2375 for( int i=0; i<ffvideo.size(); ++i )
2376 ffvideo[i]->drain();
2378 for( int i=0; i<ffaudio.size(); ++i )
2379 ffaudio[i]->flush();
2380 for( int i=0; i<ffvideo.size(); ++i )
2381 ffvideo[i]->flush();
2385 int FFMPEG::ff_total_audio_channels()
2387 return astrm_index.size();
2390 int FFMPEG::ff_total_astreams()
2392 return ffaudio.size();
2395 int FFMPEG::ff_audio_channels(int stream)
2397 return ffaudio[stream]->channels;
2400 int FFMPEG::ff_sample_rate(int stream)
2402 return ffaudio[stream]->sample_rate;
2405 const char* FFMPEG::ff_audio_format(int stream)
2407 AVStream *st = ffaudio[stream]->st;
2408 AVCodecID id = st->codecpar->codec_id;
2409 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2410 return desc ? desc->name : _("Unknown");
2413 int FFMPEG::ff_audio_pid(int stream)
2415 return ffaudio[stream]->st->id;
2418 int64_t FFMPEG::ff_audio_samples(int stream)
2420 return ffaudio[stream]->length;
2423 // find audio astream/channels with this program,
2424 // or all program audio channels (astream=-1)
2425 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
2429 int vidx = ffvideo[vstream]->fidx;
2430 // find first program with this video stream
2431 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
2432 AVProgram *pgrm = fmt_ctx->programs[i];
2433 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
2434 int st_idx = pgrm->stream_index[j];
2435 AVStream *st = fmt_ctx->streams[st_idx];
2436 if( st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
2437 if( st_idx == vidx ) pidx = i;
2440 if( pidx < 0 ) return -1;
2442 int64_t channels = 0;
2443 AVProgram *pgrm = fmt_ctx->programs[pidx];
2444 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2445 int aidx = pgrm->stream_index[j];
2446 AVStream *st = fmt_ctx->streams[aidx];
2447 if( st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
2448 if( astream > 0 ) { --astream; continue; }
2450 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
2451 if( ffaudio[i]->fidx == aidx ) astrm = i;
2453 if( ret < 0 ) ret = astrm;
2454 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
2455 channels |= mask << ffaudio[astrm]->channel0;
2457 if( !astream ) break;
2459 channel_mask = channels;
2464 int FFMPEG::ff_total_video_layers()
2466 return vstrm_index.size();
2469 int FFMPEG::ff_total_vstreams()
2471 return ffvideo.size();
2474 int FFMPEG::ff_video_width(int stream)
2476 return ffvideo[stream]->width;
2479 int FFMPEG::ff_video_height(int stream)
2481 return ffvideo[stream]->height;
2484 int FFMPEG::ff_set_video_width(int stream, int width)
2486 int w = ffvideo[stream]->width;
2487 ffvideo[stream]->width = width;
2491 int FFMPEG::ff_set_video_height(int stream, int height)
2493 int h = ffvideo[stream]->height;
2494 ffvideo[stream]->height = height;
2498 int FFMPEG::ff_coded_width(int stream)
2500 return ffvideo[stream]->avctx->coded_width;
2503 int FFMPEG::ff_coded_height(int stream)
2505 return ffvideo[stream]->avctx->coded_height;
2508 float FFMPEG::ff_aspect_ratio(int stream)
2510 return ffvideo[stream]->aspect_ratio;
2513 const char* FFMPEG::ff_video_format(int stream)
2515 AVStream *st = ffvideo[stream]->st;
2516 AVCodecID id = st->codecpar->codec_id;
2517 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2518 return desc ? desc->name : _("Unknown");
2521 double FFMPEG::ff_frame_rate(int stream)
2523 return ffvideo[stream]->frame_rate;
2526 int64_t FFMPEG::ff_video_frames(int stream)
2528 return ffvideo[stream]->length;
2531 int FFMPEG::ff_video_pid(int stream)
2533 return ffvideo[stream]->st->id;
2537 int FFMPEG::ff_cpus()
2539 return file_base->file->cpus;
2542 int FFVideoStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
2544 avfilter_register_all();
2545 const char *sp = filter_spec;
2546 char filter_name[BCSTRLEN], *np = filter_name;
2547 int i = sizeof(filter_name);
2548 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
2550 AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
2551 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_VIDEO ) {
2552 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
2555 filter_graph = avfilter_graph_alloc();
2556 AVFilter *buffersrc = avfilter_get_by_name("buffer");
2557 AVFilter *buffersink = avfilter_get_by_name("buffersink");
2559 int ret = 0; char args[BCTEXTLEN];
2560 AVPixelFormat pix_fmt = (AVPixelFormat)avpar->format;
2561 snprintf(args, sizeof(args),
2562 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
2563 avpar->width, avpar->height, (int)pix_fmt,
2564 st->time_base.num, st->time_base.den,
2565 avpar->sample_aspect_ratio.num, avpar->sample_aspect_ratio.den);
2567 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2568 args, NULL, filter_graph);
2570 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2571 NULL, NULL, filter_graph);
2573 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
2574 (uint8_t*)&pix_fmt, sizeof(pix_fmt),
2575 AV_OPT_SEARCH_CHILDREN);
2577 ff_err(ret, "FFVideoStream::create_filter");
2579 ret = FFStream::create_filter(filter_spec);
2580 return ret >= 0 ? 0 : -1;
2583 int FFAudioStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
2585 avfilter_register_all();
2586 const char *sp = filter_spec;
2587 char filter_name[BCSTRLEN], *np = filter_name;
2588 int i = sizeof(filter_name);
2589 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
2591 AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
2592 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_AUDIO ) {
2593 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
2596 filter_graph = avfilter_graph_alloc();
2597 AVFilter *buffersrc = avfilter_get_by_name("abuffer");
2598 AVFilter *buffersink = avfilter_get_by_name("abuffersink");
2599 int ret = 0; char args[BCTEXTLEN];
2600 AVSampleFormat sample_fmt = (AVSampleFormat)avpar->format;
2601 snprintf(args, sizeof(args),
2602 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
2603 st->time_base.num, st->time_base.den, avpar->sample_rate,
2604 av_get_sample_fmt_name(sample_fmt), avpar->channel_layout);
2606 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2607 args, NULL, filter_graph);
2609 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2610 NULL, NULL, filter_graph);
2612 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
2613 (uint8_t*)&sample_fmt, sizeof(sample_fmt),
2614 AV_OPT_SEARCH_CHILDREN);
2616 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
2617 (uint8_t*)&avpar->channel_layout,
2618 sizeof(avpar->channel_layout), AV_OPT_SEARCH_CHILDREN);
2620 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
2621 (uint8_t*)&sample_rate, sizeof(sample_rate),
2622 AV_OPT_SEARCH_CHILDREN);
2624 ff_err(ret, "FFAudioStream::create_filter");
2626 ret = FFStream::create_filter(filter_spec);
2627 return ret >= 0 ? 0 : -1;
2630 int FFStream::create_filter(const char *filter_spec)
2632 /* Endpoints for the filter graph. */
2633 AVFilterInOut *outputs = avfilter_inout_alloc();
2634 outputs->name = av_strdup("in");
2635 outputs->filter_ctx = buffersrc_ctx;
2636 outputs->pad_idx = 0;
2639 AVFilterInOut *inputs = avfilter_inout_alloc();
2640 inputs->name = av_strdup("out");
2641 inputs->filter_ctx = buffersink_ctx;
2642 inputs->pad_idx = 0;
2645 int ret = !outputs->name || !inputs->name ? -1 : 0;
2647 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
2648 &inputs, &outputs, NULL);
2650 ret = avfilter_graph_config(filter_graph, NULL);
2653 ff_err(ret, "FFStream::create_filter");
2654 avfilter_graph_free(&filter_graph);
2657 avfilter_inout_free(&inputs);
2658 avfilter_inout_free(&outputs);
2662 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
2665 av_init_packet(&pkt);
2666 AVFrame *frame = av_frame_alloc();
2668 fprintf(stderr,"FFMPEG::scan: ");
2669 fprintf(stderr,_("av_frame_alloc failed\n"));
2673 index_state->add_video_markers(ffvideo.size());
2674 index_state->add_audio_markers(ffaudio.size());
2676 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2678 AVDictionary *copts = 0;
2679 av_dict_copy(&copts, opts, 0);
2680 AVStream *st = fmt_ctx->streams[i];
2681 AVCodecID codec_id = st->codecpar->codec_id;
2682 AVCodec *decoder = avcodec_find_decoder(codec_id);
2683 AVCodecContext *avctx = avcodec_alloc_context3(decoder);
2685 eprintf(_("cant allocate codec context\n"));
2686 ret = AVERROR(ENOMEM);
2689 avcodec_parameters_to_context(avctx, st->codecpar);
2690 if( !av_dict_get(copts, "threads", NULL, 0) )
2691 avctx->thread_count = ff_cpus();
2692 ret = avcodec_open2(avctx, decoder, &copts);
2694 av_dict_free(&copts);
2696 AVCodecParameters *avpar = st->codecpar;
2697 switch( avpar->codec_type ) {
2698 case AVMEDIA_TYPE_VIDEO: {
2699 int vidx = ffvideo.size();
2700 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
2701 if( vidx < 0 ) break;
2702 ffvideo[vidx]->avctx = avctx;
2704 case AVMEDIA_TYPE_AUDIO: {
2705 int aidx = ffaudio.size();
2706 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
2707 if( aidx < 0 ) break;
2708 ffaudio[aidx]->avctx = avctx;
2713 fprintf(stderr,"FFMPEG::scan: ");
2714 fprintf(stderr,_("codec open failed\n"));
2715 avcodec_free_context(&avctx);
2719 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2720 AVStream *st = fmt_ctx->streams[i];
2721 AVCodecParameters *avpar = st->codecpar;
2722 if( avpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
2723 int64_t tstmp = st->start_time;
2724 if( tstmp == AV_NOPTS_VALUE ) continue;
2725 int aidx = ffaudio.size();
2726 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
2727 if( aidx < 0 ) continue;
2728 FFAudioStream *aud = ffaudio[aidx];
2729 tstmp -= aud->nudge;
2730 double secs = to_secs(tstmp, st->time_base);
2731 aud->curr_pos = secs * aud->sample_rate + 0.5;
2735 for( int64_t count=0; !*canceled; ++count ) {
2736 av_packet_unref(&pkt);
2737 pkt.data = 0; pkt.size = 0;
2739 int ret = av_read_frame(fmt_ctx, &pkt);
2741 if( ret == AVERROR_EOF ) break;
2742 if( ++errs > 100 ) {
2743 ff_err(ret,_("over 100 read_frame errs\n"));
2748 if( !pkt.data ) continue;
2749 int i = pkt.stream_index;
2750 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
2751 AVStream *st = fmt_ctx->streams[i];
2752 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
2754 AVCodecParameters *avpar = st->codecpar;
2755 switch( avpar->codec_type ) {
2756 case AVMEDIA_TYPE_VIDEO: {
2757 int vidx = ffvideo.size();
2758 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
2759 if( vidx < 0 ) break;
2760 FFVideoStream *vid = ffvideo[vidx];
2761 if( !vid->avctx ) break;
2762 int64_t tstmp = pkt.dts;
2763 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.pts;
2764 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
2765 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
2766 double secs = to_secs(tstmp, st->time_base);
2767 int64_t frm = secs * vid->frame_rate + 0.5;
2768 if( frm < 0 ) frm = 0;
2769 index_state->put_video_mark(vidx, frm, pkt.pos);
2772 ret = avcodec_send_packet(vid->avctx, pkt);
2773 if( ret < 0 ) break;
2774 while( (ret=vid->decode_frame(frame)) > 0 ) {}
2777 case AVMEDIA_TYPE_AUDIO: {
2778 int aidx = ffaudio.size();
2779 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
2780 if( aidx < 0 ) break;
2781 FFAudioStream *aud = ffaudio[aidx];
2782 if( !aud->avctx ) break;
2783 int64_t tstmp = pkt.pts;
2784 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
2785 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
2786 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
2787 double secs = to_secs(tstmp, st->time_base);
2788 int64_t sample = secs * aud->sample_rate + 0.5;
2790 index_state->put_audio_mark(aidx, sample, pkt.pos);
2792 ret = avcodec_send_packet(aud->avctx, &pkt);
2793 if( ret < 0 ) break;
2794 int ch = aud->channel0, nch = aud->channels;
2795 int64_t pos = index_state->pos(ch);
2796 if( pos != aud->curr_pos ) {
2797 if( abs(pos-aud->curr_pos) > 1 )
2798 printf("audio%d pad %jd %jd (%jd)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
2799 index_state->pad_data(ch, nch, aud->curr_pos);
2801 while( (ret=aud->decode_frame(frame)) > 0 ) {
2802 //if( frame->channels != nch ) break;
2803 aud->init_swr(frame->channels, frame->format, frame->sample_rate);
2805 int len = aud->get_samples(samples,
2806 &frame->extended_data[0], frame->nb_samples);
2807 pos = aud->curr_pos;
2808 if( (aud->curr_pos += len) >= 0 ) {
2810 samples += -pos * nch;
2811 len = aud->curr_pos;
2813 for( int i=0; i<nch; ++i )
2814 index_state->put_data(ch+i,nch,samples+i,len);
2821 av_frame_free(&frame);
2825 void FFStream::load_markers(IndexMarks &marks, double rate)
2828 int64_t sz = marks.size();
2829 int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
2830 int nb_ent = st->nb_index_entries;
2831 // some formats already have an index
2833 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
2834 int64_t tstmp = ep->timestamp;
2835 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
2836 double secs = ffmpeg->to_secs(tstmp, st->time_base);
2837 int64_t no = secs * rate;
2838 while( in < sz && marks[in].no <= no ) ++in;
2840 int64_t len = sz - in;
2841 int64_t count = max_entries - nb_ent;
2842 if( count > len ) count = len;
2843 for( int i=0; i<count; ++i ) {
2844 int k = in + i * len / count;
2845 int64_t no = marks[k].no, pos = marks[k].pos;
2846 double secs = (double)no / rate;
2847 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
2848 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
2849 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);