po: Update Korean resource.
[wine.git] / dlls / winecoreaudio.drv / audio.c
blobded830d4ad5b8f977748b31023347e6b901d02ae
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 #ifdef HAVE_COREAUDIO_COREAUDIO_H
38 #include <CoreAudio/CoreAudio.h>
39 #include <CoreFoundation/CoreFoundation.h>
40 #include <libkern/OSAtomic.h>
41 #endif
43 #include "windef.h"
44 #include "winbase.h"
45 #include "winnls.h"
46 #include "wingdi.h"
47 #include "winerror.h"
48 #include "mmddk.h"
49 #include "mmreg.h"
50 #include "dsound.h"
51 #include "dsdriver.h"
52 #include "ks.h"
53 #include "ksguid.h"
54 #include "ksmedia.h"
55 #include "coreaudio.h"
56 #include "wine/unicode.h"
57 #include "wine/library.h"
58 #include "wine/debug.h"
59 #include "wine/list.h"
61 WINE_DEFAULT_DEBUG_CHANNEL(wave);
63 #if defined(HAVE_COREAUDIO_COREAUDIO_H) && defined(HAVE_AUDIOUNIT_AUDIOUNIT_H)
65 WINE_DECLARE_DEBUG_CHANNEL(coreaudio);
68 Due to AudioUnit headers conflict define some needed types.
71 typedef void *AudioUnit;
73 /* From AudioUnit/AUComponents.h */
74 enum
76 kAudioUnitRenderAction_OutputIsSilence = (1 << 4),
77 /* provides hint on return from Render(): if set the buffer contains all zeroes */
79 typedef UInt32 AudioUnitRenderActionFlags;
81 typedef long ComponentResult;
82 extern ComponentResult
83 AudioUnitRender( AudioUnit ci,
84 AudioUnitRenderActionFlags * ioActionFlags,
85 const AudioTimeStamp * inTimeStamp,
86 UInt32 inOutputBusNumber,
87 UInt32 inNumberFrames,
88 AudioBufferList * ioData) AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER;
90 /* only allow 10 output devices through this driver, this ought to be adequate */
91 #define MAX_WAVEOUTDRV (1)
92 #define MAX_WAVEINDRV (1)
94 /* state diagram for waveOut writing:
96 * +---------+-------------+---------------+---------------------------------+
97 * | state | function | event | new state |
98 * +---------+-------------+---------------+---------------------------------+
99 * | | open() | | PLAYING |
100 * | PAUSED | write() | | PAUSED |
101 * | PLAYING | write() | HEADER | PLAYING |
102 * | (other) | write() | <error> | |
103 * | (any) | pause() | PAUSING | PAUSED |
104 * | PAUSED | restart() | RESTARTING | PLAYING |
105 * | (any) | reset() | RESETTING | PLAYING |
106 * | (any) | close() | CLOSING | <deallocated> |
107 * +---------+-------------+---------------+---------------------------------+
110 /* states of the playing device */
111 #define WINE_WS_PLAYING 0 /* for waveOut: lpPlayPtr == NULL -> stopped */
112 #define WINE_WS_PAUSED 1
113 #define WINE_WS_STOPPED 2 /* Not used for waveOut */
114 #define WINE_WS_CLOSED 3 /* Not used for waveOut */
115 #define WINE_WS_OPENING 4
116 #define WINE_WS_CLOSING 5
118 typedef struct tagCoreAudio_Device {
119 char dev_name[32];
120 char mixer_name[32];
121 unsigned open_count;
122 char* interface_name;
124 WAVEOUTCAPSW out_caps;
125 WAVEINCAPSW in_caps;
126 DWORD in_caps_support;
127 int sample_rate;
128 int stereo;
129 int format;
130 unsigned audio_fragment;
131 BOOL full_duplex;
132 BOOL bTriggerSupport;
133 BOOL bOutputEnabled;
134 BOOL bInputEnabled;
135 DSDRIVERDESC ds_desc;
136 DSDRIVERCAPS ds_caps;
137 DSCDRIVERCAPS dsc_caps;
138 GUID ds_guid;
139 GUID dsc_guid;
141 AudioDeviceID outputDeviceID;
142 AudioDeviceID inputDeviceID;
143 AudioStreamBasicDescription streamDescription;
144 } CoreAudio_Device;
146 /* for now use the default device */
147 static CoreAudio_Device CoreAudio_DefaultDevice;
149 typedef struct {
150 struct list entry;
152 volatile int state; /* one of the WINE_WS_ manifest constants */
153 WAVEOPENDESC waveDesc;
154 WORD wFlags;
155 PCMWAVEFORMAT format;
156 DWORD woID;
157 AudioUnit audioUnit;
158 AudioStreamBasicDescription streamDescription;
160 LPWAVEHDR lpQueuePtr; /* start of queued WAVEHDRs (waiting to be notified) */
161 LPWAVEHDR lpPlayPtr; /* start of not yet fully played buffers */
162 DWORD dwPartialOffset; /* Offset of not yet written bytes in lpPlayPtr */
164 LPWAVEHDR lpLoopPtr; /* pointer of first buffer in loop, if any */
165 DWORD dwLoops; /* private copy of loop counter */
167 DWORD dwPlayedTotal; /* number of bytes actually played since opening */
169 OSSpinLock lock; /* synchronization stuff */
170 } WINE_WAVEOUT_INSTANCE;
172 typedef struct {
173 CoreAudio_Device *cadev;
174 WAVEOUTCAPSW caps;
175 char interface_name[32];
176 DWORD device_volume;
178 BOOL trace_on;
179 BOOL warn_on;
180 BOOL err_on;
182 struct list instances;
183 OSSpinLock lock; /* guards the instances list */
184 } WINE_WAVEOUT;
186 typedef struct {
187 /* This device's device number */
188 DWORD wiID;
190 /* Access to the following fields is synchronized across threads. */
191 volatile int state;
192 LPWAVEHDR lpQueuePtr;
193 DWORD dwTotalRecorded;
195 /* Synchronization mechanism to protect above fields */
196 OSSpinLock lock;
198 /* Capabilities description */
199 WAVEINCAPSW caps;
200 char interface_name[32];
202 /* Record the arguments used when opening the device. */
203 WAVEOPENDESC waveDesc;
204 WORD wFlags;
205 PCMWAVEFORMAT format;
207 AudioUnit audioUnit;
208 AudioBufferList*bufferList;
209 AudioBufferList*bufferListCopy;
211 /* Record state of debug channels at open. Used to control fprintf's since
212 * we can't use Wine debug channel calls in non-Wine AudioUnit threads. */
213 BOOL trace_on;
214 BOOL warn_on;
215 BOOL err_on;
217 /* These fields aren't used. */
218 #if 0
219 CoreAudio_Device *cadev;
221 AudioStreamBasicDescription streamDescription;
222 #endif
223 } WINE_WAVEIN;
225 static WINE_WAVEOUT WOutDev [MAX_WAVEOUTDRV];
226 static WINE_WAVEIN WInDev [MAX_WAVEINDRV];
228 static HANDLE hThread = NULL; /* Track the thread we create so we can clean it up later */
229 static CFMessagePortRef Port_SendToMessageThread;
231 static void wodHelper_PlayPtrNext(WINE_WAVEOUT_INSTANCE* wwo);
232 static void wodHelper_NotifyDoneForList(WINE_WAVEOUT_INSTANCE* wwo, LPWAVEHDR lpWaveHdr);
233 static void wodHelper_NotifyCompletions(WINE_WAVEOUT_INSTANCE* wwo, BOOL force);
234 static void widHelper_NotifyCompletions(WINE_WAVEIN* wwi);
236 extern int AudioUnit_CreateDefaultAudioUnit(void *wwo, AudioUnit *au);
237 extern int AudioUnit_CloseAudioUnit(AudioUnit au);
238 extern int AudioUnit_InitializeWithStreamDescription(AudioUnit au, AudioStreamBasicDescription *streamFormat);
240 extern OSStatus AudioOutputUnitStart(AudioUnit au);
241 extern OSStatus AudioOutputUnitStop(AudioUnit au);
242 extern OSStatus AudioUnitUninitialize(AudioUnit au);
244 extern int AudioUnit_SetVolume(AudioUnit au, float left, float right);
245 extern int AudioUnit_GetVolume(AudioUnit au, float *left, float *right);
247 extern int AudioUnit_GetInputDeviceSampleRate(void);
249 extern int AudioUnit_CreateInputUnit(void* wwi, AudioUnit* out_au,
250 WORD nChannels, DWORD nSamplesPerSec, WORD wBitsPerSample,
251 UInt32* outFrameCount);
253 OSStatus CoreAudio_woAudioUnitIOProc(void *inRefCon,
254 AudioUnitRenderActionFlags *ioActionFlags,
255 const AudioTimeStamp *inTimeStamp,
256 UInt32 inBusNumber,
257 UInt32 inNumberFrames,
258 AudioBufferList *ioData);
259 OSStatus CoreAudio_wiAudioUnitIOProc(void *inRefCon,
260 AudioUnitRenderActionFlags *ioActionFlags,
261 const AudioTimeStamp *inTimeStamp,
262 UInt32 inBusNumber,
263 UInt32 inNumberFrames,
264 AudioBufferList *ioData);
266 /* These strings used only for tracing */
268 static const char * getMessage(UINT msg)
270 #define MSG_TO_STR(x) case x: return #x
271 switch(msg) {
272 MSG_TO_STR(DRVM_INIT);
273 MSG_TO_STR(DRVM_EXIT);
274 MSG_TO_STR(DRVM_ENABLE);
275 MSG_TO_STR(DRVM_DISABLE);
276 MSG_TO_STR(WIDM_OPEN);
277 MSG_TO_STR(WIDM_CLOSE);
278 MSG_TO_STR(WIDM_ADDBUFFER);
279 MSG_TO_STR(WIDM_PREPARE);
280 MSG_TO_STR(WIDM_UNPREPARE);
281 MSG_TO_STR(WIDM_GETDEVCAPS);
282 MSG_TO_STR(WIDM_GETNUMDEVS);
283 MSG_TO_STR(WIDM_GETPOS);
284 MSG_TO_STR(WIDM_RESET);
285 MSG_TO_STR(WIDM_START);
286 MSG_TO_STR(WIDM_STOP);
287 MSG_TO_STR(WODM_OPEN);
288 MSG_TO_STR(WODM_CLOSE);
289 MSG_TO_STR(WODM_WRITE);
290 MSG_TO_STR(WODM_PAUSE);
291 MSG_TO_STR(WODM_GETPOS);
292 MSG_TO_STR(WODM_BREAKLOOP);
293 MSG_TO_STR(WODM_PREPARE);
294 MSG_TO_STR(WODM_UNPREPARE);
295 MSG_TO_STR(WODM_GETDEVCAPS);
296 MSG_TO_STR(WODM_GETNUMDEVS);
297 MSG_TO_STR(WODM_GETPITCH);
298 MSG_TO_STR(WODM_SETPITCH);
299 MSG_TO_STR(WODM_GETPLAYBACKRATE);
300 MSG_TO_STR(WODM_SETPLAYBACKRATE);
301 MSG_TO_STR(WODM_GETVOLUME);
302 MSG_TO_STR(WODM_SETVOLUME);
303 MSG_TO_STR(WODM_RESTART);
304 MSG_TO_STR(WODM_RESET);
305 MSG_TO_STR(DRV_QUERYDEVICEINTERFACESIZE);
306 MSG_TO_STR(DRV_QUERYDEVICEINTERFACE);
307 MSG_TO_STR(DRV_QUERYDSOUNDIFACE);
308 MSG_TO_STR(DRV_QUERYDSOUNDDESC);
310 #undef MSG_TO_STR
311 return wine_dbg_sprintf("UNKNOWN(0x%04x)", msg);
314 #define kStopLoopMessage 0
315 #define kWaveOutNotifyCompletionsMessage 1
316 #define kWaveInNotifyCompletionsMessage 2
318 /* Mach Message Handling */
319 static CFDataRef wodMessageHandler(CFMessagePortRef port_ReceiveInMessageThread, SInt32 msgid, CFDataRef data, void *info)
321 UInt32 *buffer = NULL;
323 switch (msgid)
325 case kWaveOutNotifyCompletionsMessage:
326 wodHelper_NotifyCompletions(*(WINE_WAVEOUT_INSTANCE**)CFDataGetBytePtr(data), FALSE);
327 break;
328 case kWaveInNotifyCompletionsMessage:
329 buffer = (UInt32 *) CFDataGetBytePtr(data);
330 widHelper_NotifyCompletions(&WInDev[buffer[0]]);
331 break;
332 default:
333 CFRunLoopStop(CFRunLoopGetCurrent());
334 break;
337 return NULL;
340 static DWORD WINAPI messageThread(LPVOID p)
342 CFMessagePortRef port_ReceiveInMessageThread = (CFMessagePortRef) p;
343 CFRunLoopSourceRef source;
345 source = CFMessagePortCreateRunLoopSource(kCFAllocatorDefault, port_ReceiveInMessageThread, 0);
346 CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
348 CFRunLoopRun();
350 CFRunLoopSourceInvalidate(source);
351 CFRelease(source);
352 CFRelease(port_ReceiveInMessageThread);
354 return 0;
357 /**************************************************************************
358 * wodSendNotifyCompletionsMessage [internal]
359 * Call from AudioUnit IO thread can't use Wine debug channels.
361 static void wodSendNotifyCompletionsMessage(WINE_WAVEOUT_INSTANCE* wwo)
363 CFDataRef data;
365 if (!Port_SendToMessageThread)
366 return;
368 data = CFDataCreate(kCFAllocatorDefault, (UInt8 *)&wwo, sizeof(wwo));
369 if (!data)
370 return;
372 CFMessagePortSendRequest(Port_SendToMessageThread, kWaveOutNotifyCompletionsMessage, data, 0.0, 0.0, NULL, NULL);
373 CFRelease(data);
376 /**************************************************************************
377 * wodSendNotifyInputCompletionsMessage [internal]
378 * Call from AudioUnit IO thread can't use Wine debug channels.
380 static void wodSendNotifyInputCompletionsMessage(WINE_WAVEIN* wwi)
382 CFDataRef data;
383 UInt32 buffer;
385 if (!Port_SendToMessageThread)
386 return;
388 buffer = (UInt32) wwi->wiID;
390 data = CFDataCreate(kCFAllocatorDefault, (UInt8 *)&buffer, sizeof(buffer));
391 if (!data)
392 return;
394 CFMessagePortSendRequest(Port_SendToMessageThread, kWaveInNotifyCompletionsMessage, data, 0.0, 0.0, NULL, NULL);
395 CFRelease(data);
398 static DWORD bytes_to_mmtime(LPMMTIME lpTime, DWORD position,
399 PCMWAVEFORMAT* format)
401 TRACE("wType=%04X wBitsPerSample=%u nSamplesPerSec=%u nChannels=%u nAvgBytesPerSec=%u\n",
402 lpTime->wType, format->wBitsPerSample, format->wf.nSamplesPerSec,
403 format->wf.nChannels, format->wf.nAvgBytesPerSec);
404 TRACE("Position in bytes=%u\n", position);
406 switch (lpTime->wType) {
407 case TIME_SAMPLES:
408 lpTime->u.sample = position / (format->wBitsPerSample / 8 * format->wf.nChannels);
409 TRACE("TIME_SAMPLES=%u\n", lpTime->u.sample);
410 break;
411 case TIME_MS:
412 lpTime->u.ms = 1000.0 * position / (format->wBitsPerSample / 8 * format->wf.nChannels * format->wf.nSamplesPerSec);
413 TRACE("TIME_MS=%u\n", lpTime->u.ms);
414 break;
415 case TIME_SMPTE:
416 lpTime->u.smpte.fps = 30;
417 position = position / (format->wBitsPerSample / 8 * format->wf.nChannels);
418 position += (format->wf.nSamplesPerSec / lpTime->u.smpte.fps) - 1; /* round up */
419 lpTime->u.smpte.sec = position / format->wf.nSamplesPerSec;
420 position -= lpTime->u.smpte.sec * format->wf.nSamplesPerSec;
421 lpTime->u.smpte.min = lpTime->u.smpte.sec / 60;
422 lpTime->u.smpte.sec -= 60 * lpTime->u.smpte.min;
423 lpTime->u.smpte.hour = lpTime->u.smpte.min / 60;
424 lpTime->u.smpte.min -= 60 * lpTime->u.smpte.hour;
425 lpTime->u.smpte.fps = 30;
426 lpTime->u.smpte.frame = position * lpTime->u.smpte.fps / format->wf.nSamplesPerSec;
427 TRACE("TIME_SMPTE=%02u:%02u:%02u:%02u\n",
428 lpTime->u.smpte.hour, lpTime->u.smpte.min,
429 lpTime->u.smpte.sec, lpTime->u.smpte.frame);
430 break;
431 default:
432 WARN("Format %d not supported, using TIME_BYTES !\n", lpTime->wType);
433 lpTime->wType = TIME_BYTES;
434 /* fall through */
435 case TIME_BYTES:
436 lpTime->u.cb = position;
437 TRACE("TIME_BYTES=%u\n", lpTime->u.cb);
438 break;
440 return MMSYSERR_NOERROR;
443 static BOOL supportedFormat(LPWAVEFORMATEX wf)
445 if (wf->nSamplesPerSec < DSBFREQUENCY_MIN || wf->nSamplesPerSec > DSBFREQUENCY_MAX)
446 return FALSE;
448 if (wf->wFormatTag == WAVE_FORMAT_PCM) {
449 if (wf->nChannels >= 1 && wf->nChannels <= 2) {
450 if (wf->wBitsPerSample==8||wf->wBitsPerSample==16)
451 return TRUE;
453 } else if (wf->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
454 WAVEFORMATEXTENSIBLE * wfex = (WAVEFORMATEXTENSIBLE *)wf;
456 if (wf->cbSize == 22 && IsEqualGUID(&wfex->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM)) {
457 if (wf->nChannels >=1 && wf->nChannels <= 8) {
458 if (wf->wBitsPerSample==wfex->Samples.wValidBitsPerSample) {
459 if (wf->wBitsPerSample==8||wf->wBitsPerSample==16)
460 return TRUE;
461 } else
462 WARN("wBitsPerSample != wValidBitsPerSample not supported yet\n");
464 } else
465 WARN("only KSDATAFORMAT_SUBTYPE_PCM supported\n");
466 } else
467 WARN("only WAVE_FORMAT_PCM and WAVE_FORMAT_EXTENSIBLE supported\n");
469 return FALSE;
472 void copyFormat(LPWAVEFORMATEX wf1, LPPCMWAVEFORMAT wf2)
474 memcpy(wf2, wf1, sizeof(PCMWAVEFORMAT));
475 /* Downgrade WAVE_FORMAT_EXTENSIBLE KSDATAFORMAT_SUBTYPE_PCM
476 * to smaller yet compatible WAVE_FORMAT_PCM structure */
477 if (wf2->wf.wFormatTag == WAVE_FORMAT_EXTENSIBLE)
478 wf2->wf.wFormatTag = WAVE_FORMAT_PCM;
481 /**************************************************************************
482 * CoreAudio_GetDevCaps [internal]
484 BOOL CoreAudio_GetDevCaps (void)
486 OSStatus status;
487 UInt32 propertySize;
488 AudioDeviceID devId = CoreAudio_DefaultDevice.outputDeviceID;
489 AudioObjectPropertyAddress propertyAddress;
491 CFStringRef name;
492 CFRange range;
494 propertySize = sizeof(name);
495 propertyAddress.mSelector = kAudioObjectPropertyName;
496 propertyAddress.mScope = kAudioDevicePropertyScopeOutput;
497 propertyAddress.mElement = kAudioObjectPropertyElementMaster;
498 status = AudioObjectGetPropertyData(devId, &propertyAddress, 0, NULL, &propertySize, &name);
499 if (status) {
500 ERR("AudioObjectGetPropertyData for kAudioObjectPropertyName return %s\n", wine_dbgstr_fourcc(status));
501 return FALSE;
504 CFStringGetCString(name, CoreAudio_DefaultDevice.ds_desc.szDesc,
505 sizeof(CoreAudio_DefaultDevice.ds_desc.szDesc),
506 kCFStringEncodingUTF8);
507 strcpy(CoreAudio_DefaultDevice.ds_desc.szDrvname, "winecoreaudio.drv");
508 range = CFRangeMake(0, min(sizeof(CoreAudio_DefaultDevice.out_caps.szPname) / sizeof(WCHAR) - 1, CFStringGetLength(name)));
509 CFStringGetCharacters(name, range, CoreAudio_DefaultDevice.out_caps.szPname);
510 CoreAudio_DefaultDevice.out_caps.szPname[range.length] = 0;
511 CFStringGetCString(name, CoreAudio_DefaultDevice.dev_name, 32, kCFStringEncodingUTF8);
512 CFRelease(name);
514 propertySize = sizeof(CoreAudio_DefaultDevice.streamDescription);
515 /* FIXME: kAudioDevicePropertyStreamFormat is deprecated. We're
516 * "supposed" to get an AudioStream object from the AudioDevice,
517 * then query it for the format with kAudioStreamPropertyVirtualFormat.
518 * Apple says that this is for our own good, because this property
519 * "has been shown to lead to programming mistakes by clients when
520 * working with devices with multiple streams." Only one problem:
521 * which stream? For now, just query the device.
523 propertyAddress.mSelector = kAudioDevicePropertyStreamFormat;
524 status = AudioObjectGetPropertyData(devId, &propertyAddress, 0, NULL, &propertySize, &CoreAudio_DefaultDevice.streamDescription);
525 if (status != noErr) {
526 ERR("AudioObjectGetPropertyData for kAudioDevicePropertyStreamFormat return %s\n", wine_dbgstr_fourcc(status));
527 return FALSE;
530 TRACE("Device Stream Description mSampleRate : %f\n mFormatID : %s\n"
531 "mFormatFlags : %lX\n mBytesPerPacket : %lu\n mFramesPerPacket : %lu\n"
532 "mBytesPerFrame : %lu\n mChannelsPerFrame : %lu\n mBitsPerChannel : %lu\n",
533 CoreAudio_DefaultDevice.streamDescription.mSampleRate,
534 wine_dbgstr_fourcc(CoreAudio_DefaultDevice.streamDescription.mFormatID),
535 CoreAudio_DefaultDevice.streamDescription.mFormatFlags,
536 CoreAudio_DefaultDevice.streamDescription.mBytesPerPacket,
537 CoreAudio_DefaultDevice.streamDescription.mFramesPerPacket,
538 CoreAudio_DefaultDevice.streamDescription.mBytesPerFrame,
539 CoreAudio_DefaultDevice.streamDescription.mChannelsPerFrame,
540 CoreAudio_DefaultDevice.streamDescription.mBitsPerChannel);
542 CoreAudio_DefaultDevice.out_caps.wMid = 0xcafe;
543 CoreAudio_DefaultDevice.out_caps.wPid = 0x0001;
545 CoreAudio_DefaultDevice.out_caps.vDriverVersion = 0x0001;
546 CoreAudio_DefaultDevice.out_caps.dwFormats = 0x00000000;
547 CoreAudio_DefaultDevice.out_caps.wReserved1 = 0;
548 CoreAudio_DefaultDevice.out_caps.dwSupport = WAVECAPS_VOLUME;
549 CoreAudio_DefaultDevice.out_caps.dwSupport |= WAVECAPS_LRVOLUME;
551 CoreAudio_DefaultDevice.out_caps.wChannels = 2;
552 CoreAudio_DefaultDevice.out_caps.dwFormats|= WAVE_FORMAT_4S16;
554 TRACE_(coreaudio)("out dwFormats = %08x, dwSupport = %08x\n",
555 CoreAudio_DefaultDevice.out_caps.dwFormats, CoreAudio_DefaultDevice.out_caps.dwSupport);
557 return TRUE;
560 /******************************************************************
561 * CoreAudio_WaveInit
563 * Initialize CoreAudio_DefaultDevice
565 LONG CoreAudio_WaveInit(void)
567 OSStatus status;
568 UInt32 propertySize;
569 AudioObjectPropertyAddress propertyAddress;
570 int i;
571 CFStringRef messageThreadPortName;
572 CFMessagePortRef port_ReceiveInMessageThread;
573 int inputSampleRate;
575 TRACE("()\n");
577 /* number of sound cards */
578 propertyAddress.mSelector = kAudioHardwarePropertyDevices;
579 propertyAddress.mScope = kAudioObjectPropertyScopeGlobal;
580 propertyAddress.mElement = kAudioObjectPropertyElementMaster;
581 AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &propertyAddress, 0, NULL, &propertySize);
582 propertySize /= sizeof(AudioDeviceID);
583 TRACE("sound cards : %lu\n", propertySize);
585 /* Get the output device */
586 propertySize = sizeof(CoreAudio_DefaultDevice.outputDeviceID);
587 propertyAddress.mSelector = kAudioHardwarePropertyDefaultOutputDevice;
588 status = AudioObjectGetPropertyData(kAudioObjectSystemObject, &propertyAddress, 0, NULL, &propertySize, &CoreAudio_DefaultDevice.outputDeviceID);
589 if (status) {
590 ERR("AudioObjectGetPropertyData return %s for kAudioHardwarePropertyDefaultOutputDevice\n", wine_dbgstr_fourcc(status));
591 return DRV_FAILURE;
593 if (CoreAudio_DefaultDevice.outputDeviceID == kAudioDeviceUnknown) {
594 ERR("AudioObjectGetPropertyData: CoreAudio_DefaultDevice.outputDeviceID == kAudioDeviceUnknown\n");
595 return DRV_FAILURE;
598 if ( ! CoreAudio_GetDevCaps() )
599 return DRV_FAILURE;
601 CoreAudio_DefaultDevice.interface_name=HeapAlloc(GetProcessHeap(),0,strlen(CoreAudio_DefaultDevice.dev_name)+1);
602 strcpy(CoreAudio_DefaultDevice.interface_name, CoreAudio_DefaultDevice.dev_name);
604 for (i = 0; i < MAX_WAVEOUTDRV; ++i)
606 static const WCHAR wszWaveOutFormat[] =
607 {'C','o','r','e','A','u','d','i','o',' ','W','a','v','e','O','u','t',' ','%','d',0};
609 list_init(&WOutDev[i].instances);
610 WOutDev[i].cadev = &CoreAudio_DefaultDevice;
612 memset(&WOutDev[i].caps, 0, sizeof(WOutDev[i].caps));
614 WOutDev[i].caps.wMid = 0xcafe; /* Manufac ID */
615 WOutDev[i].caps.wPid = 0x0001; /* Product ID */
616 snprintfW(WOutDev[i].caps.szPname, sizeof(WOutDev[i].caps.szPname)/sizeof(WCHAR), wszWaveOutFormat, i);
617 snprintf(WOutDev[i].interface_name, sizeof(WOutDev[i].interface_name), "winecoreaudio: %d", i);
619 WOutDev[i].caps.vDriverVersion = 0x0001;
620 WOutDev[i].caps.dwFormats = 0x00000000;
621 WOutDev[i].caps.dwSupport = WAVECAPS_VOLUME;
623 WOutDev[i].caps.wChannels = 2;
624 /* WOutDev[i].caps.dwSupport |= WAVECAPS_LRVOLUME; */ /* FIXME */
626 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96M08;
627 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96S08;
628 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96M16;
629 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96S16;
630 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48M08;
631 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48S08;
632 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48M16;
633 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48S16;
634 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4M08;
635 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4S08;
636 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4S16;
637 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4M16;
638 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2M08;
639 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2S08;
640 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2M16;
641 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2S16;
642 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1M08;
643 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1S08;
644 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1M16;
645 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1S16;
647 WOutDev[i].device_volume = 0xffffffff;
649 WOutDev[i].lock = 0; /* initialize the mutex */
652 /* FIXME: implement sample rate conversion on input */
653 inputSampleRate = AudioUnit_GetInputDeviceSampleRate();
655 for (i = 0; i < MAX_WAVEINDRV; ++i)
657 static const WCHAR wszWaveInFormat[] =
658 {'C','o','r','e','A','u','d','i','o',' ','W','a','v','e','I','n',' ','%','d',0};
660 memset(&WInDev[i], 0, sizeof(WInDev[i]));
661 WInDev[i].wiID = i;
663 /* Establish preconditions for widOpen */
664 WInDev[i].state = WINE_WS_CLOSED;
665 WInDev[i].lock = 0; /* initialize the mutex */
667 /* Fill in capabilities. widGetDevCaps can be called at any time. */
668 WInDev[i].caps.wMid = 0xcafe; /* Manufac ID */
669 WInDev[i].caps.wPid = 0x0001; /* Product ID */
670 WInDev[i].caps.vDriverVersion = 0x0001;
672 snprintfW(WInDev[i].caps.szPname, sizeof(WInDev[i].caps.szPname)/sizeof(WCHAR), wszWaveInFormat, i);
673 snprintf(WInDev[i].interface_name, sizeof(WInDev[i].interface_name), "winecoreaudio in: %d", i);
675 if (inputSampleRate == 96000)
677 WInDev[i].caps.dwFormats |= WAVE_FORMAT_96M08;
678 WInDev[i].caps.dwFormats |= WAVE_FORMAT_96S08;
679 WInDev[i].caps.dwFormats |= WAVE_FORMAT_96M16;
680 WInDev[i].caps.dwFormats |= WAVE_FORMAT_96S16;
682 if (inputSampleRate == 48000)
684 WInDev[i].caps.dwFormats |= WAVE_FORMAT_48M08;
685 WInDev[i].caps.dwFormats |= WAVE_FORMAT_48S08;
686 WInDev[i].caps.dwFormats |= WAVE_FORMAT_48M16;
687 WInDev[i].caps.dwFormats |= WAVE_FORMAT_48S16;
689 if (inputSampleRate == 44100)
691 WInDev[i].caps.dwFormats |= WAVE_FORMAT_4M08;
692 WInDev[i].caps.dwFormats |= WAVE_FORMAT_4S08;
693 WInDev[i].caps.dwFormats |= WAVE_FORMAT_4M16;
694 WInDev[i].caps.dwFormats |= WAVE_FORMAT_4S16;
696 if (inputSampleRate == 22050)
698 WInDev[i].caps.dwFormats |= WAVE_FORMAT_2M08;
699 WInDev[i].caps.dwFormats |= WAVE_FORMAT_2S08;
700 WInDev[i].caps.dwFormats |= WAVE_FORMAT_2M16;
701 WInDev[i].caps.dwFormats |= WAVE_FORMAT_2S16;
703 if (inputSampleRate == 11025)
705 WInDev[i].caps.dwFormats |= WAVE_FORMAT_1M08;
706 WInDev[i].caps.dwFormats |= WAVE_FORMAT_1S08;
707 WInDev[i].caps.dwFormats |= WAVE_FORMAT_1M16;
708 WInDev[i].caps.dwFormats |= WAVE_FORMAT_1S16;
711 WInDev[i].caps.wChannels = 2;
714 /* create mach messages handler */
715 srandomdev();
716 messageThreadPortName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL,
717 CFSTR("WaveMessagePort.%d.%lu"), getpid(), (unsigned long)random());
718 if (!messageThreadPortName)
720 ERR("Can't create message thread port name\n");
721 return DRV_FAILURE;
724 port_ReceiveInMessageThread = CFMessagePortCreateLocal(kCFAllocatorDefault, messageThreadPortName,
725 &wodMessageHandler, NULL, NULL);
726 if (!port_ReceiveInMessageThread)
728 ERR("Can't create message thread local port\n");
729 CFRelease(messageThreadPortName);
730 return DRV_FAILURE;
733 Port_SendToMessageThread = CFMessagePortCreateRemote(kCFAllocatorDefault, messageThreadPortName);
734 CFRelease(messageThreadPortName);
735 if (!Port_SendToMessageThread)
737 ERR("Can't create port for sending to message thread\n");
738 CFRelease(port_ReceiveInMessageThread);
739 return DRV_FAILURE;
742 /* Cannot WAIT for any events because we are called from the loader (which has a lock on loading stuff) */
743 /* We might want to wait for this thread to be created -- but we cannot -- not here at least */
744 /* Instead track the thread so we can clean it up later */
745 if ( hThread )
747 ERR("Message thread already started -- expect problems\n");
749 hThread = CreateThread(NULL, 0, messageThread, (LPVOID)port_ReceiveInMessageThread, 0, NULL);
750 if ( !hThread )
752 ERR("Can't create message thread\n");
753 CFRelease(port_ReceiveInMessageThread);
754 CFRelease(Port_SendToMessageThread);
755 Port_SendToMessageThread = NULL;
756 return DRV_FAILURE;
759 /* The message thread is responsible for releasing port_ReceiveInMessageThread. */
761 return DRV_SUCCESS;
764 void CoreAudio_WaveRelease(void)
766 /* Stop CFRunLoop in messageThread */
767 TRACE("()\n");
769 if (!Port_SendToMessageThread)
770 return;
772 CFMessagePortSendRequest(Port_SendToMessageThread, kStopLoopMessage, NULL, 0.0, 0.0, NULL, NULL);
773 CFRelease(Port_SendToMessageThread);
774 Port_SendToMessageThread = NULL;
776 /* Wait for the thread to finish and clean it up */
777 /* This rids us of any quick start/shutdown driver crashes */
778 WaitForSingleObject(hThread, INFINITE);
779 CloseHandle(hThread);
780 hThread = NULL;
783 /*======================================================================*
784 * Low level WAVE OUT implementation *
785 *======================================================================*/
787 /**************************************************************************
788 * wodNotifyClient [internal]
790 static DWORD wodNotifyClient(WINE_WAVEOUT_INSTANCE* wwo, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
792 TRACE_(coreaudio)("wMsg = 0x%04x dwParm1 = %04x dwParam2 = %04x\n", wMsg, dwParam1, dwParam2);
794 switch (wMsg) {
795 case WOM_OPEN:
796 case WOM_CLOSE:
797 case WOM_DONE:
798 if (wwo->wFlags != DCB_NULL &&
799 !DriverCallback(wwo->waveDesc.dwCallback, wwo->wFlags,
800 (HDRVR)wwo->waveDesc.hWave, wMsg, wwo->waveDesc.dwInstance,
801 dwParam1, dwParam2))
803 ERR("can't notify client !\n");
804 return MMSYSERR_ERROR;
806 break;
807 default:
808 ERR("Unknown callback message %u\n", wMsg);
809 return MMSYSERR_INVALPARAM;
811 return MMSYSERR_NOERROR;
815 /**************************************************************************
816 * wodGetDevCaps [internal]
818 static DWORD wodGetDevCaps(WORD wDevID, LPWAVEOUTCAPSW lpCaps, DWORD dwSize)
820 TRACE("(%u, %p, %u);\n", wDevID, lpCaps, dwSize);
822 if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
824 if (wDevID >= MAX_WAVEOUTDRV)
826 TRACE("MAX_WAVOUTDRV reached !\n");
827 return MMSYSERR_BADDEVICEID;
830 TRACE("dwSupport=(0x%x), dwFormats=(0x%x)\n", WOutDev[wDevID].caps.dwSupport, WOutDev[wDevID].caps.dwFormats);
831 memcpy(lpCaps, &WOutDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
832 return MMSYSERR_NOERROR;
835 /**************************************************************************
836 * wodOpen [internal]
838 static DWORD wodOpen(WORD wDevID, WINE_WAVEOUT_INSTANCE** pInstance, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
840 WINE_WAVEOUT_INSTANCE* wwo;
841 DWORD ret;
842 AudioStreamBasicDescription streamFormat;
843 AudioUnit audioUnit = NULL;
844 BOOL auInited = FALSE;
846 TRACE("(%u, %p, %p, %08x);\n", wDevID, pInstance, lpDesc, dwFlags);
847 if (lpDesc == NULL)
849 WARN("Invalid Parameter !\n");
850 return MMSYSERR_INVALPARAM;
852 if (wDevID >= MAX_WAVEOUTDRV) {
853 TRACE("MAX_WAVOUTDRV reached !\n");
854 return MMSYSERR_BADDEVICEID;
857 TRACE("Format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
858 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
859 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
861 if (!supportedFormat(lpDesc->lpFormat))
863 WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
864 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
865 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
866 return WAVERR_BADFORMAT;
869 if (dwFlags & WAVE_FORMAT_QUERY)
871 TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
872 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
873 lpDesc->lpFormat->nSamplesPerSec);
874 return MMSYSERR_NOERROR;
877 /* nBlockAlign and nAvgBytesPerSec are output variables for dsound */
878 if (lpDesc->lpFormat->nBlockAlign != lpDesc->lpFormat->nChannels*lpDesc->lpFormat->wBitsPerSample/8) {
879 lpDesc->lpFormat->nBlockAlign = lpDesc->lpFormat->nChannels*lpDesc->lpFormat->wBitsPerSample/8;
880 WARN("Fixing nBlockAlign\n");
882 if (lpDesc->lpFormat->nAvgBytesPerSec!= lpDesc->lpFormat->nSamplesPerSec*lpDesc->lpFormat->nBlockAlign) {
883 lpDesc->lpFormat->nAvgBytesPerSec = lpDesc->lpFormat->nSamplesPerSec*lpDesc->lpFormat->nBlockAlign;
884 WARN("Fixing nAvgBytesPerSec\n");
887 /* We proceed in three phases:
888 * o Allocate the device instance, marking it as opening
889 * o Create, configure, and start the Audio Unit. To avoid deadlock,
890 * this has to be done without holding wwo->lock.
891 * o If that was successful, finish setting up our instance and add it
892 * to the device's list.
893 * Otherwise, clean up and deallocate the instance.
895 wwo = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*wwo));
896 if (!wwo)
897 return MMSYSERR_NOMEM;
899 wwo->woID = wDevID;
900 wwo->state = WINE_WS_OPENING;
902 if (!AudioUnit_CreateDefaultAudioUnit((void *) wwo, &audioUnit))
904 ERR("CoreAudio_CreateDefaultAudioUnit(0x%04x) failed\n", wDevID);
905 ret = MMSYSERR_ERROR;
906 goto error;
909 streamFormat.mFormatID = kAudioFormatLinearPCM;
910 streamFormat.mFormatFlags = kLinearPCMFormatFlagIsPacked;
911 /* FIXME check for 32bits float -> kLinearPCMFormatFlagIsFloat */
912 if (lpDesc->lpFormat->wBitsPerSample != 8)
913 streamFormat.mFormatFlags |= kLinearPCMFormatFlagIsSignedInteger;
914 # ifdef WORDS_BIGENDIAN
915 streamFormat.mFormatFlags |= kLinearPCMFormatFlagIsBigEndian; /* FIXME Wave format is little endian */
916 # endif
918 streamFormat.mSampleRate = lpDesc->lpFormat->nSamplesPerSec;
919 streamFormat.mChannelsPerFrame = lpDesc->lpFormat->nChannels;
920 streamFormat.mFramesPerPacket = 1;
921 streamFormat.mBitsPerChannel = lpDesc->lpFormat->wBitsPerSample;
922 streamFormat.mBytesPerFrame = streamFormat.mBitsPerChannel * streamFormat.mChannelsPerFrame / 8;
923 streamFormat.mBytesPerPacket = streamFormat.mBytesPerFrame * streamFormat.mFramesPerPacket;
925 ret = AudioUnit_InitializeWithStreamDescription(audioUnit, &streamFormat);
926 if (!ret)
928 ret = WAVERR_BADFORMAT; /* FIXME return an error based on the OSStatus */
929 goto error;
931 auInited = TRUE;
933 AudioUnit_SetVolume(audioUnit, LOWORD(WOutDev[wDevID].device_volume) / 65535.0f,
934 HIWORD(WOutDev[wDevID].device_volume) / 65535.0f);
936 /* Our render callback CoreAudio_woAudioUnitIOProc may be called before
937 * AudioOutputUnitStart returns. Core Audio will grab its own internal
938 * lock before calling it and the callback grabs wwo->lock. This would
939 * deadlock if we were holding wwo->lock.
940 * Also, the callback has to safely do nothing in that case, because
941 * wwo hasn't been completely filled out, yet. This is assured by state
942 * being WINE_WS_OPENING. */
943 ret = AudioOutputUnitStart(audioUnit);
944 if (ret)
946 ERR("AudioOutputUnitStart failed: %08x\n", ret);
947 ret = MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
948 goto error;
952 OSSpinLockLock(&wwo->lock);
953 assert(wwo->state == WINE_WS_OPENING);
955 wwo->audioUnit = audioUnit;
956 wwo->streamDescription = streamFormat;
958 wwo->state = WINE_WS_PLAYING;
960 wwo->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
962 wwo->waveDesc = *lpDesc;
963 copyFormat(lpDesc->lpFormat, &wwo->format);
965 WOutDev[wDevID].trace_on = TRACE_ON(wave);
966 WOutDev[wDevID].warn_on = WARN_ON(wave);
967 WOutDev[wDevID].err_on = ERR_ON(wave);
969 OSSpinLockUnlock(&wwo->lock);
971 OSSpinLockLock(&WOutDev[wDevID].lock);
972 list_add_head(&WOutDev[wDevID].instances, &wwo->entry);
973 OSSpinLockUnlock(&WOutDev[wDevID].lock);
975 *pInstance = wwo;
976 TRACE("opened instance %p\n", wwo);
978 ret = wodNotifyClient(wwo, WOM_OPEN, 0L, 0L);
980 return ret;
982 error:
983 if (audioUnit)
985 if (auInited)
986 AudioUnitUninitialize(audioUnit);
987 AudioUnit_CloseAudioUnit(audioUnit);
990 OSSpinLockLock(&wwo->lock);
991 assert(wwo->state == WINE_WS_OPENING);
992 /* OSSpinLockUnlock(&wwo->lock); *//* No need, about to free */
993 HeapFree(GetProcessHeap(), 0, wwo);
995 return ret;
998 /**************************************************************************
999 * wodClose [internal]
1001 static DWORD wodClose(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo)
1003 DWORD ret = MMSYSERR_NOERROR;
1005 TRACE("(%u, %p);\n", wDevID, wwo);
1007 if (wDevID >= MAX_WAVEOUTDRV)
1009 WARN("bad device ID !\n");
1010 return MMSYSERR_BADDEVICEID;
1013 OSSpinLockLock(&wwo->lock);
1014 if (wwo->lpQueuePtr)
1016 OSSpinLockUnlock(&wwo->lock);
1017 WARN("buffers still playing !\n");
1018 ret = WAVERR_STILLPLAYING;
1019 } else
1021 OSStatus err;
1022 AudioUnit audioUnit = wwo->audioUnit;
1024 /* sanity check: this should not happen since the device must have been reset before */
1025 if (wwo->lpQueuePtr || wwo->lpPlayPtr) ERR("out of sync\n");
1027 wwo->state = WINE_WS_CLOSING; /* mark the device as closing */
1028 wwo->audioUnit = NULL;
1030 OSSpinLockUnlock(&wwo->lock);
1032 err = AudioUnitUninitialize(audioUnit);
1033 if (err) {
1034 ERR("AudioUnitUninitialize return %s\n", wine_dbgstr_fourcc(err));
1035 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1038 if ( !AudioUnit_CloseAudioUnit(audioUnit) )
1040 ERR("Can't close AudioUnit\n");
1041 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1044 OSSpinLockLock(&WOutDev[wDevID].lock);
1045 list_remove(&wwo->entry);
1046 OSSpinLockUnlock(&WOutDev[wDevID].lock);
1048 ret = wodNotifyClient(wwo, WOM_CLOSE, 0L, 0L);
1050 HeapFree(GetProcessHeap(), 0, wwo);
1053 return ret;
1056 /**************************************************************************
1057 * wodPrepare [internal]
1059 static DWORD wodPrepare(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1061 TRACE("(%u, %p, %p, %08x);\n", wDevID, wwo, lpWaveHdr, dwSize);
1063 if (wDevID >= MAX_WAVEOUTDRV) {
1064 WARN("bad device ID !\n");
1065 return MMSYSERR_BADDEVICEID;
1068 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1069 return WAVERR_STILLPLAYING;
1071 lpWaveHdr->dwFlags |= WHDR_PREPARED;
1072 lpWaveHdr->dwFlags &= ~WHDR_DONE;
1074 return MMSYSERR_NOERROR;
1077 /**************************************************************************
1078 * wodUnprepare [internal]
1080 static DWORD wodUnprepare(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1082 TRACE("(%u, %p, %p, %08x);\n", wDevID, wwo, lpWaveHdr, dwSize);
1084 if (wDevID >= MAX_WAVEOUTDRV) {
1085 WARN("bad device ID !\n");
1086 return MMSYSERR_BADDEVICEID;
1089 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1090 return WAVERR_STILLPLAYING;
1092 lpWaveHdr->dwFlags &= ~WHDR_PREPARED;
1093 lpWaveHdr->dwFlags |= WHDR_DONE;
1095 return MMSYSERR_NOERROR;
1099 /**************************************************************************
1100 * wodHelper_CheckForLoopBegin [internal]
1102 * Check if the new waveheader is the beginning of a loop, and set up
1103 * state if so.
1104 * This is called with the WAVEOUT_INSTANCE lock held.
1105 * Call from AudioUnit IO thread can't use Wine debug channels.
1107 static void wodHelper_CheckForLoopBegin(WINE_WAVEOUT_INSTANCE* wwo)
1109 LPWAVEHDR lpWaveHdr = wwo->lpPlayPtr;
1111 if (lpWaveHdr->dwFlags & WHDR_BEGINLOOP)
1113 if (wwo->lpLoopPtr)
1115 if (WOutDev[wwo->woID].warn_on)
1116 fprintf(stderr, "warn:winecoreaudio:wodHelper_CheckForLoopBegin Already in a loop. Discarding loop on this header (%p)\n", lpWaveHdr);
1118 else
1120 if (WOutDev[wwo->woID].trace_on)
1121 fprintf(stderr, "trace:winecoreaudio:wodHelper_CheckForLoopBegin Starting loop (%dx) with %p\n", lpWaveHdr->dwLoops, lpWaveHdr);
1123 wwo->lpLoopPtr = lpWaveHdr;
1124 /* Windows does not touch WAVEHDR.dwLoops,
1125 * so we need to make an internal copy */
1126 wwo->dwLoops = lpWaveHdr->dwLoops;
1132 /**************************************************************************
1133 * wodHelper_PlayPtrNext [internal]
1135 * Advance the play pointer to the next waveheader, looping if required.
1136 * This is called with the WAVEOUT_INSTANCE lock held.
1137 * Call from AudioUnit IO thread can't use Wine debug channels.
1139 static void wodHelper_PlayPtrNext(WINE_WAVEOUT_INSTANCE* wwo)
1141 BOOL didLoopBack = FALSE;
1143 wwo->dwPartialOffset = 0;
1144 if ((wwo->lpPlayPtr->dwFlags & WHDR_ENDLOOP) && wwo->lpLoopPtr)
1146 /* We're at the end of a loop, loop if required */
1147 if (wwo->dwLoops > 1)
1149 wwo->dwLoops--;
1150 wwo->lpPlayPtr = wwo->lpLoopPtr;
1151 didLoopBack = TRUE;
1153 else
1155 wwo->lpLoopPtr = NULL;
1158 if (!didLoopBack)
1160 /* We didn't loop back. Advance to the next wave header */
1161 wwo->lpPlayPtr = wwo->lpPlayPtr->lpNext;
1163 if (wwo->lpPlayPtr)
1164 wodHelper_CheckForLoopBegin(wwo);
1168 /* Send the "done" notification for each WAVEHDR in a list. The list must be
1169 * free-standing. It should not be part of a device instance's queue.
1170 * This function must be called with the WAVEOUT_INSTANCE lock *not* held.
1171 * Furthermore, it does not lock it, itself. That's because the callback to the
1172 * application may prompt the application to operate on the device, and we don't
1173 * want to deadlock.
1175 static void wodHelper_NotifyDoneForList(WINE_WAVEOUT_INSTANCE* wwo, LPWAVEHDR lpWaveHdr)
1177 while (lpWaveHdr)
1179 LPWAVEHDR lpNext = lpWaveHdr->lpNext;
1181 lpWaveHdr->lpNext = NULL;
1182 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1183 lpWaveHdr->dwFlags |= WHDR_DONE;
1184 wodNotifyClient(wwo, WOM_DONE, (DWORD)lpWaveHdr, 0);
1186 lpWaveHdr = lpNext;
1190 /* if force is TRUE then notify the client that all the headers were completed
1192 static void wodHelper_NotifyCompletions(WINE_WAVEOUT_INSTANCE* wwo, BOOL force)
1194 LPWAVEHDR lpFirstDoneWaveHdr = NULL;
1196 OSSpinLockLock(&wwo->lock);
1198 /* First, excise all of the done headers from the queue into
1199 * a free-standing list. */
1200 if (force)
1202 lpFirstDoneWaveHdr = wwo->lpQueuePtr;
1203 wwo->lpQueuePtr = NULL;
1205 else
1207 LPWAVEHDR lpWaveHdr;
1208 LPWAVEHDR lpLastDoneWaveHdr = NULL;
1210 /* Start from lpQueuePtr and keep notifying until:
1211 * - we hit an unwritten wavehdr
1212 * - we hit the beginning of a running loop
1213 * - we hit a wavehdr which hasn't finished playing
1215 for (
1216 lpWaveHdr = wwo->lpQueuePtr;
1217 lpWaveHdr &&
1218 lpWaveHdr != wwo->lpPlayPtr &&
1219 lpWaveHdr != wwo->lpLoopPtr;
1220 lpWaveHdr = lpWaveHdr->lpNext
1223 if (!lpFirstDoneWaveHdr)
1224 lpFirstDoneWaveHdr = lpWaveHdr;
1225 lpLastDoneWaveHdr = lpWaveHdr;
1228 if (lpLastDoneWaveHdr)
1230 wwo->lpQueuePtr = lpLastDoneWaveHdr->lpNext;
1231 lpLastDoneWaveHdr->lpNext = NULL;
1235 OSSpinLockUnlock(&wwo->lock);
1237 /* Now, send the "done" notification for each header in our list. */
1238 wodHelper_NotifyDoneForList(wwo, lpFirstDoneWaveHdr);
1242 /**************************************************************************
1243 * wodWrite [internal]
1246 static DWORD wodWrite(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1248 LPWAVEHDR*wh;
1250 TRACE("(%u, %p, %p, %lu, %08X);\n", wDevID, wwo, lpWaveHdr, (unsigned long)lpWaveHdr->dwBufferLength, dwSize);
1252 /* first, do the sanity checks... */
1253 if (wDevID >= MAX_WAVEOUTDRV)
1255 WARN("bad dev ID !\n");
1256 return MMSYSERR_BADDEVICEID;
1259 if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
1261 TRACE("unprepared\n");
1262 return WAVERR_UNPREPARED;
1265 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1267 TRACE("still playing\n");
1268 return WAVERR_STILLPLAYING;
1271 lpWaveHdr->dwFlags &= ~WHDR_DONE;
1272 lpWaveHdr->dwFlags |= WHDR_INQUEUE;
1273 lpWaveHdr->lpNext = 0;
1275 OSSpinLockLock(&wwo->lock);
1276 /* insert buffer at the end of queue */
1277 for (wh = &(wwo->lpQueuePtr); *wh; wh = &((*wh)->lpNext))
1278 /* Do nothing */;
1279 *wh = lpWaveHdr;
1281 if (!wwo->lpPlayPtr)
1283 wwo->lpPlayPtr = lpWaveHdr;
1285 wodHelper_CheckForLoopBegin(wwo);
1287 wwo->dwPartialOffset = 0;
1289 OSSpinLockUnlock(&wwo->lock);
1291 return MMSYSERR_NOERROR;
1294 /**************************************************************************
1295 * wodPause [internal]
1297 static DWORD wodPause(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo)
1299 OSStatus status;
1301 TRACE("(%u, %p);!\n", wDevID, wwo);
1303 if (wDevID >= MAX_WAVEOUTDRV)
1305 WARN("bad device ID !\n");
1306 return MMSYSERR_BADDEVICEID;
1309 /* The order of the following operations is important since we can't hold
1310 * the mutex while we make an Audio Unit call. Stop the Audio Unit before
1311 * setting the PAUSED state. In wodRestart, the order is reversed. This
1312 * guarantees that we can't get into a situation where the state is
1313 * PLAYING but the Audio Unit isn't running. Although we can be in PAUSED
1314 * state with the Audio Unit still running, that's harmless because the
1315 * render callback will just produce silence.
1317 status = AudioOutputUnitStop(wwo->audioUnit);
1318 if (status)
1319 WARN("AudioOutputUnitStop return %s\n", wine_dbgstr_fourcc(status));
1321 OSSpinLockLock(&wwo->lock);
1322 if (wwo->state == WINE_WS_PLAYING)
1323 wwo->state = WINE_WS_PAUSED;
1324 OSSpinLockUnlock(&wwo->lock);
1326 return MMSYSERR_NOERROR;
1329 /**************************************************************************
1330 * wodRestart [internal]
1332 static DWORD wodRestart(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo)
1334 OSStatus status;
1336 TRACE("(%u, %p);\n", wDevID, wwo);
1338 if (wDevID >= MAX_WAVEOUTDRV )
1340 WARN("bad device ID !\n");
1341 return MMSYSERR_BADDEVICEID;
1344 /* The order of the following operations is important since we can't hold
1345 * the mutex while we make an Audio Unit call. Set the PLAYING
1346 * state before starting the Audio Unit. In wodPause, the order is
1347 * reversed. This guarantees that we can't get into a situation where
1348 * the state is PLAYING but the Audio Unit isn't running.
1349 * Although we can be in PAUSED state with the Audio Unit still running,
1350 * that's harmless because the render callback will just produce silence.
1352 OSSpinLockLock(&wwo->lock);
1353 if (wwo->state == WINE_WS_PAUSED)
1354 wwo->state = WINE_WS_PLAYING;
1355 OSSpinLockUnlock(&wwo->lock);
1357 status = AudioOutputUnitStart(wwo->audioUnit);
1358 if (status) {
1359 ERR("AudioOutputUnitStart return %s\n", wine_dbgstr_fourcc(status));
1360 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1363 return MMSYSERR_NOERROR;
1366 /**************************************************************************
1367 * wodReset [internal]
1369 static DWORD wodReset(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo)
1371 OSStatus status;
1372 LPWAVEHDR lpSavedQueuePtr;
1374 TRACE("(%u, %p);\n", wDevID, wwo);
1376 if (wDevID >= MAX_WAVEOUTDRV)
1378 WARN("bad device ID !\n");
1379 return MMSYSERR_BADDEVICEID;
1382 OSSpinLockLock(&wwo->lock);
1384 if (wwo->state == WINE_WS_CLOSING || wwo->state == WINE_WS_OPENING)
1386 OSSpinLockUnlock(&wwo->lock);
1387 WARN("resetting a closed device\n");
1388 return MMSYSERR_INVALHANDLE;
1391 lpSavedQueuePtr = wwo->lpQueuePtr;
1392 wwo->lpPlayPtr = wwo->lpQueuePtr = wwo->lpLoopPtr = NULL;
1393 wwo->state = WINE_WS_PLAYING;
1394 wwo->dwPlayedTotal = 0;
1396 wwo->dwPartialOffset = 0; /* Clear partial wavehdr */
1398 OSSpinLockUnlock(&wwo->lock);
1400 status = AudioOutputUnitStart(wwo->audioUnit);
1402 if (status) {
1403 ERR( "AudioOutputUnitStart return %s\n", wine_dbgstr_fourcc(status));
1404 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1407 /* Now, send the "done" notification for each header in our list. */
1408 /* Do this last so the reset operation is effectively complete before the
1409 * app does whatever it's going to do in response to these notifications. */
1410 wodHelper_NotifyDoneForList(wwo, lpSavedQueuePtr);
1412 return MMSYSERR_NOERROR;
1415 /**************************************************************************
1416 * wodBreakLoop [internal]
1418 static DWORD wodBreakLoop(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo)
1420 TRACE("(%u, %p);\n", wDevID, wwo);
1422 if (wDevID >= MAX_WAVEOUTDRV)
1424 WARN("bad device ID !\n");
1425 return MMSYSERR_BADDEVICEID;
1428 OSSpinLockLock(&wwo->lock);
1430 if (wwo->lpLoopPtr != NULL)
1432 /* ensure exit at end of current loop */
1433 wwo->dwLoops = 1;
1436 OSSpinLockUnlock(&wwo->lock);
1438 return MMSYSERR_NOERROR;
1441 /**************************************************************************
1442 * wodGetPosition [internal]
1444 static DWORD wodGetPosition(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, LPMMTIME lpTime, DWORD uSize)
1446 DWORD val;
1448 TRACE("(%u, %p, %p, %u);\n", wDevID, wwo, lpTime, uSize);
1450 if (wDevID >= MAX_WAVEOUTDRV)
1452 WARN("bad device ID !\n");
1453 return MMSYSERR_BADDEVICEID;
1456 /* if null pointer to time structure return error */
1457 if (lpTime == NULL) return MMSYSERR_INVALPARAM;
1459 OSSpinLockLock(&wwo->lock);
1460 val = wwo->dwPlayedTotal;
1461 OSSpinLockUnlock(&wwo->lock);
1463 return bytes_to_mmtime(lpTime, val, &wwo->format);
1466 /**************************************************************************
1467 * wodGetVolume [internal]
1469 static DWORD wodGetVolume(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, LPDWORD lpdwVol)
1471 if (wDevID >= MAX_WAVEOUTDRV)
1473 WARN("bad device ID !\n");
1474 return MMSYSERR_BADDEVICEID;
1477 TRACE("(%u, %p, %p);\n", wDevID, wwo, lpdwVol);
1479 if (wwo)
1481 float left;
1482 float right;
1484 AudioUnit_GetVolume(wwo->audioUnit, &left, &right);
1485 *lpdwVol = (WORD)(left * 0xFFFFl) + ((WORD)(right * 0xFFFFl) << 16);
1487 else
1488 *lpdwVol = WOutDev[wDevID].device_volume;
1490 return MMSYSERR_NOERROR;
1493 /**************************************************************************
1494 * wodSetVolume [internal]
1496 static DWORD wodSetVolume(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, DWORD dwParam)
1498 float left;
1499 float right;
1501 if (wDevID >= MAX_WAVEOUTDRV)
1503 WARN("bad device ID !\n");
1504 return MMSYSERR_BADDEVICEID;
1507 left = LOWORD(dwParam) / 65535.0f;
1508 right = HIWORD(dwParam) / 65535.0f;
1510 TRACE("(%u, %p, %08x);\n", wDevID, wwo, dwParam);
1512 if (wwo)
1513 AudioUnit_SetVolume(wwo->audioUnit, left, right);
1514 else
1516 OSSpinLockLock(&WOutDev[wDevID].lock);
1517 LIST_FOR_EACH_ENTRY(wwo, &WOutDev[wDevID].instances, WINE_WAVEOUT_INSTANCE, entry)
1518 AudioUnit_SetVolume(wwo->audioUnit, left, right);
1519 OSSpinLockUnlock(&WOutDev[wDevID].lock);
1521 WOutDev[wDevID].device_volume = dwParam;
1524 return MMSYSERR_NOERROR;
1527 /**************************************************************************
1528 * wodGetNumDevs [internal]
1530 static DWORD wodGetNumDevs(void)
1532 TRACE("\n");
1533 return MAX_WAVEOUTDRV;
1536 /**************************************************************************
1537 * wodDevInterfaceSize [internal]
1539 static DWORD wodDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
1541 TRACE("(%u, %p)\n", wDevID, dwParam1);
1543 *dwParam1 = MultiByteToWideChar(CP_UNIXCP, 0, WOutDev[wDevID].cadev->interface_name, -1,
1544 NULL, 0 ) * sizeof(WCHAR);
1545 return MMSYSERR_NOERROR;
1548 /**************************************************************************
1549 * wodDevInterface [internal]
1551 static DWORD wodDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
1553 TRACE("\n");
1554 if (dwParam2 >= MultiByteToWideChar(CP_UNIXCP, 0, WOutDev[wDevID].cadev->interface_name, -1,
1555 NULL, 0 ) * sizeof(WCHAR))
1557 MultiByteToWideChar(CP_UNIXCP, 0, WOutDev[wDevID].cadev->interface_name, -1,
1558 dwParam1, dwParam2 / sizeof(WCHAR));
1559 return MMSYSERR_NOERROR;
1561 return MMSYSERR_INVALPARAM;
1564 /**************************************************************************
1565 * widDsCreate [internal]
1567 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
1569 TRACE("(%d,%p)\n",wDevID,drv);
1571 FIXME("DirectSound not implemented\n");
1572 FIXME("The (slower) DirectSound HEL mode will be used instead.\n");
1573 return MMSYSERR_NOTSUPPORTED;
1576 /**************************************************************************
1577 * wodDsDesc [internal]
1579 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc)
1581 /* The DirectSound HEL will automatically wrap a non-DirectSound-capable
1582 * driver in a DirectSound adaptor, thus allowing the driver to be used by
1583 * DirectSound clients. However, it only does this if we respond
1584 * successfully to the DRV_QUERYDSOUNDDESC message. It's enough to fill in
1585 * the driver and device names of the description output parameter. */
1586 *desc = WOutDev[wDevID].cadev->ds_desc;
1587 return MMSYSERR_NOERROR;
1590 /**************************************************************************
1591 * wodMessage (WINECOREAUDIO.7)
1593 DWORD WINAPI CoreAudio_wodMessage(UINT wDevID, UINT wMsg, DWORD_PTR dwUser,
1594 DWORD_PTR dwParam1, DWORD_PTR dwParam2)
1596 WINE_WAVEOUT_INSTANCE* wwo = (WINE_WAVEOUT_INSTANCE*)dwUser;
1598 TRACE("(%u, %s, %p, %p, %p);\n",
1599 wDevID, getMessage(wMsg), (void*)dwUser, (void*)dwParam1, (void*)dwParam2);
1601 switch (wMsg) {
1602 case DRVM_INIT:
1603 case DRVM_EXIT:
1604 case DRVM_ENABLE:
1605 case DRVM_DISABLE:
1607 /* FIXME: Pretend this is supported */
1608 return 0;
1609 case WODM_OPEN: return wodOpen(wDevID, (WINE_WAVEOUT_INSTANCE**)dwUser, (LPWAVEOPENDESC) dwParam1, dwParam2);
1610 case WODM_CLOSE: return wodClose(wDevID, wwo);
1611 case WODM_WRITE: return wodWrite(wDevID, wwo, (LPWAVEHDR) dwParam1, dwParam2);
1612 case WODM_PAUSE: return wodPause(wDevID, wwo);
1613 case WODM_GETPOS: return wodGetPosition(wDevID, wwo, (LPMMTIME) dwParam1, dwParam2);
1614 case WODM_BREAKLOOP: return wodBreakLoop(wDevID, wwo);
1615 case WODM_PREPARE: return wodPrepare(wDevID, wwo, (LPWAVEHDR)dwParam1, dwParam2);
1616 case WODM_UNPREPARE: return wodUnprepare(wDevID, wwo, (LPWAVEHDR)dwParam1, dwParam2);
1618 case WODM_GETDEVCAPS: return wodGetDevCaps(wDevID, (LPWAVEOUTCAPSW) dwParam1, dwParam2);
1619 case WODM_GETNUMDEVS: return wodGetNumDevs();
1621 case WODM_GETPITCH:
1622 case WODM_SETPITCH:
1623 case WODM_GETPLAYBACKRATE:
1624 case WODM_SETPLAYBACKRATE: return MMSYSERR_NOTSUPPORTED;
1625 case WODM_GETVOLUME: return wodGetVolume(wDevID, wwo, (LPDWORD)dwParam1);
1626 case WODM_SETVOLUME: return wodSetVolume(wDevID, wwo, dwParam1);
1627 case WODM_RESTART: return wodRestart(wDevID, wwo);
1628 case WODM_RESET: return wodReset(wDevID, wwo);
1630 case DRV_QUERYDEVICEINTERFACESIZE: return wodDevInterfaceSize (wDevID, (LPDWORD)dwParam1);
1631 case DRV_QUERYDEVICEINTERFACE: return wodDevInterface (wDevID, (PWCHAR)dwParam1, dwParam2);
1632 case DRV_QUERYDSOUNDIFACE: return wodDsCreate (wDevID, (PIDSDRIVER*)dwParam1);
1633 case DRV_QUERYDSOUNDDESC: return wodDsDesc (wDevID, (PDSDRIVERDESC)dwParam1);
1635 default:
1636 FIXME("unknown message %d!\n", wMsg);
1639 return MMSYSERR_NOTSUPPORTED;
1642 /*======================================================================*
1643 * Low level DSOUND implementation *
1644 *======================================================================*/
1646 typedef struct IDsDriverImpl IDsDriverImpl;
1647 typedef struct IDsDriverBufferImpl IDsDriverBufferImpl;
1649 struct IDsDriverImpl
1651 /* IUnknown fields */
1652 const IDsDriverVtbl *lpVtbl;
1653 DWORD ref;
1654 /* IDsDriverImpl fields */
1655 UINT wDevID;
1656 IDsDriverBufferImpl*primary;
1659 struct IDsDriverBufferImpl
1661 /* IUnknown fields */
1662 const IDsDriverBufferVtbl *lpVtbl;
1663 DWORD ref;
1664 /* IDsDriverBufferImpl fields */
1665 IDsDriverImpl* drv;
1666 DWORD buflen;
1671 CoreAudio IO threaded callback,
1672 we can't call Wine debug channels, critical section or anything using NtCurrentTeb here.
1674 OSStatus CoreAudio_woAudioUnitIOProc(void *inRefCon,
1675 AudioUnitRenderActionFlags *ioActionFlags,
1676 const AudioTimeStamp *inTimeStamp,
1677 UInt32 inBusNumber,
1678 UInt32 inNumberFrames,
1679 AudioBufferList *ioData)
1681 UInt32 buffer;
1682 WINE_WAVEOUT_INSTANCE* wwo = (WINE_WAVEOUT_INSTANCE*)inRefCon;
1683 int needNotify = 0;
1685 unsigned int dataNeeded = ioData->mBuffers[0].mDataByteSize;
1686 unsigned int dataProvided = 0;
1688 OSSpinLockLock(&wwo->lock);
1690 /* We might have been called before wwo has been completely filled out by
1691 * wodOpen, or while it's being closed in wodClose. We have to do nothing
1692 * in that case. The check of wwo->state below ensures that. */
1693 while (dataNeeded > 0 && wwo->state == WINE_WS_PLAYING && wwo->lpPlayPtr)
1695 unsigned int available = wwo->lpPlayPtr->dwBufferLength - wwo->dwPartialOffset;
1696 unsigned int toCopy;
1698 if (available >= dataNeeded)
1699 toCopy = dataNeeded;
1700 else
1701 toCopy = available;
1703 if (toCopy > 0)
1705 memcpy((char*)ioData->mBuffers[0].mData + dataProvided,
1706 wwo->lpPlayPtr->lpData + wwo->dwPartialOffset, toCopy);
1707 wwo->dwPartialOffset += toCopy;
1708 wwo->dwPlayedTotal += toCopy;
1709 dataProvided += toCopy;
1710 dataNeeded -= toCopy;
1711 available -= toCopy;
1714 if (available == 0)
1716 wodHelper_PlayPtrNext(wwo);
1717 needNotify = 1;
1720 ioData->mBuffers[0].mDataByteSize = dataProvided;
1722 OSSpinLockUnlock(&wwo->lock);
1724 /* We can't provide any more wave data. Fill the rest with silence. */
1725 if (dataNeeded > 0)
1727 if (!dataProvided)
1728 *ioActionFlags |= kAudioUnitRenderAction_OutputIsSilence;
1729 memset((char*)ioData->mBuffers[0].mData + dataProvided, 0, dataNeeded);
1730 dataProvided += dataNeeded;
1731 dataNeeded = 0;
1734 /* We only fill buffer 0. Set any others that might be requested to 0. */
1735 for (buffer = 1; buffer < ioData->mNumberBuffers; buffer++)
1737 memset(ioData->mBuffers[buffer].mData, 0, ioData->mBuffers[buffer].mDataByteSize);
1740 if (needNotify) wodSendNotifyCompletionsMessage(wwo);
1741 return noErr;
1745 /*======================================================================*
1746 * Low level WAVE IN implementation *
1747 *======================================================================*/
1749 /**************************************************************************
1750 * widNotifyClient [internal]
1752 static DWORD widNotifyClient(WINE_WAVEIN* wwi, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
1754 TRACE("wMsg = 0x%04x dwParm1 = %04X dwParam2 = %04X\n", wMsg, dwParam1, dwParam2);
1756 switch (wMsg)
1758 case WIM_OPEN:
1759 case WIM_CLOSE:
1760 case WIM_DATA:
1761 if (wwi->wFlags != DCB_NULL &&
1762 !DriverCallback(wwi->waveDesc.dwCallback, wwi->wFlags,
1763 (HDRVR)wwi->waveDesc.hWave, wMsg, wwi->waveDesc.dwInstance,
1764 dwParam1, dwParam2))
1766 WARN("can't notify client !\n");
1767 return MMSYSERR_ERROR;
1769 break;
1770 default:
1771 FIXME("Unknown callback message %u\n", wMsg);
1772 return MMSYSERR_INVALPARAM;
1774 return MMSYSERR_NOERROR;
1778 /**************************************************************************
1779 * widHelper_NotifyCompletions [internal]
1781 static void widHelper_NotifyCompletions(WINE_WAVEIN* wwi)
1783 LPWAVEHDR lpWaveHdr;
1784 LPWAVEHDR lpFirstDoneWaveHdr = NULL;
1785 LPWAVEHDR lpLastDoneWaveHdr = NULL;
1787 OSSpinLockLock(&wwi->lock);
1789 /* First, excise all of the done headers from the queue into
1790 * a free-standing list. */
1792 /* Start from lpQueuePtr and keep notifying until:
1793 * - we hit an unfilled wavehdr
1794 * - we hit the end of the list
1796 for (
1797 lpWaveHdr = wwi->lpQueuePtr;
1798 lpWaveHdr &&
1799 lpWaveHdr->dwBytesRecorded >= lpWaveHdr->dwBufferLength;
1800 lpWaveHdr = lpWaveHdr->lpNext
1803 if (!lpFirstDoneWaveHdr)
1804 lpFirstDoneWaveHdr = lpWaveHdr;
1805 lpLastDoneWaveHdr = lpWaveHdr;
1808 if (lpLastDoneWaveHdr)
1810 wwi->lpQueuePtr = lpLastDoneWaveHdr->lpNext;
1811 lpLastDoneWaveHdr->lpNext = NULL;
1814 OSSpinLockUnlock(&wwi->lock);
1816 /* Now, send the "done" notification for each header in our list. */
1817 lpWaveHdr = lpFirstDoneWaveHdr;
1818 while (lpWaveHdr)
1820 LPWAVEHDR lpNext = lpWaveHdr->lpNext;
1822 lpWaveHdr->lpNext = NULL;
1823 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1824 lpWaveHdr->dwFlags |= WHDR_DONE;
1825 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
1827 lpWaveHdr = lpNext;
1832 /**************************************************************************
1833 * widGetDevCaps [internal]
1835 static DWORD widGetDevCaps(WORD wDevID, LPWAVEINCAPSW lpCaps, DWORD dwSize)
1837 TRACE("(%u, %p, %u);\n", wDevID, lpCaps, dwSize);
1839 if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
1841 if (wDevID >= MAX_WAVEINDRV)
1843 TRACE("MAX_WAVEINDRV reached !\n");
1844 return MMSYSERR_BADDEVICEID;
1847 memcpy(lpCaps, &WInDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
1848 return MMSYSERR_NOERROR;
1852 /**************************************************************************
1853 * widHelper_DestroyAudioBufferList [internal]
1854 * Convenience function to dispose of our audio buffers
1856 static void widHelper_DestroyAudioBufferList(AudioBufferList* list)
1858 if (list)
1860 UInt32 i;
1861 for (i = 0; i < list->mNumberBuffers; i++)
1863 if (list->mBuffers[i].mData)
1864 HeapFree(GetProcessHeap(), 0, list->mBuffers[i].mData);
1866 HeapFree(GetProcessHeap(), 0, list);
1871 #define AUDIOBUFFERLISTSIZE(numBuffers) (offsetof(AudioBufferList, mBuffers) + (numBuffers) * sizeof(AudioBuffer))
1873 /**************************************************************************
1874 * widHelper_AllocateAudioBufferList [internal]
1875 * Convenience function to allocate our audio buffers
1877 static AudioBufferList* widHelper_AllocateAudioBufferList(UInt32 numChannels, UInt32 bitsPerChannel, UInt32 bufferFrames, BOOL interleaved)
1879 UInt32 numBuffers;
1880 UInt32 channelsPerFrame;
1881 UInt32 bytesPerFrame;
1882 UInt32 bytesPerBuffer;
1883 AudioBufferList* list;
1884 UInt32 i;
1886 if (interleaved)
1888 /* For interleaved audio, we allocate one buffer for all channels. */
1889 numBuffers = 1;
1890 channelsPerFrame = numChannels;
1892 else
1894 numBuffers = numChannels;
1895 channelsPerFrame = 1;
1898 bytesPerFrame = bitsPerChannel * channelsPerFrame / 8;
1899 bytesPerBuffer = bytesPerFrame * bufferFrames;
1901 list = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, AUDIOBUFFERLISTSIZE(numBuffers));
1902 if (list == NULL)
1903 return NULL;
1905 list->mNumberBuffers = numBuffers;
1906 for (i = 0; i < numBuffers; ++i)
1908 list->mBuffers[i].mNumberChannels = channelsPerFrame;
1909 list->mBuffers[i].mDataByteSize = bytesPerBuffer;
1910 list->mBuffers[i].mData = HeapAlloc(GetProcessHeap(), 0, bytesPerBuffer);
1911 if (list->mBuffers[i].mData == NULL)
1913 widHelper_DestroyAudioBufferList(list);
1914 return NULL;
1917 return list;
1921 /**************************************************************************
1922 * widOpen [internal]
1924 static DWORD widOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
1926 WINE_WAVEIN* wwi;
1927 UInt32 frameCount;
1929 TRACE("(%u, %p, %08X);\n", wDevID, lpDesc, dwFlags);
1930 if (lpDesc == NULL)
1932 WARN("Invalid Parameter !\n");
1933 return MMSYSERR_INVALPARAM;
1935 if (wDevID >= MAX_WAVEINDRV)
1937 TRACE ("MAX_WAVEINDRV reached !\n");
1938 return MMSYSERR_BADDEVICEID;
1941 TRACE("Format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
1942 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1943 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
1945 if (!supportedFormat(lpDesc->lpFormat) ||
1946 lpDesc->lpFormat->nSamplesPerSec != AudioUnit_GetInputDeviceSampleRate()
1949 WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
1950 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1951 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
1952 return WAVERR_BADFORMAT;
1955 if (dwFlags & WAVE_FORMAT_QUERY)
1957 TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
1958 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1959 lpDesc->lpFormat->nSamplesPerSec);
1960 return MMSYSERR_NOERROR;
1963 /* nBlockAlign and nAvgBytesPerSec are output variables for dsound */
1964 if (lpDesc->lpFormat->nBlockAlign != lpDesc->lpFormat->nChannels*lpDesc->lpFormat->wBitsPerSample/8) {
1965 lpDesc->lpFormat->nBlockAlign = lpDesc->lpFormat->nChannels*lpDesc->lpFormat->wBitsPerSample/8;
1966 WARN("Fixing nBlockAlign\n");
1968 if (lpDesc->lpFormat->nAvgBytesPerSec!= lpDesc->lpFormat->nSamplesPerSec*lpDesc->lpFormat->nBlockAlign) {
1969 lpDesc->lpFormat->nAvgBytesPerSec = lpDesc->lpFormat->nSamplesPerSec*lpDesc->lpFormat->nBlockAlign;
1970 WARN("Fixing nAvgBytesPerSec\n");
1973 wwi = &WInDev[wDevID];
1974 if (!OSSpinLockTry(&wwi->lock))
1975 return MMSYSERR_ALLOCATED;
1977 if (wwi->state != WINE_WS_CLOSED)
1979 OSSpinLockUnlock(&wwi->lock);
1980 return MMSYSERR_ALLOCATED;
1983 wwi->state = WINE_WS_STOPPED;
1984 wwi->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
1986 wwi->waveDesc = *lpDesc;
1987 copyFormat(lpDesc->lpFormat, &wwi->format);
1989 wwi->dwTotalRecorded = 0;
1991 wwi->trace_on = TRACE_ON(wave);
1992 wwi->warn_on = WARN_ON(wave);
1993 wwi->err_on = ERR_ON(wave);
1995 if (!AudioUnit_CreateInputUnit(wwi, &wwi->audioUnit,
1996 wwi->format.wf.nChannels, wwi->format.wf.nSamplesPerSec,
1997 wwi->format.wBitsPerSample, &frameCount))
1999 OSSpinLockUnlock(&wwi->lock);
2000 ERR("AudioUnit_CreateInputUnit failed\n");
2001 return MMSYSERR_ERROR;
2004 /* Allocate our audio buffers */
2005 wwi->bufferList = widHelper_AllocateAudioBufferList(wwi->format.wf.nChannels,
2006 wwi->format.wBitsPerSample, frameCount, TRUE);
2007 if (wwi->bufferList == NULL)
2009 AudioUnitUninitialize(wwi->audioUnit);
2010 AudioUnit_CloseAudioUnit(wwi->audioUnit);
2011 OSSpinLockUnlock(&wwi->lock);
2012 ERR("Failed to allocate buffer list\n");
2013 return MMSYSERR_NOMEM;
2016 /* Keep a copy of the buffer list structure (but not the buffers themselves)
2017 * in case AudioUnitRender clobbers the original, as it tends to do. */
2018 wwi->bufferListCopy = HeapAlloc(GetProcessHeap(), 0, AUDIOBUFFERLISTSIZE(wwi->bufferList->mNumberBuffers));
2019 if (wwi->bufferListCopy == NULL)
2021 widHelper_DestroyAudioBufferList(wwi->bufferList);
2022 AudioUnitUninitialize(wwi->audioUnit);
2023 AudioUnit_CloseAudioUnit(wwi->audioUnit);
2024 OSSpinLockUnlock(&wwi->lock);
2025 ERR("Failed to allocate buffer list copy\n");
2026 return MMSYSERR_NOMEM;
2028 memcpy(wwi->bufferListCopy, wwi->bufferList, AUDIOBUFFERLISTSIZE(wwi->bufferList->mNumberBuffers));
2030 OSSpinLockUnlock(&wwi->lock);
2032 return widNotifyClient(wwi, WIM_OPEN, 0L, 0L);
2036 /**************************************************************************
2037 * widClose [internal]
2039 static DWORD widClose(WORD wDevID)
2041 DWORD ret = MMSYSERR_NOERROR;
2042 WINE_WAVEIN* wwi;
2043 OSStatus err;
2045 TRACE("(%u);\n", wDevID);
2047 if (wDevID >= MAX_WAVEINDRV)
2049 WARN("bad device ID !\n");
2050 return MMSYSERR_BADDEVICEID;
2053 wwi = &WInDev[wDevID];
2054 OSSpinLockLock(&wwi->lock);
2055 if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2057 WARN("Device already closed.\n");
2058 ret = MMSYSERR_INVALHANDLE;
2060 else if (wwi->lpQueuePtr)
2062 WARN("Buffers in queue.\n");
2063 ret = WAVERR_STILLPLAYING;
2065 else
2067 wwi->state = WINE_WS_CLOSING;
2070 OSSpinLockUnlock(&wwi->lock);
2072 if (ret != MMSYSERR_NOERROR)
2073 return ret;
2076 /* Clean up and close the audio unit. This has to be done without
2077 * wwi->lock being held to avoid deadlock. AudioUnitUninitialize will
2078 * grab an internal Core Audio lock while waiting for the device work
2079 * thread to exit. Meanwhile the device work thread may be holding
2080 * that lock and trying to grab the wwi->lock in the callback. */
2081 err = AudioUnitUninitialize(wwi->audioUnit);
2082 if (err)
2083 ERR("AudioUnitUninitialize return %s\n", wine_dbgstr_fourcc(err));
2085 if (!AudioUnit_CloseAudioUnit(wwi->audioUnit))
2086 ERR("Can't close AudioUnit\n");
2089 OSSpinLockLock(&wwi->lock);
2090 assert(wwi->state == WINE_WS_CLOSING);
2092 /* Dellocate our audio buffers */
2093 widHelper_DestroyAudioBufferList(wwi->bufferList);
2094 wwi->bufferList = NULL;
2095 HeapFree(GetProcessHeap(), 0, wwi->bufferListCopy);
2096 wwi->bufferListCopy = NULL;
2098 wwi->audioUnit = NULL;
2099 wwi->state = WINE_WS_CLOSED;
2100 OSSpinLockUnlock(&wwi->lock);
2102 ret = widNotifyClient(wwi, WIM_CLOSE, 0L, 0L);
2104 return ret;
2108 /**************************************************************************
2109 * widAddBuffer [internal]
2111 static DWORD widAddBuffer(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
2113 DWORD ret = MMSYSERR_NOERROR;
2114 WINE_WAVEIN* wwi;
2116 TRACE("(%u, %p, %08X);\n", wDevID, lpWaveHdr, dwSize);
2118 if (wDevID >= MAX_WAVEINDRV)
2120 WARN("invalid device ID\n");
2121 return MMSYSERR_INVALHANDLE;
2123 if (!(lpWaveHdr->dwFlags & WHDR_PREPARED))
2125 TRACE("never been prepared !\n");
2126 return WAVERR_UNPREPARED;
2128 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
2130 TRACE("header already in use !\n");
2131 return WAVERR_STILLPLAYING;
2134 wwi = &WInDev[wDevID];
2135 OSSpinLockLock(&wwi->lock);
2137 if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2139 WARN("Trying to add buffer to closed device.\n");
2140 ret = MMSYSERR_INVALHANDLE;
2142 else
2144 LPWAVEHDR* wh;
2146 lpWaveHdr->dwFlags |= WHDR_INQUEUE;
2147 lpWaveHdr->dwFlags &= ~WHDR_DONE;
2148 lpWaveHdr->dwBytesRecorded = 0;
2149 lpWaveHdr->lpNext = NULL;
2151 /* insert buffer at end of queue */
2152 for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext))
2153 /* Do nothing */;
2154 *wh = lpWaveHdr;
2157 OSSpinLockUnlock(&wwi->lock);
2159 return ret;
2163 /**************************************************************************
2164 * widStart [internal]
2166 static DWORD widStart(WORD wDevID)
2168 DWORD ret = MMSYSERR_NOERROR;
2169 WINE_WAVEIN* wwi;
2171 TRACE("(%u);\n", wDevID);
2172 if (wDevID >= MAX_WAVEINDRV)
2174 WARN("invalid device ID\n");
2175 return MMSYSERR_INVALHANDLE;
2178 /* The order of the following operations is important since we can't hold
2179 * the mutex while we make an Audio Unit call. Set the PLAYING state
2180 * before starting the Audio Unit. In widStop, the order is reversed.
2181 * This guarantees that we can't get into a situation where the state is
2182 * PLAYING but the Audio Unit isn't running. Although we can be in STOPPED
2183 * state with the Audio Unit still running, that's harmless because the
2184 * input callback will just throw away the sound data.
2186 wwi = &WInDev[wDevID];
2187 OSSpinLockLock(&wwi->lock);
2189 if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2191 WARN("Trying to start closed device.\n");
2192 ret = MMSYSERR_INVALHANDLE;
2194 else
2195 wwi->state = WINE_WS_PLAYING;
2197 OSSpinLockUnlock(&wwi->lock);
2199 if (ret == MMSYSERR_NOERROR)
2201 /* Start pulling for audio data */
2202 OSStatus err = AudioOutputUnitStart(wwi->audioUnit);
2203 if (err != noErr)
2204 ERR("Failed to start AU: %08lx\n", err);
2206 TRACE("Recording started...\n");
2209 return ret;
2213 /**************************************************************************
2214 * widStop [internal]
2216 static DWORD widStop(WORD wDevID)
2218 DWORD ret = MMSYSERR_NOERROR;
2219 WINE_WAVEIN* wwi;
2220 WAVEHDR* lpWaveHdr = NULL;
2221 OSStatus err;
2223 TRACE("(%u);\n", wDevID);
2224 if (wDevID >= MAX_WAVEINDRV)
2226 WARN("invalid device ID\n");
2227 return MMSYSERR_INVALHANDLE;
2230 wwi = &WInDev[wDevID];
2232 /* The order of the following operations is important since we can't hold
2233 * the mutex while we make an Audio Unit call. Stop the Audio Unit before
2234 * setting the STOPPED state. In widStart, the order is reversed. This
2235 * guarantees that we can't get into a situation where the state is
2236 * PLAYING but the Audio Unit isn't running. Although we can be in STOPPED
2237 * state with the Audio Unit still running, that's harmless because the
2238 * input callback will just throw away the sound data.
2240 err = AudioOutputUnitStop(wwi->audioUnit);
2241 if (err != noErr)
2242 WARN("Failed to stop AU: %08lx\n", err);
2244 TRACE("Recording stopped.\n");
2246 OSSpinLockLock(&wwi->lock);
2248 if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2250 WARN("Trying to stop closed device.\n");
2251 ret = MMSYSERR_INVALHANDLE;
2253 else if (wwi->state != WINE_WS_STOPPED)
2255 wwi->state = WINE_WS_STOPPED;
2256 /* If there's a buffer in progress, it's done. Remove it from the
2257 * queue so that we can return it to the app, below. */
2258 if (wwi->lpQueuePtr)
2260 lpWaveHdr = wwi->lpQueuePtr;
2261 wwi->lpQueuePtr = lpWaveHdr->lpNext;
2265 OSSpinLockUnlock(&wwi->lock);
2267 if (lpWaveHdr)
2269 lpWaveHdr->lpNext = NULL;
2270 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2271 lpWaveHdr->dwFlags |= WHDR_DONE;
2272 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2275 return ret;
2278 /**************************************************************************
2279 * widGetPos [internal]
2281 static DWORD widGetPos(WORD wDevID, LPMMTIME lpTime, UINT size)
2283 DWORD val;
2284 WINE_WAVEIN* wwi;
2286 TRACE("(%u);\n", wDevID);
2287 if (wDevID >= MAX_WAVEINDRV)
2289 WARN("invalid device ID\n");
2290 return MMSYSERR_INVALHANDLE;
2293 wwi = &WInDev[wDevID];
2295 OSSpinLockLock(&WInDev[wDevID].lock);
2296 val = wwi->dwTotalRecorded;
2297 OSSpinLockUnlock(&WInDev[wDevID].lock);
2299 return bytes_to_mmtime(lpTime, val, &wwi->format);
2302 /**************************************************************************
2303 * widReset [internal]
2305 static DWORD widReset(WORD wDevID)
2307 DWORD ret = MMSYSERR_NOERROR;
2308 WINE_WAVEIN* wwi;
2309 WAVEHDR* lpWaveHdr = NULL;
2311 TRACE("(%u);\n", wDevID);
2312 if (wDevID >= MAX_WAVEINDRV)
2314 WARN("invalid device ID\n");
2315 return MMSYSERR_INVALHANDLE;
2318 wwi = &WInDev[wDevID];
2319 OSSpinLockLock(&wwi->lock);
2321 if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2323 WARN("Trying to reset a closed device.\n");
2324 ret = MMSYSERR_INVALHANDLE;
2326 else
2328 lpWaveHdr = wwi->lpQueuePtr;
2329 wwi->lpQueuePtr = NULL;
2330 wwi->state = WINE_WS_STOPPED;
2331 wwi->dwTotalRecorded = 0;
2334 OSSpinLockUnlock(&wwi->lock);
2336 if (ret == MMSYSERR_NOERROR)
2338 OSStatus err = AudioOutputUnitStop(wwi->audioUnit);
2339 if (err != noErr)
2340 WARN("Failed to stop AU: %08lx\n", err);
2342 TRACE("Recording stopped.\n");
2345 while (lpWaveHdr)
2347 WAVEHDR* lpNext = lpWaveHdr->lpNext;
2349 lpWaveHdr->lpNext = NULL;
2350 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2351 lpWaveHdr->dwFlags |= WHDR_DONE;
2352 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2354 lpWaveHdr = lpNext;
2357 return ret;
2361 /**************************************************************************
2362 * widGetNumDevs [internal]
2364 static DWORD widGetNumDevs(void)
2366 return MAX_WAVEINDRV;
2370 /**************************************************************************
2371 * widDevInterfaceSize [internal]
2373 static DWORD widDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
2375 TRACE("(%u, %p)\n", wDevID, dwParam1);
2377 *dwParam1 = MultiByteToWideChar(CP_UNIXCP, 0, WInDev[wDevID].interface_name, -1,
2378 NULL, 0 ) * sizeof(WCHAR);
2379 return MMSYSERR_NOERROR;
2383 /**************************************************************************
2384 * widDevInterface [internal]
2386 static DWORD widDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
2388 if (dwParam2 >= MultiByteToWideChar(CP_UNIXCP, 0, WInDev[wDevID].interface_name, -1,
2389 NULL, 0 ) * sizeof(WCHAR))
2391 MultiByteToWideChar(CP_UNIXCP, 0, WInDev[wDevID].interface_name, -1,
2392 dwParam1, dwParam2 / sizeof(WCHAR));
2393 return MMSYSERR_NOERROR;
2395 return MMSYSERR_INVALPARAM;
2399 /**************************************************************************
2400 * widDsCreate [internal]
2402 static DWORD widDsCreate(UINT wDevID, PIDSCDRIVER* drv)
2404 TRACE("(%d,%p)\n",wDevID,drv);
2406 FIXME("DirectSoundCapture not implemented\n");
2407 FIXME("The (slower) DirectSound HEL mode will be used instead.\n");
2408 return MMSYSERR_NOTSUPPORTED;
2411 /**************************************************************************
2412 * widDsDesc [internal]
2414 static DWORD widDsDesc(UINT wDevID, PDSDRIVERDESC desc)
2416 /* The DirectSound HEL will automatically wrap a non-DirectSound-capable
2417 * driver in a DirectSound adaptor, thus allowing the driver to be used by
2418 * DirectSound clients. However, it only does this if we respond
2419 * successfully to the DRV_QUERYDSOUNDDESC message. It's enough to fill in
2420 * the driver and device names of the description output parameter. */
2421 memset(desc, 0, sizeof(*desc));
2422 lstrcpynA(desc->szDrvname, "winecoreaudio.drv", sizeof(desc->szDrvname) - 1);
2423 lstrcpynA(desc->szDesc, WInDev[wDevID].interface_name, sizeof(desc->szDesc) - 1);
2424 return MMSYSERR_NOERROR;
2428 /**************************************************************************
2429 * widMessage (WINECOREAUDIO.6)
2431 DWORD WINAPI CoreAudio_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2432 DWORD dwParam1, DWORD dwParam2)
2434 TRACE("(%u, %04X, %08X, %08X, %08X);\n",
2435 wDevID, wMsg, dwUser, dwParam1, dwParam2);
2437 switch (wMsg)
2439 case DRVM_INIT:
2440 case DRVM_EXIT:
2441 case DRVM_ENABLE:
2442 case DRVM_DISABLE:
2443 /* FIXME: Pretend this is supported */
2444 return 0;
2445 case WIDM_OPEN: return widOpen (wDevID, (LPWAVEOPENDESC)dwParam1, dwParam2);
2446 case WIDM_CLOSE: return widClose (wDevID);
2447 case WIDM_ADDBUFFER: return widAddBuffer (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2448 case WIDM_PREPARE: return MMSYSERR_NOTSUPPORTED;
2449 case WIDM_UNPREPARE: return MMSYSERR_NOTSUPPORTED;
2450 case WIDM_GETDEVCAPS: return widGetDevCaps (wDevID, (LPWAVEINCAPSW)dwParam1, dwParam2);
2451 case WIDM_GETNUMDEVS: return widGetNumDevs ();
2452 case WIDM_RESET: return widReset (wDevID);
2453 case WIDM_START: return widStart (wDevID);
2454 case WIDM_STOP: return widStop (wDevID);
2455 case WIDM_GETPOS: return widGetPos (wDevID, (LPMMTIME)dwParam1, (UINT)dwParam2 );
2456 case DRV_QUERYDEVICEINTERFACESIZE: return widDevInterfaceSize (wDevID, (LPDWORD)dwParam1);
2457 case DRV_QUERYDEVICEINTERFACE: return widDevInterface (wDevID, (PWCHAR)dwParam1, dwParam2);
2458 case DRV_QUERYDSOUNDIFACE: return widDsCreate (wDevID, (PIDSCDRIVER*)dwParam1);
2459 case DRV_QUERYDSOUNDDESC: return widDsDesc (wDevID, (PDSDRIVERDESC)dwParam1);
2460 default:
2461 FIXME("unknown message %d!\n", wMsg);
2464 return MMSYSERR_NOTSUPPORTED;
2468 OSStatus CoreAudio_wiAudioUnitIOProc(void *inRefCon,
2469 AudioUnitRenderActionFlags *ioActionFlags,
2470 const AudioTimeStamp *inTimeStamp,
2471 UInt32 inBusNumber,
2472 UInt32 inNumberFrames,
2473 AudioBufferList *ioData)
2475 WINE_WAVEIN* wwi = (WINE_WAVEIN*)inRefCon;
2476 OSStatus err = noErr;
2477 BOOL needNotify = FALSE;
2478 WAVEHDR* lpStorePtr;
2479 unsigned int dataToStore;
2480 unsigned int dataStored = 0;
2483 if (wwi->trace_on)
2484 fprintf(stderr, "trace:wave:CoreAudio_wiAudioUnitIOProc (ioActionFlags = %08lx, "
2485 "inTimeStamp = { %f, %x%08x, %f, %x%08x, %08lx }, inBusNumber = %lu, inNumberFrames = %lu)\n",
2486 *ioActionFlags, inTimeStamp->mSampleTime, (DWORD)(inTimeStamp->mHostTime >>32),
2487 (DWORD)inTimeStamp->mHostTime, inTimeStamp->mRateScalar, (DWORD)(inTimeStamp->mWordClockTime >> 32),
2488 (DWORD)inTimeStamp->mWordClockTime, inTimeStamp->mFlags, inBusNumber, inNumberFrames);
2490 /* Render into audio buffer */
2491 /* FIXME: implement sample rate conversion on input. This will require
2492 * a different render strategy. We'll need to buffer the sound data
2493 * received here and pass it off to an AUConverter in another thread. */
2494 err = AudioUnitRender(wwi->audioUnit, ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, wwi->bufferList);
2495 if (err)
2497 if (wwi->err_on)
2498 fprintf(stderr, "err:wave:CoreAudio_wiAudioUnitIOProc AudioUnitRender failed with error %li\n", err);
2499 return err;
2502 /* Copy from audio buffer to the wavehdrs */
2503 dataToStore = wwi->bufferList->mBuffers[0].mDataByteSize;
2505 OSSpinLockLock(&wwi->lock);
2507 lpStorePtr = wwi->lpQueuePtr;
2509 /* We might have been called while the waveIn device is being closed in
2510 * widClose. We have to do nothing in that case. The check of wwi->state
2511 * below ensures that. */
2512 while (dataToStore > 0 && wwi->state == WINE_WS_PLAYING && lpStorePtr)
2514 unsigned int room = lpStorePtr->dwBufferLength - lpStorePtr->dwBytesRecorded;
2515 unsigned int toCopy;
2517 if (wwi->trace_on)
2518 fprintf(stderr, "trace:wave:CoreAudio_wiAudioUnitIOProc Looking to store %u bytes to wavehdr %p, which has room for %u\n",
2519 dataToStore, lpStorePtr, room);
2521 if (room >= dataToStore)
2522 toCopy = dataToStore;
2523 else
2524 toCopy = room;
2526 if (toCopy > 0)
2528 memcpy(lpStorePtr->lpData + lpStorePtr->dwBytesRecorded,
2529 (char*)wwi->bufferList->mBuffers[0].mData + dataStored, toCopy);
2530 lpStorePtr->dwBytesRecorded += toCopy;
2531 wwi->dwTotalRecorded += toCopy;
2532 dataStored += toCopy;
2533 dataToStore -= toCopy;
2534 room -= toCopy;
2537 if (room == 0)
2539 lpStorePtr = lpStorePtr->lpNext;
2540 needNotify = TRUE;
2544 OSSpinLockUnlock(&wwi->lock);
2546 /* Restore the audio buffer list structure from backup, in case
2547 * AudioUnitRender clobbered it. (It modifies mDataByteSize and may even
2548 * give us a different mData buffer to avoid a copy.) */
2549 memcpy(wwi->bufferList, wwi->bufferListCopy, AUDIOBUFFERLISTSIZE(wwi->bufferList->mNumberBuffers));
2551 if (needNotify) wodSendNotifyInputCompletionsMessage(wwi);
2552 return err;
2555 #else
2557 /**************************************************************************
2558 * widMessage (WINECOREAUDIO.6)
2560 DWORD WINAPI CoreAudio_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2561 DWORD dwParam1, DWORD dwParam2)
2563 FIXME("(%u, %04X, %08X, %08X, %08X): CoreAudio support not compiled into wine\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2564 return MMSYSERR_NOTENABLED;
2567 /**************************************************************************
2568 * wodMessage (WINECOREAUDIO.7)
2570 DWORD WINAPI CoreAudio_wodMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2571 DWORD dwParam1, DWORD dwParam2)
2573 FIXME("(%u, %04X, %08X, %08X, %08X): CoreAudio support not compiled into wine\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2574 return MMSYSERR_NOTENABLED;
2577 #endif