stb_hexwave.h 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  1. // stb_hexwave - v0.5 - public domain, initial release 2021-04-01
  2. //
  3. // A flexible anti-aliased (bandlimited) digital audio oscillator.
  4. //
  5. // This library generates waveforms of a variety of shapes made of
  6. // line segments. It does not do envelopes, LFO effects, etc.; it
  7. // merely tries to solve the problem of generating an artifact-free
  8. // morphable digital waveform with a variety of spectra, and leaves
  9. // it to the user to rescale the waveform and mix multiple voices, etc.
  10. //
  11. // Compiling:
  12. //
  13. // In one C/C++ file that #includes this file, do
  14. //
  15. // #define STB_HEXWAVE_IMPLEMENTATION
  16. // #include "stb_hexwave.h"
  17. //
  18. // Optionally, #define STB_HEXWAVE_STATIC before including
  19. // the header to cause the definitions to be private to the
  20. // implementation file (i.e. to be "static" instead of "extern").
  21. //
  22. // Notes:
  23. //
  24. // Optionally performs memory allocation during initialization,
  25. // never allocates otherwise.
  26. //
  27. // License:
  28. //
  29. // See end of file for license information.
  30. //
  31. // Usage:
  32. //
  33. // Initialization:
  34. //
  35. // hexwave_init(32,16,NULL); // read "header section" for alternatives
  36. //
  37. // Create oscillator:
  38. //
  39. // HexWave *osc = malloc(sizeof(*osc)); // or "new HexWave", or declare globally or on stack
  40. // hexwave_create(osc, reflect_flag, peak_time, half_height, zero_wait);
  41. // see "Waveform shapes" below for the meaning of these parameters
  42. //
  43. // Generate audio:
  44. //
  45. // hexwave_generate_samples(output, number_of_samples, osc, oscillator_freq)
  46. // where:
  47. // output is a buffer where the library will store floating point audio samples
  48. // number_of_samples is the number of audio samples to generate
  49. // osc is a pointer to a Hexwave
  50. // oscillator_freq is the frequency of the oscillator divided by the sample rate
  51. //
  52. // The output samples will continue from where the samples generated by the
  53. // previous hexwave_generate_samples() on this oscillator ended.
  54. //
  55. // Change oscillator waveform:
  56. //
  57. // hexwave_change(osc, reflect_flag, peak_time, half_height, zero_wait);
  58. // can call in between calls to hexwave_generate_samples
  59. //
  60. // Waveform shapes:
  61. //
  62. // All waveforms generated by hexwave are constructed from six line segments
  63. // characterized by 3 parameters.
  64. //
  65. // See demonstration: https://www.youtube.com/watch?v=hsUCrAsDN-M
  66. //
  67. // reflect=0 reflect=1
  68. //
  69. // 0-----P---1 0-----P---1 peak_time = P
  70. // . 1 . 1
  71. // /\_ : /\_ :
  72. // / \_ : / \_ :
  73. // / \.H / \.H half_height = H
  74. // / | : / | :
  75. // _____/ |_:___ _____/ | : _____
  76. // . : \ | . | : /
  77. // . : \ | . | : /
  78. // . : \ _/ . \_: /
  79. // . : \ _/ . :_ /
  80. // . -1 \/ . -1 \/
  81. // 0 - Z - - - - 1 0 - Z - - - - 1 zero_wait = Z
  82. //
  83. // Classic waveforms:
  84. // peak half zero
  85. // reflect time height wait
  86. // Sawtooth 1 0 0 0
  87. // Square 1 0 1 0
  88. // Triangle 1 0.5 0 0
  89. //
  90. // Some waveforms can be produced in multiple ways, which is useful when morphing
  91. // into other waveforms, and there are a few more notable shapes:
  92. //
  93. // peak half zero
  94. // reflect time height wait
  95. // Sawtooth 1 1 any 0
  96. // Sawtooth (8va) 1 0 -1 0
  97. // Triangle 1 0.5 0 0
  98. // Square 1 0 1 0
  99. // Square 0 0 1 0
  100. // Triangle 0 0.5 0 0
  101. // Triangle 0 0 -1 0
  102. // AlternatingSaw 0 0 0 0
  103. // AlternatingSaw 0 1 any 0
  104. // Stairs 0 0 1 0.5
  105. //
  106. // The "Sawtooth (8va)" waveform is identical to a sawtooth wave with 2x the
  107. // frequency, but when morphed with other values, it becomes an overtone of
  108. // the base frequency.
  109. //
  110. // Morphing waveforms:
  111. //
  112. // Sweeping peak_time morphs the waveform while producing various spectra.
  113. // Sweeping half_height effectively crossfades between two waveforms; useful, but less exciting.
  114. // Sweeping zero_wait produces a similar effect no matter the reset of the waveform,
  115. // a sort of high-pass/PWM effect where the wave becomes silent at zero_wait=1.
  116. //
  117. // You can trivially morph between any two waveforms from the above table
  118. // which only differ in one column.
  119. //
  120. // Crossfade between classic waveforms:
  121. // peak half zero
  122. // Start End reflect time height wait
  123. // ----- --- ------- ---- ------ ----
  124. // Triangle Square 0 0 -1..1 0
  125. // Saw Square 1 0 0..1 0
  126. // Triangle Saw 1 0.5 0..2 0
  127. //
  128. // The last morph uses uses half-height values larger than 1, which means it will
  129. // be louder and the output should be scaled down by half to compensate, or better
  130. // by dynamically tracking the morph: volume_scale = 1 - half_height/4
  131. //
  132. // Non-crossfade morph between classic waveforms, most require changing
  133. // two parameters at the same time:
  134. // peak half zero
  135. // Start End reflect time height wait
  136. // ----- --- ------- ---- ------ ----
  137. // Square Triangle any 0..0.5 1..0 0
  138. // Square Saw 1 0..1 1..any 0
  139. // Triangle Saw 1 0.5..1 0..-1 0
  140. //
  141. // Other noteworthy morphs between simple shapes:
  142. // peak half zero
  143. // Start Halfway End reflect time height wait
  144. // ----- --------- --- ------- ---- ------ ----
  145. // Saw (8va,neg) Saw (pos) 1 0..1 -1 0
  146. // Saw (neg) Saw (pos) 1 0..1 0 0
  147. // Triangle AlternatingSaw 0 0..1 -1 0
  148. // AlternatingSaw Triangle AlternatingSaw 0 0..1 0 0
  149. // Square AlternatingSaw 0 0..1 1 0
  150. // Triangle Triangle AlternatingSaw 0 0..1 -1..1 0
  151. // Square AlternatingSaw 0 0..1 1..0 0
  152. // Saw (8va) Triangle Saw 1 0..1 -1..1 0
  153. // Saw (neg) Saw (pos) 1 0..1 0..1 0
  154. // AlternatingSaw AlternatingSaw 0 0..1 0..any 0
  155. //
  156. // The last entry is noteworthy because the morph from the halfway point to either
  157. // endpoint sounds very different. For example, an LFO sweeping back and forth over
  158. // the whole range will morph between the middle timbre and the AlternatingSaw
  159. // timbre in two different ways, alternating.
  160. //
  161. // Entries with "any" for half_height are whole families of morphs, as you can pick
  162. // any value you want as the endpoint for half_height.
  163. //
  164. // You can always morph between any two waveforms with the same value of 'reflect'
  165. // by just sweeping the parameters simultaneously. There will never be artifacts
  166. // and the result will always be useful, if not necessarily what you want.
  167. //
  168. // You can vary the sound of two-parameter morphs by ramping them differently,
  169. // e.g. if the morph goes from t=0..1, then square-to-triangle looks like:
  170. // peak_time = lerp(t, 0, 0.5)
  171. // half_height = lerp(t, 1, 0 )
  172. // but you can also do things like:
  173. // peak_time = lerp(smoothstep(t), 0, 0.5)
  174. // half_height = cos(PI/2 * t)
  175. //
  176. // How it works:
  177. //
  178. // hexwave use BLEP to bandlimit discontinuities and BLAMP
  179. // to bandlimit C1 discontinuities. This is not polyBLEP
  180. // (polynomial BLEP), it is table-driven BLEP. It is
  181. // also not minBLEP (minimum-phase BLEP), as that complicates
  182. // things for little benefit once BLAMP is involved.
  183. //
  184. // The previous oscillator frequency is remembered, and when
  185. // the frequency changes, a BLAMP is generated to remove the
  186. // C1 discontinuity, which reduces artifacts for sweeps/LFO.
  187. //
  188. // Changes to an oscillator timbre using hexwave_change() actually
  189. // wait until the oscillator finishes its current cycle. All
  190. // waveforms with non-zero "zero_wait" settings pass through 0
  191. // and have 0-slope at the start of a cycle, which means changing
  192. // the settings is artifact free at that time. (If zero_wait is 0,
  193. // the code still treats it as passing through 0 with 0-slope; it'll
  194. // apply the necessary fixups to make it artifact free as if it does
  195. // transition to 0 with 0-slope vs. the waveform at the end of
  196. // the cycle, then adds the fixups for a non-0 and non-0 slope
  197. // at the start of the cycle, which cancels out if zero_wait is 0,
  198. // and still does the right thing if zero_wait is 0 when the
  199. // settings are updated.)
  200. //
  201. // BLEP/BLAMP normally requires overlapping buffers, but this
  202. // is hidden from the user by generating the waveform to a
  203. // temporary buffer and saving the overlap regions internally
  204. // between calls. (It is slightly more complicated; see code.)
  205. //
  206. // By design all shapes have 0 DC offset; this is one reason
  207. // hexwave uses zero_wait instead of standard PWM.
  208. //
  209. // The internals of hexwave could support any arbitrary shape
  210. // made of line segments, but I chose not to expose this
  211. // generality in favor of a simple, easy-to-use API.
  212. #ifndef STB_INCLUDE_STB_HEXWAVE_H
  213. #define STB_INCLUDE_STB_HEXWAVE_H
  214. #ifndef STB_HEXWAVE_MAX_BLEP_LENGTH
  215. #define STB_HEXWAVE_MAX_BLEP_LENGTH 64 // good enough for anybody
  216. #endif
  217. #ifdef STB_HEXWAVE_STATIC
  218. #define STB_HEXWAVE_DEF static
  219. #else
  220. #define STB_HEXWAVE_DEF extern
  221. #endif
  222. typedef struct HexWave HexWave;
  223. STB_HEXWAVE_DEF void hexwave_init(int width, int oversample, float *user_buffer);
  224. // width: size of BLEP, from 4..64, larger is slower & more memory but less aliasing
  225. // oversample: 2+, number of subsample positions, larger uses more memory but less noise
  226. // user_buffer: optional, if provided the library will perform no allocations.
  227. // 16*width*(oversample+1) bytes, must stay allocated as long as library is used
  228. // technically it only needs: 8*( width * (oversample + 1))
  229. // + 8*((width * oversample) + 1) bytes
  230. //
  231. // width can be larger than 64 if you define STB_HEXWAVE_MAX_BLEP_LENGTH to a larger value
  232. STB_HEXWAVE_DEF void hexwave_shutdown(float *user_buffer);
  233. // user_buffer: pass in same parameter as passed to hexwave_init
  234. STB_HEXWAVE_DEF void hexwave_create(HexWave *hex, int reflect, float peak_time, float half_height, float zero_wait);
  235. // see docs above for description
  236. //
  237. // reflect is tested as 0 or non-zero
  238. // peak_time is clamped to 0..1
  239. // half_height is not clamped
  240. // zero_wait is clamped to 0..1
  241. STB_HEXWAVE_DEF void hexwave_change(HexWave *hex, int reflect, float peak_time, float half_height, float zero_wait);
  242. // see docs
  243. STB_HEXWAVE_DEF void hexwave_generate_samples(float *output, int num_samples, HexWave *hex, float freq);
  244. // output: buffer where the library will store generated floating point audio samples
  245. // number_of_samples: the number of audio samples to generate
  246. // osc: pointer to a Hexwave initialized with 'hexwave_create'
  247. // oscillator_freq: frequency of the oscillator divided by the sample rate
  248. // private:
  249. typedef struct
  250. {
  251. int reflect;
  252. float peak_time;
  253. float zero_wait;
  254. float half_height;
  255. } HexWaveParameters;
  256. struct HexWave
  257. {
  258. float t, prev_dt;
  259. HexWaveParameters current, pending;
  260. int have_pending;
  261. float buffer[STB_HEXWAVE_MAX_BLEP_LENGTH];
  262. };
  263. #endif
  264. #ifdef STB_HEXWAVE_IMPLEMENTATION
  265. #ifndef STB_HEXWAVE_NO_ALLOCATION
  266. #include <stdlib.h> // malloc,free
  267. #endif
  268. #include <string.h> // memset,memcpy,memmove
  269. #include <math.h> // sin,cos,fabs
  270. #define hexwave_clamp(v,a,b) ((v) < (a) ? (a) : (v) > (b) ? (b) : (v))
  271. STB_HEXWAVE_DEF void hexwave_change(HexWave *hex, int reflect, float peak_time, float half_height, float zero_wait)
  272. {
  273. hex->pending.reflect = reflect;
  274. hex->pending.peak_time = hexwave_clamp(peak_time,0,1);
  275. hex->pending.half_height = half_height;
  276. hex->pending.zero_wait = hexwave_clamp(zero_wait,0,1);
  277. // put a barrier here to allow changing from a different thread than the generator
  278. hex->have_pending = 1;
  279. }
  280. STB_HEXWAVE_DEF void hexwave_create(HexWave *hex, int reflect, float peak_time, float half_height, float zero_wait)
  281. {
  282. memset(hex, 0, sizeof(*hex));
  283. hexwave_change(hex, reflect, peak_time, half_height, zero_wait);
  284. hex->current = hex->pending;
  285. hex->have_pending = 0;
  286. hex->t = 0;
  287. hex->prev_dt = 0;
  288. }
  289. static struct
  290. {
  291. int width; // width of fixup in samples
  292. int oversample; // number of oversampled versions (there's actually one more to allow lerpign)
  293. float *blep;
  294. float *blamp;
  295. } hexblep;
  296. static void hex_add_oversampled_bleplike(float *output, float time_since_transition, float scale, float *data)
  297. {
  298. float *d1,*d2;
  299. float lerpweight;
  300. int i, bw = hexblep.width;
  301. int slot = (int) (time_since_transition * hexblep.oversample);
  302. if (slot >= hexblep.oversample)
  303. slot = hexblep.oversample-1; // clamp in case the floats overshoot
  304. d1 = &data[ slot *bw];
  305. d2 = &data[(slot+1)*bw];
  306. lerpweight = time_since_transition * hexblep.oversample - slot;
  307. for (i=0; i < bw; ++i)
  308. output[i] += scale * (d1[i] + (d2[i]-d1[i])*lerpweight);
  309. }
  310. static void hex_blep (float *output, float time_since_transition, float scale)
  311. {
  312. hex_add_oversampled_bleplike(output, time_since_transition, scale, hexblep.blep);
  313. }
  314. static void hex_blamp(float *output, float time_since_transition, float scale)
  315. {
  316. hex_add_oversampled_bleplike(output, time_since_transition, scale, hexblep.blamp);
  317. }
  318. typedef struct
  319. {
  320. float t,v,s; // time, value, slope
  321. } hexvert;
  322. // each half of the waveform needs 4 vertices to represent 3 line
  323. // segments, plus 1 more for wraparound
  324. static void hexwave_generate_linesegs(hexvert vert[9], HexWave *hex, float dt)
  325. {
  326. int j;
  327. float min_len = dt / 256.0f;
  328. vert[0].t = 0;
  329. vert[0].v = 0;
  330. vert[1].t = hex->current.zero_wait*0.5f;
  331. vert[1].v = 0;
  332. vert[2].t = 0.5f*hex->current.peak_time + vert[1].t*(1-hex->current.peak_time);
  333. vert[2].v = 1;
  334. vert[3].t = 0.5f;
  335. vert[3].v = hex->current.half_height;
  336. if (hex->current.reflect) {
  337. for (j=4; j <= 7; ++j) {
  338. vert[j].t = 1 - vert[7-j].t;
  339. vert[j].v = - vert[7-j].v;
  340. }
  341. } else {
  342. for (j=4; j <= 7; ++j) {
  343. vert[j].t = 0.5f + vert[j-4].t;
  344. vert[j].v = - vert[j-4].v;
  345. }
  346. }
  347. vert[8].t = 1;
  348. vert[8].v = 0;
  349. for (j=0; j < 8; ++j) {
  350. if (vert[j+1].t <= vert[j].t + min_len) {
  351. // if change takes place over less than a fraction of a sample treat as discontinuity
  352. //
  353. // otherwise the slope computation can blow up to arbitrarily large and we
  354. // try to generate a huge BLAMP and the result is wrong.
  355. //
  356. // why does this happen if the math is right? i believe if done perfectly,
  357. // the two BLAMPs on either side of the slope would cancel out, but our
  358. // BLAMPs have only limited sub-sample precision and limited integration
  359. // accuracy. or maybe it's just the math blowing up w/ floating point precision
  360. // limits as we try to make x * (1/x) cancel out
  361. //
  362. // min_len verified artifact-free even near nyquist with only oversample=4
  363. vert[j+1].t = vert[j].t;
  364. }
  365. }
  366. if (vert[8].t != 1.0f) {
  367. // if the above fixup moved the endpoint away from 1.0, move it back,
  368. // along with any other vertices that got moved to the same time
  369. float t = vert[8].t;
  370. for (j=5; j <= 8; ++j)
  371. if (vert[j].t == t)
  372. vert[j].t = 1.0f;
  373. }
  374. // compute the exact slopes from the final fixed-up positions
  375. for (j=0; j < 8; ++j)
  376. if (vert[j+1].t == vert[j].t)
  377. vert[j].s = 0;
  378. else
  379. vert[j].s = (vert[j+1].v - vert[j].v) / (vert[j+1].t - vert[j].t);
  380. // wraparound at end
  381. vert[8].t = 1;
  382. vert[8].v = vert[0].v;
  383. vert[8].s = vert[0].s;
  384. }
  385. STB_HEXWAVE_DEF void hexwave_generate_samples(float *output, int num_samples, HexWave *hex, float freq)
  386. {
  387. hexvert vert[9];
  388. int pass,i,j;
  389. float t = hex->t;
  390. float temp_output[2*STB_HEXWAVE_MAX_BLEP_LENGTH];
  391. int buffered_length = sizeof(float)*hexblep.width;
  392. float dt = (float) fabs(freq);
  393. float recip_dt = (dt == 0.0f) ? 0.0f : 1.0f / dt;
  394. int halfw = hexblep.width/2;
  395. // all sample times are biased by halfw to leave room for BLEP/BLAMP to go back in time
  396. if (num_samples <= 0)
  397. return;
  398. // convert parameters to times and slopes
  399. hexwave_generate_linesegs(vert, hex, dt);
  400. if (hex->prev_dt != dt) {
  401. // if frequency changes, add a fixup at the derivative discontinuity starting at now
  402. float slope;
  403. for (j=1; j < 6; ++j)
  404. if (t < vert[j].t)
  405. break;
  406. slope = vert[j].s;
  407. if (slope != 0)
  408. hex_blamp(output, 0, (dt - hex->prev_dt)*slope);
  409. hex->prev_dt = dt;
  410. }
  411. // copy the buffered data from last call and clear the rest of the output array
  412. memset(output, 0, sizeof(float)*num_samples);
  413. memset(temp_output, 0, 2*hexblep.width*sizeof(float));
  414. if (num_samples >= hexblep.width) {
  415. memcpy(output, hex->buffer, buffered_length);
  416. } else {
  417. // if the output is shorter than hexblep.width, we do all synthesis to temp_output
  418. memcpy(temp_output, hex->buffer, buffered_length);
  419. }
  420. for (pass=0; pass < 2; ++pass) {
  421. int i0,i1;
  422. float *out;
  423. // we want to simulate having one buffer that is num_output + hexblep.width
  424. // samples long, without putting that requirement on the user, and without
  425. // allocating a temp buffer that's as long as the whole thing. so we use two
  426. // overlapping buffers, one the user's buffer and one a fixed-length temp
  427. // buffer.
  428. if (pass == 0) {
  429. if (num_samples < hexblep.width)
  430. continue;
  431. // run as far as we can without overwriting the end of the user's buffer
  432. out = output;
  433. i0 = 0;
  434. i1 = num_samples - hexblep.width;
  435. } else {
  436. // generate the rest into a temp buffer
  437. out = temp_output;
  438. i0 = 0;
  439. if (num_samples >= hexblep.width)
  440. i1 = hexblep.width;
  441. else
  442. i1 = num_samples;
  443. }
  444. // determine current segment
  445. for (j=0; j < 8; ++j)
  446. if (t < vert[j+1].t)
  447. break;
  448. i = i0;
  449. for(;;) {
  450. while (t < vert[j+1].t) {
  451. if (i == i1)
  452. goto done;
  453. out[i+halfw] += vert[j].v + vert[j].s*(t - vert[j].t);
  454. t += dt;
  455. ++i;
  456. }
  457. // transition from lineseg starting at j to lineseg starting at j+1
  458. if (vert[j].t == vert[j+1].t)
  459. hex_blep(out+i, recip_dt*(t-vert[j+1].t), (vert[j+1].v - vert[j].v));
  460. hex_blamp(out+i, recip_dt*(t-vert[j+1].t), dt*(vert[j+1].s - vert[j].s));
  461. ++j;
  462. if (j == 8) {
  463. // change to different waveform if there's a change pending
  464. j = 0;
  465. t -= 1.0; // t was >= 1.f if j==8
  466. if (hex->have_pending) {
  467. float prev_s0 = vert[j].s;
  468. float prev_v0 = vert[j].v;
  469. hex->current = hex->pending;
  470. hex->have_pending = 0;
  471. hexwave_generate_linesegs(vert, hex, dt);
  472. // the following never occurs with this oscillator, but it makes
  473. // the code work in more general cases
  474. if (vert[j].v != prev_v0)
  475. hex_blep (out+i, recip_dt*t, (vert[j].v - prev_v0));
  476. if (vert[j].s != prev_s0)
  477. hex_blamp(out+i, recip_dt*t, dt*(vert[j].s - prev_s0));
  478. }
  479. }
  480. }
  481. done:
  482. ;
  483. }
  484. // at this point, we've written output[] and temp_output[]
  485. if (num_samples >= hexblep.width) {
  486. // the first half of temp[] overlaps the end of output, the second half will be the new start overlap
  487. for (i=0; i < hexblep.width; ++i)
  488. output[num_samples-hexblep.width + i] += temp_output[i];
  489. memcpy(hex->buffer, temp_output+hexblep.width, buffered_length);
  490. } else {
  491. for (i=0; i < num_samples; ++i)
  492. output[i] = temp_output[i];
  493. memcpy(hex->buffer, temp_output+num_samples, buffered_length);
  494. }
  495. hex->t = t;
  496. }
  497. STB_HEXWAVE_DEF void hexwave_shutdown(float *user_buffer)
  498. {
  499. #ifndef STB_HEXWAVE_NO_ALLOCATION
  500. if (user_buffer != 0) {
  501. free(hexblep.blep);
  502. free(hexblep.blamp);
  503. }
  504. #endif
  505. }
  506. // buffer should be NULL or must be 4*(width*(oversample+1)*2 +
  507. STB_HEXWAVE_DEF void hexwave_init(int width, int oversample, float *user_buffer)
  508. {
  509. int halfwidth = width/2;
  510. int half = halfwidth*oversample;
  511. int blep_buffer_count = width*(oversample+1);
  512. int n = 2*half+1;
  513. #ifdef STB_HEXWAVE_NO_ALLOCATION
  514. float *buffers = user_buffer;
  515. #else
  516. float *buffers = user_buffer ? user_buffer : (float *) malloc(sizeof(float) * n * 2);
  517. #endif
  518. float *step = buffers+0*n;
  519. float *ramp = buffers+1*n;
  520. float *blep_buffer, *blamp_buffer;
  521. double integrate_impulse=0, integrate_step=0;
  522. int i,j;
  523. if (width > STB_HEXWAVE_MAX_BLEP_LENGTH)
  524. width = STB_HEXWAVE_MAX_BLEP_LENGTH;
  525. if (user_buffer == 0) {
  526. #ifndef STB_HEXWAVE_NO_ALLOCATION
  527. blep_buffer = (float *) malloc(sizeof(float)*blep_buffer_count);
  528. blamp_buffer = (float *) malloc(sizeof(float)*blep_buffer_count);
  529. #endif
  530. } else {
  531. blep_buffer = ramp+n;
  532. blamp_buffer = blep_buffer + blep_buffer_count;
  533. }
  534. // compute BLEP and BLAMP by integerating windowed sinc
  535. for (i=0; i < n; ++i) {
  536. for (j=0; j < 16; ++j) {
  537. float sinc_t = 3.141592f* (i-half) / oversample;
  538. float sinc = (i==half) ? 1.0f : (float) sin(sinc_t) / (sinc_t);
  539. float wt = 2.0f*3.1415926f * i / (n-1);
  540. float window = (float) (0.355768 - 0.487396*cos(wt) + 0.144232*cos(2*wt) - 0.012604*cos(3*wt)); // Nuttall
  541. double value = window * sinc;
  542. integrate_impulse += value/16;
  543. integrate_step += integrate_impulse/16;
  544. }
  545. step[i] = (float) integrate_impulse;
  546. ramp[i] = (float) integrate_step;
  547. }
  548. // renormalize
  549. for (i=0; i < n; ++i) {
  550. step[i] = step[i] * (float) (1.0 / step[n-1]); // step needs to reach to 1.0
  551. ramp[i] = ramp[i] * (float) (halfwidth / ramp[n-1]); // ramp needs to become a slope of 1.0 after oversampling
  552. }
  553. // deinterleave to allow efficient interpolation e.g. w/SIMD
  554. for (j=0; j <= oversample; ++j) {
  555. for (i=0; i < width; ++i) {
  556. blep_buffer [j*width+i] = step[j+i*oversample];
  557. blamp_buffer[j*width+i] = ramp[j+i*oversample];
  558. }
  559. }
  560. // subtract out the naive waveform; note we can't do this to the raw data
  561. // above, because we want the discontinuity to be in a different locations
  562. // for j=0 and j=oversample (which exists to provide something to interpolate against)
  563. for (j=0; j <= oversample; ++j) {
  564. // subtract step
  565. for (i=halfwidth; i < width; ++i)
  566. blep_buffer [j*width+i] -= 1.0f;
  567. // subtract ramp
  568. for (i=halfwidth; i < width; ++i)
  569. blamp_buffer[j*width+i] -= (j+i*oversample-half)*(1.0f/oversample);
  570. }
  571. hexblep.blep = blep_buffer;
  572. hexblep.blamp = blamp_buffer;
  573. hexblep.width = width;
  574. hexblep.oversample = oversample;
  575. #ifndef STB_HEXWAVE_NO_ALLOCATION
  576. if (user_buffer == 0)
  577. free(buffers);
  578. #endif
  579. }
  580. #endif // STB_HEXWAVE_IMPLEMENTATION
  581. /*
  582. ------------------------------------------------------------------------------
  583. This software is available under 2 licenses -- choose whichever you prefer.
  584. ------------------------------------------------------------------------------
  585. ALTERNATIVE A - MIT License
  586. Copyright (c) 2017 Sean Barrett
  587. Permission is hereby granted, free of charge, to any person obtaining a copy of
  588. this software and associated documentation files (the "Software"), to deal in
  589. the Software without restriction, including without limitation the rights to
  590. use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  591. of the Software, and to permit persons to whom the Software is furnished to do
  592. so, subject to the following conditions:
  593. The above copyright notice and this permission notice shall be included in all
  594. copies or substantial portions of the Software.
  595. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  596. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  597. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  598. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  599. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  600. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  601. SOFTWARE.
  602. ------------------------------------------------------------------------------
  603. ALTERNATIVE B - Public Domain (www.unlicense.org)
  604. This is free and unencumbered software released into the public domain.
  605. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
  606. software, either in source code form or as a compiled binary, for any purpose,
  607. commercial or non-commercial, and by any means.
  608. In jurisdictions that recognize copyright laws, the author or authors of this
  609. software dedicate any and all copyright interest in the software to the public
  610. domain. We make this dedication for the benefit of the public at large and to
  611. the detriment of our heirs and successors. We intend this dedication to be an
  612. overt act of relinquishment in perpetuity of all present and future rights to
  613. this software under copyright law.
  614. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  615. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  616. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  617. AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  618. ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  619. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  620. ------------------------------------------------------------------------------
  621. */