You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1161 lines
37KB

  1. /*
  2. * Copyright (c) 2012 Pavel Koshevoy <pkoshevoy at gmail dot com>
  3. *
  4. * This file is part of FFmpeg.
  5. *
  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.
  10. *
  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.
  15. *
  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
  19. */
  20. /**
  21. * @file
  22. * tempo scaling audio filter -- an implementation of WSOLA algorithm
  23. *
  24. * Based on MIT licensed yaeAudioTempoFilter.h and yaeAudioFragment.h
  25. * from Apprentice Video player by Pavel Koshevoy.
  26. * https://sourceforge.net/projects/apprenticevideo/
  27. *
  28. * An explanation of SOLA algorithm is available at
  29. * http://www.surina.net/article/time-and-pitch-scaling.html
  30. *
  31. * WSOLA is very similar to SOLA, only one major difference exists between
  32. * these algorithms. SOLA shifts audio fragments along the output stream,
  33. * where as WSOLA shifts audio fragments along the input stream.
  34. *
  35. * The advantage of WSOLA algorithm is that the overlap region size is
  36. * always the same, therefore the blending function is constant and
  37. * can be precomputed.
  38. */
  39. #include <float.h>
  40. #include "libavcodec/avfft.h"
  41. #include "libavutil/avassert.h"
  42. #include "libavutil/avstring.h"
  43. #include "libavutil/eval.h"
  44. #include "libavutil/opt.h"
  45. #include "libavutil/samplefmt.h"
  46. #include "avfilter.h"
  47. #include "audio.h"
  48. #include "internal.h"
  49. /**
  50. * A fragment of audio waveform
  51. */
  52. typedef struct {
  53. // index of the first sample of this fragment in the overall waveform;
  54. // 0: input sample position
  55. // 1: output sample position
  56. int64_t position[2];
  57. // original packed multi-channel samples:
  58. uint8_t *data;
  59. // number of samples in this fragment:
  60. int nsamples;
  61. // rDFT transform of the down-mixed mono fragment, used for
  62. // fast waveform alignment via correlation in frequency domain:
  63. FFTSample *xdat;
  64. } AudioFragment;
  65. /**
  66. * Filter state machine states
  67. */
  68. typedef enum {
  69. YAE_LOAD_FRAGMENT,
  70. YAE_ADJUST_POSITION,
  71. YAE_RELOAD_FRAGMENT,
  72. YAE_OUTPUT_OVERLAP_ADD,
  73. YAE_FLUSH_OUTPUT,
  74. } FilterState;
  75. /**
  76. * Filter state machine
  77. */
  78. typedef struct {
  79. // ring-buffer of input samples, necessary because some times
  80. // input fragment position may be adjusted backwards:
  81. uint8_t *buffer;
  82. // ring-buffer maximum capacity, expressed in sample rate time base:
  83. int ring;
  84. // ring-buffer house keeping:
  85. int size;
  86. int head;
  87. int tail;
  88. // 0: input sample position corresponding to the ring buffer tail
  89. // 1: output sample position
  90. int64_t position[2];
  91. // sample format:
  92. enum AVSampleFormat format;
  93. // number of channels:
  94. int channels;
  95. // row of bytes to skip from one sample to next, across multple channels;
  96. // stride = (number-of-channels * bits-per-sample-per-channel) / 8
  97. int stride;
  98. // fragment window size, power-of-two integer:
  99. int window;
  100. // Hann window coefficients, for feathering
  101. // (blending) the overlapping fragment region:
  102. float *hann;
  103. // tempo scaling factor:
  104. double tempo;
  105. // cumulative alignment drift:
  106. int drift;
  107. // current/previous fragment ring-buffer:
  108. AudioFragment frag[2];
  109. // current fragment index:
  110. uint64_t nfrag;
  111. // current state:
  112. FilterState state;
  113. // for fast correlation calculation in frequency domain:
  114. RDFTContext *real_to_complex;
  115. RDFTContext *complex_to_real;
  116. FFTSample *correlation;
  117. // for managing AVFilterPad.request_frame and AVFilterPad.filter_samples
  118. int request_fulfilled;
  119. AVFilterBufferRef *dst_buffer;
  120. uint8_t *dst;
  121. uint8_t *dst_end;
  122. uint64_t nsamples_in;
  123. uint64_t nsamples_out;
  124. } ATempoContext;
  125. /**
  126. * Reset filter to initial state, do not deallocate existing local buffers.
  127. */
  128. static void yae_clear(ATempoContext *atempo)
  129. {
  130. atempo->size = 0;
  131. atempo->head = 0;
  132. atempo->tail = 0;
  133. atempo->drift = 0;
  134. atempo->nfrag = 0;
  135. atempo->state = YAE_LOAD_FRAGMENT;
  136. atempo->position[0] = 0;
  137. atempo->position[1] = 0;
  138. atempo->frag[0].position[0] = 0;
  139. atempo->frag[0].position[1] = 0;
  140. atempo->frag[0].nsamples = 0;
  141. atempo->frag[1].position[0] = 0;
  142. atempo->frag[1].position[1] = 0;
  143. atempo->frag[1].nsamples = 0;
  144. // shift left position of 1st fragment by half a window
  145. // so that no re-normalization would be required for
  146. // the left half of the 1st fragment:
  147. atempo->frag[0].position[0] = -(int64_t)(atempo->window / 2);
  148. atempo->frag[0].position[1] = -(int64_t)(atempo->window / 2);
  149. avfilter_unref_bufferp(&atempo->dst_buffer);
  150. atempo->dst = NULL;
  151. atempo->dst_end = NULL;
  152. atempo->request_fulfilled = 0;
  153. atempo->nsamples_in = 0;
  154. atempo->nsamples_out = 0;
  155. }
  156. /**
  157. * Reset filter to initial state and deallocate all buffers.
  158. */
  159. static void yae_release_buffers(ATempoContext *atempo)
  160. {
  161. yae_clear(atempo);
  162. av_freep(&atempo->frag[0].data);
  163. av_freep(&atempo->frag[1].data);
  164. av_freep(&atempo->frag[0].xdat);
  165. av_freep(&atempo->frag[1].xdat);
  166. av_freep(&atempo->buffer);
  167. av_freep(&atempo->hann);
  168. av_freep(&atempo->correlation);
  169. av_rdft_end(atempo->real_to_complex);
  170. atempo->real_to_complex = NULL;
  171. av_rdft_end(atempo->complex_to_real);
  172. atempo->complex_to_real = NULL;
  173. }
  174. #define REALLOC_OR_FAIL(field, field_size) \
  175. do { \
  176. void * new_field = av_realloc(field, (field_size)); \
  177. if (!new_field) { \
  178. yae_release_buffers(atempo); \
  179. return AVERROR(ENOMEM); \
  180. } \
  181. field = new_field; \
  182. } while (0)
  183. /**
  184. * Prepare filter for processing audio data of given format,
  185. * sample rate and number of channels.
  186. */
  187. static int yae_reset(ATempoContext *atempo,
  188. enum AVSampleFormat format,
  189. int sample_rate,
  190. int channels)
  191. {
  192. const int sample_size = av_get_bytes_per_sample(format);
  193. uint32_t nlevels = 0;
  194. uint32_t pot;
  195. int i;
  196. atempo->format = format;
  197. atempo->channels = channels;
  198. atempo->stride = sample_size * channels;
  199. // pick a segment window size:
  200. atempo->window = sample_rate / 24;
  201. // adjust window size to be a power-of-two integer:
  202. nlevels = av_log2(atempo->window);
  203. pot = 1 << nlevels;
  204. av_assert0(pot <= atempo->window);
  205. if (pot < atempo->window) {
  206. atempo->window = pot * 2;
  207. nlevels++;
  208. }
  209. // initialize audio fragment buffers:
  210. REALLOC_OR_FAIL(atempo->frag[0].data, atempo->window * atempo->stride);
  211. REALLOC_OR_FAIL(atempo->frag[1].data, atempo->window * atempo->stride);
  212. REALLOC_OR_FAIL(atempo->frag[0].xdat, atempo->window * sizeof(FFTComplex));
  213. REALLOC_OR_FAIL(atempo->frag[1].xdat, atempo->window * sizeof(FFTComplex));
  214. // initialize rDFT contexts:
  215. av_rdft_end(atempo->real_to_complex);
  216. atempo->real_to_complex = NULL;
  217. av_rdft_end(atempo->complex_to_real);
  218. atempo->complex_to_real = NULL;
  219. atempo->real_to_complex = av_rdft_init(nlevels + 1, DFT_R2C);
  220. if (!atempo->real_to_complex) {
  221. yae_release_buffers(atempo);
  222. return AVERROR(ENOMEM);
  223. }
  224. atempo->complex_to_real = av_rdft_init(nlevels + 1, IDFT_C2R);
  225. if (!atempo->complex_to_real) {
  226. yae_release_buffers(atempo);
  227. return AVERROR(ENOMEM);
  228. }
  229. REALLOC_OR_FAIL(atempo->correlation, atempo->window * sizeof(FFTComplex));
  230. atempo->ring = atempo->window * 3;
  231. REALLOC_OR_FAIL(atempo->buffer, atempo->ring * atempo->stride);
  232. // initialize the Hann window function:
  233. REALLOC_OR_FAIL(atempo->hann, atempo->window * sizeof(float));
  234. for (i = 0; i < atempo->window; i++) {
  235. double t = (double)i / (double)(atempo->window - 1);
  236. double h = 0.5 * (1.0 - cos(2.0 * M_PI * t));
  237. atempo->hann[i] = (float)h;
  238. }
  239. yae_clear(atempo);
  240. return 0;
  241. }
  242. static int yae_set_tempo(AVFilterContext *ctx, const char *arg_tempo)
  243. {
  244. ATempoContext *atempo = ctx->priv;
  245. char *tail = NULL;
  246. double tempo = av_strtod(arg_tempo, &tail);
  247. if (tail && *tail) {
  248. av_log(ctx, AV_LOG_ERROR, "Invalid tempo value '%s'\n", arg_tempo);
  249. return AVERROR(EINVAL);
  250. }
  251. if (tempo < 0.5 || tempo > 2.0) {
  252. av_log(ctx, AV_LOG_ERROR, "Tempo value %f exceeds [0.5, 2.0] range\n",
  253. tempo);
  254. return AVERROR(EINVAL);
  255. }
  256. atempo->tempo = tempo;
  257. return 0;
  258. }
  259. inline static AudioFragment *yae_curr_frag(ATempoContext *atempo)
  260. {
  261. return &atempo->frag[atempo->nfrag % 2];
  262. }
  263. inline static AudioFragment *yae_prev_frag(ATempoContext *atempo)
  264. {
  265. return &atempo->frag[(atempo->nfrag + 1) % 2];
  266. }
  267. /**
  268. * A helper macro for initializing complex data buffer with scalar data
  269. * of a given type.
  270. */
  271. #define yae_init_xdat(scalar_type, scalar_max) \
  272. do { \
  273. const uint8_t *src_end = src + \
  274. frag->nsamples * atempo->channels * sizeof(scalar_type); \
  275. \
  276. FFTSample *xdat = frag->xdat; \
  277. scalar_type tmp; \
  278. \
  279. if (atempo->channels == 1) { \
  280. for (; src < src_end; xdat++) { \
  281. tmp = *(const scalar_type *)src; \
  282. src += sizeof(scalar_type); \
  283. \
  284. *xdat = (FFTSample)tmp; \
  285. } \
  286. } else { \
  287. FFTSample s, max, ti, si; \
  288. int i; \
  289. \
  290. for (; src < src_end; xdat++) { \
  291. tmp = *(const scalar_type *)src; \
  292. src += sizeof(scalar_type); \
  293. \
  294. max = (FFTSample)tmp; \
  295. s = FFMIN((FFTSample)scalar_max, \
  296. (FFTSample)fabsf(max)); \
  297. \
  298. for (i = 1; i < atempo->channels; i++) { \
  299. tmp = *(const scalar_type *)src; \
  300. src += sizeof(scalar_type); \
  301. \
  302. ti = (FFTSample)tmp; \
  303. si = FFMIN((FFTSample)scalar_max, \
  304. (FFTSample)fabsf(ti)); \
  305. \
  306. if (s < si) { \
  307. s = si; \
  308. max = ti; \
  309. } \
  310. } \
  311. \
  312. *xdat = max; \
  313. } \
  314. } \
  315. } while (0)
  316. /**
  317. * Initialize complex data buffer of a given audio fragment
  318. * with down-mixed mono data of appropriate scalar type.
  319. */
  320. static void yae_downmix(ATempoContext *atempo, AudioFragment *frag)
  321. {
  322. // shortcuts:
  323. const uint8_t *src = frag->data;
  324. // init complex data buffer used for FFT and Correlation:
  325. memset(frag->xdat, 0, sizeof(FFTComplex) * atempo->window);
  326. if (atempo->format == AV_SAMPLE_FMT_U8) {
  327. yae_init_xdat(uint8_t, 127);
  328. } else if (atempo->format == AV_SAMPLE_FMT_S16) {
  329. yae_init_xdat(int16_t, 32767);
  330. } else if (atempo->format == AV_SAMPLE_FMT_S32) {
  331. yae_init_xdat(int, 2147483647);
  332. } else if (atempo->format == AV_SAMPLE_FMT_FLT) {
  333. yae_init_xdat(float, 1);
  334. } else if (atempo->format == AV_SAMPLE_FMT_DBL) {
  335. yae_init_xdat(double, 1);
  336. }
  337. }
  338. /**
  339. * Populate the internal data buffer on as-needed basis.
  340. *
  341. * @return
  342. * 0 if requested data was already available or was successfully loaded,
  343. * AVERROR(EAGAIN) if more input data is required.
  344. */
  345. static int yae_load_data(ATempoContext *atempo,
  346. const uint8_t **src_ref,
  347. const uint8_t *src_end,
  348. int64_t stop_here)
  349. {
  350. // shortcut:
  351. const uint8_t *src = *src_ref;
  352. const int read_size = stop_here - atempo->position[0];
  353. if (stop_here <= atempo->position[0]) {
  354. return 0;
  355. }
  356. // samples are not expected to be skipped:
  357. av_assert0(read_size <= atempo->ring);
  358. while (atempo->position[0] < stop_here && src < src_end) {
  359. int src_samples = (src_end - src) / atempo->stride;
  360. // load data piece-wise, in order to avoid complicating the logic:
  361. int nsamples = FFMIN(read_size, src_samples);
  362. int na;
  363. int nb;
  364. nsamples = FFMIN(nsamples, atempo->ring);
  365. na = FFMIN(nsamples, atempo->ring - atempo->tail);
  366. nb = FFMIN(nsamples - na, atempo->ring);
  367. if (na) {
  368. uint8_t *a = atempo->buffer + atempo->tail * atempo->stride;
  369. memcpy(a, src, na * atempo->stride);
  370. src += na * atempo->stride;
  371. atempo->position[0] += na;
  372. atempo->size = FFMIN(atempo->size + na, atempo->ring);
  373. atempo->tail = (atempo->tail + na) % atempo->ring;
  374. atempo->head =
  375. atempo->size < atempo->ring ?
  376. atempo->tail - atempo->size :
  377. atempo->tail;
  378. }
  379. if (nb) {
  380. uint8_t *b = atempo->buffer;
  381. memcpy(b, src, nb * atempo->stride);
  382. src += nb * atempo->stride;
  383. atempo->position[0] += nb;
  384. atempo->size = FFMIN(atempo->size + nb, atempo->ring);
  385. atempo->tail = (atempo->tail + nb) % atempo->ring;
  386. atempo->head =
  387. atempo->size < atempo->ring ?
  388. atempo->tail - atempo->size :
  389. atempo->tail;
  390. }
  391. }
  392. // pass back the updated source buffer pointer:
  393. *src_ref = src;
  394. // sanity check:
  395. av_assert0(atempo->position[0] <= stop_here);
  396. return atempo->position[0] == stop_here ? 0 : AVERROR(EAGAIN);
  397. }
  398. /**
  399. * Populate current audio fragment data buffer.
  400. *
  401. * @return
  402. * 0 when the fragment is ready,
  403. * AVERROR(EAGAIN) if more input data is required.
  404. */
  405. static int yae_load_frag(ATempoContext *atempo,
  406. const uint8_t **src_ref,
  407. const uint8_t *src_end)
  408. {
  409. // shortcuts:
  410. AudioFragment *frag = yae_curr_frag(atempo);
  411. uint8_t *dst;
  412. int64_t missing, start, zeros;
  413. uint32_t nsamples;
  414. const uint8_t *a, *b;
  415. int i0, i1, n0, n1, na, nb;
  416. int64_t stop_here = frag->position[0] + atempo->window;
  417. if (src_ref && yae_load_data(atempo, src_ref, src_end, stop_here) != 0) {
  418. return AVERROR(EAGAIN);
  419. }
  420. // calculate the number of samples we don't have:
  421. missing =
  422. stop_here > atempo->position[0] ?
  423. stop_here - atempo->position[0] : 0;
  424. nsamples =
  425. missing < (int64_t)atempo->window ?
  426. (uint32_t)(atempo->window - missing) : 0;
  427. // setup the output buffer:
  428. frag->nsamples = nsamples;
  429. dst = frag->data;
  430. start = atempo->position[0] - atempo->size;
  431. zeros = 0;
  432. if (frag->position[0] < start) {
  433. // what we don't have we substitute with zeros:
  434. zeros = FFMIN(start - frag->position[0], (int64_t)nsamples);
  435. av_assert0(zeros != nsamples);
  436. memset(dst, 0, zeros * atempo->stride);
  437. dst += zeros * atempo->stride;
  438. }
  439. if (zeros == nsamples) {
  440. return 0;
  441. }
  442. // get the remaining data from the ring buffer:
  443. na = (atempo->head < atempo->tail ?
  444. atempo->tail - atempo->head :
  445. atempo->ring - atempo->head);
  446. nb = atempo->head < atempo->tail ? 0 : atempo->tail;
  447. // sanity check:
  448. av_assert0(nsamples <= zeros + na + nb);
  449. a = atempo->buffer + atempo->head * atempo->stride;
  450. b = atempo->buffer;
  451. i0 = frag->position[0] + zeros - start;
  452. i1 = i0 < na ? 0 : i0 - na;
  453. n0 = i0 < na ? FFMIN(na - i0, (int)(nsamples - zeros)) : 0;
  454. n1 = nsamples - zeros - n0;
  455. if (n0) {
  456. memcpy(dst, a + i0 * atempo->stride, n0 * atempo->stride);
  457. dst += n0 * atempo->stride;
  458. }
  459. if (n1) {
  460. memcpy(dst, b + i1 * atempo->stride, n1 * atempo->stride);
  461. dst += n1 * atempo->stride;
  462. }
  463. return 0;
  464. }
  465. /**
  466. * Prepare for loading next audio fragment.
  467. */
  468. static void yae_advance_to_next_frag(ATempoContext *atempo)
  469. {
  470. const double fragment_step = atempo->tempo * (double)(atempo->window / 2);
  471. const AudioFragment *prev;
  472. AudioFragment *frag;
  473. atempo->nfrag++;
  474. prev = yae_prev_frag(atempo);
  475. frag = yae_curr_frag(atempo);
  476. frag->position[0] = prev->position[0] + (int64_t)fragment_step;
  477. frag->position[1] = prev->position[1] + atempo->window / 2;
  478. frag->nsamples = 0;
  479. }
  480. /**
  481. * Calculate cross-correlation via rDFT.
  482. *
  483. * Multiply two vectors of complex numbers (result of real_to_complex rDFT)
  484. * and transform back via complex_to_real rDFT.
  485. */
  486. static void yae_xcorr_via_rdft(FFTSample *xcorr,
  487. RDFTContext *complex_to_real,
  488. const FFTComplex *xa,
  489. const FFTComplex *xb,
  490. const int window)
  491. {
  492. FFTComplex *xc = (FFTComplex *)xcorr;
  493. int i;
  494. // NOTE: first element requires special care -- Given Y = rDFT(X),
  495. // Im(Y[0]) and Im(Y[N/2]) are always zero, therefore av_rdft_calc
  496. // stores Re(Y[N/2]) in place of Im(Y[0]).
  497. xc->re = xa->re * xb->re;
  498. xc->im = xa->im * xb->im;
  499. xa++;
  500. xb++;
  501. xc++;
  502. for (i = 1; i < window; i++, xa++, xb++, xc++) {
  503. xc->re = (xa->re * xb->re + xa->im * xb->im);
  504. xc->im = (xa->im * xb->re - xa->re * xb->im);
  505. }
  506. // apply inverse rDFT:
  507. av_rdft_calc(complex_to_real, xcorr);
  508. }
  509. /**
  510. * Calculate alignment offset for given fragment
  511. * relative to the previous fragment.
  512. *
  513. * @return alignment offset of current fragment relative to previous.
  514. */
  515. static int yae_align(AudioFragment *frag,
  516. const AudioFragment *prev,
  517. const int window,
  518. const int delta_max,
  519. const int drift,
  520. FFTSample *correlation,
  521. RDFTContext *complex_to_real)
  522. {
  523. int best_offset = -drift;
  524. FFTSample best_metric = -FLT_MAX;
  525. FFTSample *xcorr;
  526. int i0;
  527. int i1;
  528. int i;
  529. yae_xcorr_via_rdft(correlation,
  530. complex_to_real,
  531. (const FFTComplex *)prev->xdat,
  532. (const FFTComplex *)frag->xdat,
  533. window);
  534. // identify search window boundaries:
  535. i0 = FFMAX(window / 2 - delta_max - drift, 0);
  536. i0 = FFMIN(i0, window);
  537. i1 = FFMIN(window / 2 + delta_max - drift, window - window / 16);
  538. i1 = FFMAX(i1, 0);
  539. // identify cross-correlation peaks within search window:
  540. xcorr = correlation + i0;
  541. for (i = i0; i < i1; i++, xcorr++) {
  542. FFTSample metric = *xcorr;
  543. // normalize:
  544. FFTSample drifti = (FFTSample)(drift + i);
  545. metric *= drifti;
  546. if (metric > best_metric) {
  547. best_metric = metric;
  548. best_offset = i - window / 2;
  549. }
  550. }
  551. return best_offset;
  552. }
  553. /**
  554. * Adjust current fragment position for better alignment
  555. * with previous fragment.
  556. *
  557. * @return alignment correction.
  558. */
  559. static int yae_adjust_position(ATempoContext *atempo)
  560. {
  561. const AudioFragment *prev = yae_prev_frag(atempo);
  562. AudioFragment *frag = yae_curr_frag(atempo);
  563. const int delta_max = atempo->window / 2;
  564. const int correction = yae_align(frag,
  565. prev,
  566. atempo->window,
  567. delta_max,
  568. atempo->drift,
  569. atempo->correlation,
  570. atempo->complex_to_real);
  571. if (correction) {
  572. // adjust fragment position:
  573. frag->position[0] -= correction;
  574. // clear so that the fragment can be reloaded:
  575. frag->nsamples = 0;
  576. // update cumulative correction drift counter:
  577. atempo->drift += correction;
  578. }
  579. return correction;
  580. }
  581. /**
  582. * A helper macro for blending the overlap region of previous
  583. * and current audio fragment.
  584. */
  585. #define yae_blend(scalar_type) \
  586. do { \
  587. const scalar_type *aaa = (const scalar_type *)a; \
  588. const scalar_type *bbb = (const scalar_type *)b; \
  589. \
  590. scalar_type *out = (scalar_type *)dst; \
  591. scalar_type *out_end = (scalar_type *)dst_end; \
  592. int64_t i; \
  593. \
  594. for (i = 0; i < overlap && out < out_end; \
  595. i++, atempo->position[1]++, wa++, wb++) { \
  596. float w0 = *wa; \
  597. float w1 = *wb; \
  598. int j; \
  599. \
  600. for (j = 0; j < atempo->channels; \
  601. j++, aaa++, bbb++, out++) { \
  602. float t0 = (float)*aaa; \
  603. float t1 = (float)*bbb; \
  604. \
  605. *out = \
  606. frag->position[0] + i < 0 ? \
  607. *aaa : \
  608. (scalar_type)(t0 * w0 + t1 * w1); \
  609. } \
  610. } \
  611. dst = (uint8_t *)out; \
  612. } while (0)
  613. /**
  614. * Blend the overlap region of previous and current audio fragment
  615. * and output the results to the given destination buffer.
  616. *
  617. * @return
  618. * 0 if the overlap region was completely stored in the dst buffer,
  619. * AVERROR(EAGAIN) if more destination buffer space is required.
  620. */
  621. static int yae_overlap_add(ATempoContext *atempo,
  622. uint8_t **dst_ref,
  623. uint8_t *dst_end)
  624. {
  625. // shortcuts:
  626. const AudioFragment *prev = yae_prev_frag(atempo);
  627. const AudioFragment *frag = yae_curr_frag(atempo);
  628. const int64_t start_here = FFMAX(atempo->position[1],
  629. frag->position[1]);
  630. const int64_t stop_here = FFMIN(prev->position[1] + prev->nsamples,
  631. frag->position[1] + frag->nsamples);
  632. const int64_t overlap = stop_here - start_here;
  633. const int64_t ia = start_here - prev->position[1];
  634. const int64_t ib = start_here - frag->position[1];
  635. const float *wa = atempo->hann + ia;
  636. const float *wb = atempo->hann + ib;
  637. const uint8_t *a = prev->data + ia * atempo->stride;
  638. const uint8_t *b = frag->data + ib * atempo->stride;
  639. uint8_t *dst = *dst_ref;
  640. av_assert0(start_here <= stop_here &&
  641. frag->position[1] <= start_here &&
  642. overlap <= frag->nsamples);
  643. if (atempo->format == AV_SAMPLE_FMT_U8) {
  644. yae_blend(uint8_t);
  645. } else if (atempo->format == AV_SAMPLE_FMT_S16) {
  646. yae_blend(int16_t);
  647. } else if (atempo->format == AV_SAMPLE_FMT_S32) {
  648. yae_blend(int);
  649. } else if (atempo->format == AV_SAMPLE_FMT_FLT) {
  650. yae_blend(float);
  651. } else if (atempo->format == AV_SAMPLE_FMT_DBL) {
  652. yae_blend(double);
  653. }
  654. // pass-back the updated destination buffer pointer:
  655. *dst_ref = dst;
  656. return atempo->position[1] == stop_here ? 0 : AVERROR(EAGAIN);
  657. }
  658. /**
  659. * Feed as much data to the filter as it is able to consume
  660. * and receive as much processed data in the destination buffer
  661. * as it is able to produce or store.
  662. */
  663. static void
  664. yae_apply(ATempoContext *atempo,
  665. const uint8_t **src_ref,
  666. const uint8_t *src_end,
  667. uint8_t **dst_ref,
  668. uint8_t *dst_end)
  669. {
  670. while (1) {
  671. if (atempo->state == YAE_LOAD_FRAGMENT) {
  672. // load additional data for the current fragment:
  673. if (yae_load_frag(atempo, src_ref, src_end) != 0) {
  674. break;
  675. }
  676. // down-mix to mono:
  677. yae_downmix(atempo, yae_curr_frag(atempo));
  678. // apply rDFT:
  679. av_rdft_calc(atempo->real_to_complex, yae_curr_frag(atempo)->xdat);
  680. // must load the second fragment before alignment can start:
  681. if (!atempo->nfrag) {
  682. yae_advance_to_next_frag(atempo);
  683. continue;
  684. }
  685. atempo->state = YAE_ADJUST_POSITION;
  686. }
  687. if (atempo->state == YAE_ADJUST_POSITION) {
  688. // adjust position for better alignment:
  689. if (yae_adjust_position(atempo)) {
  690. // reload the fragment at the corrected position, so that the
  691. // Hann window blending would not require normalization:
  692. atempo->state = YAE_RELOAD_FRAGMENT;
  693. } else {
  694. atempo->state = YAE_OUTPUT_OVERLAP_ADD;
  695. }
  696. }
  697. if (atempo->state == YAE_RELOAD_FRAGMENT) {
  698. // load additional data if necessary due to position adjustment:
  699. if (yae_load_frag(atempo, src_ref, src_end) != 0) {
  700. break;
  701. }
  702. // down-mix to mono:
  703. yae_downmix(atempo, yae_curr_frag(atempo));
  704. // apply rDFT:
  705. av_rdft_calc(atempo->real_to_complex, yae_curr_frag(atempo)->xdat);
  706. atempo->state = YAE_OUTPUT_OVERLAP_ADD;
  707. }
  708. if (atempo->state == YAE_OUTPUT_OVERLAP_ADD) {
  709. // overlap-add and output the result:
  710. if (yae_overlap_add(atempo, dst_ref, dst_end) != 0) {
  711. break;
  712. }
  713. // advance to the next fragment, repeat:
  714. yae_advance_to_next_frag(atempo);
  715. atempo->state = YAE_LOAD_FRAGMENT;
  716. }
  717. }
  718. }
  719. /**
  720. * Flush any buffered data from the filter.
  721. *
  722. * @return
  723. * 0 if all data was completely stored in the dst buffer,
  724. * AVERROR(EAGAIN) if more destination buffer space is required.
  725. */
  726. static int yae_flush(ATempoContext *atempo,
  727. uint8_t **dst_ref,
  728. uint8_t *dst_end)
  729. {
  730. AudioFragment *frag = yae_curr_frag(atempo);
  731. int64_t overlap_end;
  732. int64_t start_here;
  733. int64_t stop_here;
  734. int64_t offset;
  735. const uint8_t *src;
  736. uint8_t *dst;
  737. int src_size;
  738. int dst_size;
  739. int nbytes;
  740. atempo->state = YAE_FLUSH_OUTPUT;
  741. if (atempo->position[0] == frag->position[0] + frag->nsamples &&
  742. atempo->position[1] == frag->position[1] + frag->nsamples) {
  743. // the current fragment is already flushed:
  744. return 0;
  745. }
  746. if (frag->position[0] + frag->nsamples < atempo->position[0]) {
  747. // finish loading the current (possibly partial) fragment:
  748. yae_load_frag(atempo, NULL, NULL);
  749. if (atempo->nfrag) {
  750. // down-mix to mono:
  751. yae_downmix(atempo, frag);
  752. // apply rDFT:
  753. av_rdft_calc(atempo->real_to_complex, frag->xdat);
  754. // align current fragment to previous fragment:
  755. if (yae_adjust_position(atempo)) {
  756. // reload the current fragment due to adjusted position:
  757. yae_load_frag(atempo, NULL, NULL);
  758. }
  759. }
  760. }
  761. // flush the overlap region:
  762. overlap_end = frag->position[1] + FFMIN(atempo->window / 2,
  763. frag->nsamples);
  764. while (atempo->position[1] < overlap_end) {
  765. if (yae_overlap_add(atempo, dst_ref, dst_end) != 0) {
  766. return AVERROR(EAGAIN);
  767. }
  768. }
  769. // flush the remaininder of the current fragment:
  770. start_here = FFMAX(atempo->position[1], overlap_end);
  771. stop_here = frag->position[1] + frag->nsamples;
  772. offset = start_here - frag->position[1];
  773. av_assert0(start_here <= stop_here && frag->position[1] <= start_here);
  774. src = frag->data + offset * atempo->stride;
  775. dst = (uint8_t *)*dst_ref;
  776. src_size = (int)(stop_here - start_here) * atempo->stride;
  777. dst_size = dst_end - dst;
  778. nbytes = FFMIN(src_size, dst_size);
  779. memcpy(dst, src, nbytes);
  780. dst += nbytes;
  781. atempo->position[1] += (nbytes / atempo->stride);
  782. // pass-back the updated destination buffer pointer:
  783. *dst_ref = (uint8_t *)dst;
  784. return atempo->position[1] == stop_here ? 0 : AVERROR(EAGAIN);
  785. }
  786. static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
  787. {
  788. ATempoContext *atempo = ctx->priv;
  789. // NOTE: this assumes that the caller has memset ctx->priv to 0:
  790. atempo->format = AV_SAMPLE_FMT_NONE;
  791. atempo->tempo = 1.0;
  792. atempo->state = YAE_LOAD_FRAGMENT;
  793. return args ? yae_set_tempo(ctx, args) : 0;
  794. }
  795. static av_cold void uninit(AVFilterContext *ctx)
  796. {
  797. ATempoContext *atempo = ctx->priv;
  798. yae_release_buffers(atempo);
  799. }
  800. static int query_formats(AVFilterContext *ctx)
  801. {
  802. AVFilterChannelLayouts *layouts = NULL;
  803. AVFilterFormats *formats = NULL;
  804. // WSOLA necessitates an internal sliding window ring buffer
  805. // for incoming audio stream.
  806. //
  807. // Planar sample formats are too cumbersome to store in a ring buffer,
  808. // therefore planar sample formats are not supported.
  809. //
  810. enum AVSampleFormat sample_fmts[] = {
  811. AV_SAMPLE_FMT_U8,
  812. AV_SAMPLE_FMT_S16,
  813. AV_SAMPLE_FMT_S32,
  814. AV_SAMPLE_FMT_FLT,
  815. AV_SAMPLE_FMT_DBL,
  816. AV_SAMPLE_FMT_NONE
  817. };
  818. layouts = ff_all_channel_layouts();
  819. if (!layouts) {
  820. return AVERROR(ENOMEM);
  821. }
  822. ff_set_common_channel_layouts(ctx, layouts);
  823. formats = ff_make_format_list(sample_fmts);
  824. if (!formats) {
  825. return AVERROR(ENOMEM);
  826. }
  827. ff_set_common_formats(ctx, formats);
  828. formats = ff_all_samplerates();
  829. if (!formats) {
  830. return AVERROR(ENOMEM);
  831. }
  832. ff_set_common_samplerates(ctx, formats);
  833. return 0;
  834. }
  835. static int config_props(AVFilterLink *inlink)
  836. {
  837. AVFilterContext *ctx = inlink->dst;
  838. ATempoContext *atempo = ctx->priv;
  839. enum AVSampleFormat format = inlink->format;
  840. int sample_rate = (int)inlink->sample_rate;
  841. int channels = av_get_channel_layout_nb_channels(inlink->channel_layout);
  842. return yae_reset(atempo, format, sample_rate, channels);
  843. }
  844. static void push_samples(ATempoContext *atempo,
  845. AVFilterLink *outlink,
  846. int n_out)
  847. {
  848. atempo->dst_buffer->audio->sample_rate = outlink->sample_rate;
  849. atempo->dst_buffer->audio->nb_samples = n_out;
  850. // adjust the PTS:
  851. atempo->dst_buffer->pts =
  852. av_rescale_q(atempo->nsamples_out,
  853. (AVRational){ 1, outlink->sample_rate },
  854. outlink->time_base);
  855. ff_filter_samples(outlink, atempo->dst_buffer);
  856. atempo->dst_buffer = NULL;
  857. atempo->dst = NULL;
  858. atempo->dst_end = NULL;
  859. atempo->nsamples_out += n_out;
  860. }
  861. static void filter_samples(AVFilterLink *inlink,
  862. AVFilterBufferRef *src_buffer)
  863. {
  864. AVFilterContext *ctx = inlink->dst;
  865. ATempoContext *atempo = ctx->priv;
  866. AVFilterLink *outlink = ctx->outputs[0];
  867. int n_in = src_buffer->audio->nb_samples;
  868. int n_out = (int)(0.5 + ((double)n_in) / atempo->tempo);
  869. const uint8_t *src = src_buffer->data[0];
  870. const uint8_t *src_end = src + n_in * atempo->stride;
  871. while (src < src_end) {
  872. if (!atempo->dst_buffer) {
  873. atempo->dst_buffer = ff_get_audio_buffer(outlink,
  874. AV_PERM_WRITE,
  875. n_out);
  876. avfilter_copy_buffer_ref_props(atempo->dst_buffer, src_buffer);
  877. atempo->dst = atempo->dst_buffer->data[0];
  878. atempo->dst_end = atempo->dst + n_out * atempo->stride;
  879. }
  880. yae_apply(atempo, &src, src_end, &atempo->dst, atempo->dst_end);
  881. if (atempo->dst == atempo->dst_end) {
  882. push_samples(atempo, outlink, n_out);
  883. atempo->request_fulfilled = 1;
  884. }
  885. }
  886. atempo->nsamples_in += n_in;
  887. avfilter_unref_bufferp(&src_buffer);
  888. }
  889. static int request_frame(AVFilterLink *outlink)
  890. {
  891. AVFilterContext *ctx = outlink->src;
  892. ATempoContext *atempo = ctx->priv;
  893. int ret;
  894. atempo->request_fulfilled = 0;
  895. do {
  896. ret = avfilter_request_frame(ctx->inputs[0]);
  897. }
  898. while (!atempo->request_fulfilled && ret >= 0);
  899. if (ret == AVERROR_EOF) {
  900. // flush the filter:
  901. int n_max = atempo->ring;
  902. int n_out;
  903. int err = AVERROR(EAGAIN);
  904. while (err == AVERROR(EAGAIN)) {
  905. if (!atempo->dst_buffer) {
  906. atempo->dst_buffer = ff_get_audio_buffer(outlink,
  907. AV_PERM_WRITE,
  908. n_max);
  909. atempo->dst = atempo->dst_buffer->data[0];
  910. atempo->dst_end = atempo->dst + n_max * atempo->stride;
  911. }
  912. err = yae_flush(atempo, &atempo->dst, atempo->dst_end);
  913. n_out = ((atempo->dst - atempo->dst_buffer->data[0]) /
  914. atempo->stride);
  915. if (n_out) {
  916. push_samples(atempo, outlink, n_out);
  917. }
  918. }
  919. avfilter_unref_bufferp(&atempo->dst_buffer);
  920. atempo->dst = NULL;
  921. atempo->dst_end = NULL;
  922. return AVERROR_EOF;
  923. }
  924. return ret;
  925. }
  926. static int process_command(AVFilterContext *ctx,
  927. const char *cmd,
  928. const char *arg,
  929. char *res,
  930. int res_len,
  931. int flags)
  932. {
  933. return !strcmp(cmd, "tempo") ? yae_set_tempo(ctx, arg) : AVERROR(ENOSYS);
  934. }
  935. AVFilter avfilter_af_atempo = {
  936. .name = "atempo",
  937. .description = NULL_IF_CONFIG_SMALL("Adjust audio tempo."),
  938. .init = init,
  939. .uninit = uninit,
  940. .query_formats = query_formats,
  941. .process_command = process_command,
  942. .priv_size = sizeof(ATempoContext),
  943. .inputs = (const AVFilterPad[]) {
  944. { .name = "default",
  945. .type = AVMEDIA_TYPE_AUDIO,
  946. .filter_samples = filter_samples,
  947. .config_props = config_props,
  948. .min_perms = AV_PERM_READ, },
  949. { .name = NULL}
  950. },
  951. .outputs = (const AVFilterPad[]) {
  952. { .name = "default",
  953. .request_frame = request_frame,
  954. .type = AVMEDIA_TYPE_AUDIO, },
  955. { .name = NULL}
  956. },
  957. };