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