2 * QEMU DirectSound audio driver
4 * Copyright (c) 2005 Vassili Karpov (malc)
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26 * SEAL 1.07 by Carlos 'pel' Hasan was used as documentation
29 #include "qemu-common.h"
32 #define AUDIO_CAP "dsound"
33 #include "audio_int.h"
35 #define WIN32_LEAN_AND_MEAN
41 /* #define DEBUG_DSOUND */
46 int getstatus_retries;
50 audsettings_t settings;
69 LPDIRECTSOUNDCAPTURE dsound_capture;
70 LPDIRECTSOUNDBUFFER dsound_primary_buffer;
71 audsettings_t settings;
74 static dsound glob_dsound;
78 LPDIRECTSOUNDBUFFER dsound_buffer;
91 LPDIRECTSOUNDCAPTUREBUFFER dsound_capture_buffer;
94 static void dsound_log_hresult (HRESULT hr)
96 const char *str = "BUG";
100 str = "The method succeeded";
102 #ifdef DS_NO_VIRTUALIZATION
103 case DS_NO_VIRTUALIZATION:
104 str = "The buffer was created, but another 3D algorithm was substituted";
109 str = "The method succeeded, but not all the optional effects were obtained";
112 #ifdef DSERR_ACCESSDENIED
113 case DSERR_ACCESSDENIED:
114 str = "The request failed because access was denied";
117 #ifdef DSERR_ALLOCATED
118 case DSERR_ALLOCATED:
119 str = "The request failed because resources, such as a priority level, were already in use by another caller";
122 #ifdef DSERR_ALREADYINITIALIZED
123 case DSERR_ALREADYINITIALIZED:
124 str = "The object is already initialized";
127 #ifdef DSERR_BADFORMAT
128 case DSERR_BADFORMAT:
129 str = "The specified wave format is not supported";
132 #ifdef DSERR_BADSENDBUFFERGUID
133 case DSERR_BADSENDBUFFERGUID:
134 str = "The GUID specified in an audiopath file does not match a valid mix-in buffer";
137 #ifdef DSERR_BUFFERLOST
138 case DSERR_BUFFERLOST:
139 str = "The buffer memory has been lost and must be restored";
142 #ifdef DSERR_BUFFERTOOSMALL
143 case DSERR_BUFFERTOOSMALL:
144 str = "The buffer size is not great enough to enable effects processing";
147 #ifdef DSERR_CONTROLUNAVAIL
148 case DSERR_CONTROLUNAVAIL:
149 str = "The buffer control (volume, pan, and so on) requested by the caller is not available. Controls must be specified when the buffer is created, using the dwFlags member of DSBUFFERDESC";
152 #ifdef DSERR_DS8_REQUIRED
153 case DSERR_DS8_REQUIRED:
154 str = "A DirectSound object of class CLSID_DirectSound8 or later is required for the requested functionality. For more information, see IDirectSound8 Interface";
157 #ifdef DSERR_FXUNAVAILABLE
158 case DSERR_FXUNAVAILABLE:
159 str = "The effects requested could not be found on the system, or they are in the wrong order or in the wrong location; for example, an effect expected in hardware was found in software";
164 str = "An undetermined error occurred inside the DirectSound subsystem";
167 #ifdef DSERR_INVALIDCALL
168 case DSERR_INVALIDCALL:
169 str = "This function is not valid for the current state of this object";
172 #ifdef DSERR_INVALIDPARAM
173 case DSERR_INVALIDPARAM:
174 str = "An invalid parameter was passed to the returning function";
177 #ifdef DSERR_NOAGGREGATION
178 case DSERR_NOAGGREGATION:
179 str = "The object does not support aggregation";
182 #ifdef DSERR_NODRIVER
184 str = "No sound driver is available for use, or the given GUID is not a valid DirectSound device ID";
187 #ifdef DSERR_NOINTERFACE
188 case DSERR_NOINTERFACE:
189 str = "The requested COM interface is not available";
192 #ifdef DSERR_OBJECTNOTFOUND
193 case DSERR_OBJECTNOTFOUND:
194 str = "The requested object was not found";
197 #ifdef DSERR_OTHERAPPHASPRIO
198 case DSERR_OTHERAPPHASPRIO:
199 str = "Another application has a higher priority level, preventing this call from succeeding";
202 #ifdef DSERR_OUTOFMEMORY
203 case DSERR_OUTOFMEMORY:
204 str = "The DirectSound subsystem could not allocate sufficient memory to complete the caller's request";
207 #ifdef DSERR_PRIOLEVELNEEDED
208 case DSERR_PRIOLEVELNEEDED:
209 str = "A cooperative level of DSSCL_PRIORITY or higher is required";
212 #ifdef DSERR_SENDLOOP
214 str = "A circular loop of send effects was detected";
217 #ifdef DSERR_UNINITIALIZED
218 case DSERR_UNINITIALIZED:
219 str = "The Initialize method has not been called or has not been called successfully before other methods were called";
222 #ifdef DSERR_UNSUPPORTED
223 case DSERR_UNSUPPORTED:
224 str = "The function called is not supported at this time";
228 AUD_log (AUDIO_CAP, "Reason: Unknown (HRESULT %#lx)\n", hr);
232 AUD_log (AUDIO_CAP, "Reason: %s\n", str);
235 static void GCC_FMT_ATTR (2, 3) dsound_logerr (
244 AUD_vlog (AUDIO_CAP, fmt, ap);
247 dsound_log_hresult (hr);
250 static void GCC_FMT_ATTR (3, 4) dsound_logerr2 (
259 AUD_log (AUDIO_CAP, "Could not initialize %s\n", typ);
261 AUD_vlog (AUDIO_CAP, fmt, ap);
264 dsound_log_hresult (hr);
267 static DWORD millis_to_bytes (struct audio_pcm_info *info, DWORD millis)
269 return (millis * info->bytes_per_second) / 1000;
273 static void print_wave_format (WAVEFORMATEX *wfx)
275 dolog ("tag = %d\n", wfx->wFormatTag);
276 dolog ("nChannels = %d\n", wfx->nChannels);
277 dolog ("nSamplesPerSec = %ld\n", wfx->nSamplesPerSec);
278 dolog ("nAvgBytesPerSec = %ld\n", wfx->nAvgBytesPerSec);
279 dolog ("nBlockAlign = %d\n", wfx->nBlockAlign);
280 dolog ("wBitsPerSample = %d\n", wfx->wBitsPerSample);
281 dolog ("cbSize = %d\n", wfx->cbSize);
285 static int dsound_restore_out (LPDIRECTSOUNDBUFFER dsb)
290 for (i = 0; i < conf.restore_retries; ++i) {
291 hr = IDirectSoundBuffer_Restore (dsb);
297 case DSERR_BUFFERLOST:
301 dsound_logerr (hr, "Could not restore playback buffer\n");
306 dolog ("%d attempts to restore playback buffer failed\n", i);
310 static int waveformat_from_audio_settings (WAVEFORMATEX *wfx, audsettings_t *as)
312 memset (wfx, 0, sizeof (*wfx));
314 wfx->wFormatTag = WAVE_FORMAT_PCM;
315 wfx->nChannels = as->nchannels;
316 wfx->nSamplesPerSec = as->freq;
317 wfx->nAvgBytesPerSec = as->freq << (as->nchannels == 2);
318 wfx->nBlockAlign = 1 << (as->nchannels == 2);
324 wfx->wBitsPerSample = 8;
329 wfx->wBitsPerSample = 16;
330 wfx->nAvgBytesPerSec <<= 1;
331 wfx->nBlockAlign <<= 1;
336 wfx->wBitsPerSample = 32;
337 wfx->nAvgBytesPerSec <<= 2;
338 wfx->nBlockAlign <<= 2;
342 dolog ("Internal logic error: Bad audio format %d\n", as->freq);
349 static int waveformat_to_audio_settings (WAVEFORMATEX *wfx, audsettings_t *as)
351 if (wfx->wFormatTag != WAVE_FORMAT_PCM) {
352 dolog ("Invalid wave format, tag is not PCM, but %d\n",
357 if (!wfx->nSamplesPerSec) {
358 dolog ("Invalid wave format, frequency is zero\n");
361 as->freq = wfx->nSamplesPerSec;
363 switch (wfx->nChannels) {
374 "Invalid wave format, number of channels is not 1 or 2, but %d\n",
380 switch (wfx->wBitsPerSample) {
382 as->fmt = AUD_FMT_U8;
386 as->fmt = AUD_FMT_S16;
390 as->fmt = AUD_FMT_S32;
394 dolog ("Invalid wave format, bits per sample is not "
395 "8, 16 or 32, but %d\n",
396 wfx->wBitsPerSample);
403 #include "dsound_template.h"
405 #include "dsound_template.h"
408 static int dsound_get_status_out (LPDIRECTSOUNDBUFFER dsb, DWORD *statusp)
413 for (i = 0; i < conf.getstatus_retries; ++i) {
414 hr = IDirectSoundBuffer_GetStatus (dsb, statusp);
416 dsound_logerr (hr, "Could not get playback buffer status\n");
420 if (*statusp & DSERR_BUFFERLOST) {
421 if (dsound_restore_out (dsb)) {
432 static int dsound_get_status_in (LPDIRECTSOUNDCAPTUREBUFFER dscb,
437 hr = IDirectSoundCaptureBuffer_GetStatus (dscb, statusp);
439 dsound_logerr (hr, "Could not get capture buffer status\n");
446 static void dsound_write_sample (HWVoiceOut *hw, uint8_t *dst, int dst_len)
448 int src_len1 = dst_len;
450 int pos = hw->rpos + dst_len;
451 st_sample_t *src1 = hw->mix_buf + hw->rpos;
452 st_sample_t *src2 = NULL;
454 if (pos > hw->samples) {
455 src_len1 = hw->samples - hw->rpos;
457 src_len2 = dst_len - src_len1;
462 hw->clip (dst, src1, src_len1);
466 dst = advance (dst, src_len1 << hw->info.shift);
467 hw->clip (dst, src2, src_len2);
470 hw->rpos = pos % hw->samples;
473 static void dsound_clear_sample (HWVoiceOut *hw, LPDIRECTSOUNDBUFFER dsb)
477 DWORD blen1, blen2, len1, len2;
479 err = dsound_lock_out (
483 hw->samples << hw->info.shift,
492 len1 = blen1 >> hw->info.shift;
493 len2 = blen2 >> hw->info.shift;
496 dolog ("clear %p,%ld,%ld %p,%ld,%ld\n",
502 audio_pcm_info_clear_buf (&hw->info, p1, len1);
506 audio_pcm_info_clear_buf (&hw->info, p2, len2);
509 dsound_unlock_out (dsb, p1, p2, blen1, blen2);
512 static void dsound_close (dsound *s)
516 if (s->dsound_primary_buffer) {
517 hr = IDirectSoundBuffer_Release (s->dsound_primary_buffer);
519 dsound_logerr (hr, "Could not release primary buffer\n");
521 s->dsound_primary_buffer = NULL;
525 static int dsound_open (dsound *s)
533 hwnd = GetForegroundWindow ();
534 hr = IDirectSound_SetCooperativeLevel (
541 dsound_logerr (hr, "Could not set cooperative level for window %p\n",
546 if (!conf.set_primary) {
550 err = waveformat_from_audio_settings (&wfx, &conf.settings);
555 memset (&dsbd, 0, sizeof (dsbd));
556 dsbd.dwSize = sizeof (dsbd);
557 dsbd.dwFlags = DSBCAPS_PRIMARYBUFFER;
558 dsbd.dwBufferBytes = 0;
559 dsbd.lpwfxFormat = NULL;
561 hr = IDirectSound_CreateSoundBuffer (
564 &s->dsound_primary_buffer,
568 dsound_logerr (hr, "Could not create primary playback buffer\n");
572 hr = IDirectSoundBuffer_SetFormat (s->dsound_primary_buffer, &wfx);
574 dsound_logerr (hr, "Could not set primary playback buffer format\n");
577 hr = IDirectSoundBuffer_GetFormat (
578 s->dsound_primary_buffer,
584 dsound_logerr (hr, "Could not get primary playback buffer format\n");
590 print_wave_format (&wfx);
593 err = waveformat_to_audio_settings (&wfx, &s->settings);
605 static int dsound_ctl_out (HWVoiceOut *hw, int cmd, ...)
609 DSoundVoiceOut *ds = (DSoundVoiceOut *) hw;
610 LPDIRECTSOUNDBUFFER dsb = ds->dsound_buffer;
613 dolog ("Attempt to control voice without a buffer\n");
619 if (dsound_get_status_out (dsb, &status)) {
623 if (status & DSBSTATUS_PLAYING) {
624 dolog ("warning: Voice is already playing\n");
628 dsound_clear_sample (hw, dsb);
630 hr = IDirectSoundBuffer_Play (dsb, 0, 0, DSBPLAY_LOOPING);
632 dsound_logerr (hr, "Could not start playing buffer\n");
638 if (dsound_get_status_out (dsb, &status)) {
642 if (status & DSBSTATUS_PLAYING) {
643 hr = IDirectSoundBuffer_Stop (dsb);
645 dsound_logerr (hr, "Could not stop playing buffer\n");
650 dolog ("warning: Voice is not playing\n");
657 static int dsound_write (SWVoiceOut *sw, void *buf, int len)
659 return audio_pcm_sw_write (sw, buf, len);
662 static int dsound_run_out (HWVoiceOut *hw)
666 DSoundVoiceOut *ds = (DSoundVoiceOut *) hw;
667 LPDIRECTSOUNDBUFFER dsb = ds->dsound_buffer;
668 int live, len, hwshift;
672 DWORD wpos, ppos, old_pos;
677 dolog ("Attempt to run empty with playback buffer\n");
681 hwshift = hw->info.shift;
682 bufsize = hw->samples << hwshift;
684 live = audio_pcm_hw_get_live_out (hw);
686 hr = IDirectSoundBuffer_GetCurrentPosition (
689 ds->first_time ? &wpos : NULL
692 dsound_logerr (hr, "Could not get playback buffer position\n");
696 len = live << hwshift;
698 if (ds->first_time) {
699 if (conf.latency_millis) {
702 cur_blat = audio_ring_dist (wpos, ppos, bufsize);
706 millis_to_bytes (&hw->info, conf.latency_millis) - cur_blat;
708 old_pos &= ~hw->info.align;
719 if (ds->old_pos == ppos) {
721 dolog ("old_pos == ppos\n");
727 ds->played += audio_ring_dist (ds->old_pos, ppos, hw->bufsize);
729 old_pos = ds->old_pos;
732 if ((old_pos < ppos) && ((old_pos + len) > ppos)) {
733 len = ppos - old_pos;
736 if ((old_pos > ppos) && ((old_pos + len) > (ppos + bufsize))) {
737 len = bufsize - old_pos + ppos;
741 if (audio_bug (AUDIO_FUNC, len < 0 || len > bufsize)) {
742 dolog ("len=%d bufsize=%d old_pos=%ld ppos=%ld\n",
743 len, bufsize, old_pos, ppos);
747 len &= ~hw->info.align;
755 err = dsound_lock_out (
768 len1 = blen1 >> hwshift;
769 len2 = blen2 >> hwshift;
773 dsound_write_sample (hw, p1, len1);
777 dsound_write_sample (hw, p2, len2);
780 dsound_unlock_out (dsb, p1, p2, blen1, blen2);
781 ds->old_pos = (old_pos + (decr << hwshift)) % bufsize;
784 ds->mixed += decr << hwshift;
786 dolog ("played %lu mixed %lu diff %ld sec %f\n",
789 ds->mixed - ds->played,
790 abs (ds->mixed - ds->played) / (double) hw->info.bytes_per_second);
795 static int dsound_ctl_in (HWVoiceIn *hw, int cmd, ...)
799 DSoundVoiceIn *ds = (DSoundVoiceIn *) hw;
800 LPDIRECTSOUNDCAPTUREBUFFER dscb = ds->dsound_capture_buffer;
803 dolog ("Attempt to control capture voice without a buffer\n");
809 if (dsound_get_status_in (dscb, &status)) {
813 if (status & DSCBSTATUS_CAPTURING) {
814 dolog ("warning: Voice is already capturing\n");
820 hr = IDirectSoundCaptureBuffer_Start (dscb, DSCBSTART_LOOPING);
822 dsound_logerr (hr, "Could not start capturing\n");
828 if (dsound_get_status_in (dscb, &status)) {
832 if (status & DSCBSTATUS_CAPTURING) {
833 hr = IDirectSoundCaptureBuffer_Stop (dscb);
835 dsound_logerr (hr, "Could not stop capturing\n");
840 dolog ("warning: Voice is not capturing\n");
847 static int dsound_read (SWVoiceIn *sw, void *buf, int len)
849 return audio_pcm_sw_read (sw, buf, len);
852 static int dsound_run_in (HWVoiceIn *hw)
856 DSoundVoiceIn *ds = (DSoundVoiceIn *) hw;
857 LPDIRECTSOUNDCAPTUREBUFFER dscb = ds->dsound_capture_buffer;
867 dolog ("Attempt to run without capture buffer\n");
871 hwshift = hw->info.shift;
873 live = audio_pcm_hw_get_live_in (hw);
874 dead = hw->samples - live;
879 hr = IDirectSoundCaptureBuffer_GetCurrentPosition (
882 ds->first_time ? &rpos : NULL
885 dsound_logerr (hr, "Could not get capture buffer position\n");
889 if (ds->first_time) {
891 if (rpos & hw->info.align) {
892 ldebug ("warning: Misaligned capture read position %ld(%d)\n",
893 rpos, hw->info.align);
895 hw->wpos = rpos >> hwshift;
898 if (cpos & hw->info.align) {
899 ldebug ("warning: Misaligned capture position %ld(%d)\n",
900 cpos, hw->info.align);
904 len = audio_ring_dist (cpos, hw->wpos, hw->samples);
908 len = audio_MIN (len, dead);
910 err = dsound_lock_in (
925 len1 = blen1 >> hwshift;
926 len2 = blen2 >> hwshift;
930 hw->conv (hw->conv_buf + hw->wpos, p1, len1, &nominal_volume);
934 hw->conv (hw->conv_buf, p2, len2, &nominal_volume);
937 dsound_unlock_in (dscb, p1, p2, blen1, blen2);
938 hw->wpos = (hw->wpos + decr) % hw->samples;
942 static void dsound_audio_fini (void *opaque)
951 hr = IDirectSound_Release (s->dsound);
953 dsound_logerr (hr, "Could not release DirectSound\n");
957 if (!s->dsound_capture) {
961 hr = IDirectSoundCapture_Release (s->dsound_capture);
963 dsound_logerr (hr, "Could not release DirectSoundCapture\n");
965 s->dsound_capture = NULL;
968 static void *dsound_audio_init (void)
972 dsound *s = &glob_dsound;
974 hr = CoInitialize (NULL);
976 dsound_logerr (hr, "Could not initialize COM\n");
980 hr = CoCreateInstance (
988 dsound_logerr (hr, "Could not create DirectSound instance\n");
992 hr = IDirectSound_Initialize (s->dsound, NULL);
994 dsound_logerr (hr, "Could not initialize DirectSound\n");
996 hr = IDirectSound_Release (s->dsound);
998 dsound_logerr (hr, "Could not release DirectSound\n");
1004 hr = CoCreateInstance (
1005 &CLSID_DirectSoundCapture,
1008 &IID_IDirectSoundCapture,
1009 (void **) &s->dsound_capture
1012 dsound_logerr (hr, "Could not create DirectSoundCapture instance\n");
1015 hr = IDirectSoundCapture_Initialize (s->dsound_capture, NULL);
1017 dsound_logerr (hr, "Could not initialize DirectSoundCapture\n");
1019 hr = IDirectSoundCapture_Release (s->dsound_capture);
1021 dsound_logerr (hr, "Could not release DirectSoundCapture\n");
1023 s->dsound_capture = NULL;
1027 err = dsound_open (s);
1029 dsound_audio_fini (s);
1036 static struct audio_option dsound_options[] = {
1037 {"LOCK_RETRIES", AUD_OPT_INT, &conf.lock_retries,
1038 "Number of times to attempt locking the buffer", NULL, 0},
1039 {"RESTOURE_RETRIES", AUD_OPT_INT, &conf.restore_retries,
1040 "Number of times to attempt restoring the buffer", NULL, 0},
1041 {"GETSTATUS_RETRIES", AUD_OPT_INT, &conf.getstatus_retries,
1042 "Number of times to attempt getting status of the buffer", NULL, 0},
1043 {"SET_PRIMARY", AUD_OPT_BOOL, &conf.set_primary,
1044 "Set the parameters of primary buffer", NULL, 0},
1045 {"LATENCY_MILLIS", AUD_OPT_INT, &conf.latency_millis,
1046 "(undocumented)", NULL, 0},
1047 {"PRIMARY_FREQ", AUD_OPT_INT, &conf.settings.freq,
1048 "Primary buffer frequency", NULL, 0},
1049 {"PRIMARY_CHANNELS", AUD_OPT_INT, &conf.settings.nchannels,
1050 "Primary buffer number of channels (1 - mono, 2 - stereo)", NULL, 0},
1051 {"PRIMARY_FMT", AUD_OPT_FMT, &conf.settings.fmt,
1052 "Primary buffer format", NULL, 0},
1053 {"BUFSIZE_OUT", AUD_OPT_INT, &conf.bufsize_out,
1054 "(undocumented)", NULL, 0},
1055 {"BUFSIZE_IN", AUD_OPT_INT, &conf.bufsize_in,
1056 "(undocumented)", NULL, 0},
1057 {NULL, 0, NULL, NULL, NULL, 0}
1060 static struct audio_pcm_ops dsound_pcm_ops = {
1074 struct audio_driver dsound_audio_driver = {
1075 INIT_FIELD (name = ) "dsound",
1076 INIT_FIELD (descr = )
1077 "DirectSound http://wikipedia.org/wiki/DirectSound",
1078 INIT_FIELD (options = ) dsound_options,
1079 INIT_FIELD (init = ) dsound_audio_init,
1080 INIT_FIELD (fini = ) dsound_audio_fini,
1081 INIT_FIELD (pcm_ops = ) &dsound_pcm_ops,
1082 INIT_FIELD (can_be_default = ) 1,
1083 INIT_FIELD (max_voices_out = ) INT_MAX,
1084 INIT_FIELD (max_voices_in = ) 1,
1085 INIT_FIELD (voice_size_out = ) sizeof (DSoundVoiceOut),
1086 INIT_FIELD (voice_size_in = ) sizeof (DSoundVoiceIn)