winebuild: Remove Alpha support.
[wine/testsucceed.git] / dlls / winecoreaudio.drv / audio.c
blob43420b15e98186ebdd1a447fb185a9988c04e767
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);
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];
173 DWORD device_volume;
175 BOOL trace_on;
176 BOOL warn_on;
177 BOOL err_on;
179 struct list instances;
180 OSSpinLock lock; /* guards the instances list */
181 } WINE_WAVEOUT;
183 typedef struct {
184 /* This device's device number */
185 DWORD wiID;
187 /* Access to the following fields is synchronized across threads. */
188 volatile int state;
189 LPWAVEHDR lpQueuePtr;
190 DWORD dwTotalRecorded;
192 /* Synchronization mechanism to protect above fields */
193 OSSpinLock lock;
195 /* Capabilities description */
196 WAVEINCAPSW caps;
197 char interface_name[32];
199 /* Record the arguments used when opening the device. */
200 WAVEOPENDESC waveDesc;
201 WORD wFlags;
202 PCMWAVEFORMAT format;
204 AudioUnit audioUnit;
205 AudioBufferList*bufferList;
206 AudioBufferList*bufferListCopy;
208 /* Record state of debug channels at open. Used to control fprintf's since
209 * we can't use Wine debug channel calls in non-Wine AudioUnit threads. */
210 BOOL trace_on;
211 BOOL warn_on;
212 BOOL err_on;
214 /* These fields aren't used. */
215 #if 0
216 CoreAudio_Device *cadev;
218 AudioStreamBasicDescription streamDescription;
219 #endif
220 } WINE_WAVEIN;
222 static WINE_WAVEOUT WOutDev [MAX_WAVEOUTDRV];
223 static WINE_WAVEIN WInDev [MAX_WAVEINDRV];
225 static HANDLE hThread = NULL; /* Track the thread we create so we can clean it up later */
226 static CFMessagePortRef Port_SendToMessageThread;
228 static void wodHelper_PlayPtrNext(WINE_WAVEOUT_INSTANCE* wwo);
229 static void wodHelper_NotifyDoneForList(WINE_WAVEOUT_INSTANCE* wwo, LPWAVEHDR lpWaveHdr);
230 static void wodHelper_NotifyCompletions(WINE_WAVEOUT_INSTANCE* wwo, BOOL force);
231 static void widHelper_NotifyCompletions(WINE_WAVEIN* wwi);
233 extern int AudioUnit_CreateDefaultAudioUnit(void *wwo, AudioUnit *au);
234 extern int AudioUnit_CloseAudioUnit(AudioUnit au);
235 extern int AudioUnit_InitializeWithStreamDescription(AudioUnit au, AudioStreamBasicDescription *streamFormat);
237 extern OSStatus AudioOutputUnitStart(AudioUnit au);
238 extern OSStatus AudioOutputUnitStop(AudioUnit au);
239 extern OSStatus AudioUnitUninitialize(AudioUnit au);
241 extern int AudioUnit_SetVolume(AudioUnit au, float left, float right);
242 extern int AudioUnit_GetVolume(AudioUnit au, float *left, float *right);
244 extern int AudioUnit_GetInputDeviceSampleRate(void);
246 extern int AudioUnit_CreateInputUnit(void* wwi, AudioUnit* out_au,
247 WORD nChannels, DWORD nSamplesPerSec, WORD wBitsPerSample,
248 UInt32* outFrameCount);
250 OSStatus CoreAudio_woAudioUnitIOProc(void *inRefCon,
251 AudioUnitRenderActionFlags *ioActionFlags,
252 const AudioTimeStamp *inTimeStamp,
253 UInt32 inBusNumber,
254 UInt32 inNumberFrames,
255 AudioBufferList *ioData);
256 OSStatus CoreAudio_wiAudioUnitIOProc(void *inRefCon,
257 AudioUnitRenderActionFlags *ioActionFlags,
258 const AudioTimeStamp *inTimeStamp,
259 UInt32 inBusNumber,
260 UInt32 inNumberFrames,
261 AudioBufferList *ioData);
263 /* These strings used only for tracing */
265 static const char * getMessage(UINT msg)
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 return wine_dbg_sprintf("UNKNOWN(0x%04x)", msg);
311 #define kStopLoopMessage 0
312 #define kWaveOutNotifyCompletionsMessage 1
313 #define kWaveInNotifyCompletionsMessage 2
315 /* Mach Message Handling */
316 static CFDataRef wodMessageHandler(CFMessagePortRef port_ReceiveInMessageThread, SInt32 msgid, CFDataRef data, void *info)
318 UInt32 *buffer = NULL;
320 switch (msgid)
322 case kWaveOutNotifyCompletionsMessage:
323 wodHelper_NotifyCompletions(*(WINE_WAVEOUT_INSTANCE**)CFDataGetBytePtr(data), FALSE);
324 break;
325 case kWaveInNotifyCompletionsMessage:
326 buffer = (UInt32 *) CFDataGetBytePtr(data);
327 widHelper_NotifyCompletions(&WInDev[buffer[0]]);
328 break;
329 default:
330 CFRunLoopStop(CFRunLoopGetCurrent());
331 break;
334 return NULL;
337 static DWORD WINAPI messageThread(LPVOID p)
339 CFMessagePortRef port_ReceiveInMessageThread = (CFMessagePortRef) p;
340 CFRunLoopSourceRef source;
342 source = CFMessagePortCreateRunLoopSource(kCFAllocatorDefault, port_ReceiveInMessageThread, 0);
343 CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
345 CFRunLoopRun();
347 CFRunLoopSourceInvalidate(source);
348 CFRelease(source);
349 CFRelease(port_ReceiveInMessageThread);
351 return 0;
354 /**************************************************************************
355 * wodSendNotifyCompletionsMessage [internal]
356 * Call from AudioUnit IO thread can't use Wine debug channels.
358 static void wodSendNotifyCompletionsMessage(WINE_WAVEOUT_INSTANCE* wwo)
360 CFDataRef data;
362 if (!Port_SendToMessageThread)
363 return;
365 data = CFDataCreate(kCFAllocatorDefault, (UInt8 *)&wwo, sizeof(wwo));
366 if (!data)
367 return;
369 CFMessagePortSendRequest(Port_SendToMessageThread, kWaveOutNotifyCompletionsMessage, data, 0.0, 0.0, NULL, NULL);
370 CFRelease(data);
373 /**************************************************************************
374 * wodSendNotifyInputCompletionsMessage [internal]
375 * Call from AudioUnit IO thread can't use Wine debug channels.
377 static void wodSendNotifyInputCompletionsMessage(WINE_WAVEIN* wwi)
379 CFDataRef data;
380 UInt32 buffer;
382 if (!Port_SendToMessageThread)
383 return;
385 buffer = (UInt32) wwi->wiID;
387 data = CFDataCreate(kCFAllocatorDefault, (UInt8 *)&buffer, sizeof(buffer));
388 if (!data)
389 return;
391 CFMessagePortSendRequest(Port_SendToMessageThread, kWaveInNotifyCompletionsMessage, data, 0.0, 0.0, NULL, NULL);
392 CFRelease(data);
395 static DWORD bytes_to_mmtime(LPMMTIME lpTime, DWORD position,
396 PCMWAVEFORMAT* format)
398 TRACE("wType=%04X wBitsPerSample=%u nSamplesPerSec=%u nChannels=%u nAvgBytesPerSec=%u\n",
399 lpTime->wType, format->wBitsPerSample, format->wf.nSamplesPerSec,
400 format->wf.nChannels, format->wf.nAvgBytesPerSec);
401 TRACE("Position in bytes=%u\n", position);
403 switch (lpTime->wType) {
404 case TIME_SAMPLES:
405 lpTime->u.sample = position / (format->wBitsPerSample / 8 * format->wf.nChannels);
406 TRACE("TIME_SAMPLES=%u\n", lpTime->u.sample);
407 break;
408 case TIME_MS:
409 lpTime->u.ms = 1000.0 * position / (format->wBitsPerSample / 8 * format->wf.nChannels * format->wf.nSamplesPerSec);
410 TRACE("TIME_MS=%u\n", lpTime->u.ms);
411 break;
412 case TIME_SMPTE:
413 lpTime->u.smpte.fps = 30;
414 position = position / (format->wBitsPerSample / 8 * format->wf.nChannels);
415 position += (format->wf.nSamplesPerSec / lpTime->u.smpte.fps) - 1; /* round up */
416 lpTime->u.smpte.sec = position / format->wf.nSamplesPerSec;
417 position -= lpTime->u.smpte.sec * format->wf.nSamplesPerSec;
418 lpTime->u.smpte.min = lpTime->u.smpte.sec / 60;
419 lpTime->u.smpte.sec -= 60 * lpTime->u.smpte.min;
420 lpTime->u.smpte.hour = lpTime->u.smpte.min / 60;
421 lpTime->u.smpte.min -= 60 * lpTime->u.smpte.hour;
422 lpTime->u.smpte.fps = 30;
423 lpTime->u.smpte.frame = position * lpTime->u.smpte.fps / format->wf.nSamplesPerSec;
424 TRACE("TIME_SMPTE=%02u:%02u:%02u:%02u\n",
425 lpTime->u.smpte.hour, lpTime->u.smpte.min,
426 lpTime->u.smpte.sec, lpTime->u.smpte.frame);
427 break;
428 default:
429 WARN("Format %d not supported, using TIME_BYTES !\n", lpTime->wType);
430 lpTime->wType = TIME_BYTES;
431 /* fall through */
432 case TIME_BYTES:
433 lpTime->u.cb = position;
434 TRACE("TIME_BYTES=%u\n", lpTime->u.cb);
435 break;
437 return MMSYSERR_NOERROR;
440 static BOOL supportedFormat(LPWAVEFORMATEX wf)
442 if (wf->nSamplesPerSec < DSBFREQUENCY_MIN || wf->nSamplesPerSec > DSBFREQUENCY_MAX)
443 return FALSE;
445 if (wf->wFormatTag == WAVE_FORMAT_PCM) {
446 if (wf->nChannels >= 1 && wf->nChannels <= 2) {
447 if (wf->wBitsPerSample==8||wf->wBitsPerSample==16)
448 return TRUE;
450 } else if (wf->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
451 WAVEFORMATEXTENSIBLE * wfex = (WAVEFORMATEXTENSIBLE *)wf;
453 if (wf->cbSize == 22 && IsEqualGUID(&wfex->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM)) {
454 if (wf->nChannels >=1 && wf->nChannels <= 8) {
455 if (wf->wBitsPerSample==wfex->Samples.wValidBitsPerSample) {
456 if (wf->wBitsPerSample==8||wf->wBitsPerSample==16)
457 return TRUE;
458 } else
459 WARN("wBitsPerSample != wValidBitsPerSample not supported yet\n");
461 } else
462 WARN("only KSDATAFORMAT_SUBTYPE_PCM supported\n");
463 } else
464 WARN("only WAVE_FORMAT_PCM and WAVE_FORMAT_EXTENSIBLE supported\n");
466 return FALSE;
469 void copyFormat(LPWAVEFORMATEX wf1, LPPCMWAVEFORMAT wf2)
471 memcpy(wf2, wf1, sizeof(PCMWAVEFORMAT));
472 /* Downgrade WAVE_FORMAT_EXTENSIBLE KSDATAFORMAT_SUBTYPE_PCM
473 * to smaller yet compatible WAVE_FORMAT_PCM structure */
474 if (wf2->wf.wFormatTag == WAVE_FORMAT_EXTENSIBLE)
475 wf2->wf.wFormatTag = WAVE_FORMAT_PCM;
478 /**************************************************************************
479 * CoreAudio_GetDevCaps [internal]
481 BOOL CoreAudio_GetDevCaps (void)
483 OSStatus status;
484 UInt32 propertySize;
485 AudioDeviceID devId = CoreAudio_DefaultDevice.outputDeviceID;
486 AudioObjectPropertyAddress propertyAddress;
488 CFStringRef name;
489 CFRange range;
491 propertySize = sizeof(name);
492 propertyAddress.mSelector = kAudioObjectPropertyName;
493 propertyAddress.mScope = kAudioDevicePropertyScopeOutput;
494 propertyAddress.mElement = kAudioObjectPropertyElementMaster;
495 status = AudioObjectGetPropertyData(devId, &propertyAddress, 0, NULL, &propertySize, &name);
496 if (status) {
497 ERR("AudioObjectGetPropertyData for kAudioObjectPropertyName return %s\n", wine_dbgstr_fourcc(status));
498 return FALSE;
501 CFStringGetCString(name, CoreAudio_DefaultDevice.ds_desc.szDesc,
502 sizeof(CoreAudio_DefaultDevice.ds_desc.szDesc),
503 kCFStringEncodingUTF8);
504 strcpy(CoreAudio_DefaultDevice.ds_desc.szDrvname, "winecoreaudio.drv");
505 range = CFRangeMake(0, min(sizeof(CoreAudio_DefaultDevice.out_caps.szPname) / sizeof(WCHAR) - 1, CFStringGetLength(name)));
506 CFStringGetCharacters(name, range, CoreAudio_DefaultDevice.out_caps.szPname);
507 CoreAudio_DefaultDevice.out_caps.szPname[range.length] = 0;
508 CFStringGetCString(name, CoreAudio_DefaultDevice.dev_name, 32, kCFStringEncodingUTF8);
509 CFRelease(name);
511 propertySize = sizeof(CoreAudio_DefaultDevice.streamDescription);
512 /* FIXME: kAudioDevicePropertyStreamFormat is deprecated. We're
513 * "supposed" to get an AudioStream object from the AudioDevice,
514 * then query it for the format with kAudioStreamPropertyVirtualFormat.
515 * Apple says that this is for our own good, because this property
516 * "has been shown to lead to programming mistakes by clients when
517 * working with devices with multiple streams." Only one problem:
518 * which stream? For now, just query the device.
520 propertyAddress.mSelector = kAudioDevicePropertyStreamFormat;
521 status = AudioObjectGetPropertyData(devId, &propertyAddress, 0, NULL, &propertySize, &CoreAudio_DefaultDevice.streamDescription);
522 if (status != noErr) {
523 ERR("AudioObjectGetPropertyData for kAudioDevicePropertyStreamFormat return %s\n", wine_dbgstr_fourcc(status));
524 return FALSE;
527 TRACE("Device Stream Description mSampleRate : %f\n mFormatID : %s\n"
528 "mFormatFlags : %lX\n mBytesPerPacket : %lu\n mFramesPerPacket : %lu\n"
529 "mBytesPerFrame : %lu\n mChannelsPerFrame : %lu\n mBitsPerChannel : %lu\n",
530 CoreAudio_DefaultDevice.streamDescription.mSampleRate,
531 wine_dbgstr_fourcc(CoreAudio_DefaultDevice.streamDescription.mFormatID),
532 CoreAudio_DefaultDevice.streamDescription.mFormatFlags,
533 CoreAudio_DefaultDevice.streamDescription.mBytesPerPacket,
534 CoreAudio_DefaultDevice.streamDescription.mFramesPerPacket,
535 CoreAudio_DefaultDevice.streamDescription.mBytesPerFrame,
536 CoreAudio_DefaultDevice.streamDescription.mChannelsPerFrame,
537 CoreAudio_DefaultDevice.streamDescription.mBitsPerChannel);
539 CoreAudio_DefaultDevice.out_caps.wMid = 0xcafe;
540 CoreAudio_DefaultDevice.out_caps.wPid = 0x0001;
542 CoreAudio_DefaultDevice.out_caps.vDriverVersion = 0x0001;
543 CoreAudio_DefaultDevice.out_caps.dwFormats = 0x00000000;
544 CoreAudio_DefaultDevice.out_caps.wReserved1 = 0;
545 CoreAudio_DefaultDevice.out_caps.dwSupport = WAVECAPS_VOLUME;
546 CoreAudio_DefaultDevice.out_caps.dwSupport |= WAVECAPS_LRVOLUME;
548 CoreAudio_DefaultDevice.out_caps.wChannels = 2;
549 CoreAudio_DefaultDevice.out_caps.dwFormats|= WAVE_FORMAT_4S16;
551 TRACE_(coreaudio)("out dwFormats = %08x, dwSupport = %08x\n",
552 CoreAudio_DefaultDevice.out_caps.dwFormats, CoreAudio_DefaultDevice.out_caps.dwSupport);
554 return TRUE;
557 /******************************************************************
558 * CoreAudio_WaveInit
560 * Initialize CoreAudio_DefaultDevice
562 LONG CoreAudio_WaveInit(void)
564 OSStatus status;
565 UInt32 propertySize;
566 AudioObjectPropertyAddress propertyAddress;
567 int i;
568 CFStringRef messageThreadPortName;
569 CFMessagePortRef port_ReceiveInMessageThread;
570 int inputSampleRate;
572 TRACE("()\n");
574 /* number of sound cards */
575 propertyAddress.mSelector = kAudioHardwarePropertyDevices;
576 propertyAddress.mScope = kAudioObjectPropertyScopeGlobal;
577 propertyAddress.mElement = kAudioObjectPropertyElementMaster;
578 AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &propertyAddress, 0, NULL, &propertySize);
579 propertySize /= sizeof(AudioDeviceID);
580 TRACE("sound cards : %lu\n", propertySize);
582 /* Get the output device */
583 propertySize = sizeof(CoreAudio_DefaultDevice.outputDeviceID);
584 propertyAddress.mSelector = kAudioHardwarePropertyDefaultOutputDevice;
585 status = AudioObjectGetPropertyData(kAudioObjectSystemObject, &propertyAddress, 0, NULL, &propertySize, &CoreAudio_DefaultDevice.outputDeviceID);
586 if (status) {
587 ERR("AudioObjectGetPropertyData return %s for kAudioHardwarePropertyDefaultOutputDevice\n", wine_dbgstr_fourcc(status));
588 return DRV_FAILURE;
590 if (CoreAudio_DefaultDevice.outputDeviceID == kAudioDeviceUnknown) {
591 ERR("AudioObjectGetPropertyData: CoreAudio_DefaultDevice.outputDeviceID == kAudioDeviceUnknown\n");
592 return DRV_FAILURE;
595 if ( ! CoreAudio_GetDevCaps() )
596 return DRV_FAILURE;
598 CoreAudio_DefaultDevice.interface_name=HeapAlloc(GetProcessHeap(),0,strlen(CoreAudio_DefaultDevice.dev_name)+1);
599 strcpy(CoreAudio_DefaultDevice.interface_name, CoreAudio_DefaultDevice.dev_name);
601 for (i = 0; i < MAX_WAVEOUTDRV; ++i)
603 static const WCHAR wszWaveOutFormat[] =
604 {'C','o','r','e','A','u','d','i','o',' ','W','a','v','e','O','u','t',' ','%','d',0};
606 list_init(&WOutDev[i].instances);
607 WOutDev[i].cadev = &CoreAudio_DefaultDevice;
609 memset(&WOutDev[i].caps, 0, sizeof(WOutDev[i].caps));
611 WOutDev[i].caps.wMid = 0xcafe; /* Manufac ID */
612 WOutDev[i].caps.wPid = 0x0001; /* Product ID */
613 snprintfW(WOutDev[i].caps.szPname, sizeof(WOutDev[i].caps.szPname)/sizeof(WCHAR), wszWaveOutFormat, i);
614 snprintf(WOutDev[i].interface_name, sizeof(WOutDev[i].interface_name), "winecoreaudio: %d", i);
616 WOutDev[i].caps.vDriverVersion = 0x0001;
617 WOutDev[i].caps.dwFormats = 0x00000000;
618 WOutDev[i].caps.dwSupport = WAVECAPS_VOLUME;
620 WOutDev[i].caps.wChannels = 2;
621 /* WOutDev[i].caps.dwSupport |= WAVECAPS_LRVOLUME; */ /* FIXME */
623 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96M08;
624 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96S08;
625 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96M16;
626 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96S16;
627 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48M08;
628 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48S08;
629 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48M16;
630 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48S16;
631 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4M08;
632 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4S08;
633 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4S16;
634 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4M16;
635 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2M08;
636 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2S08;
637 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2M16;
638 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2S16;
639 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1M08;
640 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1S08;
641 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1M16;
642 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1S16;
644 WOutDev[i].device_volume = 0xffffffff;
646 WOutDev[i].lock = 0; /* initialize the mutex */
649 /* FIXME: implement sample rate conversion on input */
650 inputSampleRate = AudioUnit_GetInputDeviceSampleRate();
652 for (i = 0; i < MAX_WAVEINDRV; ++i)
654 static const WCHAR wszWaveInFormat[] =
655 {'C','o','r','e','A','u','d','i','o',' ','W','a','v','e','I','n',' ','%','d',0};
657 memset(&WInDev[i], 0, sizeof(WInDev[i]));
658 WInDev[i].wiID = i;
660 /* Establish preconditions for widOpen */
661 WInDev[i].state = WINE_WS_CLOSED;
662 WInDev[i].lock = 0; /* initialize the mutex */
664 /* Fill in capabilities. widGetDevCaps can be called at any time. */
665 WInDev[i].caps.wMid = 0xcafe; /* Manufac ID */
666 WInDev[i].caps.wPid = 0x0001; /* Product ID */
667 WInDev[i].caps.vDriverVersion = 0x0001;
669 snprintfW(WInDev[i].caps.szPname, sizeof(WInDev[i].caps.szPname)/sizeof(WCHAR), wszWaveInFormat, i);
670 snprintf(WInDev[i].interface_name, sizeof(WInDev[i].interface_name), "winecoreaudio in: %d", i);
672 if (inputSampleRate == 96000)
674 WInDev[i].caps.dwFormats |= WAVE_FORMAT_96M08;
675 WInDev[i].caps.dwFormats |= WAVE_FORMAT_96S08;
676 WInDev[i].caps.dwFormats |= WAVE_FORMAT_96M16;
677 WInDev[i].caps.dwFormats |= WAVE_FORMAT_96S16;
679 if (inputSampleRate == 48000)
681 WInDev[i].caps.dwFormats |= WAVE_FORMAT_48M08;
682 WInDev[i].caps.dwFormats |= WAVE_FORMAT_48S08;
683 WInDev[i].caps.dwFormats |= WAVE_FORMAT_48M16;
684 WInDev[i].caps.dwFormats |= WAVE_FORMAT_48S16;
686 if (inputSampleRate == 44100)
688 WInDev[i].caps.dwFormats |= WAVE_FORMAT_4M08;
689 WInDev[i].caps.dwFormats |= WAVE_FORMAT_4S08;
690 WInDev[i].caps.dwFormats |= WAVE_FORMAT_4M16;
691 WInDev[i].caps.dwFormats |= WAVE_FORMAT_4S16;
693 if (inputSampleRate == 22050)
695 WInDev[i].caps.dwFormats |= WAVE_FORMAT_2M08;
696 WInDev[i].caps.dwFormats |= WAVE_FORMAT_2S08;
697 WInDev[i].caps.dwFormats |= WAVE_FORMAT_2M16;
698 WInDev[i].caps.dwFormats |= WAVE_FORMAT_2S16;
700 if (inputSampleRate == 11025)
702 WInDev[i].caps.dwFormats |= WAVE_FORMAT_1M08;
703 WInDev[i].caps.dwFormats |= WAVE_FORMAT_1S08;
704 WInDev[i].caps.dwFormats |= WAVE_FORMAT_1M16;
705 WInDev[i].caps.dwFormats |= WAVE_FORMAT_1S16;
708 WInDev[i].caps.wChannels = 2;
711 /* create mach messages handler */
712 srandomdev();
713 messageThreadPortName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL,
714 CFSTR("WaveMessagePort.%d.%lu"), getpid(), (unsigned long)random());
715 if (!messageThreadPortName)
717 ERR("Can't create message thread port name\n");
718 return DRV_FAILURE;
721 port_ReceiveInMessageThread = CFMessagePortCreateLocal(kCFAllocatorDefault, messageThreadPortName,
722 &wodMessageHandler, NULL, NULL);
723 if (!port_ReceiveInMessageThread)
725 ERR("Can't create message thread local port\n");
726 CFRelease(messageThreadPortName);
727 return DRV_FAILURE;
730 Port_SendToMessageThread = CFMessagePortCreateRemote(kCFAllocatorDefault, messageThreadPortName);
731 CFRelease(messageThreadPortName);
732 if (!Port_SendToMessageThread)
734 ERR("Can't create port for sending to message thread\n");
735 CFRelease(port_ReceiveInMessageThread);
736 return DRV_FAILURE;
739 /* Cannot WAIT for any events because we are called from the loader (which has a lock on loading stuff) */
740 /* We might want to wait for this thread to be created -- but we cannot -- not here at least */
741 /* Instead track the thread so we can clean it up later */
742 if ( hThread )
744 ERR("Message thread already started -- expect problems\n");
746 hThread = CreateThread(NULL, 0, messageThread, (LPVOID)port_ReceiveInMessageThread, 0, NULL);
747 if ( !hThread )
749 ERR("Can't create message thread\n");
750 CFRelease(port_ReceiveInMessageThread);
751 CFRelease(Port_SendToMessageThread);
752 Port_SendToMessageThread = NULL;
753 return DRV_FAILURE;
756 /* The message thread is responsible for releasing port_ReceiveInMessageThread. */
758 return DRV_SUCCESS;
761 void CoreAudio_WaveRelease(void)
763 /* Stop CFRunLoop in messageThread */
764 TRACE("()\n");
766 if (!Port_SendToMessageThread)
767 return;
769 CFMessagePortSendRequest(Port_SendToMessageThread, kStopLoopMessage, NULL, 0.0, 0.0, NULL, NULL);
770 CFRelease(Port_SendToMessageThread);
771 Port_SendToMessageThread = NULL;
773 /* Wait for the thread to finish and clean it up */
774 /* This rids us of any quick start/shutdown driver crashes */
775 WaitForSingleObject(hThread, INFINITE);
776 CloseHandle(hThread);
777 hThread = NULL;
780 /*======================================================================*
781 * Low level WAVE OUT implementation *
782 *======================================================================*/
784 /**************************************************************************
785 * wodNotifyClient [internal]
787 static void wodNotifyClient(WINE_WAVEOUT_INSTANCE* wwo, WORD wMsg, DWORD_PTR dwParam1, DWORD_PTR dwParam2)
789 TRACE("wMsg = 0x%04x dwParm1 = %04lx dwParam2 = %04lx\n", wMsg, dwParam1, dwParam2);
791 switch (wMsg) {
792 case WOM_OPEN:
793 case WOM_CLOSE:
794 case WOM_DONE:
795 DriverCallback(wwo->waveDesc.dwCallback, wwo->wFlags,
796 (HDRVR)wwo->waveDesc.hWave, wMsg, wwo->waveDesc.dwInstance,
797 dwParam1, dwParam2);
798 break;
799 default:
800 FIXME("Unknown callback message %u\n", wMsg);
805 /**************************************************************************
806 * wodGetDevCaps [internal]
808 static DWORD wodGetDevCaps(WORD wDevID, LPWAVEOUTCAPSW lpCaps, DWORD dwSize)
810 TRACE("(%u, %p, %u);\n", wDevID, lpCaps, dwSize);
812 if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
814 if (wDevID >= MAX_WAVEOUTDRV)
816 TRACE("MAX_WAVOUTDRV reached !\n");
817 return MMSYSERR_BADDEVICEID;
820 TRACE("dwSupport=(0x%x), dwFormats=(0x%x)\n", WOutDev[wDevID].caps.dwSupport, WOutDev[wDevID].caps.dwFormats);
821 memcpy(lpCaps, &WOutDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
822 return MMSYSERR_NOERROR;
825 /**************************************************************************
826 * wodOpen [internal]
828 static DWORD wodOpen(WORD wDevID, WINE_WAVEOUT_INSTANCE** pInstance, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
830 WINE_WAVEOUT_INSTANCE* wwo;
831 DWORD ret;
832 AudioStreamBasicDescription streamFormat;
833 AudioUnit audioUnit = NULL;
834 BOOL auInited = FALSE;
836 TRACE("(%u, %p, %p, %08x);\n", wDevID, pInstance, lpDesc, dwFlags);
837 if (lpDesc == NULL)
839 WARN("Invalid Parameter !\n");
840 return MMSYSERR_INVALPARAM;
842 if (wDevID >= MAX_WAVEOUTDRV) {
843 TRACE("MAX_WAVOUTDRV reached !\n");
844 return MMSYSERR_BADDEVICEID;
847 TRACE("Format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
848 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
849 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
851 if (!supportedFormat(lpDesc->lpFormat))
853 WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
854 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
855 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
856 return WAVERR_BADFORMAT;
859 if (dwFlags & WAVE_FORMAT_QUERY)
861 TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
862 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
863 lpDesc->lpFormat->nSamplesPerSec);
864 return MMSYSERR_NOERROR;
867 /* nBlockAlign and nAvgBytesPerSec are output variables for dsound */
868 if (lpDesc->lpFormat->nBlockAlign != lpDesc->lpFormat->nChannels*lpDesc->lpFormat->wBitsPerSample/8) {
869 lpDesc->lpFormat->nBlockAlign = lpDesc->lpFormat->nChannels*lpDesc->lpFormat->wBitsPerSample/8;
870 WARN("Fixing nBlockAlign\n");
872 if (lpDesc->lpFormat->nAvgBytesPerSec!= lpDesc->lpFormat->nSamplesPerSec*lpDesc->lpFormat->nBlockAlign) {
873 lpDesc->lpFormat->nAvgBytesPerSec = lpDesc->lpFormat->nSamplesPerSec*lpDesc->lpFormat->nBlockAlign;
874 WARN("Fixing nAvgBytesPerSec\n");
877 /* We proceed in three phases:
878 * o Allocate the device instance, marking it as opening
879 * o Create, configure, and start the Audio Unit. To avoid deadlock,
880 * this has to be done without holding wwo->lock.
881 * o If that was successful, finish setting up our instance and add it
882 * to the device's list.
883 * Otherwise, clean up and deallocate the instance.
885 wwo = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*wwo));
886 if (!wwo)
887 return MMSYSERR_NOMEM;
889 wwo->woID = wDevID;
890 wwo->state = WINE_WS_OPENING;
892 if (!AudioUnit_CreateDefaultAudioUnit((void *) wwo, &audioUnit))
894 ERR("CoreAudio_CreateDefaultAudioUnit(0x%04x) failed\n", wDevID);
895 ret = MMSYSERR_ERROR;
896 goto error;
899 streamFormat.mFormatID = kAudioFormatLinearPCM;
900 streamFormat.mFormatFlags = kLinearPCMFormatFlagIsPacked;
901 /* FIXME check for 32bits float -> kLinearPCMFormatFlagIsFloat */
902 if (lpDesc->lpFormat->wBitsPerSample != 8)
903 streamFormat.mFormatFlags |= kLinearPCMFormatFlagIsSignedInteger;
904 # ifdef WORDS_BIGENDIAN
905 streamFormat.mFormatFlags |= kLinearPCMFormatFlagIsBigEndian; /* FIXME Wave format is little endian */
906 # endif
908 streamFormat.mSampleRate = lpDesc->lpFormat->nSamplesPerSec;
909 streamFormat.mChannelsPerFrame = lpDesc->lpFormat->nChannels;
910 streamFormat.mFramesPerPacket = 1;
911 streamFormat.mBitsPerChannel = lpDesc->lpFormat->wBitsPerSample;
912 streamFormat.mBytesPerFrame = streamFormat.mBitsPerChannel * streamFormat.mChannelsPerFrame / 8;
913 streamFormat.mBytesPerPacket = streamFormat.mBytesPerFrame * streamFormat.mFramesPerPacket;
915 ret = AudioUnit_InitializeWithStreamDescription(audioUnit, &streamFormat);
916 if (!ret)
918 ret = WAVERR_BADFORMAT; /* FIXME return an error based on the OSStatus */
919 goto error;
921 auInited = TRUE;
923 AudioUnit_SetVolume(audioUnit, LOWORD(WOutDev[wDevID].device_volume) / 65535.0f,
924 HIWORD(WOutDev[wDevID].device_volume) / 65535.0f);
926 /* Our render callback CoreAudio_woAudioUnitIOProc may be called before
927 * AudioOutputUnitStart returns. Core Audio will grab its own internal
928 * lock before calling it and the callback grabs wwo->lock. This would
929 * deadlock if we were holding wwo->lock.
930 * Also, the callback has to safely do nothing in that case, because
931 * wwo hasn't been completely filled out, yet. This is assured by state
932 * being WINE_WS_OPENING. */
933 ret = AudioOutputUnitStart(audioUnit);
934 if (ret)
936 ERR("AudioOutputUnitStart failed: %08x\n", ret);
937 ret = MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
938 goto error;
942 OSSpinLockLock(&wwo->lock);
943 assert(wwo->state == WINE_WS_OPENING);
945 wwo->audioUnit = audioUnit;
946 wwo->streamDescription = streamFormat;
948 wwo->state = WINE_WS_PLAYING;
950 wwo->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
952 wwo->waveDesc = *lpDesc;
953 copyFormat(lpDesc->lpFormat, &wwo->format);
955 WOutDev[wDevID].trace_on = TRACE_ON(wave);
956 WOutDev[wDevID].warn_on = WARN_ON(wave);
957 WOutDev[wDevID].err_on = ERR_ON(wave);
959 OSSpinLockUnlock(&wwo->lock);
961 OSSpinLockLock(&WOutDev[wDevID].lock);
962 list_add_head(&WOutDev[wDevID].instances, &wwo->entry);
963 OSSpinLockUnlock(&WOutDev[wDevID].lock);
965 *pInstance = wwo;
966 TRACE("opened instance %p\n", wwo);
968 wodNotifyClient(wwo, WOM_OPEN, 0L, 0L);
970 return MMSYSERR_NOERROR;
972 error:
973 if (audioUnit)
975 if (auInited)
976 AudioUnitUninitialize(audioUnit);
977 AudioUnit_CloseAudioUnit(audioUnit);
980 OSSpinLockLock(&wwo->lock);
981 assert(wwo->state == WINE_WS_OPENING);
982 /* OSSpinLockUnlock(&wwo->lock); *//* No need, about to free */
983 HeapFree(GetProcessHeap(), 0, wwo);
985 return ret;
988 /**************************************************************************
989 * wodClose [internal]
991 static DWORD wodClose(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo)
993 DWORD ret = MMSYSERR_NOERROR;
995 TRACE("(%u, %p);\n", wDevID, wwo);
997 if (wDevID >= MAX_WAVEOUTDRV)
999 WARN("bad device ID !\n");
1000 return MMSYSERR_BADDEVICEID;
1003 OSSpinLockLock(&wwo->lock);
1004 if (wwo->lpQueuePtr)
1006 OSSpinLockUnlock(&wwo->lock);
1007 WARN("buffers still playing !\n");
1008 return WAVERR_STILLPLAYING;
1009 } else
1011 OSStatus err;
1012 AudioUnit audioUnit = wwo->audioUnit;
1014 /* sanity check: this should not happen since the device must have been reset before */
1015 if (wwo->lpQueuePtr || wwo->lpPlayPtr) ERR("out of sync\n");
1017 wwo->state = WINE_WS_CLOSING; /* mark the device as closing */
1018 wwo->audioUnit = NULL;
1020 OSSpinLockUnlock(&wwo->lock);
1022 err = AudioUnitUninitialize(audioUnit);
1023 if (err) {
1024 ERR("AudioUnitUninitialize return %s\n", wine_dbgstr_fourcc(err));
1025 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1028 if ( !AudioUnit_CloseAudioUnit(audioUnit) )
1030 ERR("Can't close AudioUnit\n");
1031 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1034 OSSpinLockLock(&WOutDev[wDevID].lock);
1035 list_remove(&wwo->entry);
1036 OSSpinLockUnlock(&WOutDev[wDevID].lock);
1038 wodNotifyClient(wwo, WOM_CLOSE, 0L, 0L);
1040 HeapFree(GetProcessHeap(), 0, wwo);
1043 return ret;
1046 /**************************************************************************
1047 * wodPrepare [internal]
1049 static DWORD wodPrepare(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1051 TRACE("(%u, %p, %p, %08x);\n", wDevID, wwo, lpWaveHdr, dwSize);
1053 if (wDevID >= MAX_WAVEOUTDRV) {
1054 WARN("bad device ID !\n");
1055 return MMSYSERR_BADDEVICEID;
1058 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1059 return WAVERR_STILLPLAYING;
1061 lpWaveHdr->dwFlags |= WHDR_PREPARED;
1062 lpWaveHdr->dwFlags &= ~WHDR_DONE;
1064 return MMSYSERR_NOERROR;
1067 /**************************************************************************
1068 * wodUnprepare [internal]
1070 static DWORD wodUnprepare(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1072 TRACE("(%u, %p, %p, %08x);\n", wDevID, wwo, lpWaveHdr, dwSize);
1074 if (wDevID >= MAX_WAVEOUTDRV) {
1075 WARN("bad device ID !\n");
1076 return MMSYSERR_BADDEVICEID;
1079 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1080 return WAVERR_STILLPLAYING;
1082 lpWaveHdr->dwFlags &= ~WHDR_PREPARED;
1083 lpWaveHdr->dwFlags |= WHDR_DONE;
1085 return MMSYSERR_NOERROR;
1089 /**************************************************************************
1090 * wodHelper_CheckForLoopBegin [internal]
1092 * Check if the new waveheader is the beginning of a loop, and set up
1093 * state if so.
1094 * This is called with the WAVEOUT_INSTANCE lock held.
1095 * Call from AudioUnit IO thread can't use Wine debug channels.
1097 static void wodHelper_CheckForLoopBegin(WINE_WAVEOUT_INSTANCE* wwo)
1099 LPWAVEHDR lpWaveHdr = wwo->lpPlayPtr;
1101 if (lpWaveHdr->dwFlags & WHDR_BEGINLOOP)
1103 if (wwo->lpLoopPtr)
1105 if (WOutDev[wwo->woID].warn_on)
1106 fprintf(stderr, "warn:winecoreaudio:wodHelper_CheckForLoopBegin Already in a loop. Discarding loop on this header (%p)\n", lpWaveHdr);
1108 else
1110 if (WOutDev[wwo->woID].trace_on)
1111 fprintf(stderr, "trace:winecoreaudio:wodHelper_CheckForLoopBegin Starting loop (%dx) with %p\n", lpWaveHdr->dwLoops, lpWaveHdr);
1113 wwo->lpLoopPtr = lpWaveHdr;
1114 /* Windows does not touch WAVEHDR.dwLoops,
1115 * so we need to make an internal copy */
1116 wwo->dwLoops = lpWaveHdr->dwLoops;
1122 /**************************************************************************
1123 * wodHelper_PlayPtrNext [internal]
1125 * Advance the play pointer to the next waveheader, looping if required.
1126 * This is called with the WAVEOUT_INSTANCE lock held.
1127 * Call from AudioUnit IO thread can't use Wine debug channels.
1129 static void wodHelper_PlayPtrNext(WINE_WAVEOUT_INSTANCE* wwo)
1131 BOOL didLoopBack = FALSE;
1133 wwo->dwPartialOffset = 0;
1134 if ((wwo->lpPlayPtr->dwFlags & WHDR_ENDLOOP) && wwo->lpLoopPtr)
1136 /* We're at the end of a loop, loop if required */
1137 if (wwo->dwLoops > 1)
1139 wwo->dwLoops--;
1140 wwo->lpPlayPtr = wwo->lpLoopPtr;
1141 didLoopBack = TRUE;
1143 else
1145 wwo->lpLoopPtr = NULL;
1148 if (!didLoopBack)
1150 /* We didn't loop back. Advance to the next wave header */
1151 wwo->lpPlayPtr = wwo->lpPlayPtr->lpNext;
1153 if (wwo->lpPlayPtr)
1154 wodHelper_CheckForLoopBegin(wwo);
1158 /* Send the "done" notification for each WAVEHDR in a list. The list must be
1159 * free-standing. It should not be part of a device instance's queue.
1160 * This function must be called with the WAVEOUT_INSTANCE lock *not* held.
1161 * Furthermore, it does not lock it, itself. That's because the callback to the
1162 * application may prompt the application to operate on the device, and we don't
1163 * want to deadlock.
1165 static void wodHelper_NotifyDoneForList(WINE_WAVEOUT_INSTANCE* wwo, LPWAVEHDR lpWaveHdr)
1167 while (lpWaveHdr)
1169 LPWAVEHDR lpNext = lpWaveHdr->lpNext;
1171 lpWaveHdr->lpNext = NULL;
1172 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1173 lpWaveHdr->dwFlags |= WHDR_DONE;
1174 wodNotifyClient(wwo, WOM_DONE, (DWORD_PTR)lpWaveHdr, 0);
1176 lpWaveHdr = lpNext;
1180 /* if force is TRUE then notify the client that all the headers were completed
1182 static void wodHelper_NotifyCompletions(WINE_WAVEOUT_INSTANCE* wwo, BOOL force)
1184 LPWAVEHDR lpFirstDoneWaveHdr = NULL;
1186 OSSpinLockLock(&wwo->lock);
1188 /* First, excise all of the done headers from the queue into
1189 * a free-standing list. */
1190 if (force)
1192 lpFirstDoneWaveHdr = wwo->lpQueuePtr;
1193 wwo->lpQueuePtr = NULL;
1195 else
1197 LPWAVEHDR lpWaveHdr;
1198 LPWAVEHDR lpLastDoneWaveHdr = NULL;
1200 /* Start from lpQueuePtr and keep notifying until:
1201 * - we hit an unwritten wavehdr
1202 * - we hit the beginning of a running loop
1203 * - we hit a wavehdr which hasn't finished playing
1205 for (
1206 lpWaveHdr = wwo->lpQueuePtr;
1207 lpWaveHdr &&
1208 lpWaveHdr != wwo->lpPlayPtr &&
1209 lpWaveHdr != wwo->lpLoopPtr;
1210 lpWaveHdr = lpWaveHdr->lpNext
1213 if (!lpFirstDoneWaveHdr)
1214 lpFirstDoneWaveHdr = lpWaveHdr;
1215 lpLastDoneWaveHdr = lpWaveHdr;
1218 if (lpLastDoneWaveHdr)
1220 wwo->lpQueuePtr = lpLastDoneWaveHdr->lpNext;
1221 lpLastDoneWaveHdr->lpNext = NULL;
1225 OSSpinLockUnlock(&wwo->lock);
1227 /* Now, send the "done" notification for each header in our list. */
1228 wodHelper_NotifyDoneForList(wwo, lpFirstDoneWaveHdr);
1232 /**************************************************************************
1233 * wodWrite [internal]
1236 static DWORD wodWrite(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1238 LPWAVEHDR*wh;
1240 TRACE("(%u, %p, %p, %lu, %08X);\n", wDevID, wwo, lpWaveHdr, (unsigned long)lpWaveHdr->dwBufferLength, dwSize);
1242 /* first, do the sanity checks... */
1243 if (wDevID >= MAX_WAVEOUTDRV)
1245 WARN("bad dev ID !\n");
1246 return MMSYSERR_BADDEVICEID;
1249 if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
1251 TRACE("unprepared\n");
1252 return WAVERR_UNPREPARED;
1255 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1257 TRACE("still playing\n");
1258 return WAVERR_STILLPLAYING;
1261 lpWaveHdr->dwFlags &= ~WHDR_DONE;
1262 lpWaveHdr->dwFlags |= WHDR_INQUEUE;
1263 lpWaveHdr->lpNext = 0;
1265 OSSpinLockLock(&wwo->lock);
1266 /* insert buffer at the end of queue */
1267 for (wh = &(wwo->lpQueuePtr); *wh; wh = &((*wh)->lpNext))
1268 /* Do nothing */;
1269 *wh = lpWaveHdr;
1271 if (!wwo->lpPlayPtr)
1273 wwo->lpPlayPtr = lpWaveHdr;
1275 wodHelper_CheckForLoopBegin(wwo);
1277 wwo->dwPartialOffset = 0;
1279 OSSpinLockUnlock(&wwo->lock);
1281 return MMSYSERR_NOERROR;
1284 /**************************************************************************
1285 * wodPause [internal]
1287 static DWORD wodPause(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo)
1289 OSStatus status;
1291 TRACE("(%u, %p);!\n", wDevID, wwo);
1293 if (wDevID >= MAX_WAVEOUTDRV)
1295 WARN("bad device ID !\n");
1296 return MMSYSERR_BADDEVICEID;
1299 /* The order of the following operations is important since we can't hold
1300 * the mutex while we make an Audio Unit call. Stop the Audio Unit before
1301 * setting the PAUSED state. In wodRestart, the order is reversed. This
1302 * guarantees that we can't get into a situation where the state is
1303 * PLAYING but the Audio Unit isn't running. Although we can be in PAUSED
1304 * state with the Audio Unit still running, that's harmless because the
1305 * render callback will just produce silence.
1307 status = AudioOutputUnitStop(wwo->audioUnit);
1308 if (status)
1309 WARN("AudioOutputUnitStop return %s\n", wine_dbgstr_fourcc(status));
1311 OSSpinLockLock(&wwo->lock);
1312 if (wwo->state == WINE_WS_PLAYING)
1313 wwo->state = WINE_WS_PAUSED;
1314 OSSpinLockUnlock(&wwo->lock);
1316 return MMSYSERR_NOERROR;
1319 /**************************************************************************
1320 * wodRestart [internal]
1322 static DWORD wodRestart(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo)
1324 OSStatus status;
1326 TRACE("(%u, %p);\n", wDevID, wwo);
1328 if (wDevID >= MAX_WAVEOUTDRV )
1330 WARN("bad device ID !\n");
1331 return MMSYSERR_BADDEVICEID;
1334 /* The order of the following operations is important since we can't hold
1335 * the mutex while we make an Audio Unit call. Set the PLAYING
1336 * state before starting the Audio Unit. In wodPause, the order is
1337 * reversed. This guarantees that we can't get into a situation where
1338 * the state is PLAYING but the Audio Unit isn't running.
1339 * Although we can be in PAUSED state with the Audio Unit still running,
1340 * that's harmless because the render callback will just produce silence.
1342 OSSpinLockLock(&wwo->lock);
1343 if (wwo->state == WINE_WS_PAUSED)
1344 wwo->state = WINE_WS_PLAYING;
1345 OSSpinLockUnlock(&wwo->lock);
1347 status = AudioOutputUnitStart(wwo->audioUnit);
1348 if (status) {
1349 ERR("AudioOutputUnitStart return %s\n", wine_dbgstr_fourcc(status));
1350 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1353 return MMSYSERR_NOERROR;
1356 /**************************************************************************
1357 * wodReset [internal]
1359 static DWORD wodReset(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo)
1361 OSStatus status;
1362 LPWAVEHDR lpSavedQueuePtr;
1364 TRACE("(%u, %p);\n", wDevID, wwo);
1366 if (wDevID >= MAX_WAVEOUTDRV)
1368 WARN("bad device ID !\n");
1369 return MMSYSERR_BADDEVICEID;
1372 OSSpinLockLock(&wwo->lock);
1374 if (wwo->state == WINE_WS_CLOSING || wwo->state == WINE_WS_OPENING)
1376 OSSpinLockUnlock(&wwo->lock);
1377 WARN("resetting a closed device\n");
1378 return MMSYSERR_INVALHANDLE;
1381 lpSavedQueuePtr = wwo->lpQueuePtr;
1382 wwo->lpPlayPtr = wwo->lpQueuePtr = wwo->lpLoopPtr = NULL;
1383 wwo->state = WINE_WS_PLAYING;
1384 wwo->dwPlayedTotal = 0;
1386 wwo->dwPartialOffset = 0; /* Clear partial wavehdr */
1388 OSSpinLockUnlock(&wwo->lock);
1390 status = AudioOutputUnitStart(wwo->audioUnit);
1392 if (status) {
1393 ERR( "AudioOutputUnitStart return %s\n", wine_dbgstr_fourcc(status));
1394 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1397 /* Now, send the "done" notification for each header in our list. */
1398 /* Do this last so the reset operation is effectively complete before the
1399 * app does whatever it's going to do in response to these notifications. */
1400 wodHelper_NotifyDoneForList(wwo, lpSavedQueuePtr);
1402 return MMSYSERR_NOERROR;
1405 /**************************************************************************
1406 * wodBreakLoop [internal]
1408 static DWORD wodBreakLoop(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo)
1410 TRACE("(%u, %p);\n", wDevID, wwo);
1412 if (wDevID >= MAX_WAVEOUTDRV)
1414 WARN("bad device ID !\n");
1415 return MMSYSERR_BADDEVICEID;
1418 OSSpinLockLock(&wwo->lock);
1420 if (wwo->lpLoopPtr != NULL)
1422 /* ensure exit at end of current loop */
1423 wwo->dwLoops = 1;
1426 OSSpinLockUnlock(&wwo->lock);
1428 return MMSYSERR_NOERROR;
1431 /**************************************************************************
1432 * wodGetPosition [internal]
1434 static DWORD wodGetPosition(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, LPMMTIME lpTime, DWORD uSize)
1436 DWORD val;
1438 TRACE("(%u, %p, %p, %u);\n", wDevID, wwo, lpTime, uSize);
1440 if (wDevID >= MAX_WAVEOUTDRV)
1442 WARN("bad device ID !\n");
1443 return MMSYSERR_BADDEVICEID;
1446 /* if null pointer to time structure return error */
1447 if (lpTime == NULL) return MMSYSERR_INVALPARAM;
1449 OSSpinLockLock(&wwo->lock);
1450 val = wwo->dwPlayedTotal;
1451 OSSpinLockUnlock(&wwo->lock);
1453 return bytes_to_mmtime(lpTime, val, &wwo->format);
1456 /**************************************************************************
1457 * wodGetVolume [internal]
1459 static DWORD wodGetVolume(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, LPDWORD lpdwVol)
1461 if (wDevID >= MAX_WAVEOUTDRV)
1463 WARN("bad device ID !\n");
1464 return MMSYSERR_BADDEVICEID;
1467 TRACE("(%u, %p, %p);\n", wDevID, wwo, lpdwVol);
1469 if (wwo)
1471 float left;
1472 float right;
1474 AudioUnit_GetVolume(wwo->audioUnit, &left, &right);
1475 *lpdwVol = (WORD)(left * 0xFFFFl) + ((WORD)(right * 0xFFFFl) << 16);
1477 else
1478 *lpdwVol = WOutDev[wDevID].device_volume;
1480 return MMSYSERR_NOERROR;
1483 /**************************************************************************
1484 * wodSetVolume [internal]
1486 static DWORD wodSetVolume(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, DWORD dwParam)
1488 float left;
1489 float right;
1491 if (wDevID >= MAX_WAVEOUTDRV)
1493 WARN("bad device ID !\n");
1494 return MMSYSERR_BADDEVICEID;
1497 left = LOWORD(dwParam) / 65535.0f;
1498 right = HIWORD(dwParam) / 65535.0f;
1500 TRACE("(%u, %p, %08x);\n", wDevID, wwo, dwParam);
1502 if (wwo)
1503 AudioUnit_SetVolume(wwo->audioUnit, left, right);
1504 else
1506 OSSpinLockLock(&WOutDev[wDevID].lock);
1507 LIST_FOR_EACH_ENTRY(wwo, &WOutDev[wDevID].instances, WINE_WAVEOUT_INSTANCE, entry)
1508 AudioUnit_SetVolume(wwo->audioUnit, left, right);
1509 OSSpinLockUnlock(&WOutDev[wDevID].lock);
1511 WOutDev[wDevID].device_volume = dwParam;
1514 return MMSYSERR_NOERROR;
1517 /**************************************************************************
1518 * wodGetNumDevs [internal]
1520 static DWORD wodGetNumDevs(void)
1522 TRACE("\n");
1523 return MAX_WAVEOUTDRV;
1526 /**************************************************************************
1527 * wodDevInterfaceSize [internal]
1529 static DWORD wodDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
1531 TRACE("(%u, %p)\n", wDevID, dwParam1);
1533 *dwParam1 = MultiByteToWideChar(CP_UNIXCP, 0, WOutDev[wDevID].cadev->interface_name, -1,
1534 NULL, 0 ) * sizeof(WCHAR);
1535 return MMSYSERR_NOERROR;
1538 /**************************************************************************
1539 * wodDevInterface [internal]
1541 static DWORD wodDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
1543 TRACE("\n");
1544 if (dwParam2 >= MultiByteToWideChar(CP_UNIXCP, 0, WOutDev[wDevID].cadev->interface_name, -1,
1545 NULL, 0 ) * sizeof(WCHAR))
1547 MultiByteToWideChar(CP_UNIXCP, 0, WOutDev[wDevID].cadev->interface_name, -1,
1548 dwParam1, dwParam2 / sizeof(WCHAR));
1549 return MMSYSERR_NOERROR;
1551 return MMSYSERR_INVALPARAM;
1554 /**************************************************************************
1555 * widDsCreate [internal]
1557 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
1559 TRACE("(%d,%p)\n",wDevID,drv);
1561 FIXME("DirectSound not implemented\n");
1562 FIXME("The (slower) DirectSound HEL mode will be used instead.\n");
1563 return MMSYSERR_NOTSUPPORTED;
1566 /**************************************************************************
1567 * wodDsDesc [internal]
1569 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc)
1571 /* The DirectSound HEL will automatically wrap a non-DirectSound-capable
1572 * driver in a DirectSound adaptor, thus allowing the driver to be used by
1573 * DirectSound clients. However, it only does this if we respond
1574 * successfully to the DRV_QUERYDSOUNDDESC message. It's enough to fill in
1575 * the driver and device names of the description output parameter. */
1576 *desc = WOutDev[wDevID].cadev->ds_desc;
1577 return MMSYSERR_NOERROR;
1580 /**************************************************************************
1581 * wodMessage (WINECOREAUDIO.7)
1583 DWORD WINAPI CoreAudio_wodMessage(UINT wDevID, UINT wMsg, DWORD_PTR dwUser,
1584 DWORD_PTR dwParam1, DWORD_PTR dwParam2)
1586 WINE_WAVEOUT_INSTANCE* wwo = (WINE_WAVEOUT_INSTANCE*)dwUser;
1588 TRACE("(%u, %s, %p, %p, %p);\n",
1589 wDevID, getMessage(wMsg), (void*)dwUser, (void*)dwParam1, (void*)dwParam2);
1591 switch (wMsg) {
1592 case DRVM_INIT:
1593 case DRVM_EXIT:
1594 case DRVM_ENABLE:
1595 case DRVM_DISABLE:
1597 /* FIXME: Pretend this is supported */
1598 return 0;
1599 case WODM_OPEN: return wodOpen(wDevID, (WINE_WAVEOUT_INSTANCE**)dwUser, (LPWAVEOPENDESC) dwParam1, dwParam2);
1600 case WODM_CLOSE: return wodClose(wDevID, wwo);
1601 case WODM_WRITE: return wodWrite(wDevID, wwo, (LPWAVEHDR) dwParam1, dwParam2);
1602 case WODM_PAUSE: return wodPause(wDevID, wwo);
1603 case WODM_GETPOS: return wodGetPosition(wDevID, wwo, (LPMMTIME) dwParam1, dwParam2);
1604 case WODM_BREAKLOOP: return wodBreakLoop(wDevID, wwo);
1605 case WODM_PREPARE: return wodPrepare(wDevID, wwo, (LPWAVEHDR)dwParam1, dwParam2);
1606 case WODM_UNPREPARE: return wodUnprepare(wDevID, wwo, (LPWAVEHDR)dwParam1, dwParam2);
1608 case WODM_GETDEVCAPS: return wodGetDevCaps(wDevID, (LPWAVEOUTCAPSW) dwParam1, dwParam2);
1609 case WODM_GETNUMDEVS: return wodGetNumDevs();
1611 case WODM_GETPITCH:
1612 case WODM_SETPITCH:
1613 case WODM_GETPLAYBACKRATE:
1614 case WODM_SETPLAYBACKRATE: return MMSYSERR_NOTSUPPORTED;
1615 case WODM_GETVOLUME: return wodGetVolume(wDevID, wwo, (LPDWORD)dwParam1);
1616 case WODM_SETVOLUME: return wodSetVolume(wDevID, wwo, dwParam1);
1617 case WODM_RESTART: return wodRestart(wDevID, wwo);
1618 case WODM_RESET: return wodReset(wDevID, wwo);
1620 case DRV_QUERYDEVICEINTERFACESIZE: return wodDevInterfaceSize (wDevID, (LPDWORD)dwParam1);
1621 case DRV_QUERYDEVICEINTERFACE: return wodDevInterface (wDevID, (PWCHAR)dwParam1, dwParam2);
1622 case DRV_QUERYDSOUNDIFACE: return wodDsCreate (wDevID, (PIDSDRIVER*)dwParam1);
1623 case DRV_QUERYDSOUNDDESC: return wodDsDesc (wDevID, (PDSDRIVERDESC)dwParam1);
1625 default:
1626 FIXME("unknown message %d!\n", wMsg);
1629 return MMSYSERR_NOTSUPPORTED;
1632 /*======================================================================*
1633 * Low level DSOUND implementation *
1634 *======================================================================*/
1636 typedef struct IDsDriverImpl IDsDriverImpl;
1637 typedef struct IDsDriverBufferImpl IDsDriverBufferImpl;
1639 struct IDsDriverImpl
1641 /* IUnknown fields */
1642 const IDsDriverVtbl *lpVtbl;
1643 DWORD ref;
1644 /* IDsDriverImpl fields */
1645 UINT wDevID;
1646 IDsDriverBufferImpl*primary;
1649 struct IDsDriverBufferImpl
1651 /* IUnknown fields */
1652 const IDsDriverBufferVtbl *lpVtbl;
1653 DWORD ref;
1654 /* IDsDriverBufferImpl fields */
1655 IDsDriverImpl* drv;
1656 DWORD buflen;
1661 CoreAudio IO threaded callback,
1662 we can't call Wine debug channels, critical section or anything using NtCurrentTeb here.
1664 OSStatus CoreAudio_woAudioUnitIOProc(void *inRefCon,
1665 AudioUnitRenderActionFlags *ioActionFlags,
1666 const AudioTimeStamp *inTimeStamp,
1667 UInt32 inBusNumber,
1668 UInt32 inNumberFrames,
1669 AudioBufferList *ioData)
1671 UInt32 buffer;
1672 WINE_WAVEOUT_INSTANCE* wwo = (WINE_WAVEOUT_INSTANCE*)inRefCon;
1673 int needNotify = 0;
1675 unsigned int dataNeeded = ioData->mBuffers[0].mDataByteSize;
1676 unsigned int dataProvided = 0;
1678 OSSpinLockLock(&wwo->lock);
1680 /* We might have been called before wwo has been completely filled out by
1681 * wodOpen, or while it's being closed in wodClose. We have to do nothing
1682 * in that case. The check of wwo->state below ensures that. */
1683 while (dataNeeded > 0 && wwo->state == WINE_WS_PLAYING && wwo->lpPlayPtr)
1685 unsigned int available = wwo->lpPlayPtr->dwBufferLength - wwo->dwPartialOffset;
1686 unsigned int toCopy;
1688 if (available >= dataNeeded)
1689 toCopy = dataNeeded;
1690 else
1691 toCopy = available;
1693 if (toCopy > 0)
1695 memcpy((char*)ioData->mBuffers[0].mData + dataProvided,
1696 wwo->lpPlayPtr->lpData + wwo->dwPartialOffset, toCopy);
1697 wwo->dwPartialOffset += toCopy;
1698 wwo->dwPlayedTotal += toCopy;
1699 dataProvided += toCopy;
1700 dataNeeded -= toCopy;
1701 available -= toCopy;
1704 if (available == 0)
1706 wodHelper_PlayPtrNext(wwo);
1707 needNotify = 1;
1710 ioData->mBuffers[0].mDataByteSize = dataProvided;
1712 OSSpinLockUnlock(&wwo->lock);
1714 /* We can't provide any more wave data. Fill the rest with silence. */
1715 if (dataNeeded > 0)
1717 if (!dataProvided)
1718 *ioActionFlags |= kAudioUnitRenderAction_OutputIsSilence;
1719 memset((char*)ioData->mBuffers[0].mData + dataProvided, 0, dataNeeded);
1720 dataProvided += dataNeeded;
1721 dataNeeded = 0;
1724 /* We only fill buffer 0. Set any others that might be requested to 0. */
1725 for (buffer = 1; buffer < ioData->mNumberBuffers; buffer++)
1727 memset(ioData->mBuffers[buffer].mData, 0, ioData->mBuffers[buffer].mDataByteSize);
1730 if (needNotify) wodSendNotifyCompletionsMessage(wwo);
1731 return noErr;
1735 /*======================================================================*
1736 * Low level WAVE IN implementation *
1737 *======================================================================*/
1739 /**************************************************************************
1740 * widNotifyClient [internal]
1742 static void widNotifyClient(WINE_WAVEIN* wwi, WORD wMsg, DWORD_PTR dwParam1, DWORD_PTR dwParam2)
1744 TRACE("wMsg = 0x%04x dwParm1 = %04lX dwParam2 = %04lX\n", wMsg, dwParam1, dwParam2);
1746 switch (wMsg)
1748 case WIM_OPEN:
1749 case WIM_CLOSE:
1750 case WIM_DATA:
1751 DriverCallback(wwi->waveDesc.dwCallback, wwi->wFlags,
1752 (HDRVR)wwi->waveDesc.hWave, wMsg, wwi->waveDesc.dwInstance,
1753 dwParam1, dwParam2);
1754 break;
1755 default:
1756 FIXME("Unknown callback message %u\n", wMsg);
1761 /**************************************************************************
1762 * widHelper_NotifyCompletions [internal]
1764 static void widHelper_NotifyCompletions(WINE_WAVEIN* wwi)
1766 LPWAVEHDR lpWaveHdr;
1767 LPWAVEHDR lpFirstDoneWaveHdr = NULL;
1768 LPWAVEHDR lpLastDoneWaveHdr = NULL;
1770 OSSpinLockLock(&wwi->lock);
1772 /* First, excise all of the done headers from the queue into
1773 * a free-standing list. */
1775 /* Start from lpQueuePtr and keep notifying until:
1776 * - we hit an unfilled wavehdr
1777 * - we hit the end of the list
1779 for (
1780 lpWaveHdr = wwi->lpQueuePtr;
1781 lpWaveHdr &&
1782 lpWaveHdr->dwBytesRecorded >= lpWaveHdr->dwBufferLength;
1783 lpWaveHdr = lpWaveHdr->lpNext
1786 if (!lpFirstDoneWaveHdr)
1787 lpFirstDoneWaveHdr = lpWaveHdr;
1788 lpLastDoneWaveHdr = lpWaveHdr;
1791 if (lpLastDoneWaveHdr)
1793 wwi->lpQueuePtr = lpLastDoneWaveHdr->lpNext;
1794 lpLastDoneWaveHdr->lpNext = NULL;
1797 OSSpinLockUnlock(&wwi->lock);
1799 /* Now, send the "done" notification for each header in our list. */
1800 lpWaveHdr = lpFirstDoneWaveHdr;
1801 while (lpWaveHdr)
1803 LPWAVEHDR lpNext = lpWaveHdr->lpNext;
1805 lpWaveHdr->lpNext = NULL;
1806 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1807 lpWaveHdr->dwFlags |= WHDR_DONE;
1808 widNotifyClient(wwi, WIM_DATA, (DWORD_PTR)lpWaveHdr, 0);
1810 lpWaveHdr = lpNext;
1815 /**************************************************************************
1816 * widGetDevCaps [internal]
1818 static DWORD widGetDevCaps(WORD wDevID, LPWAVEINCAPSW lpCaps, DWORD dwSize)
1820 TRACE("(%u, %p, %u);\n", wDevID, lpCaps, dwSize);
1822 if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
1824 if (wDevID >= MAX_WAVEINDRV)
1826 TRACE("MAX_WAVEINDRV reached !\n");
1827 return MMSYSERR_BADDEVICEID;
1830 memcpy(lpCaps, &WInDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
1831 return MMSYSERR_NOERROR;
1835 /**************************************************************************
1836 * widHelper_DestroyAudioBufferList [internal]
1837 * Convenience function to dispose of our audio buffers
1839 static void widHelper_DestroyAudioBufferList(AudioBufferList* list)
1841 if (list)
1843 UInt32 i;
1844 for (i = 0; i < list->mNumberBuffers; i++)
1846 if (list->mBuffers[i].mData)
1847 HeapFree(GetProcessHeap(), 0, list->mBuffers[i].mData);
1849 HeapFree(GetProcessHeap(), 0, list);
1854 #define AUDIOBUFFERLISTSIZE(numBuffers) (offsetof(AudioBufferList, mBuffers) + (numBuffers) * sizeof(AudioBuffer))
1856 /**************************************************************************
1857 * widHelper_AllocateAudioBufferList [internal]
1858 * Convenience function to allocate our audio buffers
1860 static AudioBufferList* widHelper_AllocateAudioBufferList(UInt32 numChannels, UInt32 bitsPerChannel, UInt32 bufferFrames, BOOL interleaved)
1862 UInt32 numBuffers;
1863 UInt32 channelsPerFrame;
1864 UInt32 bytesPerFrame;
1865 UInt32 bytesPerBuffer;
1866 AudioBufferList* list;
1867 UInt32 i;
1869 if (interleaved)
1871 /* For interleaved audio, we allocate one buffer for all channels. */
1872 numBuffers = 1;
1873 channelsPerFrame = numChannels;
1875 else
1877 numBuffers = numChannels;
1878 channelsPerFrame = 1;
1881 bytesPerFrame = bitsPerChannel * channelsPerFrame / 8;
1882 bytesPerBuffer = bytesPerFrame * bufferFrames;
1884 list = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, AUDIOBUFFERLISTSIZE(numBuffers));
1885 if (list == NULL)
1886 return NULL;
1888 list->mNumberBuffers = numBuffers;
1889 for (i = 0; i < numBuffers; ++i)
1891 list->mBuffers[i].mNumberChannels = channelsPerFrame;
1892 list->mBuffers[i].mDataByteSize = bytesPerBuffer;
1893 list->mBuffers[i].mData = HeapAlloc(GetProcessHeap(), 0, bytesPerBuffer);
1894 if (list->mBuffers[i].mData == NULL)
1896 widHelper_DestroyAudioBufferList(list);
1897 return NULL;
1900 return list;
1904 /**************************************************************************
1905 * widOpen [internal]
1907 static DWORD widOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
1909 WINE_WAVEIN* wwi;
1910 UInt32 frameCount;
1912 TRACE("(%u, %p, %08X);\n", wDevID, lpDesc, dwFlags);
1913 if (lpDesc == NULL)
1915 WARN("Invalid Parameter !\n");
1916 return MMSYSERR_INVALPARAM;
1918 if (wDevID >= MAX_WAVEINDRV)
1920 TRACE ("MAX_WAVEINDRV reached !\n");
1921 return MMSYSERR_BADDEVICEID;
1924 TRACE("Format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
1925 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1926 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
1928 if (!supportedFormat(lpDesc->lpFormat) ||
1929 lpDesc->lpFormat->nSamplesPerSec != AudioUnit_GetInputDeviceSampleRate()
1932 WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
1933 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1934 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
1935 return WAVERR_BADFORMAT;
1938 if (dwFlags & WAVE_FORMAT_QUERY)
1940 TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
1941 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1942 lpDesc->lpFormat->nSamplesPerSec);
1943 return MMSYSERR_NOERROR;
1946 /* nBlockAlign and nAvgBytesPerSec are output variables for dsound */
1947 if (lpDesc->lpFormat->nBlockAlign != lpDesc->lpFormat->nChannels*lpDesc->lpFormat->wBitsPerSample/8) {
1948 lpDesc->lpFormat->nBlockAlign = lpDesc->lpFormat->nChannels*lpDesc->lpFormat->wBitsPerSample/8;
1949 WARN("Fixing nBlockAlign\n");
1951 if (lpDesc->lpFormat->nAvgBytesPerSec!= lpDesc->lpFormat->nSamplesPerSec*lpDesc->lpFormat->nBlockAlign) {
1952 lpDesc->lpFormat->nAvgBytesPerSec = lpDesc->lpFormat->nSamplesPerSec*lpDesc->lpFormat->nBlockAlign;
1953 WARN("Fixing nAvgBytesPerSec\n");
1956 wwi = &WInDev[wDevID];
1957 if (!OSSpinLockTry(&wwi->lock))
1958 return MMSYSERR_ALLOCATED;
1960 if (wwi->state != WINE_WS_CLOSED)
1962 OSSpinLockUnlock(&wwi->lock);
1963 return MMSYSERR_ALLOCATED;
1966 wwi->state = WINE_WS_STOPPED;
1967 wwi->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
1969 wwi->waveDesc = *lpDesc;
1970 copyFormat(lpDesc->lpFormat, &wwi->format);
1972 wwi->dwTotalRecorded = 0;
1974 wwi->trace_on = TRACE_ON(wave);
1975 wwi->warn_on = WARN_ON(wave);
1976 wwi->err_on = ERR_ON(wave);
1978 if (!AudioUnit_CreateInputUnit(wwi, &wwi->audioUnit,
1979 wwi->format.wf.nChannels, wwi->format.wf.nSamplesPerSec,
1980 wwi->format.wBitsPerSample, &frameCount))
1982 OSSpinLockUnlock(&wwi->lock);
1983 ERR("AudioUnit_CreateInputUnit failed\n");
1984 return MMSYSERR_ERROR;
1987 /* Allocate our audio buffers */
1988 wwi->bufferList = widHelper_AllocateAudioBufferList(wwi->format.wf.nChannels,
1989 wwi->format.wBitsPerSample, frameCount, TRUE);
1990 if (wwi->bufferList == NULL)
1992 AudioUnitUninitialize(wwi->audioUnit);
1993 AudioUnit_CloseAudioUnit(wwi->audioUnit);
1994 OSSpinLockUnlock(&wwi->lock);
1995 ERR("Failed to allocate buffer list\n");
1996 return MMSYSERR_NOMEM;
1999 /* Keep a copy of the buffer list structure (but not the buffers themselves)
2000 * in case AudioUnitRender clobbers the original, as it tends to do. */
2001 wwi->bufferListCopy = HeapAlloc(GetProcessHeap(), 0, AUDIOBUFFERLISTSIZE(wwi->bufferList->mNumberBuffers));
2002 if (wwi->bufferListCopy == NULL)
2004 widHelper_DestroyAudioBufferList(wwi->bufferList);
2005 AudioUnitUninitialize(wwi->audioUnit);
2006 AudioUnit_CloseAudioUnit(wwi->audioUnit);
2007 OSSpinLockUnlock(&wwi->lock);
2008 ERR("Failed to allocate buffer list copy\n");
2009 return MMSYSERR_NOMEM;
2011 memcpy(wwi->bufferListCopy, wwi->bufferList, AUDIOBUFFERLISTSIZE(wwi->bufferList->mNumberBuffers));
2013 OSSpinLockUnlock(&wwi->lock);
2015 widNotifyClient(wwi, WIM_OPEN, 0L, 0L);
2017 return MMSYSERR_NOERROR;
2021 /**************************************************************************
2022 * widClose [internal]
2024 static DWORD widClose(WORD wDevID)
2026 DWORD ret = MMSYSERR_NOERROR;
2027 WINE_WAVEIN* wwi;
2028 OSStatus err;
2030 TRACE("(%u);\n", wDevID);
2032 if (wDevID >= MAX_WAVEINDRV)
2034 WARN("bad device ID !\n");
2035 return MMSYSERR_BADDEVICEID;
2038 wwi = &WInDev[wDevID];
2039 OSSpinLockLock(&wwi->lock);
2040 if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2042 WARN("Device already closed.\n");
2043 ret = MMSYSERR_INVALHANDLE;
2045 else if (wwi->lpQueuePtr)
2047 WARN("Buffers in queue.\n");
2048 ret = WAVERR_STILLPLAYING;
2050 else
2052 wwi->state = WINE_WS_CLOSING;
2055 OSSpinLockUnlock(&wwi->lock);
2057 if (ret != MMSYSERR_NOERROR)
2058 return ret;
2061 /* Clean up and close the audio unit. This has to be done without
2062 * wwi->lock being held to avoid deadlock. AudioUnitUninitialize will
2063 * grab an internal Core Audio lock while waiting for the device work
2064 * thread to exit. Meanwhile the device work thread may be holding
2065 * that lock and trying to grab the wwi->lock in the callback. */
2066 err = AudioUnitUninitialize(wwi->audioUnit);
2067 if (err)
2068 ERR("AudioUnitUninitialize return %s\n", wine_dbgstr_fourcc(err));
2070 if (!AudioUnit_CloseAudioUnit(wwi->audioUnit))
2071 ERR("Can't close AudioUnit\n");
2074 OSSpinLockLock(&wwi->lock);
2075 assert(wwi->state == WINE_WS_CLOSING);
2077 /* Dellocate our audio buffers */
2078 widHelper_DestroyAudioBufferList(wwi->bufferList);
2079 wwi->bufferList = NULL;
2080 HeapFree(GetProcessHeap(), 0, wwi->bufferListCopy);
2081 wwi->bufferListCopy = NULL;
2083 wwi->audioUnit = NULL;
2084 wwi->state = WINE_WS_CLOSED;
2085 OSSpinLockUnlock(&wwi->lock);
2087 widNotifyClient(wwi, WIM_CLOSE, 0L, 0L);
2089 return ret;
2093 /**************************************************************************
2094 * widAddBuffer [internal]
2096 static DWORD widAddBuffer(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
2098 DWORD ret = MMSYSERR_NOERROR;
2099 WINE_WAVEIN* wwi;
2101 TRACE("(%u, %p, %08X);\n", wDevID, lpWaveHdr, dwSize);
2103 if (wDevID >= MAX_WAVEINDRV)
2105 WARN("invalid device ID\n");
2106 return MMSYSERR_INVALHANDLE;
2108 if (!(lpWaveHdr->dwFlags & WHDR_PREPARED))
2110 TRACE("never been prepared !\n");
2111 return WAVERR_UNPREPARED;
2113 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
2115 TRACE("header already in use !\n");
2116 return WAVERR_STILLPLAYING;
2119 wwi = &WInDev[wDevID];
2120 OSSpinLockLock(&wwi->lock);
2122 if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2124 WARN("Trying to add buffer to closed device.\n");
2125 ret = MMSYSERR_INVALHANDLE;
2127 else
2129 LPWAVEHDR* wh;
2131 lpWaveHdr->dwFlags |= WHDR_INQUEUE;
2132 lpWaveHdr->dwFlags &= ~WHDR_DONE;
2133 lpWaveHdr->dwBytesRecorded = 0;
2134 lpWaveHdr->lpNext = NULL;
2136 /* insert buffer at end of queue */
2137 for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext))
2138 /* Do nothing */;
2139 *wh = lpWaveHdr;
2142 OSSpinLockUnlock(&wwi->lock);
2144 return ret;
2148 /**************************************************************************
2149 * widStart [internal]
2151 static DWORD widStart(WORD wDevID)
2153 DWORD ret = MMSYSERR_NOERROR;
2154 WINE_WAVEIN* wwi;
2156 TRACE("(%u);\n", wDevID);
2157 if (wDevID >= MAX_WAVEINDRV)
2159 WARN("invalid device ID\n");
2160 return MMSYSERR_INVALHANDLE;
2163 /* The order of the following operations is important since we can't hold
2164 * the mutex while we make an Audio Unit call. Set the PLAYING state
2165 * before starting the Audio Unit. In widStop, the order is reversed.
2166 * This guarantees that we can't get into a situation where the state is
2167 * PLAYING but the Audio Unit isn't running. Although we can be in STOPPED
2168 * state with the Audio Unit still running, that's harmless because the
2169 * input callback will just throw away the sound data.
2171 wwi = &WInDev[wDevID];
2172 OSSpinLockLock(&wwi->lock);
2174 if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2176 WARN("Trying to start closed device.\n");
2177 ret = MMSYSERR_INVALHANDLE;
2179 else
2180 wwi->state = WINE_WS_PLAYING;
2182 OSSpinLockUnlock(&wwi->lock);
2184 if (ret == MMSYSERR_NOERROR)
2186 /* Start pulling for audio data */
2187 OSStatus err = AudioOutputUnitStart(wwi->audioUnit);
2188 if (err != noErr)
2189 ERR("Failed to start AU: %08lx\n", err);
2191 TRACE("Recording started...\n");
2194 return ret;
2198 /**************************************************************************
2199 * widStop [internal]
2201 static DWORD widStop(WORD wDevID)
2203 DWORD ret = MMSYSERR_NOERROR;
2204 WINE_WAVEIN* wwi;
2205 WAVEHDR* lpWaveHdr = NULL;
2206 OSStatus err;
2208 TRACE("(%u);\n", wDevID);
2209 if (wDevID >= MAX_WAVEINDRV)
2211 WARN("invalid device ID\n");
2212 return MMSYSERR_INVALHANDLE;
2215 wwi = &WInDev[wDevID];
2217 /* The order of the following operations is important since we can't hold
2218 * the mutex while we make an Audio Unit call. Stop the Audio Unit before
2219 * setting the STOPPED state. In widStart, the order is reversed. This
2220 * guarantees that we can't get into a situation where the state is
2221 * PLAYING but the Audio Unit isn't running. Although we can be in STOPPED
2222 * state with the Audio Unit still running, that's harmless because the
2223 * input callback will just throw away the sound data.
2225 err = AudioOutputUnitStop(wwi->audioUnit);
2226 if (err != noErr)
2227 WARN("Failed to stop AU: %08lx\n", err);
2229 TRACE("Recording stopped.\n");
2231 OSSpinLockLock(&wwi->lock);
2233 if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2235 WARN("Trying to stop closed device.\n");
2236 ret = MMSYSERR_INVALHANDLE;
2238 else if (wwi->state != WINE_WS_STOPPED)
2240 wwi->state = WINE_WS_STOPPED;
2241 /* If there's a buffer in progress, it's done. Remove it from the
2242 * queue so that we can return it to the app, below. */
2243 if (wwi->lpQueuePtr)
2245 lpWaveHdr = wwi->lpQueuePtr;
2246 wwi->lpQueuePtr = lpWaveHdr->lpNext;
2250 OSSpinLockUnlock(&wwi->lock);
2252 if (lpWaveHdr)
2254 lpWaveHdr->lpNext = NULL;
2255 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2256 lpWaveHdr->dwFlags |= WHDR_DONE;
2257 widNotifyClient(wwi, WIM_DATA, (DWORD_PTR)lpWaveHdr, 0);
2260 return ret;
2263 /**************************************************************************
2264 * widGetPos [internal]
2266 static DWORD widGetPos(WORD wDevID, LPMMTIME lpTime, UINT size)
2268 DWORD val;
2269 WINE_WAVEIN* wwi;
2271 TRACE("(%u);\n", wDevID);
2272 if (wDevID >= MAX_WAVEINDRV)
2274 WARN("invalid device ID\n");
2275 return MMSYSERR_INVALHANDLE;
2278 wwi = &WInDev[wDevID];
2280 OSSpinLockLock(&WInDev[wDevID].lock);
2281 val = wwi->dwTotalRecorded;
2282 OSSpinLockUnlock(&WInDev[wDevID].lock);
2284 return bytes_to_mmtime(lpTime, val, &wwi->format);
2287 /**************************************************************************
2288 * widReset [internal]
2290 static DWORD widReset(WORD wDevID)
2292 DWORD ret = MMSYSERR_NOERROR;
2293 WINE_WAVEIN* wwi;
2294 WAVEHDR* lpWaveHdr = NULL;
2296 TRACE("(%u);\n", wDevID);
2297 if (wDevID >= MAX_WAVEINDRV)
2299 WARN("invalid device ID\n");
2300 return MMSYSERR_INVALHANDLE;
2303 wwi = &WInDev[wDevID];
2304 OSSpinLockLock(&wwi->lock);
2306 if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2308 WARN("Trying to reset a closed device.\n");
2309 ret = MMSYSERR_INVALHANDLE;
2311 else
2313 lpWaveHdr = wwi->lpQueuePtr;
2314 wwi->lpQueuePtr = NULL;
2315 wwi->state = WINE_WS_STOPPED;
2316 wwi->dwTotalRecorded = 0;
2319 OSSpinLockUnlock(&wwi->lock);
2321 if (ret == MMSYSERR_NOERROR)
2323 OSStatus err = AudioOutputUnitStop(wwi->audioUnit);
2324 if (err != noErr)
2325 WARN("Failed to stop AU: %08lx\n", err);
2327 TRACE("Recording stopped.\n");
2330 while (lpWaveHdr)
2332 WAVEHDR* lpNext = lpWaveHdr->lpNext;
2334 lpWaveHdr->lpNext = NULL;
2335 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2336 lpWaveHdr->dwFlags |= WHDR_DONE;
2337 widNotifyClient(wwi, WIM_DATA, (DWORD_PTR)lpWaveHdr, 0);
2339 lpWaveHdr = lpNext;
2342 return ret;
2346 /**************************************************************************
2347 * widGetNumDevs [internal]
2349 static DWORD widGetNumDevs(void)
2351 return MAX_WAVEINDRV;
2355 /**************************************************************************
2356 * widDevInterfaceSize [internal]
2358 static DWORD widDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
2360 TRACE("(%u, %p)\n", wDevID, dwParam1);
2362 *dwParam1 = MultiByteToWideChar(CP_UNIXCP, 0, WInDev[wDevID].interface_name, -1,
2363 NULL, 0 ) * sizeof(WCHAR);
2364 return MMSYSERR_NOERROR;
2368 /**************************************************************************
2369 * widDevInterface [internal]
2371 static DWORD widDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
2373 if (dwParam2 >= MultiByteToWideChar(CP_UNIXCP, 0, WInDev[wDevID].interface_name, -1,
2374 NULL, 0 ) * sizeof(WCHAR))
2376 MultiByteToWideChar(CP_UNIXCP, 0, WInDev[wDevID].interface_name, -1,
2377 dwParam1, dwParam2 / sizeof(WCHAR));
2378 return MMSYSERR_NOERROR;
2380 return MMSYSERR_INVALPARAM;
2384 /**************************************************************************
2385 * widDsCreate [internal]
2387 static DWORD widDsCreate(UINT wDevID, PIDSCDRIVER* drv)
2389 TRACE("(%d,%p)\n",wDevID,drv);
2391 FIXME("DirectSoundCapture not implemented\n");
2392 FIXME("The (slower) DirectSound HEL mode will be used instead.\n");
2393 return MMSYSERR_NOTSUPPORTED;
2396 /**************************************************************************
2397 * widDsDesc [internal]
2399 static DWORD widDsDesc(UINT wDevID, PDSDRIVERDESC desc)
2401 /* The DirectSound HEL will automatically wrap a non-DirectSound-capable
2402 * driver in a DirectSound adaptor, thus allowing the driver to be used by
2403 * DirectSound clients. However, it only does this if we respond
2404 * successfully to the DRV_QUERYDSOUNDDESC message. It's enough to fill in
2405 * the driver and device names of the description output parameter. */
2406 memset(desc, 0, sizeof(*desc));
2407 lstrcpynA(desc->szDrvname, "winecoreaudio.drv", sizeof(desc->szDrvname) - 1);
2408 lstrcpynA(desc->szDesc, WInDev[wDevID].interface_name, sizeof(desc->szDesc) - 1);
2409 return MMSYSERR_NOERROR;
2413 /**************************************************************************
2414 * widMessage (WINECOREAUDIO.6)
2416 DWORD WINAPI CoreAudio_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2417 DWORD dwParam1, DWORD dwParam2)
2419 TRACE("(%u, %04X, %08X, %08X, %08X);\n",
2420 wDevID, wMsg, dwUser, dwParam1, dwParam2);
2422 switch (wMsg)
2424 case DRVM_INIT:
2425 case DRVM_EXIT:
2426 case DRVM_ENABLE:
2427 case DRVM_DISABLE:
2428 /* FIXME: Pretend this is supported */
2429 return 0;
2430 case WIDM_OPEN: return widOpen (wDevID, (LPWAVEOPENDESC)dwParam1, dwParam2);
2431 case WIDM_CLOSE: return widClose (wDevID);
2432 case WIDM_ADDBUFFER: return widAddBuffer (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2433 case WIDM_PREPARE: return MMSYSERR_NOTSUPPORTED;
2434 case WIDM_UNPREPARE: return MMSYSERR_NOTSUPPORTED;
2435 case WIDM_GETDEVCAPS: return widGetDevCaps (wDevID, (LPWAVEINCAPSW)dwParam1, dwParam2);
2436 case WIDM_GETNUMDEVS: return widGetNumDevs ();
2437 case WIDM_RESET: return widReset (wDevID);
2438 case WIDM_START: return widStart (wDevID);
2439 case WIDM_STOP: return widStop (wDevID);
2440 case WIDM_GETPOS: return widGetPos (wDevID, (LPMMTIME)dwParam1, (UINT)dwParam2 );
2441 case DRV_QUERYDEVICEINTERFACESIZE: return widDevInterfaceSize (wDevID, (LPDWORD)dwParam1);
2442 case DRV_QUERYDEVICEINTERFACE: return widDevInterface (wDevID, (PWCHAR)dwParam1, dwParam2);
2443 case DRV_QUERYDSOUNDIFACE: return widDsCreate (wDevID, (PIDSCDRIVER*)dwParam1);
2444 case DRV_QUERYDSOUNDDESC: return widDsDesc (wDevID, (PDSDRIVERDESC)dwParam1);
2445 default:
2446 FIXME("unknown message %d!\n", wMsg);
2449 return MMSYSERR_NOTSUPPORTED;
2453 OSStatus CoreAudio_wiAudioUnitIOProc(void *inRefCon,
2454 AudioUnitRenderActionFlags *ioActionFlags,
2455 const AudioTimeStamp *inTimeStamp,
2456 UInt32 inBusNumber,
2457 UInt32 inNumberFrames,
2458 AudioBufferList *ioData)
2460 WINE_WAVEIN* wwi = (WINE_WAVEIN*)inRefCon;
2461 OSStatus err = noErr;
2462 BOOL needNotify = FALSE;
2463 WAVEHDR* lpStorePtr;
2464 unsigned int dataToStore;
2465 unsigned int dataStored = 0;
2468 if (wwi->trace_on)
2469 fprintf(stderr, "trace:wave:CoreAudio_wiAudioUnitIOProc (ioActionFlags = %08lx, "
2470 "inTimeStamp = { %f, %x%08x, %f, %x%08x, %08lx }, inBusNumber = %lu, inNumberFrames = %lu)\n",
2471 *ioActionFlags, inTimeStamp->mSampleTime, (DWORD)(inTimeStamp->mHostTime >>32),
2472 (DWORD)inTimeStamp->mHostTime, inTimeStamp->mRateScalar, (DWORD)(inTimeStamp->mWordClockTime >> 32),
2473 (DWORD)inTimeStamp->mWordClockTime, inTimeStamp->mFlags, inBusNumber, inNumberFrames);
2475 /* Render into audio buffer */
2476 /* FIXME: implement sample rate conversion on input. This will require
2477 * a different render strategy. We'll need to buffer the sound data
2478 * received here and pass it off to an AUConverter in another thread. */
2479 err = AudioUnitRender(wwi->audioUnit, ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, wwi->bufferList);
2480 if (err)
2482 if (wwi->err_on)
2483 fprintf(stderr, "err:wave:CoreAudio_wiAudioUnitIOProc AudioUnitRender failed with error %li\n", err);
2484 return err;
2487 /* Copy from audio buffer to the wavehdrs */
2488 dataToStore = wwi->bufferList->mBuffers[0].mDataByteSize;
2490 OSSpinLockLock(&wwi->lock);
2492 lpStorePtr = wwi->lpQueuePtr;
2494 /* We might have been called while the waveIn device is being closed in
2495 * widClose. We have to do nothing in that case. The check of wwi->state
2496 * below ensures that. */
2497 while (dataToStore > 0 && wwi->state == WINE_WS_PLAYING && lpStorePtr)
2499 unsigned int room = lpStorePtr->dwBufferLength - lpStorePtr->dwBytesRecorded;
2500 unsigned int toCopy;
2502 if (wwi->trace_on)
2503 fprintf(stderr, "trace:wave:CoreAudio_wiAudioUnitIOProc Looking to store %u bytes to wavehdr %p, which has room for %u\n",
2504 dataToStore, lpStorePtr, room);
2506 if (room >= dataToStore)
2507 toCopy = dataToStore;
2508 else
2509 toCopy = room;
2511 if (toCopy > 0)
2513 memcpy(lpStorePtr->lpData + lpStorePtr->dwBytesRecorded,
2514 (char*)wwi->bufferList->mBuffers[0].mData + dataStored, toCopy);
2515 lpStorePtr->dwBytesRecorded += toCopy;
2516 wwi->dwTotalRecorded += toCopy;
2517 dataStored += toCopy;
2518 dataToStore -= toCopy;
2519 room -= toCopy;
2522 if (room == 0)
2524 lpStorePtr = lpStorePtr->lpNext;
2525 needNotify = TRUE;
2529 OSSpinLockUnlock(&wwi->lock);
2531 /* Restore the audio buffer list structure from backup, in case
2532 * AudioUnitRender clobbered it. (It modifies mDataByteSize and may even
2533 * give us a different mData buffer to avoid a copy.) */
2534 memcpy(wwi->bufferList, wwi->bufferListCopy, AUDIOBUFFERLISTSIZE(wwi->bufferList->mNumberBuffers));
2536 if (needNotify) wodSendNotifyInputCompletionsMessage(wwi);
2537 return err;