wined3d: Remove IWineD3DSurface::GetImplType() from the public interface.
[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             DriverCallback(wwo->waveDesc.dwCallback, wwo->wFlags,
796                            (HDRVR)wwo->waveDesc.hWave, wMsg, wwo->waveDesc.dwInstance,
797                            dwParam1, dwParam2);
798             break;
799         default:
800             FIXME("Unknown callback message %u\n", wMsg);
801     }
802 }
803
804
805 /**************************************************************************
806 *                       wodGetDevCaps               [internal]
807 */
808 static DWORD wodGetDevCaps(WORD wDevID, LPWAVEOUTCAPSW lpCaps, DWORD dwSize)
809 {
810     TRACE("(%u, %p, %u);\n", wDevID, lpCaps, dwSize);
811     
812     if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
813     
814     if (wDevID >= MAX_WAVEOUTDRV)
815     {
816         TRACE("MAX_WAVOUTDRV reached !\n");
817         return MMSYSERR_BADDEVICEID;
818     }
819     
820     TRACE("dwSupport=(0x%x), dwFormats=(0x%x)\n", WOutDev[wDevID].caps.dwSupport, WOutDev[wDevID].caps.dwFormats);
821     memcpy(lpCaps, &WOutDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
822     return MMSYSERR_NOERROR;
823 }
824
825 /**************************************************************************
826 *                               wodOpen                         [internal]
827 */
828 static DWORD wodOpen(WORD wDevID, WINE_WAVEOUT_INSTANCE** pInstance, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
829 {
830     WINE_WAVEOUT_INSTANCE*      wwo;
831     DWORD               ret;
832     AudioStreamBasicDescription streamFormat;
833     AudioUnit           audioUnit = NULL;
834     BOOL                auInited  = FALSE;
835
836     TRACE("(%u, %p, %p, %08x);\n", wDevID, pInstance, lpDesc, dwFlags);
837     if (lpDesc == NULL)
838     {
839         WARN("Invalid Parameter !\n");
840         return MMSYSERR_INVALPARAM;
841     }
842     if (wDevID >= MAX_WAVEOUTDRV) {
843         TRACE("MAX_WAVOUTDRV reached !\n");
844         return MMSYSERR_BADDEVICEID;
845     }
846     
847     TRACE("Format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
848           lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
849           lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
850     
851     if (!supportedFormat(lpDesc->lpFormat))
852     {
853         WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
854              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
855              lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
856         return WAVERR_BADFORMAT;
857     }
858     
859     if (dwFlags & WAVE_FORMAT_QUERY)
860     {
861         TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
862               lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
863               lpDesc->lpFormat->nSamplesPerSec);
864         return MMSYSERR_NOERROR;
865     }
866
867     /* nBlockAlign and nAvgBytesPerSec are output variables for dsound */
868     if (lpDesc->lpFormat->nBlockAlign != lpDesc->lpFormat->nChannels*lpDesc->lpFormat->wBitsPerSample/8) {
869         lpDesc->lpFormat->nBlockAlign  = lpDesc->lpFormat->nChannels*lpDesc->lpFormat->wBitsPerSample/8;
870         WARN("Fixing nBlockAlign\n");
871     }
872     if (lpDesc->lpFormat->nAvgBytesPerSec!= lpDesc->lpFormat->nSamplesPerSec*lpDesc->lpFormat->nBlockAlign) {
873         lpDesc->lpFormat->nAvgBytesPerSec = lpDesc->lpFormat->nSamplesPerSec*lpDesc->lpFormat->nBlockAlign;
874         WARN("Fixing nAvgBytesPerSec\n");
875     }
876
877     /* We proceed in three phases:
878      * o Allocate the device instance, marking it as opening
879      * o Create, configure, and start the Audio Unit.  To avoid deadlock,
880      *   this has to be done without holding wwo->lock.
881      * o If that was successful, finish setting up our instance and add it
882      *   to the device's list.
883      *   Otherwise, clean up and deallocate the instance.
884      */
885     wwo = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*wwo));
886     if (!wwo)
887         return MMSYSERR_NOMEM;
888
889     wwo->woID = wDevID;
890     wwo->state = WINE_WS_OPENING;
891
892     if (!AudioUnit_CreateDefaultAudioUnit((void *) wwo, &audioUnit))
893     {
894         ERR("CoreAudio_CreateDefaultAudioUnit(0x%04x) failed\n", wDevID);
895         ret = MMSYSERR_ERROR;
896         goto error;
897     }
898
899     streamFormat.mFormatID = kAudioFormatLinearPCM;
900     streamFormat.mFormatFlags = kLinearPCMFormatFlagIsPacked;
901     /* FIXME check for 32bits float -> kLinearPCMFormatFlagIsFloat */
902     if (lpDesc->lpFormat->wBitsPerSample != 8)
903         streamFormat.mFormatFlags |= kLinearPCMFormatFlagIsSignedInteger;
904 # ifdef WORDS_BIGENDIAN
905     streamFormat.mFormatFlags |= kLinearPCMFormatFlagIsBigEndian; /* FIXME Wave format is little endian */
906 # endif
907
908     streamFormat.mSampleRate = lpDesc->lpFormat->nSamplesPerSec;
909     streamFormat.mChannelsPerFrame = lpDesc->lpFormat->nChannels;       
910     streamFormat.mFramesPerPacket = 1;  
911     streamFormat.mBitsPerChannel = lpDesc->lpFormat->wBitsPerSample;
912     streamFormat.mBytesPerFrame = streamFormat.mBitsPerChannel * streamFormat.mChannelsPerFrame / 8;    
913     streamFormat.mBytesPerPacket = streamFormat.mBytesPerFrame * streamFormat.mFramesPerPacket;         
914
915     ret = AudioUnit_InitializeWithStreamDescription(audioUnit, &streamFormat);
916     if (!ret) 
917     {
918         ret = WAVERR_BADFORMAT; /* FIXME return an error based on the OSStatus */
919         goto error;
920     }
921     auInited = TRUE;
922
923     AudioUnit_SetVolume(audioUnit, LOWORD(WOutDev[wDevID].device_volume) / 65535.0f,
924                         HIWORD(WOutDev[wDevID].device_volume) / 65535.0f);
925
926     /* Our render callback CoreAudio_woAudioUnitIOProc may be called before
927      * AudioOutputUnitStart returns.  Core Audio will grab its own internal
928      * lock before calling it and the callback grabs wwo->lock.  This would
929      * deadlock if we were holding wwo->lock.
930      * Also, the callback has to safely do nothing in that case, because
931      * wwo hasn't been completely filled out, yet. This is assured by state
932      * being WINE_WS_OPENING. */
933     ret = AudioOutputUnitStart(audioUnit);
934     if (ret)
935     {
936         ERR("AudioOutputUnitStart failed: %08x\n", ret);
937         ret = MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
938         goto error;
939     }
940
941
942     OSSpinLockLock(&wwo->lock);
943     assert(wwo->state == WINE_WS_OPENING);
944
945     wwo->audioUnit = audioUnit;
946     wwo->streamDescription = streamFormat;
947
948     wwo->state = WINE_WS_PLAYING;
949
950     wwo->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
951
952     wwo->waveDesc = *lpDesc;
953     copyFormat(lpDesc->lpFormat, &wwo->format);
954
955     WOutDev[wDevID].trace_on = TRACE_ON(wave);
956     WOutDev[wDevID].warn_on  = WARN_ON(wave);
957     WOutDev[wDevID].err_on   = ERR_ON(wave);
958
959     OSSpinLockUnlock(&wwo->lock);
960
961     OSSpinLockLock(&WOutDev[wDevID].lock);
962     list_add_head(&WOutDev[wDevID].instances, &wwo->entry);
963     OSSpinLockUnlock(&WOutDev[wDevID].lock);
964
965     *pInstance = wwo;
966     TRACE("opened instance %p\n", wwo);
967
968     wodNotifyClient(wwo, WOM_OPEN, 0L, 0L);
969     
970     return MMSYSERR_NOERROR;
971
972 error:
973     if (audioUnit)
974     {
975         if (auInited)
976             AudioUnitUninitialize(audioUnit);
977         AudioUnit_CloseAudioUnit(audioUnit);
978     }
979
980     OSSpinLockLock(&wwo->lock);
981     assert(wwo->state == WINE_WS_OPENING);
982     /* OSSpinLockUnlock(&wwo->lock); *//* No need, about to free */
983     HeapFree(GetProcessHeap(), 0, wwo);
984
985     return ret;
986 }
987
988 /**************************************************************************
989 *                               wodClose                        [internal]
990 */
991 static DWORD wodClose(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo)
992 {
993     DWORD               ret = MMSYSERR_NOERROR;
994     
995     TRACE("(%u, %p);\n", wDevID, wwo);
996     
997     if (wDevID >= MAX_WAVEOUTDRV)
998     {
999         WARN("bad device ID !\n");
1000         return MMSYSERR_BADDEVICEID;
1001     }
1002     
1003     OSSpinLockLock(&wwo->lock);
1004     if (wwo->lpQueuePtr)
1005     {
1006         OSSpinLockUnlock(&wwo->lock);
1007         WARN("buffers still playing !\n");
1008         return WAVERR_STILLPLAYING;
1009     } else
1010     {
1011         OSStatus err;
1012         AudioUnit audioUnit = wwo->audioUnit;
1013
1014         /* sanity check: this should not happen since the device must have been reset before */
1015         if (wwo->lpQueuePtr || wwo->lpPlayPtr) ERR("out of sync\n");
1016         
1017         wwo->state = WINE_WS_CLOSING; /* mark the device as closing */
1018         wwo->audioUnit = NULL;
1019         
1020         OSSpinLockUnlock(&wwo->lock);
1021
1022         err = AudioUnitUninitialize(audioUnit);
1023         if (err) {
1024             ERR("AudioUnitUninitialize return %s\n", wine_dbgstr_fourcc(err));
1025             return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1026         }
1027         
1028         if ( !AudioUnit_CloseAudioUnit(audioUnit) )
1029         {
1030             ERR("Can't close AudioUnit\n");
1031             return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1032         }  
1033         
1034         OSSpinLockLock(&WOutDev[wDevID].lock);
1035         list_remove(&wwo->entry);
1036         OSSpinLockUnlock(&WOutDev[wDevID].lock);
1037
1038         wodNotifyClient(wwo, WOM_CLOSE, 0L, 0L);
1039
1040         HeapFree(GetProcessHeap(), 0, wwo);
1041     }
1042     
1043     return ret;
1044 }
1045
1046 /**************************************************************************
1047 *                               wodPrepare                      [internal]
1048 */
1049 static DWORD wodPrepare(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1050 {
1051     TRACE("(%u, %p, %p, %08x);\n", wDevID, wwo, lpWaveHdr, dwSize);
1052     
1053     if (wDevID >= MAX_WAVEOUTDRV) {
1054         WARN("bad device ID !\n");
1055         return MMSYSERR_BADDEVICEID;
1056     }
1057     
1058     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1059         return WAVERR_STILLPLAYING;
1060     
1061     lpWaveHdr->dwFlags |= WHDR_PREPARED;
1062     lpWaveHdr->dwFlags &= ~WHDR_DONE;
1063
1064     return MMSYSERR_NOERROR;
1065 }
1066
1067 /**************************************************************************
1068 *                               wodUnprepare                    [internal]
1069 */
1070 static DWORD wodUnprepare(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1071 {
1072     TRACE("(%u, %p, %p, %08x);\n", wDevID, wwo, lpWaveHdr, dwSize);
1073     
1074     if (wDevID >= MAX_WAVEOUTDRV) {
1075         WARN("bad device ID !\n");
1076         return MMSYSERR_BADDEVICEID;
1077     }
1078     
1079     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1080         return WAVERR_STILLPLAYING;
1081     
1082     lpWaveHdr->dwFlags &= ~WHDR_PREPARED;
1083     lpWaveHdr->dwFlags |= WHDR_DONE;
1084    
1085     return MMSYSERR_NOERROR;
1086 }
1087
1088
1089 /**************************************************************************
1090 *                               wodHelper_CheckForLoopBegin             [internal]
1091 *
1092 * Check if the new waveheader is the beginning of a loop, and set up
1093 * state if so.
1094 * This is called with the WAVEOUT_INSTANCE lock held.
1095 * Call from AudioUnit IO thread can't use Wine debug channels.
1096 */
1097 static void wodHelper_CheckForLoopBegin(WINE_WAVEOUT_INSTANCE* wwo)
1098 {
1099     LPWAVEHDR lpWaveHdr = wwo->lpPlayPtr;
1100
1101     if (lpWaveHdr->dwFlags & WHDR_BEGINLOOP)
1102     {
1103         if (wwo->lpLoopPtr)
1104         {
1105             if (WOutDev[wwo->woID].warn_on)
1106                 fprintf(stderr, "warn:winecoreaudio:wodHelper_CheckForLoopBegin Already in a loop. Discarding loop on this header (%p)\n", lpWaveHdr);
1107         }
1108         else
1109         {
1110             if (WOutDev[wwo->woID].trace_on)
1111                 fprintf(stderr, "trace:winecoreaudio:wodHelper_CheckForLoopBegin Starting loop (%dx) with %p\n", lpWaveHdr->dwLoops, lpWaveHdr);
1112
1113             wwo->lpLoopPtr = lpWaveHdr;
1114             /* Windows does not touch WAVEHDR.dwLoops,
1115                 * so we need to make an internal copy */
1116             wwo->dwLoops = lpWaveHdr->dwLoops;
1117         }
1118     }
1119 }
1120
1121
1122 /**************************************************************************
1123 *                               wodHelper_PlayPtrNext           [internal]
1124 *
1125 * Advance the play pointer to the next waveheader, looping if required.
1126 * This is called with the WAVEOUT_INSTANCE lock held.
1127 * Call from AudioUnit IO thread can't use Wine debug channels.
1128 */
1129 static void wodHelper_PlayPtrNext(WINE_WAVEOUT_INSTANCE* wwo)
1130 {
1131     BOOL didLoopBack = FALSE;
1132
1133     wwo->dwPartialOffset = 0;
1134     if ((wwo->lpPlayPtr->dwFlags & WHDR_ENDLOOP) && wwo->lpLoopPtr)
1135     {
1136         /* We're at the end of a loop, loop if required */
1137         if (wwo->dwLoops > 1)
1138         {
1139             wwo->dwLoops--;
1140             wwo->lpPlayPtr = wwo->lpLoopPtr;
1141             didLoopBack = TRUE;
1142         }
1143         else
1144         {
1145             wwo->lpLoopPtr = NULL;
1146         }
1147     }
1148     if (!didLoopBack)
1149     {
1150         /* We didn't loop back.  Advance to the next wave header */
1151         wwo->lpPlayPtr = wwo->lpPlayPtr->lpNext;
1152
1153         if (wwo->lpPlayPtr)
1154             wodHelper_CheckForLoopBegin(wwo);
1155     }
1156 }
1157
1158 /* Send the "done" notification for each WAVEHDR in a list.  The list must be
1159  * free-standing.  It should not be part of a device instance's queue.
1160  * This function must be called with the WAVEOUT_INSTANCE lock *not* held.
1161  * Furthermore, it does not lock it, itself.  That's because the callback to the
1162  * application may prompt the application to operate on the device, and we don't
1163  * want to deadlock.
1164  */
1165 static void wodHelper_NotifyDoneForList(WINE_WAVEOUT_INSTANCE* wwo, LPWAVEHDR lpWaveHdr)
1166 {
1167     while (lpWaveHdr)
1168     {
1169         LPWAVEHDR lpNext = lpWaveHdr->lpNext;
1170
1171         lpWaveHdr->lpNext = NULL;
1172         lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1173         lpWaveHdr->dwFlags |= WHDR_DONE;
1174         wodNotifyClient(wwo, WOM_DONE, (DWORD_PTR)lpWaveHdr, 0);
1175
1176         lpWaveHdr = lpNext;
1177     }
1178 }
1179
1180 /* if force is TRUE then notify the client that all the headers were completed
1181  */
1182 static void wodHelper_NotifyCompletions(WINE_WAVEOUT_INSTANCE* wwo, BOOL force)
1183 {
1184     LPWAVEHDR lpFirstDoneWaveHdr = NULL;
1185
1186     OSSpinLockLock(&wwo->lock);
1187
1188     /* First, excise all of the done headers from the queue into
1189      * a free-standing list. */
1190     if (force)
1191     {
1192         lpFirstDoneWaveHdr = wwo->lpQueuePtr;
1193         wwo->lpQueuePtr = NULL;
1194     }
1195     else
1196     {
1197         LPWAVEHDR lpWaveHdr;
1198         LPWAVEHDR lpLastDoneWaveHdr = NULL;
1199
1200         /* Start from lpQueuePtr and keep notifying until:
1201             * - we hit an unwritten wavehdr
1202             * - we hit the beginning of a running loop
1203             * - we hit a wavehdr which hasn't finished playing
1204             */
1205         for (
1206             lpWaveHdr = wwo->lpQueuePtr;
1207             lpWaveHdr &&
1208                 lpWaveHdr != wwo->lpPlayPtr &&
1209                 lpWaveHdr != wwo->lpLoopPtr;
1210             lpWaveHdr = lpWaveHdr->lpNext
1211             )
1212         {
1213             if (!lpFirstDoneWaveHdr)
1214                 lpFirstDoneWaveHdr = lpWaveHdr;
1215             lpLastDoneWaveHdr = lpWaveHdr;
1216         }
1217
1218         if (lpLastDoneWaveHdr)
1219         {
1220             wwo->lpQueuePtr = lpLastDoneWaveHdr->lpNext;
1221             lpLastDoneWaveHdr->lpNext = NULL;
1222         }
1223     }
1224     
1225     OSSpinLockUnlock(&wwo->lock);
1226
1227     /* Now, send the "done" notification for each header in our list. */
1228     wodHelper_NotifyDoneForList(wwo, lpFirstDoneWaveHdr);
1229 }
1230
1231
1232 /**************************************************************************
1233 *                               wodWrite                        [internal]
1234
1235 */
1236 static DWORD wodWrite(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1237 {
1238     LPWAVEHDR*wh;
1239     
1240     TRACE("(%u, %p, %p, %lu, %08X);\n", wDevID, wwo, lpWaveHdr, (unsigned long)lpWaveHdr->dwBufferLength, dwSize);
1241     
1242     /* first, do the sanity checks... */
1243     if (wDevID >= MAX_WAVEOUTDRV)
1244     {
1245         WARN("bad dev ID !\n");
1246         return MMSYSERR_BADDEVICEID;
1247     }
1248     
1249     if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
1250     {
1251         TRACE("unprepared\n");
1252         return WAVERR_UNPREPARED;
1253     }
1254     
1255     if (lpWaveHdr->dwFlags & WHDR_INQUEUE) 
1256     {
1257         TRACE("still playing\n");
1258         return WAVERR_STILLPLAYING;
1259     }
1260     
1261     lpWaveHdr->dwFlags &= ~WHDR_DONE;
1262     lpWaveHdr->dwFlags |= WHDR_INQUEUE;
1263     lpWaveHdr->lpNext = 0;
1264
1265     OSSpinLockLock(&wwo->lock);
1266     /* insert buffer at the end of queue */
1267     for (wh = &(wwo->lpQueuePtr); *wh; wh = &((*wh)->lpNext))
1268         /* Do nothing */;
1269     *wh = lpWaveHdr;
1270     
1271     if (!wwo->lpPlayPtr)
1272     {
1273         wwo->lpPlayPtr = lpWaveHdr;
1274
1275         wodHelper_CheckForLoopBegin(wwo);
1276
1277         wwo->dwPartialOffset = 0;
1278     }
1279     OSSpinLockUnlock(&wwo->lock);
1280
1281     return MMSYSERR_NOERROR;
1282 }
1283
1284 /**************************************************************************
1285 *                       wodPause                                [internal]
1286 */
1287 static DWORD wodPause(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo)
1288 {
1289     OSStatus status;
1290
1291     TRACE("(%u, %p);!\n", wDevID, wwo);
1292     
1293     if (wDevID >= MAX_WAVEOUTDRV)
1294     {
1295         WARN("bad device ID !\n");
1296         return MMSYSERR_BADDEVICEID;
1297     }
1298
1299     /* The order of the following operations is important since we can't hold
1300      * the mutex while we make an Audio Unit call.  Stop the Audio Unit before
1301      * setting the PAUSED state.  In wodRestart, the order is reversed.  This
1302      * guarantees that we can't get into a situation where the state is
1303      * PLAYING but the Audio Unit isn't running.  Although we can be in PAUSED
1304      * state with the Audio Unit still running, that's harmless because the
1305      * render callback will just produce silence.
1306      */
1307     status = AudioOutputUnitStop(wwo->audioUnit);
1308     if (status)
1309         WARN("AudioOutputUnitStop return %s\n", wine_dbgstr_fourcc(status));
1310
1311     OSSpinLockLock(&wwo->lock);
1312     if (wwo->state == WINE_WS_PLAYING)
1313         wwo->state = WINE_WS_PAUSED;
1314     OSSpinLockUnlock(&wwo->lock);
1315
1316     return MMSYSERR_NOERROR;
1317 }
1318
1319 /**************************************************************************
1320 *                       wodRestart                              [internal]
1321 */
1322 static DWORD wodRestart(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo)
1323 {
1324     OSStatus status;
1325
1326     TRACE("(%u, %p);\n", wDevID, wwo);
1327     
1328     if (wDevID >= MAX_WAVEOUTDRV )
1329     {
1330         WARN("bad device ID !\n");
1331         return MMSYSERR_BADDEVICEID;
1332     }
1333
1334     /* The order of the following operations is important since we can't hold
1335      * the mutex while we make an Audio Unit call.  Set the PLAYING
1336      * state before starting the Audio Unit.  In wodPause, the order is
1337      * reversed.  This guarantees that we can't get into a situation where
1338      * the state is PLAYING but the Audio Unit isn't running.
1339      * Although we can be in PAUSED state with the Audio Unit still running,
1340      * that's harmless because the render callback will just produce silence.
1341      */
1342     OSSpinLockLock(&wwo->lock);
1343     if (wwo->state == WINE_WS_PAUSED)
1344         wwo->state = WINE_WS_PLAYING;
1345     OSSpinLockUnlock(&wwo->lock);
1346
1347     status = AudioOutputUnitStart(wwo->audioUnit);
1348     if (status) {
1349         ERR("AudioOutputUnitStart return %s\n", wine_dbgstr_fourcc(status));
1350         return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1351     }
1352
1353     return MMSYSERR_NOERROR;
1354 }
1355
1356 /**************************************************************************
1357 *                       wodReset                                [internal]
1358 */
1359 static DWORD wodReset(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo)
1360 {
1361     OSStatus status;
1362     LPWAVEHDR lpSavedQueuePtr;
1363
1364     TRACE("(%u, %p);\n", wDevID, wwo);
1365
1366     if (wDevID >= MAX_WAVEOUTDRV)
1367     {
1368         WARN("bad device ID !\n");
1369         return MMSYSERR_BADDEVICEID;
1370     }
1371
1372     OSSpinLockLock(&wwo->lock);
1373
1374     if (wwo->state == WINE_WS_CLOSING || wwo->state == WINE_WS_OPENING)
1375     {
1376         OSSpinLockUnlock(&wwo->lock);
1377         WARN("resetting a closed device\n");
1378         return MMSYSERR_INVALHANDLE;
1379     }
1380
1381     lpSavedQueuePtr = wwo->lpQueuePtr;
1382     wwo->lpPlayPtr = wwo->lpQueuePtr = wwo->lpLoopPtr = NULL;
1383     wwo->state = WINE_WS_PLAYING;
1384     wwo->dwPlayedTotal = 0;
1385
1386     wwo->dwPartialOffset = 0;        /* Clear partial wavehdr */
1387
1388     OSSpinLockUnlock(&wwo->lock);
1389
1390     status = AudioOutputUnitStart(wwo->audioUnit);
1391
1392     if (status) {
1393         ERR( "AudioOutputUnitStart return %s\n", wine_dbgstr_fourcc(status));
1394         return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1395     }
1396
1397     /* Now, send the "done" notification for each header in our list. */
1398     /* Do this last so the reset operation is effectively complete before the
1399      * app does whatever it's going to do in response to these notifications. */
1400     wodHelper_NotifyDoneForList(wwo, lpSavedQueuePtr);
1401
1402     return MMSYSERR_NOERROR;
1403 }
1404
1405 /**************************************************************************
1406 *           wodBreakLoop                [internal]
1407 */
1408 static DWORD wodBreakLoop(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo)
1409 {
1410     TRACE("(%u, %p);\n", wDevID, wwo);
1411
1412     if (wDevID >= MAX_WAVEOUTDRV)
1413     {
1414         WARN("bad device ID !\n");
1415         return MMSYSERR_BADDEVICEID;
1416     }
1417
1418     OSSpinLockLock(&wwo->lock);
1419
1420     if (wwo->lpLoopPtr != NULL)
1421     {
1422         /* ensure exit at end of current loop */
1423         wwo->dwLoops = 1;
1424     }
1425
1426     OSSpinLockUnlock(&wwo->lock);
1427
1428     return MMSYSERR_NOERROR;
1429 }
1430
1431 /**************************************************************************
1432 *                               wodGetPosition                  [internal]
1433 */
1434 static DWORD wodGetPosition(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, LPMMTIME lpTime, DWORD uSize)
1435 {
1436     DWORD               val;
1437
1438     TRACE("(%u, %p, %p, %u);\n", wDevID, wwo, lpTime, uSize);
1439     
1440     if (wDevID >= MAX_WAVEOUTDRV)
1441     {
1442         WARN("bad device ID !\n");
1443         return MMSYSERR_BADDEVICEID;
1444     }
1445     
1446     /* if null pointer to time structure return error */
1447     if (lpTime == NULL) return MMSYSERR_INVALPARAM;
1448     
1449     OSSpinLockLock(&wwo->lock);
1450     val = wwo->dwPlayedTotal;
1451     OSSpinLockUnlock(&wwo->lock);
1452     
1453     return bytes_to_mmtime(lpTime, val, &wwo->format);
1454 }
1455
1456 /**************************************************************************
1457 *                               wodGetVolume                    [internal]
1458 */
1459 static DWORD wodGetVolume(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, LPDWORD lpdwVol)
1460 {
1461     if (wDevID >= MAX_WAVEOUTDRV)
1462     {
1463         WARN("bad device ID !\n");
1464         return MMSYSERR_BADDEVICEID;
1465     }    
1466     
1467     TRACE("(%u, %p, %p);\n", wDevID, wwo, lpdwVol);
1468
1469     if (wwo)
1470     {
1471         float left;
1472         float right;
1473
1474         AudioUnit_GetVolume(wwo->audioUnit, &left, &right);
1475         *lpdwVol = (WORD)(left * 0xFFFFl) + ((WORD)(right * 0xFFFFl) << 16);
1476     }
1477     else
1478         *lpdwVol = WOutDev[wDevID].device_volume;
1479
1480     return MMSYSERR_NOERROR;
1481 }
1482
1483 /**************************************************************************
1484 *                               wodSetVolume                    [internal]
1485 */
1486 static DWORD wodSetVolume(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, DWORD dwParam)
1487 {
1488     float left;
1489     float right;
1490     
1491     if (wDevID >= MAX_WAVEOUTDRV)
1492     {
1493         WARN("bad device ID !\n");
1494         return MMSYSERR_BADDEVICEID;
1495     }
1496
1497     left  = LOWORD(dwParam) / 65535.0f;
1498     right = HIWORD(dwParam) / 65535.0f;
1499     
1500     TRACE("(%u, %p, %08x);\n", wDevID, wwo, dwParam);
1501
1502     if (wwo)
1503         AudioUnit_SetVolume(wwo->audioUnit, left, right);
1504     else
1505     {
1506         OSSpinLockLock(&WOutDev[wDevID].lock);
1507         LIST_FOR_EACH_ENTRY(wwo, &WOutDev[wDevID].instances, WINE_WAVEOUT_INSTANCE, entry)
1508             AudioUnit_SetVolume(wwo->audioUnit, left, right);
1509         OSSpinLockUnlock(&WOutDev[wDevID].lock);
1510
1511         WOutDev[wDevID].device_volume = dwParam;
1512     }
1513
1514     return MMSYSERR_NOERROR;
1515 }
1516
1517 /**************************************************************************
1518 *                               wodGetNumDevs                   [internal]
1519 */
1520 static DWORD wodGetNumDevs(void)
1521 {
1522     TRACE("\n");
1523     return MAX_WAVEOUTDRV;
1524 }
1525
1526 /**************************************************************************
1527 *                              wodDevInterfaceSize             [internal]
1528 */
1529 static DWORD wodDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
1530 {
1531     TRACE("(%u, %p)\n", wDevID, dwParam1);
1532     
1533     *dwParam1 = MultiByteToWideChar(CP_UNIXCP, 0, WOutDev[wDevID].cadev->interface_name, -1,
1534                                     NULL, 0 ) * sizeof(WCHAR);
1535     return MMSYSERR_NOERROR;
1536 }
1537
1538 /**************************************************************************
1539 *                              wodDevInterface                 [internal]
1540 */
1541 static DWORD wodDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
1542 {
1543     TRACE("\n");
1544     if (dwParam2 >= MultiByteToWideChar(CP_UNIXCP, 0, WOutDev[wDevID].cadev->interface_name, -1,
1545                                         NULL, 0 ) * sizeof(WCHAR))
1546     {
1547         MultiByteToWideChar(CP_UNIXCP, 0, WOutDev[wDevID].cadev->interface_name, -1,
1548                             dwParam1, dwParam2 / sizeof(WCHAR));
1549         return MMSYSERR_NOERROR;
1550     }
1551     return MMSYSERR_INVALPARAM;
1552 }
1553
1554 /**************************************************************************
1555  *                              widDsCreate                     [internal]
1556  */
1557 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
1558 {
1559     TRACE("(%d,%p)\n",wDevID,drv);
1560
1561     FIXME("DirectSound not implemented\n");
1562     FIXME("The (slower) DirectSound HEL mode will be used instead.\n");
1563     return MMSYSERR_NOTSUPPORTED;
1564 }
1565
1566 /**************************************************************************
1567 *                              wodDsDesc                 [internal]
1568 */
1569 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc)
1570 {
1571     /* The DirectSound HEL will automatically wrap a non-DirectSound-capable
1572      * driver in a DirectSound adaptor, thus allowing the driver to be used by
1573      * DirectSound clients.  However, it only does this if we respond
1574      * successfully to the DRV_QUERYDSOUNDDESC message.  It's enough to fill in
1575      * the driver and device names of the description output parameter. */
1576     *desc = WOutDev[wDevID].cadev->ds_desc;
1577     return MMSYSERR_NOERROR;
1578 }
1579
1580 /**************************************************************************
1581 *                               wodMessage (WINECOREAUDIO.7)
1582 */
1583 DWORD WINAPI CoreAudio_wodMessage(UINT wDevID, UINT wMsg, DWORD_PTR dwUser,
1584                                   DWORD_PTR dwParam1, DWORD_PTR dwParam2)
1585 {
1586     WINE_WAVEOUT_INSTANCE* wwo = (WINE_WAVEOUT_INSTANCE*)dwUser;
1587
1588     TRACE("(%u, %s, %p, %p, %p);\n",
1589           wDevID, getMessage(wMsg), (void*)dwUser, (void*)dwParam1, (void*)dwParam2);
1590     
1591     switch (wMsg) {
1592         case DRVM_INIT:
1593         case DRVM_EXIT:
1594         case DRVM_ENABLE:
1595         case DRVM_DISABLE:
1596             
1597             /* FIXME: Pretend this is supported */
1598             return 0;
1599         case WODM_OPEN:         return wodOpen(wDevID, (WINE_WAVEOUT_INSTANCE**)dwUser, (LPWAVEOPENDESC) dwParam1, dwParam2);
1600         case WODM_CLOSE:        return wodClose(wDevID, wwo);
1601         case WODM_WRITE:        return wodWrite(wDevID, wwo, (LPWAVEHDR) dwParam1, dwParam2);
1602         case WODM_PAUSE:        return wodPause(wDevID, wwo);
1603         case WODM_GETPOS:       return wodGetPosition(wDevID, wwo, (LPMMTIME) dwParam1, dwParam2);
1604         case WODM_BREAKLOOP:    return wodBreakLoop(wDevID, wwo);
1605         case WODM_PREPARE:      return wodPrepare(wDevID, wwo, (LPWAVEHDR)dwParam1, dwParam2);
1606         case WODM_UNPREPARE:    return wodUnprepare(wDevID, wwo, (LPWAVEHDR)dwParam1, dwParam2);
1607             
1608         case WODM_GETDEVCAPS:   return wodGetDevCaps(wDevID, (LPWAVEOUTCAPSW) dwParam1, dwParam2);
1609         case WODM_GETNUMDEVS:   return wodGetNumDevs();  
1610             
1611         case WODM_GETPITCH:         
1612         case WODM_SETPITCH:        
1613         case WODM_GETPLAYBACKRATE:      
1614         case WODM_SETPLAYBACKRATE:      return MMSYSERR_NOTSUPPORTED;
1615         case WODM_GETVOLUME:    return wodGetVolume(wDevID, wwo, (LPDWORD)dwParam1);
1616         case WODM_SETVOLUME:    return wodSetVolume(wDevID, wwo, dwParam1);
1617         case WODM_RESTART:      return wodRestart(wDevID, wwo);
1618         case WODM_RESET:        return wodReset(wDevID, wwo);
1619             
1620         case DRV_QUERYDEVICEINTERFACESIZE:  return wodDevInterfaceSize (wDevID, (LPDWORD)dwParam1);
1621         case DRV_QUERYDEVICEINTERFACE:      return wodDevInterface (wDevID, (PWCHAR)dwParam1, dwParam2);
1622         case DRV_QUERYDSOUNDIFACE:  return wodDsCreate  (wDevID, (PIDSDRIVER*)dwParam1);
1623         case DRV_QUERYDSOUNDDESC:   return wodDsDesc    (wDevID, (PDSDRIVERDESC)dwParam1);
1624             
1625         default:
1626             FIXME("unknown message %d!\n", wMsg);
1627     }
1628     
1629     return MMSYSERR_NOTSUPPORTED;
1630 }
1631
1632 /*======================================================================*
1633 *                  Low level DSOUND implementation                      *
1634 *======================================================================*/
1635
1636 typedef struct IDsDriverImpl IDsDriverImpl;
1637 typedef struct IDsDriverBufferImpl IDsDriverBufferImpl;
1638
1639 struct IDsDriverImpl
1640 {
1641     /* IUnknown fields */
1642     const IDsDriverVtbl *lpVtbl;
1643     DWORD               ref;
1644     /* IDsDriverImpl fields */
1645     UINT                wDevID;
1646     IDsDriverBufferImpl*primary;
1647 };
1648
1649 struct IDsDriverBufferImpl
1650 {
1651     /* IUnknown fields */
1652     const IDsDriverBufferVtbl *lpVtbl;
1653     DWORD ref;
1654     /* IDsDriverBufferImpl fields */
1655     IDsDriverImpl* drv;
1656     DWORD buflen;
1657 };
1658
1659
1660 /*
1661     CoreAudio IO threaded callback,
1662     we can't call Wine debug channels, critical section or anything using NtCurrentTeb here.
1663 */
1664 OSStatus CoreAudio_woAudioUnitIOProc(void *inRefCon, 
1665                                      AudioUnitRenderActionFlags *ioActionFlags, 
1666                                      const AudioTimeStamp *inTimeStamp, 
1667                                      UInt32 inBusNumber, 
1668                                      UInt32 inNumberFrames, 
1669                                      AudioBufferList *ioData)
1670 {
1671     UInt32 buffer;
1672     WINE_WAVEOUT_INSTANCE* wwo = (WINE_WAVEOUT_INSTANCE*)inRefCon;
1673     int needNotify = 0;
1674
1675     unsigned int dataNeeded = ioData->mBuffers[0].mDataByteSize;
1676     unsigned int dataProvided = 0;
1677
1678     OSSpinLockLock(&wwo->lock);
1679
1680     /* We might have been called before wwo has been completely filled out by
1681      * wodOpen, or while it's being closed in wodClose.  We have to do nothing
1682      * in that case.  The check of wwo->state below ensures that. */
1683     while (dataNeeded > 0 && wwo->state == WINE_WS_PLAYING && wwo->lpPlayPtr)
1684     {
1685         unsigned int available = wwo->lpPlayPtr->dwBufferLength - wwo->dwPartialOffset;
1686         unsigned int toCopy;
1687
1688         if (available >= dataNeeded)
1689             toCopy = dataNeeded;
1690         else
1691             toCopy = available;
1692
1693         if (toCopy > 0)
1694         {
1695             memcpy((char*)ioData->mBuffers[0].mData + dataProvided,
1696                 wwo->lpPlayPtr->lpData + wwo->dwPartialOffset, toCopy);
1697             wwo->dwPartialOffset += toCopy;
1698             wwo->dwPlayedTotal += toCopy;
1699             dataProvided += toCopy;
1700             dataNeeded -= toCopy;
1701             available -= toCopy;
1702         }
1703
1704         if (available == 0)
1705         {
1706             wodHelper_PlayPtrNext(wwo);
1707             needNotify = 1;
1708         }
1709     }
1710     ioData->mBuffers[0].mDataByteSize = dataProvided;
1711
1712     OSSpinLockUnlock(&wwo->lock);
1713
1714     /* We can't provide any more wave data.  Fill the rest with silence. */
1715     if (dataNeeded > 0)
1716     {
1717         if (!dataProvided)
1718             *ioActionFlags |= kAudioUnitRenderAction_OutputIsSilence;
1719         memset((char*)ioData->mBuffers[0].mData + dataProvided, 0, dataNeeded);
1720         dataProvided += dataNeeded;
1721         dataNeeded = 0;
1722     }
1723
1724     /* We only fill buffer 0.  Set any others that might be requested to 0. */
1725     for (buffer = 1; buffer < ioData->mNumberBuffers; buffer++)
1726     {
1727         memset(ioData->mBuffers[buffer].mData, 0, ioData->mBuffers[buffer].mDataByteSize);
1728     }
1729
1730     if (needNotify) wodSendNotifyCompletionsMessage(wwo);
1731     return noErr;
1732 }
1733
1734
1735 /*======================================================================*
1736  *                  Low level WAVE IN implementation                    *
1737  *======================================================================*/
1738
1739 /**************************************************************************
1740  *                      widNotifyClient                 [internal]
1741  */
1742 static void widNotifyClient(WINE_WAVEIN* wwi, WORD wMsg, DWORD_PTR dwParam1, DWORD_PTR dwParam2)
1743 {
1744     TRACE("wMsg = 0x%04x dwParm1 = %04lX dwParam2 = %04lX\n", wMsg, dwParam1, dwParam2);
1745
1746     switch (wMsg)
1747     {
1748         case WIM_OPEN:
1749         case WIM_CLOSE:
1750         case WIM_DATA:
1751             DriverCallback(wwi->waveDesc.dwCallback, wwi->wFlags,
1752                            (HDRVR)wwi->waveDesc.hWave, wMsg, wwi->waveDesc.dwInstance,
1753                            dwParam1, dwParam2);
1754             break;
1755         default:
1756             FIXME("Unknown callback message %u\n", wMsg);
1757     }
1758 }
1759
1760
1761 /**************************************************************************
1762  *                      widHelper_NotifyCompletions              [internal]
1763  */
1764 static void widHelper_NotifyCompletions(WINE_WAVEIN* wwi)
1765 {
1766     LPWAVEHDR       lpWaveHdr;
1767     LPWAVEHDR       lpFirstDoneWaveHdr = NULL;
1768     LPWAVEHDR       lpLastDoneWaveHdr = NULL;
1769
1770     OSSpinLockLock(&wwi->lock);
1771
1772     /* First, excise all of the done headers from the queue into
1773      * a free-standing list. */
1774
1775     /* Start from lpQueuePtr and keep notifying until:
1776         * - we hit an unfilled wavehdr
1777         * - we hit the end of the list
1778         */
1779     for (
1780         lpWaveHdr = wwi->lpQueuePtr;
1781         lpWaveHdr &&
1782             lpWaveHdr->dwBytesRecorded >= lpWaveHdr->dwBufferLength;
1783         lpWaveHdr = lpWaveHdr->lpNext
1784         )
1785     {
1786         if (!lpFirstDoneWaveHdr)
1787             lpFirstDoneWaveHdr = lpWaveHdr;
1788         lpLastDoneWaveHdr = lpWaveHdr;
1789     }
1790
1791     if (lpLastDoneWaveHdr)
1792     {
1793         wwi->lpQueuePtr = lpLastDoneWaveHdr->lpNext;
1794         lpLastDoneWaveHdr->lpNext = NULL;
1795     }
1796
1797     OSSpinLockUnlock(&wwi->lock);
1798
1799     /* Now, send the "done" notification for each header in our list. */
1800     lpWaveHdr = lpFirstDoneWaveHdr;
1801     while (lpWaveHdr)
1802     {
1803         LPWAVEHDR lpNext = lpWaveHdr->lpNext;
1804
1805         lpWaveHdr->lpNext = NULL;
1806         lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1807         lpWaveHdr->dwFlags |= WHDR_DONE;
1808         widNotifyClient(wwi, WIM_DATA, (DWORD_PTR)lpWaveHdr, 0);
1809
1810         lpWaveHdr = lpNext;
1811     }
1812 }
1813
1814
1815 /**************************************************************************
1816  *                      widGetDevCaps                           [internal]
1817  */
1818 static DWORD widGetDevCaps(WORD wDevID, LPWAVEINCAPSW lpCaps, DWORD dwSize)
1819 {
1820     TRACE("(%u, %p, %u);\n", wDevID, lpCaps, dwSize);
1821
1822     if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
1823
1824     if (wDevID >= MAX_WAVEINDRV)
1825     {
1826         TRACE("MAX_WAVEINDRV reached !\n");
1827         return MMSYSERR_BADDEVICEID;
1828     }
1829
1830     memcpy(lpCaps, &WInDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
1831     return MMSYSERR_NOERROR;
1832 }
1833
1834
1835 /**************************************************************************
1836  *                    widHelper_DestroyAudioBufferList           [internal]
1837  * Convenience function to dispose of our audio buffers
1838  */
1839 static void widHelper_DestroyAudioBufferList(AudioBufferList* list)
1840 {
1841     if (list)
1842     {
1843         UInt32 i;
1844         for (i = 0; i < list->mNumberBuffers; i++)
1845         {
1846             if (list->mBuffers[i].mData)
1847                 HeapFree(GetProcessHeap(), 0, list->mBuffers[i].mData);
1848         }
1849         HeapFree(GetProcessHeap(), 0, list);
1850     }
1851 }
1852
1853
1854 #define AUDIOBUFFERLISTSIZE(numBuffers) (offsetof(AudioBufferList, mBuffers) + (numBuffers) * sizeof(AudioBuffer))
1855
1856 /**************************************************************************
1857  *                    widHelper_AllocateAudioBufferList          [internal]
1858  * Convenience function to allocate our audio buffers
1859  */
1860 static AudioBufferList* widHelper_AllocateAudioBufferList(UInt32 numChannels, UInt32 bitsPerChannel, UInt32 bufferFrames, BOOL interleaved)
1861 {
1862     UInt32                      numBuffers;
1863     UInt32                      channelsPerFrame;
1864     UInt32                      bytesPerFrame;
1865     UInt32                      bytesPerBuffer;
1866     AudioBufferList*            list;
1867     UInt32                      i;
1868
1869     if (interleaved)
1870     {
1871         /* For interleaved audio, we allocate one buffer for all channels. */
1872         numBuffers = 1;
1873         channelsPerFrame = numChannels;
1874     }
1875     else
1876     {
1877         numBuffers = numChannels;
1878         channelsPerFrame = 1;
1879     }
1880
1881     bytesPerFrame = bitsPerChannel * channelsPerFrame / 8;
1882     bytesPerBuffer = bytesPerFrame * bufferFrames;
1883
1884     list = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, AUDIOBUFFERLISTSIZE(numBuffers));
1885     if (list == NULL)
1886         return NULL;
1887
1888     list->mNumberBuffers = numBuffers;
1889     for (i = 0; i < numBuffers; ++i)
1890     {
1891         list->mBuffers[i].mNumberChannels = channelsPerFrame;
1892         list->mBuffers[i].mDataByteSize = bytesPerBuffer;
1893         list->mBuffers[i].mData = HeapAlloc(GetProcessHeap(), 0, bytesPerBuffer);
1894         if (list->mBuffers[i].mData == NULL)
1895         {
1896             widHelper_DestroyAudioBufferList(list);
1897             return NULL;
1898         }
1899     }
1900     return list;
1901 }
1902
1903
1904 /**************************************************************************
1905  *                              widOpen                         [internal]
1906  */
1907 static DWORD widOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
1908 {
1909     WINE_WAVEIN*    wwi;
1910     UInt32          frameCount;
1911
1912     TRACE("(%u, %p, %08X);\n", wDevID, lpDesc, dwFlags);
1913     if (lpDesc == NULL)
1914     {
1915         WARN("Invalid Parameter !\n");
1916         return MMSYSERR_INVALPARAM;
1917     }
1918     if (wDevID >= MAX_WAVEINDRV)
1919     {
1920         TRACE ("MAX_WAVEINDRV reached !\n");
1921         return MMSYSERR_BADDEVICEID;
1922     }
1923
1924     TRACE("Format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
1925           lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1926           lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
1927
1928     if (!supportedFormat(lpDesc->lpFormat) ||
1929         lpDesc->lpFormat->nSamplesPerSec != AudioUnit_GetInputDeviceSampleRate()
1930         )
1931     {
1932         WARN("Bad 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         return WAVERR_BADFORMAT;
1936     }
1937
1938     if (dwFlags & WAVE_FORMAT_QUERY)
1939     {
1940         TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
1941               lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1942               lpDesc->lpFormat->nSamplesPerSec);
1943         return MMSYSERR_NOERROR;
1944     }
1945
1946     /* nBlockAlign and nAvgBytesPerSec are output variables for dsound */
1947     if (lpDesc->lpFormat->nBlockAlign != lpDesc->lpFormat->nChannels*lpDesc->lpFormat->wBitsPerSample/8) {
1948         lpDesc->lpFormat->nBlockAlign  = lpDesc->lpFormat->nChannels*lpDesc->lpFormat->wBitsPerSample/8;
1949         WARN("Fixing nBlockAlign\n");
1950     }
1951     if (lpDesc->lpFormat->nAvgBytesPerSec!= lpDesc->lpFormat->nSamplesPerSec*lpDesc->lpFormat->nBlockAlign) {
1952         lpDesc->lpFormat->nAvgBytesPerSec = lpDesc->lpFormat->nSamplesPerSec*lpDesc->lpFormat->nBlockAlign;
1953         WARN("Fixing nAvgBytesPerSec\n");
1954     }
1955
1956     wwi = &WInDev[wDevID];
1957     if (!OSSpinLockTry(&wwi->lock))
1958         return MMSYSERR_ALLOCATED;
1959
1960     if (wwi->state != WINE_WS_CLOSED)
1961     {
1962         OSSpinLockUnlock(&wwi->lock);
1963         return MMSYSERR_ALLOCATED;
1964     }
1965
1966     wwi->state = WINE_WS_STOPPED;
1967     wwi->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
1968
1969     wwi->waveDesc = *lpDesc;
1970     copyFormat(lpDesc->lpFormat, &wwi->format);
1971
1972     wwi->dwTotalRecorded = 0;
1973
1974     wwi->trace_on = TRACE_ON(wave);
1975     wwi->warn_on  = WARN_ON(wave);
1976     wwi->err_on   = ERR_ON(wave);
1977
1978     if (!AudioUnit_CreateInputUnit(wwi, &wwi->audioUnit,
1979         wwi->format.wf.nChannels, wwi->format.wf.nSamplesPerSec,
1980         wwi->format.wBitsPerSample, &frameCount))
1981     {
1982         OSSpinLockUnlock(&wwi->lock);
1983         ERR("AudioUnit_CreateInputUnit failed\n");
1984         return MMSYSERR_ERROR;
1985     }
1986
1987     /* Allocate our audio buffers */
1988     wwi->bufferList = widHelper_AllocateAudioBufferList(wwi->format.wf.nChannels,
1989         wwi->format.wBitsPerSample, frameCount, TRUE);
1990     if (wwi->bufferList == NULL)
1991     {
1992         AudioUnitUninitialize(wwi->audioUnit);
1993         AudioUnit_CloseAudioUnit(wwi->audioUnit);
1994         OSSpinLockUnlock(&wwi->lock);
1995         ERR("Failed to allocate buffer list\n");
1996         return MMSYSERR_NOMEM;
1997     }
1998
1999     /* Keep a copy of the buffer list structure (but not the buffers themselves)
2000      * in case AudioUnitRender clobbers the original, as it tends to do. */
2001     wwi->bufferListCopy = HeapAlloc(GetProcessHeap(), 0, AUDIOBUFFERLISTSIZE(wwi->bufferList->mNumberBuffers));
2002     if (wwi->bufferListCopy == NULL)
2003     {
2004         widHelper_DestroyAudioBufferList(wwi->bufferList);
2005         AudioUnitUninitialize(wwi->audioUnit);
2006         AudioUnit_CloseAudioUnit(wwi->audioUnit);
2007         OSSpinLockUnlock(&wwi->lock);
2008         ERR("Failed to allocate buffer list copy\n");
2009         return MMSYSERR_NOMEM;
2010     }
2011     memcpy(wwi->bufferListCopy, wwi->bufferList, AUDIOBUFFERLISTSIZE(wwi->bufferList->mNumberBuffers));
2012
2013     OSSpinLockUnlock(&wwi->lock);
2014
2015     widNotifyClient(wwi, WIM_OPEN, 0L, 0L);
2016
2017     return MMSYSERR_NOERROR;
2018 }
2019
2020
2021 /**************************************************************************
2022  *                              widClose                        [internal]
2023  */
2024 static DWORD widClose(WORD wDevID)
2025 {
2026     DWORD           ret = MMSYSERR_NOERROR;
2027     WINE_WAVEIN*    wwi;
2028     OSStatus        err;
2029
2030     TRACE("(%u);\n", wDevID);
2031
2032     if (wDevID >= MAX_WAVEINDRV)
2033     {
2034         WARN("bad device ID !\n");
2035         return MMSYSERR_BADDEVICEID;
2036     }
2037
2038     wwi = &WInDev[wDevID];
2039     OSSpinLockLock(&wwi->lock);
2040     if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2041     {
2042         WARN("Device already closed.\n");
2043         ret = MMSYSERR_INVALHANDLE;
2044     }
2045     else if (wwi->lpQueuePtr)
2046     {
2047         WARN("Buffers in queue.\n");
2048         ret = WAVERR_STILLPLAYING;
2049     }
2050     else
2051     {
2052         wwi->state = WINE_WS_CLOSING;
2053     }
2054
2055     OSSpinLockUnlock(&wwi->lock);
2056
2057     if (ret != MMSYSERR_NOERROR)
2058         return ret;
2059
2060
2061     /* Clean up and close the audio unit.  This has to be done without
2062      * wwi->lock being held to avoid deadlock.  AudioUnitUninitialize will
2063      * grab an internal Core Audio lock while waiting for the device work
2064      * thread to exit.  Meanwhile the device work thread may be holding
2065      * that lock and trying to grab the wwi->lock in the callback. */
2066     err = AudioUnitUninitialize(wwi->audioUnit);
2067     if (err)
2068         ERR("AudioUnitUninitialize return %s\n", wine_dbgstr_fourcc(err));
2069
2070     if (!AudioUnit_CloseAudioUnit(wwi->audioUnit))
2071         ERR("Can't close AudioUnit\n");
2072
2073
2074     OSSpinLockLock(&wwi->lock);
2075     assert(wwi->state == WINE_WS_CLOSING);
2076
2077     /* Dellocate our audio buffers */
2078     widHelper_DestroyAudioBufferList(wwi->bufferList);
2079     wwi->bufferList = NULL;
2080     HeapFree(GetProcessHeap(), 0, wwi->bufferListCopy);
2081     wwi->bufferListCopy = NULL;
2082
2083     wwi->audioUnit = NULL;
2084     wwi->state = WINE_WS_CLOSED;
2085     OSSpinLockUnlock(&wwi->lock);
2086
2087     widNotifyClient(wwi, WIM_CLOSE, 0L, 0L);
2088
2089     return ret;
2090 }
2091
2092
2093 /**************************************************************************
2094  *                              widAddBuffer            [internal]
2095  */
2096 static DWORD widAddBuffer(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
2097 {
2098     DWORD           ret = MMSYSERR_NOERROR;
2099     WINE_WAVEIN*    wwi;
2100
2101     TRACE("(%u, %p, %08X);\n", wDevID, lpWaveHdr, dwSize);
2102
2103     if (wDevID >= MAX_WAVEINDRV)
2104     {
2105         WARN("invalid device ID\n");
2106         return MMSYSERR_INVALHANDLE;
2107     }
2108     if (!(lpWaveHdr->dwFlags & WHDR_PREPARED))
2109     {
2110         TRACE("never been prepared !\n");
2111         return WAVERR_UNPREPARED;
2112     }
2113     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
2114     {
2115         TRACE("header already in use !\n");
2116         return WAVERR_STILLPLAYING;
2117     }
2118
2119     wwi = &WInDev[wDevID];
2120     OSSpinLockLock(&wwi->lock);
2121
2122     if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2123     {
2124         WARN("Trying to add buffer to closed device.\n");
2125         ret = MMSYSERR_INVALHANDLE;
2126     }
2127     else
2128     {
2129         LPWAVEHDR* wh;
2130
2131         lpWaveHdr->dwFlags |= WHDR_INQUEUE;
2132         lpWaveHdr->dwFlags &= ~WHDR_DONE;
2133         lpWaveHdr->dwBytesRecorded = 0;
2134         lpWaveHdr->lpNext = NULL;
2135
2136         /* insert buffer at end of queue */
2137         for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext))
2138             /* Do nothing */;
2139         *wh = lpWaveHdr;
2140     }
2141
2142     OSSpinLockUnlock(&wwi->lock);
2143
2144     return ret;
2145 }
2146
2147
2148 /**************************************************************************
2149  *                      widStart                                [internal]
2150  */
2151 static DWORD widStart(WORD wDevID)
2152 {
2153     DWORD           ret = MMSYSERR_NOERROR;
2154     WINE_WAVEIN*    wwi;
2155
2156     TRACE("(%u);\n", wDevID);
2157     if (wDevID >= MAX_WAVEINDRV)
2158     {
2159         WARN("invalid device ID\n");
2160         return MMSYSERR_INVALHANDLE;
2161     }
2162
2163     /* The order of the following operations is important since we can't hold
2164      * the mutex while we make an Audio Unit call.  Set the PLAYING state
2165      * before starting the Audio Unit.  In widStop, the order is reversed.
2166      * This guarantees that we can't get into a situation where the state is
2167      * PLAYING but the Audio Unit isn't running.  Although we can be in STOPPED
2168      * state with the Audio Unit still running, that's harmless because the
2169      * input callback will just throw away the sound data.
2170      */
2171     wwi = &WInDev[wDevID];
2172     OSSpinLockLock(&wwi->lock);
2173
2174     if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2175     {
2176         WARN("Trying to start closed device.\n");
2177         ret = MMSYSERR_INVALHANDLE;
2178     }
2179     else
2180         wwi->state = WINE_WS_PLAYING;
2181
2182     OSSpinLockUnlock(&wwi->lock);
2183
2184     if (ret == MMSYSERR_NOERROR)
2185     {
2186         /* Start pulling for audio data */
2187         OSStatus err = AudioOutputUnitStart(wwi->audioUnit);
2188         if (err != noErr)
2189             ERR("Failed to start AU: %08lx\n", err);
2190
2191         TRACE("Recording started...\n");
2192     }
2193
2194     return ret;
2195 }
2196
2197
2198 /**************************************************************************
2199  *                      widStop                                 [internal]
2200  */
2201 static DWORD widStop(WORD wDevID)
2202 {
2203     DWORD           ret = MMSYSERR_NOERROR;
2204     WINE_WAVEIN*    wwi;
2205     WAVEHDR*        lpWaveHdr = NULL;
2206     OSStatus        err;
2207
2208     TRACE("(%u);\n", wDevID);
2209     if (wDevID >= MAX_WAVEINDRV)
2210     {
2211         WARN("invalid device ID\n");
2212         return MMSYSERR_INVALHANDLE;
2213     }
2214
2215     wwi = &WInDev[wDevID];
2216
2217     /* The order of the following operations is important since we can't hold
2218      * the mutex while we make an Audio Unit call.  Stop the Audio Unit before
2219      * setting the STOPPED state.  In widStart, the order is reversed.  This
2220      * guarantees that we can't get into a situation where the state is
2221      * PLAYING but the Audio Unit isn't running.  Although we can be in STOPPED
2222      * state with the Audio Unit still running, that's harmless because the
2223      * input callback will just throw away the sound data.
2224      */
2225     err = AudioOutputUnitStop(wwi->audioUnit);
2226     if (err != noErr)
2227         WARN("Failed to stop AU: %08lx\n", err);
2228
2229     TRACE("Recording stopped.\n");
2230
2231     OSSpinLockLock(&wwi->lock);
2232
2233     if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2234     {
2235         WARN("Trying to stop closed device.\n");
2236         ret = MMSYSERR_INVALHANDLE;
2237     }
2238     else if (wwi->state != WINE_WS_STOPPED)
2239     {
2240         wwi->state = WINE_WS_STOPPED;
2241         /* If there's a buffer in progress, it's done.  Remove it from the
2242          * queue so that we can return it to the app, below. */
2243         if (wwi->lpQueuePtr)
2244         {
2245             lpWaveHdr = wwi->lpQueuePtr;
2246             wwi->lpQueuePtr = lpWaveHdr->lpNext;
2247         }
2248     }
2249
2250     OSSpinLockUnlock(&wwi->lock);
2251
2252     if (lpWaveHdr)
2253     {
2254         lpWaveHdr->lpNext = NULL;
2255         lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2256         lpWaveHdr->dwFlags |= WHDR_DONE;
2257         widNotifyClient(wwi, WIM_DATA, (DWORD_PTR)lpWaveHdr, 0);
2258     }
2259
2260     return ret;
2261 }
2262
2263 /**************************************************************************
2264  *                      widGetPos                                 [internal]
2265  */
2266 static DWORD widGetPos(WORD wDevID, LPMMTIME lpTime, UINT size)
2267 {
2268     DWORD                   val;
2269     WINE_WAVEIN*    wwi;
2270
2271     TRACE("(%u);\n", wDevID);
2272     if (wDevID >= MAX_WAVEINDRV)
2273     {
2274         WARN("invalid device ID\n");
2275         return MMSYSERR_INVALHANDLE;
2276     }
2277
2278     wwi = &WInDev[wDevID];
2279
2280     OSSpinLockLock(&WInDev[wDevID].lock);
2281     val = wwi->dwTotalRecorded;
2282     OSSpinLockUnlock(&WInDev[wDevID].lock);
2283
2284     return bytes_to_mmtime(lpTime, val, &wwi->format);
2285 }
2286
2287 /**************************************************************************
2288  *                      widReset                                [internal]
2289  */
2290 static DWORD widReset(WORD wDevID)
2291 {
2292     DWORD           ret = MMSYSERR_NOERROR;
2293     WINE_WAVEIN*    wwi;
2294     WAVEHDR*        lpWaveHdr = NULL;
2295
2296     TRACE("(%u);\n", wDevID);
2297     if (wDevID >= MAX_WAVEINDRV)
2298     {
2299         WARN("invalid device ID\n");
2300         return MMSYSERR_INVALHANDLE;
2301     }
2302
2303     wwi = &WInDev[wDevID];
2304     OSSpinLockLock(&wwi->lock);
2305
2306     if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2307     {
2308         WARN("Trying to reset a closed device.\n");
2309         ret = MMSYSERR_INVALHANDLE;
2310     }
2311     else
2312     {
2313         lpWaveHdr               = wwi->lpQueuePtr;
2314         wwi->lpQueuePtr         = NULL;
2315         wwi->state              = WINE_WS_STOPPED;
2316         wwi->dwTotalRecorded    = 0;
2317     }
2318
2319     OSSpinLockUnlock(&wwi->lock);
2320
2321     if (ret == MMSYSERR_NOERROR)
2322     {
2323         OSStatus err = AudioOutputUnitStop(wwi->audioUnit);
2324         if (err != noErr)
2325             WARN("Failed to stop AU: %08lx\n", err);
2326
2327         TRACE("Recording stopped.\n");
2328     }
2329
2330     while (lpWaveHdr)
2331     {
2332         WAVEHDR* lpNext = lpWaveHdr->lpNext;
2333
2334         lpWaveHdr->lpNext = NULL;
2335         lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2336         lpWaveHdr->dwFlags |= WHDR_DONE;
2337         widNotifyClient(wwi, WIM_DATA, (DWORD_PTR)lpWaveHdr, 0);
2338
2339         lpWaveHdr = lpNext;
2340     }
2341
2342     return ret;
2343 }
2344
2345
2346 /**************************************************************************
2347  *                              widGetNumDevs                   [internal]
2348  */
2349 static DWORD widGetNumDevs(void)
2350 {
2351     return MAX_WAVEINDRV;
2352 }
2353
2354
2355 /**************************************************************************
2356  *                              widDevInterfaceSize             [internal]
2357  */
2358 static DWORD widDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
2359 {
2360     TRACE("(%u, %p)\n", wDevID, dwParam1);
2361
2362     *dwParam1 = MultiByteToWideChar(CP_UNIXCP, 0, WInDev[wDevID].interface_name, -1,
2363                                     NULL, 0 ) * sizeof(WCHAR);
2364     return MMSYSERR_NOERROR;
2365 }
2366
2367
2368 /**************************************************************************
2369  *                              widDevInterface                 [internal]
2370  */
2371 static DWORD widDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
2372 {
2373     if (dwParam2 >= MultiByteToWideChar(CP_UNIXCP, 0, WInDev[wDevID].interface_name, -1,
2374                                         NULL, 0 ) * sizeof(WCHAR))
2375     {
2376         MultiByteToWideChar(CP_UNIXCP, 0, WInDev[wDevID].interface_name, -1,
2377                             dwParam1, dwParam2 / sizeof(WCHAR));
2378         return MMSYSERR_NOERROR;
2379     }
2380     return MMSYSERR_INVALPARAM;
2381 }
2382
2383
2384 /**************************************************************************
2385  *                              widDsCreate                     [internal]
2386  */
2387 static DWORD widDsCreate(UINT wDevID, PIDSCDRIVER* drv)
2388 {
2389     TRACE("(%d,%p)\n",wDevID,drv);
2390
2391     FIXME("DirectSoundCapture not implemented\n");
2392     FIXME("The (slower) DirectSound HEL mode will be used instead.\n");
2393     return MMSYSERR_NOTSUPPORTED;
2394 }
2395
2396 /**************************************************************************
2397  *                              widDsDesc                       [internal]
2398  */
2399 static DWORD widDsDesc(UINT wDevID, PDSDRIVERDESC desc)
2400 {
2401     /* The DirectSound HEL will automatically wrap a non-DirectSound-capable
2402      * driver in a DirectSound adaptor, thus allowing the driver to be used by
2403      * DirectSound clients.  However, it only does this if we respond
2404      * successfully to the DRV_QUERYDSOUNDDESC message.  It's enough to fill in
2405      * the driver and device names of the description output parameter. */
2406     memset(desc, 0, sizeof(*desc));
2407     lstrcpynA(desc->szDrvname, "winecoreaudio.drv", sizeof(desc->szDrvname) - 1);
2408     lstrcpynA(desc->szDesc, WInDev[wDevID].interface_name, sizeof(desc->szDesc) - 1);
2409     return MMSYSERR_NOERROR;
2410 }
2411
2412
2413 /**************************************************************************
2414  *                              widMessage (WINECOREAUDIO.6)
2415  */
2416 DWORD WINAPI CoreAudio_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2417                             DWORD dwParam1, DWORD dwParam2)
2418 {
2419     TRACE("(%u, %04X, %08X, %08X, %08X);\n",
2420             wDevID, wMsg, dwUser, dwParam1, dwParam2);
2421
2422     switch (wMsg)
2423     {
2424         case DRVM_INIT:
2425         case DRVM_EXIT:
2426         case DRVM_ENABLE:
2427         case DRVM_DISABLE:
2428             /* FIXME: Pretend this is supported */
2429             return 0;
2430         case WIDM_OPEN:             return widOpen          (wDevID, (LPWAVEOPENDESC)dwParam1,  dwParam2);
2431         case WIDM_CLOSE:            return widClose         (wDevID);
2432         case WIDM_ADDBUFFER:        return widAddBuffer     (wDevID, (LPWAVEHDR)dwParam1,       dwParam2);
2433         case WIDM_PREPARE:          return MMSYSERR_NOTSUPPORTED;
2434         case WIDM_UNPREPARE:        return MMSYSERR_NOTSUPPORTED;
2435         case WIDM_GETDEVCAPS:       return widGetDevCaps    (wDevID, (LPWAVEINCAPSW)dwParam1,   dwParam2);
2436         case WIDM_GETNUMDEVS:       return widGetNumDevs    ();
2437         case WIDM_RESET:            return widReset         (wDevID);
2438         case WIDM_START:            return widStart         (wDevID);
2439         case WIDM_STOP:             return widStop          (wDevID);
2440         case WIDM_GETPOS:           return widGetPos        (wDevID, (LPMMTIME)dwParam1, (UINT)dwParam2  );
2441         case DRV_QUERYDEVICEINTERFACESIZE: return widDevInterfaceSize       (wDevID, (LPDWORD)dwParam1);
2442         case DRV_QUERYDEVICEINTERFACE:     return widDevInterface           (wDevID, (PWCHAR)dwParam1, dwParam2);
2443         case DRV_QUERYDSOUNDIFACE:  return widDsCreate   (wDevID, (PIDSCDRIVER*)dwParam1);
2444         case DRV_QUERYDSOUNDDESC:   return widDsDesc     (wDevID, (PDSDRIVERDESC)dwParam1);
2445         default:
2446             FIXME("unknown message %d!\n", wMsg);
2447     }
2448
2449     return MMSYSERR_NOTSUPPORTED;
2450 }
2451
2452
2453 OSStatus CoreAudio_wiAudioUnitIOProc(void *inRefCon,
2454                                      AudioUnitRenderActionFlags *ioActionFlags,
2455                                      const AudioTimeStamp *inTimeStamp,
2456                                      UInt32 inBusNumber,
2457                                      UInt32 inNumberFrames,
2458                                      AudioBufferList *ioData)
2459 {
2460     WINE_WAVEIN*    wwi = (WINE_WAVEIN*)inRefCon;
2461     OSStatus        err = noErr;
2462     BOOL            needNotify = FALSE;
2463     WAVEHDR*        lpStorePtr;
2464     unsigned int    dataToStore;
2465     unsigned int    dataStored = 0;
2466
2467
2468     if (wwi->trace_on)
2469         fprintf(stderr, "trace:wave:CoreAudio_wiAudioUnitIOProc (ioActionFlags = %08lx, "
2470             "inTimeStamp = { %f, %x%08x, %f, %x%08x, %08lx }, inBusNumber = %lu, inNumberFrames = %lu)\n",
2471             *ioActionFlags, inTimeStamp->mSampleTime, (DWORD)(inTimeStamp->mHostTime >>32),
2472             (DWORD)inTimeStamp->mHostTime, inTimeStamp->mRateScalar, (DWORD)(inTimeStamp->mWordClockTime >> 32),
2473             (DWORD)inTimeStamp->mWordClockTime, inTimeStamp->mFlags, inBusNumber, inNumberFrames);
2474
2475     /* Render into audio buffer */
2476     /* FIXME: implement sample rate conversion on input.  This will require
2477      * a different render strategy.  We'll need to buffer the sound data
2478      * received here and pass it off to an AUConverter in another thread. */
2479     err = AudioUnitRender(wwi->audioUnit, ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, wwi->bufferList);
2480     if (err)
2481     {
2482         if (wwi->err_on)
2483             fprintf(stderr, "err:wave:CoreAudio_wiAudioUnitIOProc AudioUnitRender failed with error %li\n", err);
2484         return err;
2485     }
2486
2487     /* Copy from audio buffer to the wavehdrs */
2488     dataToStore = wwi->bufferList->mBuffers[0].mDataByteSize;
2489
2490     OSSpinLockLock(&wwi->lock);
2491
2492     lpStorePtr = wwi->lpQueuePtr;
2493
2494     /* We might have been called while the waveIn device is being closed in
2495      * widClose.  We have to do nothing in that case.  The check of wwi->state
2496      * below ensures that. */
2497     while (dataToStore > 0 && wwi->state == WINE_WS_PLAYING && lpStorePtr)
2498     {
2499         unsigned int room = lpStorePtr->dwBufferLength - lpStorePtr->dwBytesRecorded;
2500         unsigned int toCopy;
2501
2502         if (wwi->trace_on)
2503             fprintf(stderr, "trace:wave:CoreAudio_wiAudioUnitIOProc Looking to store %u bytes to wavehdr %p, which has room for %u\n",
2504                 dataToStore, lpStorePtr, room);
2505
2506         if (room >= dataToStore)
2507             toCopy = dataToStore;
2508         else
2509             toCopy = room;
2510
2511         if (toCopy > 0)
2512         {
2513             memcpy(lpStorePtr->lpData + lpStorePtr->dwBytesRecorded,
2514                 (char*)wwi->bufferList->mBuffers[0].mData + dataStored, toCopy);
2515             lpStorePtr->dwBytesRecorded += toCopy;
2516             wwi->dwTotalRecorded += toCopy;
2517             dataStored += toCopy;
2518             dataToStore -= toCopy;
2519             room -= toCopy;
2520         }
2521
2522         if (room == 0)
2523         {
2524             lpStorePtr = lpStorePtr->lpNext;
2525             needNotify = TRUE;
2526         }
2527     }
2528
2529     OSSpinLockUnlock(&wwi->lock);
2530
2531     /* Restore the audio buffer list structure from backup, in case
2532      * AudioUnitRender clobbered it.  (It modifies mDataByteSize and may even
2533      * give us a different mData buffer to avoid a copy.) */
2534     memcpy(wwi->bufferList, wwi->bufferListCopy, AUDIOBUFFERLISTSIZE(wwi->bufferList->mNumberBuffers));
2535
2536     if (needNotify) wodSendNotifyInputCompletionsMessage(wwi);
2537     return err;
2538 }