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