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"
40 /* #define DEBUG_DSOUND */
45 int getstatus_retries;
49 struct audsettings settings;
54 .getstatus_retries = 1,
58 .settings.freq = 44100,
59 .settings.nchannels = 2,
60 .settings.fmt = AUD_FMT_S16,
66 LPDIRECTSOUNDCAPTURE dsound_capture;
67 LPDIRECTSOUNDBUFFER dsound_primary_buffer;
68 struct audsettings settings;
71 static dsound glob_dsound;
75 LPDIRECTSOUNDBUFFER dsound_buffer;
88 LPDIRECTSOUNDCAPTUREBUFFER dsound_capture_buffer;
91 static void dsound_log_hresult (HRESULT hr)
93 const char *str = "BUG";
97 str = "The method succeeded";
99 #ifdef DS_NO_VIRTUALIZATION
100 case DS_NO_VIRTUALIZATION:
101 str = "The buffer was created, but another 3D algorithm was substituted";
106 str = "The method succeeded, but not all the optional effects were obtained";
109 #ifdef DSERR_ACCESSDENIED
110 case DSERR_ACCESSDENIED:
111 str = "The request failed because access was denied";
114 #ifdef DSERR_ALLOCATED
115 case DSERR_ALLOCATED:
116 str = "The request failed because resources, such as a priority level, were already in use by another caller";
119 #ifdef DSERR_ALREADYINITIALIZED
120 case DSERR_ALREADYINITIALIZED:
121 str = "The object is already initialized";
124 #ifdef DSERR_BADFORMAT
125 case DSERR_BADFORMAT:
126 str = "The specified wave format is not supported";
129 #ifdef DSERR_BADSENDBUFFERGUID
130 case DSERR_BADSENDBUFFERGUID:
131 str = "The GUID specified in an audiopath file does not match a valid mix-in buffer";
134 #ifdef DSERR_BUFFERLOST
135 case DSERR_BUFFERLOST:
136 str = "The buffer memory has been lost and must be restored";
139 #ifdef DSERR_BUFFERTOOSMALL
140 case DSERR_BUFFERTOOSMALL:
141 str = "The buffer size is not great enough to enable effects processing";
144 #ifdef DSERR_CONTROLUNAVAIL
145 case DSERR_CONTROLUNAVAIL:
146 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";
149 #ifdef DSERR_DS8_REQUIRED
150 case DSERR_DS8_REQUIRED:
151 str = "A DirectSound object of class CLSID_DirectSound8 or later is required for the requested functionality. For more information, see IDirectSound8 Interface";
154 #ifdef DSERR_FXUNAVAILABLE
155 case DSERR_FXUNAVAILABLE:
156 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";
161 str = "An undetermined error occurred inside the DirectSound subsystem";
164 #ifdef DSERR_INVALIDCALL
165 case DSERR_INVALIDCALL:
166 str = "This function is not valid for the current state of this object";
169 #ifdef DSERR_INVALIDPARAM
170 case DSERR_INVALIDPARAM:
171 str = "An invalid parameter was passed to the returning function";
174 #ifdef DSERR_NOAGGREGATION
175 case DSERR_NOAGGREGATION:
176 str = "The object does not support aggregation";
179 #ifdef DSERR_NODRIVER
181 str = "No sound driver is available for use, or the given GUID is not a valid DirectSound device ID";
184 #ifdef DSERR_NOINTERFACE
185 case DSERR_NOINTERFACE:
186 str = "The requested COM interface is not available";
189 #ifdef DSERR_OBJECTNOTFOUND
190 case DSERR_OBJECTNOTFOUND:
191 str = "The requested object was not found";
194 #ifdef DSERR_OTHERAPPHASPRIO
195 case DSERR_OTHERAPPHASPRIO:
196 str = "Another application has a higher priority level, preventing this call from succeeding";
199 #ifdef DSERR_OUTOFMEMORY
200 case DSERR_OUTOFMEMORY:
201 str = "The DirectSound subsystem could not allocate sufficient memory to complete the caller's request";
204 #ifdef DSERR_PRIOLEVELNEEDED
205 case DSERR_PRIOLEVELNEEDED:
206 str = "A cooperative level of DSSCL_PRIORITY or higher is required";
209 #ifdef DSERR_SENDLOOP
211 str = "A circular loop of send effects was detected";
214 #ifdef DSERR_UNINITIALIZED
215 case DSERR_UNINITIALIZED:
216 str = "The Initialize method has not been called or has not been called successfully before other methods were called";
219 #ifdef DSERR_UNSUPPORTED
220 case DSERR_UNSUPPORTED:
221 str = "The function called is not supported at this time";
225 AUD_log (AUDIO_CAP, "Reason: Unknown (HRESULT %#lx)\n", hr);
229 AUD_log (AUDIO_CAP, "Reason: %s\n", str);
232 static void GCC_FMT_ATTR (2, 3) dsound_logerr (
241 AUD_vlog (AUDIO_CAP, fmt, ap);
244 dsound_log_hresult (hr);
247 static void GCC_FMT_ATTR (3, 4) dsound_logerr2 (
256 AUD_log (AUDIO_CAP, "Could not initialize %s\n", typ);
258 AUD_vlog (AUDIO_CAP, fmt, ap);
261 dsound_log_hresult (hr);
264 static DWORD millis_to_bytes (struct audio_pcm_info *info, DWORD millis)
266 return (millis * info->bytes_per_second) / 1000;
270 static void print_wave_format (WAVEFORMATEX *wfx)
272 dolog ("tag = %d\n", wfx->wFormatTag);
273 dolog ("nChannels = %d\n", wfx->nChannels);
274 dolog ("nSamplesPerSec = %ld\n", wfx->nSamplesPerSec);
275 dolog ("nAvgBytesPerSec = %ld\n", wfx->nAvgBytesPerSec);
276 dolog ("nBlockAlign = %d\n", wfx->nBlockAlign);
277 dolog ("wBitsPerSample = %d\n", wfx->wBitsPerSample);
278 dolog ("cbSize = %d\n", wfx->cbSize);
282 static int dsound_restore_out (LPDIRECTSOUNDBUFFER dsb)
287 for (i = 0; i < conf.restore_retries; ++i) {
288 hr = IDirectSoundBuffer_Restore (dsb);
294 case DSERR_BUFFERLOST:
298 dsound_logerr (hr, "Could not restore playback buffer\n");
303 dolog ("%d attempts to restore playback buffer failed\n", i);
307 static int waveformat_from_audio_settings (WAVEFORMATEX *wfx,
308 struct audsettings *as)
310 memset (wfx, 0, sizeof (*wfx));
312 wfx->wFormatTag = WAVE_FORMAT_PCM;
313 wfx->nChannels = as->nchannels;
314 wfx->nSamplesPerSec = as->freq;
315 wfx->nAvgBytesPerSec = as->freq << (as->nchannels == 2);
316 wfx->nBlockAlign = 1 << (as->nchannels == 2);
322 wfx->wBitsPerSample = 8;
327 wfx->wBitsPerSample = 16;
328 wfx->nAvgBytesPerSec <<= 1;
329 wfx->nBlockAlign <<= 1;
334 wfx->wBitsPerSample = 32;
335 wfx->nAvgBytesPerSec <<= 2;
336 wfx->nBlockAlign <<= 2;
340 dolog ("Internal logic error: Bad audio format %d\n", as->freq);
347 static int waveformat_to_audio_settings (WAVEFORMATEX *wfx,
348 struct audsettings *as)
350 if (wfx->wFormatTag != WAVE_FORMAT_PCM) {
351 dolog ("Invalid wave format, tag is not PCM, but %d\n",
356 if (!wfx->nSamplesPerSec) {
357 dolog ("Invalid wave format, frequency is zero\n");
360 as->freq = wfx->nSamplesPerSec;
362 switch (wfx->nChannels) {
373 "Invalid wave format, number of channels is not 1 or 2, but %d\n",
379 switch (wfx->wBitsPerSample) {
381 as->fmt = AUD_FMT_U8;
385 as->fmt = AUD_FMT_S16;
389 as->fmt = AUD_FMT_S32;
393 dolog ("Invalid wave format, bits per sample is not "
394 "8, 16 or 32, but %d\n",
395 wfx->wBitsPerSample);
402 #include "dsound_template.h"
404 #include "dsound_template.h"
407 static int dsound_get_status_out (LPDIRECTSOUNDBUFFER dsb, DWORD *statusp)
412 for (i = 0; i < conf.getstatus_retries; ++i) {
413 hr = IDirectSoundBuffer_GetStatus (dsb, statusp);
415 dsound_logerr (hr, "Could not get playback buffer status\n");
419 if (*statusp & DSERR_BUFFERLOST) {
420 if (dsound_restore_out (dsb)) {
431 static int dsound_get_status_in (LPDIRECTSOUNDCAPTUREBUFFER dscb,
436 hr = IDirectSoundCaptureBuffer_GetStatus (dscb, statusp);
438 dsound_logerr (hr, "Could not get capture buffer status\n");
445 static void dsound_write_sample (HWVoiceOut *hw, uint8_t *dst, int dst_len)
447 int src_len1 = dst_len;
449 int pos = hw->rpos + dst_len;
450 struct st_sample *src1 = hw->mix_buf + hw->rpos;
451 struct st_sample *src2 = NULL;
453 if (pos > hw->samples) {
454 src_len1 = hw->samples - hw->rpos;
456 src_len2 = dst_len - src_len1;
461 hw->clip (dst, src1, src_len1);
465 dst = advance (dst, src_len1 << hw->info.shift);
466 hw->clip (dst, src2, src_len2);
469 hw->rpos = pos % hw->samples;
472 static void dsound_clear_sample (HWVoiceOut *hw, LPDIRECTSOUNDBUFFER dsb)
476 DWORD blen1, blen2, len1, len2;
478 err = dsound_lock_out (
482 hw->samples << hw->info.shift,
491 len1 = blen1 >> hw->info.shift;
492 len2 = blen2 >> hw->info.shift;
495 dolog ("clear %p,%ld,%ld %p,%ld,%ld\n",
501 audio_pcm_info_clear_buf (&hw->info, p1, len1);
505 audio_pcm_info_clear_buf (&hw->info, p2, len2);
508 dsound_unlock_out (dsb, p1, p2, blen1, blen2);
511 static void dsound_close (dsound *s)
515 if (s->dsound_primary_buffer) {
516 hr = IDirectSoundBuffer_Release (s->dsound_primary_buffer);
518 dsound_logerr (hr, "Could not release primary buffer\n");
520 s->dsound_primary_buffer = NULL;
524 static int dsound_open (dsound *s)
532 hwnd = GetForegroundWindow ();
533 hr = IDirectSound_SetCooperativeLevel (
540 dsound_logerr (hr, "Could not set cooperative level for window %p\n",
545 if (!conf.set_primary) {
549 err = waveformat_from_audio_settings (&wfx, &conf.settings);
554 memset (&dsbd, 0, sizeof (dsbd));
555 dsbd.dwSize = sizeof (dsbd);
556 dsbd.dwFlags = DSBCAPS_PRIMARYBUFFER;
557 dsbd.dwBufferBytes = 0;
558 dsbd.lpwfxFormat = NULL;
560 hr = IDirectSound_CreateSoundBuffer (
563 &s->dsound_primary_buffer,
567 dsound_logerr (hr, "Could not create primary playback buffer\n");
571 hr = IDirectSoundBuffer_SetFormat (s->dsound_primary_buffer, &wfx);
573 dsound_logerr (hr, "Could not set primary playback buffer format\n");
576 hr = IDirectSoundBuffer_GetFormat (
577 s->dsound_primary_buffer,
583 dsound_logerr (hr, "Could not get primary playback buffer format\n");
589 print_wave_format (&wfx);
592 err = waveformat_to_audio_settings (&wfx, &s->settings);
604 static int dsound_ctl_out (HWVoiceOut *hw, int cmd, ...)
608 DSoundVoiceOut *ds = (DSoundVoiceOut *) hw;
609 LPDIRECTSOUNDBUFFER dsb = ds->dsound_buffer;
612 dolog ("Attempt to control voice without a buffer\n");
618 if (dsound_get_status_out (dsb, &status)) {
622 if (status & DSBSTATUS_PLAYING) {
623 dolog ("warning: Voice is already playing\n");
627 dsound_clear_sample (hw, dsb);
629 hr = IDirectSoundBuffer_Play (dsb, 0, 0, DSBPLAY_LOOPING);
631 dsound_logerr (hr, "Could not start playing buffer\n");
637 if (dsound_get_status_out (dsb, &status)) {
641 if (status & DSBSTATUS_PLAYING) {
642 hr = IDirectSoundBuffer_Stop (dsb);
644 dsound_logerr (hr, "Could not stop playing buffer\n");
649 dolog ("warning: Voice is not playing\n");
656 static int dsound_write (SWVoiceOut *sw, void *buf, int len)
658 return audio_pcm_sw_write (sw, buf, len);
661 static int dsound_run_out (HWVoiceOut *hw)
665 DSoundVoiceOut *ds = (DSoundVoiceOut *) hw;
666 LPDIRECTSOUNDBUFFER dsb = ds->dsound_buffer;
667 int live, len, hwshift;
671 DWORD wpos, ppos, old_pos;
676 dolog ("Attempt to run empty with playback buffer\n");
680 hwshift = hw->info.shift;
681 bufsize = hw->samples << hwshift;
683 live = audio_pcm_hw_get_live_out (hw);
685 hr = IDirectSoundBuffer_GetCurrentPosition (
688 ds->first_time ? &wpos : NULL
691 dsound_logerr (hr, "Could not get playback buffer position\n");
695 len = live << hwshift;
697 if (ds->first_time) {
698 if (conf.latency_millis) {
701 cur_blat = audio_ring_dist (wpos, ppos, bufsize);
705 millis_to_bytes (&hw->info, conf.latency_millis) - cur_blat;
707 old_pos &= ~hw->info.align;
718 if (ds->old_pos == ppos) {
720 dolog ("old_pos == ppos\n");
726 ds->played += audio_ring_dist (ds->old_pos, ppos, hw->bufsize);
728 old_pos = ds->old_pos;
731 if ((old_pos < ppos) && ((old_pos + len) > ppos)) {
732 len = ppos - old_pos;
735 if ((old_pos > ppos) && ((old_pos + len) > (ppos + bufsize))) {
736 len = bufsize - old_pos + ppos;
740 if (audio_bug (AUDIO_FUNC, len < 0 || len > bufsize)) {
741 dolog ("len=%d bufsize=%d old_pos=%ld ppos=%ld\n",
742 len, bufsize, old_pos, ppos);
746 len &= ~hw->info.align;
754 err = dsound_lock_out (
767 len1 = blen1 >> hwshift;
768 len2 = blen2 >> hwshift;
772 dsound_write_sample (hw, p1, len1);
776 dsound_write_sample (hw, p2, len2);
779 dsound_unlock_out (dsb, p1, p2, blen1, blen2);
780 ds->old_pos = (old_pos + (decr << hwshift)) % bufsize;
783 ds->mixed += decr << hwshift;
785 dolog ("played %lu mixed %lu diff %ld sec %f\n",
788 ds->mixed - ds->played,
789 abs (ds->mixed - ds->played) / (double) hw->info.bytes_per_second);
794 static int dsound_ctl_in (HWVoiceIn *hw, int cmd, ...)
798 DSoundVoiceIn *ds = (DSoundVoiceIn *) hw;
799 LPDIRECTSOUNDCAPTUREBUFFER dscb = ds->dsound_capture_buffer;
802 dolog ("Attempt to control capture voice without a buffer\n");
808 if (dsound_get_status_in (dscb, &status)) {
812 if (status & DSCBSTATUS_CAPTURING) {
813 dolog ("warning: Voice is already capturing\n");
819 hr = IDirectSoundCaptureBuffer_Start (dscb, DSCBSTART_LOOPING);
821 dsound_logerr (hr, "Could not start capturing\n");
827 if (dsound_get_status_in (dscb, &status)) {
831 if (status & DSCBSTATUS_CAPTURING) {
832 hr = IDirectSoundCaptureBuffer_Stop (dscb);
834 dsound_logerr (hr, "Could not stop capturing\n");
839 dolog ("warning: Voice is not capturing\n");
846 static int dsound_read (SWVoiceIn *sw, void *buf, int len)
848 return audio_pcm_sw_read (sw, buf, len);
851 static int dsound_run_in (HWVoiceIn *hw)
855 DSoundVoiceIn *ds = (DSoundVoiceIn *) hw;
856 LPDIRECTSOUNDCAPTUREBUFFER dscb = ds->dsound_capture_buffer;
866 dolog ("Attempt to run without capture buffer\n");
870 hwshift = hw->info.shift;
872 live = audio_pcm_hw_get_live_in (hw);
873 dead = hw->samples - live;
878 hr = IDirectSoundCaptureBuffer_GetCurrentPosition (
881 ds->first_time ? &rpos : NULL
884 dsound_logerr (hr, "Could not get capture buffer position\n");
888 if (ds->first_time) {
890 if (rpos & hw->info.align) {
891 ldebug ("warning: Misaligned capture read position %ld(%d)\n",
892 rpos, hw->info.align);
894 hw->wpos = rpos >> hwshift;
897 if (cpos & hw->info.align) {
898 ldebug ("warning: Misaligned capture position %ld(%d)\n",
899 cpos, hw->info.align);
903 len = audio_ring_dist (cpos, hw->wpos, hw->samples);
907 len = audio_MIN (len, dead);
909 err = dsound_lock_in (
924 len1 = blen1 >> hwshift;
925 len2 = blen2 >> hwshift;
929 hw->conv (hw->conv_buf + hw->wpos, p1, len1, &nominal_volume);
933 hw->conv (hw->conv_buf, p2, len2, &nominal_volume);
936 dsound_unlock_in (dscb, p1, p2, blen1, blen2);
937 hw->wpos = (hw->wpos + decr) % hw->samples;
941 static void dsound_audio_fini (void *opaque)
950 hr = IDirectSound_Release (s->dsound);
952 dsound_logerr (hr, "Could not release DirectSound\n");
956 if (!s->dsound_capture) {
960 hr = IDirectSoundCapture_Release (s->dsound_capture);
962 dsound_logerr (hr, "Could not release DirectSoundCapture\n");
964 s->dsound_capture = NULL;
967 static void *dsound_audio_init (void)
971 dsound *s = &glob_dsound;
973 hr = CoInitialize (NULL);
975 dsound_logerr (hr, "Could not initialize COM\n");
979 hr = CoCreateInstance (
987 dsound_logerr (hr, "Could not create DirectSound instance\n");
991 hr = IDirectSound_Initialize (s->dsound, NULL);
993 dsound_logerr (hr, "Could not initialize DirectSound\n");
995 hr = IDirectSound_Release (s->dsound);
997 dsound_logerr (hr, "Could not release DirectSound\n");
1003 hr = CoCreateInstance (
1004 &CLSID_DirectSoundCapture,
1007 &IID_IDirectSoundCapture,
1008 (void **) &s->dsound_capture
1011 dsound_logerr (hr, "Could not create DirectSoundCapture instance\n");
1014 hr = IDirectSoundCapture_Initialize (s->dsound_capture, NULL);
1016 dsound_logerr (hr, "Could not initialize DirectSoundCapture\n");
1018 hr = IDirectSoundCapture_Release (s->dsound_capture);
1020 dsound_logerr (hr, "Could not release DirectSoundCapture\n");
1022 s->dsound_capture = NULL;
1026 err = dsound_open (s);
1028 dsound_audio_fini (s);
1035 static struct audio_option dsound_options[] = {
1037 .name = "LOCK_RETRIES",
1039 .valp = &conf.lock_retries,
1040 .descr = "Number of times to attempt locking the buffer"
1043 .name = "RESTOURE_RETRIES",
1045 .valp = &conf.restore_retries,
1046 .descr = "Number of times to attempt restoring the buffer"
1049 .name = "GETSTATUS_RETRIES",
1051 .valp = &conf.getstatus_retries,
1052 .descr = "Number of times to attempt getting status of the buffer"
1055 .name = "SET_PRIMARY",
1056 .tag = AUD_OPT_BOOL,
1057 .valp = &conf.set_primary,
1058 .descr = "Set the parameters of primary buffer"
1061 .name = "LATENCY_MILLIS",
1063 .valp = &conf.latency_millis,
1064 .descr = "(undocumented)"
1067 .name = "PRIMARY_FREQ",
1069 .valp = &conf.settings.freq,
1070 .descr = "Primary buffer frequency"
1073 .name = "PRIMARY_CHANNELS",
1075 .valp = &conf.settings.nchannels,
1076 .descr = "Primary buffer number of channels (1 - mono, 2 - stereo)"
1079 .name = "PRIMARY_FMT",
1081 .valp = &conf.settings.fmt,
1082 .descr = "Primary buffer format"
1085 .name = "BUFSIZE_OUT",
1087 .valp = &conf.bufsize_out,
1088 .descr = "(undocumented)"
1091 .name = "BUFSIZE_IN",
1093 .valp = &conf.bufsize_in,
1094 .descr = "(undocumented)"
1096 { /* End of list */ }
1099 static struct audio_pcm_ops dsound_pcm_ops = {
1100 .init_out = dsound_init_out,
1101 .fini_out = dsound_fini_out,
1102 .run_out = dsound_run_out,
1103 .write = dsound_write,
1104 .ctl_out = dsound_ctl_out,
1106 .init_in = dsound_init_in,
1107 .fini_in = dsound_fini_in,
1108 .run_in = dsound_run_in,
1109 .read = dsound_read,
1110 .ctl_in = dsound_ctl_in
1113 struct audio_driver dsound_audio_driver = {
1115 .descr = "DirectSound http://wikipedia.org/wiki/DirectSound",
1116 .options = dsound_options,
1117 .init = dsound_audio_init,
1118 .fini = dsound_audio_fini,
1119 .pcm_ops = &dsound_pcm_ops,
1120 .can_be_default = 1,
1121 .max_voices_out = INT_MAX,
1123 .voice_size_out = sizeof (DSoundVoiceOut),
1124 .voice_size_in = sizeof (DSoundVoiceIn)