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 Mutex FFMPEG::fflock("FFMPEG::fflock");
53 static void ff_err(int ret, const char *fmt, ...)
58 vsnprintf(msg, sizeof(msg), fmt, ap);
60 char errmsg[BCSTRLEN];
61 av_strerror(ret, errmsg, sizeof(errmsg));
62 fprintf(stderr,_("%s err: %s\n"),msg, errmsg);
68 pkt.data = 0; pkt.size = 0;
70 void FFPacket::finit()
72 av_packet_unref(&pkt);
75 FFrame::FFrame(FFStream *fst)
78 frm = av_frame_alloc();
79 init = fst->init_frame(frm);
87 void FFrame::queue(int64_t pos)
93 void FFrame::dequeue()
98 int FFAudioStream::read(float *fp, long len)
106 while( --k >= 0 ) *fp++ = *op++;
107 if( op >= lmt ) op = bfr;
112 void FFAudioStream::realloc(long nsz, int nch, long len)
114 long bsz = nsz * nch;
115 float *np = new float[bsz];
116 inp = np + read(np, len) * nch;
121 delete [] bfr; bfr = np;
124 void FFAudioStream::realloc(long nsz, int nch)
126 if( nsz > sz || this->nch != nch ) {
127 long len = this->nch != nch ? 0 : hpos;
128 if( len > sz ) len = sz;
130 realloc(nsz, nch, len);
134 void FFAudioStream::reserve(long nsz, int nch)
136 long len = (inp - outp) / nch;
138 if( nsz > sz || this->nch != nch ) {
139 if( this->nch != nch ) len = 0;
140 realloc(nsz, nch, len);
143 if( (len*=nch) > 0 && bfr != outp )
144 memmove(bfr, outp, len*sizeof(*bfr));
149 long FFAudioStream::used()
151 long len = inp>=outp ? inp-outp : inp-bfr + lmt-outp;
154 long FFAudioStream::avail()
157 if( in1 >= lmt ) in1 = bfr;
158 long len = outp >= in1 ? outp-in1 : outp-bfr + lmt-in1;
161 void FFAudioStream::reset_history()
165 memset(bfr, 0, lmt-bfr);
168 void FFAudioStream::iseek(int64_t ofs)
170 if( ofs > hpos ) ofs = hpos;
171 if( ofs > sz ) ofs = sz;
172 outp = inp - ofs*nch;
173 if( outp < bfr ) outp += sz*nch;
176 float *FFAudioStream::get_outp(int ofs)
183 int64_t FFAudioStream::put_inp(int ofs)
186 return (inp-outp) / nch;
189 int FFAudioStream::write(const float *fp, long len)
197 while( --k >= 0 ) *ip++ = *fp++;
198 if( ip >= lmt ) ip = bfr;
205 int FFAudioStream::zero(long len)
213 while( --k >= 0 ) *ip++ = 0;
214 if( ip >= lmt ) ip = bfr;
221 // does not advance outp
222 int FFAudioStream::read(double *dp, long len, int ch)
225 float *op = outp + ch;
226 float *lmt1 = lmt + nch-1;
228 int k = (lmt1 - op) / nch;
231 while( --k >= 0 ) { *dp++ = *op; op += nch; }
232 if( op >= lmt ) op -= sz*nch;
237 // load linear buffer, no wrapping allowed, does not advance inp
238 int FFAudioStream::write(const double *dp, long len, int ch)
241 float *ip = inp + ch;
242 while( --n >= 0 ) { *ip = *dp++; ip += nch; }
247 FFStream::FFStream(FFMPEG *ffmpeg, AVStream *st, int fidx)
249 this->ffmpeg = ffmpeg;
252 frm_lock = new Mutex("FFStream::frm_lock");
259 nudge = AV_NOPTS_VALUE;
260 seek_pos = curr_pos = 0;
262 reading = writing = 0;
273 FFStream::~FFStream()
275 if( reading > 0 || writing > 0 ) avcodec_close(avctx);
276 if( avctx ) avcodec_free_context(&avctx);
277 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
278 if( bsfc ) av_bsf_free(&bsfc);
279 while( frms.first ) frms.remove(frms.first);
280 if( filter_graph ) avfilter_graph_free(&filter_graph);
281 if( frame ) av_frame_free(&frame);
282 if( fframe ) av_frame_free(&fframe);
284 if( stats_fp ) fclose(stats_fp);
285 if( stats_in ) av_freep(&stats_in);
286 delete [] stats_filename;
289 void FFStream::ff_lock(const char *cp)
291 FFMPEG::fflock.lock(cp);
294 void FFStream::ff_unlock()
296 FFMPEG::fflock.unlock();
299 void FFStream::queue(FFrame *frm)
301 frm_lock->lock("FFStream::queue");
305 ffmpeg->mux_lock->unlock();
308 void FFStream::dequeue(FFrame *frm)
310 frm_lock->lock("FFStream::dequeue");
312 frms.remove_pointer(frm);
316 int FFStream::encode_activate()
319 writing = ffmpeg->encode_activate();
323 int FFStream::decode_activate()
325 if( reading < 0 && (reading=ffmpeg->decode_activate()) > 0 ) {
326 ff_lock("FFStream::decode_activate");
328 AVDictionary *copts = 0;
329 av_dict_copy(&copts, ffmpeg->opts, 0);
331 // this should be avformat_copy_context(), but no copy avail
332 ret = avformat_open_input(&fmt_ctx,
333 ffmpeg->fmt_ctx->url, ffmpeg->fmt_ctx->iformat, &copts);
335 ret = avformat_find_stream_info(fmt_ctx, 0);
336 st = fmt_ctx->streams[fidx];
339 if( ret >= 0 && st != 0 ) {
340 AVCodecID codec_id = st->codecpar->codec_id;
341 AVCodec *decoder = avcodec_find_decoder(codec_id);
342 avctx = avcodec_alloc_context3(decoder);
344 eprintf(_("cant allocate codec context\n"));
345 ret = AVERROR(ENOMEM);
348 avcodec_parameters_to_context(avctx, st->codecpar);
349 if( !av_dict_get(copts, "threads", NULL, 0) )
350 avctx->thread_count = ffmpeg->ff_cpus();
351 ret = avcodec_open2(avctx, decoder, &copts);
357 eprintf(_("open decoder failed\n"));
360 eprintf(_("can't clone input file\n"));
361 av_dict_free(&copts);
367 int FFStream::read_packet()
369 av_packet_unref(ipkt);
370 int ret = av_read_frame(fmt_ctx, ipkt);
373 if( ret == AVERROR_EOF ) return 0;
374 ff_err(ret, "FFStream::read_packet: av_read_frame failed\n");
381 int FFStream::decode(AVFrame *frame)
384 int retries = MAX_RETRY;
386 while( ret >= 0 && !flushed && --retries >= 0 ) {
388 if( (ret=read_packet()) < 0 ) break;
389 AVPacket *pkt = ret > 0 ? (AVPacket*)ipkt : 0;
391 if( pkt->stream_index != st->index ) continue;
392 if( !pkt->data | !pkt->size ) continue;
394 if( (ret=avcodec_send_packet(avctx, pkt)) < 0 ) {
395 ff_err(ret, "FFStream::decode: avcodec_send_packet failed\n");
401 if( (ret=decode_frame(frame)) > 0 ) break;
409 fprintf(stderr, "FFStream::decode: Retry limit\n");
413 fprintf(stderr, "FFStream::decode: failed\n");
417 int FFStream::load_filter(AVFrame *frame)
419 int ret = av_buffersrc_add_frame_flags(buffersrc_ctx, frame, 0);
421 eprintf(_("av_buffersrc_add_frame_flags failed\n"));
425 int FFStream::read_filter(AVFrame *frame)
427 int ret = av_buffersink_get_frame(buffersink_ctx, frame);
429 if( ret == AVERROR(EAGAIN) ) return 0;
430 if( ret == AVERROR_EOF ) { st_eof(1); return -1; }
431 ff_err(ret, "FFStream::read_filter: av_buffersink_get_frame failed\n");
437 int FFStream::read_frame(AVFrame *frame)
439 av_frame_unref(frame);
440 if( !filter_graph || !buffersrc_ctx || !buffersink_ctx )
441 return decode(frame);
442 if( !fframe && !(fframe=av_frame_alloc()) ) {
443 fprintf(stderr, "FFStream::read_frame: av_frame_alloc failed\n");
447 while( !flushed && !(ret=read_filter(frame)) ) {
448 if( (ret=decode(fframe)) < 0 ) break;
449 if( ret > 0 && (ret=load_filter(fframe)) < 0 ) break;
454 int FFStream::write_packet(FFPacket &pkt)
458 av_packet_rescale_ts(pkt, avctx->time_base, st->time_base);
459 pkt->stream_index = st->index;
460 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, pkt);
463 ret = av_bsf_send_packet(bsfc, pkt);
466 if( (ret=av_bsf_receive_packet(bsfc, bs)) < 0 ) {
467 if( ret == AVERROR(EAGAIN) ) return 0;
468 if( ret == AVERROR_EOF ) return -1;
471 av_packet_rescale_ts(bs, avctx->time_base, st->time_base);
472 bs->stream_index = st->index;
473 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, bs);
477 ff_err(ret, "FFStream::write_packet: write packet failed\n");
481 int FFStream::encode_frame(AVFrame *frame)
483 int pkts = 0, ret = 0;
484 for( int retry=100; --retry>=0; ) {
486 ret = avcodec_send_frame(avctx, frame);
487 if( !ret && frame ) return pkts;
488 if( ret < 0 && ret != AVERROR(EAGAIN) ) break;
490 ret = avcodec_receive_packet(avctx, opkt);
491 if( !frame && ret == AVERROR_EOF ) return pkts;
493 ret = write_packet(opkt);
496 if( frame && stats_fp ) {
497 ret = write_stats_file();
501 ff_err(ret, "FFStream::encode_frame: encode failed\n");
505 int FFStream::flush()
509 int ret = encode_frame(0);
510 if( ret >= 0 && stats_fp ) {
511 ret = write_stats_file();
515 ff_err(ret, "FFStream::flush");
516 return ret >= 0 ? 0 : 1;
520 int FFStream::open_stats_file()
522 stats_fp = fopen(stats_filename,"w");
523 return stats_fp ? 0 : AVERROR(errno);
526 int FFStream::close_stats_file()
529 fclose(stats_fp); stats_fp = 0;
534 int FFStream::read_stats_file()
536 int64_t len = 0; struct stat stats_st;
537 int fd = open(stats_filename, O_RDONLY);
538 int ret = fd >= 0 ? 0: ENOENT;
539 if( !ret && fstat(fd, &stats_st) )
542 len = stats_st.st_size;
543 stats_in = (char *)av_malloc(len+1);
547 if( !ret && read(fd, stats_in, len+1) != len )
551 avctx->stats_in = stats_in;
555 return !ret ? 0 : AVERROR(ret);
558 int FFStream::write_stats_file()
561 if( avctx->stats_out && (ret=strlen(avctx->stats_out)) > 0 ) {
562 int len = fwrite(avctx->stats_out, 1, ret, stats_fp);
564 ff_err(ret = AVERROR(errno), "FFStream::write_stats_file");
569 int FFStream::init_stats_file()
572 if( (pass & 2) && (ret = read_stats_file()) < 0 )
573 ff_err(ret, "stat file read: %s", stats_filename);
574 if( (pass & 1) && (ret=open_stats_file()) < 0 )
575 ff_err(ret, "stat file open: %s", stats_filename);
576 return ret >= 0 ? 0 : ret;
579 int FFStream::seek(int64_t no, double rate)
581 // default ffmpeg native seek
583 int64_t pos = no, pkt_pos = -1;
584 IndexMarks *index_markers = get_markers();
585 if( index_markers && index_markers->size() > 1 ) {
586 IndexMarks &marks = *index_markers;
587 int i = marks.find(pos);
588 int64_t n = i < 0 ? (i=0) : marks[i].no;
589 // if indexed seek point not too far away (<30 secs), use index
590 if( no-n < 30*rate ) {
593 if( i < marks.size() ) pkt_pos = marks[i].pos;
597 if( pos == curr_pos ) return 0;
598 double secs = pos < 0 ? 0. : pos / rate;
599 AVRational time_base = st->time_base;
600 int64_t tstmp = time_base.num > 0 ? secs * time_base.den/time_base.num : 0;
602 if( st->nb_index_entries > 0 ) tstmp = st->index_entries[0].timestamp;
603 else if( st->start_time != AV_NOPTS_VALUE ) tstmp = st->start_time;
604 else if( st->first_dts != AV_NOPTS_VALUE ) tstmp = st->first_dts;
605 else tstmp = INT64_MIN+1;
607 else if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
610 // seek all streams using the default timebase.
611 // this is how ffmpeg and ffplay work. stream seeks are less tested.
612 tstmp = av_rescale_q(tstmp, time_base, AV_TIME_BASE_Q);
616 avcodec_flush_buffers(avctx);
617 avformat_flush(fmt_ctx);
619 int64_t seek = tstmp;
620 int flags = AVSEEK_FLAG_ANY;
621 if( !(fmt_ctx->iformat->flags & AVFMT_NO_BYTE_SEEK) && pkt_pos >= 0 ) {
623 flags = AVSEEK_FLAG_BYTE;
625 int ret = avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, seek, INT64_MAX, flags);
627 // finds the first index frame below the target time
628 int flags = AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_ANY;
629 int ret = av_seek_frame(fmt_ctx, idx, tstmp, flags);
631 int retry = MAX_RETRY;
633 need_packet = 0; flushed = 0;
634 seeked = 1; st_eof(0);
635 // read up to retry packets, limited to npkts in stream, and not pkt.pos past pkt_pos
636 while( --retry >= 0 ) {
637 if( read_packet() <= 0 ) { ret = -1; break; }
638 if( ipkt->stream_index != st->index ) continue;
639 if( !ipkt->data || !ipkt->size ) continue;
640 if( pkt_pos >= 0 && ipkt->pos >= pkt_pos ) break;
641 if( --npkts <= 0 ) break;
642 int64_t pkt_ts = ipkt->dts != AV_NOPTS_VALUE ? ipkt->dts : ipkt->pts;
643 if( pkt_ts == AV_NOPTS_VALUE ) continue;
644 if( pkt_ts >= tstmp ) break;
647 fprintf(stderr,"FFStream::seek: retry limit, pos=%jd tstmp=%jd\n",pos,tstmp);
651 ret = avcodec_send_packet(avctx, ipkt);
653 //some codecs need more than one pkt to resync
654 if( ret == AVERROR_INVALIDDATA ) ret = 0;
656 ff_err(ret, "FFStream::avcodec_send_packet failed\n");
661 printf("** seek fail %jd, %jd\n", pos, tstmp);
662 seeked = need_packet = 0;
666 //printf("seeked pos = %ld, %ld\n", pos, tstmp);
667 seek_pos = curr_pos = pos;
671 FFAudioStream::FFAudioStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
672 : FFStream(ffmpeg, strm, fidx)
675 channel0 = channels = 0;
678 frame_sz = AUDIO_MIN_FRAME_SZ;
680 resample_context = 0;
681 swr_ichs = swr_ifmt = swr_irate = 0;
690 bfr = new float[bsz];
695 FFAudioStream::~FFAudioStream()
697 if( resample_context ) swr_free(&resample_context);
702 void FFAudioStream::init_swr(int ichs, int ifmt, int irate)
704 if( resample_context ) {
705 if( swr_ichs == ichs && swr_ifmt == ifmt && swr_irate == irate )
707 swr_free(&resample_context);
709 swr_ichs = ichs; swr_ifmt = ifmt; swr_irate = irate;
710 if( ichs == channels && ifmt == AV_SAMPLE_FMT_FLT && irate == sample_rate )
712 uint64_t ilayout = av_get_default_channel_layout(ichs);
713 if( !ilayout ) ilayout = ((uint64_t)1<<ichs) - 1;
714 uint64_t olayout = av_get_default_channel_layout(channels);
715 if( !olayout ) olayout = ((uint64_t)1<<channels) - 1;
716 resample_context = swr_alloc_set_opts(NULL,
717 olayout, AV_SAMPLE_FMT_FLT, sample_rate,
718 ilayout, (AVSampleFormat)ifmt, irate,
720 if( resample_context )
721 swr_init(resample_context);
724 int FFAudioStream::get_samples(float *&samples, uint8_t **data, int len)
726 samples = *(float **)data;
727 if( resample_context ) {
728 if( len > aud_bfr_sz ) {
734 aud_bfr = new float[aud_bfr_sz*channels];
736 int ret = swr_convert(resample_context,
737 (uint8_t**)&aud_bfr, aud_bfr_sz, (const uint8_t**)data, len);
739 ff_err(ret, "FFAudioStream::get_samples: swr_convert failed\n");
748 int FFAudioStream::load_history(uint8_t **data, int len)
751 len = get_samples(samples, data, len);
753 // biggest user bfr since seek + frame
754 realloc(mbsz + len + 1, channels);
760 int FFAudioStream::decode_frame(AVFrame *frame)
762 int first_frame = seeked; seeked = 0;
763 frame->best_effort_timestamp = AV_NOPTS_VALUE;
764 int ret = avcodec_receive_frame(avctx, frame);
766 if( first_frame || ret == AVERROR(EAGAIN) ) return 0;
767 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
768 ff_err(ret, "FFAudioStream::decode_frame: Could not read audio frame\n");
771 int64_t pkt_ts = frame->best_effort_timestamp;
772 if( pkt_ts != AV_NOPTS_VALUE ) {
773 double ts = ffmpeg->to_secs(pkt_ts - nudge, st->time_base);
774 double t = (double)curr_pos / sample_rate;
775 // some time_base clocks are very grainy, too grainy for audio (clicks, pops)
776 if( fabs(ts - t) > AUDIO_PTS_TOLERANCE )
777 curr_pos = ts * sample_rate + 0.5;
782 int FFAudioStream::encode_activate()
784 if( writing >= 0 ) return writing;
785 if( !avctx->codec ) return writing = 0;
786 frame_sz = avctx->codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE ?
787 10000 : avctx->frame_size;
788 return FFStream::encode_activate();
791 int64_t FFAudioStream::load_buffer(double ** const sp, int len)
793 reserve(len+1, st->codecpar->channels);
794 for( int ch=0; ch<nch; ++ch )
795 write(sp[ch], len, ch);
799 int FFAudioStream::in_history(int64_t pos)
801 if( pos > curr_pos ) return 0;
803 if( len > sz ) len = sz;
804 if( pos < curr_pos - len ) return 0;
809 int FFAudioStream::init_frame(AVFrame *frame)
811 frame->nb_samples = frame_sz;
812 frame->format = avctx->sample_fmt;
813 frame->channel_layout = avctx->channel_layout;
814 frame->sample_rate = avctx->sample_rate;
815 int ret = av_frame_get_buffer(frame, 0);
817 ff_err(ret, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
821 int FFAudioStream::load(int64_t pos, int len)
823 if( audio_seek(pos) < 0 ) return -1;
824 if( !frame && !(frame=av_frame_alloc()) ) {
825 fprintf(stderr, "FFAudioStream::load: av_frame_alloc failed\n");
828 if( mbsz < len ) mbsz = len;
829 int64_t end_pos = pos + len;
830 int ret = 0, i = len / frame_sz + MAX_RETRY;
831 while( ret>=0 && !flushed && curr_pos<end_pos && --i>=0 ) {
832 ret = read_frame(frame);
833 if( ret > 0 && frame->nb_samples > 0 ) {
834 init_swr(frame->channels, frame->format, frame->sample_rate);
835 load_history(&frame->extended_data[0], frame->nb_samples);
836 curr_pos += frame->nb_samples;
839 if( end_pos > curr_pos ) {
840 zero(end_pos - curr_pos);
843 len = curr_pos - pos;
848 int FFAudioStream::audio_seek(int64_t pos)
850 if( decode_activate() <= 0 ) return -1;
851 if( !st->codecpar ) return -1;
852 if( in_history(pos) ) return 0;
853 if( pos == curr_pos ) return 0;
854 reset_history(); mbsz = 0;
855 // guarentee preload > 1sec samples
856 if( (pos-=sample_rate) < 0 ) pos = 0;
857 if( seek(pos, sample_rate) < 0 ) return -1;
861 int FFAudioStream::encode(double **samples, int len)
863 if( encode_activate() <= 0 ) return -1;
866 int64_t count = samples ? load_buffer(samples, len) : used();
867 int frame_sz1 = samples ? frame_sz-1 : 0;
870 while( ret >= 0 && count > frame_sz1 ) {
871 frm = new FFrame(this);
872 if( (ret=frm->initted()) < 0 ) break;
873 AVFrame *frame = *frm;
874 len = count >= frame_sz ? frame_sz : count;
875 float *bfrp = get_outp(len);
876 ret = swr_convert(resample_context,
877 (uint8_t **)frame->extended_data, len,
878 (const uint8_t **)&bfrp, len);
880 ff_err(ret, "FFAudioStream::encode: swr_convert failed\n");
883 frame->nb_samples = len;
884 frm->queue(curr_pos);
891 return ret >= 0 ? 0 : 1;
894 int FFAudioStream::drain()
899 int FFAudioStream::encode_frame(AVFrame *frame)
901 return FFStream::encode_frame(frame);
904 int FFAudioStream::write_packet(FFPacket &pkt)
906 return FFStream::write_packet(pkt);
909 void FFAudioStream::load_markers()
911 IndexState *index_state = ffmpeg->file_base->asset->index_state;
912 if( !index_state || idx >= index_state->audio_markers.size() ) return;
913 if( index_state->marker_status == MARKERS_NOTTESTED ) return;
914 FFStream::load_markers(*index_state->audio_markers[idx], sample_rate);
917 IndexMarks *FFAudioStream::get_markers()
919 IndexState *index_state = ffmpeg->file_base->asset->index_state;
920 if( !index_state || idx >= index_state->audio_markers.size() ) return 0;
921 return index_state->audio_markers[idx];
924 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
925 : FFStream(ffmpeg, strm, fidx)
936 FFVideoStream::~FFVideoStream()
940 int FFVideoStream::decode_frame(AVFrame *frame)
942 int first_frame = seeked; seeked = 0;
943 int ret = avcodec_receive_frame(avctx, frame);
945 if( first_frame || ret == AVERROR(EAGAIN) ) return 0;
946 if( ret == AVERROR(EAGAIN) ) return 0;
947 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
948 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame\n");
951 int64_t pkt_ts = frame->best_effort_timestamp;
952 if( pkt_ts != AV_NOPTS_VALUE )
953 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * frame_rate + 0.5;
957 int FFVideoStream::load(VFrame *vframe, int64_t pos)
959 int ret = video_seek(pos);
960 if( ret < 0 ) return -1;
961 if( !frame && !(frame=av_frame_alloc()) ) {
962 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
965 int i = MAX_RETRY + pos - curr_pos;
966 while( ret>=0 && !flushed && curr_pos<=pos && --i>=0 ) {
967 ret = read_frame(frame);
968 if( ret > 0 ) ++curr_pos;
970 if( frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0 )
973 ret = convert_cmodel(vframe, frame);
975 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
979 int FFVideoStream::video_seek(int64_t pos)
981 if( decode_activate() <= 0 ) return -1;
982 if( !st->codecpar ) return -1;
983 if( pos == curr_pos-1 && !seeked ) return 0;
984 // if close enough, just read up to current
985 int gop = avctx->gop_size;
986 if( gop < 4 ) gop = 4;
987 if( gop > 64 ) gop = 64;
988 int read_limit = curr_pos + 3*gop;
989 if( pos >= curr_pos && pos <= read_limit ) return 0;
990 // guarentee preload more than 2*gop frames
991 if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
995 int FFVideoStream::init_frame(AVFrame *picture)
997 picture->format = avctx->pix_fmt;
998 picture->width = avctx->width;
999 picture->height = avctx->height;
1000 int ret = av_frame_get_buffer(picture, 32);
1004 int FFVideoStream::encode(VFrame *vframe)
1006 if( encode_activate() <= 0 ) return -1;
1008 FFrame *picture = new FFrame(this);
1009 int ret = picture->initted();
1011 AVFrame *frame = *picture;
1012 frame->pts = curr_pos;
1013 ret = convert_pixfmt(vframe, frame);
1016 picture->queue(curr_pos);
1020 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
1023 return ret >= 0 ? 0 : 1;
1026 int FFVideoStream::drain()
1031 int FFVideoStream::encode_frame(AVFrame *frame)
1034 frame->interlaced_frame = interlaced;
1035 frame->top_field_first = top_field_first;
1037 return FFStream::encode_frame(frame);
1040 int FFVideoStream::write_packet(FFPacket &pkt)
1042 if( !(ffmpeg->fmt_ctx->oformat->flags & AVFMT_VARIABLE_FPS) )
1044 return FFStream::write_packet(pkt);
1047 AVPixelFormat FFVideoConvert::color_model_to_pix_fmt(int color_model)
1049 switch( color_model ) {
1050 case BC_YUV422: return AV_PIX_FMT_YUYV422;
1051 case BC_RGB888: return AV_PIX_FMT_RGB24;
1052 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
1053 case BC_BGR8888: return AV_PIX_FMT_BGR0;
1054 case BC_BGR888: return AV_PIX_FMT_BGR24;
1055 case BC_ARGB8888: return AV_PIX_FMT_ARGB;
1056 case BC_ABGR8888: return AV_PIX_FMT_ABGR;
1057 case BC_RGB8: return AV_PIX_FMT_RGB8;
1058 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
1059 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
1060 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
1061 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
1062 case BC_RGB565: return AV_PIX_FMT_RGB565;
1063 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
1064 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
1065 case BC_AYUV16161616: return AV_PIX_FMT_AYUV64LE;
1066 case BC_GBRP: return AV_PIX_FMT_GBRP;
1070 return AV_PIX_FMT_NB;
1073 int FFVideoConvert::pix_fmt_to_color_model(AVPixelFormat pix_fmt)
1076 case AV_PIX_FMT_YUYV422: return BC_YUV422;
1077 case AV_PIX_FMT_RGB24: return BC_RGB888;
1078 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
1079 case AV_PIX_FMT_BGR0: return BC_BGR8888;
1080 case AV_PIX_FMT_BGR24: return BC_BGR888;
1081 case AV_PIX_FMT_ARGB: return BC_ARGB8888;
1082 case AV_PIX_FMT_ABGR: return BC_ABGR8888;
1083 case AV_PIX_FMT_RGB8: return BC_RGB8;
1084 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
1085 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
1086 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
1087 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
1088 case AV_PIX_FMT_RGB565: return BC_RGB565;
1089 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
1090 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
1091 case AV_PIX_FMT_AYUV64LE: return BC_AYUV16161616;
1092 case AV_PIX_FMT_GBRP: return BC_GBRP;
1099 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip)
1101 AVFrame *ipic = av_frame_alloc();
1102 int ret = convert_picture_vframe(frame, ip, ipic);
1103 av_frame_free(&ipic);
1107 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip, AVFrame *ipic)
1109 int cmodel = frame->get_color_model();
1110 AVPixelFormat ofmt = color_model_to_pix_fmt(cmodel);
1111 if( ofmt == AV_PIX_FMT_NB ) return -1;
1112 int size = av_image_fill_arrays(ipic->data, ipic->linesize,
1113 frame->get_data(), ofmt, frame->get_w(), frame->get_h(), 1);
1114 if( size < 0 ) return -1;
1116 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1117 int ysz = bpp * frame->get_w(), usz = ysz;
1127 // override av_image_fill_arrays() for planar types
1128 ipic->data[0] = frame->get_y(); ipic->linesize[0] = ysz;
1129 ipic->data[1] = frame->get_u(); ipic->linesize[1] = usz;
1130 ipic->data[2] = frame->get_v(); ipic->linesize[2] = usz;
1133 ipic->data[0] = frame->get_data();
1134 ipic->linesize[0] = frame->get_bytes_per_line();
1138 AVPixelFormat pix_fmt = (AVPixelFormat)ip->format;
1139 convert_ctx = sws_getCachedContext(convert_ctx, ip->width, ip->height, pix_fmt,
1140 frame->get_w(), frame->get_h(), ofmt, SWS_POINT, NULL, NULL, NULL);
1141 if( !convert_ctx ) {
1142 fprintf(stderr, "FFVideoConvert::convert_picture_frame:"
1143 " sws_getCachedContext() failed\n");
1146 int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ip->height,
1147 ipic->data, ipic->linesize);
1149 ff_err(ret, "FFVideoConvert::convert_picture_frame: sws_scale() failed\n");
1155 int FFVideoConvert::convert_cmodel(VFrame *frame, AVFrame *ip)
1157 // try direct transfer
1158 if( !convert_picture_vframe(frame, ip) ) return 1;
1159 // use indirect transfer
1160 AVPixelFormat ifmt = (AVPixelFormat)ip->format;
1161 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
1163 for( int i = 0; i <desc->nb_components; ++i ) {
1164 int bits = desc->comp[i].depth;
1165 if( bits > max_bits ) max_bits = bits;
1167 int imodel = pix_fmt_to_color_model(ifmt);
1168 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1169 int cmodel = frame->get_color_model();
1170 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1171 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1172 imodel = cmodel_is_yuv ?
1173 (BC_CModels::has_alpha(cmodel) ?
1175 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1176 (BC_CModels::has_alpha(cmodel) ?
1177 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1178 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1180 VFrame vframe(ip->width, ip->height, imodel);
1181 if( convert_picture_vframe(&vframe, ip) ) return -1;
1182 frame->transfer_from(&vframe);
1186 int FFVideoConvert::transfer_cmodel(VFrame *frame, AVFrame *ifp)
1188 int ret = convert_cmodel(frame, ifp);
1190 const AVDictionary *src = ifp->metadata;
1191 AVDictionaryEntry *t = NULL;
1192 BC_Hash *hp = frame->get_params();
1194 while( (t=av_dict_get(src, "", t, AV_DICT_IGNORE_SUFFIX)) )
1195 hp->update(t->key, t->value);
1200 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op)
1202 AVFrame *opic = av_frame_alloc();
1203 int ret = convert_vframe_picture(frame, op, opic);
1204 av_frame_free(&opic);
1208 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op, AVFrame *opic)
1210 int cmodel = frame->get_color_model();
1211 AVPixelFormat ifmt = color_model_to_pix_fmt(cmodel);
1212 if( ifmt == AV_PIX_FMT_NB ) return -1;
1213 int size = av_image_fill_arrays(opic->data, opic->linesize,
1214 frame->get_data(), ifmt, frame->get_w(), frame->get_h(), 1);
1215 if( size < 0 ) return -1;
1217 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1218 int ysz = bpp * frame->get_w(), usz = ysz;
1228 // override av_image_fill_arrays() for planar types
1229 opic->data[0] = frame->get_y(); opic->linesize[0] = ysz;
1230 opic->data[1] = frame->get_u(); opic->linesize[1] = usz;
1231 opic->data[2] = frame->get_v(); opic->linesize[2] = usz;
1234 opic->data[0] = frame->get_data();
1235 opic->linesize[0] = frame->get_bytes_per_line();
1239 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1240 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(),
1241 ifmt, op->width, op->height, ofmt, SWS_POINT, NULL, NULL, NULL);
1242 if( !convert_ctx ) {
1243 fprintf(stderr, "FFVideoConvert::convert_frame_picture:"
1244 " sws_getCachedContext() failed\n");
1247 int ret = sws_scale(convert_ctx, opic->data, opic->linesize, 0, frame->get_h(),
1248 op->data, op->linesize);
1250 ff_err(ret, "FFVideoConvert::convert_frame_picture: sws_scale() failed\n");
1256 int FFVideoConvert::convert_pixfmt(VFrame *frame, AVFrame *op)
1258 // try direct transfer
1259 if( !convert_vframe_picture(frame, op) ) return 1;
1260 // use indirect transfer
1261 int cmodel = frame->get_color_model();
1262 int max_bits = BC_CModels::calculate_pixelsize(cmodel) * 8;
1263 max_bits /= BC_CModels::components(cmodel);
1264 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1265 int imodel = pix_fmt_to_color_model(ofmt);
1266 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1267 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1268 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1269 imodel = cmodel_is_yuv ?
1270 (BC_CModels::has_alpha(cmodel) ?
1272 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1273 (BC_CModels::has_alpha(cmodel) ?
1274 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1275 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1277 VFrame vframe(frame->get_w(), frame->get_h(), imodel);
1278 vframe.transfer_from(frame);
1279 if( !convert_vframe_picture(&vframe, op) ) return 1;
1283 int FFVideoConvert::transfer_pixfmt(VFrame *frame, AVFrame *ofp)
1285 int ret = convert_pixfmt(frame, ofp);
1287 BC_Hash *hp = frame->get_params();
1288 AVDictionary **dict = &ofp->metadata;
1289 //av_dict_free(dict);
1290 for( int i=0; i<hp->size(); ++i ) {
1291 char *key = hp->get_key(i), *val = hp->get_value(i);
1292 av_dict_set(dict, key, val, 0);
1298 void FFVideoStream::load_markers()
1300 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1301 if( !index_state || idx >= index_state->video_markers.size() ) return;
1302 FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
1305 IndexMarks *FFVideoStream::get_markers()
1307 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1308 if( !index_state || idx >= index_state->video_markers.size() ) return 0;
1309 return !index_state ? 0 : index_state->video_markers[idx];
1313 FFMPEG::FFMPEG(FileBase *file_base)
1316 this->file_base = file_base;
1317 memset(file_format,0,sizeof(file_format));
1318 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
1319 flow_lock = new Condition(1,"FFStream::flow_lock",0);
1322 decoding = encoding = 0;
1323 has_audio = has_video = 0;
1326 opt_video_filter = 0;
1327 opt_audio_filter = 0;
1328 char option_path[BCTEXTLEN];
1329 set_option_path(option_path, "%s", "ffmpeg.opts");
1330 read_options(option_path, opts);
1335 ff_lock("FFMPEG::~FFMPEG()");
1337 ffaudio.remove_all_objects();
1338 ffvideo.remove_all_objects();
1339 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1343 av_dict_free(&opts);
1344 delete [] opt_video_filter;
1345 delete [] opt_audio_filter;
1348 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1350 const int *p = codec->supported_samplerates;
1351 if( !p ) return sample_rate;
1353 if( *p == sample_rate ) return *p;
1359 static inline AVRational std_frame_rate(int i)
1361 static const int m1 = 1001*12, m2 = 1000*12;
1362 static const int freqs[] = {
1363 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1364 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
1366 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1367 return (AVRational) { freq, 1001*12 };
1370 AVRational FFMPEG::check_frame_rate(AVCodec *codec, double frame_rate)
1372 const AVRational *p = codec->supported_framerates;
1373 AVRational rate, best_rate = (AVRational) { 0, 0 };
1374 double max_err = 1.; int i = 0;
1375 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1376 double framerate = (double) rate.num / rate.den;
1377 double err = fabs(frame_rate/framerate - 1.);
1378 if( err >= max_err ) continue;
1382 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1385 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1388 double display_aspect = asset->width / (double)asset->height;
1389 double sample_aspect = display_aspect / asset->aspect_ratio;
1390 int width = 1000000, height = width * sample_aspect + 0.5;
1392 MWindow::create_aspect_ratio(w, h, width, height);
1393 return (AVRational){(int)w, (int)h};
1396 return (AVRational){1, 1};
1400 AVRational FFMPEG::to_time_base(int sample_rate)
1402 return (AVRational){1, sample_rate};
1405 int FFMPEG::get_fmt_score(AVSampleFormat dst_fmt, AVSampleFormat src_fmt)
1408 int dst_planar = av_sample_fmt_is_planar(dst_fmt);
1409 int src_planar = av_sample_fmt_is_planar(src_fmt);
1410 if( dst_planar != src_planar ) ++score;
1411 int dst_bytes = av_get_bytes_per_sample(dst_fmt);
1412 int src_bytes = av_get_bytes_per_sample(src_fmt);
1413 score += (src_bytes > dst_bytes ? 100 : -10) * (src_bytes - dst_bytes);
1414 int src_packed = av_get_packed_sample_fmt(src_fmt);
1415 int dst_packed = av_get_packed_sample_fmt(dst_fmt);
1416 if( dst_packed == AV_SAMPLE_FMT_S32 && src_packed == AV_SAMPLE_FMT_FLT ) score += 20;
1417 if( dst_packed == AV_SAMPLE_FMT_FLT && src_packed == AV_SAMPLE_FMT_S32 ) score += 2;
1421 AVSampleFormat FFMPEG::find_best_sample_fmt_of_list(
1422 const AVSampleFormat *sample_fmts, AVSampleFormat src_fmt)
1424 AVSampleFormat best = AV_SAMPLE_FMT_NONE;
1425 int best_score = get_fmt_score(best, src_fmt);
1426 for( int i=0; sample_fmts[i] >= 0; ++i ) {
1427 AVSampleFormat sample_fmt = sample_fmts[i];
1428 int score = get_fmt_score(sample_fmt, src_fmt);
1429 if( score >= best_score ) continue;
1430 best = sample_fmt; best_score = score;
1436 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
1438 char *ep = path + BCTEXTLEN-1;
1439 strncpy(path, File::get_cindat_path(), ep-path);
1440 strncat(path, "/ffmpeg/", ep-path);
1441 path += strlen(path);
1444 path += vsnprintf(path, ep-path, fmt, ap);
1449 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
1454 set_option_path(path, "%s/%s", type, spec);
1457 int FFMPEG::get_format(char *format, const char *path, const char *spec)
1459 char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
1460 get_option_path(option_path, path, spec);
1461 FILE *fp = fopen(option_path,"r");
1464 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1466 line[sizeof(line)-1] = 0;
1467 ret = scan_option_line(line, format, codec);
1473 int FFMPEG::get_codec(char *codec, const char *path, const char *spec)
1475 char option_path[BCTEXTLEN], line[BCTEXTLEN], format[BCTEXTLEN];
1476 get_option_path(option_path, path, spec);
1477 FILE *fp = fopen(option_path,"r");
1480 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1483 line[sizeof(line)-1] = 0;
1484 ret = scan_option_line(line, format, codec);
1487 char *vp = codec, *ep = vp+BCTEXTLEN-1;
1488 while( vp < ep && *vp && *vp != '|' ) ++vp;
1489 if( *vp == '|' ) --vp;
1490 while( vp > codec && (*vp==' ' || *vp=='\t') ) *vp-- = 0;
1495 int FFMPEG::get_file_format()
1497 char audio_muxer[BCSTRLEN], video_muxer[BCSTRLEN];
1498 char audio_format[BCSTRLEN], video_format[BCSTRLEN];
1499 audio_muxer[0] = audio_format[0] = 0;
1500 video_muxer[0] = video_format[0] = 0;
1501 Asset *asset = file_base->asset;
1502 int ret = asset ? 0 : 1;
1503 if( !ret && asset->audio_data ) {
1504 if( !(ret=get_format(audio_format, "audio", asset->acodec)) ) {
1505 if( get_format(audio_muxer, "format", audio_format) ) {
1506 strcpy(audio_muxer, audio_format);
1507 audio_format[0] = 0;
1511 if( !ret && asset->video_data ) {
1512 if( !(ret=get_format(video_format, "video", asset->vcodec)) ) {
1513 if( get_format(video_muxer, "format", video_format) ) {
1514 strcpy(video_muxer, video_format);
1515 video_format[0] = 0;
1519 if( !ret && !audio_muxer[0] && !video_muxer[0] )
1521 if( !ret && audio_muxer[0] && video_muxer[0] &&
1522 strcmp(audio_muxer, video_muxer) ) ret = -1;
1523 if( !ret && audio_format[0] && video_format[0] &&
1524 strcmp(audio_format, video_format) ) ret = -1;
1526 strcpy(file_format, !audio_format[0] && !video_format[0] ?
1527 (audio_muxer[0] ? audio_muxer : video_muxer) :
1528 (audio_format[0] ? audio_format : video_format));
1532 int FFMPEG::scan_option_line(const char *cp, char *tag, char *val)
1534 while( *cp == ' ' || *cp == '\t' ) ++cp;
1535 const char *bp = cp;
1536 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' && *cp != '\n' ) ++cp;
1538 if( !len || len > BCSTRLEN-1 ) return 1;
1539 while( bp < cp ) *tag++ = *bp++;
1541 while( *cp == ' ' || *cp == '\t' ) ++cp;
1542 if( *cp == '=' ) ++cp;
1543 while( *cp == ' ' || *cp == '\t' ) ++cp;
1545 while( *cp && *cp != '\n' ) ++cp;
1547 if( len > BCTEXTLEN-1 ) return 1;
1548 while( bp < cp ) *val++ = *bp++;
1553 int FFMPEG::can_render(const char *fformat, const char *type)
1556 char option_path[BCTEXTLEN];
1557 FFMPEG::set_option_path(option_path, type);
1558 fs.update(option_path);
1559 int total_files = fs.total_files();
1560 for( int i=0; i<total_files; ++i ) {
1561 const char *name = fs.get_entry(i)->get_name();
1562 const char *ext = strrchr(name,'.');
1563 if( !ext ) continue;
1564 if( !strcmp(fformat, ++ext) ) return 1;
1569 int FFMPEG::get_ff_option(const char *nm, const char *options, char *value)
1571 for( const char *cp=options; *cp!=0; ) {
1572 char line[BCTEXTLEN], *bp = line, *ep = bp+sizeof(line)-1;
1573 while( bp < ep && *cp && *cp!='\n' ) *bp++ = *cp++;
1576 if( !line[0] || line[0] == '#' || line[0] == ';' ) continue;
1577 char key[BCSTRLEN], val[BCTEXTLEN];
1578 if( FFMPEG::scan_option_line(line, key, val) ) continue;
1579 if( !strcmp(key, nm) ) {
1580 strncpy(value, val, BCSTRLEN);
1587 void FFMPEG::scan_audio_options(Asset *asset, EDL *edl)
1589 char cin_sample_fmt[BCSTRLEN];
1590 int cin_fmt = AV_SAMPLE_FMT_NONE;
1591 const char *options = asset->ff_audio_options;
1592 if( !get_ff_option("cin_sample_fmt", options, cin_sample_fmt) )
1593 cin_fmt = (int)av_get_sample_fmt(cin_sample_fmt);
1595 char audio_codec[BCSTRLEN]; audio_codec[0] = 0;
1596 AVCodec *av_codec = !FFMPEG::get_codec(audio_codec, "audio", asset->acodec) ?
1597 avcodec_find_encoder_by_name(audio_codec) : 0;
1598 if( av_codec && av_codec->sample_fmts )
1599 cin_fmt = find_best_sample_fmt_of_list(av_codec->sample_fmts, AV_SAMPLE_FMT_FLT);
1601 if( cin_fmt < 0 ) cin_fmt = AV_SAMPLE_FMT_S16;
1602 const char *name = av_get_sample_fmt_name((AVSampleFormat)cin_fmt);
1603 if( !name ) name = _("None");
1604 strcpy(asset->ff_sample_format, name);
1606 char value[BCSTRLEN];
1607 if( !get_ff_option("cin_bitrate", options, value) )
1608 asset->ff_audio_bitrate = atoi(value);
1609 if( !get_ff_option("cin_quality", options, value) )
1610 asset->ff_audio_quality = atoi(value);
1613 void FFMPEG::load_audio_options(Asset *asset, EDL *edl)
1615 char options_path[BCTEXTLEN];
1616 set_option_path(options_path, "audio/%s", asset->acodec);
1617 if( !load_options(options_path,
1618 asset->ff_audio_options,
1619 sizeof(asset->ff_audio_options)) )
1620 scan_audio_options(asset, edl);
1623 void FFMPEG::scan_video_options(Asset *asset, EDL *edl)
1625 char cin_pix_fmt[BCSTRLEN];
1626 int cin_fmt = AV_PIX_FMT_NONE;
1627 const char *options = asset->ff_video_options;
1628 if( !get_ff_option("cin_pix_fmt", options, cin_pix_fmt) )
1629 cin_fmt = (int)av_get_pix_fmt(cin_pix_fmt);
1631 char video_codec[BCSTRLEN]; video_codec[0] = 0;
1632 AVCodec *av_codec = !get_codec(video_codec, "video", asset->vcodec) ?
1633 avcodec_find_encoder_by_name(video_codec) : 0;
1634 if( av_codec && av_codec->pix_fmts ) {
1635 if( 0 && edl ) { // frequently picks a bad answer
1636 int color_model = edl->session->color_model;
1637 int max_bits = BC_CModels::calculate_pixelsize(color_model) * 8;
1638 max_bits /= BC_CModels::components(color_model);
1639 cin_fmt = avcodec_find_best_pix_fmt_of_list(av_codec->pix_fmts,
1640 (BC_CModels::is_yuv(color_model) ?
1641 (max_bits > 8 ? AV_PIX_FMT_AYUV64LE : AV_PIX_FMT_YUV444P) :
1642 (max_bits > 8 ? AV_PIX_FMT_RGB48LE : AV_PIX_FMT_RGB24)), 0, 0);
1645 cin_fmt = av_codec->pix_fmts[0];
1648 if( cin_fmt < 0 ) cin_fmt = AV_PIX_FMT_YUV420P;
1649 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get((AVPixelFormat)cin_fmt);
1650 const char *name = desc ? desc->name : _("None");
1651 strcpy(asset->ff_pixel_format, name);
1653 char value[BCSTRLEN];
1654 if( !get_ff_option("cin_bitrate", options, value) )
1655 asset->ff_video_bitrate = atoi(value);
1656 if( !get_ff_option("cin_quality", options, value) )
1657 asset->ff_video_quality = atoi(value);
1660 void FFMPEG::load_video_options(Asset *asset, EDL *edl)
1662 char options_path[BCTEXTLEN];
1663 set_option_path(options_path, "video/%s", asset->vcodec);
1664 if( !load_options(options_path,
1665 asset->ff_video_options,
1666 sizeof(asset->ff_video_options)) )
1667 scan_video_options(asset, edl);
1670 int FFMPEG::load_defaults(const char *path, const char *type,
1671 char *codec, char *codec_options, int len)
1673 char default_file[BCTEXTLEN];
1674 set_option_path(default_file, "%s/%s.dfl", path, type);
1675 FILE *fp = fopen(default_file,"r");
1677 fgets(codec, BCSTRLEN, fp);
1679 while( *cp && *cp!='\n' ) ++cp;
1681 while( len > 0 && fgets(codec_options, len, fp) ) {
1682 int n = strlen(codec_options);
1683 codec_options += n; len -= n;
1686 set_option_path(default_file, "%s/%s", path, codec);
1687 return load_options(default_file, codec_options, len);
1690 void FFMPEG::set_asset_format(Asset *asset, EDL *edl, const char *text)
1692 if( asset->format != FILE_FFMPEG ) return;
1693 if( text != asset->fformat )
1694 strcpy(asset->fformat, text);
1695 if( asset->audio_data && !asset->ff_audio_options[0] ) {
1696 if( !load_defaults("audio", text, asset->acodec,
1697 asset->ff_audio_options, sizeof(asset->ff_audio_options)) )
1698 scan_audio_options(asset, edl);
1700 asset->audio_data = 0;
1702 if( asset->video_data && !asset->ff_video_options[0] ) {
1703 if( !load_defaults("video", text, asset->vcodec,
1704 asset->ff_video_options, sizeof(asset->ff_video_options)) )
1705 scan_video_options(asset, edl);
1707 asset->video_data = 0;
1711 int FFMPEG::get_encoder(const char *options,
1712 char *format, char *codec, char *bsfilter)
1714 FILE *fp = fopen(options,"r");
1716 eprintf(_("options open failed %s\n"),options);
1719 char line[BCTEXTLEN];
1720 if( !fgets(line, sizeof(line), fp) ||
1721 scan_encoder(line, format, codec, bsfilter) )
1722 eprintf(_("format/codec not found %s\n"), options);
1727 int FFMPEG::scan_encoder(const char *line,
1728 char *format, char *codec, char *bsfilter)
1730 format[0] = codec[0] = bsfilter[0] = 0;
1731 if( scan_option_line(line, format, codec) ) return 1;
1733 while( *cp && *cp != '|' ) ++cp;
1734 if( !*cp ) return 0;
1736 do { *bp-- = 0; } while( bp>=codec && (*bp==' ' || *bp == '\t' ) );
1737 while( *++cp && (*cp==' ' || *cp == '\t') );
1739 for( int i=BCTEXTLEN; --i>0 && *cp; ) *bp++ = *cp++;
1744 int FFMPEG::read_options(const char *options, AVDictionary *&opts, int skip)
1746 FILE *fp = fopen(options,"r");
1749 while( !ret && --skip >= 0 ) {
1751 while( ch >= 0 && ch != '\n' ) ch = getc(fp);
1752 if( ch < 0 ) ret = 1;
1755 ret = read_options(fp, options, opts);
1760 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
1762 FILE *fp = fmemopen((void *)options,strlen(options),"r");
1764 int ret = read_options(fp, options, opts);
1766 AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
1767 if( tag ) st->id = strtol(tag->value,0,0);
1771 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
1773 int ret = 0, no = 0;
1774 char line[BCTEXTLEN];
1775 while( !ret && fgets(line, sizeof(line), fp) ) {
1776 line[sizeof(line)-1] = 0;
1777 if( line[0] == '#' ) continue;
1778 if( line[0] == '\n' ) continue;
1779 char key[BCSTRLEN], val[BCTEXTLEN];
1780 if( scan_option_line(line, key, val) ) {
1781 eprintf(_("err reading %s: line %d\n"), options, no);
1785 if( !strcmp(key, "duration") )
1786 opt_duration = strtod(val, 0);
1787 else if( !strcmp(key, "video_filter") )
1788 opt_video_filter = cstrdup(val);
1789 else if( !strcmp(key, "audio_filter") )
1790 opt_audio_filter = cstrdup(val);
1791 else if( !strcmp(key, "loglevel") )
1794 av_dict_set(&opts, key, val, 0);
1800 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
1802 char option_path[BCTEXTLEN];
1803 set_option_path(option_path, "%s", options);
1804 return read_options(option_path, opts);
1807 int FFMPEG::load_options(const char *path, char *bfr, int len)
1810 FILE *fp = fopen(path, "r");
1812 fgets(bfr, len, fp); // skip hdr
1813 len = fread(bfr, 1, len-1, fp);
1814 if( len < 0 ) len = 0;
1820 void FFMPEG::set_loglevel(const char *ap)
1822 if( !ap || !*ap ) return;
1827 { "quiet" , AV_LOG_QUIET },
1828 { "panic" , AV_LOG_PANIC },
1829 { "fatal" , AV_LOG_FATAL },
1830 { "error" , AV_LOG_ERROR },
1831 { "warning", AV_LOG_WARNING },
1832 { "info" , AV_LOG_INFO },
1833 { "verbose", AV_LOG_VERBOSE },
1834 { "debug" , AV_LOG_DEBUG },
1836 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
1837 if( !strcmp(log_levels[i].name, ap) ) {
1838 av_log_set_level(log_levels[i].level);
1842 av_log_set_level(atoi(ap));
1845 double FFMPEG::to_secs(int64_t time, AVRational time_base)
1847 double base_time = time == AV_NOPTS_VALUE ? 0 :
1848 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
1849 return base_time / AV_TIME_BASE;
1852 int FFMPEG::info(char *text, int len)
1854 if( len <= 0 ) return 0;
1856 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
1858 report("format: %s\n",fmt_ctx->iformat->name);
1859 if( ffvideo.size() > 0 )
1860 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
1861 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
1862 FFVideoStream *vid = ffvideo[vidx];
1863 AVStream *st = vid->st;
1864 AVCodecID codec_id = st->codecpar->codec_id;
1865 report(_("vid%d (%d), id 0x%06x:\n"), vid->idx, vid->fidx, codec_id);
1866 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
1867 report(" video%d %s", vidx+1, desc ? desc->name : " (unkn)");
1868 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
1869 AVPixelFormat pix_fmt = (AVPixelFormat)st->codecpar->format;
1870 const char *pfn = av_get_pix_fmt_name(pix_fmt);
1871 report(" pix %s\n", pfn ? pfn : "(unkn)");
1872 double secs = to_secs(st->duration, st->time_base);
1873 int64_t length = secs * vid->frame_rate + 0.5;
1874 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
1875 int64_t nudge = ofs * vid->frame_rate;
1876 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1877 report(" %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
1878 int hrs = secs/3600; secs -= hrs*3600;
1879 int mins = secs/60; secs -= mins*60;
1880 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1882 if( ffaudio.size() > 0 )
1883 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
1884 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
1885 FFAudioStream *aud = ffaudio[aidx];
1886 AVStream *st = aud->st;
1887 AVCodecID codec_id = st->codecpar->codec_id;
1888 report(_("aud%d (%d), id 0x%06x:\n"), aud->idx, aud->fidx, codec_id);
1889 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
1890 int nch = aud->channels, ch0 = aud->channel0+1;
1891 report(" audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
1892 AVSampleFormat sample_fmt = (AVSampleFormat)st->codecpar->format;
1893 const char *fmt = av_get_sample_fmt_name(sample_fmt);
1894 report(" %s %d", fmt, aud->sample_rate);
1895 int sample_bits = av_get_bits_per_sample(codec_id);
1896 report(" %dbits\n", sample_bits);
1897 double secs = to_secs(st->duration, st->time_base);
1898 int64_t length = secs * aud->sample_rate + 0.5;
1899 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
1900 int64_t nudge = ofs * aud->sample_rate;
1901 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1902 report(" %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
1903 int hrs = secs/3600; secs -= hrs*3600;
1904 int mins = secs/60; secs -= mins*60;
1905 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1907 if( fmt_ctx->nb_programs > 0 )
1908 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
1909 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
1910 report("program %d", i+1);
1911 AVProgram *pgrm = fmt_ctx->programs[i];
1912 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1913 int idx = pgrm->stream_index[j];
1914 int vidx = ffvideo.size();
1915 while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
1917 report(", vid%d", vidx);
1920 int aidx = ffaudio.size();
1921 while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
1923 report(", aud%d", aidx);
1926 report(", (%d)", pgrm->stream_index[j]);
1931 AVDictionaryEntry *tag = 0;
1932 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
1933 report("%s=%s\n", tag->key, tag->value);
1942 int FFMPEG::init_decoder(const char *filename)
1944 ff_lock("FFMPEG::init_decoder");
1946 char file_opts[BCTEXTLEN];
1947 char *bp = strrchr(strcpy(file_opts, filename), '/');
1948 char *sp = strrchr(!bp ? file_opts : bp, '.');
1949 if( !sp ) sp = bp + strlen(bp);
1951 AVInputFormat *ifmt = 0;
1953 strcpy(sp, ".opts");
1954 fp = fopen(file_opts, "r");
1957 read_options(fp, file_opts, opts);
1959 AVDictionaryEntry *tag;
1960 if( (tag=av_dict_get(opts, "format", NULL, 0)) != 0 ) {
1961 ifmt = av_find_input_format(tag->value);
1965 load_options("decode.opts", opts);
1966 AVDictionary *fopts = 0;
1967 av_dict_copy(&fopts, opts, 0);
1968 int ret = avformat_open_input(&fmt_ctx, filename, ifmt, &fopts);
1969 av_dict_free(&fopts);
1971 ret = avformat_find_stream_info(fmt_ctx, NULL);
1976 return !ret ? 0 : 1;
1979 int FFMPEG::open_decoder()
1982 if( stat(fmt_ctx->url, &st) < 0 ) {
1983 eprintf(_("can't stat file: %s\n"), fmt_ctx->url);
1987 int64_t file_bits = 8 * st.st_size;
1988 if( !fmt_ctx->bit_rate && opt_duration > 0 )
1989 fmt_ctx->bit_rate = file_bits / opt_duration;
1992 if( fmt_ctx->bit_rate > 0 ) {
1993 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1994 AVStream *st = fmt_ctx->streams[i];
1995 if( st->duration != AV_NOPTS_VALUE ) continue;
1996 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
1997 st->duration = av_rescale(file_bits, st->time_base.den,
1998 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
2002 static int notified = 0;
2003 if( !notified && estimated ) {
2005 printf("FFMPEG::open_decoder: some stream times estimated\n");
2008 ff_lock("FFMPEG::open_decoder");
2009 int ret = 0, bad_time = 0;
2010 for( int i=0; !ret && i<(int)fmt_ctx->nb_streams; ++i ) {
2011 AVStream *st = fmt_ctx->streams[i];
2012 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
2013 AVCodecParameters *avpar = st->codecpar;
2014 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avpar->codec_id);
2015 if( !codec_desc ) continue;
2016 switch( avpar->codec_type ) {
2017 case AVMEDIA_TYPE_VIDEO: {
2018 if( avpar->width < 1 ) continue;
2019 if( avpar->height < 1 ) continue;
2020 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
2021 if( framerate.num < 1 ) continue;
2023 int vidx = ffvideo.size();
2024 FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
2025 vstrm_index.append(ffidx(vidx, 0));
2026 ffvideo.append(vid);
2027 vid->width = avpar->width;
2028 vid->height = avpar->height;
2029 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
2030 double secs = to_secs(st->duration, st->time_base);
2031 vid->length = secs * vid->frame_rate;
2032 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
2033 vid->nudge = st->start_time;
2035 if( opt_video_filter )
2036 ret = vid->create_filter(opt_video_filter, avpar);
2038 case AVMEDIA_TYPE_AUDIO: {
2039 if( avpar->channels < 1 ) continue;
2040 if( avpar->sample_rate < 1 ) continue;
2042 int aidx = ffaudio.size();
2043 FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
2044 ffaudio.append(aud);
2045 aud->channel0 = astrm_index.size();
2046 aud->channels = avpar->channels;
2047 for( int ch=0; ch<aud->channels; ++ch )
2048 astrm_index.append(ffidx(aidx, ch));
2049 aud->sample_rate = avpar->sample_rate;
2050 double secs = to_secs(st->duration, st->time_base);
2051 aud->length = secs * aud->sample_rate;
2052 aud->init_swr(aud->channels, avpar->format, aud->sample_rate);
2053 aud->nudge = st->start_time;
2055 if( opt_audio_filter )
2056 ret = aud->create_filter(opt_audio_filter, avpar);
2062 printf("FFMPEG::open_decoder: some stream have bad times\n");
2064 return ret < 0 ? -1 : 0;
2068 int FFMPEG::init_encoder(const char *filename)
2070 // try access first for named pipes
2071 int ret = access(filename, W_OK);
2073 int fd = ::open(filename,O_WRONLY);
2074 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
2075 if( fd >= 0 ) { close(fd); ret = 0; }
2078 eprintf(_("bad file path: %s\n"), filename);
2081 ret = get_file_format();
2083 eprintf(_("bad file format: %s\n"), filename);
2087 eprintf(_("mismatch audio/video file format: %s\n"), filename);
2090 ff_lock("FFMPEG::init_encoder");
2092 char format[BCSTRLEN];
2093 if( get_format(format, "format", file_format) )
2094 strcpy(format, file_format);
2095 avformat_alloc_output_context2(&fmt_ctx, 0, format, filename);
2097 eprintf(_("failed: %s\n"), filename);
2102 load_options("encode.opts", opts);
2108 int FFMPEG::open_encoder(const char *type, const char *spec)
2111 Asset *asset = file_base->asset;
2112 char *filename = asset->path;
2113 AVDictionary *sopts = 0;
2114 av_dict_copy(&sopts, opts, 0);
2115 char option_path[BCTEXTLEN];
2116 set_option_path(option_path, "%s/%s.opts", type, type);
2117 read_options(option_path, sopts);
2118 get_option_path(option_path, type, spec);
2119 char format_name[BCSTRLEN], codec_name[BCTEXTLEN], bsfilter[BCTEXTLEN];
2120 if( get_encoder(option_path, format_name, codec_name, bsfilter) ) {
2121 eprintf(_("get_encoder failed %s:%s\n"), option_path, filename);
2126 if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
2128 else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
2129 else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
2132 ff_lock("FFMPEG::open_encoder");
2135 AVCodecContext *ctx = 0;
2137 const AVCodecDescriptor *codec_desc = 0;
2138 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
2140 eprintf(_("cant find codec %s:%s\n"), codec_name, filename);
2144 codec_desc = avcodec_descriptor_get(codec->id);
2146 eprintf(_("unknown codec %s:%s\n"), codec_name, filename);
2151 st = avformat_new_stream(fmt_ctx, 0);
2153 eprintf(_("cant create stream %s:%s\n"), codec_name, filename);
2158 switch( codec_desc->type ) {
2159 case AVMEDIA_TYPE_AUDIO: {
2161 eprintf(_("duplicate audio %s:%s\n"), codec_name, filename);
2165 if( scan_options(asset->ff_audio_options, sopts, st) ) {
2166 eprintf(_("bad audio options %s:%s\n"), codec_name, filename);
2171 ctx = avcodec_alloc_context3(codec);
2172 if( asset->ff_audio_bitrate > 0 ) {
2173 ctx->bit_rate = asset->ff_audio_bitrate;
2175 sprintf(arg, "%d", asset->ff_audio_bitrate);
2176 av_dict_set(&sopts, "b", arg, 0);
2178 else if( asset->ff_audio_quality >= 0 ) {
2179 ctx->global_quality = asset->ff_audio_quality * FF_QP2LAMBDA;
2180 ctx->qmin = ctx->qmax = asset->ff_audio_quality;
2181 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2182 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2183 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2185 av_dict_set(&sopts, "flags", "+qscale", 0);
2186 sprintf(arg, "%d", asset->ff_audio_quality);
2187 av_dict_set(&sopts, "qscale", arg, 0);
2188 sprintf(arg, "%d", ctx->global_quality);
2189 av_dict_set(&sopts, "global_quality", arg, 0);
2191 int aidx = ffaudio.size();
2192 int fidx = aidx + ffvideo.size();
2193 FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
2194 aud->avctx = ctx; ffaudio.append(aud); fst = aud;
2195 aud->sample_rate = asset->sample_rate;
2196 ctx->channels = aud->channels = asset->channels;
2197 for( int ch=0; ch<aud->channels; ++ch )
2198 astrm_index.append(ffidx(aidx, ch));
2199 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
2200 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
2201 if( !ctx->sample_rate ) {
2202 eprintf(_("check_sample_rate failed %s\n"), filename);
2206 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
2207 AVSampleFormat sample_fmt = av_get_sample_fmt(asset->ff_sample_format);
2208 if( sample_fmt == AV_SAMPLE_FMT_NONE )
2209 sample_fmt = codec->sample_fmts ? codec->sample_fmts[0] : AV_SAMPLE_FMT_S16;
2210 ctx->sample_fmt = sample_fmt;
2211 uint64_t layout = av_get_default_channel_layout(ctx->channels);
2212 aud->resample_context = swr_alloc_set_opts(NULL,
2213 layout, ctx->sample_fmt, aud->sample_rate,
2214 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
2216 swr_init(aud->resample_context);
2219 case AVMEDIA_TYPE_VIDEO: {
2221 eprintf(_("duplicate video %s:%s\n"), codec_name, filename);
2225 if( scan_options(asset->ff_video_options, sopts, st) ) {
2226 eprintf(_("bad video options %s:%s\n"), codec_name, filename);
2231 ctx = avcodec_alloc_context3(codec);
2232 if( asset->ff_video_bitrate > 0 ) {
2233 ctx->bit_rate = asset->ff_video_bitrate;
2235 sprintf(arg, "%d", asset->ff_video_bitrate);
2236 av_dict_set(&sopts, "b", arg, 0);
2238 else if( asset->ff_video_quality >= 0 ) {
2239 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
2240 ctx->qmin = ctx->qmax = asset->ff_video_quality;
2241 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2242 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2243 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2245 av_dict_set(&sopts, "flags", "+qscale", 0);
2246 sprintf(arg, "%d", asset->ff_video_quality);
2247 av_dict_set(&sopts, "qscale", arg, 0);
2248 sprintf(arg, "%d", ctx->global_quality);
2249 av_dict_set(&sopts, "global_quality", arg, 0);
2251 int vidx = ffvideo.size();
2252 int fidx = vidx + ffaudio.size();
2253 FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
2254 vstrm_index.append(ffidx(vidx, 0));
2255 vid->avctx = ctx; ffvideo.append(vid); fst = vid;
2256 vid->width = asset->width;
2257 vid->height = asset->height;
2258 vid->frame_rate = asset->frame_rate;
2260 AVPixelFormat pix_fmt = av_get_pix_fmt(asset->ff_pixel_format);
2261 if( pix_fmt == AV_PIX_FMT_NONE )
2262 pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
2263 ctx->pix_fmt = pix_fmt;
2264 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
2265 int mask_w = (1<<desc->log2_chroma_w)-1;
2266 ctx->width = (vid->width+mask_w) & ~mask_w;
2267 int mask_h = (1<<desc->log2_chroma_h)-1;
2268 ctx->height = (vid->height+mask_h) & ~mask_h;
2269 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
2270 AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
2271 if( !frame_rate.num || !frame_rate.den ) {
2272 eprintf(_("check_frame_rate failed %s\n"), filename);
2276 av_reduce(&frame_rate.num, &frame_rate.den,
2277 frame_rate.num, frame_rate.den, INT_MAX);
2278 ctx->framerate = (AVRational) { frame_rate.num, frame_rate.den };
2279 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
2280 st->avg_frame_rate = frame_rate;
2281 st->time_base = ctx->time_base;
2283 vid->interlaced = asset->interlace_mode == ILACE_MODE_TOP_FIRST ||
2284 asset->interlace_mode == ILACE_MODE_BOTTOM_FIRST ? 1 : 0;
2285 vid->top_field_first = asset->interlace_mode == ILACE_MODE_TOP_FIRST ? 1 : 0;
2288 eprintf(_("not audio/video, %s:%s\n"), codec_name, filename);
2293 AVDictionaryEntry *tag;
2294 if( (tag=av_dict_get(sopts, "cin_stats_filename", NULL, 0)) != 0 ) {
2295 char suffix[BCSTRLEN]; sprintf(suffix,"-%d.log",fst->fidx);
2296 fst->stats_filename = cstrcat(2, tag->value, suffix);
2298 if( (tag=av_dict_get(sopts, "flags", NULL, 0)) != 0 ) {
2299 int pass = fst->pass;
2300 char *cp = tag->value;
2302 int ch = *cp++, pfx = ch=='-' ? -1 : ch=='+' ? 1 : 0;
2303 if( !isalnum(!pfx ? ch : (ch=*cp++)) ) continue;
2304 char id[BCSTRLEN], *bp = id, *ep = bp+sizeof(id)-1;
2305 for( *bp++=ch; isalnum(ch=*cp); ++cp )
2306 if( bp < ep ) *bp++ = ch;
2308 if( !strcmp(id, "pass1") ) {
2309 pass = pfx<0 ? (pass&~1) : pfx>0 ? (pass|1) : 1;
2311 else if( !strcmp(id, "pass2") ) {
2312 pass = pfx<0 ? (pass&~2) : pfx>0 ? (pass|2) : 2;
2315 if( (fst->pass=pass) ) {
2316 if( pass & 1 ) ctx->flags |= AV_CODEC_FLAG_PASS1;
2317 if( pass & 2 ) ctx->flags |= AV_CODEC_FLAG_PASS2;
2323 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
2324 ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
2325 if( fst->stats_filename && (ret=fst->init_stats_file()) )
2326 eprintf(_("error: stats file = %s\n"), fst->stats_filename);
2329 av_dict_set(&sopts, "cin_bitrate", 0, 0);
2330 av_dict_set(&sopts, "cin_quality", 0, 0);
2332 if( !av_dict_get(sopts, "threads", NULL, 0) )
2333 ctx->thread_count = ff_cpus();
2334 ret = avcodec_open2(ctx, codec, &sopts);
2336 ret = avcodec_parameters_from_context(st->codecpar, ctx);
2338 fprintf(stderr, "Could not copy the stream parameters\n");
2341 _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
2342 ret = avcodec_copy_context(st->codec, ctx);
2343 _Pragma("GCC diagnostic warning \"-Wdeprecated-declarations\"")
2345 fprintf(stderr, "Could not copy the stream context\n");
2348 ff_err(ret,"FFMPEG::open_encoder");
2349 eprintf(_("open failed %s:%s\n"), codec_name, filename);
2355 if( !ret && fst && bsfilter[0] ) {
2356 ret = av_bsf_list_parse_str(bsfilter, &fst->bsfc);
2358 ff_err(ret,"FFMPEG::open_encoder");
2359 eprintf(_("bitstream filter failed %s:\n%s\n"), filename, bsfilter);
2370 av_dict_free(&sopts);
2374 int FFMPEG::close_encoder()
2377 if( encoding > 0 ) {
2378 av_write_trailer(fmt_ctx);
2379 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
2380 avio_closep(&fmt_ctx->pb);
2386 int FFMPEG::decode_activate()
2388 if( decoding < 0 ) {
2390 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
2391 ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
2392 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
2393 ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
2394 // set nudges for each program stream set
2395 const int64_t min_nudge = INT64_MIN+1;
2396 int npgrms = fmt_ctx->nb_programs;
2397 for( int i=0; i<npgrms; ++i ) {
2398 AVProgram *pgrm = fmt_ctx->programs[i];
2399 // first start time video stream
2400 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2401 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2402 int fidx = pgrm->stream_index[j];
2403 AVStream *st = fmt_ctx->streams[fidx];
2404 AVCodecParameters *avpar = st->codecpar;
2405 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2406 if( st->start_time == AV_NOPTS_VALUE ) continue;
2407 if( vstart_time < st->start_time )
2408 vstart_time = st->start_time;
2411 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2412 if( st->start_time == AV_NOPTS_VALUE ) continue;
2413 if( astart_time < st->start_time )
2414 astart_time = st->start_time;
2418 //since frame rate is much more grainy than sample rate, it is better to
2419 // align using video, so that total absolute error is minimized.
2420 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2421 astart_time > min_nudge ? astart_time : AV_NOPTS_VALUE;
2422 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2423 int fidx = pgrm->stream_index[j];
2424 AVStream *st = fmt_ctx->streams[fidx];
2425 AVCodecParameters *avpar = st->codecpar;
2426 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2427 for( int k=0; k<ffvideo.size(); ++k ) {
2428 if( ffvideo[k]->fidx != fidx ) continue;
2429 ffvideo[k]->nudge = nudge;
2433 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2434 for( int k=0; k<ffaudio.size(); ++k ) {
2435 if( ffaudio[k]->fidx != fidx ) continue;
2436 ffaudio[k]->nudge = nudge;
2442 // set nudges for any streams not yet set
2443 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2444 int nstreams = fmt_ctx->nb_streams;
2445 for( int i=0; i<nstreams; ++i ) {
2446 AVStream *st = fmt_ctx->streams[i];
2447 AVCodecParameters *avpar = st->codecpar;
2448 switch( avpar->codec_type ) {
2449 case AVMEDIA_TYPE_VIDEO: {
2450 if( st->start_time == AV_NOPTS_VALUE ) continue;
2451 int vidx = ffvideo.size();
2452 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
2453 if( vidx < 0 ) continue;
2454 if( ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
2455 if( vstart_time < st->start_time )
2456 vstart_time = st->start_time;
2458 case AVMEDIA_TYPE_AUDIO: {
2459 if( st->start_time == AV_NOPTS_VALUE ) continue;
2460 int aidx = ffaudio.size();
2461 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
2462 if( aidx < 0 ) continue;
2463 if( ffaudio[aidx]->frame_sz < avpar->frame_size )
2464 ffaudio[aidx]->frame_sz = avpar->frame_size;
2465 if( ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
2466 if( astart_time < st->start_time )
2467 astart_time = st->start_time;
2472 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2473 astart_time > min_nudge ? astart_time : 0;
2474 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
2475 if( ffvideo[vidx]->nudge == AV_NOPTS_VALUE )
2476 ffvideo[vidx]->nudge = nudge;
2478 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2479 if( ffaudio[aidx]->nudge == AV_NOPTS_VALUE )
2480 ffaudio[aidx]->nudge = nudge;
2487 int FFMPEG::encode_activate()
2490 if( encoding < 0 ) {
2492 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
2493 (ret=avio_open(&fmt_ctx->pb, fmt_ctx->url, AVIO_FLAG_WRITE)) < 0 ) {
2494 ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
2500 AVProgram *prog = av_new_program(fmt_ctx, prog_id);
2501 for( int i=0; i< ffvideo.size(); ++i )
2502 av_program_add_stream_index(fmt_ctx, prog_id, ffvideo[i]->fidx);
2503 for( int i=0; i< ffaudio.size(); ++i )
2504 av_program_add_stream_index(fmt_ctx, prog_id, ffaudio[i]->fidx);
2505 int pi = fmt_ctx->nb_programs;
2506 while( --pi >= 0 && fmt_ctx->programs[pi]->id != prog_id );
2507 AVDictionary **meta = &prog->metadata;
2508 av_dict_set(meta, "service_provider", "cin5", 0);
2509 const char *path = fmt_ctx->url, *bp = strrchr(path,'/');
2510 if( bp ) path = bp + 1;
2511 av_dict_set(meta, "title", path, 0);
2513 if( ffaudio.size() ) {
2514 const char *ep = getenv("CIN_AUDIO_LANG"), *lp = 0;
2515 if( !ep && (lp=getenv("LANG")) ) { // some are guesses
2516 static struct { const char lc[3], lng[4]; } lcode[] = {
2517 { "en", "eng" }, { "de", "ger" }, { "es", "spa" },
2518 { "eu", "bas" }, { "fr", "fre" }, { "el", "gre" },
2519 { "hi", "hin" }, { "it", "ita" }, { "ja", "jap" },
2520 { "ko", "kor" }, { "du", "dut" }, { "pl", "pol" },
2521 { "pt", "por" }, { "ru", "rus" }, { "sl", "slv" },
2522 { "uk", "ukr" }, { "vi", "vie" }, { "zh", "chi" },
2524 for( int i=sizeof(lcode)/sizeof(lcode[0]); --i>=0 && !ep; )
2525 if( !strncmp(lcode[i].lc,lp,2) ) ep = lcode[i].lng;
2527 if( !ep ) ep = "und";
2529 strncpy(lang,ep,3); lang[3] = 0;
2530 AVStream *st = ffaudio[0]->st;
2531 av_dict_set(&st->metadata,"language",lang,0);
2534 AVDictionary *fopts = 0;
2535 char option_path[BCTEXTLEN];
2536 set_option_path(option_path, "format/%s", file_format);
2537 read_options(option_path, fopts, 1);
2538 ret = avformat_write_header(fmt_ctx, &fopts);
2540 ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
2544 av_dict_free(&fopts);
2551 int FFMPEG::audio_seek(int stream, int64_t pos)
2553 int aidx = astrm_index[stream].st_idx;
2554 FFAudioStream *aud = ffaudio[aidx];
2555 aud->audio_seek(pos);
2559 int FFMPEG::video_seek(int stream, int64_t pos)
2561 int vidx = vstrm_index[stream].st_idx;
2562 FFVideoStream *vid = ffvideo[vidx];
2563 vid->video_seek(pos);
2568 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
2570 if( !has_audio || chn >= astrm_index.size() ) return -1;
2571 int aidx = astrm_index[chn].st_idx;
2572 FFAudioStream *aud = ffaudio[aidx];
2573 if( aud->load(pos, len) < len ) return -1;
2574 int ch = astrm_index[chn].st_ch;
2575 int ret = aud->read(samples,len,ch);
2579 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
2581 if( !has_video || layer >= vstrm_index.size() ) return -1;
2582 int vidx = vstrm_index[layer].st_idx;
2583 FFVideoStream *vid = ffvideo[vidx];
2584 return vid->load(vframe, pos);
2588 int FFMPEG::encode(int stream, double **samples, int len)
2590 FFAudioStream *aud = ffaudio[stream];
2591 return aud->encode(samples, len);
2595 int FFMPEG::encode(int stream, VFrame *frame)
2597 FFVideoStream *vid = ffvideo[stream];
2598 return vid->encode(frame);
2601 void FFMPEG::start_muxer()
2609 void FFMPEG::stop_muxer()
2618 void FFMPEG::flow_off()
2621 flow_lock->lock("FFMPEG::flow_off");
2625 void FFMPEG::flow_on()
2629 flow_lock->unlock();
2632 void FFMPEG::flow_ctl()
2635 flow_lock->lock("FFMPEG::flow_ctl");
2636 flow_lock->unlock();
2640 int FFMPEG::mux_audio(FFrame *frm)
2642 FFStream *fst = frm->fst;
2643 AVCodecContext *ctx = fst->avctx;
2644 AVFrame *frame = *frm;
2645 AVRational tick_rate = {1, ctx->sample_rate};
2646 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
2647 int ret = fst->encode_frame(frame);
2649 ff_err(ret, "FFMPEG::mux_audio");
2650 return ret >= 0 ? 0 : 1;
2653 int FFMPEG::mux_video(FFrame *frm)
2655 FFStream *fst = frm->fst;
2656 AVFrame *frame = *frm;
2657 frame->pts = frm->position;
2658 int ret = fst->encode_frame(frame);
2660 ff_err(ret, "FFMPEG::mux_video");
2661 return ret >= 0 ? 0 : 1;
2667 double atm = -1, vtm = -1;
2668 FFrame *afrm = 0, *vfrm = 0;
2670 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
2671 FFStream *fst = ffaudio[i];
2672 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
2673 FFrame *frm = fst->frms.first;
2674 if( !frm ) { if( !done ) return; continue; }
2675 double tm = to_secs(frm->position, fst->avctx->time_base);
2676 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
2678 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
2679 FFStream *fst = ffvideo[i];
2680 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
2681 FFrame *frm = fst->frms.first;
2682 if( !frm ) { if( !done ) return; continue; }
2683 double tm = to_secs(frm->position, fst->avctx->time_base);
2684 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
2686 if( !demand ) flow_off();
2687 if( !afrm && !vfrm ) break;
2688 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
2689 vfrm->position, vfrm->fst->avctx->time_base,
2690 afrm->position, afrm->fst->avctx->time_base);
2691 FFrame *frm = v <= 0 ? vfrm : afrm;
2692 if( frm == afrm ) mux_audio(frm);
2693 if( frm == vfrm ) mux_video(frm);
2702 mux_lock->lock("FFMPEG::run");
2705 for( int i=0; i<ffaudio.size(); ++i )
2706 ffaudio[i]->drain();
2707 for( int i=0; i<ffvideo.size(); ++i )
2708 ffvideo[i]->drain();
2710 for( int i=0; i<ffaudio.size(); ++i )
2711 ffaudio[i]->flush();
2712 for( int i=0; i<ffvideo.size(); ++i )
2713 ffvideo[i]->flush();
2717 int FFMPEG::ff_total_audio_channels()
2719 return astrm_index.size();
2722 int FFMPEG::ff_total_astreams()
2724 return ffaudio.size();
2727 int FFMPEG::ff_audio_channels(int stream)
2729 return ffaudio[stream]->channels;
2732 int FFMPEG::ff_sample_rate(int stream)
2734 return ffaudio[stream]->sample_rate;
2737 const char* FFMPEG::ff_audio_format(int stream)
2739 AVStream *st = ffaudio[stream]->st;
2740 AVCodecID id = st->codecpar->codec_id;
2741 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2742 return desc ? desc->name : _("Unknown");
2745 int FFMPEG::ff_audio_pid(int stream)
2747 return ffaudio[stream]->st->id;
2750 int64_t FFMPEG::ff_audio_samples(int stream)
2752 return ffaudio[stream]->length;
2755 // find audio astream/channels with this program,
2756 // or all program audio channels (astream=-1)
2757 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
2761 int vidx = ffvideo[vstream]->fidx;
2762 // find first program with this video stream
2763 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
2764 AVProgram *pgrm = fmt_ctx->programs[i];
2765 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
2766 int st_idx = pgrm->stream_index[j];
2767 AVStream *st = fmt_ctx->streams[st_idx];
2768 if( st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
2769 if( st_idx == vidx ) pidx = i;
2772 if( pidx < 0 ) return -1;
2774 int64_t channels = 0;
2775 AVProgram *pgrm = fmt_ctx->programs[pidx];
2776 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2777 int aidx = pgrm->stream_index[j];
2778 AVStream *st = fmt_ctx->streams[aidx];
2779 if( st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
2780 if( astream > 0 ) { --astream; continue; }
2782 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
2783 if( ffaudio[i]->fidx == aidx ) astrm = i;
2785 if( ret < 0 ) ret = astrm;
2786 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
2787 channels |= mask << ffaudio[astrm]->channel0;
2789 if( !astream ) break;
2791 channel_mask = channels;
2796 int FFMPEG::ff_total_video_layers()
2798 return vstrm_index.size();
2801 int FFMPEG::ff_total_vstreams()
2803 return ffvideo.size();
2806 int FFMPEG::ff_video_width(int stream)
2808 return ffvideo[stream]->width;
2811 int FFMPEG::ff_video_height(int stream)
2813 return ffvideo[stream]->height;
2816 int FFMPEG::ff_set_video_width(int stream, int width)
2818 int w = ffvideo[stream]->width;
2819 ffvideo[stream]->width = width;
2823 int FFMPEG::ff_set_video_height(int stream, int height)
2825 int h = ffvideo[stream]->height;
2826 ffvideo[stream]->height = height;
2830 int FFMPEG::ff_coded_width(int stream)
2832 return ffvideo[stream]->avctx->coded_width;
2835 int FFMPEG::ff_coded_height(int stream)
2837 return ffvideo[stream]->avctx->coded_height;
2840 float FFMPEG::ff_aspect_ratio(int stream)
2842 return ffvideo[stream]->aspect_ratio;
2845 const char* FFMPEG::ff_video_format(int stream)
2847 AVStream *st = ffvideo[stream]->st;
2848 AVCodecID id = st->codecpar->codec_id;
2849 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2850 return desc ? desc->name : _("Unknown");
2853 double FFMPEG::ff_frame_rate(int stream)
2855 return ffvideo[stream]->frame_rate;
2858 int64_t FFMPEG::ff_video_frames(int stream)
2860 return ffvideo[stream]->length;
2863 int FFMPEG::ff_video_pid(int stream)
2865 return ffvideo[stream]->st->id;
2868 int FFMPEG::ff_video_mpeg_color_range(int stream)
2870 return ffvideo[stream]->st->codecpar->color_range == AVCOL_RANGE_MPEG ? 1 : 0;
2873 int FFMPEG::ff_cpus()
2875 return file_base->file->cpus;
2878 int FFVideoStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
2880 avfilter_register_all();
2881 const char *sp = filter_spec;
2882 char filter_name[BCSTRLEN], *np = filter_name;
2883 int i = sizeof(filter_name);
2884 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
2886 const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
2887 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_VIDEO ) {
2888 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
2891 filter_graph = avfilter_graph_alloc();
2892 const AVFilter *buffersrc = avfilter_get_by_name("buffer");
2893 const AVFilter *buffersink = avfilter_get_by_name("buffersink");
2895 int ret = 0; char args[BCTEXTLEN];
2896 AVPixelFormat pix_fmt = (AVPixelFormat)avpar->format;
2897 snprintf(args, sizeof(args),
2898 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
2899 avpar->width, avpar->height, (int)pix_fmt,
2900 st->time_base.num, st->time_base.den,
2901 avpar->sample_aspect_ratio.num, avpar->sample_aspect_ratio.den);
2903 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2904 args, NULL, filter_graph);
2906 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2907 NULL, NULL, filter_graph);
2909 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
2910 (uint8_t*)&pix_fmt, sizeof(pix_fmt),
2911 AV_OPT_SEARCH_CHILDREN);
2913 ff_err(ret, "FFVideoStream::create_filter");
2915 ret = FFStream::create_filter(filter_spec);
2916 return ret >= 0 ? 0 : -1;
2919 int FFAudioStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
2921 avfilter_register_all();
2922 const char *sp = filter_spec;
2923 char filter_name[BCSTRLEN], *np = filter_name;
2924 int i = sizeof(filter_name);
2925 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
2927 const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
2928 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_AUDIO ) {
2929 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
2932 filter_graph = avfilter_graph_alloc();
2933 const AVFilter *buffersrc = avfilter_get_by_name("abuffer");
2934 const AVFilter *buffersink = avfilter_get_by_name("abuffersink");
2935 int ret = 0; char args[BCTEXTLEN];
2936 AVSampleFormat sample_fmt = (AVSampleFormat)avpar->format;
2937 snprintf(args, sizeof(args),
2938 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
2939 st->time_base.num, st->time_base.den, avpar->sample_rate,
2940 av_get_sample_fmt_name(sample_fmt), avpar->channel_layout);
2942 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2943 args, NULL, filter_graph);
2945 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2946 NULL, NULL, filter_graph);
2948 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
2949 (uint8_t*)&sample_fmt, sizeof(sample_fmt),
2950 AV_OPT_SEARCH_CHILDREN);
2952 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
2953 (uint8_t*)&avpar->channel_layout,
2954 sizeof(avpar->channel_layout), AV_OPT_SEARCH_CHILDREN);
2956 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
2957 (uint8_t*)&sample_rate, sizeof(sample_rate),
2958 AV_OPT_SEARCH_CHILDREN);
2960 ff_err(ret, "FFAudioStream::create_filter");
2962 ret = FFStream::create_filter(filter_spec);
2963 return ret >= 0 ? 0 : -1;
2966 int FFStream::create_filter(const char *filter_spec)
2968 /* Endpoints for the filter graph. */
2969 AVFilterInOut *outputs = avfilter_inout_alloc();
2970 outputs->name = av_strdup("in");
2971 outputs->filter_ctx = buffersrc_ctx;
2972 outputs->pad_idx = 0;
2975 AVFilterInOut *inputs = avfilter_inout_alloc();
2976 inputs->name = av_strdup("out");
2977 inputs->filter_ctx = buffersink_ctx;
2978 inputs->pad_idx = 0;
2981 int ret = !outputs->name || !inputs->name ? -1 : 0;
2983 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
2984 &inputs, &outputs, NULL);
2986 ret = avfilter_graph_config(filter_graph, NULL);
2989 ff_err(ret, "FFStream::create_filter");
2990 avfilter_graph_free(&filter_graph);
2993 avfilter_inout_free(&inputs);
2994 avfilter_inout_free(&outputs);
2998 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
3001 av_init_packet(&pkt);
3002 AVFrame *frame = av_frame_alloc();
3004 fprintf(stderr,"FFMPEG::scan: ");
3005 fprintf(stderr,_("av_frame_alloc failed\n"));
3006 fprintf(stderr,"FFMPEG::scan:file=%s\n", file_base->asset->path);
3010 index_state->add_video_markers(ffvideo.size());
3011 index_state->add_audio_markers(ffaudio.size());
3013 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
3015 AVDictionary *copts = 0;
3016 av_dict_copy(&copts, opts, 0);
3017 AVStream *st = fmt_ctx->streams[i];
3018 AVCodecID codec_id = st->codecpar->codec_id;
3019 AVCodec *decoder = avcodec_find_decoder(codec_id);
3020 AVCodecContext *avctx = avcodec_alloc_context3(decoder);
3022 eprintf(_("cant allocate codec context\n"));
3023 ret = AVERROR(ENOMEM);
3026 avcodec_parameters_to_context(avctx, st->codecpar);
3027 if( !av_dict_get(copts, "threads", NULL, 0) )
3028 avctx->thread_count = ff_cpus();
3029 ret = avcodec_open2(avctx, decoder, &copts);
3031 av_dict_free(&copts);
3033 AVCodecParameters *avpar = st->codecpar;
3034 switch( avpar->codec_type ) {
3035 case AVMEDIA_TYPE_VIDEO: {
3036 int vidx = ffvideo.size();
3037 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
3038 if( vidx < 0 ) break;
3039 ffvideo[vidx]->avctx = avctx;
3041 case AVMEDIA_TYPE_AUDIO: {
3042 int aidx = ffaudio.size();
3043 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3044 if( aidx < 0 ) break;
3045 ffaudio[aidx]->avctx = avctx;
3050 fprintf(stderr,"FFMPEG::scan: ");
3051 fprintf(stderr,_("codec open failed\n"));
3052 fprintf(stderr,"FFMPEG::scan:file=%s\n", file_base->asset->path);
3053 avcodec_free_context(&avctx);
3057 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
3058 AVStream *st = fmt_ctx->streams[i];
3059 AVCodecParameters *avpar = st->codecpar;
3060 if( avpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
3061 int64_t tstmp = st->start_time;
3062 if( tstmp == AV_NOPTS_VALUE ) continue;
3063 int aidx = ffaudio.size();
3064 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3065 if( aidx < 0 ) continue;
3066 FFAudioStream *aud = ffaudio[aidx];
3067 tstmp -= aud->nudge;
3068 double secs = to_secs(tstmp, st->time_base);
3069 aud->curr_pos = secs * aud->sample_rate + 0.5;
3073 for( int64_t count=0; !*canceled; ++count ) {
3074 av_packet_unref(&pkt);
3075 pkt.data = 0; pkt.size = 0;
3077 int ret = av_read_frame(fmt_ctx, &pkt);
3079 if( ret == AVERROR_EOF ) break;
3080 if( ++errs > 100 ) {
3081 ff_err(ret,_("over 100 read_frame errs\n"));
3086 if( !pkt.data ) continue;
3087 int i = pkt.stream_index;
3088 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
3089 AVStream *st = fmt_ctx->streams[i];
3090 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
3092 AVCodecParameters *avpar = st->codecpar;
3093 switch( avpar->codec_type ) {
3094 case AVMEDIA_TYPE_VIDEO: {
3095 int vidx = ffvideo.size();
3096 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
3097 if( vidx < 0 ) break;
3098 FFVideoStream *vid = ffvideo[vidx];
3099 if( !vid->avctx ) break;
3100 int64_t tstmp = pkt.dts;
3101 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.pts;
3102 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
3103 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
3104 double secs = to_secs(tstmp, st->time_base);
3105 int64_t frm = secs * vid->frame_rate + 0.5;
3106 if( frm < 0 ) frm = 0;
3107 index_state->put_video_mark(vidx, frm, pkt.pos);
3110 ret = avcodec_send_packet(vid->avctx, pkt);
3111 if( ret < 0 ) break;
3112 while( (ret=vid->decode_frame(frame)) > 0 ) {}
3115 case AVMEDIA_TYPE_AUDIO: {
3116 int aidx = ffaudio.size();
3117 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3118 if( aidx < 0 ) break;
3119 FFAudioStream *aud = ffaudio[aidx];
3120 if( !aud->avctx ) break;
3121 int64_t tstmp = pkt.pts;
3122 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
3123 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
3124 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
3125 double secs = to_secs(tstmp, st->time_base);
3126 int64_t sample = secs * aud->sample_rate + 0.5;
3128 index_state->put_audio_mark(aidx, sample, pkt.pos);
3130 ret = avcodec_send_packet(aud->avctx, &pkt);
3131 if( ret < 0 ) break;
3132 int ch = aud->channel0, nch = aud->channels;
3133 int64_t pos = index_state->pos(ch);
3134 if( pos != aud->curr_pos ) {
3135 if( abs(pos-aud->curr_pos) > 1 )
3136 printf("audio%d pad %jd %jd (%jd)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
3137 index_state->pad_data(ch, nch, aud->curr_pos);
3139 while( (ret=aud->decode_frame(frame)) > 0 ) {
3140 //if( frame->channels != nch ) break;
3141 aud->init_swr(frame->channels, frame->format, frame->sample_rate);
3143 int len = aud->get_samples(samples,
3144 &frame->extended_data[0], frame->nb_samples);
3145 pos = aud->curr_pos;
3146 if( (aud->curr_pos += len) >= 0 ) {
3148 samples += -pos * nch;
3149 len = aud->curr_pos;
3151 for( int i=0; i<nch; ++i )
3152 index_state->put_data(ch+i,nch,samples+i,len);
3159 av_frame_free(&frame);
3163 void FFStream::load_markers(IndexMarks &marks, double rate)
3166 int64_t sz = marks.size();
3167 int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
3168 int nb_ent = st->nb_index_entries;
3169 // some formats already have an index
3171 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
3172 int64_t tstmp = ep->timestamp;
3173 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
3174 double secs = ffmpeg->to_secs(tstmp, st->time_base);
3175 int64_t no = secs * rate;
3176 while( in < sz && marks[in].no <= no ) ++in;
3178 int64_t len = sz - in;
3179 int64_t count = max_entries - nb_ent;
3180 if( count > len ) count = len;
3181 for( int i=0; i<count; ++i ) {
3182 int k = in + i * len / count;
3183 int64_t no = marks[k].no, pos = marks[k].pos;
3184 double secs = (double)no / rate;
3185 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
3186 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
3187 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);