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