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.

1217 lines
38KB

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