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
49 #include "coreaudio.h"
50 #include "wine/unicode.h"
51 #include "wine/library.h"
52 #include "wine/debug.h"
53 #include "wine/list.h"
55 WINE_DEFAULT_DEBUG_CHANNEL(wave);
57 #if defined(HAVE_COREAUDIO_COREAUDIO_H) && defined(HAVE_AUDIOUNIT_AUDIOUNIT_H)
58 #include <CoreAudio/CoreAudio.h>
59 #include <CoreFoundation/CoreFoundation.h>
60 #include <libkern/OSAtomic.h>
62 WINE_DECLARE_DEBUG_CHANNEL(coreaudio);
65 Due to AudioUnit headers conflict define some needed types.
68 typedef void *AudioUnit;
70 /* From AudioUnit/AUComponents.h */
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 {
119 char* interface_name;
121 WAVEOUTCAPSW out_caps;
123 DWORD in_caps_support;
127 unsigned audio_fragment;
129 BOOL bTriggerSupport;
132 DSDRIVERDESC ds_desc;
133 DSDRIVERCAPS ds_caps;
134 DSCDRIVERCAPS dsc_caps;
138 AudioDeviceID outputDeviceID;
139 AudioDeviceID inputDeviceID;
140 AudioStreamBasicDescription streamDescription;
143 /* for now use the default device */
144 static CoreAudio_Device CoreAudio_DefaultDevice;
149 volatile int state; /* one of the WINE_WS_ manifest constants */
150 WAVEOPENDESC waveDesc;
152 PCMWAVEFORMAT format;
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;
170 CoreAudio_Device *cadev;
172 char interface_name[32];
179 struct list instances;
180 OSSpinLock lock; /* guards the instances list */
184 /* This device's device number */
187 /* Access to the following fields is synchronized across threads. */
189 LPWAVEHDR lpQueuePtr;
190 DWORD dwTotalRecorded;
192 /* Synchronization mechanism to protect above fields */
195 /* Capabilities description */
197 char interface_name[32];
199 /* Record the arguments used when opening the device. */
200 WAVEOPENDESC waveDesc;
202 PCMWAVEFORMAT format;
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. */
214 /* These fields aren't used. */
216 CoreAudio_Device *cadev;
218 AudioStreamBasicDescription streamDescription;
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,
254 UInt32 inNumberFrames,
255 AudioBufferList *ioData);
256 OSStatus CoreAudio_wiAudioUnitIOProc(void *inRefCon,
257 AudioUnitRenderActionFlags *ioActionFlags,
258 const AudioTimeStamp *inTimeStamp,
260 UInt32 inNumberFrames,
261 AudioBufferList *ioData);
263 /* These strings used only for tracing */
265 static const char * getMessage(UINT msg)
267 static char unknown[32];
268 #define MSG_TO_STR(x) case x: return #x
270 MSG_TO_STR(DRVM_INIT);
271 MSG_TO_STR(DRVM_EXIT);
272 MSG_TO_STR(DRVM_ENABLE);
273 MSG_TO_STR(DRVM_DISABLE);
274 MSG_TO_STR(WIDM_OPEN);
275 MSG_TO_STR(WIDM_CLOSE);
276 MSG_TO_STR(WIDM_ADDBUFFER);
277 MSG_TO_STR(WIDM_PREPARE);
278 MSG_TO_STR(WIDM_UNPREPARE);
279 MSG_TO_STR(WIDM_GETDEVCAPS);
280 MSG_TO_STR(WIDM_GETNUMDEVS);
281 MSG_TO_STR(WIDM_GETPOS);
282 MSG_TO_STR(WIDM_RESET);
283 MSG_TO_STR(WIDM_START);
284 MSG_TO_STR(WIDM_STOP);
285 MSG_TO_STR(WODM_OPEN);
286 MSG_TO_STR(WODM_CLOSE);
287 MSG_TO_STR(WODM_WRITE);
288 MSG_TO_STR(WODM_PAUSE);
289 MSG_TO_STR(WODM_GETPOS);
290 MSG_TO_STR(WODM_BREAKLOOP);
291 MSG_TO_STR(WODM_PREPARE);
292 MSG_TO_STR(WODM_UNPREPARE);
293 MSG_TO_STR(WODM_GETDEVCAPS);
294 MSG_TO_STR(WODM_GETNUMDEVS);
295 MSG_TO_STR(WODM_GETPITCH);
296 MSG_TO_STR(WODM_SETPITCH);
297 MSG_TO_STR(WODM_GETPLAYBACKRATE);
298 MSG_TO_STR(WODM_SETPLAYBACKRATE);
299 MSG_TO_STR(WODM_GETVOLUME);
300 MSG_TO_STR(WODM_SETVOLUME);
301 MSG_TO_STR(WODM_RESTART);
302 MSG_TO_STR(WODM_RESET);
303 MSG_TO_STR(DRV_QUERYDEVICEINTERFACESIZE);
304 MSG_TO_STR(DRV_QUERYDEVICEINTERFACE);
305 MSG_TO_STR(DRV_QUERYDSOUNDIFACE);
306 MSG_TO_STR(DRV_QUERYDSOUNDDESC);
309 sprintf(unknown, "UNKNOWN(0x%04x)", msg);
313 #define kStopLoopMessage 0
314 #define kWaveOutNotifyCompletionsMessage 1
315 #define kWaveInNotifyCompletionsMessage 2
317 /* Mach Message Handling */
318 static CFDataRef wodMessageHandler(CFMessagePortRef port_ReceiveInMessageThread, SInt32 msgid, CFDataRef data, void *info)
320 UInt32 *buffer = NULL;
324 case kWaveOutNotifyCompletionsMessage:
325 wodHelper_NotifyCompletions(*(WINE_WAVEOUT_INSTANCE**)CFDataGetBytePtr(data), FALSE);
327 case kWaveInNotifyCompletionsMessage:
328 buffer = (UInt32 *) CFDataGetBytePtr(data);
329 widHelper_NotifyCompletions(&WInDev[buffer[0]]);
332 CFRunLoopStop(CFRunLoopGetCurrent());
339 static DWORD WINAPI messageThread(LPVOID p)
341 CFMessagePortRef port_ReceiveInMessageThread = (CFMessagePortRef) p;
342 CFRunLoopSourceRef source;
344 source = CFMessagePortCreateRunLoopSource(kCFAllocatorDefault, port_ReceiveInMessageThread, (CFIndex)0);
345 CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
349 CFRunLoopSourceInvalidate(source);
351 CFRelease(port_ReceiveInMessageThread);
356 /**************************************************************************
357 * wodSendNotifyCompletionsMessage [internal]
358 * Call from AudioUnit IO thread can't use Wine debug channels.
360 static void wodSendNotifyCompletionsMessage(WINE_WAVEOUT_INSTANCE* wwo)
364 if (!Port_SendToMessageThread)
367 data = CFDataCreate(kCFAllocatorDefault, (UInt8 *)&wwo, sizeof(wwo));
371 CFMessagePortSendRequest(Port_SendToMessageThread, kWaveOutNotifyCompletionsMessage, data, 0.0, 0.0, NULL, NULL);
375 /**************************************************************************
376 * wodSendNotifyInputCompletionsMessage [internal]
377 * Call from AudioUnit IO thread can't use Wine debug channels.
379 static void wodSendNotifyInputCompletionsMessage(WINE_WAVEIN* wwi)
384 if (!Port_SendToMessageThread)
387 buffer = (UInt32) wwi->wiID;
389 data = CFDataCreate(kCFAllocatorDefault, (UInt8 *)&buffer, sizeof(buffer));
393 CFMessagePortSendRequest(Port_SendToMessageThread, kWaveInNotifyCompletionsMessage, data, 0.0, 0.0, NULL, NULL);
397 static DWORD bytes_to_mmtime(LPMMTIME lpTime, DWORD position,
398 PCMWAVEFORMAT* format)
400 TRACE("wType=%04X wBitsPerSample=%u nSamplesPerSec=%u nChannels=%u nAvgBytesPerSec=%u\n",
401 lpTime->wType, format->wBitsPerSample, format->wf.nSamplesPerSec,
402 format->wf.nChannels, format->wf.nAvgBytesPerSec);
403 TRACE("Position in bytes=%u\n", position);
405 switch (lpTime->wType) {
407 lpTime->u.sample = position / (format->wBitsPerSample / 8 * format->wf.nChannels);
408 TRACE("TIME_SAMPLES=%u\n", lpTime->u.sample);
411 lpTime->u.ms = 1000.0 * position / (format->wBitsPerSample / 8 * format->wf.nChannels * format->wf.nSamplesPerSec);
412 TRACE("TIME_MS=%u\n", lpTime->u.ms);
415 lpTime->u.smpte.fps = 30;
416 position = position / (format->wBitsPerSample / 8 * format->wf.nChannels);
417 position += (format->wf.nSamplesPerSec / lpTime->u.smpte.fps) - 1; /* round up */
418 lpTime->u.smpte.sec = position / format->wf.nSamplesPerSec;
419 position -= lpTime->u.smpte.sec * format->wf.nSamplesPerSec;
420 lpTime->u.smpte.min = lpTime->u.smpte.sec / 60;
421 lpTime->u.smpte.sec -= 60 * lpTime->u.smpte.min;
422 lpTime->u.smpte.hour = lpTime->u.smpte.min / 60;
423 lpTime->u.smpte.min -= 60 * lpTime->u.smpte.hour;
424 lpTime->u.smpte.fps = 30;
425 lpTime->u.smpte.frame = position * lpTime->u.smpte.fps / format->wf.nSamplesPerSec;
426 TRACE("TIME_SMPTE=%02u:%02u:%02u:%02u\n",
427 lpTime->u.smpte.hour, lpTime->u.smpte.min,
428 lpTime->u.smpte.sec, lpTime->u.smpte.frame);
431 WARN("Format %d not supported, using TIME_BYTES !\n", lpTime->wType);
432 lpTime->wType = TIME_BYTES;
435 lpTime->u.cb = position;
436 TRACE("TIME_BYTES=%u\n", lpTime->u.cb);
439 return MMSYSERR_NOERROR;
442 static BOOL supportedFormat(LPWAVEFORMATEX wf)
444 if (wf->nSamplesPerSec == 0)
447 if (wf->wFormatTag == WAVE_FORMAT_PCM) {
448 if (wf->nChannels >= 1 && wf->nChannels <= 2) {
449 if (wf->wBitsPerSample==8||wf->wBitsPerSample==16)
452 } else if (wf->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
453 WAVEFORMATEXTENSIBLE * wfex = (WAVEFORMATEXTENSIBLE *)wf;
455 if (wf->cbSize == 22 && IsEqualGUID(&wfex->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM)) {
456 if (wf->nChannels >=1 && wf->nChannels <= 8) {
457 if (wf->wBitsPerSample==wfex->Samples.wValidBitsPerSample) {
458 if (wf->wBitsPerSample==8||wf->wBitsPerSample==16)
461 WARN("wBitsPerSample != wValidBitsPerSample not supported yet\n");
464 WARN("only KSDATAFORMAT_SUBTYPE_PCM supported\n");
466 WARN("only WAVE_FORMAT_PCM supported\n");
471 void copyFormat(LPWAVEFORMATEX wf1, LPPCMWAVEFORMAT wf2)
473 memcpy(wf2, wf1, sizeof(PCMWAVEFORMAT));
474 /* Downgrade WAVE_FORMAT_EXTENSIBLE KSDATAFORMAT_SUBTYPE_PCM
475 * to smaller yet compatible WAVE_FORMAT_PCM structure */
476 if (wf2->wf.wFormatTag == WAVE_FORMAT_EXTENSIBLE)
477 wf2->wf.wFormatTag = WAVE_FORMAT_PCM;
480 /**************************************************************************
481 * CoreAudio_GetDevCaps [internal]
483 BOOL CoreAudio_GetDevCaps (void)
487 AudioDeviceID devId = CoreAudio_DefaultDevice.outputDeviceID;
489 char name[MAXPNAMELEN];
491 propertySize = MAXPNAMELEN;
492 status = AudioDeviceGetProperty(devId, 0 , FALSE, kAudioDevicePropertyDeviceName, &propertySize, name);
494 ERR("AudioHardwareGetProperty for kAudioDevicePropertyDeviceName return %s\n", wine_dbgstr_fourcc(status));
498 memcpy(CoreAudio_DefaultDevice.ds_desc.szDesc, name, sizeof(name));
499 strcpy(CoreAudio_DefaultDevice.ds_desc.szDrvname, "winecoreaudio.drv");
500 MultiByteToWideChar(CP_UNIXCP, 0, name, sizeof(name),
501 CoreAudio_DefaultDevice.out_caps.szPname,
502 sizeof(CoreAudio_DefaultDevice.out_caps.szPname) / sizeof(WCHAR));
503 memcpy(CoreAudio_DefaultDevice.dev_name, name, 32);
505 propertySize = sizeof(CoreAudio_DefaultDevice.streamDescription);
506 status = AudioDeviceGetProperty(devId, 0, FALSE , kAudioDevicePropertyStreamFormat, &propertySize, &CoreAudio_DefaultDevice.streamDescription);
507 if (status != noErr) {
508 ERR("AudioHardwareGetProperty for kAudioDevicePropertyStreamFormat return %s\n", wine_dbgstr_fourcc(status));
512 TRACE("Device Stream Description mSampleRate : %f\n mFormatID : %s\n"
513 "mFormatFlags : %lX\n mBytesPerPacket : %lu\n mFramesPerPacket : %lu\n"
514 "mBytesPerFrame : %lu\n mChannelsPerFrame : %lu\n mBitsPerChannel : %lu\n",
515 CoreAudio_DefaultDevice.streamDescription.mSampleRate,
516 wine_dbgstr_fourcc(CoreAudio_DefaultDevice.streamDescription.mFormatID),
517 CoreAudio_DefaultDevice.streamDescription.mFormatFlags,
518 CoreAudio_DefaultDevice.streamDescription.mBytesPerPacket,
519 CoreAudio_DefaultDevice.streamDescription.mFramesPerPacket,
520 CoreAudio_DefaultDevice.streamDescription.mBytesPerFrame,
521 CoreAudio_DefaultDevice.streamDescription.mChannelsPerFrame,
522 CoreAudio_DefaultDevice.streamDescription.mBitsPerChannel);
524 CoreAudio_DefaultDevice.out_caps.wMid = 0xcafe;
525 CoreAudio_DefaultDevice.out_caps.wPid = 0x0001;
527 CoreAudio_DefaultDevice.out_caps.vDriverVersion = 0x0001;
528 CoreAudio_DefaultDevice.out_caps.dwFormats = 0x00000000;
529 CoreAudio_DefaultDevice.out_caps.wReserved1 = 0;
530 CoreAudio_DefaultDevice.out_caps.dwSupport = WAVECAPS_VOLUME;
531 CoreAudio_DefaultDevice.out_caps.dwSupport |= WAVECAPS_LRVOLUME;
533 CoreAudio_DefaultDevice.out_caps.wChannels = 2;
534 CoreAudio_DefaultDevice.out_caps.dwFormats|= WAVE_FORMAT_4S16;
536 TRACE_(coreaudio)("out dwFormats = %08x, dwSupport = %08x\n",
537 CoreAudio_DefaultDevice.out_caps.dwFormats, CoreAudio_DefaultDevice.out_caps.dwSupport);
542 /******************************************************************
545 * Initialize CoreAudio_DefaultDevice
547 LONG CoreAudio_WaveInit(void)
552 CFStringRef messageThreadPortName;
553 CFMessagePortRef port_ReceiveInMessageThread;
558 /* number of sound cards */
559 AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &propertySize, NULL);
560 propertySize /= sizeof(AudioDeviceID);
561 TRACE("sound cards : %lu\n", propertySize);
563 /* Get the output device */
564 propertySize = sizeof(CoreAudio_DefaultDevice.outputDeviceID);
565 status = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &propertySize, &CoreAudio_DefaultDevice.outputDeviceID);
567 ERR("AudioHardwareGetProperty return %s for kAudioHardwarePropertyDefaultOutputDevice\n", wine_dbgstr_fourcc(status));
570 if (CoreAudio_DefaultDevice.outputDeviceID == kAudioDeviceUnknown) {
571 ERR("AudioHardwareGetProperty: CoreAudio_DefaultDevice.outputDeviceID == kAudioDeviceUnknown\n");
575 if ( ! CoreAudio_GetDevCaps() )
578 CoreAudio_DefaultDevice.interface_name=HeapAlloc(GetProcessHeap(),0,strlen(CoreAudio_DefaultDevice.dev_name)+1);
579 strcpy(CoreAudio_DefaultDevice.interface_name, CoreAudio_DefaultDevice.dev_name);
581 for (i = 0; i < MAX_WAVEOUTDRV; ++i)
583 static const WCHAR wszWaveOutFormat[] =
584 {'C','o','r','e','A','u','d','i','o',' ','W','a','v','e','O','u','t',' ','%','d',0};
586 list_init(&WOutDev[i].instances);
587 WOutDev[i].cadev = &CoreAudio_DefaultDevice;
589 memset(&WOutDev[i].caps, 0, sizeof(WOutDev[i].caps));
591 WOutDev[i].caps.wMid = 0xcafe; /* Manufac ID */
592 WOutDev[i].caps.wPid = 0x0001; /* Product ID */
593 snprintfW(WOutDev[i].caps.szPname, sizeof(WOutDev[i].caps.szPname)/sizeof(WCHAR), wszWaveOutFormat, i);
594 snprintf(WOutDev[i].interface_name, sizeof(WOutDev[i].interface_name), "winecoreaudio: %d", i);
596 WOutDev[i].caps.vDriverVersion = 0x0001;
597 WOutDev[i].caps.dwFormats = 0x00000000;
598 WOutDev[i].caps.dwSupport = WAVECAPS_VOLUME;
600 WOutDev[i].caps.wChannels = 2;
601 /* WOutDev[i].caps.dwSupport |= WAVECAPS_LRVOLUME; */ /* FIXME */
603 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96M08;
604 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96S08;
605 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96M16;
606 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96S16;
607 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48M08;
608 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48S08;
609 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48M16;
610 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48S16;
611 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4M08;
612 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4S08;
613 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4S16;
614 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4M16;
615 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2M08;
616 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2S08;
617 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2M16;
618 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2S16;
619 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1M08;
620 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1S08;
621 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1M16;
622 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1S16;
624 WOutDev[i].device_volume = 0xffffffff;
626 WOutDev[i].lock = 0; /* initialize the mutex */
629 /* FIXME: implement sample rate conversion on input */
630 inputSampleRate = AudioUnit_GetInputDeviceSampleRate();
632 for (i = 0; i < MAX_WAVEINDRV; ++i)
634 static const WCHAR wszWaveInFormat[] =
635 {'C','o','r','e','A','u','d','i','o',' ','W','a','v','e','I','n',' ','%','d',0};
637 memset(&WInDev[i], 0, sizeof(WInDev[i]));
640 /* Establish preconditions for widOpen */
641 WInDev[i].state = WINE_WS_CLOSED;
642 WInDev[i].lock = 0; /* initialize the mutex */
644 /* Fill in capabilities. widGetDevCaps can be called at any time. */
645 WInDev[i].caps.wMid = 0xcafe; /* Manufac ID */
646 WInDev[i].caps.wPid = 0x0001; /* Product ID */
647 WInDev[i].caps.vDriverVersion = 0x0001;
649 snprintfW(WInDev[i].caps.szPname, sizeof(WInDev[i].caps.szPname)/sizeof(WCHAR), wszWaveInFormat, i);
650 snprintf(WInDev[i].interface_name, sizeof(WInDev[i].interface_name), "winecoreaudio in: %d", i);
652 if (inputSampleRate == 96000)
654 WInDev[i].caps.dwFormats |= WAVE_FORMAT_96M08;
655 WInDev[i].caps.dwFormats |= WAVE_FORMAT_96S08;
656 WInDev[i].caps.dwFormats |= WAVE_FORMAT_96M16;
657 WInDev[i].caps.dwFormats |= WAVE_FORMAT_96S16;
659 if (inputSampleRate == 48000)
661 WInDev[i].caps.dwFormats |= WAVE_FORMAT_48M08;
662 WInDev[i].caps.dwFormats |= WAVE_FORMAT_48S08;
663 WInDev[i].caps.dwFormats |= WAVE_FORMAT_48M16;
664 WInDev[i].caps.dwFormats |= WAVE_FORMAT_48S16;
666 if (inputSampleRate == 44100)
668 WInDev[i].caps.dwFormats |= WAVE_FORMAT_4M08;
669 WInDev[i].caps.dwFormats |= WAVE_FORMAT_4S08;
670 WInDev[i].caps.dwFormats |= WAVE_FORMAT_4M16;
671 WInDev[i].caps.dwFormats |= WAVE_FORMAT_4S16;
673 if (inputSampleRate == 22050)
675 WInDev[i].caps.dwFormats |= WAVE_FORMAT_2M08;
676 WInDev[i].caps.dwFormats |= WAVE_FORMAT_2S08;
677 WInDev[i].caps.dwFormats |= WAVE_FORMAT_2M16;
678 WInDev[i].caps.dwFormats |= WAVE_FORMAT_2S16;
680 if (inputSampleRate == 11025)
682 WInDev[i].caps.dwFormats |= WAVE_FORMAT_1M08;
683 WInDev[i].caps.dwFormats |= WAVE_FORMAT_1S08;
684 WInDev[i].caps.dwFormats |= WAVE_FORMAT_1M16;
685 WInDev[i].caps.dwFormats |= WAVE_FORMAT_1S16;
688 WInDev[i].caps.wChannels = 2;
691 /* create mach messages handler */
693 messageThreadPortName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL,
694 CFSTR("WaveMessagePort.%d.%lu"), getpid(), (unsigned long)random());
695 if (!messageThreadPortName)
697 ERR("Can't create message thread port name\n");
701 port_ReceiveInMessageThread = CFMessagePortCreateLocal(kCFAllocatorDefault, messageThreadPortName,
702 &wodMessageHandler, NULL, NULL);
703 if (!port_ReceiveInMessageThread)
705 ERR("Can't create message thread local port\n");
706 CFRelease(messageThreadPortName);
710 Port_SendToMessageThread = CFMessagePortCreateRemote(kCFAllocatorDefault, messageThreadPortName);
711 CFRelease(messageThreadPortName);
712 if (!Port_SendToMessageThread)
714 ERR("Can't create port for sending to message thread\n");
715 CFRelease(port_ReceiveInMessageThread);
719 /* Cannot WAIT for any events because we are called from the loader (which has a lock on loading stuff) */
720 /* We might want to wait for this thread to be created -- but we cannot -- not here at least */
721 /* Instead track the thread so we can clean it up later */
724 ERR("Message thread already started -- expect problems\n");
726 hThread = CreateThread(NULL, 0, messageThread, (LPVOID)port_ReceiveInMessageThread, 0, NULL);
729 ERR("Can't create message thread\n");
730 CFRelease(port_ReceiveInMessageThread);
731 CFRelease(Port_SendToMessageThread);
732 Port_SendToMessageThread = NULL;
736 /* The message thread is responsible for releasing port_ReceiveInMessageThread. */
741 void CoreAudio_WaveRelease(void)
743 /* Stop CFRunLoop in messageThread */
746 if (!Port_SendToMessageThread)
749 CFMessagePortSendRequest(Port_SendToMessageThread, kStopLoopMessage, NULL, 0.0, 0.0, NULL, NULL);
750 CFRelease(Port_SendToMessageThread);
751 Port_SendToMessageThread = NULL;
753 /* Wait for the thread to finish and clean it up */
754 /* This rids us of any quick start/shutdown driver crashes */
755 WaitForSingleObject(hThread, INFINITE);
756 CloseHandle(hThread);
760 /*======================================================================*
761 * Low level WAVE OUT implementation *
762 *======================================================================*/
764 /**************************************************************************
765 * wodNotifyClient [internal]
767 static DWORD wodNotifyClient(WINE_WAVEOUT_INSTANCE* wwo, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
769 TRACE_(coreaudio)("wMsg = 0x%04x dwParm1 = %04x dwParam2 = %04x\n", wMsg, dwParam1, dwParam2);
775 if (wwo->wFlags != DCB_NULL &&
776 !DriverCallback(wwo->waveDesc.dwCallback, wwo->wFlags,
777 (HDRVR)wwo->waveDesc.hWave, wMsg, wwo->waveDesc.dwInstance,
780 ERR("can't notify client !\n");
781 return MMSYSERR_ERROR;
785 ERR("Unknown callback message %u\n", wMsg);
786 return MMSYSERR_INVALPARAM;
788 return MMSYSERR_NOERROR;
792 /**************************************************************************
793 * wodGetDevCaps [internal]
795 static DWORD wodGetDevCaps(WORD wDevID, LPWAVEOUTCAPSW lpCaps, DWORD dwSize)
797 TRACE("(%u, %p, %u);\n", wDevID, lpCaps, dwSize);
799 if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
801 if (wDevID >= MAX_WAVEOUTDRV)
803 TRACE("MAX_WAVOUTDRV reached !\n");
804 return MMSYSERR_BADDEVICEID;
807 TRACE("dwSupport=(0x%x), dwFormats=(0x%x)\n", WOutDev[wDevID].caps.dwSupport, WOutDev[wDevID].caps.dwFormats);
808 memcpy(lpCaps, &WOutDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
809 return MMSYSERR_NOERROR;
812 /**************************************************************************
815 static DWORD wodOpen(WORD wDevID, WINE_WAVEOUT_INSTANCE** pInstance, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
817 WINE_WAVEOUT_INSTANCE* wwo;
819 AudioStreamBasicDescription streamFormat;
820 AudioUnit audioUnit = NULL;
821 BOOL auInited = FALSE;
823 TRACE("(%u, %p, %p, %08x);\n", wDevID, pInstance, lpDesc, dwFlags);
826 WARN("Invalid Parameter !\n");
827 return MMSYSERR_INVALPARAM;
829 if (wDevID >= MAX_WAVEOUTDRV) {
830 TRACE("MAX_WAVOUTDRV reached !\n");
831 return MMSYSERR_BADDEVICEID;
834 TRACE("Format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
835 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
836 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
838 if (!supportedFormat(lpDesc->lpFormat))
840 WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
841 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
842 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
843 return WAVERR_BADFORMAT;
846 if (dwFlags & WAVE_FORMAT_QUERY)
848 TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
849 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
850 lpDesc->lpFormat->nSamplesPerSec);
851 return MMSYSERR_NOERROR;
854 /* nBlockAlign and nAvgBytesPerSec are output variables for dsound */
855 if (lpDesc->lpFormat->nBlockAlign != lpDesc->lpFormat->nChannels*lpDesc->lpFormat->wBitsPerSample/8) {
856 lpDesc->lpFormat->nBlockAlign = lpDesc->lpFormat->nChannels*lpDesc->lpFormat->wBitsPerSample/8;
857 WARN("Fixing nBlockAlign\n");
859 if (lpDesc->lpFormat->nAvgBytesPerSec!= lpDesc->lpFormat->nSamplesPerSec*lpDesc->lpFormat->nBlockAlign) {
860 lpDesc->lpFormat->nAvgBytesPerSec = lpDesc->lpFormat->nSamplesPerSec*lpDesc->lpFormat->nBlockAlign;
861 WARN("Fixing nAvgBytesPerSec\n");
864 /* We proceed in three phases:
865 * o Allocate the device instance, marking it as opening
866 * o Create, configure, and start the Audio Unit. To avoid deadlock,
867 * this has to be done without holding wwo->lock.
868 * o If that was successful, finish setting up our instance and add it
869 * to the device's list.
870 * Otherwise, clean up and deallocate the instance.
872 wwo = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*wwo));
874 return MMSYSERR_NOMEM;
877 wwo->state = WINE_WS_OPENING;
879 if (!AudioUnit_CreateDefaultAudioUnit((void *) wwo, &audioUnit))
881 ERR("CoreAudio_CreateDefaultAudioUnit(0x%04x) failed\n", wDevID);
882 ret = MMSYSERR_ERROR;
886 streamFormat.mFormatID = kAudioFormatLinearPCM;
887 streamFormat.mFormatFlags = kLinearPCMFormatFlagIsPacked;
888 /* FIXME check for 32bits float -> kLinearPCMFormatFlagIsFloat */
889 if (lpDesc->lpFormat->wBitsPerSample != 8)
890 streamFormat.mFormatFlags |= kLinearPCMFormatFlagIsSignedInteger;
891 # ifdef WORDS_BIGENDIAN
892 streamFormat.mFormatFlags |= kLinearPCMFormatFlagIsBigEndian; /* FIXME Wave format is little endian */
895 streamFormat.mSampleRate = lpDesc->lpFormat->nSamplesPerSec;
896 streamFormat.mChannelsPerFrame = lpDesc->lpFormat->nChannels;
897 streamFormat.mFramesPerPacket = 1;
898 streamFormat.mBitsPerChannel = lpDesc->lpFormat->wBitsPerSample;
899 streamFormat.mBytesPerFrame = streamFormat.mBitsPerChannel * streamFormat.mChannelsPerFrame / 8;
900 streamFormat.mBytesPerPacket = streamFormat.mBytesPerFrame * streamFormat.mFramesPerPacket;
902 ret = AudioUnit_InitializeWithStreamDescription(audioUnit, &streamFormat);
905 ret = WAVERR_BADFORMAT; /* FIXME return an error based on the OSStatus */
910 AudioUnit_SetVolume(audioUnit, LOWORD(WOutDev[wDevID].device_volume) / 65535.0f,
911 HIWORD(WOutDev[wDevID].device_volume) / 65535.0f);
913 /* Our render callback CoreAudio_woAudioUnitIOProc may be called before
914 * AudioOutputUnitStart returns. Core Audio will grab its own internal
915 * lock before calling it and the callback grabs wwo->lock. This would
916 * deadlock if we were holding wwo->lock.
917 * Also, the callback has to safely do nothing in that case, because
918 * wwo hasn't been completely filled out, yet. This is assured by state
919 * being WINE_WS_OPENING. */
920 ret = AudioOutputUnitStart(audioUnit);
923 ERR("AudioOutputUnitStart failed: %08x\n", ret);
924 ret = MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
929 OSSpinLockLock(&wwo->lock);
930 assert(wwo->state == WINE_WS_OPENING);
932 wwo->audioUnit = audioUnit;
933 wwo->streamDescription = streamFormat;
935 wwo->state = WINE_WS_PLAYING;
937 wwo->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
939 wwo->waveDesc = *lpDesc;
940 copyFormat(lpDesc->lpFormat, &wwo->format);
942 WOutDev[wDevID].trace_on = TRACE_ON(wave);
943 WOutDev[wDevID].warn_on = WARN_ON(wave);
944 WOutDev[wDevID].err_on = ERR_ON(wave);
946 OSSpinLockUnlock(&wwo->lock);
948 OSSpinLockLock(&WOutDev[wDevID].lock);
949 list_add_head(&WOutDev[wDevID].instances, &wwo->entry);
950 OSSpinLockUnlock(&WOutDev[wDevID].lock);
953 TRACE("opened instance %p\n", wwo);
955 ret = wodNotifyClient(wwo, WOM_OPEN, 0L, 0L);
963 AudioUnitUninitialize(audioUnit);
964 AudioUnit_CloseAudioUnit(audioUnit);
967 OSSpinLockLock(&wwo->lock);
968 assert(wwo->state == WINE_WS_OPENING);
969 /* OSSpinLockUnlock(&wwo->lock); *//* No need, about to free */
970 HeapFree(GetProcessHeap(), 0, wwo);
975 /**************************************************************************
976 * wodClose [internal]
978 static DWORD wodClose(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo)
980 DWORD ret = MMSYSERR_NOERROR;
982 TRACE("(%u, %p);\n", wDevID, wwo);
984 if (wDevID >= MAX_WAVEOUTDRV)
986 WARN("bad device ID !\n");
987 return MMSYSERR_BADDEVICEID;
990 OSSpinLockLock(&wwo->lock);
993 OSSpinLockUnlock(&wwo->lock);
994 WARN("buffers still playing !\n");
995 ret = WAVERR_STILLPLAYING;
999 AudioUnit audioUnit = wwo->audioUnit;
1001 /* sanity check: this should not happen since the device must have been reset before */
1002 if (wwo->lpQueuePtr || wwo->lpPlayPtr) ERR("out of sync\n");
1004 wwo->state = WINE_WS_CLOSING; /* mark the device as closing */
1005 wwo->audioUnit = NULL;
1007 OSSpinLockUnlock(&wwo->lock);
1009 err = AudioUnitUninitialize(audioUnit);
1011 ERR("AudioUnitUninitialize return %s\n", wine_dbgstr_fourcc(err));
1012 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1015 if ( !AudioUnit_CloseAudioUnit(audioUnit) )
1017 ERR("Can't close AudioUnit\n");
1018 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1021 OSSpinLockLock(&WOutDev[wDevID].lock);
1022 list_remove(&wwo->entry);
1023 OSSpinLockUnlock(&WOutDev[wDevID].lock);
1025 ret = wodNotifyClient(wwo, WOM_CLOSE, 0L, 0L);
1027 HeapFree(GetProcessHeap(), 0, wwo);
1033 /**************************************************************************
1034 * wodPrepare [internal]
1036 static DWORD wodPrepare(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1038 TRACE("(%u, %p, %p, %08x);\n", wDevID, wwo, lpWaveHdr, dwSize);
1040 if (wDevID >= MAX_WAVEOUTDRV) {
1041 WARN("bad device ID !\n");
1042 return MMSYSERR_BADDEVICEID;
1045 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1046 return WAVERR_STILLPLAYING;
1048 lpWaveHdr->dwFlags |= WHDR_PREPARED;
1049 lpWaveHdr->dwFlags &= ~WHDR_DONE;
1051 return MMSYSERR_NOERROR;
1054 /**************************************************************************
1055 * wodUnprepare [internal]
1057 static DWORD wodUnprepare(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1059 TRACE("(%u, %p, %p, %08x);\n", wDevID, wwo, lpWaveHdr, dwSize);
1061 if (wDevID >= MAX_WAVEOUTDRV) {
1062 WARN("bad device ID !\n");
1063 return MMSYSERR_BADDEVICEID;
1066 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1067 return WAVERR_STILLPLAYING;
1069 lpWaveHdr->dwFlags &= ~WHDR_PREPARED;
1070 lpWaveHdr->dwFlags |= WHDR_DONE;
1072 return MMSYSERR_NOERROR;
1076 /**************************************************************************
1077 * wodHelper_CheckForLoopBegin [internal]
1079 * Check if the new waveheader is the beginning of a loop, and set up
1081 * This is called with the WAVEOUT_INSTANCE lock held.
1082 * Call from AudioUnit IO thread can't use Wine debug channels.
1084 static void wodHelper_CheckForLoopBegin(WINE_WAVEOUT_INSTANCE* wwo)
1086 LPWAVEHDR lpWaveHdr = wwo->lpPlayPtr;
1088 if (lpWaveHdr->dwFlags & WHDR_BEGINLOOP)
1092 if (WOutDev[wwo->woID].warn_on)
1093 fprintf(stderr, "warn:winecoreaudio:wodHelper_CheckForLoopBegin Already in a loop. Discarding loop on this header (%p)\n", lpWaveHdr);
1097 if (WOutDev[wwo->woID].trace_on)
1098 fprintf(stderr, "trace:winecoreaudio:wodHelper_CheckForLoopBegin Starting loop (%dx) with %p\n", lpWaveHdr->dwLoops, lpWaveHdr);
1100 wwo->lpLoopPtr = lpWaveHdr;
1101 /* Windows does not touch WAVEHDR.dwLoops,
1102 * so we need to make an internal copy */
1103 wwo->dwLoops = lpWaveHdr->dwLoops;
1109 /**************************************************************************
1110 * wodHelper_PlayPtrNext [internal]
1112 * Advance the play pointer to the next waveheader, looping if required.
1113 * This is called with the WAVEOUT_INSTANCE lock held.
1114 * Call from AudioUnit IO thread can't use Wine debug channels.
1116 static void wodHelper_PlayPtrNext(WINE_WAVEOUT_INSTANCE* wwo)
1118 BOOL didLoopBack = FALSE;
1120 wwo->dwPartialOffset = 0;
1121 if ((wwo->lpPlayPtr->dwFlags & WHDR_ENDLOOP) && wwo->lpLoopPtr)
1123 /* We're at the end of a loop, loop if required */
1124 if (wwo->dwLoops > 1)
1127 wwo->lpPlayPtr = wwo->lpLoopPtr;
1132 wwo->lpLoopPtr = NULL;
1137 /* We didn't loop back. Advance to the next wave header */
1138 wwo->lpPlayPtr = wwo->lpPlayPtr->lpNext;
1141 wodHelper_CheckForLoopBegin(wwo);
1145 /* Send the "done" notification for each WAVEHDR in a list. The list must be
1146 * free-standing. It should not be part of a device instance's queue.
1147 * This function must be called with the WAVEOUT_INSTANCE lock *not* held.
1148 * Furthermore, it does not lock it, itself. That's because the callback to the
1149 * application may prompt the application to operate on the device, and we don't
1152 static void wodHelper_NotifyDoneForList(WINE_WAVEOUT_INSTANCE* wwo, LPWAVEHDR lpWaveHdr)
1156 LPWAVEHDR lpNext = lpWaveHdr->lpNext;
1158 lpWaveHdr->lpNext = NULL;
1159 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1160 lpWaveHdr->dwFlags |= WHDR_DONE;
1161 wodNotifyClient(wwo, WOM_DONE, (DWORD)lpWaveHdr, 0);
1167 /* if force is TRUE then notify the client that all the headers were completed
1169 static void wodHelper_NotifyCompletions(WINE_WAVEOUT_INSTANCE* wwo, BOOL force)
1171 LPWAVEHDR lpFirstDoneWaveHdr = NULL;
1173 OSSpinLockLock(&wwo->lock);
1175 /* First, excise all of the done headers from the queue into
1176 * a free-standing list. */
1179 lpFirstDoneWaveHdr = wwo->lpQueuePtr;
1180 wwo->lpQueuePtr = NULL;
1184 LPWAVEHDR lpWaveHdr;
1185 LPWAVEHDR lpLastDoneWaveHdr = NULL;
1187 /* Start from lpQueuePtr and keep notifying until:
1188 * - we hit an unwritten wavehdr
1189 * - we hit the beginning of a running loop
1190 * - we hit a wavehdr which hasn't finished playing
1193 lpWaveHdr = wwo->lpQueuePtr;
1195 lpWaveHdr != wwo->lpPlayPtr &&
1196 lpWaveHdr != wwo->lpLoopPtr;
1197 lpWaveHdr = lpWaveHdr->lpNext
1200 if (!lpFirstDoneWaveHdr)
1201 lpFirstDoneWaveHdr = lpWaveHdr;
1202 lpLastDoneWaveHdr = lpWaveHdr;
1205 if (lpLastDoneWaveHdr)
1207 wwo->lpQueuePtr = lpLastDoneWaveHdr->lpNext;
1208 lpLastDoneWaveHdr->lpNext = NULL;
1212 OSSpinLockUnlock(&wwo->lock);
1214 /* Now, send the "done" notification for each header in our list. */
1215 wodHelper_NotifyDoneForList(wwo, lpFirstDoneWaveHdr);
1219 /**************************************************************************
1220 * wodWrite [internal]
1223 static DWORD wodWrite(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1227 TRACE("(%u, %p, %p, %lu, %08X);\n", wDevID, wwo, lpWaveHdr, (unsigned long)lpWaveHdr->dwBufferLength, dwSize);
1229 /* first, do the sanity checks... */
1230 if (wDevID >= MAX_WAVEOUTDRV)
1232 WARN("bad dev ID !\n");
1233 return MMSYSERR_BADDEVICEID;
1236 if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
1238 TRACE("unprepared\n");
1239 return WAVERR_UNPREPARED;
1242 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1244 TRACE("still playing\n");
1245 return WAVERR_STILLPLAYING;
1248 lpWaveHdr->dwFlags &= ~WHDR_DONE;
1249 lpWaveHdr->dwFlags |= WHDR_INQUEUE;
1250 lpWaveHdr->lpNext = 0;
1252 OSSpinLockLock(&wwo->lock);
1253 /* insert buffer at the end of queue */
1254 for (wh = &(wwo->lpQueuePtr); *wh; wh = &((*wh)->lpNext))
1258 if (!wwo->lpPlayPtr)
1260 wwo->lpPlayPtr = lpWaveHdr;
1262 wodHelper_CheckForLoopBegin(wwo);
1264 wwo->dwPartialOffset = 0;
1266 OSSpinLockUnlock(&wwo->lock);
1268 return MMSYSERR_NOERROR;
1271 /**************************************************************************
1272 * wodPause [internal]
1274 static DWORD wodPause(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo)
1278 TRACE("(%u, %p);!\n", wDevID, wwo);
1280 if (wDevID >= MAX_WAVEOUTDRV)
1282 WARN("bad device ID !\n");
1283 return MMSYSERR_BADDEVICEID;
1286 /* The order of the following operations is important since we can't hold
1287 * the mutex while we make an Audio Unit call. Stop the Audio Unit before
1288 * setting the PAUSED state. In wodRestart, the order is reversed. This
1289 * guarantees that we can't get into a situation where the state is
1290 * PLAYING but the Audio Unit isn't running. Although we can be in PAUSED
1291 * state with the Audio Unit still running, that's harmless because the
1292 * render callback will just produce silence.
1294 status = AudioOutputUnitStop(wwo->audioUnit);
1296 WARN("AudioOutputUnitStop return %s\n", wine_dbgstr_fourcc(status));
1298 OSSpinLockLock(&wwo->lock);
1299 if (wwo->state == WINE_WS_PLAYING)
1300 wwo->state = WINE_WS_PAUSED;
1301 OSSpinLockUnlock(&wwo->lock);
1303 return MMSYSERR_NOERROR;
1306 /**************************************************************************
1307 * wodRestart [internal]
1309 static DWORD wodRestart(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo)
1313 TRACE("(%u, %p);\n", wDevID, wwo);
1315 if (wDevID >= MAX_WAVEOUTDRV )
1317 WARN("bad device ID !\n");
1318 return MMSYSERR_BADDEVICEID;
1321 /* The order of the following operations is important since we can't hold
1322 * the mutex while we make an Audio Unit call. Set the PLAYING
1323 * state before starting the Audio Unit. In wodPause, the order is
1324 * reversed. This guarantees that we can't get into a situation where
1325 * the state is PLAYING but the Audio Unit isn't running.
1326 * Although we can be in PAUSED state with the Audio Unit still running,
1327 * that's harmless because the render callback will just produce silence.
1329 OSSpinLockLock(&wwo->lock);
1330 if (wwo->state == WINE_WS_PAUSED)
1331 wwo->state = WINE_WS_PLAYING;
1332 OSSpinLockUnlock(&wwo->lock);
1334 status = AudioOutputUnitStart(wwo->audioUnit);
1336 ERR("AudioOutputUnitStart return %s\n", wine_dbgstr_fourcc(status));
1337 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1340 return MMSYSERR_NOERROR;
1343 /**************************************************************************
1344 * wodReset [internal]
1346 static DWORD wodReset(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo)
1349 LPWAVEHDR lpSavedQueuePtr;
1351 TRACE("(%u, %p);\n", wDevID, wwo);
1353 if (wDevID >= MAX_WAVEOUTDRV)
1355 WARN("bad device ID !\n");
1356 return MMSYSERR_BADDEVICEID;
1359 OSSpinLockLock(&wwo->lock);
1361 if (wwo->state == WINE_WS_CLOSING || wwo->state == WINE_WS_OPENING)
1363 OSSpinLockUnlock(&wwo->lock);
1364 WARN("resetting a closed device\n");
1365 return MMSYSERR_INVALHANDLE;
1368 lpSavedQueuePtr = wwo->lpQueuePtr;
1369 wwo->lpPlayPtr = wwo->lpQueuePtr = wwo->lpLoopPtr = NULL;
1370 wwo->state = WINE_WS_PLAYING;
1371 wwo->dwPlayedTotal = 0;
1373 wwo->dwPartialOffset = 0; /* Clear partial wavehdr */
1375 OSSpinLockUnlock(&wwo->lock);
1377 status = AudioOutputUnitStart(wwo->audioUnit);
1380 ERR( "AudioOutputUnitStart return %s\n", wine_dbgstr_fourcc(status));
1381 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1384 /* Now, send the "done" notification for each header in our list. */
1385 /* Do this last so the reset operation is effectively complete before the
1386 * app does whatever it's going to do in response to these notifications. */
1387 wodHelper_NotifyDoneForList(wwo, lpSavedQueuePtr);
1389 return MMSYSERR_NOERROR;
1392 /**************************************************************************
1393 * wodBreakLoop [internal]
1395 static DWORD wodBreakLoop(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo)
1397 TRACE("(%u, %p);\n", wDevID, wwo);
1399 if (wDevID >= MAX_WAVEOUTDRV)
1401 WARN("bad device ID !\n");
1402 return MMSYSERR_BADDEVICEID;
1405 OSSpinLockLock(&wwo->lock);
1407 if (wwo->lpLoopPtr != NULL)
1409 /* ensure exit at end of current loop */
1413 OSSpinLockUnlock(&wwo->lock);
1415 return MMSYSERR_NOERROR;
1418 /**************************************************************************
1419 * wodGetPosition [internal]
1421 static DWORD wodGetPosition(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, LPMMTIME lpTime, DWORD uSize)
1425 TRACE("(%u, %p, %p, %u);\n", wDevID, wwo, lpTime, uSize);
1427 if (wDevID >= MAX_WAVEOUTDRV)
1429 WARN("bad device ID !\n");
1430 return MMSYSERR_BADDEVICEID;
1433 /* if null pointer to time structure return error */
1434 if (lpTime == NULL) return MMSYSERR_INVALPARAM;
1436 OSSpinLockLock(&wwo->lock);
1437 val = wwo->dwPlayedTotal;
1438 OSSpinLockUnlock(&wwo->lock);
1440 return bytes_to_mmtime(lpTime, val, &wwo->format);
1443 /**************************************************************************
1444 * wodGetVolume [internal]
1446 static DWORD wodGetVolume(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, LPDWORD lpdwVol)
1448 if (wDevID >= MAX_WAVEOUTDRV)
1450 WARN("bad device ID !\n");
1451 return MMSYSERR_BADDEVICEID;
1454 TRACE("(%u, %p, %p);\n", wDevID, wwo, lpdwVol);
1461 AudioUnit_GetVolume(wwo->audioUnit, &left, &right);
1462 *lpdwVol = (WORD)(left * 0xFFFFl) + ((WORD)(right * 0xFFFFl) << 16);
1465 *lpdwVol = WOutDev[wDevID].device_volume;
1467 return MMSYSERR_NOERROR;
1470 /**************************************************************************
1471 * wodSetVolume [internal]
1473 static DWORD wodSetVolume(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, DWORD dwParam)
1478 if (wDevID >= MAX_WAVEOUTDRV)
1480 WARN("bad device ID !\n");
1481 return MMSYSERR_BADDEVICEID;
1484 left = LOWORD(dwParam) / 65535.0f;
1485 right = HIWORD(dwParam) / 65535.0f;
1487 TRACE("(%u, %p, %08x);\n", wDevID, wwo, dwParam);
1490 AudioUnit_SetVolume(wwo->audioUnit, left, right);
1493 OSSpinLockLock(&WOutDev[wDevID].lock);
1494 LIST_FOR_EACH_ENTRY(wwo, &WOutDev[wDevID].instances, WINE_WAVEOUT_INSTANCE, entry)
1495 AudioUnit_SetVolume(wwo->audioUnit, left, right);
1496 OSSpinLockUnlock(&WOutDev[wDevID].lock);
1498 WOutDev[wDevID].device_volume = dwParam;
1501 return MMSYSERR_NOERROR;
1504 /**************************************************************************
1505 * wodGetNumDevs [internal]
1507 static DWORD wodGetNumDevs(void)
1510 return MAX_WAVEOUTDRV;
1513 /**************************************************************************
1514 * wodDevInterfaceSize [internal]
1516 static DWORD wodDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
1518 TRACE("(%u, %p)\n", wDevID, dwParam1);
1520 *dwParam1 = MultiByteToWideChar(CP_UNIXCP, 0, WOutDev[wDevID].cadev->interface_name, -1,
1521 NULL, 0 ) * sizeof(WCHAR);
1522 return MMSYSERR_NOERROR;
1525 /**************************************************************************
1526 * wodDevInterface [internal]
1528 static DWORD wodDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
1531 if (dwParam2 >= MultiByteToWideChar(CP_UNIXCP, 0, WOutDev[wDevID].cadev->interface_name, -1,
1532 NULL, 0 ) * sizeof(WCHAR))
1534 MultiByteToWideChar(CP_UNIXCP, 0, WOutDev[wDevID].cadev->interface_name, -1,
1535 dwParam1, dwParam2 / sizeof(WCHAR));
1536 return MMSYSERR_NOERROR;
1538 return MMSYSERR_INVALPARAM;
1541 /**************************************************************************
1542 * widDsCreate [internal]
1544 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
1546 TRACE("(%d,%p)\n",wDevID,drv);
1548 FIXME("DirectSound not implemented\n");
1549 FIXME("The (slower) DirectSound HEL mode will be used instead.\n");
1550 return MMSYSERR_NOTSUPPORTED;
1553 /**************************************************************************
1554 * wodDsDesc [internal]
1556 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc)
1558 /* The DirectSound HEL will automatically wrap a non-DirectSound-capable
1559 * driver in a DirectSound adaptor, thus allowing the driver to be used by
1560 * DirectSound clients. However, it only does this if we respond
1561 * successfully to the DRV_QUERYDSOUNDDESC message. It's enough to fill in
1562 * the driver and device names of the description output parameter. */
1563 *desc = WOutDev[wDevID].cadev->ds_desc;
1564 return MMSYSERR_NOERROR;
1567 /**************************************************************************
1568 * wodMessage (WINECOREAUDIO.7)
1570 DWORD WINAPI CoreAudio_wodMessage(UINT wDevID, UINT wMsg, DWORD_PTR dwUser,
1571 DWORD_PTR dwParam1, DWORD_PTR dwParam2)
1573 WINE_WAVEOUT_INSTANCE* wwo = (WINE_WAVEOUT_INSTANCE*)dwUser;
1575 TRACE("(%u, %s, %p, %p, %p);\n",
1576 wDevID, getMessage(wMsg), (void*)dwUser, (void*)dwParam1, (void*)dwParam2);
1584 /* FIXME: Pretend this is supported */
1586 case WODM_OPEN: return wodOpen(wDevID, (WINE_WAVEOUT_INSTANCE**)dwUser, (LPWAVEOPENDESC) dwParam1, dwParam2);
1587 case WODM_CLOSE: return wodClose(wDevID, wwo);
1588 case WODM_WRITE: return wodWrite(wDevID, wwo, (LPWAVEHDR) dwParam1, dwParam2);
1589 case WODM_PAUSE: return wodPause(wDevID, wwo);
1590 case WODM_GETPOS: return wodGetPosition(wDevID, wwo, (LPMMTIME) dwParam1, dwParam2);
1591 case WODM_BREAKLOOP: return wodBreakLoop(wDevID, wwo);
1592 case WODM_PREPARE: return wodPrepare(wDevID, wwo, (LPWAVEHDR)dwParam1, dwParam2);
1593 case WODM_UNPREPARE: return wodUnprepare(wDevID, wwo, (LPWAVEHDR)dwParam1, dwParam2);
1595 case WODM_GETDEVCAPS: return wodGetDevCaps(wDevID, (LPWAVEOUTCAPSW) dwParam1, dwParam2);
1596 case WODM_GETNUMDEVS: return wodGetNumDevs();
1600 case WODM_GETPLAYBACKRATE:
1601 case WODM_SETPLAYBACKRATE: return MMSYSERR_NOTSUPPORTED;
1602 case WODM_GETVOLUME: return wodGetVolume(wDevID, wwo, (LPDWORD)dwParam1);
1603 case WODM_SETVOLUME: return wodSetVolume(wDevID, wwo, dwParam1);
1604 case WODM_RESTART: return wodRestart(wDevID, wwo);
1605 case WODM_RESET: return wodReset(wDevID, wwo);
1607 case DRV_QUERYDEVICEINTERFACESIZE: return wodDevInterfaceSize (wDevID, (LPDWORD)dwParam1);
1608 case DRV_QUERYDEVICEINTERFACE: return wodDevInterface (wDevID, (PWCHAR)dwParam1, dwParam2);
1609 case DRV_QUERYDSOUNDIFACE: return wodDsCreate (wDevID, (PIDSDRIVER*)dwParam1);
1610 case DRV_QUERYDSOUNDDESC: return wodDsDesc (wDevID, (PDSDRIVERDESC)dwParam1);
1613 FIXME("unknown message %d!\n", wMsg);
1616 return MMSYSERR_NOTSUPPORTED;
1619 /*======================================================================*
1620 * Low level DSOUND implementation *
1621 *======================================================================*/
1623 typedef struct IDsDriverImpl IDsDriverImpl;
1624 typedef struct IDsDriverBufferImpl IDsDriverBufferImpl;
1626 struct IDsDriverImpl
1628 /* IUnknown fields */
1629 const IDsDriverVtbl *lpVtbl;
1631 /* IDsDriverImpl fields */
1633 IDsDriverBufferImpl*primary;
1636 struct IDsDriverBufferImpl
1638 /* IUnknown fields */
1639 const IDsDriverBufferVtbl *lpVtbl;
1641 /* IDsDriverBufferImpl fields */
1648 CoreAudio IO threaded callback,
1649 we can't call Wine debug channels, critical section or anything using NtCurrentTeb here.
1651 OSStatus CoreAudio_woAudioUnitIOProc(void *inRefCon,
1652 AudioUnitRenderActionFlags *ioActionFlags,
1653 const AudioTimeStamp *inTimeStamp,
1655 UInt32 inNumberFrames,
1656 AudioBufferList *ioData)
1659 WINE_WAVEOUT_INSTANCE* wwo = (WINE_WAVEOUT_INSTANCE*)inRefCon;
1662 unsigned int dataNeeded = ioData->mBuffers[0].mDataByteSize;
1663 unsigned int dataProvided = 0;
1665 OSSpinLockLock(&wwo->lock);
1667 /* We might have been called before wwo has been completely filled out by
1668 * wodOpen, or while it's being closed in wodClose. We have to do nothing
1669 * in that case. The check of wwo->state below ensures that. */
1670 while (dataNeeded > 0 && wwo->state == WINE_WS_PLAYING && wwo->lpPlayPtr)
1672 unsigned int available = wwo->lpPlayPtr->dwBufferLength - wwo->dwPartialOffset;
1673 unsigned int toCopy;
1675 if (available >= dataNeeded)
1676 toCopy = dataNeeded;
1682 memcpy((char*)ioData->mBuffers[0].mData + dataProvided,
1683 wwo->lpPlayPtr->lpData + wwo->dwPartialOffset, toCopy);
1684 wwo->dwPartialOffset += toCopy;
1685 wwo->dwPlayedTotal += toCopy;
1686 dataProvided += toCopy;
1687 dataNeeded -= toCopy;
1688 available -= toCopy;
1693 wodHelper_PlayPtrNext(wwo);
1697 ioData->mBuffers[0].mDataByteSize = dataProvided;
1699 OSSpinLockUnlock(&wwo->lock);
1701 /* We can't provide any more wave data. Fill the rest with silence. */
1705 *ioActionFlags |= kAudioUnitRenderAction_OutputIsSilence;
1706 memset((char*)ioData->mBuffers[0].mData + dataProvided, 0, dataNeeded);
1707 dataProvided += dataNeeded;
1711 /* We only fill buffer 0. Set any others that might be requested to 0. */
1712 for (buffer = 1; buffer < ioData->mNumberBuffers; buffer++)
1714 memset(ioData->mBuffers[buffer].mData, 0, ioData->mBuffers[buffer].mDataByteSize);
1717 if (needNotify) wodSendNotifyCompletionsMessage(wwo);
1722 /*======================================================================*
1723 * Low level WAVE IN implementation *
1724 *======================================================================*/
1726 /**************************************************************************
1727 * widNotifyClient [internal]
1729 static DWORD widNotifyClient(WINE_WAVEIN* wwi, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
1731 TRACE("wMsg = 0x%04x dwParm1 = %04X dwParam2 = %04X\n", wMsg, dwParam1, dwParam2);
1738 if (wwi->wFlags != DCB_NULL &&
1739 !DriverCallback(wwi->waveDesc.dwCallback, wwi->wFlags,
1740 (HDRVR)wwi->waveDesc.hWave, wMsg, wwi->waveDesc.dwInstance,
1741 dwParam1, dwParam2))
1743 WARN("can't notify client !\n");
1744 return MMSYSERR_ERROR;
1748 FIXME("Unknown callback message %u\n", wMsg);
1749 return MMSYSERR_INVALPARAM;
1751 return MMSYSERR_NOERROR;
1755 /**************************************************************************
1756 * widHelper_NotifyCompletions [internal]
1758 static void widHelper_NotifyCompletions(WINE_WAVEIN* wwi)
1760 LPWAVEHDR lpWaveHdr;
1761 LPWAVEHDR lpFirstDoneWaveHdr = NULL;
1762 LPWAVEHDR lpLastDoneWaveHdr = NULL;
1764 OSSpinLockLock(&wwi->lock);
1766 /* First, excise all of the done headers from the queue into
1767 * a free-standing list. */
1769 /* Start from lpQueuePtr and keep notifying until:
1770 * - we hit an unfilled wavehdr
1771 * - we hit the end of the list
1774 lpWaveHdr = wwi->lpQueuePtr;
1776 lpWaveHdr->dwBytesRecorded >= lpWaveHdr->dwBufferLength;
1777 lpWaveHdr = lpWaveHdr->lpNext
1780 if (!lpFirstDoneWaveHdr)
1781 lpFirstDoneWaveHdr = lpWaveHdr;
1782 lpLastDoneWaveHdr = lpWaveHdr;
1785 if (lpLastDoneWaveHdr)
1787 wwi->lpQueuePtr = lpLastDoneWaveHdr->lpNext;
1788 lpLastDoneWaveHdr->lpNext = NULL;
1791 OSSpinLockUnlock(&wwi->lock);
1793 /* Now, send the "done" notification for each header in our list. */
1794 lpWaveHdr = lpFirstDoneWaveHdr;
1797 LPWAVEHDR lpNext = lpWaveHdr->lpNext;
1799 lpWaveHdr->lpNext = NULL;
1800 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1801 lpWaveHdr->dwFlags |= WHDR_DONE;
1802 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
1809 /**************************************************************************
1810 * widGetDevCaps [internal]
1812 static DWORD widGetDevCaps(WORD wDevID, LPWAVEINCAPSW lpCaps, DWORD dwSize)
1814 TRACE("(%u, %p, %u);\n", wDevID, lpCaps, dwSize);
1816 if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
1818 if (wDevID >= MAX_WAVEINDRV)
1820 TRACE("MAX_WAVEINDRV reached !\n");
1821 return MMSYSERR_BADDEVICEID;
1824 memcpy(lpCaps, &WInDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
1825 return MMSYSERR_NOERROR;
1829 /**************************************************************************
1830 * widHelper_DestroyAudioBufferList [internal]
1831 * Convenience function to dispose of our audio buffers
1833 static void widHelper_DestroyAudioBufferList(AudioBufferList* list)
1838 for (i = 0; i < list->mNumberBuffers; i++)
1840 if (list->mBuffers[i].mData)
1841 HeapFree(GetProcessHeap(), 0, list->mBuffers[i].mData);
1843 HeapFree(GetProcessHeap(), 0, list);
1848 #define AUDIOBUFFERLISTSIZE(numBuffers) (offsetof(AudioBufferList, mBuffers) + (numBuffers) * sizeof(AudioBuffer))
1850 /**************************************************************************
1851 * widHelper_AllocateAudioBufferList [internal]
1852 * Convenience function to allocate our audio buffers
1854 static AudioBufferList* widHelper_AllocateAudioBufferList(UInt32 numChannels, UInt32 bitsPerChannel, UInt32 bufferFrames, BOOL interleaved)
1857 UInt32 channelsPerFrame;
1858 UInt32 bytesPerFrame;
1859 UInt32 bytesPerBuffer;
1860 AudioBufferList* list;
1865 /* For interleaved audio, we allocate one buffer for all channels. */
1867 channelsPerFrame = numChannels;
1871 numBuffers = numChannels;
1872 channelsPerFrame = 1;
1875 bytesPerFrame = bitsPerChannel * channelsPerFrame / 8;
1876 bytesPerBuffer = bytesPerFrame * bufferFrames;
1878 list = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, AUDIOBUFFERLISTSIZE(numBuffers));
1882 list->mNumberBuffers = numBuffers;
1883 for (i = 0; i < numBuffers; ++i)
1885 list->mBuffers[i].mNumberChannels = channelsPerFrame;
1886 list->mBuffers[i].mDataByteSize = bytesPerBuffer;
1887 list->mBuffers[i].mData = HeapAlloc(GetProcessHeap(), 0, bytesPerBuffer);
1888 if (list->mBuffers[i].mData == NULL)
1890 widHelper_DestroyAudioBufferList(list);
1898 /**************************************************************************
1899 * widOpen [internal]
1901 static DWORD widOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
1906 TRACE("(%u, %p, %08X);\n", wDevID, lpDesc, dwFlags);
1909 WARN("Invalid Parameter !\n");
1910 return MMSYSERR_INVALPARAM;
1912 if (wDevID >= MAX_WAVEINDRV)
1914 TRACE ("MAX_WAVEINDRV reached !\n");
1915 return MMSYSERR_BADDEVICEID;
1918 TRACE("Format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
1919 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1920 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
1922 if (!supportedFormat(lpDesc->lpFormat) ||
1923 lpDesc->lpFormat->nSamplesPerSec != AudioUnit_GetInputDeviceSampleRate()
1926 WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
1927 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1928 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
1929 return WAVERR_BADFORMAT;
1932 if (dwFlags & WAVE_FORMAT_QUERY)
1934 TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
1935 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1936 lpDesc->lpFormat->nSamplesPerSec);
1937 return MMSYSERR_NOERROR;
1940 /* nBlockAlign and nAvgBytesPerSec are output variables for dsound */
1941 if (lpDesc->lpFormat->nBlockAlign != lpDesc->lpFormat->nChannels*lpDesc->lpFormat->wBitsPerSample/8) {
1942 lpDesc->lpFormat->nBlockAlign = lpDesc->lpFormat->nChannels*lpDesc->lpFormat->wBitsPerSample/8;
1943 WARN("Fixing nBlockAlign\n");
1945 if (lpDesc->lpFormat->nAvgBytesPerSec!= lpDesc->lpFormat->nSamplesPerSec*lpDesc->lpFormat->nBlockAlign) {
1946 lpDesc->lpFormat->nAvgBytesPerSec = lpDesc->lpFormat->nSamplesPerSec*lpDesc->lpFormat->nBlockAlign;
1947 WARN("Fixing nAvgBytesPerSec\n");
1950 wwi = &WInDev[wDevID];
1951 if (!OSSpinLockTry(&wwi->lock))
1952 return MMSYSERR_ALLOCATED;
1954 if (wwi->state != WINE_WS_CLOSED)
1956 OSSpinLockUnlock(&wwi->lock);
1957 return MMSYSERR_ALLOCATED;
1960 wwi->state = WINE_WS_STOPPED;
1961 wwi->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
1963 wwi->waveDesc = *lpDesc;
1964 copyFormat(lpDesc->lpFormat, &wwi->format);
1966 wwi->dwTotalRecorded = 0;
1968 wwi->trace_on = TRACE_ON(wave);
1969 wwi->warn_on = WARN_ON(wave);
1970 wwi->err_on = ERR_ON(wave);
1972 if (!AudioUnit_CreateInputUnit(wwi, &wwi->audioUnit,
1973 wwi->format.wf.nChannels, wwi->format.wf.nSamplesPerSec,
1974 wwi->format.wBitsPerSample, &frameCount))
1976 OSSpinLockUnlock(&wwi->lock);
1977 ERR("AudioUnit_CreateInputUnit failed\n");
1978 return MMSYSERR_ERROR;
1981 /* Allocate our audio buffers */
1982 wwi->bufferList = widHelper_AllocateAudioBufferList(wwi->format.wf.nChannels,
1983 wwi->format.wBitsPerSample, frameCount, TRUE);
1984 if (wwi->bufferList == NULL)
1986 AudioUnitUninitialize(wwi->audioUnit);
1987 AudioUnit_CloseAudioUnit(wwi->audioUnit);
1988 OSSpinLockUnlock(&wwi->lock);
1989 ERR("Failed to allocate buffer list\n");
1990 return MMSYSERR_NOMEM;
1993 /* Keep a copy of the buffer list structure (but not the buffers themselves)
1994 * in case AudioUnitRender clobbers the original, as it tends to do. */
1995 wwi->bufferListCopy = HeapAlloc(GetProcessHeap(), 0, AUDIOBUFFERLISTSIZE(wwi->bufferList->mNumberBuffers));
1996 if (wwi->bufferListCopy == NULL)
1998 widHelper_DestroyAudioBufferList(wwi->bufferList);
1999 AudioUnitUninitialize(wwi->audioUnit);
2000 AudioUnit_CloseAudioUnit(wwi->audioUnit);
2001 OSSpinLockUnlock(&wwi->lock);
2002 ERR("Failed to allocate buffer list copy\n");
2003 return MMSYSERR_NOMEM;
2005 memcpy(wwi->bufferListCopy, wwi->bufferList, AUDIOBUFFERLISTSIZE(wwi->bufferList->mNumberBuffers));
2007 OSSpinLockUnlock(&wwi->lock);
2009 return widNotifyClient(wwi, WIM_OPEN, 0L, 0L);
2013 /**************************************************************************
2014 * widClose [internal]
2016 static DWORD widClose(WORD wDevID)
2018 DWORD ret = MMSYSERR_NOERROR;
2022 TRACE("(%u);\n", wDevID);
2024 if (wDevID >= MAX_WAVEINDRV)
2026 WARN("bad device ID !\n");
2027 return MMSYSERR_BADDEVICEID;
2030 wwi = &WInDev[wDevID];
2031 OSSpinLockLock(&wwi->lock);
2032 if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2034 WARN("Device already closed.\n");
2035 ret = MMSYSERR_INVALHANDLE;
2037 else if (wwi->lpQueuePtr)
2039 WARN("Buffers in queue.\n");
2040 ret = WAVERR_STILLPLAYING;
2044 wwi->state = WINE_WS_CLOSING;
2047 OSSpinLockUnlock(&wwi->lock);
2049 if (ret != MMSYSERR_NOERROR)
2053 /* Clean up and close the audio unit. This has to be done without
2054 * wwi->lock being held to avoid deadlock. AudioUnitUninitialize will
2055 * grab an internal Core Audio lock while waiting for the device work
2056 * thread to exit. Meanwhile the device work thread may be holding
2057 * that lock and trying to grab the wwi->lock in the callback. */
2058 err = AudioUnitUninitialize(wwi->audioUnit);
2060 ERR("AudioUnitUninitialize return %s\n", wine_dbgstr_fourcc(err));
2062 if (!AudioUnit_CloseAudioUnit(wwi->audioUnit))
2063 ERR("Can't close AudioUnit\n");
2066 OSSpinLockLock(&wwi->lock);
2067 assert(wwi->state == WINE_WS_CLOSING);
2069 /* Dellocate our audio buffers */
2070 widHelper_DestroyAudioBufferList(wwi->bufferList);
2071 wwi->bufferList = NULL;
2072 HeapFree(GetProcessHeap(), 0, wwi->bufferListCopy);
2073 wwi->bufferListCopy = NULL;
2075 wwi->audioUnit = NULL;
2076 wwi->state = WINE_WS_CLOSED;
2077 OSSpinLockUnlock(&wwi->lock);
2079 ret = widNotifyClient(wwi, WIM_CLOSE, 0L, 0L);
2085 /**************************************************************************
2086 * widAddBuffer [internal]
2088 static DWORD widAddBuffer(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
2090 DWORD ret = MMSYSERR_NOERROR;
2093 TRACE("(%u, %p, %08X);\n", wDevID, lpWaveHdr, dwSize);
2095 if (wDevID >= MAX_WAVEINDRV)
2097 WARN("invalid device ID\n");
2098 return MMSYSERR_INVALHANDLE;
2100 if (!(lpWaveHdr->dwFlags & WHDR_PREPARED))
2102 TRACE("never been prepared !\n");
2103 return WAVERR_UNPREPARED;
2105 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
2107 TRACE("header already in use !\n");
2108 return WAVERR_STILLPLAYING;
2111 wwi = &WInDev[wDevID];
2112 OSSpinLockLock(&wwi->lock);
2114 if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2116 WARN("Trying to add buffer to closed device.\n");
2117 ret = MMSYSERR_INVALHANDLE;
2123 lpWaveHdr->dwFlags |= WHDR_INQUEUE;
2124 lpWaveHdr->dwFlags &= ~WHDR_DONE;
2125 lpWaveHdr->dwBytesRecorded = 0;
2126 lpWaveHdr->lpNext = NULL;
2128 /* insert buffer at end of queue */
2129 for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext))
2134 OSSpinLockUnlock(&wwi->lock);
2140 /**************************************************************************
2141 * widStart [internal]
2143 static DWORD widStart(WORD wDevID)
2145 DWORD ret = MMSYSERR_NOERROR;
2148 TRACE("(%u);\n", wDevID);
2149 if (wDevID >= MAX_WAVEINDRV)
2151 WARN("invalid device ID\n");
2152 return MMSYSERR_INVALHANDLE;
2155 /* The order of the following operations is important since we can't hold
2156 * the mutex while we make an Audio Unit call. Set the PLAYING state
2157 * before starting the Audio Unit. In widStop, the order is reversed.
2158 * This guarantees that we can't get into a situation where the state is
2159 * PLAYING but the Audio Unit isn't running. Although we can be in STOPPED
2160 * state with the Audio Unit still running, that's harmless because the
2161 * input callback will just throw away the sound data.
2163 wwi = &WInDev[wDevID];
2164 OSSpinLockLock(&wwi->lock);
2166 if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2168 WARN("Trying to start closed device.\n");
2169 ret = MMSYSERR_INVALHANDLE;
2172 wwi->state = WINE_WS_PLAYING;
2174 OSSpinLockUnlock(&wwi->lock);
2176 if (ret == MMSYSERR_NOERROR)
2178 /* Start pulling for audio data */
2179 OSStatus err = AudioOutputUnitStart(wwi->audioUnit);
2181 ERR("Failed to start AU: %08lx\n", err);
2183 TRACE("Recording started...\n");
2190 /**************************************************************************
2191 * widStop [internal]
2193 static DWORD widStop(WORD wDevID)
2195 DWORD ret = MMSYSERR_NOERROR;
2197 WAVEHDR* lpWaveHdr = NULL;
2200 TRACE("(%u);\n", wDevID);
2201 if (wDevID >= MAX_WAVEINDRV)
2203 WARN("invalid device ID\n");
2204 return MMSYSERR_INVALHANDLE;
2207 wwi = &WInDev[wDevID];
2209 /* The order of the following operations is important since we can't hold
2210 * the mutex while we make an Audio Unit call. Stop the Audio Unit before
2211 * setting the STOPPED state. In widStart, the order is reversed. This
2212 * guarantees that we can't get into a situation where the state is
2213 * PLAYING but the Audio Unit isn't running. Although we can be in STOPPED
2214 * state with the Audio Unit still running, that's harmless because the
2215 * input callback will just throw away the sound data.
2217 err = AudioOutputUnitStop(wwi->audioUnit);
2219 WARN("Failed to stop AU: %08lx\n", err);
2221 TRACE("Recording stopped.\n");
2223 OSSpinLockLock(&wwi->lock);
2225 if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2227 WARN("Trying to stop closed device.\n");
2228 ret = MMSYSERR_INVALHANDLE;
2230 else if (wwi->state != WINE_WS_STOPPED)
2232 wwi->state = WINE_WS_STOPPED;
2233 /* If there's a buffer in progress, it's done. Remove it from the
2234 * queue so that we can return it to the app, below. */
2235 if (wwi->lpQueuePtr)
2237 lpWaveHdr = wwi->lpQueuePtr;
2238 wwi->lpQueuePtr = lpWaveHdr->lpNext;
2242 OSSpinLockUnlock(&wwi->lock);
2246 lpWaveHdr->lpNext = NULL;
2247 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2248 lpWaveHdr->dwFlags |= WHDR_DONE;
2249 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2255 /**************************************************************************
2256 * widGetPos [internal]
2258 static DWORD widGetPos(WORD wDevID, LPMMTIME lpTime, UINT size)
2263 TRACE("(%u);\n", wDevID);
2264 if (wDevID >= MAX_WAVEINDRV)
2266 WARN("invalid device ID\n");
2267 return MMSYSERR_INVALHANDLE;
2270 wwi = &WInDev[wDevID];
2272 OSSpinLockLock(&WInDev[wDevID].lock);
2273 val = wwi->dwTotalRecorded;
2274 OSSpinLockUnlock(&WInDev[wDevID].lock);
2276 return bytes_to_mmtime(lpTime, val, &wwi->format);
2279 /**************************************************************************
2280 * widReset [internal]
2282 static DWORD widReset(WORD wDevID)
2284 DWORD ret = MMSYSERR_NOERROR;
2286 WAVEHDR* lpWaveHdr = NULL;
2288 TRACE("(%u);\n", wDevID);
2289 if (wDevID >= MAX_WAVEINDRV)
2291 WARN("invalid device ID\n");
2292 return MMSYSERR_INVALHANDLE;
2295 wwi = &WInDev[wDevID];
2296 OSSpinLockLock(&wwi->lock);
2298 if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2300 WARN("Trying to reset a closed device.\n");
2301 ret = MMSYSERR_INVALHANDLE;
2305 lpWaveHdr = wwi->lpQueuePtr;
2306 wwi->lpQueuePtr = NULL;
2307 wwi->state = WINE_WS_STOPPED;
2308 wwi->dwTotalRecorded = 0;
2311 OSSpinLockUnlock(&wwi->lock);
2313 if (ret == MMSYSERR_NOERROR)
2315 OSStatus err = AudioOutputUnitStop(wwi->audioUnit);
2317 WARN("Failed to stop AU: %08lx\n", err);
2319 TRACE("Recording stopped.\n");
2324 WAVEHDR* lpNext = lpWaveHdr->lpNext;
2326 lpWaveHdr->lpNext = NULL;
2327 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2328 lpWaveHdr->dwFlags |= WHDR_DONE;
2329 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2338 /**************************************************************************
2339 * widGetNumDevs [internal]
2341 static DWORD widGetNumDevs(void)
2343 return MAX_WAVEINDRV;
2347 /**************************************************************************
2348 * widDevInterfaceSize [internal]
2350 static DWORD widDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
2352 TRACE("(%u, %p)\n", wDevID, dwParam1);
2354 *dwParam1 = MultiByteToWideChar(CP_UNIXCP, 0, WInDev[wDevID].interface_name, -1,
2355 NULL, 0 ) * sizeof(WCHAR);
2356 return MMSYSERR_NOERROR;
2360 /**************************************************************************
2361 * widDevInterface [internal]
2363 static DWORD widDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
2365 if (dwParam2 >= MultiByteToWideChar(CP_UNIXCP, 0, WInDev[wDevID].interface_name, -1,
2366 NULL, 0 ) * sizeof(WCHAR))
2368 MultiByteToWideChar(CP_UNIXCP, 0, WInDev[wDevID].interface_name, -1,
2369 dwParam1, dwParam2 / sizeof(WCHAR));
2370 return MMSYSERR_NOERROR;
2372 return MMSYSERR_INVALPARAM;
2376 /**************************************************************************
2377 * widDsCreate [internal]
2379 static DWORD widDsCreate(UINT wDevID, PIDSCDRIVER* drv)
2381 TRACE("(%d,%p)\n",wDevID,drv);
2383 FIXME("DirectSoundCapture not implemented\n");
2384 FIXME("The (slower) DirectSound HEL mode will be used instead.\n");
2385 return MMSYSERR_NOTSUPPORTED;
2388 /**************************************************************************
2389 * widDsDesc [internal]
2391 static DWORD widDsDesc(UINT wDevID, PDSDRIVERDESC desc)
2393 /* The DirectSound HEL will automatically wrap a non-DirectSound-capable
2394 * driver in a DirectSound adaptor, thus allowing the driver to be used by
2395 * DirectSound clients. However, it only does this if we respond
2396 * successfully to the DRV_QUERYDSOUNDDESC message. It's enough to fill in
2397 * the driver and device names of the description output parameter. */
2398 memset(desc, 0, sizeof(*desc));
2399 lstrcpynA(desc->szDrvname, "winecoreaudio.drv", sizeof(desc->szDrvname) - 1);
2400 lstrcpynA(desc->szDesc, WInDev[wDevID].interface_name, sizeof(desc->szDesc) - 1);
2401 return MMSYSERR_NOERROR;
2405 /**************************************************************************
2406 * widMessage (WINECOREAUDIO.6)
2408 DWORD WINAPI CoreAudio_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2409 DWORD dwParam1, DWORD dwParam2)
2411 TRACE("(%u, %04X, %08X, %08X, %08X);\n",
2412 wDevID, wMsg, dwUser, dwParam1, dwParam2);
2420 /* FIXME: Pretend this is supported */
2422 case WIDM_OPEN: return widOpen (wDevID, (LPWAVEOPENDESC)dwParam1, dwParam2);
2423 case WIDM_CLOSE: return widClose (wDevID);
2424 case WIDM_ADDBUFFER: return widAddBuffer (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2425 case WIDM_PREPARE: return MMSYSERR_NOTSUPPORTED;
2426 case WIDM_UNPREPARE: return MMSYSERR_NOTSUPPORTED;
2427 case WIDM_GETDEVCAPS: return widGetDevCaps (wDevID, (LPWAVEINCAPSW)dwParam1, dwParam2);
2428 case WIDM_GETNUMDEVS: return widGetNumDevs ();
2429 case WIDM_RESET: return widReset (wDevID);
2430 case WIDM_START: return widStart (wDevID);
2431 case WIDM_STOP: return widStop (wDevID);
2432 case WIDM_GETPOS: return widGetPos (wDevID, (LPMMTIME)dwParam1, (UINT)dwParam2 );
2433 case DRV_QUERYDEVICEINTERFACESIZE: return widDevInterfaceSize (wDevID, (LPDWORD)dwParam1);
2434 case DRV_QUERYDEVICEINTERFACE: return widDevInterface (wDevID, (PWCHAR)dwParam1, dwParam2);
2435 case DRV_QUERYDSOUNDIFACE: return widDsCreate (wDevID, (PIDSCDRIVER*)dwParam1);
2436 case DRV_QUERYDSOUNDDESC: return widDsDesc (wDevID, (PDSDRIVERDESC)dwParam1);
2438 FIXME("unknown message %d!\n", wMsg);
2441 return MMSYSERR_NOTSUPPORTED;
2445 OSStatus CoreAudio_wiAudioUnitIOProc(void *inRefCon,
2446 AudioUnitRenderActionFlags *ioActionFlags,
2447 const AudioTimeStamp *inTimeStamp,
2449 UInt32 inNumberFrames,
2450 AudioBufferList *ioData)
2452 WINE_WAVEIN* wwi = (WINE_WAVEIN*)inRefCon;
2453 OSStatus err = noErr;
2454 BOOL needNotify = FALSE;
2455 WAVEHDR* lpStorePtr;
2456 unsigned int dataToStore;
2457 unsigned int dataStored = 0;
2461 fprintf(stderr, "trace:wave:CoreAudio_wiAudioUnitIOProc (ioActionFlags = %08lx, "
2462 "inTimeStamp = { %f, %x%08x, %f, %x%08x, %08lx }, inBusNumber = %lu, inNumberFrames = %lu)\n",
2463 *ioActionFlags, inTimeStamp->mSampleTime, (DWORD)(inTimeStamp->mHostTime >>32),
2464 (DWORD)inTimeStamp->mHostTime, inTimeStamp->mRateScalar, (DWORD)(inTimeStamp->mWordClockTime >> 32),
2465 (DWORD)inTimeStamp->mWordClockTime, inTimeStamp->mFlags, inBusNumber, inNumberFrames);
2467 /* Render into audio buffer */
2468 /* FIXME: implement sample rate conversion on input. This will require
2469 * a different render strategy. We'll need to buffer the sound data
2470 * received here and pass it off to an AUConverter in another thread. */
2471 err = AudioUnitRender(wwi->audioUnit, ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, wwi->bufferList);
2475 fprintf(stderr, "err:wave:CoreAudio_wiAudioUnitIOProc AudioUnitRender failed with error %li\n", err);
2479 /* Copy from audio buffer to the wavehdrs */
2480 dataToStore = wwi->bufferList->mBuffers[0].mDataByteSize;
2482 OSSpinLockLock(&wwi->lock);
2484 lpStorePtr = wwi->lpQueuePtr;
2486 /* We might have been called while the waveIn device is being closed in
2487 * widClose. We have to do nothing in that case. The check of wwi->state
2488 * below ensures that. */
2489 while (dataToStore > 0 && wwi->state == WINE_WS_PLAYING && lpStorePtr)
2491 unsigned int room = lpStorePtr->dwBufferLength - lpStorePtr->dwBytesRecorded;
2492 unsigned int toCopy;
2495 fprintf(stderr, "trace:wave:CoreAudio_wiAudioUnitIOProc Looking to store %u bytes to wavehdr %p, which has room for %u\n",
2496 dataToStore, lpStorePtr, room);
2498 if (room >= dataToStore)
2499 toCopy = dataToStore;
2505 memcpy(lpStorePtr->lpData + lpStorePtr->dwBytesRecorded,
2506 (char*)wwi->bufferList->mBuffers[0].mData + dataStored, toCopy);
2507 lpStorePtr->dwBytesRecorded += toCopy;
2508 wwi->dwTotalRecorded += toCopy;
2509 dataStored += toCopy;
2510 dataToStore -= toCopy;
2516 lpStorePtr = lpStorePtr->lpNext;
2521 OSSpinLockUnlock(&wwi->lock);
2523 /* Restore the audio buffer list structure from backup, in case
2524 * AudioUnitRender clobbered it. (It modifies mDataByteSize and may even
2525 * give us a different mData buffer to avoid a copy.) */
2526 memcpy(wwi->bufferList, wwi->bufferListCopy, AUDIOBUFFERLISTSIZE(wwi->bufferList->mNumberBuffers));
2528 if (needNotify) wodSendNotifyInputCompletionsMessage(wwi);
2534 /**************************************************************************
2535 * widMessage (WINECOREAUDIO.6)
2537 DWORD WINAPI CoreAudio_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2538 DWORD dwParam1, DWORD dwParam2)
2540 FIXME("(%u, %04X, %08X, %08X, %08X): CoreAudio support not compiled into wine\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2541 return MMSYSERR_NOTENABLED;
2544 /**************************************************************************
2545 * wodMessage (WINECOREAUDIO.7)
2547 DWORD WINAPI CoreAudio_wodMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2548 DWORD dwParam1, DWORD dwParam2)
2550 FIXME("(%u, %04X, %08X, %08X, %08X): CoreAudio support not compiled into wine\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2551 return MMSYSERR_NOTENABLED;