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
37 #ifdef HAVE_COREAUDIO_COREAUDIO_H
38 #include <CoreAudio/CoreAudio.h>
39 #include <CoreFoundation/CoreFoundation.h>
40 #include <libkern/OSAtomic.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 */
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 #define MSG_TO_STR(x) case x: return #x
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);
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;
322 case kWaveOutNotifyCompletionsMessage:
323 wodHelper_NotifyCompletions(*(WINE_WAVEOUT_INSTANCE**)CFDataGetBytePtr(data), FALSE);
325 case kWaveInNotifyCompletionsMessage:
326 buffer = (UInt32 *) CFDataGetBytePtr(data);
327 widHelper_NotifyCompletions(&WInDev[buffer[0]]);
330 CFRunLoopStop(CFRunLoopGetCurrent());
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);
347 CFRunLoopSourceInvalidate(source);
349 CFRelease(port_ReceiveInMessageThread);
354 /**************************************************************************
355 * wodSendNotifyCompletionsMessage [internal]
356 * Call from AudioUnit IO thread can't use Wine debug channels.
358 static void wodSendNotifyCompletionsMessage(WINE_WAVEOUT_INSTANCE* wwo)
362 if (!Port_SendToMessageThread)
365 data = CFDataCreate(kCFAllocatorDefault, (UInt8 *)&wwo, sizeof(wwo));
369 CFMessagePortSendRequest(Port_SendToMessageThread, kWaveOutNotifyCompletionsMessage, data, 0.0, 0.0, NULL, NULL);
373 /**************************************************************************
374 * wodSendNotifyInputCompletionsMessage [internal]
375 * Call from AudioUnit IO thread can't use Wine debug channels.
377 static void wodSendNotifyInputCompletionsMessage(WINE_WAVEIN* wwi)
382 if (!Port_SendToMessageThread)
385 buffer = (UInt32) wwi->wiID;
387 data = CFDataCreate(kCFAllocatorDefault, (UInt8 *)&buffer, sizeof(buffer));
391 CFMessagePortSendRequest(Port_SendToMessageThread, kWaveInNotifyCompletionsMessage, data, 0.0, 0.0, NULL, NULL);
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) {
405 lpTime->u.sample = position / (format->wBitsPerSample / 8 * format->wf.nChannels);
406 TRACE("TIME_SAMPLES=%u\n", lpTime->u.sample);
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);
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);
429 WARN("Format %d not supported, using TIME_BYTES !\n", lpTime->wType);
430 lpTime->wType = TIME_BYTES;
433 lpTime->u.cb = position;
434 TRACE("TIME_BYTES=%u\n", lpTime->u.cb);
437 return MMSYSERR_NOERROR;
440 static BOOL supportedFormat(LPWAVEFORMATEX wf)
442 if (wf->nSamplesPerSec < DSBFREQUENCY_MIN || wf->nSamplesPerSec > DSBFREQUENCY_MAX)
445 if (wf->wFormatTag == WAVE_FORMAT_PCM) {
446 if (wf->nChannels >= 1 && wf->nChannels <= 2) {
447 if (wf->wBitsPerSample==8||wf->wBitsPerSample==16)
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)
459 WARN("wBitsPerSample != wValidBitsPerSample not supported yet\n");
462 WARN("only KSDATAFORMAT_SUBTYPE_PCM supported\n");
464 WARN("only WAVE_FORMAT_PCM and WAVE_FORMAT_EXTENSIBLE supported\n");
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)
485 AudioDeviceID devId = CoreAudio_DefaultDevice.outputDeviceID;
486 AudioObjectPropertyAddress propertyAddress;
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);
497 ERR("AudioObjectGetPropertyData for kAudioObjectPropertyName return %s\n", wine_dbgstr_fourcc(status));
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);
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));
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);
557 /******************************************************************
560 * Initialize CoreAudio_DefaultDevice
562 LONG CoreAudio_WaveInit(void)
566 AudioObjectPropertyAddress propertyAddress;
568 CFStringRef messageThreadPortName;
569 CFMessagePortRef port_ReceiveInMessageThread;
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);
587 ERR("AudioObjectGetPropertyData return %s for kAudioHardwarePropertyDefaultOutputDevice\n", wine_dbgstr_fourcc(status));
590 if (CoreAudio_DefaultDevice.outputDeviceID == kAudioDeviceUnknown) {
591 ERR("AudioObjectGetPropertyData: CoreAudio_DefaultDevice.outputDeviceID == kAudioDeviceUnknown\n");
595 if ( ! CoreAudio_GetDevCaps() )
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]));
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 */
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");
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);
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);
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 */
744 ERR("Message thread already started -- expect problems\n");
746 hThread = CreateThread(NULL, 0, messageThread, (LPVOID)port_ReceiveInMessageThread, 0, NULL);
749 ERR("Can't create message thread\n");
750 CFRelease(port_ReceiveInMessageThread);
751 CFRelease(Port_SendToMessageThread);
752 Port_SendToMessageThread = NULL;
756 /* The message thread is responsible for releasing port_ReceiveInMessageThread. */
761 void CoreAudio_WaveRelease(void)
763 /* Stop CFRunLoop in messageThread */
766 if (!Port_SendToMessageThread)
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);
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);
795 if (wwo->wFlags != DCB_NULL &&
796 !DriverCallback(wwo->waveDesc.dwCallback, wwo->wFlags,
797 (HDRVR)wwo->waveDesc.hWave, wMsg, wwo->waveDesc.dwInstance,
800 WARN("can't notify client !\n");
804 FIXME("Unknown callback message %u\n", wMsg);
809 /**************************************************************************
810 * wodGetDevCaps [internal]
812 static DWORD wodGetDevCaps(WORD wDevID, LPWAVEOUTCAPSW lpCaps, DWORD dwSize)
814 TRACE("(%u, %p, %u);\n", wDevID, lpCaps, dwSize);
816 if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
818 if (wDevID >= MAX_WAVEOUTDRV)
820 TRACE("MAX_WAVOUTDRV reached !\n");
821 return MMSYSERR_BADDEVICEID;
824 TRACE("dwSupport=(0x%x), dwFormats=(0x%x)\n", WOutDev[wDevID].caps.dwSupport, WOutDev[wDevID].caps.dwFormats);
825 memcpy(lpCaps, &WOutDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
826 return MMSYSERR_NOERROR;
829 /**************************************************************************
832 static DWORD wodOpen(WORD wDevID, WINE_WAVEOUT_INSTANCE** pInstance, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
834 WINE_WAVEOUT_INSTANCE* wwo;
836 AudioStreamBasicDescription streamFormat;
837 AudioUnit audioUnit = NULL;
838 BOOL auInited = FALSE;
840 TRACE("(%u, %p, %p, %08x);\n", wDevID, pInstance, lpDesc, dwFlags);
843 WARN("Invalid Parameter !\n");
844 return MMSYSERR_INVALPARAM;
846 if (wDevID >= MAX_WAVEOUTDRV) {
847 TRACE("MAX_WAVOUTDRV reached !\n");
848 return MMSYSERR_BADDEVICEID;
851 TRACE("Format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
852 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
853 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
855 if (!supportedFormat(lpDesc->lpFormat))
857 WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
858 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
859 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
860 return WAVERR_BADFORMAT;
863 if (dwFlags & WAVE_FORMAT_QUERY)
865 TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
866 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
867 lpDesc->lpFormat->nSamplesPerSec);
868 return MMSYSERR_NOERROR;
871 /* nBlockAlign and nAvgBytesPerSec are output variables for dsound */
872 if (lpDesc->lpFormat->nBlockAlign != lpDesc->lpFormat->nChannels*lpDesc->lpFormat->wBitsPerSample/8) {
873 lpDesc->lpFormat->nBlockAlign = lpDesc->lpFormat->nChannels*lpDesc->lpFormat->wBitsPerSample/8;
874 WARN("Fixing nBlockAlign\n");
876 if (lpDesc->lpFormat->nAvgBytesPerSec!= lpDesc->lpFormat->nSamplesPerSec*lpDesc->lpFormat->nBlockAlign) {
877 lpDesc->lpFormat->nAvgBytesPerSec = lpDesc->lpFormat->nSamplesPerSec*lpDesc->lpFormat->nBlockAlign;
878 WARN("Fixing nAvgBytesPerSec\n");
881 /* We proceed in three phases:
882 * o Allocate the device instance, marking it as opening
883 * o Create, configure, and start the Audio Unit. To avoid deadlock,
884 * this has to be done without holding wwo->lock.
885 * o If that was successful, finish setting up our instance and add it
886 * to the device's list.
887 * Otherwise, clean up and deallocate the instance.
889 wwo = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*wwo));
891 return MMSYSERR_NOMEM;
894 wwo->state = WINE_WS_OPENING;
896 if (!AudioUnit_CreateDefaultAudioUnit((void *) wwo, &audioUnit))
898 ERR("CoreAudio_CreateDefaultAudioUnit(0x%04x) failed\n", wDevID);
899 ret = MMSYSERR_ERROR;
903 streamFormat.mFormatID = kAudioFormatLinearPCM;
904 streamFormat.mFormatFlags = kLinearPCMFormatFlagIsPacked;
905 /* FIXME check for 32bits float -> kLinearPCMFormatFlagIsFloat */
906 if (lpDesc->lpFormat->wBitsPerSample != 8)
907 streamFormat.mFormatFlags |= kLinearPCMFormatFlagIsSignedInteger;
908 # ifdef WORDS_BIGENDIAN
909 streamFormat.mFormatFlags |= kLinearPCMFormatFlagIsBigEndian; /* FIXME Wave format is little endian */
912 streamFormat.mSampleRate = lpDesc->lpFormat->nSamplesPerSec;
913 streamFormat.mChannelsPerFrame = lpDesc->lpFormat->nChannels;
914 streamFormat.mFramesPerPacket = 1;
915 streamFormat.mBitsPerChannel = lpDesc->lpFormat->wBitsPerSample;
916 streamFormat.mBytesPerFrame = streamFormat.mBitsPerChannel * streamFormat.mChannelsPerFrame / 8;
917 streamFormat.mBytesPerPacket = streamFormat.mBytesPerFrame * streamFormat.mFramesPerPacket;
919 ret = AudioUnit_InitializeWithStreamDescription(audioUnit, &streamFormat);
922 ret = WAVERR_BADFORMAT; /* FIXME return an error based on the OSStatus */
927 AudioUnit_SetVolume(audioUnit, LOWORD(WOutDev[wDevID].device_volume) / 65535.0f,
928 HIWORD(WOutDev[wDevID].device_volume) / 65535.0f);
930 /* Our render callback CoreAudio_woAudioUnitIOProc may be called before
931 * AudioOutputUnitStart returns. Core Audio will grab its own internal
932 * lock before calling it and the callback grabs wwo->lock. This would
933 * deadlock if we were holding wwo->lock.
934 * Also, the callback has to safely do nothing in that case, because
935 * wwo hasn't been completely filled out, yet. This is assured by state
936 * being WINE_WS_OPENING. */
937 ret = AudioOutputUnitStart(audioUnit);
940 ERR("AudioOutputUnitStart failed: %08x\n", ret);
941 ret = MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
946 OSSpinLockLock(&wwo->lock);
947 assert(wwo->state == WINE_WS_OPENING);
949 wwo->audioUnit = audioUnit;
950 wwo->streamDescription = streamFormat;
952 wwo->state = WINE_WS_PLAYING;
954 wwo->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
956 wwo->waveDesc = *lpDesc;
957 copyFormat(lpDesc->lpFormat, &wwo->format);
959 WOutDev[wDevID].trace_on = TRACE_ON(wave);
960 WOutDev[wDevID].warn_on = WARN_ON(wave);
961 WOutDev[wDevID].err_on = ERR_ON(wave);
963 OSSpinLockUnlock(&wwo->lock);
965 OSSpinLockLock(&WOutDev[wDevID].lock);
966 list_add_head(&WOutDev[wDevID].instances, &wwo->entry);
967 OSSpinLockUnlock(&WOutDev[wDevID].lock);
970 TRACE("opened instance %p\n", wwo);
972 wodNotifyClient(wwo, WOM_OPEN, 0L, 0L);
974 return MMSYSERR_NOERROR;
980 AudioUnitUninitialize(audioUnit);
981 AudioUnit_CloseAudioUnit(audioUnit);
984 OSSpinLockLock(&wwo->lock);
985 assert(wwo->state == WINE_WS_OPENING);
986 /* OSSpinLockUnlock(&wwo->lock); *//* No need, about to free */
987 HeapFree(GetProcessHeap(), 0, wwo);
992 /**************************************************************************
993 * wodClose [internal]
995 static DWORD wodClose(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo)
997 DWORD ret = MMSYSERR_NOERROR;
999 TRACE("(%u, %p);\n", wDevID, wwo);
1001 if (wDevID >= MAX_WAVEOUTDRV)
1003 WARN("bad device ID !\n");
1004 return MMSYSERR_BADDEVICEID;
1007 OSSpinLockLock(&wwo->lock);
1008 if (wwo->lpQueuePtr)
1010 OSSpinLockUnlock(&wwo->lock);
1011 WARN("buffers still playing !\n");
1012 return WAVERR_STILLPLAYING;
1016 AudioUnit audioUnit = wwo->audioUnit;
1018 /* sanity check: this should not happen since the device must have been reset before */
1019 if (wwo->lpQueuePtr || wwo->lpPlayPtr) ERR("out of sync\n");
1021 wwo->state = WINE_WS_CLOSING; /* mark the device as closing */
1022 wwo->audioUnit = NULL;
1024 OSSpinLockUnlock(&wwo->lock);
1026 err = AudioUnitUninitialize(audioUnit);
1028 ERR("AudioUnitUninitialize return %s\n", wine_dbgstr_fourcc(err));
1029 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1032 if ( !AudioUnit_CloseAudioUnit(audioUnit) )
1034 ERR("Can't close AudioUnit\n");
1035 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1038 OSSpinLockLock(&WOutDev[wDevID].lock);
1039 list_remove(&wwo->entry);
1040 OSSpinLockUnlock(&WOutDev[wDevID].lock);
1042 wodNotifyClient(wwo, WOM_CLOSE, 0L, 0L);
1044 HeapFree(GetProcessHeap(), 0, wwo);
1050 /**************************************************************************
1051 * wodPrepare [internal]
1053 static DWORD wodPrepare(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1055 TRACE("(%u, %p, %p, %08x);\n", wDevID, wwo, lpWaveHdr, dwSize);
1057 if (wDevID >= MAX_WAVEOUTDRV) {
1058 WARN("bad device ID !\n");
1059 return MMSYSERR_BADDEVICEID;
1062 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1063 return WAVERR_STILLPLAYING;
1065 lpWaveHdr->dwFlags |= WHDR_PREPARED;
1066 lpWaveHdr->dwFlags &= ~WHDR_DONE;
1068 return MMSYSERR_NOERROR;
1071 /**************************************************************************
1072 * wodUnprepare [internal]
1074 static DWORD wodUnprepare(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1076 TRACE("(%u, %p, %p, %08x);\n", wDevID, wwo, lpWaveHdr, dwSize);
1078 if (wDevID >= MAX_WAVEOUTDRV) {
1079 WARN("bad device ID !\n");
1080 return MMSYSERR_BADDEVICEID;
1083 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1084 return WAVERR_STILLPLAYING;
1086 lpWaveHdr->dwFlags &= ~WHDR_PREPARED;
1087 lpWaveHdr->dwFlags |= WHDR_DONE;
1089 return MMSYSERR_NOERROR;
1093 /**************************************************************************
1094 * wodHelper_CheckForLoopBegin [internal]
1096 * Check if the new waveheader is the beginning of a loop, and set up
1098 * This is called with the WAVEOUT_INSTANCE lock held.
1099 * Call from AudioUnit IO thread can't use Wine debug channels.
1101 static void wodHelper_CheckForLoopBegin(WINE_WAVEOUT_INSTANCE* wwo)
1103 LPWAVEHDR lpWaveHdr = wwo->lpPlayPtr;
1105 if (lpWaveHdr->dwFlags & WHDR_BEGINLOOP)
1109 if (WOutDev[wwo->woID].warn_on)
1110 fprintf(stderr, "warn:winecoreaudio:wodHelper_CheckForLoopBegin Already in a loop. Discarding loop on this header (%p)\n", lpWaveHdr);
1114 if (WOutDev[wwo->woID].trace_on)
1115 fprintf(stderr, "trace:winecoreaudio:wodHelper_CheckForLoopBegin Starting loop (%dx) with %p\n", lpWaveHdr->dwLoops, lpWaveHdr);
1117 wwo->lpLoopPtr = lpWaveHdr;
1118 /* Windows does not touch WAVEHDR.dwLoops,
1119 * so we need to make an internal copy */
1120 wwo->dwLoops = lpWaveHdr->dwLoops;
1126 /**************************************************************************
1127 * wodHelper_PlayPtrNext [internal]
1129 * Advance the play pointer to the next waveheader, looping if required.
1130 * This is called with the WAVEOUT_INSTANCE lock held.
1131 * Call from AudioUnit IO thread can't use Wine debug channels.
1133 static void wodHelper_PlayPtrNext(WINE_WAVEOUT_INSTANCE* wwo)
1135 BOOL didLoopBack = FALSE;
1137 wwo->dwPartialOffset = 0;
1138 if ((wwo->lpPlayPtr->dwFlags & WHDR_ENDLOOP) && wwo->lpLoopPtr)
1140 /* We're at the end of a loop, loop if required */
1141 if (wwo->dwLoops > 1)
1144 wwo->lpPlayPtr = wwo->lpLoopPtr;
1149 wwo->lpLoopPtr = NULL;
1154 /* We didn't loop back. Advance to the next wave header */
1155 wwo->lpPlayPtr = wwo->lpPlayPtr->lpNext;
1158 wodHelper_CheckForLoopBegin(wwo);
1162 /* Send the "done" notification for each WAVEHDR in a list. The list must be
1163 * free-standing. It should not be part of a device instance's queue.
1164 * This function must be called with the WAVEOUT_INSTANCE lock *not* held.
1165 * Furthermore, it does not lock it, itself. That's because the callback to the
1166 * application may prompt the application to operate on the device, and we don't
1169 static void wodHelper_NotifyDoneForList(WINE_WAVEOUT_INSTANCE* wwo, LPWAVEHDR lpWaveHdr)
1173 LPWAVEHDR lpNext = lpWaveHdr->lpNext;
1175 lpWaveHdr->lpNext = NULL;
1176 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1177 lpWaveHdr->dwFlags |= WHDR_DONE;
1178 wodNotifyClient(wwo, WOM_DONE, (DWORD_PTR)lpWaveHdr, 0);
1184 /* if force is TRUE then notify the client that all the headers were completed
1186 static void wodHelper_NotifyCompletions(WINE_WAVEOUT_INSTANCE* wwo, BOOL force)
1188 LPWAVEHDR lpFirstDoneWaveHdr = NULL;
1190 OSSpinLockLock(&wwo->lock);
1192 /* First, excise all of the done headers from the queue into
1193 * a free-standing list. */
1196 lpFirstDoneWaveHdr = wwo->lpQueuePtr;
1197 wwo->lpQueuePtr = NULL;
1201 LPWAVEHDR lpWaveHdr;
1202 LPWAVEHDR lpLastDoneWaveHdr = NULL;
1204 /* Start from lpQueuePtr and keep notifying until:
1205 * - we hit an unwritten wavehdr
1206 * - we hit the beginning of a running loop
1207 * - we hit a wavehdr which hasn't finished playing
1210 lpWaveHdr = wwo->lpQueuePtr;
1212 lpWaveHdr != wwo->lpPlayPtr &&
1213 lpWaveHdr != wwo->lpLoopPtr;
1214 lpWaveHdr = lpWaveHdr->lpNext
1217 if (!lpFirstDoneWaveHdr)
1218 lpFirstDoneWaveHdr = lpWaveHdr;
1219 lpLastDoneWaveHdr = lpWaveHdr;
1222 if (lpLastDoneWaveHdr)
1224 wwo->lpQueuePtr = lpLastDoneWaveHdr->lpNext;
1225 lpLastDoneWaveHdr->lpNext = NULL;
1229 OSSpinLockUnlock(&wwo->lock);
1231 /* Now, send the "done" notification for each header in our list. */
1232 wodHelper_NotifyDoneForList(wwo, lpFirstDoneWaveHdr);
1236 /**************************************************************************
1237 * wodWrite [internal]
1240 static DWORD wodWrite(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1244 TRACE("(%u, %p, %p, %lu, %08X);\n", wDevID, wwo, lpWaveHdr, (unsigned long)lpWaveHdr->dwBufferLength, dwSize);
1246 /* first, do the sanity checks... */
1247 if (wDevID >= MAX_WAVEOUTDRV)
1249 WARN("bad dev ID !\n");
1250 return MMSYSERR_BADDEVICEID;
1253 if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
1255 TRACE("unprepared\n");
1256 return WAVERR_UNPREPARED;
1259 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1261 TRACE("still playing\n");
1262 return WAVERR_STILLPLAYING;
1265 lpWaveHdr->dwFlags &= ~WHDR_DONE;
1266 lpWaveHdr->dwFlags |= WHDR_INQUEUE;
1267 lpWaveHdr->lpNext = 0;
1269 OSSpinLockLock(&wwo->lock);
1270 /* insert buffer at the end of queue */
1271 for (wh = &(wwo->lpQueuePtr); *wh; wh = &((*wh)->lpNext))
1275 if (!wwo->lpPlayPtr)
1277 wwo->lpPlayPtr = lpWaveHdr;
1279 wodHelper_CheckForLoopBegin(wwo);
1281 wwo->dwPartialOffset = 0;
1283 OSSpinLockUnlock(&wwo->lock);
1285 return MMSYSERR_NOERROR;
1288 /**************************************************************************
1289 * wodPause [internal]
1291 static DWORD wodPause(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo)
1295 TRACE("(%u, %p);!\n", wDevID, wwo);
1297 if (wDevID >= MAX_WAVEOUTDRV)
1299 WARN("bad device ID !\n");
1300 return MMSYSERR_BADDEVICEID;
1303 /* The order of the following operations is important since we can't hold
1304 * the mutex while we make an Audio Unit call. Stop the Audio Unit before
1305 * setting the PAUSED state. In wodRestart, the order is reversed. This
1306 * guarantees that we can't get into a situation where the state is
1307 * PLAYING but the Audio Unit isn't running. Although we can be in PAUSED
1308 * state with the Audio Unit still running, that's harmless because the
1309 * render callback will just produce silence.
1311 status = AudioOutputUnitStop(wwo->audioUnit);
1313 WARN("AudioOutputUnitStop return %s\n", wine_dbgstr_fourcc(status));
1315 OSSpinLockLock(&wwo->lock);
1316 if (wwo->state == WINE_WS_PLAYING)
1317 wwo->state = WINE_WS_PAUSED;
1318 OSSpinLockUnlock(&wwo->lock);
1320 return MMSYSERR_NOERROR;
1323 /**************************************************************************
1324 * wodRestart [internal]
1326 static DWORD wodRestart(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo)
1330 TRACE("(%u, %p);\n", wDevID, wwo);
1332 if (wDevID >= MAX_WAVEOUTDRV )
1334 WARN("bad device ID !\n");
1335 return MMSYSERR_BADDEVICEID;
1338 /* The order of the following operations is important since we can't hold
1339 * the mutex while we make an Audio Unit call. Set the PLAYING
1340 * state before starting the Audio Unit. In wodPause, the order is
1341 * reversed. This guarantees that we can't get into a situation where
1342 * the state is PLAYING but the Audio Unit isn't running.
1343 * Although we can be in PAUSED state with the Audio Unit still running,
1344 * that's harmless because the render callback will just produce silence.
1346 OSSpinLockLock(&wwo->lock);
1347 if (wwo->state == WINE_WS_PAUSED)
1348 wwo->state = WINE_WS_PLAYING;
1349 OSSpinLockUnlock(&wwo->lock);
1351 status = AudioOutputUnitStart(wwo->audioUnit);
1353 ERR("AudioOutputUnitStart return %s\n", wine_dbgstr_fourcc(status));
1354 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1357 return MMSYSERR_NOERROR;
1360 /**************************************************************************
1361 * wodReset [internal]
1363 static DWORD wodReset(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo)
1366 LPWAVEHDR lpSavedQueuePtr;
1368 TRACE("(%u, %p);\n", wDevID, wwo);
1370 if (wDevID >= MAX_WAVEOUTDRV)
1372 WARN("bad device ID !\n");
1373 return MMSYSERR_BADDEVICEID;
1376 OSSpinLockLock(&wwo->lock);
1378 if (wwo->state == WINE_WS_CLOSING || wwo->state == WINE_WS_OPENING)
1380 OSSpinLockUnlock(&wwo->lock);
1381 WARN("resetting a closed device\n");
1382 return MMSYSERR_INVALHANDLE;
1385 lpSavedQueuePtr = wwo->lpQueuePtr;
1386 wwo->lpPlayPtr = wwo->lpQueuePtr = wwo->lpLoopPtr = NULL;
1387 wwo->state = WINE_WS_PLAYING;
1388 wwo->dwPlayedTotal = 0;
1390 wwo->dwPartialOffset = 0; /* Clear partial wavehdr */
1392 OSSpinLockUnlock(&wwo->lock);
1394 status = AudioOutputUnitStart(wwo->audioUnit);
1397 ERR( "AudioOutputUnitStart return %s\n", wine_dbgstr_fourcc(status));
1398 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1401 /* Now, send the "done" notification for each header in our list. */
1402 /* Do this last so the reset operation is effectively complete before the
1403 * app does whatever it's going to do in response to these notifications. */
1404 wodHelper_NotifyDoneForList(wwo, lpSavedQueuePtr);
1406 return MMSYSERR_NOERROR;
1409 /**************************************************************************
1410 * wodBreakLoop [internal]
1412 static DWORD wodBreakLoop(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo)
1414 TRACE("(%u, %p);\n", wDevID, wwo);
1416 if (wDevID >= MAX_WAVEOUTDRV)
1418 WARN("bad device ID !\n");
1419 return MMSYSERR_BADDEVICEID;
1422 OSSpinLockLock(&wwo->lock);
1424 if (wwo->lpLoopPtr != NULL)
1426 /* ensure exit at end of current loop */
1430 OSSpinLockUnlock(&wwo->lock);
1432 return MMSYSERR_NOERROR;
1435 /**************************************************************************
1436 * wodGetPosition [internal]
1438 static DWORD wodGetPosition(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, LPMMTIME lpTime, DWORD uSize)
1442 TRACE("(%u, %p, %p, %u);\n", wDevID, wwo, lpTime, uSize);
1444 if (wDevID >= MAX_WAVEOUTDRV)
1446 WARN("bad device ID !\n");
1447 return MMSYSERR_BADDEVICEID;
1450 /* if null pointer to time structure return error */
1451 if (lpTime == NULL) return MMSYSERR_INVALPARAM;
1453 OSSpinLockLock(&wwo->lock);
1454 val = wwo->dwPlayedTotal;
1455 OSSpinLockUnlock(&wwo->lock);
1457 return bytes_to_mmtime(lpTime, val, &wwo->format);
1460 /**************************************************************************
1461 * wodGetVolume [internal]
1463 static DWORD wodGetVolume(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, LPDWORD lpdwVol)
1465 if (wDevID >= MAX_WAVEOUTDRV)
1467 WARN("bad device ID !\n");
1468 return MMSYSERR_BADDEVICEID;
1471 TRACE("(%u, %p, %p);\n", wDevID, wwo, lpdwVol);
1478 AudioUnit_GetVolume(wwo->audioUnit, &left, &right);
1479 *lpdwVol = (WORD)(left * 0xFFFFl) + ((WORD)(right * 0xFFFFl) << 16);
1482 *lpdwVol = WOutDev[wDevID].device_volume;
1484 return MMSYSERR_NOERROR;
1487 /**************************************************************************
1488 * wodSetVolume [internal]
1490 static DWORD wodSetVolume(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, DWORD dwParam)
1495 if (wDevID >= MAX_WAVEOUTDRV)
1497 WARN("bad device ID !\n");
1498 return MMSYSERR_BADDEVICEID;
1501 left = LOWORD(dwParam) / 65535.0f;
1502 right = HIWORD(dwParam) / 65535.0f;
1504 TRACE("(%u, %p, %08x);\n", wDevID, wwo, dwParam);
1507 AudioUnit_SetVolume(wwo->audioUnit, left, right);
1510 OSSpinLockLock(&WOutDev[wDevID].lock);
1511 LIST_FOR_EACH_ENTRY(wwo, &WOutDev[wDevID].instances, WINE_WAVEOUT_INSTANCE, entry)
1512 AudioUnit_SetVolume(wwo->audioUnit, left, right);
1513 OSSpinLockUnlock(&WOutDev[wDevID].lock);
1515 WOutDev[wDevID].device_volume = dwParam;
1518 return MMSYSERR_NOERROR;
1521 /**************************************************************************
1522 * wodGetNumDevs [internal]
1524 static DWORD wodGetNumDevs(void)
1527 return MAX_WAVEOUTDRV;
1530 /**************************************************************************
1531 * wodDevInterfaceSize [internal]
1533 static DWORD wodDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
1535 TRACE("(%u, %p)\n", wDevID, dwParam1);
1537 *dwParam1 = MultiByteToWideChar(CP_UNIXCP, 0, WOutDev[wDevID].cadev->interface_name, -1,
1538 NULL, 0 ) * sizeof(WCHAR);
1539 return MMSYSERR_NOERROR;
1542 /**************************************************************************
1543 * wodDevInterface [internal]
1545 static DWORD wodDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
1548 if (dwParam2 >= MultiByteToWideChar(CP_UNIXCP, 0, WOutDev[wDevID].cadev->interface_name, -1,
1549 NULL, 0 ) * sizeof(WCHAR))
1551 MultiByteToWideChar(CP_UNIXCP, 0, WOutDev[wDevID].cadev->interface_name, -1,
1552 dwParam1, dwParam2 / sizeof(WCHAR));
1553 return MMSYSERR_NOERROR;
1555 return MMSYSERR_INVALPARAM;
1558 /**************************************************************************
1559 * widDsCreate [internal]
1561 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
1563 TRACE("(%d,%p)\n",wDevID,drv);
1565 FIXME("DirectSound not implemented\n");
1566 FIXME("The (slower) DirectSound HEL mode will be used instead.\n");
1567 return MMSYSERR_NOTSUPPORTED;
1570 /**************************************************************************
1571 * wodDsDesc [internal]
1573 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc)
1575 /* The DirectSound HEL will automatically wrap a non-DirectSound-capable
1576 * driver in a DirectSound adaptor, thus allowing the driver to be used by
1577 * DirectSound clients. However, it only does this if we respond
1578 * successfully to the DRV_QUERYDSOUNDDESC message. It's enough to fill in
1579 * the driver and device names of the description output parameter. */
1580 *desc = WOutDev[wDevID].cadev->ds_desc;
1581 return MMSYSERR_NOERROR;
1584 /**************************************************************************
1585 * wodMessage (WINECOREAUDIO.7)
1587 DWORD WINAPI CoreAudio_wodMessage(UINT wDevID, UINT wMsg, DWORD_PTR dwUser,
1588 DWORD_PTR dwParam1, DWORD_PTR dwParam2)
1590 WINE_WAVEOUT_INSTANCE* wwo = (WINE_WAVEOUT_INSTANCE*)dwUser;
1592 TRACE("(%u, %s, %p, %p, %p);\n",
1593 wDevID, getMessage(wMsg), (void*)dwUser, (void*)dwParam1, (void*)dwParam2);
1601 /* FIXME: Pretend this is supported */
1603 case WODM_OPEN: return wodOpen(wDevID, (WINE_WAVEOUT_INSTANCE**)dwUser, (LPWAVEOPENDESC) dwParam1, dwParam2);
1604 case WODM_CLOSE: return wodClose(wDevID, wwo);
1605 case WODM_WRITE: return wodWrite(wDevID, wwo, (LPWAVEHDR) dwParam1, dwParam2);
1606 case WODM_PAUSE: return wodPause(wDevID, wwo);
1607 case WODM_GETPOS: return wodGetPosition(wDevID, wwo, (LPMMTIME) dwParam1, dwParam2);
1608 case WODM_BREAKLOOP: return wodBreakLoop(wDevID, wwo);
1609 case WODM_PREPARE: return wodPrepare(wDevID, wwo, (LPWAVEHDR)dwParam1, dwParam2);
1610 case WODM_UNPREPARE: return wodUnprepare(wDevID, wwo, (LPWAVEHDR)dwParam1, dwParam2);
1612 case WODM_GETDEVCAPS: return wodGetDevCaps(wDevID, (LPWAVEOUTCAPSW) dwParam1, dwParam2);
1613 case WODM_GETNUMDEVS: return wodGetNumDevs();
1617 case WODM_GETPLAYBACKRATE:
1618 case WODM_SETPLAYBACKRATE: return MMSYSERR_NOTSUPPORTED;
1619 case WODM_GETVOLUME: return wodGetVolume(wDevID, wwo, (LPDWORD)dwParam1);
1620 case WODM_SETVOLUME: return wodSetVolume(wDevID, wwo, dwParam1);
1621 case WODM_RESTART: return wodRestart(wDevID, wwo);
1622 case WODM_RESET: return wodReset(wDevID, wwo);
1624 case DRV_QUERYDEVICEINTERFACESIZE: return wodDevInterfaceSize (wDevID, (LPDWORD)dwParam1);
1625 case DRV_QUERYDEVICEINTERFACE: return wodDevInterface (wDevID, (PWCHAR)dwParam1, dwParam2);
1626 case DRV_QUERYDSOUNDIFACE: return wodDsCreate (wDevID, (PIDSDRIVER*)dwParam1);
1627 case DRV_QUERYDSOUNDDESC: return wodDsDesc (wDevID, (PDSDRIVERDESC)dwParam1);
1630 FIXME("unknown message %d!\n", wMsg);
1633 return MMSYSERR_NOTSUPPORTED;
1636 /*======================================================================*
1637 * Low level DSOUND implementation *
1638 *======================================================================*/
1640 typedef struct IDsDriverImpl IDsDriverImpl;
1641 typedef struct IDsDriverBufferImpl IDsDriverBufferImpl;
1643 struct IDsDriverImpl
1645 /* IUnknown fields */
1646 const IDsDriverVtbl *lpVtbl;
1648 /* IDsDriverImpl fields */
1650 IDsDriverBufferImpl*primary;
1653 struct IDsDriverBufferImpl
1655 /* IUnknown fields */
1656 const IDsDriverBufferVtbl *lpVtbl;
1658 /* IDsDriverBufferImpl fields */
1665 CoreAudio IO threaded callback,
1666 we can't call Wine debug channels, critical section or anything using NtCurrentTeb here.
1668 OSStatus CoreAudio_woAudioUnitIOProc(void *inRefCon,
1669 AudioUnitRenderActionFlags *ioActionFlags,
1670 const AudioTimeStamp *inTimeStamp,
1672 UInt32 inNumberFrames,
1673 AudioBufferList *ioData)
1676 WINE_WAVEOUT_INSTANCE* wwo = (WINE_WAVEOUT_INSTANCE*)inRefCon;
1679 unsigned int dataNeeded = ioData->mBuffers[0].mDataByteSize;
1680 unsigned int dataProvided = 0;
1682 OSSpinLockLock(&wwo->lock);
1684 /* We might have been called before wwo has been completely filled out by
1685 * wodOpen, or while it's being closed in wodClose. We have to do nothing
1686 * in that case. The check of wwo->state below ensures that. */
1687 while (dataNeeded > 0 && wwo->state == WINE_WS_PLAYING && wwo->lpPlayPtr)
1689 unsigned int available = wwo->lpPlayPtr->dwBufferLength - wwo->dwPartialOffset;
1690 unsigned int toCopy;
1692 if (available >= dataNeeded)
1693 toCopy = dataNeeded;
1699 memcpy((char*)ioData->mBuffers[0].mData + dataProvided,
1700 wwo->lpPlayPtr->lpData + wwo->dwPartialOffset, toCopy);
1701 wwo->dwPartialOffset += toCopy;
1702 wwo->dwPlayedTotal += toCopy;
1703 dataProvided += toCopy;
1704 dataNeeded -= toCopy;
1705 available -= toCopy;
1710 wodHelper_PlayPtrNext(wwo);
1714 ioData->mBuffers[0].mDataByteSize = dataProvided;
1716 OSSpinLockUnlock(&wwo->lock);
1718 /* We can't provide any more wave data. Fill the rest with silence. */
1722 *ioActionFlags |= kAudioUnitRenderAction_OutputIsSilence;
1723 memset((char*)ioData->mBuffers[0].mData + dataProvided, 0, dataNeeded);
1724 dataProvided += dataNeeded;
1728 /* We only fill buffer 0. Set any others that might be requested to 0. */
1729 for (buffer = 1; buffer < ioData->mNumberBuffers; buffer++)
1731 memset(ioData->mBuffers[buffer].mData, 0, ioData->mBuffers[buffer].mDataByteSize);
1734 if (needNotify) wodSendNotifyCompletionsMessage(wwo);
1739 /*======================================================================*
1740 * Low level WAVE IN implementation *
1741 *======================================================================*/
1743 /**************************************************************************
1744 * widNotifyClient [internal]
1746 static void widNotifyClient(WINE_WAVEIN* wwi, WORD wMsg, DWORD_PTR dwParam1, DWORD_PTR dwParam2)
1748 TRACE("wMsg = 0x%04x dwParm1 = %04lX dwParam2 = %04lX\n", wMsg, dwParam1, dwParam2);
1755 if (wwi->wFlags != DCB_NULL &&
1756 !DriverCallback(wwi->waveDesc.dwCallback, wwi->wFlags,
1757 (HDRVR)wwi->waveDesc.hWave, wMsg, wwi->waveDesc.dwInstance,
1758 dwParam1, dwParam2))
1760 WARN("can't notify client !\n");
1764 FIXME("Unknown callback message %u\n", wMsg);
1769 /**************************************************************************
1770 * widHelper_NotifyCompletions [internal]
1772 static void widHelper_NotifyCompletions(WINE_WAVEIN* wwi)
1774 LPWAVEHDR lpWaveHdr;
1775 LPWAVEHDR lpFirstDoneWaveHdr = NULL;
1776 LPWAVEHDR lpLastDoneWaveHdr = NULL;
1778 OSSpinLockLock(&wwi->lock);
1780 /* First, excise all of the done headers from the queue into
1781 * a free-standing list. */
1783 /* Start from lpQueuePtr and keep notifying until:
1784 * - we hit an unfilled wavehdr
1785 * - we hit the end of the list
1788 lpWaveHdr = wwi->lpQueuePtr;
1790 lpWaveHdr->dwBytesRecorded >= lpWaveHdr->dwBufferLength;
1791 lpWaveHdr = lpWaveHdr->lpNext
1794 if (!lpFirstDoneWaveHdr)
1795 lpFirstDoneWaveHdr = lpWaveHdr;
1796 lpLastDoneWaveHdr = lpWaveHdr;
1799 if (lpLastDoneWaveHdr)
1801 wwi->lpQueuePtr = lpLastDoneWaveHdr->lpNext;
1802 lpLastDoneWaveHdr->lpNext = NULL;
1805 OSSpinLockUnlock(&wwi->lock);
1807 /* Now, send the "done" notification for each header in our list. */
1808 lpWaveHdr = lpFirstDoneWaveHdr;
1811 LPWAVEHDR lpNext = lpWaveHdr->lpNext;
1813 lpWaveHdr->lpNext = NULL;
1814 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1815 lpWaveHdr->dwFlags |= WHDR_DONE;
1816 widNotifyClient(wwi, WIM_DATA, (DWORD_PTR)lpWaveHdr, 0);
1823 /**************************************************************************
1824 * widGetDevCaps [internal]
1826 static DWORD widGetDevCaps(WORD wDevID, LPWAVEINCAPSW lpCaps, DWORD dwSize)
1828 TRACE("(%u, %p, %u);\n", wDevID, lpCaps, dwSize);
1830 if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
1832 if (wDevID >= MAX_WAVEINDRV)
1834 TRACE("MAX_WAVEINDRV reached !\n");
1835 return MMSYSERR_BADDEVICEID;
1838 memcpy(lpCaps, &WInDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
1839 return MMSYSERR_NOERROR;
1843 /**************************************************************************
1844 * widHelper_DestroyAudioBufferList [internal]
1845 * Convenience function to dispose of our audio buffers
1847 static void widHelper_DestroyAudioBufferList(AudioBufferList* list)
1852 for (i = 0; i < list->mNumberBuffers; i++)
1854 if (list->mBuffers[i].mData)
1855 HeapFree(GetProcessHeap(), 0, list->mBuffers[i].mData);
1857 HeapFree(GetProcessHeap(), 0, list);
1862 #define AUDIOBUFFERLISTSIZE(numBuffers) (offsetof(AudioBufferList, mBuffers) + (numBuffers) * sizeof(AudioBuffer))
1864 /**************************************************************************
1865 * widHelper_AllocateAudioBufferList [internal]
1866 * Convenience function to allocate our audio buffers
1868 static AudioBufferList* widHelper_AllocateAudioBufferList(UInt32 numChannels, UInt32 bitsPerChannel, UInt32 bufferFrames, BOOL interleaved)
1871 UInt32 channelsPerFrame;
1872 UInt32 bytesPerFrame;
1873 UInt32 bytesPerBuffer;
1874 AudioBufferList* list;
1879 /* For interleaved audio, we allocate one buffer for all channels. */
1881 channelsPerFrame = numChannels;
1885 numBuffers = numChannels;
1886 channelsPerFrame = 1;
1889 bytesPerFrame = bitsPerChannel * channelsPerFrame / 8;
1890 bytesPerBuffer = bytesPerFrame * bufferFrames;
1892 list = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, AUDIOBUFFERLISTSIZE(numBuffers));
1896 list->mNumberBuffers = numBuffers;
1897 for (i = 0; i < numBuffers; ++i)
1899 list->mBuffers[i].mNumberChannels = channelsPerFrame;
1900 list->mBuffers[i].mDataByteSize = bytesPerBuffer;
1901 list->mBuffers[i].mData = HeapAlloc(GetProcessHeap(), 0, bytesPerBuffer);
1902 if (list->mBuffers[i].mData == NULL)
1904 widHelper_DestroyAudioBufferList(list);
1912 /**************************************************************************
1913 * widOpen [internal]
1915 static DWORD widOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
1920 TRACE("(%u, %p, %08X);\n", wDevID, lpDesc, dwFlags);
1923 WARN("Invalid Parameter !\n");
1924 return MMSYSERR_INVALPARAM;
1926 if (wDevID >= MAX_WAVEINDRV)
1928 TRACE ("MAX_WAVEINDRV reached !\n");
1929 return MMSYSERR_BADDEVICEID;
1932 TRACE("Format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
1933 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1934 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
1936 if (!supportedFormat(lpDesc->lpFormat) ||
1937 lpDesc->lpFormat->nSamplesPerSec != AudioUnit_GetInputDeviceSampleRate()
1940 WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
1941 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1942 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
1943 return WAVERR_BADFORMAT;
1946 if (dwFlags & WAVE_FORMAT_QUERY)
1948 TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
1949 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1950 lpDesc->lpFormat->nSamplesPerSec);
1951 return MMSYSERR_NOERROR;
1954 /* nBlockAlign and nAvgBytesPerSec are output variables for dsound */
1955 if (lpDesc->lpFormat->nBlockAlign != lpDesc->lpFormat->nChannels*lpDesc->lpFormat->wBitsPerSample/8) {
1956 lpDesc->lpFormat->nBlockAlign = lpDesc->lpFormat->nChannels*lpDesc->lpFormat->wBitsPerSample/8;
1957 WARN("Fixing nBlockAlign\n");
1959 if (lpDesc->lpFormat->nAvgBytesPerSec!= lpDesc->lpFormat->nSamplesPerSec*lpDesc->lpFormat->nBlockAlign) {
1960 lpDesc->lpFormat->nAvgBytesPerSec = lpDesc->lpFormat->nSamplesPerSec*lpDesc->lpFormat->nBlockAlign;
1961 WARN("Fixing nAvgBytesPerSec\n");
1964 wwi = &WInDev[wDevID];
1965 if (!OSSpinLockTry(&wwi->lock))
1966 return MMSYSERR_ALLOCATED;
1968 if (wwi->state != WINE_WS_CLOSED)
1970 OSSpinLockUnlock(&wwi->lock);
1971 return MMSYSERR_ALLOCATED;
1974 wwi->state = WINE_WS_STOPPED;
1975 wwi->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
1977 wwi->waveDesc = *lpDesc;
1978 copyFormat(lpDesc->lpFormat, &wwi->format);
1980 wwi->dwTotalRecorded = 0;
1982 wwi->trace_on = TRACE_ON(wave);
1983 wwi->warn_on = WARN_ON(wave);
1984 wwi->err_on = ERR_ON(wave);
1986 if (!AudioUnit_CreateInputUnit(wwi, &wwi->audioUnit,
1987 wwi->format.wf.nChannels, wwi->format.wf.nSamplesPerSec,
1988 wwi->format.wBitsPerSample, &frameCount))
1990 OSSpinLockUnlock(&wwi->lock);
1991 ERR("AudioUnit_CreateInputUnit failed\n");
1992 return MMSYSERR_ERROR;
1995 /* Allocate our audio buffers */
1996 wwi->bufferList = widHelper_AllocateAudioBufferList(wwi->format.wf.nChannels,
1997 wwi->format.wBitsPerSample, frameCount, TRUE);
1998 if (wwi->bufferList == NULL)
2000 AudioUnitUninitialize(wwi->audioUnit);
2001 AudioUnit_CloseAudioUnit(wwi->audioUnit);
2002 OSSpinLockUnlock(&wwi->lock);
2003 ERR("Failed to allocate buffer list\n");
2004 return MMSYSERR_NOMEM;
2007 /* Keep a copy of the buffer list structure (but not the buffers themselves)
2008 * in case AudioUnitRender clobbers the original, as it tends to do. */
2009 wwi->bufferListCopy = HeapAlloc(GetProcessHeap(), 0, AUDIOBUFFERLISTSIZE(wwi->bufferList->mNumberBuffers));
2010 if (wwi->bufferListCopy == NULL)
2012 widHelper_DestroyAudioBufferList(wwi->bufferList);
2013 AudioUnitUninitialize(wwi->audioUnit);
2014 AudioUnit_CloseAudioUnit(wwi->audioUnit);
2015 OSSpinLockUnlock(&wwi->lock);
2016 ERR("Failed to allocate buffer list copy\n");
2017 return MMSYSERR_NOMEM;
2019 memcpy(wwi->bufferListCopy, wwi->bufferList, AUDIOBUFFERLISTSIZE(wwi->bufferList->mNumberBuffers));
2021 OSSpinLockUnlock(&wwi->lock);
2023 widNotifyClient(wwi, WIM_OPEN, 0L, 0L);
2025 return MMSYSERR_NOERROR;
2029 /**************************************************************************
2030 * widClose [internal]
2032 static DWORD widClose(WORD wDevID)
2034 DWORD ret = MMSYSERR_NOERROR;
2038 TRACE("(%u);\n", wDevID);
2040 if (wDevID >= MAX_WAVEINDRV)
2042 WARN("bad device ID !\n");
2043 return MMSYSERR_BADDEVICEID;
2046 wwi = &WInDev[wDevID];
2047 OSSpinLockLock(&wwi->lock);
2048 if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2050 WARN("Device already closed.\n");
2051 ret = MMSYSERR_INVALHANDLE;
2053 else if (wwi->lpQueuePtr)
2055 WARN("Buffers in queue.\n");
2056 ret = WAVERR_STILLPLAYING;
2060 wwi->state = WINE_WS_CLOSING;
2063 OSSpinLockUnlock(&wwi->lock);
2065 if (ret != MMSYSERR_NOERROR)
2069 /* Clean up and close the audio unit. This has to be done without
2070 * wwi->lock being held to avoid deadlock. AudioUnitUninitialize will
2071 * grab an internal Core Audio lock while waiting for the device work
2072 * thread to exit. Meanwhile the device work thread may be holding
2073 * that lock and trying to grab the wwi->lock in the callback. */
2074 err = AudioUnitUninitialize(wwi->audioUnit);
2076 ERR("AudioUnitUninitialize return %s\n", wine_dbgstr_fourcc(err));
2078 if (!AudioUnit_CloseAudioUnit(wwi->audioUnit))
2079 ERR("Can't close AudioUnit\n");
2082 OSSpinLockLock(&wwi->lock);
2083 assert(wwi->state == WINE_WS_CLOSING);
2085 /* Dellocate our audio buffers */
2086 widHelper_DestroyAudioBufferList(wwi->bufferList);
2087 wwi->bufferList = NULL;
2088 HeapFree(GetProcessHeap(), 0, wwi->bufferListCopy);
2089 wwi->bufferListCopy = NULL;
2091 wwi->audioUnit = NULL;
2092 wwi->state = WINE_WS_CLOSED;
2093 OSSpinLockUnlock(&wwi->lock);
2095 widNotifyClient(wwi, WIM_CLOSE, 0L, 0L);
2101 /**************************************************************************
2102 * widAddBuffer [internal]
2104 static DWORD widAddBuffer(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
2106 DWORD ret = MMSYSERR_NOERROR;
2109 TRACE("(%u, %p, %08X);\n", wDevID, lpWaveHdr, dwSize);
2111 if (wDevID >= MAX_WAVEINDRV)
2113 WARN("invalid device ID\n");
2114 return MMSYSERR_INVALHANDLE;
2116 if (!(lpWaveHdr->dwFlags & WHDR_PREPARED))
2118 TRACE("never been prepared !\n");
2119 return WAVERR_UNPREPARED;
2121 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
2123 TRACE("header already in use !\n");
2124 return WAVERR_STILLPLAYING;
2127 wwi = &WInDev[wDevID];
2128 OSSpinLockLock(&wwi->lock);
2130 if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2132 WARN("Trying to add buffer to closed device.\n");
2133 ret = MMSYSERR_INVALHANDLE;
2139 lpWaveHdr->dwFlags |= WHDR_INQUEUE;
2140 lpWaveHdr->dwFlags &= ~WHDR_DONE;
2141 lpWaveHdr->dwBytesRecorded = 0;
2142 lpWaveHdr->lpNext = NULL;
2144 /* insert buffer at end of queue */
2145 for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext))
2150 OSSpinLockUnlock(&wwi->lock);
2156 /**************************************************************************
2157 * widStart [internal]
2159 static DWORD widStart(WORD wDevID)
2161 DWORD ret = MMSYSERR_NOERROR;
2164 TRACE("(%u);\n", wDevID);
2165 if (wDevID >= MAX_WAVEINDRV)
2167 WARN("invalid device ID\n");
2168 return MMSYSERR_INVALHANDLE;
2171 /* The order of the following operations is important since we can't hold
2172 * the mutex while we make an Audio Unit call. Set the PLAYING state
2173 * before starting the Audio Unit. In widStop, the order is reversed.
2174 * This guarantees that we can't get into a situation where the state is
2175 * PLAYING but the Audio Unit isn't running. Although we can be in STOPPED
2176 * state with the Audio Unit still running, that's harmless because the
2177 * input callback will just throw away the sound data.
2179 wwi = &WInDev[wDevID];
2180 OSSpinLockLock(&wwi->lock);
2182 if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2184 WARN("Trying to start closed device.\n");
2185 ret = MMSYSERR_INVALHANDLE;
2188 wwi->state = WINE_WS_PLAYING;
2190 OSSpinLockUnlock(&wwi->lock);
2192 if (ret == MMSYSERR_NOERROR)
2194 /* Start pulling for audio data */
2195 OSStatus err = AudioOutputUnitStart(wwi->audioUnit);
2197 ERR("Failed to start AU: %08lx\n", err);
2199 TRACE("Recording started...\n");
2206 /**************************************************************************
2207 * widStop [internal]
2209 static DWORD widStop(WORD wDevID)
2211 DWORD ret = MMSYSERR_NOERROR;
2213 WAVEHDR* lpWaveHdr = NULL;
2216 TRACE("(%u);\n", wDevID);
2217 if (wDevID >= MAX_WAVEINDRV)
2219 WARN("invalid device ID\n");
2220 return MMSYSERR_INVALHANDLE;
2223 wwi = &WInDev[wDevID];
2225 /* The order of the following operations is important since we can't hold
2226 * the mutex while we make an Audio Unit call. Stop the Audio Unit before
2227 * setting the STOPPED state. In widStart, the order is reversed. This
2228 * guarantees that we can't get into a situation where the state is
2229 * PLAYING but the Audio Unit isn't running. Although we can be in STOPPED
2230 * state with the Audio Unit still running, that's harmless because the
2231 * input callback will just throw away the sound data.
2233 err = AudioOutputUnitStop(wwi->audioUnit);
2235 WARN("Failed to stop AU: %08lx\n", err);
2237 TRACE("Recording stopped.\n");
2239 OSSpinLockLock(&wwi->lock);
2241 if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2243 WARN("Trying to stop closed device.\n");
2244 ret = MMSYSERR_INVALHANDLE;
2246 else if (wwi->state != WINE_WS_STOPPED)
2248 wwi->state = WINE_WS_STOPPED;
2249 /* If there's a buffer in progress, it's done. Remove it from the
2250 * queue so that we can return it to the app, below. */
2251 if (wwi->lpQueuePtr)
2253 lpWaveHdr = wwi->lpQueuePtr;
2254 wwi->lpQueuePtr = lpWaveHdr->lpNext;
2258 OSSpinLockUnlock(&wwi->lock);
2262 lpWaveHdr->lpNext = NULL;
2263 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2264 lpWaveHdr->dwFlags |= WHDR_DONE;
2265 widNotifyClient(wwi, WIM_DATA, (DWORD_PTR)lpWaveHdr, 0);
2271 /**************************************************************************
2272 * widGetPos [internal]
2274 static DWORD widGetPos(WORD wDevID, LPMMTIME lpTime, UINT size)
2279 TRACE("(%u);\n", wDevID);
2280 if (wDevID >= MAX_WAVEINDRV)
2282 WARN("invalid device ID\n");
2283 return MMSYSERR_INVALHANDLE;
2286 wwi = &WInDev[wDevID];
2288 OSSpinLockLock(&WInDev[wDevID].lock);
2289 val = wwi->dwTotalRecorded;
2290 OSSpinLockUnlock(&WInDev[wDevID].lock);
2292 return bytes_to_mmtime(lpTime, val, &wwi->format);
2295 /**************************************************************************
2296 * widReset [internal]
2298 static DWORD widReset(WORD wDevID)
2300 DWORD ret = MMSYSERR_NOERROR;
2302 WAVEHDR* lpWaveHdr = NULL;
2304 TRACE("(%u);\n", wDevID);
2305 if (wDevID >= MAX_WAVEINDRV)
2307 WARN("invalid device ID\n");
2308 return MMSYSERR_INVALHANDLE;
2311 wwi = &WInDev[wDevID];
2312 OSSpinLockLock(&wwi->lock);
2314 if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2316 WARN("Trying to reset a closed device.\n");
2317 ret = MMSYSERR_INVALHANDLE;
2321 lpWaveHdr = wwi->lpQueuePtr;
2322 wwi->lpQueuePtr = NULL;
2323 wwi->state = WINE_WS_STOPPED;
2324 wwi->dwTotalRecorded = 0;
2327 OSSpinLockUnlock(&wwi->lock);
2329 if (ret == MMSYSERR_NOERROR)
2331 OSStatus err = AudioOutputUnitStop(wwi->audioUnit);
2333 WARN("Failed to stop AU: %08lx\n", err);
2335 TRACE("Recording stopped.\n");
2340 WAVEHDR* lpNext = lpWaveHdr->lpNext;
2342 lpWaveHdr->lpNext = NULL;
2343 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2344 lpWaveHdr->dwFlags |= WHDR_DONE;
2345 widNotifyClient(wwi, WIM_DATA, (DWORD_PTR)lpWaveHdr, 0);
2354 /**************************************************************************
2355 * widGetNumDevs [internal]
2357 static DWORD widGetNumDevs(void)
2359 return MAX_WAVEINDRV;
2363 /**************************************************************************
2364 * widDevInterfaceSize [internal]
2366 static DWORD widDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
2368 TRACE("(%u, %p)\n", wDevID, dwParam1);
2370 *dwParam1 = MultiByteToWideChar(CP_UNIXCP, 0, WInDev[wDevID].interface_name, -1,
2371 NULL, 0 ) * sizeof(WCHAR);
2372 return MMSYSERR_NOERROR;
2376 /**************************************************************************
2377 * widDevInterface [internal]
2379 static DWORD widDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
2381 if (dwParam2 >= MultiByteToWideChar(CP_UNIXCP, 0, WInDev[wDevID].interface_name, -1,
2382 NULL, 0 ) * sizeof(WCHAR))
2384 MultiByteToWideChar(CP_UNIXCP, 0, WInDev[wDevID].interface_name, -1,
2385 dwParam1, dwParam2 / sizeof(WCHAR));
2386 return MMSYSERR_NOERROR;
2388 return MMSYSERR_INVALPARAM;
2392 /**************************************************************************
2393 * widDsCreate [internal]
2395 static DWORD widDsCreate(UINT wDevID, PIDSCDRIVER* drv)
2397 TRACE("(%d,%p)\n",wDevID,drv);
2399 FIXME("DirectSoundCapture not implemented\n");
2400 FIXME("The (slower) DirectSound HEL mode will be used instead.\n");
2401 return MMSYSERR_NOTSUPPORTED;
2404 /**************************************************************************
2405 * widDsDesc [internal]
2407 static DWORD widDsDesc(UINT wDevID, PDSDRIVERDESC desc)
2409 /* The DirectSound HEL will automatically wrap a non-DirectSound-capable
2410 * driver in a DirectSound adaptor, thus allowing the driver to be used by
2411 * DirectSound clients. However, it only does this if we respond
2412 * successfully to the DRV_QUERYDSOUNDDESC message. It's enough to fill in
2413 * the driver and device names of the description output parameter. */
2414 memset(desc, 0, sizeof(*desc));
2415 lstrcpynA(desc->szDrvname, "winecoreaudio.drv", sizeof(desc->szDrvname) - 1);
2416 lstrcpynA(desc->szDesc, WInDev[wDevID].interface_name, sizeof(desc->szDesc) - 1);
2417 return MMSYSERR_NOERROR;
2421 /**************************************************************************
2422 * widMessage (WINECOREAUDIO.6)
2424 DWORD WINAPI CoreAudio_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2425 DWORD dwParam1, DWORD dwParam2)
2427 TRACE("(%u, %04X, %08X, %08X, %08X);\n",
2428 wDevID, wMsg, dwUser, dwParam1, dwParam2);
2436 /* FIXME: Pretend this is supported */
2438 case WIDM_OPEN: return widOpen (wDevID, (LPWAVEOPENDESC)dwParam1, dwParam2);
2439 case WIDM_CLOSE: return widClose (wDevID);
2440 case WIDM_ADDBUFFER: return widAddBuffer (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2441 case WIDM_PREPARE: return MMSYSERR_NOTSUPPORTED;
2442 case WIDM_UNPREPARE: return MMSYSERR_NOTSUPPORTED;
2443 case WIDM_GETDEVCAPS: return widGetDevCaps (wDevID, (LPWAVEINCAPSW)dwParam1, dwParam2);
2444 case WIDM_GETNUMDEVS: return widGetNumDevs ();
2445 case WIDM_RESET: return widReset (wDevID);
2446 case WIDM_START: return widStart (wDevID);
2447 case WIDM_STOP: return widStop (wDevID);
2448 case WIDM_GETPOS: return widGetPos (wDevID, (LPMMTIME)dwParam1, (UINT)dwParam2 );
2449 case DRV_QUERYDEVICEINTERFACESIZE: return widDevInterfaceSize (wDevID, (LPDWORD)dwParam1);
2450 case DRV_QUERYDEVICEINTERFACE: return widDevInterface (wDevID, (PWCHAR)dwParam1, dwParam2);
2451 case DRV_QUERYDSOUNDIFACE: return widDsCreate (wDevID, (PIDSCDRIVER*)dwParam1);
2452 case DRV_QUERYDSOUNDDESC: return widDsDesc (wDevID, (PDSDRIVERDESC)dwParam1);
2454 FIXME("unknown message %d!\n", wMsg);
2457 return MMSYSERR_NOTSUPPORTED;
2461 OSStatus CoreAudio_wiAudioUnitIOProc(void *inRefCon,
2462 AudioUnitRenderActionFlags *ioActionFlags,
2463 const AudioTimeStamp *inTimeStamp,
2465 UInt32 inNumberFrames,
2466 AudioBufferList *ioData)
2468 WINE_WAVEIN* wwi = (WINE_WAVEIN*)inRefCon;
2469 OSStatus err = noErr;
2470 BOOL needNotify = FALSE;
2471 WAVEHDR* lpStorePtr;
2472 unsigned int dataToStore;
2473 unsigned int dataStored = 0;
2477 fprintf(stderr, "trace:wave:CoreAudio_wiAudioUnitIOProc (ioActionFlags = %08lx, "
2478 "inTimeStamp = { %f, %x%08x, %f, %x%08x, %08lx }, inBusNumber = %lu, inNumberFrames = %lu)\n",
2479 *ioActionFlags, inTimeStamp->mSampleTime, (DWORD)(inTimeStamp->mHostTime >>32),
2480 (DWORD)inTimeStamp->mHostTime, inTimeStamp->mRateScalar, (DWORD)(inTimeStamp->mWordClockTime >> 32),
2481 (DWORD)inTimeStamp->mWordClockTime, inTimeStamp->mFlags, inBusNumber, inNumberFrames);
2483 /* Render into audio buffer */
2484 /* FIXME: implement sample rate conversion on input. This will require
2485 * a different render strategy. We'll need to buffer the sound data
2486 * received here and pass it off to an AUConverter in another thread. */
2487 err = AudioUnitRender(wwi->audioUnit, ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, wwi->bufferList);
2491 fprintf(stderr, "err:wave:CoreAudio_wiAudioUnitIOProc AudioUnitRender failed with error %li\n", err);
2495 /* Copy from audio buffer to the wavehdrs */
2496 dataToStore = wwi->bufferList->mBuffers[0].mDataByteSize;
2498 OSSpinLockLock(&wwi->lock);
2500 lpStorePtr = wwi->lpQueuePtr;
2502 /* We might have been called while the waveIn device is being closed in
2503 * widClose. We have to do nothing in that case. The check of wwi->state
2504 * below ensures that. */
2505 while (dataToStore > 0 && wwi->state == WINE_WS_PLAYING && lpStorePtr)
2507 unsigned int room = lpStorePtr->dwBufferLength - lpStorePtr->dwBytesRecorded;
2508 unsigned int toCopy;
2511 fprintf(stderr, "trace:wave:CoreAudio_wiAudioUnitIOProc Looking to store %u bytes to wavehdr %p, which has room for %u\n",
2512 dataToStore, lpStorePtr, room);
2514 if (room >= dataToStore)
2515 toCopy = dataToStore;
2521 memcpy(lpStorePtr->lpData + lpStorePtr->dwBytesRecorded,
2522 (char*)wwi->bufferList->mBuffers[0].mData + dataStored, toCopy);
2523 lpStorePtr->dwBytesRecorded += toCopy;
2524 wwi->dwTotalRecorded += toCopy;
2525 dataStored += toCopy;
2526 dataToStore -= toCopy;
2532 lpStorePtr = lpStorePtr->lpNext;
2537 OSSpinLockUnlock(&wwi->lock);
2539 /* Restore the audio buffer list structure from backup, in case
2540 * AudioUnitRender clobbered it. (It modifies mDataByteSize and may even
2541 * give us a different mData buffer to avoid a copy.) */
2542 memcpy(wwi->bufferList, wwi->bufferListCopy, AUDIOBUFFERLISTSIZE(wwi->bufferList->mNumberBuffers));
2544 if (needNotify) wodSendNotifyInputCompletionsMessage(wwi);