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