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"
39 /* #define DEBUG_DSOUND */
44 int getstatus_retries;
48 audsettings_t settings;
67 LPDIRECTSOUNDCAPTURE dsound_capture;
68 LPDIRECTSOUNDBUFFER dsound_primary_buffer;
69 audsettings_t settings;
72 static dsound glob_dsound;
76 LPDIRECTSOUNDBUFFER dsound_buffer;
89 LPDIRECTSOUNDCAPTUREBUFFER dsound_capture_buffer;
92 static void dsound_log_hresult (HRESULT hr)
94 const char *str = "BUG";
98 str = "The method succeeded";
100 #ifdef DS_NO_VIRTUALIZATION
101 case DS_NO_VIRTUALIZATION:
102 str = "The buffer was created, but another 3D algorithm was substituted";
107 str = "The method succeeded, but not all the optional effects were obtained";
110 #ifdef DSERR_ACCESSDENIED
111 case DSERR_ACCESSDENIED:
112 str = "The request failed because access was denied";
115 #ifdef DSERR_ALLOCATED
116 case DSERR_ALLOCATED:
117 str = "The request failed because resources, such as a priority level, were already in use by another caller";
120 #ifdef DSERR_ALREADYINITIALIZED
121 case DSERR_ALREADYINITIALIZED:
122 str = "The object is already initialized";
125 #ifdef DSERR_BADFORMAT
126 case DSERR_BADFORMAT:
127 str = "The specified wave format is not supported";
130 #ifdef DSERR_BADSENDBUFFERGUID
131 case DSERR_BADSENDBUFFERGUID:
132 str = "The GUID specified in an audiopath file does not match a valid mix-in buffer";
135 #ifdef DSERR_BUFFERLOST
136 case DSERR_BUFFERLOST:
137 str = "The buffer memory has been lost and must be restored";
140 #ifdef DSERR_BUFFERTOOSMALL
141 case DSERR_BUFFERTOOSMALL:
142 str = "The buffer size is not great enough to enable effects processing";
145 #ifdef DSERR_CONTROLUNAVAIL
146 case DSERR_CONTROLUNAVAIL:
147 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";
150 #ifdef DSERR_DS8_REQUIRED
151 case DSERR_DS8_REQUIRED:
152 str = "A DirectSound object of class CLSID_DirectSound8 or later is required for the requested functionality. For more information, see IDirectSound8 Interface";
155 #ifdef DSERR_FXUNAVAILABLE
156 case DSERR_FXUNAVAILABLE:
157 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";
162 str = "An undetermined error occurred inside the DirectSound subsystem";
165 #ifdef DSERR_INVALIDCALL
166 case DSERR_INVALIDCALL:
167 str = "This function is not valid for the current state of this object";
170 #ifdef DSERR_INVALIDPARAM
171 case DSERR_INVALIDPARAM:
172 str = "An invalid parameter was passed to the returning function";
175 #ifdef DSERR_NOAGGREGATION
176 case DSERR_NOAGGREGATION:
177 str = "The object does not support aggregation";
180 #ifdef DSERR_NODRIVER
182 str = "No sound driver is available for use, or the given GUID is not a valid DirectSound device ID";
185 #ifdef DSERR_NOINTERFACE
186 case DSERR_NOINTERFACE:
187 str = "The requested COM interface is not available";
190 #ifdef DSERR_OBJECTNOTFOUND
191 case DSERR_OBJECTNOTFOUND:
192 str = "The requested object was not found";
195 #ifdef DSERR_OTHERAPPHASPRIO
196 case DSERR_OTHERAPPHASPRIO:
197 str = "Another application has a higher priority level, preventing this call from succeeding";
200 #ifdef DSERR_OUTOFMEMORY
201 case DSERR_OUTOFMEMORY:
202 str = "The DirectSound subsystem could not allocate sufficient memory to complete the caller's request";
205 #ifdef DSERR_PRIOLEVELNEEDED
206 case DSERR_PRIOLEVELNEEDED:
207 str = "A cooperative level of DSSCL_PRIORITY or higher is required";
210 #ifdef DSERR_SENDLOOP
212 str = "A circular loop of send effects was detected";
215 #ifdef DSERR_UNINITIALIZED
216 case DSERR_UNINITIALIZED:
217 str = "The Initialize method has not been called or has not been called successfully before other methods were called";
220 #ifdef DSERR_UNSUPPORTED
221 case DSERR_UNSUPPORTED:
222 str = "The function called is not supported at this time";
226 AUD_log (AUDIO_CAP, "Reason: Unknown (HRESULT %#lx)\n", hr);
230 AUD_log (AUDIO_CAP, "Reason: %s\n", str);
233 static void GCC_FMT_ATTR (2, 3) dsound_logerr (
242 AUD_vlog (AUDIO_CAP, fmt, ap);
245 dsound_log_hresult (hr);
248 static void GCC_FMT_ATTR (3, 4) dsound_logerr2 (
257 AUD_log (AUDIO_CAP, "Could not initialize %s\n", typ);
259 AUD_vlog (AUDIO_CAP, fmt, ap);
262 dsound_log_hresult (hr);
265 static DWORD millis_to_bytes (struct audio_pcm_info *info, DWORD millis)
267 return (millis * info->bytes_per_second) / 1000;
271 static void print_wave_format (WAVEFORMATEX *wfx)
273 dolog ("tag = %d\n", wfx->wFormatTag);
274 dolog ("nChannels = %d\n", wfx->nChannels);
275 dolog ("nSamplesPerSec = %ld\n", wfx->nSamplesPerSec);
276 dolog ("nAvgBytesPerSec = %ld\n", wfx->nAvgBytesPerSec);
277 dolog ("nBlockAlign = %d\n", wfx->nBlockAlign);
278 dolog ("wBitsPerSample = %d\n", wfx->wBitsPerSample);
279 dolog ("cbSize = %d\n", wfx->cbSize);
283 static int dsound_restore_out (LPDIRECTSOUNDBUFFER dsb)
288 for (i = 0; i < conf.restore_retries; ++i) {
289 hr = IDirectSoundBuffer_Restore (dsb);
295 case DSERR_BUFFERLOST:
299 dsound_logerr (hr, "Could not restore playback buffer\n");
304 dolog ("%d attempts to restore playback buffer failed\n", i);
308 static int waveformat_from_audio_settings (WAVEFORMATEX *wfx, audsettings_t *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);
321 wfx->wBitsPerSample = 8;
325 wfx->wBitsPerSample = 8;
329 wfx->wBitsPerSample = 16;
330 wfx->nAvgBytesPerSec <<= 1;
331 wfx->nBlockAlign <<= 1;
335 wfx->wBitsPerSample = 16;
336 wfx->nAvgBytesPerSec <<= 1;
337 wfx->nBlockAlign <<= 1;
341 dolog ("Internal logic error: Bad audio format %d\n", as->freq);
348 static int waveformat_to_audio_settings (WAVEFORMATEX *wfx, audsettings_t *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 dolog ("Invalid wave format, bits per sample is not 8 or 16, but %d\n",
390 wfx->wBitsPerSample);
397 #include "dsound_template.h"
399 #include "dsound_template.h"
402 static int dsound_get_status_out (LPDIRECTSOUNDBUFFER dsb, DWORD *statusp)
407 for (i = 0; i < conf.getstatus_retries; ++i) {
408 hr = IDirectSoundBuffer_GetStatus (dsb, statusp);
410 dsound_logerr (hr, "Could not get playback buffer status\n");
414 if (*statusp & DSERR_BUFFERLOST) {
415 if (dsound_restore_out (dsb)) {
426 static int dsound_get_status_in (LPDIRECTSOUNDCAPTUREBUFFER dscb,
431 hr = IDirectSoundCaptureBuffer_GetStatus (dscb, statusp);
433 dsound_logerr (hr, "Could not get capture buffer status\n");
440 static void dsound_write_sample (HWVoiceOut *hw, uint8_t *dst, int dst_len)
442 int src_len1 = dst_len;
444 int pos = hw->rpos + dst_len;
445 st_sample_t *src1 = hw->mix_buf + hw->rpos;
446 st_sample_t *src2 = NULL;
448 if (pos > hw->samples) {
449 src_len1 = hw->samples - hw->rpos;
451 src_len2 = dst_len - src_len1;
456 hw->clip (dst, src1, src_len1);
460 dst = advance (dst, src_len1 << hw->info.shift);
461 hw->clip (dst, src2, src_len2);
464 hw->rpos = pos % hw->samples;
467 static void dsound_clear_sample (HWVoiceOut *hw, LPDIRECTSOUNDBUFFER dsb)
471 DWORD blen1, blen2, len1, len2;
473 err = dsound_lock_out (
477 hw->samples << hw->info.shift,
486 len1 = blen1 >> hw->info.shift;
487 len2 = blen2 >> hw->info.shift;
490 dolog ("clear %p,%ld,%ld %p,%ld,%ld\n",
496 audio_pcm_info_clear_buf (&hw->info, p1, len1);
500 audio_pcm_info_clear_buf (&hw->info, p2, len2);
503 dsound_unlock_out (dsb, p1, p2, blen1, blen2);
506 static void dsound_close (dsound *s)
510 if (s->dsound_primary_buffer) {
511 hr = IDirectSoundBuffer_Release (s->dsound_primary_buffer);
513 dsound_logerr (hr, "Could not release primary buffer\n");
515 s->dsound_primary_buffer = NULL;
519 static int dsound_open (dsound *s)
527 hwnd = GetForegroundWindow ();
528 hr = IDirectSound_SetCooperativeLevel (
535 dsound_logerr (hr, "Could not set cooperative level for window %p\n",
540 if (!conf.set_primary) {
544 err = waveformat_from_audio_settings (&wfx, &conf.settings);
549 memset (&dsbd, 0, sizeof (dsbd));
550 dsbd.dwSize = sizeof (dsbd);
551 dsbd.dwFlags = DSBCAPS_PRIMARYBUFFER;
552 dsbd.dwBufferBytes = 0;
553 dsbd.lpwfxFormat = NULL;
555 hr = IDirectSound_CreateSoundBuffer (
558 &s->dsound_primary_buffer,
562 dsound_logerr (hr, "Could not create primary playback buffer\n");
566 hr = IDirectSoundBuffer_SetFormat (s->dsound_primary_buffer, &wfx);
568 dsound_logerr (hr, "Could not set primary playback buffer format\n");
571 hr = IDirectSoundBuffer_GetFormat (
572 s->dsound_primary_buffer,
578 dsound_logerr (hr, "Could not get primary playback buffer format\n");
584 print_wave_format (&wfx);
587 err = waveformat_to_audio_settings (&wfx, &s->settings);
599 static int dsound_ctl_out (HWVoiceOut *hw, int cmd, ...)
603 DSoundVoiceOut *ds = (DSoundVoiceOut *) hw;
604 LPDIRECTSOUNDBUFFER dsb = ds->dsound_buffer;
607 dolog ("Attempt to control voice without a buffer\n");
613 if (dsound_get_status_out (dsb, &status)) {
617 if (status & DSBSTATUS_PLAYING) {
618 dolog ("warning: Voice is already playing\n");
622 dsound_clear_sample (hw, dsb);
624 hr = IDirectSoundBuffer_Play (dsb, 0, 0, DSBPLAY_LOOPING);
626 dsound_logerr (hr, "Could not start playing buffer\n");
632 if (dsound_get_status_out (dsb, &status)) {
636 if (status & DSBSTATUS_PLAYING) {
637 hr = IDirectSoundBuffer_Stop (dsb);
639 dsound_logerr (hr, "Could not stop playing buffer\n");
644 dolog ("warning: Voice is not playing\n");
651 static int dsound_write (SWVoiceOut *sw, void *buf, int len)
653 return audio_pcm_sw_write (sw, buf, len);
656 static int dsound_run_out (HWVoiceOut *hw)
660 DSoundVoiceOut *ds = (DSoundVoiceOut *) hw;
661 LPDIRECTSOUNDBUFFER dsb = ds->dsound_buffer;
662 int live, len, hwshift;
666 DWORD wpos, ppos, old_pos;
671 dolog ("Attempt to run empty with playback buffer\n");
675 hwshift = hw->info.shift;
676 bufsize = hw->samples << hwshift;
678 live = audio_pcm_hw_get_live_out (hw);
680 hr = IDirectSoundBuffer_GetCurrentPosition (
683 ds->first_time ? &wpos : NULL
686 dsound_logerr (hr, "Could not get playback buffer position\n");
690 len = live << hwshift;
692 if (ds->first_time) {
693 if (conf.latency_millis) {
696 cur_blat = audio_ring_dist (wpos, ppos, bufsize);
700 millis_to_bytes (&hw->info, conf.latency_millis) - cur_blat;
702 old_pos &= ~hw->info.align;
713 if (ds->old_pos == ppos) {
715 dolog ("old_pos == ppos\n");
721 ds->played += audio_ring_dist (ds->old_pos, ppos, hw->bufsize);
723 old_pos = ds->old_pos;
726 if ((old_pos < ppos) && ((old_pos + len) > ppos)) {
727 len = ppos - old_pos;
730 if ((old_pos > ppos) && ((old_pos + len) > (ppos + bufsize))) {
731 len = bufsize - old_pos + ppos;
735 if (audio_bug (AUDIO_FUNC, len < 0 || len > bufsize)) {
736 dolog ("len=%d bufsize=%d old_pos=%ld ppos=%ld\n",
737 len, bufsize, old_pos, ppos);
741 len &= ~hw->info.align;
749 err = dsound_lock_out (
762 len1 = blen1 >> hwshift;
763 len2 = blen2 >> hwshift;
767 dsound_write_sample (hw, p1, len1);
771 dsound_write_sample (hw, p2, len2);
774 dsound_unlock_out (dsb, p1, p2, blen1, blen2);
775 ds->old_pos = (old_pos + (decr << hwshift)) % bufsize;
778 ds->mixed += decr << hwshift;
780 dolog ("played %lu mixed %lu diff %ld sec %f\n",
783 ds->mixed - ds->played,
784 abs (ds->mixed - ds->played) / (double) hw->info.bytes_per_second);
789 static int dsound_ctl_in (HWVoiceIn *hw, int cmd, ...)
793 DSoundVoiceIn *ds = (DSoundVoiceIn *) hw;
794 LPDIRECTSOUNDCAPTUREBUFFER dscb = ds->dsound_capture_buffer;
797 dolog ("Attempt to control capture voice without a buffer\n");
803 if (dsound_get_status_in (dscb, &status)) {
807 if (status & DSCBSTATUS_CAPTURING) {
808 dolog ("warning: Voice is already capturing\n");
814 hr = IDirectSoundCaptureBuffer_Start (dscb, DSCBSTART_LOOPING);
816 dsound_logerr (hr, "Could not start capturing\n");
822 if (dsound_get_status_in (dscb, &status)) {
826 if (status & DSCBSTATUS_CAPTURING) {
827 hr = IDirectSoundCaptureBuffer_Stop (dscb);
829 dsound_logerr (hr, "Could not stop capturing\n");
834 dolog ("warning: Voice is not capturing\n");
841 static int dsound_read (SWVoiceIn *sw, void *buf, int len)
843 return audio_pcm_sw_read (sw, buf, len);
846 static int dsound_run_in (HWVoiceIn *hw)
850 DSoundVoiceIn *ds = (DSoundVoiceIn *) hw;
851 LPDIRECTSOUNDCAPTUREBUFFER dscb = ds->dsound_capture_buffer;
861 dolog ("Attempt to run without capture buffer\n");
865 hwshift = hw->info.shift;
867 live = audio_pcm_hw_get_live_in (hw);
868 dead = hw->samples - live;
873 hr = IDirectSoundCaptureBuffer_GetCurrentPosition (
876 ds->first_time ? &rpos : NULL
879 dsound_logerr (hr, "Could not get capture buffer position\n");
883 if (ds->first_time) {
885 if (rpos & hw->info.align) {
886 ldebug ("warning: Misaligned capture read position %ld(%d)\n",
887 rpos, hw->info.align);
889 hw->wpos = rpos >> hwshift;
892 if (cpos & hw->info.align) {
893 ldebug ("warning: Misaligned capture position %ld(%d)\n",
894 cpos, hw->info.align);
898 len = audio_ring_dist (cpos, hw->wpos, hw->samples);
902 len = audio_MIN (len, dead);
904 err = dsound_lock_in (
919 len1 = blen1 >> hwshift;
920 len2 = blen2 >> hwshift;
924 hw->conv (hw->conv_buf + hw->wpos, p1, len1, &nominal_volume);
928 hw->conv (hw->conv_buf, p2, len2, &nominal_volume);
931 dsound_unlock_in (dscb, p1, p2, blen1, blen2);
932 hw->wpos = (hw->wpos + decr) % hw->samples;
936 static void dsound_audio_fini (void *opaque)
945 hr = IDirectSound_Release (s->dsound);
947 dsound_logerr (hr, "Could not release DirectSound\n");
951 if (!s->dsound_capture) {
955 hr = IDirectSoundCapture_Release (s->dsound_capture);
957 dsound_logerr (hr, "Could not release DirectSoundCapture\n");
959 s->dsound_capture = NULL;
962 static void *dsound_audio_init (void)
966 dsound *s = &glob_dsound;
968 hr = CoInitialize (NULL);
970 dsound_logerr (hr, "Could not initialize COM\n");
974 hr = CoCreateInstance (
982 dsound_logerr (hr, "Could not create DirectSound instance\n");
986 hr = IDirectSound_Initialize (s->dsound, NULL);
988 dsound_logerr (hr, "Could not initialize DirectSound\n");
990 hr = IDirectSound_Release (s->dsound);
992 dsound_logerr (hr, "Could not release DirectSound\n");
998 hr = CoCreateInstance (
999 &CLSID_DirectSoundCapture,
1002 &IID_IDirectSoundCapture,
1003 (void **) &s->dsound_capture
1006 dsound_logerr (hr, "Could not create DirectSoundCapture instance\n");
1009 hr = IDirectSoundCapture_Initialize (s->dsound_capture, NULL);
1011 dsound_logerr (hr, "Could not initialize DirectSoundCapture\n");
1013 hr = IDirectSoundCapture_Release (s->dsound_capture);
1015 dsound_logerr (hr, "Could not release DirectSoundCapture\n");
1017 s->dsound_capture = NULL;
1021 err = dsound_open (s);
1023 dsound_audio_fini (s);
1030 static struct audio_option dsound_options[] = {
1031 {"LOCK_RETRIES", AUD_OPT_INT, &conf.lock_retries,
1032 "Number of times to attempt locking the buffer", NULL, 0},
1033 {"RESTOURE_RETRIES", AUD_OPT_INT, &conf.restore_retries,
1034 "Number of times to attempt restoring the buffer", NULL, 0},
1035 {"GETSTATUS_RETRIES", AUD_OPT_INT, &conf.getstatus_retries,
1036 "Number of times to attempt getting status of the buffer", NULL, 0},
1037 {"SET_PRIMARY", AUD_OPT_BOOL, &conf.set_primary,
1038 "Set the parameters of primary buffer", NULL, 0},
1039 {"LATENCY_MILLIS", AUD_OPT_INT, &conf.latency_millis,
1040 "(undocumented)", NULL, 0},
1041 {"PRIMARY_FREQ", AUD_OPT_INT, &conf.settings.freq,
1042 "Primary buffer frequency", NULL, 0},
1043 {"PRIMARY_CHANNELS", AUD_OPT_INT, &conf.settings.nchannels,
1044 "Primary buffer number of channels (1 - mono, 2 - stereo)", NULL, 0},
1045 {"PRIMARY_FMT", AUD_OPT_FMT, &conf.settings.fmt,
1046 "Primary buffer format", NULL, 0},
1047 {"BUFSIZE_OUT", AUD_OPT_INT, &conf.bufsize_out,
1048 "(undocumented)", NULL, 0},
1049 {"BUFSIZE_IN", AUD_OPT_INT, &conf.bufsize_in,
1050 "(undocumented)", NULL, 0},
1051 {NULL, 0, NULL, NULL, NULL, 0}
1054 static struct audio_pcm_ops dsound_pcm_ops = {
1068 struct audio_driver dsound_audio_driver = {
1069 INIT_FIELD (name = ) "dsound",
1070 INIT_FIELD (descr = )
1071 "DirectSound http://wikipedia.org/wiki/DirectSound",
1072 INIT_FIELD (options = ) dsound_options,
1073 INIT_FIELD (init = ) dsound_audio_init,
1074 INIT_FIELD (fini = ) dsound_audio_fini,
1075 INIT_FIELD (pcm_ops = ) &dsound_pcm_ops,
1076 INIT_FIELD (can_be_default = ) 1,
1077 INIT_FIELD (max_voices_out = ) INT_MAX,
1078 INIT_FIELD (max_voices_in = ) 1,
1079 INIT_FIELD (voice_size_out = ) sizeof (DSoundVoiceOut),
1080 INIT_FIELD (voice_size_in = ) sizeof (DSoundVoiceIn)