summaryrefslogtreecommitdiff
path: root/pcsound/pcsound_bsd.c
blob: 4e1252d1e9e8a7791ea3130d21161d241b8fb9ed (plain)
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
//
// Copyright(C) 2005-2014 Simon Howard
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// DESCRIPTION:
//    PC speaker driver for [Open]BSD 
//    (Should be NetBSD as well, but untested).
//

#include "config.h"

// OpenBSD/NetBSD:

#ifdef HAVE_DEV_ISA_SPKRIO_H
#define HAVE_BSD_SPEAKER
#include <dev/isa/spkrio.h>
#endif

// FreeBSD

#ifdef HAVE_DEV_SPEAKER_SPEAKER_H
#define HAVE_BSD_SPEAKER
#include <dev/speaker/speaker.h>
#endif

#ifdef HAVE_BSD_SPEAKER

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <signal.h>
#include <sys/ioctl.h>
#include <sys/signal.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <fcntl.h>

#include "SDL.h"
#include "SDL_thread.h"

#include "pcsound.h"
#include "pcsound_internal.h"

#define SPEAKER_DEVICE "/dev/speaker"

//
// This driver is far more complicated than it should be, because 
// OpenBSD has sucky support for threads.  Because multithreading
// is done in userspace, invoking the ioctl to make the speaker
// beep will lock all threads until the beep has completed.  
// 
// Thus, to get the beeping to occur in real-time, we must invoke
// the ioctl in a separate process.  To do this, a separate 
// sound server is forked that listens on a socket for tones to
// play.  When a tone is received, a reply is sent back to the
// main process and the tone played.
//
// Meanwhile, back in the main process, there is a sound thread
// that runs, invoking the pcsound callback function to get 
// more tones.  This blocks on the sound server socket, waiting
// for replies.  In this way, when the sound server finishes 
// playing a tone, the next one is sent.
//
// This driver is a bit less accurate than the others, because
// we can only specify sound durations in 1/100ths of a second,
// as opposed to the normal millisecond durations.

static pcsound_callback_func callback;
static int sound_server_pid;
static int sleep_adjust = 0;
static int sound_thread_running;
static SDL_Thread *sound_thread_handle;
static int sound_server_pipe[2];

// Play a sound, checking how long the system call takes to complete
// and autoadjusting for drift.

static void AdjustedBeep(int speaker_handle, int ms, int freq)
{
    unsigned int start_time;
    unsigned int end_time;
    unsigned int actual_time;
    tone_t tone;

    // Adjust based on previous error to keep the tempo right

    if (sleep_adjust > ms)
    {
        sleep_adjust -= ms;
        return;
    }
    else
    {
        ms -= sleep_adjust;
    }

    // Invoke the system call and time how long it takes

    start_time = SDL_GetTicks();

    tone.duration = ms / 10;        // in 100ths of a second
    tone.frequency = freq;

    // Always a positive duration

    if (tone.duration < 1)
    {
        tone.duration = 1;
    }

    if (ioctl(speaker_handle, SPKRTONE, &tone) != 0)
    {
        perror("ioctl");
        return;
    }
    
    end_time = SDL_GetTicks();

    if (end_time > start_time)
    {
        actual_time = end_time - start_time;
    }
    else
    {
        actual_time = ms;
    }

    if (actual_time < ms)
    {
        actual_time = ms;
    }

    // Save sleep_adjust for next time

    sleep_adjust = actual_time - ms;
}

static void SoundServer(int speaker_handle)
{
    tone_t tone;
    int result;

    // Run in a loop, invoking the callback

    for (;;)
    {
        result = read(sound_server_pipe[1], &tone, sizeof(tone_t));

        if (result < 0)
        {
            perror("read");
            return;
        }

        // Send back a response, so the main process knows to send another

        write(sound_server_pipe[1], &tone, sizeof(tone_t));

        // Beep! (blocks until complete)

        AdjustedBeep(speaker_handle, tone.duration, tone.frequency);
    }
}

// Start up the sound server.  Returns non-zero if successful.

static int StartSoundServer(void)
{
    int result;
    int speaker_handle;

    // Try to open the speaker device

    speaker_handle = open(SPEAKER_DEVICE, O_WRONLY);

    if (speaker_handle == -1)
    {
        // Don't have permissions for the console device?

	fprintf(stderr, "StartSoundServer: Failed to open '%s': %s\n",
                        SPEAKER_DEVICE, strerror(errno));
        return 0;
    }

    // Create a pipe for communications

    if (socketpair(AF_UNIX, SOCK_STREAM, 0, sound_server_pipe) < 0)
    {
        perror("socketpair");
        close(speaker_handle);
        return 0;
    }

    // Start a separate process to generate PC speaker output
    // We can't use the SDL threading functions because OpenBSD's
    // threading sucks :-(
    
    result = fork();

    if (result < 0)
    {
        fprintf(stderr, "Failed to fork sound server!\n");
        close(speaker_handle);
        return 0;
    }
    else if (result == 0)
    {
        // This is the child (sound server)

        SoundServer(speaker_handle);
        close(speaker_handle);

        exit(0);
    }
    else
    {
        // This is the parent

        sound_server_pid = result;
        close(speaker_handle);
    }

    return 1;
}

static void StopSoundServer(void)
{
    int status;

    kill(sound_server_pid, SIGINT);
    waitpid(sound_server_pid, &status, 0);
}

static int SoundThread(void *unused)
{
    tone_t tone;
    int duration;
    int frequency;

    while (sound_thread_running)
    {
        // Get the next frequency to play

        callback(&duration, &frequency);

//printf("dur: %i, freq: %i\n", duration, frequency);

        // Build up a tone structure and send to the sound server

        tone.frequency = frequency;
        tone.duration = duration;

        if (write(sound_server_pipe[0], &tone, sizeof(tone_t)) < 0) 
        {
            perror("write");
            break;
        }

        // Wait until the sound server responds before sending another

        if (read(sound_server_pipe[0], &tone, sizeof(tone_t)) < 0)
        {
            perror("read");
            break;
        }
    }

    return 0;
}

static int PCSound_BSD_Init(pcsound_callback_func callback_func)
{
    callback = callback_func;

    if (!StartSoundServer())
    {
        fprintf(stderr, "PCSound_BSD_Init: Failed to start sound server.\n");
        return 0;
    }

    sound_thread_running = 1;
    sound_thread_handle = SDL_CreateThread(SoundThread, NULL);

    return 1;
}

static void PCSound_BSD_Shutdown(void)
{
    // Stop the sound thread

    sound_thread_running = 0;

    SDL_WaitThread(sound_thread_handle, NULL);

    // Stop the sound server

    StopSoundServer();
}

pcsound_driver_t pcsound_bsd_driver =
{
    "BSD",
    PCSound_BSD_Init,
    PCSound_BSD_Shutdown,
};

#endif /* #ifdef HAVE_BSD_SPEAKER */