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;
68 LPDIRECTSOUNDCAPTURE dsound_capture;
69 LPDIRECTSOUNDBUFFER dsound_primary_buffer;
70 struct audsettings settings;
73 static dsound glob_dsound;
77 LPDIRECTSOUNDBUFFER dsound_buffer;
90 LPDIRECTSOUNDCAPTUREBUFFER dsound_capture_buffer;
93 static void dsound_log_hresult (HRESULT hr)
95 const char *str = "BUG";
99 str = "The method succeeded";
101 #ifdef DS_NO_VIRTUALIZATION
102 case DS_NO_VIRTUALIZATION:
103 str = "The buffer was created, but another 3D algorithm was substituted";
108 str = "The method succeeded, but not all the optional effects were obtained";
111 #ifdef DSERR_ACCESSDENIED
112 case DSERR_ACCESSDENIED:
113 str = "The request failed because access was denied";
116 #ifdef DSERR_ALLOCATED
117 case DSERR_ALLOCATED:
118 str = "The request failed because resources, such as a priority level, were already in use by another caller";
121 #ifdef DSERR_ALREADYINITIALIZED
122 case DSERR_ALREADYINITIALIZED:
123 str = "The object is already initialized";
126 #ifdef DSERR_BADFORMAT
127 case DSERR_BADFORMAT:
128 str = "The specified wave format is not supported";
131 #ifdef DSERR_BADSENDBUFFERGUID
132 case DSERR_BADSENDBUFFERGUID:
133 str = "The GUID specified in an audiopath file does not match a valid mix-in buffer";
136 #ifdef DSERR_BUFFERLOST
137 case DSERR_BUFFERLOST:
138 str = "The buffer memory has been lost and must be restored";
141 #ifdef DSERR_BUFFERTOOSMALL
142 case DSERR_BUFFERTOOSMALL:
143 str = "The buffer size is not great enough to enable effects processing";
146 #ifdef DSERR_CONTROLUNAVAIL
147 case DSERR_CONTROLUNAVAIL:
148 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";
151 #ifdef DSERR_DS8_REQUIRED
152 case DSERR_DS8_REQUIRED:
153 str = "A DirectSound object of class CLSID_DirectSound8 or later is required for the requested functionality. For more information, see IDirectSound8 Interface";
156 #ifdef DSERR_FXUNAVAILABLE
157 case DSERR_FXUNAVAILABLE:
158 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";
163 str = "An undetermined error occurred inside the DirectSound subsystem";
166 #ifdef DSERR_INVALIDCALL
167 case DSERR_INVALIDCALL:
168 str = "This function is not valid for the current state of this object";
171 #ifdef DSERR_INVALIDPARAM
172 case DSERR_INVALIDPARAM:
173 str = "An invalid parameter was passed to the returning function";
176 #ifdef DSERR_NOAGGREGATION
177 case DSERR_NOAGGREGATION:
178 str = "The object does not support aggregation";
181 #ifdef DSERR_NODRIVER
183 str = "No sound driver is available for use, or the given GUID is not a valid DirectSound device ID";
186 #ifdef DSERR_NOINTERFACE
187 case DSERR_NOINTERFACE:
188 str = "The requested COM interface is not available";
191 #ifdef DSERR_OBJECTNOTFOUND
192 case DSERR_OBJECTNOTFOUND:
193 str = "The requested object was not found";
196 #ifdef DSERR_OTHERAPPHASPRIO
197 case DSERR_OTHERAPPHASPRIO:
198 str = "Another application has a higher priority level, preventing this call from succeeding";
201 #ifdef DSERR_OUTOFMEMORY
202 case DSERR_OUTOFMEMORY:
203 str = "The DirectSound subsystem could not allocate sufficient memory to complete the caller's request";
206 #ifdef DSERR_PRIOLEVELNEEDED
207 case DSERR_PRIOLEVELNEEDED:
208 str = "A cooperative level of DSSCL_PRIORITY or higher is required";
211 #ifdef DSERR_SENDLOOP
213 str = "A circular loop of send effects was detected";
216 #ifdef DSERR_UNINITIALIZED
217 case DSERR_UNINITIALIZED:
218 str = "The Initialize method has not been called or has not been called successfully before other methods were called";
221 #ifdef DSERR_UNSUPPORTED
222 case DSERR_UNSUPPORTED:
223 str = "The function called is not supported at this time";
227 AUD_log (AUDIO_CAP, "Reason: Unknown (HRESULT %#lx)\n", hr);
231 AUD_log (AUDIO_CAP, "Reason: %s\n", str);
234 static void GCC_FMT_ATTR (2, 3) dsound_logerr (
243 AUD_vlog (AUDIO_CAP, fmt, ap);
246 dsound_log_hresult (hr);
249 static void GCC_FMT_ATTR (3, 4) dsound_logerr2 (
258 AUD_log (AUDIO_CAP, "Could not initialize %s\n", typ);
260 AUD_vlog (AUDIO_CAP, fmt, ap);
263 dsound_log_hresult (hr);
266 static DWORD millis_to_bytes (struct audio_pcm_info *info, DWORD millis)
268 return (millis * info->bytes_per_second) / 1000;
272 static void print_wave_format (WAVEFORMATEX *wfx)
274 dolog ("tag = %d\n", wfx->wFormatTag);
275 dolog ("nChannels = %d\n", wfx->nChannels);
276 dolog ("nSamplesPerSec = %ld\n", wfx->nSamplesPerSec);
277 dolog ("nAvgBytesPerSec = %ld\n", wfx->nAvgBytesPerSec);
278 dolog ("nBlockAlign = %d\n", wfx->nBlockAlign);
279 dolog ("wBitsPerSample = %d\n", wfx->wBitsPerSample);
280 dolog ("cbSize = %d\n", wfx->cbSize);
284 static int dsound_restore_out (LPDIRECTSOUNDBUFFER dsb)
289 for (i = 0; i < conf.restore_retries; ++i) {
290 hr = IDirectSoundBuffer_Restore (dsb);
296 case DSERR_BUFFERLOST:
300 dsound_logerr (hr, "Could not restore playback buffer\n");
305 dolog ("%d attempts to restore playback buffer failed\n", i);
309 static int waveformat_from_audio_settings (WAVEFORMATEX *wfx,
310 struct audsettings *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,
350 struct audsettings *as)
352 if (wfx->wFormatTag != WAVE_FORMAT_PCM) {
353 dolog ("Invalid wave format, tag is not PCM, but %d\n",
358 if (!wfx->nSamplesPerSec) {
359 dolog ("Invalid wave format, frequency is zero\n");
362 as->freq = wfx->nSamplesPerSec;
364 switch (wfx->nChannels) {
375 "Invalid wave format, number of channels is not 1 or 2, but %d\n",
381 switch (wfx->wBitsPerSample) {
383 as->fmt = AUD_FMT_U8;
387 as->fmt = AUD_FMT_S16;
391 as->fmt = AUD_FMT_S32;
395 dolog ("Invalid wave format, bits per sample is not "
396 "8, 16 or 32, but %d\n",
397 wfx->wBitsPerSample);
404 #include "dsound_template.h"
406 #include "dsound_template.h"
409 static int dsound_get_status_out (LPDIRECTSOUNDBUFFER dsb, DWORD *statusp)
414 for (i = 0; i < conf.getstatus_retries; ++i) {
415 hr = IDirectSoundBuffer_GetStatus (dsb, statusp);
417 dsound_logerr (hr, "Could not get playback buffer status\n");
421 if (*statusp & DSERR_BUFFERLOST) {
422 if (dsound_restore_out (dsb)) {
433 static int dsound_get_status_in (LPDIRECTSOUNDCAPTUREBUFFER dscb,
438 hr = IDirectSoundCaptureBuffer_GetStatus (dscb, statusp);
440 dsound_logerr (hr, "Could not get capture buffer status\n");
447 static void dsound_write_sample (HWVoiceOut *hw, uint8_t *dst, int dst_len)
449 int src_len1 = dst_len;
451 int pos = hw->rpos + dst_len;
452 struct st_sample *src1 = hw->mix_buf + hw->rpos;
453 struct st_sample *src2 = NULL;
455 if (pos > hw->samples) {
456 src_len1 = hw->samples - hw->rpos;
458 src_len2 = dst_len - src_len1;
463 hw->clip (dst, src1, src_len1);
467 dst = advance (dst, src_len1 << hw->info.shift);
468 hw->clip (dst, src2, src_len2);
471 hw->rpos = pos % hw->samples;
474 static void dsound_clear_sample (HWVoiceOut *hw, LPDIRECTSOUNDBUFFER dsb)
478 DWORD blen1, blen2, len1, len2;
480 err = dsound_lock_out (
484 hw->samples << hw->info.shift,
493 len1 = blen1 >> hw->info.shift;
494 len2 = blen2 >> hw->info.shift;
497 dolog ("clear %p,%ld,%ld %p,%ld,%ld\n",
503 audio_pcm_info_clear_buf (&hw->info, p1, len1);
507 audio_pcm_info_clear_buf (&hw->info, p2, len2);
510 dsound_unlock_out (dsb, p1, p2, blen1, blen2);
513 static void dsound_close (dsound *s)
517 if (s->dsound_primary_buffer) {
518 hr = IDirectSoundBuffer_Release (s->dsound_primary_buffer);
520 dsound_logerr (hr, "Could not release primary buffer\n");
522 s->dsound_primary_buffer = NULL;
526 static int dsound_open (dsound *s)
534 hwnd = GetForegroundWindow ();
535 hr = IDirectSound_SetCooperativeLevel (
542 dsound_logerr (hr, "Could not set cooperative level for window %p\n",
547 if (!conf.set_primary) {
551 err = waveformat_from_audio_settings (&wfx, &conf.settings);
556 memset (&dsbd, 0, sizeof (dsbd));
557 dsbd.dwSize = sizeof (dsbd);
558 dsbd.dwFlags = DSBCAPS_PRIMARYBUFFER;
559 dsbd.dwBufferBytes = 0;
560 dsbd.lpwfxFormat = NULL;
562 hr = IDirectSound_CreateSoundBuffer (
565 &s->dsound_primary_buffer,
569 dsound_logerr (hr, "Could not create primary playback buffer\n");
573 hr = IDirectSoundBuffer_SetFormat (s->dsound_primary_buffer, &wfx);
575 dsound_logerr (hr, "Could not set primary playback buffer format\n");
578 hr = IDirectSoundBuffer_GetFormat (
579 s->dsound_primary_buffer,
585 dsound_logerr (hr, "Could not get primary playback buffer format\n");
591 print_wave_format (&wfx);
594 err = waveformat_to_audio_settings (&wfx, &s->settings);
606 static int dsound_ctl_out (HWVoiceOut *hw, int cmd, ...)
610 DSoundVoiceOut *ds = (DSoundVoiceOut *) hw;
611 LPDIRECTSOUNDBUFFER dsb = ds->dsound_buffer;
614 dolog ("Attempt to control voice without a buffer\n");
620 if (dsound_get_status_out (dsb, &status)) {
624 if (status & DSBSTATUS_PLAYING) {
625 dolog ("warning: Voice is already playing\n");
629 dsound_clear_sample (hw, dsb);
631 hr = IDirectSoundBuffer_Play (dsb, 0, 0, DSBPLAY_LOOPING);
633 dsound_logerr (hr, "Could not start playing buffer\n");
639 if (dsound_get_status_out (dsb, &status)) {
643 if (status & DSBSTATUS_PLAYING) {
644 hr = IDirectSoundBuffer_Stop (dsb);
646 dsound_logerr (hr, "Could not stop playing buffer\n");
651 dolog ("warning: Voice is not playing\n");
658 static int dsound_write (SWVoiceOut *sw, void *buf, int len)
660 return audio_pcm_sw_write (sw, buf, len);
663 static int dsound_run_out (HWVoiceOut *hw)
667 DSoundVoiceOut *ds = (DSoundVoiceOut *) hw;
668 LPDIRECTSOUNDBUFFER dsb = ds->dsound_buffer;
669 int live, len, hwshift;
673 DWORD wpos, ppos, old_pos;
678 dolog ("Attempt to run empty with playback buffer\n");
682 hwshift = hw->info.shift;
683 bufsize = hw->samples << hwshift;
685 live = audio_pcm_hw_get_live_out (hw);
687 hr = IDirectSoundBuffer_GetCurrentPosition (
690 ds->first_time ? &wpos : NULL
693 dsound_logerr (hr, "Could not get playback buffer position\n");
697 len = live << hwshift;
699 if (ds->first_time) {
700 if (conf.latency_millis) {
703 cur_blat = audio_ring_dist (wpos, ppos, bufsize);
707 millis_to_bytes (&hw->info, conf.latency_millis) - cur_blat;
709 old_pos &= ~hw->info.align;
720 if (ds->old_pos == ppos) {
722 dolog ("old_pos == ppos\n");
728 ds->played += audio_ring_dist (ds->old_pos, ppos, hw->bufsize);
730 old_pos = ds->old_pos;
733 if ((old_pos < ppos) && ((old_pos + len) > ppos)) {
734 len = ppos - old_pos;
737 if ((old_pos > ppos) && ((old_pos + len) > (ppos + bufsize))) {
738 len = bufsize - old_pos + ppos;
742 if (audio_bug (AUDIO_FUNC, len < 0 || len > bufsize)) {
743 dolog ("len=%d bufsize=%d old_pos=%ld ppos=%ld\n",
744 len, bufsize, old_pos, ppos);
748 len &= ~hw->info.align;
756 err = dsound_lock_out (
769 len1 = blen1 >> hwshift;
770 len2 = blen2 >> hwshift;
774 dsound_write_sample (hw, p1, len1);
778 dsound_write_sample (hw, p2, len2);
781 dsound_unlock_out (dsb, p1, p2, blen1, blen2);
782 ds->old_pos = (old_pos + (decr << hwshift)) % bufsize;
785 ds->mixed += decr << hwshift;
787 dolog ("played %lu mixed %lu diff %ld sec %f\n",
790 ds->mixed - ds->played,
791 abs (ds->mixed - ds->played) / (double) hw->info.bytes_per_second);
796 static int dsound_ctl_in (HWVoiceIn *hw, int cmd, ...)
800 DSoundVoiceIn *ds = (DSoundVoiceIn *) hw;
801 LPDIRECTSOUNDCAPTUREBUFFER dscb = ds->dsound_capture_buffer;
804 dolog ("Attempt to control capture voice without a buffer\n");
810 if (dsound_get_status_in (dscb, &status)) {
814 if (status & DSCBSTATUS_CAPTURING) {
815 dolog ("warning: Voice is already capturing\n");
821 hr = IDirectSoundCaptureBuffer_Start (dscb, DSCBSTART_LOOPING);
823 dsound_logerr (hr, "Could not start capturing\n");
829 if (dsound_get_status_in (dscb, &status)) {
833 if (status & DSCBSTATUS_CAPTURING) {
834 hr = IDirectSoundCaptureBuffer_Stop (dscb);
836 dsound_logerr (hr, "Could not stop capturing\n");
841 dolog ("warning: Voice is not capturing\n");
848 static int dsound_read (SWVoiceIn *sw, void *buf, int len)
850 return audio_pcm_sw_read (sw, buf, len);
853 static int dsound_run_in (HWVoiceIn *hw)
857 DSoundVoiceIn *ds = (DSoundVoiceIn *) hw;
858 LPDIRECTSOUNDCAPTUREBUFFER dscb = ds->dsound_capture_buffer;
868 dolog ("Attempt to run without capture buffer\n");
872 hwshift = hw->info.shift;
874 live = audio_pcm_hw_get_live_in (hw);
875 dead = hw->samples - live;
880 hr = IDirectSoundCaptureBuffer_GetCurrentPosition (
883 ds->first_time ? &rpos : NULL
886 dsound_logerr (hr, "Could not get capture buffer position\n");
890 if (ds->first_time) {
892 if (rpos & hw->info.align) {
893 ldebug ("warning: Misaligned capture read position %ld(%d)\n",
894 rpos, hw->info.align);
896 hw->wpos = rpos >> hwshift;
899 if (cpos & hw->info.align) {
900 ldebug ("warning: Misaligned capture position %ld(%d)\n",
901 cpos, hw->info.align);
905 len = audio_ring_dist (cpos, hw->wpos, hw->samples);
909 len = audio_MIN (len, dead);
911 err = dsound_lock_in (
926 len1 = blen1 >> hwshift;
927 len2 = blen2 >> hwshift;
931 hw->conv (hw->conv_buf + hw->wpos, p1, len1, &nominal_volume);
935 hw->conv (hw->conv_buf, p2, len2, &nominal_volume);
938 dsound_unlock_in (dscb, p1, p2, blen1, blen2);
939 hw->wpos = (hw->wpos + decr) % hw->samples;
943 static void dsound_audio_fini (void *opaque)
952 hr = IDirectSound_Release (s->dsound);
954 dsound_logerr (hr, "Could not release DirectSound\n");
958 if (!s->dsound_capture) {
962 hr = IDirectSoundCapture_Release (s->dsound_capture);
964 dsound_logerr (hr, "Could not release DirectSoundCapture\n");
966 s->dsound_capture = NULL;
969 static void *dsound_audio_init (void)
973 dsound *s = &glob_dsound;
975 hr = CoInitialize (NULL);
977 dsound_logerr (hr, "Could not initialize COM\n");
981 hr = CoCreateInstance (
989 dsound_logerr (hr, "Could not create DirectSound instance\n");
993 hr = IDirectSound_Initialize (s->dsound, NULL);
995 dsound_logerr (hr, "Could not initialize DirectSound\n");
997 hr = IDirectSound_Release (s->dsound);
999 dsound_logerr (hr, "Could not release DirectSound\n");
1005 hr = CoCreateInstance (
1006 &CLSID_DirectSoundCapture,
1009 &IID_IDirectSoundCapture,
1010 (void **) &s->dsound_capture
1013 dsound_logerr (hr, "Could not create DirectSoundCapture instance\n");
1016 hr = IDirectSoundCapture_Initialize (s->dsound_capture, NULL);
1018 dsound_logerr (hr, "Could not initialize DirectSoundCapture\n");
1020 hr = IDirectSoundCapture_Release (s->dsound_capture);
1022 dsound_logerr (hr, "Could not release DirectSoundCapture\n");
1024 s->dsound_capture = NULL;
1028 err = dsound_open (s);
1030 dsound_audio_fini (s);
1037 static struct audio_option dsound_options[] = {
1038 {"LOCK_RETRIES", AUD_OPT_INT, &conf.lock_retries,
1039 "Number of times to attempt locking the buffer", NULL, 0},
1040 {"RESTOURE_RETRIES", AUD_OPT_INT, &conf.restore_retries,
1041 "Number of times to attempt restoring the buffer", NULL, 0},
1042 {"GETSTATUS_RETRIES", AUD_OPT_INT, &conf.getstatus_retries,
1043 "Number of times to attempt getting status of the buffer", NULL, 0},
1044 {"SET_PRIMARY", AUD_OPT_BOOL, &conf.set_primary,
1045 "Set the parameters of primary buffer", NULL, 0},
1046 {"LATENCY_MILLIS", AUD_OPT_INT, &conf.latency_millis,
1047 "(undocumented)", NULL, 0},
1048 {"PRIMARY_FREQ", AUD_OPT_INT, &conf.settings.freq,
1049 "Primary buffer frequency", NULL, 0},
1050 {"PRIMARY_CHANNELS", AUD_OPT_INT, &conf.settings.nchannels,
1051 "Primary buffer number of channels (1 - mono, 2 - stereo)", NULL, 0},
1052 {"PRIMARY_FMT", AUD_OPT_FMT, &conf.settings.fmt,
1053 "Primary buffer format", NULL, 0},
1054 {"BUFSIZE_OUT", AUD_OPT_INT, &conf.bufsize_out,
1055 "(undocumented)", NULL, 0},
1056 {"BUFSIZE_IN", AUD_OPT_INT, &conf.bufsize_in,
1057 "(undocumented)", NULL, 0},
1058 {NULL, 0, NULL, NULL, NULL, 0}
1061 static struct audio_pcm_ops dsound_pcm_ops = {
1075 struct audio_driver dsound_audio_driver = {
1076 INIT_FIELD (name = ) "dsound",
1077 INIT_FIELD (descr = )
1078 "DirectSound http://wikipedia.org/wiki/DirectSound",
1079 INIT_FIELD (options = ) dsound_options,
1080 INIT_FIELD (init = ) dsound_audio_init,
1081 INIT_FIELD (fini = ) dsound_audio_fini,
1082 INIT_FIELD (pcm_ops = ) &dsound_pcm_ops,
1083 INIT_FIELD (can_be_default = ) 1,
1084 INIT_FIELD (max_voices_out = ) INT_MAX,
1085 INIT_FIELD (max_voices_in = ) 1,
1086 INIT_FIELD (voice_size_out = ) sizeof (DSoundVoiceOut),
1087 INIT_FIELD (voice_size_in = ) sizeof (DSoundVoiceIn)