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