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