Skip to content

Instantly share code, notes, and snippets.

@laserbat
Created June 16, 2022 21:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laserbat/0134a1b0bdc6013fd13a17b1e0f11d3c to your computer and use it in GitHub Desktop.
Save laserbat/0134a1b0bdc6013fd13a17b1e0f11d3c to your computer and use it in GitHub Desktop.
#include <complex.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <tgmath.h>
#define SR 44100
#define SIMPLE_HARMONIC
#ifdef SIMPLE_HARMONIC
int main(void) {
double freq = 100;
double phase = 0;
complex double osc = exp(-I * phase);
complex double multiplier = exp(-I * 2 * M_PI * freq / SR);
while (true) {
fwrite(&osc, sizeof(double), 2, stdout);
osc *= multiplier;
}
}
#else
#define TABLE_BITS (16ULL)
#define TABLE_SIZE (1ULL << TABLE_BITS)
#define COUNTER_BITS 32ULL
#define COUNTER_MAX ((1ULL << COUNTER_BITS) - 1ULL)
#define DISCARD_BITS (COUNTER_BITS - TABLE_BITS)
#define DISCARD_MASK ((1ULL << DISCARD_BITS) - 1ULL)
int main(void) {
double freq = 100;
double phase = 0;
double table[TABLE_SIZE];
for (int i = 0; i < TABLE_SIZE; i++) {
table[i] = sin(2 * M_PI * i / (double)(TABLE_SIZE));
}
uint64_t osc = phase * COUNTER_MAX;
uint64_t increment = COUNTER_MAX * freq / (double)SR;
srand48(12345);
while (true) {
uint64_t dither[2] = {
lrand48() & DISCARD_MASK,
lrand48() & DISCARD_MASK,
};
double out[2] = {
table[((osc + dither[0]) & COUNTER_MAX) >> DISCARD_BITS],
table[(((osc + dither[1]) + COUNTER_MAX / 4) & COUNTER_MAX) >> DISCARD_BITS],
};
fwrite(&out, sizeof(double), 2, stdout);
osc += increment;
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment