resampler.c 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427
  1. ////////////////////////////////////////////////////////////////////////////
  2. // **** RESAMPLER **** //
  3. // Sinc-based Audio Resampling //
  4. // Copyright (c) 2006 - 2023 David Bryant. //
  5. // All Rights Reserved. //
  6. // Distributed under the BSD Software License (see license.txt) //
  7. ////////////////////////////////////////////////////////////////////////////
  8. // resampler.c
  9. #include "resampler.h"
  10. #ifdef ENABLE_EXTRAPOLATION
  11. #include "extrapolator.h"
  12. #endif
  13. static void init_filter(Resample *cxt, artsample_t *filter, double fraction);
  14. static double subsample_no_interpolate_precise(Resample *cxt,
  15. artsample_t *source,
  16. double offset);
  17. static double subsample_interpolate_precise(Resample *cxt, artsample_t *source,
  18. double offset);
  19. static double subsample_no_interpolate(Resample *cxt, artsample_t *source,
  20. double offset);
  21. static double subsample_interpolate(Resample *cxt, artsample_t *source,
  22. double offset);
  23. static unsigned long gcd(unsigned long a, unsigned long b);
  24. // There are now two functions to initialize a resampler context. The legacy
  25. // version is for arbitrary resampling operations with no fixed ratio (i.e.,
  26. // ASRCs), and its API is unchanged from previous versions of the resampler. The
  27. // resampler initially targeted this use case.
  28. //
  29. // A new version of the initialization function, resamplerFixedRatioInit(), is
  30. // for fixed-ratio sample rate conversions (i.e., conversions from one specific
  31. // sample rate to another) with no fractional phase shift. This version can
  32. // provide significantly improved performance and accuracy for such conversions.
  33. // See the new function's description below.
  34. ////////////////////////////////////////////////////////////////////////////////////////////////////
  35. // Initialize a resampler context with the specified characteristics. The
  36. // returned context pointer is used for all subsequent calls to the resampler
  37. // (and should not be dereferenced). A NULL return indicates an error. For the
  38. // flags parameter, note that SUBSAMPLE_INTERPOLATE and BLACKMAN_HARRIS are
  39. // recommended for most applications. This function assumes that the "ratio"
  40. // parameter will be appropriately specified for every call to the resampler.
  41. // The parameters are:
  42. //
  43. // numChannels: the number of audio channels present
  44. //
  45. // numTaps: the number of taps for each sinc interpolation filter
  46. // - must be a multiple of 4, from 4 - 1024 taps
  47. // - affects quality by controlling cutoff sharpness of
  48. // filters
  49. // - linearly affects memory usage and CPU load of resampling
  50. //
  51. // numFilters: the number of sinc filters generated
  52. // - must be 1 - 1024
  53. // - affects quality of interpolated filtering
  54. // - linearly affects memory usage of resampler
  55. //
  56. // lowpassRatio: enable lowpass by specifying the ratio relative to the
  57. // Nyquist frequency of
  58. // the *input* samples (must be > 0.0 and < 1.0); required for
  59. // quality downsampling (except in special cases), but is
  60. // optional otherwise ex: lowpassRatio = lowpass freq in Hz /
  61. // (source rate in Hz / 2.0)
  62. //
  63. // flags: mask for optional feature configuration:
  64. //
  65. // SUBSAMPLE_INTERPOLATE: interpolate values from adjacent filters
  66. // - generally recommended except in special
  67. // situations
  68. // - approximately doubles the CPU load
  69. //
  70. // BLACKMAN_HARRIS: use 4-term Blackman Harris window function
  71. // - generally recommended except in special
  72. // situations
  73. // - if not specified, the default window is Hann
  74. // (raised cosine)
  75. // which has steeper cutoff but poorer stopband
  76. // rejection
  77. //
  78. // RESAMPLE_MULTITHREADED: use multiple threads for processing multiple
  79. // channels in parallel
  80. // - might be slower depending on CPU,
  81. // optimization, caching, etc.
  82. // - optional (define ENABLE_THREADS)
  83. //
  84. //
  85. // EXTRAPOLATE_ENDPOINTS enable sample extrapolation at the beginning and
  86. // end of conversion
  87. // - to use this properly, the resampleAdvance()
  88. // function must be
  89. // called BEFORE sending any data to the
  90. // resampler to delay the initial conversion
  91. // (otherwise samples will be generated
  92. // immediately when there aren't enough samples
  93. // to extrapolate)
  94. // - also, the new "flush" functionality must be
  95. // used instead of
  96. // just sending zeros to the resampler to
  97. // perform a final flush (although this should
  98. // be obvious)
  99. // - optional (define ENABLE_EXTRAPOLATION)
  100. //
  101. // EXTEND_CONVOLUTION_MATH use precise math in convolution (doubles, not
  102. // floats)
  103. // - this can improve resampling quality, but
  104. // just a few dB at best
  105. // - can result in significant performance hit on
  106. // some platforms
  107. // - might be worth it, but generally not
  108. // recommended
  109. // - non-operational when the 64-bit path
  110. // selected
  111. // Notes:
  112. //
  113. // 1. The same resampling instance can be used for upsampling, downsampling, or
  114. // simple (near-unity)
  115. // resampling (e.g., for asynchronous sample rate conversion, phase shifting,
  116. // or filtering). The behavior is controlled by the "ratio" parameter during
  117. // the actual resample processing call. To prevent aliasing, it's important
  118. // to specify a lowpassRatio if the resampler will be used for any
  119. // significant degree of downsampling (ratio < 1.0), but the lowpass can also
  120. // be used independently without any rate conversion (or even when
  121. // upsampling).
  122. //
  123. // 2. When the context is initialized (or reset) the sample histories are filled
  124. // with silence such
  125. // that the resampler is ready to generate output immediately. However, this
  126. // also means that there is an implicit signal delay equal to half the tap
  127. // length of the sinc filters in samples. If zero delay is desired then that
  128. // many samples can be ignored, or the resampleAdvancePosition() function can
  129. // be used to bypass them. Also, at the end of processing an equal length of
  130. // silence must be appended to the input audio to align the output with the
  131. // actual input.
  132. //
  133. // 3. Both the number of interpolation filters and the number of taps per filter
  134. // directly control
  135. // the fidelity of the resampling. The filter length has an approximately
  136. // linear affect on the the CPU load consumed by the resampler, and also on
  137. // the memory requirement (both for the filters themselves and also for the
  138. // sample history storage). On the other hand, the number of filters
  139. // allocated primarily affects just the memory footprint (it has little
  140. // affect on CPU load and so can be large on systems with lots of RAM).
  141. //
  142. // 4. For a fixed-ratio conversion (i.e., conversions from one specific sample
  143. // rate to another) with
  144. // no fractional phase shift, see resampleFixedRatioInit() below.
  145. Resample *resampleInit(int numChannels, int numTaps, int numFilters,
  146. double lowpassRatio, int flags) {
  147. Resample *cxt = calloc(1, sizeof(Resample));
  148. int i;
  149. if (lowpassRatio > 0.0 && lowpassRatio < 1.0) {
  150. flags |= INCLUDE_LOWPASS;
  151. } else {
  152. flags &= ~INCLUDE_LOWPASS;
  153. lowpassRatio = 1.0;
  154. }
  155. if ((numTaps & 3) || numTaps <= 0 || numTaps > 1024) {
  156. fprintf(stderr, "must 4-1024 filter taps, and a multiple of 4!\n");
  157. return NULL;
  158. }
  159. if (numFilters < 1 || numFilters > 1024) {
  160. fprintf(stderr, "must be 1-1024 filters!\n");
  161. return NULL;
  162. }
  163. cxt->lowpassRatio = lowpassRatio;
  164. cxt->numChannels = numChannels;
  165. cxt->numSamples = numTaps * 16;
  166. cxt->numFilters = numFilters;
  167. cxt->numTaps = numTaps;
  168. cxt->flags = flags;
  169. // note that we actually have one more than the specified number of filters
  170. cxt->filters =
  171. (artsample_t **)calloc(cxt->numFilters + 1, sizeof(artsample_t *));
  172. cxt->tempFilter = malloc(numTaps * sizeof(double));
  173. for (i = 0; i <= cxt->numFilters; ++i) {
  174. int j;
  175. cxt->filters[i] = calloc(cxt->numTaps, sizeof(artsample_t));
  176. if (i < cxt->numFilters) {
  177. init_filter(cxt, cxt->filters[i], (double)i / cxt->numFilters);
  178. } else {
  179. // the last filter is essentially identical to the first (just offset one
  180. // tap)
  181. for (j = 0; j < cxt->numTaps; ++j) {
  182. cxt->filters[cxt->numFilters][(j + 1) % cxt->numTaps] =
  183. cxt->filters[0][j];
  184. }
  185. }
  186. }
  187. // The first and last filters should actually have just an odd number of taps,
  188. // but Blackman-Harris doesn't go all the way to zero, so clear the outliers
  189. // here. This almost eliminates the tiny discrepancies caused by different
  190. // processing chunk sizes (those remaining come from math errors and
  191. // rounding).
  192. cxt->filters[0][cxt->numTaps - 1] = (artsample_t)0.0;
  193. cxt->filters[cxt->numFilters][0] = (artsample_t)0.0;
  194. free(cxt->tempFilter);
  195. cxt->tempFilter = NULL;
  196. cxt->buffers = (artsample_t **)calloc(numChannels, sizeof(artsample_t *));
  197. for (i = 0; i < numChannels; ++i) {
  198. cxt->buffers[i] = calloc(cxt->numSamples, sizeof(artsample_t));
  199. }
  200. cxt->outputOffset = numTaps / 2.0;
  201. cxt->inputIndex = numTaps;
  202. #ifdef ENABLE_EXTRAPOLATION
  203. if (cxt->flags & EXTRAPOLATE_ENDPOINTS) {
  204. cxt->flags |= EXTRAPOLATE_PREFILL;
  205. }
  206. #endif
  207. #ifdef ENABLE_THREADS
  208. if (numChannels > 1 && (flags & RESAMPLE_MULTITHREADED)) {
  209. cxt->workers = workersInit(numChannels);
  210. }
  211. #endif
  212. // extended math only makes sense if we have a 32-bit path
  213. if (sizeof(artsample_t) == 4 && (cxt->flags & EXTEND_CONVOLUTION_MATH)) {
  214. cxt->subsample = (cxt->flags & SUBSAMPLE_INTERPOLATE)
  215. ? subsample_interpolate_precise
  216. : subsample_no_interpolate_precise;
  217. } else {
  218. cxt->subsample = (cxt->flags & SUBSAMPLE_INTERPOLATE)
  219. ? subsample_interpolate
  220. : subsample_no_interpolate;
  221. }
  222. return cxt;
  223. }
  224. // Initialize a resampler context with the specified characteristics. The
  225. // returned context pointer is used for all subsequent calls to the resampler
  226. // (and should not be dereferenced). A NULL return indicates an error. For the
  227. // flags parameter, note that SUBSAMPLE_INTERPOLATE, BLACKMAN_HARRIS, and
  228. // INCLUDE_LOWPASS are all recommended for most applications.
  229. //
  230. // This function will determine whether the specified fixed-ratio conversion
  231. // operation is possible with a reduced number of filters that can be used
  232. // directly without interpolation (i.e., every calculation exactly aligns to a
  233. // single filter). If this is possible then several advantages result. First,
  234. // fewer filters are required which reduces the memory footprint. Also, the
  235. // performance is approximately doubled due to the elimination of the
  236. // interpolation step. And finally, the numerical accuracy of the resampling is
  237. // improved, also due to the lack of interpolation inaccuracies. Note that
  238. // subsample phase shifts are not allowed in this mode, so if these are required
  239. // set the NO_FILTER_REDUCTION bit in the flags to prevent this optimization.
  240. //
  241. // If the number of filters cannot be reduced because the sample rates are not
  242. // sufficiently related for the max number of filters specified, then that
  243. // specified maximum filter count will be used with the specfied interpolation
  244. // mode (recommended to be ON). If the number filters is reduced, then the
  245. // supplied interpolation mode flag is ignored.
  246. //
  247. // When using this version there is also the ability of the resampler to choose
  248. // an optimum lowpass cutoff frequency for downsampling operations only based on
  249. // the sampling rates and the number of filter taps. Simply set the
  250. // INCLUDE_LOWPASS bit in the flags parameter and set the lowpassFreq parameter
  251. // to zero. This is generally recommended because it does not introduce a
  252. // lowpass for upsampling.
  253. //
  254. // numChannels: the number of audio channels present
  255. //
  256. // numTaps: the number of taps for each sinc interpolation filter
  257. // - must be a multiple of 4, from 4 - 1024 taps
  258. // - affects quality by controlling cutoff sharpness of
  259. // filters
  260. // - linearly affects memory usage and CPU load of resampling
  261. //
  262. // maxFilters: the maximum number of sinc filters allowed
  263. // - must be 1 - 1024, will be reduced if possible
  264. // - affects quality of interpolated filtering
  265. // - linearly affects memory usage of resampler
  266. //
  267. // sourceRate: the fixed source and destination sample rates
  268. // destinRate: - the "ratio" parameter to other resampling functions is
  269. // ignored
  270. //
  271. // lowpassFreq: enable lowpass by specifying a lowpass frequency here
  272. // - to have the library determine an appropriate lowpass
  273. // frequency based
  274. // on the sample rates and filter length, leave this
  275. // parameter zero and set the INCLUDE_LOWPASS flag bit
  276. // below
  277. //
  278. // flags: mask for optional feature configuration:
  279. //
  280. // SUBSAMPLE_INTERPOLATE: interpolate values from adjacent filters
  281. // - recommended in case the reduced filter
  282. // determination fails
  283. // - will be ignored if a reduced filter count is
  284. // selected
  285. // - approximately doubles the CPU load (if used)
  286. //
  287. // NO_FILTER_REDUCTION: don't allow the automatic reduction of filter
  288. // count optimization
  289. // - this prevents the resampler from attempting
  290. // to reduce the
  291. // number of filters, which includes disabling
  292. // interpolation
  293. // - only necessary if subsample phase-shifts are
  294. // required, which
  295. // is not a normal use case for fixed-ratio
  296. // resampling
  297. //
  298. // BLACKMAN_HARRIS: use 4-term Blackman Harris window function
  299. // - generally recommended except in special
  300. // situations
  301. // - if not specified, the default window is Hann
  302. // (raised cosine)
  303. // which has steeper cutoff but poorer stopband
  304. // rejection
  305. //
  306. // RESAMPLE_MULTITHREADED: use multiple threads for processing multiple
  307. // channels in parallel
  308. // - might be slower depending on CPU,
  309. // optimization, caching, etc.
  310. // - optional (define ENABLE_THREADS)
  311. //
  312. // INCLUDE_LOWPASS: enable automatic calculation of appropriate
  313. // lowpass frequency
  314. // - also set the lowpassFreq parameter (above)
  315. // to zero
  316. // - calculation is based on sample rates and
  317. // filter length
  318. // - no lowpass is used for upsampling or
  319. // near-unity resampling,
  320. // but can always be enabled by setting the
  321. // lowpassFreq directly
  322. //
  323. // EXTRAPOLATE_ENDPOINTS enable sample extrapolation at the beginning and
  324. // end of conversion
  325. // - to use this properly, the resampleAdvance()
  326. // function must be
  327. // called BEFORE sending any data to the
  328. // resampler to delay the initial conversion
  329. // (otherwise samples will be generated
  330. // immediately when there aren't enough samples
  331. // to extrapolate)
  332. // - also, the new "flush" functionality must be
  333. // used instead of
  334. // just sending zeros to the resampler to
  335. // perform a final flush (although this should
  336. // be obvious)
  337. // - optional (define ENABLE_EXTRAPOLATION)
  338. //
  339. // EXTEND_CONVOLUTION_MATH use precise math in convolution (doubles, not
  340. // floats)
  341. // - this can improve resampling quality, but
  342. // just a few dB at best
  343. // - can result in significant performance hit on
  344. // some platforms
  345. // - might be worth it, but generally not
  346. // recommended
  347. // - non-operational when the 64-bit path
  348. // selected
  349. // Notes:
  350. //
  351. // 1. The resampling instance created by this call can only be used to perform
  352. // the specified
  353. // conversion as the "ratio" parameter in the processing functions is
  354. // ignored. Also subsample phase advances are not allowed.
  355. //
  356. // 2. When the context is initialized (or reset) the sample histories are filled
  357. // with silence such
  358. // that the resampler is ready to generate output immediately. However, this
  359. // also means that there is an implicit signal delay equal to half the tap
  360. // length of the sinc filters in samples. If zero delay is desired then that
  361. // many samples can be ignored, or the resampleAdvancePosition() function can
  362. // be used to bypass them. Also, at the end of processing an equal length of
  363. // silence must be appended to the input audio to align the output with the
  364. // actual input.
  365. //
  366. // 3. The number of taps per filter directly control the fidelity of the
  367. // resampling. The filter length
  368. // has an approximately linear affect on the the CPU load consumed by the
  369. // resampler, and also on the memory requirement (both for the filters
  370. // themselves and also for the sample history storage). It is assumed that
  371. // this version of the resampler instance has exactly the optimum number of
  372. // filters to eliminate the need for interpolation and provide the highest
  373. // possible accuracy, but otherwise the maximum number of filters specified
  374. // will be used.
  375. Resample *resampleFixedRatioInit(int numChannels, int numTaps, int maxFilters,
  376. double sourceRate, double destinRate,
  377. int lowpassFreq, int flags) {
  378. double lowpassRatio = lowpassFreq / (destinRate / 2.0);
  379. double resampleRatio = destinRate / sourceRate;
  380. Resample *cxt;
  381. if (lowpassFreq > destinRate / 2.0) {
  382. fprintf(stderr,
  383. "lowpass frequency must be lower than destination Nyquist!\n");
  384. return NULL;
  385. }
  386. // if we can use the exact number of filters for interpolation-free resampling
  387. // without exceeding the specified limit, do it
  388. if (sourceRate == floor(sourceRate) && destinRate == floor(destinRate) &&
  389. !(flags & NO_FILTER_REDUCTION)) {
  390. unsigned long factor =
  391. (unsigned long)destinRate /
  392. gcd((unsigned long)sourceRate, (unsigned long)destinRate);
  393. if (factor <= maxFilters) {
  394. flags &= ~SUBSAMPLE_INTERPOLATE;
  395. maxFilters = (int)factor;
  396. // if the number of filters is not a power of two, snap to the nearest
  397. // filter after each buffer
  398. if (maxFilters & (maxFilters - 1)) {
  399. flags |= RESAMPLER_SNAP_OFFSET;
  400. }
  401. }
  402. }
  403. // this is where we calculate an optimized lowpass ratio for the specified
  404. // rates and filter length current target is around 98 dB attenuation at the
  405. // Nyquist frequency, assuming a long enough filter
  406. if (!lowpassFreq && (flags & INCLUDE_LOWPASS) && destinRate < sourceRate) {
  407. lowpassRatio = 1.0 - (7.5 / numTaps / resampleRatio);
  408. if (lowpassRatio < 0.8) {
  409. lowpassRatio = 0.8;
  410. }
  411. if (lowpassRatio < resampleRatio) {
  412. lowpassRatio = resampleRatio;
  413. }
  414. }
  415. cxt =
  416. resampleInit(numChannels, numTaps, maxFilters,
  417. lowpassRatio * resampleRatio, flags | RESAMPLE_FIXED_RATIO);
  418. if (cxt) {
  419. cxt->fixedRatio = destinRate / sourceRate;
  420. }
  421. return cxt;
  422. }
  423. // Here are several functions to query the configuration of the resampler. These
  424. // were not previously required because the configuration was fully specfied by
  425. // the initialization call, but with the new fixed-ratio initialization some
  426. // configuration is indeterminate.
  427. // Note that lowpass ratio is relative to the Nyquist frequency of the *source*
  428. // sample rate with 1.0 indicating no lowpass configured.
  429. double resampleGetLowpassRatio(Resample *cxt) {
  430. return cxt->lowpassRatio;
  431. }
  432. int resampleGetNumFilters(Resample *cxt) {
  433. return cxt->numFilters;
  434. }
  435. int resampleInterpolationUsed(Resample *cxt) {
  436. return cxt->flags & SUBSAMPLE_INTERPOLATE;
  437. }
  438. // Reset a resampler context to its initialized state. Specifically, any history
  439. // is discarded and this should be used when an audio "flush" or other
  440. // discontinuity occurs.
  441. void resampleReset(Resample *cxt) {
  442. int i;
  443. for (i = 0; i < cxt->numChannels; ++i) {
  444. memset(cxt->buffers[i], 0, cxt->numSamples * sizeof(artsample_t));
  445. }
  446. cxt->outputOffset = cxt->numTaps / 2.0;
  447. cxt->inputIndex = cxt->numTaps;
  448. if (cxt->flags & EXTRAPOLATE_ENDPOINTS) {
  449. cxt->flags |= EXTRAPOLATE_PREFILL;
  450. }
  451. cxt->flags &=
  452. ~RESAMPLER_FLUSHED; // resampler can now be used again after flush
  453. }
  454. // Run the resampler context at the specified output ratio and return both the
  455. // number of input samples consumed and output samples generated (in the
  456. // ResampleResult structure). Over time the average number of output samples
  457. // will be equal to the number of input samples multiplied by the given ratio,
  458. // but of course in a single call only an integer number of samples can be
  459. // generated. The numInputFrames parameter indicates the number of samples
  460. // available at "input" and the numOutputFrames indicates the number of samples
  461. // at "output" that can be written. The resampling proceeds until EITHER the
  462. // input is exhausted or space at the output is exhausted (there is no other
  463. // limit).
  464. //
  465. // This is the "non-interleaved" version of the resampler where the audio sample
  466. // buffers for different channels are passed in as an array of float pointers.
  467. // There is also an "interleaved" version (see below).
  468. //
  469. // If this resampler was created with the resampleFixedRatioInit() function,
  470. // then the "ratio" parameter is ignored and the originally specified conversion
  471. // is performed.
  472. //
  473. // To perform a "flush" operation on the resampler, set the numInputFrames to -1
  474. // (the input pointer can be NULL in this case). This flush is required to align
  475. // the output of the resampler, which is delayed by half the sinc filter width,
  476. // with the input. Previously, this flush alignment was forced by feeding the
  477. // appropriate number of zeros into the resampler, but now this can be
  478. // accomplished explicitly, and more cleanly, this way. Also, if sample
  479. // extrapolation has been selected in the init call (with the
  480. // EXTRAPOLATE_ENDPOINTS flag), that is also performed during the flush.
  481. #ifdef ENABLE_THREADS
  482. static int resampleProcessChannelJob(void *ptr, void *sync_not_used);
  483. #endif
  484. #ifdef ENABLE_EXTRAPOLATION
  485. static void prefillAllChannels(Resample *cxt),
  486. postfillAllChannels(Resample *cxt);
  487. #else
  488. static void postfillAllChannels(Resample *cxt);
  489. #endif
  490. ResampleResult resampleProcess(Resample *cxt, const artsample_t *const *input,
  491. int numInputFrames, artsample_t *const *output,
  492. int numOutputFrames, double ratio) {
  493. if (cxt->flags & RESAMPLE_FIXED_RATIO) { // override any supplied ratio if
  494. // doing fixed ratio resampling
  495. ratio = cxt->fixedRatio;
  496. }
  497. if (cxt->flags &
  498. RESAMPLER_FLUSHED) { // ignore new input after flush but before reset
  499. numInputFrames = 0;
  500. }
  501. #ifdef ENABLE_THREADS
  502. if (cxt->workers) {
  503. Resample *worker_contexts = calloc(cxt->numChannels, sizeof(Resample));
  504. ResampleResult res = {0, 0};
  505. int ch;
  506. for (ch = 0; ch < cxt->numChannels; ++ch) {
  507. Resample *wcxt = worker_contexts + ch;
  508. *wcxt = *cxt;
  509. if (input) {
  510. wcxt->input = input[ch] - 1;
  511. }
  512. wcxt->numInputFrames = numInputFrames;
  513. wcxt->output = output[ch] - 1;
  514. wcxt->numOutputFrames = numOutputFrames;
  515. wcxt->cbuffer = cxt->buffers[ch];
  516. wcxt->ratio = ratio;
  517. wcxt->stride = 1;
  518. wcxt->res = res;
  519. workersEnqueueJob(cxt->workers, resampleProcessChannelJob, wcxt,
  520. ch < cxt->numChannels - 1 ? WaitForAvailableWorkerThread
  521. : DontUseWorkerThread);
  522. }
  523. workersWaitAllJobs(cxt->workers);
  524. res = worker_contexts[0].res;
  525. *cxt = worker_contexts[0];
  526. free(worker_contexts);
  527. return res;
  528. } else if (cxt->numChannels == 1) {
  529. if (input) {
  530. cxt->input = input[0] - 1;
  531. }
  532. cxt->numInputFrames = numInputFrames;
  533. cxt->output = output[0] - 1;
  534. cxt->numOutputFrames = numOutputFrames;
  535. cxt->cbuffer = cxt->buffers[0];
  536. cxt->ratio = ratio;
  537. cxt->stride = 1;
  538. cxt->res.output_generated = 0;
  539. cxt->res.input_used = 0;
  540. resampleProcessChannelJob(cxt, NULL);
  541. return cxt->res;
  542. } else {
  543. #endif
  544. int half_taps = cxt->numTaps / 2, i;
  545. ResampleResult res = {0, 0};
  546. double offset2 = 0.0;
  547. if (numInputFrames < 0) { // this is where flush is handled
  548. postfillAllChannels(cxt);
  549. }
  550. while (numOutputFrames > 0) {
  551. if (cxt->outputOffset + offset2 >= cxt->inputIndex - half_taps) {
  552. if (numInputFrames > 0) {
  553. if (cxt->inputIndex == cxt->numSamples) {
  554. for (i = 0; i < cxt->numChannels; ++i) {
  555. memmove(cxt->buffers[i],
  556. cxt->buffers[i] + cxt->numSamples - cxt->numTaps,
  557. cxt->numTaps * sizeof(artsample_t));
  558. }
  559. cxt->outputOffset -= cxt->numSamples - cxt->numTaps;
  560. cxt->inputIndex -= cxt->numSamples - cxt->numTaps;
  561. }
  562. for (i = 0; i < cxt->numChannels; ++i) {
  563. cxt->buffers[i][cxt->inputIndex] = input[i][res.input_used];
  564. }
  565. cxt->inputIndex++;
  566. res.input_used++;
  567. numInputFrames--;
  568. } else {
  569. break;
  570. }
  571. } else {
  572. #ifdef ENABLE_EXTRAPOLATION
  573. // if we are extrapolating backwards and haven't yet, now is the time
  574. if (cxt->flags & EXTRAPOLATE_PREFILL) {
  575. cxt->flags &= ~EXTRAPOLATE_PREFILL;
  576. prefillAllChannels(cxt);
  577. }
  578. #endif
  579. for (i = 0; i < cxt->numChannels; ++i) {
  580. output[i][res.output_generated] = (artsample_t)cxt->subsample(
  581. cxt, cxt->buffers[i], cxt->outputOffset + offset2);
  582. }
  583. offset2 = ++res.output_generated / ratio;
  584. numOutputFrames--;
  585. }
  586. }
  587. cxt->outputOffset += offset2;
  588. if (cxt->flags & RESAMPLER_SNAP_OFFSET) {
  589. cxt->outputOffset = floor(cxt->outputOffset) +
  590. floor((cxt->outputOffset - floor(cxt->outputOffset)) *
  591. cxt->numFilters +
  592. 0.5) /
  593. cxt->numFilters;
  594. }
  595. return res;
  596. #ifdef ENABLE_THREADS
  597. }
  598. #endif
  599. }
  600. // This is the "interleaved" version of the resampler where the audio samples
  601. // for different channels are passed in sequence in a single buffer. There is
  602. // also a "non-interleaved" version for independent buffers, which is otherwise
  603. // identical (see above).
  604. //
  605. // If this resampler was created with the resampleFixedRatioInit() function,
  606. // then the "ratio" parameter is ignored and the originally specified conversion
  607. // is performed.
  608. ResampleResult resampleProcessInterleaved(Resample *cxt,
  609. const artsample_t *input,
  610. int numInputFrames,
  611. artsample_t *output,
  612. int numOutputFrames, double ratio) {
  613. if (cxt->flags & RESAMPLE_FIXED_RATIO) { // override any supplied ratio if
  614. // doing fixed ratio resampling
  615. ratio = cxt->fixedRatio;
  616. }
  617. if (cxt->flags &
  618. RESAMPLER_FLUSHED) { // ignore new input after flush but before reset
  619. numInputFrames = 0;
  620. }
  621. #ifdef ENABLE_THREADS
  622. if (cxt->workers) {
  623. Resample *worker_contexts = calloc(cxt->numChannels, sizeof(Resample));
  624. ResampleResult res = {0, 0};
  625. int ch;
  626. for (ch = 0; ch < cxt->numChannels; ++ch) {
  627. Resample *wcxt = worker_contexts + ch;
  628. *wcxt = *cxt;
  629. if (input) {
  630. wcxt->input = input + ch - cxt->numChannels;
  631. }
  632. wcxt->numInputFrames = numInputFrames;
  633. wcxt->output = output + ch - cxt->numChannels;
  634. wcxt->numOutputFrames = numOutputFrames;
  635. wcxt->cbuffer = cxt->buffers[ch];
  636. wcxt->stride = cxt->numChannels;
  637. wcxt->ratio = ratio;
  638. wcxt->res = res;
  639. workersEnqueueJob(cxt->workers, resampleProcessChannelJob, wcxt,
  640. ch < cxt->numChannels - 1 ? WaitForAvailableWorkerThread
  641. : DontUseWorkerThread);
  642. }
  643. workersWaitAllJobs(cxt->workers);
  644. res = worker_contexts[0].res;
  645. *cxt = worker_contexts[0];
  646. free(worker_contexts);
  647. return res;
  648. } else if (cxt->numChannels == 1) {
  649. if (input) {
  650. cxt->input = input - 1;
  651. }
  652. cxt->numInputFrames = numInputFrames;
  653. cxt->output = output - 1;
  654. cxt->numOutputFrames = numOutputFrames;
  655. cxt->cbuffer = cxt->buffers[0];
  656. cxt->ratio = ratio;
  657. cxt->stride = 1;
  658. cxt->res.output_generated = 0;
  659. cxt->res.input_used = 0;
  660. resampleProcessChannelJob(cxt, NULL);
  661. return cxt->res;
  662. } else {
  663. #endif
  664. int half_taps = cxt->numTaps / 2, i;
  665. ResampleResult res = {0, 0};
  666. double offset2 = 0.0;
  667. if (numInputFrames < 0) { // this is where flush is handled
  668. postfillAllChannels(cxt);
  669. }
  670. while (numOutputFrames > 0) {
  671. if (cxt->outputOffset + offset2 >= cxt->inputIndex - half_taps) {
  672. if (numInputFrames > 0) {
  673. if (cxt->inputIndex == cxt->numSamples) {
  674. for (i = 0; i < cxt->numChannels; ++i) {
  675. memmove(cxt->buffers[i],
  676. cxt->buffers[i] + cxt->numSamples - cxt->numTaps,
  677. cxt->numTaps * sizeof(artsample_t));
  678. }
  679. cxt->outputOffset -= cxt->numSamples - cxt->numTaps;
  680. cxt->inputIndex -= cxt->numSamples - cxt->numTaps;
  681. }
  682. for (i = 0; i < cxt->numChannels; ++i) {
  683. cxt->buffers[i][cxt->inputIndex] = *input++;
  684. }
  685. cxt->inputIndex++;
  686. res.input_used++;
  687. numInputFrames--;
  688. } else {
  689. break;
  690. }
  691. } else {
  692. #ifdef ENABLE_EXTRAPOLATION
  693. // if we are extrapolating backwards and haven't yet, now is the time
  694. if (cxt->flags & EXTRAPOLATE_PREFILL) {
  695. cxt->flags &= ~EXTRAPOLATE_PREFILL;
  696. prefillAllChannels(cxt);
  697. }
  698. #endif
  699. for (i = 0; i < cxt->numChannels; ++i) {
  700. *output++ = (artsample_t)cxt->subsample(cxt, cxt->buffers[i],
  701. cxt->outputOffset + offset2);
  702. }
  703. offset2 = ++res.output_generated / ratio;
  704. numOutputFrames--;
  705. }
  706. }
  707. cxt->outputOffset += offset2;
  708. if (cxt->flags & RESAMPLER_SNAP_OFFSET) {
  709. cxt->outputOffset = floor(cxt->outputOffset) +
  710. floor((cxt->outputOffset - floor(cxt->outputOffset)) *
  711. cxt->numFilters +
  712. 0.5) /
  713. cxt->numFilters;
  714. }
  715. return res;
  716. #ifdef ENABLE_THREADS
  717. }
  718. #endif
  719. }
  720. // This is where we flush the resampler by simulating enough input (half the
  721. // number of filter taps) to align the output. We may fill with zeros, or
  722. // extrapolate the most recent samples if that option is selected.
  723. static void postfillAllChannels(Resample *cxt) {
  724. int c;
  725. if (cxt->numSamples - cxt->inputIndex < cxt->numTaps / 2) {
  726. for (c = 0; c < cxt->numChannels; ++c) {
  727. memmove(cxt->buffers[c], cxt->buffers[c] + cxt->numSamples - cxt->numTaps,
  728. cxt->numTaps * sizeof(artsample_t));
  729. }
  730. cxt->outputOffset -= cxt->numSamples - cxt->numTaps;
  731. cxt->inputIndex -= cxt->numSamples - cxt->numTaps;
  732. }
  733. for (c = 0; c < cxt->numChannels; ++c) {
  734. memset(cxt->buffers[c] + cxt->inputIndex, 0,
  735. (cxt->numSamples - cxt->inputIndex) * sizeof(artsample_t));
  736. #ifdef ENABLE_EXTRAPOLATION
  737. if (cxt->flags & EXTRAPOLATE_ENDPOINTS) {
  738. extrapolate_forward(cxt->buffers[c] + cxt->inputIndex - cxt->numTaps / 2,
  739. cxt->numTaps / 2, cxt->numTaps / 2);
  740. }
  741. #endif
  742. }
  743. cxt->flags |= RESAMPLER_FLUSHED;
  744. cxt->inputIndex += cxt->numTaps / 2;
  745. }
  746. // Extrapolate the samples received so far back into the sample buffers.
  747. #ifdef ENABLE_EXTRAPOLATION
  748. static void prefillAllChannels(Resample *cxt) {
  749. int num_samples = cxt->inputIndex - cxt->numTaps, c;
  750. if (num_samples >= 8) {
  751. for (c = 0; c < cxt->numChannels; ++c) {
  752. extrapolate_reverse(cxt->buffers[c] + cxt->inputIndex, num_samples,
  753. cxt->numTaps - num_samples);
  754. }
  755. }
  756. }
  757. #endif
  758. // These two convenience functions are extensions of resampleProcess() and
  759. // resampleProcessInterleaved() that additionally perform the final "flush"
  760. // operation on the specified resampler. Simply call them for the last block of
  761. // samples and the "flushed" samples will be appended to the generated output,
  762. // with the total number of samples generated still indicated by the
  763. // "output_generated" field of the ResampleResult. Be sure to have enough buffer
  764. // space available.
  765. //
  766. // Using these is equivalent to calling the regular resampling functions with
  767. // the final block to be resampled and then calling them again with
  768. // numInputFrames set to -1 to execute the flush. This simply combines the two
  769. // calls into one.
  770. ResampleResult resampleProcessAndFlush(Resample *cxt,
  771. const artsample_t *const *input,
  772. int numInputFrames,
  773. artsample_t *const *output,
  774. int numOutputFrames, double ratio) {
  775. artsample_t **output_array =
  776. (artsample_t **)calloc(sizeof(artsample_t *), cxt->numChannels);
  777. ResampleResult res = {0, 0}, fres;
  778. int c;
  779. for (c = 0; c < cxt->numChannels; ++c) {
  780. output_array[c] = output[c];
  781. }
  782. res = resampleProcess(cxt, input, numInputFrames, output_array,
  783. numOutputFrames, ratio);
  784. // if we didn't consume all the input or ran out of output space, we're
  785. // finished (and this is obviously an unforced error, but the caller will have
  786. // to sort that out)
  787. numInputFrames -= (int)res.input_used;
  788. numOutputFrames -= (int)res.output_generated;
  789. if (numInputFrames != 0 || numOutputFrames == 0) {
  790. free((void *)output_array);
  791. return res;
  792. }
  793. for (c = 0; c < cxt->numChannels; ++c) {
  794. output_array[c] += res.output_generated;
  795. }
  796. fres = resampleProcess(cxt, NULL, -1, output_array, numOutputFrames, ratio);
  797. res.output_generated += fres.output_generated;
  798. free((void *)output_array);
  799. return res;
  800. }
  801. ResampleResult
  802. resampleProcessAndFlushInterleaved(Resample *cxt, const artsample_t *input,
  803. int numInputFrames, artsample_t *output,
  804. int numOutputFrames, double ratio) {
  805. ResampleResult res = {0, 0}, fres;
  806. res = resampleProcessInterleaved(cxt, input, numInputFrames, output,
  807. numOutputFrames, ratio);
  808. // if we didn't consume all the input or ran out of output space, we're
  809. // finished (and this is obviously an unforced error, but the caller will have
  810. // to sort that out)
  811. numInputFrames -= (int)res.input_used;
  812. numOutputFrames -= (int)res.output_generated;
  813. if (numInputFrames != 0 || numOutputFrames == 0) {
  814. return res;
  815. }
  816. output += (size_t)res.output_generated * cxt->numChannels;
  817. fres =
  818. resampleProcessInterleaved(cxt, NULL, -1, output, numOutputFrames, ratio);
  819. res.output_generated += fres.output_generated;
  820. return res;
  821. }
  822. #ifdef ENABLE_THREADS
  823. // This is the resampler processing function to process a single channel. It can
  824. // be called directly or called from a worker thread (see workers.c) and is used
  825. // for both interleaved and non-interleaved channels (see the "stride" argument
  826. // in the context).
  827. static int resampleProcessChannelJob(void *ptr, void *sync_not_used) {
  828. Resample *cxt = ptr;
  829. int half_taps = cxt->numTaps / 2;
  830. double offset2 = 0.0;
  831. // This is where we flush the resampler by simulating enough input (half the
  832. // number of filter taps) to align the output. We may fill with zeros, or
  833. // extrapolate the most recent samples if that option is selected.
  834. if (cxt->numInputFrames < 0) {
  835. if (cxt->numSamples - cxt->inputIndex < cxt->numTaps / 2) {
  836. memmove(cxt->cbuffer, cxt->cbuffer + cxt->numSamples - cxt->numTaps,
  837. cxt->numTaps * sizeof(artsample_t));
  838. cxt->outputOffset -= cxt->numSamples - cxt->numTaps;
  839. cxt->inputIndex -= cxt->numSamples - cxt->numTaps;
  840. }
  841. memset(cxt->cbuffer + cxt->inputIndex, 0,
  842. (cxt->numSamples - cxt->inputIndex) * sizeof(artsample_t));
  843. #ifdef ENABLE_EXTRAPOLATION
  844. if (cxt->flags & EXTRAPOLATE_ENDPOINTS) {
  845. extrapolate_forward(cxt->cbuffer + cxt->inputIndex - cxt->numTaps / 2,
  846. cxt->numTaps / 2, cxt->numTaps / 2);
  847. }
  848. #endif
  849. cxt->flags |= RESAMPLER_FLUSHED;
  850. cxt->inputIndex += cxt->numTaps / 2;
  851. }
  852. while (cxt->numOutputFrames > 0) {
  853. if (cxt->outputOffset + offset2 >= cxt->inputIndex - half_taps) {
  854. if (cxt->numInputFrames > 0) {
  855. if (cxt->inputIndex == cxt->numSamples) {
  856. memmove(cxt->cbuffer, cxt->cbuffer + cxt->numSamples - cxt->numTaps,
  857. cxt->numTaps * sizeof(artsample_t));
  858. cxt->outputOffset -= cxt->numSamples - cxt->numTaps;
  859. cxt->inputIndex -= cxt->numSamples - cxt->numTaps;
  860. }
  861. cxt->cbuffer[cxt->inputIndex++] = *(cxt->input += cxt->stride);
  862. cxt->res.input_used++;
  863. cxt->numInputFrames--;
  864. } else {
  865. break;
  866. }
  867. } else {
  868. #ifdef ENABLE_EXTRAPOLATION
  869. // if we are extrapolating backwards and haven't yet, now is the time
  870. if (cxt->flags & EXTRAPOLATE_PREFILL) {
  871. int num_samples = cxt->inputIndex - cxt->numTaps;
  872. if (num_samples >= 8) {
  873. extrapolate_reverse(cxt->cbuffer + cxt->inputIndex, num_samples,
  874. cxt->numTaps - num_samples);
  875. }
  876. cxt->flags &= ~EXTRAPOLATE_PREFILL;
  877. }
  878. #endif
  879. *(cxt->output += cxt->stride) =
  880. cxt->subsample(cxt, cxt->cbuffer, cxt->outputOffset + offset2);
  881. offset2 = ++(cxt->res.output_generated) / cxt->ratio;
  882. cxt->numOutputFrames--;
  883. }
  884. }
  885. cxt->outputOffset += offset2;
  886. if (cxt->flags & RESAMPLER_SNAP_OFFSET) {
  887. cxt->outputOffset =
  888. floor(cxt->outputOffset) +
  889. floor((cxt->outputOffset - floor(cxt->outputOffset)) * cxt->numFilters +
  890. 0.5) /
  891. cxt->numFilters;
  892. }
  893. return 0;
  894. }
  895. #endif
  896. // These two functions are not required for any application, but might be
  897. // useful. Essentially they allow a "dry run" of the resampler to determine
  898. // beforehand how many input samples would be consumed to generate a given
  899. // output, or how many samples would be generated with a given input.
  900. //
  901. // Note that there is a tricky edge-case here for ratios just over 1.0. If a
  902. // query is made as to how many input samples are required to generate a given
  903. // output, that does NOT necessarily mean that exactly that many samples will be
  904. // generated with the indicated input (specifically an extra sample might be
  905. // generated). Therefore it is important to restrict the output with
  906. // numOutputFrames if an exact output count is desired (don't just assume the
  907. // input count can exactly determine the output count).
  908. //
  909. // If this resampler was created with the resampleFixedRatioInit() function,
  910. // then the "ratio" parameter is ignored and the originally specified conversion
  911. // is simulated.
  912. unsigned int resampleGetRequiredSamples(Resample *cxt, int numOutputFrames,
  913. double ratio) {
  914. int half_taps = cxt->numTaps / 2;
  915. int input_index = cxt->inputIndex;
  916. double offset = cxt->outputOffset;
  917. ResampleResult res = {0, 0};
  918. if (cxt->flags & RESAMPLE_FIXED_RATIO) { // override any supplied ratio if
  919. // doing fixed ratio resampling
  920. ratio = cxt->fixedRatio;
  921. }
  922. while (numOutputFrames > 0) {
  923. if (offset >= input_index - half_taps) {
  924. if (input_index == cxt->numSamples) {
  925. offset -= cxt->numSamples - cxt->numTaps;
  926. input_index -= cxt->numSamples - cxt->numTaps;
  927. }
  928. input_index++;
  929. res.input_used++;
  930. } else {
  931. offset += (1.0 / ratio);
  932. numOutputFrames--;
  933. }
  934. }
  935. return res.input_used;
  936. }
  937. unsigned int resampleGetExpectedOutput(Resample *cxt, int numInputFrames,
  938. double ratio) {
  939. int half_taps = cxt->numTaps / 2;
  940. int input_index = cxt->inputIndex;
  941. double offset = cxt->outputOffset;
  942. ResampleResult res = {0, 0};
  943. if (cxt->flags & RESAMPLE_FIXED_RATIO) { // override any supplied ratio if
  944. // doing fixed ratio resampling
  945. ratio = cxt->fixedRatio;
  946. }
  947. if (cxt->flags &
  948. RESAMPLER_FLUSHED) { // ignore new input after flush but before reset
  949. numInputFrames = 0;
  950. } else if (numInputFrames < 0) { // also check for this being a flush
  951. input_index += half_taps;
  952. }
  953. while (1) {
  954. if (offset >= input_index - half_taps) {
  955. if (numInputFrames > 0) {
  956. if (input_index == cxt->numSamples) {
  957. offset -= cxt->numSamples - cxt->numTaps;
  958. input_index -= cxt->numSamples - cxt->numTaps;
  959. }
  960. input_index++;
  961. numInputFrames--;
  962. } else {
  963. break;
  964. }
  965. } else {
  966. offset += (1.0 / ratio);
  967. res.output_generated++;
  968. }
  969. }
  970. return res.output_generated;
  971. }
  972. // Advance the resampler output without generating any output, with the units
  973. // referenced to the input sample array. This can be used to temporally align
  974. // the output to the input (by specifying half the sinc filter tap width), and
  975. // it can also be used to introduce a phase shift. The resampler cannot be
  976. // reversed. Although not strictly true, for the purpose of this function we
  977. // will not allow subsampling (non-integer advance) without interpolation being
  978. // enabled.
  979. void resampleAdvancePosition(Resample *cxt, double delta) {
  980. if (delta < 0.0) {
  981. fprintf(stderr, "resampleAdvancePosition() can only advance forward!\n");
  982. } else if (!(cxt->flags & SUBSAMPLE_INTERPOLATE) && floor(delta) != delta) {
  983. fprintf(stderr, "resampleAdvancePosition() cannot advance partial samples "
  984. "without interpolation!\n");
  985. } else {
  986. cxt->outputOffset += delta;
  987. }
  988. }
  989. // Get the subsample position of the resampler. This is initialized to zero when
  990. // the resampler is started (or reset) and moves around zero as the resampler
  991. // processes audio. Obtaining this value is generally not required, but can be
  992. // useful for applications that need accurate phase information from the
  993. // resampler such as asynchronous sample rate converter (ASRC) implementations.
  994. // The units are relative to the input samples, and a negative value indicates
  995. // that an output sample is ready (i.e., can be generated with no further input
  996. // read).
  997. //
  998. // To fully understand the meaning of the position value the following C-like
  999. // pseudo-code for the resampler is presented. Note that this code has the
  1000. // length of the sinc filters and the actual interpolation abstracted away (like
  1001. // they abstracted away from the user of the library):
  1002. //
  1003. // while (numOutputFrames > 0) {
  1004. // if (position < 0.0) {
  1005. // write (output);
  1006. // numOutputFrames--;
  1007. // position += (1.0 / ratio);
  1008. // }
  1009. // else if (numInputFrames > 0) {
  1010. // read (input);
  1011. // numInputFrames--;
  1012. // position -= 1.0;
  1013. // }
  1014. // else
  1015. // break;
  1016. // }
  1017. double resampleGetPosition(Resample *cxt) {
  1018. return cxt->outputOffset + (cxt->numTaps / 2.0) - cxt->inputIndex;
  1019. }
  1020. // Free all resources associated with the resampler context, including the
  1021. // context pointer itself. Do not use the context after this call.
  1022. void resampleFree(Resample *cxt) {
  1023. if (cxt) {
  1024. int i;
  1025. for (i = 0; i <= cxt->numFilters; ++i) {
  1026. free(cxt->filters[i]);
  1027. }
  1028. free((void *)cxt->filters);
  1029. for (i = 0; i < cxt->numChannels; ++i) {
  1030. free(cxt->buffers[i]);
  1031. }
  1032. free((void *)cxt->buffers);
  1033. #ifdef ENABLE_THREADS
  1034. if (cxt->workers) {
  1035. workersDeinit(cxt->workers);
  1036. }
  1037. #endif
  1038. free(cxt);
  1039. }
  1040. }
  1041. // greatest common divisor
  1042. static unsigned long gcd(unsigned long a, unsigned long b) {
  1043. while (b) {
  1044. unsigned long t = (a %= b);
  1045. a = b;
  1046. b = t;
  1047. }
  1048. return a;
  1049. }
  1050. // This is the basic convolution operation that is the core of the resampler and
  1051. // utilizes the bulk of the CPU load (assuming reasonably long filters). The
  1052. // first version is the canonical form for reference, followed by two variations
  1053. // that are more accurate and incorporate various degrees of parallelization
  1054. // that can be utilized by optimizing compilers. Try 'em and use the fastest, or
  1055. // rewrite them using SIMD. Note that changing the "sum" variable from a float
  1056. // to a double improves the quality somewhat at the possible expense of speed.
  1057. #if 0 // Version 1 (canonical, very simple but slow and less accurate, not
  1058. // recommended)
  1059. static double apply_filter (artsample_t *A, artsample_t *B, int num_taps)
  1060. {
  1061. artsample_t sum = 0.0;
  1062. do sum += *A++ * *B++;
  1063. while (--num_taps);
  1064. return sum;
  1065. }
  1066. #endif
  1067. #if defined(__XTENSA__) && !defined(PATH_WIDTH)
  1068. // ESP32/Xtensa: pure float to use hardware FPU (MADD.S), avoid software double
  1069. // emulation
  1070. static double apply_filter(artsample_t *A, artsample_t *B, int num_taps) {
  1071. float sum = 0.0f;
  1072. do {
  1073. sum += A[0] * B[0];
  1074. A++;
  1075. B++;
  1076. } while (--num_taps);
  1077. return sum;
  1078. }
  1079. static double apply_filter_precise(artsample_t *A, artsample_t *B,
  1080. int num_taps) {
  1081. float sum = 0.0f;
  1082. do {
  1083. sum += *A++ * *B++;
  1084. } while (--num_taps);
  1085. return sum;
  1086. }
  1087. #elif !defined(_MSC_VER) || defined(__clang__) || defined(__llvm__) || \
  1088. defined(__INTEL_COMPILER) || defined(__INTEL_LLVM_COMPILER)
  1089. // Version 2 (outside-in order, more accurate)
  1090. // Works well with most compilers but MSVC works better with the next one
  1091. // try "-O3 -mavx2 -fno-signed-zeros -fno-trapping-math -fassociative-math"
  1092. static double apply_filter(artsample_t *A, artsample_t *B, int num_taps) {
  1093. int i = num_taps - 1;
  1094. artsample_t sum = (artsample_t)0.0;
  1095. do {
  1096. sum += (A[0] * B[0]) + (A[i] * B[i]);
  1097. A++;
  1098. B++;
  1099. } while ((i -= 2) > 0);
  1100. return sum;
  1101. }
  1102. // For the "precise" version the order is not important, so just letting the
  1103. // compiler do all the parallelization seems to work better with gcc and clang
  1104. static double apply_filter_precise(artsample_t *A, artsample_t *B,
  1105. int num_taps) {
  1106. double sum = 0.0;
  1107. do {
  1108. sum += (double)*A++ * *B++;
  1109. } while (--num_taps);
  1110. return sum;
  1111. }
  1112. #else
  1113. // Version 3 (outside-in order, 2x unrolled loop)
  1114. // Works well with MSVC, but others have trouble vectorizing it
  1115. static double apply_filter(artsample_t *A, artsample_t *B, int num_taps) {
  1116. int i = num_taps - 1;
  1117. artsample_t sum = (artsample_t)0.0;
  1118. do {
  1119. sum +=
  1120. (A[0] * B[0]) + (A[i] * B[i]) + (A[1] * B[1]) + (A[i - 1] * B[i - 1]);
  1121. A += 2;
  1122. B += 2;
  1123. } while ((i -= 4) > 0);
  1124. return sum;
  1125. }
  1126. static double apply_filter_precise(artsample_t *A, artsample_t *B,
  1127. int num_taps) {
  1128. int i = num_taps - 1;
  1129. double sum = 0.0;
  1130. do {
  1131. sum += ((double)A[0] * B[0]) + ((double)A[i] * B[i]) +
  1132. ((double)A[1] * B[1]) + ((double)A[i - 1] * B[i - 1]);
  1133. A += 2;
  1134. B += 2;
  1135. } while ((i -= 4) > 0);
  1136. return sum;
  1137. }
  1138. #endif
  1139. static void init_filter(Resample *cxt, artsample_t *filter, double fraction) {
  1140. double filter_sum = 0.0, scaler, error;
  1141. const double a0 = 0.35875;
  1142. const double a1 = 0.48829;
  1143. const double a2 = 0.14128;
  1144. const double a3 = 0.01168;
  1145. int i;
  1146. // "dist" is the absolute distance from the sinc maximum to the filter tap to
  1147. // be calculated, in radians "ratio" is that distance divided by half the tap
  1148. // count such that it reaches π at the window extremes
  1149. // Note that with this scaling, the odd terms of the Blackman-Harris
  1150. // calculation appear to be negated with respect to the reference formula
  1151. // version.
  1152. for (i = 0; i < cxt->numTaps; ++i) {
  1153. double dist = fabs((cxt->numTaps / 2 - 1) + fraction - i) * M_PI;
  1154. double ratio = dist / (cxt->numTaps / 2.0);
  1155. double value;
  1156. if (dist != 0.0) {
  1157. value = sin(dist * cxt->lowpassRatio) / (dist * cxt->lowpassRatio);
  1158. if (cxt->flags & BLACKMAN_HARRIS) {
  1159. value *=
  1160. a0 + a1 * cos(ratio) + a2 * cos(2 * ratio) + a3 * cos(3 * ratio);
  1161. } else {
  1162. value *= 0.5 * (1.0 + cos(ratio)); // Hann window
  1163. }
  1164. } else {
  1165. value = 1.0;
  1166. }
  1167. filter_sum += cxt->tempFilter[i] = value;
  1168. }
  1169. // filter should have unity DC gain
  1170. scaler = 1.0 / filter_sum;
  1171. error = 0.0;
  1172. for (i = cxt->numTaps / 2; i < cxt->numTaps;
  1173. i = cxt->numTaps - i - (i >= cxt->numTaps / 2)) {
  1174. filter[i] = (artsample_t)((cxt->tempFilter[i] *= scaler) - error);
  1175. error += filter[i] - cxt->tempFilter[i];
  1176. }
  1177. }
  1178. static double subsample_no_interpolate(Resample *cxt, artsample_t *source,
  1179. double offset) {
  1180. int fi = (int)floor((offset - floor(offset)) * cxt->numFilters + 0.5);
  1181. source += (int)floor(offset);
  1182. if (!(cxt->flags & INCLUDE_LOWPASS) && !(fi % cxt->numFilters)) {
  1183. return source[fi / cxt->numFilters];
  1184. }
  1185. return apply_filter(cxt->filters[fi], source - cxt->numTaps / 2 + 1,
  1186. cxt->numTaps);
  1187. }
  1188. static double subsample_interpolate(Resample *cxt, artsample_t *source,
  1189. double offset) {
  1190. double frac = offset - floor(offset);
  1191. int fi = (int)floor(frac *= cxt->numFilters);
  1192. frac -= fi;
  1193. source += (int)floor(offset) - cxt->numTaps / 2 + 1;
  1194. return (apply_filter(cxt->filters[fi], source, cxt->numTaps) * (1.0 - frac)) +
  1195. (apply_filter(cxt->filters[fi + 1], source, cxt->numTaps) * frac);
  1196. }
  1197. static double subsample_no_interpolate_precise(Resample *cxt,
  1198. artsample_t *source,
  1199. double offset) {
  1200. int fi = (int)floor((offset - floor(offset)) * cxt->numFilters + 0.5);
  1201. source += (int)floor(offset);
  1202. if (!(cxt->flags & INCLUDE_LOWPASS) && !(fi % cxt->numFilters)) {
  1203. return source[fi / cxt->numFilters];
  1204. }
  1205. return apply_filter_precise(cxt->filters[fi], source - cxt->numTaps / 2 + 1,
  1206. cxt->numTaps);
  1207. }
  1208. static double subsample_interpolate_precise(Resample *cxt, artsample_t *source,
  1209. double offset) {
  1210. double frac = offset - floor(offset);
  1211. int fi = (int)floor(frac *= cxt->numFilters);
  1212. frac -= fi;
  1213. source += (int)floor(offset) - cxt->numTaps / 2 + 1;
  1214. return (apply_filter_precise(cxt->filters[fi], source, cxt->numTaps) *
  1215. (1.0 - frac)) +
  1216. (apply_filter_precise(cxt->filters[fi + 1], source, cxt->numTaps) *
  1217. frac);
  1218. }