2 * Copyright (c) 2012 Pavel Koshevoy <pkoshevoy at gmail dot com>
4 * This file is part of FFmpeg.
6 * FFmpeg is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * FFmpeg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with FFmpeg; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 * tempo scaling audio filter -- an implementation of WSOLA algorithm
25 * Based on MIT licensed yaeAudioTempoFilter.h and yaeAudioFragment.h
26 * from Apprentice Video player by Pavel Koshevoy.
27 * https://sourceforge.net/projects/apprenticevideo/
29 * An explanation of SOLA algorithm is available at
30 * http://www.surina.net/article/time-and-pitch-scaling.html
32 * WSOLA is very similar to SOLA, only one major difference exists between
33 * these algorithms. SOLA shifts audio fragments along the output stream,
34 * where as WSOLA shifts audio fragments along the input stream.
36 * The advantage of WSOLA algorithm is that the overlap region size is
37 * always the same, therefore the blending function is constant and
42 #include "libavcodec/avfft.h"
43 #include "libavutil/avassert.h"
44 #include "libavutil/avstring.h"
45 #include "libavutil/channel_layout.h"
46 #include "libavutil/eval.h"
47 #include "libavutil/opt.h"
48 #include "libavutil/samplefmt.h"
54 * A fragment of audio waveform
57 // index of the first sample of this fragment in the overall waveform;
58 // 0: input sample position
59 // 1: output sample position
62 // original packed multi-channel samples:
65 // number of samples in this fragment:
68 // rDFT transform of the down-mixed mono fragment, used for
69 // fast waveform alignment via correlation in frequency domain:
74 * Filter state machine states
80 YAE_OUTPUT_OVERLAP_ADD,
85 * Filter state machine
90 // ring-buffer of input samples, necessary because some times
91 // input fragment position may be adjusted backwards:
94 // ring-buffer maximum capacity, expressed in sample rate time base:
97 // ring-buffer house keeping:
102 // 0: input sample position corresponding to the ring buffer tail
103 // 1: output sample position
107 enum AVSampleFormat format;
109 // number of channels:
112 // row of bytes to skip from one sample to next, across multple channels;
113 // stride = (number-of-channels * bits-per-sample-per-channel) / 8
116 // fragment window size, power-of-two integer:
119 // Hann window coefficients, for feathering
120 // (blending) the overlapping fragment region:
123 // tempo scaling factor:
126 // cumulative alignment drift:
129 // current/previous fragment ring-buffer:
130 AudioFragment frag[2];
132 // current fragment index:
138 // for fast correlation calculation in frequency domain:
139 RDFTContext *real_to_complex;
140 RDFTContext *complex_to_real;
141 FFTSample *correlation;
143 // for managing AVFilterPad.request_frame and AVFilterPad.filter_frame
147 uint64_t nsamples_in;
148 uint64_t nsamples_out;
151 #define OFFSET(x) offsetof(ATempoContext, x)
153 static const AVOption atempo_options[] = {
154 { "tempo", "set tempo scale factor",
155 OFFSET(tempo), AV_OPT_TYPE_DOUBLE, { .dbl = 1.0 }, 0.5, 2.0,
156 AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_FILTERING_PARAM },
160 AVFILTER_DEFINE_CLASS(atempo);
163 * Reset filter to initial state, do not deallocate existing local buffers.
165 static void yae_clear(ATempoContext *atempo)
173 atempo->state = YAE_LOAD_FRAGMENT;
175 atempo->position[0] = 0;
176 atempo->position[1] = 0;
178 atempo->frag[0].position[0] = 0;
179 atempo->frag[0].position[1] = 0;
180 atempo->frag[0].nsamples = 0;
182 atempo->frag[1].position[0] = 0;
183 atempo->frag[1].position[1] = 0;
184 atempo->frag[1].nsamples = 0;
186 // shift left position of 1st fragment by half a window
187 // so that no re-normalization would be required for
188 // the left half of the 1st fragment:
189 atempo->frag[0].position[0] = -(int64_t)(atempo->window / 2);
190 atempo->frag[0].position[1] = -(int64_t)(atempo->window / 2);
192 av_frame_free(&atempo->dst_buffer);
194 atempo->dst_end = NULL;
196 atempo->nsamples_in = 0;
197 atempo->nsamples_out = 0;
201 * Reset filter to initial state and deallocate all buffers.
203 static void yae_release_buffers(ATempoContext *atempo)
207 av_freep(&atempo->frag[0].data);
208 av_freep(&atempo->frag[1].data);
209 av_freep(&atempo->frag[0].xdat);
210 av_freep(&atempo->frag[1].xdat);
212 av_freep(&atempo->buffer);
213 av_freep(&atempo->hann);
214 av_freep(&atempo->correlation);
216 av_rdft_end(atempo->real_to_complex);
217 atempo->real_to_complex = NULL;
219 av_rdft_end(atempo->complex_to_real);
220 atempo->complex_to_real = NULL;
223 /* av_realloc is not aligned enough; fortunately, the data does not need to
225 #define RE_MALLOC_OR_FAIL(field, field_size) \
228 field = av_malloc(field_size); \
230 yae_release_buffers(atempo); \
231 return AVERROR(ENOMEM); \
236 * Prepare filter for processing audio data of given format,
237 * sample rate and number of channels.
239 static int yae_reset(ATempoContext *atempo,
240 enum AVSampleFormat format,
244 const int sample_size = av_get_bytes_per_sample(format);
245 uint32_t nlevels = 0;
249 atempo->format = format;
250 atempo->channels = channels;
251 atempo->stride = sample_size * channels;
253 // pick a segment window size:
254 atempo->window = sample_rate / 24;
256 // adjust window size to be a power-of-two integer:
257 nlevels = av_log2(atempo->window);
259 av_assert0(pot <= atempo->window);
261 if (pot < atempo->window) {
262 atempo->window = pot * 2;
266 // initialize audio fragment buffers:
267 RE_MALLOC_OR_FAIL(atempo->frag[0].data, atempo->window * atempo->stride);
268 RE_MALLOC_OR_FAIL(atempo->frag[1].data, atempo->window * atempo->stride);
269 RE_MALLOC_OR_FAIL(atempo->frag[0].xdat, atempo->window * sizeof(FFTComplex));
270 RE_MALLOC_OR_FAIL(atempo->frag[1].xdat, atempo->window * sizeof(FFTComplex));
272 // initialize rDFT contexts:
273 av_rdft_end(atempo->real_to_complex);
274 atempo->real_to_complex = NULL;
276 av_rdft_end(atempo->complex_to_real);
277 atempo->complex_to_real = NULL;
279 atempo->real_to_complex = av_rdft_init(nlevels + 1, DFT_R2C);
280 if (!atempo->real_to_complex) {
281 yae_release_buffers(atempo);
282 return AVERROR(ENOMEM);
285 atempo->complex_to_real = av_rdft_init(nlevels + 1, IDFT_C2R);
286 if (!atempo->complex_to_real) {
287 yae_release_buffers(atempo);
288 return AVERROR(ENOMEM);
291 RE_MALLOC_OR_FAIL(atempo->correlation, atempo->window * sizeof(FFTComplex));
293 atempo->ring = atempo->window * 3;
294 RE_MALLOC_OR_FAIL(atempo->buffer, atempo->ring * atempo->stride);
296 // initialize the Hann window function:
297 RE_MALLOC_OR_FAIL(atempo->hann, atempo->window * sizeof(float));
299 for (i = 0; i < atempo->window; i++) {
300 double t = (double)i / (double)(atempo->window - 1);
301 double h = 0.5 * (1.0 - cos(2.0 * M_PI * t));
302 atempo->hann[i] = (float)h;
309 static int yae_set_tempo(AVFilterContext *ctx, const char *arg_tempo)
311 ATempoContext *atempo = ctx->priv;
313 double tempo = av_strtod(arg_tempo, &tail);
316 av_log(ctx, AV_LOG_ERROR, "Invalid tempo value '%s'\n", arg_tempo);
317 return AVERROR(EINVAL);
320 if (tempo < 0.5 || tempo > 2.0) {
321 av_log(ctx, AV_LOG_ERROR, "Tempo value %f exceeds [0.5, 2.0] range\n",
323 return AVERROR(EINVAL);
326 atempo->tempo = tempo;
330 inline static AudioFragment *yae_curr_frag(ATempoContext *atempo)
332 return &atempo->frag[atempo->nfrag % 2];
335 inline static AudioFragment *yae_prev_frag(ATempoContext *atempo)
337 return &atempo->frag[(atempo->nfrag + 1) % 2];
341 * A helper macro for initializing complex data buffer with scalar data
344 #define yae_init_xdat(scalar_type, scalar_max) \
346 const uint8_t *src_end = src + \
347 frag->nsamples * atempo->channels * sizeof(scalar_type); \
349 FFTSample *xdat = frag->xdat; \
352 if (atempo->channels == 1) { \
353 for (; src < src_end; xdat++) { \
354 tmp = *(const scalar_type *)src; \
355 src += sizeof(scalar_type); \
357 *xdat = (FFTSample)tmp; \
360 FFTSample s, max, ti, si; \
363 for (; src < src_end; xdat++) { \
364 tmp = *(const scalar_type *)src; \
365 src += sizeof(scalar_type); \
367 max = (FFTSample)tmp; \
368 s = FFMIN((FFTSample)scalar_max, \
369 (FFTSample)fabsf(max)); \
371 for (i = 1; i < atempo->channels; i++) { \
372 tmp = *(const scalar_type *)src; \
373 src += sizeof(scalar_type); \
375 ti = (FFTSample)tmp; \
376 si = FFMIN((FFTSample)scalar_max, \
377 (FFTSample)fabsf(ti)); \
391 * Initialize complex data buffer of a given audio fragment
392 * with down-mixed mono data of appropriate scalar type.
394 static void yae_downmix(ATempoContext *atempo, AudioFragment *frag)
397 const uint8_t *src = frag->data;
399 // init complex data buffer used for FFT and Correlation:
400 memset(frag->xdat, 0, sizeof(FFTComplex) * atempo->window);
402 if (atempo->format == AV_SAMPLE_FMT_U8) {
403 yae_init_xdat(uint8_t, 127);
404 } else if (atempo->format == AV_SAMPLE_FMT_S16) {
405 yae_init_xdat(int16_t, 32767);
406 } else if (atempo->format == AV_SAMPLE_FMT_S32) {
407 yae_init_xdat(int, 2147483647);
408 } else if (atempo->format == AV_SAMPLE_FMT_FLT) {
409 yae_init_xdat(float, 1);
410 } else if (atempo->format == AV_SAMPLE_FMT_DBL) {
411 yae_init_xdat(double, 1);
416 * Populate the internal data buffer on as-needed basis.
419 * 0 if requested data was already available or was successfully loaded,
420 * AVERROR(EAGAIN) if more input data is required.
422 static int yae_load_data(ATempoContext *atempo,
423 const uint8_t **src_ref,
424 const uint8_t *src_end,
428 const uint8_t *src = *src_ref;
429 const int read_size = stop_here - atempo->position[0];
431 if (stop_here <= atempo->position[0]) {
435 // samples are not expected to be skipped:
436 av_assert0(read_size <= atempo->ring);
438 while (atempo->position[0] < stop_here && src < src_end) {
439 int src_samples = (src_end - src) / atempo->stride;
441 // load data piece-wise, in order to avoid complicating the logic:
442 int nsamples = FFMIN(read_size, src_samples);
446 nsamples = FFMIN(nsamples, atempo->ring);
447 na = FFMIN(nsamples, atempo->ring - atempo->tail);
448 nb = FFMIN(nsamples - na, atempo->ring);
451 uint8_t *a = atempo->buffer + atempo->tail * atempo->stride;
452 memcpy(a, src, na * atempo->stride);
454 src += na * atempo->stride;
455 atempo->position[0] += na;
457 atempo->size = FFMIN(atempo->size + na, atempo->ring);
458 atempo->tail = (atempo->tail + na) % atempo->ring;
460 atempo->size < atempo->ring ?
461 atempo->tail - atempo->size :
466 uint8_t *b = atempo->buffer;
467 memcpy(b, src, nb * atempo->stride);
469 src += nb * atempo->stride;
470 atempo->position[0] += nb;
472 atempo->size = FFMIN(atempo->size + nb, atempo->ring);
473 atempo->tail = (atempo->tail + nb) % atempo->ring;
475 atempo->size < atempo->ring ?
476 atempo->tail - atempo->size :
481 // pass back the updated source buffer pointer:
485 av_assert0(atempo->position[0] <= stop_here);
487 return atempo->position[0] == stop_here ? 0 : AVERROR(EAGAIN);
491 * Populate current audio fragment data buffer.
494 * 0 when the fragment is ready,
495 * AVERROR(EAGAIN) if more input data is required.
497 static int yae_load_frag(ATempoContext *atempo,
498 const uint8_t **src_ref,
499 const uint8_t *src_end)
502 AudioFragment *frag = yae_curr_frag(atempo);
504 int64_t missing, start, zeros;
506 const uint8_t *a, *b;
507 int i0, i1, n0, n1, na, nb;
509 int64_t stop_here = frag->position[0] + atempo->window;
510 if (src_ref && yae_load_data(atempo, src_ref, src_end, stop_here) != 0) {
511 return AVERROR(EAGAIN);
514 // calculate the number of samples we don't have:
516 stop_here > atempo->position[0] ?
517 stop_here - atempo->position[0] : 0;
520 missing < (int64_t)atempo->window ?
521 (uint32_t)(atempo->window - missing) : 0;
523 // setup the output buffer:
524 frag->nsamples = nsamples;
527 start = atempo->position[0] - atempo->size;
530 if (frag->position[0] < start) {
531 // what we don't have we substitute with zeros:
532 zeros = FFMIN(start - frag->position[0], (int64_t)nsamples);
533 av_assert0(zeros != nsamples);
535 memset(dst, 0, zeros * atempo->stride);
536 dst += zeros * atempo->stride;
539 if (zeros == nsamples) {
543 // get the remaining data from the ring buffer:
544 na = (atempo->head < atempo->tail ?
545 atempo->tail - atempo->head :
546 atempo->ring - atempo->head);
548 nb = atempo->head < atempo->tail ? 0 : atempo->tail;
551 av_assert0(nsamples <= zeros + na + nb);
553 a = atempo->buffer + atempo->head * atempo->stride;
556 i0 = frag->position[0] + zeros - start;
557 i1 = i0 < na ? 0 : i0 - na;
559 n0 = i0 < na ? FFMIN(na - i0, (int)(nsamples - zeros)) : 0;
560 n1 = nsamples - zeros - n0;
563 memcpy(dst, a + i0 * atempo->stride, n0 * atempo->stride);
564 dst += n0 * atempo->stride;
568 memcpy(dst, b + i1 * atempo->stride, n1 * atempo->stride);
575 * Prepare for loading next audio fragment.
577 static void yae_advance_to_next_frag(ATempoContext *atempo)
579 const double fragment_step = atempo->tempo * (double)(atempo->window / 2);
581 const AudioFragment *prev;
585 prev = yae_prev_frag(atempo);
586 frag = yae_curr_frag(atempo);
588 frag->position[0] = prev->position[0] + (int64_t)fragment_step;
589 frag->position[1] = prev->position[1] + atempo->window / 2;
594 * Calculate cross-correlation via rDFT.
596 * Multiply two vectors of complex numbers (result of real_to_complex rDFT)
597 * and transform back via complex_to_real rDFT.
599 static void yae_xcorr_via_rdft(FFTSample *xcorr,
600 RDFTContext *complex_to_real,
601 const FFTComplex *xa,
602 const FFTComplex *xb,
605 FFTComplex *xc = (FFTComplex *)xcorr;
608 // NOTE: first element requires special care -- Given Y = rDFT(X),
609 // Im(Y[0]) and Im(Y[N/2]) are always zero, therefore av_rdft_calc
610 // stores Re(Y[N/2]) in place of Im(Y[0]).
612 xc->re = xa->re * xb->re;
613 xc->im = xa->im * xb->im;
618 for (i = 1; i < window; i++, xa++, xb++, xc++) {
619 xc->re = (xa->re * xb->re + xa->im * xb->im);
620 xc->im = (xa->im * xb->re - xa->re * xb->im);
623 // apply inverse rDFT:
624 av_rdft_calc(complex_to_real, xcorr);
628 * Calculate alignment offset for given fragment
629 * relative to the previous fragment.
631 * @return alignment offset of current fragment relative to previous.
633 static int yae_align(AudioFragment *frag,
634 const AudioFragment *prev,
638 FFTSample *correlation,
639 RDFTContext *complex_to_real)
641 int best_offset = -drift;
642 FFTSample best_metric = -FLT_MAX;
649 yae_xcorr_via_rdft(correlation,
651 (const FFTComplex *)prev->xdat,
652 (const FFTComplex *)frag->xdat,
655 // identify search window boundaries:
656 i0 = FFMAX(window / 2 - delta_max - drift, 0);
657 i0 = FFMIN(i0, window);
659 i1 = FFMIN(window / 2 + delta_max - drift, window - window / 16);
662 // identify cross-correlation peaks within search window:
663 xcorr = correlation + i0;
665 for (i = i0; i < i1; i++, xcorr++) {
666 FFTSample metric = *xcorr;
669 FFTSample drifti = (FFTSample)(drift + i);
670 metric *= drifti * (FFTSample)(i - i0) * (FFTSample)(i1 - i);
672 if (metric > best_metric) {
673 best_metric = metric;
674 best_offset = i - window / 2;
682 * Adjust current fragment position for better alignment
683 * with previous fragment.
685 * @return alignment correction.
687 static int yae_adjust_position(ATempoContext *atempo)
689 const AudioFragment *prev = yae_prev_frag(atempo);
690 AudioFragment *frag = yae_curr_frag(atempo);
692 const int delta_max = atempo->window / 2;
693 const int correction = yae_align(frag,
699 atempo->complex_to_real);
702 // adjust fragment position:
703 frag->position[0] -= correction;
705 // clear so that the fragment can be reloaded:
708 // update cumulative correction drift counter:
709 atempo->drift += correction;
716 * A helper macro for blending the overlap region of previous
717 * and current audio fragment.
719 #define yae_blend(scalar_type) \
721 const scalar_type *aaa = (const scalar_type *)a; \
722 const scalar_type *bbb = (const scalar_type *)b; \
724 scalar_type *out = (scalar_type *)dst; \
725 scalar_type *out_end = (scalar_type *)dst_end; \
728 for (i = 0; i < overlap && out < out_end; \
729 i++, atempo->position[1]++, wa++, wb++) { \
734 for (j = 0; j < atempo->channels; \
735 j++, aaa++, bbb++, out++) { \
736 float t0 = (float)*aaa; \
737 float t1 = (float)*bbb; \
740 frag->position[0] + i < 0 ? \
742 (scalar_type)(t0 * w0 + t1 * w1); \
745 dst = (uint8_t *)out; \
749 * Blend the overlap region of previous and current audio fragment
750 * and output the results to the given destination buffer.
753 * 0 if the overlap region was completely stored in the dst buffer,
754 * AVERROR(EAGAIN) if more destination buffer space is required.
756 static int yae_overlap_add(ATempoContext *atempo,
761 const AudioFragment *prev = yae_prev_frag(atempo);
762 const AudioFragment *frag = yae_curr_frag(atempo);
764 const int64_t start_here = FFMAX(atempo->position[1],
767 const int64_t stop_here = FFMIN(prev->position[1] + prev->nsamples,
768 frag->position[1] + frag->nsamples);
770 const int64_t overlap = stop_here - start_here;
772 const int64_t ia = start_here - prev->position[1];
773 const int64_t ib = start_here - frag->position[1];
775 const float *wa = atempo->hann + ia;
776 const float *wb = atempo->hann + ib;
778 const uint8_t *a = prev->data + ia * atempo->stride;
779 const uint8_t *b = frag->data + ib * atempo->stride;
781 uint8_t *dst = *dst_ref;
783 av_assert0(start_here <= stop_here &&
784 frag->position[1] <= start_here &&
785 overlap <= frag->nsamples);
787 if (atempo->format == AV_SAMPLE_FMT_U8) {
789 } else if (atempo->format == AV_SAMPLE_FMT_S16) {
791 } else if (atempo->format == AV_SAMPLE_FMT_S32) {
793 } else if (atempo->format == AV_SAMPLE_FMT_FLT) {
795 } else if (atempo->format == AV_SAMPLE_FMT_DBL) {
799 // pass-back the updated destination buffer pointer:
802 return atempo->position[1] == stop_here ? 0 : AVERROR(EAGAIN);
806 * Feed as much data to the filter as it is able to consume
807 * and receive as much processed data in the destination buffer
808 * as it is able to produce or store.
811 yae_apply(ATempoContext *atempo,
812 const uint8_t **src_ref,
813 const uint8_t *src_end,
818 if (atempo->state == YAE_LOAD_FRAGMENT) {
819 // load additional data for the current fragment:
820 if (yae_load_frag(atempo, src_ref, src_end) != 0) {
825 yae_downmix(atempo, yae_curr_frag(atempo));
828 av_rdft_calc(atempo->real_to_complex, yae_curr_frag(atempo)->xdat);
830 // must load the second fragment before alignment can start:
831 if (!atempo->nfrag) {
832 yae_advance_to_next_frag(atempo);
836 atempo->state = YAE_ADJUST_POSITION;
839 if (atempo->state == YAE_ADJUST_POSITION) {
840 // adjust position for better alignment:
841 if (yae_adjust_position(atempo)) {
842 // reload the fragment at the corrected position, so that the
843 // Hann window blending would not require normalization:
844 atempo->state = YAE_RELOAD_FRAGMENT;
846 atempo->state = YAE_OUTPUT_OVERLAP_ADD;
850 if (atempo->state == YAE_RELOAD_FRAGMENT) {
851 // load additional data if necessary due to position adjustment:
852 if (yae_load_frag(atempo, src_ref, src_end) != 0) {
857 yae_downmix(atempo, yae_curr_frag(atempo));
860 av_rdft_calc(atempo->real_to_complex, yae_curr_frag(atempo)->xdat);
862 atempo->state = YAE_OUTPUT_OVERLAP_ADD;
865 if (atempo->state == YAE_OUTPUT_OVERLAP_ADD) {
866 // overlap-add and output the result:
867 if (yae_overlap_add(atempo, dst_ref, dst_end) != 0) {
871 // advance to the next fragment, repeat:
872 yae_advance_to_next_frag(atempo);
873 atempo->state = YAE_LOAD_FRAGMENT;
879 * Flush any buffered data from the filter.
882 * 0 if all data was completely stored in the dst buffer,
883 * AVERROR(EAGAIN) if more destination buffer space is required.
885 static int yae_flush(ATempoContext *atempo,
889 AudioFragment *frag = yae_curr_frag(atempo);
902 atempo->state = YAE_FLUSH_OUTPUT;
904 if (atempo->position[0] == frag->position[0] + frag->nsamples &&
905 atempo->position[1] == frag->position[1] + frag->nsamples) {
906 // the current fragment is already flushed:
910 if (frag->position[0] + frag->nsamples < atempo->position[0]) {
911 // finish loading the current (possibly partial) fragment:
912 yae_load_frag(atempo, NULL, NULL);
916 yae_downmix(atempo, frag);
919 av_rdft_calc(atempo->real_to_complex, frag->xdat);
921 // align current fragment to previous fragment:
922 if (yae_adjust_position(atempo)) {
923 // reload the current fragment due to adjusted position:
924 yae_load_frag(atempo, NULL, NULL);
929 // flush the overlap region:
930 overlap_end = frag->position[1] + FFMIN(atempo->window / 2,
933 while (atempo->position[1] < overlap_end) {
934 if (yae_overlap_add(atempo, dst_ref, dst_end) != 0) {
935 return AVERROR(EAGAIN);
939 // flush the remaininder of the current fragment:
940 start_here = FFMAX(atempo->position[1], overlap_end);
941 stop_here = frag->position[1] + frag->nsamples;
942 offset = start_here - frag->position[1];
943 av_assert0(start_here <= stop_here && frag->position[1] <= start_here);
945 src = frag->data + offset * atempo->stride;
946 dst = (uint8_t *)*dst_ref;
948 src_size = (int)(stop_here - start_here) * atempo->stride;
949 dst_size = dst_end - dst;
950 nbytes = FFMIN(src_size, dst_size);
952 memcpy(dst, src, nbytes);
955 atempo->position[1] += (nbytes / atempo->stride);
957 // pass-back the updated destination buffer pointer:
958 *dst_ref = (uint8_t *)dst;
960 return atempo->position[1] == stop_here ? 0 : AVERROR(EAGAIN);
963 static av_cold int init(AVFilterContext *ctx)
965 ATempoContext *atempo = ctx->priv;
966 atempo->format = AV_SAMPLE_FMT_NONE;
967 atempo->state = YAE_LOAD_FRAGMENT;
971 static av_cold void uninit(AVFilterContext *ctx)
973 ATempoContext *atempo = ctx->priv;
974 yae_release_buffers(atempo);
977 static int query_formats(AVFilterContext *ctx)
979 AVFilterChannelLayouts *layouts = NULL;
980 AVFilterFormats *formats = NULL;
982 // WSOLA necessitates an internal sliding window ring buffer
983 // for incoming audio stream.
985 // Planar sample formats are too cumbersome to store in a ring buffer,
986 // therefore planar sample formats are not supported.
988 static const enum AVSampleFormat sample_fmts[] = {
997 layouts = ff_all_channel_layouts();
999 return AVERROR(ENOMEM);
1001 ff_set_common_channel_layouts(ctx, layouts);
1003 formats = ff_make_format_list(sample_fmts);
1005 return AVERROR(ENOMEM);
1007 ff_set_common_formats(ctx, formats);
1009 formats = ff_all_samplerates();
1011 return AVERROR(ENOMEM);
1013 ff_set_common_samplerates(ctx, formats);
1018 static int config_props(AVFilterLink *inlink)
1020 AVFilterContext *ctx = inlink->dst;
1021 ATempoContext *atempo = ctx->priv;
1023 enum AVSampleFormat format = inlink->format;
1024 int sample_rate = (int)inlink->sample_rate;
1025 int channels = av_get_channel_layout_nb_channels(inlink->channel_layout);
1027 ctx->outputs[0]->flags |= FF_LINK_FLAG_REQUEST_LOOP;
1029 return yae_reset(atempo, format, sample_rate, channels);
1032 static int push_samples(ATempoContext *atempo,
1033 AVFilterLink *outlink,
1038 atempo->dst_buffer->sample_rate = outlink->sample_rate;
1039 atempo->dst_buffer->nb_samples = n_out;
1042 atempo->dst_buffer->pts =
1043 av_rescale_q(atempo->nsamples_out,
1044 (AVRational){ 1, outlink->sample_rate },
1045 outlink->time_base);
1047 ret = ff_filter_frame(outlink, atempo->dst_buffer);
1050 atempo->dst_buffer = NULL;
1052 atempo->dst_end = NULL;
1054 atempo->nsamples_out += n_out;
1058 static int filter_frame(AVFilterLink *inlink, AVFrame *src_buffer)
1060 AVFilterContext *ctx = inlink->dst;
1061 ATempoContext *atempo = ctx->priv;
1062 AVFilterLink *outlink = ctx->outputs[0];
1065 int n_in = src_buffer->nb_samples;
1066 int n_out = (int)(0.5 + ((double)n_in) / atempo->tempo);
1068 const uint8_t *src = src_buffer->data[0];
1069 const uint8_t *src_end = src + n_in * atempo->stride;
1071 while (src < src_end) {
1072 if (!atempo->dst_buffer) {
1073 atempo->dst_buffer = ff_get_audio_buffer(outlink, n_out);
1074 if (!atempo->dst_buffer)
1075 return AVERROR(ENOMEM);
1076 av_frame_copy_props(atempo->dst_buffer, src_buffer);
1078 atempo->dst = atempo->dst_buffer->data[0];
1079 atempo->dst_end = atempo->dst + n_out * atempo->stride;
1082 yae_apply(atempo, &src, src_end, &atempo->dst, atempo->dst_end);
1084 if (atempo->dst == atempo->dst_end) {
1085 ret = push_samples(atempo, outlink, n_out);
1091 atempo->nsamples_in += n_in;
1093 av_frame_free(&src_buffer);
1097 static int request_frame(AVFilterLink *outlink)
1099 AVFilterContext *ctx = outlink->src;
1100 ATempoContext *atempo = ctx->priv;
1103 ret = ff_request_frame(ctx->inputs[0]);
1105 if (ret == AVERROR_EOF) {
1106 // flush the filter:
1107 int n_max = atempo->ring;
1109 int err = AVERROR(EAGAIN);
1111 while (err == AVERROR(EAGAIN)) {
1112 if (!atempo->dst_buffer) {
1113 atempo->dst_buffer = ff_get_audio_buffer(outlink, n_max);
1114 if (!atempo->dst_buffer)
1115 return AVERROR(ENOMEM);
1117 atempo->dst = atempo->dst_buffer->data[0];
1118 atempo->dst_end = atempo->dst + n_max * atempo->stride;
1121 err = yae_flush(atempo, &atempo->dst, atempo->dst_end);
1123 n_out = ((atempo->dst - atempo->dst_buffer->data[0]) /
1127 ret = push_samples(atempo, outlink, n_out);
1131 av_frame_free(&atempo->dst_buffer);
1133 atempo->dst_end = NULL;
1141 static int process_command(AVFilterContext *ctx,
1148 return !strcmp(cmd, "tempo") ? yae_set_tempo(ctx, arg) : AVERROR(ENOSYS);
1151 static const AVFilterPad atempo_inputs[] = {
1154 .type = AVMEDIA_TYPE_AUDIO,
1155 .filter_frame = filter_frame,
1156 .config_props = config_props,
1161 static const AVFilterPad atempo_outputs[] = {
1164 .request_frame = request_frame,
1165 .type = AVMEDIA_TYPE_AUDIO,
1170 AVFilter avfilter_af_atempo = {
1172 .description = NULL_IF_CONFIG_SMALL("Adjust audio tempo."),
1175 .query_formats = query_formats,
1176 .process_command = process_command,
1177 .priv_size = sizeof(ATempoContext),
1178 .priv_class = &atempo_class,
1179 .inputs = atempo_inputs,
1180 .outputs = atempo_outputs,