resample.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. /*
  2. * Copyright (c) 2004 Michael Niedermayer <michaelni@gmx.at>
  3. * Copyright (c) 2012 Justin Ruggles <justin.ruggles@gmail.com>
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "libavutil/common.h"
  22. #include "libavutil/libm.h"
  23. #include "libavutil/log.h"
  24. #include "internal.h"
  25. #include "resample.h"
  26. #include "audio_data.h"
  27. /* double template */
  28. #define CONFIG_RESAMPLE_DBL
  29. #include "resample_template.c"
  30. #undef CONFIG_RESAMPLE_DBL
  31. /* float template */
  32. #define CONFIG_RESAMPLE_FLT
  33. #include "resample_template.c"
  34. #undef CONFIG_RESAMPLE_FLT
  35. /* s32 template */
  36. #define CONFIG_RESAMPLE_S32
  37. #include "resample_template.c"
  38. #undef CONFIG_RESAMPLE_S32
  39. /* s16 template */
  40. #include "resample_template.c"
  41. /* 0th order modified bessel function of the first kind. */
  42. static double bessel(double x)
  43. {
  44. double v = 1;
  45. double lastv = 0;
  46. double t = 1;
  47. int i;
  48. x = x * x / 4;
  49. for (i = 1; v != lastv; i++) {
  50. lastv = v;
  51. t *= x / (i * i);
  52. v += t;
  53. }
  54. return v;
  55. }
  56. /* Build a polyphase filterbank. */
  57. static int build_filter(ResampleContext *c, double factor)
  58. {
  59. int ph, i;
  60. double x, y, w;
  61. double *tab;
  62. int tap_count = c->filter_length;
  63. int phase_count = 1 << c->phase_shift;
  64. const int center = (tap_count - 1) / 2;
  65. tab = av_malloc(tap_count * sizeof(*tab));
  66. if (!tab)
  67. return AVERROR(ENOMEM);
  68. for (ph = 0; ph < phase_count; ph++) {
  69. double norm = 0;
  70. for (i = 0; i < tap_count; i++) {
  71. x = M_PI * ((double)(i - center) - (double)ph / phase_count) * factor;
  72. if (x == 0) y = 1.0;
  73. else y = sin(x) / x;
  74. switch (c->filter_type) {
  75. case AV_RESAMPLE_FILTER_TYPE_CUBIC: {
  76. const float d = -0.5; //first order derivative = -0.5
  77. x = fabs(((double)(i - center) - (double)ph / phase_count) * factor);
  78. if (x < 1.0) y = 1 - 3 * x*x + 2 * x*x*x + d * ( -x*x + x*x*x);
  79. else y = d * (-4 + 8 * x - 5 * x*x + x*x*x);
  80. break;
  81. }
  82. case AV_RESAMPLE_FILTER_TYPE_BLACKMAN_NUTTALL:
  83. w = 2.0 * x / (factor * tap_count) + M_PI;
  84. y *= 0.3635819 - 0.4891775 * cos( w) +
  85. 0.1365995 * cos(2 * w) -
  86. 0.0106411 * cos(3 * w);
  87. break;
  88. case AV_RESAMPLE_FILTER_TYPE_KAISER:
  89. w = 2.0 * x / (factor * tap_count * M_PI);
  90. y *= bessel(c->kaiser_beta * sqrt(FFMAX(1 - w * w, 0)));
  91. break;
  92. }
  93. tab[i] = y;
  94. norm += y;
  95. }
  96. /* normalize so that an uniform color remains the same */
  97. for (i = 0; i < tap_count; i++)
  98. tab[i] = tab[i] / norm;
  99. c->set_filter(c->filter_bank, tab, ph, tap_count);
  100. }
  101. av_free(tab);
  102. return 0;
  103. }
  104. ResampleContext *ff_audio_resample_init(AVAudioResampleContext *avr)
  105. {
  106. ResampleContext *c;
  107. int out_rate = avr->out_sample_rate;
  108. int in_rate = avr->in_sample_rate;
  109. double factor = FFMIN(out_rate * avr->cutoff / in_rate, 1.0);
  110. int phase_count = 1 << avr->phase_shift;
  111. int felem_size;
  112. if (avr->internal_sample_fmt != AV_SAMPLE_FMT_S16P &&
  113. avr->internal_sample_fmt != AV_SAMPLE_FMT_S32P &&
  114. avr->internal_sample_fmt != AV_SAMPLE_FMT_FLTP &&
  115. avr->internal_sample_fmt != AV_SAMPLE_FMT_DBLP) {
  116. av_log(avr, AV_LOG_ERROR, "Unsupported internal format for "
  117. "resampling: %s\n",
  118. av_get_sample_fmt_name(avr->internal_sample_fmt));
  119. return NULL;
  120. }
  121. c = av_mallocz(sizeof(*c));
  122. if (!c)
  123. return NULL;
  124. c->avr = avr;
  125. c->phase_shift = avr->phase_shift;
  126. c->phase_mask = phase_count - 1;
  127. c->linear = avr->linear_interp;
  128. c->filter_length = FFMAX((int)ceil(avr->filter_size / factor), 1);
  129. c->filter_type = avr->filter_type;
  130. c->kaiser_beta = avr->kaiser_beta;
  131. switch (avr->internal_sample_fmt) {
  132. case AV_SAMPLE_FMT_DBLP:
  133. c->resample_one = c->linear ? resample_linear_dbl : resample_one_dbl;
  134. c->resample_nearest = resample_nearest_dbl;
  135. c->set_filter = set_filter_dbl;
  136. break;
  137. case AV_SAMPLE_FMT_FLTP:
  138. c->resample_one = c->linear ? resample_linear_flt : resample_one_flt;
  139. c->resample_nearest = resample_nearest_flt;
  140. c->set_filter = set_filter_flt;
  141. break;
  142. case AV_SAMPLE_FMT_S32P:
  143. c->resample_one = c->linear ? resample_linear_s32 : resample_one_s32;
  144. c->resample_nearest = resample_nearest_s32;
  145. c->set_filter = set_filter_s32;
  146. break;
  147. case AV_SAMPLE_FMT_S16P:
  148. c->resample_one = c->linear ? resample_linear_s16 : resample_one_s16;
  149. c->resample_nearest = resample_nearest_s16;
  150. c->set_filter = set_filter_s16;
  151. break;
  152. }
  153. if (ARCH_AARCH64)
  154. ff_audio_resample_init_aarch64(c, avr->internal_sample_fmt);
  155. felem_size = av_get_bytes_per_sample(avr->internal_sample_fmt);
  156. c->filter_bank = av_mallocz(c->filter_length * (phase_count + 1) * felem_size);
  157. if (!c->filter_bank)
  158. goto error;
  159. if (build_filter(c, factor) < 0)
  160. goto error;
  161. memcpy(&c->filter_bank[(c->filter_length * phase_count + 1) * felem_size],
  162. c->filter_bank, (c->filter_length - 1) * felem_size);
  163. memcpy(&c->filter_bank[c->filter_length * phase_count * felem_size],
  164. &c->filter_bank[(c->filter_length - 1) * felem_size], felem_size);
  165. c->compensation_distance = 0;
  166. if (!av_reduce(&c->src_incr, &c->dst_incr, out_rate,
  167. in_rate * (int64_t)phase_count, INT32_MAX / 2))
  168. goto error;
  169. c->ideal_dst_incr = c->dst_incr;
  170. c->padding_size = (c->filter_length - 1) / 2;
  171. c->initial_padding_filled = 0;
  172. c->index = 0;
  173. c->frac = 0;
  174. /* allocate internal buffer */
  175. c->buffer = ff_audio_data_alloc(avr->resample_channels, c->padding_size,
  176. avr->internal_sample_fmt,
  177. "resample buffer");
  178. if (!c->buffer)
  179. goto error;
  180. c->buffer->nb_samples = c->padding_size;
  181. c->initial_padding_samples = c->padding_size;
  182. av_log(avr, AV_LOG_DEBUG, "resample: %s from %d Hz to %d Hz\n",
  183. av_get_sample_fmt_name(avr->internal_sample_fmt),
  184. avr->in_sample_rate, avr->out_sample_rate);
  185. return c;
  186. error:
  187. ff_audio_data_free(&c->buffer);
  188. av_free(c->filter_bank);
  189. av_free(c);
  190. return NULL;
  191. }
  192. void ff_audio_resample_free(ResampleContext **c)
  193. {
  194. if (!*c)
  195. return;
  196. ff_audio_data_free(&(*c)->buffer);
  197. av_free((*c)->filter_bank);
  198. av_freep(c);
  199. }
  200. int avresample_set_compensation(AVAudioResampleContext *avr, int sample_delta,
  201. int compensation_distance)
  202. {
  203. ResampleContext *c;
  204. AudioData *fifo_buf = NULL;
  205. int ret = 0;
  206. if (compensation_distance < 0)
  207. return AVERROR(EINVAL);
  208. if (!compensation_distance && sample_delta)
  209. return AVERROR(EINVAL);
  210. if (!avr->resample_needed) {
  211. #if FF_API_RESAMPLE_CLOSE_OPEN
  212. /* if resampling was not enabled previously, re-initialize the
  213. AVAudioResampleContext and force resampling */
  214. int fifo_samples;
  215. int restore_matrix = 0;
  216. double matrix[AVRESAMPLE_MAX_CHANNELS * AVRESAMPLE_MAX_CHANNELS] = { 0 };
  217. /* buffer any remaining samples in the output FIFO before closing */
  218. fifo_samples = av_audio_fifo_size(avr->out_fifo);
  219. if (fifo_samples > 0) {
  220. fifo_buf = ff_audio_data_alloc(avr->out_channels, fifo_samples,
  221. avr->out_sample_fmt, NULL);
  222. if (!fifo_buf)
  223. return AVERROR(EINVAL);
  224. ret = ff_audio_data_read_from_fifo(avr->out_fifo, fifo_buf,
  225. fifo_samples);
  226. if (ret < 0)
  227. goto reinit_fail;
  228. }
  229. /* save the channel mixing matrix */
  230. if (avr->am) {
  231. ret = avresample_get_matrix(avr, matrix, AVRESAMPLE_MAX_CHANNELS);
  232. if (ret < 0)
  233. goto reinit_fail;
  234. restore_matrix = 1;
  235. }
  236. /* close the AVAudioResampleContext */
  237. avresample_close(avr);
  238. avr->force_resampling = 1;
  239. /* restore the channel mixing matrix */
  240. if (restore_matrix) {
  241. ret = avresample_set_matrix(avr, matrix, AVRESAMPLE_MAX_CHANNELS);
  242. if (ret < 0)
  243. goto reinit_fail;
  244. }
  245. /* re-open the AVAudioResampleContext */
  246. ret = avresample_open(avr);
  247. if (ret < 0)
  248. goto reinit_fail;
  249. /* restore buffered samples to the output FIFO */
  250. if (fifo_samples > 0) {
  251. ret = ff_audio_data_add_to_fifo(avr->out_fifo, fifo_buf, 0,
  252. fifo_samples);
  253. if (ret < 0)
  254. goto reinit_fail;
  255. ff_audio_data_free(&fifo_buf);
  256. }
  257. #else
  258. av_log(avr, AV_LOG_ERROR, "Unable to set resampling compensation\n");
  259. return AVERROR(EINVAL);
  260. #endif
  261. }
  262. c = avr->resample;
  263. c->compensation_distance = compensation_distance;
  264. if (compensation_distance) {
  265. c->dst_incr = c->ideal_dst_incr - c->ideal_dst_incr *
  266. (int64_t)sample_delta / compensation_distance;
  267. } else {
  268. c->dst_incr = c->ideal_dst_incr;
  269. }
  270. return 0;
  271. reinit_fail:
  272. ff_audio_data_free(&fifo_buf);
  273. return ret;
  274. }
  275. static int resample(ResampleContext *c, void *dst, const void *src,
  276. int *consumed, int src_size, int dst_size, int update_ctx,
  277. int nearest_neighbour)
  278. {
  279. int dst_index;
  280. unsigned int index = c->index;
  281. int frac = c->frac;
  282. int dst_incr_frac = c->dst_incr % c->src_incr;
  283. int dst_incr = c->dst_incr / c->src_incr;
  284. int compensation_distance = c->compensation_distance;
  285. if (!dst != !src)
  286. return AVERROR(EINVAL);
  287. if (nearest_neighbour) {
  288. uint64_t index2 = ((uint64_t)index) << 32;
  289. int64_t incr = (1LL << 32) * c->dst_incr / c->src_incr;
  290. dst_size = FFMIN(dst_size,
  291. (src_size-1-index) * (int64_t)c->src_incr /
  292. c->dst_incr);
  293. if (dst) {
  294. for(dst_index = 0; dst_index < dst_size; dst_index++) {
  295. c->resample_nearest(dst, dst_index, src, index2 >> 32);
  296. index2 += incr;
  297. }
  298. } else {
  299. dst_index = dst_size;
  300. }
  301. index += dst_index * dst_incr;
  302. index += (frac + dst_index * (int64_t)dst_incr_frac) / c->src_incr;
  303. frac = (frac + dst_index * (int64_t)dst_incr_frac) % c->src_incr;
  304. } else {
  305. for (dst_index = 0; dst_index < dst_size; dst_index++) {
  306. int sample_index = index >> c->phase_shift;
  307. if (sample_index + c->filter_length > src_size)
  308. break;
  309. if (dst)
  310. c->resample_one(c, dst, dst_index, src, index, frac);
  311. frac += dst_incr_frac;
  312. index += dst_incr;
  313. if (frac >= c->src_incr) {
  314. frac -= c->src_incr;
  315. index++;
  316. }
  317. if (dst_index + 1 == compensation_distance) {
  318. compensation_distance = 0;
  319. dst_incr_frac = c->ideal_dst_incr % c->src_incr;
  320. dst_incr = c->ideal_dst_incr / c->src_incr;
  321. }
  322. }
  323. }
  324. if (consumed)
  325. *consumed = index >> c->phase_shift;
  326. if (update_ctx) {
  327. index &= c->phase_mask;
  328. if (compensation_distance) {
  329. compensation_distance -= dst_index;
  330. if (compensation_distance <= 0)
  331. return AVERROR_BUG;
  332. }
  333. c->frac = frac;
  334. c->index = index;
  335. c->dst_incr = dst_incr_frac + c->src_incr*dst_incr;
  336. c->compensation_distance = compensation_distance;
  337. }
  338. return dst_index;
  339. }
  340. int ff_audio_resample(ResampleContext *c, AudioData *dst, AudioData *src)
  341. {
  342. int ch, in_samples, in_leftover, consumed = 0, out_samples = 0;
  343. int ret = AVERROR(EINVAL);
  344. int nearest_neighbour = (c->compensation_distance == 0 &&
  345. c->filter_length == 1 &&
  346. c->phase_shift == 0);
  347. in_samples = src ? src->nb_samples : 0;
  348. in_leftover = c->buffer->nb_samples;
  349. /* add input samples to the internal buffer */
  350. if (src) {
  351. ret = ff_audio_data_combine(c->buffer, in_leftover, src, 0, in_samples);
  352. if (ret < 0)
  353. return ret;
  354. } else if (in_leftover <= c->final_padding_samples) {
  355. /* no remaining samples to flush */
  356. return 0;
  357. }
  358. if (!c->initial_padding_filled) {
  359. int bps = av_get_bytes_per_sample(c->avr->internal_sample_fmt);
  360. int i;
  361. if (src && c->buffer->nb_samples < 2 * c->padding_size)
  362. return 0;
  363. for (i = 0; i < c->padding_size; i++)
  364. for (ch = 0; ch < c->buffer->channels; ch++) {
  365. if (c->buffer->nb_samples > 2 * c->padding_size - i) {
  366. memcpy(c->buffer->data[ch] + bps * i,
  367. c->buffer->data[ch] + bps * (2 * c->padding_size - i), bps);
  368. } else {
  369. memset(c->buffer->data[ch] + bps * i, 0, bps);
  370. }
  371. }
  372. c->initial_padding_filled = 1;
  373. }
  374. if (!src && !c->final_padding_filled) {
  375. int bps = av_get_bytes_per_sample(c->avr->internal_sample_fmt);
  376. int i;
  377. ret = ff_audio_data_realloc(c->buffer, in_samples + c->padding_size);
  378. if (ret < 0) {
  379. av_log(c->avr, AV_LOG_ERROR, "Error reallocating resampling buffer\n");
  380. return AVERROR(ENOMEM);
  381. }
  382. for (i = 0; i < c->padding_size; i++)
  383. for (ch = 0; ch < c->buffer->channels; ch++) {
  384. if (in_leftover > i) {
  385. memcpy(c->buffer->data[ch] + bps * (in_leftover + i),
  386. c->buffer->data[ch] + bps * (in_leftover - i - 1),
  387. bps);
  388. } else {
  389. memset(c->buffer->data[ch] + bps * (in_leftover + i),
  390. 0, bps);
  391. }
  392. }
  393. c->buffer->nb_samples += c->padding_size;
  394. c->final_padding_samples = c->padding_size;
  395. c->final_padding_filled = 1;
  396. }
  397. /* calculate output size and reallocate output buffer if needed */
  398. /* TODO: try to calculate this without the dummy resample() run */
  399. if (!dst->read_only && dst->allow_realloc) {
  400. out_samples = resample(c, NULL, NULL, NULL, c->buffer->nb_samples,
  401. INT_MAX, 0, nearest_neighbour);
  402. ret = ff_audio_data_realloc(dst, out_samples);
  403. if (ret < 0) {
  404. av_log(c->avr, AV_LOG_ERROR, "error reallocating output\n");
  405. return ret;
  406. }
  407. }
  408. /* resample each channel plane */
  409. for (ch = 0; ch < c->buffer->channels; ch++) {
  410. out_samples = resample(c, (void *)dst->data[ch],
  411. (const void *)c->buffer->data[ch], &consumed,
  412. c->buffer->nb_samples, dst->allocated_samples,
  413. ch + 1 == c->buffer->channels, nearest_neighbour);
  414. }
  415. if (out_samples < 0) {
  416. av_log(c->avr, AV_LOG_ERROR, "error during resampling\n");
  417. return out_samples;
  418. }
  419. /* drain consumed samples from the internal buffer */
  420. ff_audio_data_drain(c->buffer, consumed);
  421. c->initial_padding_samples = FFMAX(c->initial_padding_samples - consumed, 0);
  422. av_dlog(c->avr, "resampled %d in + %d leftover to %d out + %d leftover\n",
  423. in_samples, in_leftover, out_samples, c->buffer->nb_samples);
  424. dst->nb_samples = out_samples;
  425. return 0;
  426. }
  427. int avresample_get_delay(AVAudioResampleContext *avr)
  428. {
  429. ResampleContext *c = avr->resample;
  430. if (!avr->resample_needed || !avr->resample)
  431. return 0;
  432. return FFMAX(c->buffer->nb_samples - c->padding_size, 0);
  433. }