resample.c 15 KB

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