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