resample.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. /*
  2. * audio resampling
  3. * Copyright (c) 2004-2012 Michael Niedermayer <michaelni@gmx.at>
  4. * bessel function: Copyright (c) 2006 Xiaogang Zhang
  5. *
  6. * This file is part of FFmpeg.
  7. *
  8. * FFmpeg is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Lesser General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2.1 of the License, or (at your option) any later version.
  12. *
  13. * FFmpeg is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * Lesser General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Lesser General Public
  19. * License along with FFmpeg; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. */
  22. /**
  23. * @file
  24. * audio resampling
  25. * @author Michael Niedermayer <michaelni@gmx.at>
  26. */
  27. #include "libavutil/avassert.h"
  28. #include "libavutil/cpu.h"
  29. #include "resample.h"
  30. /**
  31. * builds a polyphase filterbank.
  32. * @param factor resampling factor
  33. * @param scale wanted sum of coefficients for each filter
  34. * @param filter_type filter type
  35. * @param kaiser_beta kaiser window beta
  36. * @return 0 on success, negative on error
  37. */
  38. static int build_filter(ResampleContext *c, void *filter, double factor, int tap_count, int alloc, int phase_count, int scale,
  39. int filter_type, double kaiser_beta){
  40. int ph, i;
  41. int ph_nb = phase_count % 2 ? phase_count : phase_count / 2 + 1;
  42. double x, y, w, t, s;
  43. double *tab = av_malloc_array(tap_count+1, sizeof(*tab));
  44. double *sin_lut = av_malloc_array(ph_nb, sizeof(*sin_lut));
  45. const int center= (tap_count-1)/2;
  46. double norm = 0;
  47. int ret = AVERROR(ENOMEM);
  48. if (!tab || !sin_lut)
  49. goto fail;
  50. av_assert0(tap_count == 1 || tap_count % 2 == 0);
  51. /* if upsampling, only need to interpolate, no filter */
  52. if (factor > 1.0)
  53. factor = 1.0;
  54. if (factor == 1.0) {
  55. for (ph = 0; ph < ph_nb; ph++)
  56. sin_lut[ph] = sin(M_PI * ph / phase_count) * (center & 1 ? 1 : -1);
  57. }
  58. for(ph = 0; ph < ph_nb; ph++) {
  59. s = sin_lut[ph];
  60. for(i=0;i<tap_count;i++) {
  61. x = M_PI * ((double)(i - center) - (double)ph / phase_count) * factor;
  62. if (x == 0) y = 1.0;
  63. else if (factor == 1.0)
  64. y = s / x;
  65. else
  66. y = sin(x) / x;
  67. switch(filter_type){
  68. case SWR_FILTER_TYPE_CUBIC:{
  69. const float d= -0.5; //first order derivative = -0.5
  70. x = fabs(((double)(i - center) - (double)ph / phase_count) * factor);
  71. if(x<1.0) y= 1 - 3*x*x + 2*x*x*x + d*( -x*x + x*x*x);
  72. else y= d*(-4 + 8*x - 5*x*x + x*x*x);
  73. break;}
  74. case SWR_FILTER_TYPE_BLACKMAN_NUTTALL:
  75. w = 2.0*x / (factor*tap_count);
  76. t = -cos(w);
  77. y *= 0.3635819 - 0.4891775 * t + 0.1365995 * (2*t*t-1) - 0.0106411 * (4*t*t*t - 3*t);
  78. break;
  79. case SWR_FILTER_TYPE_KAISER:
  80. w = 2.0*x / (factor*tap_count*M_PI);
  81. y *= av_bessel_i0(kaiser_beta*sqrt(FFMAX(1-w*w, 0)));
  82. break;
  83. default:
  84. av_assert0(0);
  85. }
  86. tab[i] = y;
  87. s = -s;
  88. if (!ph)
  89. norm += y;
  90. }
  91. /* normalize so that an uniform color remains the same */
  92. switch(c->format){
  93. case AV_SAMPLE_FMT_S16P:
  94. for(i=0;i<tap_count;i++)
  95. ((int16_t*)filter)[ph * alloc + i] = av_clip_int16(lrintf(tab[i] * scale / norm));
  96. if (phase_count % 2) break;
  97. for (i = 0; i < tap_count; i++)
  98. ((int16_t*)filter)[(phase_count-ph) * alloc + tap_count-1-i] = ((int16_t*)filter)[ph * alloc + i];
  99. break;
  100. case AV_SAMPLE_FMT_S32P:
  101. for(i=0;i<tap_count;i++)
  102. ((int32_t*)filter)[ph * alloc + i] = av_clipl_int32(llrint(tab[i] * scale / norm));
  103. if (phase_count % 2) break;
  104. for (i = 0; i < tap_count; i++)
  105. ((int32_t*)filter)[(phase_count-ph) * alloc + tap_count-1-i] = ((int32_t*)filter)[ph * alloc + i];
  106. break;
  107. case AV_SAMPLE_FMT_FLTP:
  108. for(i=0;i<tap_count;i++)
  109. ((float*)filter)[ph * alloc + i] = tab[i] * scale / norm;
  110. if (phase_count % 2) break;
  111. for (i = 0; i < tap_count; i++)
  112. ((float*)filter)[(phase_count-ph) * alloc + tap_count-1-i] = ((float*)filter)[ph * alloc + i];
  113. break;
  114. case AV_SAMPLE_FMT_DBLP:
  115. for(i=0;i<tap_count;i++)
  116. ((double*)filter)[ph * alloc + i] = tab[i] * scale / norm;
  117. if (phase_count % 2) break;
  118. for (i = 0; i < tap_count; i++)
  119. ((double*)filter)[(phase_count-ph) * alloc + tap_count-1-i] = ((double*)filter)[ph * alloc + i];
  120. break;
  121. }
  122. }
  123. #if 0
  124. {
  125. #define LEN 1024
  126. int j,k;
  127. double sine[LEN + tap_count];
  128. double filtered[LEN];
  129. double maxff=-2, minff=2, maxsf=-2, minsf=2;
  130. for(i=0; i<LEN; i++){
  131. double ss=0, sf=0, ff=0;
  132. for(j=0; j<LEN+tap_count; j++)
  133. sine[j]= cos(i*j*M_PI/LEN);
  134. for(j=0; j<LEN; j++){
  135. double sum=0;
  136. ph=0;
  137. for(k=0; k<tap_count; k++)
  138. sum += filter[ph * tap_count + k] * sine[k+j];
  139. filtered[j]= sum / (1<<FILTER_SHIFT);
  140. ss+= sine[j + center] * sine[j + center];
  141. ff+= filtered[j] * filtered[j];
  142. sf+= sine[j + center] * filtered[j];
  143. }
  144. ss= sqrt(2*ss/LEN);
  145. ff= sqrt(2*ff/LEN);
  146. sf= 2*sf/LEN;
  147. maxff= FFMAX(maxff, ff);
  148. minff= FFMIN(minff, ff);
  149. maxsf= FFMAX(maxsf, sf);
  150. minsf= FFMIN(minsf, sf);
  151. if(i%11==0){
  152. av_log(NULL, AV_LOG_ERROR, "i:%4d ss:%f ff:%13.6e-%13.6e sf:%13.6e-%13.6e\n", i, ss, maxff, minff, maxsf, minsf);
  153. minff=minsf= 2;
  154. maxff=maxsf= -2;
  155. }
  156. }
  157. }
  158. #endif
  159. ret = 0;
  160. fail:
  161. av_free(tab);
  162. av_free(sin_lut);
  163. return ret;
  164. }
  165. static void resample_free(ResampleContext **cc){
  166. ResampleContext *c = *cc;
  167. if(!c)
  168. return;
  169. av_freep(&c->filter_bank);
  170. av_freep(cc);
  171. }
  172. static ResampleContext *resample_init(ResampleContext *c, int out_rate, int in_rate, int filter_size, int phase_shift, int linear,
  173. double cutoff0, enum AVSampleFormat format, enum SwrFilterType filter_type, double kaiser_beta,
  174. double precision, int cheby, int exact_rational)
  175. {
  176. double cutoff = cutoff0? cutoff0 : 0.97;
  177. double factor= FFMIN(out_rate * cutoff / in_rate, 1.0);
  178. int phase_count= 1<<phase_shift;
  179. int phase_count_compensation = phase_count;
  180. int filter_length = FFMAX((int)ceil(filter_size/factor), 1);
  181. if (filter_length > 1)
  182. filter_length = FFALIGN(filter_length, 2);
  183. if (exact_rational) {
  184. int phase_count_exact, phase_count_exact_den;
  185. av_reduce(&phase_count_exact, &phase_count_exact_den, out_rate, in_rate, INT_MAX);
  186. if (phase_count_exact <= phase_count) {
  187. phase_count_compensation = phase_count_exact * (phase_count / phase_count_exact);
  188. phase_count = phase_count_exact;
  189. }
  190. }
  191. if (!c || c->phase_count != phase_count || c->linear!=linear || c->factor != factor
  192. || c->filter_length != filter_length || c->format != format
  193. || c->filter_type != filter_type || c->kaiser_beta != kaiser_beta) {
  194. resample_free(&c);
  195. c = av_mallocz(sizeof(*c));
  196. if (!c)
  197. return NULL;
  198. c->format= format;
  199. c->felem_size= av_get_bytes_per_sample(c->format);
  200. switch(c->format){
  201. case AV_SAMPLE_FMT_S16P:
  202. c->filter_shift = 15;
  203. break;
  204. case AV_SAMPLE_FMT_S32P:
  205. c->filter_shift = 30;
  206. break;
  207. case AV_SAMPLE_FMT_FLTP:
  208. case AV_SAMPLE_FMT_DBLP:
  209. c->filter_shift = 0;
  210. break;
  211. default:
  212. av_log(NULL, AV_LOG_ERROR, "Unsupported sample format\n");
  213. av_assert0(0);
  214. }
  215. if (filter_size/factor > INT32_MAX/256) {
  216. av_log(NULL, AV_LOG_ERROR, "Filter length too large\n");
  217. goto error;
  218. }
  219. c->phase_count = phase_count;
  220. c->linear = linear;
  221. c->factor = factor;
  222. c->filter_length = filter_length;
  223. c->filter_alloc = FFALIGN(c->filter_length, 8);
  224. c->filter_bank = av_calloc(c->filter_alloc, (phase_count+1)*c->felem_size);
  225. c->filter_type = filter_type;
  226. c->kaiser_beta = kaiser_beta;
  227. c->phase_count_compensation = phase_count_compensation;
  228. if (!c->filter_bank)
  229. goto error;
  230. if (build_filter(c, (void*)c->filter_bank, factor, c->filter_length, c->filter_alloc, phase_count, 1<<c->filter_shift, filter_type, kaiser_beta))
  231. goto error;
  232. memcpy(c->filter_bank + (c->filter_alloc*phase_count+1)*c->felem_size, c->filter_bank, (c->filter_alloc-1)*c->felem_size);
  233. memcpy(c->filter_bank + (c->filter_alloc*phase_count )*c->felem_size, c->filter_bank + (c->filter_alloc - 1)*c->felem_size, c->felem_size);
  234. }
  235. c->compensation_distance= 0;
  236. if(!av_reduce(&c->src_incr, &c->dst_incr, out_rate, in_rate * (int64_t)phase_count, INT32_MAX/2))
  237. goto error;
  238. while (c->dst_incr < (1<<20) && c->src_incr < (1<<20)) {
  239. c->dst_incr *= 2;
  240. c->src_incr *= 2;
  241. }
  242. c->ideal_dst_incr = c->dst_incr;
  243. c->dst_incr_div = c->dst_incr / c->src_incr;
  244. c->dst_incr_mod = c->dst_incr % c->src_incr;
  245. c->index= -phase_count*((c->filter_length-1)/2);
  246. c->frac= 0;
  247. swri_resample_dsp_init(c);
  248. return c;
  249. error:
  250. av_freep(&c->filter_bank);
  251. av_free(c);
  252. return NULL;
  253. }
  254. static int rebuild_filter_bank_with_compensation(ResampleContext *c)
  255. {
  256. uint8_t *new_filter_bank;
  257. int new_src_incr, new_dst_incr;
  258. int phase_count = c->phase_count_compensation;
  259. int ret;
  260. if (phase_count == c->phase_count)
  261. return 0;
  262. av_assert0(!c->frac && !c->dst_incr_mod);
  263. new_filter_bank = av_calloc(c->filter_alloc, (phase_count + 1) * c->felem_size);
  264. if (!new_filter_bank)
  265. return AVERROR(ENOMEM);
  266. ret = build_filter(c, new_filter_bank, c->factor, c->filter_length, c->filter_alloc,
  267. phase_count, 1 << c->filter_shift, c->filter_type, c->kaiser_beta);
  268. if (ret < 0) {
  269. av_freep(&new_filter_bank);
  270. return ret;
  271. }
  272. memcpy(new_filter_bank + (c->filter_alloc*phase_count+1)*c->felem_size, new_filter_bank, (c->filter_alloc-1)*c->felem_size);
  273. memcpy(new_filter_bank + (c->filter_alloc*phase_count )*c->felem_size, new_filter_bank + (c->filter_alloc - 1)*c->felem_size, c->felem_size);
  274. if (!av_reduce(&new_src_incr, &new_dst_incr, c->src_incr,
  275. c->dst_incr * (int64_t)(phase_count/c->phase_count), INT32_MAX/2))
  276. {
  277. av_freep(&new_filter_bank);
  278. return AVERROR(EINVAL);
  279. }
  280. c->src_incr = new_src_incr;
  281. c->dst_incr = new_dst_incr;
  282. while (c->dst_incr < (1<<20) && c->src_incr < (1<<20)) {
  283. c->dst_incr *= 2;
  284. c->src_incr *= 2;
  285. }
  286. c->ideal_dst_incr = c->dst_incr;
  287. c->dst_incr_div = c->dst_incr / c->src_incr;
  288. c->dst_incr_mod = c->dst_incr % c->src_incr;
  289. c->index *= phase_count / c->phase_count;
  290. c->phase_count = phase_count;
  291. av_freep(&c->filter_bank);
  292. c->filter_bank = new_filter_bank;
  293. return 0;
  294. }
  295. static int set_compensation(ResampleContext *c, int sample_delta, int compensation_distance){
  296. int ret;
  297. if (compensation_distance && sample_delta) {
  298. ret = rebuild_filter_bank_with_compensation(c);
  299. if (ret < 0)
  300. return ret;
  301. }
  302. c->compensation_distance= compensation_distance;
  303. if (compensation_distance)
  304. c->dst_incr = c->ideal_dst_incr - c->ideal_dst_incr * (int64_t)sample_delta / compensation_distance;
  305. else
  306. c->dst_incr = c->ideal_dst_incr;
  307. c->dst_incr_div = c->dst_incr / c->src_incr;
  308. c->dst_incr_mod = c->dst_incr % c->src_incr;
  309. return 0;
  310. }
  311. static int multiple_resample(ResampleContext *c, AudioData *dst, int dst_size, AudioData *src, int src_size, int *consumed){
  312. int i;
  313. int64_t max_src_size = (INT64_MAX/2 / c->phase_count) / c->src_incr;
  314. if (c->compensation_distance)
  315. dst_size = FFMIN(dst_size, c->compensation_distance);
  316. src_size = FFMIN(src_size, max_src_size);
  317. *consumed = 0;
  318. if (c->filter_length == 1 && c->phase_count == 1) {
  319. int64_t index2= (1LL<<32)*c->frac/c->src_incr + (1LL<<32)*c->index + 1;
  320. int64_t incr= (1LL<<32) * c->dst_incr / c->src_incr + 1;
  321. int new_size = (src_size * (int64_t)c->src_incr - c->frac + c->dst_incr - 1) / c->dst_incr;
  322. dst_size = FFMAX(FFMIN(dst_size, new_size), 0);
  323. if (dst_size > 0) {
  324. for (i = 0; i < dst->ch_count; i++) {
  325. c->dsp.resample_one(dst->ch[i], src->ch[i], dst_size, index2, incr);
  326. if (i+1 == dst->ch_count) {
  327. c->index += dst_size * c->dst_incr_div;
  328. c->index += (c->frac + dst_size * (int64_t)c->dst_incr_mod) / c->src_incr;
  329. av_assert2(c->index >= 0);
  330. *consumed = c->index;
  331. c->frac = (c->frac + dst_size * (int64_t)c->dst_incr_mod) % c->src_incr;
  332. c->index = 0;
  333. }
  334. }
  335. }
  336. } else {
  337. int64_t end_index = (1LL + src_size - c->filter_length) * c->phase_count;
  338. int64_t delta_frac = (end_index - c->index) * c->src_incr - c->frac;
  339. int delta_n = (delta_frac + c->dst_incr - 1) / c->dst_incr;
  340. int (*resample_func)(struct ResampleContext *c, void *dst,
  341. const void *src, int n, int update_ctx);
  342. dst_size = FFMAX(FFMIN(dst_size, delta_n), 0);
  343. if (dst_size > 0) {
  344. /* resample_linear and resample_common should have same behavior
  345. * when frac and dst_incr_mod are zero */
  346. resample_func = (c->linear && (c->frac || c->dst_incr_mod)) ?
  347. c->dsp.resample_linear : c->dsp.resample_common;
  348. for (i = 0; i < dst->ch_count; i++)
  349. *consumed = resample_func(c, dst->ch[i], src->ch[i], dst_size, i+1 == dst->ch_count);
  350. }
  351. }
  352. if (c->compensation_distance) {
  353. c->compensation_distance -= dst_size;
  354. if (!c->compensation_distance) {
  355. c->dst_incr = c->ideal_dst_incr;
  356. c->dst_incr_div = c->dst_incr / c->src_incr;
  357. c->dst_incr_mod = c->dst_incr % c->src_incr;
  358. }
  359. }
  360. return dst_size;
  361. }
  362. static int64_t get_delay(struct SwrContext *s, int64_t base){
  363. ResampleContext *c = s->resample;
  364. int64_t num = s->in_buffer_count - (c->filter_length-1)/2;
  365. num *= c->phase_count;
  366. num -= c->index;
  367. num *= c->src_incr;
  368. num -= c->frac;
  369. return av_rescale(num, base, s->in_sample_rate*(int64_t)c->src_incr * c->phase_count);
  370. }
  371. static int64_t get_out_samples(struct SwrContext *s, int in_samples) {
  372. ResampleContext *c = s->resample;
  373. // The + 2 are added to allow implementations to be slightly inaccurate, they should not be needed currently.
  374. // They also make it easier to proof that changes and optimizations do not
  375. // break the upper bound.
  376. int64_t num = s->in_buffer_count + 2LL + in_samples;
  377. num *= c->phase_count;
  378. num -= c->index;
  379. num = av_rescale_rnd(num, s->out_sample_rate, ((int64_t)s->in_sample_rate) * c->phase_count, AV_ROUND_UP) + 2;
  380. if (c->compensation_distance) {
  381. if (num > INT_MAX)
  382. return AVERROR(EINVAL);
  383. num = FFMAX(num, (num * c->ideal_dst_incr - 1) / c->dst_incr + 1);
  384. }
  385. return num;
  386. }
  387. static int resample_flush(struct SwrContext *s) {
  388. ResampleContext *c = s->resample;
  389. AudioData *a= &s->in_buffer;
  390. int i, j, ret;
  391. int reflection = (FFMIN(s->in_buffer_count, c->filter_length) + 1) / 2;
  392. if((ret = swri_realloc_audio(a, s->in_buffer_index + s->in_buffer_count + reflection)) < 0)
  393. return ret;
  394. av_assert0(a->planar);
  395. for(i=0; i<a->ch_count; i++){
  396. for(j=0; j<reflection; j++){
  397. memcpy(a->ch[i] + (s->in_buffer_index+s->in_buffer_count+j )*a->bps,
  398. a->ch[i] + (s->in_buffer_index+s->in_buffer_count-j-1)*a->bps, a->bps);
  399. }
  400. }
  401. s->in_buffer_count += reflection;
  402. return 0;
  403. }
  404. // in fact the whole handle multiple ridiculously small buffers might need more thinking...
  405. static int invert_initial_buffer(ResampleContext *c, AudioData *dst, const AudioData *src,
  406. int in_count, int *out_idx, int *out_sz)
  407. {
  408. int n, ch, num = FFMIN(in_count + *out_sz, c->filter_length + 1), res;
  409. if (c->index >= 0)
  410. return 0;
  411. if ((res = swri_realloc_audio(dst, c->filter_length * 2 + 1)) < 0)
  412. return res;
  413. // copy
  414. for (n = *out_sz; n < num; n++) {
  415. for (ch = 0; ch < src->ch_count; ch++) {
  416. memcpy(dst->ch[ch] + ((c->filter_length + n) * c->felem_size),
  417. src->ch[ch] + ((n - *out_sz) * c->felem_size), c->felem_size);
  418. }
  419. }
  420. // if not enough data is in, return and wait for more
  421. if (num < c->filter_length + 1) {
  422. *out_sz = num;
  423. *out_idx = c->filter_length;
  424. return INT_MAX;
  425. }
  426. // else invert
  427. for (n = 1; n <= c->filter_length; n++) {
  428. for (ch = 0; ch < src->ch_count; ch++) {
  429. memcpy(dst->ch[ch] + ((c->filter_length - n) * c->felem_size),
  430. dst->ch[ch] + ((c->filter_length + n) * c->felem_size),
  431. c->felem_size);
  432. }
  433. }
  434. res = num - *out_sz;
  435. *out_idx = c->filter_length;
  436. while (c->index < 0) {
  437. --*out_idx;
  438. c->index += c->phase_count;
  439. }
  440. *out_sz = FFMAX(*out_sz + c->filter_length,
  441. 1 + c->filter_length * 2) - *out_idx;
  442. return FFMAX(res, 0);
  443. }
  444. struct Resampler const swri_resampler={
  445. resample_init,
  446. resample_free,
  447. multiple_resample,
  448. resample_flush,
  449. set_compensation,
  450. get_delay,
  451. invert_initial_buffer,
  452. get_out_samples,
  453. };