2 * Wine Driver for CoreAudio based on Jack Driver
4 * Copyright 1994 Martin Ayotte
5 * Copyright 1999 Eric Pouech (async playing in waveOut/waveIn)
6 * Copyright 2000 Eric Pouech (loops in waveOut)
7 * Copyright 2002 Chris Morgan (jack version of this file)
8 * Copyright 2005, 2006 Emmanuel Maillard
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
49 #include "coreaudio.h"
50 #include "wine/unicode.h"
51 #include "wine/library.h"
52 #include "wine/debug.h"
54 WINE_DEFAULT_DEBUG_CHANNEL(wave);
57 #if defined(HAVE_COREAUDIO_COREAUDIO_H) && defined(HAVE_AUDIOUNIT_AUDIOUNIT_H)
58 #include <CoreAudio/CoreAudio.h>
59 #include <CoreFoundation/CoreFoundation.h>
60 #include <libkern/OSAtomic.h>
63 Due to AudioUnit headers conflict define some needed types.
66 typedef void *AudioUnit;
68 /* From AudioUnit/AUComponents.h */
71 kAudioUnitRenderAction_OutputIsSilence = (1 << 4),
72 /* provides hint on return from Render(): if set the buffer contains all zeroes */
74 typedef UInt32 AudioUnitRenderActionFlags;
76 typedef long ComponentResult;
77 extern ComponentResult
78 AudioUnitRender( AudioUnit ci,
79 AudioUnitRenderActionFlags * ioActionFlags,
80 const AudioTimeStamp * inTimeStamp,
81 UInt32 inOutputBusNumber,
82 UInt32 inNumberFrames,
83 AudioBufferList * ioData) AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER;
85 /* only allow 10 output devices through this driver, this ought to be adequate */
86 #define MAX_WAVEOUTDRV (1)
87 #define MAX_WAVEINDRV (1)
89 /* state diagram for waveOut writing:
91 * +---------+-------------+---------------+---------------------------------+
92 * | state | function | event | new state |
93 * +---------+-------------+---------------+---------------------------------+
94 * | | open() | | PLAYING |
95 * | PAUSED | write() | | PAUSED |
96 * | PLAYING | write() | HEADER | PLAYING |
97 * | (other) | write() | <error> | |
98 * | (any) | pause() | PAUSING | PAUSED |
99 * | PAUSED | restart() | RESTARTING | PLAYING |
100 * | (any) | reset() | RESETTING | PLAYING |
101 * | (any) | close() | CLOSING | CLOSED |
102 * +---------+-------------+---------------+---------------------------------+
105 /* states of the playing device */
106 #define WINE_WS_PLAYING 0 /* for waveOut: lpPlayPtr == NULL -> stopped */
107 #define WINE_WS_PAUSED 1
108 #define WINE_WS_STOPPED 2 /* Not used for waveOut */
109 #define WINE_WS_CLOSED 3
110 #define WINE_WS_OPENING 4
111 #define WINE_WS_CLOSING 5
113 typedef struct tagCoreAudio_Device {
117 char* interface_name;
119 WAVEOUTCAPSW out_caps;
121 DWORD in_caps_support;
125 unsigned audio_fragment;
127 BOOL bTriggerSupport;
130 DSDRIVERDESC ds_desc;
131 DSDRIVERCAPS ds_caps;
132 DSCDRIVERCAPS dsc_caps;
136 AudioDeviceID outputDeviceID;
137 AudioDeviceID inputDeviceID;
138 AudioStreamBasicDescription streamDescription;
141 /* for now use the default device */
142 static CoreAudio_Device CoreAudio_DefaultDevice;
145 volatile int state; /* one of the WINE_WS_ manifest constants */
146 CoreAudio_Device *cadev;
147 WAVEOPENDESC waveDesc;
149 PCMWAVEFORMAT format;
152 AudioStreamBasicDescription streamDescription;
155 char interface_name[32];
156 LPWAVEHDR lpQueuePtr; /* start of queued WAVEHDRs (waiting to be notified) */
157 LPWAVEHDR lpPlayPtr; /* start of not yet fully played buffers */
158 DWORD dwPartialOffset; /* Offset of not yet written bytes in lpPlayPtr */
160 LPWAVEHDR lpLoopPtr; /* pointer of first buffer in loop, if any */
161 DWORD dwLoops; /* private copy of loop counter */
163 DWORD dwPlayedTotal; /* number of bytes actually played since opening */
164 DWORD dwWrittenTotal; /* number of bytes written to OSS buffer since opening */
166 DWORD tickCountMS; /* time in MS of last AudioUnit callback */
168 OSSpinLock lock; /* synchronization stuff */
176 /* This device's device number */
179 /* Access to the following fields is synchronized across threads. */
181 LPWAVEHDR lpQueuePtr;
182 DWORD dwTotalRecorded;
184 /* Synchronization mechanism to protect above fields */
187 /* Capabilities description */
189 char interface_name[32];
191 /* Record the arguments used when opening the device. */
192 WAVEOPENDESC waveDesc;
194 PCMWAVEFORMAT format;
197 AudioBufferList*bufferList;
198 AudioBufferList*bufferListCopy;
200 /* Record state of debug channels at open. Used to control fprintf's since
201 * we can't use Wine debug channel calls in non-Wine AudioUnit threads. */
206 /* These fields aren't used. */
208 CoreAudio_Device *cadev;
210 AudioStreamBasicDescription streamDescription;
214 static WINE_WAVEOUT WOutDev [MAX_WAVEOUTDRV];
215 static WINE_WAVEIN WInDev [MAX_WAVEINDRV];
217 static HANDLE hThread = NULL; /* Track the thread we create so we can clean it up later */
218 static CFMessagePortRef Port_SendToMessageThread;
220 static void wodHelper_PlayPtrNext(WINE_WAVEOUT* wwo);
221 static void wodHelper_NotifyDoneForList(WINE_WAVEOUT* wwo, LPWAVEHDR lpWaveHdr);
222 static void wodHelper_NotifyCompletions(WINE_WAVEOUT* wwo, BOOL force);
223 static void widHelper_NotifyCompletions(WINE_WAVEIN* wwi);
225 extern int AudioUnit_CreateDefaultAudioUnit(void *wwo, AudioUnit *au);
226 extern int AudioUnit_CloseAudioUnit(AudioUnit au);
227 extern int AudioUnit_InitializeWithStreamDescription(AudioUnit au, AudioStreamBasicDescription *streamFormat);
229 extern OSStatus AudioOutputUnitStart(AudioUnit au);
230 extern OSStatus AudioOutputUnitStop(AudioUnit au);
231 extern OSStatus AudioUnitUninitialize(AudioUnit au);
233 extern int AudioUnit_SetVolume(AudioUnit au, float left, float right);
234 extern int AudioUnit_GetVolume(AudioUnit au, float *left, float *right);
236 extern int AudioUnit_GetInputDeviceSampleRate(void);
238 extern int AudioUnit_CreateInputUnit(void* wwi, AudioUnit* out_au,
239 WORD nChannels, DWORD nSamplesPerSec, WORD wBitsPerSample,
240 UInt32* outFrameCount);
242 OSStatus CoreAudio_woAudioUnitIOProc(void *inRefCon,
243 AudioUnitRenderActionFlags *ioActionFlags,
244 const AudioTimeStamp *inTimeStamp,
246 UInt32 inNumberFrames,
247 AudioBufferList *ioData);
248 OSStatus CoreAudio_wiAudioUnitIOProc(void *inRefCon,
249 AudioUnitRenderActionFlags *ioActionFlags,
250 const AudioTimeStamp *inTimeStamp,
252 UInt32 inNumberFrames,
253 AudioBufferList *ioData);
255 /* These strings used only for tracing */
257 static const char * getMessage(UINT msg)
259 static char unknown[32];
260 #define MSG_TO_STR(x) case x: return #x
262 MSG_TO_STR(DRVM_INIT);
263 MSG_TO_STR(DRVM_EXIT);
264 MSG_TO_STR(DRVM_ENABLE);
265 MSG_TO_STR(DRVM_DISABLE);
266 MSG_TO_STR(WIDM_OPEN);
267 MSG_TO_STR(WIDM_CLOSE);
268 MSG_TO_STR(WIDM_ADDBUFFER);
269 MSG_TO_STR(WIDM_PREPARE);
270 MSG_TO_STR(WIDM_UNPREPARE);
271 MSG_TO_STR(WIDM_GETDEVCAPS);
272 MSG_TO_STR(WIDM_GETNUMDEVS);
273 MSG_TO_STR(WIDM_GETPOS);
274 MSG_TO_STR(WIDM_RESET);
275 MSG_TO_STR(WIDM_START);
276 MSG_TO_STR(WIDM_STOP);
277 MSG_TO_STR(WODM_OPEN);
278 MSG_TO_STR(WODM_CLOSE);
279 MSG_TO_STR(WODM_WRITE);
280 MSG_TO_STR(WODM_PAUSE);
281 MSG_TO_STR(WODM_GETPOS);
282 MSG_TO_STR(WODM_BREAKLOOP);
283 MSG_TO_STR(WODM_PREPARE);
284 MSG_TO_STR(WODM_UNPREPARE);
285 MSG_TO_STR(WODM_GETDEVCAPS);
286 MSG_TO_STR(WODM_GETNUMDEVS);
287 MSG_TO_STR(WODM_GETPITCH);
288 MSG_TO_STR(WODM_SETPITCH);
289 MSG_TO_STR(WODM_GETPLAYBACKRATE);
290 MSG_TO_STR(WODM_SETPLAYBACKRATE);
291 MSG_TO_STR(WODM_GETVOLUME);
292 MSG_TO_STR(WODM_SETVOLUME);
293 MSG_TO_STR(WODM_RESTART);
294 MSG_TO_STR(WODM_RESET);
295 MSG_TO_STR(DRV_QUERYDEVICEINTERFACESIZE);
296 MSG_TO_STR(DRV_QUERYDEVICEINTERFACE);
297 MSG_TO_STR(DRV_QUERYDSOUNDIFACE);
298 MSG_TO_STR(DRV_QUERYDSOUNDDESC);
301 sprintf(unknown, "UNKNOWN(0x%04x)", msg);
305 #define kStopLoopMessage 0
306 #define kWaveOutNotifyCompletionsMessage 1
307 #define kWaveInNotifyCompletionsMessage 2
309 /* Mach Message Handling */
310 static CFDataRef wodMessageHandler(CFMessagePortRef port_ReceiveInMessageThread, SInt32 msgid, CFDataRef data, void *info)
312 UInt32 *buffer = NULL;
316 case kWaveOutNotifyCompletionsMessage:
317 buffer = (UInt32 *) CFDataGetBytePtr(data);
318 wodHelper_NotifyCompletions(&WOutDev[buffer[0]], FALSE);
320 case kWaveInNotifyCompletionsMessage:
321 buffer = (UInt32 *) CFDataGetBytePtr(data);
322 widHelper_NotifyCompletions(&WInDev[buffer[0]]);
325 CFRunLoopStop(CFRunLoopGetCurrent());
332 static DWORD WINAPI messageThread(LPVOID p)
334 CFMessagePortRef port_ReceiveInMessageThread = (CFMessagePortRef) p;
335 CFRunLoopSourceRef source;
337 source = CFMessagePortCreateRunLoopSource(kCFAllocatorDefault, port_ReceiveInMessageThread, (CFIndex)0);
338 CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
342 CFRunLoopSourceInvalidate(source);
344 CFRelease(port_ReceiveInMessageThread);
349 /**************************************************************************
350 * wodSendNotifyCompletionsMessage [internal]
351 * Call from AudioUnit IO thread can't use Wine debug channels.
353 static void wodSendNotifyCompletionsMessage(WINE_WAVEOUT* wwo)
358 if (!Port_SendToMessageThread)
361 buffer = (UInt32) wwo->woID;
363 data = CFDataCreate(kCFAllocatorDefault, (UInt8 *)&buffer, sizeof(buffer));
367 CFMessagePortSendRequest(Port_SendToMessageThread, kWaveOutNotifyCompletionsMessage, data, 0.0, 0.0, NULL, NULL);
371 /**************************************************************************
372 * wodSendNotifyInputCompletionsMessage [internal]
373 * Call from AudioUnit IO thread can't use Wine debug channels.
375 static void wodSendNotifyInputCompletionsMessage(WINE_WAVEIN* wwi)
380 if (!Port_SendToMessageThread)
383 buffer = (UInt32) wwi->wiID;
385 data = CFDataCreate(kCFAllocatorDefault, (UInt8 *)&buffer, sizeof(buffer));
389 CFMessagePortSendRequest(Port_SendToMessageThread, kWaveInNotifyCompletionsMessage, data, 0.0, 0.0, NULL, NULL);
393 static DWORD bytes_to_mmtime(LPMMTIME lpTime, DWORD position,
394 PCMWAVEFORMAT* format)
396 TRACE("wType=%04X wBitsPerSample=%u nSamplesPerSec=%u nChannels=%u nAvgBytesPerSec=%u\n",
397 lpTime->wType, format->wBitsPerSample, format->wf.nSamplesPerSec,
398 format->wf.nChannels, format->wf.nAvgBytesPerSec);
399 TRACE("Position in bytes=%u\n", position);
401 switch (lpTime->wType) {
403 lpTime->u.sample = position / (format->wBitsPerSample / 8 * format->wf.nChannels);
404 TRACE("TIME_SAMPLES=%u\n", lpTime->u.sample);
407 lpTime->u.ms = 1000.0 * position / (format->wBitsPerSample / 8 * format->wf.nChannels * format->wf.nSamplesPerSec);
408 TRACE("TIME_MS=%u\n", lpTime->u.ms);
411 lpTime->u.smpte.fps = 30;
412 position = position / (format->wBitsPerSample / 8 * format->wf.nChannels);
413 position += (format->wf.nSamplesPerSec / lpTime->u.smpte.fps) - 1; /* round up */
414 lpTime->u.smpte.sec = position / format->wf.nSamplesPerSec;
415 position -= lpTime->u.smpte.sec * format->wf.nSamplesPerSec;
416 lpTime->u.smpte.min = lpTime->u.smpte.sec / 60;
417 lpTime->u.smpte.sec -= 60 * lpTime->u.smpte.min;
418 lpTime->u.smpte.hour = lpTime->u.smpte.min / 60;
419 lpTime->u.smpte.min -= 60 * lpTime->u.smpte.hour;
420 lpTime->u.smpte.fps = 30;
421 lpTime->u.smpte.frame = position * lpTime->u.smpte.fps / format->wf.nSamplesPerSec;
422 TRACE("TIME_SMPTE=%02u:%02u:%02u:%02u\n",
423 lpTime->u.smpte.hour, lpTime->u.smpte.min,
424 lpTime->u.smpte.sec, lpTime->u.smpte.frame);
427 WARN("Format %d not supported, using TIME_BYTES !\n", lpTime->wType);
428 lpTime->wType = TIME_BYTES;
431 lpTime->u.cb = position;
432 TRACE("TIME_BYTES=%u\n", lpTime->u.cb);
435 return MMSYSERR_NOERROR;
438 static BOOL supportedFormat(LPWAVEFORMATEX wf)
440 if (wf->nSamplesPerSec == 0)
443 if (wf->wFormatTag == WAVE_FORMAT_PCM) {
444 if (wf->nChannels >= 1 && wf->nChannels <= 2) {
445 if (wf->wBitsPerSample==8||wf->wBitsPerSample==16)
448 } else if (wf->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
449 WAVEFORMATEXTENSIBLE * wfex = (WAVEFORMATEXTENSIBLE *)wf;
451 if (wf->cbSize == 22 && IsEqualGUID(&wfex->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM)) {
452 if (wf->nChannels >=1 && wf->nChannels <= 2) {
453 if (wf->wBitsPerSample==wfex->Samples.wValidBitsPerSample) {
454 if (wf->wBitsPerSample==8||wf->wBitsPerSample==16)
457 WARN("wBitsPerSample != wValidBitsPerSample not supported yet\n");
460 WARN("only KSDATAFORMAT_SUBTYPE_PCM supported\n");
462 WARN("only WAVE_FORMAT_PCM supported\n");
467 void copyFormat(LPWAVEFORMATEX wf1, LPPCMWAVEFORMAT wf2)
469 memcpy(wf2, wf1, sizeof(PCMWAVEFORMAT));
470 /* Downgrade WAVE_FORMAT_EXTENSIBLE KSDATAFORMAT_SUBTYPE_PCM
471 * to smaller yet compatible WAVE_FORMAT_PCM structure */
472 if (wf2->wf.wFormatTag == WAVE_FORMAT_EXTENSIBLE)
473 wf2->wf.wFormatTag = WAVE_FORMAT_PCM;
476 /**************************************************************************
477 * CoreAudio_GetDevCaps [internal]
479 BOOL CoreAudio_GetDevCaps (void)
483 AudioDeviceID devId = CoreAudio_DefaultDevice.outputDeviceID;
485 char name[MAXPNAMELEN];
487 propertySize = MAXPNAMELEN;
488 status = AudioDeviceGetProperty(devId, 0 , FALSE, kAudioDevicePropertyDeviceName, &propertySize, name);
490 ERR("AudioHardwareGetProperty for kAudioDevicePropertyDeviceName return %c%c%c%c\n", (char) (status >> 24),
491 (char) (status >> 16),
492 (char) (status >> 8),
497 memcpy(CoreAudio_DefaultDevice.ds_desc.szDesc, name, sizeof(name));
498 strcpy(CoreAudio_DefaultDevice.ds_desc.szDrvname, "winecoreaudio.drv");
499 MultiByteToWideChar(CP_UNIXCP, 0, name, sizeof(name),
500 CoreAudio_DefaultDevice.out_caps.szPname,
501 sizeof(CoreAudio_DefaultDevice.out_caps.szPname) / sizeof(WCHAR));
502 memcpy(CoreAudio_DefaultDevice.dev_name, name, 32);
504 propertySize = sizeof(CoreAudio_DefaultDevice.streamDescription);
505 status = AudioDeviceGetProperty(devId, 0, FALSE , kAudioDevicePropertyStreamFormat, &propertySize, &CoreAudio_DefaultDevice.streamDescription);
506 if (status != noErr) {
507 ERR("AudioHardwareGetProperty for kAudioDevicePropertyStreamFormat return %c%c%c%c\n", (char) (status >> 24),
508 (char) (status >> 16),
509 (char) (status >> 8),
514 TRACE("Device Stream Description mSampleRate : %f\n mFormatID : %c%c%c%c\n"
515 "mFormatFlags : %lX\n mBytesPerPacket : %lu\n mFramesPerPacket : %lu\n"
516 "mBytesPerFrame : %lu\n mChannelsPerFrame : %lu\n mBitsPerChannel : %lu\n",
517 CoreAudio_DefaultDevice.streamDescription.mSampleRate,
518 (char) (CoreAudio_DefaultDevice.streamDescription.mFormatID >> 24),
519 (char) (CoreAudio_DefaultDevice.streamDescription.mFormatID >> 16),
520 (char) (CoreAudio_DefaultDevice.streamDescription.mFormatID >> 8),
521 (char) CoreAudio_DefaultDevice.streamDescription.mFormatID,
522 CoreAudio_DefaultDevice.streamDescription.mFormatFlags,
523 CoreAudio_DefaultDevice.streamDescription.mBytesPerPacket,
524 CoreAudio_DefaultDevice.streamDescription.mFramesPerPacket,
525 CoreAudio_DefaultDevice.streamDescription.mBytesPerFrame,
526 CoreAudio_DefaultDevice.streamDescription.mChannelsPerFrame,
527 CoreAudio_DefaultDevice.streamDescription.mBitsPerChannel);
529 CoreAudio_DefaultDevice.out_caps.wMid = 0xcafe;
530 CoreAudio_DefaultDevice.out_caps.wPid = 0x0001;
532 CoreAudio_DefaultDevice.out_caps.vDriverVersion = 0x0001;
533 CoreAudio_DefaultDevice.out_caps.dwFormats = 0x00000000;
534 CoreAudio_DefaultDevice.out_caps.wReserved1 = 0;
535 CoreAudio_DefaultDevice.out_caps.dwSupport = WAVECAPS_VOLUME;
536 CoreAudio_DefaultDevice.out_caps.dwSupport |= WAVECAPS_LRVOLUME;
538 CoreAudio_DefaultDevice.out_caps.wChannels = 2;
539 CoreAudio_DefaultDevice.out_caps.dwFormats|= WAVE_FORMAT_4S16;
544 /******************************************************************
547 * Initialize CoreAudio_DefaultDevice
549 LONG CoreAudio_WaveInit(void)
554 CFStringRef messageThreadPortName;
555 CFMessagePortRef port_ReceiveInMessageThread;
560 /* number of sound cards */
561 AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &propertySize, NULL);
562 propertySize /= sizeof(AudioDeviceID);
563 TRACE("sound cards : %lu\n", propertySize);
565 /* Get the output device */
566 propertySize = sizeof(CoreAudio_DefaultDevice.outputDeviceID);
567 status = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &propertySize, &CoreAudio_DefaultDevice.outputDeviceID);
569 ERR("AudioHardwareGetProperty return %c%c%c%c for kAudioHardwarePropertyDefaultOutputDevice\n", (char) (status >> 24),
570 (char) (status >> 16),
571 (char) (status >> 8),
575 if (CoreAudio_DefaultDevice.outputDeviceID == kAudioDeviceUnknown) {
576 ERR("AudioHardwareGetProperty: CoreAudio_DefaultDevice.outputDeviceID == kAudioDeviceUnknown\n");
580 if ( ! CoreAudio_GetDevCaps() )
583 CoreAudio_DefaultDevice.interface_name=HeapAlloc(GetProcessHeap(),0,strlen(CoreAudio_DefaultDevice.dev_name)+1);
584 strcpy(CoreAudio_DefaultDevice.interface_name, CoreAudio_DefaultDevice.dev_name);
586 for (i = 0; i < MAX_WAVEOUTDRV; ++i)
588 static const WCHAR wszWaveOutFormat[] =
589 {'C','o','r','e','A','u','d','i','o',' ','W','a','v','e','O','u','t',' ','%','d',0};
591 WOutDev[i].state = WINE_WS_CLOSED;
592 WOutDev[i].cadev = &CoreAudio_DefaultDevice;
595 memset(&WOutDev[i].caps, 0, sizeof(WOutDev[i].caps));
597 WOutDev[i].caps.wMid = 0xcafe; /* Manufac ID */
598 WOutDev[i].caps.wPid = 0x0001; /* Product ID */
599 snprintfW(WOutDev[i].caps.szPname, sizeof(WOutDev[i].caps.szPname)/sizeof(WCHAR), wszWaveOutFormat, i);
600 snprintf(WOutDev[i].interface_name, sizeof(WOutDev[i].interface_name), "winecoreaudio: %d", i);
602 WOutDev[i].caps.vDriverVersion = 0x0001;
603 WOutDev[i].caps.dwFormats = 0x00000000;
604 WOutDev[i].caps.dwSupport = WAVECAPS_VOLUME;
606 WOutDev[i].caps.wChannels = 2;
607 /* WOutDev[i].caps.dwSupport |= WAVECAPS_LRVOLUME; */ /* FIXME */
609 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96M08;
610 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96S08;
611 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96M16;
612 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96S16;
613 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48M08;
614 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48S08;
615 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48M16;
616 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48S16;
617 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4M08;
618 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4S08;
619 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4S16;
620 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4M16;
621 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2M08;
622 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2S08;
623 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2M16;
624 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2S16;
625 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1M08;
626 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1S08;
627 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1M16;
628 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1S16;
630 WOutDev[i].lock = 0; /* initialize the mutex */
633 /* FIXME: implement sample rate conversion on input */
634 inputSampleRate = AudioUnit_GetInputDeviceSampleRate();
636 for (i = 0; i < MAX_WAVEINDRV; ++i)
638 static const WCHAR wszWaveInFormat[] =
639 {'C','o','r','e','A','u','d','i','o',' ','W','a','v','e','I','n',' ','%','d',0};
641 memset(&WInDev[i], 0, sizeof(WInDev[i]));
644 /* Establish preconditions for widOpen */
645 WInDev[i].state = WINE_WS_CLOSED;
646 WInDev[i].lock = 0; /* initialize the mutex */
648 /* Fill in capabilities. widGetDevCaps can be called at any time. */
649 WInDev[i].caps.wMid = 0xcafe; /* Manufac ID */
650 WInDev[i].caps.wPid = 0x0001; /* Product ID */
651 WInDev[i].caps.vDriverVersion = 0x0001;
653 snprintfW(WInDev[i].caps.szPname, sizeof(WInDev[i].caps.szPname)/sizeof(WCHAR), wszWaveInFormat, i);
654 snprintf(WInDev[i].interface_name, sizeof(WInDev[i].interface_name), "winecoreaudio in: %d", i);
656 if (inputSampleRate == 96000)
658 WInDev[i].caps.dwFormats |= WAVE_FORMAT_96M08;
659 WInDev[i].caps.dwFormats |= WAVE_FORMAT_96S08;
660 WInDev[i].caps.dwFormats |= WAVE_FORMAT_96M16;
661 WInDev[i].caps.dwFormats |= WAVE_FORMAT_96S16;
663 if (inputSampleRate == 48000)
665 WInDev[i].caps.dwFormats |= WAVE_FORMAT_48M08;
666 WInDev[i].caps.dwFormats |= WAVE_FORMAT_48S08;
667 WInDev[i].caps.dwFormats |= WAVE_FORMAT_48M16;
668 WInDev[i].caps.dwFormats |= WAVE_FORMAT_48S16;
670 if (inputSampleRate == 44100)
672 WInDev[i].caps.dwFormats |= WAVE_FORMAT_4M08;
673 WInDev[i].caps.dwFormats |= WAVE_FORMAT_4S08;
674 WInDev[i].caps.dwFormats |= WAVE_FORMAT_4M16;
675 WInDev[i].caps.dwFormats |= WAVE_FORMAT_4S16;
677 if (inputSampleRate == 22050)
679 WInDev[i].caps.dwFormats |= WAVE_FORMAT_2M08;
680 WInDev[i].caps.dwFormats |= WAVE_FORMAT_2S08;
681 WInDev[i].caps.dwFormats |= WAVE_FORMAT_2M16;
682 WInDev[i].caps.dwFormats |= WAVE_FORMAT_2S16;
684 if (inputSampleRate == 11025)
686 WInDev[i].caps.dwFormats |= WAVE_FORMAT_1M08;
687 WInDev[i].caps.dwFormats |= WAVE_FORMAT_1S08;
688 WInDev[i].caps.dwFormats |= WAVE_FORMAT_1M16;
689 WInDev[i].caps.dwFormats |= WAVE_FORMAT_1S16;
692 WInDev[i].caps.wChannels = 2;
695 /* create mach messages handler */
697 messageThreadPortName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL,
698 CFSTR("WaveMessagePort.%d.%lu"), getpid(), (unsigned long)random());
699 if (!messageThreadPortName)
701 ERR("Can't create message thread port name\n");
705 port_ReceiveInMessageThread = CFMessagePortCreateLocal(kCFAllocatorDefault, messageThreadPortName,
706 &wodMessageHandler, NULL, NULL);
707 if (!port_ReceiveInMessageThread)
709 ERR("Can't create message thread local port\n");
710 CFRelease(messageThreadPortName);
714 Port_SendToMessageThread = CFMessagePortCreateRemote(kCFAllocatorDefault, messageThreadPortName);
715 CFRelease(messageThreadPortName);
716 if (!Port_SendToMessageThread)
718 ERR("Can't create port for sending to message thread\n");
719 CFRelease(port_ReceiveInMessageThread);
723 /* Cannot WAIT for any events because we are called from the loader (which has a lock on loading stuff) */
724 /* We might want to wait for this thread to be created -- but we cannot -- not here at least */
725 /* Instead track the thread so we can clean it up later */
728 ERR("Message thread already started -- expect problems\n");
730 hThread = CreateThread(NULL, 0, messageThread, (LPVOID)port_ReceiveInMessageThread, 0, NULL);
733 ERR("Can't create message thread\n");
734 CFRelease(port_ReceiveInMessageThread);
735 CFRelease(Port_SendToMessageThread);
736 Port_SendToMessageThread = NULL;
740 /* The message thread is responsible for releasing port_ReceiveInMessageThread. */
745 void CoreAudio_WaveRelease(void)
747 /* Stop CFRunLoop in messageThread */
750 if (!Port_SendToMessageThread)
753 CFMessagePortSendRequest(Port_SendToMessageThread, kStopLoopMessage, NULL, 0.0, 0.0, NULL, NULL);
754 CFRelease(Port_SendToMessageThread);
755 Port_SendToMessageThread = NULL;
757 /* Wait for the thread to finish and clean it up */
758 /* This rids us of any quick start/shutdown driver crashes */
759 WaitForSingleObject(hThread, INFINITE);
760 CloseHandle(hThread);
764 /*======================================================================*
765 * Low level WAVE OUT implementation *
766 *======================================================================*/
768 /**************************************************************************
769 * wodNotifyClient [internal]
771 static DWORD wodNotifyClient(WINE_WAVEOUT* wwo, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
777 if (wwo->wFlags != DCB_NULL &&
778 !DriverCallback(wwo->waveDesc.dwCallback, wwo->wFlags,
779 (HDRVR)wwo->waveDesc.hWave, wMsg, wwo->waveDesc.dwInstance,
782 return MMSYSERR_ERROR;
786 return MMSYSERR_INVALPARAM;
788 return MMSYSERR_NOERROR;
792 /**************************************************************************
793 * wodGetDevCaps [internal]
795 static DWORD wodGetDevCaps(WORD wDevID, LPWAVEOUTCAPSW lpCaps, DWORD dwSize)
797 TRACE("(%u, %p, %u);\n", wDevID, lpCaps, dwSize);
799 if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
801 if (wDevID >= MAX_WAVEOUTDRV)
803 TRACE("MAX_WAVOUTDRV reached !\n");
804 return MMSYSERR_BADDEVICEID;
807 TRACE("dwSupport=(0x%x), dwFormats=(0x%x)\n", WOutDev[wDevID].caps.dwSupport, WOutDev[wDevID].caps.dwFormats);
808 memcpy(lpCaps, &WOutDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
809 return MMSYSERR_NOERROR;
812 /**************************************************************************
815 static DWORD wodOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
819 AudioStreamBasicDescription streamFormat;
820 AudioUnit audioUnit = NULL;
821 BOOL auInited = FALSE;
823 TRACE("(%u, %p, %08x);\n", wDevID, lpDesc, dwFlags);
826 WARN("Invalid Parameter !\n");
827 return MMSYSERR_INVALPARAM;
829 if (wDevID >= MAX_WAVEOUTDRV) {
830 TRACE("MAX_WAVOUTDRV reached !\n");
831 return MMSYSERR_BADDEVICEID;
834 TRACE("Format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
835 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
836 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
838 if (!supportedFormat(lpDesc->lpFormat))
840 WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
841 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
842 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
843 return WAVERR_BADFORMAT;
846 if (dwFlags & WAVE_FORMAT_QUERY)
848 TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
849 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
850 lpDesc->lpFormat->nSamplesPerSec);
851 return MMSYSERR_NOERROR;
854 /* nBlockAlign and nAvgBytesPerSec are output variables for dsound */
855 if (lpDesc->lpFormat->nBlockAlign != lpDesc->lpFormat->nChannels*lpDesc->lpFormat->wBitsPerSample/8) {
856 lpDesc->lpFormat->nBlockAlign = lpDesc->lpFormat->nChannels*lpDesc->lpFormat->wBitsPerSample/8;
857 WARN("Fixing nBlockAlign\n");
859 if (lpDesc->lpFormat->nAvgBytesPerSec!= lpDesc->lpFormat->nSamplesPerSec*lpDesc->lpFormat->nBlockAlign) {
860 lpDesc->lpFormat->nAvgBytesPerSec = lpDesc->lpFormat->nSamplesPerSec*lpDesc->lpFormat->nBlockAlign;
861 WARN("Fixing nAvgBytesPerSec\n");
864 /* We proceed in three phases:
865 * o Reserve the device for us, marking it as unavailable (not closed)
866 * o Create, configure, and start the Audio Unit. To avoid deadlock,
867 * this has to be done without holding wwo->lock.
868 * o If that was successful, finish setting up our device info and
869 * mark the device as ready.
870 * Otherwise, clean up and mark the device as available.
872 wwo = &WOutDev[wDevID];
873 if (!OSSpinLockTry(&wwo->lock))
874 return MMSYSERR_ALLOCATED;
876 if (wwo->state != WINE_WS_CLOSED)
878 OSSpinLockUnlock(&wwo->lock);
879 return MMSYSERR_ALLOCATED;
882 wwo->state = WINE_WS_OPENING;
883 wwo->audioUnit = NULL;
884 OSSpinLockUnlock(&wwo->lock);
887 if (!AudioUnit_CreateDefaultAudioUnit((void *) wwo, &audioUnit))
889 ERR("CoreAudio_CreateDefaultAudioUnit(%p) failed\n", wwo);
890 ret = MMSYSERR_ERROR;
894 streamFormat.mFormatID = kAudioFormatLinearPCM;
895 streamFormat.mFormatFlags = kLinearPCMFormatFlagIsPacked;
896 /* FIXME check for 32bits float -> kLinearPCMFormatFlagIsFloat */
897 if (lpDesc->lpFormat->wBitsPerSample != 8)
898 streamFormat.mFormatFlags |= kLinearPCMFormatFlagIsSignedInteger;
899 # ifdef WORDS_BIGENDIAN
900 streamFormat.mFormatFlags |= kLinearPCMFormatFlagIsBigEndian; /* FIXME Wave format is little endian */
903 streamFormat.mSampleRate = lpDesc->lpFormat->nSamplesPerSec;
904 streamFormat.mChannelsPerFrame = lpDesc->lpFormat->nChannels;
905 streamFormat.mFramesPerPacket = 1;
906 streamFormat.mBitsPerChannel = lpDesc->lpFormat->wBitsPerSample;
907 streamFormat.mBytesPerFrame = streamFormat.mBitsPerChannel * streamFormat.mChannelsPerFrame / 8;
908 streamFormat.mBytesPerPacket = streamFormat.mBytesPerFrame * streamFormat.mFramesPerPacket;
910 ret = AudioUnit_InitializeWithStreamDescription(audioUnit, &streamFormat);
913 ret = WAVERR_BADFORMAT; /* FIXME return an error based on the OSStatus */
918 /* Our render callback CoreAudio_woAudioUnitIOProc may be called before
919 * AudioOutputUnitStart returns. Core Audio will grab its own internal
920 * lock before calling it and the callback grabs wwo->lock. This would
921 * deadlock if we were holding wwo->lock.
922 * Also, the callback has to safely do nothing in that case, because
923 * wwo hasn't been completely filled out, yet. */
924 ret = AudioOutputUnitStart(audioUnit);
927 ERR("AudioOutputUnitStart failed: %08x\n", ret);
928 ret = MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
933 OSSpinLockLock(&wwo->lock);
934 assert(wwo->state == WINE_WS_OPENING);
936 wwo->audioUnit = audioUnit;
937 wwo->streamDescription = streamFormat;
939 wwo->state = WINE_WS_PLAYING;
941 wwo->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
943 wwo->waveDesc = *lpDesc;
944 copyFormat(lpDesc->lpFormat, &wwo->format);
946 wwo->dwPlayedTotal = 0;
947 wwo->dwWrittenTotal = 0;
949 wwo->trace_on = TRACE_ON(wave);
950 wwo->warn_on = WARN_ON(wave);
951 wwo->err_on = ERR_ON(wave);
953 OSSpinLockUnlock(&wwo->lock);
955 ret = wodNotifyClient(wwo, WOM_OPEN, 0L, 0L);
963 AudioUnitUninitialize(audioUnit);
964 AudioUnit_CloseAudioUnit(audioUnit);
967 OSSpinLockLock(&wwo->lock);
968 assert(wwo->state == WINE_WS_OPENING);
969 wwo->state = WINE_WS_CLOSED;
970 OSSpinLockUnlock(&wwo->lock);
975 /**************************************************************************
976 * wodClose [internal]
978 static DWORD wodClose(WORD wDevID)
980 DWORD ret = MMSYSERR_NOERROR;
983 TRACE("(%u);\n", wDevID);
985 if (wDevID >= MAX_WAVEOUTDRV)
987 WARN("bad device ID !\n");
988 return MMSYSERR_BADDEVICEID;
991 wwo = &WOutDev[wDevID];
992 OSSpinLockLock(&wwo->lock);
995 WARN("buffers still playing !\n");
996 OSSpinLockUnlock(&wwo->lock);
997 ret = WAVERR_STILLPLAYING;
1001 AudioUnit audioUnit = wwo->audioUnit;
1003 /* sanity check: this should not happen since the device must have been reset before */
1004 if (wwo->lpQueuePtr || wwo->lpPlayPtr) ERR("out of sync\n");
1006 wwo->state = WINE_WS_CLOSING; /* mark the device as closing */
1007 wwo->audioUnit = NULL;
1009 OSSpinLockUnlock(&wwo->lock);
1011 err = AudioUnitUninitialize(audioUnit);
1013 ERR("AudioUnitUninitialize return %c%c%c%c\n", (char) (err >> 24),
1017 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1020 if ( !AudioUnit_CloseAudioUnit(audioUnit) )
1022 ERR("Can't close AudioUnit\n");
1023 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1026 OSSpinLockLock(&wwo->lock);
1027 assert(wwo->state == WINE_WS_CLOSING);
1028 wwo->state = WINE_WS_CLOSED; /* mark the device as closed */
1029 OSSpinLockUnlock(&wwo->lock);
1031 ret = wodNotifyClient(wwo, WOM_CLOSE, 0L, 0L);
1037 /**************************************************************************
1038 * wodPrepare [internal]
1040 static DWORD wodPrepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1042 TRACE("(%u, %p, %08x);\n", wDevID, lpWaveHdr, dwSize);
1044 if (wDevID >= MAX_WAVEOUTDRV) {
1045 WARN("bad device ID !\n");
1046 return MMSYSERR_BADDEVICEID;
1049 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1050 return WAVERR_STILLPLAYING;
1052 lpWaveHdr->dwFlags |= WHDR_PREPARED;
1053 lpWaveHdr->dwFlags &= ~WHDR_DONE;
1055 return MMSYSERR_NOERROR;
1058 /**************************************************************************
1059 * wodUnprepare [internal]
1061 static DWORD wodUnprepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1063 TRACE("(%u, %p, %08x);\n", wDevID, lpWaveHdr, dwSize);
1065 if (wDevID >= MAX_WAVEOUTDRV) {
1066 WARN("bad device ID !\n");
1067 return MMSYSERR_BADDEVICEID;
1070 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1071 return WAVERR_STILLPLAYING;
1073 lpWaveHdr->dwFlags &= ~WHDR_PREPARED;
1074 lpWaveHdr->dwFlags |= WHDR_DONE;
1076 return MMSYSERR_NOERROR;
1080 /**************************************************************************
1081 * wodHelper_CheckForLoopBegin [internal]
1083 * Check if the new waveheader is the beginning of a loop, and set up
1085 * This is called with the WAVEOUT lock held.
1086 * Call from AudioUnit IO thread can't use Wine debug channels.
1088 static void wodHelper_CheckForLoopBegin(WINE_WAVEOUT* wwo)
1090 LPWAVEHDR lpWaveHdr = wwo->lpPlayPtr;
1092 if (lpWaveHdr->dwFlags & WHDR_BEGINLOOP)
1097 fprintf(stderr, "warn:winecoreaudio:wodHelper_CheckForLoopBegin Already in a loop. Discarding loop on this header (%p)\n", lpWaveHdr);
1102 fprintf(stderr, "trace:winecoreaudio:wodHelper_CheckForLoopBegin Starting loop (%dx) with %p\n", lpWaveHdr->dwLoops, lpWaveHdr);
1104 wwo->lpLoopPtr = lpWaveHdr;
1105 /* Windows does not touch WAVEHDR.dwLoops,
1106 * so we need to make an internal copy */
1107 wwo->dwLoops = lpWaveHdr->dwLoops;
1113 /**************************************************************************
1114 * wodHelper_PlayPtrNext [internal]
1116 * Advance the play pointer to the next waveheader, looping if required.
1117 * This is called with the WAVEOUT lock held.
1118 * Call from AudioUnit IO thread can't use Wine debug channels.
1120 static void wodHelper_PlayPtrNext(WINE_WAVEOUT* wwo)
1122 BOOL didLoopBack = FALSE;
1124 wwo->dwPartialOffset = 0;
1125 if ((wwo->lpPlayPtr->dwFlags & WHDR_ENDLOOP) && wwo->lpLoopPtr)
1127 /* We're at the end of a loop, loop if required */
1128 if (wwo->dwLoops > 1)
1131 wwo->lpPlayPtr = wwo->lpLoopPtr;
1136 wwo->lpLoopPtr = NULL;
1141 /* We didn't loop back. Advance to the next wave header */
1142 wwo->lpPlayPtr = wwo->lpPlayPtr->lpNext;
1145 wodHelper_CheckForLoopBegin(wwo);
1149 /* Send the "done" notification for each WAVEHDR in a list. The list must be
1150 * free-standing. It should not be part of a device's queue.
1151 * This function must be called with the WAVEOUT lock *not* held. Furthermore,
1152 * it does not lock it, itself. That's because the callback to the application
1153 * may prompt the application to operate on the device, and we don't want to
1156 static void wodHelper_NotifyDoneForList(WINE_WAVEOUT* wwo, LPWAVEHDR lpWaveHdr)
1160 LPWAVEHDR lpNext = lpWaveHdr->lpNext;
1162 lpWaveHdr->lpNext = NULL;
1163 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1164 lpWaveHdr->dwFlags |= WHDR_DONE;
1165 wodNotifyClient(wwo, WOM_DONE, (DWORD)lpWaveHdr, 0);
1171 /* if force is TRUE then notify the client that all the headers were completed
1173 static void wodHelper_NotifyCompletions(WINE_WAVEOUT* wwo, BOOL force)
1175 LPWAVEHDR lpFirstDoneWaveHdr = NULL;
1177 OSSpinLockLock(&wwo->lock);
1179 /* First, excise all of the done headers from the queue into
1180 * a free-standing list. */
1183 lpFirstDoneWaveHdr = wwo->lpQueuePtr;
1184 wwo->lpQueuePtr = NULL;
1188 LPWAVEHDR lpWaveHdr;
1189 LPWAVEHDR lpLastDoneWaveHdr = NULL;
1191 /* Start from lpQueuePtr and keep notifying until:
1192 * - we hit an unwritten wavehdr
1193 * - we hit the beginning of a running loop
1194 * - we hit a wavehdr which hasn't finished playing
1197 lpWaveHdr = wwo->lpQueuePtr;
1199 lpWaveHdr != wwo->lpPlayPtr &&
1200 lpWaveHdr != wwo->lpLoopPtr;
1201 lpWaveHdr = lpWaveHdr->lpNext
1204 if (!lpFirstDoneWaveHdr)
1205 lpFirstDoneWaveHdr = lpWaveHdr;
1206 lpLastDoneWaveHdr = lpWaveHdr;
1209 if (lpLastDoneWaveHdr)
1211 wwo->lpQueuePtr = lpLastDoneWaveHdr->lpNext;
1212 lpLastDoneWaveHdr->lpNext = NULL;
1216 OSSpinLockUnlock(&wwo->lock);
1218 /* Now, send the "done" notification for each header in our list. */
1219 wodHelper_NotifyDoneForList(wwo, lpFirstDoneWaveHdr);
1223 /**************************************************************************
1224 * wodWrite [internal]
1227 static DWORD wodWrite(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1232 TRACE("(%u, %p, %08X);\n", wDevID, lpWaveHdr, dwSize);
1234 /* first, do the sanity checks... */
1235 if (wDevID >= MAX_WAVEOUTDRV)
1237 WARN("bad dev ID !\n");
1238 return MMSYSERR_BADDEVICEID;
1241 wwo = &WOutDev[wDevID];
1243 if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
1245 TRACE("unprepared\n");
1246 return WAVERR_UNPREPARED;
1249 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1251 TRACE("still playing\n");
1252 return WAVERR_STILLPLAYING;
1255 lpWaveHdr->dwFlags &= ~WHDR_DONE;
1256 lpWaveHdr->dwFlags |= WHDR_INQUEUE;
1257 lpWaveHdr->lpNext = 0;
1259 OSSpinLockLock(&wwo->lock);
1260 /* insert buffer at the end of queue */
1261 for (wh = &(wwo->lpQueuePtr); *wh; wh = &((*wh)->lpNext))
1265 if (!wwo->lpPlayPtr)
1267 wwo->lpPlayPtr = lpWaveHdr;
1269 wodHelper_CheckForLoopBegin(wwo);
1271 wwo->dwPartialOffset = 0;
1273 OSSpinLockUnlock(&wwo->lock);
1275 return MMSYSERR_NOERROR;
1278 /**************************************************************************
1279 * wodPause [internal]
1281 static DWORD wodPause(WORD wDevID)
1285 TRACE("(%u);!\n", wDevID);
1287 if (wDevID >= MAX_WAVEOUTDRV)
1289 WARN("bad device ID !\n");
1290 return MMSYSERR_BADDEVICEID;
1293 /* The order of the following operations is important since we can't hold
1294 * the mutex while we make an Audio Unit call. Stop the Audio Unit before
1295 * setting the PAUSED state. In wodRestart, the order is reversed. This
1296 * guarantees that we can't get into a situation where the state is
1297 * PLAYING but the Audio Unit isn't running. Although we can be in PAUSED
1298 * state with the Audio Unit still running, that's harmless because the
1299 * render callback will just produce silence.
1301 status = AudioOutputUnitStop(WOutDev[wDevID].audioUnit);
1303 WARN("AudioOutputUnitStop return %c%c%c%c\n",
1304 (char) (status >> 24), (char) (status >> 16), (char) (status >> 8), (char) status);
1307 OSSpinLockLock(&WOutDev[wDevID].lock);
1308 if (WOutDev[wDevID].state == WINE_WS_PLAYING)
1309 WOutDev[wDevID].state = WINE_WS_PAUSED;
1310 OSSpinLockUnlock(&WOutDev[wDevID].lock);
1312 return MMSYSERR_NOERROR;
1315 /**************************************************************************
1316 * wodRestart [internal]
1318 static DWORD wodRestart(WORD wDevID)
1322 TRACE("(%u);\n", wDevID);
1324 if (wDevID >= MAX_WAVEOUTDRV )
1326 WARN("bad device ID !\n");
1327 return MMSYSERR_BADDEVICEID;
1330 /* The order of the following operations is important since we can't hold
1331 * the mutex while we make an Audio Unit call. Set the PLAYING
1332 * state before starting the Audio Unit. In wodPause, the order is
1333 * reversed. This guarantees that we can't get into a situation where
1334 * the state is PLAYING but the Audio Unit isn't running.
1335 * Although we can be in PAUSED state with the Audio Unit still running,
1336 * that's harmless because the render callback will just produce silence.
1338 OSSpinLockLock(&WOutDev[wDevID].lock);
1339 if (WOutDev[wDevID].state == WINE_WS_PAUSED)
1340 WOutDev[wDevID].state = WINE_WS_PLAYING;
1341 OSSpinLockUnlock(&WOutDev[wDevID].lock);
1343 status = AudioOutputUnitStart(WOutDev[wDevID].audioUnit);
1345 ERR("AudioOutputUnitStart return %c%c%c%c\n",
1346 (char) (status >> 24), (char) (status >> 16), (char) (status >> 8), (char) status);
1347 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1350 return MMSYSERR_NOERROR;
1353 /**************************************************************************
1354 * wodReset [internal]
1356 static DWORD wodReset(WORD wDevID)
1360 LPWAVEHDR lpSavedQueuePtr;
1362 TRACE("(%u);\n", wDevID);
1364 if (wDevID >= MAX_WAVEOUTDRV)
1366 WARN("bad device ID !\n");
1367 return MMSYSERR_BADDEVICEID;
1370 wwo = &WOutDev[wDevID];
1372 OSSpinLockLock(&wwo->lock);
1374 if (wwo->state == WINE_WS_CLOSED || wwo->state == WINE_WS_CLOSING ||
1375 wwo->state == WINE_WS_OPENING)
1377 OSSpinLockUnlock(&wwo->lock);
1378 WARN("resetting a closed device\n");
1379 return MMSYSERR_INVALHANDLE;
1382 lpSavedQueuePtr = wwo->lpQueuePtr;
1383 wwo->lpPlayPtr = wwo->lpQueuePtr = wwo->lpLoopPtr = NULL;
1384 wwo->state = WINE_WS_PLAYING;
1385 wwo->dwPlayedTotal = wwo->dwWrittenTotal = 0;
1387 wwo->dwPartialOffset = 0; /* Clear partial wavehdr */
1389 OSSpinLockUnlock(&wwo->lock);
1391 status = AudioOutputUnitStart(wwo->audioUnit);
1394 ERR( "AudioOutputUnitStart return %c%c%c%c\n",
1395 (char) (status >> 24), (char) (status >> 16), (char) (status >> 8), (char) status);
1396 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1399 /* Now, send the "done" notification for each header in our list. */
1400 /* Do this last so the reset operation is effectively complete before the
1401 * app does whatever it's going to do in response to these notifications. */
1402 wodHelper_NotifyDoneForList(wwo, lpSavedQueuePtr);
1404 return MMSYSERR_NOERROR;
1407 /**************************************************************************
1408 * wodBreakLoop [internal]
1410 static DWORD wodBreakLoop(WORD wDevID)
1414 TRACE("(%u);\n", wDevID);
1416 if (wDevID >= MAX_WAVEOUTDRV)
1418 WARN("bad device ID !\n");
1419 return MMSYSERR_BADDEVICEID;
1422 wwo = &WOutDev[wDevID];
1424 OSSpinLockLock(&wwo->lock);
1426 if (wwo->lpLoopPtr != NULL)
1428 /* ensure exit at end of current loop */
1432 OSSpinLockUnlock(&wwo->lock);
1434 return MMSYSERR_NOERROR;
1437 /**************************************************************************
1438 * wodGetPosition [internal]
1440 static DWORD wodGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
1445 TRACE("(%u, %p, %u);\n", wDevID, lpTime, uSize);
1447 if (wDevID >= MAX_WAVEOUTDRV)
1449 WARN("bad device ID !\n");
1450 return MMSYSERR_BADDEVICEID;
1453 /* if null pointer to time structure return error */
1454 if (lpTime == NULL) return MMSYSERR_INVALPARAM;
1456 wwo = &WOutDev[wDevID];
1458 OSSpinLockLock(&WOutDev[wDevID].lock);
1459 val = wwo->dwPlayedTotal;
1460 OSSpinLockUnlock(&WOutDev[wDevID].lock);
1462 return bytes_to_mmtime(lpTime, val, &wwo->format);
1465 /**************************************************************************
1466 * wodGetVolume [internal]
1468 static DWORD wodGetVolume(WORD wDevID, LPDWORD lpdwVol)
1473 if (wDevID >= MAX_WAVEOUTDRV)
1475 WARN("bad device ID !\n");
1476 return MMSYSERR_BADDEVICEID;
1479 TRACE("(%u, %p);\n", wDevID, lpdwVol);
1481 AudioUnit_GetVolume(WOutDev[wDevID].audioUnit, &left, &right);
1483 *lpdwVol = ((WORD) left * 0xFFFFl) + (((WORD) right * 0xFFFFl) << 16);
1485 return MMSYSERR_NOERROR;
1488 /**************************************************************************
1489 * wodSetVolume [internal]
1491 static DWORD wodSetVolume(WORD wDevID, DWORD dwParam)
1496 if (wDevID >= MAX_WAVEOUTDRV)
1498 WARN("bad device ID !\n");
1499 return MMSYSERR_BADDEVICEID;
1502 left = LOWORD(dwParam) / 65535.0f;
1503 right = HIWORD(dwParam) / 65535.0f;
1505 TRACE("(%u, %08x);\n", wDevID, dwParam);
1507 AudioUnit_SetVolume(WOutDev[wDevID].audioUnit, left, right);
1509 return MMSYSERR_NOERROR;
1512 /**************************************************************************
1513 * wodGetNumDevs [internal]
1515 static DWORD wodGetNumDevs(void)
1518 return MAX_WAVEOUTDRV;
1521 /**************************************************************************
1522 * wodDevInterfaceSize [internal]
1524 static DWORD wodDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
1526 TRACE("(%u, %p)\n", wDevID, dwParam1);
1528 *dwParam1 = MultiByteToWideChar(CP_UNIXCP, 0, WOutDev[wDevID].cadev->interface_name, -1,
1529 NULL, 0 ) * sizeof(WCHAR);
1530 return MMSYSERR_NOERROR;
1533 /**************************************************************************
1534 * wodDevInterface [internal]
1536 static DWORD wodDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
1539 if (dwParam2 >= MultiByteToWideChar(CP_UNIXCP, 0, WOutDev[wDevID].cadev->interface_name, -1,
1540 NULL, 0 ) * sizeof(WCHAR))
1542 MultiByteToWideChar(CP_UNIXCP, 0, WOutDev[wDevID].cadev->interface_name, -1,
1543 dwParam1, dwParam2 / sizeof(WCHAR));
1544 return MMSYSERR_NOERROR;
1546 return MMSYSERR_INVALPARAM;
1549 /**************************************************************************
1550 * widDsCreate [internal]
1552 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
1554 TRACE("(%d,%p)\n",wDevID,drv);
1556 FIXME("DirectSound not implemented\n");
1557 FIXME("The (slower) DirectSound HEL mode will be used instead.\n");
1558 return MMSYSERR_NOTSUPPORTED;
1561 /**************************************************************************
1562 * wodDsDesc [internal]
1564 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc)
1566 /* The DirectSound HEL will automatically wrap a non-DirectSound-capable
1567 * driver in a DirectSound adaptor, thus allowing the driver to be used by
1568 * DirectSound clients. However, it only does this if we respond
1569 * successfully to the DRV_QUERYDSOUNDDESC message. It's enough to fill in
1570 * the driver and device names of the description output parameter. */
1571 *desc = WOutDev[wDevID].cadev->ds_desc;
1572 return MMSYSERR_NOERROR;
1575 /**************************************************************************
1576 * wodMessage (WINECOREAUDIO.7)
1578 DWORD WINAPI CoreAudio_wodMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
1579 DWORD dwParam1, DWORD dwParam2)
1581 TRACE("(%u, %s, %08x, %08x, %08x);\n",
1582 wDevID, getMessage(wMsg), dwUser, dwParam1, dwParam2);
1590 /* FIXME: Pretend this is supported */
1592 case WODM_OPEN: return wodOpen(wDevID, (LPWAVEOPENDESC) dwParam1, dwParam2);
1593 case WODM_CLOSE: return wodClose(wDevID);
1594 case WODM_WRITE: return wodWrite(wDevID, (LPWAVEHDR) dwParam1, dwParam2);
1595 case WODM_PAUSE: return wodPause(wDevID);
1596 case WODM_GETPOS: return wodGetPosition(wDevID, (LPMMTIME) dwParam1, dwParam2);
1597 case WODM_BREAKLOOP: return wodBreakLoop(wDevID);
1598 case WODM_PREPARE: return wodPrepare(wDevID, (LPWAVEHDR)dwParam1, dwParam2);
1599 case WODM_UNPREPARE: return wodUnprepare(wDevID, (LPWAVEHDR)dwParam1, dwParam2);
1601 case WODM_GETDEVCAPS: return wodGetDevCaps(wDevID, (LPWAVEOUTCAPSW) dwParam1, dwParam2);
1602 case WODM_GETNUMDEVS: return wodGetNumDevs();
1606 case WODM_GETPLAYBACKRATE:
1607 case WODM_SETPLAYBACKRATE: return MMSYSERR_NOTSUPPORTED;
1608 case WODM_GETVOLUME: return wodGetVolume(wDevID, (LPDWORD)dwParam1);
1609 case WODM_SETVOLUME: return wodSetVolume(wDevID, dwParam1);
1610 case WODM_RESTART: return wodRestart(wDevID);
1611 case WODM_RESET: return wodReset(wDevID);
1613 case DRV_QUERYDEVICEINTERFACESIZE: return wodDevInterfaceSize (wDevID, (LPDWORD)dwParam1);
1614 case DRV_QUERYDEVICEINTERFACE: return wodDevInterface (wDevID, (PWCHAR)dwParam1, dwParam2);
1615 case DRV_QUERYDSOUNDIFACE: return wodDsCreate (wDevID, (PIDSDRIVER*)dwParam1);
1616 case DRV_QUERYDSOUNDDESC: return wodDsDesc (wDevID, (PDSDRIVERDESC)dwParam1);
1619 FIXME("unknown message %d!\n", wMsg);
1622 return MMSYSERR_NOTSUPPORTED;
1625 /*======================================================================*
1626 * Low level DSOUND implementation *
1627 *======================================================================*/
1629 typedef struct IDsDriverImpl IDsDriverImpl;
1630 typedef struct IDsDriverBufferImpl IDsDriverBufferImpl;
1632 struct IDsDriverImpl
1634 /* IUnknown fields */
1635 const IDsDriverVtbl *lpVtbl;
1637 /* IDsDriverImpl fields */
1639 IDsDriverBufferImpl*primary;
1642 struct IDsDriverBufferImpl
1644 /* IUnknown fields */
1645 const IDsDriverBufferVtbl *lpVtbl;
1647 /* IDsDriverBufferImpl fields */
1654 CoreAudio IO threaded callback,
1655 we can't call Wine debug channels, critical section or anything using NtCurrentTeb here.
1657 OSStatus CoreAudio_woAudioUnitIOProc(void *inRefCon,
1658 AudioUnitRenderActionFlags *ioActionFlags,
1659 const AudioTimeStamp *inTimeStamp,
1661 UInt32 inNumberFrames,
1662 AudioBufferList *ioData)
1665 WINE_WAVEOUT *wwo = (WINE_WAVEOUT *) inRefCon;
1668 unsigned int dataNeeded = ioData->mBuffers[0].mDataByteSize;
1669 unsigned int dataProvided = 0;
1671 OSSpinLockLock(&wwo->lock);
1673 /* We might have been called before wwo has been completely filled out by
1674 * wodOpen, or while it's being closed in wodClose. We have to do nothing
1675 * in that case. The check of wwo->state below ensures that. */
1676 while (dataNeeded > 0 && wwo->state == WINE_WS_PLAYING && wwo->lpPlayPtr)
1678 unsigned int available = wwo->lpPlayPtr->dwBufferLength - wwo->dwPartialOffset;
1679 unsigned int toCopy;
1681 if (available >= dataNeeded)
1682 toCopy = dataNeeded;
1688 memcpy((char*)ioData->mBuffers[0].mData + dataProvided,
1689 wwo->lpPlayPtr->lpData + wwo->dwPartialOffset, toCopy);
1690 wwo->dwPartialOffset += toCopy;
1691 wwo->dwPlayedTotal += toCopy;
1692 dataProvided += toCopy;
1693 dataNeeded -= toCopy;
1694 available -= toCopy;
1699 wodHelper_PlayPtrNext(wwo);
1703 ioData->mBuffers[0].mDataByteSize = dataProvided;
1705 OSSpinLockUnlock(&wwo->lock);
1707 /* We can't provide any more wave data. Fill the rest with silence. */
1711 *ioActionFlags |= kAudioUnitRenderAction_OutputIsSilence;
1712 memset((char*)ioData->mBuffers[0].mData + dataProvided, 0, dataNeeded);
1713 dataProvided += dataNeeded;
1717 /* We only fill buffer 0. Set any others that might be requested to 0. */
1718 for (buffer = 1; buffer < ioData->mNumberBuffers; buffer++)
1720 memset(ioData->mBuffers[buffer].mData, 0, ioData->mBuffers[buffer].mDataByteSize);
1723 if (needNotify) wodSendNotifyCompletionsMessage(wwo);
1728 /*======================================================================*
1729 * Low level WAVE IN implementation *
1730 *======================================================================*/
1732 /**************************************************************************
1733 * widNotifyClient [internal]
1735 static DWORD widNotifyClient(WINE_WAVEIN* wwi, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
1737 TRACE("wMsg = 0x%04x dwParm1 = %04X dwParam2 = %04X\n", wMsg, dwParam1, dwParam2);
1744 if (wwi->wFlags != DCB_NULL &&
1745 !DriverCallback(wwi->waveDesc.dwCallback, wwi->wFlags,
1746 (HDRVR)wwi->waveDesc.hWave, wMsg, wwi->waveDesc.dwInstance,
1747 dwParam1, dwParam2))
1749 WARN("can't notify client !\n");
1750 return MMSYSERR_ERROR;
1754 FIXME("Unknown callback message %u\n", wMsg);
1755 return MMSYSERR_INVALPARAM;
1757 return MMSYSERR_NOERROR;
1761 /**************************************************************************
1762 * widHelper_NotifyCompletions [internal]
1764 static void widHelper_NotifyCompletions(WINE_WAVEIN* wwi)
1766 LPWAVEHDR lpWaveHdr;
1767 LPWAVEHDR lpFirstDoneWaveHdr = NULL;
1768 LPWAVEHDR lpLastDoneWaveHdr = NULL;
1770 OSSpinLockLock(&wwi->lock);
1772 /* First, excise all of the done headers from the queue into
1773 * a free-standing list. */
1775 /* Start from lpQueuePtr and keep notifying until:
1776 * - we hit an unfilled wavehdr
1777 * - we hit the end of the list
1780 lpWaveHdr = wwi->lpQueuePtr;
1782 lpWaveHdr->dwBytesRecorded >= lpWaveHdr->dwBufferLength;
1783 lpWaveHdr = lpWaveHdr->lpNext
1786 if (!lpFirstDoneWaveHdr)
1787 lpFirstDoneWaveHdr = lpWaveHdr;
1788 lpLastDoneWaveHdr = lpWaveHdr;
1791 if (lpLastDoneWaveHdr)
1793 wwi->lpQueuePtr = lpLastDoneWaveHdr->lpNext;
1794 lpLastDoneWaveHdr->lpNext = NULL;
1797 OSSpinLockUnlock(&wwi->lock);
1799 /* Now, send the "done" notification for each header in our list. */
1800 lpWaveHdr = lpFirstDoneWaveHdr;
1803 LPWAVEHDR lpNext = lpWaveHdr->lpNext;
1805 lpWaveHdr->lpNext = NULL;
1806 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1807 lpWaveHdr->dwFlags |= WHDR_DONE;
1808 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
1815 /**************************************************************************
1816 * widGetDevCaps [internal]
1818 static DWORD widGetDevCaps(WORD wDevID, LPWAVEINCAPSW lpCaps, DWORD dwSize)
1820 TRACE("(%u, %p, %u);\n", wDevID, lpCaps, dwSize);
1822 if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
1824 if (wDevID >= MAX_WAVEINDRV)
1826 TRACE("MAX_WAVEINDRV reached !\n");
1827 return MMSYSERR_BADDEVICEID;
1830 memcpy(lpCaps, &WInDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
1831 return MMSYSERR_NOERROR;
1835 /**************************************************************************
1836 * widHelper_DestroyAudioBufferList [internal]
1837 * Convenience function to dispose of our audio buffers
1839 static void widHelper_DestroyAudioBufferList(AudioBufferList* list)
1844 for (i = 0; i < list->mNumberBuffers; i++)
1846 if (list->mBuffers[i].mData)
1847 HeapFree(GetProcessHeap(), 0, list->mBuffers[i].mData);
1849 HeapFree(GetProcessHeap(), 0, list);
1854 #define AUDIOBUFFERLISTSIZE(numBuffers) (offsetof(AudioBufferList, mBuffers) + (numBuffers) * sizeof(AudioBuffer))
1856 /**************************************************************************
1857 * widHelper_AllocateAudioBufferList [internal]
1858 * Convenience function to allocate our audio buffers
1860 static AudioBufferList* widHelper_AllocateAudioBufferList(UInt32 numChannels, UInt32 bitsPerChannel, UInt32 bufferFrames, BOOL interleaved)
1863 UInt32 channelsPerFrame;
1864 UInt32 bytesPerFrame;
1865 UInt32 bytesPerBuffer;
1866 AudioBufferList* list;
1871 /* For interleaved audio, we allocate one buffer for all channels. */
1873 channelsPerFrame = numChannels;
1877 numBuffers = numChannels;
1878 channelsPerFrame = 1;
1881 bytesPerFrame = bitsPerChannel * channelsPerFrame / 8;
1882 bytesPerBuffer = bytesPerFrame * bufferFrames;
1884 list = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, AUDIOBUFFERLISTSIZE(numBuffers));
1888 list->mNumberBuffers = numBuffers;
1889 for (i = 0; i < numBuffers; ++i)
1891 list->mBuffers[i].mNumberChannels = channelsPerFrame;
1892 list->mBuffers[i].mDataByteSize = bytesPerBuffer;
1893 list->mBuffers[i].mData = HeapAlloc(GetProcessHeap(), 0, bytesPerBuffer);
1894 if (list->mBuffers[i].mData == NULL)
1896 widHelper_DestroyAudioBufferList(list);
1904 /**************************************************************************
1905 * widOpen [internal]
1907 static DWORD widOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
1912 TRACE("(%u, %p, %08X);\n", wDevID, lpDesc, dwFlags);
1915 WARN("Invalid Parameter !\n");
1916 return MMSYSERR_INVALPARAM;
1918 if (wDevID >= MAX_WAVEINDRV)
1920 TRACE ("MAX_WAVEINDRV reached !\n");
1921 return MMSYSERR_BADDEVICEID;
1924 TRACE("Format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
1925 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1926 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
1928 if (!supportedFormat(lpDesc->lpFormat) ||
1929 lpDesc->lpFormat->nSamplesPerSec != AudioUnit_GetInputDeviceSampleRate()
1932 WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
1933 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1934 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
1935 return WAVERR_BADFORMAT;
1938 if (dwFlags & WAVE_FORMAT_QUERY)
1940 TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
1941 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1942 lpDesc->lpFormat->nSamplesPerSec);
1943 return MMSYSERR_NOERROR;
1946 /* nBlockAlign and nAvgBytesPerSec are output variables for dsound */
1947 if (lpDesc->lpFormat->nBlockAlign != lpDesc->lpFormat->nChannels*lpDesc->lpFormat->wBitsPerSample/8) {
1948 lpDesc->lpFormat->nBlockAlign = lpDesc->lpFormat->nChannels*lpDesc->lpFormat->wBitsPerSample/8;
1949 WARN("Fixing nBlockAlign\n");
1951 if (lpDesc->lpFormat->nAvgBytesPerSec!= lpDesc->lpFormat->nSamplesPerSec*lpDesc->lpFormat->nBlockAlign) {
1952 lpDesc->lpFormat->nAvgBytesPerSec = lpDesc->lpFormat->nSamplesPerSec*lpDesc->lpFormat->nBlockAlign;
1953 WARN("Fixing nAvgBytesPerSec\n");
1956 wwi = &WInDev[wDevID];
1957 if (!OSSpinLockTry(&wwi->lock))
1958 return MMSYSERR_ALLOCATED;
1960 if (wwi->state != WINE_WS_CLOSED)
1962 OSSpinLockUnlock(&wwi->lock);
1963 return MMSYSERR_ALLOCATED;
1966 wwi->state = WINE_WS_STOPPED;
1967 wwi->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
1969 wwi->waveDesc = *lpDesc;
1970 copyFormat(lpDesc->lpFormat, &wwi->format);
1972 wwi->dwTotalRecorded = 0;
1974 wwi->trace_on = TRACE_ON(wave);
1975 wwi->warn_on = WARN_ON(wave);
1976 wwi->err_on = ERR_ON(wave);
1978 if (!AudioUnit_CreateInputUnit(wwi, &wwi->audioUnit,
1979 wwi->format.wf.nChannels, wwi->format.wf.nSamplesPerSec,
1980 wwi->format.wBitsPerSample, &frameCount))
1982 ERR("AudioUnit_CreateInputUnit failed\n");
1983 OSSpinLockUnlock(&wwi->lock);
1984 return MMSYSERR_ERROR;
1987 /* Allocate our audio buffers */
1988 wwi->bufferList = widHelper_AllocateAudioBufferList(wwi->format.wf.nChannels,
1989 wwi->format.wBitsPerSample, frameCount, TRUE);
1990 if (wwi->bufferList == NULL)
1992 ERR("Failed to allocate buffer list\n");
1993 AudioUnitUninitialize(wwi->audioUnit);
1994 AudioUnit_CloseAudioUnit(wwi->audioUnit);
1995 OSSpinLockUnlock(&wwi->lock);
1996 return MMSYSERR_NOMEM;
1999 /* Keep a copy of the buffer list structure (but not the buffers themselves)
2000 * in case AudioUnitRender clobbers the original, as it won't to do. */
2001 wwi->bufferListCopy = HeapAlloc(GetProcessHeap(), 0, AUDIOBUFFERLISTSIZE(wwi->bufferList->mNumberBuffers));
2002 if (wwi->bufferListCopy == NULL)
2004 ERR("Failed to allocate buffer list copy\n");
2005 widHelper_DestroyAudioBufferList(wwi->bufferList);
2006 AudioUnitUninitialize(wwi->audioUnit);
2007 AudioUnit_CloseAudioUnit(wwi->audioUnit);
2008 OSSpinLockUnlock(&wwi->lock);
2009 return MMSYSERR_NOMEM;
2011 memcpy(wwi->bufferListCopy, wwi->bufferList, AUDIOBUFFERLISTSIZE(wwi->bufferList->mNumberBuffers));
2013 OSSpinLockUnlock(&wwi->lock);
2015 return widNotifyClient(wwi, WIM_OPEN, 0L, 0L);
2019 /**************************************************************************
2020 * widClose [internal]
2022 static DWORD widClose(WORD wDevID)
2024 DWORD ret = MMSYSERR_NOERROR;
2028 TRACE("(%u);\n", wDevID);
2030 if (wDevID >= MAX_WAVEINDRV)
2032 WARN("bad device ID !\n");
2033 return MMSYSERR_BADDEVICEID;
2036 wwi = &WInDev[wDevID];
2037 OSSpinLockLock(&wwi->lock);
2038 if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2040 WARN("Device already closed.\n");
2041 ret = MMSYSERR_INVALHANDLE;
2043 else if (wwi->lpQueuePtr)
2045 WARN("Buffers in queue.\n");
2046 ret = WAVERR_STILLPLAYING;
2050 wwi->state = WINE_WS_CLOSING;
2053 OSSpinLockUnlock(&wwi->lock);
2055 if (ret != MMSYSERR_NOERROR)
2059 /* Clean up and close the audio unit. This has to be done without
2060 * wwi->lock being held to avoid deadlock. AudioUnitUninitialize will
2061 * grab an internal Core Audio lock while waiting for the device work
2062 * thread to exit. Meanwhile the device work thread may be holding
2063 * that lock and trying to grab the wwi->lock in the callback. */
2064 err = AudioUnitUninitialize(wwi->audioUnit);
2067 ERR("AudioUnitUninitialize return %c%c%c%c\n", (char) (err >> 24),
2073 if (!AudioUnit_CloseAudioUnit(wwi->audioUnit))
2075 ERR("Can't close AudioUnit\n");
2079 OSSpinLockLock(&wwi->lock);
2080 assert(wwi->state == WINE_WS_CLOSING);
2082 /* Dellocate our audio buffers */
2083 widHelper_DestroyAudioBufferList(wwi->bufferList);
2084 wwi->bufferList = NULL;
2085 HeapFree(GetProcessHeap(), 0, wwi->bufferListCopy);
2086 wwi->bufferListCopy = NULL;
2088 wwi->audioUnit = NULL;
2089 wwi->state = WINE_WS_CLOSED;
2090 OSSpinLockUnlock(&wwi->lock);
2092 ret = widNotifyClient(wwi, WIM_CLOSE, 0L, 0L);
2098 /**************************************************************************
2099 * widAddBuffer [internal]
2101 static DWORD widAddBuffer(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
2103 DWORD ret = MMSYSERR_NOERROR;
2106 TRACE("(%u, %p, %08X);\n", wDevID, lpWaveHdr, dwSize);
2108 if (wDevID >= MAX_WAVEINDRV)
2110 WARN("invalid device ID\n");
2111 return MMSYSERR_INVALHANDLE;
2113 if (!(lpWaveHdr->dwFlags & WHDR_PREPARED))
2115 TRACE("never been prepared !\n");
2116 return WAVERR_UNPREPARED;
2118 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
2120 TRACE("header already in use !\n");
2121 return WAVERR_STILLPLAYING;
2124 wwi = &WInDev[wDevID];
2125 OSSpinLockLock(&wwi->lock);
2127 if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2129 WARN("Trying to add buffer to closed device.\n");
2130 ret = MMSYSERR_INVALHANDLE;
2136 lpWaveHdr->dwFlags |= WHDR_INQUEUE;
2137 lpWaveHdr->dwFlags &= ~WHDR_DONE;
2138 lpWaveHdr->dwBytesRecorded = 0;
2139 lpWaveHdr->lpNext = NULL;
2141 /* insert buffer at end of queue */
2142 for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext))
2147 OSSpinLockUnlock(&wwi->lock);
2153 /**************************************************************************
2154 * widStart [internal]
2156 static DWORD widStart(WORD wDevID)
2158 DWORD ret = MMSYSERR_NOERROR;
2161 TRACE("(%u);\n", wDevID);
2162 if (wDevID >= MAX_WAVEINDRV)
2164 WARN("invalid device ID\n");
2165 return MMSYSERR_INVALHANDLE;
2168 /* The order of the following operations is important since we can't hold
2169 * the mutex while we make an Audio Unit call. Set the PLAYING state
2170 * before starting the Audio Unit. In widStop, the order is reversed.
2171 * This guarantees that we can't get into a situation where the state is
2172 * PLAYING but the Audio Unit isn't running. Although we can be in STOPPED
2173 * state with the Audio Unit still running, that's harmless because the
2174 * input callback will just throw away the sound data.
2176 wwi = &WInDev[wDevID];
2177 OSSpinLockLock(&wwi->lock);
2179 if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2181 WARN("Trying to start closed device.\n");
2182 ret = MMSYSERR_INVALHANDLE;
2185 wwi->state = WINE_WS_PLAYING;
2187 OSSpinLockUnlock(&wwi->lock);
2189 if (ret == MMSYSERR_NOERROR)
2191 /* Start pulling for audio data */
2192 OSStatus err = AudioOutputUnitStart(wwi->audioUnit);
2194 ERR("Failed to start AU: %08lx\n", err);
2196 TRACE("Recording started...\n");
2203 /**************************************************************************
2204 * widStop [internal]
2206 static DWORD widStop(WORD wDevID)
2208 DWORD ret = MMSYSERR_NOERROR;
2210 WAVEHDR* lpWaveHdr = NULL;
2213 TRACE("(%u);\n", wDevID);
2214 if (wDevID >= MAX_WAVEINDRV)
2216 WARN("invalid device ID\n");
2217 return MMSYSERR_INVALHANDLE;
2220 wwi = &WInDev[wDevID];
2222 /* The order of the following operations is important since we can't hold
2223 * the mutex while we make an Audio Unit call. Stop the Audio Unit before
2224 * setting the STOPPED state. In widStart, the order is reversed. This
2225 * guarantees that we can't get into a situation where the state is
2226 * PLAYING but the Audio Unit isn't running. Although we can be in STOPPED
2227 * state with the Audio Unit still running, that's harmless because the
2228 * input callback will just throw away the sound data.
2230 err = AudioOutputUnitStop(wwi->audioUnit);
2232 WARN("Failed to stop AU: %08lx\n", err);
2234 TRACE("Recording stopped.\n");
2236 OSSpinLockLock(&wwi->lock);
2238 if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2240 WARN("Trying to stop closed device.\n");
2241 ret = MMSYSERR_INVALHANDLE;
2243 else if (wwi->state != WINE_WS_STOPPED)
2245 wwi->state = WINE_WS_STOPPED;
2246 /* If there's a buffer in progress, it's done. Remove it from the
2247 * queue so that we can return it to the app, below. */
2248 if (wwi->lpQueuePtr)
2250 lpWaveHdr = wwi->lpQueuePtr;
2251 wwi->lpQueuePtr = lpWaveHdr->lpNext;
2255 OSSpinLockUnlock(&wwi->lock);
2259 lpWaveHdr->lpNext = NULL;
2260 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2261 lpWaveHdr->dwFlags |= WHDR_DONE;
2262 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2268 /**************************************************************************
2269 * widGetPos [internal]
2271 static DWORD widGetPos(WORD wDevID, LPMMTIME lpTime, UINT size)
2276 TRACE("(%u);\n", wDevID);
2277 if (wDevID >= MAX_WAVEINDRV)
2279 WARN("invalid device ID\n");
2280 return MMSYSERR_INVALHANDLE;
2283 wwi = &WInDev[wDevID];
2285 OSSpinLockLock(&WInDev[wDevID].lock);
2286 val = wwi->dwTotalRecorded;
2287 OSSpinLockUnlock(&WInDev[wDevID].lock);
2289 return bytes_to_mmtime(lpTime, val, &wwi->format);
2292 /**************************************************************************
2293 * widReset [internal]
2295 static DWORD widReset(WORD wDevID)
2297 DWORD ret = MMSYSERR_NOERROR;
2299 WAVEHDR* lpWaveHdr = NULL;
2301 TRACE("(%u);\n", wDevID);
2302 if (wDevID >= MAX_WAVEINDRV)
2304 WARN("invalid device ID\n");
2305 return MMSYSERR_INVALHANDLE;
2308 wwi = &WInDev[wDevID];
2309 OSSpinLockLock(&wwi->lock);
2311 if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2313 WARN("Trying to reset a closed device.\n");
2314 ret = MMSYSERR_INVALHANDLE;
2318 lpWaveHdr = wwi->lpQueuePtr;
2319 wwi->lpQueuePtr = NULL;
2320 wwi->state = WINE_WS_STOPPED;
2321 wwi->dwTotalRecorded = 0;
2324 OSSpinLockUnlock(&wwi->lock);
2326 if (ret == MMSYSERR_NOERROR)
2328 OSStatus err = AudioOutputUnitStop(wwi->audioUnit);
2330 WARN("Failed to stop AU: %08lx\n", err);
2332 TRACE("Recording stopped.\n");
2337 WAVEHDR* lpNext = lpWaveHdr->lpNext;
2339 lpWaveHdr->lpNext = NULL;
2340 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2341 lpWaveHdr->dwFlags |= WHDR_DONE;
2342 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2351 /**************************************************************************
2352 * widGetNumDevs [internal]
2354 static DWORD widGetNumDevs(void)
2356 return MAX_WAVEINDRV;
2360 /**************************************************************************
2361 * widDevInterfaceSize [internal]
2363 static DWORD widDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
2365 TRACE("(%u, %p)\n", wDevID, dwParam1);
2367 *dwParam1 = MultiByteToWideChar(CP_UNIXCP, 0, WInDev[wDevID].interface_name, -1,
2368 NULL, 0 ) * sizeof(WCHAR);
2369 return MMSYSERR_NOERROR;
2373 /**************************************************************************
2374 * widDevInterface [internal]
2376 static DWORD widDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
2378 if (dwParam2 >= MultiByteToWideChar(CP_UNIXCP, 0, WInDev[wDevID].interface_name, -1,
2379 NULL, 0 ) * sizeof(WCHAR))
2381 MultiByteToWideChar(CP_UNIXCP, 0, WInDev[wDevID].interface_name, -1,
2382 dwParam1, dwParam2 / sizeof(WCHAR));
2383 return MMSYSERR_NOERROR;
2385 return MMSYSERR_INVALPARAM;
2389 /**************************************************************************
2390 * widDsCreate [internal]
2392 static DWORD widDsCreate(UINT wDevID, PIDSCDRIVER* drv)
2394 TRACE("(%d,%p)\n",wDevID,drv);
2396 FIXME("DirectSoundCapture not implemented\n");
2397 FIXME("The (slower) DirectSound HEL mode will be used instead.\n");
2398 return MMSYSERR_NOTSUPPORTED;
2401 /**************************************************************************
2402 * widDsDesc [internal]
2404 static DWORD widDsDesc(UINT wDevID, PDSDRIVERDESC desc)
2406 /* The DirectSound HEL will automatically wrap a non-DirectSound-capable
2407 * driver in a DirectSound adaptor, thus allowing the driver to be used by
2408 * DirectSound clients. However, it only does this if we respond
2409 * successfully to the DRV_QUERYDSOUNDDESC message. It's enough to fill in
2410 * the driver and device names of the description output parameter. */
2411 memset(desc, 0, sizeof(*desc));
2412 lstrcpynA(desc->szDrvname, "winecoreaudio.drv", sizeof(desc->szDrvname) - 1);
2413 lstrcpynA(desc->szDesc, WInDev[wDevID].interface_name, sizeof(desc->szDesc) - 1);
2414 return MMSYSERR_NOERROR;
2418 /**************************************************************************
2419 * widMessage (WINECOREAUDIO.6)
2421 DWORD WINAPI CoreAudio_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2422 DWORD dwParam1, DWORD dwParam2)
2424 TRACE("(%u, %04X, %08X, %08X, %08X);\n",
2425 wDevID, wMsg, dwUser, dwParam1, dwParam2);
2433 /* FIXME: Pretend this is supported */
2435 case WIDM_OPEN: return widOpen (wDevID, (LPWAVEOPENDESC)dwParam1, dwParam2);
2436 case WIDM_CLOSE: return widClose (wDevID);
2437 case WIDM_ADDBUFFER: return widAddBuffer (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2438 case WIDM_PREPARE: return MMSYSERR_NOTSUPPORTED;
2439 case WIDM_UNPREPARE: return MMSYSERR_NOTSUPPORTED;
2440 case WIDM_GETDEVCAPS: return widGetDevCaps (wDevID, (LPWAVEINCAPSW)dwParam1, dwParam2);
2441 case WIDM_GETNUMDEVS: return widGetNumDevs ();
2442 case WIDM_RESET: return widReset (wDevID);
2443 case WIDM_START: return widStart (wDevID);
2444 case WIDM_STOP: return widStop (wDevID);
2445 case WIDM_GETPOS: return widGetPos (wDevID, (LPMMTIME)dwParam1, (UINT)dwParam2 );
2446 case DRV_QUERYDEVICEINTERFACESIZE: return widDevInterfaceSize (wDevID, (LPDWORD)dwParam1);
2447 case DRV_QUERYDEVICEINTERFACE: return widDevInterface (wDevID, (PWCHAR)dwParam1, dwParam2);
2448 case DRV_QUERYDSOUNDIFACE: return widDsCreate (wDevID, (PIDSCDRIVER*)dwParam1);
2449 case DRV_QUERYDSOUNDDESC: return widDsDesc (wDevID, (PDSDRIVERDESC)dwParam1);
2451 FIXME("unknown message %d!\n", wMsg);
2454 return MMSYSERR_NOTSUPPORTED;
2458 OSStatus CoreAudio_wiAudioUnitIOProc(void *inRefCon,
2459 AudioUnitRenderActionFlags *ioActionFlags,
2460 const AudioTimeStamp *inTimeStamp,
2462 UInt32 inNumberFrames,
2463 AudioBufferList *ioData)
2465 WINE_WAVEIN* wwi = (WINE_WAVEIN*)inRefCon;
2466 OSStatus err = noErr;
2467 BOOL needNotify = FALSE;
2468 WAVEHDR* lpStorePtr;
2469 unsigned int dataToStore;
2470 unsigned int dataStored = 0;
2474 fprintf(stderr, "trace:wave:CoreAudio_wiAudioUnitIOProc (ioActionFlags = %08lx, "
2475 "inTimeStamp = { %f, %x%08x, %f, %x%08x, %08lx }, inBusNumber = %lu, inNumberFrames = %lu)\n",
2476 *ioActionFlags, inTimeStamp->mSampleTime, (DWORD)(inTimeStamp->mHostTime >>32),
2477 (DWORD)inTimeStamp->mHostTime, inTimeStamp->mRateScalar, (DWORD)(inTimeStamp->mWordClockTime >> 32),
2478 (DWORD)inTimeStamp->mWordClockTime, inTimeStamp->mFlags, inBusNumber, inNumberFrames);
2480 /* Render into audio buffer */
2481 /* FIXME: implement sample rate conversion on input. This will require
2482 * a different render strategy. We'll need to buffer the sound data
2483 * received here and pass it off to an AUConverter in another thread. */
2484 err = AudioUnitRender(wwi->audioUnit, ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, wwi->bufferList);
2488 fprintf(stderr, "err:wave:CoreAudio_wiAudioUnitIOProc AudioUnitRender failed with error %li\n", err);
2492 /* Copy from audio buffer to the wavehdrs */
2493 dataToStore = wwi->bufferList->mBuffers[0].mDataByteSize;
2495 OSSpinLockLock(&wwi->lock);
2497 lpStorePtr = wwi->lpQueuePtr;
2499 /* We might have been called while the waveIn device is being closed in
2500 * widClose. We have to do nothing in that case. The check of wwi->state
2501 * below ensures that. */
2502 while (dataToStore > 0 && wwi->state == WINE_WS_PLAYING && lpStorePtr)
2504 unsigned int room = lpStorePtr->dwBufferLength - lpStorePtr->dwBytesRecorded;
2505 unsigned int toCopy;
2508 fprintf(stderr, "trace:wave:CoreAudio_wiAudioUnitIOProc Looking to store %u bytes to wavehdr %p, which has room for %u\n",
2509 dataToStore, lpStorePtr, room);
2511 if (room >= dataToStore)
2512 toCopy = dataToStore;
2518 memcpy(lpStorePtr->lpData + lpStorePtr->dwBytesRecorded,
2519 (char*)wwi->bufferList->mBuffers[0].mData + dataStored, toCopy);
2520 lpStorePtr->dwBytesRecorded += toCopy;
2521 wwi->dwTotalRecorded += toCopy;
2522 dataStored += toCopy;
2523 dataToStore -= toCopy;
2529 lpStorePtr = lpStorePtr->lpNext;
2534 OSSpinLockUnlock(&wwi->lock);
2536 /* Restore the audio buffer list structure from backup, in case
2537 * AudioUnitRender clobbered it. (It modifies mDataByteSize and may even
2538 * give us a different mData buffer to avoid a copy.) */
2539 memcpy(wwi->bufferList, wwi->bufferListCopy, AUDIOBUFFERLISTSIZE(wwi->bufferList->mNumberBuffers));
2541 if (needNotify) wodSendNotifyInputCompletionsMessage(wwi);
2547 /**************************************************************************
2548 * widMessage (WINECOREAUDIO.6)
2550 DWORD WINAPI CoreAudio_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2551 DWORD dwParam1, DWORD dwParam2)
2553 FIXME("(%u, %04X, %08X, %08X, %08X): CoreAudio support not compiled into wine\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2554 return MMSYSERR_NOTENABLED;
2557 /**************************************************************************
2558 * wodMessage (WINECOREAUDIO.7)
2560 DWORD WINAPI CoreAudio_wodMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2561 DWORD dwParam1, DWORD dwParam2)
2563 FIXME("(%u, %04X, %08X, %08X, %08X): CoreAudio support not compiled into wine\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2564 return MMSYSERR_NOTENABLED;