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.

528 lines
17KB

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