resample.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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 "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. 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, int no_filter, void *dst0,
  46. int dst_index, const void *src0, int src_size,
  47. int index, int frac);
  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->index = -phase_count * ((c->filter_length - 1) / 2);
  190. c->frac = 0;
  191. /* allocate internal buffer */
  192. c->buffer = ff_audio_data_alloc(avr->resample_channels, 0,
  193. avr->internal_sample_fmt,
  194. "resample buffer");
  195. if (!c->buffer)
  196. goto error;
  197. av_log(avr, AV_LOG_DEBUG, "resample: %s from %d Hz to %d Hz\n",
  198. av_get_sample_fmt_name(avr->internal_sample_fmt),
  199. avr->in_sample_rate, avr->out_sample_rate);
  200. return c;
  201. error:
  202. ff_audio_data_free(&c->buffer);
  203. av_free(c->filter_bank);
  204. av_free(c);
  205. return NULL;
  206. }
  207. void ff_audio_resample_free(ResampleContext **c)
  208. {
  209. if (!*c)
  210. return;
  211. ff_audio_data_free(&(*c)->buffer);
  212. av_free((*c)->filter_bank);
  213. av_freep(c);
  214. }
  215. int avresample_set_compensation(AVAudioResampleContext *avr, int sample_delta,
  216. int compensation_distance)
  217. {
  218. ResampleContext *c;
  219. AudioData *fifo_buf = NULL;
  220. int ret = 0;
  221. if (compensation_distance < 0)
  222. return AVERROR(EINVAL);
  223. if (!compensation_distance && sample_delta)
  224. return AVERROR(EINVAL);
  225. if (!avr->resample_needed) {
  226. #if FF_API_RESAMPLE_CLOSE_OPEN
  227. /* if resampling was not enabled previously, re-initialize the
  228. AVAudioResampleContext and force resampling */
  229. int fifo_samples;
  230. int restore_matrix = 0;
  231. double matrix[AVRESAMPLE_MAX_CHANNELS * AVRESAMPLE_MAX_CHANNELS] = { 0 };
  232. /* buffer any remaining samples in the output FIFO before closing */
  233. fifo_samples = av_audio_fifo_size(avr->out_fifo);
  234. if (fifo_samples > 0) {
  235. fifo_buf = ff_audio_data_alloc(avr->out_channels, fifo_samples,
  236. avr->out_sample_fmt, NULL);
  237. if (!fifo_buf)
  238. return AVERROR(EINVAL);
  239. ret = ff_audio_data_read_from_fifo(avr->out_fifo, fifo_buf,
  240. fifo_samples);
  241. if (ret < 0)
  242. goto reinit_fail;
  243. }
  244. /* save the channel mixing matrix */
  245. if (avr->am) {
  246. ret = avresample_get_matrix(avr, matrix, AVRESAMPLE_MAX_CHANNELS);
  247. if (ret < 0)
  248. goto reinit_fail;
  249. restore_matrix = 1;
  250. }
  251. /* close the AVAudioResampleContext */
  252. avresample_close(avr);
  253. avr->force_resampling = 1;
  254. /* restore the channel mixing matrix */
  255. if (restore_matrix) {
  256. ret = avresample_set_matrix(avr, matrix, AVRESAMPLE_MAX_CHANNELS);
  257. if (ret < 0)
  258. goto reinit_fail;
  259. }
  260. /* re-open the AVAudioResampleContext */
  261. ret = avresample_open(avr);
  262. if (ret < 0)
  263. goto reinit_fail;
  264. /* restore buffered samples to the output FIFO */
  265. if (fifo_samples > 0) {
  266. ret = ff_audio_data_add_to_fifo(avr->out_fifo, fifo_buf, 0,
  267. fifo_samples);
  268. if (ret < 0)
  269. goto reinit_fail;
  270. ff_audio_data_free(&fifo_buf);
  271. }
  272. #else
  273. av_log(avr, AV_LOG_ERROR, "Unable to set resampling compensation\n");
  274. return AVERROR(EINVAL);
  275. #endif
  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. {
  359. int ch, in_samples, in_leftover, consumed = 0, out_samples = 0;
  360. int ret = AVERROR(EINVAL);
  361. in_samples = src ? src->nb_samples : 0;
  362. in_leftover = c->buffer->nb_samples;
  363. /* add input samples to the internal buffer */
  364. if (src) {
  365. ret = ff_audio_data_combine(c->buffer, in_leftover, src, 0, in_samples);
  366. if (ret < 0)
  367. return ret;
  368. } else if (!in_leftover) {
  369. /* no remaining samples to flush */
  370. return 0;
  371. } else {
  372. /* TODO: pad buffer to flush completely */
  373. }
  374. /* calculate output size and reallocate output buffer if needed */
  375. /* TODO: try to calculate this without the dummy resample() run */
  376. if (!dst->read_only && dst->allow_realloc) {
  377. out_samples = resample(c, NULL, NULL, NULL, c->buffer->nb_samples,
  378. INT_MAX, 0);
  379. ret = ff_audio_data_realloc(dst, out_samples);
  380. if (ret < 0) {
  381. av_log(c->avr, AV_LOG_ERROR, "error reallocating output\n");
  382. return ret;
  383. }
  384. }
  385. /* resample each channel plane */
  386. for (ch = 0; ch < c->buffer->channels; ch++) {
  387. out_samples = resample(c, (void *)dst->data[ch],
  388. (const void *)c->buffer->data[ch], &consumed,
  389. c->buffer->nb_samples, dst->allocated_samples,
  390. ch + 1 == c->buffer->channels);
  391. }
  392. if (out_samples < 0) {
  393. av_log(c->avr, AV_LOG_ERROR, "error during resampling\n");
  394. return out_samples;
  395. }
  396. /* drain consumed samples from the internal buffer */
  397. ff_audio_data_drain(c->buffer, consumed);
  398. av_dlog(c->avr, "resampled %d in + %d leftover to %d out + %d leftover\n",
  399. in_samples, in_leftover, out_samples, c->buffer->nb_samples);
  400. dst->nb_samples = out_samples;
  401. return 0;
  402. }
  403. int avresample_get_delay(AVAudioResampleContext *avr)
  404. {
  405. if (!avr->resample_needed || !avr->resample)
  406. return 0;
  407. return avr->resample->buffer->nb_samples;
  408. }