12 // work arounds (centos)
15 #define INT64_MAX 9223372036854775807LL
17 #define MAX_RETRY 1000
20 #include "bccmodels.h"
23 #include "edlsession.h"
25 #include "fileffmpeg.h"
26 #include "filesystem.h"
28 #include "indexfile.h"
29 #include "interlacemodes.h"
32 #include "mainerror.h"
37 #define VIDEO_INBUF_SIZE 0x10000
38 #define AUDIO_INBUF_SIZE 0x10000
39 #define VIDEO_REFILL_THRESH 0
40 #define AUDIO_REFILL_THRESH 0x1000
41 #define AUDIO_MIN_FRAME_SZ 128
43 Mutex FFMPEG::fflock("FFMPEG::fflock");
45 static void ff_err(int ret, const char *fmt, ...)
50 vsnprintf(msg, sizeof(msg), fmt, ap);
52 char errmsg[BCSTRLEN];
53 av_strerror(ret, errmsg, sizeof(errmsg));
54 fprintf(stderr,_("%s err: %s\n"),msg, errmsg);
60 pkt.data = 0; pkt.size = 0;
62 void FFPacket::finit()
64 av_packet_unref(&pkt);
67 FFrame::FFrame(FFStream *fst)
70 frm = av_frame_alloc();
71 init = fst->init_frame(frm);
79 void FFrame::queue(int64_t pos)
85 void FFrame::dequeue()
90 int FFAudioStream::read(float *fp, long len)
98 while( --k >= 0 ) *fp++ = *op++;
99 if( op >= lmt ) op = bfr;
104 void FFAudioStream::realloc(long nsz, int nch, long len)
106 long bsz = nsz * nch;
107 float *np = new float[bsz];
108 inp = np + read(np, len) * nch;
113 delete [] bfr; bfr = np;
116 void FFAudioStream::realloc(long nsz, int nch)
118 if( nsz > sz || this->nch != nch ) {
119 long len = this->nch != nch ? 0 : hpos;
120 if( len > sz ) len = sz;
122 realloc(nsz, nch, len);
126 void FFAudioStream::reserve(long nsz, int nch)
128 long len = (inp - outp) / nch;
130 if( nsz > sz || this->nch != nch ) {
131 if( this->nch != nch ) len = 0;
132 realloc(nsz, nch, len);
135 if( (len*=nch) > 0 && bfr != outp )
136 memmove(bfr, outp, len*sizeof(*bfr));
141 long FFAudioStream::used()
143 long len = inp>=outp ? inp-outp : inp-bfr + lmt-outp;
146 long FFAudioStream::avail()
149 if( in1 >= lmt ) in1 = bfr;
150 long len = outp >= in1 ? outp-in1 : outp-bfr + lmt-in1;
153 void FFAudioStream::reset_history()
157 memset(bfr, 0, lmt-bfr);
160 void FFAudioStream::iseek(int64_t ofs)
162 if( ofs > hpos ) ofs = hpos;
163 if( ofs > sz ) ofs = sz;
164 outp = inp - ofs*nch;
165 if( outp < bfr ) outp += sz*nch;
168 float *FFAudioStream::get_outp(int ofs)
175 int64_t FFAudioStream::put_inp(int ofs)
178 return (inp-outp) / nch;
181 int FFAudioStream::write(const float *fp, long len)
189 while( --k >= 0 ) *ip++ = *fp++;
190 if( ip >= lmt ) ip = bfr;
197 int FFAudioStream::zero(long len)
205 while( --k >= 0 ) *ip++ = 0;
206 if( ip >= lmt ) ip = bfr;
213 // does not advance outp
214 int FFAudioStream::read(double *dp, long len, int ch)
217 float *op = outp + ch;
218 float *lmt1 = lmt + nch-1;
220 int k = (lmt1 - op) / nch;
223 while( --k >= 0 ) { *dp++ = *op; op += nch; }
224 if( op >= lmt ) op -= sz*nch;
229 // load linear buffer, no wrapping allowed, does not advance inp
230 int FFAudioStream::write(const double *dp, long len, int ch)
233 float *ip = inp + ch;
234 while( --n >= 0 ) { *ip = *dp++; ip += nch; }
239 FFStream::FFStream(FFMPEG *ffmpeg, AVStream *st, int fidx)
241 this->ffmpeg = ffmpeg;
244 frm_lock = new Mutex("FFStream::frm_lock");
251 nudge = AV_NOPTS_VALUE;
252 seek_pos = curr_pos = 0;
254 reading = writing = 0;
265 FFStream::~FFStream()
267 if( reading > 0 || writing > 0 ) avcodec_close(avctx);
268 if( avctx ) avcodec_free_context(&avctx);
269 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
270 if( bsfc ) av_bsf_free(&bsfc);
271 while( frms.first ) frms.remove(frms.first);
272 if( filter_graph ) avfilter_graph_free(&filter_graph);
273 if( frame ) av_frame_free(&frame);
274 if( fframe ) av_frame_free(&fframe);
276 if( stats_fp ) fclose(stats_fp);
277 if( stats_in ) av_freep(&stats_in);
278 delete [] stats_filename;
281 void FFStream::ff_lock(const char *cp)
283 FFMPEG::fflock.lock(cp);
286 void FFStream::ff_unlock()
288 FFMPEG::fflock.unlock();
291 void FFStream::queue(FFrame *frm)
293 frm_lock->lock("FFStream::queue");
297 ffmpeg->mux_lock->unlock();
300 void FFStream::dequeue(FFrame *frm)
302 frm_lock->lock("FFStream::dequeue");
304 frms.remove_pointer(frm);
308 int FFStream::encode_activate()
311 writing = ffmpeg->encode_activate();
315 int FFStream::decode_activate()
317 if( reading < 0 && (reading=ffmpeg->decode_activate()) > 0 ) {
318 ff_lock("FFStream::decode_activate");
320 AVDictionary *copts = 0;
321 av_dict_copy(&copts, ffmpeg->opts, 0);
323 // this should be avformat_copy_context(), but no copy avail
324 ret = avformat_open_input(&fmt_ctx, ffmpeg->fmt_ctx->filename, NULL, &copts);
326 ret = avformat_find_stream_info(fmt_ctx, 0);
327 st = fmt_ctx->streams[fidx];
330 if( ret >= 0 && st != 0 ) {
331 AVCodecID codec_id = st->codecpar->codec_id;
332 AVCodec *decoder = avcodec_find_decoder(codec_id);
333 avctx = avcodec_alloc_context3(decoder);
335 eprintf(_("cant allocate codec context\n"));
336 ret = AVERROR(ENOMEM);
339 av_codec_set_pkt_timebase(avctx, st->time_base);
340 if( decoder->capabilities & AV_CODEC_CAP_DR1 )
341 avctx->flags |= CODEC_FLAG_EMU_EDGE;
342 avcodec_parameters_to_context(avctx, st->codecpar);
343 if( !av_dict_get(copts, "threads", NULL, 0) )
344 avctx->thread_count = ffmpeg->ff_cpus();
345 ret = avcodec_open2(avctx, decoder, &copts);
351 eprintf(_("open decoder failed\n"));
354 eprintf(_("can't clone input file\n"));
355 av_dict_free(&copts);
361 int FFStream::read_packet()
363 av_packet_unref(ipkt);
364 int ret = av_read_frame(fmt_ctx, ipkt);
367 if( ret == AVERROR_EOF ) return 0;
368 ff_err(ret, "FFStream::read_packet: av_read_frame failed\n");
375 int FFStream::decode(AVFrame *frame)
378 int retries = MAX_RETRY;
380 while( ret >= 0 && !flushed && --retries >= 0 ) {
382 if( (ret=read_packet()) < 0 ) break;
383 AVPacket *pkt = ret > 0 ? (AVPacket*)ipkt : 0;
385 if( pkt->stream_index != st->index ) continue;
386 if( !pkt->data | !pkt->size ) continue;
388 if( (ret=avcodec_send_packet(avctx, pkt)) < 0 ) {
389 ff_err(ret, "FFStream::decode: avcodec_send_packet failed\n");
395 if( (ret=decode_frame(frame)) > 0 ) break;
403 fprintf(stderr, "FFStream::decode: Retry limit\n");
407 fprintf(stderr, "FFStream::decode: failed\n");
411 int FFStream::load_filter(AVFrame *frame)
413 int ret = av_buffersrc_add_frame_flags(buffersrc_ctx, frame, 0);
415 eprintf(_("av_buffersrc_add_frame_flags failed\n"));
419 int FFStream::read_filter(AVFrame *frame)
421 int ret = av_buffersink_get_frame(buffersink_ctx, frame);
423 if( ret == AVERROR(EAGAIN) ) return 0;
424 if( ret == AVERROR_EOF ) { st_eof(1); return -1; }
425 ff_err(ret, "FFStream::read_filter: av_buffersink_get_frame failed\n");
431 int FFStream::read_frame(AVFrame *frame)
433 av_frame_unref(frame);
434 if( !filter_graph || !buffersrc_ctx || !buffersink_ctx )
435 return decode(frame);
436 if( !fframe && !(fframe=av_frame_alloc()) ) {
437 fprintf(stderr, "FFStream::read_frame: av_frame_alloc failed\n");
441 while( !flushed && !(ret=read_filter(frame)) ) {
442 if( (ret=decode(fframe)) < 0 ) break;
443 if( ret > 0 && (ret=load_filter(fframe)) < 0 ) break;
448 int FFStream::write_packet(FFPacket &pkt)
452 av_packet_rescale_ts(pkt, avctx->time_base, st->time_base);
453 pkt->stream_index = st->index;
454 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, pkt);
457 ret = av_bsf_send_packet(bsfc, pkt);
460 if( (ret=av_bsf_receive_packet(bsfc, bs)) < 0 ) {
461 if( ret == AVERROR(EAGAIN) ) return 0;
462 if( ret == AVERROR_EOF ) return -1;
465 av_packet_rescale_ts(bs, avctx->time_base, st->time_base);
466 bs->stream_index = st->index;
467 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, bs);
471 ff_err(ret, "FFStream::write_packet: write packet failed\n");
475 int FFStream::encode_frame(AVFrame *frame)
477 int pkts = 0, ret = 0;
478 for( int retry=100; --retry>=0; ) {
480 ret = avcodec_send_frame(avctx, frame);
481 if( !ret && frame ) return pkts;
482 if( ret < 0 && ret != AVERROR(EAGAIN) ) break;
484 ret = avcodec_receive_packet(avctx, opkt);
485 if( !frame && ret == AVERROR_EOF ) return pkts;
487 ret = write_packet(opkt);
490 if( frame && stats_fp ) {
491 ret = write_stats_file();
495 ff_err(ret, "FFStream::encode_frame: encode failed\n");
499 int FFStream::flush()
503 int ret = encode_frame(0);
504 if( ret >= 0 && stats_fp ) {
505 ret = write_stats_file();
509 ff_err(ret, "FFStream::flush");
510 return ret >= 0 ? 0 : 1;
514 int FFStream::open_stats_file()
516 stats_fp = fopen(stats_filename,"w");
517 return stats_fp ? 0 : AVERROR(errno);
520 int FFStream::close_stats_file()
523 fclose(stats_fp); stats_fp = 0;
528 int FFStream::read_stats_file()
530 int64_t len = 0; struct stat stats_st;
531 int fd = open(stats_filename, O_RDONLY);
532 int ret = fd >= 0 ? 0: ENOENT;
533 if( !ret && fstat(fd, &stats_st) )
536 len = stats_st.st_size;
537 stats_in = (char *)av_malloc(len+1);
541 if( !ret && read(fd, stats_in, len+1) != len )
545 avctx->stats_in = stats_in;
549 return !ret ? 0 : AVERROR(ret);
552 int FFStream::write_stats_file()
555 if( avctx->stats_out && (ret=strlen(avctx->stats_out)) > 0 ) {
556 int len = fwrite(avctx->stats_out, 1, ret, stats_fp);
558 ff_err(ret = AVERROR(errno), "FFStream::write_stats_file");
563 int FFStream::init_stats_file()
566 if( (pass & 2) && (ret = read_stats_file()) < 0 )
567 ff_err(ret, "stat file read: %s", stats_filename);
568 if( (pass & 1) && (ret=open_stats_file()) < 0 )
569 ff_err(ret, "stat file open: %s", stats_filename);
570 return ret >= 0 ? 0 : ret;
573 int FFStream::seek(int64_t no, double rate)
575 // default ffmpeg native seek
577 int64_t pos = no, pkt_pos = -1;
578 IndexMarks *index_markers = get_markers();
579 if( index_markers && index_markers->size() > 1 ) {
580 IndexMarks &marks = *index_markers;
581 int i = marks.find(pos);
582 int64_t n = i < 0 ? (i=0) : marks[i].no;
583 // if indexed seek point not too far away (<30 secs), use index
584 if( no-n < 30*rate ) {
587 if( i < marks.size() ) pkt_pos = marks[i].pos;
591 if( pos == curr_pos ) return 0;
592 double secs = pos < 0 ? 0. : pos / rate;
593 AVRational time_base = st->time_base;
594 int64_t tstmp = time_base.num > 0 ? secs * time_base.den/time_base.num : 0;
596 if( st->nb_index_entries > 0 ) tstmp = st->index_entries[0].timestamp;
597 else if( st->start_time != AV_NOPTS_VALUE ) tstmp = st->start_time;
598 else if( st->first_dts != AV_NOPTS_VALUE ) tstmp = st->first_dts;
599 else tstmp = INT64_MIN+1;
601 else if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
604 // seek all streams using the default timebase.
605 // this is how ffmpeg and ffplay work. stream seeks are less tested.
606 tstmp = av_rescale_q(tstmp, time_base, AV_TIME_BASE_Q);
610 avcodec_flush_buffers(avctx);
611 avformat_flush(fmt_ctx);
613 int64_t seek = tstmp;
614 int flags = AVSEEK_FLAG_ANY;
615 if( !(fmt_ctx->iformat->flags & AVFMT_NO_BYTE_SEEK) && pkt_pos >= 0 ) {
617 flags = AVSEEK_FLAG_BYTE;
619 int ret = avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, seek, INT64_MAX, flags);
621 // finds the first index frame below the target time
622 int flags = AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_ANY;
623 int ret = av_seek_frame(fmt_ctx, idx, tstmp, flags);
625 int retry = MAX_RETRY;
627 need_packet = 0; flushed = 0;
628 seeked = 1; st_eof(0);
629 // read up to retry packets, limited to npkts in stream, and not pkt.pos past pkt_pos
630 while( --retry >= 0 ) {
631 if( read_packet() <= 0 ) { ret = -1; break; }
632 if( ipkt->stream_index != st->index ) continue;
633 if( !ipkt->data || !ipkt->size ) continue;
634 if( pkt_pos >= 0 && ipkt->pos >= pkt_pos ) break;
635 if( --npkts <= 0 ) break;
636 int64_t pkt_ts = ipkt->dts != AV_NOPTS_VALUE ? ipkt->dts : ipkt->pts;
637 if( pkt_ts == AV_NOPTS_VALUE ) continue;
638 if( pkt_ts >= tstmp ) break;
641 fprintf(stderr,"FFStream::seek: retry limit, pos=%jd tstmp=%jd\n",pos,tstmp);
645 ret = avcodec_send_packet(avctx, ipkt);
647 //some codecs need more than one pkt to resync
648 if( ret == AVERROR_INVALIDDATA ) ret = 0;
650 ff_err(ret, "FFStream::avcodec_send_packet failed\n");
655 printf("** seek fail %jd, %jd\n", pos, tstmp);
656 seeked = need_packet = 0;
660 //printf("seeked pos = %ld, %ld\n", pos, tstmp);
661 seek_pos = curr_pos = pos;
665 FFAudioStream::FFAudioStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
666 : FFStream(ffmpeg, strm, fidx)
669 channel0 = channels = 0;
672 frame_sz = AUDIO_MIN_FRAME_SZ;
674 resample_context = 0;
675 swr_ichs = swr_ifmt = swr_irate = 0;
684 bfr = new float[bsz];
689 FFAudioStream::~FFAudioStream()
691 if( resample_context ) swr_free(&resample_context);
696 void FFAudioStream::init_swr(int ichs, int ifmt, int irate)
698 if( resample_context ) {
699 if( swr_ichs == ichs && swr_ifmt == ifmt && swr_irate == irate )
701 swr_free(&resample_context);
703 swr_ichs = ichs; swr_ifmt = ifmt; swr_irate = irate;
704 if( ichs == channels && ifmt == AV_SAMPLE_FMT_FLT && irate == sample_rate )
706 uint64_t ilayout = av_get_default_channel_layout(ichs);
707 if( !ilayout ) ilayout = ((uint64_t)1<<ichs) - 1;
708 uint64_t olayout = av_get_default_channel_layout(channels);
709 if( !olayout ) olayout = ((uint64_t)1<<channels) - 1;
710 resample_context = swr_alloc_set_opts(NULL,
711 olayout, AV_SAMPLE_FMT_FLT, sample_rate,
712 ilayout, (AVSampleFormat)ifmt, irate,
714 if( resample_context )
715 swr_init(resample_context);
718 int FFAudioStream::get_samples(float *&samples, uint8_t **data, int len)
720 samples = *(float **)data;
721 if( resample_context ) {
722 if( len > aud_bfr_sz ) {
728 aud_bfr = new float[aud_bfr_sz*channels];
730 int ret = swr_convert(resample_context,
731 (uint8_t**)&aud_bfr, aud_bfr_sz, (const uint8_t**)data, len);
733 ff_err(ret, "FFAudioStream::get_samples: swr_convert failed\n");
742 int FFAudioStream::load_history(uint8_t **data, int len)
745 len = get_samples(samples, data, len);
747 // biggest user bfr since seek + frame
748 realloc(mbsz + len + 1, channels);
754 int FFAudioStream::decode_frame(AVFrame *frame)
756 int first_frame = seeked; seeked = 0;
757 int ret = avcodec_receive_frame(avctx, frame);
759 if( first_frame || ret == AVERROR(EAGAIN) ) return 0;
760 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
761 ff_err(ret, "FFAudioStream::decode_frame: Could not read audio frame\n");
764 int64_t pkt_ts = av_frame_get_best_effort_timestamp(frame);
765 if( pkt_ts != AV_NOPTS_VALUE )
766 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * sample_rate + 0.5;
770 int FFAudioStream::encode_activate()
772 if( writing >= 0 ) return writing;
773 if( !avctx->codec ) return writing = 0;
774 frame_sz = avctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE ?
775 10000 : avctx->frame_size;
776 return FFStream::encode_activate();
779 int64_t FFAudioStream::load_buffer(double ** const sp, int len)
781 reserve(len+1, st->codecpar->channels);
782 for( int ch=0; ch<nch; ++ch )
783 write(sp[ch], len, ch);
787 int FFAudioStream::in_history(int64_t pos)
789 if( pos > curr_pos ) return 0;
791 if( len > sz ) len = sz;
792 if( pos < curr_pos - len ) return 0;
797 int FFAudioStream::init_frame(AVFrame *frame)
799 frame->nb_samples = frame_sz;
800 frame->format = avctx->sample_fmt;
801 frame->channel_layout = avctx->channel_layout;
802 frame->sample_rate = avctx->sample_rate;
803 int ret = av_frame_get_buffer(frame, 0);
805 ff_err(ret, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
809 int FFAudioStream::load(int64_t pos, int len)
811 if( audio_seek(pos) < 0 ) return -1;
812 if( !frame && !(frame=av_frame_alloc()) ) {
813 fprintf(stderr, "FFAudioStream::load: av_frame_alloc failed\n");
816 if( mbsz < len ) mbsz = len;
817 int64_t end_pos = pos + len;
818 int ret = 0, i = len / frame_sz + MAX_RETRY;
819 while( ret>=0 && !flushed && curr_pos<end_pos && --i>=0 ) {
820 ret = read_frame(frame);
821 if( ret > 0 && frame->nb_samples > 0 ) {
822 init_swr(frame->channels, frame->format, frame->sample_rate);
823 load_history(&frame->extended_data[0], frame->nb_samples);
824 curr_pos += frame->nb_samples;
827 if( end_pos > curr_pos ) {
828 zero(end_pos - curr_pos);
831 len = curr_pos - pos;
836 int FFAudioStream::audio_seek(int64_t pos)
838 if( decode_activate() <= 0 ) return -1;
839 if( !st->codecpar ) return -1;
840 if( in_history(pos) ) return 0;
841 if( pos == curr_pos ) return 0;
842 reset_history(); mbsz = 0;
843 // guarentee preload > 1sec samples
844 if( seek(pos-sample_rate, sample_rate) < 0 ) return -1;
848 int FFAudioStream::encode(double **samples, int len)
850 if( encode_activate() <= 0 ) return -1;
853 int64_t count = samples ? load_buffer(samples, len) : used();
854 int frame_sz1 = samples ? frame_sz-1 : 0;
857 while( ret >= 0 && count > frame_sz1 ) {
858 frm = new FFrame(this);
859 if( (ret=frm->initted()) < 0 ) break;
860 AVFrame *frame = *frm;
861 len = count >= frame_sz ? frame_sz : count;
862 float *bfrp = get_outp(len);
863 ret = swr_convert(resample_context,
864 (uint8_t **)frame->extended_data, len,
865 (const uint8_t **)&bfrp, len);
867 ff_err(ret, "FFAudioStream::encode: swr_convert failed\n");
870 frame->nb_samples = len;
871 frm->queue(curr_pos);
878 return ret >= 0 ? 0 : 1;
881 int FFAudioStream::drain()
886 int FFAudioStream::encode_frame(AVFrame *frame)
888 return FFStream::encode_frame(frame);
891 int FFAudioStream::write_packet(FFPacket &pkt)
893 return FFStream::write_packet(pkt);
896 void FFAudioStream::load_markers()
898 IndexState *index_state = ffmpeg->file_base->asset->index_state;
899 if( !index_state || idx >= index_state->audio_markers.size() ) return;
900 if( index_state->marker_status == MARKERS_NOTTESTED ) return;
901 FFStream::load_markers(*index_state->audio_markers[idx], sample_rate);
904 IndexMarks *FFAudioStream::get_markers()
906 IndexState *index_state = ffmpeg->file_base->asset->index_state;
907 if( !index_state || idx >= index_state->audio_markers.size() ) return 0;
908 return index_state->audio_markers[idx];
911 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
912 : FFStream(ffmpeg, strm, fidx)
923 FFVideoStream::~FFVideoStream()
927 int FFVideoStream::decode_frame(AVFrame *frame)
929 int first_frame = seeked; seeked = 0;
930 int ret = avcodec_receive_frame(avctx, frame);
932 if( first_frame || ret == AVERROR(EAGAIN) ) return 0;
933 if( ret == AVERROR(EAGAIN) ) return 0;
934 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
935 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame\n");
938 int64_t pkt_ts = av_frame_get_best_effort_timestamp(frame);
939 if( pkt_ts != AV_NOPTS_VALUE )
940 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * frame_rate + 0.5;
944 int FFVideoStream::load(VFrame *vframe, int64_t pos)
946 int ret = video_seek(pos);
947 if( ret < 0 ) return -1;
948 if( !frame && !(frame=av_frame_alloc()) ) {
949 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
952 int i = MAX_RETRY + pos - curr_pos;
953 while( ret>=0 && !flushed && curr_pos<=pos && --i>=0 ) {
954 ret = read_frame(frame);
955 if( ret > 0 ) ++curr_pos;
957 if( frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0 )
960 ret = convert_cmodel(vframe, frame);
962 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
966 int FFVideoStream::video_seek(int64_t pos)
968 if( decode_activate() <= 0 ) return -1;
969 if( !st->codecpar ) return -1;
970 if( pos == curr_pos-1 && !seeked ) return 0;
971 // if close enough, just read up to current
972 int gop = avctx->gop_size;
973 if( gop < 4 ) gop = 4;
974 if( gop > 64 ) gop = 64;
975 int read_limit = curr_pos + 3*gop;
976 if( pos >= curr_pos && pos <= read_limit ) return 0;
977 // guarentee preload more than 2*gop frames
978 if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
982 int FFVideoStream::init_frame(AVFrame *picture)
984 picture->format = avctx->pix_fmt;
985 picture->width = avctx->width;
986 picture->height = avctx->height;
987 int ret = av_frame_get_buffer(picture, 32);
991 int FFVideoStream::encode(VFrame *vframe)
993 if( encode_activate() <= 0 ) return -1;
995 FFrame *picture = new FFrame(this);
996 int ret = picture->initted();
998 AVFrame *frame = *picture;
999 frame->pts = curr_pos;
1000 ret = convert_pixfmt(vframe, frame);
1003 picture->queue(curr_pos);
1007 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
1010 return ret >= 0 ? 0 : 1;
1013 int FFVideoStream::drain()
1018 int FFVideoStream::encode_frame(AVFrame *frame)
1021 frame->interlaced_frame = interlaced;
1022 frame->top_field_first = top_field_first;
1024 return FFStream::encode_frame(frame);
1027 int FFVideoStream::write_packet(FFPacket &pkt)
1029 if( !(ffmpeg->fmt_ctx->oformat->flags & AVFMT_VARIABLE_FPS) )
1031 return FFStream::write_packet(pkt);
1034 AVPixelFormat FFVideoConvert::color_model_to_pix_fmt(int color_model)
1036 switch( color_model ) {
1037 case BC_YUV422: return AV_PIX_FMT_YUYV422;
1038 case BC_RGB888: return AV_PIX_FMT_RGB24;
1039 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
1040 case BC_BGR8888: return AV_PIX_FMT_BGR0;
1041 case BC_BGR888: return AV_PIX_FMT_BGR24;
1042 case BC_ARGB8888: return AV_PIX_FMT_ARGB;
1043 case BC_ABGR8888: return AV_PIX_FMT_ABGR;
1044 case BC_RGB8: return AV_PIX_FMT_RGB8;
1045 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
1046 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
1047 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
1048 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
1049 case BC_RGB565: return AV_PIX_FMT_RGB565;
1050 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
1051 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
1052 case BC_AYUV16161616: return AV_PIX_FMT_AYUV64LE;
1053 case BC_GBRP: return AV_PIX_FMT_GBRP;
1057 return AV_PIX_FMT_NB;
1060 int FFVideoConvert::pix_fmt_to_color_model(AVPixelFormat pix_fmt)
1063 case AV_PIX_FMT_YUYV422: return BC_YUV422;
1064 case AV_PIX_FMT_RGB24: return BC_RGB888;
1065 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
1066 case AV_PIX_FMT_BGR0: return BC_BGR8888;
1067 case AV_PIX_FMT_BGR24: return BC_BGR888;
1068 case AV_PIX_FMT_ARGB: return BC_ARGB8888;
1069 case AV_PIX_FMT_ABGR: return BC_ABGR8888;
1070 case AV_PIX_FMT_RGB8: return BC_RGB8;
1071 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
1072 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
1073 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
1074 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
1075 case AV_PIX_FMT_RGB565: return BC_RGB565;
1076 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
1077 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
1078 case AV_PIX_FMT_AYUV64LE: return BC_AYUV16161616;
1079 case AV_PIX_FMT_GBRP: return BC_GBRP;
1086 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip)
1088 AVFrame *ipic = av_frame_alloc();
1089 int ret = convert_picture_vframe(frame, ip, ipic);
1090 av_frame_free(&ipic);
1094 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip, AVFrame *ipic)
1096 int cmodel = frame->get_color_model();
1097 AVPixelFormat ofmt = color_model_to_pix_fmt(cmodel);
1098 if( ofmt == AV_PIX_FMT_NB ) return -1;
1099 int size = av_image_fill_arrays(ipic->data, ipic->linesize,
1100 frame->get_data(), ofmt, frame->get_w(), frame->get_h(), 1);
1101 if( size < 0 ) return -1;
1103 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1104 int ysz = bpp * frame->get_w(), usz = ysz;
1113 // override av_image_fill_arrays() for planar types
1114 ipic->data[0] = frame->get_y(); ipic->linesize[0] = ysz;
1115 ipic->data[1] = frame->get_u(); ipic->linesize[1] = usz;
1116 ipic->data[2] = frame->get_v(); ipic->linesize[2] = usz;
1119 ipic->data[0] = frame->get_data();
1120 ipic->linesize[0] = frame->get_bytes_per_line();
1124 AVPixelFormat pix_fmt = (AVPixelFormat)ip->format;
1125 convert_ctx = sws_getCachedContext(convert_ctx, ip->width, ip->height, pix_fmt,
1126 frame->get_w(), frame->get_h(), ofmt, SWS_POINT, NULL, NULL, NULL);
1127 if( !convert_ctx ) {
1128 fprintf(stderr, "FFVideoConvert::convert_picture_frame:"
1129 " sws_getCachedContext() failed\n");
1132 int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ip->height,
1133 ipic->data, ipic->linesize);
1135 ff_err(ret, "FFVideoConvert::convert_picture_frame: sws_scale() failed\n");
1141 int FFVideoConvert::convert_cmodel(VFrame *frame, AVFrame *ip)
1143 // try direct transfer
1144 if( !convert_picture_vframe(frame, ip) ) return 1;
1145 // use indirect transfer
1146 AVPixelFormat ifmt = (AVPixelFormat)ip->format;
1147 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
1149 for( int i = 0; i <desc->nb_components; ++i ) {
1150 int bits = desc->comp[i].depth;
1151 if( bits > max_bits ) max_bits = bits;
1153 int imodel = pix_fmt_to_color_model(ifmt);
1154 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1155 int cmodel = frame->get_color_model();
1156 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1157 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1158 imodel = cmodel_is_yuv ?
1159 (BC_CModels::has_alpha(cmodel) ?
1161 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1162 (BC_CModels::has_alpha(cmodel) ?
1163 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1164 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1166 VFrame vframe(ip->width, ip->height, imodel);
1167 if( convert_picture_vframe(&vframe, ip) ) return -1;
1168 frame->transfer_from(&vframe);
1172 int FFVideoConvert::transfer_cmodel(VFrame *frame, AVFrame *ifp)
1174 int ret = convert_cmodel(frame, ifp);
1176 const AVDictionary *src = av_frame_get_metadata(ifp);
1177 AVDictionaryEntry *t = NULL;
1178 BC_Hash *hp = frame->get_params();
1180 while( (t=av_dict_get(src, "", t, AV_DICT_IGNORE_SUFFIX)) )
1181 hp->update(t->key, t->value);
1186 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op)
1188 AVFrame *opic = av_frame_alloc();
1189 int ret = convert_vframe_picture(frame, op, opic);
1190 av_frame_free(&opic);
1194 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op, AVFrame *opic)
1196 int cmodel = frame->get_color_model();
1197 AVPixelFormat ifmt = color_model_to_pix_fmt(cmodel);
1198 if( ifmt == AV_PIX_FMT_NB ) return -1;
1199 int size = av_image_fill_arrays(opic->data, opic->linesize,
1200 frame->get_data(), ifmt, frame->get_w(), frame->get_h(), 1);
1201 if( size < 0 ) return -1;
1203 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1204 int ysz = bpp * frame->get_w(), usz = ysz;
1213 // override av_image_fill_arrays() for planar types
1214 opic->data[0] = frame->get_y(); opic->linesize[0] = ysz;
1215 opic->data[1] = frame->get_u(); opic->linesize[1] = usz;
1216 opic->data[2] = frame->get_v(); opic->linesize[2] = usz;
1219 opic->data[0] = frame->get_data();
1220 opic->linesize[0] = frame->get_bytes_per_line();
1224 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1225 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(),
1226 ifmt, op->width, op->height, ofmt, SWS_POINT, NULL, NULL, NULL);
1227 if( !convert_ctx ) {
1228 fprintf(stderr, "FFVideoConvert::convert_frame_picture:"
1229 " sws_getCachedContext() failed\n");
1232 int ret = sws_scale(convert_ctx, opic->data, opic->linesize, 0, frame->get_h(),
1233 op->data, op->linesize);
1235 ff_err(ret, "FFVideoConvert::convert_frame_picture: sws_scale() failed\n");
1241 int FFVideoConvert::convert_pixfmt(VFrame *frame, AVFrame *op)
1243 // try direct transfer
1244 if( !convert_vframe_picture(frame, op) ) return 1;
1245 // use indirect transfer
1246 int cmodel = frame->get_color_model();
1247 int max_bits = BC_CModels::calculate_pixelsize(cmodel) * 8;
1248 max_bits /= BC_CModels::components(cmodel);
1249 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1250 int imodel = pix_fmt_to_color_model(ofmt);
1251 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1252 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1253 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1254 imodel = cmodel_is_yuv ?
1255 (BC_CModels::has_alpha(cmodel) ?
1257 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1258 (BC_CModels::has_alpha(cmodel) ?
1259 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1260 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1262 VFrame vframe(frame->get_w(), frame->get_h(), imodel);
1263 vframe.transfer_from(frame);
1264 if( !convert_vframe_picture(&vframe, op) ) return 1;
1268 int FFVideoConvert::transfer_pixfmt(VFrame *frame, AVFrame *ofp)
1270 int ret = convert_pixfmt(frame, ofp);
1272 BC_Hash *hp = frame->get_params();
1273 AVDictionary **dict = avpriv_frame_get_metadatap(ofp);
1274 //av_dict_free(dict);
1275 for( int i=0; i<hp->size(); ++i ) {
1276 char *key = hp->get_key(i), *val = hp->get_value(i);
1277 av_dict_set(dict, key, val, 0);
1283 void FFVideoStream::load_markers()
1285 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1286 if( !index_state || idx >= index_state->video_markers.size() ) return;
1287 FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
1290 IndexMarks *FFVideoStream::get_markers()
1292 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1293 if( !index_state || idx >= index_state->video_markers.size() ) return 0;
1294 return !index_state ? 0 : index_state->video_markers[idx];
1298 FFMPEG::FFMPEG(FileBase *file_base)
1301 this->file_base = file_base;
1302 memset(file_format,0,sizeof(file_format));
1303 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
1304 flow_lock = new Condition(1,"FFStream::flow_lock",0);
1307 decoding = encoding = 0;
1308 has_audio = has_video = 0;
1311 opt_video_filter = 0;
1312 opt_audio_filter = 0;
1313 char option_path[BCTEXTLEN];
1314 set_option_path(option_path, "%s", "ffmpeg.opts");
1315 read_options(option_path, opts);
1320 ff_lock("FFMPEG::~FFMPEG()");
1322 ffaudio.remove_all_objects();
1323 ffvideo.remove_all_objects();
1324 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1328 av_dict_free(&opts);
1329 delete [] opt_video_filter;
1330 delete [] opt_audio_filter;
1333 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1335 const int *p = codec->supported_samplerates;
1336 if( !p ) return sample_rate;
1338 if( *p == sample_rate ) return *p;
1344 static inline AVRational std_frame_rate(int i)
1346 static const int m1 = 1001*12, m2 = 1000*12;
1347 static const int freqs[] = {
1348 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1349 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
1351 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1352 return (AVRational) { freq, 1001*12 };
1355 AVRational FFMPEG::check_frame_rate(AVCodec *codec, double frame_rate)
1357 const AVRational *p = codec->supported_framerates;
1358 AVRational rate, best_rate = (AVRational) { 0, 0 };
1359 double max_err = 1.; int i = 0;
1360 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1361 double framerate = (double) rate.num / rate.den;
1362 double err = fabs(frame_rate/framerate - 1.);
1363 if( err >= max_err ) continue;
1367 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1370 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1373 double display_aspect = asset->width / (double)asset->height;
1374 double sample_aspect = display_aspect / asset->aspect_ratio;
1375 int width = 1000000, height = width * sample_aspect + 0.5;
1377 MWindow::create_aspect_ratio(w, h, width, height);
1378 return (AVRational){(int)w, (int)h};
1381 return (AVRational){1, 1};
1385 AVRational FFMPEG::to_time_base(int sample_rate)
1387 return (AVRational){1, sample_rate};
1390 int FFMPEG::get_fmt_score(AVSampleFormat dst_fmt, AVSampleFormat src_fmt)
1393 int dst_planar = av_sample_fmt_is_planar(dst_fmt);
1394 int src_planar = av_sample_fmt_is_planar(src_fmt);
1395 if( dst_planar != src_planar ) ++score;
1396 int dst_bytes = av_get_bytes_per_sample(dst_fmt);
1397 int src_bytes = av_get_bytes_per_sample(src_fmt);
1398 score += (src_bytes > dst_bytes ? 100 : -10) * (src_bytes - dst_bytes);
1399 int src_packed = av_get_packed_sample_fmt(src_fmt);
1400 int dst_packed = av_get_packed_sample_fmt(dst_fmt);
1401 if( dst_packed == AV_SAMPLE_FMT_S32 && src_packed == AV_SAMPLE_FMT_FLT ) score += 20;
1402 if( dst_packed == AV_SAMPLE_FMT_FLT && src_packed == AV_SAMPLE_FMT_S32 ) score += 2;
1406 AVSampleFormat FFMPEG::find_best_sample_fmt_of_list(
1407 const AVSampleFormat *sample_fmts, AVSampleFormat src_fmt)
1409 AVSampleFormat best = AV_SAMPLE_FMT_NONE;
1410 int best_score = get_fmt_score(best, src_fmt);
1411 for( int i=0; sample_fmts[i] >= 0; ++i ) {
1412 AVSampleFormat sample_fmt = sample_fmts[i];
1413 int score = get_fmt_score(sample_fmt, src_fmt);
1414 if( score >= best_score ) continue;
1415 best = sample_fmt; best_score = score;
1421 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
1423 char *ep = path + BCTEXTLEN-1;
1424 strncpy(path, File::get_cindat_path(), ep-path);
1425 strncat(path, "/ffmpeg/", ep-path);
1426 path += strlen(path);
1429 path += vsnprintf(path, ep-path, fmt, ap);
1434 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
1439 set_option_path(path, "%s/%s", type, spec);
1442 int FFMPEG::get_format(char *format, const char *path, const char *spec)
1444 char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
1445 get_option_path(option_path, path, spec);
1446 FILE *fp = fopen(option_path,"r");
1449 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1451 line[sizeof(line)-1] = 0;
1452 ret = scan_option_line(line, format, codec);
1458 int FFMPEG::get_codec(char *codec, const char *path, const char *spec)
1460 char option_path[BCTEXTLEN], line[BCTEXTLEN], format[BCTEXTLEN];
1461 get_option_path(option_path, path, spec);
1462 FILE *fp = fopen(option_path,"r");
1465 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1468 line[sizeof(line)-1] = 0;
1469 ret = scan_option_line(line, format, codec);
1472 char *vp = codec, *ep = vp+BCTEXTLEN-1;
1473 while( vp < ep && *vp && *vp != '|' ) ++vp;
1474 if( *vp == '|' ) --vp;
1475 while( vp > codec && (*vp==' ' || *vp=='\t') ) *vp-- = 0;
1480 int FFMPEG::get_file_format()
1482 char audio_muxer[BCSTRLEN], video_muxer[BCSTRLEN];
1483 char audio_format[BCSTRLEN], video_format[BCSTRLEN];
1484 audio_muxer[0] = audio_format[0] = 0;
1485 video_muxer[0] = video_format[0] = 0;
1486 Asset *asset = file_base->asset;
1487 int ret = asset ? 0 : 1;
1488 if( !ret && asset->audio_data ) {
1489 if( !(ret=get_format(audio_format, "audio", asset->acodec)) ) {
1490 if( get_format(audio_muxer, "format", audio_format) ) {
1491 strcpy(audio_muxer, audio_format);
1492 audio_format[0] = 0;
1496 if( !ret && asset->video_data ) {
1497 if( !(ret=get_format(video_format, "video", asset->vcodec)) ) {
1498 if( get_format(video_muxer, "format", video_format) ) {
1499 strcpy(video_muxer, video_format);
1500 video_format[0] = 0;
1504 if( !ret && !audio_muxer[0] && !video_muxer[0] )
1506 if( !ret && audio_muxer[0] && video_muxer[0] &&
1507 strcmp(audio_muxer, video_muxer) ) ret = -1;
1508 if( !ret && audio_format[0] && video_format[0] &&
1509 strcmp(audio_format, video_format) ) ret = -1;
1511 strcpy(file_format, !audio_format[0] && !video_format[0] ?
1512 (audio_muxer[0] ? audio_muxer : video_muxer) :
1513 (audio_format[0] ? audio_format : video_format));
1517 int FFMPEG::scan_option_line(const char *cp, char *tag, char *val)
1519 while( *cp == ' ' || *cp == '\t' ) ++cp;
1520 const char *bp = cp;
1521 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' && *cp != '\n' ) ++cp;
1523 if( !len || len > BCSTRLEN-1 ) return 1;
1524 while( bp < cp ) *tag++ = *bp++;
1526 while( *cp == ' ' || *cp == '\t' ) ++cp;
1527 if( *cp == '=' ) ++cp;
1528 while( *cp == ' ' || *cp == '\t' ) ++cp;
1530 while( *cp && *cp != '\n' ) ++cp;
1532 if( len > BCTEXTLEN-1 ) return 1;
1533 while( bp < cp ) *val++ = *bp++;
1538 int FFMPEG::can_render(const char *fformat, const char *type)
1541 char option_path[BCTEXTLEN];
1542 FFMPEG::set_option_path(option_path, type);
1543 fs.update(option_path);
1544 int total_files = fs.total_files();
1545 for( int i=0; i<total_files; ++i ) {
1546 const char *name = fs.get_entry(i)->get_name();
1547 const char *ext = strrchr(name,'.');
1548 if( !ext ) continue;
1549 if( !strcmp(fformat, ++ext) ) return 1;
1554 int FFMPEG::get_ff_option(const char *nm, const char *options, char *value)
1556 for( const char *cp=options; *cp!=0; ) {
1557 char line[BCTEXTLEN], *bp = line, *ep = bp+sizeof(line)-1;
1558 while( bp < ep && *cp && *cp!='\n' ) *bp++ = *cp++;
1561 if( !line[0] || line[0] == '#' || line[0] == ';' ) continue;
1562 char key[BCSTRLEN], val[BCTEXTLEN];
1563 if( FFMPEG::scan_option_line(line, key, val) ) continue;
1564 if( !strcmp(key, nm) ) {
1565 strncpy(value, val, BCSTRLEN);
1572 void FFMPEG::scan_audio_options(Asset *asset, EDL *edl)
1574 char cin_sample_fmt[BCSTRLEN];
1575 int cin_fmt = AV_SAMPLE_FMT_NONE;
1576 const char *options = asset->ff_audio_options;
1577 if( !get_ff_option("cin_sample_fmt", options, cin_sample_fmt) )
1578 cin_fmt = (int)av_get_sample_fmt(cin_sample_fmt);
1580 char audio_codec[BCSTRLEN]; audio_codec[0] = 0;
1581 AVCodec *av_codec = !FFMPEG::get_codec(audio_codec, "audio", asset->acodec) ?
1582 avcodec_find_encoder_by_name(audio_codec) : 0;
1583 if( av_codec && av_codec->sample_fmts )
1584 cin_fmt = find_best_sample_fmt_of_list(av_codec->sample_fmts, AV_SAMPLE_FMT_FLT);
1586 if( cin_fmt < 0 ) cin_fmt = AV_SAMPLE_FMT_S16;
1587 const char *name = av_get_sample_fmt_name((AVSampleFormat)cin_fmt);
1588 if( !name ) name = _("None");
1589 strcpy(asset->ff_sample_format, name);
1591 char value[BCSTRLEN];
1592 if( !get_ff_option("cin_bitrate", options, value) )
1593 asset->ff_audio_bitrate = atoi(value);
1594 if( !get_ff_option("cin_quality", options, value) )
1595 asset->ff_audio_quality = atoi(value);
1598 void FFMPEG::load_audio_options(Asset *asset, EDL *edl)
1600 char options_path[BCTEXTLEN];
1601 set_option_path(options_path, "audio/%s", asset->acodec);
1602 if( !load_options(options_path,
1603 asset->ff_audio_options,
1604 sizeof(asset->ff_audio_options)) )
1605 scan_audio_options(asset, edl);
1608 void FFMPEG::scan_video_options(Asset *asset, EDL *edl)
1610 char cin_pix_fmt[BCSTRLEN];
1611 int cin_fmt = AV_PIX_FMT_NONE;
1612 const char *options = asset->ff_video_options;
1613 if( !get_ff_option("cin_pix_fmt", options, cin_pix_fmt) )
1614 cin_fmt = (int)av_get_pix_fmt(cin_pix_fmt);
1616 char video_codec[BCSTRLEN]; video_codec[0] = 0;
1617 AVCodec *av_codec = !get_codec(video_codec, "video", asset->vcodec) ?
1618 avcodec_find_encoder_by_name(video_codec) : 0;
1619 if( av_codec && av_codec->pix_fmts ) {
1621 int color_model = edl->session->color_model;
1622 int max_bits = BC_CModels::calculate_pixelsize(color_model) * 8;
1623 max_bits /= BC_CModels::components(color_model);
1624 cin_fmt = avcodec_find_best_pix_fmt_of_list(av_codec->pix_fmts,
1625 (BC_CModels::is_yuv(color_model) ?
1626 (max_bits > 8 ? AV_PIX_FMT_AYUV64LE : AV_PIX_FMT_YUV444P) :
1627 (max_bits > 8 ? AV_PIX_FMT_RGB48LE : AV_PIX_FMT_RGB24)), 0, 0);
1630 cin_fmt = av_codec->pix_fmts[0];
1633 if( cin_fmt < 0 ) cin_fmt = AV_PIX_FMT_YUV420P;
1634 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get((AVPixelFormat)cin_fmt);
1635 const char *name = desc ? desc->name : _("None");
1636 strcpy(asset->ff_pixel_format, name);
1638 char value[BCSTRLEN];
1639 if( !get_ff_option("cin_bitrate", options, value) )
1640 asset->ff_video_bitrate = atoi(value);
1641 if( !get_ff_option("cin_quality", options, value) )
1642 asset->ff_video_quality = atoi(value);
1645 void FFMPEG::load_video_options(Asset *asset, EDL *edl)
1647 char options_path[BCTEXTLEN];
1648 set_option_path(options_path, "video/%s", asset->vcodec);
1649 if( !load_options(options_path,
1650 asset->ff_video_options,
1651 sizeof(asset->ff_video_options)) )
1652 scan_video_options(asset, edl);
1655 int FFMPEG::load_defaults(const char *path, const char *type,
1656 char *codec, char *codec_options, int len)
1658 char default_file[BCTEXTLEN];
1659 set_option_path(default_file, "%s/%s.dfl", path, type);
1660 FILE *fp = fopen(default_file,"r");
1662 fgets(codec, BCSTRLEN, fp);
1664 while( *cp && *cp!='\n' ) ++cp;
1666 while( len > 0 && fgets(codec_options, len, fp) ) {
1667 int n = strlen(codec_options);
1668 codec_options += n; len -= n;
1671 set_option_path(default_file, "%s/%s", path, codec);
1672 return load_options(default_file, codec_options, len);
1675 void FFMPEG::set_asset_format(Asset *asset, EDL *edl, const char *text)
1677 if( asset->format != FILE_FFMPEG ) return;
1678 if( text != asset->fformat )
1679 strcpy(asset->fformat, text);
1680 if( asset->audio_data && !asset->ff_audio_options[0] ) {
1681 if( !load_defaults("audio", text, asset->acodec,
1682 asset->ff_audio_options, sizeof(asset->ff_audio_options)) )
1683 scan_audio_options(asset, edl);
1685 asset->audio_data = 0;
1687 if( asset->video_data && !asset->ff_video_options[0] ) {
1688 if( !load_defaults("video", text, asset->vcodec,
1689 asset->ff_video_options, sizeof(asset->ff_video_options)) )
1690 scan_video_options(asset, edl);
1692 asset->video_data = 0;
1696 int FFMPEG::get_encoder(const char *options,
1697 char *format, char *codec, char *bsfilter)
1699 FILE *fp = fopen(options,"r");
1701 eprintf(_("options open failed %s\n"),options);
1704 char line[BCTEXTLEN];
1705 if( !fgets(line, sizeof(line), fp) ||
1706 scan_encoder(line, format, codec, bsfilter) )
1707 eprintf(_("format/codec not found %s\n"), options);
1712 int FFMPEG::scan_encoder(const char *line,
1713 char *format, char *codec, char *bsfilter)
1715 format[0] = codec[0] = bsfilter[0] = 0;
1716 if( scan_option_line(line, format, codec) ) return 1;
1718 while( *cp && *cp != '|' ) ++cp;
1719 if( !*cp ) return 0;
1721 do { *bp-- = 0; } while( bp>=codec && (*bp==' ' || *bp == '\t' ) );
1722 while( *++cp && (*cp==' ' || *cp == '\t') );
1724 for( int i=BCTEXTLEN; --i>0 && *cp; ) *bp++ = *cp++;
1729 int FFMPEG::read_options(const char *options, AVDictionary *&opts, int skip)
1731 FILE *fp = fopen(options,"r");
1734 while( !ret && --skip >= 0 ) {
1736 while( ch >= 0 && ch != '\n' ) ch = getc(fp);
1737 if( ch < 0 ) ret = 1;
1740 ret = read_options(fp, options, opts);
1745 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
1747 FILE *fp = fmemopen((void *)options,strlen(options),"r");
1749 int ret = read_options(fp, options, opts);
1751 AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
1752 if( tag ) st->id = strtol(tag->value,0,0);
1756 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
1758 int ret = 0, no = 0;
1759 char line[BCTEXTLEN];
1760 while( !ret && fgets(line, sizeof(line), fp) ) {
1761 line[sizeof(line)-1] = 0;
1762 if( line[0] == '#' ) continue;
1763 if( line[0] == '\n' ) continue;
1764 char key[BCSTRLEN], val[BCTEXTLEN];
1765 if( scan_option_line(line, key, val) ) {
1766 eprintf(_("err reading %s: line %d\n"), options, no);
1770 if( !strcmp(key, "duration") )
1771 opt_duration = strtod(val, 0);
1772 else if( !strcmp(key, "video_filter") )
1773 opt_video_filter = cstrdup(val);
1774 else if( !strcmp(key, "audio_filter") )
1775 opt_audio_filter = cstrdup(val);
1776 else if( !strcmp(key, "loglevel") )
1779 av_dict_set(&opts, key, val, 0);
1785 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
1787 char option_path[BCTEXTLEN];
1788 set_option_path(option_path, "%s", options);
1789 return read_options(option_path, opts);
1792 int FFMPEG::load_options(const char *path, char *bfr, int len)
1795 FILE *fp = fopen(path, "r");
1797 fgets(bfr, len, fp); // skip hdr
1798 len = fread(bfr, 1, len-1, fp);
1799 if( len < 0 ) len = 0;
1805 void FFMPEG::set_loglevel(const char *ap)
1807 if( !ap || !*ap ) return;
1812 { "quiet" , AV_LOG_QUIET },
1813 { "panic" , AV_LOG_PANIC },
1814 { "fatal" , AV_LOG_FATAL },
1815 { "error" , AV_LOG_ERROR },
1816 { "warning", AV_LOG_WARNING },
1817 { "info" , AV_LOG_INFO },
1818 { "verbose", AV_LOG_VERBOSE },
1819 { "debug" , AV_LOG_DEBUG },
1821 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
1822 if( !strcmp(log_levels[i].name, ap) ) {
1823 av_log_set_level(log_levels[i].level);
1827 av_log_set_level(atoi(ap));
1830 double FFMPEG::to_secs(int64_t time, AVRational time_base)
1832 double base_time = time == AV_NOPTS_VALUE ? 0 :
1833 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
1834 return base_time / AV_TIME_BASE;
1837 int FFMPEG::info(char *text, int len)
1839 if( len <= 0 ) return 0;
1841 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
1843 report("format: %s\n",fmt_ctx->iformat->name);
1844 if( ffvideo.size() > 0 )
1845 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
1846 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
1847 FFVideoStream *vid = ffvideo[vidx];
1848 AVStream *st = vid->st;
1849 AVCodecID codec_id = st->codecpar->codec_id;
1850 report(_("vid%d (%d), id 0x%06x:\n"), vid->idx, vid->fidx, codec_id);
1851 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
1852 report(" video%d %s", vidx+1, desc ? desc->name : " (unkn)");
1853 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
1854 AVPixelFormat pix_fmt = (AVPixelFormat)st->codecpar->format;
1855 const char *pfn = av_get_pix_fmt_name(pix_fmt);
1856 report(" pix %s\n", pfn ? pfn : "(unkn)");
1857 double secs = to_secs(st->duration, st->time_base);
1858 int64_t length = secs * vid->frame_rate + 0.5;
1859 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
1860 int64_t nudge = ofs * vid->frame_rate;
1861 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1862 report(" %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
1863 int hrs = secs/3600; secs -= hrs*3600;
1864 int mins = secs/60; secs -= mins*60;
1865 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1867 if( ffaudio.size() > 0 )
1868 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
1869 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
1870 FFAudioStream *aud = ffaudio[aidx];
1871 AVStream *st = aud->st;
1872 AVCodecID codec_id = st->codecpar->codec_id;
1873 report(_("aud%d (%d), id 0x%06x:\n"), aud->idx, aud->fidx, codec_id);
1874 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
1875 int nch = aud->channels, ch0 = aud->channel0+1;
1876 report(" audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
1877 AVSampleFormat sample_fmt = (AVSampleFormat)st->codecpar->format;
1878 const char *fmt = av_get_sample_fmt_name(sample_fmt);
1879 report(" %s %d", fmt, aud->sample_rate);
1880 int sample_bits = av_get_bits_per_sample(codec_id);
1881 report(" %dbits\n", sample_bits);
1882 double secs = to_secs(st->duration, st->time_base);
1883 int64_t length = secs * aud->sample_rate + 0.5;
1884 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
1885 int64_t nudge = ofs * aud->sample_rate;
1886 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1887 report(" %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
1888 int hrs = secs/3600; secs -= hrs*3600;
1889 int mins = secs/60; secs -= mins*60;
1890 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1892 if( fmt_ctx->nb_programs > 0 )
1893 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
1894 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
1895 report("program %d", i+1);
1896 AVProgram *pgrm = fmt_ctx->programs[i];
1897 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1898 int idx = pgrm->stream_index[j];
1899 int vidx = ffvideo.size();
1900 while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
1902 report(", vid%d", vidx);
1905 int aidx = ffaudio.size();
1906 while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
1908 report(", aud%d", aidx);
1911 report(", (%d)", pgrm->stream_index[j]);
1916 AVDictionaryEntry *tag = 0;
1917 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
1918 report("%s=%s\n", tag->key, tag->value);
1927 int FFMPEG::init_decoder(const char *filename)
1929 ff_lock("FFMPEG::init_decoder");
1931 char file_opts[BCTEXTLEN];
1932 char *bp = strrchr(strcpy(file_opts, filename), '/');
1933 char *sp = strrchr(!bp ? file_opts : bp, '.');
1936 strcpy(sp, ".opts");
1937 fp = fopen(file_opts, "r");
1940 read_options(fp, file_opts, opts);
1944 load_options("decode.opts", opts);
1945 AVDictionary *fopts = 0;
1946 av_dict_copy(&fopts, opts, 0);
1947 int ret = avformat_open_input(&fmt_ctx, filename, NULL, &fopts);
1948 av_dict_free(&fopts);
1950 ret = avformat_find_stream_info(fmt_ctx, NULL);
1955 return !ret ? 0 : 1;
1958 int FFMPEG::open_decoder()
1961 if( stat(fmt_ctx->filename, &st) < 0 ) {
1962 eprintf(_("can't stat file: %s\n"), fmt_ctx->filename);
1966 int64_t file_bits = 8 * st.st_size;
1967 if( !fmt_ctx->bit_rate && opt_duration > 0 )
1968 fmt_ctx->bit_rate = file_bits / opt_duration;
1971 if( fmt_ctx->bit_rate > 0 ) {
1972 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1973 AVStream *st = fmt_ctx->streams[i];
1974 if( st->duration != AV_NOPTS_VALUE ) continue;
1975 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
1976 st->duration = av_rescale(file_bits, st->time_base.den,
1977 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
1981 static int notified = 0;
1982 if( !notified && estimated ) {
1984 printf("FFMPEG::open_decoder: some stream times estimated\n");
1987 ff_lock("FFMPEG::open_decoder");
1988 int ret = 0, bad_time = 0;
1989 for( int i=0; !ret && i<(int)fmt_ctx->nb_streams; ++i ) {
1990 AVStream *st = fmt_ctx->streams[i];
1991 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
1992 AVCodecParameters *avpar = st->codecpar;
1993 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avpar->codec_id);
1994 if( !codec_desc ) continue;
1995 switch( avpar->codec_type ) {
1996 case AVMEDIA_TYPE_VIDEO: {
1997 if( avpar->width < 1 ) continue;
1998 if( avpar->height < 1 ) continue;
1999 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
2000 if( framerate.num < 1 ) continue;
2002 int vidx = ffvideo.size();
2003 FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
2004 vstrm_index.append(ffidx(vidx, 0));
2005 ffvideo.append(vid);
2006 vid->width = avpar->width;
2007 vid->height = avpar->height;
2008 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
2009 double secs = to_secs(st->duration, st->time_base);
2010 vid->length = secs * vid->frame_rate;
2011 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
2012 vid->nudge = st->start_time;
2014 if( opt_video_filter )
2015 ret = vid->create_filter(opt_video_filter, avpar);
2017 case AVMEDIA_TYPE_AUDIO: {
2018 if( avpar->channels < 1 ) continue;
2019 if( avpar->sample_rate < 1 ) continue;
2021 int aidx = ffaudio.size();
2022 FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
2023 ffaudio.append(aud);
2024 aud->channel0 = astrm_index.size();
2025 aud->channels = avpar->channels;
2026 for( int ch=0; ch<aud->channels; ++ch )
2027 astrm_index.append(ffidx(aidx, ch));
2028 aud->sample_rate = avpar->sample_rate;
2029 double secs = to_secs(st->duration, st->time_base);
2030 aud->length = secs * aud->sample_rate;
2031 aud->init_swr(aud->channels, avpar->format, aud->sample_rate);
2032 aud->nudge = st->start_time;
2034 if( opt_audio_filter )
2035 ret = aud->create_filter(opt_audio_filter, avpar);
2041 printf("FFMPEG::open_decoder: some stream have bad times\n");
2043 return ret < 0 ? -1 : 0;
2047 int FFMPEG::init_encoder(const char *filename)
2049 // try access first for named pipes
2050 int ret = access(filename, W_OK);
2052 int fd = ::open(filename,O_WRONLY);
2053 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
2054 if( fd >= 0 ) { close(fd); ret = 0; }
2057 eprintf(_("bad file path: %s\n"), filename);
2060 ret = get_file_format();
2062 eprintf(_("bad file format: %s\n"), filename);
2066 eprintf(_("mismatch audio/video file format: %s\n"), filename);
2069 ff_lock("FFMPEG::init_encoder");
2071 char format[BCSTRLEN];
2072 if( get_format(format, "format", file_format) )
2073 strcpy(format, file_format);
2074 avformat_alloc_output_context2(&fmt_ctx, 0, format, filename);
2076 eprintf(_("failed: %s\n"), filename);
2081 load_options("encode.opts", opts);
2087 int FFMPEG::open_encoder(const char *type, const char *spec)
2090 Asset *asset = file_base->asset;
2091 char *filename = asset->path;
2092 AVDictionary *sopts = 0;
2093 av_dict_copy(&sopts, opts, 0);
2094 char option_path[BCTEXTLEN];
2095 set_option_path(option_path, "%s/%s.opts", type, type);
2096 read_options(option_path, sopts);
2097 get_option_path(option_path, type, spec);
2098 char format_name[BCSTRLEN], codec_name[BCTEXTLEN], bsfilter[BCTEXTLEN];
2099 if( get_encoder(option_path, format_name, codec_name, bsfilter) ) {
2100 eprintf(_("get_encoder failed %s:%s\n"), option_path, filename);
2104 if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
2105 else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
2106 else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
2109 ff_lock("FFMPEG::open_encoder");
2112 AVCodecContext *ctx = 0;
2114 const AVCodecDescriptor *codec_desc = 0;
2115 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
2117 eprintf(_("cant find codec %s:%s\n"), codec_name, filename);
2121 codec_desc = avcodec_descriptor_get(codec->id);
2123 eprintf(_("unknown codec %s:%s\n"), codec_name, filename);
2128 st = avformat_new_stream(fmt_ctx, 0);
2130 eprintf(_("cant create stream %s:%s\n"), codec_name, filename);
2135 switch( codec_desc->type ) {
2136 case AVMEDIA_TYPE_AUDIO: {
2138 eprintf(_("duplicate audio %s:%s\n"), codec_name, filename);
2142 if( scan_options(asset->ff_audio_options, sopts, st) ) {
2143 eprintf(_("bad audio options %s:%s\n"), codec_name, filename);
2148 ctx = avcodec_alloc_context3(codec);
2149 if( asset->ff_audio_bitrate > 0 ) {
2150 ctx->bit_rate = asset->ff_audio_bitrate;
2152 sprintf(arg, "%d", asset->ff_audio_bitrate);
2153 av_dict_set(&sopts, "b", arg, 0);
2155 else if( asset->ff_audio_quality >= 0 ) {
2156 ctx->global_quality = asset->ff_audio_quality * FF_QP2LAMBDA;
2157 ctx->qmin = ctx->qmax = asset->ff_audio_quality;
2158 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2159 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2160 ctx->flags |= CODEC_FLAG_QSCALE;
2162 av_dict_set(&sopts, "flags", "+qscale", 0);
2163 sprintf(arg, "%d", asset->ff_audio_quality);
2164 av_dict_set(&sopts, "qscale", arg, 0);
2165 sprintf(arg, "%d", ctx->global_quality);
2166 av_dict_set(&sopts, "global_quality", arg, 0);
2168 int aidx = ffaudio.size();
2169 int fidx = aidx + ffvideo.size();
2170 FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
2171 aud->avctx = ctx; ffaudio.append(aud); fst = aud;
2172 aud->sample_rate = asset->sample_rate;
2173 ctx->channels = aud->channels = asset->channels;
2174 for( int ch=0; ch<aud->channels; ++ch )
2175 astrm_index.append(ffidx(aidx, ch));
2176 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
2177 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
2178 if( !ctx->sample_rate ) {
2179 eprintf(_("check_sample_rate failed %s\n"), filename);
2183 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
2184 AVSampleFormat sample_fmt = av_get_sample_fmt(asset->ff_sample_format);
2185 if( sample_fmt == AV_SAMPLE_FMT_NONE )
2186 sample_fmt = codec->sample_fmts ? codec->sample_fmts[0] : AV_SAMPLE_FMT_S16;
2187 ctx->sample_fmt = sample_fmt;
2188 uint64_t layout = av_get_default_channel_layout(ctx->channels);
2189 aud->resample_context = swr_alloc_set_opts(NULL,
2190 layout, ctx->sample_fmt, aud->sample_rate,
2191 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
2193 swr_init(aud->resample_context);
2196 case AVMEDIA_TYPE_VIDEO: {
2198 eprintf(_("duplicate video %s:%s\n"), codec_name, filename);
2202 if( scan_options(asset->ff_video_options, sopts, st) ) {
2203 eprintf(_("bad video options %s:%s\n"), codec_name, filename);
2208 ctx = avcodec_alloc_context3(codec);
2209 if( asset->ff_video_bitrate > 0 ) {
2210 ctx->bit_rate = asset->ff_video_bitrate;
2212 sprintf(arg, "%d", asset->ff_video_bitrate);
2213 av_dict_set(&sopts, "b", arg, 0);
2215 else if( asset->ff_video_quality >= 0 ) {
2216 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
2217 ctx->qmin = ctx->qmax = asset->ff_video_quality;
2218 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2219 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2220 ctx->flags |= CODEC_FLAG_QSCALE;
2222 av_dict_set(&sopts, "flags", "+qscale", 0);
2223 sprintf(arg, "%d", asset->ff_video_quality);
2224 av_dict_set(&sopts, "qscale", arg, 0);
2225 sprintf(arg, "%d", ctx->global_quality);
2226 av_dict_set(&sopts, "global_quality", arg, 0);
2228 int vidx = ffvideo.size();
2229 int fidx = vidx + ffaudio.size();
2230 FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
2231 vstrm_index.append(ffidx(vidx, 0));
2232 vid->avctx = ctx; ffvideo.append(vid); fst = vid;
2233 vid->width = asset->width;
2234 vid->height = asset->height;
2235 vid->frame_rate = asset->frame_rate;
2237 AVPixelFormat pix_fmt = av_get_pix_fmt(asset->ff_pixel_format);
2238 if( pix_fmt == AV_PIX_FMT_NONE )
2239 pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
2240 ctx->pix_fmt = pix_fmt;
2241 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
2242 int mask_w = (1<<desc->log2_chroma_w)-1;
2243 ctx->width = (vid->width+mask_w) & ~mask_w;
2244 int mask_h = (1<<desc->log2_chroma_h)-1;
2245 ctx->height = (vid->height+mask_h) & ~mask_h;
2246 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
2247 AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
2248 if( !frame_rate.num || !frame_rate.den ) {
2249 eprintf(_("check_frame_rate failed %s\n"), filename);
2253 av_reduce(&frame_rate.num, &frame_rate.den,
2254 frame_rate.num, frame_rate.den, INT_MAX);
2255 ctx->framerate = (AVRational) { frame_rate.num, frame_rate.den };
2256 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
2257 st->avg_frame_rate = frame_rate;
2258 st->time_base = ctx->time_base;
2260 vid->interlaced = asset->interlace_mode == ILACE_MODE_TOP_FIRST ||
2261 asset->interlace_mode == ILACE_MODE_BOTTOM_FIRST ? 1 : 0;
2262 vid->top_field_first = asset->interlace_mode == ILACE_MODE_TOP_FIRST ? 1 : 0;
2265 eprintf(_("not audio/video, %s:%s\n"), codec_name, filename);
2270 AVDictionaryEntry *tag;
2271 if( (tag=av_dict_get(sopts, "cin_stats_filename", NULL, 0)) != 0 ) {
2272 char suffix[BCSTRLEN]; sprintf(suffix,"-%d.log",fst->fidx);
2273 fst->stats_filename = cstrcat(2, tag->value, suffix);
2275 if( (tag=av_dict_get(sopts, "flags", NULL, 0)) != 0 ) {
2276 int pass = fst->pass;
2277 char *cp = tag->value;
2279 int ch = *cp++, pfx = ch=='-' ? -1 : ch=='+' ? 1 : 0;
2280 if( !isalnum(!pfx ? ch : (ch=*cp++)) ) continue;
2281 char id[BCSTRLEN], *bp = id, *ep = bp+sizeof(id)-1;
2282 for( *bp++=ch; isalnum(ch=*cp); ++cp )
2283 if( bp < ep ) *bp++ = ch;
2285 if( !strcmp(id, "pass1") ) {
2286 pass = pfx<0 ? (pass&~1) : pfx>0 ? (pass|1) : 1;
2288 else if( !strcmp(id, "pass2") ) {
2289 pass = pfx<0 ? (pass&~2) : pfx>0 ? (pass|2) : 2;
2292 if( (fst->pass=pass) ) {
2293 if( pass & 1 ) ctx->flags |= AV_CODEC_FLAG_PASS1;
2294 if( pass & 2 ) ctx->flags |= AV_CODEC_FLAG_PASS2;
2300 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
2301 ctx->flags |= CODEC_FLAG_GLOBAL_HEADER;
2302 if( fst->stats_filename && (ret=fst->init_stats_file()) )
2303 eprintf(_("error: stats file = %s\n"), fst->stats_filename);
2306 av_dict_set(&sopts, "cin_bitrate", 0, 0);
2307 av_dict_set(&sopts, "cin_quality", 0, 0);
2309 if( !av_dict_get(sopts, "threads", NULL, 0) )
2310 ctx->thread_count = ff_cpus();
2311 ret = avcodec_open2(ctx, codec, &sopts);
2313 ret = avcodec_parameters_from_context(st->codecpar, ctx);
2315 fprintf(stderr, "Could not copy the stream parameters\n");
2318 _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
2319 ret = avcodec_copy_context(st->codec, ctx);
2320 _Pragma("GCC diagnostic warning \"-Wdeprecated-declarations\"")
2322 fprintf(stderr, "Could not copy the stream context\n");
2325 ff_err(ret,"FFMPEG::open_encoder");
2326 eprintf(_("open failed %s:%s\n"), codec_name, filename);
2332 if( !ret && fst && bsfilter[0] ) {
2333 ret = av_bsf_list_parse_str(bsfilter, &fst->bsfc);
2335 ff_err(ret,"FFMPEG::open_encoder");
2336 eprintf(_("bitstream filter failed %s:\n%s\n"), filename, bsfilter);
2347 av_dict_free(&sopts);
2351 int FFMPEG::close_encoder()
2354 if( encoding > 0 ) {
2355 av_write_trailer(fmt_ctx);
2356 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
2357 avio_closep(&fmt_ctx->pb);
2363 int FFMPEG::decode_activate()
2365 if( decoding < 0 ) {
2367 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
2368 ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
2369 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
2370 ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
2371 // set nudges for each program stream set
2372 const int64_t min_nudge = INT64_MIN+1;
2373 int npgrms = fmt_ctx->nb_programs;
2374 for( int i=0; i<npgrms; ++i ) {
2375 AVProgram *pgrm = fmt_ctx->programs[i];
2376 // first start time video stream
2377 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2378 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2379 int fidx = pgrm->stream_index[j];
2380 AVStream *st = fmt_ctx->streams[fidx];
2381 AVCodecParameters *avpar = st->codecpar;
2382 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2383 if( st->start_time == AV_NOPTS_VALUE ) continue;
2384 if( vstart_time < st->start_time )
2385 vstart_time = st->start_time;
2388 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2389 if( st->start_time == AV_NOPTS_VALUE ) continue;
2390 if( astart_time < st->start_time )
2391 astart_time = st->start_time;
2395 //since frame rate is much more grainy than sample rate, it is better to
2396 // align using video, so that total absolute error is minimized.
2397 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2398 astart_time > min_nudge ? astart_time : AV_NOPTS_VALUE;
2399 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2400 int fidx = pgrm->stream_index[j];
2401 AVStream *st = fmt_ctx->streams[fidx];
2402 AVCodecParameters *avpar = st->codecpar;
2403 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2404 for( int k=0; k<ffvideo.size(); ++k ) {
2405 if( ffvideo[k]->fidx != fidx ) continue;
2406 ffvideo[k]->nudge = nudge;
2410 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2411 for( int k=0; k<ffaudio.size(); ++k ) {
2412 if( ffaudio[k]->fidx != fidx ) continue;
2413 ffaudio[k]->nudge = nudge;
2419 // set nudges for any streams not yet set
2420 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2421 int nstreams = fmt_ctx->nb_streams;
2422 for( int i=0; i<nstreams; ++i ) {
2423 AVStream *st = fmt_ctx->streams[i];
2424 AVCodecParameters *avpar = st->codecpar;
2425 switch( avpar->codec_type ) {
2426 case AVMEDIA_TYPE_VIDEO: {
2427 if( st->start_time == AV_NOPTS_VALUE ) continue;
2428 int vidx = ffvideo.size();
2429 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
2430 if( vidx < 0 ) continue;
2431 if( ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
2432 if( vstart_time < st->start_time )
2433 vstart_time = st->start_time;
2435 case AVMEDIA_TYPE_AUDIO: {
2436 if( st->start_time == AV_NOPTS_VALUE ) continue;
2437 int aidx = ffaudio.size();
2438 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
2439 if( aidx < 0 ) continue;
2440 if( ffaudio[aidx]->frame_sz < avpar->frame_size )
2441 ffaudio[aidx]->frame_sz = avpar->frame_size;
2442 if( ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
2443 if( astart_time < st->start_time )
2444 astart_time = st->start_time;
2449 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2450 astart_time > min_nudge ? astart_time : 0;
2451 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
2452 if( ffvideo[vidx]->nudge == AV_NOPTS_VALUE )
2453 ffvideo[vidx]->nudge = nudge;
2455 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2456 if( ffaudio[aidx]->nudge == AV_NOPTS_VALUE )
2457 ffaudio[aidx]->nudge = nudge;
2464 int FFMPEG::encode_activate()
2467 if( encoding < 0 ) {
2469 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
2470 (ret=avio_open(&fmt_ctx->pb, fmt_ctx->filename, AVIO_FLAG_WRITE)) < 0 ) {
2471 ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
2477 AVProgram *prog = av_new_program(fmt_ctx, prog_id);
2478 for( int i=0; i< ffvideo.size(); ++i )
2479 av_program_add_stream_index(fmt_ctx, prog_id, ffvideo[i]->fidx);
2480 for( int i=0; i< ffaudio.size(); ++i )
2481 av_program_add_stream_index(fmt_ctx, prog_id, ffaudio[i]->fidx);
2482 int pi = fmt_ctx->nb_programs;
2483 while( --pi >= 0 && fmt_ctx->programs[pi]->id != prog_id );
2484 AVDictionary **meta = &prog->metadata;
2485 av_dict_set(meta, "service_provider", "cin5", 0);
2486 const char *path = fmt_ctx->filename, *bp = strrchr(path,'/');
2487 if( bp ) path = bp + 1;
2488 av_dict_set(meta, "title", path, 0);
2490 if( ffaudio.size() ) {
2491 const char *ep = getenv("CIN_AUDIO_LANG"), *lp = 0;
2492 if( !ep && (lp=getenv("LANG")) ) { // some are guesses
2493 static struct { const char lc[3], lng[4]; } lcode[] = {
2494 { "en", "eng" }, { "de", "ger" }, { "es", "spa" },
2495 { "eu", "bas" }, { "fr", "fre" }, { "el", "gre" },
2496 { "hi", "hin" }, { "it", "ita" }, { "ja", "jap" },
2497 { "ko", "kor" }, { "du", "dut" }, { "pl", "pol" },
2498 { "pt", "por" }, { "ru", "rus" }, { "sl", "slv" },
2499 { "uk", "ukr" }, { "vi", "vie" }, { "zh", "chi" },
2501 for( int i=sizeof(lcode)/sizeof(lcode[0]); --i>=0 && !ep; )
2502 if( !strncmp(lcode[i].lc,lp,2) ) ep = lcode[i].lng;
2504 if( !ep ) ep = "und";
2506 strncpy(lang,ep,3); lang[3] = 0;
2507 AVStream *st = ffaudio[0]->st;
2508 av_dict_set(&st->metadata,"language",lang,0);
2511 AVDictionary *fopts = 0;
2512 char option_path[BCTEXTLEN];
2513 set_option_path(option_path, "format/%s", file_format);
2514 read_options(option_path, fopts, 1);
2515 ret = avformat_write_header(fmt_ctx, &fopts);
2517 ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
2521 av_dict_free(&fopts);
2528 int FFMPEG::audio_seek(int stream, int64_t pos)
2530 int aidx = astrm_index[stream].st_idx;
2531 FFAudioStream *aud = ffaudio[aidx];
2532 aud->audio_seek(pos);
2536 int FFMPEG::video_seek(int stream, int64_t pos)
2538 int vidx = vstrm_index[stream].st_idx;
2539 FFVideoStream *vid = ffvideo[vidx];
2540 vid->video_seek(pos);
2545 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
2547 if( !has_audio || chn >= astrm_index.size() ) return -1;
2548 int aidx = astrm_index[chn].st_idx;
2549 FFAudioStream *aud = ffaudio[aidx];
2550 if( aud->load(pos, len) < len ) return -1;
2551 int ch = astrm_index[chn].st_ch;
2552 int ret = aud->read(samples,len,ch);
2556 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
2558 if( !has_video || layer >= vstrm_index.size() ) return -1;
2559 int vidx = vstrm_index[layer].st_idx;
2560 FFVideoStream *vid = ffvideo[vidx];
2561 return vid->load(vframe, pos);
2565 int FFMPEG::encode(int stream, double **samples, int len)
2567 FFAudioStream *aud = ffaudio[stream];
2568 return aud->encode(samples, len);
2572 int FFMPEG::encode(int stream, VFrame *frame)
2574 FFVideoStream *vid = ffvideo[stream];
2575 return vid->encode(frame);
2578 void FFMPEG::start_muxer()
2586 void FFMPEG::stop_muxer()
2595 void FFMPEG::flow_off()
2598 flow_lock->lock("FFMPEG::flow_off");
2602 void FFMPEG::flow_on()
2606 flow_lock->unlock();
2609 void FFMPEG::flow_ctl()
2612 flow_lock->lock("FFMPEG::flow_ctl");
2613 flow_lock->unlock();
2617 int FFMPEG::mux_audio(FFrame *frm)
2619 FFStream *fst = frm->fst;
2620 AVCodecContext *ctx = fst->avctx;
2621 AVFrame *frame = *frm;
2622 AVRational tick_rate = {1, ctx->sample_rate};
2623 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
2624 int ret = fst->encode_frame(frame);
2626 ff_err(ret, "FFMPEG::mux_audio");
2627 return ret >= 0 ? 0 : 1;
2630 int FFMPEG::mux_video(FFrame *frm)
2632 FFStream *fst = frm->fst;
2633 AVFrame *frame = *frm;
2634 frame->pts = frm->position;
2635 int ret = fst->encode_frame(frame);
2637 ff_err(ret, "FFMPEG::mux_video");
2638 return ret >= 0 ? 0 : 1;
2644 double atm = -1, vtm = -1;
2645 FFrame *afrm = 0, *vfrm = 0;
2647 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
2648 FFStream *fst = ffaudio[i];
2649 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
2650 FFrame *frm = fst->frms.first;
2651 if( !frm ) { if( !done ) return; continue; }
2652 double tm = to_secs(frm->position, fst->avctx->time_base);
2653 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
2655 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
2656 FFStream *fst = ffvideo[i];
2657 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
2658 FFrame *frm = fst->frms.first;
2659 if( !frm ) { if( !done ) return; continue; }
2660 double tm = to_secs(frm->position, fst->avctx->time_base);
2661 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
2663 if( !demand ) flow_off();
2664 if( !afrm && !vfrm ) break;
2665 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
2666 vfrm->position, vfrm->fst->avctx->time_base,
2667 afrm->position, afrm->fst->avctx->time_base);
2668 FFrame *frm = v <= 0 ? vfrm : afrm;
2669 if( frm == afrm ) mux_audio(frm);
2670 if( frm == vfrm ) mux_video(frm);
2679 mux_lock->lock("FFMPEG::run");
2682 for( int i=0; i<ffaudio.size(); ++i )
2683 ffaudio[i]->drain();
2684 for( int i=0; i<ffvideo.size(); ++i )
2685 ffvideo[i]->drain();
2687 for( int i=0; i<ffaudio.size(); ++i )
2688 ffaudio[i]->flush();
2689 for( int i=0; i<ffvideo.size(); ++i )
2690 ffvideo[i]->flush();
2694 int FFMPEG::ff_total_audio_channels()
2696 return astrm_index.size();
2699 int FFMPEG::ff_total_astreams()
2701 return ffaudio.size();
2704 int FFMPEG::ff_audio_channels(int stream)
2706 return ffaudio[stream]->channels;
2709 int FFMPEG::ff_sample_rate(int stream)
2711 return ffaudio[stream]->sample_rate;
2714 const char* FFMPEG::ff_audio_format(int stream)
2716 AVStream *st = ffaudio[stream]->st;
2717 AVCodecID id = st->codecpar->codec_id;
2718 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2719 return desc ? desc->name : _("Unknown");
2722 int FFMPEG::ff_audio_pid(int stream)
2724 return ffaudio[stream]->st->id;
2727 int64_t FFMPEG::ff_audio_samples(int stream)
2729 return ffaudio[stream]->length;
2732 // find audio astream/channels with this program,
2733 // or all program audio channels (astream=-1)
2734 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
2738 int vidx = ffvideo[vstream]->fidx;
2739 // find first program with this video stream
2740 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
2741 AVProgram *pgrm = fmt_ctx->programs[i];
2742 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
2743 int st_idx = pgrm->stream_index[j];
2744 AVStream *st = fmt_ctx->streams[st_idx];
2745 if( st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
2746 if( st_idx == vidx ) pidx = i;
2749 if( pidx < 0 ) return -1;
2751 int64_t channels = 0;
2752 AVProgram *pgrm = fmt_ctx->programs[pidx];
2753 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2754 int aidx = pgrm->stream_index[j];
2755 AVStream *st = fmt_ctx->streams[aidx];
2756 if( st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
2757 if( astream > 0 ) { --astream; continue; }
2759 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
2760 if( ffaudio[i]->fidx == aidx ) astrm = i;
2762 if( ret < 0 ) ret = astrm;
2763 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
2764 channels |= mask << ffaudio[astrm]->channel0;
2766 if( !astream ) break;
2768 channel_mask = channels;
2773 int FFMPEG::ff_total_video_layers()
2775 return vstrm_index.size();
2778 int FFMPEG::ff_total_vstreams()
2780 return ffvideo.size();
2783 int FFMPEG::ff_video_width(int stream)
2785 return ffvideo[stream]->width;
2788 int FFMPEG::ff_video_height(int stream)
2790 return ffvideo[stream]->height;
2793 int FFMPEG::ff_set_video_width(int stream, int width)
2795 int w = ffvideo[stream]->width;
2796 ffvideo[stream]->width = width;
2800 int FFMPEG::ff_set_video_height(int stream, int height)
2802 int h = ffvideo[stream]->height;
2803 ffvideo[stream]->height = height;
2807 int FFMPEG::ff_coded_width(int stream)
2809 return ffvideo[stream]->avctx->coded_width;
2812 int FFMPEG::ff_coded_height(int stream)
2814 return ffvideo[stream]->avctx->coded_height;
2817 float FFMPEG::ff_aspect_ratio(int stream)
2819 return ffvideo[stream]->aspect_ratio;
2822 const char* FFMPEG::ff_video_format(int stream)
2824 AVStream *st = ffvideo[stream]->st;
2825 AVCodecID id = st->codecpar->codec_id;
2826 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2827 return desc ? desc->name : _("Unknown");
2830 double FFMPEG::ff_frame_rate(int stream)
2832 return ffvideo[stream]->frame_rate;
2835 int64_t FFMPEG::ff_video_frames(int stream)
2837 return ffvideo[stream]->length;
2840 int FFMPEG::ff_video_pid(int stream)
2842 return ffvideo[stream]->st->id;
2845 int FFMPEG::ff_video_mpeg_color_range(int stream)
2847 return ffvideo[stream]->st->codecpar->color_range == AVCOL_RANGE_MPEG ? 1 : 0;
2850 int FFMPEG::ff_cpus()
2852 return file_base->file->cpus;
2855 int FFVideoStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
2857 avfilter_register_all();
2858 const char *sp = filter_spec;
2859 char filter_name[BCSTRLEN], *np = filter_name;
2860 int i = sizeof(filter_name);
2861 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
2863 AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
2864 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_VIDEO ) {
2865 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
2868 filter_graph = avfilter_graph_alloc();
2869 AVFilter *buffersrc = avfilter_get_by_name("buffer");
2870 AVFilter *buffersink = avfilter_get_by_name("buffersink");
2872 int ret = 0; char args[BCTEXTLEN];
2873 AVPixelFormat pix_fmt = (AVPixelFormat)avpar->format;
2874 snprintf(args, sizeof(args),
2875 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
2876 avpar->width, avpar->height, (int)pix_fmt,
2877 st->time_base.num, st->time_base.den,
2878 avpar->sample_aspect_ratio.num, avpar->sample_aspect_ratio.den);
2880 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2881 args, NULL, filter_graph);
2883 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2884 NULL, NULL, filter_graph);
2886 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
2887 (uint8_t*)&pix_fmt, sizeof(pix_fmt),
2888 AV_OPT_SEARCH_CHILDREN);
2890 ff_err(ret, "FFVideoStream::create_filter");
2892 ret = FFStream::create_filter(filter_spec);
2893 return ret >= 0 ? 0 : -1;
2896 int FFAudioStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
2898 avfilter_register_all();
2899 const char *sp = filter_spec;
2900 char filter_name[BCSTRLEN], *np = filter_name;
2901 int i = sizeof(filter_name);
2902 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
2904 AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
2905 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_AUDIO ) {
2906 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
2909 filter_graph = avfilter_graph_alloc();
2910 AVFilter *buffersrc = avfilter_get_by_name("abuffer");
2911 AVFilter *buffersink = avfilter_get_by_name("abuffersink");
2912 int ret = 0; char args[BCTEXTLEN];
2913 AVSampleFormat sample_fmt = (AVSampleFormat)avpar->format;
2914 snprintf(args, sizeof(args),
2915 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
2916 st->time_base.num, st->time_base.den, avpar->sample_rate,
2917 av_get_sample_fmt_name(sample_fmt), avpar->channel_layout);
2919 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2920 args, NULL, filter_graph);
2922 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2923 NULL, NULL, filter_graph);
2925 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
2926 (uint8_t*)&sample_fmt, sizeof(sample_fmt),
2927 AV_OPT_SEARCH_CHILDREN);
2929 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
2930 (uint8_t*)&avpar->channel_layout,
2931 sizeof(avpar->channel_layout), AV_OPT_SEARCH_CHILDREN);
2933 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
2934 (uint8_t*)&sample_rate, sizeof(sample_rate),
2935 AV_OPT_SEARCH_CHILDREN);
2937 ff_err(ret, "FFAudioStream::create_filter");
2939 ret = FFStream::create_filter(filter_spec);
2940 return ret >= 0 ? 0 : -1;
2943 int FFStream::create_filter(const char *filter_spec)
2945 /* Endpoints for the filter graph. */
2946 AVFilterInOut *outputs = avfilter_inout_alloc();
2947 outputs->name = av_strdup("in");
2948 outputs->filter_ctx = buffersrc_ctx;
2949 outputs->pad_idx = 0;
2952 AVFilterInOut *inputs = avfilter_inout_alloc();
2953 inputs->name = av_strdup("out");
2954 inputs->filter_ctx = buffersink_ctx;
2955 inputs->pad_idx = 0;
2958 int ret = !outputs->name || !inputs->name ? -1 : 0;
2960 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
2961 &inputs, &outputs, NULL);
2963 ret = avfilter_graph_config(filter_graph, NULL);
2966 ff_err(ret, "FFStream::create_filter");
2967 avfilter_graph_free(&filter_graph);
2970 avfilter_inout_free(&inputs);
2971 avfilter_inout_free(&outputs);
2975 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
2978 av_init_packet(&pkt);
2979 AVFrame *frame = av_frame_alloc();
2981 fprintf(stderr,"FFMPEG::scan: ");
2982 fprintf(stderr,_("av_frame_alloc failed\n"));
2986 index_state->add_video_markers(ffvideo.size());
2987 index_state->add_audio_markers(ffaudio.size());
2989 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2991 AVDictionary *copts = 0;
2992 av_dict_copy(&copts, opts, 0);
2993 AVStream *st = fmt_ctx->streams[i];
2994 AVCodecID codec_id = st->codecpar->codec_id;
2995 AVCodec *decoder = avcodec_find_decoder(codec_id);
2996 AVCodecContext *avctx = avcodec_alloc_context3(decoder);
2998 eprintf(_("cant allocate codec context\n"));
2999 ret = AVERROR(ENOMEM);
3002 avcodec_parameters_to_context(avctx, st->codecpar);
3003 if( !av_dict_get(copts, "threads", NULL, 0) )
3004 avctx->thread_count = ff_cpus();
3005 ret = avcodec_open2(avctx, decoder, &copts);
3007 av_dict_free(&copts);
3009 AVCodecParameters *avpar = st->codecpar;
3010 switch( avpar->codec_type ) {
3011 case AVMEDIA_TYPE_VIDEO: {
3012 int vidx = ffvideo.size();
3013 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
3014 if( vidx < 0 ) break;
3015 ffvideo[vidx]->avctx = avctx;
3017 case AVMEDIA_TYPE_AUDIO: {
3018 int aidx = ffaudio.size();
3019 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3020 if( aidx < 0 ) break;
3021 ffaudio[aidx]->avctx = avctx;
3026 fprintf(stderr,"FFMPEG::scan: ");
3027 fprintf(stderr,_("codec open failed\n"));
3028 avcodec_free_context(&avctx);
3032 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
3033 AVStream *st = fmt_ctx->streams[i];
3034 AVCodecParameters *avpar = st->codecpar;
3035 if( avpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
3036 int64_t tstmp = st->start_time;
3037 if( tstmp == AV_NOPTS_VALUE ) continue;
3038 int aidx = ffaudio.size();
3039 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3040 if( aidx < 0 ) continue;
3041 FFAudioStream *aud = ffaudio[aidx];
3042 tstmp -= aud->nudge;
3043 double secs = to_secs(tstmp, st->time_base);
3044 aud->curr_pos = secs * aud->sample_rate + 0.5;
3048 for( int64_t count=0; !*canceled; ++count ) {
3049 av_packet_unref(&pkt);
3050 pkt.data = 0; pkt.size = 0;
3052 int ret = av_read_frame(fmt_ctx, &pkt);
3054 if( ret == AVERROR_EOF ) break;
3055 if( ++errs > 100 ) {
3056 ff_err(ret,_("over 100 read_frame errs\n"));
3061 if( !pkt.data ) continue;
3062 int i = pkt.stream_index;
3063 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
3064 AVStream *st = fmt_ctx->streams[i];
3065 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
3067 AVCodecParameters *avpar = st->codecpar;
3068 switch( avpar->codec_type ) {
3069 case AVMEDIA_TYPE_VIDEO: {
3070 int vidx = ffvideo.size();
3071 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
3072 if( vidx < 0 ) break;
3073 FFVideoStream *vid = ffvideo[vidx];
3074 if( !vid->avctx ) break;
3075 int64_t tstmp = pkt.dts;
3076 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.pts;
3077 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
3078 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
3079 double secs = to_secs(tstmp, st->time_base);
3080 int64_t frm = secs * vid->frame_rate + 0.5;
3081 if( frm < 0 ) frm = 0;
3082 index_state->put_video_mark(vidx, frm, pkt.pos);
3085 ret = avcodec_send_packet(vid->avctx, pkt);
3086 if( ret < 0 ) break;
3087 while( (ret=vid->decode_frame(frame)) > 0 ) {}
3090 case AVMEDIA_TYPE_AUDIO: {
3091 int aidx = ffaudio.size();
3092 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3093 if( aidx < 0 ) break;
3094 FFAudioStream *aud = ffaudio[aidx];
3095 if( !aud->avctx ) break;
3096 int64_t tstmp = pkt.pts;
3097 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
3098 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
3099 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
3100 double secs = to_secs(tstmp, st->time_base);
3101 int64_t sample = secs * aud->sample_rate + 0.5;
3103 index_state->put_audio_mark(aidx, sample, pkt.pos);
3105 ret = avcodec_send_packet(aud->avctx, &pkt);
3106 if( ret < 0 ) break;
3107 int ch = aud->channel0, nch = aud->channels;
3108 int64_t pos = index_state->pos(ch);
3109 if( pos != aud->curr_pos ) {
3110 if( abs(pos-aud->curr_pos) > 1 )
3111 printf("audio%d pad %jd %jd (%jd)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
3112 index_state->pad_data(ch, nch, aud->curr_pos);
3114 while( (ret=aud->decode_frame(frame)) > 0 ) {
3115 //if( frame->channels != nch ) break;
3116 aud->init_swr(frame->channels, frame->format, frame->sample_rate);
3118 int len = aud->get_samples(samples,
3119 &frame->extended_data[0], frame->nb_samples);
3120 pos = aud->curr_pos;
3121 if( (aud->curr_pos += len) >= 0 ) {
3123 samples += -pos * nch;
3124 len = aud->curr_pos;
3126 for( int i=0; i<nch; ++i )
3127 index_state->put_data(ch+i,nch,samples+i,len);
3134 av_frame_free(&frame);
3138 void FFStream::load_markers(IndexMarks &marks, double rate)
3141 int64_t sz = marks.size();
3142 int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
3143 int nb_ent = st->nb_index_entries;
3144 // some formats already have an index
3146 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
3147 int64_t tstmp = ep->timestamp;
3148 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
3149 double secs = ffmpeg->to_secs(tstmp, st->time_base);
3150 int64_t no = secs * rate;
3151 while( in < sz && marks[in].no <= no ) ++in;
3153 int64_t len = sz - in;
3154 int64_t count = max_entries - nb_ent;
3155 if( count > len ) count = len;
3156 for( int i=0; i<count; ++i ) {
3157 int k = in + i * len / count;
3158 int64_t no = marks[k].no, pos = marks[k].pos;
3159 double secs = (double)no / rate;
3160 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
3161 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
3162 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);