12 // work arounds (centos)
15 #define INT64_MAX 9223372036854775807LL
17 #define MAX_RETRY 1000
18 // max pts/curr_pos drift allowed before correction (in seconds)
19 #define AUDIO_PTS_TOLERANCE 0.04
22 #include "bccmodels.h"
25 #include "edlsession.h"
27 #include "fileffmpeg.h"
28 #include "filesystem.h"
30 #include "indexfile.h"
31 #include "interlacemodes.h"
34 #include "mainerror.h"
41 #define av_register_all(s)
42 #define avfilter_register_all(s)
45 #define VIDEO_INBUF_SIZE 0x10000
46 #define AUDIO_INBUF_SIZE 0x10000
47 #define VIDEO_REFILL_THRESH 0
48 #define AUDIO_REFILL_THRESH 0x1000
49 #define AUDIO_MIN_FRAME_SZ 128
51 #define FF_ESTM_TIMES 0x0001
52 #define FF_BAD_TIMES 0x0002
54 Mutex FFMPEG::fflock("FFMPEG::fflock");
56 static void ff_err(int ret, const char *fmt, ...)
61 vsnprintf(msg, sizeof(msg), fmt, ap);
63 char errmsg[BCSTRLEN];
64 av_strerror(ret, errmsg, sizeof(errmsg));
65 fprintf(stderr,_("%s err: %s\n"),msg, errmsg);
71 pkt.data = 0; pkt.size = 0;
73 void FFPacket::finit()
75 av_packet_unref(&pkt);
78 FFrame::FFrame(FFStream *fst)
81 frm = av_frame_alloc();
82 init = fst->init_frame(frm);
90 void FFrame::queue(int64_t pos)
96 void FFrame::dequeue()
101 int FFAudioStream::read(float *fp, long len)
109 while( --k >= 0 ) *fp++ = *op++;
110 if( op >= lmt ) op = bfr;
115 void FFAudioStream::realloc(long nsz, int nch, long len)
117 long bsz = nsz * nch;
118 float *np = new float[bsz];
119 inp = np + read(np, len) * nch;
124 delete [] bfr; bfr = np;
127 void FFAudioStream::realloc(long nsz, int nch)
129 if( nsz > sz || this->nch != nch ) {
130 long len = this->nch != nch ? 0 : hpos;
131 if( len > sz ) len = sz;
133 realloc(nsz, nch, len);
137 void FFAudioStream::reserve(long nsz, int nch)
139 long len = (inp - outp) / nch;
141 if( nsz > sz || this->nch != nch ) {
142 if( this->nch != nch ) len = 0;
143 realloc(nsz, nch, len);
146 if( (len*=nch) > 0 && bfr != outp )
147 memmove(bfr, outp, len*sizeof(*bfr));
152 long FFAudioStream::used()
154 long len = inp>=outp ? inp-outp : inp-bfr + lmt-outp;
157 long FFAudioStream::avail()
160 if( in1 >= lmt ) in1 = bfr;
161 long len = outp >= in1 ? outp-in1 : outp-bfr + lmt-in1;
164 void FFAudioStream::reset_history()
168 memset(bfr, 0, lmt-bfr);
171 void FFAudioStream::iseek(int64_t ofs)
173 if( ofs > hpos ) ofs = hpos;
174 if( ofs > sz ) ofs = sz;
175 outp = inp - ofs*nch;
176 if( outp < bfr ) outp += sz*nch;
179 float *FFAudioStream::get_outp(int ofs)
186 int64_t FFAudioStream::put_inp(int ofs)
189 return (inp-outp) / nch;
192 int FFAudioStream::write(const float *fp, long len)
200 while( --k >= 0 ) *ip++ = *fp++;
201 if( ip >= lmt ) ip = bfr;
208 int FFAudioStream::zero(long len)
216 while( --k >= 0 ) *ip++ = 0;
217 if( ip >= lmt ) ip = bfr;
224 // does not advance outp
225 int FFAudioStream::read(double *dp, long len, int ch)
228 float *op = outp + ch;
229 float *lmt1 = lmt + nch-1;
231 int k = (lmt1 - op) / nch;
234 while( --k >= 0 ) { *dp++ = *op; op += nch; }
235 if( op >= lmt ) op -= sz*nch;
240 // load linear buffer, no wrapping allowed, does not advance inp
241 int FFAudioStream::write(const double *dp, long len, int ch)
244 float *ip = inp + ch;
245 while( --n >= 0 ) { *ip = *dp++; ip += nch; }
250 FFStream::FFStream(FFMPEG *ffmpeg, AVStream *st, int fidx)
252 this->ffmpeg = ffmpeg;
255 frm_lock = new Mutex("FFStream::frm_lock");
262 nudge = AV_NOPTS_VALUE;
263 seek_pos = curr_pos = 0;
265 reading = writing = 0;
276 FFStream::~FFStream()
278 if( reading > 0 || writing > 0 ) avcodec_close(avctx);
279 if( avctx ) avcodec_free_context(&avctx);
280 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
281 if( bsfc ) av_bsf_free(&bsfc);
282 while( frms.first ) frms.remove(frms.first);
283 if( filter_graph ) avfilter_graph_free(&filter_graph);
284 if( frame ) av_frame_free(&frame);
285 if( fframe ) av_frame_free(&fframe);
287 if( stats_fp ) fclose(stats_fp);
288 if( stats_in ) av_freep(&stats_in);
289 delete [] stats_filename;
292 void FFStream::ff_lock(const char *cp)
294 FFMPEG::fflock.lock(cp);
297 void FFStream::ff_unlock()
299 FFMPEG::fflock.unlock();
302 void FFStream::queue(FFrame *frm)
304 frm_lock->lock("FFStream::queue");
308 ffmpeg->mux_lock->unlock();
311 void FFStream::dequeue(FFrame *frm)
313 frm_lock->lock("FFStream::dequeue");
315 frms.remove_pointer(frm);
319 int FFStream::encode_activate()
322 writing = ffmpeg->encode_activate();
326 int FFStream::decode_activate()
328 if( reading < 0 && (reading=ffmpeg->decode_activate()) > 0 ) {
329 ff_lock("FFStream::decode_activate");
331 AVDictionary *copts = 0;
332 av_dict_copy(&copts, ffmpeg->opts, 0);
334 // this should be avformat_copy_context(), but no copy avail
335 ret = avformat_open_input(&fmt_ctx,
336 ffmpeg->fmt_ctx->url, ffmpeg->fmt_ctx->iformat, &copts);
338 ret = avformat_find_stream_info(fmt_ctx, 0);
339 st = fmt_ctx->streams[fidx];
342 if( ret >= 0 && st != 0 ) {
343 AVCodecID codec_id = st->codecpar->codec_id;
344 AVCodec *decoder = avcodec_find_decoder(codec_id);
345 avctx = avcodec_alloc_context3(decoder);
347 eprintf(_("cant allocate codec context\n"));
348 ret = AVERROR(ENOMEM);
351 avcodec_parameters_to_context(avctx, st->codecpar);
352 if( !av_dict_get(copts, "threads", NULL, 0) )
353 avctx->thread_count = ffmpeg->ff_cpus();
354 ret = avcodec_open2(avctx, decoder, &copts);
360 eprintf(_("open decoder failed\n"));
363 eprintf(_("can't clone input file\n"));
364 av_dict_free(&copts);
370 int FFStream::read_packet()
372 av_packet_unref(ipkt);
373 int ret = av_read_frame(fmt_ctx, ipkt);
376 if( ret == AVERROR_EOF ) return 0;
377 ff_err(ret, "FFStream::read_packet: av_read_frame failed\n");
384 int FFStream::decode(AVFrame *frame)
387 int retries = MAX_RETRY;
389 while( ret >= 0 && !flushed && --retries >= 0 ) {
391 if( (ret=read_packet()) < 0 ) break;
392 AVPacket *pkt = ret > 0 ? (AVPacket*)ipkt : 0;
394 if( pkt->stream_index != st->index ) continue;
395 if( !pkt->data | !pkt->size ) continue;
397 if( (ret=avcodec_send_packet(avctx, pkt)) < 0 ) {
398 ff_err(ret, "FFStream::decode: avcodec_send_packet failed\n");
404 if( (ret=decode_frame(frame)) > 0 ) break;
412 fprintf(stderr, "FFStream::decode: Retry limit\n");
416 fprintf(stderr, "FFStream::decode: failed\n");
420 int FFStream::load_filter(AVFrame *frame)
422 int ret = av_buffersrc_add_frame_flags(buffersrc_ctx, frame, 0);
424 eprintf(_("av_buffersrc_add_frame_flags failed\n"));
428 int FFStream::read_filter(AVFrame *frame)
430 int ret = av_buffersink_get_frame(buffersink_ctx, frame);
432 if( ret == AVERROR(EAGAIN) ) return 0;
433 if( ret == AVERROR_EOF ) { st_eof(1); return -1; }
434 ff_err(ret, "FFStream::read_filter: av_buffersink_get_frame failed\n");
440 int FFStream::read_frame(AVFrame *frame)
442 av_frame_unref(frame);
443 if( !filter_graph || !buffersrc_ctx || !buffersink_ctx )
444 return decode(frame);
445 if( !fframe && !(fframe=av_frame_alloc()) ) {
446 fprintf(stderr, "FFStream::read_frame: av_frame_alloc failed\n");
450 while( !flushed && !(ret=read_filter(frame)) ) {
451 if( (ret=decode(fframe)) < 0 ) break;
452 if( ret > 0 && (ret=load_filter(fframe)) < 0 ) break;
457 int FFStream::write_packet(FFPacket &pkt)
461 av_packet_rescale_ts(pkt, avctx->time_base, st->time_base);
462 pkt->stream_index = st->index;
463 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, pkt);
466 ret = av_bsf_send_packet(bsfc, pkt);
469 if( (ret=av_bsf_receive_packet(bsfc, bs)) < 0 ) {
470 if( ret == AVERROR(EAGAIN) ) return 0;
471 if( ret == AVERROR_EOF ) return -1;
474 av_packet_rescale_ts(bs, avctx->time_base, st->time_base);
475 bs->stream_index = st->index;
476 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, bs);
480 ff_err(ret, "FFStream::write_packet: write packet failed\n");
484 int FFStream::encode_frame(AVFrame *frame)
486 int pkts = 0, ret = 0;
487 for( int retry=MAX_RETRY; --retry>=0; ) {
489 ret = avcodec_send_frame(avctx, frame);
490 if( !ret && frame ) return pkts;
491 if( ret < 0 && ret != AVERROR(EAGAIN) ) break;
493 ret = avcodec_receive_packet(avctx, opkt);
494 if( !frame && ret == AVERROR_EOF ) return pkts;
496 ret = write_packet(opkt);
499 if( frame && stats_fp ) {
500 ret = write_stats_file();
504 ff_err(ret, "FFStream::encode_frame: encode failed\n");
508 int FFStream::flush()
512 int ret = encode_frame(0);
513 if( ret >= 0 && stats_fp ) {
514 ret = write_stats_file();
518 ff_err(ret, "FFStream::flush");
519 return ret >= 0 ? 0 : 1;
523 int FFStream::open_stats_file()
525 stats_fp = fopen(stats_filename,"w");
526 return stats_fp ? 0 : AVERROR(errno);
529 int FFStream::close_stats_file()
532 fclose(stats_fp); stats_fp = 0;
537 int FFStream::read_stats_file()
539 int64_t len = 0; struct stat stats_st;
540 int fd = open(stats_filename, O_RDONLY);
541 int ret = fd >= 0 ? 0: ENOENT;
542 if( !ret && fstat(fd, &stats_st) )
545 len = stats_st.st_size;
546 stats_in = (char *)av_malloc(len+1);
550 if( !ret && read(fd, stats_in, len+1) != len )
554 avctx->stats_in = stats_in;
558 return !ret ? 0 : AVERROR(ret);
561 int FFStream::write_stats_file()
564 if( avctx->stats_out && (ret=strlen(avctx->stats_out)) > 0 ) {
565 int len = fwrite(avctx->stats_out, 1, ret, stats_fp);
567 ff_err(ret = AVERROR(errno), "FFStream::write_stats_file");
572 int FFStream::init_stats_file()
575 if( (pass & 2) && (ret = read_stats_file()) < 0 )
576 ff_err(ret, "stat file read: %s", stats_filename);
577 if( (pass & 1) && (ret=open_stats_file()) < 0 )
578 ff_err(ret, "stat file open: %s", stats_filename);
579 return ret >= 0 ? 0 : ret;
582 int FFStream::seek(int64_t no, double rate)
584 // default ffmpeg native seek
586 int64_t pos = no, pkt_pos = -1;
587 IndexMarks *index_markers = get_markers();
588 if( index_markers && index_markers->size() > 1 ) {
589 IndexMarks &marks = *index_markers;
590 int i = marks.find(pos);
591 int64_t n = i < 0 ? (i=0) : marks[i].no;
592 // if indexed seek point not too far away (<30 secs), use index
593 if( no-n < 30*rate ) {
596 if( i < marks.size() ) pkt_pos = marks[i].pos;
600 if( pos == curr_pos ) return 0;
601 double secs = pos < 0 ? 0. : pos / rate;
602 AVRational time_base = st->time_base;
603 int64_t tstmp = time_base.num > 0 ? secs * time_base.den/time_base.num : 0;
605 if( st->nb_index_entries > 0 ) tstmp = st->index_entries[0].timestamp;
606 else if( st->start_time != AV_NOPTS_VALUE ) tstmp = st->start_time;
607 else if( st->first_dts != AV_NOPTS_VALUE ) tstmp = st->first_dts;
608 else tstmp = INT64_MIN+1;
610 else if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
613 // seek all streams using the default timebase.
614 // this is how ffmpeg and ffplay work. stream seeks are less tested.
615 tstmp = av_rescale_q(tstmp, time_base, AV_TIME_BASE_Q);
619 avcodec_flush_buffers(avctx);
620 avformat_flush(fmt_ctx);
622 int64_t seek = tstmp;
623 int flags = AVSEEK_FLAG_ANY;
624 if( !(fmt_ctx->iformat->flags & AVFMT_NO_BYTE_SEEK) && pkt_pos >= 0 ) {
626 flags = AVSEEK_FLAG_BYTE;
628 int ret = avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, seek, INT64_MAX, flags);
630 // finds the first index frame below the target time
631 int flags = AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_ANY;
632 int ret = av_seek_frame(fmt_ctx, idx, tstmp, flags);
634 int retry = MAX_RETRY;
636 need_packet = 0; flushed = 0;
637 seeked = 1; st_eof(0);
638 // read up to retry packets, limited to npkts in stream, and not pkt.pos past pkt_pos
639 while( --retry >= 0 ) {
640 if( read_packet() <= 0 ) { ret = -1; break; }
641 if( ipkt->stream_index != st->index ) continue;
642 if( !ipkt->data || !ipkt->size ) continue;
643 if( pkt_pos >= 0 && ipkt->pos >= pkt_pos ) break;
644 if( --npkts <= 0 ) break;
645 int64_t pkt_ts = ipkt->dts != AV_NOPTS_VALUE ? ipkt->dts : ipkt->pts;
646 if( pkt_ts == AV_NOPTS_VALUE ) continue;
647 if( pkt_ts >= tstmp ) break;
650 fprintf(stderr,"FFStream::seek: retry limit, pos=%jd tstmp=%jd\n",pos,tstmp);
654 ret = avcodec_send_packet(avctx, ipkt);
656 //some codecs need more than one pkt to resync
657 if( ret == AVERROR_INVALIDDATA ) ret = 0;
659 ff_err(ret, "FFStream::avcodec_send_packet failed\n");
664 printf("** seek fail %jd, %jd\n", pos, tstmp);
665 seeked = need_packet = 0;
669 //printf("seeked pos = %ld, %ld\n", pos, tstmp);
670 seek_pos = curr_pos = pos;
674 FFAudioStream::FFAudioStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
675 : FFStream(ffmpeg, strm, fidx)
678 channel0 = channels = 0;
681 frame_sz = AUDIO_MIN_FRAME_SZ;
683 resample_context = 0;
684 swr_ichs = swr_ifmt = swr_irate = 0;
693 bfr = new float[bsz];
698 FFAudioStream::~FFAudioStream()
700 if( resample_context ) swr_free(&resample_context);
705 void FFAudioStream::init_swr(int ichs, int ifmt, int irate)
707 if( resample_context ) {
708 if( swr_ichs == ichs && swr_ifmt == ifmt && swr_irate == irate )
710 swr_free(&resample_context);
712 swr_ichs = ichs; swr_ifmt = ifmt; swr_irate = irate;
713 if( ichs == channels && ifmt == AV_SAMPLE_FMT_FLT && irate == sample_rate )
715 uint64_t ilayout = av_get_default_channel_layout(ichs);
716 if( !ilayout ) ilayout = ((uint64_t)1<<ichs) - 1;
717 uint64_t olayout = av_get_default_channel_layout(channels);
718 if( !olayout ) olayout = ((uint64_t)1<<channels) - 1;
719 resample_context = swr_alloc_set_opts(NULL,
720 olayout, AV_SAMPLE_FMT_FLT, sample_rate,
721 ilayout, (AVSampleFormat)ifmt, irate,
723 if( resample_context )
724 swr_init(resample_context);
727 int FFAudioStream::get_samples(float *&samples, uint8_t **data, int len)
729 samples = *(float **)data;
730 if( resample_context ) {
731 if( len > aud_bfr_sz ) {
737 aud_bfr = new float[aud_bfr_sz*channels];
739 int ret = swr_convert(resample_context,
740 (uint8_t**)&aud_bfr, aud_bfr_sz, (const uint8_t**)data, len);
742 ff_err(ret, "FFAudioStream::get_samples: swr_convert failed\n");
751 int FFAudioStream::load_history(uint8_t **data, int len)
754 len = get_samples(samples, data, len);
756 // biggest user bfr since seek + frame
757 realloc(mbsz + len + 1, channels);
763 int FFAudioStream::decode_frame(AVFrame *frame)
765 int first_frame = seeked; seeked = 0;
766 frame->best_effort_timestamp = AV_NOPTS_VALUE;
767 int ret = avcodec_receive_frame(avctx, frame);
769 if( first_frame || ret == AVERROR(EAGAIN) ) return 0;
770 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
771 ff_err(ret, "FFAudioStream::decode_frame: Could not read audio frame\n");
774 int64_t pkt_ts = frame->best_effort_timestamp;
775 if( pkt_ts != AV_NOPTS_VALUE ) {
776 double ts = ffmpeg->to_secs(pkt_ts - nudge, st->time_base);
777 double t = (double)curr_pos / sample_rate;
778 // some time_base clocks are very grainy, too grainy for audio (clicks, pops)
779 if( fabs(ts - t) > AUDIO_PTS_TOLERANCE )
780 curr_pos = ts * sample_rate + 0.5;
785 int FFAudioStream::encode_activate()
787 if( writing >= 0 ) return writing;
788 if( !avctx->codec ) return writing = 0;
789 frame_sz = avctx->codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE ?
790 10000 : avctx->frame_size;
791 return FFStream::encode_activate();
794 int64_t FFAudioStream::load_buffer(double ** const sp, int len)
796 reserve(len+1, st->codecpar->channels);
797 for( int ch=0; ch<nch; ++ch )
798 write(sp[ch], len, ch);
802 int FFAudioStream::in_history(int64_t pos)
804 if( pos > curr_pos ) return 0;
806 if( len > sz ) len = sz;
807 if( pos < curr_pos - len ) return 0;
812 int FFAudioStream::init_frame(AVFrame *frame)
814 frame->nb_samples = frame_sz;
815 frame->format = avctx->sample_fmt;
816 frame->channel_layout = avctx->channel_layout;
817 frame->sample_rate = avctx->sample_rate;
818 int ret = av_frame_get_buffer(frame, 0);
820 ff_err(ret, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
824 int FFAudioStream::load(int64_t pos, int len)
826 if( audio_seek(pos) < 0 ) return -1;
827 if( !frame && !(frame=av_frame_alloc()) ) {
828 fprintf(stderr, "FFAudioStream::load: av_frame_alloc failed\n");
831 if( mbsz < len ) mbsz = len;
832 int64_t end_pos = pos + len;
833 int ret = 0, i = len / frame_sz + MAX_RETRY;
834 while( ret>=0 && !flushed && curr_pos<end_pos && --i>=0 ) {
835 ret = read_frame(frame);
836 if( ret > 0 && frame->nb_samples > 0 ) {
837 init_swr(frame->channels, frame->format, frame->sample_rate);
838 load_history(&frame->extended_data[0], frame->nb_samples);
839 curr_pos += frame->nb_samples;
842 if( end_pos > curr_pos ) {
843 zero(end_pos - curr_pos);
846 len = curr_pos - pos;
851 int FFAudioStream::audio_seek(int64_t pos)
853 if( decode_activate() <= 0 ) return -1;
854 if( !st->codecpar ) return -1;
855 if( in_history(pos) ) return 0;
856 if( pos == curr_pos ) return 0;
857 reset_history(); mbsz = 0;
858 // guarentee preload > 1sec samples
859 if( (pos-=sample_rate) < 0 ) pos = 0;
860 if( seek(pos, sample_rate) < 0 ) return -1;
864 int FFAudioStream::encode(double **samples, int len)
866 if( encode_activate() <= 0 ) return -1;
869 int64_t count = samples ? load_buffer(samples, len) : used();
870 int frame_sz1 = samples ? frame_sz-1 : 0;
873 while( ret >= 0 && count > frame_sz1 ) {
874 frm = new FFrame(this);
875 if( (ret=frm->initted()) < 0 ) break;
876 AVFrame *frame = *frm;
877 len = count >= frame_sz ? frame_sz : count;
878 float *bfrp = get_outp(len);
879 ret = swr_convert(resample_context,
880 (uint8_t **)frame->extended_data, len,
881 (const uint8_t **)&bfrp, len);
883 ff_err(ret, "FFAudioStream::encode: swr_convert failed\n");
886 frame->nb_samples = len;
887 frm->queue(curr_pos);
894 return ret >= 0 ? 0 : 1;
897 int FFAudioStream::drain()
902 int FFAudioStream::encode_frame(AVFrame *frame)
904 return FFStream::encode_frame(frame);
907 int FFAudioStream::write_packet(FFPacket &pkt)
909 return FFStream::write_packet(pkt);
912 void FFAudioStream::load_markers()
914 IndexState *index_state = ffmpeg->file_base->asset->index_state;
915 if( !index_state || idx >= index_state->audio_markers.size() ) return;
916 if( index_state->marker_status == MARKERS_NOTTESTED ) return;
917 FFStream::load_markers(*index_state->audio_markers[idx], sample_rate);
920 IndexMarks *FFAudioStream::get_markers()
922 IndexState *index_state = ffmpeg->file_base->asset->index_state;
923 if( !index_state || idx >= index_state->audio_markers.size() ) return 0;
924 return index_state->audio_markers[idx];
927 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
928 : FFStream(ffmpeg, strm, fidx)
939 FFVideoStream::~FFVideoStream()
943 int FFVideoStream::decode_frame(AVFrame *frame)
945 int first_frame = seeked; seeked = 0;
946 int ret = avcodec_receive_frame(avctx, frame);
948 if( first_frame || ret == AVERROR(EAGAIN) ) return 0;
949 if( ret == AVERROR(EAGAIN) ) return 0;
950 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
951 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame\n");
954 int64_t pkt_ts = frame->best_effort_timestamp;
955 if( pkt_ts != AV_NOPTS_VALUE )
956 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * frame_rate + 0.5;
960 int FFVideoStream::load(VFrame *vframe, int64_t pos)
962 int ret = video_seek(pos);
963 if( ret < 0 ) return -1;
964 if( !frame && !(frame=av_frame_alloc()) ) {
965 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
968 int i = MAX_RETRY + pos - curr_pos;
969 while( ret>=0 && !flushed && curr_pos<=pos && --i>=0 ) {
970 ret = read_frame(frame);
971 if( ret > 0 ) ++curr_pos;
973 if( frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0 )
976 ret = convert_cmodel(vframe, frame);
978 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
982 int FFVideoStream::video_seek(int64_t pos)
984 if( decode_activate() <= 0 ) return -1;
985 if( !st->codecpar ) return -1;
986 if( pos == curr_pos-1 && !seeked ) return 0;
987 // if close enough, just read up to current
988 int gop = avctx->gop_size;
989 if( gop < 4 ) gop = 4;
990 if( gop > 64 ) gop = 64;
991 int read_limit = curr_pos + 3*gop;
992 if( pos >= curr_pos && pos <= read_limit ) return 0;
993 // guarentee preload more than 2*gop frames
994 if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
998 int FFVideoStream::init_frame(AVFrame *picture)
1000 picture->format = avctx->pix_fmt;
1001 picture->width = avctx->width;
1002 picture->height = avctx->height;
1003 int ret = av_frame_get_buffer(picture, 32);
1007 int FFVideoStream::encode(VFrame *vframe)
1009 if( encode_activate() <= 0 ) return -1;
1011 FFrame *picture = new FFrame(this);
1012 int ret = picture->initted();
1014 AVFrame *frame = *picture;
1015 frame->pts = curr_pos;
1016 ret = convert_pixfmt(vframe, frame);
1019 picture->queue(curr_pos);
1023 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
1026 return ret >= 0 ? 0 : 1;
1029 int FFVideoStream::drain()
1034 int FFVideoStream::encode_frame(AVFrame *frame)
1037 frame->interlaced_frame = interlaced;
1038 frame->top_field_first = top_field_first;
1040 return FFStream::encode_frame(frame);
1043 int FFVideoStream::write_packet(FFPacket &pkt)
1045 if( !(ffmpeg->fmt_ctx->oformat->flags & AVFMT_VARIABLE_FPS) )
1047 return FFStream::write_packet(pkt);
1050 AVPixelFormat FFVideoConvert::color_model_to_pix_fmt(int color_model)
1052 switch( color_model ) {
1053 case BC_YUV422: return AV_PIX_FMT_YUYV422;
1054 case BC_RGB888: return AV_PIX_FMT_RGB24;
1055 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
1056 case BC_BGR8888: return AV_PIX_FMT_BGR0;
1057 case BC_BGR888: return AV_PIX_FMT_BGR24;
1058 case BC_ARGB8888: return AV_PIX_FMT_ARGB;
1059 case BC_ABGR8888: return AV_PIX_FMT_ABGR;
1060 case BC_RGB8: return AV_PIX_FMT_RGB8;
1061 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
1062 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
1063 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
1064 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
1065 case BC_RGB565: return AV_PIX_FMT_RGB565;
1066 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
1067 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
1068 case BC_AYUV16161616: return AV_PIX_FMT_AYUV64LE;
1069 case BC_GBRP: return AV_PIX_FMT_GBRP;
1073 return AV_PIX_FMT_NB;
1076 int FFVideoConvert::pix_fmt_to_color_model(AVPixelFormat pix_fmt)
1079 case AV_PIX_FMT_YUYV422: return BC_YUV422;
1080 case AV_PIX_FMT_RGB24: return BC_RGB888;
1081 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
1082 case AV_PIX_FMT_BGR0: return BC_BGR8888;
1083 case AV_PIX_FMT_BGR24: return BC_BGR888;
1084 case AV_PIX_FMT_ARGB: return BC_ARGB8888;
1085 case AV_PIX_FMT_ABGR: return BC_ABGR8888;
1086 case AV_PIX_FMT_RGB8: return BC_RGB8;
1087 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
1088 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
1089 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
1090 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
1091 case AV_PIX_FMT_RGB565: return BC_RGB565;
1092 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
1093 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
1094 case AV_PIX_FMT_AYUV64LE: return BC_AYUV16161616;
1095 case AV_PIX_FMT_GBRP: return BC_GBRP;
1102 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip)
1104 AVFrame *ipic = av_frame_alloc();
1105 int ret = convert_picture_vframe(frame, ip, ipic);
1106 av_frame_free(&ipic);
1110 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip, AVFrame *ipic)
1112 int cmodel = frame->get_color_model();
1113 AVPixelFormat ofmt = color_model_to_pix_fmt(cmodel);
1114 if( ofmt == AV_PIX_FMT_NB ) return -1;
1115 int size = av_image_fill_arrays(ipic->data, ipic->linesize,
1116 frame->get_data(), ofmt, frame->get_w(), frame->get_h(), 1);
1117 if( size < 0 ) return -1;
1119 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1120 int ysz = bpp * frame->get_w(), usz = ysz;
1130 // override av_image_fill_arrays() for planar types
1131 ipic->data[0] = frame->get_y(); ipic->linesize[0] = ysz;
1132 ipic->data[1] = frame->get_u(); ipic->linesize[1] = usz;
1133 ipic->data[2] = frame->get_v(); ipic->linesize[2] = usz;
1136 ipic->data[0] = frame->get_data();
1137 ipic->linesize[0] = frame->get_bytes_per_line();
1141 AVPixelFormat pix_fmt = (AVPixelFormat)ip->format;
1142 convert_ctx = sws_getCachedContext(convert_ctx, ip->width, ip->height, pix_fmt,
1143 frame->get_w(), frame->get_h(), ofmt, SWS_POINT, NULL, NULL, NULL);
1144 if( !convert_ctx ) {
1145 fprintf(stderr, "FFVideoConvert::convert_picture_frame:"
1146 " sws_getCachedContext() failed\n");
1149 int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ip->height,
1150 ipic->data, ipic->linesize);
1152 ff_err(ret, "FFVideoConvert::convert_picture_frame: sws_scale() failed\n");
1158 int FFVideoConvert::convert_cmodel(VFrame *frame, AVFrame *ip)
1160 // try direct transfer
1161 if( !convert_picture_vframe(frame, ip) ) return 1;
1162 // use indirect transfer
1163 AVPixelFormat ifmt = (AVPixelFormat)ip->format;
1164 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
1166 for( int i = 0; i <desc->nb_components; ++i ) {
1167 int bits = desc->comp[i].depth;
1168 if( bits > max_bits ) max_bits = bits;
1170 int imodel = pix_fmt_to_color_model(ifmt);
1171 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1172 int cmodel = frame->get_color_model();
1173 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1174 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1175 imodel = cmodel_is_yuv ?
1176 (BC_CModels::has_alpha(cmodel) ?
1178 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1179 (BC_CModels::has_alpha(cmodel) ?
1180 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1181 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1183 VFrame vframe(ip->width, ip->height, imodel);
1184 if( convert_picture_vframe(&vframe, ip) ) return -1;
1185 frame->transfer_from(&vframe);
1189 int FFVideoConvert::transfer_cmodel(VFrame *frame, AVFrame *ifp)
1191 int ret = convert_cmodel(frame, ifp);
1193 const AVDictionary *src = ifp->metadata;
1194 AVDictionaryEntry *t = NULL;
1195 BC_Hash *hp = frame->get_params();
1197 while( (t=av_dict_get(src, "", t, AV_DICT_IGNORE_SUFFIX)) )
1198 hp->update(t->key, t->value);
1203 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op)
1205 AVFrame *opic = av_frame_alloc();
1206 int ret = convert_vframe_picture(frame, op, opic);
1207 av_frame_free(&opic);
1211 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op, AVFrame *opic)
1213 int cmodel = frame->get_color_model();
1214 AVPixelFormat ifmt = color_model_to_pix_fmt(cmodel);
1215 if( ifmt == AV_PIX_FMT_NB ) return -1;
1216 int size = av_image_fill_arrays(opic->data, opic->linesize,
1217 frame->get_data(), ifmt, frame->get_w(), frame->get_h(), 1);
1218 if( size < 0 ) return -1;
1220 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1221 int ysz = bpp * frame->get_w(), usz = ysz;
1231 // override av_image_fill_arrays() for planar types
1232 opic->data[0] = frame->get_y(); opic->linesize[0] = ysz;
1233 opic->data[1] = frame->get_u(); opic->linesize[1] = usz;
1234 opic->data[2] = frame->get_v(); opic->linesize[2] = usz;
1237 opic->data[0] = frame->get_data();
1238 opic->linesize[0] = frame->get_bytes_per_line();
1242 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1243 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(),
1244 ifmt, op->width, op->height, ofmt, SWS_POINT, NULL, NULL, NULL);
1245 if( !convert_ctx ) {
1246 fprintf(stderr, "FFVideoConvert::convert_frame_picture:"
1247 " sws_getCachedContext() failed\n");
1250 int ret = sws_scale(convert_ctx, opic->data, opic->linesize, 0, frame->get_h(),
1251 op->data, op->linesize);
1253 ff_err(ret, "FFVideoConvert::convert_frame_picture: sws_scale() failed\n");
1259 int FFVideoConvert::convert_pixfmt(VFrame *frame, AVFrame *op)
1261 // try direct transfer
1262 if( !convert_vframe_picture(frame, op) ) return 1;
1263 // use indirect transfer
1264 int cmodel = frame->get_color_model();
1265 int max_bits = BC_CModels::calculate_pixelsize(cmodel) * 8;
1266 max_bits /= BC_CModels::components(cmodel);
1267 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1268 int imodel = pix_fmt_to_color_model(ofmt);
1269 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1270 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1271 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1272 imodel = cmodel_is_yuv ?
1273 (BC_CModels::has_alpha(cmodel) ?
1275 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1276 (BC_CModels::has_alpha(cmodel) ?
1277 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1278 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1280 VFrame vframe(frame->get_w(), frame->get_h(), imodel);
1281 vframe.transfer_from(frame);
1282 if( !convert_vframe_picture(&vframe, op) ) return 1;
1286 int FFVideoConvert::transfer_pixfmt(VFrame *frame, AVFrame *ofp)
1288 int ret = convert_pixfmt(frame, ofp);
1290 BC_Hash *hp = frame->get_params();
1291 AVDictionary **dict = &ofp->metadata;
1292 //av_dict_free(dict);
1293 for( int i=0; i<hp->size(); ++i ) {
1294 char *key = hp->get_key(i), *val = hp->get_value(i);
1295 av_dict_set(dict, key, val, 0);
1301 void FFVideoStream::load_markers()
1303 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1304 if( !index_state || idx >= index_state->video_markers.size() ) return;
1305 FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
1308 IndexMarks *FFVideoStream::get_markers()
1310 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1311 if( !index_state || idx >= index_state->video_markers.size() ) return 0;
1312 return !index_state ? 0 : index_state->video_markers[idx];
1316 FFMPEG::FFMPEG(FileBase *file_base)
1319 this->file_base = file_base;
1320 memset(file_format,0,sizeof(file_format));
1321 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
1322 flow_lock = new Condition(1,"FFStream::flow_lock",0);
1325 decoding = encoding = 0;
1326 has_audio = has_video = 0;
1329 opt_video_filter = 0;
1330 opt_audio_filter = 0;
1332 char option_path[BCTEXTLEN];
1333 set_option_path(option_path, "%s", "ffmpeg.opts");
1334 read_options(option_path, opts);
1339 ff_lock("FFMPEG::~FFMPEG()");
1341 ffaudio.remove_all_objects();
1342 ffvideo.remove_all_objects();
1343 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1347 av_dict_free(&opts);
1348 delete [] opt_video_filter;
1349 delete [] opt_audio_filter;
1352 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1354 const int *p = codec->supported_samplerates;
1355 if( !p ) return sample_rate;
1357 if( *p == sample_rate ) return *p;
1363 static inline AVRational std_frame_rate(int i)
1365 static const int m1 = 1001*12, m2 = 1000*12;
1366 static const int freqs[] = {
1367 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1368 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
1370 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1371 return (AVRational) { freq, 1001*12 };
1374 AVRational FFMPEG::check_frame_rate(AVCodec *codec, double frame_rate)
1376 const AVRational *p = codec->supported_framerates;
1377 AVRational rate, best_rate = (AVRational) { 0, 0 };
1378 double max_err = 1.; int i = 0;
1379 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1380 double framerate = (double) rate.num / rate.den;
1381 double err = fabs(frame_rate/framerate - 1.);
1382 if( err >= max_err ) continue;
1386 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1389 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1392 double display_aspect = asset->width / (double)asset->height;
1393 double sample_aspect = display_aspect / asset->aspect_ratio;
1394 int width = 1000000, height = width * sample_aspect + 0.5;
1396 MWindow::create_aspect_ratio(w, h, width, height);
1397 return (AVRational){(int)w, (int)h};
1400 return (AVRational){1, 1};
1404 AVRational FFMPEG::to_time_base(int sample_rate)
1406 return (AVRational){1, sample_rate};
1409 int FFMPEG::get_fmt_score(AVSampleFormat dst_fmt, AVSampleFormat src_fmt)
1412 int dst_planar = av_sample_fmt_is_planar(dst_fmt);
1413 int src_planar = av_sample_fmt_is_planar(src_fmt);
1414 if( dst_planar != src_planar ) ++score;
1415 int dst_bytes = av_get_bytes_per_sample(dst_fmt);
1416 int src_bytes = av_get_bytes_per_sample(src_fmt);
1417 score += (src_bytes > dst_bytes ? 100 : -10) * (src_bytes - dst_bytes);
1418 int src_packed = av_get_packed_sample_fmt(src_fmt);
1419 int dst_packed = av_get_packed_sample_fmt(dst_fmt);
1420 if( dst_packed == AV_SAMPLE_FMT_S32 && src_packed == AV_SAMPLE_FMT_FLT ) score += 20;
1421 if( dst_packed == AV_SAMPLE_FMT_FLT && src_packed == AV_SAMPLE_FMT_S32 ) score += 2;
1425 AVSampleFormat FFMPEG::find_best_sample_fmt_of_list(
1426 const AVSampleFormat *sample_fmts, AVSampleFormat src_fmt)
1428 AVSampleFormat best = AV_SAMPLE_FMT_NONE;
1429 int best_score = get_fmt_score(best, src_fmt);
1430 for( int i=0; sample_fmts[i] >= 0; ++i ) {
1431 AVSampleFormat sample_fmt = sample_fmts[i];
1432 int score = get_fmt_score(sample_fmt, src_fmt);
1433 if( score >= best_score ) continue;
1434 best = sample_fmt; best_score = score;
1440 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
1442 char *ep = path + BCTEXTLEN-1;
1443 strncpy(path, File::get_cindat_path(), ep-path);
1444 strncat(path, "/ffmpeg/", ep-path);
1445 path += strlen(path);
1448 path += vsnprintf(path, ep-path, fmt, ap);
1453 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
1458 set_option_path(path, "%s/%s", type, spec);
1461 int FFMPEG::get_format(char *format, const char *path, const char *spec)
1463 char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
1464 get_option_path(option_path, path, spec);
1465 FILE *fp = fopen(option_path,"r");
1468 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1470 line[sizeof(line)-1] = 0;
1471 ret = scan_option_line(line, format, codec);
1477 int FFMPEG::get_codec(char *codec, const char *path, const char *spec)
1479 char option_path[BCTEXTLEN], line[BCTEXTLEN], format[BCTEXTLEN];
1480 get_option_path(option_path, path, spec);
1481 FILE *fp = fopen(option_path,"r");
1484 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1487 line[sizeof(line)-1] = 0;
1488 ret = scan_option_line(line, format, codec);
1491 char *vp = codec, *ep = vp+BCTEXTLEN-1;
1492 while( vp < ep && *vp && *vp != '|' ) ++vp;
1493 if( *vp == '|' ) --vp;
1494 while( vp > codec && (*vp==' ' || *vp=='\t') ) *vp-- = 0;
1499 int FFMPEG::get_file_format()
1501 char audio_muxer[BCSTRLEN], video_muxer[BCSTRLEN];
1502 char audio_format[BCSTRLEN], video_format[BCSTRLEN];
1503 audio_muxer[0] = audio_format[0] = 0;
1504 video_muxer[0] = video_format[0] = 0;
1505 Asset *asset = file_base->asset;
1506 int ret = asset ? 0 : 1;
1507 if( !ret && asset->audio_data ) {
1508 if( !(ret=get_format(audio_format, "audio", asset->acodec)) ) {
1509 if( get_format(audio_muxer, "format", audio_format) ) {
1510 strcpy(audio_muxer, audio_format);
1511 audio_format[0] = 0;
1515 if( !ret && asset->video_data ) {
1516 if( !(ret=get_format(video_format, "video", asset->vcodec)) ) {
1517 if( get_format(video_muxer, "format", video_format) ) {
1518 strcpy(video_muxer, video_format);
1519 video_format[0] = 0;
1523 if( !ret && !audio_muxer[0] && !video_muxer[0] )
1525 if( !ret && audio_muxer[0] && video_muxer[0] &&
1526 strcmp(audio_muxer, video_muxer) ) ret = -1;
1527 if( !ret && audio_format[0] && video_format[0] &&
1528 strcmp(audio_format, video_format) ) ret = -1;
1530 strcpy(file_format, !audio_format[0] && !video_format[0] ?
1531 (audio_muxer[0] ? audio_muxer : video_muxer) :
1532 (audio_format[0] ? audio_format : video_format));
1536 int FFMPEG::scan_option_line(const char *cp, char *tag, char *val)
1538 while( *cp == ' ' || *cp == '\t' ) ++cp;
1539 const char *bp = cp;
1540 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' && *cp != '\n' ) ++cp;
1542 if( !len || len > BCSTRLEN-1 ) return 1;
1543 while( bp < cp ) *tag++ = *bp++;
1545 while( *cp == ' ' || *cp == '\t' ) ++cp;
1546 if( *cp == '=' ) ++cp;
1547 while( *cp == ' ' || *cp == '\t' ) ++cp;
1549 while( *cp && *cp != '\n' ) ++cp;
1551 if( len > BCTEXTLEN-1 ) return 1;
1552 while( bp < cp ) *val++ = *bp++;
1557 int FFMPEG::can_render(const char *fformat, const char *type)
1560 char option_path[BCTEXTLEN];
1561 FFMPEG::set_option_path(option_path, type);
1562 fs.update(option_path);
1563 int total_files = fs.total_files();
1564 for( int i=0; i<total_files; ++i ) {
1565 const char *name = fs.get_entry(i)->get_name();
1566 const char *ext = strrchr(name,'.');
1567 if( !ext ) continue;
1568 if( !strcmp(fformat, ++ext) ) return 1;
1573 int FFMPEG::get_ff_option(const char *nm, const char *options, char *value)
1575 for( const char *cp=options; *cp!=0; ) {
1576 char line[BCTEXTLEN], *bp = line, *ep = bp+sizeof(line)-1;
1577 while( bp < ep && *cp && *cp!='\n' ) *bp++ = *cp++;
1580 if( !line[0] || line[0] == '#' || line[0] == ';' ) continue;
1581 char key[BCSTRLEN], val[BCTEXTLEN];
1582 if( FFMPEG::scan_option_line(line, key, val) ) continue;
1583 if( !strcmp(key, nm) ) {
1584 strncpy(value, val, BCSTRLEN);
1591 void FFMPEG::scan_audio_options(Asset *asset, EDL *edl)
1593 char cin_sample_fmt[BCSTRLEN];
1594 int cin_fmt = AV_SAMPLE_FMT_NONE;
1595 const char *options = asset->ff_audio_options;
1596 if( !get_ff_option("cin_sample_fmt", options, cin_sample_fmt) )
1597 cin_fmt = (int)av_get_sample_fmt(cin_sample_fmt);
1599 char audio_codec[BCSTRLEN]; audio_codec[0] = 0;
1600 AVCodec *av_codec = !FFMPEG::get_codec(audio_codec, "audio", asset->acodec) ?
1601 avcodec_find_encoder_by_name(audio_codec) : 0;
1602 if( av_codec && av_codec->sample_fmts )
1603 cin_fmt = find_best_sample_fmt_of_list(av_codec->sample_fmts, AV_SAMPLE_FMT_FLT);
1605 if( cin_fmt < 0 ) cin_fmt = AV_SAMPLE_FMT_S16;
1606 const char *name = av_get_sample_fmt_name((AVSampleFormat)cin_fmt);
1607 if( !name ) name = _("None");
1608 strcpy(asset->ff_sample_format, name);
1610 char value[BCSTRLEN];
1611 if( !get_ff_option("cin_bitrate", options, value) )
1612 asset->ff_audio_bitrate = atoi(value);
1613 if( !get_ff_option("cin_quality", options, value) )
1614 asset->ff_audio_quality = atoi(value);
1617 void FFMPEG::load_audio_options(Asset *asset, EDL *edl)
1619 char options_path[BCTEXTLEN];
1620 set_option_path(options_path, "audio/%s", asset->acodec);
1621 if( !load_options(options_path,
1622 asset->ff_audio_options,
1623 sizeof(asset->ff_audio_options)) )
1624 scan_audio_options(asset, edl);
1627 void FFMPEG::scan_video_options(Asset *asset, EDL *edl)
1629 char cin_pix_fmt[BCSTRLEN];
1630 int cin_fmt = AV_PIX_FMT_NONE;
1631 const char *options = asset->ff_video_options;
1632 if( !get_ff_option("cin_pix_fmt", options, cin_pix_fmt) )
1633 cin_fmt = (int)av_get_pix_fmt(cin_pix_fmt);
1635 char video_codec[BCSTRLEN]; video_codec[0] = 0;
1636 AVCodec *av_codec = !get_codec(video_codec, "video", asset->vcodec) ?
1637 avcodec_find_encoder_by_name(video_codec) : 0;
1638 if( av_codec && av_codec->pix_fmts ) {
1639 if( 0 && edl ) { // frequently picks a bad answer
1640 int color_model = edl->session->color_model;
1641 int max_bits = BC_CModels::calculate_pixelsize(color_model) * 8;
1642 max_bits /= BC_CModels::components(color_model);
1643 cin_fmt = avcodec_find_best_pix_fmt_of_list(av_codec->pix_fmts,
1644 (BC_CModels::is_yuv(color_model) ?
1645 (max_bits > 8 ? AV_PIX_FMT_AYUV64LE : AV_PIX_FMT_YUV444P) :
1646 (max_bits > 8 ? AV_PIX_FMT_RGB48LE : AV_PIX_FMT_RGB24)), 0, 0);
1649 cin_fmt = av_codec->pix_fmts[0];
1652 if( cin_fmt < 0 ) cin_fmt = AV_PIX_FMT_YUV420P;
1653 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get((AVPixelFormat)cin_fmt);
1654 const char *name = desc ? desc->name : _("None");
1655 strcpy(asset->ff_pixel_format, name);
1657 char value[BCSTRLEN];
1658 if( !get_ff_option("cin_bitrate", options, value) )
1659 asset->ff_video_bitrate = atoi(value);
1660 if( !get_ff_option("cin_quality", options, value) )
1661 asset->ff_video_quality = atoi(value);
1664 void FFMPEG::load_video_options(Asset *asset, EDL *edl)
1666 char options_path[BCTEXTLEN];
1667 set_option_path(options_path, "video/%s", asset->vcodec);
1668 if( !load_options(options_path,
1669 asset->ff_video_options,
1670 sizeof(asset->ff_video_options)) )
1671 scan_video_options(asset, edl);
1674 int FFMPEG::load_defaults(const char *path, const char *type,
1675 char *codec, char *codec_options, int len)
1677 char default_file[BCTEXTLEN];
1678 set_option_path(default_file, "%s/%s.dfl", path, type);
1679 FILE *fp = fopen(default_file,"r");
1681 fgets(codec, BCSTRLEN, fp);
1683 while( *cp && *cp!='\n' ) ++cp;
1685 while( len > 0 && fgets(codec_options, len, fp) ) {
1686 int n = strlen(codec_options);
1687 codec_options += n; len -= n;
1690 set_option_path(default_file, "%s/%s", path, codec);
1691 return load_options(default_file, codec_options, len);
1694 void FFMPEG::set_asset_format(Asset *asset, EDL *edl, const char *text)
1696 if( asset->format != FILE_FFMPEG ) return;
1697 if( text != asset->fformat )
1698 strcpy(asset->fformat, text);
1699 if( asset->audio_data && !asset->ff_audio_options[0] ) {
1700 if( !load_defaults("audio", text, asset->acodec,
1701 asset->ff_audio_options, sizeof(asset->ff_audio_options)) )
1702 scan_audio_options(asset, edl);
1704 asset->audio_data = 0;
1706 if( asset->video_data && !asset->ff_video_options[0] ) {
1707 if( !load_defaults("video", text, asset->vcodec,
1708 asset->ff_video_options, sizeof(asset->ff_video_options)) )
1709 scan_video_options(asset, edl);
1711 asset->video_data = 0;
1715 int FFMPEG::get_encoder(const char *options,
1716 char *format, char *codec, char *bsfilter)
1718 FILE *fp = fopen(options,"r");
1720 eprintf(_("options open failed %s\n"),options);
1723 char line[BCTEXTLEN];
1724 if( !fgets(line, sizeof(line), fp) ||
1725 scan_encoder(line, format, codec, bsfilter) )
1726 eprintf(_("format/codec not found %s\n"), options);
1731 int FFMPEG::scan_encoder(const char *line,
1732 char *format, char *codec, char *bsfilter)
1734 format[0] = codec[0] = bsfilter[0] = 0;
1735 if( scan_option_line(line, format, codec) ) return 1;
1737 while( *cp && *cp != '|' ) ++cp;
1738 if( !*cp ) return 0;
1740 do { *bp-- = 0; } while( bp>=codec && (*bp==' ' || *bp == '\t' ) );
1741 while( *++cp && (*cp==' ' || *cp == '\t') );
1743 for( int i=BCTEXTLEN; --i>0 && *cp; ) *bp++ = *cp++;
1748 int FFMPEG::read_options(const char *options, AVDictionary *&opts, int skip)
1750 FILE *fp = fopen(options,"r");
1753 while( !ret && --skip >= 0 ) {
1755 while( ch >= 0 && ch != '\n' ) ch = getc(fp);
1756 if( ch < 0 ) ret = 1;
1759 ret = read_options(fp, options, opts);
1764 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
1766 FILE *fp = fmemopen((void *)options,strlen(options),"r");
1768 int ret = read_options(fp, options, opts);
1770 AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
1771 if( tag ) st->id = strtol(tag->value,0,0);
1775 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
1777 int ret = 0, no = 0;
1778 char line[BCTEXTLEN];
1779 while( !ret && fgets(line, sizeof(line), fp) ) {
1780 line[sizeof(line)-1] = 0;
1781 if( line[0] == '#' ) continue;
1782 if( line[0] == '\n' ) continue;
1783 char key[BCSTRLEN], val[BCTEXTLEN];
1784 if( scan_option_line(line, key, val) ) {
1785 eprintf(_("err reading %s: line %d\n"), options, no);
1789 if( !strcmp(key, "duration") )
1790 opt_duration = strtod(val, 0);
1791 else if( !strcmp(key, "video_filter") )
1792 opt_video_filter = cstrdup(val);
1793 else if( !strcmp(key, "audio_filter") )
1794 opt_audio_filter = cstrdup(val);
1795 else if( !strcmp(key, "loglevel") )
1798 av_dict_set(&opts, key, val, 0);
1804 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
1806 char option_path[BCTEXTLEN];
1807 set_option_path(option_path, "%s", options);
1808 return read_options(option_path, opts);
1811 int FFMPEG::load_options(const char *path, char *bfr, int len)
1814 FILE *fp = fopen(path, "r");
1816 fgets(bfr, len, fp); // skip hdr
1817 len = fread(bfr, 1, len-1, fp);
1818 if( len < 0 ) len = 0;
1824 void FFMPEG::set_loglevel(const char *ap)
1826 if( !ap || !*ap ) return;
1831 { "quiet" , AV_LOG_QUIET },
1832 { "panic" , AV_LOG_PANIC },
1833 { "fatal" , AV_LOG_FATAL },
1834 { "error" , AV_LOG_ERROR },
1835 { "warning", AV_LOG_WARNING },
1836 { "info" , AV_LOG_INFO },
1837 { "verbose", AV_LOG_VERBOSE },
1838 { "debug" , AV_LOG_DEBUG },
1840 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
1841 if( !strcmp(log_levels[i].name, ap) ) {
1842 av_log_set_level(log_levels[i].level);
1846 av_log_set_level(atoi(ap));
1849 double FFMPEG::to_secs(int64_t time, AVRational time_base)
1851 double base_time = time == AV_NOPTS_VALUE ? 0 :
1852 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
1853 return base_time / AV_TIME_BASE;
1856 int FFMPEG::info(char *text, int len)
1858 if( len <= 0 ) return 0;
1860 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
1862 report("format: %s\n",fmt_ctx->iformat->name);
1863 if( ffvideo.size() > 0 )
1864 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
1865 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
1866 FFVideoStream *vid = ffvideo[vidx];
1867 AVStream *st = vid->st;
1868 AVCodecID codec_id = st->codecpar->codec_id;
1869 report(_("vid%d (%d), id 0x%06x:\n"), vid->idx, vid->fidx, codec_id);
1870 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
1871 report(" video%d %s", vidx+1, desc ? desc->name : " (unkn)");
1872 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
1873 AVPixelFormat pix_fmt = (AVPixelFormat)st->codecpar->format;
1874 const char *pfn = av_get_pix_fmt_name(pix_fmt);
1875 report(" pix %s\n", pfn ? pfn : "(unkn)");
1876 double secs = to_secs(st->duration, st->time_base);
1877 int64_t length = secs * vid->frame_rate + 0.5;
1878 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
1879 int64_t nudge = ofs * vid->frame_rate;
1880 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1881 report(" %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
1882 int hrs = secs/3600; secs -= hrs*3600;
1883 int mins = secs/60; secs -= mins*60;
1884 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1886 if( ffaudio.size() > 0 )
1887 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
1888 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
1889 FFAudioStream *aud = ffaudio[aidx];
1890 AVStream *st = aud->st;
1891 AVCodecID codec_id = st->codecpar->codec_id;
1892 report(_("aud%d (%d), id 0x%06x:\n"), aud->idx, aud->fidx, codec_id);
1893 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
1894 int nch = aud->channels, ch0 = aud->channel0+1;
1895 report(" audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
1896 AVSampleFormat sample_fmt = (AVSampleFormat)st->codecpar->format;
1897 const char *fmt = av_get_sample_fmt_name(sample_fmt);
1898 report(" %s %d", fmt, aud->sample_rate);
1899 int sample_bits = av_get_bits_per_sample(codec_id);
1900 report(" %dbits\n", sample_bits);
1901 double secs = to_secs(st->duration, st->time_base);
1902 int64_t length = secs * aud->sample_rate + 0.5;
1903 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
1904 int64_t nudge = ofs * aud->sample_rate;
1905 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1906 report(" %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
1907 int hrs = secs/3600; secs -= hrs*3600;
1908 int mins = secs/60; secs -= mins*60;
1909 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1911 if( fmt_ctx->nb_programs > 0 )
1912 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
1913 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
1914 report("program %d", i+1);
1915 AVProgram *pgrm = fmt_ctx->programs[i];
1916 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1917 int idx = pgrm->stream_index[j];
1918 int vidx = ffvideo.size();
1919 while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
1921 report(", vid%d", vidx);
1924 int aidx = ffaudio.size();
1925 while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
1927 report(", aud%d", aidx);
1930 report(", (%d)", pgrm->stream_index[j]);
1935 AVDictionaryEntry *tag = 0;
1936 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
1937 report("%s=%s\n", tag->key, tag->value);
1946 int FFMPEG::init_decoder(const char *filename)
1948 ff_lock("FFMPEG::init_decoder");
1950 char file_opts[BCTEXTLEN];
1951 char *bp = strrchr(strcpy(file_opts, filename), '/');
1952 char *sp = strrchr(!bp ? file_opts : bp, '.');
1953 if( !sp ) sp = bp + strlen(bp);
1955 AVInputFormat *ifmt = 0;
1957 strcpy(sp, ".opts");
1958 fp = fopen(file_opts, "r");
1961 read_options(fp, file_opts, opts);
1963 AVDictionaryEntry *tag;
1964 if( (tag=av_dict_get(opts, "format", NULL, 0)) != 0 ) {
1965 ifmt = av_find_input_format(tag->value);
1969 load_options("decode.opts", opts);
1970 AVDictionary *fopts = 0;
1971 av_dict_copy(&fopts, opts, 0);
1972 int ret = avformat_open_input(&fmt_ctx, filename, ifmt, &fopts);
1973 av_dict_free(&fopts);
1975 ret = avformat_find_stream_info(fmt_ctx, NULL);
1980 return !ret ? 0 : 1;
1983 int FFMPEG::open_decoder()
1986 if( stat(fmt_ctx->url, &st) < 0 ) {
1987 eprintf(_("can't stat file: %s\n"), fmt_ctx->url);
1991 int64_t file_bits = 8 * st.st_size;
1992 if( !fmt_ctx->bit_rate && opt_duration > 0 )
1993 fmt_ctx->bit_rate = file_bits / opt_duration;
1996 if( fmt_ctx->bit_rate > 0 ) {
1997 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1998 AVStream *st = fmt_ctx->streams[i];
1999 if( st->duration != AV_NOPTS_VALUE ) continue;
2000 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
2001 st->duration = av_rescale(file_bits, st->time_base.den,
2002 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
2006 if( estimated && !(fflags & FF_ESTM_TIMES) ) {
2007 fflags |= FF_ESTM_TIMES;
2008 printf("FFMPEG::open_decoder: some stream times estimated: %s\n",
2012 ff_lock("FFMPEG::open_decoder");
2013 int ret = 0, bad_time = 0;
2014 for( int i=0; !ret && i<(int)fmt_ctx->nb_streams; ++i ) {
2015 AVStream *st = fmt_ctx->streams[i];
2016 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
2017 AVCodecParameters *avpar = st->codecpar;
2018 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avpar->codec_id);
2019 if( !codec_desc ) continue;
2020 switch( avpar->codec_type ) {
2021 case AVMEDIA_TYPE_VIDEO: {
2022 if( avpar->width < 1 ) continue;
2023 if( avpar->height < 1 ) continue;
2024 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
2025 if( framerate.num < 1 ) continue;
2027 int vidx = ffvideo.size();
2028 FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
2029 vstrm_index.append(ffidx(vidx, 0));
2030 ffvideo.append(vid);
2031 vid->width = avpar->width;
2032 vid->height = avpar->height;
2033 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
2034 double secs = to_secs(st->duration, st->time_base);
2035 vid->length = secs * vid->frame_rate;
2036 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
2037 vid->nudge = st->start_time;
2039 if( opt_video_filter )
2040 ret = vid->create_filter(opt_video_filter, avpar);
2042 case AVMEDIA_TYPE_AUDIO: {
2043 if( avpar->channels < 1 ) continue;
2044 if( avpar->sample_rate < 1 ) continue;
2046 int aidx = ffaudio.size();
2047 FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
2048 ffaudio.append(aud);
2049 aud->channel0 = astrm_index.size();
2050 aud->channels = avpar->channels;
2051 for( int ch=0; ch<aud->channels; ++ch )
2052 astrm_index.append(ffidx(aidx, ch));
2053 aud->sample_rate = avpar->sample_rate;
2054 double secs = to_secs(st->duration, st->time_base);
2055 aud->length = secs * aud->sample_rate;
2056 aud->init_swr(aud->channels, avpar->format, aud->sample_rate);
2057 aud->nudge = st->start_time;
2059 if( opt_audio_filter )
2060 ret = aud->create_filter(opt_audio_filter, avpar);
2065 if( bad_time && !(fflags & FF_BAD_TIMES) ) {
2066 fflags |= FF_BAD_TIMES;
2067 printf("FFMPEG::open_decoder: some stream have bad times: %s\n",
2071 return ret < 0 ? -1 : 0;
2075 int FFMPEG::init_encoder(const char *filename)
2077 // try access first for named pipes
2078 int ret = access(filename, W_OK);
2080 int fd = ::open(filename,O_WRONLY);
2081 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
2082 if( fd >= 0 ) { close(fd); ret = 0; }
2085 eprintf(_("bad file path: %s\n"), filename);
2088 ret = get_file_format();
2090 eprintf(_("bad file format: %s\n"), filename);
2094 eprintf(_("mismatch audio/video file format: %s\n"), filename);
2097 ff_lock("FFMPEG::init_encoder");
2099 char format[BCSTRLEN];
2100 if( get_format(format, "format", file_format) )
2101 strcpy(format, file_format);
2102 avformat_alloc_output_context2(&fmt_ctx, 0, format, filename);
2104 eprintf(_("failed: %s\n"), filename);
2109 load_options("encode.opts", opts);
2115 int FFMPEG::open_encoder(const char *type, const char *spec)
2118 Asset *asset = file_base->asset;
2119 char *filename = asset->path;
2120 AVDictionary *sopts = 0;
2121 av_dict_copy(&sopts, opts, 0);
2122 char option_path[BCTEXTLEN];
2123 set_option_path(option_path, "%s/%s.opts", type, type);
2124 read_options(option_path, sopts);
2125 get_option_path(option_path, type, spec);
2126 char format_name[BCSTRLEN], codec_name[BCTEXTLEN], bsfilter[BCTEXTLEN];
2127 if( get_encoder(option_path, format_name, codec_name, bsfilter) ) {
2128 eprintf(_("get_encoder failed %s:%s\n"), option_path, filename);
2133 if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
2135 else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
2136 else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
2139 ff_lock("FFMPEG::open_encoder");
2142 AVCodecContext *ctx = 0;
2144 const AVCodecDescriptor *codec_desc = 0;
2145 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
2147 eprintf(_("cant find codec %s:%s\n"), codec_name, filename);
2151 codec_desc = avcodec_descriptor_get(codec->id);
2153 eprintf(_("unknown codec %s:%s\n"), codec_name, filename);
2158 st = avformat_new_stream(fmt_ctx, 0);
2160 eprintf(_("cant create stream %s:%s\n"), codec_name, filename);
2165 switch( codec_desc->type ) {
2166 case AVMEDIA_TYPE_AUDIO: {
2168 eprintf(_("duplicate audio %s:%s\n"), codec_name, filename);
2172 if( scan_options(asset->ff_audio_options, sopts, st) ) {
2173 eprintf(_("bad audio options %s:%s\n"), codec_name, filename);
2178 ctx = avcodec_alloc_context3(codec);
2179 if( asset->ff_audio_bitrate > 0 ) {
2180 ctx->bit_rate = asset->ff_audio_bitrate;
2182 sprintf(arg, "%d", asset->ff_audio_bitrate);
2183 av_dict_set(&sopts, "b", arg, 0);
2185 else if( asset->ff_audio_quality >= 0 ) {
2186 ctx->global_quality = asset->ff_audio_quality * FF_QP2LAMBDA;
2187 ctx->qmin = ctx->qmax = asset->ff_audio_quality;
2188 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2189 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2190 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2192 av_dict_set(&sopts, "flags", "+qscale", 0);
2193 sprintf(arg, "%d", asset->ff_audio_quality);
2194 av_dict_set(&sopts, "qscale", arg, 0);
2195 sprintf(arg, "%d", ctx->global_quality);
2196 av_dict_set(&sopts, "global_quality", arg, 0);
2198 int aidx = ffaudio.size();
2199 int fidx = aidx + ffvideo.size();
2200 FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
2201 aud->avctx = ctx; ffaudio.append(aud); fst = aud;
2202 aud->sample_rate = asset->sample_rate;
2203 ctx->channels = aud->channels = asset->channels;
2204 for( int ch=0; ch<aud->channels; ++ch )
2205 astrm_index.append(ffidx(aidx, ch));
2206 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
2207 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
2208 if( !ctx->sample_rate ) {
2209 eprintf(_("check_sample_rate failed %s\n"), filename);
2213 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
2214 AVSampleFormat sample_fmt = av_get_sample_fmt(asset->ff_sample_format);
2215 if( sample_fmt == AV_SAMPLE_FMT_NONE )
2216 sample_fmt = codec->sample_fmts ? codec->sample_fmts[0] : AV_SAMPLE_FMT_S16;
2217 ctx->sample_fmt = sample_fmt;
2218 uint64_t layout = av_get_default_channel_layout(ctx->channels);
2219 aud->resample_context = swr_alloc_set_opts(NULL,
2220 layout, ctx->sample_fmt, aud->sample_rate,
2221 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
2223 swr_init(aud->resample_context);
2226 case AVMEDIA_TYPE_VIDEO: {
2228 eprintf(_("duplicate video %s:%s\n"), codec_name, filename);
2232 if( scan_options(asset->ff_video_options, sopts, st) ) {
2233 eprintf(_("bad video options %s:%s\n"), codec_name, filename);
2238 ctx = avcodec_alloc_context3(codec);
2239 if( asset->ff_video_bitrate > 0 ) {
2240 ctx->bit_rate = asset->ff_video_bitrate;
2242 sprintf(arg, "%d", asset->ff_video_bitrate);
2243 av_dict_set(&sopts, "b", arg, 0);
2245 else if( asset->ff_video_quality >= 0 ) {
2246 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
2247 ctx->qmin = ctx->qmax = asset->ff_video_quality;
2248 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2249 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2250 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2252 av_dict_set(&sopts, "flags", "+qscale", 0);
2253 sprintf(arg, "%d", asset->ff_video_quality);
2254 av_dict_set(&sopts, "qscale", arg, 0);
2255 sprintf(arg, "%d", ctx->global_quality);
2256 av_dict_set(&sopts, "global_quality", arg, 0);
2258 int vidx = ffvideo.size();
2259 int fidx = vidx + ffaudio.size();
2260 FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
2261 vstrm_index.append(ffidx(vidx, 0));
2262 vid->avctx = ctx; ffvideo.append(vid); fst = vid;
2263 vid->width = asset->width;
2264 vid->height = asset->height;
2265 vid->frame_rate = asset->frame_rate;
2267 AVPixelFormat pix_fmt = av_get_pix_fmt(asset->ff_pixel_format);
2268 if( pix_fmt == AV_PIX_FMT_NONE )
2269 pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
2270 ctx->pix_fmt = pix_fmt;
2271 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
2272 int mask_w = (1<<desc->log2_chroma_w)-1;
2273 ctx->width = (vid->width+mask_w) & ~mask_w;
2274 int mask_h = (1<<desc->log2_chroma_h)-1;
2275 ctx->height = (vid->height+mask_h) & ~mask_h;
2276 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
2277 AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
2278 if( !frame_rate.num || !frame_rate.den ) {
2279 eprintf(_("check_frame_rate failed %s\n"), filename);
2283 av_reduce(&frame_rate.num, &frame_rate.den,
2284 frame_rate.num, frame_rate.den, INT_MAX);
2285 ctx->framerate = (AVRational) { frame_rate.num, frame_rate.den };
2286 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
2287 st->avg_frame_rate = frame_rate;
2288 st->time_base = ctx->time_base;
2290 vid->interlaced = asset->interlace_mode == ILACE_MODE_TOP_FIRST ||
2291 asset->interlace_mode == ILACE_MODE_BOTTOM_FIRST ? 1 : 0;
2292 vid->top_field_first = asset->interlace_mode == ILACE_MODE_TOP_FIRST ? 1 : 0;
2295 eprintf(_("not audio/video, %s:%s\n"), codec_name, filename);
2300 AVDictionaryEntry *tag;
2301 if( (tag=av_dict_get(sopts, "cin_stats_filename", NULL, 0)) != 0 ) {
2302 char suffix[BCSTRLEN]; sprintf(suffix,"-%d.log",fst->fidx);
2303 fst->stats_filename = cstrcat(2, tag->value, suffix);
2305 if( (tag=av_dict_get(sopts, "flags", NULL, 0)) != 0 ) {
2306 int pass = fst->pass;
2307 char *cp = tag->value;
2309 int ch = *cp++, pfx = ch=='-' ? -1 : ch=='+' ? 1 : 0;
2310 if( !isalnum(!pfx ? ch : (ch=*cp++)) ) continue;
2311 char id[BCSTRLEN], *bp = id, *ep = bp+sizeof(id)-1;
2312 for( *bp++=ch; isalnum(ch=*cp); ++cp )
2313 if( bp < ep ) *bp++ = ch;
2315 if( !strcmp(id, "pass1") ) {
2316 pass = pfx<0 ? (pass&~1) : pfx>0 ? (pass|1) : 1;
2318 else if( !strcmp(id, "pass2") ) {
2319 pass = pfx<0 ? (pass&~2) : pfx>0 ? (pass|2) : 2;
2322 if( (fst->pass=pass) ) {
2323 if( pass & 1 ) ctx->flags |= AV_CODEC_FLAG_PASS1;
2324 if( pass & 2 ) ctx->flags |= AV_CODEC_FLAG_PASS2;
2330 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
2331 ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
2332 if( fst->stats_filename && (ret=fst->init_stats_file()) )
2333 eprintf(_("error: stats file = %s\n"), fst->stats_filename);
2336 av_dict_set(&sopts, "cin_bitrate", 0, 0);
2337 av_dict_set(&sopts, "cin_quality", 0, 0);
2339 if( !av_dict_get(sopts, "threads", NULL, 0) )
2340 ctx->thread_count = ff_cpus();
2341 ret = avcodec_open2(ctx, codec, &sopts);
2343 ret = avcodec_parameters_from_context(st->codecpar, ctx);
2345 fprintf(stderr, "Could not copy the stream parameters\n");
2348 _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
2349 ret = avcodec_copy_context(st->codec, ctx);
2350 _Pragma("GCC diagnostic warning \"-Wdeprecated-declarations\"")
2352 fprintf(stderr, "Could not copy the stream context\n");
2355 ff_err(ret,"FFMPEG::open_encoder");
2356 eprintf(_("open failed %s:%s\n"), codec_name, filename);
2362 if( !ret && fst && bsfilter[0] ) {
2363 ret = av_bsf_list_parse_str(bsfilter, &fst->bsfc);
2365 ff_err(ret,"FFMPEG::open_encoder");
2366 eprintf(_("bitstream filter failed %s:\n%s\n"), filename, bsfilter);
2377 av_dict_free(&sopts);
2381 int FFMPEG::close_encoder()
2384 if( encoding > 0 ) {
2385 av_write_trailer(fmt_ctx);
2386 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
2387 avio_closep(&fmt_ctx->pb);
2393 int FFMPEG::decode_activate()
2395 if( decoding < 0 ) {
2397 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
2398 ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
2399 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
2400 ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
2401 // set nudges for each program stream set
2402 const int64_t min_nudge = INT64_MIN+1;
2403 int npgrms = fmt_ctx->nb_programs;
2404 for( int i=0; i<npgrms; ++i ) {
2405 AVProgram *pgrm = fmt_ctx->programs[i];
2406 // first start time video stream
2407 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2408 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2409 int fidx = pgrm->stream_index[j];
2410 AVStream *st = fmt_ctx->streams[fidx];
2411 AVCodecParameters *avpar = st->codecpar;
2412 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2413 if( st->start_time == AV_NOPTS_VALUE ) continue;
2414 if( vstart_time < st->start_time )
2415 vstart_time = st->start_time;
2418 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2419 if( st->start_time == AV_NOPTS_VALUE ) continue;
2420 if( astart_time < st->start_time )
2421 astart_time = st->start_time;
2425 //since frame rate is much more grainy than sample rate, it is better to
2426 // align using video, so that total absolute error is minimized.
2427 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2428 astart_time > min_nudge ? astart_time : AV_NOPTS_VALUE;
2429 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2430 int fidx = pgrm->stream_index[j];
2431 AVStream *st = fmt_ctx->streams[fidx];
2432 AVCodecParameters *avpar = st->codecpar;
2433 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2434 for( int k=0; k<ffvideo.size(); ++k ) {
2435 if( ffvideo[k]->fidx != fidx ) continue;
2436 ffvideo[k]->nudge = nudge;
2440 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2441 for( int k=0; k<ffaudio.size(); ++k ) {
2442 if( ffaudio[k]->fidx != fidx ) continue;
2443 ffaudio[k]->nudge = nudge;
2449 // set nudges for any streams not yet set
2450 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2451 int nstreams = fmt_ctx->nb_streams;
2452 for( int i=0; i<nstreams; ++i ) {
2453 AVStream *st = fmt_ctx->streams[i];
2454 AVCodecParameters *avpar = st->codecpar;
2455 switch( avpar->codec_type ) {
2456 case AVMEDIA_TYPE_VIDEO: {
2457 if( st->start_time == AV_NOPTS_VALUE ) continue;
2458 int vidx = ffvideo.size();
2459 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
2460 if( vidx < 0 ) continue;
2461 if( ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
2462 if( vstart_time < st->start_time )
2463 vstart_time = st->start_time;
2465 case AVMEDIA_TYPE_AUDIO: {
2466 if( st->start_time == AV_NOPTS_VALUE ) continue;
2467 int aidx = ffaudio.size();
2468 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
2469 if( aidx < 0 ) continue;
2470 if( ffaudio[aidx]->frame_sz < avpar->frame_size )
2471 ffaudio[aidx]->frame_sz = avpar->frame_size;
2472 if( ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
2473 if( astart_time < st->start_time )
2474 astart_time = st->start_time;
2479 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2480 astart_time > min_nudge ? astart_time : 0;
2481 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
2482 if( ffvideo[vidx]->nudge == AV_NOPTS_VALUE )
2483 ffvideo[vidx]->nudge = nudge;
2485 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2486 if( ffaudio[aidx]->nudge == AV_NOPTS_VALUE )
2487 ffaudio[aidx]->nudge = nudge;
2494 int FFMPEG::encode_activate()
2497 if( encoding < 0 ) {
2499 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
2500 (ret=avio_open(&fmt_ctx->pb, fmt_ctx->url, AVIO_FLAG_WRITE)) < 0 ) {
2501 ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
2507 AVProgram *prog = av_new_program(fmt_ctx, prog_id);
2508 for( int i=0; i< ffvideo.size(); ++i )
2509 av_program_add_stream_index(fmt_ctx, prog_id, ffvideo[i]->fidx);
2510 for( int i=0; i< ffaudio.size(); ++i )
2511 av_program_add_stream_index(fmt_ctx, prog_id, ffaudio[i]->fidx);
2512 int pi = fmt_ctx->nb_programs;
2513 while( --pi >= 0 && fmt_ctx->programs[pi]->id != prog_id );
2514 AVDictionary **meta = &prog->metadata;
2515 av_dict_set(meta, "service_provider", "cin5", 0);
2516 const char *path = fmt_ctx->url, *bp = strrchr(path,'/');
2517 if( bp ) path = bp + 1;
2518 av_dict_set(meta, "title", path, 0);
2520 if( ffaudio.size() ) {
2521 const char *ep = getenv("CIN_AUDIO_LANG"), *lp = 0;
2522 if( !ep && (lp=getenv("LANG")) ) { // some are guesses
2523 static struct { const char lc[3], lng[4]; } lcode[] = {
2524 { "en", "eng" }, { "de", "ger" }, { "es", "spa" },
2525 { "eu", "bas" }, { "fr", "fre" }, { "el", "gre" },
2526 { "hi", "hin" }, { "it", "ita" }, { "ja", "jap" },
2527 { "ko", "kor" }, { "du", "dut" }, { "pl", "pol" },
2528 { "pt", "por" }, { "ru", "rus" }, { "sl", "slv" },
2529 { "uk", "ukr" }, { "vi", "vie" }, { "zh", "chi" },
2531 for( int i=sizeof(lcode)/sizeof(lcode[0]); --i>=0 && !ep; )
2532 if( !strncmp(lcode[i].lc,lp,2) ) ep = lcode[i].lng;
2534 if( !ep ) ep = "und";
2536 strncpy(lang,ep,3); lang[3] = 0;
2537 AVStream *st = ffaudio[0]->st;
2538 av_dict_set(&st->metadata,"language",lang,0);
2541 AVDictionary *fopts = 0;
2542 char option_path[BCTEXTLEN];
2543 set_option_path(option_path, "format/%s", file_format);
2544 read_options(option_path, fopts, 1);
2545 ret = avformat_write_header(fmt_ctx, &fopts);
2547 ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
2551 av_dict_free(&fopts);
2558 int FFMPEG::audio_seek(int stream, int64_t pos)
2560 int aidx = astrm_index[stream].st_idx;
2561 FFAudioStream *aud = ffaudio[aidx];
2562 aud->audio_seek(pos);
2566 int FFMPEG::video_seek(int stream, int64_t pos)
2568 int vidx = vstrm_index[stream].st_idx;
2569 FFVideoStream *vid = ffvideo[vidx];
2570 vid->video_seek(pos);
2575 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
2577 if( !has_audio || chn >= astrm_index.size() ) return -1;
2578 int aidx = astrm_index[chn].st_idx;
2579 FFAudioStream *aud = ffaudio[aidx];
2580 if( aud->load(pos, len) < len ) return -1;
2581 int ch = astrm_index[chn].st_ch;
2582 int ret = aud->read(samples,len,ch);
2586 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
2588 if( !has_video || layer >= vstrm_index.size() ) return -1;
2589 int vidx = vstrm_index[layer].st_idx;
2590 FFVideoStream *vid = ffvideo[vidx];
2591 return vid->load(vframe, pos);
2595 int FFMPEG::encode(int stream, double **samples, int len)
2597 FFAudioStream *aud = ffaudio[stream];
2598 return aud->encode(samples, len);
2602 int FFMPEG::encode(int stream, VFrame *frame)
2604 FFVideoStream *vid = ffvideo[stream];
2605 return vid->encode(frame);
2608 void FFMPEG::start_muxer()
2616 void FFMPEG::stop_muxer()
2625 void FFMPEG::flow_off()
2628 flow_lock->lock("FFMPEG::flow_off");
2632 void FFMPEG::flow_on()
2636 flow_lock->unlock();
2639 void FFMPEG::flow_ctl()
2642 flow_lock->lock("FFMPEG::flow_ctl");
2643 flow_lock->unlock();
2647 int FFMPEG::mux_audio(FFrame *frm)
2649 FFStream *fst = frm->fst;
2650 AVCodecContext *ctx = fst->avctx;
2651 AVFrame *frame = *frm;
2652 AVRational tick_rate = {1, ctx->sample_rate};
2653 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
2654 int ret = fst->encode_frame(frame);
2656 ff_err(ret, "FFMPEG::mux_audio");
2657 return ret >= 0 ? 0 : 1;
2660 int FFMPEG::mux_video(FFrame *frm)
2662 FFStream *fst = frm->fst;
2663 AVFrame *frame = *frm;
2664 frame->pts = frm->position;
2665 int ret = fst->encode_frame(frame);
2667 ff_err(ret, "FFMPEG::mux_video");
2668 return ret >= 0 ? 0 : 1;
2674 double atm = -1, vtm = -1;
2675 FFrame *afrm = 0, *vfrm = 0;
2677 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
2678 FFStream *fst = ffaudio[i];
2679 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
2680 FFrame *frm = fst->frms.first;
2681 if( !frm ) { if( !done ) return; continue; }
2682 double tm = to_secs(frm->position, fst->avctx->time_base);
2683 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
2685 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
2686 FFStream *fst = ffvideo[i];
2687 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
2688 FFrame *frm = fst->frms.first;
2689 if( !frm ) { if( !done ) return; continue; }
2690 double tm = to_secs(frm->position, fst->avctx->time_base);
2691 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
2693 if( !demand ) flow_off();
2694 if( !afrm && !vfrm ) break;
2695 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
2696 vfrm->position, vfrm->fst->avctx->time_base,
2697 afrm->position, afrm->fst->avctx->time_base);
2698 FFrame *frm = v <= 0 ? vfrm : afrm;
2699 if( frm == afrm ) mux_audio(frm);
2700 if( frm == vfrm ) mux_video(frm);
2709 mux_lock->lock("FFMPEG::run");
2712 for( int i=0; i<ffaudio.size(); ++i )
2713 ffaudio[i]->drain();
2714 for( int i=0; i<ffvideo.size(); ++i )
2715 ffvideo[i]->drain();
2717 for( int i=0; i<ffaudio.size(); ++i )
2718 ffaudio[i]->flush();
2719 for( int i=0; i<ffvideo.size(); ++i )
2720 ffvideo[i]->flush();
2724 int FFMPEG::ff_total_audio_channels()
2726 return astrm_index.size();
2729 int FFMPEG::ff_total_astreams()
2731 return ffaudio.size();
2734 int FFMPEG::ff_audio_channels(int stream)
2736 return ffaudio[stream]->channels;
2739 int FFMPEG::ff_sample_rate(int stream)
2741 return ffaudio[stream]->sample_rate;
2744 const char* FFMPEG::ff_audio_format(int stream)
2746 AVStream *st = ffaudio[stream]->st;
2747 AVCodecID id = st->codecpar->codec_id;
2748 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2749 return desc ? desc->name : _("Unknown");
2752 int FFMPEG::ff_audio_pid(int stream)
2754 return ffaudio[stream]->st->id;
2757 int64_t FFMPEG::ff_audio_samples(int stream)
2759 return ffaudio[stream]->length;
2762 // find audio astream/channels with this program,
2763 // or all program audio channels (astream=-1)
2764 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
2768 int vidx = ffvideo[vstream]->fidx;
2769 // find first program with this video stream
2770 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
2771 AVProgram *pgrm = fmt_ctx->programs[i];
2772 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
2773 int st_idx = pgrm->stream_index[j];
2774 AVStream *st = fmt_ctx->streams[st_idx];
2775 if( st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
2776 if( st_idx == vidx ) pidx = i;
2779 if( pidx < 0 ) return -1;
2781 int64_t channels = 0;
2782 AVProgram *pgrm = fmt_ctx->programs[pidx];
2783 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2784 int aidx = pgrm->stream_index[j];
2785 AVStream *st = fmt_ctx->streams[aidx];
2786 if( st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
2787 if( astream > 0 ) { --astream; continue; }
2789 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
2790 if( ffaudio[i]->fidx == aidx ) astrm = i;
2792 if( ret < 0 ) ret = astrm;
2793 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
2794 channels |= mask << ffaudio[astrm]->channel0;
2796 if( !astream ) break;
2798 channel_mask = channels;
2803 int FFMPEG::ff_total_video_layers()
2805 return vstrm_index.size();
2808 int FFMPEG::ff_total_vstreams()
2810 return ffvideo.size();
2813 int FFMPEG::ff_video_width(int stream)
2815 return ffvideo[stream]->width;
2818 int FFMPEG::ff_video_height(int stream)
2820 return ffvideo[stream]->height;
2823 int FFMPEG::ff_set_video_width(int stream, int width)
2825 int w = ffvideo[stream]->width;
2826 ffvideo[stream]->width = width;
2830 int FFMPEG::ff_set_video_height(int stream, int height)
2832 int h = ffvideo[stream]->height;
2833 ffvideo[stream]->height = height;
2837 int FFMPEG::ff_coded_width(int stream)
2839 return ffvideo[stream]->avctx->coded_width;
2842 int FFMPEG::ff_coded_height(int stream)
2844 return ffvideo[stream]->avctx->coded_height;
2847 float FFMPEG::ff_aspect_ratio(int stream)
2849 return ffvideo[stream]->aspect_ratio;
2852 const char* FFMPEG::ff_video_format(int stream)
2854 AVStream *st = ffvideo[stream]->st;
2855 AVCodecID id = st->codecpar->codec_id;
2856 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2857 return desc ? desc->name : _("Unknown");
2860 double FFMPEG::ff_frame_rate(int stream)
2862 return ffvideo[stream]->frame_rate;
2865 int64_t FFMPEG::ff_video_frames(int stream)
2867 return ffvideo[stream]->length;
2870 int FFMPEG::ff_video_pid(int stream)
2872 return ffvideo[stream]->st->id;
2875 int FFMPEG::ff_video_mpeg_color_range(int stream)
2877 return ffvideo[stream]->st->codecpar->color_range == AVCOL_RANGE_MPEG ? 1 : 0;
2880 int FFMPEG::ff_cpus()
2882 return file_base->file->cpus;
2885 int FFVideoStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
2887 avfilter_register_all();
2888 const char *sp = filter_spec;
2889 char filter_name[BCSTRLEN], *np = filter_name;
2890 int i = sizeof(filter_name);
2891 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
2893 const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
2894 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_VIDEO ) {
2895 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
2898 filter_graph = avfilter_graph_alloc();
2899 const AVFilter *buffersrc = avfilter_get_by_name("buffer");
2900 const AVFilter *buffersink = avfilter_get_by_name("buffersink");
2902 int ret = 0; char args[BCTEXTLEN];
2903 AVPixelFormat pix_fmt = (AVPixelFormat)avpar->format;
2904 snprintf(args, sizeof(args),
2905 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
2906 avpar->width, avpar->height, (int)pix_fmt,
2907 st->time_base.num, st->time_base.den,
2908 avpar->sample_aspect_ratio.num, avpar->sample_aspect_ratio.den);
2910 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2911 args, NULL, filter_graph);
2913 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2914 NULL, NULL, filter_graph);
2916 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
2917 (uint8_t*)&pix_fmt, sizeof(pix_fmt),
2918 AV_OPT_SEARCH_CHILDREN);
2920 ff_err(ret, "FFVideoStream::create_filter");
2922 ret = FFStream::create_filter(filter_spec);
2923 return ret >= 0 ? 0 : -1;
2926 int FFAudioStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
2928 avfilter_register_all();
2929 const char *sp = filter_spec;
2930 char filter_name[BCSTRLEN], *np = filter_name;
2931 int i = sizeof(filter_name);
2932 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
2934 const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
2935 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_AUDIO ) {
2936 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
2939 filter_graph = avfilter_graph_alloc();
2940 const AVFilter *buffersrc = avfilter_get_by_name("abuffer");
2941 const AVFilter *buffersink = avfilter_get_by_name("abuffersink");
2942 int ret = 0; char args[BCTEXTLEN];
2943 AVSampleFormat sample_fmt = (AVSampleFormat)avpar->format;
2944 snprintf(args, sizeof(args),
2945 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
2946 st->time_base.num, st->time_base.den, avpar->sample_rate,
2947 av_get_sample_fmt_name(sample_fmt), avpar->channel_layout);
2949 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2950 args, NULL, filter_graph);
2952 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2953 NULL, NULL, filter_graph);
2955 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
2956 (uint8_t*)&sample_fmt, sizeof(sample_fmt),
2957 AV_OPT_SEARCH_CHILDREN);
2959 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
2960 (uint8_t*)&avpar->channel_layout,
2961 sizeof(avpar->channel_layout), AV_OPT_SEARCH_CHILDREN);
2963 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
2964 (uint8_t*)&sample_rate, sizeof(sample_rate),
2965 AV_OPT_SEARCH_CHILDREN);
2967 ff_err(ret, "FFAudioStream::create_filter");
2969 ret = FFStream::create_filter(filter_spec);
2970 return ret >= 0 ? 0 : -1;
2973 int FFStream::create_filter(const char *filter_spec)
2975 /* Endpoints for the filter graph. */
2976 AVFilterInOut *outputs = avfilter_inout_alloc();
2977 outputs->name = av_strdup("in");
2978 outputs->filter_ctx = buffersrc_ctx;
2979 outputs->pad_idx = 0;
2982 AVFilterInOut *inputs = avfilter_inout_alloc();
2983 inputs->name = av_strdup("out");
2984 inputs->filter_ctx = buffersink_ctx;
2985 inputs->pad_idx = 0;
2988 int ret = !outputs->name || !inputs->name ? -1 : 0;
2990 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
2991 &inputs, &outputs, NULL);
2993 ret = avfilter_graph_config(filter_graph, NULL);
2996 ff_err(ret, "FFStream::create_filter");
2997 avfilter_graph_free(&filter_graph);
3000 avfilter_inout_free(&inputs);
3001 avfilter_inout_free(&outputs);
3005 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
3008 av_init_packet(&pkt);
3009 AVFrame *frame = av_frame_alloc();
3011 fprintf(stderr,"FFMPEG::scan: ");
3012 fprintf(stderr,_("av_frame_alloc failed\n"));
3013 fprintf(stderr,"FFMPEG::scan:file=%s\n", file_base->asset->path);
3017 index_state->add_video_markers(ffvideo.size());
3018 index_state->add_audio_markers(ffaudio.size());
3020 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
3022 AVDictionary *copts = 0;
3023 av_dict_copy(&copts, opts, 0);
3024 AVStream *st = fmt_ctx->streams[i];
3025 AVCodecID codec_id = st->codecpar->codec_id;
3026 AVCodec *decoder = avcodec_find_decoder(codec_id);
3027 AVCodecContext *avctx = avcodec_alloc_context3(decoder);
3029 eprintf(_("cant allocate codec context\n"));
3030 ret = AVERROR(ENOMEM);
3033 avcodec_parameters_to_context(avctx, st->codecpar);
3034 if( !av_dict_get(copts, "threads", NULL, 0) )
3035 avctx->thread_count = ff_cpus();
3036 ret = avcodec_open2(avctx, decoder, &copts);
3038 av_dict_free(&copts);
3040 AVCodecParameters *avpar = st->codecpar;
3041 switch( avpar->codec_type ) {
3042 case AVMEDIA_TYPE_VIDEO: {
3043 int vidx = ffvideo.size();
3044 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
3045 if( vidx < 0 ) break;
3046 ffvideo[vidx]->avctx = avctx;
3048 case AVMEDIA_TYPE_AUDIO: {
3049 int aidx = ffaudio.size();
3050 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3051 if( aidx < 0 ) break;
3052 ffaudio[aidx]->avctx = avctx;
3057 fprintf(stderr,"FFMPEG::scan: ");
3058 fprintf(stderr,_("codec open failed\n"));
3059 fprintf(stderr,"FFMPEG::scan:file=%s\n", file_base->asset->path);
3060 avcodec_free_context(&avctx);
3064 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
3065 AVStream *st = fmt_ctx->streams[i];
3066 AVCodecParameters *avpar = st->codecpar;
3067 if( avpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
3068 int64_t tstmp = st->start_time;
3069 if( tstmp == AV_NOPTS_VALUE ) continue;
3070 int aidx = ffaudio.size();
3071 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3072 if( aidx < 0 ) continue;
3073 FFAudioStream *aud = ffaudio[aidx];
3074 tstmp -= aud->nudge;
3075 double secs = to_secs(tstmp, st->time_base);
3076 aud->curr_pos = secs * aud->sample_rate + 0.5;
3080 for( int64_t count=0; !*canceled; ++count ) {
3081 av_packet_unref(&pkt);
3082 pkt.data = 0; pkt.size = 0;
3084 int ret = av_read_frame(fmt_ctx, &pkt);
3086 if( ret == AVERROR_EOF ) break;
3087 if( ++errs > 100 ) {
3088 ff_err(ret,_("over 100 read_frame errs\n"));
3093 if( !pkt.data ) continue;
3094 int i = pkt.stream_index;
3095 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
3096 AVStream *st = fmt_ctx->streams[i];
3097 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
3099 AVCodecParameters *avpar = st->codecpar;
3100 switch( avpar->codec_type ) {
3101 case AVMEDIA_TYPE_VIDEO: {
3102 int vidx = ffvideo.size();
3103 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
3104 if( vidx < 0 ) break;
3105 FFVideoStream *vid = ffvideo[vidx];
3106 if( !vid->avctx ) break;
3107 int64_t tstmp = pkt.dts;
3108 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.pts;
3109 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
3110 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
3111 double secs = to_secs(tstmp, st->time_base);
3112 int64_t frm = secs * vid->frame_rate + 0.5;
3113 if( frm < 0 ) frm = 0;
3114 index_state->put_video_mark(vidx, frm, pkt.pos);
3117 ret = avcodec_send_packet(vid->avctx, pkt);
3118 if( ret < 0 ) break;
3119 while( (ret=vid->decode_frame(frame)) > 0 ) {}
3122 case AVMEDIA_TYPE_AUDIO: {
3123 int aidx = ffaudio.size();
3124 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3125 if( aidx < 0 ) break;
3126 FFAudioStream *aud = ffaudio[aidx];
3127 if( !aud->avctx ) break;
3128 int64_t tstmp = pkt.pts;
3129 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
3130 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
3131 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
3132 double secs = to_secs(tstmp, st->time_base);
3133 int64_t sample = secs * aud->sample_rate + 0.5;
3135 index_state->put_audio_mark(aidx, sample, pkt.pos);
3137 ret = avcodec_send_packet(aud->avctx, &pkt);
3138 if( ret < 0 ) break;
3139 int ch = aud->channel0, nch = aud->channels;
3140 int64_t pos = index_state->pos(ch);
3141 if( pos != aud->curr_pos ) {
3142 if( abs(pos-aud->curr_pos) > 1 )
3143 printf("audio%d pad %jd %jd (%jd)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
3144 index_state->pad_data(ch, nch, aud->curr_pos);
3146 while( (ret=aud->decode_frame(frame)) > 0 ) {
3147 //if( frame->channels != nch ) break;
3148 aud->init_swr(frame->channels, frame->format, frame->sample_rate);
3150 int len = aud->get_samples(samples,
3151 &frame->extended_data[0], frame->nb_samples);
3152 pos = aud->curr_pos;
3153 if( (aud->curr_pos += len) >= 0 ) {
3155 samples += -pos * nch;
3156 len = aud->curr_pos;
3158 for( int i=0; i<nch; ++i )
3159 index_state->put_data(ch+i,nch,samples+i,len);
3166 av_frame_free(&frame);
3170 void FFStream::load_markers(IndexMarks &marks, double rate)
3173 int64_t sz = marks.size();
3174 int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
3175 int nb_ent = st->nb_index_entries;
3176 // some formats already have an index
3178 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
3179 int64_t tstmp = ep->timestamp;
3180 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
3181 double secs = ffmpeg->to_secs(tstmp, st->time_base);
3182 int64_t no = secs * rate;
3183 while( in < sz && marks[in].no <= no ) ++in;
3185 int64_t len = sz - in;
3186 int64_t count = max_entries - nb_ent;
3187 if( count > len ) count = len;
3188 for( int i=0; i<count; ++i ) {
3189 int k = in + i * len / count;
3190 int64_t no = marks[k].no, pos = marks[k].pos;
3191 double secs = (double)no / rate;
3192 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
3193 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
3194 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);