all repos — xyw @ 9b95f8c88d280f439af31a5aa65421325eed00f3

A minimal virtual machine and assembler for terminals.

devices/beeper.c

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
#include <stdlib.h>
#include <string.h>
#include "../xyw.h"

// beeper device 
#define BEEPER_PITCH 0x0
#define BEEPER_LENGTH 0x2
#define BEEPER_LEVEL 0x4

// 8-bit era constraints 
#define BEEPER_MAX_FREQ 0x2000 // 8192 Hz - typical PC speaker limit
#define BEEPER_MAX_LEVEL 0x0F  // 4-bit volume (0-15)
#define BEEP_SAMPLE_RATE 22050 // Period-accurate low sample rate

// Error codes (high nibble = 4 for beeper device) 
#define BEEPER_ERROR_DEVICE 0x41   // Could not open or configure the audio device
#define BEEPER_ERROR_MEMORY 0x42   // Could not allocate the tone buffer
#define BEEPER_ERROR_PLAYBACK 0x43 // Playback failed once started

/*
 * beep_play_tone() synthesizes a mono square wave and blocks until it has
 * finished playing (a zero/negative frequency or zero volume just sleeps
 * for the duration instead). xyw's beeper device is intentionally
 * synchronous, so there's no streaming/callback machinery: the whole tone
 * is generated up front and handed to the OS in a single call, and each
 * call opens/closes its own audio handle - there's no persistent device
 * state to set up or tear down.
 *
 * Failures (device unavailable, out of memory, playback failure) are
 * reported through *error using the codes above, following the same
 * convention as file.c.
 *
 * Build requirements (see Makefile):
 *   Windows      -> nothing extra (winmm is linked via #pragma comment;
 *                   MinGW users should add -lwinmm)
 *   macOS        -> -framework AudioToolbox -framework CoreFoundation
 *   Linux        -> -lasound, if the ALSA headers are available at compile
 *                   time (see XYW_HAVE_ALSA below); otherwise falls back
 *                   to the OSS backend, same as *BSD
 *   *BSD/other   -> nothing extra (uses /dev/dsp)
 */
static void beep_play_tone(double frequency_hz, unsigned long duration_ms, double volume, xyw_byte *error);

// Detect whether ALSA's development headers are actually installed.
// libasound2-dev isn't always present (e.g. on minimal/headless VPS
// images), so rather than hard-failing the build we fall back to the
// generic OSS backend below when it's missing.
#if defined(__linux__) && defined(__has_include)
#if __has_include(<alsa/asoundlib.h>)
#define XYW_HAVE_ALSA 1
#endif
#endif

// Synthesizes a mono 16-bit square wave. 
// Caller owns the returned buffer.
// Shared by every backend below - this is the only part of tone
// generation that isn't platform-specific. Returns NULL 
// (with *out_frames == 0) if the buffer couldn't be allocated. 
static short *generate_square_wave(double freq, unsigned long duration_ms, double volume, size_t *out_frames)
{
    size_t frames = (size_t)((unsigned long)BEEP_SAMPLE_RATE * duration_ms / 1000);
    if (frames == 0)
        frames = 1;

    short *buf = (short *)malloc(frames * sizeof(short));
    if (!buf)
    {
        *out_frames = 0;
        return NULL;
    }

    size_t period = (size_t)(BEEP_SAMPLE_RATE / freq + 0.5);
    if (period < 2)
        period = 2;
    size_t half = period / 2;
    short amp = (short)(volume * 32767.0);

    for (size_t i = 0; i < frames; i++)
        buf[i] = ((i % period) < half) ? amp : (short)-amp;

    *out_frames = frames;
    return buf;
}

#if defined(_WIN32)

#include <windows.h>
#include <mmsystem.h>
#ifdef _MSC_VER
#pragma comment(lib, "winmm.lib") // MinGW links winmm via the Makefile's -lwinmm instead 
#endif

static void play_buffer(const short *samples, size_t frames, unsigned sample_rate, xyw_byte *error)
{
    size_t data_bytes = frames * sizeof(short);
    size_t total = 44 + data_bytes;
    unsigned char *wav = (unsigned char *)malloc(total);
    if (!wav)
    {
        *error = BEEPER_ERROR_MEMORY;
        return;
    }

    unsigned block_align = 2; // mono, 16-bit 
    unsigned byte_rate = sample_rate * block_align;

    memcpy(wav, "RIFF", 4);
    *(unsigned *)(wav + 4) = (unsigned)(total - 8);
    memcpy(wav + 8, "WAVEfmt ", 8);
    *(unsigned *)(wav + 16) = 16;
    *(unsigned short *)(wav + 20) = 1; // PCM 
    *(unsigned short *)(wav + 22) = 1; // mono 
    *(unsigned *)(wav + 24) = sample_rate;
    *(unsigned *)(wav + 28) = byte_rate;
    *(unsigned short *)(wav + 32) = (unsigned short)block_align;
    *(unsigned short *)(wav + 34) = 16;
    memcpy(wav + 36, "data", 4);
    *(unsigned *)(wav + 40) = (unsigned)data_bytes;
    memcpy(wav + 44, samples, data_bytes);

    // SND_SYNC: PlaySound doesn't return until the clip has finished. 
    if (!PlaySoundA((LPCSTR)wav, NULL, SND_MEMORY | SND_SYNC))
    {
        *error = BEEPER_ERROR_PLAYBACK;
    }
    free(wav);
}

static void beep_play_tone(double frequency_hz, unsigned long duration_ms, double volume, xyw_byte *error)
{
    if (frequency_hz <= 0.0 || volume <= 0.0 || duration_ms == 0)
    {
        Sleep((DWORD)duration_ms);
        return;
    }
    size_t frames;
    short *buf = generate_square_wave(frequency_hz, duration_ms, volume, &frames);
    if (!buf)
    {
        *error = BEEPER_ERROR_MEMORY;
        return;
    }
    play_buffer(buf, frames, BEEP_SAMPLE_RATE, error);
    free(buf);
}

#elif defined(__APPLE__)

#include <AudioToolbox/AudioToolbox.h>
#include <unistd.h>

// AudioQueue requires an output callback, but since we only ever enqueue
// one buffer and don't refill it, there's nothing for it to do.
static void noop_callback(void *ud, AudioQueueRef q, AudioQueueBufferRef buf)
{
    (void)ud;
    (void)q;
    (void)buf;
}

static void play_buffer(const short *samples, size_t frames, unsigned sample_rate, xyw_byte *error)
{
    AudioStreamBasicDescription asbd;
    memset(&asbd, 0, sizeof(asbd));
    asbd.mSampleRate = sample_rate;
    asbd.mFormatID = kAudioFormatLinearPCM;
    asbd.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked;
    asbd.mChannelsPerFrame = 1;
    asbd.mBitsPerChannel = 16;
    asbd.mBytesPerFrame = 2;
    asbd.mFramesPerPacket = 1;
    asbd.mBytesPerPacket = 2;

    AudioQueueRef queue;
    if (AudioQueueNewOutput(&asbd, noop_callback, NULL, NULL, NULL, 0, &queue) != noErr)
    {
        *error = BEEPER_ERROR_DEVICE;
        return;
    }

    AudioQueueBufferRef buf;
    size_t bytes = frames * sizeof(short);
    if (AudioQueueAllocateBuffer(queue, (UInt32)bytes, &buf) != noErr)
    {
        *error = BEEPER_ERROR_DEVICE;
        AudioQueueDispose(queue, true);
        return;
    }
    memcpy(buf->mAudioData, samples, bytes);
    buf->mAudioDataByteSize = (UInt32)bytes;

    if (AudioQueueEnqueueBuffer(queue, buf, 0, NULL) != noErr ||
        AudioQueueStart(queue, NULL) != noErr)
    {
        *error = BEEPER_ERROR_PLAYBACK;
        AudioQueueDispose(queue, true);
        return;
    }

    usleep((useconds_t)((double)frames / sample_rate * 1000000.0));
    AudioQueueStop(queue, true); // synchronous: flushes immediately 
    AudioQueueDispose(queue, true);
}

static void beep_play_tone(double frequency_hz, unsigned long duration_ms, double volume, xyw_byte *error)
{
    if (frequency_hz <= 0.0 || volume <= 0.0 || duration_ms == 0)
    {
        usleep((useconds_t)(duration_ms * 1000));
        return;
    }
    size_t frames;
    short *buf = generate_square_wave(frequency_hz, duration_ms, volume, &frames);
    if (!buf)
    {
        *error = BEEPER_ERROR_MEMORY;
        return;
    }
    play_buffer(buf, frames, BEEP_SAMPLE_RATE, error);
    free(buf);
}

#elif defined(XYW_HAVE_ALSA)

#include <alsa/asoundlib.h>
#include <unistd.h>

static void play_buffer(const short *samples, size_t frames, unsigned sample_rate, xyw_byte *error)
{
    snd_pcm_t *pcm;
    if (snd_pcm_open(&pcm, "default", SND_PCM_STREAM_PLAYBACK, 0) < 0)
    {
        *error = BEEPER_ERROR_DEVICE;
        return;
    }

    if (snd_pcm_set_params(pcm, SND_PCM_FORMAT_S16_LE, SND_PCM_ACCESS_RW_INTERLEAVED,
                            1, sample_rate, 1, 500000) < 0)
    {
        *error = BEEPER_ERROR_DEVICE;
        snd_pcm_close(pcm);
        return;
    }

    snd_pcm_sframes_t written = 0;
    while ((size_t)written < frames)
    {
        snd_pcm_sframes_t n = snd_pcm_writei(pcm, samples + written, frames - written);
        if (n < 0)
        {
            if (snd_pcm_recover(pcm, (int)n, 1) < 0)
            {
                *error = BEEPER_ERROR_PLAYBACK;
                break;
            }
            continue;
        }
        written += n;
    }
    snd_pcm_drain(pcm); // blocks until everything queued has actually played 
    snd_pcm_close(pcm);
}

static void beep_play_tone(double frequency_hz, unsigned long duration_ms, double volume, xyw_byte *error)
{
    if (frequency_hz <= 0.0 || volume <= 0.0 || duration_ms == 0)
    {
        usleep((useconds_t)(duration_ms * 1000));
        return;
    }
    size_t frames;
    short *buf = generate_square_wave(frequency_hz, duration_ms, volume, &frames);
    if (!buf)
    {
        *error = BEEPER_ERROR_MEMORY;
        return;
    }
    play_buffer(buf, frames, BEEP_SAMPLE_RATE, error);
    free(buf);
}

#else // generic OSS backend: FreeBSD, NetBSD, OpenBSD, DragonFly, and
      // Linux systems where the ALSA headers aren't installed

#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/soundcard.h>

static void play_buffer(const short *samples, size_t frames, unsigned sample_rate, xyw_byte *error)
{
    int fd = open("/dev/dsp", O_WRONLY);
    if (fd < 0)
    {
        *error = BEEPER_ERROR_DEVICE;
        return;
    }

    int fmt = AFMT_S16_LE, channels = 1, rate = (int)sample_rate;
    if (ioctl(fd, SNDCTL_DSP_SETFMT, &fmt) < 0 ||
        ioctl(fd, SNDCTL_DSP_CHANNELS, &channels) < 0 ||
        ioctl(fd, SNDCTL_DSP_SPEED, &rate) < 0)
    {
        *error = BEEPER_ERROR_DEVICE;
        close(fd);
        return;
    }

    if (write(fd, samples, frames * sizeof(short)) < 0)
    {
        *error = BEEPER_ERROR_PLAYBACK;
    }
    ioctl(fd, SNDCTL_DSP_SYNC, 0); // blocks until the driver has drained the buffer 
    close(fd);
}

static void beep_play_tone(double frequency_hz, unsigned long duration_ms, double volume, xyw_byte *error)
{
    if (frequency_hz <= 0.0 || volume <= 0.0 || duration_ms == 0)
    {
        usleep((useconds_t)(duration_ms * 1000));
        return;
    }
    size_t frames;
    short *buf = generate_square_wave(frequency_hz, duration_ms, volume, &frames);
    if (!buf)
    {
        *error = BEEPER_ERROR_MEMORY;
        return;
    }
    play_buffer(buf, frames, BEEP_SAMPLE_RATE, error);
    free(buf);
}

#endif // platform selection 

//// Actual device handling                               

void beeper_output(xyw_byte *data, xyw_byte addr, xyw_byte *error)
{
    // Pitch and length are just stored; the beep triggers on level write 
    if (addr != BEEPER_LEVEL)
        return;

    xyw_word pitch = XYW_PEEKW(&data[BEEPER_PITCH]);
    xyw_word length = XYW_PEEKW(&data[BEEPER_LENGTH]);
    xyw_byte level = data[BEEPER_LEVEL];

    if (pitch > BEEPER_MAX_FREQ)
        pitch = BEEPER_MAX_FREQ;
    if (level > BEEPER_MAX_LEVEL)
        level = BEEPER_MAX_LEVEL;

    if (level == 0 || length == 0)
        return;

    // Convert length from 1/256 seconds to milliseconds
    unsigned long duration_ms = ((unsigned long)length * 1000) / 256;
    if (duration_ms == 0)
        duration_ms = 1;

    double volume = (double)level / (double)BEEPER_MAX_LEVEL;

    // Pitch of 0 means silence (pause for the duration)
    beep_play_tone((double)pitch, duration_ms, volume, error);
}

xyw_byte beeper_input(xyw_byte *data, xyw_byte addr, xyw_byte *error)
{
    (void)error;
    return data[addr];
}

void beeper_teardown(xyw_byte *data)
{
    (void)data;
}