winecoreaudio: Protect against AudioUnitRender clobbering our buffer list.
[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 1;
525     }
526     if (CoreAudio_DefaultDevice.outputDeviceID == kAudioDeviceUnknown) {
527         ERR("AudioHardwareGetProperty: CoreAudio_DefaultDevice.outputDeviceID == kAudioDeviceUnknown\n");
528         return 1;
529     }
530     
531     if ( ! CoreAudio_GetDevCaps() )
532         return 1;
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 1;
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 1;
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 1;
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 1;
685     }
686
687     /* The message thread is responsible for releasing port_ReceiveInMessageThread. */
688
689     return 0;
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     memcpy(&wwo->waveDesc, lpDesc,           sizeof(WAVEOPENDESC));
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     memcpy(desc, &(WOutDev[wDevID].cadev->ds_desc), sizeof(DSDRIVERDESC));
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
1583     OSSpinLockUnlock(&wwo->lock);
1584
1585     /* We can't provide any more wave data.  Fill the rest with silence. */
1586     if (dataNeeded > 0)
1587     {
1588         if (!dataProvided)
1589             *ioActionFlags |= kAudioUnitRenderAction_OutputIsSilence;
1590         memset((char*)ioData->mBuffers[0].mData + dataProvided, 0, dataNeeded);
1591         dataProvided += dataNeeded;
1592         dataNeeded = 0;
1593     }
1594
1595     /* We only fill buffer 0.  Set any others that might be requested to 0. */
1596     for (buffer = 1; buffer < ioData->mNumberBuffers; buffer++)
1597     {
1598         memset(ioData->mBuffers[buffer].mData, 0, ioData->mBuffers[buffer].mDataByteSize);
1599     }
1600
1601     if (needNotify) wodSendNotifyCompletionsMessage(wwo);
1602     return noErr;
1603 }
1604
1605
1606 /*======================================================================*
1607  *                  Low level WAVE IN implementation                    *
1608  *======================================================================*/
1609
1610 /**************************************************************************
1611  *                      widNotifyClient                 [internal]
1612  */
1613 static DWORD widNotifyClient(WINE_WAVEIN* wwi, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
1614 {
1615     TRACE("wMsg = 0x%04x dwParm1 = %04X dwParam2 = %04X\n", wMsg, dwParam1, dwParam2);
1616
1617     switch (wMsg)
1618     {
1619         case WIM_OPEN:
1620         case WIM_CLOSE:
1621         case WIM_DATA:
1622             if (wwi->wFlags != DCB_NULL &&
1623                 !DriverCallback(wwi->waveDesc.dwCallback, wwi->wFlags,
1624                                 (HDRVR)wwi->waveDesc.hWave, wMsg, wwi->waveDesc.dwInstance,
1625                                 dwParam1, dwParam2))
1626             {
1627                 WARN("can't notify client !\n");
1628                 return MMSYSERR_ERROR;
1629             }
1630             break;
1631         default:
1632             FIXME("Unknown callback message %u\n", wMsg);
1633             return MMSYSERR_INVALPARAM;
1634     }
1635     return MMSYSERR_NOERROR;
1636 }
1637
1638
1639 /**************************************************************************
1640  *                      widHelper_NotifyCompletions              [internal]
1641  */
1642 static void widHelper_NotifyCompletions(WINE_WAVEIN* wwi)
1643 {
1644     LPWAVEHDR       lpWaveHdr;
1645     LPWAVEHDR       lpFirstDoneWaveHdr = NULL;
1646     LPWAVEHDR       lpLastDoneWaveHdr = NULL;
1647
1648     OSSpinLockLock(&wwi->lock);
1649
1650     /* First, excise all of the done headers from the queue into
1651      * a free-standing list. */
1652
1653     /* Start from lpQueuePtr and keep notifying until:
1654         * - we hit an unfilled wavehdr
1655         * - we hit the end of the list
1656         */
1657     for (
1658         lpWaveHdr = wwi->lpQueuePtr;
1659         lpWaveHdr &&
1660             lpWaveHdr->dwBytesRecorded >= lpWaveHdr->dwBufferLength;
1661         lpWaveHdr = lpWaveHdr->lpNext
1662         )
1663     {
1664         if (!lpFirstDoneWaveHdr)
1665             lpFirstDoneWaveHdr = lpWaveHdr;
1666         lpLastDoneWaveHdr = lpWaveHdr;
1667     }
1668
1669     if (lpLastDoneWaveHdr)
1670     {
1671         wwi->lpQueuePtr = lpLastDoneWaveHdr->lpNext;
1672         lpLastDoneWaveHdr->lpNext = NULL;
1673     }
1674
1675     OSSpinLockUnlock(&wwi->lock);
1676
1677     /* Now, send the "done" notification for each header in our list. */
1678     lpWaveHdr = lpFirstDoneWaveHdr;
1679     while (lpWaveHdr)
1680     {
1681         LPWAVEHDR lpNext = lpWaveHdr->lpNext;
1682
1683         lpWaveHdr->lpNext = NULL;
1684         lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1685         lpWaveHdr->dwFlags |= WHDR_DONE;
1686         widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
1687
1688         lpWaveHdr = lpNext;
1689     }
1690 }
1691
1692
1693 /**************************************************************************
1694  *                      widGetDevCaps                           [internal]
1695  */
1696 static DWORD widGetDevCaps(WORD wDevID, LPWAVEINCAPSW lpCaps, DWORD dwSize)
1697 {
1698     TRACE("(%u, %p, %u);\n", wDevID, lpCaps, dwSize);
1699
1700     if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
1701
1702     if (wDevID >= MAX_WAVEINDRV)
1703     {
1704         TRACE("MAX_WAVEINDRV reached !\n");
1705         return MMSYSERR_BADDEVICEID;
1706     }
1707
1708     memcpy(lpCaps, &WInDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
1709     return MMSYSERR_NOERROR;
1710 }
1711
1712
1713 /**************************************************************************
1714  *                    widHelper_DestroyAudioBufferList           [internal]
1715  * Convenience function to dispose of our audio buffers
1716  */
1717 static void widHelper_DestroyAudioBufferList(AudioBufferList* list)
1718 {
1719     if (list)
1720     {
1721         UInt32 i;
1722         for (i = 0; i < list->mNumberBuffers; i++)
1723         {
1724             if (list->mBuffers[i].mData)
1725                 HeapFree(GetProcessHeap(), 0, list->mBuffers[i].mData);
1726         }
1727         HeapFree(GetProcessHeap(), 0, list);
1728     }
1729 }
1730
1731
1732 #define AUDIOBUFFERLISTSIZE(numBuffers) (offsetof(AudioBufferList, mBuffers) + (numBuffers) * sizeof(AudioBuffer))
1733
1734 /**************************************************************************
1735  *                    widHelper_AllocateAudioBufferList          [internal]
1736  * Convenience function to allocate our audio buffers
1737  */
1738 static AudioBufferList* widHelper_AllocateAudioBufferList(UInt32 numChannels, UInt32 bitsPerChannel, UInt32 bufferFrames, BOOL interleaved)
1739 {
1740     UInt32                      numBuffers;
1741     UInt32                      channelsPerFrame;
1742     UInt32                      bytesPerFrame;
1743     UInt32                      bytesPerBuffer;
1744     AudioBufferList*            list;
1745     UInt32                      i;
1746
1747     if (interleaved)
1748     {
1749         /* For interleaved audio, we allocate one buffer for all channels. */
1750         numBuffers = 1;
1751         channelsPerFrame = numChannels;
1752     }
1753     else
1754     {
1755         numBuffers = numChannels;
1756         channelsPerFrame = 1;
1757     }
1758
1759     bytesPerFrame = bitsPerChannel * channelsPerFrame / 8;
1760     bytesPerBuffer = bytesPerFrame * bufferFrames;
1761
1762     list = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, AUDIOBUFFERLISTSIZE(numBuffers));
1763     if (list == NULL)
1764         return NULL;
1765
1766     list->mNumberBuffers = numBuffers;
1767     for (i = 0; i < numBuffers; ++i)
1768     {
1769         list->mBuffers[i].mNumberChannels = channelsPerFrame;
1770         list->mBuffers[i].mDataByteSize = bytesPerBuffer;
1771         list->mBuffers[i].mData = HeapAlloc(GetProcessHeap(), 0, bytesPerBuffer);
1772         if (list->mBuffers[i].mData == NULL)
1773         {
1774             widHelper_DestroyAudioBufferList(list);
1775             return NULL;
1776         }
1777     }
1778     return list;
1779 }
1780
1781
1782 /**************************************************************************
1783  *                              widOpen                         [internal]
1784  */
1785 static DWORD widOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
1786 {
1787     WINE_WAVEIN*    wwi;
1788     UInt32          frameCount;
1789
1790     TRACE("(%u, %p, %08X);\n", wDevID, lpDesc, dwFlags);
1791     if (lpDesc == NULL)
1792     {
1793         WARN("Invalid Parameter !\n");
1794         return MMSYSERR_INVALPARAM;
1795     }
1796     if (wDevID >= MAX_WAVEINDRV)
1797     {
1798         TRACE ("MAX_WAVEINDRV reached !\n");
1799         return MMSYSERR_BADDEVICEID;
1800     }
1801
1802     TRACE("Format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
1803           lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1804           lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
1805
1806     if (lpDesc->lpFormat->wFormatTag != WAVE_FORMAT_PCM ||
1807         lpDesc->lpFormat->nChannels == 0 ||
1808         lpDesc->lpFormat->nSamplesPerSec == 0
1809         )
1810     {
1811         WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
1812              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1813              lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
1814         return WAVERR_BADFORMAT;
1815     }
1816
1817     if (dwFlags & WAVE_FORMAT_QUERY)
1818     {
1819         TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
1820               lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1821               lpDesc->lpFormat->nSamplesPerSec);
1822         return MMSYSERR_NOERROR;
1823     }
1824
1825     wwi = &WInDev[wDevID];
1826     if (!OSSpinLockTry(&wwi->lock))
1827         return MMSYSERR_ALLOCATED;
1828
1829     if (wwi->state != WINE_WS_CLOSED)
1830     {
1831         OSSpinLockUnlock(&wwi->lock);
1832         return MMSYSERR_ALLOCATED;
1833     }
1834
1835     wwi->state = WINE_WS_STOPPED;
1836     wwi->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
1837
1838     memcpy(&wwi->waveDesc, lpDesc,              sizeof(WAVEOPENDESC));
1839     memcpy(&wwi->format,   lpDesc->lpFormat,    sizeof(PCMWAVEFORMAT));
1840
1841     if (wwi->format.wBitsPerSample == 0)
1842     {
1843         WARN("Resetting zeroed wBitsPerSample\n");
1844         wwi->format.wBitsPerSample = 8 *
1845             (wwi->format.wf.nAvgBytesPerSec /
1846             wwi->format.wf.nSamplesPerSec) /
1847             wwi->format.wf.nChannels;
1848     }
1849
1850     wwi->dwTotalRecorded = 0;
1851
1852     wwi->trace_on = TRACE_ON(wave);
1853     wwi->warn_on  = WARN_ON(wave);
1854     wwi->err_on   = ERR_ON(wave);
1855
1856     if (!AudioUnit_CreateInputUnit(wwi, &wwi->audioUnit,
1857         wwi->format.wf.nChannels, wwi->format.wf.nSamplesPerSec,
1858         wwi->format.wBitsPerSample, &frameCount))
1859     {
1860         ERR("AudioUnit_CreateInputUnit failed\n");
1861         OSSpinLockUnlock(&wwi->lock);
1862         return MMSYSERR_ERROR;
1863     }
1864
1865     /* Allocate our audio buffers */
1866     wwi->bufferList = widHelper_AllocateAudioBufferList(wwi->format.wf.nChannels,
1867         wwi->format.wBitsPerSample, frameCount, TRUE);
1868     if (wwi->bufferList == NULL)
1869     {
1870         ERR("Failed to allocate buffer list\n");
1871         AudioUnitUninitialize(wwi->audioUnit);
1872         AudioUnit_CloseAudioUnit(wwi->audioUnit);
1873         OSSpinLockUnlock(&wwi->lock);
1874         return MMSYSERR_NOMEM;
1875     }
1876
1877     /* Keep a copy of the buffer list structure (but not the buffers themselves)
1878      * in case AudioUnitRender clobbers the original, as it is wont to do. */
1879     wwi->bufferListCopy = HeapAlloc(GetProcessHeap(), 0, AUDIOBUFFERLISTSIZE(wwi->bufferList->mNumberBuffers));
1880     if (wwi->bufferListCopy == NULL)
1881     {
1882         ERR("Failed to allocate buffer list copy\n");
1883         widHelper_DestroyAudioBufferList(wwi->bufferList);
1884         AudioUnitUninitialize(wwi->audioUnit);
1885         AudioUnit_CloseAudioUnit(wwi->audioUnit);
1886         OSSpinLockUnlock(&wwi->lock);
1887         return MMSYSERR_NOMEM;
1888     }
1889     memcpy(wwi->bufferListCopy, wwi->bufferList, AUDIOBUFFERLISTSIZE(wwi->bufferList->mNumberBuffers));
1890
1891     OSSpinLockUnlock(&wwi->lock);
1892
1893     return widNotifyClient(wwi, WIM_OPEN, 0L, 0L);
1894 }
1895
1896
1897 /**************************************************************************
1898  *                              widClose                        [internal]
1899  */
1900 static DWORD widClose(WORD wDevID)
1901 {
1902     DWORD           ret = MMSYSERR_NOERROR;
1903     WINE_WAVEIN*    wwi;
1904
1905     TRACE("(%u);\n", wDevID);
1906
1907     if (wDevID >= MAX_WAVEINDRV)
1908     {
1909         WARN("bad device ID !\n");
1910         return MMSYSERR_BADDEVICEID;
1911     }
1912
1913     wwi = &WInDev[wDevID];
1914     OSSpinLockLock(&wwi->lock);
1915     if (wwi->state == WINE_WS_CLOSED)
1916     {
1917         WARN("Device already closed.\n");
1918         ret = MMSYSERR_INVALHANDLE;
1919     }
1920     else if (wwi->lpQueuePtr)
1921     {
1922         WARN("Buffers in queue.\n");
1923         ret = WAVERR_STILLPLAYING;
1924     }
1925     else
1926     {
1927         wwi->state = WINE_WS_CLOSED;
1928     }
1929
1930     OSSpinLockUnlock(&wwi->lock);
1931
1932     if (ret == MMSYSERR_NOERROR)
1933     {
1934         OSStatus err = AudioUnitUninitialize(wwi->audioUnit);
1935         if (err)
1936         {
1937             ERR("AudioUnitUninitialize return %c%c%c%c\n", (char) (err >> 24),
1938                                                            (char) (err >> 16),
1939                                                            (char) (err >> 8),
1940                                                            (char) err);
1941         }
1942
1943         if (!AudioUnit_CloseAudioUnit(wwi->audioUnit))
1944         {
1945             ERR("Can't close AudioUnit\n");
1946         }
1947
1948         /* Dellocate our audio buffers */
1949         widHelper_DestroyAudioBufferList(wwi->bufferList);
1950         wwi->bufferList = NULL;
1951         HeapFree(GetProcessHeap(), 0, wwi->bufferListCopy);
1952         wwi->bufferListCopy = NULL;
1953
1954         ret = widNotifyClient(wwi, WIM_CLOSE, 0L, 0L);
1955     }
1956
1957     return ret;
1958 }
1959
1960
1961 /**************************************************************************
1962  *                              widAddBuffer            [internal]
1963  */
1964 static DWORD widAddBuffer(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1965 {
1966     DWORD           ret = MMSYSERR_NOERROR;
1967     WINE_WAVEIN*    wwi;
1968
1969     TRACE("(%u, %p, %08X);\n", wDevID, lpWaveHdr, dwSize);
1970
1971     if (wDevID >= MAX_WAVEINDRV)
1972     {
1973         WARN("invalid device ID\n");
1974         return MMSYSERR_INVALHANDLE;
1975     }
1976     if (!(lpWaveHdr->dwFlags & WHDR_PREPARED))
1977     {
1978         TRACE("never been prepared !\n");
1979         return WAVERR_UNPREPARED;
1980     }
1981     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1982     {
1983         TRACE("header already in use !\n");
1984         return WAVERR_STILLPLAYING;
1985     }
1986
1987     wwi = &WInDev[wDevID];
1988     OSSpinLockLock(&wwi->lock);
1989
1990     if (wwi->state == WINE_WS_CLOSED)
1991     {
1992         WARN("Trying to add buffer to closed device.\n");
1993         ret = MMSYSERR_INVALHANDLE;
1994     }
1995     else
1996     {
1997         LPWAVEHDR* wh;
1998
1999         lpWaveHdr->dwFlags |= WHDR_INQUEUE;
2000         lpWaveHdr->dwFlags &= ~WHDR_DONE;
2001         lpWaveHdr->dwBytesRecorded = 0;
2002         lpWaveHdr->lpNext = NULL;
2003
2004         /* insert buffer at end of queue */
2005         for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext))
2006             /* Do nothing */;
2007         *wh = lpWaveHdr;
2008     }
2009
2010     OSSpinLockUnlock(&wwi->lock);
2011
2012     return ret;
2013 }
2014
2015
2016 /**************************************************************************
2017  *                      widStart                                [internal]
2018  */
2019 static DWORD widStart(WORD wDevID)
2020 {
2021     DWORD           ret = MMSYSERR_NOERROR;
2022     WINE_WAVEIN*    wwi;
2023
2024     TRACE("(%u);\n", wDevID);
2025     if (wDevID >= MAX_WAVEINDRV)
2026     {
2027         WARN("invalid device ID\n");
2028         return MMSYSERR_INVALHANDLE;
2029     }
2030
2031     /* The order of the following operations is important since we can't hold
2032      * the mutex while we make an Audio Unit call.  Set the PLAYING state
2033      * before starting the Audio Unit.  In widStop, the order is reversed.
2034      * This guarantees that we can't get into a situation where the state is
2035      * PLAYING but the Audio Unit isn't running.  Although we can be in STOPPED
2036      * state with the Audio Unit still running, that's harmless because the
2037      * input callback will just throw away the sound data.
2038      */
2039     wwi = &WInDev[wDevID];
2040     OSSpinLockLock(&wwi->lock);
2041
2042     if (wwi->state == WINE_WS_CLOSED)
2043     {
2044         WARN("Trying to start closed device.\n");
2045         ret = MMSYSERR_INVALHANDLE;
2046     }
2047     else
2048         wwi->state = WINE_WS_PLAYING;
2049
2050     OSSpinLockUnlock(&wwi->lock);
2051
2052     if (ret == MMSYSERR_NOERROR)
2053     {
2054         /* Start pulling for audio data */
2055         OSStatus err = AudioOutputUnitStart(wwi->audioUnit);
2056         if (err != noErr)
2057             ERR("Failed to start AU: %08lx\n", err);
2058
2059         TRACE("Recording started...\n");
2060     }
2061
2062     return ret;
2063 }
2064
2065
2066 /**************************************************************************
2067  *                      widStop                                 [internal]
2068  */
2069 static DWORD widStop(WORD wDevID)
2070 {
2071     DWORD           ret = MMSYSERR_NOERROR;
2072     WINE_WAVEIN*    wwi;
2073     WAVEHDR*        lpWaveHdr = NULL;
2074     OSStatus        err;
2075
2076     TRACE("(%u);\n", wDevID);
2077     if (wDevID >= MAX_WAVEINDRV)
2078     {
2079         WARN("invalid device ID\n");
2080         return MMSYSERR_INVALHANDLE;
2081     }
2082
2083     wwi = &WInDev[wDevID];
2084
2085     /* The order of the following operations is important since we can't hold
2086      * the mutex while we make an Audio Unit call.  Stop the Audio Unit before
2087      * setting the STOPPED state.  In widStart, the order is reversed.  This
2088      * guarantees that we can't get into a situation where the state is
2089      * PLAYING but the Audio Unit isn't running.  Although we can be in STOPPED
2090      * state with the Audio Unit still running, that's harmless because the
2091      * input callback will just throw away the sound data.
2092      */
2093     err = AudioOutputUnitStop(wwi->audioUnit);
2094     if (err != noErr)
2095         WARN("Failed to stop AU: %08lx\n", err);
2096
2097     TRACE("Recording stopped.\n");
2098
2099     OSSpinLockLock(&wwi->lock);
2100
2101     if (wwi->state == WINE_WS_CLOSED)
2102     {
2103         WARN("Trying to stop closed device.\n");
2104         ret = MMSYSERR_INVALHANDLE;
2105     }
2106     else if (wwi->state != WINE_WS_STOPPED)
2107     {
2108         wwi->state = WINE_WS_STOPPED;
2109         /* If there's a buffer in progress, it's done.  Remove it from the
2110          * queue so that we can return it to the app, below. */
2111         if (wwi->lpQueuePtr)
2112         {
2113             lpWaveHdr = wwi->lpQueuePtr;
2114             wwi->lpQueuePtr = lpWaveHdr->lpNext;
2115         }
2116     }
2117
2118     OSSpinLockUnlock(&wwi->lock);
2119
2120     if (lpWaveHdr)
2121     {
2122         lpWaveHdr->lpNext = NULL;
2123         lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2124         lpWaveHdr->dwFlags |= WHDR_DONE;
2125         widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2126     }
2127
2128     return ret;
2129 }
2130
2131
2132 /**************************************************************************
2133  *                      widReset                                [internal]
2134  */
2135 static DWORD widReset(WORD wDevID)
2136 {
2137     DWORD           ret = MMSYSERR_NOERROR;
2138     WINE_WAVEIN*    wwi;
2139     WAVEHDR*        lpWaveHdr = NULL;
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     OSSpinLockLock(&wwi->lock);
2150
2151     if (wwi->state == WINE_WS_CLOSED)
2152     {
2153         WARN("Trying to reset a closed device.\n");
2154         ret = MMSYSERR_INVALHANDLE;
2155     }
2156     else
2157     {
2158         lpWaveHdr               = wwi->lpQueuePtr;
2159         wwi->lpQueuePtr         = NULL;
2160         wwi->state              = WINE_WS_STOPPED;
2161         wwi->dwTotalRecorded    = 0;
2162     }
2163
2164     OSSpinLockUnlock(&wwi->lock);
2165
2166     if (ret == MMSYSERR_NOERROR)
2167     {
2168         OSStatus err = AudioOutputUnitStop(wwi->audioUnit);
2169         if (err != noErr)
2170             WARN("Failed to stop AU: %08lx\n", err);
2171
2172         TRACE("Recording stopped.\n");
2173     }
2174
2175     while (lpWaveHdr)
2176     {
2177         WAVEHDR* lpNext = lpWaveHdr->lpNext;
2178
2179         lpWaveHdr->lpNext = NULL;
2180         lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2181         lpWaveHdr->dwFlags |= WHDR_DONE;
2182         widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2183
2184         lpWaveHdr = lpNext;
2185     }
2186
2187     return ret;
2188 }
2189
2190
2191 /**************************************************************************
2192  *                              widGetNumDevs                   [internal]
2193  */
2194 static DWORD widGetNumDevs(void)
2195 {
2196     return MAX_WAVEINDRV;
2197 }
2198
2199
2200 /**************************************************************************
2201  *                              widDevInterfaceSize             [internal]
2202  */
2203 static DWORD widDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
2204 {
2205     TRACE("(%u, %p)\n", wDevID, dwParam1);
2206
2207     *dwParam1 = MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
2208                                     NULL, 0 ) * sizeof(WCHAR);
2209     return MMSYSERR_NOERROR;
2210 }
2211
2212
2213 /**************************************************************************
2214  *                              widDevInterface                 [internal]
2215  */
2216 static DWORD widDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
2217 {
2218     if (dwParam2 >= MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
2219                                         NULL, 0 ) * sizeof(WCHAR))
2220     {
2221         MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
2222                             dwParam1, dwParam2 / sizeof(WCHAR));
2223         return MMSYSERR_NOERROR;
2224     }
2225     return MMSYSERR_INVALPARAM;
2226 }
2227
2228
2229 /**************************************************************************
2230  *                              widDsCreate                     [internal]
2231  */
2232 static DWORD widDsCreate(UINT wDevID, PIDSCDRIVER* drv)
2233 {
2234     TRACE("(%d,%p)\n",wDevID,drv);
2235
2236     FIXME("DirectSoundCapture not implemented\n");
2237     FIXME("The (slower) DirectSound HEL mode will be used instead.\n");
2238     return MMSYSERR_NOTSUPPORTED;
2239 }
2240
2241 /**************************************************************************
2242  *                              widDsDesc                       [internal]
2243  */
2244 static DWORD widDsDesc(UINT wDevID, PDSDRIVERDESC desc)
2245 {
2246     /* The DirectSound HEL will automatically wrap a non-DirectSound-capable
2247      * driver in a DirectSound adaptor, thus allowing the driver to be used by
2248      * DirectSound clients.  However, it only does this if we respond
2249      * successfully to the DRV_QUERYDSOUNDDESC message.  It's enough to fill in
2250      * the driver and device names of the description output parameter. */
2251     memset(desc, 0, sizeof(*desc));
2252     lstrcpynA(desc->szDrvname, "winecoreaudio.drv", sizeof(desc->szDrvname) - 1);
2253     lstrcpynA(desc->szDesc, WInDev[wDevID].interface_name, sizeof(desc->szDesc) - 1);
2254     return MMSYSERR_NOERROR;
2255 }
2256
2257
2258 /**************************************************************************
2259  *                              widMessage (WINECOREAUDIO.6)
2260  */
2261 DWORD WINAPI CoreAudio_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2262                             DWORD dwParam1, DWORD dwParam2)
2263 {
2264     TRACE("(%u, %04X, %08X, %08X, %08X);\n",
2265             wDevID, wMsg, dwUser, dwParam1, dwParam2);
2266
2267     switch (wMsg)
2268     {
2269         case DRVM_INIT:
2270         case DRVM_EXIT:
2271         case DRVM_ENABLE:
2272         case DRVM_DISABLE:
2273             /* FIXME: Pretend this is supported */
2274             return 0;
2275         case WIDM_OPEN:             return widOpen          (wDevID, (LPWAVEOPENDESC)dwParam1,  dwParam2);
2276         case WIDM_CLOSE:            return widClose         (wDevID);
2277         case WIDM_ADDBUFFER:        return widAddBuffer     (wDevID, (LPWAVEHDR)dwParam1,       dwParam2);
2278         case WIDM_PREPARE:          return MMSYSERR_NOTSUPPORTED;
2279         case WIDM_UNPREPARE:        return MMSYSERR_NOTSUPPORTED;
2280         case WIDM_GETDEVCAPS:       return widGetDevCaps    (wDevID, (LPWAVEINCAPSW)dwParam1,   dwParam2);
2281         case WIDM_GETNUMDEVS:       return widGetNumDevs    ();
2282         case WIDM_RESET:            return widReset         (wDevID);
2283         case WIDM_START:            return widStart         (wDevID);
2284         case WIDM_STOP:             return widStop          (wDevID);
2285         case DRV_QUERYDEVICEINTERFACESIZE: return widDevInterfaceSize       (wDevID, (LPDWORD)dwParam1);
2286         case DRV_QUERYDEVICEINTERFACE:     return widDevInterface           (wDevID, (PWCHAR)dwParam1, dwParam2);
2287         case DRV_QUERYDSOUNDIFACE:  return widDsCreate   (wDevID, (PIDSCDRIVER*)dwParam1);
2288         case DRV_QUERYDSOUNDDESC:   return widDsDesc     (wDevID, (PDSDRIVERDESC)dwParam1);
2289         default:
2290             FIXME("unknown message %d!\n", wMsg);
2291     }
2292
2293     return MMSYSERR_NOTSUPPORTED;
2294 }
2295
2296
2297 OSStatus CoreAudio_wiAudioUnitIOProc(void *inRefCon,
2298                                      AudioUnitRenderActionFlags *ioActionFlags,
2299                                      const AudioTimeStamp *inTimeStamp,
2300                                      UInt32 inBusNumber,
2301                                      UInt32 inNumberFrames,
2302                                      AudioBufferList *ioData)
2303 {
2304     WINE_WAVEIN*    wwi = (WINE_WAVEIN*)inRefCon;
2305     OSStatus        err = noErr;
2306     BOOL            needNotify = FALSE;
2307     WAVEHDR*        lpStorePtr;
2308     unsigned int    dataToStore;
2309     unsigned int    dataStored = 0;
2310
2311
2312     if (wwi->trace_on)
2313         fprintf(stderr, "trace:wave:CoreAudio_wiAudioUnitIOProc (ioActionFlags = %08lx, "
2314             "inTimeStamp = { %f, %x%08x, %f, %x%08x, %08lx }, inBusNumber = %lu, inNumberFrames = %lu)\n",
2315             *ioActionFlags, inTimeStamp->mSampleTime, (DWORD)(inTimeStamp->mHostTime >>32),
2316             (DWORD)inTimeStamp->mHostTime, inTimeStamp->mRateScalar, (DWORD)(inTimeStamp->mWordClockTime >> 32),
2317             (DWORD)inTimeStamp->mWordClockTime, inTimeStamp->mFlags, inBusNumber, inNumberFrames);
2318
2319     /* Render into audio buffer */
2320     /* FIXME: implement sample rate conversion on input.  This will require
2321      * a different render strategy.  We'll need to buffer the sound data
2322      * received here and pass it off to an AUConverter in another thread. */
2323     err = AudioUnitRender(wwi->audioUnit, ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, wwi->bufferList);
2324     if (err)
2325     {
2326         if (wwi->err_on)
2327             fprintf(stderr, "err:wave:CoreAudio_wiAudioUnitIOProc AudioUnitRender failed with error %li\n", err);
2328         return err;
2329     }
2330
2331     /* Copy from audio buffer to the wavehdrs */
2332     dataToStore = wwi->bufferList->mBuffers[0].mDataByteSize;
2333
2334     OSSpinLockLock(&wwi->lock);
2335
2336     lpStorePtr = wwi->lpQueuePtr;
2337
2338     while (dataToStore > 0 && wwi->state == WINE_WS_PLAYING && lpStorePtr)
2339     {
2340         unsigned int room = lpStorePtr->dwBufferLength - lpStorePtr->dwBytesRecorded;
2341         unsigned int toCopy;
2342
2343         if (wwi->trace_on)
2344             fprintf(stderr, "trace:wave:CoreAudio_wiAudioUnitIOProc Looking to store %u bytes to wavehdr %p, which has room for %u\n",
2345                 dataToStore, lpStorePtr, room);
2346
2347         if (room >= dataToStore)
2348             toCopy = dataToStore;
2349         else
2350             toCopy = room;
2351
2352         if (toCopy > 0)
2353         {
2354             memcpy(lpStorePtr->lpData + lpStorePtr->dwBytesRecorded,
2355                 (char*)wwi->bufferList->mBuffers[0].mData + dataStored, toCopy);
2356             lpStorePtr->dwBytesRecorded += toCopy;
2357             wwi->dwTotalRecorded += toCopy;
2358             dataStored += toCopy;
2359             dataToStore -= toCopy;
2360             room -= toCopy;
2361         }
2362
2363         if (room == 0)
2364         {
2365             lpStorePtr = lpStorePtr->lpNext;
2366             needNotify = TRUE;
2367         }
2368     }
2369
2370     OSSpinLockUnlock(&wwi->lock);
2371
2372     /* Restore the audio buffer list structure from backup, in case
2373      * AudioUnitRender clobbered it.  (It modifies mDataByteSize and may even
2374      * give us a different mData buffer to avoid a copy.) */
2375     memcpy(wwi->bufferList, wwi->bufferListCopy, AUDIOBUFFERLISTSIZE(wwi->bufferList->mNumberBuffers));
2376
2377     if (needNotify) wodSendNotifyInputCompletionsMessage(wwi);
2378     return err;
2379 }
2380
2381 #else
2382
2383 /**************************************************************************
2384  *                              widMessage (WINECOREAUDIO.6)
2385  */
2386 DWORD WINAPI CoreAudio_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2387                             DWORD dwParam1, DWORD dwParam2)
2388 {
2389     FIXME("(%u, %04X, %08X, %08X, %08X): CoreAudio support not compiled into wine\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2390     return MMSYSERR_NOTENABLED;
2391 }
2392
2393 /**************************************************************************
2394 *                               wodMessage (WINECOREAUDIO.7)
2395 */
2396 DWORD WINAPI CoreAudio_wodMessage(WORD wDevID, WORD wMsg, DWORD dwUser, 
2397                                   DWORD dwParam1, DWORD dwParam2)
2398 {
2399     FIXME("(%u, %04X, %08X, %08X, %08X): CoreAudio support not compiled into wine\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2400     return MMSYSERR_NOTENABLED;
2401 }
2402
2403 #endif