resample.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  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/common.h"
  22. #include "libavutil/libm.h"
  23. #include "libavutil/log.h"
  24. #include "internal.h"
  25. #include "audio_data.h"
  26. struct ResampleContext {
  27. AVAudioResampleContext *avr;
  28. AudioData *buffer;
  29. uint8_t *filter_bank;
  30. int filter_length;
  31. int ideal_dst_incr;
  32. int dst_incr;
  33. int index;
  34. int frac;
  35. int src_incr;
  36. int compensation_distance;
  37. int phase_shift;
  38. int phase_mask;
  39. int linear;
  40. enum AVResampleFilterType filter_type;
  41. int kaiser_beta;
  42. double factor;
  43. void (*set_filter)(void *filter, double *tab, int phase, int tap_count);
  44. void (*resample_one)(struct ResampleContext *c, int no_filter, void *dst0,
  45. int dst_index, const void *src0, int src_size,
  46. int index, int frac);
  47. int padding_size;
  48. };
  49. /* double template */
  50. #define CONFIG_RESAMPLE_DBL
  51. #include "resample_template.c"
  52. #undef CONFIG_RESAMPLE_DBL
  53. /* float template */
  54. #define CONFIG_RESAMPLE_FLT
  55. #include "resample_template.c"
  56. #undef CONFIG_RESAMPLE_FLT
  57. /* s32 template */
  58. #define CONFIG_RESAMPLE_S32
  59. #include "resample_template.c"
  60. #undef CONFIG_RESAMPLE_S32
  61. /* s16 template */
  62. #include "resample_template.c"
  63. /* 0th order modified bessel function of the first kind. */
  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. /* Build a polyphase filterbank. */
  79. static int build_filter(ResampleContext *c)
  80. {
  81. int ph, i;
  82. double x, y, w, factor;
  83. double *tab;
  84. int tap_count = c->filter_length;
  85. int phase_count = 1 << c->phase_shift;
  86. const int center = (tap_count - 1) / 2;
  87. tab = av_malloc(tap_count * sizeof(*tab));
  88. if (!tab)
  89. return AVERROR(ENOMEM);
  90. /* if upsampling, only need to interpolate, no filter */
  91. factor = FFMIN(c->factor, 1.0);
  92. for (ph = 0; ph < phase_count; ph++) {
  93. double norm = 0;
  94. for (i = 0; i < tap_count; i++) {
  95. x = M_PI * ((double)(i - center) - (double)ph / phase_count) * factor;
  96. if (x == 0) y = 1.0;
  97. else y = sin(x) / x;
  98. switch (c->filter_type) {
  99. case AV_RESAMPLE_FILTER_TYPE_CUBIC: {
  100. const float d = -0.5; //first order derivative = -0.5
  101. x = fabs(((double)(i - center) - (double)ph / phase_count) * factor);
  102. if (x < 1.0) y = 1 - 3 * x*x + 2 * x*x*x + d * ( -x*x + x*x*x);
  103. else y = d * (-4 + 8 * x - 5 * x*x + x*x*x);
  104. break;
  105. }
  106. case AV_RESAMPLE_FILTER_TYPE_BLACKMAN_NUTTALL:
  107. w = 2.0 * x / (factor * tap_count) + M_PI;
  108. y *= 0.3635819 - 0.4891775 * cos( w) +
  109. 0.1365995 * cos(2 * w) -
  110. 0.0106411 * cos(3 * w);
  111. break;
  112. case AV_RESAMPLE_FILTER_TYPE_KAISER:
  113. w = 2.0 * x / (factor * tap_count * M_PI);
  114. y *= bessel(c->kaiser_beta * sqrt(FFMAX(1 - w * w, 0)));
  115. break;
  116. }
  117. tab[i] = y;
  118. norm += y;
  119. }
  120. /* normalize so that an uniform color remains the same */
  121. for (i = 0; i < tap_count; i++)
  122. tab[i] = tab[i] / norm;
  123. c->set_filter(c->filter_bank, tab, ph, tap_count);
  124. }
  125. av_free(tab);
  126. return 0;
  127. }
  128. ResampleContext *ff_audio_resample_init(AVAudioResampleContext *avr)
  129. {
  130. ResampleContext *c;
  131. int out_rate = avr->out_sample_rate;
  132. int in_rate = avr->in_sample_rate;
  133. double factor = FFMIN(out_rate * avr->cutoff / in_rate, 1.0);
  134. int phase_count = 1 << avr->phase_shift;
  135. int felem_size;
  136. if (avr->internal_sample_fmt != AV_SAMPLE_FMT_S16P &&
  137. avr->internal_sample_fmt != AV_SAMPLE_FMT_S32P &&
  138. avr->internal_sample_fmt != AV_SAMPLE_FMT_FLTP &&
  139. avr->internal_sample_fmt != AV_SAMPLE_FMT_DBLP) {
  140. av_log(avr, AV_LOG_ERROR, "Unsupported internal format for "
  141. "resampling: %s\n",
  142. av_get_sample_fmt_name(avr->internal_sample_fmt));
  143. return NULL;
  144. }
  145. c = av_mallocz(sizeof(*c));
  146. if (!c)
  147. return NULL;
  148. c->avr = avr;
  149. c->phase_shift = avr->phase_shift;
  150. c->phase_mask = phase_count - 1;
  151. c->linear = avr->linear_interp;
  152. c->factor = factor;
  153. c->filter_length = FFMAX((int)ceil(avr->filter_size / factor), 1);
  154. c->filter_type = avr->filter_type;
  155. c->kaiser_beta = avr->kaiser_beta;
  156. switch (avr->internal_sample_fmt) {
  157. case AV_SAMPLE_FMT_DBLP:
  158. c->resample_one = resample_one_dbl;
  159. c->set_filter = set_filter_dbl;
  160. break;
  161. case AV_SAMPLE_FMT_FLTP:
  162. c->resample_one = resample_one_flt;
  163. c->set_filter = set_filter_flt;
  164. break;
  165. case AV_SAMPLE_FMT_S32P:
  166. c->resample_one = resample_one_s32;
  167. c->set_filter = set_filter_s32;
  168. break;
  169. case AV_SAMPLE_FMT_S16P:
  170. c->resample_one = resample_one_s16;
  171. c->set_filter = set_filter_s16;
  172. break;
  173. }
  174. felem_size = av_get_bytes_per_sample(avr->internal_sample_fmt);
  175. c->filter_bank = av_mallocz(c->filter_length * (phase_count + 1) * felem_size);
  176. if (!c->filter_bank)
  177. goto error;
  178. if (build_filter(c) < 0)
  179. goto error;
  180. memcpy(&c->filter_bank[(c->filter_length * phase_count + 1) * felem_size],
  181. c->filter_bank, (c->filter_length - 1) * felem_size);
  182. memcpy(&c->filter_bank[c->filter_length * phase_count * felem_size],
  183. &c->filter_bank[(c->filter_length - 1) * felem_size], felem_size);
  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->padding_size = (c->filter_length - 1) / 2;
  190. c->index = -phase_count * ((c->filter_length - 1) / 2);
  191. c->frac = 0;
  192. /* allocate internal buffer */
  193. c->buffer = ff_audio_data_alloc(avr->resample_channels, 0,
  194. avr->internal_sample_fmt,
  195. "resample buffer");
  196. if (!c->buffer)
  197. goto error;
  198. av_log(avr, AV_LOG_DEBUG, "resample: %s from %d Hz to %d Hz\n",
  199. av_get_sample_fmt_name(avr->internal_sample_fmt),
  200. avr->in_sample_rate, avr->out_sample_rate);
  201. return c;
  202. error:
  203. ff_audio_data_free(&c->buffer);
  204. av_free(c->filter_bank);
  205. av_free(c);
  206. return NULL;
  207. }
  208. void ff_audio_resample_free(ResampleContext **c)
  209. {
  210. if (!*c)
  211. return;
  212. ff_audio_data_free(&(*c)->buffer);
  213. av_free((*c)->filter_bank);
  214. av_freep(c);
  215. }
  216. int avresample_set_compensation(AVAudioResampleContext *avr, int sample_delta,
  217. int compensation_distance)
  218. {
  219. ResampleContext *c;
  220. AudioData *fifo_buf = NULL;
  221. int ret = 0;
  222. if (compensation_distance < 0)
  223. return AVERROR(EINVAL);
  224. if (!compensation_distance && sample_delta)
  225. return AVERROR(EINVAL);
  226. if (!avr->resample_needed) {
  227. #if FF_API_RESAMPLE_CLOSE_OPEN
  228. /* if resampling was not enabled previously, re-initialize the
  229. AVAudioResampleContext and force resampling */
  230. int fifo_samples;
  231. int restore_matrix = 0;
  232. double matrix[AVRESAMPLE_MAX_CHANNELS * AVRESAMPLE_MAX_CHANNELS] = { 0 };
  233. /* buffer any remaining samples in the output FIFO before closing */
  234. fifo_samples = av_audio_fifo_size(avr->out_fifo);
  235. if (fifo_samples > 0) {
  236. fifo_buf = ff_audio_data_alloc(avr->out_channels, fifo_samples,
  237. avr->out_sample_fmt, NULL);
  238. if (!fifo_buf)
  239. return AVERROR(EINVAL);
  240. ret = ff_audio_data_read_from_fifo(avr->out_fifo, fifo_buf,
  241. fifo_samples);
  242. if (ret < 0)
  243. goto reinit_fail;
  244. }
  245. /* save the channel mixing matrix */
  246. if (avr->am) {
  247. ret = avresample_get_matrix(avr, matrix, AVRESAMPLE_MAX_CHANNELS);
  248. if (ret < 0)
  249. goto reinit_fail;
  250. restore_matrix = 1;
  251. }
  252. /* close the AVAudioResampleContext */
  253. avresample_close(avr);
  254. avr->force_resampling = 1;
  255. /* restore the channel mixing matrix */
  256. if (restore_matrix) {
  257. ret = avresample_set_matrix(avr, matrix, AVRESAMPLE_MAX_CHANNELS);
  258. if (ret < 0)
  259. goto reinit_fail;
  260. }
  261. /* re-open the AVAudioResampleContext */
  262. ret = avresample_open(avr);
  263. if (ret < 0)
  264. goto reinit_fail;
  265. /* restore buffered samples to the output FIFO */
  266. if (fifo_samples > 0) {
  267. ret = ff_audio_data_add_to_fifo(avr->out_fifo, fifo_buf, 0,
  268. fifo_samples);
  269. if (ret < 0)
  270. goto reinit_fail;
  271. ff_audio_data_free(&fifo_buf);
  272. }
  273. #else
  274. av_log(avr, AV_LOG_ERROR, "Unable to set resampling compensation\n");
  275. return AVERROR(EINVAL);
  276. #endif
  277. }
  278. c = avr->resample;
  279. c->compensation_distance = compensation_distance;
  280. if (compensation_distance) {
  281. c->dst_incr = c->ideal_dst_incr - c->ideal_dst_incr *
  282. (int64_t)sample_delta / compensation_distance;
  283. } else {
  284. c->dst_incr = c->ideal_dst_incr;
  285. }
  286. return 0;
  287. reinit_fail:
  288. ff_audio_data_free(&fifo_buf);
  289. return ret;
  290. }
  291. static int resample(ResampleContext *c, void *dst, const void *src,
  292. int *consumed, int src_size, int dst_size, int update_ctx)
  293. {
  294. int dst_index;
  295. int index = c->index;
  296. int frac = c->frac;
  297. int dst_incr_frac = c->dst_incr % c->src_incr;
  298. int dst_incr = c->dst_incr / c->src_incr;
  299. int compensation_distance = c->compensation_distance;
  300. if (!dst != !src)
  301. return AVERROR(EINVAL);
  302. if (compensation_distance == 0 && c->filter_length == 1 &&
  303. c->phase_shift == 0) {
  304. int64_t index2 = ((int64_t)index) << 32;
  305. int64_t incr = (1LL << 32) * c->dst_incr / c->src_incr;
  306. dst_size = FFMIN(dst_size,
  307. (src_size-1-index) * (int64_t)c->src_incr /
  308. c->dst_incr);
  309. if (dst) {
  310. for(dst_index = 0; dst_index < dst_size; dst_index++) {
  311. c->resample_one(c, 1, dst, dst_index, src, 0, index2 >> 32, 0);
  312. index2 += incr;
  313. }
  314. } else {
  315. dst_index = dst_size;
  316. }
  317. index += dst_index * dst_incr;
  318. index += (frac + dst_index * (int64_t)dst_incr_frac) / c->src_incr;
  319. frac = (frac + dst_index * (int64_t)dst_incr_frac) % c->src_incr;
  320. } else {
  321. for (dst_index = 0; dst_index < dst_size; dst_index++) {
  322. int sample_index = index >> c->phase_shift;
  323. if (sample_index + c->filter_length > src_size ||
  324. -sample_index >= src_size)
  325. break;
  326. if (dst)
  327. c->resample_one(c, 0, dst, dst_index, src, src_size, index, frac);
  328. frac += dst_incr_frac;
  329. index += dst_incr;
  330. if (frac >= c->src_incr) {
  331. frac -= c->src_incr;
  332. index++;
  333. }
  334. if (dst_index + 1 == compensation_distance) {
  335. compensation_distance = 0;
  336. dst_incr_frac = c->ideal_dst_incr % c->src_incr;
  337. dst_incr = c->ideal_dst_incr / c->src_incr;
  338. }
  339. }
  340. }
  341. if (consumed)
  342. *consumed = FFMAX(index, 0) >> c->phase_shift;
  343. if (update_ctx) {
  344. if (index >= 0)
  345. index &= c->phase_mask;
  346. if (compensation_distance) {
  347. compensation_distance -= dst_index;
  348. if (compensation_distance <= 0)
  349. return AVERROR_BUG;
  350. }
  351. c->frac = frac;
  352. c->index = index;
  353. c->dst_incr = dst_incr_frac + c->src_incr*dst_incr;
  354. c->compensation_distance = compensation_distance;
  355. }
  356. return dst_index;
  357. }
  358. int ff_audio_resample(ResampleContext *c, AudioData *dst, AudioData *src)
  359. {
  360. int ch, in_samples, in_leftover, consumed = 0, 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. ResampleContext *c = avr->resample;
  407. if (!avr->resample_needed || !avr->resample)
  408. return 0;
  409. return FFMAX(c->buffer->nb_samples - c->padding_size, 0);
  410. }