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