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