Fix wrong signedness, by Andre Przywara.
[qemu] / audio / dsoundaudio.c
1 /*
2  * QEMU DirectSound audio driver
3  *
4  * Copyright (c) 2005 Vassili Karpov (malc)
5  *
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:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
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
22  * THE SOFTWARE.
23  */
24
25 /*
26  * SEAL 1.07 by Carlos 'pel' Hasan was used as documentation
27  */
28
29 #include "qemu-common.h"
30 #include "audio.h"
31
32 #define AUDIO_CAP "dsound"
33 #include "audio_int.h"
34
35 #include <windows.h>
36 #include <objbase.h>
37 #include <dsound.h>
38
39 /* #define DEBUG_DSOUND */
40
41 static struct {
42     int lock_retries;
43     int restore_retries;
44     int getstatus_retries;
45     int set_primary;
46     int bufsize_in;
47     int bufsize_out;
48     audsettings_t settings;
49     int latency_millis;
50 } conf = {
51     1,
52     1,
53     1,
54     0,
55     16384,
56     16384,
57     {
58         44100,
59         2,
60         AUD_FMT_S16
61     },
62     10
63 };
64
65 typedef struct {
66     LPDIRECTSOUND dsound;
67     LPDIRECTSOUNDCAPTURE dsound_capture;
68     LPDIRECTSOUNDBUFFER dsound_primary_buffer;
69     audsettings_t settings;
70 } dsound;
71
72 static dsound glob_dsound;
73
74 typedef struct {
75     HWVoiceOut hw;
76     LPDIRECTSOUNDBUFFER dsound_buffer;
77     DWORD old_pos;
78     int first_time;
79 #ifdef DEBUG_DSOUND
80     DWORD old_ppos;
81     DWORD played;
82     DWORD mixed;
83 #endif
84 } DSoundVoiceOut;
85
86 typedef struct {
87     HWVoiceIn hw;
88     int first_time;
89     LPDIRECTSOUNDCAPTUREBUFFER dsound_capture_buffer;
90 } DSoundVoiceIn;
91
92 static void dsound_log_hresult (HRESULT hr)
93 {
94     const char *str = "BUG";
95
96     switch (hr) {
97     case DS_OK:
98         str = "The method succeeded";
99         break;
100 #ifdef DS_NO_VIRTUALIZATION
101     case DS_NO_VIRTUALIZATION:
102         str = "The buffer was created, but another 3D algorithm was substituted";
103         break;
104 #endif
105 #ifdef DS_INCOMPLETE
106     case DS_INCOMPLETE:
107         str = "The method succeeded, but not all the optional effects were obtained";
108         break;
109 #endif
110 #ifdef DSERR_ACCESSDENIED
111     case DSERR_ACCESSDENIED:
112         str = "The request failed because access was denied";
113         break;
114 #endif
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";
118         break;
119 #endif
120 #ifdef DSERR_ALREADYINITIALIZED
121     case DSERR_ALREADYINITIALIZED:
122         str = "The object is already initialized";
123         break;
124 #endif
125 #ifdef DSERR_BADFORMAT
126     case DSERR_BADFORMAT:
127         str = "The specified wave format is not supported";
128         break;
129 #endif
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";
133         break;
134 #endif
135 #ifdef DSERR_BUFFERLOST
136     case DSERR_BUFFERLOST:
137         str = "The buffer memory has been lost and must be restored";
138         break;
139 #endif
140 #ifdef DSERR_BUFFERTOOSMALL
141     case DSERR_BUFFERTOOSMALL:
142         str = "The buffer size is not great enough to enable effects processing";
143         break;
144 #endif
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";
148         break;
149 #endif
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";
153         break;
154 #endif
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";
158         break;
159 #endif
160 #ifdef DSERR_GENERIC
161     case DSERR_GENERIC :
162         str = "An undetermined error occurred inside the DirectSound subsystem";
163         break;
164 #endif
165 #ifdef DSERR_INVALIDCALL
166     case DSERR_INVALIDCALL:
167         str = "This function is not valid for the current state of this object";
168         break;
169 #endif
170 #ifdef DSERR_INVALIDPARAM
171     case DSERR_INVALIDPARAM:
172         str = "An invalid parameter was passed to the returning function";
173         break;
174 #endif
175 #ifdef DSERR_NOAGGREGATION
176     case DSERR_NOAGGREGATION:
177         str = "The object does not support aggregation";
178         break;
179 #endif
180 #ifdef DSERR_NODRIVER
181     case DSERR_NODRIVER:
182         str = "No sound driver is available for use, or the given GUID is not a valid DirectSound device ID";
183         break;
184 #endif
185 #ifdef DSERR_NOINTERFACE
186     case DSERR_NOINTERFACE:
187         str = "The requested COM interface is not available";
188         break;
189 #endif
190 #ifdef DSERR_OBJECTNOTFOUND
191     case DSERR_OBJECTNOTFOUND:
192         str = "The requested object was not found";
193         break;
194 #endif
195 #ifdef DSERR_OTHERAPPHASPRIO
196     case DSERR_OTHERAPPHASPRIO:
197         str = "Another application has a higher priority level, preventing this call from succeeding";
198         break;
199 #endif
200 #ifdef DSERR_OUTOFMEMORY
201     case DSERR_OUTOFMEMORY:
202         str = "The DirectSound subsystem could not allocate sufficient memory to complete the caller's request";
203         break;
204 #endif
205 #ifdef DSERR_PRIOLEVELNEEDED
206     case DSERR_PRIOLEVELNEEDED:
207         str = "A cooperative level of DSSCL_PRIORITY or higher is required";
208         break;
209 #endif
210 #ifdef DSERR_SENDLOOP
211     case DSERR_SENDLOOP:
212         str = "A circular loop of send effects was detected";
213         break;
214 #endif
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";
218         break;
219 #endif
220 #ifdef DSERR_UNSUPPORTED
221     case DSERR_UNSUPPORTED:
222         str = "The function called is not supported at this time";
223         break;
224 #endif
225     default:
226         AUD_log (AUDIO_CAP, "Reason: Unknown (HRESULT %#lx)\n", hr);
227         return;
228     }
229
230     AUD_log (AUDIO_CAP, "Reason: %s\n", str);
231 }
232
233 static void GCC_FMT_ATTR (2, 3) dsound_logerr (
234     HRESULT hr,
235     const char *fmt,
236     ...
237     )
238 {
239     va_list ap;
240
241     va_start (ap, fmt);
242     AUD_vlog (AUDIO_CAP, fmt, ap);
243     va_end (ap);
244
245     dsound_log_hresult (hr);
246 }
247
248 static void GCC_FMT_ATTR (3, 4) dsound_logerr2 (
249     HRESULT hr,
250     const char *typ,
251     const char *fmt,
252     ...
253     )
254 {
255     va_list ap;
256
257     AUD_log (AUDIO_CAP, "Could not initialize %s\n", typ);
258     va_start (ap, fmt);
259     AUD_vlog (AUDIO_CAP, fmt, ap);
260     va_end (ap);
261
262     dsound_log_hresult (hr);
263 }
264
265 static DWORD millis_to_bytes (struct audio_pcm_info *info, DWORD millis)
266 {
267     return (millis * info->bytes_per_second) / 1000;
268 }
269
270 #ifdef DEBUG_DSOUND
271 static void print_wave_format (WAVEFORMATEX *wfx)
272 {
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);
280 }
281 #endif
282
283 static int dsound_restore_out (LPDIRECTSOUNDBUFFER dsb)
284 {
285     HRESULT hr;
286     int i;
287
288     for (i = 0; i < conf.restore_retries; ++i) {
289         hr = IDirectSoundBuffer_Restore (dsb);
290
291         switch (hr) {
292         case DS_OK:
293             return 0;
294
295         case DSERR_BUFFERLOST:
296             continue;
297
298         default:
299             dsound_logerr (hr, "Could not restore playback buffer\n");
300             return -1;
301         }
302     }
303
304     dolog ("%d attempts to restore playback buffer failed\n", i);
305     return -1;
306 }
307
308 static int waveformat_from_audio_settings (WAVEFORMATEX *wfx, audsettings_t *as)
309 {
310     memset (wfx, 0, sizeof (*wfx));
311
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);
317     wfx->cbSize = 0;
318
319     switch (as->fmt) {
320     case AUD_FMT_S8:
321         wfx->wBitsPerSample = 8;
322         break;
323
324     case AUD_FMT_U8:
325         wfx->wBitsPerSample = 8;
326         break;
327
328     case AUD_FMT_S16:
329         wfx->wBitsPerSample = 16;
330         wfx->nAvgBytesPerSec <<= 1;
331         wfx->nBlockAlign <<= 1;
332         break;
333
334     case AUD_FMT_U16:
335         wfx->wBitsPerSample = 16;
336         wfx->nAvgBytesPerSec <<= 1;
337         wfx->nBlockAlign <<= 1;
338         break;
339
340     default:
341         dolog ("Internal logic error: Bad audio format %d\n", as->freq);
342         return -1;
343     }
344
345     return 0;
346 }
347
348 static int waveformat_to_audio_settings (WAVEFORMATEX *wfx, audsettings_t *as)
349 {
350     if (wfx->wFormatTag != WAVE_FORMAT_PCM) {
351         dolog ("Invalid wave format, tag is not PCM, but %d\n",
352                wfx->wFormatTag);
353         return -1;
354     }
355
356     if (!wfx->nSamplesPerSec) {
357         dolog ("Invalid wave format, frequency is zero\n");
358         return -1;
359     }
360     as->freq = wfx->nSamplesPerSec;
361
362     switch (wfx->nChannels) {
363     case 1:
364         as->nchannels = 1;
365         break;
366
367     case 2:
368         as->nchannels = 2;
369         break;
370
371     default:
372         dolog (
373             "Invalid wave format, number of channels is not 1 or 2, but %d\n",
374             wfx->nChannels
375             );
376         return -1;
377     }
378
379     switch (wfx->wBitsPerSample) {
380     case 8:
381         as->fmt = AUD_FMT_U8;
382         break;
383
384     case 16:
385         as->fmt = AUD_FMT_S16;
386         break;
387
388     default:
389         dolog ("Invalid wave format, bits per sample is not 8 or 16, but %d\n",
390                wfx->wBitsPerSample);
391         return -1;
392     }
393
394     return 0;
395 }
396
397 #include "dsound_template.h"
398 #define DSBTYPE_IN
399 #include "dsound_template.h"
400 #undef DSBTYPE_IN
401
402 static int dsound_get_status_out (LPDIRECTSOUNDBUFFER dsb, DWORD *statusp)
403 {
404     HRESULT hr;
405     int i;
406
407     for (i = 0; i < conf.getstatus_retries; ++i) {
408         hr = IDirectSoundBuffer_GetStatus (dsb, statusp);
409         if (FAILED (hr)) {
410             dsound_logerr (hr, "Could not get playback buffer status\n");
411             return -1;
412         }
413
414         if (*statusp & DSERR_BUFFERLOST) {
415             if (dsound_restore_out (dsb)) {
416                 return -1;
417             }
418             continue;
419         }
420         break;
421     }
422
423     return 0;
424 }
425
426 static int dsound_get_status_in (LPDIRECTSOUNDCAPTUREBUFFER dscb,
427                                  DWORD *statusp)
428 {
429     HRESULT hr;
430
431     hr = IDirectSoundCaptureBuffer_GetStatus (dscb, statusp);
432     if (FAILED (hr)) {
433         dsound_logerr (hr, "Could not get capture buffer status\n");
434         return -1;
435     }
436
437     return 0;
438 }
439
440 static void dsound_write_sample (HWVoiceOut *hw, uint8_t *dst, int dst_len)
441 {
442     int src_len1 = dst_len;
443     int src_len2 = 0;
444     int pos = hw->rpos + dst_len;
445     st_sample_t *src1 = hw->mix_buf + hw->rpos;
446     st_sample_t *src2 = NULL;
447
448     if (pos > hw->samples) {
449         src_len1 = hw->samples - hw->rpos;
450         src2 = hw->mix_buf;
451         src_len2 = dst_len - src_len1;
452         pos = src_len2;
453     }
454
455     if (src_len1) {
456         hw->clip (dst, src1, src_len1);
457     }
458
459     if (src_len2) {
460         dst = advance (dst, src_len1 << hw->info.shift);
461         hw->clip (dst, src2, src_len2);
462     }
463
464     hw->rpos = pos % hw->samples;
465 }
466
467 static void dsound_clear_sample (HWVoiceOut *hw, LPDIRECTSOUNDBUFFER dsb)
468 {
469     int err;
470     LPVOID p1, p2;
471     DWORD blen1, blen2, len1, len2;
472
473     err = dsound_lock_out (
474         dsb,
475         &hw->info,
476         0,
477         hw->samples << hw->info.shift,
478         &p1, &p2,
479         &blen1, &blen2,
480         1
481         );
482     if (err) {
483         return;
484     }
485
486     len1 = blen1 >> hw->info.shift;
487     len2 = blen2 >> hw->info.shift;
488
489 #ifdef DEBUG_DSOUND
490     dolog ("clear %p,%ld,%ld %p,%ld,%ld\n",
491            p1, blen1, len1,
492            p2, blen2, len2);
493 #endif
494
495     if (p1 && len1) {
496         audio_pcm_info_clear_buf (&hw->info, p1, len1);
497     }
498
499     if (p2 && len2) {
500         audio_pcm_info_clear_buf (&hw->info, p2, len2);
501     }
502
503     dsound_unlock_out (dsb, p1, p2, blen1, blen2);
504 }
505
506 static void dsound_close (dsound *s)
507 {
508     HRESULT hr;
509
510     if (s->dsound_primary_buffer) {
511         hr = IDirectSoundBuffer_Release (s->dsound_primary_buffer);
512         if (FAILED (hr)) {
513             dsound_logerr (hr, "Could not release primary buffer\n");
514         }
515         s->dsound_primary_buffer = NULL;
516     }
517 }
518
519 static int dsound_open (dsound *s)
520 {
521     int err;
522     HRESULT hr;
523     WAVEFORMATEX wfx;
524     DSBUFFERDESC dsbd;
525     HWND hwnd;
526
527     hwnd = GetForegroundWindow ();
528     hr = IDirectSound_SetCooperativeLevel (
529         s->dsound,
530         hwnd,
531         DSSCL_PRIORITY
532         );
533
534     if (FAILED (hr)) {
535         dsound_logerr (hr, "Could not set cooperative level for window %p\n",
536                        hwnd);
537         return -1;
538     }
539
540     if (!conf.set_primary) {
541         return 0;
542     }
543
544     err = waveformat_from_audio_settings (&wfx, &conf.settings);
545     if (err) {
546         return -1;
547     }
548
549     memset (&dsbd, 0, sizeof (dsbd));
550     dsbd.dwSize = sizeof (dsbd);
551     dsbd.dwFlags = DSBCAPS_PRIMARYBUFFER;
552     dsbd.dwBufferBytes = 0;
553     dsbd.lpwfxFormat = NULL;
554
555     hr = IDirectSound_CreateSoundBuffer (
556         s->dsound,
557         &dsbd,
558         &s->dsound_primary_buffer,
559         NULL
560         );
561     if (FAILED (hr)) {
562         dsound_logerr (hr, "Could not create primary playback buffer\n");
563         return -1;
564     }
565
566     hr = IDirectSoundBuffer_SetFormat (s->dsound_primary_buffer, &wfx);
567     if (FAILED (hr)) {
568         dsound_logerr (hr, "Could not set primary playback buffer format\n");
569     }
570
571     hr = IDirectSoundBuffer_GetFormat (
572         s->dsound_primary_buffer,
573         &wfx,
574         sizeof (wfx),
575         NULL
576         );
577     if (FAILED (hr)) {
578         dsound_logerr (hr, "Could not get primary playback buffer format\n");
579         goto fail0;
580     }
581
582 #ifdef DEBUG_DSOUND
583     dolog ("Primary\n");
584     print_wave_format (&wfx);
585 #endif
586
587     err = waveformat_to_audio_settings (&wfx, &s->settings);
588     if (err) {
589         goto fail0;
590     }
591
592     return 0;
593
594  fail0:
595     dsound_close (s);
596     return -1;
597 }
598
599 static int dsound_ctl_out (HWVoiceOut *hw, int cmd, ...)
600 {
601     HRESULT hr;
602     DWORD status;
603     DSoundVoiceOut *ds = (DSoundVoiceOut *) hw;
604     LPDIRECTSOUNDBUFFER dsb = ds->dsound_buffer;
605
606     if (!dsb) {
607         dolog ("Attempt to control voice without a buffer\n");
608         return 0;
609     }
610
611     switch (cmd) {
612     case VOICE_ENABLE:
613         if (dsound_get_status_out (dsb, &status)) {
614             return -1;
615         }
616
617         if (status & DSBSTATUS_PLAYING) {
618             dolog ("warning: Voice is already playing\n");
619             return 0;
620         }
621
622         dsound_clear_sample (hw, dsb);
623
624         hr = IDirectSoundBuffer_Play (dsb, 0, 0, DSBPLAY_LOOPING);
625         if (FAILED (hr)) {
626             dsound_logerr (hr, "Could not start playing buffer\n");
627             return -1;
628         }
629         break;
630
631     case VOICE_DISABLE:
632         if (dsound_get_status_out (dsb, &status)) {
633             return -1;
634         }
635
636         if (status & DSBSTATUS_PLAYING) {
637             hr = IDirectSoundBuffer_Stop (dsb);
638             if (FAILED (hr)) {
639                 dsound_logerr (hr, "Could not stop playing buffer\n");
640                 return -1;
641             }
642         }
643         else {
644             dolog ("warning: Voice is not playing\n");
645         }
646         break;
647     }
648     return 0;
649 }
650
651 static int dsound_write (SWVoiceOut *sw, void *buf, int len)
652 {
653     return audio_pcm_sw_write (sw, buf, len);
654 }
655
656 static int dsound_run_out (HWVoiceOut *hw)
657 {
658     int err;
659     HRESULT hr;
660     DSoundVoiceOut *ds = (DSoundVoiceOut *) hw;
661     LPDIRECTSOUNDBUFFER dsb = ds->dsound_buffer;
662     int live, len, hwshift;
663     DWORD blen1, blen2;
664     DWORD len1, len2;
665     DWORD decr;
666     DWORD wpos, ppos, old_pos;
667     LPVOID p1, p2;
668     int bufsize;
669
670     if (!dsb) {
671         dolog ("Attempt to run empty with playback buffer\n");
672         return 0;
673     }
674
675     hwshift = hw->info.shift;
676     bufsize = hw->samples << hwshift;
677
678     live = audio_pcm_hw_get_live_out (hw);
679
680     hr = IDirectSoundBuffer_GetCurrentPosition (
681         dsb,
682         &ppos,
683         ds->first_time ? &wpos : NULL
684         );
685     if (FAILED (hr)) {
686         dsound_logerr (hr, "Could not get playback buffer position\n");
687         return 0;
688     }
689
690     len = live << hwshift;
691
692     if (ds->first_time) {
693         if (conf.latency_millis) {
694             DWORD cur_blat;
695
696             cur_blat = audio_ring_dist (wpos, ppos, bufsize);
697             ds->first_time = 0;
698             old_pos = wpos;
699             old_pos +=
700                 millis_to_bytes (&hw->info, conf.latency_millis) - cur_blat;
701             old_pos %= bufsize;
702             old_pos &= ~hw->info.align;
703         }
704         else {
705             old_pos = wpos;
706         }
707 #ifdef DEBUG_DSOUND
708         ds->played = 0;
709         ds->mixed = 0;
710 #endif
711     }
712     else {
713         if (ds->old_pos == ppos) {
714 #ifdef DEBUG_DSOUND
715             dolog ("old_pos == ppos\n");
716 #endif
717             return 0;
718         }
719
720 #ifdef DEBUG_DSOUND
721         ds->played += audio_ring_dist (ds->old_pos, ppos, hw->bufsize);
722 #endif
723         old_pos = ds->old_pos;
724     }
725
726     if ((old_pos < ppos) && ((old_pos + len) > ppos)) {
727         len = ppos - old_pos;
728     }
729     else {
730         if ((old_pos > ppos) && ((old_pos + len) > (ppos + bufsize))) {
731             len = bufsize - old_pos + ppos;
732         }
733     }
734
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);
738         return 0;
739     }
740
741     len &= ~hw->info.align;
742     if (!len) {
743         return 0;
744     }
745
746 #ifdef DEBUG_DSOUND
747     ds->old_ppos = ppos;
748 #endif
749     err = dsound_lock_out (
750         dsb,
751         &hw->info,
752         old_pos,
753         len,
754         &p1, &p2,
755         &blen1, &blen2,
756         0
757         );
758     if (err) {
759         return 0;
760     }
761
762     len1 = blen1 >> hwshift;
763     len2 = blen2 >> hwshift;
764     decr = len1 + len2;
765
766     if (p1 && len1) {
767         dsound_write_sample (hw, p1, len1);
768     }
769
770     if (p2 && len2) {
771         dsound_write_sample (hw, p2, len2);
772     }
773
774     dsound_unlock_out (dsb, p1, p2, blen1, blen2);
775     ds->old_pos = (old_pos + (decr << hwshift)) % bufsize;
776
777 #ifdef DEBUG_DSOUND
778     ds->mixed += decr << hwshift;
779
780     dolog ("played %lu mixed %lu diff %ld sec %f\n",
781            ds->played,
782            ds->mixed,
783            ds->mixed - ds->played,
784            abs (ds->mixed - ds->played) / (double) hw->info.bytes_per_second);
785 #endif
786     return decr;
787 }
788
789 static int dsound_ctl_in (HWVoiceIn *hw, int cmd, ...)
790 {
791     HRESULT hr;
792     DWORD status;
793     DSoundVoiceIn *ds = (DSoundVoiceIn *) hw;
794     LPDIRECTSOUNDCAPTUREBUFFER dscb = ds->dsound_capture_buffer;
795
796     if (!dscb) {
797         dolog ("Attempt to control capture voice without a buffer\n");
798         return -1;
799     }
800
801     switch (cmd) {
802     case VOICE_ENABLE:
803         if (dsound_get_status_in (dscb, &status)) {
804             return -1;
805         }
806
807         if (status & DSCBSTATUS_CAPTURING) {
808             dolog ("warning: Voice is already capturing\n");
809             return 0;
810         }
811
812         /* clear ?? */
813
814         hr = IDirectSoundCaptureBuffer_Start (dscb, DSCBSTART_LOOPING);
815         if (FAILED (hr)) {
816             dsound_logerr (hr, "Could not start capturing\n");
817             return -1;
818         }
819         break;
820
821     case VOICE_DISABLE:
822         if (dsound_get_status_in (dscb, &status)) {
823             return -1;
824         }
825
826         if (status & DSCBSTATUS_CAPTURING) {
827             hr = IDirectSoundCaptureBuffer_Stop (dscb);
828             if (FAILED (hr)) {
829                 dsound_logerr (hr, "Could not stop capturing\n");
830                 return -1;
831             }
832         }
833         else {
834             dolog ("warning: Voice is not capturing\n");
835         }
836         break;
837     }
838     return 0;
839 }
840
841 static int dsound_read (SWVoiceIn *sw, void *buf, int len)
842 {
843     return audio_pcm_sw_read (sw, buf, len);
844 }
845
846 static int dsound_run_in (HWVoiceIn *hw)
847 {
848     int err;
849     HRESULT hr;
850     DSoundVoiceIn *ds = (DSoundVoiceIn *) hw;
851     LPDIRECTSOUNDCAPTUREBUFFER dscb = ds->dsound_capture_buffer;
852     int live, len, dead;
853     DWORD blen1, blen2;
854     DWORD len1, len2;
855     DWORD decr;
856     DWORD cpos, rpos;
857     LPVOID p1, p2;
858     int hwshift;
859
860     if (!dscb) {
861         dolog ("Attempt to run without capture buffer\n");
862         return 0;
863     }
864
865     hwshift = hw->info.shift;
866
867     live = audio_pcm_hw_get_live_in (hw);
868     dead = hw->samples - live;
869     if (!dead) {
870         return 0;
871     }
872
873     hr = IDirectSoundCaptureBuffer_GetCurrentPosition (
874         dscb,
875         &cpos,
876         ds->first_time ? &rpos : NULL
877         );
878     if (FAILED (hr)) {
879         dsound_logerr (hr, "Could not get capture buffer position\n");
880         return 0;
881     }
882
883     if (ds->first_time) {
884         ds->first_time = 0;
885         if (rpos & hw->info.align) {
886             ldebug ("warning: Misaligned capture read position %ld(%d)\n",
887                     rpos, hw->info.align);
888         }
889         hw->wpos = rpos >> hwshift;
890     }
891
892     if (cpos & hw->info.align) {
893         ldebug ("warning: Misaligned capture position %ld(%d)\n",
894                 cpos, hw->info.align);
895     }
896     cpos >>= hwshift;
897
898     len = audio_ring_dist (cpos, hw->wpos, hw->samples);
899     if (!len) {
900         return 0;
901     }
902     len = audio_MIN (len, dead);
903
904     err = dsound_lock_in (
905         dscb,
906         &hw->info,
907         hw->wpos << hwshift,
908         len << hwshift,
909         &p1,
910         &p2,
911         &blen1,
912         &blen2,
913         0
914         );
915     if (err) {
916         return 0;
917     }
918
919     len1 = blen1 >> hwshift;
920     len2 = blen2 >> hwshift;
921     decr = len1 + len2;
922
923     if (p1 && len1) {
924         hw->conv (hw->conv_buf + hw->wpos, p1, len1, &nominal_volume);
925     }
926
927     if (p2 && len2) {
928         hw->conv (hw->conv_buf, p2, len2, &nominal_volume);
929     }
930
931     dsound_unlock_in (dscb, p1, p2, blen1, blen2);
932     hw->wpos = (hw->wpos + decr) % hw->samples;
933     return decr;
934 }
935
936 static void dsound_audio_fini (void *opaque)
937 {
938     HRESULT hr;
939     dsound *s = opaque;
940
941     if (!s->dsound) {
942         return;
943     }
944
945     hr = IDirectSound_Release (s->dsound);
946     if (FAILED (hr)) {
947         dsound_logerr (hr, "Could not release DirectSound\n");
948     }
949     s->dsound = NULL;
950
951     if (!s->dsound_capture) {
952         return;
953     }
954
955     hr = IDirectSoundCapture_Release (s->dsound_capture);
956     if (FAILED (hr)) {
957         dsound_logerr (hr, "Could not release DirectSoundCapture\n");
958     }
959     s->dsound_capture = NULL;
960 }
961
962 static void *dsound_audio_init (void)
963 {
964     int err;
965     HRESULT hr;
966     dsound *s = &glob_dsound;
967
968     hr = CoInitialize (NULL);
969     if (FAILED (hr)) {
970         dsound_logerr (hr, "Could not initialize COM\n");
971         return NULL;
972     }
973
974     hr = CoCreateInstance (
975         &CLSID_DirectSound,
976         NULL,
977         CLSCTX_ALL,
978         &IID_IDirectSound,
979         (void **) &s->dsound
980         );
981     if (FAILED (hr)) {
982         dsound_logerr (hr, "Could not create DirectSound instance\n");
983         return NULL;
984     }
985
986     hr = IDirectSound_Initialize (s->dsound, NULL);
987     if (FAILED (hr)) {
988         dsound_logerr (hr, "Could not initialize DirectSound\n");
989
990         hr = IDirectSound_Release (s->dsound);
991         if (FAILED (hr)) {
992             dsound_logerr (hr, "Could not release DirectSound\n");
993         }
994         s->dsound = NULL;
995         return NULL;
996     }
997
998     hr = CoCreateInstance (
999         &CLSID_DirectSoundCapture,
1000         NULL,
1001         CLSCTX_ALL,
1002         &IID_IDirectSoundCapture,
1003         (void **) &s->dsound_capture
1004         );
1005     if (FAILED (hr)) {
1006         dsound_logerr (hr, "Could not create DirectSoundCapture instance\n");
1007     }
1008     else {
1009         hr = IDirectSoundCapture_Initialize (s->dsound_capture, NULL);
1010         if (FAILED (hr)) {
1011             dsound_logerr (hr, "Could not initialize DirectSoundCapture\n");
1012
1013             hr = IDirectSoundCapture_Release (s->dsound_capture);
1014             if (FAILED (hr)) {
1015                 dsound_logerr (hr, "Could not release DirectSoundCapture\n");
1016             }
1017             s->dsound_capture = NULL;
1018         }
1019     }
1020
1021     err = dsound_open (s);
1022     if (err) {
1023         dsound_audio_fini (s);
1024         return NULL;
1025     }
1026
1027     return s;
1028 }
1029
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}
1052 };
1053
1054 static struct audio_pcm_ops dsound_pcm_ops = {
1055     dsound_init_out,
1056     dsound_fini_out,
1057     dsound_run_out,
1058     dsound_write,
1059     dsound_ctl_out,
1060
1061     dsound_init_in,
1062     dsound_fini_in,
1063     dsound_run_in,
1064     dsound_read,
1065     dsound_ctl_in
1066 };
1067
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)
1081 };