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.

471 lines
15KB

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