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