diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 1fcbbc8..60b240b 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -21,7 +21,7 @@ jobs: sudo apt-get update sudo apt-get install -y --no-install-recommends \ cmake ninja-build pkg-config libgtk-4-dev libadwaita-1-dev \ - libvte-2.91-gtk4-dev + libvte-2.91-gtk4-dev libpulse-dev libsndfile1-dev - name: Build run: | cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo diff --git a/README.md b/README.md index 821b671..72fea2d 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,8 @@ behave the same. Linux: - sudo apt install cmake libgtk-4-dev libadwaita-1-dev libvte-2.91-gtk4-dev + sudo apt install cmake libgtk-4-dev libadwaita-1-dev libvte-2.91-gtk4-dev \ + libpulse-dev libsndfile1-dev cmake -S . -B build && cmake --build build && ./build/linux/dmodem-gui Windows: `cmake -S . -B build -A Win32 && cmake --build build --config Release`, diff --git a/core/include/dmodemctl.h b/core/include/dmodemctl.h index fca8ef5..a11b0bb 100644 --- a/core/include/dmodemctl.h +++ b/core/include/dmodemctl.h @@ -52,7 +52,7 @@ extern "C" { #endif /* the library's version: major * 10000 + minor * 100 + patch */ -#define DMC_VERSION 10100 +#define DMC_VERSION 10200 DMC_API int dmc_version(void); /* @@ -231,15 +231,20 @@ DMC_API int dmc_voice_message(const dmc_session *s, const int16_t **pcm); DMC_API int dmc_ring_count(const dmc_session *s); /* - * WAV files (greetings and messages) + * Sound files (greetings and messages) */ /* the 44-byte header of a WAV file of n 16-bit samples, 8 kHz, mono, into buf (44 bytes): 44 */ DMC_API int dmc_wav_header(char *buf, int n); -/* a WAV file's samples at 8 kHz, mono, 16-bit (from 8 or 16-bit PCM, - A-law or mu-law, any rate and channels): how many, *pcm then - allocated (dmc_free() it); -1 if it is not a WAV file of those */ +/* a sound file's samples at 8 kHz, mono, 16-bit: how many, *pcm then + allocated (dmc_free() it); -1 if it is not one this reads. It reads + WAV (PCM of 8, 16, 24 or 32 bits, 32 or 64-bit floats, A-law, mu-law, + IMA and Microsoft ADPCM), AIFF and AIFF-C (PCM, floats, A-law, + mu-law) and Sun/NeXT .au, of any rate and channels. (The apps read + MP3, AAC, FLAC, Ogg and the like with their platforms' decoders.) */ +DMC_API int dmc_audio_decode(const char *data, int n, int16_t **pcm); +/* (dmc_audio_decode's old name) */ DMC_API int dmc_wav_decode(const char *data, int n, int16_t **pcm); DMC_API void dmc_free(void *p); diff --git a/core/src/voice.c b/core/src/voice.c index 4a98cac..331d847 100644 --- a/core/src/voice.c +++ b/core/src/voice.c @@ -188,16 +188,6 @@ static void put32(char *p, unsigned long v) put16(p + 2, (unsigned)((v >> 16) & 0xffff)); } -static unsigned get16(const char *p) -{ - return (unsigned char)p[0] | ((unsigned)(unsigned char)p[1] << 8); -} - -static unsigned long get32(const char *p) -{ - return get16(p) | ((unsigned long)get16(p + 2) << 16); -} - int dmc_wav_header(char *buf, int n) { unsigned long bytes = n > 0 ? (unsigned long)n * 2 : 0; @@ -216,91 +206,463 @@ int dmc_wav_header(char *buf, int n) return 44; } -int dmc_wav_decode(const char *data, int n, int16_t **pcm) -{ - unsigned format = 0, channels = 0, bits = 0; - unsigned long rate = 0; - const char *samples = NULL; - long bytes = 0, frames, out_n, i; - int have_fmt = 0, width; - const char *p, *end; - int16_t *out; +/* + * Sound files read: WAV (PCM of 8 to 32 bits, floats, A-law, mu-law, + * IMA and Microsoft ADPCM), AIFF and AIFF-C (PCM, floats, A-law, + * mu-law), Sun/NeXT .au; any rate and channels, made 8 kHz mono + */ - *pcm = NULL; - if (!data || n < 12 || memcmp(data, "RIFF", 4) || - memcmp(data + 8, "WAVE", 4)) - return -1; - p = data + 12; - end = data + n; +/* what a file's samples are */ +enum { E_PCM, E_FLOAT, E_ALAW, E_ULAW, E_IMA, E_MSADPCM }; + +struct sound { + int enc, bits, big, channels, block; + double rate; + const unsigned char *p; + long bytes; + /* (MS ADPCM's coefficient pairs, from its fmt chunk) */ + int ncoef; + int coef[64][2]; +}; + +static unsigned long get32be(const unsigned char *p) +{ + return ((unsigned long)p[0] << 24) | ((unsigned long)p[1] << 16) | + ((unsigned long)p[2] << 8) | p[3]; +} + +static unsigned ug16(const unsigned char *p) +{ + return p[0] | ((unsigned)p[1] << 8); +} + +static unsigned long ug32(const unsigned char *p) +{ + return ug16(p) | ((unsigned long)ug16(p + 2) << 16); +} + +/* an 80-bit IEEE extended (AIFF's rate) as a double */ +static double extended(const unsigned char *p) +{ + int e = ((p[0] & 0x7f) << 8 | p[1]) - 16383 - 63; + double m = (double)get32be(p + 2) * 4294967296.0 + + (double)get32be(p + 6); + double v = ldexp(m, e); + return (p[0] & 0x80) ? -v : v; +} + +/* a RIFF WAVE's: 0, or -1 if it isn't one this reads */ +static int parse_wav(const unsigned char *d, long n, struct sound *f) +{ + const unsigned char *p = d + 12, *end = d + n; + int fmt = 0, tag = 0; while (end - p >= 8) { - unsigned long len = get32(p + 4); - const char *body = p + 8; + unsigned long len = ug32(p + 4); + const unsigned char *body = p + 8; long left = (long)(end - body); if (!memcmp(p, "fmt ", 4) && len >= 16 && left >= 16) { - format = get16(body); - channels = get16(body + 2); - rate = get32(body + 4); - bits = get16(body + 14); + tag = (int)ug16(body); + f->channels = (int)ug16(body + 2); + f->rate = ug32(body + 4); + f->block = (int)ug16(body + 12); + f->bits = (int)ug16(body + 14); /* WAVE_FORMAT_EXTENSIBLE: its subformat's code */ - if (format == 0xfffe && len >= 26 && left >= 26) - format = get16(body + 24); - have_fmt = 1; + if (tag == 0xfffe && len >= 26 && left >= 26) + tag = (int)ug16(body + 24); + if (tag == 2 && len >= 22 && left >= 22) { + int i, k = (int)ug16(body + 20); + if (k > 64 || (long)(22 + 4 * k) > left) + return -1; + f->ncoef = k; + for (i = 0; i < k; i++) { + f->coef[i][0] = (int16_t)ug16(body + 22 + 4 * i); + f->coef[i][1] = (int16_t)ug16(body + 24 + 4 * i); + } + } + fmt = 1; } else if (!memcmp(p, "data", 4)) { - samples = body; - bytes = len > (unsigned long)left ? left : (long)len; + f->p = body; + f->bytes = len > (unsigned long)left ? left : (long)len; break; } if (len > (unsigned long)left) break; p = body + len + (len & 1); } - if (!have_fmt || !samples || !channels || channels > 8 || - rate < 1000 || rate > 192000) + if (!fmt || !f->p) return -1; - if (format == 1 && (bits == 8 || bits == 16)) - width = (int)bits / 8; - else if ((format == 6 || format == 7) && bits == 8) - width = 1; - else - return -1; - frames = bytes / (long)(width * (int)channels); - out_n = (long)((double)frames * DMC_VOICE_RATE / (double)rate); - out = malloc((size_t)(out_n > 0 ? out_n : 1) * sizeof(int16_t)); - if (!out) - return -1; - for (i = 0; i < out_n; i++) { - /* (linear between the two frames around it, each the mean - of its channels) */ - double at = (double)i * (double)rate / DMC_VOICE_RATE; - long f = (long)at; - double frac = at - (double)f, y = 0; - int k, c; - for (k = 0; k < 2; k++) { - long ff = f + k < frames ? f + k : frames - 1; - double sum = 0; - for (c = 0; c < (int)channels; c++) { - const char *q = samples + - (ff * (long)channels + c) * width; - int v; - if (format == 7) - v = ulaw_decode((unsigned char)*q); - else if (format == 6) - v = alaw_decode((unsigned char)*q); - else if (width == 1) - v = ((int)(unsigned char)*q - 128) * 256; - else - v = (int16_t)get16(q); - sum += v; - } - sum /= channels; - y += k ? frac * sum : (1 - frac) * sum; + switch (tag) { + case 1: f->enc = E_PCM; break; + case 3: f->enc = E_FLOAT; break; + case 6: f->enc = E_ALAW; break; + case 7: f->enc = E_ULAW; break; + case 0x11: f->enc = E_IMA; break; + case 2: f->enc = E_MSADPCM; break; + default: return -1; + } + return 0; +} + +/* an AIFF or AIFF-C's */ +static int parse_aiff(const unsigned char *d, long n, struct sound *f) +{ + const unsigned char *p = d + 12, *end = d + n; + int comm = 0, aifc = !memcmp(d + 8, "AIFC", 4); + char comp[4] = { 'N', 'O', 'N', 'E' }; + while (end - p >= 8) { + unsigned long len = get32be(p + 4); + const unsigned char *body = p + 8; + long left = (long)(end - body); + if (!memcmp(p, "COMM", 4) && len >= 18 && left >= 18) { + f->channels = (int)(body[0] << 8 | body[1]); + f->bits = (int)(body[6] << 8 | body[7]); + f->rate = extended(body + 8); + if (aifc && len >= 22 && left >= 22) + memcpy(comp, body + 18, 4); + comm = 1; + } else if (!memcmp(p, "SSND", 4) && len >= 8 && left >= 8) { + unsigned long off = get32be(body); + long l = len > (unsigned long)left ? left : (long)len; + if ((long)off > l - 8) + return -1; + f->p = body + 8 + off; + f->bytes = l - 8 - (long)off; } + if (len > (unsigned long)left) + break; + p = body + len + (len & 1); + } + if (!comm || !f->p) + return -1; + f->big = 1; + if (!memcmp(comp, "NONE", 4) || !memcmp(comp, "twos", 4)) { + f->enc = E_PCM; + } else if (!memcmp(comp, "sowt", 4)) { + f->enc = E_PCM; + f->big = 0; + } else if (!memcmp(comp, "fl32", 4) || !memcmp(comp, "FL32", 4)) { + f->enc = E_FLOAT; + f->bits = 32; + } else if (!memcmp(comp, "fl64", 4) || !memcmp(comp, "FL64", 4)) { + f->enc = E_FLOAT; + f->bits = 64; + } else if (!memcmp(comp, "ulaw", 4) || !memcmp(comp, "ULAW", 4)) { + f->enc = E_ULAW; + f->bits = 8; + } else if (!memcmp(comp, "alaw", 4) || !memcmp(comp, "ALAW", 4)) { + f->enc = E_ALAW; + f->bits = 8; + } else { + return -1; + } + /* (AIFF's 8-bit samples are signed) */ + if (f->enc == E_PCM && f->bits == 8) + f->big = 2; + return 0; +} + +/* a Sun/NeXT .au's */ +static int parse_au(const unsigned char *d, long n, struct sound *f) +{ + unsigned long off, len, enc; + if (n < 24) + return -1; + off = get32be(d + 4); + len = get32be(d + 8); + enc = get32be(d + 12); + f->rate = get32be(d + 16); + f->channels = (int)get32be(d + 20); + if (off < 24 || (long)off > n) + return -1; + f->p = d + off; + f->bytes = n - (long)off; + if (len != 0xffffffffUL && (long)len < f->bytes) + f->bytes = (long)len; + f->big = 1; + switch (enc) { + case 1: f->enc = E_ULAW; f->bits = 8; break; + case 2: f->enc = E_PCM; f->bits = 8; f->big = 2; break; + case 3: f->enc = E_PCM; f->bits = 16; break; + case 4: f->enc = E_PCM; f->bits = 24; break; + case 5: f->enc = E_PCM; f->bits = 32; break; + case 6: f->enc = E_FLOAT; f->bits = 32; break; + case 7: f->enc = E_FLOAT; f->bits = 64; break; + case 27: f->enc = E_ALAW; f->bits = 8; break; + default: return -1; + } + return 0; +} + +/* a sample of width w bytes at q as 16 bits (big: 1 big-endian, 2 + big-endian with 8-bit samples signed) */ +static int pcm_at(const unsigned char *q, int w, int big) +{ + unsigned long v = 0; + int i; + if (w == 1) + return big == 2 ? (int)(signed char)q[0] * 256 : + ((int)q[0] - 128) * 256; + for (i = 0; i < w; i++) + v |= (unsigned long)q[big ? i : w - 1 - i] << (8 * (w - 1 - i)); + /* (the top two bytes: the sample's sign is the top bit) */ + v >>= 8 * (w - 2); + return (int16_t)(v & 0xffff); +} + +static int float_at(const unsigned char *q, int w, int big) +{ + unsigned char b[8]; + double x; + int i; + for (i = 0; i < w; i++) + b[i] = q[big ? w - 1 - i : i]; + /* (b is little-endian now, as the machines this runs on are) */ + if (w == 4) { + float y; + memcpy(&y, b, 4); + x = y; + } else { + memcpy(&x, b, 8); + } + if (x != x) + return 0; + x *= 32767.0; + return x > 32767 ? 32767 : x < -32768 ? -32768 : (int)x; +} + +static const int ima_steps[89] = { + 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, + 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, 130, 143, + 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, + 544, 598, 658, 724, 796, 876, 963, 1060, 1166, 1282, 1411, 1552, + 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, + 4871, 5358, 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, + 12635, 13899, 15289, 16818, 18500, 20350, 22385, 24623, 27086, + 29794, 32767 +}; +static const int ima_index[16] = { -1, -1, -1, -1, 2, 4, 6, 8, + -1, -1, -1, -1, 2, 4, 6, 8 }; + +static int ima_nibble(int *pred, int *idx, int nib) +{ + int step = ima_steps[*idx], diff = step >> 3; + if (nib & 4) diff += step; + if (nib & 2) diff += step >> 1; + if (nib & 1) diff += step >> 2; + *pred += (nib & 8) ? -diff : diff; + if (*pred > 32767) *pred = 32767; + if (*pred < -32768) *pred = -32768; + *idx += ima_index[nib]; + if (*idx < 0) *idx = 0; + if (*idx > 88) *idx = 88; + return *pred; +} + +/* one channel's sample of frame i: the files' samples mixed to mono + into out (frames of them): how many frames */ +static long decode_mono(const struct sound *f, int16_t *out, long cap) +{ + int c, ch = f->channels; + long fr = 0; + if (f->enc == E_IMA) { + /* blocks: per channel a header (sample, index), then 4-byte + groups of 8 nibbles per channel in turn */ + const unsigned char *b = f->p, *end = f->p + f->bytes; + int per = f->block > 4 * ch ? (f->block - 4 * ch) * 2 / ch + 1 : 0; + if (per <= 0 || per > 65536) + return -1; + while (end - b >= f->block && fr < cap) { + int pred[8], idx[8], i; + int16_t *o = out + fr; + long n = per < cap - fr ? per : cap - fr; + for (i = 0; i < n; i++) + o[i] = 0; + for (c = 0; c < ch; c++) { + const unsigned char *h = b + 4 * c; + pred[c] = (int16_t)ug16(h); + idx[c] = h[2] > 88 ? 88 : h[2]; + } + for (c = 0; c < ch; c++) { + long k = 0; + const unsigned char *q = b + 4 * ch + 4 * c; + if (k < n) + o[k] = (int16_t)(o[k] + pred[c] / ch); + k = 1; + while (k < per && q + 4 <= b + f->block) { + int j; + for (j = 0; j < 8 && k < per; j++, k++) { + int nib = (q[j / 2] >> ((j & 1) * 4)) & 15; + int v = ima_nibble(&pred[c], &idx[c], nib); + if (k < n) + o[k] = (int16_t)(o[k] + v / ch); + } + q += 4 * ch; + } + } + fr += n; + b += f->block; + } + return fr; + } + if (f->enc == E_MSADPCM) { + static const int adapt[16] = { 230, 230, 230, 230, 307, 409, + 512, 614, 768, 614, 512, 409, + 307, 230, 230, 230 }; + const unsigned char *b = f->p, *end = f->p + f->bytes; + int per; + if (ch > 2 || !f->ncoef || f->block < 7 * ch) + return -1; + per = (f->block - 7 * ch) * 2 / ch + 2; + while (end - b >= f->block && fr < cap) { + int pred[2], delta[2], s1[2], s2[2]; + const unsigned char *q = b; + long n = per < cap - fr ? per : cap - fr, k; + int16_t *o = out + fr; + for (c = 0; c < ch; c++) + pred[c] = q[c] < f->ncoef ? q[c] : 0; + q += ch; + for (c = 0; c < ch; c++, q += 2) + delta[c] = (int16_t)ug16(q); + for (c = 0; c < ch; c++, q += 2) + s1[c] = (int16_t)ug16(q); + for (c = 0; c < ch; c++, q += 2) + s2[c] = (int16_t)ug16(q); + /* (the header's two samples: the older first) */ + if (n > 0) { + long v = 0; + for (c = 0; c < ch; c++) v += s2[c]; + o[0] = (int16_t)(v / ch); + } + if (n > 1) { + long v = 0; + for (c = 0; c < ch; c++) v += s1[c]; + o[1] = (int16_t)(v / ch); + } + for (k = 2; k < per; k++) { + long v = 0; + for (c = 0; c < ch; c++) { + long nib_i = (k - 2) * ch + c; + int nib = (q[nib_i / 2] >> ((nib_i & 1) ? 0 : 4)) & 15; + int sn = nib & 8 ? nib - 16 : nib; + long long p = ((long long)s1[c] * f->coef[pred[c]][0] + + (long long)s2[c] * f->coef[pred[c]][1]) / 256; + p += (long long)sn * delta[c]; + if (p > 32767) p = 32767; + if (p < -32768) p = -32768; + s2[c] = s1[c]; + s1[c] = (int)p; + delta[c] = (int)((long)delta[c] * adapt[nib] / 256); + /* (a broken file's grows without end) */ + if (delta[c] > 0x100000) delta[c] = 0x100000; + if (delta[c] < 16) delta[c] = 16; + v += (long)p; + } + if (k < n) + o[k] = (int16_t)(v / ch); + } + fr += n; + b += f->block; + } + return fr; + } + { + int w = f->bits / 8; + long frames, i; + if (w < 1 || w > 8 || (f->enc == E_PCM && w > 4) || + (f->enc == E_FLOAT && w != 4 && w != 8) || + ((f->enc == E_ALAW || f->enc == E_ULAW) && w != 1)) + return -1; + frames = f->bytes / ((long)w * ch); + if (frames > cap) + frames = cap; + for (i = 0; i < frames; i++) { + long sum = 0; + for (c = 0; c < ch; c++) { + const unsigned char *q = f->p + (i * ch + c) * w; + switch (f->enc) { + case E_ULAW: sum += ulaw_decode(*q); break; + case E_ALAW: sum += alaw_decode(*q); break; + case E_FLOAT: sum += float_at(q, w, f->big); break; + default: sum += pcm_at(q, w, f->big); break; + } + } + out[i] = (int16_t)(sum / ch); + } + return frames; + } +} + +/* the most frames f could hold */ +static long most_frames(const struct sound *f) +{ + if (f->enc == E_IMA || f->enc == E_MSADPCM) { + if (f->block <= 0) + return 0; + return (f->bytes / f->block + 1) * ((long)f->block * 2 + 2); + } + if (f->bits < 8) + return 0; + return f->bytes / ((long)(f->bits / 8) * f->channels); +} + +int dmc_audio_decode(const char *data, int n, int16_t **pcm) +{ + const unsigned char *d = (const unsigned char *)data; + struct sound f; + int16_t *mono, *out; + long frames, cap, out_n, i; + int r = -1; + + *pcm = NULL; + if (!data || n < 12) + return -1; + memset(&f, 0, sizeof(f)); + if (!memcmp(d, "RIFF", 4) && !memcmp(d + 8, "WAVE", 4)) + r = parse_wav(d, n, &f); + else if (!memcmp(d, "FORM", 4) && + (!memcmp(d + 8, "AIFF", 4) || !memcmp(d + 8, "AIFC", 4))) + r = parse_aiff(d, n, &f); + else if (!memcmp(d, ".snd", 4)) + r = parse_au(d, n, &f); + if (r || f.channels < 1 || f.channels > 8 || !(f.rate >= 1000) || + f.rate > 384000) + return -1; + cap = most_frames(&f); + if (cap < 0 || cap > 100000000L) + return -1; + mono = malloc((size_t)(cap > 0 ? cap : 1) * sizeof(int16_t)); + if (!mono) + return -1; + frames = decode_mono(&f, mono, cap); + if (frames < 0) { + free(mono); + return -1; + } + out_n = (long)((double)frames * DMC_VOICE_RATE / f.rate); + out = malloc((size_t)(out_n > 0 ? out_n : 1) * sizeof(int16_t)); + if (!out) { + free(mono); + return -1; + } + for (i = 0; i < out_n; i++) { + /* (linear between the two frames around it) */ + double at = (double)i * f.rate / DMC_VOICE_RATE; + long k = (long)at; + double frac = at - (double)k; + long k1 = k + 1 < frames ? k + 1 : frames - 1; + double y = (1 - frac) * mono[k] + frac * mono[k1]; out[i] = (int16_t)(y > 32767 ? 32767 : y < -32768 ? -32768 : y); } + free(mono); *pcm = out; return (int)out_n; } +int dmc_wav_decode(const char *data, int n, int16_t **pcm) +{ + return dmc_audio_decode(data, n, pcm); +} + void dmc_free(void *p) { free(p); diff --git a/core/test/dmodemctl_test.c b/core/test/dmodemctl_test.c index c0e7667..a288396 100644 --- a/core/test/dmodemctl_test.c +++ b/core/test/dmodemctl_test.c @@ -747,6 +747,137 @@ static void test_wav(void) CHECK(dmc_wav_decode("RIFF", 4, &pcm) == -1 && !pcm); } +/* (ffmpeg -f lavfi -i sine=f=500:r=8000:d=0.07, -c:a adpcm_ima_wav or adpcm_ms -block_size 64) */ +static const unsigned char ima_wav[414] = { + 0x52, 0x49, 0x46, 0x46, 0x96, 0x01, 0x00, 0x00, 0x57, 0x41, 0x56, 0x45, 0x66, 0x6d, 0x74, 0x20, + 0x14, 0x00, 0x00, 0x00, 0x11, 0x00, 0x01, 0x00, 0x40, 0x1f, 0x00, 0x00, 0x80, 0x3e, 0x00, 0x00, + 0x40, 0x00, 0x04, 0x00, 0x02, 0x00, 0x79, 0x00, 0x66, 0x61, 0x63, 0x74, 0x04, 0x00, 0x00, 0x00, + 0x30, 0x02, 0x00, 0x00, 0x4c, 0x49, 0x53, 0x54, 0x1a, 0x00, 0x00, 0x00, 0x49, 0x4e, 0x46, 0x4f, + 0x49, 0x53, 0x46, 0x54, 0x0e, 0x00, 0x00, 0x00, 0x4c, 0x61, 0x76, 0x66, 0x36, 0x30, 0x2e, 0x31, + 0x36, 0x2e, 0x31, 0x30, 0x30, 0x00, 0x64, 0x61, 0x74, 0x61, 0x40, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x77, 0x77, 0x77, 0xf2, 0xad, 0x99, 0x21, 0x53, 0x33, 0x12, 0xb9, 0xcd, 0xbb, 0x8a, + 0x30, 0x45, 0x33, 0x12, 0xb9, 0xcd, 0xbb, 0x9a, 0x31, 0x45, 0x33, 0x12, 0xb9, 0xcd, 0xbb, 0x9a, + 0x31, 0x45, 0x33, 0x12, 0xb9, 0xcd, 0xbb, 0x9a, 0x31, 0x45, 0x33, 0x12, 0xb9, 0xcd, 0xbb, 0x9a, + 0x31, 0x45, 0x33, 0x12, 0xb9, 0xcd, 0xbb, 0x9a, 0x31, 0x45, 0x33, 0x12, 0xb9, 0xcd, 0xe1, 0xf9, + 0x39, 0x00, 0x9b, 0x19, 0x52, 0x43, 0x23, 0x80, 0xdb, 0xcb, 0xab, 0x18, 0x52, 0x43, 0x23, 0x90, + 0xda, 0xcb, 0xab, 0x18, 0x52, 0x43, 0x23, 0x90, 0xda, 0xcb, 0xab, 0x18, 0x52, 0x43, 0x23, 0x90, + 0xda, 0xcb, 0xab, 0x18, 0x52, 0x43, 0x23, 0x90, 0xda, 0xcb, 0xab, 0x18, 0x52, 0x43, 0x23, 0x90, + 0xda, 0xcb, 0xab, 0x18, 0x52, 0x43, 0x23, 0x90, 0xda, 0xcb, 0xab, 0x18, 0x52, 0x43, 0x50, 0x0b, + 0x39, 0x00, 0x02, 0xa9, 0xcc, 0xbb, 0x8a, 0x30, 0x45, 0x33, 0x12, 0xb9, 0xcd, 0xbb, 0x8a, 0x30, + 0x45, 0x33, 0x02, 0xb8, 0xcd, 0xbb, 0x8a, 0x30, 0x45, 0x33, 0x02, 0xb8, 0xcd, 0xbb, 0x8a, 0x30, + 0x45, 0x33, 0x02, 0xb8, 0xcd, 0xbb, 0x8a, 0x30, 0x45, 0x33, 0x02, 0xb8, 0xcd, 0xbb, 0x8a, 0x30, + 0x45, 0x33, 0x02, 0xb8, 0xcd, 0xbb, 0x8a, 0x30, 0x45, 0x33, 0x02, 0xb8, 0xcd, 0xbb, 0x39, 0xf1, + 0x37, 0x00, 0x08, 0x43, 0x44, 0x22, 0x80, 0xcb, 0xbc, 0xab, 0x08, 0x53, 0x34, 0x23, 0x91, 0xdb, + 0xbc, 0xab, 0x08, 0x53, 0x34, 0x23, 0x91, 0xdb, 0xbc, 0xab, 0x08, 0x53, 0x34, 0x23, 0x91, 0xdb, + 0xbc, 0xab, 0x08, 0x53, 0x34, 0x23, 0x91, 0xdb, 0xbc, 0xab, 0x08, 0x53, 0x34, 0x23, 0x91, 0xdb, + 0xbc, 0xab, 0x19, 0x53, 0x34, 0x23, 0x91, 0xdb, 0xbc, 0xab, 0x19, 0x53, 0x34, 0x23, 0xff, 0x0f, + 0x36, 0x00, 0xb8, 0xbd, 0xbc, 0x8a, 0x21, 0x35, 0x34, 0x02, 0xa9, 0xbd, 0xbc, 0x8a, 0x21, 0x35, + 0x34, 0x02, 0xa9, 0xbd, 0xbc, 0x8a, 0x21, 0x35, 0x34, 0x02, 0xa9, 0xbd, 0xbc, 0x8a, 0x21, 0x35, + 0x34, 0x02, 0xa9, 0xbd, 0xbc, 0x8a, 0x21, 0x35, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, + 0x80, 0x80, 0x80, 0x80, 0x00, 0x88, 0x00, 0x88, 0x00, 0x88, 0x00, 0x88, 0x00, 0x08, +}; + +static const unsigned char ms_wav[444] = { + 0x52, 0x49, 0x46, 0x46, 0xb4, 0x01, 0x00, 0x00, 0x57, 0x41, 0x56, 0x45, 0x66, 0x6d, 0x74, 0x20, + 0x32, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x40, 0x1f, 0x00, 0x00, 0x80, 0x3e, 0x00, 0x00, + 0x40, 0x00, 0x04, 0x00, 0x20, 0x00, 0x74, 0x00, 0x07, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, + 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x40, 0x00, 0xf0, 0x00, 0x00, 0x00, 0xcc, 0x01, + 0x30, 0xff, 0x88, 0x01, 0x18, 0xff, 0x66, 0x61, 0x63, 0x74, 0x04, 0x00, 0x00, 0x00, 0x30, 0x02, + 0x00, 0x00, 0x4c, 0x49, 0x53, 0x54, 0x1a, 0x00, 0x00, 0x00, 0x49, 0x4e, 0x46, 0x4f, 0x49, 0x53, + 0x46, 0x54, 0x0e, 0x00, 0x00, 0x00, 0x4c, 0x61, 0x76, 0x66, 0x36, 0x30, 0x2e, 0x31, 0x36, 0x2e, + 0x31, 0x30, 0x30, 0x00, 0x64, 0x61, 0x74, 0x61, 0x40, 0x01, 0x00, 0x00, 0x00, 0x10, 0x00, 0x1f, + 0x06, 0x00, 0x00, 0x77, 0x76, 0xec, 0xdc, 0xdf, 0xf1, 0x25, 0x34, 0x32, 0x00, 0xdb, 0xdc, 0xde, + 0x00, 0x35, 0x34, 0x32, 0x00, 0xdb, 0xdc, 0xde, 0x00, 0x35, 0x34, 0x32, 0x00, 0xdb, 0xdc, 0xde, + 0xf1, 0x35, 0x34, 0x32, 0x1f, 0xdb, 0xdc, 0xde, 0xf1, 0x35, 0x34, 0x32, 0x1f, 0xdb, 0xdc, 0xde, + 0xf1, 0x35, 0x34, 0x32, 0x1f, 0xdb, 0xdc, 0xde, 0xf1, 0x35, 0x34, 0x32, 0x00, 0x87, 0x01, 0xc7, + 0x0e, 0xff, 0x0f, 0xec, 0xcd, 0xde, 0xf1, 0x35, 0x43, 0x32, 0x1f, 0xdb, 0xcd, 0xde, 0xf1, 0x35, + 0x43, 0x32, 0x1f, 0xdb, 0xcd, 0xde, 0xf1, 0x35, 0x43, 0x32, 0x1f, 0xdb, 0xcd, 0xde, 0xf1, 0x35, + 0x43, 0x32, 0x1f, 0xdb, 0xcd, 0xde, 0xf1, 0x35, 0x43, 0x32, 0x1f, 0xdb, 0xcd, 0xde, 0xf1, 0x35, + 0x43, 0x32, 0x1f, 0xdb, 0xcd, 0xde, 0xf1, 0x35, 0x43, 0x32, 0x1f, 0xdb, 0x00, 0x99, 0x01, 0xe1, + 0xf9, 0x00, 0x00, 0xdd, 0xf1, 0x44, 0x44, 0x22, 0x1f, 0xdc, 0xcd, 0xce, 0x00, 0x34, 0x44, 0x22, + 0x1f, 0xdc, 0xcd, 0xce, 0x01, 0x24, 0x44, 0x22, 0x1f, 0xdc, 0xcd, 0xce, 0x01, 0x24, 0x44, 0x22, + 0x1f, 0xdc, 0xcd, 0xce, 0x01, 0x24, 0x44, 0x22, 0x1f, 0xdc, 0xcd, 0xce, 0x01, 0x24, 0x44, 0x22, + 0x1f, 0xdc, 0xcd, 0xce, 0x01, 0x24, 0x44, 0x22, 0x1f, 0xdc, 0xcd, 0xce, 0x00, 0xb7, 0x01, 0x39, + 0xf1, 0x01, 0xf0, 0x23, 0x53, 0x22, 0x1f, 0xeb, 0xdc, 0xde, 0x00, 0x35, 0x34, 0x32, 0x0f, 0xeb, + 0xdc, 0xde, 0x00, 0x35, 0x34, 0x32, 0x00, 0xdb, 0xdc, 0xde, 0x00, 0x35, 0x34, 0x32, 0x00, 0xdb, + 0xdc, 0xde, 0xf1, 0x35, 0x34, 0x32, 0x1f, 0xdb, 0xdc, 0xde, 0xf1, 0x35, 0x34, 0x32, 0x1f, 0xdb, + 0xdc, 0xde, 0xf1, 0x35, 0x34, 0x32, 0x1f, 0xdb, 0xdc, 0xde, 0xf1, 0x35, 0x00, 0xc4, 0x01, 0x1f, + 0x06, 0x00, 0x00, 0x32, 0x1f, 0xdb, 0xcd, 0xde, 0xf1, 0x35, 0x43, 0x32, 0x1f, 0xdb, 0xcd, 0xde, + 0xf1, 0x35, 0x43, 0x32, 0x1f, 0xdb, 0xcd, 0xde, 0xf1, 0x35, 0x43, 0x32, 0x1f, 0xdb, 0xcd, 0xde, + 0xf1, 0x35, 0x43, 0x32, 0x1f, 0xdb, 0xcd, 0xde, 0xf1, 0x35, 0x43, 0x32, 0x1f, 0xdb, 0xcd, 0xde, + 0xf1, 0x35, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x1f, 0x1f, +}; + +/* ffmpeg's samples [1, 5, 9, 100, 300, 577] of it */ +static const int ima_at[] = { 1, 5, 9, 100, 300, 577 }; +static const int ima_want[] = { 13, 536, -1554, 4238, -3936, 8 }; +static const int ima_n = 605; +/* ffmpeg's samples [1, 5, 9, 100, 300, 577] of it */ +static const int ms_at[] = { 1, 5, 9, 100, 300, 577 }; +static const int ms_want[] = { 1567, 3890, -1630, 4191, -4014, -40 }; +static const int ms_n = 580; + +static void be16(char *p, unsigned v) { p[0] = (char)(v >> 8); p[1] = (char)v; } +static void be32(char *p, unsigned long v) { be16(p, (unsigned)(v >> 16)); be16(p + 2, (unsigned)(v & 0xffff)); } + +/* sound files other than 16-bit WAV: AIFF, .au, 24-bit and float WAV, + IMA and Microsoft ADPCM (against ffmpeg's decoding) */ +static void test_formats(void) +{ + int16_t *pcm; + int i, n; + /* AIFF, 16-bit big-endian, 8000 Hz (80-bit: 0x400B FA00...), mono */ + char a[12 + 26 + 16 + 8]; + memset(a, 0, sizeof(a)); + memcpy(a, "FORM", 4); be32(a + 4, sizeof(a) - 8); memcpy(a + 8, "AIFF", 4); + memcpy(a + 12, "COMM", 4); be32(a + 16, 18); + be16(a + 20, 1); be32(a + 22, 4); be16(a + 26, 16); + a[28] = 0x40; a[29] = 0x0b; a[30] = (char)0xfa; + memcpy(a + 38, "SSND", 4); be32(a + 42, 8 + 8); + be16(a + 54, 0x1000); be16(a + 56, 0xf000); be16(a + 58, 0x7fff); be16(a + 60, 0x8000); + CHECK(dmc_audio_decode(a, sizeof(a), &pcm) == 4); + CHECK(pcm[0] == 4096 && pcm[1] == -4096 && pcm[2] == 32767 && pcm[3] == -32768); + dmc_free(pcm); + /* .au, mu-law, 8000 Hz, mono */ + char u[24 + 3]; + memcpy(u, ".snd", 4); be32(u + 4, 24); be32(u + 8, 3); be32(u + 12, 1); + be32(u + 16, 8000); be32(u + 20, 1); + u[24] = (char)0xff; u[25] = 0x00; u[26] = (char)0x80; + CHECK(dmc_audio_decode(u, sizeof(u), &pcm) == 3); + CHECK(pcm[0] == 0 && pcm[1] == -32124 && pcm[2] == 32124); + dmc_free(pcm); + /* WAV, 24-bit, then 32-bit float */ + char w[44 + 6]; + dmc_wav_header(w, 3); + w[32] = 3; w[34] = 24; w[40] = 6; + memcpy(w + 44, "\x00\x00\x40\x00\x00\xc0", 6); + CHECK(dmc_audio_decode(w, sizeof(w), &pcm) == 2); + CHECK(pcm[0] == 16384 && pcm[1] == -16384); + dmc_free(pcm); + char f[44 + 8]; + float h = 0.5f, m = -1.0f; + dmc_wav_header(f, 4); + f[20] = 3; f[32] = 4; f[34] = 32; f[40] = 8; + memcpy(f + 44, &h, 4); memcpy(f + 48, &m, 4); + CHECK(dmc_audio_decode(f, sizeof(f), &pcm) == 2); + CHECK(pcm[0] == 16383 && pcm[1] == -32767); + dmc_free(pcm); + /* ADPCM: Microsoft's as ffmpeg decodes it, IMA within a few steps + (ffmpeg's arithmetic is finer than the IMA's own) */ + n = dmc_audio_decode((const char *)ms_wav, sizeof(ms_wav), &pcm); + CHECK(n == ms_n); + for (i = 0; n == ms_n && i < (int)(sizeof(ms_at) / sizeof(ms_at[0])); i++) + CHECK(pcm[ms_at[i]] == ms_want[i]); + dmc_free(pcm); + n = dmc_audio_decode((const char *)ima_wav, sizeof(ima_wav), &pcm); + CHECK(n == ima_n); + for (i = 0; n == ima_n && i < (int)(sizeof(ima_at) / sizeof(ima_at[0])); i++) + CHECK(abs(pcm[ima_at[i]] - ima_want[i]) <= 8); + dmc_free(pcm); + CHECK(dmc_audio_decode("FORM\0\0\0\4AIFF", 12, &pcm) == -1 && !pcm); + CHECK(dmc_audio_decode("ID3\4\0\0\0\0\0\0\0\0", 12, &pcm) == -1); +} + int main(int argc, char **argv) { const char *dir = argc > 1 ? argv[1] : "."; @@ -762,6 +893,7 @@ int main(int argc, char **argv) test_voice(); test_voicemail(); test_wav(); + test_formats(); printf("%d checks, %d failed\n", checks, failures); return failures ? 1 : 0; } diff --git a/docs/design.md b/docs/design.md index 13b86d9..73e820f 100644 --- a/docs/design.md +++ b/docs/design.md @@ -73,18 +73,22 @@ stream by the clock given to `dmc_poll`, DTMF, and the answering machine. The apps only move 8 kHz 16-bit samples between it and the sound card (`dmc_voice_read`, `dmc_voice_write`): -| | Sound | Settings | Messages | -| --- | --- | --- | --- | -| Linux | PulseAudio on the GLib main loop (or PipeWire's Pulse server) | `settings.ini`, `[voice]` | `~/.local/share/dmodem-gui/voicemail` | -| Windows | `waveOut` and `waveIn` with window callbacks (Windows 95 has them) | `dmodem.ini`, `[voice]` | `%APPDATA%\D-Modem\Voicemail`, or beside the exe | -| macOS | AVAudioEngine, converted to 8 kHz | UserDefaults | `~/Library/Application Support/D-Modem/Voicemail` | +| | Sound | Settings | Messages | Greeting files beyond the library's | +| --- | --- | --- | --- | --- | +| Linux | PulseAudio on the GLib main loop (or PipeWire's Pulse server) | `settings.ini`, `[voice]` | `~/.local/share/dmodem-gui/voicemail` | libsndfile, when built with it: MP3, FLAC, Ogg Vorbis, Opus | +| Windows | `waveOut` and `waveIn` with window callbacks (Windows 95 has them) | `dmodem.ini`, `[voice]` | `%APPDATA%\D-Modem\Voicemail`, or beside the exe | the system's ACM codecs: MP3 and compressed WAVs (GSM 6.10 and the rest installed) | +| macOS | AVAudioEngine, converted to 8 kHz | UserDefaults | `~/Library/Application Support/D-Modem/Voicemail` | AVAudioFile: MP3, AAC/M4A, FLAC, ALAC, CAF | The answering machine is off until it is turned on. When on, after the chosen number of rings (4 by default) it answers, plays the greeting (or none), beeps, and records until the caller hangs up, 7 s of silence, or 2 minutes. Each message is a WAV file named for its time and the caller's number; one under a second is dropped. A greeting can be recorded from the -microphone or chosen from any WAV file, which is converted to 8 kHz mono. +microphone or chosen from a sound file, which is converted to 8 kHz mono. +The library reads WAV (8 to 32-bit PCM, floats, A-law, μ-law, IMA and +Microsoft ADPCM), AIFF and AIFF-C, and Sun/NeXT `.au` itself +(`dmc_audio_decode`); each app hands the rest to the system's decoders, +as in the table. Pick Up turns a message being taken into a call; Listen plays it as it is left. Messages stay on this computer. diff --git a/linux/CMakeLists.txt b/linux/CMakeLists.txt index 1ab6068..e4da09e 100644 --- a/linux/CMakeLists.txt +++ b/linux/CMakeLists.txt @@ -18,6 +18,15 @@ if(PULSE_FOUND) else() message(STATUS "libpulse-mainloop-glib not found: the Linux app has no sound for voice calls") endif() +# greetings from MP3, FLAC, Ogg and the like (WAV, AIFF and .au need +# nothing more) +pkg_check_modules(SNDFILE IMPORTED_TARGET sndfile) +if(SNDFILE_FOUND) + target_link_libraries(dmodem-gui PRIVATE PkgConfig::SNDFILE) + target_compile_definitions(dmodem-gui PRIVATE HAVE_SNDFILE) +else() + message(STATUS "libsndfile not found: greetings are read from WAV, AIFF and .au files only") +endif() target_compile_options(dmodem-gui PRIVATE -Wall -Wextra -Wno-unused-parameter) include(GNUInstallDirs) diff --git a/linux/src/voice.c b/linux/src/voice.c index 420c319..421d02f 100644 --- a/linux/src/voice.c +++ b/linux/src/voice.c @@ -15,6 +15,10 @@ #include "app.h" +#ifdef HAVE_SNDFILE +#include +#endif + /* the longest greeting recorded (s) */ #define GREETING_MAX_S 30 @@ -81,7 +85,70 @@ static gboolean write_wav(const char *path, const int16_t *pcm, int n, return ok; } -/* a WAV file's samples at 8 kHz: how many (*pcm to dmc_free()), -1 */ +#ifdef HAVE_SNDFILE +/* a sound file libsndfile reads (MP3, FLAC, Ogg Vorbis, Opus and the + rest it knows) as samples at 8 kHz, mono: how many (*pcm to free()), -1 */ +static int read_sndfile(const char *path, int16_t **pcm) +{ + SF_INFO info = { 0 }; + SNDFILE *sf = sf_open(path, SFM_READ, &info); + *pcm = NULL; + if (!sf) + return -1; + int ch = info.channels; + if (ch < 1 || info.samplerate < 1 || info.frames < 1 || + info.frames > (sf_count_t)info.samplerate * 3600) { + sf_close(sf); + return -1; + } + /* read in pieces (the frame count of an MP3 is a guess), mixed to mono */ + GArray *mono = g_array_new(FALSE, FALSE, sizeof(float)); + float *buf = g_new(float, 4096 * (gsize)ch); + sf_count_t got; + while ((got = sf_readf_float(sf, buf, 4096)) > 0) { + for (sf_count_t i = 0; i < got; i++) { + float m = 0; + for (int c = 0; c < ch; c++) + m += buf[i * ch + c]; + m /= (float)ch; + g_array_append_val(mono, m); + } + if (mono->len > (guint)info.samplerate * 3600) + break; + } + g_free(buf); + sf_close(sf); + double step = (double)info.samplerate / 8000; + gint64 n = mono->len ? (gint64)((mono->len - 1) / step) + 1 : 0; + if (n < 1 || n > G_MAXINT) { + g_array_free(mono, TRUE); + return -1; + } + int16_t *out = malloc((size_t)n * sizeof(int16_t)); + if (!out) { + g_array_free(mono, TRUE); + return -1; + } + const float *x = (const float *)mono->data; + for (gint64 i = 0; i < n; i++) { + double t = i * step; + guint k = (guint)t; + double f = t - k; + double y = x[k]; + if (k + 1 < mono->len) + y += (x[k + 1] - y) * f; + y *= 32767; + out[i] = (int16_t)(y > 32767 ? 32767 : y < -32768 ? -32768 : y); + } + g_array_free(mono, TRUE); + *pcm = out; + return (int)n; +} +#endif + +/* a sound file's samples at 8 kHz, mono: WAV, AIFF and .au by + libdmodemctl, the rest (MP3, FLAC, Ogg) by libsndfile where it's + built in. How many (*pcm to dmc_free()), -1 */ static int read_wav(const char *path, int16_t **pcm) { char *b; @@ -89,8 +156,12 @@ static int read_wav(const char *path, int16_t **pcm) *pcm = NULL; if (!g_file_get_contents(path, &b, &len, NULL)) return -1; - int n = len > G_MAXINT ? -1 : dmc_wav_decode(b, (int)len, pcm); + int n = len > G_MAXINT ? -1 : dmc_audio_decode(b, (int)len, pcm); g_free(b); +#ifdef HAVE_SNDFILE + if (n < 0) + n = read_sndfile(path, pcm); +#endif return n; } @@ -431,8 +502,7 @@ static void greeting_chosen(GObject *src, GAsyncResult *res, gpointer data) if (n <= 0) { if (n == 0) dmc_free(pcm); - window_toast(a, "That isn't a WAV file D-Modem can play " - "(PCM, A-law or µ-law)"); + window_toast(a, "That isn't a sound file D-Modem can play"); return; } char *p = greeting_path(); @@ -455,8 +525,15 @@ static void choose_greeting(GtkWidget *w, gpointer data) GtkFileDialog *d = gtk_file_dialog_new(); gtk_file_dialog_set_title(d, "Greeting"); GtkFileFilter *f = gtk_file_filter_new(); - gtk_file_filter_set_name(f, "WAV files"); - gtk_file_filter_add_suffix(f, "wav"); + gtk_file_filter_set_name(f, "Sound files"); + static const char *const kinds[] = { + "wav", "aif", "aiff", "aifc", "au", "snd", +#ifdef HAVE_SNDFILE + "mp3", "flac", "ogg", "oga", "opus", "caf", "w64", +#endif + }; + for (gsize i = 0; i < G_N_ELEMENTS(kinds); i++) + gtk_file_filter_add_suffix(f, kinds[i]); GListStore *filters = g_list_store_new(GTK_TYPE_FILE_FILTER); g_list_store_append(filters, f); gtk_file_dialog_set_filters(d, G_LIST_MODEL(filters)); @@ -820,7 +897,7 @@ GtkWidget *voice_page_new(App *a) G_CALLBACK(play_greeting), a); v->record_btn = button("Record", G_CALLBACK(record_greeting), a); GtkWidget *choose = icon_button("document-open-symbolic", - "Use a WAV file", + "Use a sound file", G_CALLBACK(choose_greeting), a); v->greeting_clear = icon_button("user-trash-symbolic", "No greeting: the beep alone", diff --git a/macos/DModem/Voice.swift b/macos/DModem/Voice.swift index c9ba0a6..6e83ed0 100644 --- a/macos/DModem/Voice.swift +++ b/macos/DModem/Voice.swift @@ -234,19 +234,61 @@ final class Voice: ObservableObject { try d.write(to: url, options: .atomic) } - /// a WAV file's samples at 8 kHz, nil if it is not one D-Modem reads + /// a sound file's samples at 8 kHz, mono: WAV, AIFF and .au by the + /// library, the rest (MP3, AAC/M4A, FLAC, ALAC, CAF) by the Mac's own + /// decoders; nil if it is not one D-Modem reads static func readWav(_ url: URL) -> [Int16]? { guard let d = try? Data(contentsOf: url), d.count < Int(Int32.max) else { return nil } var pcm: UnsafeMutablePointer? let n = d.withUnsafeBytes { b in - dmc_wav_decode(b.baseAddress?.assumingMemoryBound(to: CChar.self), - Int32(b.count), &pcm) + dmc_audio_decode(b.baseAddress?.assumingMemoryBound(to: CChar.self), + Int32(b.count), &pcm) } defer { dmc_free(pcm) } - guard n >= 0, let p = pcm else { return nil } + guard n >= 0, let p = pcm else { return readBySystem(url) } return Array(UnsafeBufferPointer(start: p, count: Int(n))) } + /// a sound file the system decodes, as samples at 8 kHz, mono (five + /// minutes at most); nil if it can't + static func readBySystem(_ url: URL, maxSeconds: Int = 300) -> [Int16]? { + guard let f = try? AVAudioFile(forReading: url) else { return nil } + let src = f.processingFormat + guard src.sampleRate > 0, src.channelCount > 0, + let dst = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 8000, channels: 1, interleaved: false), + let conv = AVAudioConverter(from: src, to: dst), + let inBuf = AVAudioPCMBuffer(pcmFormat: src, frameCapacity: 4096), + let outBuf = AVAudioPCMBuffer(pcmFormat: dst, frameCapacity: AVAudioFrameCount(4096 * 8000 / src.sampleRate) + 64) + else { return nil } + // (the channels mixed, not the first alone) + conv.downmix = true + var out: [Int16] = [] + var ended = false + while out.count < maxSeconds * 8000 { + outBuf.frameLength = 0 + var err: NSError? + let st = conv.convert(to: outBuf, error: &err) { _, status in + if !ended { + do { try f.read(into: inBuf) } catch { inBuf.frameLength = 0 } + ended = inBuf.frameLength == 0 + } + if ended { + status.pointee = .endOfStream + return nil + } + status.pointee = .haveData + return inBuf + } + if let x = outBuf.floatChannelData?[0] { + for i in 0.. dmodem.lnk wlink @dmodem.lnk diff --git a/windows/src/voice.cpp b/windows/src/voice.cpp index e02a9ef..f462893 100644 --- a/windows/src/voice.cpp +++ b/windows/src/voice.cpp @@ -14,6 +14,9 @@ #include "app.h" #include +#include +#include +#include #include "resource.h" #ifndef OPENFILENAME_SIZE_VERSION_400 @@ -82,7 +85,266 @@ static bool write_wav(const char *path, const short *pcm, int n) return ok; } -/* a WAV file's samples at 8 kHz: how many (*pcm to dmc_free()), -1 */ +/* + * sound files the library doesn't read, by Windows' own codecs (ACM): + * compressed WAVs (GSM 6.10, MP3 and the rest installed) and MP3s + */ + +/* the most decoded (s): a greeting is shorter */ +#define DECODE_MAX_S 300 + +static unsigned long le32(const unsigned char *p) +{ + return p[0] | (unsigned long)p[1] << 8 | (unsigned long)p[2] << 16 | + (unsigned long)p[3] << 24; +} + +/* a RIFF WAVE's format (*fmt to free()) and sound: false if it's not one */ +static bool wav_chunks(const unsigned char *b, long len, WAVEFORMATEX **fmt, + const unsigned char **data, long *data_len) +{ + if (len < 12 || memcmp(b, "RIFF", 4) || memcmp(b + 8, "WAVE", 4)) + return false; + *fmt = NULL; + *data = NULL; + for (long i = 12; i + 8 <= len;) { + unsigned long n = le32(b + i + 4); + long have = len - i - 8; + long take = n > (unsigned long)have ? have : (long)n; + if (!memcmp(b + i, "fmt ", 4) && !*fmt && take >= 16) { + /* (cbSize, 0 when the chunk has none) */ + long size = take < 18 ? 18 : take; + *fmt = (WAVEFORMATEX *)calloc(1, size); + if (!*fmt) + return false; + memcpy(*fmt, b + i + 8, take); + if (take < 18) + (*fmt)->cbSize = 0; + else if ((*fmt)->cbSize > take - 18) + (*fmt)->cbSize = (WORD)(take - 18); + } else if (!memcmp(b + i, "data", 4) && !*data) { + *data = b + i + 8; + *data_len = take; + } + if (n > (unsigned long)have) + break; + i += 8 + (long)n + (n & 1); + } + if (*fmt && *data) + return true; + free(*fmt); + *fmt = NULL; + return false; +} + +/* an MP3 frame's header at p: its length (0: not one), the format */ +static long mp3_frame(const unsigned char *p, MPEGLAYER3WAVEFORMAT *f) +{ + static const int rates[3] = { 44100, 48000, 32000 }; + static const int kbps1[15] = { 0, 32, 40, 48, 56, 64, 80, 96, 112, + 128, 160, 192, 224, 256, 320 }; + static const int kbps2[15] = { 0, 8, 16, 24, 32, 40, 48, 56, 64, 80, + 96, 112, 128, 144, 160 }; + if (p[0] != 0xff || (p[1] & 0xe0) != 0xe0) + return 0; + int version = (p[1] >> 3) & 3; /* 3: MPEG-1, 2: MPEG-2, 0: 2.5 */ + int layer = (p[1] >> 1) & 3; /* 1: layer III */ + int bi = p[2] >> 4, ri = (p[2] >> 2) & 3; + if (version == 1 || layer != 1 || bi == 0 || bi == 15 || ri == 3) + return 0; + int rate = rates[ri] >> (version == 3 ? 0 : version == 2 ? 1 : 2); + int kbps = version == 3 ? kbps1[bi] : kbps2[bi]; + long block = (version == 3 ? 144000L : 72000L) * kbps / rate; + memset(f, 0, sizeof(*f)); + f->wfx.wFormatTag = WAVE_FORMAT_MPEGLAYER3; + f->wfx.nChannels = (p[3] >> 6) == 3 ? 1 : 2; + f->wfx.nSamplesPerSec = rate; + f->wfx.nAvgBytesPerSec = kbps * 1000 / 8; + f->wfx.nBlockAlign = 1; + f->wfx.cbSize = MPEGLAYER3_WFX_EXTRA_BYTES; + f->wID = MPEGLAYER3_ID_MPEG; + f->fdwFlags = MPEGLAYER3_FLAG_PADDING_OFF; + f->nBlockSize = (WORD)block; + f->nFramesPerBlock = 1; + f->nCodecDelay = 1393; + return block + ((p[2] >> 1) & 1); +} + +/* an MP3 file's format and frames: false if it's not one (the first + frame's header checked against the next's) */ +static bool mp3_parts(const unsigned char *b, long len, + MPEGLAYER3WAVEFORMAT *f, const unsigned char **data, + long *data_len) +{ + long i = 0; + if (len >= 10 && !memcmp(b, "ID3", 3)) + i = 10 + ((long)(b[6] & 0x7f) << 21 | (long)(b[7] & 0x7f) << 14 | + (long)(b[8] & 0x7f) << 7 | (b[9] & 0x7f)) + + (b[5] & 0x10 ? 10 : 0); + /* (some junk before the first frame) */ + for (long end = i + 4096; i + 4 <= len && i < end; i++) { + long n = mp3_frame(b + i, f); + MPEGLAYER3WAVEFORMAT next; + if (n > 0 && (i + n + 4 > len || mp3_frame(b + i + n, &next))) { + *data = b + i; + *data_len = len - i; + return true; + } + } + return false; +} + +/* the sound in fmt decoded by the system's codecs, as a 16-bit PCM WAV + file (to free()): its length, -1 if no codec reads it */ +static long acm_decode(WAVEFORMATEX *fmt, const unsigned char *data, + long len, char **wav) +{ + WAVEFORMATEX pcm; + memset(&pcm, 0, sizeof(pcm)); + pcm.wFormatTag = WAVE_FORMAT_PCM; + pcm.wBitsPerSample = 16; + if (acmFormatSuggest(NULL, fmt, &pcm, sizeof(pcm), + ACM_FORMATSUGGESTF_WFORMATTAG | + ACM_FORMATSUGGESTF_WBITSPERSAMPLE)) + return -1; + HACMSTREAM h; + if (acmStreamOpen(&h, NULL, fmt, &pcm, NULL, 0, 0, + ACM_STREAMOPENF_NONREALTIME)) + return -1; + /* pieces of whole blocks */ + DWORD align = fmt->nBlockAlign ? fmt->nBlockAlign : 1; + DWORD piece = (16384 / align + 1) * align, out_size = 0; + if (acmStreamSize(h, piece, &out_size, ACM_STREAMSIZEF_SOURCE) || + !out_size) { + acmStreamClose(h, 0); + return -1; + } + unsigned char *src = (unsigned char *)malloc(piece); + unsigned char *dst = (unsigned char *)malloc(out_size); + long max = (long)pcm.nAvgBytesPerSec * DECODE_MAX_S; + long cap = 1 << 20, got = 0; + char *w = (char *)malloc(44 + cap); + ACMSTREAMHEADER hd; + memset(&hd, 0, sizeof(hd)); + hd.cbStruct = sizeof(hd); + hd.pbSrc = src; + hd.cbSrcLength = piece; + hd.pbDst = dst; + hd.cbDstLength = out_size; + bool ok = src && dst && w && !acmStreamPrepareHeader(h, &hd, 0); + if (ok) { + DWORD left = 0; + long at = 0; + bool first = true; + for (;;) { + DWORD n = piece - left; + if (n > (DWORD)(len - at)) + n = (DWORD)(len - at); + memcpy(src + left, data + at, n); + at += n; + bool last = at >= len; + hd.cbSrcLength = left + n; + DWORD flags = (first ? ACM_STREAMCONVERTF_START : 0) | + (last ? ACM_STREAMCONVERTF_END : + ACM_STREAMCONVERTF_BLOCKALIGN); + first = false; + if (acmStreamConvert(h, &hd, flags)) { + ok = got > 0; + break; + } + if (got + (long)hd.cbDstLengthUsed > cap) { + while (got + (long)hd.cbDstLengthUsed > cap) + cap *= 2; + char *m = (char *)realloc(w, 44 + cap); + if (!m) { + ok = false; + break; + } + w = m; + } + memcpy(w + 44 + got, dst, hd.cbDstLengthUsed); + got += hd.cbDstLengthUsed; + left = hd.cbSrcLength - hd.cbSrcLengthUsed; + if (left) + memmove(src, src + hd.cbSrcLengthUsed, left); + /* (the end, or nothing more taken) */ + if (last || got >= max || + (!hd.cbSrcLengthUsed && !hd.cbDstLengthUsed)) + break; + } + hd.cbSrcLength = piece; + hd.cbDstLength = out_size; + acmStreamUnprepareHeader(h, &hd, 0); + } + acmStreamClose(h, 0); + free(src); + free(dst); + if (!ok || got < 2) { + free(w); + return -1; + } + /* the PCM as a WAV file, for the library to mix and resample */ + unsigned char *p = (unsigned char *)w; + unsigned long v[] = { (unsigned long)(36 + got), 16, + (unsigned long)pcm.nSamplesPerSec, + (unsigned long)pcm.nAvgBytesPerSec, + (unsigned long)got }; + memcpy(p, "RIFF\0\0\0\0WAVEfmt \0\0\0\0", 20); + for (int k = 0; k < 4; k++) + p[4 + k] = (unsigned char)(v[0] >> (8 * k)); + p[16] = 16; + p[20] = 1; /* PCM */ + p[21] = 0; + p[22] = (unsigned char)pcm.nChannels; + p[23] = 0; + for (int k = 0; k < 4; k++) { + p[24 + k] = (unsigned char)(v[2] >> (8 * k)); + p[28 + k] = (unsigned char)(v[3] >> (8 * k)); + p[40 + k] = (unsigned char)(v[4] >> (8 * k)); + } + p[32] = (unsigned char)pcm.nBlockAlign; + p[33] = 0; + p[34] = 16; + p[35] = 0; + memcpy(p + 36, "data", 4); + *wav = w; + return 44 + got; +} + +/* a file the library doesn't read (in b) by the system's codecs, at + 8 kHz: how many (*pcm to dmc_free()), -1 */ +static int read_by_system(const unsigned char *b, long len, short **pcm) +{ + WAVEFORMATEX *fmt; + MPEGLAYER3WAVEFORMAT mp3; + const unsigned char *data; + long data_len; + char *wav; + long n; + if (wav_chunks(b, len, &fmt, &data, &data_len)) { + /* (an MP3 in a WAV: the format from its frames, the header's + often short of what the codec needs) */ + if (fmt->wFormatTag == WAVE_FORMAT_MPEGLAYER3 && + mp3_parts(data, data_len, &mp3, &data, &data_len)) + n = acm_decode(&mp3.wfx, data, data_len, &wav); + else + n = acm_decode(fmt, data, data_len, &wav); + free(fmt); + } else if (mp3_parts(b, len, &mp3, &data, &data_len)) { + n = acm_decode(&mp3.wfx, data, data_len, &wav); + } else { + return -1; + } + if (n < 0) + return -1; + int k = dmc_audio_decode(wav, (int)n, (int16_t **)pcm); + free(wav); + return k; +} + +/* a sound file's samples at 8 kHz, mono: WAV, AIFF and .au by the + library, compressed WAVs and MP3s by the system's codecs. How many + (*pcm to dmc_free()), -1 */ static int read_wav(const char *path, short **pcm) { *pcm = NULL; @@ -102,8 +364,11 @@ static int read_wav(const char *path, short **pcm) return -1; } int n = -1; - if (fread(b, 1, len, f) == (size_t)len) - n = dmc_wav_decode(b, (int)len, (int16_t **)pcm); + if (fread(b, 1, len, f) == (size_t)len) { + n = dmc_audio_decode(b, (int)len, (int16_t **)pcm); + if (n < 0) + n = read_by_system((const unsigned char *)b, len, pcm); + } fclose(f); free(b); return n; @@ -388,7 +653,8 @@ static void choose_greeting() /* (the size Windows 95 and NT 4 know) */ o.lStructSize = OPENFILENAME_SIZE_VERSION_400; o.hwndOwner = app.main; - o.lpstrFilter = "WAV files\0*.wav\0"; + o.lpstrFilter = "Sound files\0*.wav;*.mp3;*.aif;*.aiff;*.aifc;*.au;*.snd\0" + "All files\0*.*\0"; o.lpstrFile = file; o.nMaxFile = sizeof(file); o.lpstrTitle = "Greeting"; @@ -400,7 +666,7 @@ static void choose_greeting() if (n <= 0) { if (pcm) dmc_free(pcm); - app_message("That isn't a WAV file D-Modem can play"); + app_message("That isn't a sound file D-Modem can play"); return; } char p[MAX_PATH];