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.

482 lines
16KB

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