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.

533 lines
18KB

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