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
56 typedef struct AudioFragment {
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
87 typedef struct ATempoContext {
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 // a snapshot of previous fragment input and output position values
127 // captured when the tempo scale factor was set most recently:
130 // current/previous fragment ring-buffer:
131 AudioFragment frag[2];
133 // current fragment index:
139 // for fast correlation calculation in frequency domain:
140 RDFTContext *real_to_complex;
141 RDFTContext *complex_to_real;
142 FFTSample *correlation;
144 // for managing AVFilterPad.request_frame and AVFilterPad.filter_frame
148 uint64_t nsamples_in;
149 uint64_t nsamples_out;
152 #define YAE_ATEMPO_MIN 0.5
153 #define YAE_ATEMPO_MAX 100.0
155 #define OFFSET(x) offsetof(ATempoContext, x)
157 static const AVOption atempo_options[] = {
158 { "tempo", "set tempo scale factor",
159 OFFSET(tempo), AV_OPT_TYPE_DOUBLE, { .dbl = 1.0 },
162 AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_FILTERING_PARAM },
166 AVFILTER_DEFINE_CLASS(atempo);
168 inline static AudioFragment *yae_curr_frag(ATempoContext *atempo)
170 return &atempo->frag[atempo->nfrag % 2];
173 inline static AudioFragment *yae_prev_frag(ATempoContext *atempo)
175 return &atempo->frag[(atempo->nfrag + 1) % 2];
179 * Reset filter to initial state, do not deallocate existing local buffers.
181 static void yae_clear(ATempoContext *atempo)
188 atempo->state = YAE_LOAD_FRAGMENT;
190 atempo->position[0] = 0;
191 atempo->position[1] = 0;
193 atempo->origin[0] = 0;
194 atempo->origin[1] = 0;
196 atempo->frag[0].position[0] = 0;
197 atempo->frag[0].position[1] = 0;
198 atempo->frag[0].nsamples = 0;
200 atempo->frag[1].position[0] = 0;
201 atempo->frag[1].position[1] = 0;
202 atempo->frag[1].nsamples = 0;
204 // shift left position of 1st fragment by half a window
205 // so that no re-normalization would be required for
206 // the left half of the 1st fragment:
207 atempo->frag[0].position[0] = -(int64_t)(atempo->window / 2);
208 atempo->frag[0].position[1] = -(int64_t)(atempo->window / 2);
210 av_frame_free(&atempo->dst_buffer);
212 atempo->dst_end = NULL;
214 atempo->nsamples_in = 0;
215 atempo->nsamples_out = 0;
219 * Reset filter to initial state and deallocate all buffers.
221 static void yae_release_buffers(ATempoContext *atempo)
225 av_freep(&atempo->frag[0].data);
226 av_freep(&atempo->frag[1].data);
227 av_freep(&atempo->frag[0].xdat);
228 av_freep(&atempo->frag[1].xdat);
230 av_freep(&atempo->buffer);
231 av_freep(&atempo->hann);
232 av_freep(&atempo->correlation);
234 av_rdft_end(atempo->real_to_complex);
235 atempo->real_to_complex = NULL;
237 av_rdft_end(atempo->complex_to_real);
238 atempo->complex_to_real = NULL;
241 /* av_realloc is not aligned enough; fortunately, the data does not need to
243 #define RE_MALLOC_OR_FAIL(field, field_size) \
246 field = av_malloc(field_size); \
248 yae_release_buffers(atempo); \
249 return AVERROR(ENOMEM); \
254 * Prepare filter for processing audio data of given format,
255 * sample rate and number of channels.
257 static int yae_reset(ATempoContext *atempo,
258 enum AVSampleFormat format,
262 const int sample_size = av_get_bytes_per_sample(format);
263 uint32_t nlevels = 0;
267 atempo->format = format;
268 atempo->channels = channels;
269 atempo->stride = sample_size * channels;
271 // pick a segment window size:
272 atempo->window = sample_rate / 24;
274 // adjust window size to be a power-of-two integer:
275 nlevels = av_log2(atempo->window);
277 av_assert0(pot <= atempo->window);
279 if (pot < atempo->window) {
280 atempo->window = pot * 2;
284 // initialize audio fragment buffers:
285 RE_MALLOC_OR_FAIL(atempo->frag[0].data, atempo->window * atempo->stride);
286 RE_MALLOC_OR_FAIL(atempo->frag[1].data, atempo->window * atempo->stride);
287 RE_MALLOC_OR_FAIL(atempo->frag[0].xdat, atempo->window * sizeof(FFTComplex));
288 RE_MALLOC_OR_FAIL(atempo->frag[1].xdat, atempo->window * sizeof(FFTComplex));
290 // initialize rDFT contexts:
291 av_rdft_end(atempo->real_to_complex);
292 atempo->real_to_complex = NULL;
294 av_rdft_end(atempo->complex_to_real);
295 atempo->complex_to_real = NULL;
297 atempo->real_to_complex = av_rdft_init(nlevels + 1, DFT_R2C);
298 if (!atempo->real_to_complex) {
299 yae_release_buffers(atempo);
300 return AVERROR(ENOMEM);
303 atempo->complex_to_real = av_rdft_init(nlevels + 1, IDFT_C2R);
304 if (!atempo->complex_to_real) {
305 yae_release_buffers(atempo);
306 return AVERROR(ENOMEM);
309 RE_MALLOC_OR_FAIL(atempo->correlation, atempo->window * sizeof(FFTComplex));
311 atempo->ring = atempo->window * 3;
312 RE_MALLOC_OR_FAIL(atempo->buffer, atempo->ring * atempo->stride);
314 // initialize the Hann window function:
315 RE_MALLOC_OR_FAIL(atempo->hann, atempo->window * sizeof(float));
317 for (i = 0; i < atempo->window; i++) {
318 double t = (double)i / (double)(atempo->window - 1);
319 double h = 0.5 * (1.0 - cos(2.0 * M_PI * t));
320 atempo->hann[i] = (float)h;
327 static int yae_set_tempo(AVFilterContext *ctx, const char *arg_tempo)
329 const AudioFragment *prev;
330 ATempoContext *atempo = ctx->priv;
332 double tempo = av_strtod(arg_tempo, &tail);
335 av_log(ctx, AV_LOG_ERROR, "Invalid tempo value '%s'\n", arg_tempo);
336 return AVERROR(EINVAL);
339 if (tempo < YAE_ATEMPO_MIN || tempo > YAE_ATEMPO_MAX) {
340 av_log(ctx, AV_LOG_ERROR, "Tempo value %f exceeds [%f, %f] range\n",
341 tempo, YAE_ATEMPO_MIN, YAE_ATEMPO_MAX);
342 return AVERROR(EINVAL);
345 prev = yae_prev_frag(atempo);
346 atempo->origin[0] = prev->position[0] + atempo->window / 2;
347 atempo->origin[1] = prev->position[1] + atempo->window / 2;
348 atempo->tempo = tempo;
353 * A helper macro for initializing complex data buffer with scalar data
356 #define yae_init_xdat(scalar_type, scalar_max) \
358 const uint8_t *src_end = src + \
359 frag->nsamples * atempo->channels * sizeof(scalar_type); \
361 FFTSample *xdat = frag->xdat; \
364 if (atempo->channels == 1) { \
365 for (; src < src_end; xdat++) { \
366 tmp = *(const scalar_type *)src; \
367 src += sizeof(scalar_type); \
369 *xdat = (FFTSample)tmp; \
372 FFTSample s, max, ti, si; \
375 for (; src < src_end; xdat++) { \
376 tmp = *(const scalar_type *)src; \
377 src += sizeof(scalar_type); \
379 max = (FFTSample)tmp; \
380 s = FFMIN((FFTSample)scalar_max, \
381 (FFTSample)fabsf(max)); \
383 for (i = 1; i < atempo->channels; i++) { \
384 tmp = *(const scalar_type *)src; \
385 src += sizeof(scalar_type); \
387 ti = (FFTSample)tmp; \
388 si = FFMIN((FFTSample)scalar_max, \
389 (FFTSample)fabsf(ti)); \
403 * Initialize complex data buffer of a given audio fragment
404 * with down-mixed mono data of appropriate scalar type.
406 static void yae_downmix(ATempoContext *atempo, AudioFragment *frag)
409 const uint8_t *src = frag->data;
411 // init complex data buffer used for FFT and Correlation:
412 memset(frag->xdat, 0, sizeof(FFTComplex) * atempo->window);
414 if (atempo->format == AV_SAMPLE_FMT_U8) {
415 yae_init_xdat(uint8_t, 127);
416 } else if (atempo->format == AV_SAMPLE_FMT_S16) {
417 yae_init_xdat(int16_t, 32767);
418 } else if (atempo->format == AV_SAMPLE_FMT_S32) {
419 yae_init_xdat(int, 2147483647);
420 } else if (atempo->format == AV_SAMPLE_FMT_FLT) {
421 yae_init_xdat(float, 1);
422 } else if (atempo->format == AV_SAMPLE_FMT_DBL) {
423 yae_init_xdat(double, 1);
428 * Populate the internal data buffer on as-needed basis.
431 * 0 if requested data was already available or was successfully loaded,
432 * AVERROR(EAGAIN) if more input data is required.
434 static int yae_load_data(ATempoContext *atempo,
435 const uint8_t **src_ref,
436 const uint8_t *src_end,
440 const uint8_t *src = *src_ref;
441 const int read_size = stop_here - atempo->position[0];
443 if (stop_here <= atempo->position[0]) {
447 // samples are not expected to be skipped, unless tempo is greater than 2:
448 av_assert0(read_size <= atempo->ring || atempo->tempo > 2.0);
450 while (atempo->position[0] < stop_here && src < src_end) {
451 int src_samples = (src_end - src) / atempo->stride;
453 // load data piece-wise, in order to avoid complicating the logic:
454 int nsamples = FFMIN(read_size, src_samples);
458 nsamples = FFMIN(nsamples, atempo->ring);
459 na = FFMIN(nsamples, atempo->ring - atempo->tail);
460 nb = FFMIN(nsamples - na, atempo->ring);
463 uint8_t *a = atempo->buffer + atempo->tail * atempo->stride;
464 memcpy(a, src, na * atempo->stride);
466 src += na * atempo->stride;
467 atempo->position[0] += na;
469 atempo->size = FFMIN(atempo->size + na, atempo->ring);
470 atempo->tail = (atempo->tail + na) % atempo->ring;
472 atempo->size < atempo->ring ?
473 atempo->tail - atempo->size :
478 uint8_t *b = atempo->buffer;
479 memcpy(b, src, nb * atempo->stride);
481 src += nb * atempo->stride;
482 atempo->position[0] += nb;
484 atempo->size = FFMIN(atempo->size + nb, atempo->ring);
485 atempo->tail = (atempo->tail + nb) % atempo->ring;
487 atempo->size < atempo->ring ?
488 atempo->tail - atempo->size :
493 // pass back the updated source buffer pointer:
497 av_assert0(atempo->position[0] <= stop_here);
499 return atempo->position[0] == stop_here ? 0 : AVERROR(EAGAIN);
503 * Populate current audio fragment data buffer.
506 * 0 when the fragment is ready,
507 * AVERROR(EAGAIN) if more input data is required.
509 static int yae_load_frag(ATempoContext *atempo,
510 const uint8_t **src_ref,
511 const uint8_t *src_end)
514 AudioFragment *frag = yae_curr_frag(atempo);
516 int64_t missing, start, zeros;
518 const uint8_t *a, *b;
519 int i0, i1, n0, n1, na, nb;
521 int64_t stop_here = frag->position[0] + atempo->window;
522 if (src_ref && yae_load_data(atempo, src_ref, src_end, stop_here) != 0) {
523 return AVERROR(EAGAIN);
526 // calculate the number of samples we don't have:
528 stop_here > atempo->position[0] ?
529 stop_here - atempo->position[0] : 0;
532 missing < (int64_t)atempo->window ?
533 (uint32_t)(atempo->window - missing) : 0;
535 // setup the output buffer:
536 frag->nsamples = nsamples;
539 start = atempo->position[0] - atempo->size;
542 if (frag->position[0] < start) {
543 // what we don't have we substitute with zeros:
544 zeros = FFMIN(start - frag->position[0], (int64_t)nsamples);
545 av_assert0(zeros != nsamples);
547 memset(dst, 0, zeros * atempo->stride);
548 dst += zeros * atempo->stride;
551 if (zeros == nsamples) {
555 // get the remaining data from the ring buffer:
556 na = (atempo->head < atempo->tail ?
557 atempo->tail - atempo->head :
558 atempo->ring - atempo->head);
560 nb = atempo->head < atempo->tail ? 0 : atempo->tail;
563 av_assert0(nsamples <= zeros + na + nb);
565 a = atempo->buffer + atempo->head * atempo->stride;
568 i0 = frag->position[0] + zeros - start;
569 i1 = i0 < na ? 0 : i0 - na;
571 n0 = i0 < na ? FFMIN(na - i0, (int)(nsamples - zeros)) : 0;
572 n1 = nsamples - zeros - n0;
575 memcpy(dst, a + i0 * atempo->stride, n0 * atempo->stride);
576 dst += n0 * atempo->stride;
580 memcpy(dst, b + i1 * atempo->stride, n1 * atempo->stride);
587 * Prepare for loading next audio fragment.
589 static void yae_advance_to_next_frag(ATempoContext *atempo)
591 const double fragment_step = atempo->tempo * (double)(atempo->window / 2);
593 const AudioFragment *prev;
597 prev = yae_prev_frag(atempo);
598 frag = yae_curr_frag(atempo);
600 frag->position[0] = prev->position[0] + (int64_t)fragment_step;
601 frag->position[1] = prev->position[1] + atempo->window / 2;
606 * Calculate cross-correlation via rDFT.
608 * Multiply two vectors of complex numbers (result of real_to_complex rDFT)
609 * and transform back via complex_to_real rDFT.
611 static void yae_xcorr_via_rdft(FFTSample *xcorr,
612 RDFTContext *complex_to_real,
613 const FFTComplex *xa,
614 const FFTComplex *xb,
617 FFTComplex *xc = (FFTComplex *)xcorr;
620 // NOTE: first element requires special care -- Given Y = rDFT(X),
621 // Im(Y[0]) and Im(Y[N/2]) are always zero, therefore av_rdft_calc
622 // stores Re(Y[N/2]) in place of Im(Y[0]).
624 xc->re = xa->re * xb->re;
625 xc->im = xa->im * xb->im;
630 for (i = 1; i < window; i++, xa++, xb++, xc++) {
631 xc->re = (xa->re * xb->re + xa->im * xb->im);
632 xc->im = (xa->im * xb->re - xa->re * xb->im);
635 // apply inverse rDFT:
636 av_rdft_calc(complex_to_real, xcorr);
640 * Calculate alignment offset for given fragment
641 * relative to the previous fragment.
643 * @return alignment offset of current fragment relative to previous.
645 static int yae_align(AudioFragment *frag,
646 const AudioFragment *prev,
650 FFTSample *correlation,
651 RDFTContext *complex_to_real)
653 int best_offset = -drift;
654 FFTSample best_metric = -FLT_MAX;
661 yae_xcorr_via_rdft(correlation,
663 (const FFTComplex *)prev->xdat,
664 (const FFTComplex *)frag->xdat,
667 // identify search window boundaries:
668 i0 = FFMAX(window / 2 - delta_max - drift, 0);
669 i0 = FFMIN(i0, window);
671 i1 = FFMIN(window / 2 + delta_max - drift, window - window / 16);
674 // identify cross-correlation peaks within search window:
675 xcorr = correlation + i0;
677 for (i = i0; i < i1; i++, xcorr++) {
678 FFTSample metric = *xcorr;
681 FFTSample drifti = (FFTSample)(drift + i);
682 metric *= drifti * (FFTSample)(i - i0) * (FFTSample)(i1 - i);
684 if (metric > best_metric) {
685 best_metric = metric;
686 best_offset = i - window / 2;
694 * Adjust current fragment position for better alignment
695 * with previous fragment.
697 * @return alignment correction.
699 static int yae_adjust_position(ATempoContext *atempo)
701 const AudioFragment *prev = yae_prev_frag(atempo);
702 AudioFragment *frag = yae_curr_frag(atempo);
704 const double prev_output_position =
705 (double)(prev->position[1] - atempo->origin[1] + atempo->window / 2) *
708 const double ideal_output_position =
709 (double)(prev->position[0] - atempo->origin[0] + atempo->window / 2);
711 const int drift = (int)(prev_output_position - ideal_output_position);
713 const int delta_max = atempo->window / 2;
714 const int correction = yae_align(frag,
720 atempo->complex_to_real);
723 // adjust fragment position:
724 frag->position[0] -= correction;
726 // clear so that the fragment can be reloaded:
734 * A helper macro for blending the overlap region of previous
735 * and current audio fragment.
737 #define yae_blend(scalar_type) \
739 const scalar_type *aaa = (const scalar_type *)a; \
740 const scalar_type *bbb = (const scalar_type *)b; \
742 scalar_type *out = (scalar_type *)dst; \
743 scalar_type *out_end = (scalar_type *)dst_end; \
746 for (i = 0; i < overlap && out < out_end; \
747 i++, atempo->position[1]++, wa++, wb++) { \
752 for (j = 0; j < atempo->channels; \
753 j++, aaa++, bbb++, out++) { \
754 float t0 = (float)*aaa; \
755 float t1 = (float)*bbb; \
758 frag->position[0] + i < 0 ? \
760 (scalar_type)(t0 * w0 + t1 * w1); \
763 dst = (uint8_t *)out; \
767 * Blend the overlap region of previous and current audio fragment
768 * and output the results to the given destination buffer.
771 * 0 if the overlap region was completely stored in the dst buffer,
772 * AVERROR(EAGAIN) if more destination buffer space is required.
774 static int yae_overlap_add(ATempoContext *atempo,
779 const AudioFragment *prev = yae_prev_frag(atempo);
780 const AudioFragment *frag = yae_curr_frag(atempo);
782 const int64_t start_here = FFMAX(atempo->position[1],
785 const int64_t stop_here = FFMIN(prev->position[1] + prev->nsamples,
786 frag->position[1] + frag->nsamples);
788 const int64_t overlap = stop_here - start_here;
790 const int64_t ia = start_here - prev->position[1];
791 const int64_t ib = start_here - frag->position[1];
793 const float *wa = atempo->hann + ia;
794 const float *wb = atempo->hann + ib;
796 const uint8_t *a = prev->data + ia * atempo->stride;
797 const uint8_t *b = frag->data + ib * atempo->stride;
799 uint8_t *dst = *dst_ref;
801 av_assert0(start_here <= stop_here &&
802 frag->position[1] <= start_here &&
803 overlap <= frag->nsamples);
805 if (atempo->format == AV_SAMPLE_FMT_U8) {
807 } else if (atempo->format == AV_SAMPLE_FMT_S16) {
809 } else if (atempo->format == AV_SAMPLE_FMT_S32) {
811 } else if (atempo->format == AV_SAMPLE_FMT_FLT) {
813 } else if (atempo->format == AV_SAMPLE_FMT_DBL) {
817 // pass-back the updated destination buffer pointer:
820 return atempo->position[1] == stop_here ? 0 : AVERROR(EAGAIN);
824 * Feed as much data to the filter as it is able to consume
825 * and receive as much processed data in the destination buffer
826 * as it is able to produce or store.
829 yae_apply(ATempoContext *atempo,
830 const uint8_t **src_ref,
831 const uint8_t *src_end,
836 if (atempo->state == YAE_LOAD_FRAGMENT) {
837 // load additional data for the current fragment:
838 if (yae_load_frag(atempo, src_ref, src_end) != 0) {
843 yae_downmix(atempo, yae_curr_frag(atempo));
846 av_rdft_calc(atempo->real_to_complex, yae_curr_frag(atempo)->xdat);
848 // must load the second fragment before alignment can start:
849 if (!atempo->nfrag) {
850 yae_advance_to_next_frag(atempo);
854 atempo->state = YAE_ADJUST_POSITION;
857 if (atempo->state == YAE_ADJUST_POSITION) {
858 // adjust position for better alignment:
859 if (yae_adjust_position(atempo)) {
860 // reload the fragment at the corrected position, so that the
861 // Hann window blending would not require normalization:
862 atempo->state = YAE_RELOAD_FRAGMENT;
864 atempo->state = YAE_OUTPUT_OVERLAP_ADD;
868 if (atempo->state == YAE_RELOAD_FRAGMENT) {
869 // load additional data if necessary due to position adjustment:
870 if (yae_load_frag(atempo, src_ref, src_end) != 0) {
875 yae_downmix(atempo, yae_curr_frag(atempo));
878 av_rdft_calc(atempo->real_to_complex, yae_curr_frag(atempo)->xdat);
880 atempo->state = YAE_OUTPUT_OVERLAP_ADD;
883 if (atempo->state == YAE_OUTPUT_OVERLAP_ADD) {
884 // overlap-add and output the result:
885 if (yae_overlap_add(atempo, dst_ref, dst_end) != 0) {
889 // advance to the next fragment, repeat:
890 yae_advance_to_next_frag(atempo);
891 atempo->state = YAE_LOAD_FRAGMENT;
897 * Flush any buffered data from the filter.
900 * 0 if all data was completely stored in the dst buffer,
901 * AVERROR(EAGAIN) if more destination buffer space is required.
903 static int yae_flush(ATempoContext *atempo,
907 AudioFragment *frag = yae_curr_frag(atempo);
920 atempo->state = YAE_FLUSH_OUTPUT;
922 if (!atempo->nfrag) {
923 // there is nothing to flush:
927 if (atempo->position[0] == frag->position[0] + frag->nsamples &&
928 atempo->position[1] == frag->position[1] + frag->nsamples) {
929 // the current fragment is already flushed:
933 if (frag->position[0] + frag->nsamples < atempo->position[0]) {
934 // finish loading the current (possibly partial) fragment:
935 yae_load_frag(atempo, NULL, NULL);
939 yae_downmix(atempo, frag);
942 av_rdft_calc(atempo->real_to_complex, frag->xdat);
944 // align current fragment to previous fragment:
945 if (yae_adjust_position(atempo)) {
946 // reload the current fragment due to adjusted position:
947 yae_load_frag(atempo, NULL, NULL);
952 // flush the overlap region:
953 overlap_end = frag->position[1] + FFMIN(atempo->window / 2,
956 while (atempo->position[1] < overlap_end) {
957 if (yae_overlap_add(atempo, dst_ref, dst_end) != 0) {
958 return AVERROR(EAGAIN);
962 // check whether all of the input samples have been consumed:
963 if (frag->position[0] + frag->nsamples < atempo->position[0]) {
964 yae_advance_to_next_frag(atempo);
965 return AVERROR(EAGAIN);
968 // flush the remainder of the current fragment:
969 start_here = FFMAX(atempo->position[1], overlap_end);
970 stop_here = frag->position[1] + frag->nsamples;
971 offset = start_here - frag->position[1];
972 av_assert0(start_here <= stop_here && frag->position[1] <= start_here);
974 src = frag->data + offset * atempo->stride;
975 dst = (uint8_t *)*dst_ref;
977 src_size = (int)(stop_here - start_here) * atempo->stride;
978 dst_size = dst_end - dst;
979 nbytes = FFMIN(src_size, dst_size);
981 memcpy(dst, src, nbytes);
984 atempo->position[1] += (nbytes / atempo->stride);
986 // pass-back the updated destination buffer pointer:
987 *dst_ref = (uint8_t *)dst;
989 return atempo->position[1] == stop_here ? 0 : AVERROR(EAGAIN);
992 static av_cold int init(AVFilterContext *ctx)
994 ATempoContext *atempo = ctx->priv;
995 atempo->format = AV_SAMPLE_FMT_NONE;
996 atempo->state = YAE_LOAD_FRAGMENT;
1000 static av_cold void uninit(AVFilterContext *ctx)
1002 ATempoContext *atempo = ctx->priv;
1003 yae_release_buffers(atempo);
1006 static int query_formats(AVFilterContext *ctx)
1008 AVFilterChannelLayouts *layouts = NULL;
1009 AVFilterFormats *formats = NULL;
1011 // WSOLA necessitates an internal sliding window ring buffer
1012 // for incoming audio stream.
1014 // Planar sample formats are too cumbersome to store in a ring buffer,
1015 // therefore planar sample formats are not supported.
1017 static const enum AVSampleFormat sample_fmts[] = {
1027 layouts = ff_all_channel_counts();
1029 return AVERROR(ENOMEM);
1031 ret = ff_set_common_channel_layouts(ctx, layouts);
1035 formats = ff_make_format_list(sample_fmts);
1037 return AVERROR(ENOMEM);
1039 ret = ff_set_common_formats(ctx, formats);
1043 formats = ff_all_samplerates();
1045 return AVERROR(ENOMEM);
1047 return ff_set_common_samplerates(ctx, formats);
1050 static int config_props(AVFilterLink *inlink)
1052 AVFilterContext *ctx = inlink->dst;
1053 ATempoContext *atempo = ctx->priv;
1055 enum AVSampleFormat format = inlink->format;
1056 int sample_rate = (int)inlink->sample_rate;
1058 return yae_reset(atempo, format, sample_rate, inlink->channels);
1061 static int push_samples(ATempoContext *atempo,
1062 AVFilterLink *outlink,
1067 atempo->dst_buffer->sample_rate = outlink->sample_rate;
1068 atempo->dst_buffer->nb_samples = n_out;
1071 atempo->dst_buffer->pts =
1072 av_rescale_q(atempo->nsamples_out,
1073 (AVRational){ 1, outlink->sample_rate },
1074 outlink->time_base);
1076 ret = ff_filter_frame(outlink, atempo->dst_buffer);
1077 atempo->dst_buffer = NULL;
1079 atempo->dst_end = NULL;
1083 atempo->nsamples_out += n_out;
1087 static int filter_frame(AVFilterLink *inlink, AVFrame *src_buffer)
1089 AVFilterContext *ctx = inlink->dst;
1090 ATempoContext *atempo = ctx->priv;
1091 AVFilterLink *outlink = ctx->outputs[0];
1094 int n_in = src_buffer->nb_samples;
1095 int n_out = (int)(0.5 + ((double)n_in) / atempo->tempo);
1097 const uint8_t *src = src_buffer->data[0];
1098 const uint8_t *src_end = src + n_in * atempo->stride;
1100 while (src < src_end) {
1101 if (!atempo->dst_buffer) {
1102 atempo->dst_buffer = ff_get_audio_buffer(outlink, n_out);
1103 if (!atempo->dst_buffer) {
1104 av_frame_free(&src_buffer);
1105 return AVERROR(ENOMEM);
1107 av_frame_copy_props(atempo->dst_buffer, src_buffer);
1109 atempo->dst = atempo->dst_buffer->data[0];
1110 atempo->dst_end = atempo->dst + n_out * atempo->stride;
1113 yae_apply(atempo, &src, src_end, &atempo->dst, atempo->dst_end);
1115 if (atempo->dst == atempo->dst_end) {
1116 int n_samples = ((atempo->dst - atempo->dst_buffer->data[0]) /
1118 ret = push_samples(atempo, outlink, n_samples);
1124 atempo->nsamples_in += n_in;
1126 av_frame_free(&src_buffer);
1130 static int request_frame(AVFilterLink *outlink)
1132 AVFilterContext *ctx = outlink->src;
1133 ATempoContext *atempo = ctx->priv;
1136 ret = ff_request_frame(ctx->inputs[0]);
1138 if (ret == AVERROR_EOF) {
1139 // flush the filter:
1140 int n_max = atempo->ring;
1142 int err = AVERROR(EAGAIN);
1144 while (err == AVERROR(EAGAIN)) {
1145 if (!atempo->dst_buffer) {
1146 atempo->dst_buffer = ff_get_audio_buffer(outlink, n_max);
1147 if (!atempo->dst_buffer)
1148 return AVERROR(ENOMEM);
1150 atempo->dst = atempo->dst_buffer->data[0];
1151 atempo->dst_end = atempo->dst + n_max * atempo->stride;
1154 err = yae_flush(atempo, &atempo->dst, atempo->dst_end);
1156 n_out = ((atempo->dst - atempo->dst_buffer->data[0]) /
1160 ret = push_samples(atempo, outlink, n_out);
1166 av_frame_free(&atempo->dst_buffer);
1168 atempo->dst_end = NULL;
1176 static int process_command(AVFilterContext *ctx,
1183 return !strcmp(cmd, "tempo") ? yae_set_tempo(ctx, arg) : AVERROR(ENOSYS);
1186 static const AVFilterPad atempo_inputs[] = {
1189 .type = AVMEDIA_TYPE_AUDIO,
1190 .filter_frame = filter_frame,
1191 .config_props = config_props,
1196 static const AVFilterPad atempo_outputs[] = {
1199 .request_frame = request_frame,
1200 .type = AVMEDIA_TYPE_AUDIO,
1205 AVFilter ff_af_atempo = {
1207 .description = NULL_IF_CONFIG_SMALL("Adjust audio tempo."),
1210 .query_formats = query_formats,
1211 .process_command = process_command,
1212 .priv_size = sizeof(ATempoContext),
1213 .priv_class = &atempo_class,
1214 .inputs = atempo_inputs,
1215 .outputs = atempo_outputs,