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"
39 #define av_register_all(s)
40 #define avfilter_register_all(s)
43 #define VIDEO_INBUF_SIZE 0x10000
44 #define AUDIO_INBUF_SIZE 0x10000
45 #define VIDEO_REFILL_THRESH 0
46 #define AUDIO_REFILL_THRESH 0x1000
47 #define AUDIO_MIN_FRAME_SZ 128
49 Mutex FFMPEG::fflock("FFMPEG::fflock");
51 static void ff_err(int ret, const char *fmt, ...)
56 vsnprintf(msg, sizeof(msg), fmt, ap);
58 char errmsg[BCSTRLEN];
59 av_strerror(ret, errmsg, sizeof(errmsg));
60 fprintf(stderr,_("%s err: %s\n"),msg, errmsg);
66 pkt.data = 0; pkt.size = 0;
68 void FFPacket::finit()
70 av_packet_unref(&pkt);
73 FFrame::FFrame(FFStream *fst)
76 frm = av_frame_alloc();
77 init = fst->init_frame(frm);
85 void FFrame::queue(int64_t pos)
91 void FFrame::dequeue()
96 int FFAudioStream::read(float *fp, long len)
104 while( --k >= 0 ) *fp++ = *op++;
105 if( op >= lmt ) op = bfr;
110 void FFAudioStream::realloc(long nsz, int nch, long len)
112 long bsz = nsz * nch;
113 float *np = new float[bsz];
114 inp = np + read(np, len) * nch;
119 delete [] bfr; bfr = np;
122 void FFAudioStream::realloc(long nsz, int nch)
124 if( nsz > sz || this->nch != nch ) {
125 long len = this->nch != nch ? 0 : hpos;
126 if( len > sz ) len = sz;
128 realloc(nsz, nch, len);
132 void FFAudioStream::reserve(long nsz, int nch)
134 long len = (inp - outp) / nch;
136 if( nsz > sz || this->nch != nch ) {
137 if( this->nch != nch ) len = 0;
138 realloc(nsz, nch, len);
141 if( (len*=nch) > 0 && bfr != outp )
142 memmove(bfr, outp, len*sizeof(*bfr));
147 long FFAudioStream::used()
149 long len = inp>=outp ? inp-outp : inp-bfr + lmt-outp;
152 long FFAudioStream::avail()
155 if( in1 >= lmt ) in1 = bfr;
156 long len = outp >= in1 ? outp-in1 : outp-bfr + lmt-in1;
159 void FFAudioStream::reset_history()
163 memset(bfr, 0, lmt-bfr);
166 void FFAudioStream::iseek(int64_t ofs)
168 if( ofs > hpos ) ofs = hpos;
169 if( ofs > sz ) ofs = sz;
170 outp = inp - ofs*nch;
171 if( outp < bfr ) outp += sz*nch;
174 float *FFAudioStream::get_outp(int ofs)
181 int64_t FFAudioStream::put_inp(int ofs)
184 return (inp-outp) / nch;
187 int FFAudioStream::write(const float *fp, long len)
195 while( --k >= 0 ) *ip++ = *fp++;
196 if( ip >= lmt ) ip = bfr;
203 int FFAudioStream::zero(long len)
211 while( --k >= 0 ) *ip++ = 0;
212 if( ip >= lmt ) ip = bfr;
219 // does not advance outp
220 int FFAudioStream::read(double *dp, long len, int ch)
223 float *op = outp + ch;
224 float *lmt1 = lmt + nch-1;
226 int k = (lmt1 - op) / nch;
229 while( --k >= 0 ) { *dp++ = *op; op += nch; }
230 if( op >= lmt ) op -= sz*nch;
235 // load linear buffer, no wrapping allowed, does not advance inp
236 int FFAudioStream::write(const double *dp, long len, int ch)
239 float *ip = inp + ch;
240 while( --n >= 0 ) { *ip = *dp++; ip += nch; }
245 FFStream::FFStream(FFMPEG *ffmpeg, AVStream *st, int fidx)
247 this->ffmpeg = ffmpeg;
250 frm_lock = new Mutex("FFStream::frm_lock");
257 nudge = AV_NOPTS_VALUE;
258 seek_pos = curr_pos = 0;
260 reading = writing = 0;
271 FFStream::~FFStream()
273 if( reading > 0 || writing > 0 ) avcodec_close(avctx);
274 if( avctx ) avcodec_free_context(&avctx);
275 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
276 if( bsfc ) av_bsf_free(&bsfc);
277 while( frms.first ) frms.remove(frms.first);
278 if( filter_graph ) avfilter_graph_free(&filter_graph);
279 if( frame ) av_frame_free(&frame);
280 if( fframe ) av_frame_free(&fframe);
282 if( stats_fp ) fclose(stats_fp);
283 if( stats_in ) av_freep(&stats_in);
284 delete [] stats_filename;
287 void FFStream::ff_lock(const char *cp)
289 FFMPEG::fflock.lock(cp);
292 void FFStream::ff_unlock()
294 FFMPEG::fflock.unlock();
297 void FFStream::queue(FFrame *frm)
299 frm_lock->lock("FFStream::queue");
303 ffmpeg->mux_lock->unlock();
306 void FFStream::dequeue(FFrame *frm)
308 frm_lock->lock("FFStream::dequeue");
310 frms.remove_pointer(frm);
314 int FFStream::encode_activate()
317 writing = ffmpeg->encode_activate();
321 int FFStream::decode_activate()
323 if( reading < 0 && (reading=ffmpeg->decode_activate()) > 0 ) {
324 ff_lock("FFStream::decode_activate");
326 AVDictionary *copts = 0;
327 av_dict_copy(&copts, ffmpeg->opts, 0);
329 // this should be avformat_copy_context(), but no copy avail
330 ret = avformat_open_input(&fmt_ctx,
331 ffmpeg->fmt_ctx->url, ffmpeg->fmt_ctx->iformat, &copts);
333 ret = avformat_find_stream_info(fmt_ctx, 0);
334 st = fmt_ctx->streams[fidx];
337 if( ret >= 0 && st != 0 ) {
338 AVCodecID codec_id = st->codecpar->codec_id;
339 AVCodec *decoder = avcodec_find_decoder(codec_id);
340 avctx = avcodec_alloc_context3(decoder);
342 eprintf(_("cant allocate codec context\n"));
343 ret = AVERROR(ENOMEM);
346 avcodec_parameters_to_context(avctx, st->codecpar);
347 if( !av_dict_get(copts, "threads", NULL, 0) )
348 avctx->thread_count = ffmpeg->ff_cpus();
349 ret = avcodec_open2(avctx, decoder, &copts);
355 eprintf(_("open decoder failed\n"));
358 eprintf(_("can't clone input file\n"));
359 av_dict_free(&copts);
365 int FFStream::read_packet()
367 av_packet_unref(ipkt);
368 int ret = av_read_frame(fmt_ctx, ipkt);
371 if( ret == AVERROR_EOF ) return 0;
372 ff_err(ret, "FFStream::read_packet: av_read_frame failed\n");
379 int FFStream::decode(AVFrame *frame)
382 int retries = MAX_RETRY;
384 while( ret >= 0 && !flushed && --retries >= 0 ) {
386 if( (ret=read_packet()) < 0 ) break;
387 AVPacket *pkt = ret > 0 ? (AVPacket*)ipkt : 0;
389 if( pkt->stream_index != st->index ) continue;
390 if( !pkt->data | !pkt->size ) continue;
392 if( (ret=avcodec_send_packet(avctx, pkt)) < 0 ) {
393 ff_err(ret, "FFStream::decode: avcodec_send_packet failed\n");
399 if( (ret=decode_frame(frame)) > 0 ) break;
407 fprintf(stderr, "FFStream::decode: Retry limit\n");
411 fprintf(stderr, "FFStream::decode: failed\n");
415 int FFStream::load_filter(AVFrame *frame)
417 int ret = av_buffersrc_add_frame_flags(buffersrc_ctx, frame, 0);
419 eprintf(_("av_buffersrc_add_frame_flags failed\n"));
423 int FFStream::read_filter(AVFrame *frame)
425 int ret = av_buffersink_get_frame(buffersink_ctx, frame);
427 if( ret == AVERROR(EAGAIN) ) return 0;
428 if( ret == AVERROR_EOF ) { st_eof(1); return -1; }
429 ff_err(ret, "FFStream::read_filter: av_buffersink_get_frame failed\n");
435 int FFStream::read_frame(AVFrame *frame)
437 av_frame_unref(frame);
438 if( !filter_graph || !buffersrc_ctx || !buffersink_ctx )
439 return decode(frame);
440 if( !fframe && !(fframe=av_frame_alloc()) ) {
441 fprintf(stderr, "FFStream::read_frame: av_frame_alloc failed\n");
445 while( !flushed && !(ret=read_filter(frame)) ) {
446 if( (ret=decode(fframe)) < 0 ) break;
447 if( ret > 0 && (ret=load_filter(fframe)) < 0 ) break;
452 int FFStream::write_packet(FFPacket &pkt)
456 av_packet_rescale_ts(pkt, avctx->time_base, st->time_base);
457 pkt->stream_index = st->index;
458 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, pkt);
461 ret = av_bsf_send_packet(bsfc, pkt);
464 if( (ret=av_bsf_receive_packet(bsfc, bs)) < 0 ) {
465 if( ret == AVERROR(EAGAIN) ) return 0;
466 if( ret == AVERROR_EOF ) return -1;
469 av_packet_rescale_ts(bs, avctx->time_base, st->time_base);
470 bs->stream_index = st->index;
471 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, bs);
475 ff_err(ret, "FFStream::write_packet: write packet failed\n");
479 int FFStream::encode_frame(AVFrame *frame)
481 int pkts = 0, ret = 0;
482 for( int retry=100; --retry>=0; ) {
484 ret = avcodec_send_frame(avctx, frame);
485 if( !ret && frame ) return pkts;
486 if( ret < 0 && ret != AVERROR(EAGAIN) ) break;
488 ret = avcodec_receive_packet(avctx, opkt);
489 if( !frame && ret == AVERROR_EOF ) return pkts;
491 ret = write_packet(opkt);
494 if( frame && stats_fp ) {
495 ret = write_stats_file();
499 ff_err(ret, "FFStream::encode_frame: encode failed\n");
503 int FFStream::flush()
507 int ret = encode_frame(0);
508 if( ret >= 0 && stats_fp ) {
509 ret = write_stats_file();
513 ff_err(ret, "FFStream::flush");
514 return ret >= 0 ? 0 : 1;
518 int FFStream::open_stats_file()
520 stats_fp = fopen(stats_filename,"w");
521 return stats_fp ? 0 : AVERROR(errno);
524 int FFStream::close_stats_file()
527 fclose(stats_fp); stats_fp = 0;
532 int FFStream::read_stats_file()
534 int64_t len = 0; struct stat stats_st;
535 int fd = open(stats_filename, O_RDONLY);
536 int ret = fd >= 0 ? 0: ENOENT;
537 if( !ret && fstat(fd, &stats_st) )
540 len = stats_st.st_size;
541 stats_in = (char *)av_malloc(len+1);
545 if( !ret && read(fd, stats_in, len+1) != len )
549 avctx->stats_in = stats_in;
553 return !ret ? 0 : AVERROR(ret);
556 int FFStream::write_stats_file()
559 if( avctx->stats_out && (ret=strlen(avctx->stats_out)) > 0 ) {
560 int len = fwrite(avctx->stats_out, 1, ret, stats_fp);
562 ff_err(ret = AVERROR(errno), "FFStream::write_stats_file");
567 int FFStream::init_stats_file()
570 if( (pass & 2) && (ret = read_stats_file()) < 0 )
571 ff_err(ret, "stat file read: %s", stats_filename);
572 if( (pass & 1) && (ret=open_stats_file()) < 0 )
573 ff_err(ret, "stat file open: %s", stats_filename);
574 return ret >= 0 ? 0 : ret;
577 int FFStream::seek(int64_t no, double rate)
579 // default ffmpeg native seek
581 int64_t pos = no, pkt_pos = -1;
582 IndexMarks *index_markers = get_markers();
583 if( index_markers && index_markers->size() > 1 ) {
584 IndexMarks &marks = *index_markers;
585 int i = marks.find(pos);
586 int64_t n = i < 0 ? (i=0) : marks[i].no;
587 // if indexed seek point not too far away (<30 secs), use index
588 if( no-n < 30*rate ) {
591 if( i < marks.size() ) pkt_pos = marks[i].pos;
595 if( pos == curr_pos ) return 0;
596 double secs = pos < 0 ? 0. : pos / rate;
597 AVRational time_base = st->time_base;
598 int64_t tstmp = time_base.num > 0 ? secs * time_base.den/time_base.num : 0;
600 if( st->nb_index_entries > 0 ) tstmp = st->index_entries[0].timestamp;
601 else if( st->start_time != AV_NOPTS_VALUE ) tstmp = st->start_time;
602 else if( st->first_dts != AV_NOPTS_VALUE ) tstmp = st->first_dts;
603 else tstmp = INT64_MIN+1;
605 else if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
608 // seek all streams using the default timebase.
609 // this is how ffmpeg and ffplay work. stream seeks are less tested.
610 tstmp = av_rescale_q(tstmp, time_base, AV_TIME_BASE_Q);
614 avcodec_flush_buffers(avctx);
615 avformat_flush(fmt_ctx);
617 int64_t seek = tstmp;
618 int flags = AVSEEK_FLAG_ANY;
619 if( !(fmt_ctx->iformat->flags & AVFMT_NO_BYTE_SEEK) && pkt_pos >= 0 ) {
621 flags = AVSEEK_FLAG_BYTE;
623 int ret = avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, seek, INT64_MAX, flags);
625 // finds the first index frame below the target time
626 int flags = AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_ANY;
627 int ret = av_seek_frame(fmt_ctx, idx, tstmp, flags);
629 int retry = MAX_RETRY;
631 need_packet = 0; flushed = 0;
632 seeked = 1; st_eof(0);
633 // read up to retry packets, limited to npkts in stream, and not pkt.pos past pkt_pos
634 while( --retry >= 0 ) {
635 if( read_packet() <= 0 ) { ret = -1; break; }
636 if( ipkt->stream_index != st->index ) continue;
637 if( !ipkt->data || !ipkt->size ) continue;
638 if( pkt_pos >= 0 && ipkt->pos >= pkt_pos ) break;
639 if( --npkts <= 0 ) break;
640 int64_t pkt_ts = ipkt->dts != AV_NOPTS_VALUE ? ipkt->dts : ipkt->pts;
641 if( pkt_ts == AV_NOPTS_VALUE ) continue;
642 if( pkt_ts >= tstmp ) break;
645 fprintf(stderr,"FFStream::seek: retry limit, pos=%jd tstmp=%jd\n",pos,tstmp);
649 ret = avcodec_send_packet(avctx, ipkt);
651 //some codecs need more than one pkt to resync
652 if( ret == AVERROR_INVALIDDATA ) ret = 0;
654 ff_err(ret, "FFStream::avcodec_send_packet failed\n");
659 printf("** seek fail %jd, %jd\n", pos, tstmp);
660 seeked = need_packet = 0;
664 //printf("seeked pos = %ld, %ld\n", pos, tstmp);
665 seek_pos = curr_pos = pos;
669 FFAudioStream::FFAudioStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
670 : FFStream(ffmpeg, strm, fidx)
673 channel0 = channels = 0;
676 frame_sz = AUDIO_MIN_FRAME_SZ;
678 resample_context = 0;
679 swr_ichs = swr_ifmt = swr_irate = 0;
688 bfr = new float[bsz];
693 FFAudioStream::~FFAudioStream()
695 if( resample_context ) swr_free(&resample_context);
700 void FFAudioStream::init_swr(int ichs, int ifmt, int irate)
702 if( resample_context ) {
703 if( swr_ichs == ichs && swr_ifmt == ifmt && swr_irate == irate )
705 swr_free(&resample_context);
707 swr_ichs = ichs; swr_ifmt = ifmt; swr_irate = irate;
708 if( ichs == channels && ifmt == AV_SAMPLE_FMT_FLT && irate == sample_rate )
710 uint64_t ilayout = av_get_default_channel_layout(ichs);
711 if( !ilayout ) ilayout = ((uint64_t)1<<ichs) - 1;
712 uint64_t olayout = av_get_default_channel_layout(channels);
713 if( !olayout ) olayout = ((uint64_t)1<<channels) - 1;
714 resample_context = swr_alloc_set_opts(NULL,
715 olayout, AV_SAMPLE_FMT_FLT, sample_rate,
716 ilayout, (AVSampleFormat)ifmt, irate,
718 if( resample_context )
719 swr_init(resample_context);
722 int FFAudioStream::get_samples(float *&samples, uint8_t **data, int len)
724 samples = *(float **)data;
725 if( resample_context ) {
726 if( len > aud_bfr_sz ) {
732 aud_bfr = new float[aud_bfr_sz*channels];
734 int ret = swr_convert(resample_context,
735 (uint8_t**)&aud_bfr, aud_bfr_sz, (const uint8_t**)data, len);
737 ff_err(ret, "FFAudioStream::get_samples: swr_convert failed\n");
746 int FFAudioStream::load_history(uint8_t **data, int len)
749 len = get_samples(samples, data, len);
751 // biggest user bfr since seek + frame
752 realloc(mbsz + len + 1, channels);
758 int FFAudioStream::decode_frame(AVFrame *frame)
760 int first_frame = seeked; seeked = 0;
761 int ret = avcodec_receive_frame(avctx, frame);
763 if( first_frame || ret == AVERROR(EAGAIN) ) return 0;
764 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
765 ff_err(ret, "FFAudioStream::decode_frame: Could not read audio frame\n");
768 int64_t pkt_ts = frame->best_effort_timestamp;
769 if( pkt_ts != AV_NOPTS_VALUE )
770 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * sample_rate + 0.5;
774 int FFAudioStream::encode_activate()
776 if( writing >= 0 ) return writing;
777 if( !avctx->codec ) return writing = 0;
778 frame_sz = avctx->codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE ?
779 10000 : avctx->frame_size;
780 return FFStream::encode_activate();
783 int64_t FFAudioStream::load_buffer(double ** const sp, int len)
785 reserve(len+1, st->codecpar->channels);
786 for( int ch=0; ch<nch; ++ch )
787 write(sp[ch], len, ch);
791 int FFAudioStream::in_history(int64_t pos)
793 if( pos > curr_pos ) return 0;
795 if( len > sz ) len = sz;
796 if( pos < curr_pos - len ) return 0;
801 int FFAudioStream::init_frame(AVFrame *frame)
803 frame->nb_samples = frame_sz;
804 frame->format = avctx->sample_fmt;
805 frame->channel_layout = avctx->channel_layout;
806 frame->sample_rate = avctx->sample_rate;
807 int ret = av_frame_get_buffer(frame, 0);
809 ff_err(ret, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
813 int FFAudioStream::load(int64_t pos, int len)
815 if( audio_seek(pos) < 0 ) return -1;
816 if( !frame && !(frame=av_frame_alloc()) ) {
817 fprintf(stderr, "FFAudioStream::load: av_frame_alloc failed\n");
820 if( mbsz < len ) mbsz = len;
821 int64_t end_pos = pos + len;
822 int ret = 0, i = len / frame_sz + MAX_RETRY;
823 while( ret>=0 && !flushed && curr_pos<end_pos && --i>=0 ) {
824 ret = read_frame(frame);
825 if( ret > 0 && frame->nb_samples > 0 ) {
826 init_swr(frame->channels, frame->format, frame->sample_rate);
827 load_history(&frame->extended_data[0], frame->nb_samples);
828 curr_pos += frame->nb_samples;
831 if( end_pos > curr_pos ) {
832 zero(end_pos - curr_pos);
835 len = curr_pos - pos;
840 int FFAudioStream::audio_seek(int64_t pos)
842 if( decode_activate() <= 0 ) return -1;
843 if( !st->codecpar ) return -1;
844 if( in_history(pos) ) return 0;
845 if( pos == curr_pos ) return 0;
846 reset_history(); mbsz = 0;
847 // guarentee preload > 1sec samples
848 if( seek(pos-sample_rate, sample_rate) < 0 ) return -1;
852 int FFAudioStream::encode(double **samples, int len)
854 if( encode_activate() <= 0 ) return -1;
857 int64_t count = samples ? load_buffer(samples, len) : used();
858 int frame_sz1 = samples ? frame_sz-1 : 0;
861 while( ret >= 0 && count > frame_sz1 ) {
862 frm = new FFrame(this);
863 if( (ret=frm->initted()) < 0 ) break;
864 AVFrame *frame = *frm;
865 len = count >= frame_sz ? frame_sz : count;
866 float *bfrp = get_outp(len);
867 ret = swr_convert(resample_context,
868 (uint8_t **)frame->extended_data, len,
869 (const uint8_t **)&bfrp, len);
871 ff_err(ret, "FFAudioStream::encode: swr_convert failed\n");
874 frame->nb_samples = len;
875 frm->queue(curr_pos);
882 return ret >= 0 ? 0 : 1;
885 int FFAudioStream::drain()
890 int FFAudioStream::encode_frame(AVFrame *frame)
892 return FFStream::encode_frame(frame);
895 int FFAudioStream::write_packet(FFPacket &pkt)
897 return FFStream::write_packet(pkt);
900 void FFAudioStream::load_markers()
902 IndexState *index_state = ffmpeg->file_base->asset->index_state;
903 if( !index_state || idx >= index_state->audio_markers.size() ) return;
904 if( index_state->marker_status == MARKERS_NOTTESTED ) return;
905 FFStream::load_markers(*index_state->audio_markers[idx], sample_rate);
908 IndexMarks *FFAudioStream::get_markers()
910 IndexState *index_state = ffmpeg->file_base->asset->index_state;
911 if( !index_state || idx >= index_state->audio_markers.size() ) return 0;
912 return index_state->audio_markers[idx];
915 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
916 : FFStream(ffmpeg, strm, fidx)
927 FFVideoStream::~FFVideoStream()
931 int FFVideoStream::decode_frame(AVFrame *frame)
933 int first_frame = seeked; seeked = 0;
934 int ret = avcodec_receive_frame(avctx, frame);
936 if( first_frame || ret == AVERROR(EAGAIN) ) return 0;
937 if( ret == AVERROR(EAGAIN) ) return 0;
938 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
939 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame\n");
942 int64_t pkt_ts = frame->best_effort_timestamp;
943 if( pkt_ts != AV_NOPTS_VALUE )
944 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * frame_rate + 0.5;
948 int FFVideoStream::load(VFrame *vframe, int64_t pos)
950 int ret = video_seek(pos);
951 if( ret < 0 ) return -1;
952 if( !frame && !(frame=av_frame_alloc()) ) {
953 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
956 int i = MAX_RETRY + pos - curr_pos;
957 while( ret>=0 && !flushed && curr_pos<=pos && --i>=0 ) {
958 ret = read_frame(frame);
959 if( ret > 0 ) ++curr_pos;
961 if( frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0 )
964 ret = convert_cmodel(vframe, frame);
966 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
970 int FFVideoStream::video_seek(int64_t pos)
972 if( decode_activate() <= 0 ) return -1;
973 if( !st->codecpar ) return -1;
974 if( pos == curr_pos-1 && !seeked ) return 0;
975 // if close enough, just read up to current
976 int gop = avctx->gop_size;
977 if( gop < 4 ) gop = 4;
978 if( gop > 64 ) gop = 64;
979 int read_limit = curr_pos + 3*gop;
980 if( pos >= curr_pos && pos <= read_limit ) return 0;
981 // guarentee preload more than 2*gop frames
982 if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
986 int FFVideoStream::init_frame(AVFrame *picture)
988 picture->format = avctx->pix_fmt;
989 picture->width = avctx->width;
990 picture->height = avctx->height;
991 int ret = av_frame_get_buffer(picture, 32);
995 int FFVideoStream::encode(VFrame *vframe)
997 if( encode_activate() <= 0 ) return -1;
999 FFrame *picture = new FFrame(this);
1000 int ret = picture->initted();
1002 AVFrame *frame = *picture;
1003 frame->pts = curr_pos;
1004 ret = convert_pixfmt(vframe, frame);
1007 picture->queue(curr_pos);
1011 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
1014 return ret >= 0 ? 0 : 1;
1017 int FFVideoStream::drain()
1022 int FFVideoStream::encode_frame(AVFrame *frame)
1025 frame->interlaced_frame = interlaced;
1026 frame->top_field_first = top_field_first;
1028 return FFStream::encode_frame(frame);
1031 int FFVideoStream::write_packet(FFPacket &pkt)
1033 if( !(ffmpeg->fmt_ctx->oformat->flags & AVFMT_VARIABLE_FPS) )
1035 return FFStream::write_packet(pkt);
1038 AVPixelFormat FFVideoConvert::color_model_to_pix_fmt(int color_model)
1040 switch( color_model ) {
1041 case BC_YUV422: return AV_PIX_FMT_YUYV422;
1042 case BC_RGB888: return AV_PIX_FMT_RGB24;
1043 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
1044 case BC_BGR8888: return AV_PIX_FMT_BGR0;
1045 case BC_BGR888: return AV_PIX_FMT_BGR24;
1046 case BC_ARGB8888: return AV_PIX_FMT_ARGB;
1047 case BC_ABGR8888: return AV_PIX_FMT_ABGR;
1048 case BC_RGB8: return AV_PIX_FMT_RGB8;
1049 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
1050 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
1051 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
1052 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
1053 case BC_RGB565: return AV_PIX_FMT_RGB565;
1054 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
1055 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
1056 case BC_AYUV16161616: return AV_PIX_FMT_AYUV64LE;
1057 case BC_GBRP: return AV_PIX_FMT_GBRP;
1061 return AV_PIX_FMT_NB;
1064 int FFVideoConvert::pix_fmt_to_color_model(AVPixelFormat pix_fmt)
1067 case AV_PIX_FMT_YUYV422: return BC_YUV422;
1068 case AV_PIX_FMT_RGB24: return BC_RGB888;
1069 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
1070 case AV_PIX_FMT_BGR0: return BC_BGR8888;
1071 case AV_PIX_FMT_BGR24: return BC_BGR888;
1072 case AV_PIX_FMT_ARGB: return BC_ARGB8888;
1073 case AV_PIX_FMT_ABGR: return BC_ABGR8888;
1074 case AV_PIX_FMT_RGB8: return BC_RGB8;
1075 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
1076 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
1077 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
1078 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
1079 case AV_PIX_FMT_RGB565: return BC_RGB565;
1080 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
1081 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
1082 case AV_PIX_FMT_AYUV64LE: return BC_AYUV16161616;
1083 case AV_PIX_FMT_GBRP: return BC_GBRP;
1090 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip)
1092 AVFrame *ipic = av_frame_alloc();
1093 int ret = convert_picture_vframe(frame, ip, ipic);
1094 av_frame_free(&ipic);
1098 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip, AVFrame *ipic)
1100 int cmodel = frame->get_color_model();
1101 AVPixelFormat ofmt = color_model_to_pix_fmt(cmodel);
1102 if( ofmt == AV_PIX_FMT_NB ) return -1;
1103 int size = av_image_fill_arrays(ipic->data, ipic->linesize,
1104 frame->get_data(), ofmt, frame->get_w(), frame->get_h(), 1);
1105 if( size < 0 ) return -1;
1107 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1108 int ysz = bpp * frame->get_w(), usz = ysz;
1117 // override av_image_fill_arrays() for planar types
1118 ipic->data[0] = frame->get_y(); ipic->linesize[0] = ysz;
1119 ipic->data[1] = frame->get_u(); ipic->linesize[1] = usz;
1120 ipic->data[2] = frame->get_v(); ipic->linesize[2] = usz;
1123 ipic->data[0] = frame->get_data();
1124 ipic->linesize[0] = frame->get_bytes_per_line();
1128 AVPixelFormat pix_fmt = (AVPixelFormat)ip->format;
1129 convert_ctx = sws_getCachedContext(convert_ctx, ip->width, ip->height, pix_fmt,
1130 frame->get_w(), frame->get_h(), ofmt, SWS_POINT, NULL, NULL, NULL);
1131 if( !convert_ctx ) {
1132 fprintf(stderr, "FFVideoConvert::convert_picture_frame:"
1133 " sws_getCachedContext() failed\n");
1136 int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ip->height,
1137 ipic->data, ipic->linesize);
1139 ff_err(ret, "FFVideoConvert::convert_picture_frame: sws_scale() failed\n");
1145 int FFVideoConvert::convert_cmodel(VFrame *frame, AVFrame *ip)
1147 // try direct transfer
1148 if( !convert_picture_vframe(frame, ip) ) return 1;
1149 // use indirect transfer
1150 AVPixelFormat ifmt = (AVPixelFormat)ip->format;
1151 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
1153 for( int i = 0; i <desc->nb_components; ++i ) {
1154 int bits = desc->comp[i].depth;
1155 if( bits > max_bits ) max_bits = bits;
1157 int imodel = pix_fmt_to_color_model(ifmt);
1158 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1159 int cmodel = frame->get_color_model();
1160 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1161 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1162 imodel = cmodel_is_yuv ?
1163 (BC_CModels::has_alpha(cmodel) ?
1165 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1166 (BC_CModels::has_alpha(cmodel) ?
1167 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1168 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1170 VFrame vframe(ip->width, ip->height, imodel);
1171 if( convert_picture_vframe(&vframe, ip) ) return -1;
1172 frame->transfer_from(&vframe);
1176 int FFVideoConvert::transfer_cmodel(VFrame *frame, AVFrame *ifp)
1178 int ret = convert_cmodel(frame, ifp);
1180 const AVDictionary *src = ifp->metadata;
1181 AVDictionaryEntry *t = NULL;
1182 BC_Hash *hp = frame->get_params();
1184 while( (t=av_dict_get(src, "", t, AV_DICT_IGNORE_SUFFIX)) )
1185 hp->update(t->key, t->value);
1190 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op)
1192 AVFrame *opic = av_frame_alloc();
1193 int ret = convert_vframe_picture(frame, op, opic);
1194 av_frame_free(&opic);
1198 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op, AVFrame *opic)
1200 int cmodel = frame->get_color_model();
1201 AVPixelFormat ifmt = color_model_to_pix_fmt(cmodel);
1202 if( ifmt == AV_PIX_FMT_NB ) return -1;
1203 int size = av_image_fill_arrays(opic->data, opic->linesize,
1204 frame->get_data(), ifmt, frame->get_w(), frame->get_h(), 1);
1205 if( size < 0 ) return -1;
1207 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1208 int ysz = bpp * frame->get_w(), usz = ysz;
1217 // override av_image_fill_arrays() for planar types
1218 opic->data[0] = frame->get_y(); opic->linesize[0] = ysz;
1219 opic->data[1] = frame->get_u(); opic->linesize[1] = usz;
1220 opic->data[2] = frame->get_v(); opic->linesize[2] = usz;
1223 opic->data[0] = frame->get_data();
1224 opic->linesize[0] = frame->get_bytes_per_line();
1228 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1229 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(),
1230 ifmt, op->width, op->height, ofmt, SWS_POINT, NULL, NULL, NULL);
1231 if( !convert_ctx ) {
1232 fprintf(stderr, "FFVideoConvert::convert_frame_picture:"
1233 " sws_getCachedContext() failed\n");
1236 int ret = sws_scale(convert_ctx, opic->data, opic->linesize, 0, frame->get_h(),
1237 op->data, op->linesize);
1239 ff_err(ret, "FFVideoConvert::convert_frame_picture: sws_scale() failed\n");
1245 int FFVideoConvert::convert_pixfmt(VFrame *frame, AVFrame *op)
1247 // try direct transfer
1248 if( !convert_vframe_picture(frame, op) ) return 1;
1249 // use indirect transfer
1250 int cmodel = frame->get_color_model();
1251 int max_bits = BC_CModels::calculate_pixelsize(cmodel) * 8;
1252 max_bits /= BC_CModels::components(cmodel);
1253 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1254 int imodel = pix_fmt_to_color_model(ofmt);
1255 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1256 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1257 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1258 imodel = cmodel_is_yuv ?
1259 (BC_CModels::has_alpha(cmodel) ?
1261 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1262 (BC_CModels::has_alpha(cmodel) ?
1263 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1264 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1266 VFrame vframe(frame->get_w(), frame->get_h(), imodel);
1267 vframe.transfer_from(frame);
1268 if( !convert_vframe_picture(&vframe, op) ) return 1;
1272 int FFVideoConvert::transfer_pixfmt(VFrame *frame, AVFrame *ofp)
1274 int ret = convert_pixfmt(frame, ofp);
1276 BC_Hash *hp = frame->get_params();
1277 AVDictionary **dict = &ofp->metadata;
1278 //av_dict_free(dict);
1279 for( int i=0; i<hp->size(); ++i ) {
1280 char *key = hp->get_key(i), *val = hp->get_value(i);
1281 av_dict_set(dict, key, val, 0);
1287 void FFVideoStream::load_markers()
1289 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1290 if( !index_state || idx >= index_state->video_markers.size() ) return;
1291 FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
1294 IndexMarks *FFVideoStream::get_markers()
1296 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1297 if( !index_state || idx >= index_state->video_markers.size() ) return 0;
1298 return !index_state ? 0 : index_state->video_markers[idx];
1302 FFMPEG::FFMPEG(FileBase *file_base)
1305 this->file_base = file_base;
1306 memset(file_format,0,sizeof(file_format));
1307 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
1308 flow_lock = new Condition(1,"FFStream::flow_lock",0);
1311 decoding = encoding = 0;
1312 has_audio = has_video = 0;
1315 opt_video_filter = 0;
1316 opt_audio_filter = 0;
1317 char option_path[BCTEXTLEN];
1318 set_option_path(option_path, "%s", "ffmpeg.opts");
1319 read_options(option_path, opts);
1324 ff_lock("FFMPEG::~FFMPEG()");
1326 ffaudio.remove_all_objects();
1327 ffvideo.remove_all_objects();
1328 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1332 av_dict_free(&opts);
1333 delete [] opt_video_filter;
1334 delete [] opt_audio_filter;
1337 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1339 const int *p = codec->supported_samplerates;
1340 if( !p ) return sample_rate;
1342 if( *p == sample_rate ) return *p;
1348 static inline AVRational std_frame_rate(int i)
1350 static const int m1 = 1001*12, m2 = 1000*12;
1351 static const int freqs[] = {
1352 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1353 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
1355 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1356 return (AVRational) { freq, 1001*12 };
1359 AVRational FFMPEG::check_frame_rate(AVCodec *codec, double frame_rate)
1361 const AVRational *p = codec->supported_framerates;
1362 AVRational rate, best_rate = (AVRational) { 0, 0 };
1363 double max_err = 1.; int i = 0;
1364 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1365 double framerate = (double) rate.num / rate.den;
1366 double err = fabs(frame_rate/framerate - 1.);
1367 if( err >= max_err ) continue;
1371 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1374 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1377 double display_aspect = asset->width / (double)asset->height;
1378 double sample_aspect = display_aspect / asset->aspect_ratio;
1379 int width = 1000000, height = width * sample_aspect + 0.5;
1381 MWindow::create_aspect_ratio(w, h, width, height);
1382 return (AVRational){(int)w, (int)h};
1385 return (AVRational){1, 1};
1389 AVRational FFMPEG::to_time_base(int sample_rate)
1391 return (AVRational){1, sample_rate};
1394 int FFMPEG::get_fmt_score(AVSampleFormat dst_fmt, AVSampleFormat src_fmt)
1397 int dst_planar = av_sample_fmt_is_planar(dst_fmt);
1398 int src_planar = av_sample_fmt_is_planar(src_fmt);
1399 if( dst_planar != src_planar ) ++score;
1400 int dst_bytes = av_get_bytes_per_sample(dst_fmt);
1401 int src_bytes = av_get_bytes_per_sample(src_fmt);
1402 score += (src_bytes > dst_bytes ? 100 : -10) * (src_bytes - dst_bytes);
1403 int src_packed = av_get_packed_sample_fmt(src_fmt);
1404 int dst_packed = av_get_packed_sample_fmt(dst_fmt);
1405 if( dst_packed == AV_SAMPLE_FMT_S32 && src_packed == AV_SAMPLE_FMT_FLT ) score += 20;
1406 if( dst_packed == AV_SAMPLE_FMT_FLT && src_packed == AV_SAMPLE_FMT_S32 ) score += 2;
1410 AVSampleFormat FFMPEG::find_best_sample_fmt_of_list(
1411 const AVSampleFormat *sample_fmts, AVSampleFormat src_fmt)
1413 AVSampleFormat best = AV_SAMPLE_FMT_NONE;
1414 int best_score = get_fmt_score(best, src_fmt);
1415 for( int i=0; sample_fmts[i] >= 0; ++i ) {
1416 AVSampleFormat sample_fmt = sample_fmts[i];
1417 int score = get_fmt_score(sample_fmt, src_fmt);
1418 if( score >= best_score ) continue;
1419 best = sample_fmt; best_score = score;
1425 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
1427 char *ep = path + BCTEXTLEN-1;
1428 strncpy(path, File::get_cindat_path(), ep-path);
1429 strncat(path, "/ffmpeg/", ep-path);
1430 path += strlen(path);
1433 path += vsnprintf(path, ep-path, fmt, ap);
1438 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
1443 set_option_path(path, "%s/%s", type, spec);
1446 int FFMPEG::get_format(char *format, const char *path, const char *spec)
1448 char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
1449 get_option_path(option_path, path, spec);
1450 FILE *fp = fopen(option_path,"r");
1453 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1455 line[sizeof(line)-1] = 0;
1456 ret = scan_option_line(line, format, codec);
1462 int FFMPEG::get_codec(char *codec, const char *path, const char *spec)
1464 char option_path[BCTEXTLEN], line[BCTEXTLEN], format[BCTEXTLEN];
1465 get_option_path(option_path, path, spec);
1466 FILE *fp = fopen(option_path,"r");
1469 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1472 line[sizeof(line)-1] = 0;
1473 ret = scan_option_line(line, format, codec);
1476 char *vp = codec, *ep = vp+BCTEXTLEN-1;
1477 while( vp < ep && *vp && *vp != '|' ) ++vp;
1478 if( *vp == '|' ) --vp;
1479 while( vp > codec && (*vp==' ' || *vp=='\t') ) *vp-- = 0;
1484 int FFMPEG::get_file_format()
1486 char audio_muxer[BCSTRLEN], video_muxer[BCSTRLEN];
1487 char audio_format[BCSTRLEN], video_format[BCSTRLEN];
1488 audio_muxer[0] = audio_format[0] = 0;
1489 video_muxer[0] = video_format[0] = 0;
1490 Asset *asset = file_base->asset;
1491 int ret = asset ? 0 : 1;
1492 if( !ret && asset->audio_data ) {
1493 if( !(ret=get_format(audio_format, "audio", asset->acodec)) ) {
1494 if( get_format(audio_muxer, "format", audio_format) ) {
1495 strcpy(audio_muxer, audio_format);
1496 audio_format[0] = 0;
1500 if( !ret && asset->video_data ) {
1501 if( !(ret=get_format(video_format, "video", asset->vcodec)) ) {
1502 if( get_format(video_muxer, "format", video_format) ) {
1503 strcpy(video_muxer, video_format);
1504 video_format[0] = 0;
1508 if( !ret && !audio_muxer[0] && !video_muxer[0] )
1510 if( !ret && audio_muxer[0] && video_muxer[0] &&
1511 strcmp(audio_muxer, video_muxer) ) ret = -1;
1512 if( !ret && audio_format[0] && video_format[0] &&
1513 strcmp(audio_format, video_format) ) ret = -1;
1515 strcpy(file_format, !audio_format[0] && !video_format[0] ?
1516 (audio_muxer[0] ? audio_muxer : video_muxer) :
1517 (audio_format[0] ? audio_format : video_format));
1521 int FFMPEG::scan_option_line(const char *cp, char *tag, char *val)
1523 while( *cp == ' ' || *cp == '\t' ) ++cp;
1524 const char *bp = cp;
1525 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' && *cp != '\n' ) ++cp;
1527 if( !len || len > BCSTRLEN-1 ) return 1;
1528 while( bp < cp ) *tag++ = *bp++;
1530 while( *cp == ' ' || *cp == '\t' ) ++cp;
1531 if( *cp == '=' ) ++cp;
1532 while( *cp == ' ' || *cp == '\t' ) ++cp;
1534 while( *cp && *cp != '\n' ) ++cp;
1536 if( len > BCTEXTLEN-1 ) return 1;
1537 while( bp < cp ) *val++ = *bp++;
1542 int FFMPEG::can_render(const char *fformat, const char *type)
1545 char option_path[BCTEXTLEN];
1546 FFMPEG::set_option_path(option_path, type);
1547 fs.update(option_path);
1548 int total_files = fs.total_files();
1549 for( int i=0; i<total_files; ++i ) {
1550 const char *name = fs.get_entry(i)->get_name();
1551 const char *ext = strrchr(name,'.');
1552 if( !ext ) continue;
1553 if( !strcmp(fformat, ++ext) ) return 1;
1558 int FFMPEG::get_ff_option(const char *nm, const char *options, char *value)
1560 for( const char *cp=options; *cp!=0; ) {
1561 char line[BCTEXTLEN], *bp = line, *ep = bp+sizeof(line)-1;
1562 while( bp < ep && *cp && *cp!='\n' ) *bp++ = *cp++;
1565 if( !line[0] || line[0] == '#' || line[0] == ';' ) continue;
1566 char key[BCSTRLEN], val[BCTEXTLEN];
1567 if( FFMPEG::scan_option_line(line, key, val) ) continue;
1568 if( !strcmp(key, nm) ) {
1569 strncpy(value, val, BCSTRLEN);
1576 void FFMPEG::scan_audio_options(Asset *asset, EDL *edl)
1578 char cin_sample_fmt[BCSTRLEN];
1579 int cin_fmt = AV_SAMPLE_FMT_NONE;
1580 const char *options = asset->ff_audio_options;
1581 if( !get_ff_option("cin_sample_fmt", options, cin_sample_fmt) )
1582 cin_fmt = (int)av_get_sample_fmt(cin_sample_fmt);
1584 char audio_codec[BCSTRLEN]; audio_codec[0] = 0;
1585 AVCodec *av_codec = !FFMPEG::get_codec(audio_codec, "audio", asset->acodec) ?
1586 avcodec_find_encoder_by_name(audio_codec) : 0;
1587 if( av_codec && av_codec->sample_fmts )
1588 cin_fmt = find_best_sample_fmt_of_list(av_codec->sample_fmts, AV_SAMPLE_FMT_FLT);
1590 if( cin_fmt < 0 ) cin_fmt = AV_SAMPLE_FMT_S16;
1591 const char *name = av_get_sample_fmt_name((AVSampleFormat)cin_fmt);
1592 if( !name ) name = _("None");
1593 strcpy(asset->ff_sample_format, name);
1595 char value[BCSTRLEN];
1596 if( !get_ff_option("cin_bitrate", options, value) )
1597 asset->ff_audio_bitrate = atoi(value);
1598 if( !get_ff_option("cin_quality", options, value) )
1599 asset->ff_audio_quality = atoi(value);
1602 void FFMPEG::load_audio_options(Asset *asset, EDL *edl)
1604 char options_path[BCTEXTLEN];
1605 set_option_path(options_path, "audio/%s", asset->acodec);
1606 if( !load_options(options_path,
1607 asset->ff_audio_options,
1608 sizeof(asset->ff_audio_options)) )
1609 scan_audio_options(asset, edl);
1612 void FFMPEG::scan_video_options(Asset *asset, EDL *edl)
1614 char cin_pix_fmt[BCSTRLEN];
1615 int cin_fmt = AV_PIX_FMT_NONE;
1616 const char *options = asset->ff_video_options;
1617 if( !get_ff_option("cin_pix_fmt", options, cin_pix_fmt) )
1618 cin_fmt = (int)av_get_pix_fmt(cin_pix_fmt);
1620 char video_codec[BCSTRLEN]; video_codec[0] = 0;
1621 AVCodec *av_codec = !get_codec(video_codec, "video", asset->vcodec) ?
1622 avcodec_find_encoder_by_name(video_codec) : 0;
1623 if( av_codec && av_codec->pix_fmts ) {
1624 if( 0 && edl ) { // frequently picks a bad answer
1625 int color_model = edl->session->color_model;
1626 int max_bits = BC_CModels::calculate_pixelsize(color_model) * 8;
1627 max_bits /= BC_CModels::components(color_model);
1628 cin_fmt = avcodec_find_best_pix_fmt_of_list(av_codec->pix_fmts,
1629 (BC_CModels::is_yuv(color_model) ?
1630 (max_bits > 8 ? AV_PIX_FMT_AYUV64LE : AV_PIX_FMT_YUV444P) :
1631 (max_bits > 8 ? AV_PIX_FMT_RGB48LE : AV_PIX_FMT_RGB24)), 0, 0);
1634 cin_fmt = av_codec->pix_fmts[0];
1637 if( cin_fmt < 0 ) cin_fmt = AV_PIX_FMT_YUV420P;
1638 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get((AVPixelFormat)cin_fmt);
1639 const char *name = desc ? desc->name : _("None");
1640 strcpy(asset->ff_pixel_format, name);
1642 char value[BCSTRLEN];
1643 if( !get_ff_option("cin_bitrate", options, value) )
1644 asset->ff_video_bitrate = atoi(value);
1645 if( !get_ff_option("cin_quality", options, value) )
1646 asset->ff_video_quality = atoi(value);
1649 void FFMPEG::load_video_options(Asset *asset, EDL *edl)
1651 char options_path[BCTEXTLEN];
1652 set_option_path(options_path, "video/%s", asset->vcodec);
1653 if( !load_options(options_path,
1654 asset->ff_video_options,
1655 sizeof(asset->ff_video_options)) )
1656 scan_video_options(asset, edl);
1659 int FFMPEG::load_defaults(const char *path, const char *type,
1660 char *codec, char *codec_options, int len)
1662 char default_file[BCTEXTLEN];
1663 set_option_path(default_file, "%s/%s.dfl", path, type);
1664 FILE *fp = fopen(default_file,"r");
1666 fgets(codec, BCSTRLEN, fp);
1668 while( *cp && *cp!='\n' ) ++cp;
1670 while( len > 0 && fgets(codec_options, len, fp) ) {
1671 int n = strlen(codec_options);
1672 codec_options += n; len -= n;
1675 set_option_path(default_file, "%s/%s", path, codec);
1676 return load_options(default_file, codec_options, len);
1679 void FFMPEG::set_asset_format(Asset *asset, EDL *edl, const char *text)
1681 if( asset->format != FILE_FFMPEG ) return;
1682 if( text != asset->fformat )
1683 strcpy(asset->fformat, text);
1684 if( asset->audio_data && !asset->ff_audio_options[0] ) {
1685 if( !load_defaults("audio", text, asset->acodec,
1686 asset->ff_audio_options, sizeof(asset->ff_audio_options)) )
1687 scan_audio_options(asset, edl);
1689 asset->audio_data = 0;
1691 if( asset->video_data && !asset->ff_video_options[0] ) {
1692 if( !load_defaults("video", text, asset->vcodec,
1693 asset->ff_video_options, sizeof(asset->ff_video_options)) )
1694 scan_video_options(asset, edl);
1696 asset->video_data = 0;
1700 int FFMPEG::get_encoder(const char *options,
1701 char *format, char *codec, char *bsfilter)
1703 FILE *fp = fopen(options,"r");
1705 eprintf(_("options open failed %s\n"),options);
1708 char line[BCTEXTLEN];
1709 if( !fgets(line, sizeof(line), fp) ||
1710 scan_encoder(line, format, codec, bsfilter) )
1711 eprintf(_("format/codec not found %s\n"), options);
1716 int FFMPEG::scan_encoder(const char *line,
1717 char *format, char *codec, char *bsfilter)
1719 format[0] = codec[0] = bsfilter[0] = 0;
1720 if( scan_option_line(line, format, codec) ) return 1;
1722 while( *cp && *cp != '|' ) ++cp;
1723 if( !*cp ) return 0;
1725 do { *bp-- = 0; } while( bp>=codec && (*bp==' ' || *bp == '\t' ) );
1726 while( *++cp && (*cp==' ' || *cp == '\t') );
1728 for( int i=BCTEXTLEN; --i>0 && *cp; ) *bp++ = *cp++;
1733 int FFMPEG::read_options(const char *options, AVDictionary *&opts, int skip)
1735 FILE *fp = fopen(options,"r");
1738 while( !ret && --skip >= 0 ) {
1740 while( ch >= 0 && ch != '\n' ) ch = getc(fp);
1741 if( ch < 0 ) ret = 1;
1744 ret = read_options(fp, options, opts);
1749 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
1751 FILE *fp = fmemopen((void *)options,strlen(options),"r");
1753 int ret = read_options(fp, options, opts);
1755 AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
1756 if( tag ) st->id = strtol(tag->value,0,0);
1760 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
1762 int ret = 0, no = 0;
1763 char line[BCTEXTLEN];
1764 while( !ret && fgets(line, sizeof(line), fp) ) {
1765 line[sizeof(line)-1] = 0;
1766 if( line[0] == '#' ) continue;
1767 if( line[0] == '\n' ) continue;
1768 char key[BCSTRLEN], val[BCTEXTLEN];
1769 if( scan_option_line(line, key, val) ) {
1770 eprintf(_("err reading %s: line %d\n"), options, no);
1774 if( !strcmp(key, "duration") )
1775 opt_duration = strtod(val, 0);
1776 else if( !strcmp(key, "video_filter") )
1777 opt_video_filter = cstrdup(val);
1778 else if( !strcmp(key, "audio_filter") )
1779 opt_audio_filter = cstrdup(val);
1780 else if( !strcmp(key, "loglevel") )
1783 av_dict_set(&opts, key, val, 0);
1789 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
1791 char option_path[BCTEXTLEN];
1792 set_option_path(option_path, "%s", options);
1793 return read_options(option_path, opts);
1796 int FFMPEG::load_options(const char *path, char *bfr, int len)
1799 FILE *fp = fopen(path, "r");
1801 fgets(bfr, len, fp); // skip hdr
1802 len = fread(bfr, 1, len-1, fp);
1803 if( len < 0 ) len = 0;
1809 void FFMPEG::set_loglevel(const char *ap)
1811 if( !ap || !*ap ) return;
1816 { "quiet" , AV_LOG_QUIET },
1817 { "panic" , AV_LOG_PANIC },
1818 { "fatal" , AV_LOG_FATAL },
1819 { "error" , AV_LOG_ERROR },
1820 { "warning", AV_LOG_WARNING },
1821 { "info" , AV_LOG_INFO },
1822 { "verbose", AV_LOG_VERBOSE },
1823 { "debug" , AV_LOG_DEBUG },
1825 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
1826 if( !strcmp(log_levels[i].name, ap) ) {
1827 av_log_set_level(log_levels[i].level);
1831 av_log_set_level(atoi(ap));
1834 double FFMPEG::to_secs(int64_t time, AVRational time_base)
1836 double base_time = time == AV_NOPTS_VALUE ? 0 :
1837 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
1838 return base_time / AV_TIME_BASE;
1841 int FFMPEG::info(char *text, int len)
1843 if( len <= 0 ) return 0;
1845 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
1847 report("format: %s\n",fmt_ctx->iformat->name);
1848 if( ffvideo.size() > 0 )
1849 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
1850 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
1851 FFVideoStream *vid = ffvideo[vidx];
1852 AVStream *st = vid->st;
1853 AVCodecID codec_id = st->codecpar->codec_id;
1854 report(_("vid%d (%d), id 0x%06x:\n"), vid->idx, vid->fidx, codec_id);
1855 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
1856 report(" video%d %s", vidx+1, desc ? desc->name : " (unkn)");
1857 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
1858 AVPixelFormat pix_fmt = (AVPixelFormat)st->codecpar->format;
1859 const char *pfn = av_get_pix_fmt_name(pix_fmt);
1860 report(" pix %s\n", pfn ? pfn : "(unkn)");
1861 double secs = to_secs(st->duration, st->time_base);
1862 int64_t length = secs * vid->frame_rate + 0.5;
1863 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
1864 int64_t nudge = ofs * vid->frame_rate;
1865 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1866 report(" %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
1867 int hrs = secs/3600; secs -= hrs*3600;
1868 int mins = secs/60; secs -= mins*60;
1869 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1871 if( ffaudio.size() > 0 )
1872 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
1873 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
1874 FFAudioStream *aud = ffaudio[aidx];
1875 AVStream *st = aud->st;
1876 AVCodecID codec_id = st->codecpar->codec_id;
1877 report(_("aud%d (%d), id 0x%06x:\n"), aud->idx, aud->fidx, codec_id);
1878 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
1879 int nch = aud->channels, ch0 = aud->channel0+1;
1880 report(" audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
1881 AVSampleFormat sample_fmt = (AVSampleFormat)st->codecpar->format;
1882 const char *fmt = av_get_sample_fmt_name(sample_fmt);
1883 report(" %s %d", fmt, aud->sample_rate);
1884 int sample_bits = av_get_bits_per_sample(codec_id);
1885 report(" %dbits\n", sample_bits);
1886 double secs = to_secs(st->duration, st->time_base);
1887 int64_t length = secs * aud->sample_rate + 0.5;
1888 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
1889 int64_t nudge = ofs * aud->sample_rate;
1890 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1891 report(" %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
1892 int hrs = secs/3600; secs -= hrs*3600;
1893 int mins = secs/60; secs -= mins*60;
1894 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1896 if( fmt_ctx->nb_programs > 0 )
1897 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
1898 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
1899 report("program %d", i+1);
1900 AVProgram *pgrm = fmt_ctx->programs[i];
1901 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1902 int idx = pgrm->stream_index[j];
1903 int vidx = ffvideo.size();
1904 while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
1906 report(", vid%d", vidx);
1909 int aidx = ffaudio.size();
1910 while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
1912 report(", aud%d", aidx);
1915 report(", (%d)", pgrm->stream_index[j]);
1920 AVDictionaryEntry *tag = 0;
1921 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
1922 report("%s=%s\n", tag->key, tag->value);
1931 int FFMPEG::init_decoder(const char *filename)
1933 ff_lock("FFMPEG::init_decoder");
1935 char file_opts[BCTEXTLEN];
1936 char *bp = strrchr(strcpy(file_opts, filename), '/');
1937 char *sp = strrchr(!bp ? file_opts : bp, '.');
1938 if( !sp ) sp = bp + strlen(bp);
1940 AVInputFormat *ifmt = 0;
1942 strcpy(sp, ".opts");
1943 fp = fopen(file_opts, "r");
1946 read_options(fp, file_opts, opts);
1948 AVDictionaryEntry *tag;
1949 if( (tag=av_dict_get(opts, "format", NULL, 0)) != 0 ) {
1950 ifmt = av_find_input_format(tag->value);
1954 load_options("decode.opts", opts);
1955 AVDictionary *fopts = 0;
1956 av_dict_copy(&fopts, opts, 0);
1957 int ret = avformat_open_input(&fmt_ctx, filename, ifmt, &fopts);
1958 av_dict_free(&fopts);
1960 ret = avformat_find_stream_info(fmt_ctx, NULL);
1965 return !ret ? 0 : 1;
1968 int FFMPEG::open_decoder()
1971 if( stat(fmt_ctx->url, &st) < 0 ) {
1972 eprintf(_("can't stat file: %s\n"), fmt_ctx->url);
1976 int64_t file_bits = 8 * st.st_size;
1977 if( !fmt_ctx->bit_rate && opt_duration > 0 )
1978 fmt_ctx->bit_rate = file_bits / opt_duration;
1981 if( fmt_ctx->bit_rate > 0 ) {
1982 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1983 AVStream *st = fmt_ctx->streams[i];
1984 if( st->duration != AV_NOPTS_VALUE ) continue;
1985 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
1986 st->duration = av_rescale(file_bits, st->time_base.den,
1987 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
1991 static int notified = 0;
1992 if( !notified && estimated ) {
1994 printf("FFMPEG::open_decoder: some stream times estimated\n");
1997 ff_lock("FFMPEG::open_decoder");
1998 int ret = 0, bad_time = 0;
1999 for( int i=0; !ret && i<(int)fmt_ctx->nb_streams; ++i ) {
2000 AVStream *st = fmt_ctx->streams[i];
2001 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
2002 AVCodecParameters *avpar = st->codecpar;
2003 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avpar->codec_id);
2004 if( !codec_desc ) continue;
2005 switch( avpar->codec_type ) {
2006 case AVMEDIA_TYPE_VIDEO: {
2007 if( avpar->width < 1 ) continue;
2008 if( avpar->height < 1 ) continue;
2009 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
2010 if( framerate.num < 1 ) continue;
2012 int vidx = ffvideo.size();
2013 FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
2014 vstrm_index.append(ffidx(vidx, 0));
2015 ffvideo.append(vid);
2016 vid->width = avpar->width;
2017 vid->height = avpar->height;
2018 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
2019 double secs = to_secs(st->duration, st->time_base);
2020 vid->length = secs * vid->frame_rate;
2021 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
2022 vid->nudge = st->start_time;
2024 if( opt_video_filter )
2025 ret = vid->create_filter(opt_video_filter, avpar);
2027 case AVMEDIA_TYPE_AUDIO: {
2028 if( avpar->channels < 1 ) continue;
2029 if( avpar->sample_rate < 1 ) continue;
2031 int aidx = ffaudio.size();
2032 FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
2033 ffaudio.append(aud);
2034 aud->channel0 = astrm_index.size();
2035 aud->channels = avpar->channels;
2036 for( int ch=0; ch<aud->channels; ++ch )
2037 astrm_index.append(ffidx(aidx, ch));
2038 aud->sample_rate = avpar->sample_rate;
2039 double secs = to_secs(st->duration, st->time_base);
2040 aud->length = secs * aud->sample_rate;
2041 aud->init_swr(aud->channels, avpar->format, aud->sample_rate);
2042 aud->nudge = st->start_time;
2044 if( opt_audio_filter )
2045 ret = aud->create_filter(opt_audio_filter, avpar);
2051 printf("FFMPEG::open_decoder: some stream have bad times\n");
2053 return ret < 0 ? -1 : 0;
2057 int FFMPEG::init_encoder(const char *filename)
2059 // try access first for named pipes
2060 int ret = access(filename, W_OK);
2062 int fd = ::open(filename,O_WRONLY);
2063 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
2064 if( fd >= 0 ) { close(fd); ret = 0; }
2067 eprintf(_("bad file path: %s\n"), filename);
2070 ret = get_file_format();
2072 eprintf(_("bad file format: %s\n"), filename);
2076 eprintf(_("mismatch audio/video file format: %s\n"), filename);
2079 ff_lock("FFMPEG::init_encoder");
2081 char format[BCSTRLEN];
2082 if( get_format(format, "format", file_format) )
2083 strcpy(format, file_format);
2084 avformat_alloc_output_context2(&fmt_ctx, 0, format, filename);
2086 eprintf(_("failed: %s\n"), filename);
2091 load_options("encode.opts", opts);
2097 int FFMPEG::open_encoder(const char *type, const char *spec)
2100 Asset *asset = file_base->asset;
2101 char *filename = asset->path;
2102 AVDictionary *sopts = 0;
2103 av_dict_copy(&sopts, opts, 0);
2104 char option_path[BCTEXTLEN];
2105 set_option_path(option_path, "%s/%s.opts", type, type);
2106 read_options(option_path, sopts);
2107 get_option_path(option_path, type, spec);
2108 char format_name[BCSTRLEN], codec_name[BCTEXTLEN], bsfilter[BCTEXTLEN];
2109 if( get_encoder(option_path, format_name, codec_name, bsfilter) ) {
2110 eprintf(_("get_encoder failed %s:%s\n"), option_path, filename);
2115 if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
2117 else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
2118 else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
2121 ff_lock("FFMPEG::open_encoder");
2124 AVCodecContext *ctx = 0;
2126 const AVCodecDescriptor *codec_desc = 0;
2127 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
2129 eprintf(_("cant find codec %s:%s\n"), codec_name, filename);
2133 codec_desc = avcodec_descriptor_get(codec->id);
2135 eprintf(_("unknown codec %s:%s\n"), codec_name, filename);
2140 st = avformat_new_stream(fmt_ctx, 0);
2142 eprintf(_("cant create stream %s:%s\n"), codec_name, filename);
2147 switch( codec_desc->type ) {
2148 case AVMEDIA_TYPE_AUDIO: {
2150 eprintf(_("duplicate audio %s:%s\n"), codec_name, filename);
2154 if( scan_options(asset->ff_audio_options, sopts, st) ) {
2155 eprintf(_("bad audio options %s:%s\n"), codec_name, filename);
2160 ctx = avcodec_alloc_context3(codec);
2161 if( asset->ff_audio_bitrate > 0 ) {
2162 ctx->bit_rate = asset->ff_audio_bitrate;
2164 sprintf(arg, "%d", asset->ff_audio_bitrate);
2165 av_dict_set(&sopts, "b", arg, 0);
2167 else if( asset->ff_audio_quality >= 0 ) {
2168 ctx->global_quality = asset->ff_audio_quality * FF_QP2LAMBDA;
2169 ctx->qmin = ctx->qmax = asset->ff_audio_quality;
2170 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2171 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2172 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2174 av_dict_set(&sopts, "flags", "+qscale", 0);
2175 sprintf(arg, "%d", asset->ff_audio_quality);
2176 av_dict_set(&sopts, "qscale", arg, 0);
2177 sprintf(arg, "%d", ctx->global_quality);
2178 av_dict_set(&sopts, "global_quality", arg, 0);
2180 int aidx = ffaudio.size();
2181 int fidx = aidx + ffvideo.size();
2182 FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
2183 aud->avctx = ctx; ffaudio.append(aud); fst = aud;
2184 aud->sample_rate = asset->sample_rate;
2185 ctx->channels = aud->channels = asset->channels;
2186 for( int ch=0; ch<aud->channels; ++ch )
2187 astrm_index.append(ffidx(aidx, ch));
2188 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
2189 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
2190 if( !ctx->sample_rate ) {
2191 eprintf(_("check_sample_rate failed %s\n"), filename);
2195 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
2196 AVSampleFormat sample_fmt = av_get_sample_fmt(asset->ff_sample_format);
2197 if( sample_fmt == AV_SAMPLE_FMT_NONE )
2198 sample_fmt = codec->sample_fmts ? codec->sample_fmts[0] : AV_SAMPLE_FMT_S16;
2199 ctx->sample_fmt = sample_fmt;
2200 uint64_t layout = av_get_default_channel_layout(ctx->channels);
2201 aud->resample_context = swr_alloc_set_opts(NULL,
2202 layout, ctx->sample_fmt, aud->sample_rate,
2203 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
2205 swr_init(aud->resample_context);
2208 case AVMEDIA_TYPE_VIDEO: {
2210 eprintf(_("duplicate video %s:%s\n"), codec_name, filename);
2214 if( scan_options(asset->ff_video_options, sopts, st) ) {
2215 eprintf(_("bad video options %s:%s\n"), codec_name, filename);
2220 ctx = avcodec_alloc_context3(codec);
2221 if( asset->ff_video_bitrate > 0 ) {
2222 ctx->bit_rate = asset->ff_video_bitrate;
2224 sprintf(arg, "%d", asset->ff_video_bitrate);
2225 av_dict_set(&sopts, "b", arg, 0);
2227 else if( asset->ff_video_quality >= 0 ) {
2228 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
2229 ctx->qmin = ctx->qmax = asset->ff_video_quality;
2230 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2231 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2232 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2234 av_dict_set(&sopts, "flags", "+qscale", 0);
2235 sprintf(arg, "%d", asset->ff_video_quality);
2236 av_dict_set(&sopts, "qscale", arg, 0);
2237 sprintf(arg, "%d", ctx->global_quality);
2238 av_dict_set(&sopts, "global_quality", arg, 0);
2240 int vidx = ffvideo.size();
2241 int fidx = vidx + ffaudio.size();
2242 FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
2243 vstrm_index.append(ffidx(vidx, 0));
2244 vid->avctx = ctx; ffvideo.append(vid); fst = vid;
2245 vid->width = asset->width;
2246 vid->height = asset->height;
2247 vid->frame_rate = asset->frame_rate;
2249 AVPixelFormat pix_fmt = av_get_pix_fmt(asset->ff_pixel_format);
2250 if( pix_fmt == AV_PIX_FMT_NONE )
2251 pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
2252 ctx->pix_fmt = pix_fmt;
2253 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
2254 int mask_w = (1<<desc->log2_chroma_w)-1;
2255 ctx->width = (vid->width+mask_w) & ~mask_w;
2256 int mask_h = (1<<desc->log2_chroma_h)-1;
2257 ctx->height = (vid->height+mask_h) & ~mask_h;
2258 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
2259 AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
2260 if( !frame_rate.num || !frame_rate.den ) {
2261 eprintf(_("check_frame_rate failed %s\n"), filename);
2265 av_reduce(&frame_rate.num, &frame_rate.den,
2266 frame_rate.num, frame_rate.den, INT_MAX);
2267 ctx->framerate = (AVRational) { frame_rate.num, frame_rate.den };
2268 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
2269 st->avg_frame_rate = frame_rate;
2270 st->time_base = ctx->time_base;
2272 vid->interlaced = asset->interlace_mode == ILACE_MODE_TOP_FIRST ||
2273 asset->interlace_mode == ILACE_MODE_BOTTOM_FIRST ? 1 : 0;
2274 vid->top_field_first = asset->interlace_mode == ILACE_MODE_TOP_FIRST ? 1 : 0;
2277 eprintf(_("not audio/video, %s:%s\n"), codec_name, filename);
2282 AVDictionaryEntry *tag;
2283 if( (tag=av_dict_get(sopts, "cin_stats_filename", NULL, 0)) != 0 ) {
2284 char suffix[BCSTRLEN]; sprintf(suffix,"-%d.log",fst->fidx);
2285 fst->stats_filename = cstrcat(2, tag->value, suffix);
2287 if( (tag=av_dict_get(sopts, "flags", NULL, 0)) != 0 ) {
2288 int pass = fst->pass;
2289 char *cp = tag->value;
2291 int ch = *cp++, pfx = ch=='-' ? -1 : ch=='+' ? 1 : 0;
2292 if( !isalnum(!pfx ? ch : (ch=*cp++)) ) continue;
2293 char id[BCSTRLEN], *bp = id, *ep = bp+sizeof(id)-1;
2294 for( *bp++=ch; isalnum(ch=*cp); ++cp )
2295 if( bp < ep ) *bp++ = ch;
2297 if( !strcmp(id, "pass1") ) {
2298 pass = pfx<0 ? (pass&~1) : pfx>0 ? (pass|1) : 1;
2300 else if( !strcmp(id, "pass2") ) {
2301 pass = pfx<0 ? (pass&~2) : pfx>0 ? (pass|2) : 2;
2304 if( (fst->pass=pass) ) {
2305 if( pass & 1 ) ctx->flags |= AV_CODEC_FLAG_PASS1;
2306 if( pass & 2 ) ctx->flags |= AV_CODEC_FLAG_PASS2;
2312 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
2313 ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
2314 if( fst->stats_filename && (ret=fst->init_stats_file()) )
2315 eprintf(_("error: stats file = %s\n"), fst->stats_filename);
2318 av_dict_set(&sopts, "cin_bitrate", 0, 0);
2319 av_dict_set(&sopts, "cin_quality", 0, 0);
2321 if( !av_dict_get(sopts, "threads", NULL, 0) )
2322 ctx->thread_count = ff_cpus();
2323 ret = avcodec_open2(ctx, codec, &sopts);
2325 ret = avcodec_parameters_from_context(st->codecpar, ctx);
2327 fprintf(stderr, "Could not copy the stream parameters\n");
2330 _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
2331 ret = avcodec_copy_context(st->codec, ctx);
2332 _Pragma("GCC diagnostic warning \"-Wdeprecated-declarations\"")
2334 fprintf(stderr, "Could not copy the stream context\n");
2337 ff_err(ret,"FFMPEG::open_encoder");
2338 eprintf(_("open failed %s:%s\n"), codec_name, filename);
2344 if( !ret && fst && bsfilter[0] ) {
2345 ret = av_bsf_list_parse_str(bsfilter, &fst->bsfc);
2347 ff_err(ret,"FFMPEG::open_encoder");
2348 eprintf(_("bitstream filter failed %s:\n%s\n"), filename, bsfilter);
2359 av_dict_free(&sopts);
2363 int FFMPEG::close_encoder()
2366 if( encoding > 0 ) {
2367 av_write_trailer(fmt_ctx);
2368 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
2369 avio_closep(&fmt_ctx->pb);
2375 int FFMPEG::decode_activate()
2377 if( decoding < 0 ) {
2379 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
2380 ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
2381 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
2382 ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
2383 // set nudges for each program stream set
2384 const int64_t min_nudge = INT64_MIN+1;
2385 int npgrms = fmt_ctx->nb_programs;
2386 for( int i=0; i<npgrms; ++i ) {
2387 AVProgram *pgrm = fmt_ctx->programs[i];
2388 // first start time video stream
2389 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2390 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2391 int fidx = pgrm->stream_index[j];
2392 AVStream *st = fmt_ctx->streams[fidx];
2393 AVCodecParameters *avpar = st->codecpar;
2394 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2395 if( st->start_time == AV_NOPTS_VALUE ) continue;
2396 if( vstart_time < st->start_time )
2397 vstart_time = st->start_time;
2400 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2401 if( st->start_time == AV_NOPTS_VALUE ) continue;
2402 if( astart_time < st->start_time )
2403 astart_time = st->start_time;
2407 //since frame rate is much more grainy than sample rate, it is better to
2408 // align using video, so that total absolute error is minimized.
2409 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2410 astart_time > min_nudge ? astart_time : AV_NOPTS_VALUE;
2411 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2412 int fidx = pgrm->stream_index[j];
2413 AVStream *st = fmt_ctx->streams[fidx];
2414 AVCodecParameters *avpar = st->codecpar;
2415 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2416 for( int k=0; k<ffvideo.size(); ++k ) {
2417 if( ffvideo[k]->fidx != fidx ) continue;
2418 ffvideo[k]->nudge = nudge;
2422 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2423 for( int k=0; k<ffaudio.size(); ++k ) {
2424 if( ffaudio[k]->fidx != fidx ) continue;
2425 ffaudio[k]->nudge = nudge;
2431 // set nudges for any streams not yet set
2432 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2433 int nstreams = fmt_ctx->nb_streams;
2434 for( int i=0; i<nstreams; ++i ) {
2435 AVStream *st = fmt_ctx->streams[i];
2436 AVCodecParameters *avpar = st->codecpar;
2437 switch( avpar->codec_type ) {
2438 case AVMEDIA_TYPE_VIDEO: {
2439 if( st->start_time == AV_NOPTS_VALUE ) continue;
2440 int vidx = ffvideo.size();
2441 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
2442 if( vidx < 0 ) continue;
2443 if( ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
2444 if( vstart_time < st->start_time )
2445 vstart_time = st->start_time;
2447 case AVMEDIA_TYPE_AUDIO: {
2448 if( st->start_time == AV_NOPTS_VALUE ) continue;
2449 int aidx = ffaudio.size();
2450 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
2451 if( aidx < 0 ) continue;
2452 if( ffaudio[aidx]->frame_sz < avpar->frame_size )
2453 ffaudio[aidx]->frame_sz = avpar->frame_size;
2454 if( ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
2455 if( astart_time < st->start_time )
2456 astart_time = st->start_time;
2461 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2462 astart_time > min_nudge ? astart_time : 0;
2463 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
2464 if( ffvideo[vidx]->nudge == AV_NOPTS_VALUE )
2465 ffvideo[vidx]->nudge = nudge;
2467 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2468 if( ffaudio[aidx]->nudge == AV_NOPTS_VALUE )
2469 ffaudio[aidx]->nudge = nudge;
2476 int FFMPEG::encode_activate()
2479 if( encoding < 0 ) {
2481 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
2482 (ret=avio_open(&fmt_ctx->pb, fmt_ctx->url, AVIO_FLAG_WRITE)) < 0 ) {
2483 ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
2489 AVProgram *prog = av_new_program(fmt_ctx, prog_id);
2490 for( int i=0; i< ffvideo.size(); ++i )
2491 av_program_add_stream_index(fmt_ctx, prog_id, ffvideo[i]->fidx);
2492 for( int i=0; i< ffaudio.size(); ++i )
2493 av_program_add_stream_index(fmt_ctx, prog_id, ffaudio[i]->fidx);
2494 int pi = fmt_ctx->nb_programs;
2495 while( --pi >= 0 && fmt_ctx->programs[pi]->id != prog_id );
2496 AVDictionary **meta = &prog->metadata;
2497 av_dict_set(meta, "service_provider", "cin5", 0);
2498 const char *path = fmt_ctx->url, *bp = strrchr(path,'/');
2499 if( bp ) path = bp + 1;
2500 av_dict_set(meta, "title", path, 0);
2502 if( ffaudio.size() ) {
2503 const char *ep = getenv("CIN_AUDIO_LANG"), *lp = 0;
2504 if( !ep && (lp=getenv("LANG")) ) { // some are guesses
2505 static struct { const char lc[3], lng[4]; } lcode[] = {
2506 { "en", "eng" }, { "de", "ger" }, { "es", "spa" },
2507 { "eu", "bas" }, { "fr", "fre" }, { "el", "gre" },
2508 { "hi", "hin" }, { "it", "ita" }, { "ja", "jap" },
2509 { "ko", "kor" }, { "du", "dut" }, { "pl", "pol" },
2510 { "pt", "por" }, { "ru", "rus" }, { "sl", "slv" },
2511 { "uk", "ukr" }, { "vi", "vie" }, { "zh", "chi" },
2513 for( int i=sizeof(lcode)/sizeof(lcode[0]); --i>=0 && !ep; )
2514 if( !strncmp(lcode[i].lc,lp,2) ) ep = lcode[i].lng;
2516 if( !ep ) ep = "und";
2518 strncpy(lang,ep,3); lang[3] = 0;
2519 AVStream *st = ffaudio[0]->st;
2520 av_dict_set(&st->metadata,"language",lang,0);
2523 AVDictionary *fopts = 0;
2524 char option_path[BCTEXTLEN];
2525 set_option_path(option_path, "format/%s", file_format);
2526 read_options(option_path, fopts, 1);
2527 ret = avformat_write_header(fmt_ctx, &fopts);
2529 ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
2533 av_dict_free(&fopts);
2540 int FFMPEG::audio_seek(int stream, int64_t pos)
2542 int aidx = astrm_index[stream].st_idx;
2543 FFAudioStream *aud = ffaudio[aidx];
2544 aud->audio_seek(pos);
2548 int FFMPEG::video_seek(int stream, int64_t pos)
2550 int vidx = vstrm_index[stream].st_idx;
2551 FFVideoStream *vid = ffvideo[vidx];
2552 vid->video_seek(pos);
2557 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
2559 if( !has_audio || chn >= astrm_index.size() ) return -1;
2560 int aidx = astrm_index[chn].st_idx;
2561 FFAudioStream *aud = ffaudio[aidx];
2562 if( aud->load(pos, len) < len ) return -1;
2563 int ch = astrm_index[chn].st_ch;
2564 int ret = aud->read(samples,len,ch);
2568 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
2570 if( !has_video || layer >= vstrm_index.size() ) return -1;
2571 int vidx = vstrm_index[layer].st_idx;
2572 FFVideoStream *vid = ffvideo[vidx];
2573 return vid->load(vframe, pos);
2577 int FFMPEG::encode(int stream, double **samples, int len)
2579 FFAudioStream *aud = ffaudio[stream];
2580 return aud->encode(samples, len);
2584 int FFMPEG::encode(int stream, VFrame *frame)
2586 FFVideoStream *vid = ffvideo[stream];
2587 return vid->encode(frame);
2590 void FFMPEG::start_muxer()
2598 void FFMPEG::stop_muxer()
2607 void FFMPEG::flow_off()
2610 flow_lock->lock("FFMPEG::flow_off");
2614 void FFMPEG::flow_on()
2618 flow_lock->unlock();
2621 void FFMPEG::flow_ctl()
2624 flow_lock->lock("FFMPEG::flow_ctl");
2625 flow_lock->unlock();
2629 int FFMPEG::mux_audio(FFrame *frm)
2631 FFStream *fst = frm->fst;
2632 AVCodecContext *ctx = fst->avctx;
2633 AVFrame *frame = *frm;
2634 AVRational tick_rate = {1, ctx->sample_rate};
2635 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
2636 int ret = fst->encode_frame(frame);
2638 ff_err(ret, "FFMPEG::mux_audio");
2639 return ret >= 0 ? 0 : 1;
2642 int FFMPEG::mux_video(FFrame *frm)
2644 FFStream *fst = frm->fst;
2645 AVFrame *frame = *frm;
2646 frame->pts = frm->position;
2647 int ret = fst->encode_frame(frame);
2649 ff_err(ret, "FFMPEG::mux_video");
2650 return ret >= 0 ? 0 : 1;
2656 double atm = -1, vtm = -1;
2657 FFrame *afrm = 0, *vfrm = 0;
2659 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
2660 FFStream *fst = ffaudio[i];
2661 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
2662 FFrame *frm = fst->frms.first;
2663 if( !frm ) { if( !done ) return; continue; }
2664 double tm = to_secs(frm->position, fst->avctx->time_base);
2665 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
2667 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
2668 FFStream *fst = ffvideo[i];
2669 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
2670 FFrame *frm = fst->frms.first;
2671 if( !frm ) { if( !done ) return; continue; }
2672 double tm = to_secs(frm->position, fst->avctx->time_base);
2673 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
2675 if( !demand ) flow_off();
2676 if( !afrm && !vfrm ) break;
2677 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
2678 vfrm->position, vfrm->fst->avctx->time_base,
2679 afrm->position, afrm->fst->avctx->time_base);
2680 FFrame *frm = v <= 0 ? vfrm : afrm;
2681 if( frm == afrm ) mux_audio(frm);
2682 if( frm == vfrm ) mux_video(frm);
2691 mux_lock->lock("FFMPEG::run");
2694 for( int i=0; i<ffaudio.size(); ++i )
2695 ffaudio[i]->drain();
2696 for( int i=0; i<ffvideo.size(); ++i )
2697 ffvideo[i]->drain();
2699 for( int i=0; i<ffaudio.size(); ++i )
2700 ffaudio[i]->flush();
2701 for( int i=0; i<ffvideo.size(); ++i )
2702 ffvideo[i]->flush();
2706 int FFMPEG::ff_total_audio_channels()
2708 return astrm_index.size();
2711 int FFMPEG::ff_total_astreams()
2713 return ffaudio.size();
2716 int FFMPEG::ff_audio_channels(int stream)
2718 return ffaudio[stream]->channels;
2721 int FFMPEG::ff_sample_rate(int stream)
2723 return ffaudio[stream]->sample_rate;
2726 const char* FFMPEG::ff_audio_format(int stream)
2728 AVStream *st = ffaudio[stream]->st;
2729 AVCodecID id = st->codecpar->codec_id;
2730 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2731 return desc ? desc->name : _("Unknown");
2734 int FFMPEG::ff_audio_pid(int stream)
2736 return ffaudio[stream]->st->id;
2739 int64_t FFMPEG::ff_audio_samples(int stream)
2741 return ffaudio[stream]->length;
2744 // find audio astream/channels with this program,
2745 // or all program audio channels (astream=-1)
2746 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
2750 int vidx = ffvideo[vstream]->fidx;
2751 // find first program with this video stream
2752 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
2753 AVProgram *pgrm = fmt_ctx->programs[i];
2754 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
2755 int st_idx = pgrm->stream_index[j];
2756 AVStream *st = fmt_ctx->streams[st_idx];
2757 if( st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
2758 if( st_idx == vidx ) pidx = i;
2761 if( pidx < 0 ) return -1;
2763 int64_t channels = 0;
2764 AVProgram *pgrm = fmt_ctx->programs[pidx];
2765 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2766 int aidx = pgrm->stream_index[j];
2767 AVStream *st = fmt_ctx->streams[aidx];
2768 if( st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
2769 if( astream > 0 ) { --astream; continue; }
2771 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
2772 if( ffaudio[i]->fidx == aidx ) astrm = i;
2774 if( ret < 0 ) ret = astrm;
2775 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
2776 channels |= mask << ffaudio[astrm]->channel0;
2778 if( !astream ) break;
2780 channel_mask = channels;
2785 int FFMPEG::ff_total_video_layers()
2787 return vstrm_index.size();
2790 int FFMPEG::ff_total_vstreams()
2792 return ffvideo.size();
2795 int FFMPEG::ff_video_width(int stream)
2797 return ffvideo[stream]->width;
2800 int FFMPEG::ff_video_height(int stream)
2802 return ffvideo[stream]->height;
2805 int FFMPEG::ff_set_video_width(int stream, int width)
2807 int w = ffvideo[stream]->width;
2808 ffvideo[stream]->width = width;
2812 int FFMPEG::ff_set_video_height(int stream, int height)
2814 int h = ffvideo[stream]->height;
2815 ffvideo[stream]->height = height;
2819 int FFMPEG::ff_coded_width(int stream)
2821 return ffvideo[stream]->avctx->coded_width;
2824 int FFMPEG::ff_coded_height(int stream)
2826 return ffvideo[stream]->avctx->coded_height;
2829 float FFMPEG::ff_aspect_ratio(int stream)
2831 return ffvideo[stream]->aspect_ratio;
2834 const char* FFMPEG::ff_video_format(int stream)
2836 AVStream *st = ffvideo[stream]->st;
2837 AVCodecID id = st->codecpar->codec_id;
2838 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2839 return desc ? desc->name : _("Unknown");
2842 double FFMPEG::ff_frame_rate(int stream)
2844 return ffvideo[stream]->frame_rate;
2847 int64_t FFMPEG::ff_video_frames(int stream)
2849 return ffvideo[stream]->length;
2852 int FFMPEG::ff_video_pid(int stream)
2854 return ffvideo[stream]->st->id;
2857 int FFMPEG::ff_video_mpeg_color_range(int stream)
2859 return ffvideo[stream]->st->codecpar->color_range == AVCOL_RANGE_MPEG ? 1 : 0;
2862 int FFMPEG::ff_cpus()
2864 return file_base->file->cpus;
2867 int FFVideoStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
2869 avfilter_register_all();
2870 const char *sp = filter_spec;
2871 char filter_name[BCSTRLEN], *np = filter_name;
2872 int i = sizeof(filter_name);
2873 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
2875 const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
2876 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_VIDEO ) {
2877 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
2880 filter_graph = avfilter_graph_alloc();
2881 const AVFilter *buffersrc = avfilter_get_by_name("buffer");
2882 const AVFilter *buffersink = avfilter_get_by_name("buffersink");
2884 int ret = 0; char args[BCTEXTLEN];
2885 AVPixelFormat pix_fmt = (AVPixelFormat)avpar->format;
2886 snprintf(args, sizeof(args),
2887 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
2888 avpar->width, avpar->height, (int)pix_fmt,
2889 st->time_base.num, st->time_base.den,
2890 avpar->sample_aspect_ratio.num, avpar->sample_aspect_ratio.den);
2892 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2893 args, NULL, filter_graph);
2895 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2896 NULL, NULL, filter_graph);
2898 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
2899 (uint8_t*)&pix_fmt, sizeof(pix_fmt),
2900 AV_OPT_SEARCH_CHILDREN);
2902 ff_err(ret, "FFVideoStream::create_filter");
2904 ret = FFStream::create_filter(filter_spec);
2905 return ret >= 0 ? 0 : -1;
2908 int FFAudioStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
2910 avfilter_register_all();
2911 const char *sp = filter_spec;
2912 char filter_name[BCSTRLEN], *np = filter_name;
2913 int i = sizeof(filter_name);
2914 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
2916 const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
2917 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_AUDIO ) {
2918 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
2921 filter_graph = avfilter_graph_alloc();
2922 const AVFilter *buffersrc = avfilter_get_by_name("abuffer");
2923 const AVFilter *buffersink = avfilter_get_by_name("abuffersink");
2924 int ret = 0; char args[BCTEXTLEN];
2925 AVSampleFormat sample_fmt = (AVSampleFormat)avpar->format;
2926 snprintf(args, sizeof(args),
2927 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
2928 st->time_base.num, st->time_base.den, avpar->sample_rate,
2929 av_get_sample_fmt_name(sample_fmt), avpar->channel_layout);
2931 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2932 args, NULL, filter_graph);
2934 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2935 NULL, NULL, filter_graph);
2937 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
2938 (uint8_t*)&sample_fmt, sizeof(sample_fmt),
2939 AV_OPT_SEARCH_CHILDREN);
2941 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
2942 (uint8_t*)&avpar->channel_layout,
2943 sizeof(avpar->channel_layout), AV_OPT_SEARCH_CHILDREN);
2945 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
2946 (uint8_t*)&sample_rate, sizeof(sample_rate),
2947 AV_OPT_SEARCH_CHILDREN);
2949 ff_err(ret, "FFAudioStream::create_filter");
2951 ret = FFStream::create_filter(filter_spec);
2952 return ret >= 0 ? 0 : -1;
2955 int FFStream::create_filter(const char *filter_spec)
2957 /* Endpoints for the filter graph. */
2958 AVFilterInOut *outputs = avfilter_inout_alloc();
2959 outputs->name = av_strdup("in");
2960 outputs->filter_ctx = buffersrc_ctx;
2961 outputs->pad_idx = 0;
2964 AVFilterInOut *inputs = avfilter_inout_alloc();
2965 inputs->name = av_strdup("out");
2966 inputs->filter_ctx = buffersink_ctx;
2967 inputs->pad_idx = 0;
2970 int ret = !outputs->name || !inputs->name ? -1 : 0;
2972 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
2973 &inputs, &outputs, NULL);
2975 ret = avfilter_graph_config(filter_graph, NULL);
2978 ff_err(ret, "FFStream::create_filter");
2979 avfilter_graph_free(&filter_graph);
2982 avfilter_inout_free(&inputs);
2983 avfilter_inout_free(&outputs);
2987 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
2990 av_init_packet(&pkt);
2991 AVFrame *frame = av_frame_alloc();
2993 fprintf(stderr,"FFMPEG::scan: ");
2994 fprintf(stderr,_("av_frame_alloc failed\n"));
2998 index_state->add_video_markers(ffvideo.size());
2999 index_state->add_audio_markers(ffaudio.size());
3001 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
3003 AVDictionary *copts = 0;
3004 av_dict_copy(&copts, opts, 0);
3005 AVStream *st = fmt_ctx->streams[i];
3006 AVCodecID codec_id = st->codecpar->codec_id;
3007 AVCodec *decoder = avcodec_find_decoder(codec_id);
3008 AVCodecContext *avctx = avcodec_alloc_context3(decoder);
3010 eprintf(_("cant allocate codec context\n"));
3011 ret = AVERROR(ENOMEM);
3014 avcodec_parameters_to_context(avctx, st->codecpar);
3015 if( !av_dict_get(copts, "threads", NULL, 0) )
3016 avctx->thread_count = ff_cpus();
3017 ret = avcodec_open2(avctx, decoder, &copts);
3019 av_dict_free(&copts);
3021 AVCodecParameters *avpar = st->codecpar;
3022 switch( avpar->codec_type ) {
3023 case AVMEDIA_TYPE_VIDEO: {
3024 int vidx = ffvideo.size();
3025 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
3026 if( vidx < 0 ) break;
3027 ffvideo[vidx]->avctx = avctx;
3029 case AVMEDIA_TYPE_AUDIO: {
3030 int aidx = ffaudio.size();
3031 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3032 if( aidx < 0 ) break;
3033 ffaudio[aidx]->avctx = avctx;
3038 fprintf(stderr,"FFMPEG::scan: ");
3039 fprintf(stderr,_("codec open failed\n"));
3040 avcodec_free_context(&avctx);
3044 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
3045 AVStream *st = fmt_ctx->streams[i];
3046 AVCodecParameters *avpar = st->codecpar;
3047 if( avpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
3048 int64_t tstmp = st->start_time;
3049 if( tstmp == AV_NOPTS_VALUE ) continue;
3050 int aidx = ffaudio.size();
3051 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3052 if( aidx < 0 ) continue;
3053 FFAudioStream *aud = ffaudio[aidx];
3054 tstmp -= aud->nudge;
3055 double secs = to_secs(tstmp, st->time_base);
3056 aud->curr_pos = secs * aud->sample_rate + 0.5;
3060 for( int64_t count=0; !*canceled; ++count ) {
3061 av_packet_unref(&pkt);
3062 pkt.data = 0; pkt.size = 0;
3064 int ret = av_read_frame(fmt_ctx, &pkt);
3066 if( ret == AVERROR_EOF ) break;
3067 if( ++errs > 100 ) {
3068 ff_err(ret,_("over 100 read_frame errs\n"));
3073 if( !pkt.data ) continue;
3074 int i = pkt.stream_index;
3075 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
3076 AVStream *st = fmt_ctx->streams[i];
3077 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
3079 AVCodecParameters *avpar = st->codecpar;
3080 switch( avpar->codec_type ) {
3081 case AVMEDIA_TYPE_VIDEO: {
3082 int vidx = ffvideo.size();
3083 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
3084 if( vidx < 0 ) break;
3085 FFVideoStream *vid = ffvideo[vidx];
3086 if( !vid->avctx ) break;
3087 int64_t tstmp = pkt.dts;
3088 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.pts;
3089 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
3090 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
3091 double secs = to_secs(tstmp, st->time_base);
3092 int64_t frm = secs * vid->frame_rate + 0.5;
3093 if( frm < 0 ) frm = 0;
3094 index_state->put_video_mark(vidx, frm, pkt.pos);
3097 ret = avcodec_send_packet(vid->avctx, pkt);
3098 if( ret < 0 ) break;
3099 while( (ret=vid->decode_frame(frame)) > 0 ) {}
3102 case AVMEDIA_TYPE_AUDIO: {
3103 int aidx = ffaudio.size();
3104 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3105 if( aidx < 0 ) break;
3106 FFAudioStream *aud = ffaudio[aidx];
3107 if( !aud->avctx ) break;
3108 int64_t tstmp = pkt.pts;
3109 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
3110 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
3111 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
3112 double secs = to_secs(tstmp, st->time_base);
3113 int64_t sample = secs * aud->sample_rate + 0.5;
3115 index_state->put_audio_mark(aidx, sample, pkt.pos);
3117 ret = avcodec_send_packet(aud->avctx, &pkt);
3118 if( ret < 0 ) break;
3119 int ch = aud->channel0, nch = aud->channels;
3120 int64_t pos = index_state->pos(ch);
3121 if( pos != aud->curr_pos ) {
3122 if( abs(pos-aud->curr_pos) > 1 )
3123 printf("audio%d pad %jd %jd (%jd)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
3124 index_state->pad_data(ch, nch, aud->curr_pos);
3126 while( (ret=aud->decode_frame(frame)) > 0 ) {
3127 //if( frame->channels != nch ) break;
3128 aud->init_swr(frame->channels, frame->format, frame->sample_rate);
3130 int len = aud->get_samples(samples,
3131 &frame->extended_data[0], frame->nb_samples);
3132 pos = aud->curr_pos;
3133 if( (aud->curr_pos += len) >= 0 ) {
3135 samples += -pos * nch;
3136 len = aud->curr_pos;
3138 for( int i=0; i<nch; ++i )
3139 index_state->put_data(ch+i,nch,samples+i,len);
3146 av_frame_free(&frame);
3150 void FFStream::load_markers(IndexMarks &marks, double rate)
3153 int64_t sz = marks.size();
3154 int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
3155 int nb_ent = st->nb_index_entries;
3156 // some formats already have an index
3158 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
3159 int64_t tstmp = ep->timestamp;
3160 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
3161 double secs = ffmpeg->to_secs(tstmp, st->time_base);
3162 int64_t no = secs * rate;
3163 while( in < sz && marks[in].no <= no ) ++in;
3165 int64_t len = sz - in;
3166 int64_t count = max_entries - nb_ent;
3167 if( count > len ) count = len;
3168 for( int i=0; i<count; ++i ) {
3169 int k = in + i * len / count;
3170 int64_t no = marks[k].no, pos = marks[k].pos;
3171 double secs = (double)no / rate;
3172 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
3173 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
3174 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);