Debian Codegraph @

addons/audio/dsound.cpp

raw
1 /*
2 * Based on DirectSound driver by KC/Milan
3 */
4 #ifndef _WIN32_WINNT
5 #define _WIN32_WINNT 0x0501
6 #endif
7
8 #ifndef WINVER
9 #define WINVER 0x0501
10 #endif
11
12 #include <stdio.h>
13 #include <string.h>
14
15
16 #include <windows.h>
17 #include <dsound.h>
18
19 /* dsound.h from the official DirectX SDK uses __null to annotate some
20 * function arguments. It is #defined away by a macro in sal.h, but this
21 * breaks GCC headers, as they also use __null (but for a different
22 * purpose). This pre-processor block undefines __null which returns
23 * __null to acting like a GCC keyword.
24 * This does nothing for the unofficial DirectX SDK, which has __null
25 * manually removed. */
26 #if defined __MINGW32__ && defined __null
27 #undef __null
28 #endif
29
30 /* I'm not sure what library this is supposed to be in, but I couldn't find it yet */
31 const IID GUID_NULL = { 0, 0, 0, { 0, 0, 0, 0, 0, 0, 0, 0 } };
32
33 static const IID _al_IID_IDirectSoundBuffer8 = { 0x6825a449, 0x7524, 0x4d82, { 0x92, 0x0f, 0x50, 0xe3, 0x6a, 0xb3, 0xab, 0x1e } };
34 static const IID _al_IID_IDirectSoundCaptureBuffer8 = { 0x00990df4, 0x0dbb, 0x4872, { 0x83, 0x3e, 0x6d, 0x30, 0x3e, 0x80, 0xae, 0xb6 } };
35
36 #define ALLEGRO_INTERNAL_UNSTABLE
37 #include "allegro5/allegro.h"
38
39 extern "C" {
40
41 ALLEGRO_DEBUG_CHANNEL("audio-dsound")
42
43 #include "allegro5/internal/aintern_audio.h"
44 #include "allegro5/internal/aintern_system.h"
45 #include "allegro5/internal/aintern_wunicode.h"
46
47 /* This is used to stop MinGW from complaining about type-punning */
48 #define MAKE_UNION(ptr, t) \
49 union { \
50 LPVOID *v; \
51 t p; \
52 } u; \
53 u.p = (ptr);
54
55 /* DirectSound vars */
56 static IDirectSound8 *device;
57 static IDirectSoundCapture8 *capture_device;
58 static char ds_err_str[100];
59 static int buffer_size; // in bytes
60 static _AL_LIST* output_device_list;
61
62 #define MIN_BUFFER_SIZE 1024
63 #define MIN_FILL 512
64 #define MAX_FILL 1024
65
66 static BOOL CALLBACK _ds_enum_callback(LPGUID lpGuid, LPCTSTR lpcstrDescription, LPCTSTR lpcstrModule, LPVOID lpContext);
67
68 static HWND get_window()
69 {
70 const char *val = al_get_config_value(al_get_system_config(),
71 "directsound", "window");
72 HWND ret;
73 if (val && strncmp(val, "foreground", 10) == 0) {
74 ret = GetForegroundWindow();
75 ALLEGRO_INFO("Using foreground window: %p\n", ret);
76 }
77 else {
78 ret = GetDesktopWindow();
79 ALLEGRO_INFO("Using desktop window: %p\n", ret);
80 }
81 return ret;
82 }
83
84 static void dsound_set_buffer_size(int bits_per_sample)
85 {
86 int buffer_size_in_samples = 8192; // default
87 const char *val = al_get_config_value(al_get_system_config(),
88 "directsound", "buffer_size");
89 if (val && val[0] != '\0') {
90 int n = atoi(val);
91 if (n < MIN_BUFFER_SIZE)
92 n = MIN_BUFFER_SIZE;
93 buffer_size_in_samples = n;
94 }
95
96 buffer_size = buffer_size_in_samples * (bits_per_sample/8);
97 }
98
99 static char *ds_get_error(HRESULT hr)
100 {
101 switch (hr) {
102 case DSERR_ALLOCATED:
103 strcpy(ds_err_str, "DSERR_ALLOCATED");
104 break;
105 case DSERR_BADFORMAT:
106 strcpy(ds_err_str, "DSERR_BADFORMAT");
107 break;
108 case DSERR_BUFFERTOOSMALL:
109 strcpy(ds_err_str, "DSERR_BUFFERTOOSMALL");
110 break;
111 case DSERR_CONTROLUNAVAIL:
112 strcpy(ds_err_str, "DSERR_CONTROLUNAVAIL");
113 break;
114 case DSERR_DS8_REQUIRED:
115 strcpy(ds_err_str, "DSERR_DS8_REQUIRED");
116 break;
117 case DSERR_INVALIDCALL:
118 strcpy(ds_err_str, "DSERR_INVALIDCALL");
119 break;
120 case DSERR_INVALIDPARAM:
121 strcpy(ds_err_str, "DSERR_INVALIDPARAM");
122 break;
123 case DSERR_NOAGGREGATION:
124 strcpy(ds_err_str, "DSERR_NOAGGREGATION");
125 break;
126 case DSERR_NODRIVER:
127 strcpy(ds_err_str, "DSERR_NODRIVER");
128 break;
129 case DSERR_OUTOFMEMORY:
130 strcpy(ds_err_str, "DSERR_OUTOFMEMORY");
131 break;
132 case DSERR_UNINITIALIZED:
133 strcpy(ds_err_str, "DSERR_UNINITIALIZED");
134 break;
135 case DSERR_UNSUPPORTED:
136 strcpy(ds_err_str, "DSERR_UNSUPPORTED");
137 break;
138 }
139
140 return ds_err_str;
141 }
142
143
144 /* Custom struct to hold voice information DirectSound needs */
145 /* TODO: review */
146 struct ALLEGRO_DS_DATA {
147 int bits_per_sample;
148 int channels;
149 DSBUFFERDESC desc;
150 WAVEFORMATEX wave_fmt;
151 LPDIRECTSOUNDBUFFER ds_buffer;
152 LPDIRECTSOUNDBUFFER8 ds8_buffer;
153 int stop_voice;
154 ALLEGRO_THREAD *thread;
155 };
156
157
158 static bool _dsound_voice_is_playing(const ALLEGRO_VOICE *voice);
159
160
161 /* Custom routine which runs in another thread to periodically check if DirectSound
162 wants more data for a stream */
163 static void* _dsound_update(ALLEGRO_THREAD *self, void *arg)
164 {
165 ALLEGRO_VOICE *voice = (ALLEGRO_VOICE *)arg;
166 ALLEGRO_DS_DATA *ex_data = (ALLEGRO_DS_DATA*)voice->extra;
167 const int bytes_per_sample = ex_data->bits_per_sample / 8;
168 DWORD play_cursor = 0;
169 DWORD write_cursor;
170 DWORD saved_play_cursor = 0;
171 unsigned int samples;
172 LPVOID ptr1, ptr2;
173 DWORD block1_bytes, block2_bytes;
174 unsigned char *data;
175 unsigned char *silence;
176 HRESULT hr;
177 (void)self;
178
179 /* Make a buffer full of silence. */
180 silence = (unsigned char *)al_malloc(buffer_size);
181 samples = buffer_size / bytes_per_sample / ex_data->channels;
182 al_fill_silence(silence, samples, voice->depth, voice->chan_conf);
183
184 /* Fill buffer */
185 hr = ex_data->ds8_buffer->Lock(0, buffer_size,
186 &ptr1, &block1_bytes, &ptr2, &block2_bytes,
187 DSBLOCK_ENTIREBUFFER);
188 if (!FAILED(hr)) {
189 unsigned int sample_bytes;
190 samples = buffer_size / bytes_per_sample / ex_data->channels;
191 data = (unsigned char *) _al_voice_update(voice, voice->mutex, &samples);
192 sample_bytes = samples * bytes_per_sample * ex_data->channels;
193 if (sample_bytes < block1_bytes)
194 block1_bytes = sample_bytes;
195 memcpy(ptr1, data, block1_bytes);
196 sample_bytes -= block1_bytes;
197 if (sample_bytes < block2_bytes)
198 block2_bytes = sample_bytes;
199 memcpy(ptr2, data + block1_bytes, block2_bytes);
200 ex_data->ds8_buffer->Unlock(ptr1, block1_bytes, ptr2, block2_bytes);
201 }
202 else {
203 ALLEGRO_ERROR("Lock failed: %s\n", ds_get_error(hr));
204 }
205
206 ex_data->ds8_buffer->Play(0, 0, DSBPLAY_LOOPING);
207
208 do {
209 if (!_dsound_voice_is_playing(voice)) {
210 ex_data->ds8_buffer->Play(0, 0, DSBPLAY_LOOPING);
211 }
212
213 ex_data->ds8_buffer->GetCurrentPosition(&play_cursor, &write_cursor);
214
215 /* We try to fill the gap between the saved_play_cursor and the
216 * play_cursor.
217 */
218 int d = play_cursor - saved_play_cursor;
219 if (d < 0)
220 d += buffer_size;
221
222 /* Don't fill small gaps. Let it accumulate to amortise the cost of
223 * mixing the samples and locking/unlocking the buffer.
224 */
225 if (d < MIN_FILL) {
226 al_rest(0.005);
227 continue;
228 }
229
230 /* Don't generate too many samples at once. The buffer may underrun
231 * while we wait for _al_voice_update to complete.
232 */
233 samples = d / bytes_per_sample / ex_data->channels;
234 if (samples > MAX_FILL) {
235 samples = MAX_FILL;
236 }
237
238 /* Generate the samples. */
239 data = (unsigned char *) _al_voice_update(voice, voice->mutex, &samples);
240 if (data == NULL) {
241 data = silence;
242 }
243
244 hr = ex_data->ds8_buffer->Lock(saved_play_cursor,
245 samples * bytes_per_sample * ex_data->channels,
246 &ptr1, &block1_bytes, &ptr2, &block2_bytes, 0);
247 if (!FAILED(hr)) {
248 memcpy(ptr1, data, block1_bytes);
249 memcpy(ptr2, data + block1_bytes, block2_bytes);
250 hr = ex_data->ds8_buffer->Unlock(ptr1, block1_bytes,
251 ptr2, block2_bytes);
252 if (FAILED(hr)) {
253 ALLEGRO_ERROR("Unlock failed: %s\n", ds_get_error(hr));
254 }
255 }
256 else {
257 ALLEGRO_ERROR("Lock failed: %s\n", ds_get_error(hr));
258 }
259 saved_play_cursor += block1_bytes + block2_bytes;
260 saved_play_cursor %= buffer_size;
261 } while (!ex_data->stop_voice);
262
263 ex_data->ds8_buffer->Stop();
264
265 al_free(silence);
266
267 ex_data->stop_voice = 0;
268 al_broadcast_cond(voice->cond);
269
270 return NULL;
271 }
272
273
274 /* The open method starts up the driver and should lock the device, using the
275 previously set parameters, or defaults. It shouldn't need to start sending
276 audio data to the device yet, however. */
277 static int _dsound_open()
278 {
279 HRESULT hr;
280 ALLEGRO_INFO("Starting DirectSound...\n");
281
282 output_device_list = _al_list_create();
283 DirectSoundEnumerate((LPDSENUMCALLBACK)_ds_enum_callback, NULL);
284
285 /* FIXME: Use default device until we have device enumeration */
286
287 hr = DirectSoundCreate8(NULL, &device, NULL);
288 if (FAILED(hr)) {
289 ALLEGRO_ERROR("DirectSoundCreate8 failed: %s\n", ds_get_error(hr));
290 return 1;
291 }
292
293 ALLEGRO_DEBUG("DirectSoundCreate8 succeeded\n");
294
295 hr = device->SetCooperativeLevel(get_window(), DSSCL_PRIORITY);
296 if (FAILED(hr)) {
297 ALLEGRO_ERROR("SetCooperativeLevel failed: %s\n", ds_get_error(hr));
298 return 1;
299 }
300
301 return 0;
302 }
303
304
305 /* The close method should close the device, freeing any resources, and allow
306 other processes to use the device */
307 static void _dsound_close()
308 {
309 ALLEGRO_DEBUG("Releasing device\n");
310
311 _al_list_destroy(output_device_list);
312 device->Release();
313
314 ALLEGRO_DEBUG("Released device\n");
315 ALLEGRO_INFO("DirectSound closed\n");
316 }
317
318
319 /* The allocate_voice method should grab a voice from the system, and allocate
320 any data common to streaming and non-streaming sources. */
321 static int _dsound_allocate_voice(ALLEGRO_VOICE *voice)
322 {
323 ALLEGRO_DS_DATA *ex_data;
324 int bits_per_sample;
325 int channels;
326
327 ALLEGRO_DEBUG("Allocating voice\n");
328
329 /* openal doesn't support very much! */
330 switch (voice->depth)
331 {
332 case ALLEGRO_AUDIO_DEPTH_UINT8:
333 /* format supported */
334 bits_per_sample = 8;
335 break;
336 case ALLEGRO_AUDIO_DEPTH_INT8:
337 ALLEGRO_ERROR("DirectSound requires 8-bit data to be unsigned\n");
338 return 1;
339 case ALLEGRO_AUDIO_DEPTH_UINT16:
340 ALLEGRO_ERROR("DirectSound requires 16-bit data to be signed\n");
341 return 1;
342 case ALLEGRO_AUDIO_DEPTH_INT16:
343 /* format supported */
344 bits_per_sample = 16;
345 break;
346 case ALLEGRO_AUDIO_DEPTH_UINT24:
347 ALLEGRO_ERROR("DirectSound does not support 24-bit data\n");
348 return 1;
349 case ALLEGRO_AUDIO_DEPTH_INT24:
350 ALLEGRO_ERROR("DirectSound does not support 24-bit data\n");
351 return 1;
352 case ALLEGRO_AUDIO_DEPTH_FLOAT32:
353 ALLEGRO_ERROR("DirectSound does not support 32-bit floating data\n");
354 return 1;
355 default:
356 ALLEGRO_ERROR("Cannot allocate unknown voice depth\n");
357 return 1;
358 }
359
360 switch (voice->chan_conf) {
361 case ALLEGRO_CHANNEL_CONF_1:
362 channels = 1;
363 break;
364 case ALLEGRO_CHANNEL_CONF_2:
365 channels = 2;
366 break;
367 default:
368 ALLEGRO_ERROR("Unsupported number of channels\n");
369 return 1;
370 }
371
372 ex_data = (ALLEGRO_DS_DATA *)al_calloc(1, sizeof(*ex_data));
373 if (!ex_data) {
374 ALLEGRO_ERROR("Could not allocate voice data memory\n");
375 return 1;
376 }
377
378 ex_data->bits_per_sample = bits_per_sample;
379 ex_data->channels = channels;
380 ex_data->stop_voice = 1;
381
382 dsound_set_buffer_size(bits_per_sample);
383
384 voice->extra = ex_data;
385
386 ALLEGRO_DEBUG("Allocated voice\n");
387
388 return 0;
389 }
390
391 /* The deallocate_voice method should free the resources for the given voice,
392 but still retain a hold on the device. The voice should be stopped and
393 unloaded by the time this is called */
394 static void _dsound_deallocate_voice(ALLEGRO_VOICE *voice)
395 {
396 ALLEGRO_DEBUG("Deallocating voice\n");
397
398 al_free(voice->extra);
399 voice->extra = NULL;
400
401 ALLEGRO_DEBUG("Deallocated voice\n");
402 }
403
404 /* The load_voice method loads a sample into the driver's memory. The voice's
405 'streaming' field will be set to false for these voices, and it's
406 'buffer_size' field will be the total length in bytes of the sample data.
407 The voice's attached sample's looping mode should be honored, and loading
408 must fail if it cannot be. */
409 static int _dsound_load_voice(ALLEGRO_VOICE *voice, const void *_data)
410 {
411 ALLEGRO_DS_DATA *ex_data = (ALLEGRO_DS_DATA *)voice->extra;
412 HRESULT hr;
413 LPVOID ptr1, ptr2;
414 DWORD block1_bytes, block2_bytes;
415 MAKE_UNION(&ex_data->ds8_buffer, LPDIRECTSOUNDBUFFER8 *);
416
417 ALLEGRO_DEBUG("Loading voice\n");
418
419 ex_data->wave_fmt.wFormatTag = WAVE_FORMAT_PCM;
420 ex_data->wave_fmt.nChannels = ex_data->channels;
421 ex_data->wave_fmt.nSamplesPerSec = voice->frequency;
422 ex_data->wave_fmt.nBlockAlign = ex_data->channels * (ex_data->bits_per_sample/8);
423 ex_data->wave_fmt.nAvgBytesPerSec = ex_data->wave_fmt.nBlockAlign * voice->frequency;
424 ex_data->wave_fmt.wBitsPerSample = ex_data->bits_per_sample;
425 ex_data->wave_fmt.cbSize = 0;
426
427 ex_data->desc.dwSize = sizeof(DSBUFFERDESC);
428 ex_data->desc.dwFlags = DSBCAPS_LOCSOFTWARE | DSBCAPS_GLOBALFOCUS; /* FIXME: software mixing for now */
429 ex_data->desc.dwBufferBytes = voice->buffer_size;
430 ex_data->desc.dwReserved = 0;
431 ex_data->desc.lpwfxFormat = &ex_data->wave_fmt;
432 ex_data->desc.guid3DAlgorithm = DS3DALG_DEFAULT;
433
434 hr = device->CreateSoundBuffer(&ex_data->desc, &ex_data->ds_buffer, NULL);
435 if (FAILED(hr)) {
436 ALLEGRO_ERROR("CreateSoundBuffer failed: %s\n", ds_get_error(hr));
437 return 1;
438 }
439
440 ex_data->ds_buffer->QueryInterface(_al_IID_IDirectSoundBuffer8, u.v);
441
442 hr = ex_data->ds8_buffer->Lock(0, voice->buffer_size,
443 &ptr1, &block1_bytes, &ptr2, &block2_bytes, 0);
444 if (FAILED(hr)) {
445 ALLEGRO_ERROR("Locking buffer failed: %s\n", ds_get_error(hr));
446 return 1;
447 }
448
449 unsigned char *data = (unsigned char *) _data;
450 memcpy(ptr1, data, block1_bytes);
451 memcpy(ptr2, data + block1_bytes, block2_bytes);
452
453 ex_data->ds8_buffer->Unlock(ptr1, block1_bytes, ptr2, block2_bytes);
454
455 return 0;
456 }
457
458 /* The unload_voice method unloads a sample previously loaded with load_voice.
459 This method should not be called on a streaming voice. */
460 static void _dsound_unload_voice(ALLEGRO_VOICE *voice)
461 {
462 ALLEGRO_DS_DATA *ex_data = (ALLEGRO_DS_DATA *)voice->extra;
463
464 ALLEGRO_DEBUG("Unloading voice\n");
465
466 ex_data->ds8_buffer->Release();
467
468 ALLEGRO_DEBUG("Unloaded voice\n");
469 }
470
471
472 /* The start_voice should, surprise, start the voice. For streaming voices, it
473 should start polling the device and call _al_voice_update for audio data.
474 For non-streaming voices, it should resume playing from the last set
475 position */
476 static int _dsound_start_voice(ALLEGRO_VOICE *voice)
477 {
478 ALLEGRO_DS_DATA *ex_data = (ALLEGRO_DS_DATA *)voice->extra;
479 HRESULT hr;
480 MAKE_UNION(&ex_data->ds8_buffer, LPDIRECTSOUNDBUFFER8 *);
481
482 ALLEGRO_DEBUG("Starting voice\n");
483
484 if (!voice->is_streaming) {
485 hr = ex_data->ds8_buffer->Play(0, 0, 0);
486 if (FAILED(hr)) {
487 ALLEGRO_ERROR("Streaming voice failed to start: %s\n", ds_get_error(hr));
488 return 1;
489 }
490 ALLEGRO_INFO("Streaming voice started\n");
491 return 0;
492 }
493
494 if (ex_data->stop_voice != 0) {
495 ex_data->wave_fmt.wFormatTag = WAVE_FORMAT_PCM;
496 ex_data->wave_fmt.nChannels = ex_data->channels;
497 ex_data->wave_fmt.nSamplesPerSec = voice->frequency;
498 ex_data->wave_fmt.nBlockAlign = ex_data->channels * (ex_data->bits_per_sample/8);
499 ex_data->wave_fmt.nAvgBytesPerSec = ex_data->wave_fmt.nBlockAlign * voice->frequency;
500 ex_data->wave_fmt.wBitsPerSample = ex_data->bits_per_sample;
501 ex_data->wave_fmt.cbSize = 0;
502
503 ex_data->desc.dwSize = sizeof(DSBUFFERDESC);
504 ex_data->desc.dwFlags = DSBCAPS_LOCSOFTWARE | DSBCAPS_GLOBALFOCUS; /* FIXME: software mixing for now */
505 ex_data->desc.dwBufferBytes = buffer_size;
506 ex_data->desc.dwReserved = 0;
507 ex_data->desc.lpwfxFormat = &ex_data->wave_fmt;
508 ex_data->desc.guid3DAlgorithm = DS3DALG_DEFAULT;
509
510 ALLEGRO_DEBUG("CreateSoundBuffer\n");
511
512 hr = device->CreateSoundBuffer(&ex_data->desc, &ex_data->ds_buffer, NULL);
513 if (FAILED(hr)) {
514 ALLEGRO_ERROR("CreateSoundBuffer failed: %s\n", ds_get_error(hr));
515 return 1;
516 }
517
518 ALLEGRO_DEBUG("CreateSoundBuffer succeeded\n");
519
520 ex_data->ds_buffer->QueryInterface(_al_IID_IDirectSoundBuffer8, u.v);
521
522 ex_data->ds8_buffer->SetVolume(DSBVOLUME_MAX);
523
524 ALLEGRO_DEBUG("Starting _dsound_update thread\n");
525
526 ex_data->stop_voice = 0;
527 ex_data->thread = al_create_thread(_dsound_update, (void*) voice);
528 al_start_thread(ex_data->thread);
529 }
530 else {
531 ALLEGRO_WARN("stop_voice == 0\n");
532 }
533
534 ALLEGRO_INFO("Voice started\n");
535 return 0;
536 }
537
538 /* The stop_voice method should stop playback. For non-streaming voices, it
539 should leave the data loaded, and reset the voice position to 0. */
540 static int _dsound_stop_voice(ALLEGRO_VOICE* voice)
541 {
542 ALLEGRO_DS_DATA *ex_data = (ALLEGRO_DS_DATA *)voice->extra;
543
544 ALLEGRO_DEBUG("Stopping voice\n");
545
546 if (!ex_data->ds8_buffer) {
547 ALLEGRO_ERROR("Trying to stop empty voice buffer\n");
548 return 1;
549 }
550
551 /* if playing a sample */
552 if (!voice->is_streaming) {
553 ALLEGRO_DEBUG("Stopping non-streaming voice\n");
554 ex_data->ds8_buffer->Stop();
555 ex_data->ds8_buffer->SetCurrentPosition(0);
556 ALLEGRO_INFO("Non-streaming voice stopped\n");
557 return 0;
558 }
559
560 if (ex_data->stop_voice == 0) {
561 ALLEGRO_DEBUG("Joining thread\n");
562 ex_data->stop_voice = 1;
563 while (ex_data->stop_voice == 1) {
564 al_wait_cond(voice->cond, voice->mutex);
565 }
566 al_join_thread(ex_data->thread, NULL);
567 ALLEGRO_DEBUG("Joined thread\n");
568
569 ALLEGRO_DEBUG("Destroying thread\n");
570 al_destroy_thread(ex_data->thread);
571 ALLEGRO_DEBUG("Thread destroyed\n");
572 /* This is required to restart the background thread when the voice
573 * restarts.
574 */
575 ex_data->stop_voice = 1;
576 }
577
578 ALLEGRO_DEBUG("Releasing buffer\n");
579 ex_data->ds8_buffer->Release();
580 ex_data->ds8_buffer = NULL;
581
582 ALLEGRO_INFO("Voice stopped\n");
583 return 0;
584 }
585
586 /* The voice_is_playing method should only be called on non-streaming sources,
587 and should return true if the voice is playing */
588 static bool _dsound_voice_is_playing(const ALLEGRO_VOICE *voice)
589 {
590 ALLEGRO_DS_DATA *ex_data = (ALLEGRO_DS_DATA *)voice->extra;
591 DWORD status;
592
593 if (!ex_data) {
594 ALLEGRO_WARN("ex_data is null\n");
595 return false;
596 }
597
598 ex_data->ds8_buffer->GetStatus(&status);
599
600 return (status & DSBSTATUS_PLAYING);
601 }
602
603 /* The get_voice_position method should return the current sample position of
604 the voice (sample_pos = byte_pos / (depth/8) / channels). This should never
605 be called on a streaming voice. */
606 static unsigned int _dsound_get_voice_position(const ALLEGRO_VOICE *voice)
607 {
608 ALLEGRO_DS_DATA *ex_data = (ALLEGRO_DS_DATA *)voice->extra;
609 DWORD play_pos;
610 HRESULT hr;
611
612 hr = ex_data->ds8_buffer->GetCurrentPosition(&play_pos, NULL);
613 if (FAILED(hr)) {
614 ALLEGRO_ERROR("GetCurrentPosition failed: %s\n", ds_get_error(hr));
615 return 0;
616 }
617
618 return play_pos / (ex_data->channels * (ex_data->bits_per_sample/8));
619 }
620
621 /* The set_voice_position method should set the voice's playback position,
622 given the value in samples. This should never be called on a streaming
623 voice. */
624 static int _dsound_set_voice_position(ALLEGRO_VOICE *voice, unsigned int val)
625 {
626 ALLEGRO_DS_DATA *ex_data = (ALLEGRO_DS_DATA *)voice->extra;
627 HRESULT hr;
628
629 val *= ex_data->channels * (ex_data->bits_per_sample/8);
630
631 hr = ex_data->ds8_buffer->SetCurrentPosition(val);
632 if (FAILED(hr)) {
633 ALLEGRO_ERROR("SetCurrentPosition failed: %s\n", ds_get_error(hr));
634 return 1;
635 }
636
637 return 0;
638 }
639
640 struct DSOUND_RECORD_DATA {
641 LPDIRECTSOUNDCAPTUREBUFFER buffer;
642 LPDIRECTSOUNDCAPTUREBUFFER8 buffer8;
643 DSCBUFFERDESC desc;
644 WAVEFORMATEX wave_fmt;
645 };
646
647 static void *_dsound_update_recorder(ALLEGRO_THREAD *t, void *data)
648 {
649 ALLEGRO_AUDIO_RECORDER *r = (ALLEGRO_AUDIO_RECORDER *) data;
650 DSOUND_RECORD_DATA *extra = (DSOUND_RECORD_DATA *) r->extra;
651 DWORD last_read_pos = 0;
652 ALLEGRO_EVENT user_event;
653 bool is_dsound_recording = false;
654
655 size_t fragment_i = 0;
656 size_t bytes_written = 0;
657
658 ALLEGRO_INFO("Starting recorder thread\n");
659
660 while (!al_get_thread_should_stop(t)) {
661 al_lock_mutex(r->mutex);
662 while (!r->is_recording) {
663 if (is_dsound_recording) {
664 extra->buffer8->Stop();
665 is_dsound_recording = false;
666 }
667 al_wait_cond(r->cond, r->mutex);
668 if (al_get_thread_should_stop(t))
669 goto stop_recording;
670 }
671
672 if (!is_dsound_recording) {
673 extra->buffer8->Start(DSCBSTART_LOOPING);
674 is_dsound_recording = true;
675 extra->buffer8->GetCurrentPosition(NULL, &last_read_pos);
676 }
677
678 void *buffer1, *buffer2;
679 DWORD buffer1_size, buffer2_size;
680 DWORD cap_pos, bytes_to_read;
681
682 extra->buffer8->GetCurrentPosition(NULL, &cap_pos);
683
684 /* never read past the end of the buffer; that way buffer2 is always NULL */
685 if (last_read_pos <= cap_pos)
686 bytes_to_read = cap_pos - last_read_pos;
687 else
688 bytes_to_read = extra->desc.dwBufferBytes - last_read_pos;
689
690 if (bytes_to_read) {
691 uint8_t *buffer;
692 size_t buffer_size;
693
694 extra->buffer8->Lock(last_read_pos, bytes_to_read, &buffer1, &buffer1_size, &buffer2, &buffer2_size, 0);
695
696 ALLEGRO_ASSERT(buffer2 == NULL);
697
698 buffer = (uint8_t *)buffer1;
699 buffer_size = buffer1_size;
700
701 while (buffer_size > 0) {
702 if (bytes_written + buffer_size <= r->fragment_size) {
703 memcpy((uint8_t*) r->fragments[fragment_i] + bytes_written, buffer, buffer_size);
704 bytes_written += buffer_size;
705 buffer_size = 0;
706 }
707 else {
708 ALLEGRO_AUDIO_RECORDER_EVENT *e;
709 size_t bytes_to_write = r->fragment_size - bytes_written;
710 memcpy((uint8_t*) r->fragments[fragment_i] + bytes_written, buffer, bytes_to_write);
711
712 buffer_size -= bytes_to_write;
713 buffer += bytes_to_write;
714
715 user_event.user.type = ALLEGRO_EVENT_AUDIO_RECORDER_FRAGMENT;
716 e = al_get_audio_recorder_event(&user_event);
717 e->buffer = r->fragments[fragment_i];
718 e->samples = r->samples;
719 al_emit_user_event(&r->source, &user_event, NULL);
720
721 /* advance to the next fragment */
722 if (++fragment_i == r->fragment_count) {
723 fragment_i = 0;
724 }
725 bytes_written = 0;
726 }
727 }
728
729 extra->buffer8->Unlock(buffer1, buffer1_size, buffer2, buffer2_size);
730
731 /* advanced the last read position */
732 last_read_pos += bytes_to_read;
733 if (last_read_pos >= extra->desc.dwBufferBytes)
734 last_read_pos -= extra->desc.dwBufferBytes;
735 }
736
737 al_unlock_mutex(r->mutex);
738 al_rest(0.10);
739 }
740
741 stop_recording:
742
743 if (is_dsound_recording) {
744 extra->buffer8->Stop();
745 }
746
747 ALLEGRO_INFO("Leaving recorder thread\n");
748
749 return NULL;
750 }
751
752 static int _dsound_open_recorder(ALLEGRO_AUDIO_RECORDER *r)
753 {
754 HRESULT hr;
755
756 if (capture_device != NULL) {
757 /* FIXME: It's wrong to assume only a single recording device, but since
758 there is no enumeration of devices, it doesn't matter for now. */
759 ALLEGRO_ERROR("Already recording.\n");
760 return 1;
761 }
762
763 ALLEGRO_INFO("Creating default capture device.\n");
764
765 /* FIXME: Use default device until we have device enumeration */
766 hr = DirectSoundCaptureCreate8(NULL, &capture_device, NULL);
767 if (FAILED(hr)) {
768 ALLEGRO_ERROR("DirectSoundCaptureCreate8 failed: %s\n", ds_get_error(hr));
769 return 1;
770 }
771
772 hr = device->SetCooperativeLevel(get_window(), DSSCL_PRIORITY);
773 if (FAILED(hr)) {
774 ALLEGRO_ERROR("SetCooperativeLevel failed: %s\n", ds_get_error(hr));
775 return 1;
776 }
777
778 DSOUND_RECORD_DATA *extra = (DSOUND_RECORD_DATA *) al_calloc(1, sizeof(*extra));
779
780 DSCCAPS dsccaps;
781 dsccaps.dwSize = sizeof(DSCCAPS);
782 hr = capture_device->GetCaps(&dsccaps);
783 if (FAILED(hr)) {
784 ALLEGRO_ERROR("DirectSoundCaptureCreate8::GetCaps failed: %s\n", ds_get_error(hr));
785 }
786 else {
787 ALLEGRO_INFO("caps: %lu %lu\n", dsccaps.dwFormats, dsccaps.dwFormats & WAVE_FORMAT_2M16);
788 }
789
790 memset(&extra->wave_fmt, 0, sizeof(extra->wave_fmt));
791 extra->wave_fmt.wFormatTag = WAVE_FORMAT_PCM;
792 extra->wave_fmt.nChannels = (WORD)al_get_channel_count(r->chan_conf);
793 extra->wave_fmt.nSamplesPerSec = r->frequency;
794 extra->wave_fmt.wBitsPerSample = (WORD)al_get_audio_depth_size(r->depth) * 8;
795 extra->wave_fmt.nBlockAlign = extra->wave_fmt.nChannels * extra->wave_fmt.wBitsPerSample / 8;
796 extra->wave_fmt.nAvgBytesPerSec = extra->wave_fmt.nSamplesPerSec * extra->wave_fmt.nBlockAlign;
797
798 memset(&extra->desc, 0, sizeof(extra->desc));
799 extra->desc.dwSize = sizeof(extra->desc);
800 extra->desc.lpwfxFormat = &extra->wave_fmt;
801 extra->desc.dwBufferBytes = extra->wave_fmt.nAvgBytesPerSec * 5;
802
803 hr = capture_device->CreateCaptureBuffer(&extra->desc, &extra->buffer, NULL);
804 if (FAILED(hr)) {
805 al_free(extra);
806 ALLEGRO_ERROR("Unable to create Capture Buffer\n");
807 return 1;
808 }
809
810 extra->buffer->QueryInterface(_al_IID_IDirectSoundCaptureBuffer8, (void **) &extra->buffer8);
811
812 r->extra = extra;
813 r->thread = al_create_thread(_dsound_update_recorder, r);
814
815 return 0;
816 }
817
818 void _dsound_close_recorder(ALLEGRO_AUDIO_RECORDER *r) {
819 ALLEGRO_ASSERT(capture_device);
820 (void) r;
821
822 capture_device->Release();
823 capture_device = NULL;
824 }
825
826 static void _output_device_list_dtor(void* value, void* userdata)
827 {
828 (void)userdata;
829
830 ALLEGRO_AUDIO_DEVICE* device = (ALLEGRO_AUDIO_DEVICE*)value;
831 al_free(device->name);
832 al_free(device->identifier);
833 al_free(device);
834 }
835
836 static BOOL CALLBACK _ds_enum_callback(
837 LPGUID lpGuid,
838 LPCTSTR lpcstrDescription,
839 LPCTSTR lpcstrModule,
840 LPVOID lpContext)
841 {
842 (void)lpcstrModule;
843 (void)lpContext;
844
845 if (lpGuid != NULL) {
846 ALLEGRO_AUDIO_DEVICE* device = (ALLEGRO_AUDIO_DEVICE*)al_malloc(sizeof(ALLEGRO_AUDIO_DEVICE));
847 device->identifier = (void*)al_malloc(sizeof(GUID));
848 device->name = _twin_tchar_to_utf8(lpcstrDescription);
849
850 memcpy(device->identifier, lpGuid, sizeof(GUID));
851
852 _al_list_push_back_ex(output_device_list, device, _output_device_list_dtor);
853 }
854
855 return TRUE;
856 }
857
858 static _AL_LIST* _dsound_get_output_devices(void)
859 {
860 return output_device_list;
861 }
862
863 ALLEGRO_AUDIO_DRIVER _al_kcm_dsound_driver = {
864 "DirectSound",
865
866 _dsound_open,
867 _dsound_close,
868
869 _dsound_allocate_voice,
870 _dsound_deallocate_voice,
871
872 _dsound_load_voice,
873 _dsound_unload_voice,
874
875 _dsound_start_voice,
876 _dsound_stop_voice,
877
878 _dsound_voice_is_playing,
879
880 _dsound_get_voice_position,
881 _dsound_set_voice_position,
882
883 _dsound_open_recorder,
884 _dsound_close_recorder,
885
886 _dsound_get_output_devices,
887 };
888
889 } /* End extern "C" */
890