resample.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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 Libav.
  6. *
  7. * Libav 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. * Libav 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 Libav; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "libavutil/libm.h"
  22. #include "libavutil/log.h"
  23. #include "internal.h"
  24. #include "audio_data.h"
  25. #ifdef CONFIG_RESAMPLE_FLT
  26. /* float template */
  27. #define FILTER_SHIFT 0
  28. #define FELEM float
  29. #define FELEM2 float
  30. #define FELEML float
  31. #define WINDOW_TYPE 24
  32. #elifdef CONFIG_RESAMPLE_S32
  33. /* s32 template */
  34. #define FILTER_SHIFT 30
  35. #define FELEM int32_t
  36. #define FELEM2 int64_t
  37. #define FELEML int64_t
  38. #define FELEM_MAX INT32_MAX
  39. #define FELEM_MIN INT32_MIN
  40. #define WINDOW_TYPE 12
  41. #else
  42. /* s16 template */
  43. #define FILTER_SHIFT 15
  44. #define FELEM int16_t
  45. #define FELEM2 int32_t
  46. #define FELEML int64_t
  47. #define FELEM_MAX INT16_MAX
  48. #define FELEM_MIN INT16_MIN
  49. #define WINDOW_TYPE 9
  50. #endif
  51. struct ResampleContext {
  52. AVAudioResampleContext *avr;
  53. AudioData *buffer;
  54. FELEM *filter_bank;
  55. int filter_length;
  56. int ideal_dst_incr;
  57. int dst_incr;
  58. int index;
  59. int frac;
  60. int src_incr;
  61. int compensation_distance;
  62. int phase_shift;
  63. int phase_mask;
  64. int linear;
  65. double factor;
  66. };
  67. /**
  68. * 0th order modified bessel function of the first kind.
  69. */
  70. static double bessel(double x)
  71. {
  72. double v = 1;
  73. double lastv = 0;
  74. double t = 1;
  75. int i;
  76. x = x * x / 4;
  77. for (i = 1; v != lastv; i++) {
  78. lastv = v;
  79. t *= x / (i * i);
  80. v += t;
  81. }
  82. return v;
  83. }
  84. /**
  85. * Build a polyphase filterbank.
  86. *
  87. * @param[out] filter filter coefficients
  88. * @param factor resampling factor
  89. * @param tap_count tap count
  90. * @param phase_count phase count
  91. * @param scale wanted sum of coefficients for each filter
  92. * @param type 0->cubic
  93. * 1->blackman nuttall windowed sinc
  94. * 2..16->kaiser windowed sinc beta=2..16
  95. * @return 0 on success, negative AVERROR code on failure
  96. */
  97. static int build_filter(FELEM *filter, double factor, int tap_count,
  98. int phase_count, int scale, int type)
  99. {
  100. int ph, i;
  101. double x, y, w;
  102. double *tab;
  103. const int center = (tap_count - 1) / 2;
  104. tab = av_malloc(tap_count * sizeof(*tab));
  105. if (!tab)
  106. return AVERROR(ENOMEM);
  107. /* if upsampling, only need to interpolate, no filter */
  108. if (factor > 1.0)
  109. factor = 1.0;
  110. for (ph = 0; ph < phase_count; ph++) {
  111. double norm = 0;
  112. for (i = 0; i < tap_count; i++) {
  113. x = M_PI * ((double)(i - center) - (double)ph / phase_count) * factor;
  114. if (x == 0) y = 1.0;
  115. else y = sin(x) / x;
  116. switch (type) {
  117. case 0: {
  118. const float d = -0.5; //first order derivative = -0.5
  119. x = fabs(((double)(i - center) - (double)ph / phase_count) * factor);
  120. if (x < 1.0) y = 1 - 3 * x*x + 2 * x*x*x + d * ( -x*x + x*x*x);
  121. else y = d * (-4 + 8 * x - 5 * x*x + x*x*x);
  122. break;
  123. }
  124. case 1:
  125. w = 2.0 * x / (factor * tap_count) + M_PI;
  126. y *= 0.3635819 - 0.4891775 * cos( w) +
  127. 0.1365995 * cos(2 * w) -
  128. 0.0106411 * cos(3 * w);
  129. break;
  130. default:
  131. w = 2.0 * x / (factor * tap_count * M_PI);
  132. y *= bessel(type * sqrt(FFMAX(1 - w * w, 0)));
  133. break;
  134. }
  135. tab[i] = y;
  136. norm += y;
  137. }
  138. /* normalize so that an uniform color remains the same */
  139. for (i = 0; i < tap_count; i++) {
  140. #ifdef CONFIG_RESAMPLE_FLT
  141. filter[ph * tap_count + i] = tab[i] / norm;
  142. #else
  143. filter[ph * tap_count + i] = av_clip(lrintf(tab[i] * scale / norm),
  144. FELEM_MIN, FELEM_MAX);
  145. #endif
  146. }
  147. }
  148. av_free(tab);
  149. return 0;
  150. }
  151. ResampleContext *ff_audio_resample_init(AVAudioResampleContext *avr)
  152. {
  153. ResampleContext *c;
  154. int out_rate = avr->out_sample_rate;
  155. int in_rate = avr->in_sample_rate;
  156. double factor = FFMIN(out_rate * avr->cutoff / in_rate, 1.0);
  157. int phase_count = 1 << avr->phase_shift;
  158. /* TODO: add support for s32 and float internal formats */
  159. if (avr->internal_sample_fmt != AV_SAMPLE_FMT_S16P) {
  160. av_log(avr, AV_LOG_ERROR, "Unsupported internal format for "
  161. "resampling: %s\n",
  162. av_get_sample_fmt_name(avr->internal_sample_fmt));
  163. return NULL;
  164. }
  165. c = av_mallocz(sizeof(*c));
  166. if (!c)
  167. return NULL;
  168. c->avr = avr;
  169. c->phase_shift = avr->phase_shift;
  170. c->phase_mask = phase_count - 1;
  171. c->linear = avr->linear_interp;
  172. c->factor = factor;
  173. c->filter_length = FFMAX((int)ceil(avr->filter_size / factor), 1);
  174. c->filter_bank = av_mallocz(c->filter_length * (phase_count + 1) * sizeof(FELEM));
  175. if (!c->filter_bank)
  176. goto error;
  177. if (build_filter(c->filter_bank, factor, c->filter_length, phase_count,
  178. 1 << FILTER_SHIFT, WINDOW_TYPE) < 0)
  179. goto error;
  180. memcpy(&c->filter_bank[c->filter_length * phase_count + 1],
  181. c->filter_bank, (c->filter_length - 1) * sizeof(FELEM));
  182. c->filter_bank[c->filter_length * phase_count] = c->filter_bank[c->filter_length - 1];
  183. c->compensation_distance = 0;
  184. if (!av_reduce(&c->src_incr, &c->dst_incr, out_rate,
  185. in_rate * (int64_t)phase_count, INT32_MAX / 2))
  186. goto error;
  187. c->ideal_dst_incr = c->dst_incr;
  188. c->index = -phase_count * ((c->filter_length - 1) / 2);
  189. c->frac = 0;
  190. /* allocate internal buffer */
  191. c->buffer = ff_audio_data_alloc(avr->resample_channels, 0,
  192. avr->internal_sample_fmt,
  193. "resample buffer");
  194. if (!c->buffer)
  195. goto error;
  196. av_log(avr, AV_LOG_DEBUG, "resample: %s from %d Hz to %d Hz\n",
  197. av_get_sample_fmt_name(avr->internal_sample_fmt),
  198. avr->in_sample_rate, avr->out_sample_rate);
  199. return c;
  200. error:
  201. ff_audio_data_free(&c->buffer);
  202. av_free(c->filter_bank);
  203. av_free(c);
  204. return NULL;
  205. }
  206. void ff_audio_resample_free(ResampleContext **c)
  207. {
  208. if (!*c)
  209. return;
  210. ff_audio_data_free(&(*c)->buffer);
  211. av_free((*c)->filter_bank);
  212. av_freep(c);
  213. }
  214. int avresample_set_compensation(AVAudioResampleContext *avr, int sample_delta,
  215. int compensation_distance)
  216. {
  217. ResampleContext *c;
  218. AudioData *fifo_buf = NULL;
  219. int ret = 0;
  220. if (compensation_distance < 0)
  221. return AVERROR(EINVAL);
  222. if (!compensation_distance && sample_delta)
  223. return AVERROR(EINVAL);
  224. /* if resampling was not enabled previously, re-initialize the
  225. AVAudioResampleContext and force resampling */
  226. if (!avr->resample_needed) {
  227. int fifo_samples;
  228. double matrix[AVRESAMPLE_MAX_CHANNELS * AVRESAMPLE_MAX_CHANNELS] = { 0 };
  229. /* buffer any remaining samples in the output FIFO before closing */
  230. fifo_samples = av_audio_fifo_size(avr->out_fifo);
  231. if (fifo_samples > 0) {
  232. fifo_buf = ff_audio_data_alloc(avr->out_channels, fifo_samples,
  233. avr->out_sample_fmt, NULL);
  234. if (!fifo_buf)
  235. return AVERROR(EINVAL);
  236. ret = ff_audio_data_read_from_fifo(avr->out_fifo, fifo_buf,
  237. fifo_samples);
  238. if (ret < 0)
  239. goto reinit_fail;
  240. }
  241. /* save the channel mixing matrix */
  242. ret = avresample_get_matrix(avr, matrix, AVRESAMPLE_MAX_CHANNELS);
  243. if (ret < 0)
  244. goto reinit_fail;
  245. /* close the AVAudioResampleContext */
  246. avresample_close(avr);
  247. avr->force_resampling = 1;
  248. /* restore the channel mixing matrix */
  249. ret = avresample_set_matrix(avr, matrix, AVRESAMPLE_MAX_CHANNELS);
  250. if (ret < 0)
  251. goto reinit_fail;
  252. /* re-open the AVAudioResampleContext */
  253. ret = avresample_open(avr);
  254. if (ret < 0)
  255. goto reinit_fail;
  256. /* restore buffered samples to the output FIFO */
  257. if (fifo_samples > 0) {
  258. ret = ff_audio_data_add_to_fifo(avr->out_fifo, fifo_buf, 0,
  259. fifo_samples);
  260. if (ret < 0)
  261. goto reinit_fail;
  262. ff_audio_data_free(&fifo_buf);
  263. }
  264. }
  265. c = avr->resample;
  266. c->compensation_distance = compensation_distance;
  267. if (compensation_distance) {
  268. c->dst_incr = c->ideal_dst_incr - c->ideal_dst_incr *
  269. (int64_t)sample_delta / compensation_distance;
  270. } else {
  271. c->dst_incr = c->ideal_dst_incr;
  272. }
  273. return 0;
  274. reinit_fail:
  275. ff_audio_data_free(&fifo_buf);
  276. return ret;
  277. }
  278. static int resample(ResampleContext *c, int16_t *dst, const int16_t *src,
  279. int *consumed, int src_size, int dst_size, int update_ctx)
  280. {
  281. int dst_index, i;
  282. int index = c->index;
  283. int frac = c->frac;
  284. int dst_incr_frac = c->dst_incr % c->src_incr;
  285. int dst_incr = c->dst_incr / c->src_incr;
  286. int compensation_distance = c->compensation_distance;
  287. if (!dst != !src)
  288. return AVERROR(EINVAL);
  289. if (compensation_distance == 0 && c->filter_length == 1 &&
  290. c->phase_shift == 0) {
  291. int64_t index2 = ((int64_t)index) << 32;
  292. int64_t incr = (1LL << 32) * c->dst_incr / c->src_incr;
  293. dst_size = FFMIN(dst_size,
  294. (src_size-1-index) * (int64_t)c->src_incr /
  295. c->dst_incr);
  296. if (dst) {
  297. for(dst_index = 0; dst_index < dst_size; dst_index++) {
  298. dst[dst_index] = src[index2 >> 32];
  299. index2 += incr;
  300. }
  301. } else {
  302. dst_index = dst_size;
  303. }
  304. index += dst_index * dst_incr;
  305. index += (frac + dst_index * (int64_t)dst_incr_frac) / c->src_incr;
  306. frac = (frac + dst_index * (int64_t)dst_incr_frac) % c->src_incr;
  307. } else {
  308. for (dst_index = 0; dst_index < dst_size; dst_index++) {
  309. FELEM *filter = c->filter_bank +
  310. c->filter_length * (index & c->phase_mask);
  311. int sample_index = index >> c->phase_shift;
  312. if (!dst && (sample_index + c->filter_length > src_size ||
  313. -sample_index >= src_size))
  314. break;
  315. if (dst) {
  316. FELEM2 val = 0;
  317. if (sample_index < 0) {
  318. for (i = 0; i < c->filter_length; i++)
  319. val += src[FFABS(sample_index + i) % src_size] *
  320. (FELEM2)filter[i];
  321. } else if (sample_index + c->filter_length > src_size) {
  322. break;
  323. } else if (c->linear) {
  324. FELEM2 v2 = 0;
  325. for (i = 0; i < c->filter_length; i++) {
  326. val += src[abs(sample_index + i)] * (FELEM2)filter[i];
  327. v2 += src[abs(sample_index + i)] * (FELEM2)filter[i + c->filter_length];
  328. }
  329. val += (v2 - val) * (FELEML)frac / c->src_incr;
  330. } else {
  331. for (i = 0; i < c->filter_length; i++)
  332. val += src[sample_index + i] * (FELEM2)filter[i];
  333. }
  334. #ifdef CONFIG_RESAMPLE_FLT
  335. dst[dst_index] = av_clip_int16(lrintf(val));
  336. #else
  337. val = (val + (1<<(FILTER_SHIFT-1)))>>FILTER_SHIFT;
  338. dst[dst_index] = av_clip_int16(val);
  339. #endif
  340. }
  341. frac += dst_incr_frac;
  342. index += dst_incr;
  343. if (frac >= c->src_incr) {
  344. frac -= c->src_incr;
  345. index++;
  346. }
  347. if (dst_index + 1 == compensation_distance) {
  348. compensation_distance = 0;
  349. dst_incr_frac = c->ideal_dst_incr % c->src_incr;
  350. dst_incr = c->ideal_dst_incr / c->src_incr;
  351. }
  352. }
  353. }
  354. if (consumed)
  355. *consumed = FFMAX(index, 0) >> c->phase_shift;
  356. if (update_ctx) {
  357. if (index >= 0)
  358. index &= c->phase_mask;
  359. if (compensation_distance) {
  360. compensation_distance -= dst_index;
  361. if (compensation_distance <= 0)
  362. return AVERROR_BUG;
  363. }
  364. c->frac = frac;
  365. c->index = index;
  366. c->dst_incr = dst_incr_frac + c->src_incr*dst_incr;
  367. c->compensation_distance = compensation_distance;
  368. }
  369. return dst_index;
  370. }
  371. int ff_audio_resample(ResampleContext *c, AudioData *dst, AudioData *src,
  372. int *consumed)
  373. {
  374. int ch, in_samples, in_leftover, out_samples = 0;
  375. int ret = AVERROR(EINVAL);
  376. in_samples = src ? src->nb_samples : 0;
  377. in_leftover = c->buffer->nb_samples;
  378. /* add input samples to the internal buffer */
  379. if (src) {
  380. ret = ff_audio_data_combine(c->buffer, in_leftover, src, 0, in_samples);
  381. if (ret < 0)
  382. return ret;
  383. } else if (!in_leftover) {
  384. /* no remaining samples to flush */
  385. return 0;
  386. } else {
  387. /* TODO: pad buffer to flush completely */
  388. }
  389. /* calculate output size and reallocate output buffer if needed */
  390. /* TODO: try to calculate this without the dummy resample() run */
  391. if (!dst->read_only && dst->allow_realloc) {
  392. out_samples = resample(c, NULL, NULL, NULL, c->buffer->nb_samples,
  393. INT_MAX, 0);
  394. ret = ff_audio_data_realloc(dst, out_samples);
  395. if (ret < 0) {
  396. av_log(c->avr, AV_LOG_ERROR, "error reallocating output\n");
  397. return ret;
  398. }
  399. }
  400. /* resample each channel plane */
  401. for (ch = 0; ch < c->buffer->channels; ch++) {
  402. out_samples = resample(c, (int16_t *)dst->data[ch],
  403. (const int16_t *)c->buffer->data[ch], consumed,
  404. c->buffer->nb_samples, dst->allocated_samples,
  405. ch + 1 == c->buffer->channels);
  406. }
  407. if (out_samples < 0) {
  408. av_log(c->avr, AV_LOG_ERROR, "error during resampling\n");
  409. return out_samples;
  410. }
  411. /* drain consumed samples from the internal buffer */
  412. ff_audio_data_drain(c->buffer, *consumed);
  413. av_dlog(c->avr, "resampled %d in + %d leftover to %d out + %d leftover\n",
  414. in_samples, in_leftover, out_samples, c->buffer->nb_samples);
  415. dst->nb_samples = out_samples;
  416. return 0;
  417. }
  418. int avresample_get_delay(AVAudioResampleContext *avr)
  419. {
  420. if (!avr->resample_needed || !avr->resample)
  421. return 0;
  422. return avr->resample->buffer->nb_samples;
  423. }