user32: Moved the menu activation hack on managed windows to the X11 driver.
[wine] / dlls / winecoreaudio.drv / audio.c
1 /*
2  * Wine Driver for CoreAudio based on Jack Driver
3  *
4  * Copyright 1994 Martin Ayotte
5  * Copyright 1999 Eric Pouech (async playing in waveOut/waveIn)
6  * Copyright 2000 Eric Pouech (loops in waveOut)
7  * Copyright 2002 Chris Morgan (jack version of this file)
8  * Copyright 2005, 2006 Emmanuel Maillard
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with this library; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23  */
24
25 #include "config.h"
26
27 #include <stdlib.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <string.h>
31 #ifdef HAVE_UNISTD_H
32 # include <unistd.h>
33 #endif
34 #include <fcntl.h>
35
36 #include "windef.h"
37 #include "winbase.h"
38 #include "winnls.h"
39 #include "wingdi.h"
40 #include "winerror.h"
41 #include "mmddk.h"
42 #include "dsound.h"
43 #include "dsdriver.h"
44 #include "coreaudio.h"
45 #include "wine/unicode.h"
46 #include "wine/library.h"
47 #include "wine/debug.h"
48
49 WINE_DEFAULT_DEBUG_CHANNEL(wave);
50
51
52 #if defined(HAVE_COREAUDIO_COREAUDIO_H) && defined(HAVE_AUDIOUNIT_AUDIOUNIT_H)
53 #include <CoreAudio/CoreAudio.h>
54 #include <CoreFoundation/CoreFoundation.h>
55 #include <libkern/OSAtomic.h>
56
57 /*
58     Due to AudioUnit headers conflict define some needed types.
59 */
60
61 typedef void *AudioUnit;
62
63 /* From AudioUnit/AUComponents.h */
64 enum
65 {
66     kAudioUnitRenderAction_OutputIsSilence  = (1 << 4),
67         /* provides hint on return from Render(): if set the buffer contains all zeroes */
68 };
69 typedef UInt32 AudioUnitRenderActionFlags;
70
71 typedef long ComponentResult;
72 extern ComponentResult
73 AudioUnitRender(                    AudioUnit                       ci,
74                                     AudioUnitRenderActionFlags *    ioActionFlags,
75                                     const AudioTimeStamp *          inTimeStamp,
76                                     UInt32                          inOutputBusNumber,
77                                     UInt32                          inNumberFrames,
78                                     AudioBufferList *               ioData)         AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER;
79
80 /* only allow 10 output devices through this driver, this ought to be adequate */
81 #define MAX_WAVEOUTDRV  (1)
82 #define MAX_WAVEINDRV   (1)
83
84 /* state diagram for waveOut writing:
85 *
86 * +---------+-------------+---------------+---------------------------------+
87 * |  state  |  function   |     event     |            new state             |
88 * +---------+-------------+---------------+---------------------------------+
89 * |          | open()      |               | STOPPED                         |
90 * | PAUSED  | write()      |               | PAUSED                          |
91 * | STOPPED | write()      | <thrd create> | PLAYING                         |
92 * | PLAYING | write()      | HEADER        | PLAYING                         |
93 * | (other) | write()      | <error>       |                                 |
94 * | (any)   | pause()      | PAUSING       | PAUSED                          |
95 * | PAUSED  | restart()   | RESTARTING    | PLAYING (if no thrd => STOPPED) |
96 * | (any)   | reset()      | RESETTING     | STOPPED                         |
97 * | (any)   | close()      | CLOSING       | CLOSED                          |
98 * +---------+-------------+---------------+---------------------------------+
99 */
100
101 /* states of the playing device */
102 #define WINE_WS_PLAYING   0
103 #define WINE_WS_PAUSED    1
104 #define WINE_WS_STOPPED   2
105 #define WINE_WS_CLOSED    3
106
107 typedef struct tagCoreAudio_Device {
108     char                        dev_name[32];
109     char                        mixer_name[32];
110     unsigned                    open_count;
111     char*                       interface_name;
112     
113     WAVEOUTCAPSW                out_caps;
114     WAVEINCAPSW                 in_caps;
115     DWORD                       in_caps_support;
116     int                         sample_rate;
117     int                         stereo;
118     int                         format;
119     unsigned                    audio_fragment;
120     BOOL                        full_duplex;
121     BOOL                        bTriggerSupport;
122     BOOL                        bOutputEnabled;
123     BOOL                        bInputEnabled;
124     DSDRIVERDESC                ds_desc;
125     DSDRIVERCAPS                ds_caps;
126     DSCDRIVERCAPS               dsc_caps;
127     GUID                        ds_guid;
128     GUID                        dsc_guid;
129     
130     AudioDeviceID outputDeviceID;
131     AudioDeviceID inputDeviceID;
132     AudioStreamBasicDescription streamDescription;
133 } CoreAudio_Device;
134
135 /* for now use the default device */
136 static CoreAudio_Device CoreAudio_DefaultDevice;
137
138 typedef struct {
139     volatile int                state;      /* one of the WINE_WS_ manifest constants */
140     CoreAudio_Device            *cadev;
141     WAVEOPENDESC                waveDesc;
142     WORD                        wFlags;
143     PCMWAVEFORMAT               format;
144     DWORD                       woID;
145     AudioUnit                   audioUnit;
146     AudioStreamBasicDescription streamDescription;
147     
148     WAVEOUTCAPSW                caps;
149     char                        interface_name[32];
150     LPWAVEHDR                   lpQueuePtr;             /* start of queued WAVEHDRs (waiting to be notified) */
151     LPWAVEHDR                   lpPlayPtr;              /* start of not yet fully played buffers */
152     DWORD                       dwPartialOffset;        /* Offset of not yet written bytes in lpPlayPtr */
153     
154     LPWAVEHDR                   lpLoopPtr;              /* pointer of first buffer in loop, if any */
155     DWORD                       dwLoops;                /* private copy of loop counter */
156     
157     DWORD                       dwPlayedTotal;          /* number of bytes actually played since opening */
158     DWORD                       dwWrittenTotal;         /* number of bytes written to OSS buffer since opening */
159         
160     DWORD                       tickCountMS; /* time in MS of last AudioUnit callback */
161
162     OSSpinLock                  lock;         /* synchronization stuff */
163
164     BOOL trace_on;
165     BOOL warn_on;
166     BOOL err_on;
167 } WINE_WAVEOUT;
168
169 typedef struct {
170     /* This device's device number */
171     DWORD           wiID;
172
173     /* Access to the following fields is synchronized across threads. */
174     volatile int    state;
175     LPWAVEHDR       lpQueuePtr;
176     DWORD           dwTotalRecorded;
177
178     /* Synchronization mechanism to protect above fields */
179     OSSpinLock      lock;
180
181     /* Capabilities description */
182     WAVEINCAPSW     caps;
183     char            interface_name[32];
184
185     /* Record the arguments used when opening the device. */
186     WAVEOPENDESC    waveDesc;
187     WORD            wFlags;
188     PCMWAVEFORMAT   format;
189
190     AudioUnit       audioUnit;
191     AudioBufferList*bufferList;
192     AudioBufferList*bufferListCopy;
193
194     /* Record state of debug channels at open.  Used to control fprintf's since
195      * we can't use Wine debug channel calls in non-Wine AudioUnit threads. */
196     BOOL            trace_on;
197     BOOL            warn_on;
198     BOOL            err_on;
199
200 /* These fields aren't used. */
201 #if 0
202     CoreAudio_Device *cadev;
203
204     AudioStreamBasicDescription streamDescription;
205 #endif
206 } WINE_WAVEIN;
207
208 static WINE_WAVEOUT WOutDev   [MAX_WAVEOUTDRV];
209 static WINE_WAVEIN  WInDev    [MAX_WAVEINDRV];
210
211 static HANDLE hThread = NULL; /* Track the thread we create so we can clean it up later */
212 static CFMessagePortRef Port_SendToMessageThread;
213
214 static void wodHelper_PlayPtrNext(WINE_WAVEOUT* wwo);
215 static void wodHelper_NotifyDoneForList(WINE_WAVEOUT* wwo, LPWAVEHDR lpWaveHdr);
216 static void wodHelper_NotifyCompletions(WINE_WAVEOUT* wwo, BOOL force);
217 static void widHelper_NotifyCompletions(WINE_WAVEIN* wwi);
218
219 extern int AudioUnit_CreateDefaultAudioUnit(void *wwo, AudioUnit *au);
220 extern int AudioUnit_CloseAudioUnit(AudioUnit au);
221 extern int AudioUnit_InitializeWithStreamDescription(AudioUnit au, AudioStreamBasicDescription *streamFormat);
222
223 extern OSStatus AudioOutputUnitStart(AudioUnit au);
224 extern OSStatus AudioOutputUnitStop(AudioUnit au);
225 extern OSStatus AudioUnitUninitialize(AudioUnit au);
226
227 extern int AudioUnit_SetVolume(AudioUnit au, float left, float right);
228 extern int AudioUnit_GetVolume(AudioUnit au, float *left, float *right);
229
230 extern int AudioUnit_GetInputDeviceSampleRate(void);
231
232 extern int AudioUnit_CreateInputUnit(void* wwi, AudioUnit* out_au,
233         WORD nChannels, DWORD nSamplesPerSec, WORD wBitsPerSample,
234         UInt32* outFrameCount);
235
236 OSStatus CoreAudio_woAudioUnitIOProc(void *inRefCon, 
237                                      AudioUnitRenderActionFlags *ioActionFlags, 
238                                      const AudioTimeStamp *inTimeStamp, 
239                                      UInt32 inBusNumber, 
240                                      UInt32 inNumberFrames, 
241                                      AudioBufferList *ioData);
242 OSStatus CoreAudio_wiAudioUnitIOProc(void *inRefCon,
243                                      AudioUnitRenderActionFlags *ioActionFlags,
244                                      const AudioTimeStamp *inTimeStamp,
245                                      UInt32 inBusNumber,
246                                      UInt32 inNumberFrames,
247                                      AudioBufferList *ioData);
248
249 /* These strings used only for tracing */
250
251 static const char * getMessage(UINT msg)
252 {
253     static char unknown[32];
254 #define MSG_TO_STR(x) case x: return #x
255     switch(msg) {
256         MSG_TO_STR(DRVM_INIT);
257         MSG_TO_STR(DRVM_EXIT);
258         MSG_TO_STR(DRVM_ENABLE);
259         MSG_TO_STR(DRVM_DISABLE);
260         MSG_TO_STR(WIDM_OPEN);
261         MSG_TO_STR(WIDM_CLOSE);
262         MSG_TO_STR(WIDM_ADDBUFFER);
263         MSG_TO_STR(WIDM_PREPARE);
264         MSG_TO_STR(WIDM_UNPREPARE);
265         MSG_TO_STR(WIDM_GETDEVCAPS);
266         MSG_TO_STR(WIDM_GETNUMDEVS);
267         MSG_TO_STR(WIDM_GETPOS);
268         MSG_TO_STR(WIDM_RESET);
269         MSG_TO_STR(WIDM_START);
270         MSG_TO_STR(WIDM_STOP);
271         MSG_TO_STR(WODM_OPEN);
272         MSG_TO_STR(WODM_CLOSE);
273         MSG_TO_STR(WODM_WRITE);
274         MSG_TO_STR(WODM_PAUSE);
275         MSG_TO_STR(WODM_GETPOS);
276         MSG_TO_STR(WODM_BREAKLOOP);
277         MSG_TO_STR(WODM_PREPARE);
278         MSG_TO_STR(WODM_UNPREPARE);
279         MSG_TO_STR(WODM_GETDEVCAPS);
280         MSG_TO_STR(WODM_GETNUMDEVS);
281         MSG_TO_STR(WODM_GETPITCH);
282         MSG_TO_STR(WODM_SETPITCH);
283         MSG_TO_STR(WODM_GETPLAYBACKRATE);
284         MSG_TO_STR(WODM_SETPLAYBACKRATE);
285         MSG_TO_STR(WODM_GETVOLUME);
286         MSG_TO_STR(WODM_SETVOLUME);
287         MSG_TO_STR(WODM_RESTART);
288         MSG_TO_STR(WODM_RESET);
289         MSG_TO_STR(DRV_QUERYDEVICEINTERFACESIZE);
290         MSG_TO_STR(DRV_QUERYDEVICEINTERFACE);
291         MSG_TO_STR(DRV_QUERYDSOUNDIFACE);
292         MSG_TO_STR(DRV_QUERYDSOUNDDESC);
293     }
294 #undef MSG_TO_STR
295     sprintf(unknown, "UNKNOWN(0x%04x)", msg);
296     return unknown;
297 }
298
299 #define kStopLoopMessage 0
300 #define kWaveOutNotifyCompletionsMessage 1
301 #define kWaveInNotifyCompletionsMessage 2
302
303 /* Mach Message Handling */
304 static CFDataRef wodMessageHandler(CFMessagePortRef port_ReceiveInMessageThread, SInt32 msgid, CFDataRef data, void *info)
305 {
306     UInt32 *buffer = NULL;
307
308     switch (msgid)
309     {
310         case kWaveOutNotifyCompletionsMessage:
311             buffer = (UInt32 *) CFDataGetBytePtr(data);
312             wodHelper_NotifyCompletions(&WOutDev[buffer[0]], FALSE);
313             break;
314         case kWaveInNotifyCompletionsMessage:
315             buffer = (UInt32 *) CFDataGetBytePtr(data);
316             widHelper_NotifyCompletions(&WInDev[buffer[0]]);
317             break;
318         default:
319             CFRunLoopStop(CFRunLoopGetCurrent());
320             break;
321     }
322     
323     return NULL;
324 }
325
326 static DWORD WINAPI messageThread(LPVOID p)
327 {
328     CFMessagePortRef port_ReceiveInMessageThread = (CFMessagePortRef) p;
329     CFRunLoopSourceRef source;
330     
331     source = CFMessagePortCreateRunLoopSource(kCFAllocatorDefault, port_ReceiveInMessageThread, (CFIndex)0);
332     CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
333
334     CFRunLoopRun();
335
336     CFRunLoopSourceInvalidate(source);
337     CFRelease(source);
338     CFRelease(port_ReceiveInMessageThread);
339
340     return 0;
341 }
342
343 /**************************************************************************
344 *                       wodSendNotifyCompletionsMessage                 [internal]
345 *   Call from AudioUnit IO thread can't use Wine debug channels.
346 */
347 static void wodSendNotifyCompletionsMessage(WINE_WAVEOUT* wwo)
348 {
349     CFDataRef data;
350     UInt32 buffer;
351
352     buffer = (UInt32) wwo->woID;
353
354     data = CFDataCreate(kCFAllocatorDefault, (UInt8 *)&buffer, sizeof(buffer));
355     if (!data)
356         return;
357
358     CFMessagePortSendRequest(Port_SendToMessageThread, kWaveOutNotifyCompletionsMessage, data, 0.0, 0.0, NULL, NULL);
359     CFRelease(data);
360 }
361
362 /**************************************************************************
363 *                       wodSendNotifyInputCompletionsMessage     [internal]
364 *   Call from AudioUnit IO thread can't use Wine debug channels.
365 */
366 static void wodSendNotifyInputCompletionsMessage(WINE_WAVEIN* wwi)
367 {
368     CFDataRef data;
369     UInt32 buffer;
370
371     buffer = (UInt32) wwi->wiID;
372
373     data = CFDataCreate(kCFAllocatorDefault, (UInt8 *)&buffer, sizeof(buffer));
374     if (!data)
375         return;
376
377     CFMessagePortSendRequest(Port_SendToMessageThread, kWaveInNotifyCompletionsMessage, data, 0.0, 0.0, NULL, NULL);
378     CFRelease(data);
379 }
380
381 static DWORD bytes_to_mmtime(LPMMTIME lpTime, DWORD position,
382                              PCMWAVEFORMAT* format)
383 {
384     TRACE("wType=%04X wBitsPerSample=%u nSamplesPerSec=%u nChannels=%u nAvgBytesPerSec=%u\n",
385           lpTime->wType, format->wBitsPerSample, format->wf.nSamplesPerSec,
386           format->wf.nChannels, format->wf.nAvgBytesPerSec);
387     TRACE("Position in bytes=%u\n", position);
388
389     switch (lpTime->wType) {
390     case TIME_SAMPLES:
391         lpTime->u.sample = position / (format->wBitsPerSample / 8 * format->wf.nChannels);
392         TRACE("TIME_SAMPLES=%u\n", lpTime->u.sample);
393         break;
394     case TIME_MS:
395         lpTime->u.ms = 1000.0 * position / (format->wBitsPerSample / 8 * format->wf.nChannels * format->wf.nSamplesPerSec);
396         TRACE("TIME_MS=%u\n", lpTime->u.ms);
397         break;
398     case TIME_SMPTE:
399         lpTime->u.smpte.fps = 30;
400         position = position / (format->wBitsPerSample / 8 * format->wf.nChannels);
401         position += (format->wf.nSamplesPerSec / lpTime->u.smpte.fps) - 1; /* round up */
402         lpTime->u.smpte.sec = position / format->wf.nSamplesPerSec;
403         position -= lpTime->u.smpte.sec * format->wf.nSamplesPerSec;
404         lpTime->u.smpte.min = lpTime->u.smpte.sec / 60;
405         lpTime->u.smpte.sec -= 60 * lpTime->u.smpte.min;
406         lpTime->u.smpte.hour = lpTime->u.smpte.min / 60;
407         lpTime->u.smpte.min -= 60 * lpTime->u.smpte.hour;
408         lpTime->u.smpte.fps = 30;
409         lpTime->u.smpte.frame = position * lpTime->u.smpte.fps / format->wf.nSamplesPerSec;
410         TRACE("TIME_SMPTE=%02u:%02u:%02u:%02u\n",
411               lpTime->u.smpte.hour, lpTime->u.smpte.min,
412               lpTime->u.smpte.sec, lpTime->u.smpte.frame);
413         break;
414     default:
415         WARN("Format %d not supported, using TIME_BYTES !\n", lpTime->wType);
416         lpTime->wType = TIME_BYTES;
417         /* fall through */
418     case TIME_BYTES:
419         lpTime->u.cb = position;
420         TRACE("TIME_BYTES=%u\n", lpTime->u.cb);
421         break;
422     }
423     return MMSYSERR_NOERROR;
424 }
425
426 /**************************************************************************
427 *                       CoreAudio_GetDevCaps            [internal]
428 */
429 BOOL CoreAudio_GetDevCaps (void)
430 {
431     OSStatus status;
432     UInt32 propertySize;
433     AudioDeviceID devId = CoreAudio_DefaultDevice.outputDeviceID;
434     
435     char name[MAXPNAMELEN];
436     
437     propertySize = MAXPNAMELEN;
438     status = AudioDeviceGetProperty(devId, 0 , FALSE, kAudioDevicePropertyDeviceName, &propertySize, name);
439     if (status) {
440         ERR("AudioHardwareGetProperty for kAudioDevicePropertyDeviceName return %c%c%c%c\n", (char) (status >> 24),
441                                                                                              (char) (status >> 16),
442                                                                                              (char) (status >> 8),
443                                                                                              (char) status);
444         return FALSE;
445     }
446     
447     memcpy(CoreAudio_DefaultDevice.ds_desc.szDesc, name, sizeof(name));
448     strcpy(CoreAudio_DefaultDevice.ds_desc.szDrvname, "winecoreaudio.drv");
449     MultiByteToWideChar(CP_ACP, 0, name, sizeof(name), 
450                         CoreAudio_DefaultDevice.out_caps.szPname, 
451                         sizeof(CoreAudio_DefaultDevice.out_caps.szPname) / sizeof(WCHAR));
452     memcpy(CoreAudio_DefaultDevice.dev_name, name, 32);
453     
454     propertySize = sizeof(CoreAudio_DefaultDevice.streamDescription);
455     status = AudioDeviceGetProperty(devId, 0, FALSE , kAudioDevicePropertyStreamFormat, &propertySize, &CoreAudio_DefaultDevice.streamDescription);
456     if (status != noErr) {
457         ERR("AudioHardwareGetProperty for kAudioDevicePropertyStreamFormat return %c%c%c%c\n", (char) (status >> 24),
458                                                                                                 (char) (status >> 16),
459                                                                                                 (char) (status >> 8),
460                                                                                                 (char) status);
461         return FALSE;
462     }
463     
464     TRACE("Device Stream Description mSampleRate : %f\n mFormatID : %c%c%c%c\n"
465             "mFormatFlags : %lX\n mBytesPerPacket : %lu\n mFramesPerPacket : %lu\n"
466             "mBytesPerFrame : %lu\n mChannelsPerFrame : %lu\n mBitsPerChannel : %lu\n",
467                                CoreAudio_DefaultDevice.streamDescription.mSampleRate,
468                                (char) (CoreAudio_DefaultDevice.streamDescription.mFormatID >> 24),
469                                (char) (CoreAudio_DefaultDevice.streamDescription.mFormatID >> 16),
470                                (char) (CoreAudio_DefaultDevice.streamDescription.mFormatID >> 8),
471                                (char) CoreAudio_DefaultDevice.streamDescription.mFormatID,
472                                CoreAudio_DefaultDevice.streamDescription.mFormatFlags,
473                                CoreAudio_DefaultDevice.streamDescription.mBytesPerPacket,
474                                CoreAudio_DefaultDevice.streamDescription.mFramesPerPacket,
475                                CoreAudio_DefaultDevice.streamDescription.mBytesPerFrame,
476                                CoreAudio_DefaultDevice.streamDescription.mChannelsPerFrame,
477                                CoreAudio_DefaultDevice.streamDescription.mBitsPerChannel);
478     
479     CoreAudio_DefaultDevice.out_caps.wMid = 0xcafe;
480     CoreAudio_DefaultDevice.out_caps.wPid = 0x0001;
481     
482     CoreAudio_DefaultDevice.out_caps.vDriverVersion = 0x0001;
483     CoreAudio_DefaultDevice.out_caps.dwFormats = 0x00000000;
484     CoreAudio_DefaultDevice.out_caps.wReserved1 = 0;
485     CoreAudio_DefaultDevice.out_caps.dwSupport = WAVECAPS_VOLUME;
486     CoreAudio_DefaultDevice.out_caps.dwSupport |= WAVECAPS_LRVOLUME;
487     
488     CoreAudio_DefaultDevice.out_caps.wChannels = 2;
489     CoreAudio_DefaultDevice.out_caps.dwFormats|= WAVE_FORMAT_4S16;
490     
491     return TRUE;
492 }
493
494 /******************************************************************
495 *               CoreAudio_WaveInit
496 *
497 * Initialize CoreAudio_DefaultDevice
498 */
499 LONG CoreAudio_WaveInit(void)
500 {
501     OSStatus status;
502     UInt32 propertySize;
503     CHAR szPname[MAXPNAMELEN];
504     int i;
505     CFStringRef  messageThreadPortName;
506     CFMessagePortRef port_ReceiveInMessageThread;
507     int inputSampleRate;
508
509     TRACE("()\n");
510     
511     /* number of sound cards */
512     AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &propertySize, NULL);
513     propertySize /= sizeof(AudioDeviceID);
514     TRACE("sound cards : %lu\n", propertySize);
515     
516     /* Get the output device */
517     propertySize = sizeof(CoreAudio_DefaultDevice.outputDeviceID);
518     status = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &propertySize, &CoreAudio_DefaultDevice.outputDeviceID);
519     if (status) {
520         ERR("AudioHardwareGetProperty return %c%c%c%c for kAudioHardwarePropertyDefaultOutputDevice\n", (char) (status >> 24),
521                                                                                                 (char) (status >> 16),
522                                                                                                 (char) (status >> 8),
523                                                                                                 (char) status);
524         return DRV_FAILURE;
525     }
526     if (CoreAudio_DefaultDevice.outputDeviceID == kAudioDeviceUnknown) {
527         ERR("AudioHardwareGetProperty: CoreAudio_DefaultDevice.outputDeviceID == kAudioDeviceUnknown\n");
528         return DRV_FAILURE;
529     }
530     
531     if ( ! CoreAudio_GetDevCaps() )
532         return DRV_FAILURE;
533     
534     CoreAudio_DefaultDevice.interface_name=HeapAlloc(GetProcessHeap(),0,strlen(CoreAudio_DefaultDevice.dev_name)+1);
535     sprintf(CoreAudio_DefaultDevice.interface_name, "%s", CoreAudio_DefaultDevice.dev_name);
536     
537     for (i = 0; i < MAX_WAVEOUTDRV; ++i)
538     {
539         WOutDev[i].state = WINE_WS_CLOSED;
540         WOutDev[i].cadev = &CoreAudio_DefaultDevice; 
541         WOutDev[i].woID = i;
542         
543         memset(&WOutDev[i].caps, 0, sizeof(WOutDev[i].caps));
544         
545         WOutDev[i].caps.wMid = 0xcafe;  /* Manufac ID */
546         WOutDev[i].caps.wPid = 0x0001;  /* Product ID */
547         snprintf(szPname, sizeof(szPname), "CoreAudio WaveOut %d", i);
548         MultiByteToWideChar(CP_ACP, 0, szPname, -1, WOutDev[i].caps.szPname, sizeof(WOutDev[i].caps.szPname)/sizeof(WCHAR));
549         snprintf(WOutDev[i].interface_name, sizeof(WOutDev[i].interface_name), "winecoreaudio: %d", i);
550         
551         WOutDev[i].caps.vDriverVersion = 0x0001;
552         WOutDev[i].caps.dwFormats = 0x00000000;
553         WOutDev[i].caps.dwSupport = WAVECAPS_VOLUME;
554         
555         WOutDev[i].caps.wChannels = 2;
556       /*  WOutDev[i].caps.dwSupport |= WAVECAPS_LRVOLUME; */ /* FIXME */
557         
558         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96M08;
559         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96S08;
560         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96M16;
561         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96S16;
562         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48M08;
563         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48S08;
564         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48M16;
565         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48S16;
566         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4M08;
567         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4S08; 
568         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4S16;
569         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4M16;
570         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2M08;
571         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2S08; 
572         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2M16;
573         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2S16;
574         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1M08;
575         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1S08;
576         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1M16;
577         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1S16;
578
579         WOutDev[i].lock = 0; /* initialize the mutex */
580     }
581
582     /* FIXME: implement sample rate conversion on input */
583     inputSampleRate = AudioUnit_GetInputDeviceSampleRate();
584
585     for (i = 0; i < MAX_WAVEINDRV; ++i)
586     {
587         memset(&WInDev[i], 0, sizeof(WInDev[i]));
588         WInDev[i].wiID = i;
589
590         /* Establish preconditions for widOpen */
591         WInDev[i].state = WINE_WS_CLOSED;
592         WInDev[i].lock = 0; /* initialize the mutex */
593
594         /* Fill in capabilities.  widGetDevCaps can be called at any time. */
595         WInDev[i].caps.wMid = 0xcafe;   /* Manufac ID */
596         WInDev[i].caps.wPid = 0x0001;   /* Product ID */
597         WInDev[i].caps.vDriverVersion = 0x0001;
598
599         snprintf(szPname, sizeof(szPname), "CoreAudio WaveIn %d", i);
600         MultiByteToWideChar(CP_ACP, 0, szPname, -1, WInDev[i].caps.szPname, sizeof(WInDev[i].caps.szPname)/sizeof(WCHAR));
601         snprintf(WInDev[i].interface_name, sizeof(WInDev[i].interface_name), "winecoreaudio in: %d", i);
602
603         if (inputSampleRate == 96000)
604         {
605             WInDev[i].caps.dwFormats |= WAVE_FORMAT_96M08;
606             WInDev[i].caps.dwFormats |= WAVE_FORMAT_96S08;
607             WInDev[i].caps.dwFormats |= WAVE_FORMAT_96M16;
608             WInDev[i].caps.dwFormats |= WAVE_FORMAT_96S16;
609         }
610         if (inputSampleRate == 48000)
611         {
612             WInDev[i].caps.dwFormats |= WAVE_FORMAT_48M08;
613             WInDev[i].caps.dwFormats |= WAVE_FORMAT_48S08;
614             WInDev[i].caps.dwFormats |= WAVE_FORMAT_48M16;
615             WInDev[i].caps.dwFormats |= WAVE_FORMAT_48S16;
616         }
617         if (inputSampleRate == 44100)
618         {
619             WInDev[i].caps.dwFormats |= WAVE_FORMAT_4M08;
620             WInDev[i].caps.dwFormats |= WAVE_FORMAT_4S08;
621             WInDev[i].caps.dwFormats |= WAVE_FORMAT_4M16;
622             WInDev[i].caps.dwFormats |= WAVE_FORMAT_4S16;
623         }
624         if (inputSampleRate == 22050)
625         {
626             WInDev[i].caps.dwFormats |= WAVE_FORMAT_2M08;
627             WInDev[i].caps.dwFormats |= WAVE_FORMAT_2S08;
628             WInDev[i].caps.dwFormats |= WAVE_FORMAT_2M16;
629             WInDev[i].caps.dwFormats |= WAVE_FORMAT_2S16;
630         }
631         if (inputSampleRate == 11025)
632         {
633             WInDev[i].caps.dwFormats |= WAVE_FORMAT_1M08;
634             WInDev[i].caps.dwFormats |= WAVE_FORMAT_1S08;
635             WInDev[i].caps.dwFormats |= WAVE_FORMAT_1M16;
636             WInDev[i].caps.dwFormats |= WAVE_FORMAT_1S16;
637         }
638
639         WInDev[i].caps.wChannels = 2;
640     }
641
642     /* create mach messages handler */
643     srandomdev();
644     messageThreadPortName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL,
645         CFSTR("WaveMessagePort.%d.%lu"), getpid(), (unsigned long)random());
646     if (!messageThreadPortName)
647     {
648         ERR("Can't create message thread port name\n");
649         return DRV_FAILURE;
650     }
651
652     port_ReceiveInMessageThread = CFMessagePortCreateLocal(kCFAllocatorDefault, messageThreadPortName,
653                                         &wodMessageHandler, NULL, NULL);
654     if (!port_ReceiveInMessageThread)
655     {
656         ERR("Can't create message thread local port\n");
657         CFRelease(messageThreadPortName);
658         return DRV_FAILURE;
659     }
660
661     Port_SendToMessageThread = CFMessagePortCreateRemote(kCFAllocatorDefault, messageThreadPortName);
662     CFRelease(messageThreadPortName);
663     if (!Port_SendToMessageThread)
664     {
665         ERR("Can't create port for sending to message thread\n");
666         CFRelease(port_ReceiveInMessageThread);
667         return DRV_FAILURE;
668     }
669
670     /* Cannot WAIT for any events because we are called from the loader (which has a lock on loading stuff) */
671     /* We might want to wait for this thread to be created -- but we cannot -- not here at least */
672     /* Instead track the thread so we can clean it up later */
673     if ( hThread )
674     {
675         ERR("Message thread already started -- expect problems\n");
676     }
677     hThread = CreateThread(NULL, 0, messageThread, (LPVOID)port_ReceiveInMessageThread, 0, NULL);
678     if ( !hThread )
679     {
680         ERR("Can't create message thread\n");
681         CFRelease(port_ReceiveInMessageThread);
682         CFRelease(Port_SendToMessageThread);
683         Port_SendToMessageThread = NULL;
684         return DRV_FAILURE;
685     }
686
687     /* The message thread is responsible for releasing port_ReceiveInMessageThread. */
688
689     return DRV_SUCCESS;
690 }
691
692 void CoreAudio_WaveRelease(void)
693 {
694     /* Stop CFRunLoop in messageThread */
695     TRACE("()\n");
696
697     CFMessagePortSendRequest(Port_SendToMessageThread, kStopLoopMessage, NULL, 0.0, 0.0, NULL, NULL);
698     CFRelease(Port_SendToMessageThread);
699     Port_SendToMessageThread = NULL;
700
701     /* Wait for the thread to finish and clean it up */
702     /* This rids us of any quick start/shutdown driver crashes */
703     WaitForSingleObject(hThread, INFINITE);
704     CloseHandle(hThread);
705     hThread = NULL;
706 }
707
708 /*======================================================================*
709 *                  Low level WAVE OUT implementation                    *
710 *======================================================================*/
711
712 /**************************************************************************
713 *                       wodNotifyClient                 [internal]
714 */
715 static DWORD wodNotifyClient(WINE_WAVEOUT* wwo, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
716 {
717     switch (wMsg) {
718         case WOM_OPEN:
719         case WOM_CLOSE:
720         case WOM_DONE:
721             if (wwo->wFlags != DCB_NULL &&
722                 !DriverCallback(wwo->waveDesc.dwCallback, wwo->wFlags,
723                                 (HDRVR)wwo->waveDesc.hWave, wMsg, wwo->waveDesc.dwInstance,
724                                 dwParam1, dwParam2))
725             {
726                 return MMSYSERR_ERROR;
727             }
728             break;
729         default:
730             return MMSYSERR_INVALPARAM;
731     }
732     return MMSYSERR_NOERROR;
733 }
734
735
736 /**************************************************************************
737 *                       wodGetDevCaps               [internal]
738 */
739 static DWORD wodGetDevCaps(WORD wDevID, LPWAVEOUTCAPSW lpCaps, DWORD dwSize)
740 {
741     TRACE("(%u, %p, %u);\n", wDevID, lpCaps, dwSize);
742     
743     if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
744     
745     if (wDevID >= MAX_WAVEOUTDRV)
746     {
747         TRACE("MAX_WAVOUTDRV reached !\n");
748         return MMSYSERR_BADDEVICEID;
749     }
750     
751     TRACE("dwSupport=(0x%x), dwFormats=(0x%x)\n", WOutDev[wDevID].caps.dwSupport, WOutDev[wDevID].caps.dwFormats);
752     memcpy(lpCaps, &WOutDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
753     return MMSYSERR_NOERROR;
754 }
755
756 /**************************************************************************
757 *                               wodOpen                         [internal]
758 */
759 static DWORD wodOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
760 {
761     WINE_WAVEOUT*       wwo;
762     DWORD retval;
763     DWORD               ret;
764     AudioStreamBasicDescription streamFormat;
765
766     TRACE("(%u, %p, %08x);\n", wDevID, lpDesc, dwFlags);
767     if (lpDesc == NULL)
768     {
769         WARN("Invalid Parameter !\n");
770         return MMSYSERR_INVALPARAM;
771     }
772     if (wDevID >= MAX_WAVEOUTDRV) {
773         TRACE("MAX_WAVOUTDRV reached !\n");
774         return MMSYSERR_BADDEVICEID;
775     }
776     
777     TRACE("Format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
778           lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
779           lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
780     
781     if (lpDesc->lpFormat->wFormatTag != WAVE_FORMAT_PCM ||
782         lpDesc->lpFormat->nChannels == 0 ||
783         lpDesc->lpFormat->nSamplesPerSec == 0
784          )
785     {
786         WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
787              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
788              lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
789         return WAVERR_BADFORMAT;
790     }
791     
792     if (dwFlags & WAVE_FORMAT_QUERY)
793     {
794         TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
795               lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
796               lpDesc->lpFormat->nSamplesPerSec);
797         return MMSYSERR_NOERROR;
798     }
799     
800     wwo = &WOutDev[wDevID];
801     if (!OSSpinLockTry(&wwo->lock))
802         return MMSYSERR_ALLOCATED;
803
804     if (wwo->state != WINE_WS_CLOSED)
805     {
806         OSSpinLockUnlock(&wwo->lock);
807         return MMSYSERR_ALLOCATED;
808     }
809
810     if (!AudioUnit_CreateDefaultAudioUnit((void *) wwo, &wwo->audioUnit))
811     {
812         ERR("CoreAudio_CreateDefaultAudioUnit(%p) failed\n", wwo);
813         OSSpinLockUnlock(&wwo->lock);
814         return MMSYSERR_ERROR;
815     }
816
817     if ((dwFlags & WAVE_DIRECTSOUND) && 
818         !(wwo->caps.dwSupport & WAVECAPS_DIRECTSOUND))
819         /* not supported, ignore it */
820         dwFlags &= ~WAVE_DIRECTSOUND;
821
822     streamFormat.mFormatID = kAudioFormatLinearPCM;
823     streamFormat.mFormatFlags = kLinearPCMFormatFlagIsPacked;
824     /* FIXME check for 32bits float -> kLinearPCMFormatFlagIsFloat */
825     if (lpDesc->lpFormat->wBitsPerSample != 8)
826         streamFormat.mFormatFlags |= kLinearPCMFormatFlagIsSignedInteger;
827 # ifdef WORDS_BIGENDIAN
828     streamFormat.mFormatFlags |= kLinearPCMFormatFlagIsBigEndian; /* FIXME Wave format is little endian */
829 # endif
830
831     streamFormat.mSampleRate = lpDesc->lpFormat->nSamplesPerSec;
832     streamFormat.mChannelsPerFrame = lpDesc->lpFormat->nChannels;       
833     streamFormat.mFramesPerPacket = 1;  
834     streamFormat.mBitsPerChannel = lpDesc->lpFormat->wBitsPerSample;
835     streamFormat.mBytesPerFrame = streamFormat.mBitsPerChannel * streamFormat.mChannelsPerFrame / 8;    
836     streamFormat.mBytesPerPacket = streamFormat.mBytesPerFrame * streamFormat.mFramesPerPacket;         
837
838     ret = AudioUnit_InitializeWithStreamDescription(wwo->audioUnit, &streamFormat);
839     if (!ret) 
840     {
841         AudioUnit_CloseAudioUnit(wwo->audioUnit);
842         OSSpinLockUnlock(&wwo->lock);
843         return WAVERR_BADFORMAT; /* FIXME return an error based on the OSStatus */
844     }
845     wwo->streamDescription = streamFormat;
846
847     ret = AudioOutputUnitStart(wwo->audioUnit);
848     if (ret)
849     {
850         ERR("AudioOutputUnitStart failed: %08x\n", ret);
851         AudioUnitUninitialize(wwo->audioUnit);
852         AudioUnit_CloseAudioUnit(wwo->audioUnit);
853         OSSpinLockUnlock(&wwo->lock);
854         return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
855     }
856
857     wwo->state = WINE_WS_STOPPED;
858
859     wwo->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
860
861     wwo->waveDesc = *lpDesc;
862     memcpy(&wwo->format,   lpDesc->lpFormat, sizeof(PCMWAVEFORMAT));
863
864     if (wwo->format.wBitsPerSample == 0) {
865         WARN("Resetting zeroed wBitsPerSample\n");
866         wwo->format.wBitsPerSample = 8 *
867             (wwo->format.wf.nAvgBytesPerSec /
868              wwo->format.wf.nSamplesPerSec) /
869             wwo->format.wf.nChannels;
870     }
871     
872     wwo->dwPlayedTotal = 0;
873     wwo->dwWrittenTotal = 0;
874
875     wwo->trace_on = TRACE_ON(wave);
876     wwo->warn_on  = WARN_ON(wave);
877     wwo->err_on   = ERR_ON(wave);
878
879     OSSpinLockUnlock(&wwo->lock);
880     
881     retval = wodNotifyClient(wwo, WOM_OPEN, 0L, 0L);
882     
883     return retval;
884 }
885
886 /**************************************************************************
887 *                               wodClose                        [internal]
888 */
889 static DWORD wodClose(WORD wDevID)
890 {
891     DWORD               ret = MMSYSERR_NOERROR;
892     WINE_WAVEOUT*       wwo;
893     
894     TRACE("(%u);\n", wDevID);
895     
896     if (wDevID >= MAX_WAVEOUTDRV)
897     {
898         WARN("bad device ID !\n");
899         return MMSYSERR_BADDEVICEID;
900     }
901     
902     wwo = &WOutDev[wDevID];
903     OSSpinLockLock(&wwo->lock);
904     if (wwo->lpQueuePtr)
905     {
906         WARN("buffers still playing !\n");
907         OSSpinLockUnlock(&wwo->lock);
908         ret = WAVERR_STILLPLAYING;
909     } else
910     {
911         OSStatus err;
912         /* sanity check: this should not happen since the device must have been reset before */
913         if (wwo->lpQueuePtr || wwo->lpPlayPtr) ERR("out of sync\n");
914         
915         wwo->state = WINE_WS_CLOSED; /* mark the device as closed */
916         
917         OSSpinLockUnlock(&wwo->lock);
918
919         err = AudioUnitUninitialize(wwo->audioUnit);
920         if (err) {
921             ERR("AudioUnitUninitialize return %c%c%c%c\n", (char) (err >> 24),
922                                                             (char) (err >> 16),
923                                                             (char) (err >> 8),
924                                                             (char) err);
925             return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
926         }
927         
928         if ( !AudioUnit_CloseAudioUnit(wwo->audioUnit) )
929         {
930             ERR("Can't close AudioUnit\n");
931             return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
932         }  
933         
934         ret = wodNotifyClient(wwo, WOM_CLOSE, 0L, 0L);
935     }
936     
937     return ret;
938 }
939
940 /**************************************************************************
941 *                               wodPrepare                      [internal]
942 */
943 static DWORD wodPrepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
944 {
945     TRACE("(%u, %p, %08x);\n", wDevID, lpWaveHdr, dwSize);
946     
947     if (wDevID >= MAX_WAVEOUTDRV) {
948         WARN("bad device ID !\n");
949         return MMSYSERR_BADDEVICEID;
950     }
951     
952     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
953         return WAVERR_STILLPLAYING;
954     
955     lpWaveHdr->dwFlags |= WHDR_PREPARED;
956     lpWaveHdr->dwFlags &= ~WHDR_DONE;
957
958     return MMSYSERR_NOERROR;
959 }
960
961 /**************************************************************************
962 *                               wodUnprepare                    [internal]
963 */
964 static DWORD wodUnprepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
965 {
966     TRACE("(%u, %p, %08x);\n", wDevID, lpWaveHdr, dwSize);
967     
968     if (wDevID >= MAX_WAVEOUTDRV) {
969         WARN("bad device ID !\n");
970         return MMSYSERR_BADDEVICEID;
971     }
972     
973     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
974         return WAVERR_STILLPLAYING;
975     
976     lpWaveHdr->dwFlags &= ~WHDR_PREPARED;
977     lpWaveHdr->dwFlags |= WHDR_DONE;
978    
979     return MMSYSERR_NOERROR;
980 }
981
982
983 /**************************************************************************
984 *                               wodHelper_CheckForLoopBegin             [internal]
985 *
986 * Check if the new waveheader is the beginning of a loop, and set up
987 * state if so.
988 * This is called with the WAVEOUT lock held.
989 * Call from AudioUnit IO thread can't use Wine debug channels.
990 */
991 static void wodHelper_CheckForLoopBegin(WINE_WAVEOUT* wwo)
992 {
993     LPWAVEHDR lpWaveHdr = wwo->lpPlayPtr;
994
995     if (lpWaveHdr->dwFlags & WHDR_BEGINLOOP)
996     {
997         if (wwo->lpLoopPtr)
998         {
999             if (wwo->warn_on)
1000                 fprintf(stderr, "warn:winecoreaudio:wodHelper_CheckForLoopBegin Already in a loop. Discarding loop on this header (%p)\n", lpWaveHdr);
1001         }
1002         else
1003         {
1004             if (wwo->trace_on)
1005                 fprintf(stderr, "trace:winecoreaudio:wodHelper_CheckForLoopBegin Starting loop (%dx) with %p\n", lpWaveHdr->dwLoops, lpWaveHdr);
1006
1007             wwo->lpLoopPtr = lpWaveHdr;
1008             /* Windows does not touch WAVEHDR.dwLoops,
1009                 * so we need to make an internal copy */
1010             wwo->dwLoops = lpWaveHdr->dwLoops;
1011         }
1012     }
1013 }
1014
1015
1016 /**************************************************************************
1017 *                               wodHelper_PlayPtrNext           [internal]
1018 *
1019 * Advance the play pointer to the next waveheader, looping if required.
1020 * This is called with the WAVEOUT lock held.
1021 * Call from AudioUnit IO thread can't use Wine debug channels.
1022 */
1023 static void wodHelper_PlayPtrNext(WINE_WAVEOUT* wwo)
1024 {
1025     BOOL didLoopBack = FALSE;
1026
1027     wwo->dwPartialOffset = 0;
1028     if ((wwo->lpPlayPtr->dwFlags & WHDR_ENDLOOP) && wwo->lpLoopPtr)
1029     {
1030         /* We're at the end of a loop, loop if required */
1031         if (wwo->dwLoops > 1)
1032         {
1033             wwo->dwLoops--;
1034             wwo->lpPlayPtr = wwo->lpLoopPtr;
1035             didLoopBack = TRUE;
1036         }
1037         else
1038         {
1039             wwo->lpLoopPtr = NULL;
1040         }
1041     }
1042     if (!didLoopBack)
1043     {
1044         /* We didn't loop back.  Advance to the next wave header */
1045         wwo->lpPlayPtr = wwo->lpPlayPtr->lpNext;
1046
1047         if (!wwo->lpPlayPtr)
1048             wwo->state = WINE_WS_STOPPED;
1049         else
1050             wodHelper_CheckForLoopBegin(wwo);
1051     }
1052 }
1053
1054 /* Send the "done" notification for each WAVEHDR in a list.  The list must be
1055  * free-standing.  It should not be part of a device's queue.
1056  * This function must be called with the WAVEOUT lock *not* held.  Furthermore,
1057  * it does not lock it, itself.  That's because the callback to the application
1058  * may prompt the application to operate on the device, and we don't want to
1059  * deadlock.
1060  */
1061 static void wodHelper_NotifyDoneForList(WINE_WAVEOUT* wwo, LPWAVEHDR lpWaveHdr)
1062 {
1063     while (lpWaveHdr)
1064     {
1065         LPWAVEHDR lpNext = lpWaveHdr->lpNext;
1066
1067         lpWaveHdr->lpNext = NULL;
1068         lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1069         lpWaveHdr->dwFlags |= WHDR_DONE;
1070         wodNotifyClient(wwo, WOM_DONE, (DWORD)lpWaveHdr, 0);
1071
1072         lpWaveHdr = lpNext;
1073     }
1074 }
1075
1076 /* if force is TRUE then notify the client that all the headers were completed
1077  */
1078 static void wodHelper_NotifyCompletions(WINE_WAVEOUT* wwo, BOOL force)
1079 {
1080     LPWAVEHDR lpFirstDoneWaveHdr = NULL;
1081
1082     OSSpinLockLock(&wwo->lock);
1083
1084     /* First, excise all of the done headers from the queue into
1085      * a free-standing list. */
1086     if (force)
1087     {
1088         lpFirstDoneWaveHdr = wwo->lpQueuePtr;
1089         wwo->lpQueuePtr = NULL;
1090     }
1091     else
1092     {
1093         LPWAVEHDR lpWaveHdr;
1094         LPWAVEHDR lpLastDoneWaveHdr = NULL;
1095
1096         /* Start from lpQueuePtr and keep notifying until:
1097             * - we hit an unwritten wavehdr
1098             * - we hit the beginning of a running loop
1099             * - we hit a wavehdr which hasn't finished playing
1100             */
1101         for (
1102             lpWaveHdr = wwo->lpQueuePtr;
1103             lpWaveHdr &&
1104                 lpWaveHdr != wwo->lpPlayPtr &&
1105                 lpWaveHdr != wwo->lpLoopPtr;
1106             lpWaveHdr = lpWaveHdr->lpNext
1107             )
1108         {
1109             if (!lpFirstDoneWaveHdr)
1110                 lpFirstDoneWaveHdr = lpWaveHdr;
1111             lpLastDoneWaveHdr = lpWaveHdr;
1112         }
1113
1114         if (lpLastDoneWaveHdr)
1115         {
1116             wwo->lpQueuePtr = lpLastDoneWaveHdr->lpNext;
1117             lpLastDoneWaveHdr->lpNext = NULL;
1118         }
1119     }
1120     
1121     OSSpinLockUnlock(&wwo->lock);
1122
1123     /* Now, send the "done" notification for each header in our list. */
1124     wodHelper_NotifyDoneForList(wwo, lpFirstDoneWaveHdr);
1125 }
1126
1127
1128 /**************************************************************************
1129 *                               wodWrite                        [internal]
1130
1131 */
1132 static DWORD wodWrite(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1133 {
1134     LPWAVEHDR*wh;
1135     WINE_WAVEOUT *wwo;
1136     
1137     TRACE("(%u, %p, %08X);\n", wDevID, lpWaveHdr, dwSize);
1138     
1139     /* first, do the sanity checks... */
1140     if (wDevID >= MAX_WAVEOUTDRV)
1141     {
1142         WARN("bad dev ID !\n");
1143         return MMSYSERR_BADDEVICEID;
1144     }
1145     
1146     wwo = &WOutDev[wDevID];
1147     
1148     if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
1149     {
1150         TRACE("unprepared\n");
1151         return WAVERR_UNPREPARED;
1152     }
1153     
1154     if (lpWaveHdr->dwFlags & WHDR_INQUEUE) 
1155     {
1156         TRACE("still playing\n");
1157         return WAVERR_STILLPLAYING;
1158     }
1159     
1160     lpWaveHdr->dwFlags &= ~WHDR_DONE;
1161     lpWaveHdr->dwFlags |= WHDR_INQUEUE;
1162     lpWaveHdr->lpNext = 0;
1163
1164     OSSpinLockLock(&wwo->lock);
1165     /* insert buffer at the end of queue */
1166     for (wh = &(wwo->lpQueuePtr); *wh; wh = &((*wh)->lpNext))
1167         /* Do nothing */;
1168     *wh = lpWaveHdr;
1169     
1170     if (!wwo->lpPlayPtr)
1171     {
1172         wwo->lpPlayPtr = lpWaveHdr;
1173
1174         if (wwo->state == WINE_WS_STOPPED)
1175             wwo->state = WINE_WS_PLAYING;
1176
1177         wodHelper_CheckForLoopBegin(wwo);
1178
1179         wwo->dwPartialOffset = 0;
1180     }
1181     OSSpinLockUnlock(&wwo->lock);
1182
1183     return MMSYSERR_NOERROR;
1184 }
1185
1186 /**************************************************************************
1187 *                       wodPause                                [internal]
1188 */
1189 static DWORD wodPause(WORD wDevID)
1190 {
1191     OSStatus status;
1192
1193     TRACE("(%u);!\n", wDevID);
1194     
1195     if (wDevID >= MAX_WAVEOUTDRV)
1196     {
1197         WARN("bad device ID !\n");
1198         return MMSYSERR_BADDEVICEID;
1199     }
1200
1201     /* The order of the following operations is important since we can't hold
1202      * the mutex while we make an Audio Unit call.  Stop the Audio Unit before
1203      * setting the PAUSED state.  In wodRestart, the order is reversed.  This
1204      * guarantees that we can't get into a situation where the state is
1205      * PLAYING or STOPPED but the Audio Unit isn't running.  Although we can
1206      * be in PAUSED state with the Audio Unit still running, that's harmless
1207      * because the render callback will just produce silence.
1208      */
1209     status = AudioOutputUnitStop(WOutDev[wDevID].audioUnit);
1210     if (status) {
1211         WARN("AudioOutputUnitStop return %c%c%c%c\n",
1212              (char) (status >> 24), (char) (status >> 16), (char) (status >> 8), (char) status);
1213     }
1214
1215     OSSpinLockLock(&WOutDev[wDevID].lock);
1216     if (WOutDev[wDevID].state == WINE_WS_PLAYING || WOutDev[wDevID].state == WINE_WS_STOPPED)
1217         WOutDev[wDevID].state = WINE_WS_PAUSED;
1218     OSSpinLockUnlock(&WOutDev[wDevID].lock);
1219
1220     return MMSYSERR_NOERROR;
1221 }
1222
1223 /**************************************************************************
1224 *                       wodRestart                              [internal]
1225 */
1226 static DWORD wodRestart(WORD wDevID)
1227 {
1228     OSStatus status;
1229
1230     TRACE("(%u);\n", wDevID);
1231     
1232     if (wDevID >= MAX_WAVEOUTDRV )
1233     {
1234         WARN("bad device ID !\n");
1235         return MMSYSERR_BADDEVICEID;
1236     }
1237
1238     /* The order of the following operations is important since we can't hold
1239      * the mutex while we make an Audio Unit call.  Set the PLAYING/STOPPED
1240      * state before starting the Audio Unit.  In wodPause, the order is
1241      * reversed.  This guarantees that we can't get into a situation where
1242      * the state is PLAYING or STOPPED but the Audio Unit isn't running.
1243      * Although we can be in PAUSED state with the Audio Unit still running,
1244      * that's harmless because the render callback will just produce silence.
1245      */
1246     OSSpinLockLock(&WOutDev[wDevID].lock);
1247     if (WOutDev[wDevID].state == WINE_WS_PAUSED)
1248     {
1249         if (WOutDev[wDevID].lpPlayPtr)
1250             WOutDev[wDevID].state = WINE_WS_PLAYING;
1251         else
1252             WOutDev[wDevID].state = WINE_WS_STOPPED;
1253     }
1254     OSSpinLockUnlock(&WOutDev[wDevID].lock);
1255
1256     status = AudioOutputUnitStart(WOutDev[wDevID].audioUnit);
1257     if (status) {
1258         ERR("AudioOutputUnitStart return %c%c%c%c\n",
1259             (char) (status >> 24), (char) (status >> 16), (char) (status >> 8), (char) status);
1260         return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1261     }
1262
1263     return MMSYSERR_NOERROR;
1264 }
1265
1266 /**************************************************************************
1267 *                       wodReset                                [internal]
1268 */
1269 static DWORD wodReset(WORD wDevID)
1270 {
1271     WINE_WAVEOUT* wwo;
1272     OSStatus status;
1273     LPWAVEHDR lpSavedQueuePtr;
1274
1275     TRACE("(%u);\n", wDevID);
1276
1277     if (wDevID >= MAX_WAVEOUTDRV)
1278     {
1279         WARN("bad device ID !\n");
1280         return MMSYSERR_BADDEVICEID;
1281     }
1282
1283     wwo = &WOutDev[wDevID];
1284
1285     OSSpinLockLock(&wwo->lock);
1286
1287     if (wwo->state == WINE_WS_CLOSED)
1288     {
1289         OSSpinLockUnlock(&wwo->lock);
1290         WARN("resetting a closed device\n");
1291         return MMSYSERR_INVALHANDLE;
1292     }
1293
1294     lpSavedQueuePtr = wwo->lpQueuePtr;
1295     wwo->lpPlayPtr = wwo->lpQueuePtr = wwo->lpLoopPtr = NULL;
1296     wwo->state = WINE_WS_STOPPED;
1297     wwo->dwPlayedTotal = wwo->dwWrittenTotal = 0;
1298
1299     wwo->dwPartialOffset = 0;        /* Clear partial wavehdr */
1300
1301     OSSpinLockUnlock(&wwo->lock);
1302
1303     status = AudioOutputUnitStart(wwo->audioUnit);
1304
1305     if (status) {
1306         ERR( "AudioOutputUnitStart return %c%c%c%c\n",
1307              (char) (status >> 24), (char) (status >> 16), (char) (status >> 8), (char) status);
1308         return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1309     }
1310
1311     /* Now, send the "done" notification for each header in our list. */
1312     /* Do this last so the reset operation is effectively complete before the
1313      * app does whatever it's going to do in response to these notifications. */
1314     wodHelper_NotifyDoneForList(wwo, lpSavedQueuePtr);
1315
1316     return MMSYSERR_NOERROR;
1317 }
1318
1319 /**************************************************************************
1320 *                               wodGetPosition                  [internal]
1321 */
1322 static DWORD wodGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
1323 {
1324     DWORD               val;
1325     WINE_WAVEOUT*       wwo;
1326
1327     TRACE("(%u, %p, %u);\n", wDevID, lpTime, uSize);
1328     
1329     if (wDevID >= MAX_WAVEOUTDRV)
1330     {
1331         WARN("bad device ID !\n");
1332         return MMSYSERR_BADDEVICEID;
1333     }
1334     
1335     /* if null pointer to time structure return error */
1336     if (lpTime == NULL) return MMSYSERR_INVALPARAM;
1337     
1338     wwo = &WOutDev[wDevID];
1339     
1340     OSSpinLockLock(&WOutDev[wDevID].lock);
1341     val = wwo->dwPlayedTotal;
1342     OSSpinLockUnlock(&WOutDev[wDevID].lock);
1343     
1344     return bytes_to_mmtime(lpTime, val, &wwo->format);
1345 }
1346
1347 /**************************************************************************
1348 *                               wodGetVolume                    [internal]
1349 */
1350 static DWORD wodGetVolume(WORD wDevID, LPDWORD lpdwVol)
1351 {
1352     float left;
1353     float right;
1354     
1355     if (wDevID >= MAX_WAVEOUTDRV)
1356     {
1357         WARN("bad device ID !\n");
1358         return MMSYSERR_BADDEVICEID;
1359     }    
1360     
1361     TRACE("(%u, %p);\n", wDevID, lpdwVol);
1362
1363     AudioUnit_GetVolume(WOutDev[wDevID].audioUnit, &left, &right); 
1364
1365     *lpdwVol = ((WORD) left * 0xFFFFl) + (((WORD) right * 0xFFFFl) << 16);
1366     
1367     return MMSYSERR_NOERROR;
1368 }
1369
1370 /**************************************************************************
1371 *                               wodSetVolume                    [internal]
1372 */
1373 static DWORD wodSetVolume(WORD wDevID, DWORD dwParam)
1374 {
1375     float left;
1376     float right;
1377     
1378     if (wDevID >= MAX_WAVEOUTDRV)
1379     {
1380         WARN("bad device ID !\n");
1381         return MMSYSERR_BADDEVICEID;
1382     }
1383
1384     left  = LOWORD(dwParam) / 65535.0f;
1385     right = HIWORD(dwParam) / 65535.0f;
1386     
1387     TRACE("(%u, %08x);\n", wDevID, dwParam);
1388
1389     AudioUnit_SetVolume(WOutDev[wDevID].audioUnit, left, right); 
1390
1391     return MMSYSERR_NOERROR;
1392 }
1393
1394 /**************************************************************************
1395 *                               wodGetNumDevs                   [internal]
1396 */
1397 static DWORD wodGetNumDevs(void)
1398 {
1399     TRACE("\n");
1400     return MAX_WAVEOUTDRV;
1401 }
1402
1403 /**************************************************************************
1404 *                              wodDevInterfaceSize             [internal]
1405 */
1406 static DWORD wodDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
1407 {
1408     TRACE("(%u, %p)\n", wDevID, dwParam1);
1409     
1410     *dwParam1 = MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].cadev->interface_name, -1,
1411                                     NULL, 0 ) * sizeof(WCHAR);
1412     return MMSYSERR_NOERROR;
1413 }
1414
1415 /**************************************************************************
1416 *                              wodDevInterface                 [internal]
1417 */
1418 static DWORD wodDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
1419 {
1420     TRACE("\n");
1421     if (dwParam2 >= MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].cadev->interface_name, -1,
1422                                         NULL, 0 ) * sizeof(WCHAR))
1423     {
1424         MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].cadev->interface_name, -1,
1425                             dwParam1, dwParam2 / sizeof(WCHAR));
1426         return MMSYSERR_NOERROR;
1427     }
1428     return MMSYSERR_INVALPARAM;
1429 }
1430
1431 /**************************************************************************
1432  *                              widDsCreate                     [internal]
1433  */
1434 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
1435 {
1436     TRACE("(%d,%p)\n",wDevID,drv);
1437
1438     FIXME("DirectSound not implemented\n");
1439     FIXME("The (slower) DirectSound HEL mode will be used instead.\n");
1440     return MMSYSERR_NOTSUPPORTED;
1441 }
1442
1443 /**************************************************************************
1444 *                              wodDsDesc                 [internal]
1445 */
1446 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc)
1447 {
1448     /* The DirectSound HEL will automatically wrap a non-DirectSound-capable
1449      * driver in a DirectSound adaptor, thus allowing the driver to be used by
1450      * DirectSound clients.  However, it only does this if we respond
1451      * successfully to the DRV_QUERYDSOUNDDESC message.  It's enough to fill in
1452      * the driver and device names of the description output parameter. */
1453     *desc = WOutDev[wDevID].cadev->ds_desc;
1454     return MMSYSERR_NOERROR;
1455 }
1456
1457 /**************************************************************************
1458 *                               wodMessage (WINECOREAUDIO.7)
1459 */
1460 DWORD WINAPI CoreAudio_wodMessage(UINT wDevID, UINT wMsg, DWORD dwUser, 
1461                                   DWORD dwParam1, DWORD dwParam2)
1462 {
1463     TRACE("(%u, %s, %08x, %08x, %08x);\n",
1464           wDevID, getMessage(wMsg), dwUser, dwParam1, dwParam2);
1465     
1466     switch (wMsg) {
1467         case DRVM_INIT:
1468         case DRVM_EXIT:
1469         case DRVM_ENABLE:
1470         case DRVM_DISABLE:
1471             
1472             /* FIXME: Pretend this is supported */
1473             return 0;
1474         case WODM_OPEN:         return wodOpen(wDevID, (LPWAVEOPENDESC) dwParam1, dwParam2);          
1475         case WODM_CLOSE:        return wodClose(wDevID);
1476         case WODM_WRITE:        return wodWrite(wDevID, (LPWAVEHDR) dwParam1, dwParam2);
1477         case WODM_PAUSE:        return wodPause(wDevID);  
1478         case WODM_GETPOS:       return wodGetPosition(wDevID, (LPMMTIME) dwParam1, dwParam2);
1479         case WODM_BREAKLOOP:    return MMSYSERR_NOTSUPPORTED;
1480         case WODM_PREPARE:      return wodPrepare(wDevID, (LPWAVEHDR)dwParam1, dwParam2);
1481         case WODM_UNPREPARE:    return wodUnprepare(wDevID, (LPWAVEHDR)dwParam1, dwParam2);
1482             
1483         case WODM_GETDEVCAPS:   return wodGetDevCaps(wDevID, (LPWAVEOUTCAPSW) dwParam1, dwParam2);
1484         case WODM_GETNUMDEVS:   return wodGetNumDevs();  
1485             
1486         case WODM_GETPITCH:         
1487         case WODM_SETPITCH:        
1488         case WODM_GETPLAYBACKRATE:      
1489         case WODM_SETPLAYBACKRATE:      return MMSYSERR_NOTSUPPORTED;
1490         case WODM_GETVOLUME:    return wodGetVolume(wDevID, (LPDWORD)dwParam1);
1491         case WODM_SETVOLUME:    return wodSetVolume(wDevID, dwParam1);
1492         case WODM_RESTART:      return wodRestart(wDevID);
1493         case WODM_RESET:        return wodReset(wDevID);
1494             
1495         case DRV_QUERYDEVICEINTERFACESIZE:  return wodDevInterfaceSize (wDevID, (LPDWORD)dwParam1);
1496         case DRV_QUERYDEVICEINTERFACE:      return wodDevInterface (wDevID, (PWCHAR)dwParam1, dwParam2);
1497         case DRV_QUERYDSOUNDIFACE:  return wodDsCreate  (wDevID, (PIDSDRIVER*)dwParam1);
1498         case DRV_QUERYDSOUNDDESC:   return wodDsDesc    (wDevID, (PDSDRIVERDESC)dwParam1);
1499             
1500         default:
1501             FIXME("unknown message %d!\n", wMsg);
1502     }
1503     
1504     return MMSYSERR_NOTSUPPORTED;
1505 }
1506
1507 /*======================================================================*
1508 *                  Low level DSOUND implementation                      *
1509 *======================================================================*/
1510
1511 typedef struct IDsDriverImpl IDsDriverImpl;
1512 typedef struct IDsDriverBufferImpl IDsDriverBufferImpl;
1513
1514 struct IDsDriverImpl
1515 {
1516     /* IUnknown fields */
1517     const IDsDriverVtbl *lpVtbl;
1518     DWORD               ref;
1519     /* IDsDriverImpl fields */
1520     UINT                wDevID;
1521     IDsDriverBufferImpl*primary;
1522 };
1523
1524 struct IDsDriverBufferImpl
1525 {
1526     /* IUnknown fields */
1527     const IDsDriverBufferVtbl *lpVtbl;
1528     DWORD ref;
1529     /* IDsDriverBufferImpl fields */
1530     IDsDriverImpl* drv;
1531     DWORD buflen;
1532 };
1533
1534
1535 /*
1536     CoreAudio IO threaded callback,
1537     we can't call Wine debug channels, critical section or anything using NtCurrentTeb here.
1538 */
1539 OSStatus CoreAudio_woAudioUnitIOProc(void *inRefCon, 
1540                                      AudioUnitRenderActionFlags *ioActionFlags, 
1541                                      const AudioTimeStamp *inTimeStamp, 
1542                                      UInt32 inBusNumber, 
1543                                      UInt32 inNumberFrames, 
1544                                      AudioBufferList *ioData)
1545 {
1546     UInt32 buffer;
1547     WINE_WAVEOUT *wwo = (WINE_WAVEOUT *) inRefCon;
1548     int needNotify = 0;
1549
1550     unsigned int dataNeeded = ioData->mBuffers[0].mDataByteSize;
1551     unsigned int dataProvided = 0;
1552
1553     OSSpinLockLock(&wwo->lock);
1554
1555     while (dataNeeded > 0 && wwo->state == WINE_WS_PLAYING && wwo->lpPlayPtr)
1556     {
1557         unsigned int available = wwo->lpPlayPtr->dwBufferLength - wwo->dwPartialOffset;
1558         unsigned int toCopy;
1559
1560         if (available >= dataNeeded)
1561             toCopy = dataNeeded;
1562         else
1563             toCopy = available;
1564
1565         if (toCopy > 0)
1566         {
1567             memcpy((char*)ioData->mBuffers[0].mData + dataProvided,
1568                 wwo->lpPlayPtr->lpData + wwo->dwPartialOffset, toCopy);
1569             wwo->dwPartialOffset += toCopy;
1570             wwo->dwPlayedTotal += toCopy;
1571             dataProvided += toCopy;
1572             dataNeeded -= toCopy;
1573             available -= toCopy;
1574         }
1575
1576         if (available == 0)
1577         {
1578             wodHelper_PlayPtrNext(wwo);
1579             needNotify = 1;
1580         }
1581     }
1582     ioData->mBuffers[0].mDataByteSize = dataProvided;
1583
1584     OSSpinLockUnlock(&wwo->lock);
1585
1586     /* We can't provide any more wave data.  Fill the rest with silence. */
1587     if (dataNeeded > 0)
1588     {
1589         if (!dataProvided)
1590             *ioActionFlags |= kAudioUnitRenderAction_OutputIsSilence;
1591         memset((char*)ioData->mBuffers[0].mData + dataProvided, 0, dataNeeded);
1592         dataProvided += dataNeeded;
1593         dataNeeded = 0;
1594     }
1595
1596     /* We only fill buffer 0.  Set any others that might be requested to 0. */
1597     for (buffer = 1; buffer < ioData->mNumberBuffers; buffer++)
1598     {
1599         memset(ioData->mBuffers[buffer].mData, 0, ioData->mBuffers[buffer].mDataByteSize);
1600     }
1601
1602     if (needNotify) wodSendNotifyCompletionsMessage(wwo);
1603     return noErr;
1604 }
1605
1606
1607 /*======================================================================*
1608  *                  Low level WAVE IN implementation                    *
1609  *======================================================================*/
1610
1611 /**************************************************************************
1612  *                      widNotifyClient                 [internal]
1613  */
1614 static DWORD widNotifyClient(WINE_WAVEIN* wwi, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
1615 {
1616     TRACE("wMsg = 0x%04x dwParm1 = %04X dwParam2 = %04X\n", wMsg, dwParam1, dwParam2);
1617
1618     switch (wMsg)
1619     {
1620         case WIM_OPEN:
1621         case WIM_CLOSE:
1622         case WIM_DATA:
1623             if (wwi->wFlags != DCB_NULL &&
1624                 !DriverCallback(wwi->waveDesc.dwCallback, wwi->wFlags,
1625                                 (HDRVR)wwi->waveDesc.hWave, wMsg, wwi->waveDesc.dwInstance,
1626                                 dwParam1, dwParam2))
1627             {
1628                 WARN("can't notify client !\n");
1629                 return MMSYSERR_ERROR;
1630             }
1631             break;
1632         default:
1633             FIXME("Unknown callback message %u\n", wMsg);
1634             return MMSYSERR_INVALPARAM;
1635     }
1636     return MMSYSERR_NOERROR;
1637 }
1638
1639
1640 /**************************************************************************
1641  *                      widHelper_NotifyCompletions              [internal]
1642  */
1643 static void widHelper_NotifyCompletions(WINE_WAVEIN* wwi)
1644 {
1645     LPWAVEHDR       lpWaveHdr;
1646     LPWAVEHDR       lpFirstDoneWaveHdr = NULL;
1647     LPWAVEHDR       lpLastDoneWaveHdr = NULL;
1648
1649     OSSpinLockLock(&wwi->lock);
1650
1651     /* First, excise all of the done headers from the queue into
1652      * a free-standing list. */
1653
1654     /* Start from lpQueuePtr and keep notifying until:
1655         * - we hit an unfilled wavehdr
1656         * - we hit the end of the list
1657         */
1658     for (
1659         lpWaveHdr = wwi->lpQueuePtr;
1660         lpWaveHdr &&
1661             lpWaveHdr->dwBytesRecorded >= lpWaveHdr->dwBufferLength;
1662         lpWaveHdr = lpWaveHdr->lpNext
1663         )
1664     {
1665         if (!lpFirstDoneWaveHdr)
1666             lpFirstDoneWaveHdr = lpWaveHdr;
1667         lpLastDoneWaveHdr = lpWaveHdr;
1668     }
1669
1670     if (lpLastDoneWaveHdr)
1671     {
1672         wwi->lpQueuePtr = lpLastDoneWaveHdr->lpNext;
1673         lpLastDoneWaveHdr->lpNext = NULL;
1674     }
1675
1676     OSSpinLockUnlock(&wwi->lock);
1677
1678     /* Now, send the "done" notification for each header in our list. */
1679     lpWaveHdr = lpFirstDoneWaveHdr;
1680     while (lpWaveHdr)
1681     {
1682         LPWAVEHDR lpNext = lpWaveHdr->lpNext;
1683
1684         lpWaveHdr->lpNext = NULL;
1685         lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1686         lpWaveHdr->dwFlags |= WHDR_DONE;
1687         widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
1688
1689         lpWaveHdr = lpNext;
1690     }
1691 }
1692
1693
1694 /**************************************************************************
1695  *                      widGetDevCaps                           [internal]
1696  */
1697 static DWORD widGetDevCaps(WORD wDevID, LPWAVEINCAPSW lpCaps, DWORD dwSize)
1698 {
1699     TRACE("(%u, %p, %u);\n", wDevID, lpCaps, dwSize);
1700
1701     if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
1702
1703     if (wDevID >= MAX_WAVEINDRV)
1704     {
1705         TRACE("MAX_WAVEINDRV reached !\n");
1706         return MMSYSERR_BADDEVICEID;
1707     }
1708
1709     memcpy(lpCaps, &WInDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
1710     return MMSYSERR_NOERROR;
1711 }
1712
1713
1714 /**************************************************************************
1715  *                    widHelper_DestroyAudioBufferList           [internal]
1716  * Convenience function to dispose of our audio buffers
1717  */
1718 static void widHelper_DestroyAudioBufferList(AudioBufferList* list)
1719 {
1720     if (list)
1721     {
1722         UInt32 i;
1723         for (i = 0; i < list->mNumberBuffers; i++)
1724         {
1725             if (list->mBuffers[i].mData)
1726                 HeapFree(GetProcessHeap(), 0, list->mBuffers[i].mData);
1727         }
1728         HeapFree(GetProcessHeap(), 0, list);
1729     }
1730 }
1731
1732
1733 #define AUDIOBUFFERLISTSIZE(numBuffers) (offsetof(AudioBufferList, mBuffers) + (numBuffers) * sizeof(AudioBuffer))
1734
1735 /**************************************************************************
1736  *                    widHelper_AllocateAudioBufferList          [internal]
1737  * Convenience function to allocate our audio buffers
1738  */
1739 static AudioBufferList* widHelper_AllocateAudioBufferList(UInt32 numChannels, UInt32 bitsPerChannel, UInt32 bufferFrames, BOOL interleaved)
1740 {
1741     UInt32                      numBuffers;
1742     UInt32                      channelsPerFrame;
1743     UInt32                      bytesPerFrame;
1744     UInt32                      bytesPerBuffer;
1745     AudioBufferList*            list;
1746     UInt32                      i;
1747
1748     if (interleaved)
1749     {
1750         /* For interleaved audio, we allocate one buffer for all channels. */
1751         numBuffers = 1;
1752         channelsPerFrame = numChannels;
1753     }
1754     else
1755     {
1756         numBuffers = numChannels;
1757         channelsPerFrame = 1;
1758     }
1759
1760     bytesPerFrame = bitsPerChannel * channelsPerFrame / 8;
1761     bytesPerBuffer = bytesPerFrame * bufferFrames;
1762
1763     list = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, AUDIOBUFFERLISTSIZE(numBuffers));
1764     if (list == NULL)
1765         return NULL;
1766
1767     list->mNumberBuffers = numBuffers;
1768     for (i = 0; i < numBuffers; ++i)
1769     {
1770         list->mBuffers[i].mNumberChannels = channelsPerFrame;
1771         list->mBuffers[i].mDataByteSize = bytesPerBuffer;
1772         list->mBuffers[i].mData = HeapAlloc(GetProcessHeap(), 0, bytesPerBuffer);
1773         if (list->mBuffers[i].mData == NULL)
1774         {
1775             widHelper_DestroyAudioBufferList(list);
1776             return NULL;
1777         }
1778     }
1779     return list;
1780 }
1781
1782
1783 /**************************************************************************
1784  *                              widOpen                         [internal]
1785  */
1786 static DWORD widOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
1787 {
1788     WINE_WAVEIN*    wwi;
1789     UInt32          frameCount;
1790
1791     TRACE("(%u, %p, %08X);\n", wDevID, lpDesc, dwFlags);
1792     if (lpDesc == NULL)
1793     {
1794         WARN("Invalid Parameter !\n");
1795         return MMSYSERR_INVALPARAM;
1796     }
1797     if (wDevID >= MAX_WAVEINDRV)
1798     {
1799         TRACE ("MAX_WAVEINDRV reached !\n");
1800         return MMSYSERR_BADDEVICEID;
1801     }
1802
1803     TRACE("Format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
1804           lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1805           lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
1806
1807     if (lpDesc->lpFormat->wFormatTag != WAVE_FORMAT_PCM ||
1808         lpDesc->lpFormat->nChannels == 0 ||
1809         lpDesc->lpFormat->nSamplesPerSec == 0 ||
1810         lpDesc->lpFormat->nSamplesPerSec != AudioUnit_GetInputDeviceSampleRate()
1811         )
1812     {
1813         WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
1814              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1815              lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
1816         return WAVERR_BADFORMAT;
1817     }
1818
1819     if (dwFlags & WAVE_FORMAT_QUERY)
1820     {
1821         TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
1822               lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1823               lpDesc->lpFormat->nSamplesPerSec);
1824         return MMSYSERR_NOERROR;
1825     }
1826
1827     wwi = &WInDev[wDevID];
1828     if (!OSSpinLockTry(&wwi->lock))
1829         return MMSYSERR_ALLOCATED;
1830
1831     if (wwi->state != WINE_WS_CLOSED)
1832     {
1833         OSSpinLockUnlock(&wwi->lock);
1834         return MMSYSERR_ALLOCATED;
1835     }
1836
1837     wwi->state = WINE_WS_STOPPED;
1838     wwi->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
1839
1840     wwi->waveDesc = *lpDesc;
1841     memcpy(&wwi->format,   lpDesc->lpFormat,    sizeof(PCMWAVEFORMAT));
1842
1843     if (wwi->format.wBitsPerSample == 0)
1844     {
1845         WARN("Resetting zeroed wBitsPerSample\n");
1846         wwi->format.wBitsPerSample = 8 *
1847             (wwi->format.wf.nAvgBytesPerSec /
1848             wwi->format.wf.nSamplesPerSec) /
1849             wwi->format.wf.nChannels;
1850     }
1851
1852     wwi->dwTotalRecorded = 0;
1853
1854     wwi->trace_on = TRACE_ON(wave);
1855     wwi->warn_on  = WARN_ON(wave);
1856     wwi->err_on   = ERR_ON(wave);
1857
1858     if (!AudioUnit_CreateInputUnit(wwi, &wwi->audioUnit,
1859         wwi->format.wf.nChannels, wwi->format.wf.nSamplesPerSec,
1860         wwi->format.wBitsPerSample, &frameCount))
1861     {
1862         ERR("AudioUnit_CreateInputUnit failed\n");
1863         OSSpinLockUnlock(&wwi->lock);
1864         return MMSYSERR_ERROR;
1865     }
1866
1867     /* Allocate our audio buffers */
1868     wwi->bufferList = widHelper_AllocateAudioBufferList(wwi->format.wf.nChannels,
1869         wwi->format.wBitsPerSample, frameCount, TRUE);
1870     if (wwi->bufferList == NULL)
1871     {
1872         ERR("Failed to allocate buffer list\n");
1873         AudioUnitUninitialize(wwi->audioUnit);
1874         AudioUnit_CloseAudioUnit(wwi->audioUnit);
1875         OSSpinLockUnlock(&wwi->lock);
1876         return MMSYSERR_NOMEM;
1877     }
1878
1879     /* Keep a copy of the buffer list structure (but not the buffers themselves)
1880      * in case AudioUnitRender clobbers the original, as it won't to do. */
1881     wwi->bufferListCopy = HeapAlloc(GetProcessHeap(), 0, AUDIOBUFFERLISTSIZE(wwi->bufferList->mNumberBuffers));
1882     if (wwi->bufferListCopy == NULL)
1883     {
1884         ERR("Failed to allocate buffer list copy\n");
1885         widHelper_DestroyAudioBufferList(wwi->bufferList);
1886         AudioUnitUninitialize(wwi->audioUnit);
1887         AudioUnit_CloseAudioUnit(wwi->audioUnit);
1888         OSSpinLockUnlock(&wwi->lock);
1889         return MMSYSERR_NOMEM;
1890     }
1891     memcpy(wwi->bufferListCopy, wwi->bufferList, AUDIOBUFFERLISTSIZE(wwi->bufferList->mNumberBuffers));
1892
1893     OSSpinLockUnlock(&wwi->lock);
1894
1895     return widNotifyClient(wwi, WIM_OPEN, 0L, 0L);
1896 }
1897
1898
1899 /**************************************************************************
1900  *                              widClose                        [internal]
1901  */
1902 static DWORD widClose(WORD wDevID)
1903 {
1904     DWORD           ret = MMSYSERR_NOERROR;
1905     WINE_WAVEIN*    wwi;
1906
1907     TRACE("(%u);\n", wDevID);
1908
1909     if (wDevID >= MAX_WAVEINDRV)
1910     {
1911         WARN("bad device ID !\n");
1912         return MMSYSERR_BADDEVICEID;
1913     }
1914
1915     wwi = &WInDev[wDevID];
1916     OSSpinLockLock(&wwi->lock);
1917     if (wwi->state == WINE_WS_CLOSED)
1918     {
1919         WARN("Device already closed.\n");
1920         ret = MMSYSERR_INVALHANDLE;
1921     }
1922     else if (wwi->lpQueuePtr)
1923     {
1924         WARN("Buffers in queue.\n");
1925         ret = WAVERR_STILLPLAYING;
1926     }
1927     else
1928     {
1929         wwi->state = WINE_WS_CLOSED;
1930     }
1931
1932     OSSpinLockUnlock(&wwi->lock);
1933
1934     if (ret == MMSYSERR_NOERROR)
1935     {
1936         OSStatus err = AudioUnitUninitialize(wwi->audioUnit);
1937         if (err)
1938         {
1939             ERR("AudioUnitUninitialize return %c%c%c%c\n", (char) (err >> 24),
1940                                                            (char) (err >> 16),
1941                                                            (char) (err >> 8),
1942                                                            (char) err);
1943         }
1944
1945         if (!AudioUnit_CloseAudioUnit(wwi->audioUnit))
1946         {
1947             ERR("Can't close AudioUnit\n");
1948         }
1949
1950         /* Dellocate our audio buffers */
1951         widHelper_DestroyAudioBufferList(wwi->bufferList);
1952         wwi->bufferList = NULL;
1953         HeapFree(GetProcessHeap(), 0, wwi->bufferListCopy);
1954         wwi->bufferListCopy = NULL;
1955
1956         ret = widNotifyClient(wwi, WIM_CLOSE, 0L, 0L);
1957     }
1958
1959     return ret;
1960 }
1961
1962
1963 /**************************************************************************
1964  *                              widAddBuffer            [internal]
1965  */
1966 static DWORD widAddBuffer(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1967 {
1968     DWORD           ret = MMSYSERR_NOERROR;
1969     WINE_WAVEIN*    wwi;
1970
1971     TRACE("(%u, %p, %08X);\n", wDevID, lpWaveHdr, dwSize);
1972
1973     if (wDevID >= MAX_WAVEINDRV)
1974     {
1975         WARN("invalid device ID\n");
1976         return MMSYSERR_INVALHANDLE;
1977     }
1978     if (!(lpWaveHdr->dwFlags & WHDR_PREPARED))
1979     {
1980         TRACE("never been prepared !\n");
1981         return WAVERR_UNPREPARED;
1982     }
1983     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1984     {
1985         TRACE("header already in use !\n");
1986         return WAVERR_STILLPLAYING;
1987     }
1988
1989     wwi = &WInDev[wDevID];
1990     OSSpinLockLock(&wwi->lock);
1991
1992     if (wwi->state == WINE_WS_CLOSED)
1993     {
1994         WARN("Trying to add buffer to closed device.\n");
1995         ret = MMSYSERR_INVALHANDLE;
1996     }
1997     else
1998     {
1999         LPWAVEHDR* wh;
2000
2001         lpWaveHdr->dwFlags |= WHDR_INQUEUE;
2002         lpWaveHdr->dwFlags &= ~WHDR_DONE;
2003         lpWaveHdr->dwBytesRecorded = 0;
2004         lpWaveHdr->lpNext = NULL;
2005
2006         /* insert buffer at end of queue */
2007         for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext))
2008             /* Do nothing */;
2009         *wh = lpWaveHdr;
2010     }
2011
2012     OSSpinLockUnlock(&wwi->lock);
2013
2014     return ret;
2015 }
2016
2017
2018 /**************************************************************************
2019  *                      widStart                                [internal]
2020  */
2021 static DWORD widStart(WORD wDevID)
2022 {
2023     DWORD           ret = MMSYSERR_NOERROR;
2024     WINE_WAVEIN*    wwi;
2025
2026     TRACE("(%u);\n", wDevID);
2027     if (wDevID >= MAX_WAVEINDRV)
2028     {
2029         WARN("invalid device ID\n");
2030         return MMSYSERR_INVALHANDLE;
2031     }
2032
2033     /* The order of the following operations is important since we can't hold
2034      * the mutex while we make an Audio Unit call.  Set the PLAYING state
2035      * before starting the Audio Unit.  In widStop, the order is reversed.
2036      * This guarantees that we can't get into a situation where the state is
2037      * PLAYING but the Audio Unit isn't running.  Although we can be in STOPPED
2038      * state with the Audio Unit still running, that's harmless because the
2039      * input callback will just throw away the sound data.
2040      */
2041     wwi = &WInDev[wDevID];
2042     OSSpinLockLock(&wwi->lock);
2043
2044     if (wwi->state == WINE_WS_CLOSED)
2045     {
2046         WARN("Trying to start closed device.\n");
2047         ret = MMSYSERR_INVALHANDLE;
2048     }
2049     else
2050         wwi->state = WINE_WS_PLAYING;
2051
2052     OSSpinLockUnlock(&wwi->lock);
2053
2054     if (ret == MMSYSERR_NOERROR)
2055     {
2056         /* Start pulling for audio data */
2057         OSStatus err = AudioOutputUnitStart(wwi->audioUnit);
2058         if (err != noErr)
2059             ERR("Failed to start AU: %08lx\n", err);
2060
2061         TRACE("Recording started...\n");
2062     }
2063
2064     return ret;
2065 }
2066
2067
2068 /**************************************************************************
2069  *                      widStop                                 [internal]
2070  */
2071 static DWORD widStop(WORD wDevID)
2072 {
2073     DWORD           ret = MMSYSERR_NOERROR;
2074     WINE_WAVEIN*    wwi;
2075     WAVEHDR*        lpWaveHdr = NULL;
2076     OSStatus        err;
2077
2078     TRACE("(%u);\n", wDevID);
2079     if (wDevID >= MAX_WAVEINDRV)
2080     {
2081         WARN("invalid device ID\n");
2082         return MMSYSERR_INVALHANDLE;
2083     }
2084
2085     wwi = &WInDev[wDevID];
2086
2087     /* The order of the following operations is important since we can't hold
2088      * the mutex while we make an Audio Unit call.  Stop the Audio Unit before
2089      * setting the STOPPED state.  In widStart, the order is reversed.  This
2090      * guarantees that we can't get into a situation where the state is
2091      * PLAYING but the Audio Unit isn't running.  Although we can be in STOPPED
2092      * state with the Audio Unit still running, that's harmless because the
2093      * input callback will just throw away the sound data.
2094      */
2095     err = AudioOutputUnitStop(wwi->audioUnit);
2096     if (err != noErr)
2097         WARN("Failed to stop AU: %08lx\n", err);
2098
2099     TRACE("Recording stopped.\n");
2100
2101     OSSpinLockLock(&wwi->lock);
2102
2103     if (wwi->state == WINE_WS_CLOSED)
2104     {
2105         WARN("Trying to stop closed device.\n");
2106         ret = MMSYSERR_INVALHANDLE;
2107     }
2108     else if (wwi->state != WINE_WS_STOPPED)
2109     {
2110         wwi->state = WINE_WS_STOPPED;
2111         /* If there's a buffer in progress, it's done.  Remove it from the
2112          * queue so that we can return it to the app, below. */
2113         if (wwi->lpQueuePtr)
2114         {
2115             lpWaveHdr = wwi->lpQueuePtr;
2116             wwi->lpQueuePtr = lpWaveHdr->lpNext;
2117         }
2118     }
2119
2120     OSSpinLockUnlock(&wwi->lock);
2121
2122     if (lpWaveHdr)
2123     {
2124         lpWaveHdr->lpNext = NULL;
2125         lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2126         lpWaveHdr->dwFlags |= WHDR_DONE;
2127         widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2128     }
2129
2130     return ret;
2131 }
2132
2133 /**************************************************************************
2134  *                      widGetPos                                 [internal]
2135  */
2136 static DWORD widGetPos(WORD wDevID, LPMMTIME lpTime, UINT size)
2137 {
2138     DWORD                   val;
2139     WINE_WAVEIN*    wwi;
2140
2141     TRACE("(%u);\n", wDevID);
2142     if (wDevID >= MAX_WAVEINDRV)
2143     {
2144         WARN("invalid device ID\n");
2145         return MMSYSERR_INVALHANDLE;
2146     }
2147
2148     wwi = &WInDev[wDevID];
2149
2150     OSSpinLockLock(&WInDev[wDevID].lock);
2151     val = wwi->dwTotalRecorded;
2152     OSSpinLockUnlock(&WInDev[wDevID].lock);
2153
2154     return bytes_to_mmtime(lpTime, val, &wwi->format);
2155 }
2156
2157 /**************************************************************************
2158  *                      widReset                                [internal]
2159  */
2160 static DWORD widReset(WORD wDevID)
2161 {
2162     DWORD           ret = MMSYSERR_NOERROR;
2163     WINE_WAVEIN*    wwi;
2164     WAVEHDR*        lpWaveHdr = NULL;
2165
2166     TRACE("(%u);\n", wDevID);
2167     if (wDevID >= MAX_WAVEINDRV)
2168     {
2169         WARN("invalid device ID\n");
2170         return MMSYSERR_INVALHANDLE;
2171     }
2172
2173     wwi = &WInDev[wDevID];
2174     OSSpinLockLock(&wwi->lock);
2175
2176     if (wwi->state == WINE_WS_CLOSED)
2177     {
2178         WARN("Trying to reset a closed device.\n");
2179         ret = MMSYSERR_INVALHANDLE;
2180     }
2181     else
2182     {
2183         lpWaveHdr               = wwi->lpQueuePtr;
2184         wwi->lpQueuePtr         = NULL;
2185         wwi->state              = WINE_WS_STOPPED;
2186         wwi->dwTotalRecorded    = 0;
2187     }
2188
2189     OSSpinLockUnlock(&wwi->lock);
2190
2191     if (ret == MMSYSERR_NOERROR)
2192     {
2193         OSStatus err = AudioOutputUnitStop(wwi->audioUnit);
2194         if (err != noErr)
2195             WARN("Failed to stop AU: %08lx\n", err);
2196
2197         TRACE("Recording stopped.\n");
2198     }
2199
2200     while (lpWaveHdr)
2201     {
2202         WAVEHDR* lpNext = lpWaveHdr->lpNext;
2203
2204         lpWaveHdr->lpNext = NULL;
2205         lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2206         lpWaveHdr->dwFlags |= WHDR_DONE;
2207         widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2208
2209         lpWaveHdr = lpNext;
2210     }
2211
2212     return ret;
2213 }
2214
2215
2216 /**************************************************************************
2217  *                              widGetNumDevs                   [internal]
2218  */
2219 static DWORD widGetNumDevs(void)
2220 {
2221     return MAX_WAVEINDRV;
2222 }
2223
2224
2225 /**************************************************************************
2226  *                              widDevInterfaceSize             [internal]
2227  */
2228 static DWORD widDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
2229 {
2230     TRACE("(%u, %p)\n", wDevID, dwParam1);
2231
2232     *dwParam1 = MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
2233                                     NULL, 0 ) * sizeof(WCHAR);
2234     return MMSYSERR_NOERROR;
2235 }
2236
2237
2238 /**************************************************************************
2239  *                              widDevInterface                 [internal]
2240  */
2241 static DWORD widDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
2242 {
2243     if (dwParam2 >= MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
2244                                         NULL, 0 ) * sizeof(WCHAR))
2245     {
2246         MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
2247                             dwParam1, dwParam2 / sizeof(WCHAR));
2248         return MMSYSERR_NOERROR;
2249     }
2250     return MMSYSERR_INVALPARAM;
2251 }
2252
2253
2254 /**************************************************************************
2255  *                              widDsCreate                     [internal]
2256  */
2257 static DWORD widDsCreate(UINT wDevID, PIDSCDRIVER* drv)
2258 {
2259     TRACE("(%d,%p)\n",wDevID,drv);
2260
2261     FIXME("DirectSoundCapture not implemented\n");
2262     FIXME("The (slower) DirectSound HEL mode will be used instead.\n");
2263     return MMSYSERR_NOTSUPPORTED;
2264 }
2265
2266 /**************************************************************************
2267  *                              widDsDesc                       [internal]
2268  */
2269 static DWORD widDsDesc(UINT wDevID, PDSDRIVERDESC desc)
2270 {
2271     /* The DirectSound HEL will automatically wrap a non-DirectSound-capable
2272      * driver in a DirectSound adaptor, thus allowing the driver to be used by
2273      * DirectSound clients.  However, it only does this if we respond
2274      * successfully to the DRV_QUERYDSOUNDDESC message.  It's enough to fill in
2275      * the driver and device names of the description output parameter. */
2276     memset(desc, 0, sizeof(*desc));
2277     lstrcpynA(desc->szDrvname, "winecoreaudio.drv", sizeof(desc->szDrvname) - 1);
2278     lstrcpynA(desc->szDesc, WInDev[wDevID].interface_name, sizeof(desc->szDesc) - 1);
2279     return MMSYSERR_NOERROR;
2280 }
2281
2282
2283 /**************************************************************************
2284  *                              widMessage (WINECOREAUDIO.6)
2285  */
2286 DWORD WINAPI CoreAudio_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2287                             DWORD dwParam1, DWORD dwParam2)
2288 {
2289     TRACE("(%u, %04X, %08X, %08X, %08X);\n",
2290             wDevID, wMsg, dwUser, dwParam1, dwParam2);
2291
2292     switch (wMsg)
2293     {
2294         case DRVM_INIT:
2295         case DRVM_EXIT:
2296         case DRVM_ENABLE:
2297         case DRVM_DISABLE:
2298             /* FIXME: Pretend this is supported */
2299             return 0;
2300         case WIDM_OPEN:             return widOpen          (wDevID, (LPWAVEOPENDESC)dwParam1,  dwParam2);
2301         case WIDM_CLOSE:            return widClose         (wDevID);
2302         case WIDM_ADDBUFFER:        return widAddBuffer     (wDevID, (LPWAVEHDR)dwParam1,       dwParam2);
2303         case WIDM_PREPARE:          return MMSYSERR_NOTSUPPORTED;
2304         case WIDM_UNPREPARE:        return MMSYSERR_NOTSUPPORTED;
2305         case WIDM_GETDEVCAPS:       return widGetDevCaps    (wDevID, (LPWAVEINCAPSW)dwParam1,   dwParam2);
2306         case WIDM_GETNUMDEVS:       return widGetNumDevs    ();
2307         case WIDM_RESET:            return widReset         (wDevID);
2308         case WIDM_START:            return widStart         (wDevID);
2309         case WIDM_STOP:             return widStop          (wDevID);
2310         case WIDM_GETPOS:           return widGetPos        (wDevID, (LPMMTIME)dwParam1, (UINT)dwParam2  );
2311         case DRV_QUERYDEVICEINTERFACESIZE: return widDevInterfaceSize       (wDevID, (LPDWORD)dwParam1);
2312         case DRV_QUERYDEVICEINTERFACE:     return widDevInterface           (wDevID, (PWCHAR)dwParam1, dwParam2);
2313         case DRV_QUERYDSOUNDIFACE:  return widDsCreate   (wDevID, (PIDSCDRIVER*)dwParam1);
2314         case DRV_QUERYDSOUNDDESC:   return widDsDesc     (wDevID, (PDSDRIVERDESC)dwParam1);
2315         default:
2316             FIXME("unknown message %d!\n", wMsg);
2317     }
2318
2319     return MMSYSERR_NOTSUPPORTED;
2320 }
2321
2322
2323 OSStatus CoreAudio_wiAudioUnitIOProc(void *inRefCon,
2324                                      AudioUnitRenderActionFlags *ioActionFlags,
2325                                      const AudioTimeStamp *inTimeStamp,
2326                                      UInt32 inBusNumber,
2327                                      UInt32 inNumberFrames,
2328                                      AudioBufferList *ioData)
2329 {
2330     WINE_WAVEIN*    wwi = (WINE_WAVEIN*)inRefCon;
2331     OSStatus        err = noErr;
2332     BOOL            needNotify = FALSE;
2333     WAVEHDR*        lpStorePtr;
2334     unsigned int    dataToStore;
2335     unsigned int    dataStored = 0;
2336
2337
2338     if (wwi->trace_on)
2339         fprintf(stderr, "trace:wave:CoreAudio_wiAudioUnitIOProc (ioActionFlags = %08lx, "
2340             "inTimeStamp = { %f, %x%08x, %f, %x%08x, %08lx }, inBusNumber = %lu, inNumberFrames = %lu)\n",
2341             *ioActionFlags, inTimeStamp->mSampleTime, (DWORD)(inTimeStamp->mHostTime >>32),
2342             (DWORD)inTimeStamp->mHostTime, inTimeStamp->mRateScalar, (DWORD)(inTimeStamp->mWordClockTime >> 32),
2343             (DWORD)inTimeStamp->mWordClockTime, inTimeStamp->mFlags, inBusNumber, inNumberFrames);
2344
2345     /* Render into audio buffer */
2346     /* FIXME: implement sample rate conversion on input.  This will require
2347      * a different render strategy.  We'll need to buffer the sound data
2348      * received here and pass it off to an AUConverter in another thread. */
2349     err = AudioUnitRender(wwi->audioUnit, ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, wwi->bufferList);
2350     if (err)
2351     {
2352         if (wwi->err_on)
2353             fprintf(stderr, "err:wave:CoreAudio_wiAudioUnitIOProc AudioUnitRender failed with error %li\n", err);
2354         return err;
2355     }
2356
2357     /* Copy from audio buffer to the wavehdrs */
2358     dataToStore = wwi->bufferList->mBuffers[0].mDataByteSize;
2359
2360     OSSpinLockLock(&wwi->lock);
2361
2362     lpStorePtr = wwi->lpQueuePtr;
2363
2364     while (dataToStore > 0 && wwi->state == WINE_WS_PLAYING && lpStorePtr)
2365     {
2366         unsigned int room = lpStorePtr->dwBufferLength - lpStorePtr->dwBytesRecorded;
2367         unsigned int toCopy;
2368
2369         if (wwi->trace_on)
2370             fprintf(stderr, "trace:wave:CoreAudio_wiAudioUnitIOProc Looking to store %u bytes to wavehdr %p, which has room for %u\n",
2371                 dataToStore, lpStorePtr, room);
2372
2373         if (room >= dataToStore)
2374             toCopy = dataToStore;
2375         else
2376             toCopy = room;
2377
2378         if (toCopy > 0)
2379         {
2380             memcpy(lpStorePtr->lpData + lpStorePtr->dwBytesRecorded,
2381                 (char*)wwi->bufferList->mBuffers[0].mData + dataStored, toCopy);
2382             lpStorePtr->dwBytesRecorded += toCopy;
2383             wwi->dwTotalRecorded += toCopy;
2384             dataStored += toCopy;
2385             dataToStore -= toCopy;
2386             room -= toCopy;
2387         }
2388
2389         if (room == 0)
2390         {
2391             lpStorePtr = lpStorePtr->lpNext;
2392             needNotify = TRUE;
2393         }
2394     }
2395
2396     OSSpinLockUnlock(&wwi->lock);
2397
2398     /* Restore the audio buffer list structure from backup, in case
2399      * AudioUnitRender clobbered it.  (It modifies mDataByteSize and may even
2400      * give us a different mData buffer to avoid a copy.) */
2401     memcpy(wwi->bufferList, wwi->bufferListCopy, AUDIOBUFFERLISTSIZE(wwi->bufferList->mNumberBuffers));
2402
2403     if (needNotify) wodSendNotifyInputCompletionsMessage(wwi);
2404     return err;
2405 }
2406
2407 #else
2408
2409 /**************************************************************************
2410  *                              widMessage (WINECOREAUDIO.6)
2411  */
2412 DWORD WINAPI CoreAudio_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2413                             DWORD dwParam1, DWORD dwParam2)
2414 {
2415     FIXME("(%u, %04X, %08X, %08X, %08X): CoreAudio support not compiled into wine\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2416     return MMSYSERR_NOTENABLED;
2417 }
2418
2419 /**************************************************************************
2420 *                               wodMessage (WINECOREAUDIO.7)
2421 */
2422 DWORD WINAPI CoreAudio_wodMessage(WORD wDevID, WORD wMsg, DWORD dwUser, 
2423                                   DWORD dwParam1, DWORD dwParam2)
2424 {
2425     FIXME("(%u, %04X, %08X, %08X, %08X): CoreAudio support not compiled into wine\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2426     return MMSYSERR_NOTENABLED;
2427 }
2428
2429 #endif