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
44 #include "coreaudio.h"
45 #include "wine/unicode.h"
46 #include "wine/library.h"
47 #include "wine/debug.h"
49 WINE_DEFAULT_DEBUG_CHANNEL(wave);
52 #if defined(HAVE_COREAUDIO_COREAUDIO_H) && defined(HAVE_AUDIOUNIT_AUDIOUNIT_H)
53 #include <CoreAudio/CoreAudio.h>
54 #include <CoreFoundation/CoreFoundation.h>
55 #include <libkern/OSAtomic.h>
58 Due to AudioUnit headers conflict define some needed types.
61 typedef void *AudioUnit;
63 /* From AudioUnit/AUComponents.h */
66 kAudioUnitRenderAction_OutputIsSilence = (1 << 4),
67 /* provides hint on return from Render(): if set the buffer contains all zeroes */
69 typedef UInt32 AudioUnitRenderActionFlags;
71 typedef long ComponentResult;
72 extern ComponentResult
73 AudioUnitRender( AudioUnit ci,
74 AudioUnitRenderActionFlags * ioActionFlags,
75 const AudioTimeStamp * inTimeStamp,
76 UInt32 inOutputBusNumber,
77 UInt32 inNumberFrames,
78 AudioBufferList * ioData) AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER;
80 /* only allow 10 output devices through this driver, this ought to be adequate */
81 #define MAX_WAVEOUTDRV (1)
82 #define MAX_WAVEINDRV (1)
84 /* state diagram for waveOut writing:
86 * +---------+-------------+---------------+---------------------------------+
87 * | state | function | event | new state |
88 * +---------+-------------+---------------+---------------------------------+
89 * | | open() | | STOPPED |
90 * | PAUSED | write() | | PAUSED |
91 * | STOPPED | write() | <thrd create> | PLAYING |
92 * | PLAYING | write() | HEADER | PLAYING |
93 * | (other) | write() | <error> | |
94 * | (any) | pause() | PAUSING | PAUSED |
95 * | PAUSED | restart() | RESTARTING | PLAYING (if no thrd => STOPPED) |
96 * | (any) | reset() | RESETTING | STOPPED |
97 * | (any) | close() | CLOSING | CLOSED |
98 * +---------+-------------+---------------+---------------------------------+
101 /* states of the playing device */
102 #define WINE_WS_PLAYING 0
103 #define WINE_WS_PAUSED 1
104 #define WINE_WS_STOPPED 2
105 #define WINE_WS_CLOSED 3
107 typedef struct tagCoreAudio_Device {
111 char* interface_name;
113 WAVEOUTCAPSW out_caps;
115 DWORD in_caps_support;
119 unsigned audio_fragment;
121 BOOL bTriggerSupport;
124 DSDRIVERDESC ds_desc;
125 DSDRIVERCAPS ds_caps;
126 DSCDRIVERCAPS dsc_caps;
130 AudioDeviceID outputDeviceID;
131 AudioDeviceID inputDeviceID;
132 AudioStreamBasicDescription streamDescription;
135 /* for now use the default device */
136 static CoreAudio_Device CoreAudio_DefaultDevice;
139 volatile int state; /* one of the WINE_WS_ manifest constants */
140 CoreAudio_Device *cadev;
141 WAVEOPENDESC waveDesc;
143 PCMWAVEFORMAT format;
146 AudioStreamBasicDescription streamDescription;
149 char interface_name[32];
150 LPWAVEHDR lpQueuePtr; /* start of queued WAVEHDRs (waiting to be notified) */
151 LPWAVEHDR lpPlayPtr; /* start of not yet fully played buffers */
152 DWORD dwPartialOffset; /* Offset of not yet written bytes in lpPlayPtr */
154 LPWAVEHDR lpLoopPtr; /* pointer of first buffer in loop, if any */
155 DWORD dwLoops; /* private copy of loop counter */
157 DWORD dwPlayedTotal; /* number of bytes actually played since opening */
158 DWORD dwWrittenTotal; /* number of bytes written to OSS buffer since opening */
160 DWORD tickCountMS; /* time in MS of last AudioUnit callback */
162 OSSpinLock lock; /* synchronization stuff */
170 /* This device's device number */
173 /* Access to the following fields is synchronized across threads. */
175 LPWAVEHDR lpQueuePtr;
176 DWORD dwTotalRecorded;
178 /* Synchronization mechanism to protect above fields */
181 /* Capabilities description */
183 char interface_name[32];
185 /* Record the arguments used when opening the device. */
186 WAVEOPENDESC waveDesc;
188 PCMWAVEFORMAT format;
191 AudioBufferList*bufferList;
192 AudioBufferList*bufferListCopy;
194 /* Record state of debug channels at open. Used to control fprintf's since
195 * we can't use Wine debug channel calls in non-Wine AudioUnit threads. */
200 /* These fields aren't used. */
202 CoreAudio_Device *cadev;
204 AudioStreamBasicDescription streamDescription;
208 static WINE_WAVEOUT WOutDev [MAX_WAVEOUTDRV];
209 static WINE_WAVEIN WInDev [MAX_WAVEINDRV];
211 static HANDLE hThread = NULL; /* Track the thread we create so we can clean it up later */
212 static CFMessagePortRef Port_SendToMessageThread;
214 static void wodHelper_PlayPtrNext(WINE_WAVEOUT* wwo);
215 static void wodHelper_NotifyDoneForList(WINE_WAVEOUT* wwo, LPWAVEHDR lpWaveHdr);
216 static void wodHelper_NotifyCompletions(WINE_WAVEOUT* wwo, BOOL force);
217 static void widHelper_NotifyCompletions(WINE_WAVEIN* wwi);
219 extern int AudioUnit_CreateDefaultAudioUnit(void *wwo, AudioUnit *au);
220 extern int AudioUnit_CloseAudioUnit(AudioUnit au);
221 extern int AudioUnit_InitializeWithStreamDescription(AudioUnit au, AudioStreamBasicDescription *streamFormat);
223 extern OSStatus AudioOutputUnitStart(AudioUnit au);
224 extern OSStatus AudioOutputUnitStop(AudioUnit au);
225 extern OSStatus AudioUnitUninitialize(AudioUnit au);
227 extern int AudioUnit_SetVolume(AudioUnit au, float left, float right);
228 extern int AudioUnit_GetVolume(AudioUnit au, float *left, float *right);
230 extern int AudioUnit_GetInputDeviceSampleRate(void);
232 extern int AudioUnit_CreateInputUnit(void* wwi, AudioUnit* out_au,
233 WORD nChannels, DWORD nSamplesPerSec, WORD wBitsPerSample,
234 UInt32* outFrameCount);
236 OSStatus CoreAudio_woAudioUnitIOProc(void *inRefCon,
237 AudioUnitRenderActionFlags *ioActionFlags,
238 const AudioTimeStamp *inTimeStamp,
240 UInt32 inNumberFrames,
241 AudioBufferList *ioData);
242 OSStatus CoreAudio_wiAudioUnitIOProc(void *inRefCon,
243 AudioUnitRenderActionFlags *ioActionFlags,
244 const AudioTimeStamp *inTimeStamp,
246 UInt32 inNumberFrames,
247 AudioBufferList *ioData);
249 /* These strings used only for tracing */
251 static const char * getMessage(UINT msg)
253 static char unknown[32];
254 #define MSG_TO_STR(x) case x: return #x
256 MSG_TO_STR(DRVM_INIT);
257 MSG_TO_STR(DRVM_EXIT);
258 MSG_TO_STR(DRVM_ENABLE);
259 MSG_TO_STR(DRVM_DISABLE);
260 MSG_TO_STR(WIDM_OPEN);
261 MSG_TO_STR(WIDM_CLOSE);
262 MSG_TO_STR(WIDM_ADDBUFFER);
263 MSG_TO_STR(WIDM_PREPARE);
264 MSG_TO_STR(WIDM_UNPREPARE);
265 MSG_TO_STR(WIDM_GETDEVCAPS);
266 MSG_TO_STR(WIDM_GETNUMDEVS);
267 MSG_TO_STR(WIDM_GETPOS);
268 MSG_TO_STR(WIDM_RESET);
269 MSG_TO_STR(WIDM_START);
270 MSG_TO_STR(WIDM_STOP);
271 MSG_TO_STR(WODM_OPEN);
272 MSG_TO_STR(WODM_CLOSE);
273 MSG_TO_STR(WODM_WRITE);
274 MSG_TO_STR(WODM_PAUSE);
275 MSG_TO_STR(WODM_GETPOS);
276 MSG_TO_STR(WODM_BREAKLOOP);
277 MSG_TO_STR(WODM_PREPARE);
278 MSG_TO_STR(WODM_UNPREPARE);
279 MSG_TO_STR(WODM_GETDEVCAPS);
280 MSG_TO_STR(WODM_GETNUMDEVS);
281 MSG_TO_STR(WODM_GETPITCH);
282 MSG_TO_STR(WODM_SETPITCH);
283 MSG_TO_STR(WODM_GETPLAYBACKRATE);
284 MSG_TO_STR(WODM_SETPLAYBACKRATE);
285 MSG_TO_STR(WODM_GETVOLUME);
286 MSG_TO_STR(WODM_SETVOLUME);
287 MSG_TO_STR(WODM_RESTART);
288 MSG_TO_STR(WODM_RESET);
289 MSG_TO_STR(DRV_QUERYDEVICEINTERFACESIZE);
290 MSG_TO_STR(DRV_QUERYDEVICEINTERFACE);
291 MSG_TO_STR(DRV_QUERYDSOUNDIFACE);
292 MSG_TO_STR(DRV_QUERYDSOUNDDESC);
295 sprintf(unknown, "UNKNOWN(0x%04x)", msg);
299 #define kStopLoopMessage 0
300 #define kWaveOutNotifyCompletionsMessage 1
301 #define kWaveInNotifyCompletionsMessage 2
303 /* Mach Message Handling */
304 static CFDataRef wodMessageHandler(CFMessagePortRef port_ReceiveInMessageThread, SInt32 msgid, CFDataRef data, void *info)
306 UInt32 *buffer = NULL;
310 case kWaveOutNotifyCompletionsMessage:
311 buffer = (UInt32 *) CFDataGetBytePtr(data);
312 wodHelper_NotifyCompletions(&WOutDev[buffer[0]], FALSE);
314 case kWaveInNotifyCompletionsMessage:
315 buffer = (UInt32 *) CFDataGetBytePtr(data);
316 widHelper_NotifyCompletions(&WInDev[buffer[0]]);
319 CFRunLoopStop(CFRunLoopGetCurrent());
326 static DWORD WINAPI messageThread(LPVOID p)
328 CFMessagePortRef port_ReceiveInMessageThread = (CFMessagePortRef) p;
329 CFRunLoopSourceRef source;
331 source = CFMessagePortCreateRunLoopSource(kCFAllocatorDefault, port_ReceiveInMessageThread, (CFIndex)0);
332 CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
336 CFRunLoopSourceInvalidate(source);
338 CFRelease(port_ReceiveInMessageThread);
343 /**************************************************************************
344 * wodSendNotifyCompletionsMessage [internal]
345 * Call from AudioUnit IO thread can't use Wine debug channels.
347 static void wodSendNotifyCompletionsMessage(WINE_WAVEOUT* wwo)
352 buffer = (UInt32) wwo->woID;
354 data = CFDataCreate(kCFAllocatorDefault, (UInt8 *)&buffer, sizeof(buffer));
358 CFMessagePortSendRequest(Port_SendToMessageThread, kWaveOutNotifyCompletionsMessage, data, 0.0, 0.0, NULL, NULL);
362 /**************************************************************************
363 * wodSendNotifyInputCompletionsMessage [internal]
364 * Call from AudioUnit IO thread can't use Wine debug channels.
366 static void wodSendNotifyInputCompletionsMessage(WINE_WAVEIN* wwi)
371 buffer = (UInt32) wwi->wiID;
373 data = CFDataCreate(kCFAllocatorDefault, (UInt8 *)&buffer, sizeof(buffer));
377 CFMessagePortSendRequest(Port_SendToMessageThread, kWaveInNotifyCompletionsMessage, data, 0.0, 0.0, NULL, NULL);
381 static DWORD bytes_to_mmtime(LPMMTIME lpTime, DWORD position,
382 PCMWAVEFORMAT* format)
384 TRACE("wType=%04X wBitsPerSample=%u nSamplesPerSec=%u nChannels=%u nAvgBytesPerSec=%u\n",
385 lpTime->wType, format->wBitsPerSample, format->wf.nSamplesPerSec,
386 format->wf.nChannels, format->wf.nAvgBytesPerSec);
387 TRACE("Position in bytes=%u\n", position);
389 switch (lpTime->wType) {
391 lpTime->u.sample = position / (format->wBitsPerSample / 8 * format->wf.nChannels);
392 TRACE("TIME_SAMPLES=%u\n", lpTime->u.sample);
395 lpTime->u.ms = 1000.0 * position / (format->wBitsPerSample / 8 * format->wf.nChannels * format->wf.nSamplesPerSec);
396 TRACE("TIME_MS=%u\n", lpTime->u.ms);
399 lpTime->u.smpte.fps = 30;
400 position = position / (format->wBitsPerSample / 8 * format->wf.nChannels);
401 position += (format->wf.nSamplesPerSec / lpTime->u.smpte.fps) - 1; /* round up */
402 lpTime->u.smpte.sec = position / format->wf.nSamplesPerSec;
403 position -= lpTime->u.smpte.sec * format->wf.nSamplesPerSec;
404 lpTime->u.smpte.min = lpTime->u.smpte.sec / 60;
405 lpTime->u.smpte.sec -= 60 * lpTime->u.smpte.min;
406 lpTime->u.smpte.hour = lpTime->u.smpte.min / 60;
407 lpTime->u.smpte.min -= 60 * lpTime->u.smpte.hour;
408 lpTime->u.smpte.fps = 30;
409 lpTime->u.smpte.frame = position * lpTime->u.smpte.fps / format->wf.nSamplesPerSec;
410 TRACE("TIME_SMPTE=%02u:%02u:%02u:%02u\n",
411 lpTime->u.smpte.hour, lpTime->u.smpte.min,
412 lpTime->u.smpte.sec, lpTime->u.smpte.frame);
415 WARN("Format %d not supported, using TIME_BYTES !\n", lpTime->wType);
416 lpTime->wType = TIME_BYTES;
419 lpTime->u.cb = position;
420 TRACE("TIME_BYTES=%u\n", lpTime->u.cb);
423 return MMSYSERR_NOERROR;
426 /**************************************************************************
427 * CoreAudio_GetDevCaps [internal]
429 BOOL CoreAudio_GetDevCaps (void)
433 AudioDeviceID devId = CoreAudio_DefaultDevice.outputDeviceID;
435 char name[MAXPNAMELEN];
437 propertySize = MAXPNAMELEN;
438 status = AudioDeviceGetProperty(devId, 0 , FALSE, kAudioDevicePropertyDeviceName, &propertySize, name);
440 ERR("AudioHardwareGetProperty for kAudioDevicePropertyDeviceName return %c%c%c%c\n", (char) (status >> 24),
441 (char) (status >> 16),
442 (char) (status >> 8),
447 memcpy(CoreAudio_DefaultDevice.ds_desc.szDesc, name, sizeof(name));
448 strcpy(CoreAudio_DefaultDevice.ds_desc.szDrvname, "winecoreaudio.drv");
449 MultiByteToWideChar(CP_ACP, 0, name, sizeof(name),
450 CoreAudio_DefaultDevice.out_caps.szPname,
451 sizeof(CoreAudio_DefaultDevice.out_caps.szPname) / sizeof(WCHAR));
452 memcpy(CoreAudio_DefaultDevice.dev_name, name, 32);
454 propertySize = sizeof(CoreAudio_DefaultDevice.streamDescription);
455 status = AudioDeviceGetProperty(devId, 0, FALSE , kAudioDevicePropertyStreamFormat, &propertySize, &CoreAudio_DefaultDevice.streamDescription);
456 if (status != noErr) {
457 ERR("AudioHardwareGetProperty for kAudioDevicePropertyStreamFormat return %c%c%c%c\n", (char) (status >> 24),
458 (char) (status >> 16),
459 (char) (status >> 8),
464 TRACE("Device Stream Description mSampleRate : %f\n mFormatID : %c%c%c%c\n"
465 "mFormatFlags : %lX\n mBytesPerPacket : %lu\n mFramesPerPacket : %lu\n"
466 "mBytesPerFrame : %lu\n mChannelsPerFrame : %lu\n mBitsPerChannel : %lu\n",
467 CoreAudio_DefaultDevice.streamDescription.mSampleRate,
468 (char) (CoreAudio_DefaultDevice.streamDescription.mFormatID >> 24),
469 (char) (CoreAudio_DefaultDevice.streamDescription.mFormatID >> 16),
470 (char) (CoreAudio_DefaultDevice.streamDescription.mFormatID >> 8),
471 (char) CoreAudio_DefaultDevice.streamDescription.mFormatID,
472 CoreAudio_DefaultDevice.streamDescription.mFormatFlags,
473 CoreAudio_DefaultDevice.streamDescription.mBytesPerPacket,
474 CoreAudio_DefaultDevice.streamDescription.mFramesPerPacket,
475 CoreAudio_DefaultDevice.streamDescription.mBytesPerFrame,
476 CoreAudio_DefaultDevice.streamDescription.mChannelsPerFrame,
477 CoreAudio_DefaultDevice.streamDescription.mBitsPerChannel);
479 CoreAudio_DefaultDevice.out_caps.wMid = 0xcafe;
480 CoreAudio_DefaultDevice.out_caps.wPid = 0x0001;
482 CoreAudio_DefaultDevice.out_caps.vDriverVersion = 0x0001;
483 CoreAudio_DefaultDevice.out_caps.dwFormats = 0x00000000;
484 CoreAudio_DefaultDevice.out_caps.wReserved1 = 0;
485 CoreAudio_DefaultDevice.out_caps.dwSupport = WAVECAPS_VOLUME;
486 CoreAudio_DefaultDevice.out_caps.dwSupport |= WAVECAPS_LRVOLUME;
488 CoreAudio_DefaultDevice.out_caps.wChannels = 2;
489 CoreAudio_DefaultDevice.out_caps.dwFormats|= WAVE_FORMAT_4S16;
494 /******************************************************************
497 * Initialize CoreAudio_DefaultDevice
499 LONG CoreAudio_WaveInit(void)
503 CHAR szPname[MAXPNAMELEN];
505 CFStringRef messageThreadPortName;
506 CFMessagePortRef port_ReceiveInMessageThread;
511 /* number of sound cards */
512 AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &propertySize, NULL);
513 propertySize /= sizeof(AudioDeviceID);
514 TRACE("sound cards : %lu\n", propertySize);
516 /* Get the output device */
517 propertySize = sizeof(CoreAudio_DefaultDevice.outputDeviceID);
518 status = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &propertySize, &CoreAudio_DefaultDevice.outputDeviceID);
520 ERR("AudioHardwareGetProperty return %c%c%c%c for kAudioHardwarePropertyDefaultOutputDevice\n", (char) (status >> 24),
521 (char) (status >> 16),
522 (char) (status >> 8),
526 if (CoreAudio_DefaultDevice.outputDeviceID == kAudioDeviceUnknown) {
527 ERR("AudioHardwareGetProperty: CoreAudio_DefaultDevice.outputDeviceID == kAudioDeviceUnknown\n");
531 if ( ! CoreAudio_GetDevCaps() )
534 CoreAudio_DefaultDevice.interface_name=HeapAlloc(GetProcessHeap(),0,strlen(CoreAudio_DefaultDevice.dev_name)+1);
535 sprintf(CoreAudio_DefaultDevice.interface_name, "%s", CoreAudio_DefaultDevice.dev_name);
537 for (i = 0; i < MAX_WAVEOUTDRV; ++i)
539 WOutDev[i].state = WINE_WS_CLOSED;
540 WOutDev[i].cadev = &CoreAudio_DefaultDevice;
543 memset(&WOutDev[i].caps, 0, sizeof(WOutDev[i].caps));
545 WOutDev[i].caps.wMid = 0xcafe; /* Manufac ID */
546 WOutDev[i].caps.wPid = 0x0001; /* Product ID */
547 snprintf(szPname, sizeof(szPname), "CoreAudio WaveOut %d", i);
548 MultiByteToWideChar(CP_ACP, 0, szPname, -1, WOutDev[i].caps.szPname, sizeof(WOutDev[i].caps.szPname)/sizeof(WCHAR));
549 snprintf(WOutDev[i].interface_name, sizeof(WOutDev[i].interface_name), "winecoreaudio: %d", i);
551 WOutDev[i].caps.vDriverVersion = 0x0001;
552 WOutDev[i].caps.dwFormats = 0x00000000;
553 WOutDev[i].caps.dwSupport = WAVECAPS_VOLUME;
555 WOutDev[i].caps.wChannels = 2;
556 /* WOutDev[i].caps.dwSupport |= WAVECAPS_LRVOLUME; */ /* FIXME */
558 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96M08;
559 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96S08;
560 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96M16;
561 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96S16;
562 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48M08;
563 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48S08;
564 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48M16;
565 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48S16;
566 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4M08;
567 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4S08;
568 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4S16;
569 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4M16;
570 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2M08;
571 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2S08;
572 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2M16;
573 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2S16;
574 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1M08;
575 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1S08;
576 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1M16;
577 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1S16;
579 WOutDev[i].lock = 0; /* initialize the mutex */
582 /* FIXME: implement sample rate conversion on input */
583 inputSampleRate = AudioUnit_GetInputDeviceSampleRate();
585 for (i = 0; i < MAX_WAVEINDRV; ++i)
587 memset(&WInDev[i], 0, sizeof(WInDev[i]));
590 /* Establish preconditions for widOpen */
591 WInDev[i].state = WINE_WS_CLOSED;
592 WInDev[i].lock = 0; /* initialize the mutex */
594 /* Fill in capabilities. widGetDevCaps can be called at any time. */
595 WInDev[i].caps.wMid = 0xcafe; /* Manufac ID */
596 WInDev[i].caps.wPid = 0x0001; /* Product ID */
597 WInDev[i].caps.vDriverVersion = 0x0001;
599 snprintf(szPname, sizeof(szPname), "CoreAudio WaveIn %d", i);
600 MultiByteToWideChar(CP_ACP, 0, szPname, -1, WInDev[i].caps.szPname, sizeof(WInDev[i].caps.szPname)/sizeof(WCHAR));
601 snprintf(WInDev[i].interface_name, sizeof(WInDev[i].interface_name), "winecoreaudio in: %d", i);
603 if (inputSampleRate == 96000)
605 WInDev[i].caps.dwFormats |= WAVE_FORMAT_96M08;
606 WInDev[i].caps.dwFormats |= WAVE_FORMAT_96S08;
607 WInDev[i].caps.dwFormats |= WAVE_FORMAT_96M16;
608 WInDev[i].caps.dwFormats |= WAVE_FORMAT_96S16;
610 if (inputSampleRate == 48000)
612 WInDev[i].caps.dwFormats |= WAVE_FORMAT_48M08;
613 WInDev[i].caps.dwFormats |= WAVE_FORMAT_48S08;
614 WInDev[i].caps.dwFormats |= WAVE_FORMAT_48M16;
615 WInDev[i].caps.dwFormats |= WAVE_FORMAT_48S16;
617 if (inputSampleRate == 44100)
619 WInDev[i].caps.dwFormats |= WAVE_FORMAT_4M08;
620 WInDev[i].caps.dwFormats |= WAVE_FORMAT_4S08;
621 WInDev[i].caps.dwFormats |= WAVE_FORMAT_4M16;
622 WInDev[i].caps.dwFormats |= WAVE_FORMAT_4S16;
624 if (inputSampleRate == 22050)
626 WInDev[i].caps.dwFormats |= WAVE_FORMAT_2M08;
627 WInDev[i].caps.dwFormats |= WAVE_FORMAT_2S08;
628 WInDev[i].caps.dwFormats |= WAVE_FORMAT_2M16;
629 WInDev[i].caps.dwFormats |= WAVE_FORMAT_2S16;
631 if (inputSampleRate == 11025)
633 WInDev[i].caps.dwFormats |= WAVE_FORMAT_1M08;
634 WInDev[i].caps.dwFormats |= WAVE_FORMAT_1S08;
635 WInDev[i].caps.dwFormats |= WAVE_FORMAT_1M16;
636 WInDev[i].caps.dwFormats |= WAVE_FORMAT_1S16;
639 WInDev[i].caps.wChannels = 2;
642 /* create mach messages handler */
644 messageThreadPortName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL,
645 CFSTR("WaveMessagePort.%d.%lu"), getpid(), (unsigned long)random());
646 if (!messageThreadPortName)
648 ERR("Can't create message thread port name\n");
652 port_ReceiveInMessageThread = CFMessagePortCreateLocal(kCFAllocatorDefault, messageThreadPortName,
653 &wodMessageHandler, NULL, NULL);
654 if (!port_ReceiveInMessageThread)
656 ERR("Can't create message thread local port\n");
657 CFRelease(messageThreadPortName);
661 Port_SendToMessageThread = CFMessagePortCreateRemote(kCFAllocatorDefault, messageThreadPortName);
662 CFRelease(messageThreadPortName);
663 if (!Port_SendToMessageThread)
665 ERR("Can't create port for sending to message thread\n");
666 CFRelease(port_ReceiveInMessageThread);
670 /* Cannot WAIT for any events because we are called from the loader (which has a lock on loading stuff) */
671 /* We might want to wait for this thread to be created -- but we cannot -- not here at least */
672 /* Instead track the thread so we can clean it up later */
675 ERR("Message thread already started -- expect problems\n");
677 hThread = CreateThread(NULL, 0, messageThread, (LPVOID)port_ReceiveInMessageThread, 0, NULL);
680 ERR("Can't create message thread\n");
681 CFRelease(port_ReceiveInMessageThread);
682 CFRelease(Port_SendToMessageThread);
683 Port_SendToMessageThread = NULL;
687 /* The message thread is responsible for releasing port_ReceiveInMessageThread. */
692 void CoreAudio_WaveRelease(void)
694 /* Stop CFRunLoop in messageThread */
697 CFMessagePortSendRequest(Port_SendToMessageThread, kStopLoopMessage, NULL, 0.0, 0.0, NULL, NULL);
698 CFRelease(Port_SendToMessageThread);
699 Port_SendToMessageThread = NULL;
701 /* Wait for the thread to finish and clean it up */
702 /* This rids us of any quick start/shutdown driver crashes */
703 WaitForSingleObject(hThread, INFINITE);
704 CloseHandle(hThread);
708 /*======================================================================*
709 * Low level WAVE OUT implementation *
710 *======================================================================*/
712 /**************************************************************************
713 * wodNotifyClient [internal]
715 static DWORD wodNotifyClient(WINE_WAVEOUT* wwo, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
721 if (wwo->wFlags != DCB_NULL &&
722 !DriverCallback(wwo->waveDesc.dwCallback, wwo->wFlags,
723 (HDRVR)wwo->waveDesc.hWave, wMsg, wwo->waveDesc.dwInstance,
726 return MMSYSERR_ERROR;
730 return MMSYSERR_INVALPARAM;
732 return MMSYSERR_NOERROR;
736 /**************************************************************************
737 * wodGetDevCaps [internal]
739 static DWORD wodGetDevCaps(WORD wDevID, LPWAVEOUTCAPSW lpCaps, DWORD dwSize)
741 TRACE("(%u, %p, %u);\n", wDevID, lpCaps, dwSize);
743 if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
745 if (wDevID >= MAX_WAVEOUTDRV)
747 TRACE("MAX_WAVOUTDRV reached !\n");
748 return MMSYSERR_BADDEVICEID;
751 TRACE("dwSupport=(0x%x), dwFormats=(0x%x)\n", WOutDev[wDevID].caps.dwSupport, WOutDev[wDevID].caps.dwFormats);
752 memcpy(lpCaps, &WOutDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
753 return MMSYSERR_NOERROR;
756 /**************************************************************************
759 static DWORD wodOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
764 AudioStreamBasicDescription streamFormat;
766 TRACE("(%u, %p, %08x);\n", wDevID, lpDesc, dwFlags);
769 WARN("Invalid Parameter !\n");
770 return MMSYSERR_INVALPARAM;
772 if (wDevID >= MAX_WAVEOUTDRV) {
773 TRACE("MAX_WAVOUTDRV reached !\n");
774 return MMSYSERR_BADDEVICEID;
777 TRACE("Format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
778 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
779 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
781 if (lpDesc->lpFormat->wFormatTag != WAVE_FORMAT_PCM ||
782 lpDesc->lpFormat->nChannels == 0 ||
783 lpDesc->lpFormat->nSamplesPerSec == 0
786 WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
787 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
788 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
789 return WAVERR_BADFORMAT;
792 if (dwFlags & WAVE_FORMAT_QUERY)
794 TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
795 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
796 lpDesc->lpFormat->nSamplesPerSec);
797 return MMSYSERR_NOERROR;
800 wwo = &WOutDev[wDevID];
801 if (!OSSpinLockTry(&wwo->lock))
802 return MMSYSERR_ALLOCATED;
804 if (wwo->state != WINE_WS_CLOSED)
806 OSSpinLockUnlock(&wwo->lock);
807 return MMSYSERR_ALLOCATED;
810 if (!AudioUnit_CreateDefaultAudioUnit((void *) wwo, &wwo->audioUnit))
812 ERR("CoreAudio_CreateDefaultAudioUnit(%p) failed\n", wwo);
813 OSSpinLockUnlock(&wwo->lock);
814 return MMSYSERR_ERROR;
817 if ((dwFlags & WAVE_DIRECTSOUND) &&
818 !(wwo->caps.dwSupport & WAVECAPS_DIRECTSOUND))
819 /* not supported, ignore it */
820 dwFlags &= ~WAVE_DIRECTSOUND;
822 streamFormat.mFormatID = kAudioFormatLinearPCM;
823 streamFormat.mFormatFlags = kLinearPCMFormatFlagIsPacked;
824 /* FIXME check for 32bits float -> kLinearPCMFormatFlagIsFloat */
825 if (lpDesc->lpFormat->wBitsPerSample != 8)
826 streamFormat.mFormatFlags |= kLinearPCMFormatFlagIsSignedInteger;
827 # ifdef WORDS_BIGENDIAN
828 streamFormat.mFormatFlags |= kLinearPCMFormatFlagIsBigEndian; /* FIXME Wave format is little endian */
831 streamFormat.mSampleRate = lpDesc->lpFormat->nSamplesPerSec;
832 streamFormat.mChannelsPerFrame = lpDesc->lpFormat->nChannels;
833 streamFormat.mFramesPerPacket = 1;
834 streamFormat.mBitsPerChannel = lpDesc->lpFormat->wBitsPerSample;
835 streamFormat.mBytesPerFrame = streamFormat.mBitsPerChannel * streamFormat.mChannelsPerFrame / 8;
836 streamFormat.mBytesPerPacket = streamFormat.mBytesPerFrame * streamFormat.mFramesPerPacket;
838 ret = AudioUnit_InitializeWithStreamDescription(wwo->audioUnit, &streamFormat);
841 AudioUnit_CloseAudioUnit(wwo->audioUnit);
842 OSSpinLockUnlock(&wwo->lock);
843 return WAVERR_BADFORMAT; /* FIXME return an error based on the OSStatus */
845 wwo->streamDescription = streamFormat;
847 ret = AudioOutputUnitStart(wwo->audioUnit);
850 ERR("AudioOutputUnitStart failed: %08x\n", ret);
851 AudioUnitUninitialize(wwo->audioUnit);
852 AudioUnit_CloseAudioUnit(wwo->audioUnit);
853 OSSpinLockUnlock(&wwo->lock);
854 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
857 wwo->state = WINE_WS_STOPPED;
859 wwo->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
861 wwo->waveDesc = *lpDesc;
862 memcpy(&wwo->format, lpDesc->lpFormat, sizeof(PCMWAVEFORMAT));
864 if (wwo->format.wBitsPerSample == 0) {
865 WARN("Resetting zeroed wBitsPerSample\n");
866 wwo->format.wBitsPerSample = 8 *
867 (wwo->format.wf.nAvgBytesPerSec /
868 wwo->format.wf.nSamplesPerSec) /
869 wwo->format.wf.nChannels;
872 wwo->dwPlayedTotal = 0;
873 wwo->dwWrittenTotal = 0;
875 wwo->trace_on = TRACE_ON(wave);
876 wwo->warn_on = WARN_ON(wave);
877 wwo->err_on = ERR_ON(wave);
879 OSSpinLockUnlock(&wwo->lock);
881 retval = wodNotifyClient(wwo, WOM_OPEN, 0L, 0L);
886 /**************************************************************************
887 * wodClose [internal]
889 static DWORD wodClose(WORD wDevID)
891 DWORD ret = MMSYSERR_NOERROR;
894 TRACE("(%u);\n", wDevID);
896 if (wDevID >= MAX_WAVEOUTDRV)
898 WARN("bad device ID !\n");
899 return MMSYSERR_BADDEVICEID;
902 wwo = &WOutDev[wDevID];
903 OSSpinLockLock(&wwo->lock);
906 WARN("buffers still playing !\n");
907 OSSpinLockUnlock(&wwo->lock);
908 ret = WAVERR_STILLPLAYING;
912 /* sanity check: this should not happen since the device must have been reset before */
913 if (wwo->lpQueuePtr || wwo->lpPlayPtr) ERR("out of sync\n");
915 wwo->state = WINE_WS_CLOSED; /* mark the device as closed */
917 OSSpinLockUnlock(&wwo->lock);
919 err = AudioUnitUninitialize(wwo->audioUnit);
921 ERR("AudioUnitUninitialize return %c%c%c%c\n", (char) (err >> 24),
925 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
928 if ( !AudioUnit_CloseAudioUnit(wwo->audioUnit) )
930 ERR("Can't close AudioUnit\n");
931 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
934 ret = wodNotifyClient(wwo, WOM_CLOSE, 0L, 0L);
940 /**************************************************************************
941 * wodPrepare [internal]
943 static DWORD wodPrepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
945 TRACE("(%u, %p, %08x);\n", wDevID, lpWaveHdr, dwSize);
947 if (wDevID >= MAX_WAVEOUTDRV) {
948 WARN("bad device ID !\n");
949 return MMSYSERR_BADDEVICEID;
952 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
953 return WAVERR_STILLPLAYING;
955 lpWaveHdr->dwFlags |= WHDR_PREPARED;
956 lpWaveHdr->dwFlags &= ~WHDR_DONE;
958 return MMSYSERR_NOERROR;
961 /**************************************************************************
962 * wodUnprepare [internal]
964 static DWORD wodUnprepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
966 TRACE("(%u, %p, %08x);\n", wDevID, lpWaveHdr, dwSize);
968 if (wDevID >= MAX_WAVEOUTDRV) {
969 WARN("bad device ID !\n");
970 return MMSYSERR_BADDEVICEID;
973 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
974 return WAVERR_STILLPLAYING;
976 lpWaveHdr->dwFlags &= ~WHDR_PREPARED;
977 lpWaveHdr->dwFlags |= WHDR_DONE;
979 return MMSYSERR_NOERROR;
983 /**************************************************************************
984 * wodHelper_CheckForLoopBegin [internal]
986 * Check if the new waveheader is the beginning of a loop, and set up
988 * This is called with the WAVEOUT lock held.
989 * Call from AudioUnit IO thread can't use Wine debug channels.
991 static void wodHelper_CheckForLoopBegin(WINE_WAVEOUT* wwo)
993 LPWAVEHDR lpWaveHdr = wwo->lpPlayPtr;
995 if (lpWaveHdr->dwFlags & WHDR_BEGINLOOP)
1000 fprintf(stderr, "warn:winecoreaudio:wodHelper_CheckForLoopBegin Already in a loop. Discarding loop on this header (%p)\n", lpWaveHdr);
1005 fprintf(stderr, "trace:winecoreaudio:wodHelper_CheckForLoopBegin Starting loop (%dx) with %p\n", lpWaveHdr->dwLoops, lpWaveHdr);
1007 wwo->lpLoopPtr = lpWaveHdr;
1008 /* Windows does not touch WAVEHDR.dwLoops,
1009 * so we need to make an internal copy */
1010 wwo->dwLoops = lpWaveHdr->dwLoops;
1016 /**************************************************************************
1017 * wodHelper_PlayPtrNext [internal]
1019 * Advance the play pointer to the next waveheader, looping if required.
1020 * This is called with the WAVEOUT lock held.
1021 * Call from AudioUnit IO thread can't use Wine debug channels.
1023 static void wodHelper_PlayPtrNext(WINE_WAVEOUT* wwo)
1025 BOOL didLoopBack = FALSE;
1027 wwo->dwPartialOffset = 0;
1028 if ((wwo->lpPlayPtr->dwFlags & WHDR_ENDLOOP) && wwo->lpLoopPtr)
1030 /* We're at the end of a loop, loop if required */
1031 if (wwo->dwLoops > 1)
1034 wwo->lpPlayPtr = wwo->lpLoopPtr;
1039 wwo->lpLoopPtr = NULL;
1044 /* We didn't loop back. Advance to the next wave header */
1045 wwo->lpPlayPtr = wwo->lpPlayPtr->lpNext;
1047 if (!wwo->lpPlayPtr)
1048 wwo->state = WINE_WS_STOPPED;
1050 wodHelper_CheckForLoopBegin(wwo);
1054 /* Send the "done" notification for each WAVEHDR in a list. The list must be
1055 * free-standing. It should not be part of a device's queue.
1056 * This function must be called with the WAVEOUT lock *not* held. Furthermore,
1057 * it does not lock it, itself. That's because the callback to the application
1058 * may prompt the application to operate on the device, and we don't want to
1061 static void wodHelper_NotifyDoneForList(WINE_WAVEOUT* wwo, LPWAVEHDR lpWaveHdr)
1065 LPWAVEHDR lpNext = lpWaveHdr->lpNext;
1067 lpWaveHdr->lpNext = NULL;
1068 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1069 lpWaveHdr->dwFlags |= WHDR_DONE;
1070 wodNotifyClient(wwo, WOM_DONE, (DWORD)lpWaveHdr, 0);
1076 /* if force is TRUE then notify the client that all the headers were completed
1078 static void wodHelper_NotifyCompletions(WINE_WAVEOUT* wwo, BOOL force)
1080 LPWAVEHDR lpFirstDoneWaveHdr = NULL;
1082 OSSpinLockLock(&wwo->lock);
1084 /* First, excise all of the done headers from the queue into
1085 * a free-standing list. */
1088 lpFirstDoneWaveHdr = wwo->lpQueuePtr;
1089 wwo->lpQueuePtr = NULL;
1093 LPWAVEHDR lpWaveHdr;
1094 LPWAVEHDR lpLastDoneWaveHdr = NULL;
1096 /* Start from lpQueuePtr and keep notifying until:
1097 * - we hit an unwritten wavehdr
1098 * - we hit the beginning of a running loop
1099 * - we hit a wavehdr which hasn't finished playing
1102 lpWaveHdr = wwo->lpQueuePtr;
1104 lpWaveHdr != wwo->lpPlayPtr &&
1105 lpWaveHdr != wwo->lpLoopPtr;
1106 lpWaveHdr = lpWaveHdr->lpNext
1109 if (!lpFirstDoneWaveHdr)
1110 lpFirstDoneWaveHdr = lpWaveHdr;
1111 lpLastDoneWaveHdr = lpWaveHdr;
1114 if (lpLastDoneWaveHdr)
1116 wwo->lpQueuePtr = lpLastDoneWaveHdr->lpNext;
1117 lpLastDoneWaveHdr->lpNext = NULL;
1121 OSSpinLockUnlock(&wwo->lock);
1123 /* Now, send the "done" notification for each header in our list. */
1124 wodHelper_NotifyDoneForList(wwo, lpFirstDoneWaveHdr);
1128 /**************************************************************************
1129 * wodWrite [internal]
1132 static DWORD wodWrite(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1137 TRACE("(%u, %p, %08X);\n", wDevID, lpWaveHdr, dwSize);
1139 /* first, do the sanity checks... */
1140 if (wDevID >= MAX_WAVEOUTDRV)
1142 WARN("bad dev ID !\n");
1143 return MMSYSERR_BADDEVICEID;
1146 wwo = &WOutDev[wDevID];
1148 if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
1150 TRACE("unprepared\n");
1151 return WAVERR_UNPREPARED;
1154 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1156 TRACE("still playing\n");
1157 return WAVERR_STILLPLAYING;
1160 lpWaveHdr->dwFlags &= ~WHDR_DONE;
1161 lpWaveHdr->dwFlags |= WHDR_INQUEUE;
1162 lpWaveHdr->lpNext = 0;
1164 OSSpinLockLock(&wwo->lock);
1165 /* insert buffer at the end of queue */
1166 for (wh = &(wwo->lpQueuePtr); *wh; wh = &((*wh)->lpNext))
1170 if (!wwo->lpPlayPtr)
1172 wwo->lpPlayPtr = lpWaveHdr;
1174 if (wwo->state == WINE_WS_STOPPED)
1175 wwo->state = WINE_WS_PLAYING;
1177 wodHelper_CheckForLoopBegin(wwo);
1179 wwo->dwPartialOffset = 0;
1181 OSSpinLockUnlock(&wwo->lock);
1183 return MMSYSERR_NOERROR;
1186 /**************************************************************************
1187 * wodPause [internal]
1189 static DWORD wodPause(WORD wDevID)
1193 TRACE("(%u);!\n", wDevID);
1195 if (wDevID >= MAX_WAVEOUTDRV)
1197 WARN("bad device ID !\n");
1198 return MMSYSERR_BADDEVICEID;
1201 /* The order of the following operations is important since we can't hold
1202 * the mutex while we make an Audio Unit call. Stop the Audio Unit before
1203 * setting the PAUSED state. In wodRestart, the order is reversed. This
1204 * guarantees that we can't get into a situation where the state is
1205 * PLAYING or STOPPED but the Audio Unit isn't running. Although we can
1206 * be in PAUSED state with the Audio Unit still running, that's harmless
1207 * because the render callback will just produce silence.
1209 status = AudioOutputUnitStop(WOutDev[wDevID].audioUnit);
1211 WARN("AudioOutputUnitStop return %c%c%c%c\n",
1212 (char) (status >> 24), (char) (status >> 16), (char) (status >> 8), (char) status);
1215 OSSpinLockLock(&WOutDev[wDevID].lock);
1216 if (WOutDev[wDevID].state == WINE_WS_PLAYING || WOutDev[wDevID].state == WINE_WS_STOPPED)
1217 WOutDev[wDevID].state = WINE_WS_PAUSED;
1218 OSSpinLockUnlock(&WOutDev[wDevID].lock);
1220 return MMSYSERR_NOERROR;
1223 /**************************************************************************
1224 * wodRestart [internal]
1226 static DWORD wodRestart(WORD wDevID)
1230 TRACE("(%u);\n", wDevID);
1232 if (wDevID >= MAX_WAVEOUTDRV )
1234 WARN("bad device ID !\n");
1235 return MMSYSERR_BADDEVICEID;
1238 /* The order of the following operations is important since we can't hold
1239 * the mutex while we make an Audio Unit call. Set the PLAYING/STOPPED
1240 * state before starting the Audio Unit. In wodPause, the order is
1241 * reversed. This guarantees that we can't get into a situation where
1242 * the state is PLAYING or STOPPED but the Audio Unit isn't running.
1243 * Although we can be in PAUSED state with the Audio Unit still running,
1244 * that's harmless because the render callback will just produce silence.
1246 OSSpinLockLock(&WOutDev[wDevID].lock);
1247 if (WOutDev[wDevID].state == WINE_WS_PAUSED)
1249 if (WOutDev[wDevID].lpPlayPtr)
1250 WOutDev[wDevID].state = WINE_WS_PLAYING;
1252 WOutDev[wDevID].state = WINE_WS_STOPPED;
1254 OSSpinLockUnlock(&WOutDev[wDevID].lock);
1256 status = AudioOutputUnitStart(WOutDev[wDevID].audioUnit);
1258 ERR("AudioOutputUnitStart return %c%c%c%c\n",
1259 (char) (status >> 24), (char) (status >> 16), (char) (status >> 8), (char) status);
1260 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1263 return MMSYSERR_NOERROR;
1266 /**************************************************************************
1267 * wodReset [internal]
1269 static DWORD wodReset(WORD wDevID)
1273 LPWAVEHDR lpSavedQueuePtr;
1275 TRACE("(%u);\n", wDevID);
1277 if (wDevID >= MAX_WAVEOUTDRV)
1279 WARN("bad device ID !\n");
1280 return MMSYSERR_BADDEVICEID;
1283 wwo = &WOutDev[wDevID];
1285 OSSpinLockLock(&wwo->lock);
1287 if (wwo->state == WINE_WS_CLOSED)
1289 OSSpinLockUnlock(&wwo->lock);
1290 WARN("resetting a closed device\n");
1291 return MMSYSERR_INVALHANDLE;
1294 lpSavedQueuePtr = wwo->lpQueuePtr;
1295 wwo->lpPlayPtr = wwo->lpQueuePtr = wwo->lpLoopPtr = NULL;
1296 wwo->state = WINE_WS_STOPPED;
1297 wwo->dwPlayedTotal = wwo->dwWrittenTotal = 0;
1299 wwo->dwPartialOffset = 0; /* Clear partial wavehdr */
1301 OSSpinLockUnlock(&wwo->lock);
1303 status = AudioOutputUnitStart(wwo->audioUnit);
1306 ERR( "AudioOutputUnitStart return %c%c%c%c\n",
1307 (char) (status >> 24), (char) (status >> 16), (char) (status >> 8), (char) status);
1308 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1311 /* Now, send the "done" notification for each header in our list. */
1312 /* Do this last so the reset operation is effectively complete before the
1313 * app does whatever it's going to do in response to these notifications. */
1314 wodHelper_NotifyDoneForList(wwo, lpSavedQueuePtr);
1316 return MMSYSERR_NOERROR;
1319 /**************************************************************************
1320 * wodGetPosition [internal]
1322 static DWORD wodGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
1327 TRACE("(%u, %p, %u);\n", wDevID, lpTime, uSize);
1329 if (wDevID >= MAX_WAVEOUTDRV)
1331 WARN("bad device ID !\n");
1332 return MMSYSERR_BADDEVICEID;
1335 /* if null pointer to time structure return error */
1336 if (lpTime == NULL) return MMSYSERR_INVALPARAM;
1338 wwo = &WOutDev[wDevID];
1340 OSSpinLockLock(&WOutDev[wDevID].lock);
1341 val = wwo->dwPlayedTotal;
1342 OSSpinLockUnlock(&WOutDev[wDevID].lock);
1344 return bytes_to_mmtime(lpTime, val, &wwo->format);
1347 /**************************************************************************
1348 * wodGetVolume [internal]
1350 static DWORD wodGetVolume(WORD wDevID, LPDWORD lpdwVol)
1355 if (wDevID >= MAX_WAVEOUTDRV)
1357 WARN("bad device ID !\n");
1358 return MMSYSERR_BADDEVICEID;
1361 TRACE("(%u, %p);\n", wDevID, lpdwVol);
1363 AudioUnit_GetVolume(WOutDev[wDevID].audioUnit, &left, &right);
1365 *lpdwVol = ((WORD) left * 0xFFFFl) + (((WORD) right * 0xFFFFl) << 16);
1367 return MMSYSERR_NOERROR;
1370 /**************************************************************************
1371 * wodSetVolume [internal]
1373 static DWORD wodSetVolume(WORD wDevID, DWORD dwParam)
1378 if (wDevID >= MAX_WAVEOUTDRV)
1380 WARN("bad device ID !\n");
1381 return MMSYSERR_BADDEVICEID;
1384 left = LOWORD(dwParam) / 65535.0f;
1385 right = HIWORD(dwParam) / 65535.0f;
1387 TRACE("(%u, %08x);\n", wDevID, dwParam);
1389 AudioUnit_SetVolume(WOutDev[wDevID].audioUnit, left, right);
1391 return MMSYSERR_NOERROR;
1394 /**************************************************************************
1395 * wodGetNumDevs [internal]
1397 static DWORD wodGetNumDevs(void)
1400 return MAX_WAVEOUTDRV;
1403 /**************************************************************************
1404 * wodDevInterfaceSize [internal]
1406 static DWORD wodDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
1408 TRACE("(%u, %p)\n", wDevID, dwParam1);
1410 *dwParam1 = MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].cadev->interface_name, -1,
1411 NULL, 0 ) * sizeof(WCHAR);
1412 return MMSYSERR_NOERROR;
1415 /**************************************************************************
1416 * wodDevInterface [internal]
1418 static DWORD wodDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
1421 if (dwParam2 >= MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].cadev->interface_name, -1,
1422 NULL, 0 ) * sizeof(WCHAR))
1424 MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].cadev->interface_name, -1,
1425 dwParam1, dwParam2 / sizeof(WCHAR));
1426 return MMSYSERR_NOERROR;
1428 return MMSYSERR_INVALPARAM;
1431 /**************************************************************************
1432 * widDsCreate [internal]
1434 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
1436 TRACE("(%d,%p)\n",wDevID,drv);
1438 FIXME("DirectSound not implemented\n");
1439 FIXME("The (slower) DirectSound HEL mode will be used instead.\n");
1440 return MMSYSERR_NOTSUPPORTED;
1443 /**************************************************************************
1444 * wodDsDesc [internal]
1446 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc)
1448 /* The DirectSound HEL will automatically wrap a non-DirectSound-capable
1449 * driver in a DirectSound adaptor, thus allowing the driver to be used by
1450 * DirectSound clients. However, it only does this if we respond
1451 * successfully to the DRV_QUERYDSOUNDDESC message. It's enough to fill in
1452 * the driver and device names of the description output parameter. */
1453 *desc = WOutDev[wDevID].cadev->ds_desc;
1454 return MMSYSERR_NOERROR;
1457 /**************************************************************************
1458 * wodMessage (WINECOREAUDIO.7)
1460 DWORD WINAPI CoreAudio_wodMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
1461 DWORD dwParam1, DWORD dwParam2)
1463 TRACE("(%u, %s, %08x, %08x, %08x);\n",
1464 wDevID, getMessage(wMsg), dwUser, dwParam1, dwParam2);
1472 /* FIXME: Pretend this is supported */
1474 case WODM_OPEN: return wodOpen(wDevID, (LPWAVEOPENDESC) dwParam1, dwParam2);
1475 case WODM_CLOSE: return wodClose(wDevID);
1476 case WODM_WRITE: return wodWrite(wDevID, (LPWAVEHDR) dwParam1, dwParam2);
1477 case WODM_PAUSE: return wodPause(wDevID);
1478 case WODM_GETPOS: return wodGetPosition(wDevID, (LPMMTIME) dwParam1, dwParam2);
1479 case WODM_BREAKLOOP: return MMSYSERR_NOTSUPPORTED;
1480 case WODM_PREPARE: return wodPrepare(wDevID, (LPWAVEHDR)dwParam1, dwParam2);
1481 case WODM_UNPREPARE: return wodUnprepare(wDevID, (LPWAVEHDR)dwParam1, dwParam2);
1483 case WODM_GETDEVCAPS: return wodGetDevCaps(wDevID, (LPWAVEOUTCAPSW) dwParam1, dwParam2);
1484 case WODM_GETNUMDEVS: return wodGetNumDevs();
1488 case WODM_GETPLAYBACKRATE:
1489 case WODM_SETPLAYBACKRATE: return MMSYSERR_NOTSUPPORTED;
1490 case WODM_GETVOLUME: return wodGetVolume(wDevID, (LPDWORD)dwParam1);
1491 case WODM_SETVOLUME: return wodSetVolume(wDevID, dwParam1);
1492 case WODM_RESTART: return wodRestart(wDevID);
1493 case WODM_RESET: return wodReset(wDevID);
1495 case DRV_QUERYDEVICEINTERFACESIZE: return wodDevInterfaceSize (wDevID, (LPDWORD)dwParam1);
1496 case DRV_QUERYDEVICEINTERFACE: return wodDevInterface (wDevID, (PWCHAR)dwParam1, dwParam2);
1497 case DRV_QUERYDSOUNDIFACE: return wodDsCreate (wDevID, (PIDSDRIVER*)dwParam1);
1498 case DRV_QUERYDSOUNDDESC: return wodDsDesc (wDevID, (PDSDRIVERDESC)dwParam1);
1501 FIXME("unknown message %d!\n", wMsg);
1504 return MMSYSERR_NOTSUPPORTED;
1507 /*======================================================================*
1508 * Low level DSOUND implementation *
1509 *======================================================================*/
1511 typedef struct IDsDriverImpl IDsDriverImpl;
1512 typedef struct IDsDriverBufferImpl IDsDriverBufferImpl;
1514 struct IDsDriverImpl
1516 /* IUnknown fields */
1517 const IDsDriverVtbl *lpVtbl;
1519 /* IDsDriverImpl fields */
1521 IDsDriverBufferImpl*primary;
1524 struct IDsDriverBufferImpl
1526 /* IUnknown fields */
1527 const IDsDriverBufferVtbl *lpVtbl;
1529 /* IDsDriverBufferImpl fields */
1536 CoreAudio IO threaded callback,
1537 we can't call Wine debug channels, critical section or anything using NtCurrentTeb here.
1539 OSStatus CoreAudio_woAudioUnitIOProc(void *inRefCon,
1540 AudioUnitRenderActionFlags *ioActionFlags,
1541 const AudioTimeStamp *inTimeStamp,
1543 UInt32 inNumberFrames,
1544 AudioBufferList *ioData)
1547 WINE_WAVEOUT *wwo = (WINE_WAVEOUT *) inRefCon;
1550 unsigned int dataNeeded = ioData->mBuffers[0].mDataByteSize;
1551 unsigned int dataProvided = 0;
1553 OSSpinLockLock(&wwo->lock);
1555 while (dataNeeded > 0 && wwo->state == WINE_WS_PLAYING && wwo->lpPlayPtr)
1557 unsigned int available = wwo->lpPlayPtr->dwBufferLength - wwo->dwPartialOffset;
1558 unsigned int toCopy;
1560 if (available >= dataNeeded)
1561 toCopy = dataNeeded;
1567 memcpy((char*)ioData->mBuffers[0].mData + dataProvided,
1568 wwo->lpPlayPtr->lpData + wwo->dwPartialOffset, toCopy);
1569 wwo->dwPartialOffset += toCopy;
1570 wwo->dwPlayedTotal += toCopy;
1571 dataProvided += toCopy;
1572 dataNeeded -= toCopy;
1573 available -= toCopy;
1578 wodHelper_PlayPtrNext(wwo);
1582 ioData->mBuffers[0].mDataByteSize = dataProvided;
1584 OSSpinLockUnlock(&wwo->lock);
1586 /* We can't provide any more wave data. Fill the rest with silence. */
1590 *ioActionFlags |= kAudioUnitRenderAction_OutputIsSilence;
1591 memset((char*)ioData->mBuffers[0].mData + dataProvided, 0, dataNeeded);
1592 dataProvided += dataNeeded;
1596 /* We only fill buffer 0. Set any others that might be requested to 0. */
1597 for (buffer = 1; buffer < ioData->mNumberBuffers; buffer++)
1599 memset(ioData->mBuffers[buffer].mData, 0, ioData->mBuffers[buffer].mDataByteSize);
1602 if (needNotify) wodSendNotifyCompletionsMessage(wwo);
1607 /*======================================================================*
1608 * Low level WAVE IN implementation *
1609 *======================================================================*/
1611 /**************************************************************************
1612 * widNotifyClient [internal]
1614 static DWORD widNotifyClient(WINE_WAVEIN* wwi, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
1616 TRACE("wMsg = 0x%04x dwParm1 = %04X dwParam2 = %04X\n", wMsg, dwParam1, dwParam2);
1623 if (wwi->wFlags != DCB_NULL &&
1624 !DriverCallback(wwi->waveDesc.dwCallback, wwi->wFlags,
1625 (HDRVR)wwi->waveDesc.hWave, wMsg, wwi->waveDesc.dwInstance,
1626 dwParam1, dwParam2))
1628 WARN("can't notify client !\n");
1629 return MMSYSERR_ERROR;
1633 FIXME("Unknown callback message %u\n", wMsg);
1634 return MMSYSERR_INVALPARAM;
1636 return MMSYSERR_NOERROR;
1640 /**************************************************************************
1641 * widHelper_NotifyCompletions [internal]
1643 static void widHelper_NotifyCompletions(WINE_WAVEIN* wwi)
1645 LPWAVEHDR lpWaveHdr;
1646 LPWAVEHDR lpFirstDoneWaveHdr = NULL;
1647 LPWAVEHDR lpLastDoneWaveHdr = NULL;
1649 OSSpinLockLock(&wwi->lock);
1651 /* First, excise all of the done headers from the queue into
1652 * a free-standing list. */
1654 /* Start from lpQueuePtr and keep notifying until:
1655 * - we hit an unfilled wavehdr
1656 * - we hit the end of the list
1659 lpWaveHdr = wwi->lpQueuePtr;
1661 lpWaveHdr->dwBytesRecorded >= lpWaveHdr->dwBufferLength;
1662 lpWaveHdr = lpWaveHdr->lpNext
1665 if (!lpFirstDoneWaveHdr)
1666 lpFirstDoneWaveHdr = lpWaveHdr;
1667 lpLastDoneWaveHdr = lpWaveHdr;
1670 if (lpLastDoneWaveHdr)
1672 wwi->lpQueuePtr = lpLastDoneWaveHdr->lpNext;
1673 lpLastDoneWaveHdr->lpNext = NULL;
1676 OSSpinLockUnlock(&wwi->lock);
1678 /* Now, send the "done" notification for each header in our list. */
1679 lpWaveHdr = lpFirstDoneWaveHdr;
1682 LPWAVEHDR lpNext = lpWaveHdr->lpNext;
1684 lpWaveHdr->lpNext = NULL;
1685 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1686 lpWaveHdr->dwFlags |= WHDR_DONE;
1687 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
1694 /**************************************************************************
1695 * widGetDevCaps [internal]
1697 static DWORD widGetDevCaps(WORD wDevID, LPWAVEINCAPSW lpCaps, DWORD dwSize)
1699 TRACE("(%u, %p, %u);\n", wDevID, lpCaps, dwSize);
1701 if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
1703 if (wDevID >= MAX_WAVEINDRV)
1705 TRACE("MAX_WAVEINDRV reached !\n");
1706 return MMSYSERR_BADDEVICEID;
1709 memcpy(lpCaps, &WInDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
1710 return MMSYSERR_NOERROR;
1714 /**************************************************************************
1715 * widHelper_DestroyAudioBufferList [internal]
1716 * Convenience function to dispose of our audio buffers
1718 static void widHelper_DestroyAudioBufferList(AudioBufferList* list)
1723 for (i = 0; i < list->mNumberBuffers; i++)
1725 if (list->mBuffers[i].mData)
1726 HeapFree(GetProcessHeap(), 0, list->mBuffers[i].mData);
1728 HeapFree(GetProcessHeap(), 0, list);
1733 #define AUDIOBUFFERLISTSIZE(numBuffers) (offsetof(AudioBufferList, mBuffers) + (numBuffers) * sizeof(AudioBuffer))
1735 /**************************************************************************
1736 * widHelper_AllocateAudioBufferList [internal]
1737 * Convenience function to allocate our audio buffers
1739 static AudioBufferList* widHelper_AllocateAudioBufferList(UInt32 numChannels, UInt32 bitsPerChannel, UInt32 bufferFrames, BOOL interleaved)
1742 UInt32 channelsPerFrame;
1743 UInt32 bytesPerFrame;
1744 UInt32 bytesPerBuffer;
1745 AudioBufferList* list;
1750 /* For interleaved audio, we allocate one buffer for all channels. */
1752 channelsPerFrame = numChannels;
1756 numBuffers = numChannels;
1757 channelsPerFrame = 1;
1760 bytesPerFrame = bitsPerChannel * channelsPerFrame / 8;
1761 bytesPerBuffer = bytesPerFrame * bufferFrames;
1763 list = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, AUDIOBUFFERLISTSIZE(numBuffers));
1767 list->mNumberBuffers = numBuffers;
1768 for (i = 0; i < numBuffers; ++i)
1770 list->mBuffers[i].mNumberChannels = channelsPerFrame;
1771 list->mBuffers[i].mDataByteSize = bytesPerBuffer;
1772 list->mBuffers[i].mData = HeapAlloc(GetProcessHeap(), 0, bytesPerBuffer);
1773 if (list->mBuffers[i].mData == NULL)
1775 widHelper_DestroyAudioBufferList(list);
1783 /**************************************************************************
1784 * widOpen [internal]
1786 static DWORD widOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
1791 TRACE("(%u, %p, %08X);\n", wDevID, lpDesc, dwFlags);
1794 WARN("Invalid Parameter !\n");
1795 return MMSYSERR_INVALPARAM;
1797 if (wDevID >= MAX_WAVEINDRV)
1799 TRACE ("MAX_WAVEINDRV reached !\n");
1800 return MMSYSERR_BADDEVICEID;
1803 TRACE("Format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
1804 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1805 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
1807 if (lpDesc->lpFormat->wFormatTag != WAVE_FORMAT_PCM ||
1808 lpDesc->lpFormat->nChannels == 0 ||
1809 lpDesc->lpFormat->nSamplesPerSec == 0 ||
1810 lpDesc->lpFormat->nSamplesPerSec != AudioUnit_GetInputDeviceSampleRate()
1813 WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
1814 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1815 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
1816 return WAVERR_BADFORMAT;
1819 if (dwFlags & WAVE_FORMAT_QUERY)
1821 TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
1822 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1823 lpDesc->lpFormat->nSamplesPerSec);
1824 return MMSYSERR_NOERROR;
1827 wwi = &WInDev[wDevID];
1828 if (!OSSpinLockTry(&wwi->lock))
1829 return MMSYSERR_ALLOCATED;
1831 if (wwi->state != WINE_WS_CLOSED)
1833 OSSpinLockUnlock(&wwi->lock);
1834 return MMSYSERR_ALLOCATED;
1837 wwi->state = WINE_WS_STOPPED;
1838 wwi->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
1840 wwi->waveDesc = *lpDesc;
1841 memcpy(&wwi->format, lpDesc->lpFormat, sizeof(PCMWAVEFORMAT));
1843 if (wwi->format.wBitsPerSample == 0)
1845 WARN("Resetting zeroed wBitsPerSample\n");
1846 wwi->format.wBitsPerSample = 8 *
1847 (wwi->format.wf.nAvgBytesPerSec /
1848 wwi->format.wf.nSamplesPerSec) /
1849 wwi->format.wf.nChannels;
1852 wwi->dwTotalRecorded = 0;
1854 wwi->trace_on = TRACE_ON(wave);
1855 wwi->warn_on = WARN_ON(wave);
1856 wwi->err_on = ERR_ON(wave);
1858 if (!AudioUnit_CreateInputUnit(wwi, &wwi->audioUnit,
1859 wwi->format.wf.nChannels, wwi->format.wf.nSamplesPerSec,
1860 wwi->format.wBitsPerSample, &frameCount))
1862 ERR("AudioUnit_CreateInputUnit failed\n");
1863 OSSpinLockUnlock(&wwi->lock);
1864 return MMSYSERR_ERROR;
1867 /* Allocate our audio buffers */
1868 wwi->bufferList = widHelper_AllocateAudioBufferList(wwi->format.wf.nChannels,
1869 wwi->format.wBitsPerSample, frameCount, TRUE);
1870 if (wwi->bufferList == NULL)
1872 ERR("Failed to allocate buffer list\n");
1873 AudioUnitUninitialize(wwi->audioUnit);
1874 AudioUnit_CloseAudioUnit(wwi->audioUnit);
1875 OSSpinLockUnlock(&wwi->lock);
1876 return MMSYSERR_NOMEM;
1879 /* Keep a copy of the buffer list structure (but not the buffers themselves)
1880 * in case AudioUnitRender clobbers the original, as it won't to do. */
1881 wwi->bufferListCopy = HeapAlloc(GetProcessHeap(), 0, AUDIOBUFFERLISTSIZE(wwi->bufferList->mNumberBuffers));
1882 if (wwi->bufferListCopy == NULL)
1884 ERR("Failed to allocate buffer list copy\n");
1885 widHelper_DestroyAudioBufferList(wwi->bufferList);
1886 AudioUnitUninitialize(wwi->audioUnit);
1887 AudioUnit_CloseAudioUnit(wwi->audioUnit);
1888 OSSpinLockUnlock(&wwi->lock);
1889 return MMSYSERR_NOMEM;
1891 memcpy(wwi->bufferListCopy, wwi->bufferList, AUDIOBUFFERLISTSIZE(wwi->bufferList->mNumberBuffers));
1893 OSSpinLockUnlock(&wwi->lock);
1895 return widNotifyClient(wwi, WIM_OPEN, 0L, 0L);
1899 /**************************************************************************
1900 * widClose [internal]
1902 static DWORD widClose(WORD wDevID)
1904 DWORD ret = MMSYSERR_NOERROR;
1907 TRACE("(%u);\n", wDevID);
1909 if (wDevID >= MAX_WAVEINDRV)
1911 WARN("bad device ID !\n");
1912 return MMSYSERR_BADDEVICEID;
1915 wwi = &WInDev[wDevID];
1916 OSSpinLockLock(&wwi->lock);
1917 if (wwi->state == WINE_WS_CLOSED)
1919 WARN("Device already closed.\n");
1920 ret = MMSYSERR_INVALHANDLE;
1922 else if (wwi->lpQueuePtr)
1924 WARN("Buffers in queue.\n");
1925 ret = WAVERR_STILLPLAYING;
1929 wwi->state = WINE_WS_CLOSED;
1932 OSSpinLockUnlock(&wwi->lock);
1934 if (ret == MMSYSERR_NOERROR)
1936 OSStatus err = AudioUnitUninitialize(wwi->audioUnit);
1939 ERR("AudioUnitUninitialize return %c%c%c%c\n", (char) (err >> 24),
1945 if (!AudioUnit_CloseAudioUnit(wwi->audioUnit))
1947 ERR("Can't close AudioUnit\n");
1950 /* Dellocate our audio buffers */
1951 widHelper_DestroyAudioBufferList(wwi->bufferList);
1952 wwi->bufferList = NULL;
1953 HeapFree(GetProcessHeap(), 0, wwi->bufferListCopy);
1954 wwi->bufferListCopy = NULL;
1956 ret = widNotifyClient(wwi, WIM_CLOSE, 0L, 0L);
1963 /**************************************************************************
1964 * widAddBuffer [internal]
1966 static DWORD widAddBuffer(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1968 DWORD ret = MMSYSERR_NOERROR;
1971 TRACE("(%u, %p, %08X);\n", wDevID, lpWaveHdr, dwSize);
1973 if (wDevID >= MAX_WAVEINDRV)
1975 WARN("invalid device ID\n");
1976 return MMSYSERR_INVALHANDLE;
1978 if (!(lpWaveHdr->dwFlags & WHDR_PREPARED))
1980 TRACE("never been prepared !\n");
1981 return WAVERR_UNPREPARED;
1983 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1985 TRACE("header already in use !\n");
1986 return WAVERR_STILLPLAYING;
1989 wwi = &WInDev[wDevID];
1990 OSSpinLockLock(&wwi->lock);
1992 if (wwi->state == WINE_WS_CLOSED)
1994 WARN("Trying to add buffer to closed device.\n");
1995 ret = MMSYSERR_INVALHANDLE;
2001 lpWaveHdr->dwFlags |= WHDR_INQUEUE;
2002 lpWaveHdr->dwFlags &= ~WHDR_DONE;
2003 lpWaveHdr->dwBytesRecorded = 0;
2004 lpWaveHdr->lpNext = NULL;
2006 /* insert buffer at end of queue */
2007 for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext))
2012 OSSpinLockUnlock(&wwi->lock);
2018 /**************************************************************************
2019 * widStart [internal]
2021 static DWORD widStart(WORD wDevID)
2023 DWORD ret = MMSYSERR_NOERROR;
2026 TRACE("(%u);\n", wDevID);
2027 if (wDevID >= MAX_WAVEINDRV)
2029 WARN("invalid device ID\n");
2030 return MMSYSERR_INVALHANDLE;
2033 /* The order of the following operations is important since we can't hold
2034 * the mutex while we make an Audio Unit call. Set the PLAYING state
2035 * before starting the Audio Unit. In widStop, the order is reversed.
2036 * This guarantees that we can't get into a situation where the state is
2037 * PLAYING but the Audio Unit isn't running. Although we can be in STOPPED
2038 * state with the Audio Unit still running, that's harmless because the
2039 * input callback will just throw away the sound data.
2041 wwi = &WInDev[wDevID];
2042 OSSpinLockLock(&wwi->lock);
2044 if (wwi->state == WINE_WS_CLOSED)
2046 WARN("Trying to start closed device.\n");
2047 ret = MMSYSERR_INVALHANDLE;
2050 wwi->state = WINE_WS_PLAYING;
2052 OSSpinLockUnlock(&wwi->lock);
2054 if (ret == MMSYSERR_NOERROR)
2056 /* Start pulling for audio data */
2057 OSStatus err = AudioOutputUnitStart(wwi->audioUnit);
2059 ERR("Failed to start AU: %08lx\n", err);
2061 TRACE("Recording started...\n");
2068 /**************************************************************************
2069 * widStop [internal]
2071 static DWORD widStop(WORD wDevID)
2073 DWORD ret = MMSYSERR_NOERROR;
2075 WAVEHDR* lpWaveHdr = NULL;
2078 TRACE("(%u);\n", wDevID);
2079 if (wDevID >= MAX_WAVEINDRV)
2081 WARN("invalid device ID\n");
2082 return MMSYSERR_INVALHANDLE;
2085 wwi = &WInDev[wDevID];
2087 /* The order of the following operations is important since we can't hold
2088 * the mutex while we make an Audio Unit call. Stop the Audio Unit before
2089 * setting the STOPPED state. In widStart, the order is reversed. This
2090 * guarantees that we can't get into a situation where the state is
2091 * PLAYING but the Audio Unit isn't running. Although we can be in STOPPED
2092 * state with the Audio Unit still running, that's harmless because the
2093 * input callback will just throw away the sound data.
2095 err = AudioOutputUnitStop(wwi->audioUnit);
2097 WARN("Failed to stop AU: %08lx\n", err);
2099 TRACE("Recording stopped.\n");
2101 OSSpinLockLock(&wwi->lock);
2103 if (wwi->state == WINE_WS_CLOSED)
2105 WARN("Trying to stop closed device.\n");
2106 ret = MMSYSERR_INVALHANDLE;
2108 else if (wwi->state != WINE_WS_STOPPED)
2110 wwi->state = WINE_WS_STOPPED;
2111 /* If there's a buffer in progress, it's done. Remove it from the
2112 * queue so that we can return it to the app, below. */
2113 if (wwi->lpQueuePtr)
2115 lpWaveHdr = wwi->lpQueuePtr;
2116 wwi->lpQueuePtr = lpWaveHdr->lpNext;
2120 OSSpinLockUnlock(&wwi->lock);
2124 lpWaveHdr->lpNext = NULL;
2125 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2126 lpWaveHdr->dwFlags |= WHDR_DONE;
2127 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2133 /**************************************************************************
2134 * widGetPos [internal]
2136 static DWORD widGetPos(WORD wDevID, LPMMTIME lpTime, UINT size)
2141 TRACE("(%u);\n", wDevID);
2142 if (wDevID >= MAX_WAVEINDRV)
2144 WARN("invalid device ID\n");
2145 return MMSYSERR_INVALHANDLE;
2148 wwi = &WInDev[wDevID];
2150 OSSpinLockLock(&WInDev[wDevID].lock);
2151 val = wwi->dwTotalRecorded;
2152 OSSpinLockUnlock(&WInDev[wDevID].lock);
2154 return bytes_to_mmtime(lpTime, val, &wwi->format);
2157 /**************************************************************************
2158 * widReset [internal]
2160 static DWORD widReset(WORD wDevID)
2162 DWORD ret = MMSYSERR_NOERROR;
2164 WAVEHDR* lpWaveHdr = NULL;
2166 TRACE("(%u);\n", wDevID);
2167 if (wDevID >= MAX_WAVEINDRV)
2169 WARN("invalid device ID\n");
2170 return MMSYSERR_INVALHANDLE;
2173 wwi = &WInDev[wDevID];
2174 OSSpinLockLock(&wwi->lock);
2176 if (wwi->state == WINE_WS_CLOSED)
2178 WARN("Trying to reset a closed device.\n");
2179 ret = MMSYSERR_INVALHANDLE;
2183 lpWaveHdr = wwi->lpQueuePtr;
2184 wwi->lpQueuePtr = NULL;
2185 wwi->state = WINE_WS_STOPPED;
2186 wwi->dwTotalRecorded = 0;
2189 OSSpinLockUnlock(&wwi->lock);
2191 if (ret == MMSYSERR_NOERROR)
2193 OSStatus err = AudioOutputUnitStop(wwi->audioUnit);
2195 WARN("Failed to stop AU: %08lx\n", err);
2197 TRACE("Recording stopped.\n");
2202 WAVEHDR* lpNext = lpWaveHdr->lpNext;
2204 lpWaveHdr->lpNext = NULL;
2205 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2206 lpWaveHdr->dwFlags |= WHDR_DONE;
2207 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2216 /**************************************************************************
2217 * widGetNumDevs [internal]
2219 static DWORD widGetNumDevs(void)
2221 return MAX_WAVEINDRV;
2225 /**************************************************************************
2226 * widDevInterfaceSize [internal]
2228 static DWORD widDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
2230 TRACE("(%u, %p)\n", wDevID, dwParam1);
2232 *dwParam1 = MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
2233 NULL, 0 ) * sizeof(WCHAR);
2234 return MMSYSERR_NOERROR;
2238 /**************************************************************************
2239 * widDevInterface [internal]
2241 static DWORD widDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
2243 if (dwParam2 >= MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
2244 NULL, 0 ) * sizeof(WCHAR))
2246 MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
2247 dwParam1, dwParam2 / sizeof(WCHAR));
2248 return MMSYSERR_NOERROR;
2250 return MMSYSERR_INVALPARAM;
2254 /**************************************************************************
2255 * widDsCreate [internal]
2257 static DWORD widDsCreate(UINT wDevID, PIDSCDRIVER* drv)
2259 TRACE("(%d,%p)\n",wDevID,drv);
2261 FIXME("DirectSoundCapture not implemented\n");
2262 FIXME("The (slower) DirectSound HEL mode will be used instead.\n");
2263 return MMSYSERR_NOTSUPPORTED;
2266 /**************************************************************************
2267 * widDsDesc [internal]
2269 static DWORD widDsDesc(UINT wDevID, PDSDRIVERDESC desc)
2271 /* The DirectSound HEL will automatically wrap a non-DirectSound-capable
2272 * driver in a DirectSound adaptor, thus allowing the driver to be used by
2273 * DirectSound clients. However, it only does this if we respond
2274 * successfully to the DRV_QUERYDSOUNDDESC message. It's enough to fill in
2275 * the driver and device names of the description output parameter. */
2276 memset(desc, 0, sizeof(*desc));
2277 lstrcpynA(desc->szDrvname, "winecoreaudio.drv", sizeof(desc->szDrvname) - 1);
2278 lstrcpynA(desc->szDesc, WInDev[wDevID].interface_name, sizeof(desc->szDesc) - 1);
2279 return MMSYSERR_NOERROR;
2283 /**************************************************************************
2284 * widMessage (WINECOREAUDIO.6)
2286 DWORD WINAPI CoreAudio_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2287 DWORD dwParam1, DWORD dwParam2)
2289 TRACE("(%u, %04X, %08X, %08X, %08X);\n",
2290 wDevID, wMsg, dwUser, dwParam1, dwParam2);
2298 /* FIXME: Pretend this is supported */
2300 case WIDM_OPEN: return widOpen (wDevID, (LPWAVEOPENDESC)dwParam1, dwParam2);
2301 case WIDM_CLOSE: return widClose (wDevID);
2302 case WIDM_ADDBUFFER: return widAddBuffer (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2303 case WIDM_PREPARE: return MMSYSERR_NOTSUPPORTED;
2304 case WIDM_UNPREPARE: return MMSYSERR_NOTSUPPORTED;
2305 case WIDM_GETDEVCAPS: return widGetDevCaps (wDevID, (LPWAVEINCAPSW)dwParam1, dwParam2);
2306 case WIDM_GETNUMDEVS: return widGetNumDevs ();
2307 case WIDM_RESET: return widReset (wDevID);
2308 case WIDM_START: return widStart (wDevID);
2309 case WIDM_STOP: return widStop (wDevID);
2310 case WIDM_GETPOS: return widGetPos (wDevID, (LPMMTIME)dwParam1, (UINT)dwParam2 );
2311 case DRV_QUERYDEVICEINTERFACESIZE: return widDevInterfaceSize (wDevID, (LPDWORD)dwParam1);
2312 case DRV_QUERYDEVICEINTERFACE: return widDevInterface (wDevID, (PWCHAR)dwParam1, dwParam2);
2313 case DRV_QUERYDSOUNDIFACE: return widDsCreate (wDevID, (PIDSCDRIVER*)dwParam1);
2314 case DRV_QUERYDSOUNDDESC: return widDsDesc (wDevID, (PDSDRIVERDESC)dwParam1);
2316 FIXME("unknown message %d!\n", wMsg);
2319 return MMSYSERR_NOTSUPPORTED;
2323 OSStatus CoreAudio_wiAudioUnitIOProc(void *inRefCon,
2324 AudioUnitRenderActionFlags *ioActionFlags,
2325 const AudioTimeStamp *inTimeStamp,
2327 UInt32 inNumberFrames,
2328 AudioBufferList *ioData)
2330 WINE_WAVEIN* wwi = (WINE_WAVEIN*)inRefCon;
2331 OSStatus err = noErr;
2332 BOOL needNotify = FALSE;
2333 WAVEHDR* lpStorePtr;
2334 unsigned int dataToStore;
2335 unsigned int dataStored = 0;
2339 fprintf(stderr, "trace:wave:CoreAudio_wiAudioUnitIOProc (ioActionFlags = %08lx, "
2340 "inTimeStamp = { %f, %x%08x, %f, %x%08x, %08lx }, inBusNumber = %lu, inNumberFrames = %lu)\n",
2341 *ioActionFlags, inTimeStamp->mSampleTime, (DWORD)(inTimeStamp->mHostTime >>32),
2342 (DWORD)inTimeStamp->mHostTime, inTimeStamp->mRateScalar, (DWORD)(inTimeStamp->mWordClockTime >> 32),
2343 (DWORD)inTimeStamp->mWordClockTime, inTimeStamp->mFlags, inBusNumber, inNumberFrames);
2345 /* Render into audio buffer */
2346 /* FIXME: implement sample rate conversion on input. This will require
2347 * a different render strategy. We'll need to buffer the sound data
2348 * received here and pass it off to an AUConverter in another thread. */
2349 err = AudioUnitRender(wwi->audioUnit, ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, wwi->bufferList);
2353 fprintf(stderr, "err:wave:CoreAudio_wiAudioUnitIOProc AudioUnitRender failed with error %li\n", err);
2357 /* Copy from audio buffer to the wavehdrs */
2358 dataToStore = wwi->bufferList->mBuffers[0].mDataByteSize;
2360 OSSpinLockLock(&wwi->lock);
2362 lpStorePtr = wwi->lpQueuePtr;
2364 while (dataToStore > 0 && wwi->state == WINE_WS_PLAYING && lpStorePtr)
2366 unsigned int room = lpStorePtr->dwBufferLength - lpStorePtr->dwBytesRecorded;
2367 unsigned int toCopy;
2370 fprintf(stderr, "trace:wave:CoreAudio_wiAudioUnitIOProc Looking to store %u bytes to wavehdr %p, which has room for %u\n",
2371 dataToStore, lpStorePtr, room);
2373 if (room >= dataToStore)
2374 toCopy = dataToStore;
2380 memcpy(lpStorePtr->lpData + lpStorePtr->dwBytesRecorded,
2381 (char*)wwi->bufferList->mBuffers[0].mData + dataStored, toCopy);
2382 lpStorePtr->dwBytesRecorded += toCopy;
2383 wwi->dwTotalRecorded += toCopy;
2384 dataStored += toCopy;
2385 dataToStore -= toCopy;
2391 lpStorePtr = lpStorePtr->lpNext;
2396 OSSpinLockUnlock(&wwi->lock);
2398 /* Restore the audio buffer list structure from backup, in case
2399 * AudioUnitRender clobbered it. (It modifies mDataByteSize and may even
2400 * give us a different mData buffer to avoid a copy.) */
2401 memcpy(wwi->bufferList, wwi->bufferListCopy, AUDIOBUFFERLISTSIZE(wwi->bufferList->mNumberBuffers));
2403 if (needNotify) wodSendNotifyInputCompletionsMessage(wwi);
2409 /**************************************************************************
2410 * widMessage (WINECOREAUDIO.6)
2412 DWORD WINAPI CoreAudio_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2413 DWORD dwParam1, DWORD dwParam2)
2415 FIXME("(%u, %04X, %08X, %08X, %08X): CoreAudio support not compiled into wine\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2416 return MMSYSERR_NOTENABLED;
2419 /**************************************************************************
2420 * wodMessage (WINECOREAUDIO.7)
2422 DWORD WINAPI CoreAudio_wodMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2423 DWORD dwParam1, DWORD dwParam2)
2425 FIXME("(%u, %04X, %08X, %08X, %08X): CoreAudio support not compiled into wine\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2426 return MMSYSERR_NOTENABLED;