winecoreaudio: Move ERR&WARN out of OSSpinLock sections.
[wine/wine-gecko.git] / dlls / winecoreaudio.drv / audio.c
blob835d1a9af6399182dbe239d30e0554d672d839bd
1 /*
2 * Wine Driver for CoreAudio based on Jack Driver
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
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.
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.
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
25 #include "config.h"
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>
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"
55 WINE_DEFAULT_DEBUG_CHANNEL(wave);
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>
62 WINE_DECLARE_DEBUG_CHANNEL(coreaudio);
65 Due to AudioUnit headers conflict define some needed types.
68 typedef void *AudioUnit;
70 /* From AudioUnit/AUComponents.h */
71 enum
73 kAudioUnitRenderAction_OutputIsSilence = (1 << 4),
74 /* provides hint on return from Render(): if set the buffer contains all zeroes */
76 typedef UInt32 AudioUnitRenderActionFlags;
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;
87 /* only allow 10 output devices through this driver, this ought to be adequate */
88 #define MAX_WAVEOUTDRV (1)
89 #define MAX_WAVEINDRV (1)
91 /* state diagram for waveOut writing:
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 * +---------+-------------+---------------+---------------------------------+
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
115 typedef struct tagCoreAudio_Device {
116 char dev_name[32];
117 char mixer_name[32];
118 unsigned open_count;
119 char* interface_name;
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;
138 AudioDeviceID outputDeviceID;
139 AudioDeviceID inputDeviceID;
140 AudioStreamBasicDescription streamDescription;
141 } CoreAudio_Device;
143 /* for now use the default device */
144 static CoreAudio_Device CoreAudio_DefaultDevice;
146 typedef struct {
147 struct list entry;
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;
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 */
161 LPWAVEHDR lpLoopPtr; /* pointer of first buffer in loop, if any */
162 DWORD dwLoops; /* private copy of loop counter */
164 DWORD dwPlayedTotal; /* number of bytes actually played since opening */
166 OSSpinLock lock; /* synchronization stuff */
167 } WINE_WAVEOUT_INSTANCE;
169 typedef struct {
170 CoreAudio_Device *cadev;
171 WAVEOUTCAPSW caps;
172 char interface_name[32];
174 BOOL trace_on;
175 BOOL warn_on;
176 BOOL err_on;
178 struct list instances;
179 OSSpinLock lock; /* guards the instances list */
180 } WINE_WAVEOUT;
182 typedef struct {
183 /* This device's device number */
184 DWORD wiID;
186 /* Access to the following fields is synchronized across threads. */
187 volatile int state;
188 LPWAVEHDR lpQueuePtr;
189 DWORD dwTotalRecorded;
191 /* Synchronization mechanism to protect above fields */
192 OSSpinLock lock;
194 /* Capabilities description */
195 WAVEINCAPSW caps;
196 char interface_name[32];
198 /* Record the arguments used when opening the device. */
199 WAVEOPENDESC waveDesc;
200 WORD wFlags;
201 PCMWAVEFORMAT format;
203 AudioUnit audioUnit;
204 AudioBufferList*bufferList;
205 AudioBufferList*bufferListCopy;
207 /* Record state of debug channels at open. Used to control fprintf's since
208 * we can't use Wine debug channel calls in non-Wine AudioUnit threads. */
209 BOOL trace_on;
210 BOOL warn_on;
211 BOOL err_on;
213 /* These fields aren't used. */
214 #if 0
215 CoreAudio_Device *cadev;
217 AudioStreamBasicDescription streamDescription;
218 #endif
219 } WINE_WAVEIN;
221 static WINE_WAVEOUT WOutDev [MAX_WAVEOUTDRV];
222 static WINE_WAVEIN WInDev [MAX_WAVEINDRV];
224 static HANDLE hThread = NULL; /* Track the thread we create so we can clean it up later */
225 static CFMessagePortRef Port_SendToMessageThread;
227 static void wodHelper_PlayPtrNext(WINE_WAVEOUT_INSTANCE* wwo);
228 static void wodHelper_NotifyDoneForList(WINE_WAVEOUT_INSTANCE* wwo, LPWAVEHDR lpWaveHdr);
229 static void wodHelper_NotifyCompletions(WINE_WAVEOUT_INSTANCE* wwo, BOOL force);
230 static void widHelper_NotifyCompletions(WINE_WAVEIN* wwi);
232 extern int AudioUnit_CreateDefaultAudioUnit(void *wwo, AudioUnit *au);
233 extern int AudioUnit_CloseAudioUnit(AudioUnit au);
234 extern int AudioUnit_InitializeWithStreamDescription(AudioUnit au, AudioStreamBasicDescription *streamFormat);
236 extern OSStatus AudioOutputUnitStart(AudioUnit au);
237 extern OSStatus AudioOutputUnitStop(AudioUnit au);
238 extern OSStatus AudioUnitUninitialize(AudioUnit au);
240 extern int AudioUnit_SetVolume(AudioUnit au, float left, float right);
241 extern int AudioUnit_GetVolume(AudioUnit au, float *left, float *right);
243 extern int AudioUnit_GetInputDeviceSampleRate(void);
245 extern int AudioUnit_CreateInputUnit(void* wwi, AudioUnit* out_au,
246 WORD nChannels, DWORD nSamplesPerSec, WORD wBitsPerSample,
247 UInt32* outFrameCount);
249 OSStatus CoreAudio_woAudioUnitIOProc(void *inRefCon,
250 AudioUnitRenderActionFlags *ioActionFlags,
251 const AudioTimeStamp *inTimeStamp,
252 UInt32 inBusNumber,
253 UInt32 inNumberFrames,
254 AudioBufferList *ioData);
255 OSStatus CoreAudio_wiAudioUnitIOProc(void *inRefCon,
256 AudioUnitRenderActionFlags *ioActionFlags,
257 const AudioTimeStamp *inTimeStamp,
258 UInt32 inBusNumber,
259 UInt32 inNumberFrames,
260 AudioBufferList *ioData);
262 /* These strings used only for tracing */
264 static const char * getMessage(UINT msg)
266 static char unknown[32];
267 #define MSG_TO_STR(x) case x: return #x
268 switch(msg) {
269 MSG_TO_STR(DRVM_INIT);
270 MSG_TO_STR(DRVM_EXIT);
271 MSG_TO_STR(DRVM_ENABLE);
272 MSG_TO_STR(DRVM_DISABLE);
273 MSG_TO_STR(WIDM_OPEN);
274 MSG_TO_STR(WIDM_CLOSE);
275 MSG_TO_STR(WIDM_ADDBUFFER);
276 MSG_TO_STR(WIDM_PREPARE);
277 MSG_TO_STR(WIDM_UNPREPARE);
278 MSG_TO_STR(WIDM_GETDEVCAPS);
279 MSG_TO_STR(WIDM_GETNUMDEVS);
280 MSG_TO_STR(WIDM_GETPOS);
281 MSG_TO_STR(WIDM_RESET);
282 MSG_TO_STR(WIDM_START);
283 MSG_TO_STR(WIDM_STOP);
284 MSG_TO_STR(WODM_OPEN);
285 MSG_TO_STR(WODM_CLOSE);
286 MSG_TO_STR(WODM_WRITE);
287 MSG_TO_STR(WODM_PAUSE);
288 MSG_TO_STR(WODM_GETPOS);
289 MSG_TO_STR(WODM_BREAKLOOP);
290 MSG_TO_STR(WODM_PREPARE);
291 MSG_TO_STR(WODM_UNPREPARE);
292 MSG_TO_STR(WODM_GETDEVCAPS);
293 MSG_TO_STR(WODM_GETNUMDEVS);
294 MSG_TO_STR(WODM_GETPITCH);
295 MSG_TO_STR(WODM_SETPITCH);
296 MSG_TO_STR(WODM_GETPLAYBACKRATE);
297 MSG_TO_STR(WODM_SETPLAYBACKRATE);
298 MSG_TO_STR(WODM_GETVOLUME);
299 MSG_TO_STR(WODM_SETVOLUME);
300 MSG_TO_STR(WODM_RESTART);
301 MSG_TO_STR(WODM_RESET);
302 MSG_TO_STR(DRV_QUERYDEVICEINTERFACESIZE);
303 MSG_TO_STR(DRV_QUERYDEVICEINTERFACE);
304 MSG_TO_STR(DRV_QUERYDSOUNDIFACE);
305 MSG_TO_STR(DRV_QUERYDSOUNDDESC);
307 #undef MSG_TO_STR
308 sprintf(unknown, "UNKNOWN(0x%04x)", msg);
309 return unknown;
312 #define kStopLoopMessage 0
313 #define kWaveOutNotifyCompletionsMessage 1
314 #define kWaveInNotifyCompletionsMessage 2
316 /* Mach Message Handling */
317 static CFDataRef wodMessageHandler(CFMessagePortRef port_ReceiveInMessageThread, SInt32 msgid, CFDataRef data, void *info)
319 UInt32 *buffer = NULL;
321 switch (msgid)
323 case kWaveOutNotifyCompletionsMessage:
324 wodHelper_NotifyCompletions(*(WINE_WAVEOUT_INSTANCE**)CFDataGetBytePtr(data), FALSE);
325 break;
326 case kWaveInNotifyCompletionsMessage:
327 buffer = (UInt32 *) CFDataGetBytePtr(data);
328 widHelper_NotifyCompletions(&WInDev[buffer[0]]);
329 break;
330 default:
331 CFRunLoopStop(CFRunLoopGetCurrent());
332 break;
335 return NULL;
338 static DWORD WINAPI messageThread(LPVOID p)
340 CFMessagePortRef port_ReceiveInMessageThread = (CFMessagePortRef) p;
341 CFRunLoopSourceRef source;
343 source = CFMessagePortCreateRunLoopSource(kCFAllocatorDefault, port_ReceiveInMessageThread, (CFIndex)0);
344 CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
346 CFRunLoopRun();
348 CFRunLoopSourceInvalidate(source);
349 CFRelease(source);
350 CFRelease(port_ReceiveInMessageThread);
352 return 0;
355 /**************************************************************************
356 * wodSendNotifyCompletionsMessage [internal]
357 * Call from AudioUnit IO thread can't use Wine debug channels.
359 static void wodSendNotifyCompletionsMessage(WINE_WAVEOUT_INSTANCE* wwo)
361 CFDataRef data;
363 if (!Port_SendToMessageThread)
364 return;
366 data = CFDataCreate(kCFAllocatorDefault, (UInt8 *)&wwo, sizeof(wwo));
367 if (!data)
368 return;
370 CFMessagePortSendRequest(Port_SendToMessageThread, kWaveOutNotifyCompletionsMessage, data, 0.0, 0.0, NULL, NULL);
371 CFRelease(data);
374 /**************************************************************************
375 * wodSendNotifyInputCompletionsMessage [internal]
376 * Call from AudioUnit IO thread can't use Wine debug channels.
378 static void wodSendNotifyInputCompletionsMessage(WINE_WAVEIN* wwi)
380 CFDataRef data;
381 UInt32 buffer;
383 if (!Port_SendToMessageThread)
384 return;
386 buffer = (UInt32) wwi->wiID;
388 data = CFDataCreate(kCFAllocatorDefault, (UInt8 *)&buffer, sizeof(buffer));
389 if (!data)
390 return;
392 CFMessagePortSendRequest(Port_SendToMessageThread, kWaveInNotifyCompletionsMessage, data, 0.0, 0.0, NULL, NULL);
393 CFRelease(data);
396 static DWORD bytes_to_mmtime(LPMMTIME lpTime, DWORD position,
397 PCMWAVEFORMAT* format)
399 TRACE("wType=%04X wBitsPerSample=%u nSamplesPerSec=%u nChannels=%u nAvgBytesPerSec=%u\n",
400 lpTime->wType, format->wBitsPerSample, format->wf.nSamplesPerSec,
401 format->wf.nChannels, format->wf.nAvgBytesPerSec);
402 TRACE("Position in bytes=%u\n", position);
404 switch (lpTime->wType) {
405 case TIME_SAMPLES:
406 lpTime->u.sample = position / (format->wBitsPerSample / 8 * format->wf.nChannels);
407 TRACE("TIME_SAMPLES=%u\n", lpTime->u.sample);
408 break;
409 case TIME_MS:
410 lpTime->u.ms = 1000.0 * position / (format->wBitsPerSample / 8 * format->wf.nChannels * format->wf.nSamplesPerSec);
411 TRACE("TIME_MS=%u\n", lpTime->u.ms);
412 break;
413 case TIME_SMPTE:
414 lpTime->u.smpte.fps = 30;
415 position = position / (format->wBitsPerSample / 8 * format->wf.nChannels);
416 position += (format->wf.nSamplesPerSec / lpTime->u.smpte.fps) - 1; /* round up */
417 lpTime->u.smpte.sec = position / format->wf.nSamplesPerSec;
418 position -= lpTime->u.smpte.sec * format->wf.nSamplesPerSec;
419 lpTime->u.smpte.min = lpTime->u.smpte.sec / 60;
420 lpTime->u.smpte.sec -= 60 * lpTime->u.smpte.min;
421 lpTime->u.smpte.hour = lpTime->u.smpte.min / 60;
422 lpTime->u.smpte.min -= 60 * lpTime->u.smpte.hour;
423 lpTime->u.smpte.fps = 30;
424 lpTime->u.smpte.frame = position * lpTime->u.smpte.fps / format->wf.nSamplesPerSec;
425 TRACE("TIME_SMPTE=%02u:%02u:%02u:%02u\n",
426 lpTime->u.smpte.hour, lpTime->u.smpte.min,
427 lpTime->u.smpte.sec, lpTime->u.smpte.frame);
428 break;
429 default:
430 WARN("Format %d not supported, using TIME_BYTES !\n", lpTime->wType);
431 lpTime->wType = TIME_BYTES;
432 /* fall through */
433 case TIME_BYTES:
434 lpTime->u.cb = position;
435 TRACE("TIME_BYTES=%u\n", lpTime->u.cb);
436 break;
438 return MMSYSERR_NOERROR;
441 static BOOL supportedFormat(LPWAVEFORMATEX wf)
443 if (wf->nSamplesPerSec == 0)
444 return FALSE;
446 if (wf->wFormatTag == WAVE_FORMAT_PCM) {
447 if (wf->nChannels >= 1 && wf->nChannels <= 2) {
448 if (wf->wBitsPerSample==8||wf->wBitsPerSample==16)
449 return TRUE;
451 } else if (wf->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
452 WAVEFORMATEXTENSIBLE * wfex = (WAVEFORMATEXTENSIBLE *)wf;
454 if (wf->cbSize == 22 && IsEqualGUID(&wfex->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM)) {
455 if (wf->nChannels >=1 && wf->nChannels <= 8) {
456 if (wf->wBitsPerSample==wfex->Samples.wValidBitsPerSample) {
457 if (wf->wBitsPerSample==8||wf->wBitsPerSample==16)
458 return TRUE;
459 } else
460 WARN("wBitsPerSample != wValidBitsPerSample not supported yet\n");
462 } else
463 WARN("only KSDATAFORMAT_SUBTYPE_PCM supported\n");
464 } else
465 WARN("only WAVE_FORMAT_PCM supported\n");
467 return FALSE;
470 void copyFormat(LPWAVEFORMATEX wf1, LPPCMWAVEFORMAT wf2)
472 memcpy(wf2, wf1, sizeof(PCMWAVEFORMAT));
473 /* Downgrade WAVE_FORMAT_EXTENSIBLE KSDATAFORMAT_SUBTYPE_PCM
474 * to smaller yet compatible WAVE_FORMAT_PCM structure */
475 if (wf2->wf.wFormatTag == WAVE_FORMAT_EXTENSIBLE)
476 wf2->wf.wFormatTag = WAVE_FORMAT_PCM;
479 /**************************************************************************
480 * CoreAudio_GetDevCaps [internal]
482 BOOL CoreAudio_GetDevCaps (void)
484 OSStatus status;
485 UInt32 propertySize;
486 AudioDeviceID devId = CoreAudio_DefaultDevice.outputDeviceID;
488 char name[MAXPNAMELEN];
490 propertySize = MAXPNAMELEN;
491 status = AudioDeviceGetProperty(devId, 0 , FALSE, kAudioDevicePropertyDeviceName, &propertySize, name);
492 if (status) {
493 ERR("AudioHardwareGetProperty for kAudioDevicePropertyDeviceName return %s\n", wine_dbgstr_fourcc(status));
494 return FALSE;
497 memcpy(CoreAudio_DefaultDevice.ds_desc.szDesc, name, sizeof(name));
498 strcpy(CoreAudio_DefaultDevice.ds_desc.szDrvname, "winecoreaudio.drv");
499 MultiByteToWideChar(CP_UNIXCP, 0, name, sizeof(name),
500 CoreAudio_DefaultDevice.out_caps.szPname,
501 sizeof(CoreAudio_DefaultDevice.out_caps.szPname) / sizeof(WCHAR));
502 memcpy(CoreAudio_DefaultDevice.dev_name, name, 32);
504 propertySize = sizeof(CoreAudio_DefaultDevice.streamDescription);
505 status = AudioDeviceGetProperty(devId, 0, FALSE , kAudioDevicePropertyStreamFormat, &propertySize, &CoreAudio_DefaultDevice.streamDescription);
506 if (status != noErr) {
507 ERR("AudioHardwareGetProperty for kAudioDevicePropertyStreamFormat return %s\n", wine_dbgstr_fourcc(status));
508 return FALSE;
511 TRACE("Device Stream Description mSampleRate : %f\n mFormatID : %s\n"
512 "mFormatFlags : %lX\n mBytesPerPacket : %lu\n mFramesPerPacket : %lu\n"
513 "mBytesPerFrame : %lu\n mChannelsPerFrame : %lu\n mBitsPerChannel : %lu\n",
514 CoreAudio_DefaultDevice.streamDescription.mSampleRate,
515 wine_dbgstr_fourcc(CoreAudio_DefaultDevice.streamDescription.mFormatID),
516 CoreAudio_DefaultDevice.streamDescription.mFormatFlags,
517 CoreAudio_DefaultDevice.streamDescription.mBytesPerPacket,
518 CoreAudio_DefaultDevice.streamDescription.mFramesPerPacket,
519 CoreAudio_DefaultDevice.streamDescription.mBytesPerFrame,
520 CoreAudio_DefaultDevice.streamDescription.mChannelsPerFrame,
521 CoreAudio_DefaultDevice.streamDescription.mBitsPerChannel);
523 CoreAudio_DefaultDevice.out_caps.wMid = 0xcafe;
524 CoreAudio_DefaultDevice.out_caps.wPid = 0x0001;
526 CoreAudio_DefaultDevice.out_caps.vDriverVersion = 0x0001;
527 CoreAudio_DefaultDevice.out_caps.dwFormats = 0x00000000;
528 CoreAudio_DefaultDevice.out_caps.wReserved1 = 0;
529 CoreAudio_DefaultDevice.out_caps.dwSupport = WAVECAPS_VOLUME;
530 CoreAudio_DefaultDevice.out_caps.dwSupport |= WAVECAPS_LRVOLUME;
532 CoreAudio_DefaultDevice.out_caps.wChannels = 2;
533 CoreAudio_DefaultDevice.out_caps.dwFormats|= WAVE_FORMAT_4S16;
535 TRACE_(coreaudio)("out dwFormats = %08x, dwSupport = %08x\n",
536 CoreAudio_DefaultDevice.out_caps.dwFormats, CoreAudio_DefaultDevice.out_caps.dwSupport);
538 return TRUE;
541 /******************************************************************
542 * CoreAudio_WaveInit
544 * Initialize CoreAudio_DefaultDevice
546 LONG CoreAudio_WaveInit(void)
548 OSStatus status;
549 UInt32 propertySize;
550 int i;
551 CFStringRef messageThreadPortName;
552 CFMessagePortRef port_ReceiveInMessageThread;
553 int inputSampleRate;
555 TRACE("()\n");
557 /* number of sound cards */
558 AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &propertySize, NULL);
559 propertySize /= sizeof(AudioDeviceID);
560 TRACE("sound cards : %lu\n", propertySize);
562 /* Get the output device */
563 propertySize = sizeof(CoreAudio_DefaultDevice.outputDeviceID);
564 status = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &propertySize, &CoreAudio_DefaultDevice.outputDeviceID);
565 if (status) {
566 ERR("AudioHardwareGetProperty return %s for kAudioHardwarePropertyDefaultOutputDevice\n", wine_dbgstr_fourcc(status));
567 return DRV_FAILURE;
569 if (CoreAudio_DefaultDevice.outputDeviceID == kAudioDeviceUnknown) {
570 ERR("AudioHardwareGetProperty: CoreAudio_DefaultDevice.outputDeviceID == kAudioDeviceUnknown\n");
571 return DRV_FAILURE;
574 if ( ! CoreAudio_GetDevCaps() )
575 return DRV_FAILURE;
577 CoreAudio_DefaultDevice.interface_name=HeapAlloc(GetProcessHeap(),0,strlen(CoreAudio_DefaultDevice.dev_name)+1);
578 strcpy(CoreAudio_DefaultDevice.interface_name, CoreAudio_DefaultDevice.dev_name);
580 for (i = 0; i < MAX_WAVEOUTDRV; ++i)
582 static const WCHAR wszWaveOutFormat[] =
583 {'C','o','r','e','A','u','d','i','o',' ','W','a','v','e','O','u','t',' ','%','d',0};
585 list_init(&WOutDev[i].instances);
586 WOutDev[i].cadev = &CoreAudio_DefaultDevice;
588 memset(&WOutDev[i].caps, 0, sizeof(WOutDev[i].caps));
590 WOutDev[i].caps.wMid = 0xcafe; /* Manufac ID */
591 WOutDev[i].caps.wPid = 0x0001; /* Product ID */
592 snprintfW(WOutDev[i].caps.szPname, sizeof(WOutDev[i].caps.szPname)/sizeof(WCHAR), wszWaveOutFormat, i);
593 snprintf(WOutDev[i].interface_name, sizeof(WOutDev[i].interface_name), "winecoreaudio: %d", i);
595 WOutDev[i].caps.vDriverVersion = 0x0001;
596 WOutDev[i].caps.dwFormats = 0x00000000;
597 WOutDev[i].caps.dwSupport = WAVECAPS_VOLUME;
599 WOutDev[i].caps.wChannels = 2;
600 /* WOutDev[i].caps.dwSupport |= WAVECAPS_LRVOLUME; */ /* FIXME */
602 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96M08;
603 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96S08;
604 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96M16;
605 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96S16;
606 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48M08;
607 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48S08;
608 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48M16;
609 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48S16;
610 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4M08;
611 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4S08;
612 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4S16;
613 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4M16;
614 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2M08;
615 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2S08;
616 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2M16;
617 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2S16;
618 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1M08;
619 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1S08;
620 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1M16;
621 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1S16;
623 WOutDev[i].lock = 0; /* initialize the mutex */
626 /* FIXME: implement sample rate conversion on input */
627 inputSampleRate = AudioUnit_GetInputDeviceSampleRate();
629 for (i = 0; i < MAX_WAVEINDRV; ++i)
631 static const WCHAR wszWaveInFormat[] =
632 {'C','o','r','e','A','u','d','i','o',' ','W','a','v','e','I','n',' ','%','d',0};
634 memset(&WInDev[i], 0, sizeof(WInDev[i]));
635 WInDev[i].wiID = i;
637 /* Establish preconditions for widOpen */
638 WInDev[i].state = WINE_WS_CLOSED;
639 WInDev[i].lock = 0; /* initialize the mutex */
641 /* Fill in capabilities. widGetDevCaps can be called at any time. */
642 WInDev[i].caps.wMid = 0xcafe; /* Manufac ID */
643 WInDev[i].caps.wPid = 0x0001; /* Product ID */
644 WInDev[i].caps.vDriverVersion = 0x0001;
646 snprintfW(WInDev[i].caps.szPname, sizeof(WInDev[i].caps.szPname)/sizeof(WCHAR), wszWaveInFormat, i);
647 snprintf(WInDev[i].interface_name, sizeof(WInDev[i].interface_name), "winecoreaudio in: %d", i);
649 if (inputSampleRate == 96000)
651 WInDev[i].caps.dwFormats |= WAVE_FORMAT_96M08;
652 WInDev[i].caps.dwFormats |= WAVE_FORMAT_96S08;
653 WInDev[i].caps.dwFormats |= WAVE_FORMAT_96M16;
654 WInDev[i].caps.dwFormats |= WAVE_FORMAT_96S16;
656 if (inputSampleRate == 48000)
658 WInDev[i].caps.dwFormats |= WAVE_FORMAT_48M08;
659 WInDev[i].caps.dwFormats |= WAVE_FORMAT_48S08;
660 WInDev[i].caps.dwFormats |= WAVE_FORMAT_48M16;
661 WInDev[i].caps.dwFormats |= WAVE_FORMAT_48S16;
663 if (inputSampleRate == 44100)
665 WInDev[i].caps.dwFormats |= WAVE_FORMAT_4M08;
666 WInDev[i].caps.dwFormats |= WAVE_FORMAT_4S08;
667 WInDev[i].caps.dwFormats |= WAVE_FORMAT_4M16;
668 WInDev[i].caps.dwFormats |= WAVE_FORMAT_4S16;
670 if (inputSampleRate == 22050)
672 WInDev[i].caps.dwFormats |= WAVE_FORMAT_2M08;
673 WInDev[i].caps.dwFormats |= WAVE_FORMAT_2S08;
674 WInDev[i].caps.dwFormats |= WAVE_FORMAT_2M16;
675 WInDev[i].caps.dwFormats |= WAVE_FORMAT_2S16;
677 if (inputSampleRate == 11025)
679 WInDev[i].caps.dwFormats |= WAVE_FORMAT_1M08;
680 WInDev[i].caps.dwFormats |= WAVE_FORMAT_1S08;
681 WInDev[i].caps.dwFormats |= WAVE_FORMAT_1M16;
682 WInDev[i].caps.dwFormats |= WAVE_FORMAT_1S16;
685 WInDev[i].caps.wChannels = 2;
688 /* create mach messages handler */
689 srandomdev();
690 messageThreadPortName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL,
691 CFSTR("WaveMessagePort.%d.%lu"), getpid(), (unsigned long)random());
692 if (!messageThreadPortName)
694 ERR("Can't create message thread port name\n");
695 return DRV_FAILURE;
698 port_ReceiveInMessageThread = CFMessagePortCreateLocal(kCFAllocatorDefault, messageThreadPortName,
699 &wodMessageHandler, NULL, NULL);
700 if (!port_ReceiveInMessageThread)
702 ERR("Can't create message thread local port\n");
703 CFRelease(messageThreadPortName);
704 return DRV_FAILURE;
707 Port_SendToMessageThread = CFMessagePortCreateRemote(kCFAllocatorDefault, messageThreadPortName);
708 CFRelease(messageThreadPortName);
709 if (!Port_SendToMessageThread)
711 ERR("Can't create port for sending to message thread\n");
712 CFRelease(port_ReceiveInMessageThread);
713 return DRV_FAILURE;
716 /* Cannot WAIT for any events because we are called from the loader (which has a lock on loading stuff) */
717 /* We might want to wait for this thread to be created -- but we cannot -- not here at least */
718 /* Instead track the thread so we can clean it up later */
719 if ( hThread )
721 ERR("Message thread already started -- expect problems\n");
723 hThread = CreateThread(NULL, 0, messageThread, (LPVOID)port_ReceiveInMessageThread, 0, NULL);
724 if ( !hThread )
726 ERR("Can't create message thread\n");
727 CFRelease(port_ReceiveInMessageThread);
728 CFRelease(Port_SendToMessageThread);
729 Port_SendToMessageThread = NULL;
730 return DRV_FAILURE;
733 /* The message thread is responsible for releasing port_ReceiveInMessageThread. */
735 return DRV_SUCCESS;
738 void CoreAudio_WaveRelease(void)
740 /* Stop CFRunLoop in messageThread */
741 TRACE("()\n");
743 if (!Port_SendToMessageThread)
744 return;
746 CFMessagePortSendRequest(Port_SendToMessageThread, kStopLoopMessage, NULL, 0.0, 0.0, NULL, NULL);
747 CFRelease(Port_SendToMessageThread);
748 Port_SendToMessageThread = NULL;
750 /* Wait for the thread to finish and clean it up */
751 /* This rids us of any quick start/shutdown driver crashes */
752 WaitForSingleObject(hThread, INFINITE);
753 CloseHandle(hThread);
754 hThread = NULL;
757 /*======================================================================*
758 * Low level WAVE OUT implementation *
759 *======================================================================*/
761 /**************************************************************************
762 * wodNotifyClient [internal]
764 static DWORD wodNotifyClient(WINE_WAVEOUT_INSTANCE* wwo, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
766 TRACE_(coreaudio)("wMsg = 0x%04x dwParm1 = %04x dwParam2 = %04x\n", wMsg, dwParam1, dwParam2);
768 switch (wMsg) {
769 case WOM_OPEN:
770 case WOM_CLOSE:
771 case WOM_DONE:
772 if (wwo->wFlags != DCB_NULL &&
773 !DriverCallback(wwo->waveDesc.dwCallback, wwo->wFlags,
774 (HDRVR)wwo->waveDesc.hWave, wMsg, wwo->waveDesc.dwInstance,
775 dwParam1, dwParam2))
777 ERR("can't notify client !\n");
778 return MMSYSERR_ERROR;
780 break;
781 default:
782 ERR("Unknown callback message %u\n", wMsg);
783 return MMSYSERR_INVALPARAM;
785 return MMSYSERR_NOERROR;
789 /**************************************************************************
790 * wodGetDevCaps [internal]
792 static DWORD wodGetDevCaps(WORD wDevID, LPWAVEOUTCAPSW lpCaps, DWORD dwSize)
794 TRACE("(%u, %p, %u);\n", wDevID, lpCaps, dwSize);
796 if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
798 if (wDevID >= MAX_WAVEOUTDRV)
800 TRACE("MAX_WAVOUTDRV reached !\n");
801 return MMSYSERR_BADDEVICEID;
804 TRACE("dwSupport=(0x%x), dwFormats=(0x%x)\n", WOutDev[wDevID].caps.dwSupport, WOutDev[wDevID].caps.dwFormats);
805 memcpy(lpCaps, &WOutDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
806 return MMSYSERR_NOERROR;
809 /**************************************************************************
810 * wodOpen [internal]
812 static DWORD wodOpen(WORD wDevID, WINE_WAVEOUT_INSTANCE** pInstance, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
814 WINE_WAVEOUT_INSTANCE* wwo;
815 DWORD ret;
816 AudioStreamBasicDescription streamFormat;
817 AudioUnit audioUnit = NULL;
818 BOOL auInited = FALSE;
820 TRACE("(%u, %p, %p, %08x);\n", wDevID, pInstance, lpDesc, dwFlags);
821 if (lpDesc == NULL)
823 WARN("Invalid Parameter !\n");
824 return MMSYSERR_INVALPARAM;
826 if (wDevID >= MAX_WAVEOUTDRV) {
827 TRACE("MAX_WAVOUTDRV reached !\n");
828 return MMSYSERR_BADDEVICEID;
831 TRACE("Format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
832 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
833 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
835 if (!supportedFormat(lpDesc->lpFormat))
837 WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
838 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
839 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
840 return WAVERR_BADFORMAT;
843 if (dwFlags & WAVE_FORMAT_QUERY)
845 TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
846 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
847 lpDesc->lpFormat->nSamplesPerSec);
848 return MMSYSERR_NOERROR;
851 /* nBlockAlign and nAvgBytesPerSec are output variables for dsound */
852 if (lpDesc->lpFormat->nBlockAlign != lpDesc->lpFormat->nChannels*lpDesc->lpFormat->wBitsPerSample/8) {
853 lpDesc->lpFormat->nBlockAlign = lpDesc->lpFormat->nChannels*lpDesc->lpFormat->wBitsPerSample/8;
854 WARN("Fixing nBlockAlign\n");
856 if (lpDesc->lpFormat->nAvgBytesPerSec!= lpDesc->lpFormat->nSamplesPerSec*lpDesc->lpFormat->nBlockAlign) {
857 lpDesc->lpFormat->nAvgBytesPerSec = lpDesc->lpFormat->nSamplesPerSec*lpDesc->lpFormat->nBlockAlign;
858 WARN("Fixing nAvgBytesPerSec\n");
861 /* We proceed in three phases:
862 * o Allocate the device instance, marking it as opening
863 * o Create, configure, and start the Audio Unit. To avoid deadlock,
864 * this has to be done without holding wwo->lock.
865 * o If that was successful, finish setting up our instance and add it
866 * to the device's list.
867 * Otherwise, clean up and deallocate the instance.
869 wwo = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*wwo));
870 if (!wwo)
871 return MMSYSERR_NOMEM;
873 wwo->woID = wDevID;
874 wwo->state = WINE_WS_OPENING;
876 if (!AudioUnit_CreateDefaultAudioUnit((void *) wwo, &audioUnit))
878 ERR("CoreAudio_CreateDefaultAudioUnit(0x%04x) failed\n", wDevID);
879 ret = MMSYSERR_ERROR;
880 goto error;
883 streamFormat.mFormatID = kAudioFormatLinearPCM;
884 streamFormat.mFormatFlags = kLinearPCMFormatFlagIsPacked;
885 /* FIXME check for 32bits float -> kLinearPCMFormatFlagIsFloat */
886 if (lpDesc->lpFormat->wBitsPerSample != 8)
887 streamFormat.mFormatFlags |= kLinearPCMFormatFlagIsSignedInteger;
888 # ifdef WORDS_BIGENDIAN
889 streamFormat.mFormatFlags |= kLinearPCMFormatFlagIsBigEndian; /* FIXME Wave format is little endian */
890 # endif
892 streamFormat.mSampleRate = lpDesc->lpFormat->nSamplesPerSec;
893 streamFormat.mChannelsPerFrame = lpDesc->lpFormat->nChannels;
894 streamFormat.mFramesPerPacket = 1;
895 streamFormat.mBitsPerChannel = lpDesc->lpFormat->wBitsPerSample;
896 streamFormat.mBytesPerFrame = streamFormat.mBitsPerChannel * streamFormat.mChannelsPerFrame / 8;
897 streamFormat.mBytesPerPacket = streamFormat.mBytesPerFrame * streamFormat.mFramesPerPacket;
899 ret = AudioUnit_InitializeWithStreamDescription(audioUnit, &streamFormat);
900 if (!ret)
902 ret = WAVERR_BADFORMAT; /* FIXME return an error based on the OSStatus */
903 goto error;
905 auInited = TRUE;
907 /* Our render callback CoreAudio_woAudioUnitIOProc may be called before
908 * AudioOutputUnitStart returns. Core Audio will grab its own internal
909 * lock before calling it and the callback grabs wwo->lock. This would
910 * deadlock if we were holding wwo->lock.
911 * Also, the callback has to safely do nothing in that case, because
912 * wwo hasn't been completely filled out, yet. This is assured by state
913 * being WINE_WS_OPENING. */
914 ret = AudioOutputUnitStart(audioUnit);
915 if (ret)
917 ERR("AudioOutputUnitStart failed: %08x\n", ret);
918 ret = MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
919 goto error;
923 OSSpinLockLock(&wwo->lock);
924 assert(wwo->state == WINE_WS_OPENING);
926 wwo->audioUnit = audioUnit;
927 wwo->streamDescription = streamFormat;
929 wwo->state = WINE_WS_PLAYING;
931 wwo->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
933 wwo->waveDesc = *lpDesc;
934 copyFormat(lpDesc->lpFormat, &wwo->format);
936 WOutDev[wDevID].trace_on = TRACE_ON(wave);
937 WOutDev[wDevID].warn_on = WARN_ON(wave);
938 WOutDev[wDevID].err_on = ERR_ON(wave);
940 OSSpinLockUnlock(&wwo->lock);
942 OSSpinLockLock(&WOutDev[wDevID].lock);
943 list_add_head(&WOutDev[wDevID].instances, &wwo->entry);
944 OSSpinLockUnlock(&WOutDev[wDevID].lock);
946 *pInstance = wwo;
947 TRACE("opened instance %p\n", wwo);
949 ret = wodNotifyClient(wwo, WOM_OPEN, 0L, 0L);
951 return ret;
953 error:
954 if (audioUnit)
956 if (auInited)
957 AudioUnitUninitialize(audioUnit);
958 AudioUnit_CloseAudioUnit(audioUnit);
961 OSSpinLockLock(&wwo->lock);
962 assert(wwo->state == WINE_WS_OPENING);
963 /* OSSpinLockUnlock(&wwo->lock); *//* No need, about to free */
964 HeapFree(GetProcessHeap(), 0, wwo);
966 return ret;
969 /**************************************************************************
970 * wodClose [internal]
972 static DWORD wodClose(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo)
974 DWORD ret = MMSYSERR_NOERROR;
976 TRACE("(%u, %p);\n", wDevID, wwo);
978 if (wDevID >= MAX_WAVEOUTDRV)
980 WARN("bad device ID !\n");
981 return MMSYSERR_BADDEVICEID;
984 OSSpinLockLock(&wwo->lock);
985 if (wwo->lpQueuePtr)
987 OSSpinLockUnlock(&wwo->lock);
988 WARN("buffers still playing !\n");
989 ret = WAVERR_STILLPLAYING;
990 } else
992 OSStatus err;
993 AudioUnit audioUnit = wwo->audioUnit;
995 /* sanity check: this should not happen since the device must have been reset before */
996 if (wwo->lpQueuePtr || wwo->lpPlayPtr) ERR("out of sync\n");
998 wwo->state = WINE_WS_CLOSING; /* mark the device as closing */
999 wwo->audioUnit = NULL;
1001 OSSpinLockUnlock(&wwo->lock);
1003 err = AudioUnitUninitialize(audioUnit);
1004 if (err) {
1005 ERR("AudioUnitUninitialize return %s\n", wine_dbgstr_fourcc(err));
1006 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1009 if ( !AudioUnit_CloseAudioUnit(audioUnit) )
1011 ERR("Can't close AudioUnit\n");
1012 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1015 OSSpinLockLock(&WOutDev[wDevID].lock);
1016 list_remove(&wwo->entry);
1017 OSSpinLockUnlock(&WOutDev[wDevID].lock);
1019 ret = wodNotifyClient(wwo, WOM_CLOSE, 0L, 0L);
1021 HeapFree(GetProcessHeap(), 0, wwo);
1024 return ret;
1027 /**************************************************************************
1028 * wodPrepare [internal]
1030 static DWORD wodPrepare(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1032 TRACE("(%u, %p, %p, %08x);\n", wDevID, wwo, lpWaveHdr, dwSize);
1034 if (wDevID >= MAX_WAVEOUTDRV) {
1035 WARN("bad device ID !\n");
1036 return MMSYSERR_BADDEVICEID;
1039 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1040 return WAVERR_STILLPLAYING;
1042 lpWaveHdr->dwFlags |= WHDR_PREPARED;
1043 lpWaveHdr->dwFlags &= ~WHDR_DONE;
1045 return MMSYSERR_NOERROR;
1048 /**************************************************************************
1049 * wodUnprepare [internal]
1051 static DWORD wodUnprepare(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1053 TRACE("(%u, %p, %p, %08x);\n", wDevID, wwo, lpWaveHdr, dwSize);
1055 if (wDevID >= MAX_WAVEOUTDRV) {
1056 WARN("bad device ID !\n");
1057 return MMSYSERR_BADDEVICEID;
1060 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1061 return WAVERR_STILLPLAYING;
1063 lpWaveHdr->dwFlags &= ~WHDR_PREPARED;
1064 lpWaveHdr->dwFlags |= WHDR_DONE;
1066 return MMSYSERR_NOERROR;
1070 /**************************************************************************
1071 * wodHelper_CheckForLoopBegin [internal]
1073 * Check if the new waveheader is the beginning of a loop, and set up
1074 * state if so.
1075 * This is called with the WAVEOUT_INSTANCE lock held.
1076 * Call from AudioUnit IO thread can't use Wine debug channels.
1078 static void wodHelper_CheckForLoopBegin(WINE_WAVEOUT_INSTANCE* wwo)
1080 LPWAVEHDR lpWaveHdr = wwo->lpPlayPtr;
1082 if (lpWaveHdr->dwFlags & WHDR_BEGINLOOP)
1084 if (wwo->lpLoopPtr)
1086 if (WOutDev[wwo->woID].warn_on)
1087 fprintf(stderr, "warn:winecoreaudio:wodHelper_CheckForLoopBegin Already in a loop. Discarding loop on this header (%p)\n", lpWaveHdr);
1089 else
1091 if (WOutDev[wwo->woID].trace_on)
1092 fprintf(stderr, "trace:winecoreaudio:wodHelper_CheckForLoopBegin Starting loop (%dx) with %p\n", lpWaveHdr->dwLoops, lpWaveHdr);
1094 wwo->lpLoopPtr = lpWaveHdr;
1095 /* Windows does not touch WAVEHDR.dwLoops,
1096 * so we need to make an internal copy */
1097 wwo->dwLoops = lpWaveHdr->dwLoops;
1103 /**************************************************************************
1104 * wodHelper_PlayPtrNext [internal]
1106 * Advance the play pointer to the next waveheader, looping if required.
1107 * This is called with the WAVEOUT_INSTANCE lock held.
1108 * Call from AudioUnit IO thread can't use Wine debug channels.
1110 static void wodHelper_PlayPtrNext(WINE_WAVEOUT_INSTANCE* wwo)
1112 BOOL didLoopBack = FALSE;
1114 wwo->dwPartialOffset = 0;
1115 if ((wwo->lpPlayPtr->dwFlags & WHDR_ENDLOOP) && wwo->lpLoopPtr)
1117 /* We're at the end of a loop, loop if required */
1118 if (wwo->dwLoops > 1)
1120 wwo->dwLoops--;
1121 wwo->lpPlayPtr = wwo->lpLoopPtr;
1122 didLoopBack = TRUE;
1124 else
1126 wwo->lpLoopPtr = NULL;
1129 if (!didLoopBack)
1131 /* We didn't loop back. Advance to the next wave header */
1132 wwo->lpPlayPtr = wwo->lpPlayPtr->lpNext;
1134 if (wwo->lpPlayPtr)
1135 wodHelper_CheckForLoopBegin(wwo);
1139 /* Send the "done" notification for each WAVEHDR in a list. The list must be
1140 * free-standing. It should not be part of a device instance's queue.
1141 * This function must be called with the WAVEOUT_INSTANCE lock *not* held.
1142 * Furthermore, it does not lock it, itself. That's because the callback to the
1143 * application may prompt the application to operate on the device, and we don't
1144 * want to deadlock.
1146 static void wodHelper_NotifyDoneForList(WINE_WAVEOUT_INSTANCE* wwo, LPWAVEHDR lpWaveHdr)
1148 while (lpWaveHdr)
1150 LPWAVEHDR lpNext = lpWaveHdr->lpNext;
1152 lpWaveHdr->lpNext = NULL;
1153 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1154 lpWaveHdr->dwFlags |= WHDR_DONE;
1155 wodNotifyClient(wwo, WOM_DONE, (DWORD)lpWaveHdr, 0);
1157 lpWaveHdr = lpNext;
1161 /* if force is TRUE then notify the client that all the headers were completed
1163 static void wodHelper_NotifyCompletions(WINE_WAVEOUT_INSTANCE* wwo, BOOL force)
1165 LPWAVEHDR lpFirstDoneWaveHdr = NULL;
1167 OSSpinLockLock(&wwo->lock);
1169 /* First, excise all of the done headers from the queue into
1170 * a free-standing list. */
1171 if (force)
1173 lpFirstDoneWaveHdr = wwo->lpQueuePtr;
1174 wwo->lpQueuePtr = NULL;
1176 else
1178 LPWAVEHDR lpWaveHdr;
1179 LPWAVEHDR lpLastDoneWaveHdr = NULL;
1181 /* Start from lpQueuePtr and keep notifying until:
1182 * - we hit an unwritten wavehdr
1183 * - we hit the beginning of a running loop
1184 * - we hit a wavehdr which hasn't finished playing
1186 for (
1187 lpWaveHdr = wwo->lpQueuePtr;
1188 lpWaveHdr &&
1189 lpWaveHdr != wwo->lpPlayPtr &&
1190 lpWaveHdr != wwo->lpLoopPtr;
1191 lpWaveHdr = lpWaveHdr->lpNext
1194 if (!lpFirstDoneWaveHdr)
1195 lpFirstDoneWaveHdr = lpWaveHdr;
1196 lpLastDoneWaveHdr = lpWaveHdr;
1199 if (lpLastDoneWaveHdr)
1201 wwo->lpQueuePtr = lpLastDoneWaveHdr->lpNext;
1202 lpLastDoneWaveHdr->lpNext = NULL;
1206 OSSpinLockUnlock(&wwo->lock);
1208 /* Now, send the "done" notification for each header in our list. */
1209 wodHelper_NotifyDoneForList(wwo, lpFirstDoneWaveHdr);
1213 /**************************************************************************
1214 * wodWrite [internal]
1217 static DWORD wodWrite(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1219 LPWAVEHDR*wh;
1221 TRACE("(%u, %p, %p, %lu, %08X);\n", wDevID, wwo, lpWaveHdr, (unsigned long)lpWaveHdr->dwBufferLength, dwSize);
1223 /* first, do the sanity checks... */
1224 if (wDevID >= MAX_WAVEOUTDRV)
1226 WARN("bad dev ID !\n");
1227 return MMSYSERR_BADDEVICEID;
1230 if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
1232 TRACE("unprepared\n");
1233 return WAVERR_UNPREPARED;
1236 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1238 TRACE("still playing\n");
1239 return WAVERR_STILLPLAYING;
1242 lpWaveHdr->dwFlags &= ~WHDR_DONE;
1243 lpWaveHdr->dwFlags |= WHDR_INQUEUE;
1244 lpWaveHdr->lpNext = 0;
1246 OSSpinLockLock(&wwo->lock);
1247 /* insert buffer at the end of queue */
1248 for (wh = &(wwo->lpQueuePtr); *wh; wh = &((*wh)->lpNext))
1249 /* Do nothing */;
1250 *wh = lpWaveHdr;
1252 if (!wwo->lpPlayPtr)
1254 wwo->lpPlayPtr = lpWaveHdr;
1256 wodHelper_CheckForLoopBegin(wwo);
1258 wwo->dwPartialOffset = 0;
1260 OSSpinLockUnlock(&wwo->lock);
1262 return MMSYSERR_NOERROR;
1265 /**************************************************************************
1266 * wodPause [internal]
1268 static DWORD wodPause(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo)
1270 OSStatus status;
1272 TRACE("(%u, %p);!\n", wDevID, wwo);
1274 if (wDevID >= MAX_WAVEOUTDRV)
1276 WARN("bad device ID !\n");
1277 return MMSYSERR_BADDEVICEID;
1280 /* The order of the following operations is important since we can't hold
1281 * the mutex while we make an Audio Unit call. Stop the Audio Unit before
1282 * setting the PAUSED state. In wodRestart, the order is reversed. This
1283 * guarantees that we can't get into a situation where the state is
1284 * PLAYING but the Audio Unit isn't running. Although we can be in PAUSED
1285 * state with the Audio Unit still running, that's harmless because the
1286 * render callback will just produce silence.
1288 status = AudioOutputUnitStop(wwo->audioUnit);
1289 if (status)
1290 WARN("AudioOutputUnitStop return %s\n", wine_dbgstr_fourcc(status));
1292 OSSpinLockLock(&wwo->lock);
1293 if (wwo->state == WINE_WS_PLAYING)
1294 wwo->state = WINE_WS_PAUSED;
1295 OSSpinLockUnlock(&wwo->lock);
1297 return MMSYSERR_NOERROR;
1300 /**************************************************************************
1301 * wodRestart [internal]
1303 static DWORD wodRestart(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo)
1305 OSStatus status;
1307 TRACE("(%u, %p);\n", wDevID, wwo);
1309 if (wDevID >= MAX_WAVEOUTDRV )
1311 WARN("bad device ID !\n");
1312 return MMSYSERR_BADDEVICEID;
1315 /* The order of the following operations is important since we can't hold
1316 * the mutex while we make an Audio Unit call. Set the PLAYING
1317 * state before starting the Audio Unit. In wodPause, the order is
1318 * reversed. This guarantees that we can't get into a situation where
1319 * the state is PLAYING but the Audio Unit isn't running.
1320 * Although we can be in PAUSED state with the Audio Unit still running,
1321 * that's harmless because the render callback will just produce silence.
1323 OSSpinLockLock(&wwo->lock);
1324 if (wwo->state == WINE_WS_PAUSED)
1325 wwo->state = WINE_WS_PLAYING;
1326 OSSpinLockUnlock(&wwo->lock);
1328 status = AudioOutputUnitStart(wwo->audioUnit);
1329 if (status) {
1330 ERR("AudioOutputUnitStart return %s\n", wine_dbgstr_fourcc(status));
1331 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1334 return MMSYSERR_NOERROR;
1337 /**************************************************************************
1338 * wodReset [internal]
1340 static DWORD wodReset(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo)
1342 OSStatus status;
1343 LPWAVEHDR lpSavedQueuePtr;
1345 TRACE("(%u, %p);\n", wDevID, wwo);
1347 if (wDevID >= MAX_WAVEOUTDRV)
1349 WARN("bad device ID !\n");
1350 return MMSYSERR_BADDEVICEID;
1353 OSSpinLockLock(&wwo->lock);
1355 if (wwo->state == WINE_WS_CLOSING || wwo->state == WINE_WS_OPENING)
1357 OSSpinLockUnlock(&wwo->lock);
1358 WARN("resetting a closed device\n");
1359 return MMSYSERR_INVALHANDLE;
1362 lpSavedQueuePtr = wwo->lpQueuePtr;
1363 wwo->lpPlayPtr = wwo->lpQueuePtr = wwo->lpLoopPtr = NULL;
1364 wwo->state = WINE_WS_PLAYING;
1365 wwo->dwPlayedTotal = 0;
1367 wwo->dwPartialOffset = 0; /* Clear partial wavehdr */
1369 OSSpinLockUnlock(&wwo->lock);
1371 status = AudioOutputUnitStart(wwo->audioUnit);
1373 if (status) {
1374 ERR( "AudioOutputUnitStart return %s\n", wine_dbgstr_fourcc(status));
1375 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1378 /* Now, send the "done" notification for each header in our list. */
1379 /* Do this last so the reset operation is effectively complete before the
1380 * app does whatever it's going to do in response to these notifications. */
1381 wodHelper_NotifyDoneForList(wwo, lpSavedQueuePtr);
1383 return MMSYSERR_NOERROR;
1386 /**************************************************************************
1387 * wodBreakLoop [internal]
1389 static DWORD wodBreakLoop(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo)
1391 TRACE("(%u, %p);\n", wDevID, wwo);
1393 if (wDevID >= MAX_WAVEOUTDRV)
1395 WARN("bad device ID !\n");
1396 return MMSYSERR_BADDEVICEID;
1399 OSSpinLockLock(&wwo->lock);
1401 if (wwo->lpLoopPtr != NULL)
1403 /* ensure exit at end of current loop */
1404 wwo->dwLoops = 1;
1407 OSSpinLockUnlock(&wwo->lock);
1409 return MMSYSERR_NOERROR;
1412 /**************************************************************************
1413 * wodGetPosition [internal]
1415 static DWORD wodGetPosition(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, LPMMTIME lpTime, DWORD uSize)
1417 DWORD val;
1419 TRACE("(%u, %p, %p, %u);\n", wDevID, wwo, lpTime, uSize);
1421 if (wDevID >= MAX_WAVEOUTDRV)
1423 WARN("bad device ID !\n");
1424 return MMSYSERR_BADDEVICEID;
1427 /* if null pointer to time structure return error */
1428 if (lpTime == NULL) return MMSYSERR_INVALPARAM;
1430 OSSpinLockLock(&wwo->lock);
1431 val = wwo->dwPlayedTotal;
1432 OSSpinLockUnlock(&wwo->lock);
1434 return bytes_to_mmtime(lpTime, val, &wwo->format);
1437 /**************************************************************************
1438 * wodGetVolume [internal]
1440 static DWORD wodGetVolume(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, LPDWORD lpdwVol)
1442 float left;
1443 float right;
1445 if (wDevID >= MAX_WAVEOUTDRV)
1447 WARN("bad device ID !\n");
1448 return MMSYSERR_BADDEVICEID;
1451 TRACE("(%u, %p, %p);\n", wDevID, wwo, lpdwVol);
1453 AudioUnit_GetVolume(wwo->audioUnit, &left, &right);
1455 *lpdwVol = ((WORD) left * 0xFFFFl) + (((WORD) right * 0xFFFFl) << 16);
1457 return MMSYSERR_NOERROR;
1460 /**************************************************************************
1461 * wodSetVolume [internal]
1463 static DWORD wodSetVolume(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, DWORD dwParam)
1465 float left;
1466 float right;
1468 if (wDevID >= MAX_WAVEOUTDRV)
1470 WARN("bad device ID !\n");
1471 return MMSYSERR_BADDEVICEID;
1474 left = LOWORD(dwParam) / 65535.0f;
1475 right = HIWORD(dwParam) / 65535.0f;
1477 TRACE("(%u, %p, %08x);\n", wDevID, wwo, dwParam);
1479 AudioUnit_SetVolume(wwo->audioUnit, left, right);
1481 return MMSYSERR_NOERROR;
1484 /**************************************************************************
1485 * wodGetNumDevs [internal]
1487 static DWORD wodGetNumDevs(void)
1489 TRACE("\n");
1490 return MAX_WAVEOUTDRV;
1493 /**************************************************************************
1494 * wodDevInterfaceSize [internal]
1496 static DWORD wodDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
1498 TRACE("(%u, %p)\n", wDevID, dwParam1);
1500 *dwParam1 = MultiByteToWideChar(CP_UNIXCP, 0, WOutDev[wDevID].cadev->interface_name, -1,
1501 NULL, 0 ) * sizeof(WCHAR);
1502 return MMSYSERR_NOERROR;
1505 /**************************************************************************
1506 * wodDevInterface [internal]
1508 static DWORD wodDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
1510 TRACE("\n");
1511 if (dwParam2 >= MultiByteToWideChar(CP_UNIXCP, 0, WOutDev[wDevID].cadev->interface_name, -1,
1512 NULL, 0 ) * sizeof(WCHAR))
1514 MultiByteToWideChar(CP_UNIXCP, 0, WOutDev[wDevID].cadev->interface_name, -1,
1515 dwParam1, dwParam2 / sizeof(WCHAR));
1516 return MMSYSERR_NOERROR;
1518 return MMSYSERR_INVALPARAM;
1521 /**************************************************************************
1522 * widDsCreate [internal]
1524 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
1526 TRACE("(%d,%p)\n",wDevID,drv);
1528 FIXME("DirectSound not implemented\n");
1529 FIXME("The (slower) DirectSound HEL mode will be used instead.\n");
1530 return MMSYSERR_NOTSUPPORTED;
1533 /**************************************************************************
1534 * wodDsDesc [internal]
1536 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc)
1538 /* The DirectSound HEL will automatically wrap a non-DirectSound-capable
1539 * driver in a DirectSound adaptor, thus allowing the driver to be used by
1540 * DirectSound clients. However, it only does this if we respond
1541 * successfully to the DRV_QUERYDSOUNDDESC message. It's enough to fill in
1542 * the driver and device names of the description output parameter. */
1543 *desc = WOutDev[wDevID].cadev->ds_desc;
1544 return MMSYSERR_NOERROR;
1547 /**************************************************************************
1548 * wodMessage (WINECOREAUDIO.7)
1550 DWORD WINAPI CoreAudio_wodMessage(UINT wDevID, UINT wMsg, DWORD_PTR dwUser,
1551 DWORD_PTR dwParam1, DWORD_PTR dwParam2)
1553 WINE_WAVEOUT_INSTANCE* wwo = (WINE_WAVEOUT_INSTANCE*)dwUser;
1555 TRACE("(%u, %s, %p, %p, %p);\n",
1556 wDevID, getMessage(wMsg), (void*)dwUser, (void*)dwParam1, (void*)dwParam2);
1558 switch (wMsg) {
1559 case DRVM_INIT:
1560 case DRVM_EXIT:
1561 case DRVM_ENABLE:
1562 case DRVM_DISABLE:
1564 /* FIXME: Pretend this is supported */
1565 return 0;
1566 case WODM_OPEN: return wodOpen(wDevID, (WINE_WAVEOUT_INSTANCE**)dwUser, (LPWAVEOPENDESC) dwParam1, dwParam2);
1567 case WODM_CLOSE: return wodClose(wDevID, wwo);
1568 case WODM_WRITE: return wodWrite(wDevID, wwo, (LPWAVEHDR) dwParam1, dwParam2);
1569 case WODM_PAUSE: return wodPause(wDevID, wwo);
1570 case WODM_GETPOS: return wodGetPosition(wDevID, wwo, (LPMMTIME) dwParam1, dwParam2);
1571 case WODM_BREAKLOOP: return wodBreakLoop(wDevID, wwo);
1572 case WODM_PREPARE: return wodPrepare(wDevID, wwo, (LPWAVEHDR)dwParam1, dwParam2);
1573 case WODM_UNPREPARE: return wodUnprepare(wDevID, wwo, (LPWAVEHDR)dwParam1, dwParam2);
1575 case WODM_GETDEVCAPS: return wodGetDevCaps(wDevID, (LPWAVEOUTCAPSW) dwParam1, dwParam2);
1576 case WODM_GETNUMDEVS: return wodGetNumDevs();
1578 case WODM_GETPITCH:
1579 case WODM_SETPITCH:
1580 case WODM_GETPLAYBACKRATE:
1581 case WODM_SETPLAYBACKRATE: return MMSYSERR_NOTSUPPORTED;
1582 case WODM_GETVOLUME: return wodGetVolume(wDevID, wwo, (LPDWORD)dwParam1);
1583 case WODM_SETVOLUME: return wodSetVolume(wDevID, wwo, dwParam1);
1584 case WODM_RESTART: return wodRestart(wDevID, wwo);
1585 case WODM_RESET: return wodReset(wDevID, wwo);
1587 case DRV_QUERYDEVICEINTERFACESIZE: return wodDevInterfaceSize (wDevID, (LPDWORD)dwParam1);
1588 case DRV_QUERYDEVICEINTERFACE: return wodDevInterface (wDevID, (PWCHAR)dwParam1, dwParam2);
1589 case DRV_QUERYDSOUNDIFACE: return wodDsCreate (wDevID, (PIDSDRIVER*)dwParam1);
1590 case DRV_QUERYDSOUNDDESC: return wodDsDesc (wDevID, (PDSDRIVERDESC)dwParam1);
1592 default:
1593 FIXME("unknown message %d!\n", wMsg);
1596 return MMSYSERR_NOTSUPPORTED;
1599 /*======================================================================*
1600 * Low level DSOUND implementation *
1601 *======================================================================*/
1603 typedef struct IDsDriverImpl IDsDriverImpl;
1604 typedef struct IDsDriverBufferImpl IDsDriverBufferImpl;
1606 struct IDsDriverImpl
1608 /* IUnknown fields */
1609 const IDsDriverVtbl *lpVtbl;
1610 DWORD ref;
1611 /* IDsDriverImpl fields */
1612 UINT wDevID;
1613 IDsDriverBufferImpl*primary;
1616 struct IDsDriverBufferImpl
1618 /* IUnknown fields */
1619 const IDsDriverBufferVtbl *lpVtbl;
1620 DWORD ref;
1621 /* IDsDriverBufferImpl fields */
1622 IDsDriverImpl* drv;
1623 DWORD buflen;
1628 CoreAudio IO threaded callback,
1629 we can't call Wine debug channels, critical section or anything using NtCurrentTeb here.
1631 OSStatus CoreAudio_woAudioUnitIOProc(void *inRefCon,
1632 AudioUnitRenderActionFlags *ioActionFlags,
1633 const AudioTimeStamp *inTimeStamp,
1634 UInt32 inBusNumber,
1635 UInt32 inNumberFrames,
1636 AudioBufferList *ioData)
1638 UInt32 buffer;
1639 WINE_WAVEOUT_INSTANCE* wwo = (WINE_WAVEOUT_INSTANCE*)inRefCon;
1640 int needNotify = 0;
1642 unsigned int dataNeeded = ioData->mBuffers[0].mDataByteSize;
1643 unsigned int dataProvided = 0;
1645 OSSpinLockLock(&wwo->lock);
1647 /* We might have been called before wwo has been completely filled out by
1648 * wodOpen, or while it's being closed in wodClose. We have to do nothing
1649 * in that case. The check of wwo->state below ensures that. */
1650 while (dataNeeded > 0 && wwo->state == WINE_WS_PLAYING && wwo->lpPlayPtr)
1652 unsigned int available = wwo->lpPlayPtr->dwBufferLength - wwo->dwPartialOffset;
1653 unsigned int toCopy;
1655 if (available >= dataNeeded)
1656 toCopy = dataNeeded;
1657 else
1658 toCopy = available;
1660 if (toCopy > 0)
1662 memcpy((char*)ioData->mBuffers[0].mData + dataProvided,
1663 wwo->lpPlayPtr->lpData + wwo->dwPartialOffset, toCopy);
1664 wwo->dwPartialOffset += toCopy;
1665 wwo->dwPlayedTotal += toCopy;
1666 dataProvided += toCopy;
1667 dataNeeded -= toCopy;
1668 available -= toCopy;
1671 if (available == 0)
1673 wodHelper_PlayPtrNext(wwo);
1674 needNotify = 1;
1677 ioData->mBuffers[0].mDataByteSize = dataProvided;
1679 OSSpinLockUnlock(&wwo->lock);
1681 /* We can't provide any more wave data. Fill the rest with silence. */
1682 if (dataNeeded > 0)
1684 if (!dataProvided)
1685 *ioActionFlags |= kAudioUnitRenderAction_OutputIsSilence;
1686 memset((char*)ioData->mBuffers[0].mData + dataProvided, 0, dataNeeded);
1687 dataProvided += dataNeeded;
1688 dataNeeded = 0;
1691 /* We only fill buffer 0. Set any others that might be requested to 0. */
1692 for (buffer = 1; buffer < ioData->mNumberBuffers; buffer++)
1694 memset(ioData->mBuffers[buffer].mData, 0, ioData->mBuffers[buffer].mDataByteSize);
1697 if (needNotify) wodSendNotifyCompletionsMessage(wwo);
1698 return noErr;
1702 /*======================================================================*
1703 * Low level WAVE IN implementation *
1704 *======================================================================*/
1706 /**************************************************************************
1707 * widNotifyClient [internal]
1709 static DWORD widNotifyClient(WINE_WAVEIN* wwi, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
1711 TRACE("wMsg = 0x%04x dwParm1 = %04X dwParam2 = %04X\n", wMsg, dwParam1, dwParam2);
1713 switch (wMsg)
1715 case WIM_OPEN:
1716 case WIM_CLOSE:
1717 case WIM_DATA:
1718 if (wwi->wFlags != DCB_NULL &&
1719 !DriverCallback(wwi->waveDesc.dwCallback, wwi->wFlags,
1720 (HDRVR)wwi->waveDesc.hWave, wMsg, wwi->waveDesc.dwInstance,
1721 dwParam1, dwParam2))
1723 WARN("can't notify client !\n");
1724 return MMSYSERR_ERROR;
1726 break;
1727 default:
1728 FIXME("Unknown callback message %u\n", wMsg);
1729 return MMSYSERR_INVALPARAM;
1731 return MMSYSERR_NOERROR;
1735 /**************************************************************************
1736 * widHelper_NotifyCompletions [internal]
1738 static void widHelper_NotifyCompletions(WINE_WAVEIN* wwi)
1740 LPWAVEHDR lpWaveHdr;
1741 LPWAVEHDR lpFirstDoneWaveHdr = NULL;
1742 LPWAVEHDR lpLastDoneWaveHdr = NULL;
1744 OSSpinLockLock(&wwi->lock);
1746 /* First, excise all of the done headers from the queue into
1747 * a free-standing list. */
1749 /* Start from lpQueuePtr and keep notifying until:
1750 * - we hit an unfilled wavehdr
1751 * - we hit the end of the list
1753 for (
1754 lpWaveHdr = wwi->lpQueuePtr;
1755 lpWaveHdr &&
1756 lpWaveHdr->dwBytesRecorded >= lpWaveHdr->dwBufferLength;
1757 lpWaveHdr = lpWaveHdr->lpNext
1760 if (!lpFirstDoneWaveHdr)
1761 lpFirstDoneWaveHdr = lpWaveHdr;
1762 lpLastDoneWaveHdr = lpWaveHdr;
1765 if (lpLastDoneWaveHdr)
1767 wwi->lpQueuePtr = lpLastDoneWaveHdr->lpNext;
1768 lpLastDoneWaveHdr->lpNext = NULL;
1771 OSSpinLockUnlock(&wwi->lock);
1773 /* Now, send the "done" notification for each header in our list. */
1774 lpWaveHdr = lpFirstDoneWaveHdr;
1775 while (lpWaveHdr)
1777 LPWAVEHDR lpNext = lpWaveHdr->lpNext;
1779 lpWaveHdr->lpNext = NULL;
1780 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1781 lpWaveHdr->dwFlags |= WHDR_DONE;
1782 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
1784 lpWaveHdr = lpNext;
1789 /**************************************************************************
1790 * widGetDevCaps [internal]
1792 static DWORD widGetDevCaps(WORD wDevID, LPWAVEINCAPSW lpCaps, DWORD dwSize)
1794 TRACE("(%u, %p, %u);\n", wDevID, lpCaps, dwSize);
1796 if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
1798 if (wDevID >= MAX_WAVEINDRV)
1800 TRACE("MAX_WAVEINDRV reached !\n");
1801 return MMSYSERR_BADDEVICEID;
1804 memcpy(lpCaps, &WInDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
1805 return MMSYSERR_NOERROR;
1809 /**************************************************************************
1810 * widHelper_DestroyAudioBufferList [internal]
1811 * Convenience function to dispose of our audio buffers
1813 static void widHelper_DestroyAudioBufferList(AudioBufferList* list)
1815 if (list)
1817 UInt32 i;
1818 for (i = 0; i < list->mNumberBuffers; i++)
1820 if (list->mBuffers[i].mData)
1821 HeapFree(GetProcessHeap(), 0, list->mBuffers[i].mData);
1823 HeapFree(GetProcessHeap(), 0, list);
1828 #define AUDIOBUFFERLISTSIZE(numBuffers) (offsetof(AudioBufferList, mBuffers) + (numBuffers) * sizeof(AudioBuffer))
1830 /**************************************************************************
1831 * widHelper_AllocateAudioBufferList [internal]
1832 * Convenience function to allocate our audio buffers
1834 static AudioBufferList* widHelper_AllocateAudioBufferList(UInt32 numChannels, UInt32 bitsPerChannel, UInt32 bufferFrames, BOOL interleaved)
1836 UInt32 numBuffers;
1837 UInt32 channelsPerFrame;
1838 UInt32 bytesPerFrame;
1839 UInt32 bytesPerBuffer;
1840 AudioBufferList* list;
1841 UInt32 i;
1843 if (interleaved)
1845 /* For interleaved audio, we allocate one buffer for all channels. */
1846 numBuffers = 1;
1847 channelsPerFrame = numChannels;
1849 else
1851 numBuffers = numChannels;
1852 channelsPerFrame = 1;
1855 bytesPerFrame = bitsPerChannel * channelsPerFrame / 8;
1856 bytesPerBuffer = bytesPerFrame * bufferFrames;
1858 list = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, AUDIOBUFFERLISTSIZE(numBuffers));
1859 if (list == NULL)
1860 return NULL;
1862 list->mNumberBuffers = numBuffers;
1863 for (i = 0; i < numBuffers; ++i)
1865 list->mBuffers[i].mNumberChannels = channelsPerFrame;
1866 list->mBuffers[i].mDataByteSize = bytesPerBuffer;
1867 list->mBuffers[i].mData = HeapAlloc(GetProcessHeap(), 0, bytesPerBuffer);
1868 if (list->mBuffers[i].mData == NULL)
1870 widHelper_DestroyAudioBufferList(list);
1871 return NULL;
1874 return list;
1878 /**************************************************************************
1879 * widOpen [internal]
1881 static DWORD widOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
1883 WINE_WAVEIN* wwi;
1884 UInt32 frameCount;
1886 TRACE("(%u, %p, %08X);\n", wDevID, lpDesc, dwFlags);
1887 if (lpDesc == NULL)
1889 WARN("Invalid Parameter !\n");
1890 return MMSYSERR_INVALPARAM;
1892 if (wDevID >= MAX_WAVEINDRV)
1894 TRACE ("MAX_WAVEINDRV reached !\n");
1895 return MMSYSERR_BADDEVICEID;
1898 TRACE("Format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
1899 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1900 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
1902 if (!supportedFormat(lpDesc->lpFormat) ||
1903 lpDesc->lpFormat->nSamplesPerSec != AudioUnit_GetInputDeviceSampleRate()
1906 WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
1907 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1908 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
1909 return WAVERR_BADFORMAT;
1912 if (dwFlags & WAVE_FORMAT_QUERY)
1914 TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
1915 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1916 lpDesc->lpFormat->nSamplesPerSec);
1917 return MMSYSERR_NOERROR;
1920 /* nBlockAlign and nAvgBytesPerSec are output variables for dsound */
1921 if (lpDesc->lpFormat->nBlockAlign != lpDesc->lpFormat->nChannels*lpDesc->lpFormat->wBitsPerSample/8) {
1922 lpDesc->lpFormat->nBlockAlign = lpDesc->lpFormat->nChannels*lpDesc->lpFormat->wBitsPerSample/8;
1923 WARN("Fixing nBlockAlign\n");
1925 if (lpDesc->lpFormat->nAvgBytesPerSec!= lpDesc->lpFormat->nSamplesPerSec*lpDesc->lpFormat->nBlockAlign) {
1926 lpDesc->lpFormat->nAvgBytesPerSec = lpDesc->lpFormat->nSamplesPerSec*lpDesc->lpFormat->nBlockAlign;
1927 WARN("Fixing nAvgBytesPerSec\n");
1930 wwi = &WInDev[wDevID];
1931 if (!OSSpinLockTry(&wwi->lock))
1932 return MMSYSERR_ALLOCATED;
1934 if (wwi->state != WINE_WS_CLOSED)
1936 OSSpinLockUnlock(&wwi->lock);
1937 return MMSYSERR_ALLOCATED;
1940 wwi->state = WINE_WS_STOPPED;
1941 wwi->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
1943 wwi->waveDesc = *lpDesc;
1944 copyFormat(lpDesc->lpFormat, &wwi->format);
1946 wwi->dwTotalRecorded = 0;
1948 wwi->trace_on = TRACE_ON(wave);
1949 wwi->warn_on = WARN_ON(wave);
1950 wwi->err_on = ERR_ON(wave);
1952 if (!AudioUnit_CreateInputUnit(wwi, &wwi->audioUnit,
1953 wwi->format.wf.nChannels, wwi->format.wf.nSamplesPerSec,
1954 wwi->format.wBitsPerSample, &frameCount))
1956 OSSpinLockUnlock(&wwi->lock);
1957 ERR("AudioUnit_CreateInputUnit failed\n");
1958 return MMSYSERR_ERROR;
1961 /* Allocate our audio buffers */
1962 wwi->bufferList = widHelper_AllocateAudioBufferList(wwi->format.wf.nChannels,
1963 wwi->format.wBitsPerSample, frameCount, TRUE);
1964 if (wwi->bufferList == NULL)
1966 AudioUnitUninitialize(wwi->audioUnit);
1967 AudioUnit_CloseAudioUnit(wwi->audioUnit);
1968 OSSpinLockUnlock(&wwi->lock);
1969 ERR("Failed to allocate buffer list\n");
1970 return MMSYSERR_NOMEM;
1973 /* Keep a copy of the buffer list structure (but not the buffers themselves)
1974 * in case AudioUnitRender clobbers the original, as it tends to do. */
1975 wwi->bufferListCopy = HeapAlloc(GetProcessHeap(), 0, AUDIOBUFFERLISTSIZE(wwi->bufferList->mNumberBuffers));
1976 if (wwi->bufferListCopy == NULL)
1978 widHelper_DestroyAudioBufferList(wwi->bufferList);
1979 AudioUnitUninitialize(wwi->audioUnit);
1980 AudioUnit_CloseAudioUnit(wwi->audioUnit);
1981 OSSpinLockUnlock(&wwi->lock);
1982 ERR("Failed to allocate buffer list copy\n");
1983 return MMSYSERR_NOMEM;
1985 memcpy(wwi->bufferListCopy, wwi->bufferList, AUDIOBUFFERLISTSIZE(wwi->bufferList->mNumberBuffers));
1987 OSSpinLockUnlock(&wwi->lock);
1989 return widNotifyClient(wwi, WIM_OPEN, 0L, 0L);
1993 /**************************************************************************
1994 * widClose [internal]
1996 static DWORD widClose(WORD wDevID)
1998 DWORD ret = MMSYSERR_NOERROR;
1999 WINE_WAVEIN* wwi;
2000 OSStatus err;
2002 TRACE("(%u);\n", wDevID);
2004 if (wDevID >= MAX_WAVEINDRV)
2006 WARN("bad device ID !\n");
2007 return MMSYSERR_BADDEVICEID;
2010 wwi = &WInDev[wDevID];
2011 OSSpinLockLock(&wwi->lock);
2012 if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2014 WARN("Device already closed.\n");
2015 ret = MMSYSERR_INVALHANDLE;
2017 else if (wwi->lpQueuePtr)
2019 WARN("Buffers in queue.\n");
2020 ret = WAVERR_STILLPLAYING;
2022 else
2024 wwi->state = WINE_WS_CLOSING;
2027 OSSpinLockUnlock(&wwi->lock);
2029 if (ret != MMSYSERR_NOERROR)
2030 return ret;
2033 /* Clean up and close the audio unit. This has to be done without
2034 * wwi->lock being held to avoid deadlock. AudioUnitUninitialize will
2035 * grab an internal Core Audio lock while waiting for the device work
2036 * thread to exit. Meanwhile the device work thread may be holding
2037 * that lock and trying to grab the wwi->lock in the callback. */
2038 err = AudioUnitUninitialize(wwi->audioUnit);
2039 if (err)
2040 ERR("AudioUnitUninitialize return %s\n", wine_dbgstr_fourcc(err));
2042 if (!AudioUnit_CloseAudioUnit(wwi->audioUnit))
2043 ERR("Can't close AudioUnit\n");
2046 OSSpinLockLock(&wwi->lock);
2047 assert(wwi->state == WINE_WS_CLOSING);
2049 /* Dellocate our audio buffers */
2050 widHelper_DestroyAudioBufferList(wwi->bufferList);
2051 wwi->bufferList = NULL;
2052 HeapFree(GetProcessHeap(), 0, wwi->bufferListCopy);
2053 wwi->bufferListCopy = NULL;
2055 wwi->audioUnit = NULL;
2056 wwi->state = WINE_WS_CLOSED;
2057 OSSpinLockUnlock(&wwi->lock);
2059 ret = widNotifyClient(wwi, WIM_CLOSE, 0L, 0L);
2061 return ret;
2065 /**************************************************************************
2066 * widAddBuffer [internal]
2068 static DWORD widAddBuffer(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
2070 DWORD ret = MMSYSERR_NOERROR;
2071 WINE_WAVEIN* wwi;
2073 TRACE("(%u, %p, %08X);\n", wDevID, lpWaveHdr, dwSize);
2075 if (wDevID >= MAX_WAVEINDRV)
2077 WARN("invalid device ID\n");
2078 return MMSYSERR_INVALHANDLE;
2080 if (!(lpWaveHdr->dwFlags & WHDR_PREPARED))
2082 TRACE("never been prepared !\n");
2083 return WAVERR_UNPREPARED;
2085 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
2087 TRACE("header already in use !\n");
2088 return WAVERR_STILLPLAYING;
2091 wwi = &WInDev[wDevID];
2092 OSSpinLockLock(&wwi->lock);
2094 if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2096 WARN("Trying to add buffer to closed device.\n");
2097 ret = MMSYSERR_INVALHANDLE;
2099 else
2101 LPWAVEHDR* wh;
2103 lpWaveHdr->dwFlags |= WHDR_INQUEUE;
2104 lpWaveHdr->dwFlags &= ~WHDR_DONE;
2105 lpWaveHdr->dwBytesRecorded = 0;
2106 lpWaveHdr->lpNext = NULL;
2108 /* insert buffer at end of queue */
2109 for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext))
2110 /* Do nothing */;
2111 *wh = lpWaveHdr;
2114 OSSpinLockUnlock(&wwi->lock);
2116 return ret;
2120 /**************************************************************************
2121 * widStart [internal]
2123 static DWORD widStart(WORD wDevID)
2125 DWORD ret = MMSYSERR_NOERROR;
2126 WINE_WAVEIN* wwi;
2128 TRACE("(%u);\n", wDevID);
2129 if (wDevID >= MAX_WAVEINDRV)
2131 WARN("invalid device ID\n");
2132 return MMSYSERR_INVALHANDLE;
2135 /* The order of the following operations is important since we can't hold
2136 * the mutex while we make an Audio Unit call. Set the PLAYING state
2137 * before starting the Audio Unit. In widStop, the order is reversed.
2138 * This guarantees that we can't get into a situation where the state is
2139 * PLAYING but the Audio Unit isn't running. Although we can be in STOPPED
2140 * state with the Audio Unit still running, that's harmless because the
2141 * input callback will just throw away the sound data.
2143 wwi = &WInDev[wDevID];
2144 OSSpinLockLock(&wwi->lock);
2146 if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2148 WARN("Trying to start closed device.\n");
2149 ret = MMSYSERR_INVALHANDLE;
2151 else
2152 wwi->state = WINE_WS_PLAYING;
2154 OSSpinLockUnlock(&wwi->lock);
2156 if (ret == MMSYSERR_NOERROR)
2158 /* Start pulling for audio data */
2159 OSStatus err = AudioOutputUnitStart(wwi->audioUnit);
2160 if (err != noErr)
2161 ERR("Failed to start AU: %08lx\n", err);
2163 TRACE("Recording started...\n");
2166 return ret;
2170 /**************************************************************************
2171 * widStop [internal]
2173 static DWORD widStop(WORD wDevID)
2175 DWORD ret = MMSYSERR_NOERROR;
2176 WINE_WAVEIN* wwi;
2177 WAVEHDR* lpWaveHdr = NULL;
2178 OSStatus err;
2180 TRACE("(%u);\n", wDevID);
2181 if (wDevID >= MAX_WAVEINDRV)
2183 WARN("invalid device ID\n");
2184 return MMSYSERR_INVALHANDLE;
2187 wwi = &WInDev[wDevID];
2189 /* The order of the following operations is important since we can't hold
2190 * the mutex while we make an Audio Unit call. Stop the Audio Unit before
2191 * setting the STOPPED state. In widStart, the order is reversed. This
2192 * guarantees that we can't get into a situation where the state is
2193 * PLAYING but the Audio Unit isn't running. Although we can be in STOPPED
2194 * state with the Audio Unit still running, that's harmless because the
2195 * input callback will just throw away the sound data.
2197 err = AudioOutputUnitStop(wwi->audioUnit);
2198 if (err != noErr)
2199 WARN("Failed to stop AU: %08lx\n", err);
2201 TRACE("Recording stopped.\n");
2203 OSSpinLockLock(&wwi->lock);
2205 if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2207 WARN("Trying to stop closed device.\n");
2208 ret = MMSYSERR_INVALHANDLE;
2210 else if (wwi->state != WINE_WS_STOPPED)
2212 wwi->state = WINE_WS_STOPPED;
2213 /* If there's a buffer in progress, it's done. Remove it from the
2214 * queue so that we can return it to the app, below. */
2215 if (wwi->lpQueuePtr)
2217 lpWaveHdr = wwi->lpQueuePtr;
2218 wwi->lpQueuePtr = lpWaveHdr->lpNext;
2222 OSSpinLockUnlock(&wwi->lock);
2224 if (lpWaveHdr)
2226 lpWaveHdr->lpNext = NULL;
2227 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2228 lpWaveHdr->dwFlags |= WHDR_DONE;
2229 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2232 return ret;
2235 /**************************************************************************
2236 * widGetPos [internal]
2238 static DWORD widGetPos(WORD wDevID, LPMMTIME lpTime, UINT size)
2240 DWORD val;
2241 WINE_WAVEIN* wwi;
2243 TRACE("(%u);\n", wDevID);
2244 if (wDevID >= MAX_WAVEINDRV)
2246 WARN("invalid device ID\n");
2247 return MMSYSERR_INVALHANDLE;
2250 wwi = &WInDev[wDevID];
2252 OSSpinLockLock(&WInDev[wDevID].lock);
2253 val = wwi->dwTotalRecorded;
2254 OSSpinLockUnlock(&WInDev[wDevID].lock);
2256 return bytes_to_mmtime(lpTime, val, &wwi->format);
2259 /**************************************************************************
2260 * widReset [internal]
2262 static DWORD widReset(WORD wDevID)
2264 DWORD ret = MMSYSERR_NOERROR;
2265 WINE_WAVEIN* wwi;
2266 WAVEHDR* lpWaveHdr = NULL;
2268 TRACE("(%u);\n", wDevID);
2269 if (wDevID >= MAX_WAVEINDRV)
2271 WARN("invalid device ID\n");
2272 return MMSYSERR_INVALHANDLE;
2275 wwi = &WInDev[wDevID];
2276 OSSpinLockLock(&wwi->lock);
2278 if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2280 WARN("Trying to reset a closed device.\n");
2281 ret = MMSYSERR_INVALHANDLE;
2283 else
2285 lpWaveHdr = wwi->lpQueuePtr;
2286 wwi->lpQueuePtr = NULL;
2287 wwi->state = WINE_WS_STOPPED;
2288 wwi->dwTotalRecorded = 0;
2291 OSSpinLockUnlock(&wwi->lock);
2293 if (ret == MMSYSERR_NOERROR)
2295 OSStatus err = AudioOutputUnitStop(wwi->audioUnit);
2296 if (err != noErr)
2297 WARN("Failed to stop AU: %08lx\n", err);
2299 TRACE("Recording stopped.\n");
2302 while (lpWaveHdr)
2304 WAVEHDR* lpNext = lpWaveHdr->lpNext;
2306 lpWaveHdr->lpNext = NULL;
2307 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2308 lpWaveHdr->dwFlags |= WHDR_DONE;
2309 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2311 lpWaveHdr = lpNext;
2314 return ret;
2318 /**************************************************************************
2319 * widGetNumDevs [internal]
2321 static DWORD widGetNumDevs(void)
2323 return MAX_WAVEINDRV;
2327 /**************************************************************************
2328 * widDevInterfaceSize [internal]
2330 static DWORD widDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
2332 TRACE("(%u, %p)\n", wDevID, dwParam1);
2334 *dwParam1 = MultiByteToWideChar(CP_UNIXCP, 0, WInDev[wDevID].interface_name, -1,
2335 NULL, 0 ) * sizeof(WCHAR);
2336 return MMSYSERR_NOERROR;
2340 /**************************************************************************
2341 * widDevInterface [internal]
2343 static DWORD widDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
2345 if (dwParam2 >= MultiByteToWideChar(CP_UNIXCP, 0, WInDev[wDevID].interface_name, -1,
2346 NULL, 0 ) * sizeof(WCHAR))
2348 MultiByteToWideChar(CP_UNIXCP, 0, WInDev[wDevID].interface_name, -1,
2349 dwParam1, dwParam2 / sizeof(WCHAR));
2350 return MMSYSERR_NOERROR;
2352 return MMSYSERR_INVALPARAM;
2356 /**************************************************************************
2357 * widDsCreate [internal]
2359 static DWORD widDsCreate(UINT wDevID, PIDSCDRIVER* drv)
2361 TRACE("(%d,%p)\n",wDevID,drv);
2363 FIXME("DirectSoundCapture not implemented\n");
2364 FIXME("The (slower) DirectSound HEL mode will be used instead.\n");
2365 return MMSYSERR_NOTSUPPORTED;
2368 /**************************************************************************
2369 * widDsDesc [internal]
2371 static DWORD widDsDesc(UINT wDevID, PDSDRIVERDESC desc)
2373 /* The DirectSound HEL will automatically wrap a non-DirectSound-capable
2374 * driver in a DirectSound adaptor, thus allowing the driver to be used by
2375 * DirectSound clients. However, it only does this if we respond
2376 * successfully to the DRV_QUERYDSOUNDDESC message. It's enough to fill in
2377 * the driver and device names of the description output parameter. */
2378 memset(desc, 0, sizeof(*desc));
2379 lstrcpynA(desc->szDrvname, "winecoreaudio.drv", sizeof(desc->szDrvname) - 1);
2380 lstrcpynA(desc->szDesc, WInDev[wDevID].interface_name, sizeof(desc->szDesc) - 1);
2381 return MMSYSERR_NOERROR;
2385 /**************************************************************************
2386 * widMessage (WINECOREAUDIO.6)
2388 DWORD WINAPI CoreAudio_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2389 DWORD dwParam1, DWORD dwParam2)
2391 TRACE("(%u, %04X, %08X, %08X, %08X);\n",
2392 wDevID, wMsg, dwUser, dwParam1, dwParam2);
2394 switch (wMsg)
2396 case DRVM_INIT:
2397 case DRVM_EXIT:
2398 case DRVM_ENABLE:
2399 case DRVM_DISABLE:
2400 /* FIXME: Pretend this is supported */
2401 return 0;
2402 case WIDM_OPEN: return widOpen (wDevID, (LPWAVEOPENDESC)dwParam1, dwParam2);
2403 case WIDM_CLOSE: return widClose (wDevID);
2404 case WIDM_ADDBUFFER: return widAddBuffer (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2405 case WIDM_PREPARE: return MMSYSERR_NOTSUPPORTED;
2406 case WIDM_UNPREPARE: return MMSYSERR_NOTSUPPORTED;
2407 case WIDM_GETDEVCAPS: return widGetDevCaps (wDevID, (LPWAVEINCAPSW)dwParam1, dwParam2);
2408 case WIDM_GETNUMDEVS: return widGetNumDevs ();
2409 case WIDM_RESET: return widReset (wDevID);
2410 case WIDM_START: return widStart (wDevID);
2411 case WIDM_STOP: return widStop (wDevID);
2412 case WIDM_GETPOS: return widGetPos (wDevID, (LPMMTIME)dwParam1, (UINT)dwParam2 );
2413 case DRV_QUERYDEVICEINTERFACESIZE: return widDevInterfaceSize (wDevID, (LPDWORD)dwParam1);
2414 case DRV_QUERYDEVICEINTERFACE: return widDevInterface (wDevID, (PWCHAR)dwParam1, dwParam2);
2415 case DRV_QUERYDSOUNDIFACE: return widDsCreate (wDevID, (PIDSCDRIVER*)dwParam1);
2416 case DRV_QUERYDSOUNDDESC: return widDsDesc (wDevID, (PDSDRIVERDESC)dwParam1);
2417 default:
2418 FIXME("unknown message %d!\n", wMsg);
2421 return MMSYSERR_NOTSUPPORTED;
2425 OSStatus CoreAudio_wiAudioUnitIOProc(void *inRefCon,
2426 AudioUnitRenderActionFlags *ioActionFlags,
2427 const AudioTimeStamp *inTimeStamp,
2428 UInt32 inBusNumber,
2429 UInt32 inNumberFrames,
2430 AudioBufferList *ioData)
2432 WINE_WAVEIN* wwi = (WINE_WAVEIN*)inRefCon;
2433 OSStatus err = noErr;
2434 BOOL needNotify = FALSE;
2435 WAVEHDR* lpStorePtr;
2436 unsigned int dataToStore;
2437 unsigned int dataStored = 0;
2440 if (wwi->trace_on)
2441 fprintf(stderr, "trace:wave:CoreAudio_wiAudioUnitIOProc (ioActionFlags = %08lx, "
2442 "inTimeStamp = { %f, %x%08x, %f, %x%08x, %08lx }, inBusNumber = %lu, inNumberFrames = %lu)\n",
2443 *ioActionFlags, inTimeStamp->mSampleTime, (DWORD)(inTimeStamp->mHostTime >>32),
2444 (DWORD)inTimeStamp->mHostTime, inTimeStamp->mRateScalar, (DWORD)(inTimeStamp->mWordClockTime >> 32),
2445 (DWORD)inTimeStamp->mWordClockTime, inTimeStamp->mFlags, inBusNumber, inNumberFrames);
2447 /* Render into audio buffer */
2448 /* FIXME: implement sample rate conversion on input. This will require
2449 * a different render strategy. We'll need to buffer the sound data
2450 * received here and pass it off to an AUConverter in another thread. */
2451 err = AudioUnitRender(wwi->audioUnit, ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, wwi->bufferList);
2452 if (err)
2454 if (wwi->err_on)
2455 fprintf(stderr, "err:wave:CoreAudio_wiAudioUnitIOProc AudioUnitRender failed with error %li\n", err);
2456 return err;
2459 /* Copy from audio buffer to the wavehdrs */
2460 dataToStore = wwi->bufferList->mBuffers[0].mDataByteSize;
2462 OSSpinLockLock(&wwi->lock);
2464 lpStorePtr = wwi->lpQueuePtr;
2466 /* We might have been called while the waveIn device is being closed in
2467 * widClose. We have to do nothing in that case. The check of wwi->state
2468 * below ensures that. */
2469 while (dataToStore > 0 && wwi->state == WINE_WS_PLAYING && lpStorePtr)
2471 unsigned int room = lpStorePtr->dwBufferLength - lpStorePtr->dwBytesRecorded;
2472 unsigned int toCopy;
2474 if (wwi->trace_on)
2475 fprintf(stderr, "trace:wave:CoreAudio_wiAudioUnitIOProc Looking to store %u bytes to wavehdr %p, which has room for %u\n",
2476 dataToStore, lpStorePtr, room);
2478 if (room >= dataToStore)
2479 toCopy = dataToStore;
2480 else
2481 toCopy = room;
2483 if (toCopy > 0)
2485 memcpy(lpStorePtr->lpData + lpStorePtr->dwBytesRecorded,
2486 (char*)wwi->bufferList->mBuffers[0].mData + dataStored, toCopy);
2487 lpStorePtr->dwBytesRecorded += toCopy;
2488 wwi->dwTotalRecorded += toCopy;
2489 dataStored += toCopy;
2490 dataToStore -= toCopy;
2491 room -= toCopy;
2494 if (room == 0)
2496 lpStorePtr = lpStorePtr->lpNext;
2497 needNotify = TRUE;
2501 OSSpinLockUnlock(&wwi->lock);
2503 /* Restore the audio buffer list structure from backup, in case
2504 * AudioUnitRender clobbered it. (It modifies mDataByteSize and may even
2505 * give us a different mData buffer to avoid a copy.) */
2506 memcpy(wwi->bufferList, wwi->bufferListCopy, AUDIOBUFFERLISTSIZE(wwi->bufferList->mNumberBuffers));
2508 if (needNotify) wodSendNotifyInputCompletionsMessage(wwi);
2509 return err;
2512 #else
2514 /**************************************************************************
2515 * widMessage (WINECOREAUDIO.6)
2517 DWORD WINAPI CoreAudio_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2518 DWORD dwParam1, DWORD dwParam2)
2520 FIXME("(%u, %04X, %08X, %08X, %08X): CoreAudio support not compiled into wine\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2521 return MMSYSERR_NOTENABLED;
2524 /**************************************************************************
2525 * wodMessage (WINECOREAUDIO.7)
2527 DWORD WINAPI CoreAudio_wodMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2528 DWORD dwParam1, DWORD dwParam2)
2530 FIXME("(%u, %04X, %08X, %08X, %08X): CoreAudio support not compiled into wine\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2531 return MMSYSERR_NOTENABLED;
2534 #endif