2 * Wine Driver for CoreAudio based on Jack Driver
4 * Copyright 1994 Martin Ayotte
5 * Copyright 1999 Eric Pouech (async playing in waveOut/waveIn)
6 * Copyright 2000 Eric Pouech (loops in waveOut)
7 * Copyright 2002 Chris Morgan (jack version of this file)
8 * Copyright 2005, 2006 Emmanuel Maillard
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
49 #include "coreaudio.h"
50 #include "wine/unicode.h"
51 #include "wine/library.h"
52 #include "wine/debug.h"
53 #include "wine/list.h"
55 WINE_DEFAULT_DEBUG_CHANNEL(wave);
57 #if defined(HAVE_COREAUDIO_COREAUDIO_H) && defined(HAVE_AUDIOUNIT_AUDIOUNIT_H)
58 #include <CoreAudio/CoreAudio.h>
59 #include <CoreFoundation/CoreFoundation.h>
60 #include <libkern/OSAtomic.h>
62 WINE_DECLARE_DEBUG_CHANNEL(coreaudio);
65 Due to AudioUnit headers conflict define some needed types.
68 typedef void *AudioUnit;
70 /* From AudioUnit/AUComponents.h */
73 kAudioUnitRenderAction_OutputIsSilence = (1 << 4),
74 /* provides hint on return from Render(): if set the buffer contains all zeroes */
76 typedef UInt32 AudioUnitRenderActionFlags;
78 typedef long ComponentResult;
79 extern ComponentResult
80 AudioUnitRender( AudioUnit ci,
81 AudioUnitRenderActionFlags * ioActionFlags,
82 const AudioTimeStamp * inTimeStamp,
83 UInt32 inOutputBusNumber,
84 UInt32 inNumberFrames,
85 AudioBufferList * ioData) AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER;
87 /* only allow 10 output devices through this driver, this ought to be adequate */
88 #define MAX_WAVEOUTDRV (1)
89 #define MAX_WAVEINDRV (1)
91 /* state diagram for waveOut writing:
93 * +---------+-------------+---------------+---------------------------------+
94 * | state | function | event | new state |
95 * +---------+-------------+---------------+---------------------------------+
96 * | | open() | | PLAYING |
97 * | PAUSED | write() | | PAUSED |
98 * | PLAYING | write() | HEADER | PLAYING |
99 * | (other) | write() | <error> | |
100 * | (any) | pause() | PAUSING | PAUSED |
101 * | PAUSED | restart() | RESTARTING | PLAYING |
102 * | (any) | reset() | RESETTING | PLAYING |
103 * | (any) | close() | CLOSING | <deallocated> |
104 * +---------+-------------+---------------+---------------------------------+
107 /* states of the playing device */
108 #define WINE_WS_PLAYING 0 /* for waveOut: lpPlayPtr == NULL -> stopped */
109 #define WINE_WS_PAUSED 1
110 #define WINE_WS_STOPPED 2 /* Not used for waveOut */
111 #define WINE_WS_CLOSED 3 /* Not used for waveOut */
112 #define WINE_WS_OPENING 4
113 #define WINE_WS_CLOSING 5
115 typedef struct tagCoreAudio_Device {
119 char* interface_name;
121 WAVEOUTCAPSW out_caps;
123 DWORD in_caps_support;
127 unsigned audio_fragment;
129 BOOL bTriggerSupport;
132 DSDRIVERDESC ds_desc;
133 DSDRIVERCAPS ds_caps;
134 DSCDRIVERCAPS dsc_caps;
138 AudioDeviceID outputDeviceID;
139 AudioDeviceID inputDeviceID;
140 AudioStreamBasicDescription streamDescription;
143 /* for now use the default device */
144 static CoreAudio_Device CoreAudio_DefaultDevice;
149 volatile int state; /* one of the WINE_WS_ manifest constants */
150 WAVEOPENDESC waveDesc;
152 PCMWAVEFORMAT format;
155 AudioStreamBasicDescription streamDescription;
157 LPWAVEHDR lpQueuePtr; /* start of queued WAVEHDRs (waiting to be notified) */
158 LPWAVEHDR lpPlayPtr; /* start of not yet fully played buffers */
159 DWORD dwPartialOffset; /* Offset of not yet written bytes in lpPlayPtr */
161 LPWAVEHDR lpLoopPtr; /* pointer of first buffer in loop, if any */
162 DWORD dwLoops; /* private copy of loop counter */
164 DWORD dwPlayedTotal; /* number of bytes actually played since opening */
166 OSSpinLock lock; /* synchronization stuff */
167 } WINE_WAVEOUT_INSTANCE;
170 CoreAudio_Device *cadev;
172 char interface_name[32];
179 struct list instances;
180 OSSpinLock lock; /* guards the instances list */
184 /* This device's device number */
187 /* Access to the following fields is synchronized across threads. */
189 LPWAVEHDR lpQueuePtr;
190 DWORD dwTotalRecorded;
192 /* Synchronization mechanism to protect above fields */
195 /* Capabilities description */
197 char interface_name[32];
199 /* Record the arguments used when opening the device. */
200 WAVEOPENDESC waveDesc;
202 PCMWAVEFORMAT format;
205 AudioBufferList*bufferList;
206 AudioBufferList*bufferListCopy;
208 /* Record state of debug channels at open. Used to control fprintf's since
209 * we can't use Wine debug channel calls in non-Wine AudioUnit threads. */
214 /* These fields aren't used. */
216 CoreAudio_Device *cadev;
218 AudioStreamBasicDescription streamDescription;
222 static WINE_WAVEOUT WOutDev [MAX_WAVEOUTDRV];
223 static WINE_WAVEIN WInDev [MAX_WAVEINDRV];
225 static HANDLE hThread = NULL; /* Track the thread we create so we can clean it up later */
226 static CFMessagePortRef Port_SendToMessageThread;
228 static void wodHelper_PlayPtrNext(WINE_WAVEOUT_INSTANCE* wwo);
229 static void wodHelper_NotifyDoneForList(WINE_WAVEOUT_INSTANCE* wwo, LPWAVEHDR lpWaveHdr);
230 static void wodHelper_NotifyCompletions(WINE_WAVEOUT_INSTANCE* wwo, BOOL force);
231 static void widHelper_NotifyCompletions(WINE_WAVEIN* wwi);
233 extern int AudioUnit_CreateDefaultAudioUnit(void *wwo, AudioUnit *au);
234 extern int AudioUnit_CloseAudioUnit(AudioUnit au);
235 extern int AudioUnit_InitializeWithStreamDescription(AudioUnit au, AudioStreamBasicDescription *streamFormat);
237 extern OSStatus AudioOutputUnitStart(AudioUnit au);
238 extern OSStatus AudioOutputUnitStop(AudioUnit au);
239 extern OSStatus AudioUnitUninitialize(AudioUnit au);
241 extern int AudioUnit_SetVolume(AudioUnit au, float left, float right);
242 extern int AudioUnit_GetVolume(AudioUnit au, float *left, float *right);
244 extern int AudioUnit_GetInputDeviceSampleRate(void);
246 extern int AudioUnit_CreateInputUnit(void* wwi, AudioUnit* out_au,
247 WORD nChannels, DWORD nSamplesPerSec, WORD wBitsPerSample,
248 UInt32* outFrameCount);
250 OSStatus CoreAudio_woAudioUnitIOProc(void *inRefCon,
251 AudioUnitRenderActionFlags *ioActionFlags,
252 const AudioTimeStamp *inTimeStamp,
254 UInt32 inNumberFrames,
255 AudioBufferList *ioData);
256 OSStatus CoreAudio_wiAudioUnitIOProc(void *inRefCon,
257 AudioUnitRenderActionFlags *ioActionFlags,
258 const AudioTimeStamp *inTimeStamp,
260 UInt32 inNumberFrames,
261 AudioBufferList *ioData);
263 /* These strings used only for tracing */
265 static const char * getMessage(UINT msg)
267 #define MSG_TO_STR(x) case x: return #x
269 MSG_TO_STR(DRVM_INIT);
270 MSG_TO_STR(DRVM_EXIT);
271 MSG_TO_STR(DRVM_ENABLE);
272 MSG_TO_STR(DRVM_DISABLE);
273 MSG_TO_STR(WIDM_OPEN);
274 MSG_TO_STR(WIDM_CLOSE);
275 MSG_TO_STR(WIDM_ADDBUFFER);
276 MSG_TO_STR(WIDM_PREPARE);
277 MSG_TO_STR(WIDM_UNPREPARE);
278 MSG_TO_STR(WIDM_GETDEVCAPS);
279 MSG_TO_STR(WIDM_GETNUMDEVS);
280 MSG_TO_STR(WIDM_GETPOS);
281 MSG_TO_STR(WIDM_RESET);
282 MSG_TO_STR(WIDM_START);
283 MSG_TO_STR(WIDM_STOP);
284 MSG_TO_STR(WODM_OPEN);
285 MSG_TO_STR(WODM_CLOSE);
286 MSG_TO_STR(WODM_WRITE);
287 MSG_TO_STR(WODM_PAUSE);
288 MSG_TO_STR(WODM_GETPOS);
289 MSG_TO_STR(WODM_BREAKLOOP);
290 MSG_TO_STR(WODM_PREPARE);
291 MSG_TO_STR(WODM_UNPREPARE);
292 MSG_TO_STR(WODM_GETDEVCAPS);
293 MSG_TO_STR(WODM_GETNUMDEVS);
294 MSG_TO_STR(WODM_GETPITCH);
295 MSG_TO_STR(WODM_SETPITCH);
296 MSG_TO_STR(WODM_GETPLAYBACKRATE);
297 MSG_TO_STR(WODM_SETPLAYBACKRATE);
298 MSG_TO_STR(WODM_GETVOLUME);
299 MSG_TO_STR(WODM_SETVOLUME);
300 MSG_TO_STR(WODM_RESTART);
301 MSG_TO_STR(WODM_RESET);
302 MSG_TO_STR(DRV_QUERYDEVICEINTERFACESIZE);
303 MSG_TO_STR(DRV_QUERYDEVICEINTERFACE);
304 MSG_TO_STR(DRV_QUERYDSOUNDIFACE);
305 MSG_TO_STR(DRV_QUERYDSOUNDDESC);
308 return wine_dbg_sprintf("UNKNOWN(0x%04x)", msg);
311 #define kStopLoopMessage 0
312 #define kWaveOutNotifyCompletionsMessage 1
313 #define kWaveInNotifyCompletionsMessage 2
315 /* Mach Message Handling */
316 static CFDataRef wodMessageHandler(CFMessagePortRef port_ReceiveInMessageThread, SInt32 msgid, CFDataRef data, void *info)
318 UInt32 *buffer = NULL;
322 case kWaveOutNotifyCompletionsMessage:
323 wodHelper_NotifyCompletions(*(WINE_WAVEOUT_INSTANCE**)CFDataGetBytePtr(data), FALSE);
325 case kWaveInNotifyCompletionsMessage:
326 buffer = (UInt32 *) CFDataGetBytePtr(data);
327 widHelper_NotifyCompletions(&WInDev[buffer[0]]);
330 CFRunLoopStop(CFRunLoopGetCurrent());
337 static DWORD WINAPI messageThread(LPVOID p)
339 CFMessagePortRef port_ReceiveInMessageThread = (CFMessagePortRef) p;
340 CFRunLoopSourceRef source;
342 source = CFMessagePortCreateRunLoopSource(kCFAllocatorDefault, port_ReceiveInMessageThread, (CFIndex)0);
343 CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
347 CFRunLoopSourceInvalidate(source);
349 CFRelease(port_ReceiveInMessageThread);
354 /**************************************************************************
355 * wodSendNotifyCompletionsMessage [internal]
356 * Call from AudioUnit IO thread can't use Wine debug channels.
358 static void wodSendNotifyCompletionsMessage(WINE_WAVEOUT_INSTANCE* wwo)
362 if (!Port_SendToMessageThread)
365 data = CFDataCreate(kCFAllocatorDefault, (UInt8 *)&wwo, sizeof(wwo));
369 CFMessagePortSendRequest(Port_SendToMessageThread, kWaveOutNotifyCompletionsMessage, data, 0.0, 0.0, NULL, NULL);
373 /**************************************************************************
374 * wodSendNotifyInputCompletionsMessage [internal]
375 * Call from AudioUnit IO thread can't use Wine debug channels.
377 static void wodSendNotifyInputCompletionsMessage(WINE_WAVEIN* wwi)
382 if (!Port_SendToMessageThread)
385 buffer = (UInt32) wwi->wiID;
387 data = CFDataCreate(kCFAllocatorDefault, (UInt8 *)&buffer, sizeof(buffer));
391 CFMessagePortSendRequest(Port_SendToMessageThread, kWaveInNotifyCompletionsMessage, data, 0.0, 0.0, NULL, NULL);
395 static DWORD bytes_to_mmtime(LPMMTIME lpTime, DWORD position,
396 PCMWAVEFORMAT* format)
398 TRACE("wType=%04X wBitsPerSample=%u nSamplesPerSec=%u nChannels=%u nAvgBytesPerSec=%u\n",
399 lpTime->wType, format->wBitsPerSample, format->wf.nSamplesPerSec,
400 format->wf.nChannels, format->wf.nAvgBytesPerSec);
401 TRACE("Position in bytes=%u\n", position);
403 switch (lpTime->wType) {
405 lpTime->u.sample = position / (format->wBitsPerSample / 8 * format->wf.nChannels);
406 TRACE("TIME_SAMPLES=%u\n", lpTime->u.sample);
409 lpTime->u.ms = 1000.0 * position / (format->wBitsPerSample / 8 * format->wf.nChannels * format->wf.nSamplesPerSec);
410 TRACE("TIME_MS=%u\n", lpTime->u.ms);
413 lpTime->u.smpte.fps = 30;
414 position = position / (format->wBitsPerSample / 8 * format->wf.nChannels);
415 position += (format->wf.nSamplesPerSec / lpTime->u.smpte.fps) - 1; /* round up */
416 lpTime->u.smpte.sec = position / format->wf.nSamplesPerSec;
417 position -= lpTime->u.smpte.sec * format->wf.nSamplesPerSec;
418 lpTime->u.smpte.min = lpTime->u.smpte.sec / 60;
419 lpTime->u.smpte.sec -= 60 * lpTime->u.smpte.min;
420 lpTime->u.smpte.hour = lpTime->u.smpte.min / 60;
421 lpTime->u.smpte.min -= 60 * lpTime->u.smpte.hour;
422 lpTime->u.smpte.fps = 30;
423 lpTime->u.smpte.frame = position * lpTime->u.smpte.fps / format->wf.nSamplesPerSec;
424 TRACE("TIME_SMPTE=%02u:%02u:%02u:%02u\n",
425 lpTime->u.smpte.hour, lpTime->u.smpte.min,
426 lpTime->u.smpte.sec, lpTime->u.smpte.frame);
429 WARN("Format %d not supported, using TIME_BYTES !\n", lpTime->wType);
430 lpTime->wType = TIME_BYTES;
433 lpTime->u.cb = position;
434 TRACE("TIME_BYTES=%u\n", lpTime->u.cb);
437 return MMSYSERR_NOERROR;
440 static BOOL supportedFormat(LPWAVEFORMATEX wf)
442 if (wf->nSamplesPerSec == 0)
445 if (wf->wFormatTag == WAVE_FORMAT_PCM) {
446 if (wf->nChannels >= 1 && wf->nChannels <= 2) {
447 if (wf->wBitsPerSample==8||wf->wBitsPerSample==16)
450 } else if (wf->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
451 WAVEFORMATEXTENSIBLE * wfex = (WAVEFORMATEXTENSIBLE *)wf;
453 if (wf->cbSize == 22 && IsEqualGUID(&wfex->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM)) {
454 if (wf->nChannels >=1 && wf->nChannels <= 8) {
455 if (wf->wBitsPerSample==wfex->Samples.wValidBitsPerSample) {
456 if (wf->wBitsPerSample==8||wf->wBitsPerSample==16)
459 WARN("wBitsPerSample != wValidBitsPerSample not supported yet\n");
462 WARN("only KSDATAFORMAT_SUBTYPE_PCM supported\n");
464 WARN("only WAVE_FORMAT_PCM supported\n");
469 void copyFormat(LPWAVEFORMATEX wf1, LPPCMWAVEFORMAT wf2)
471 memcpy(wf2, wf1, sizeof(PCMWAVEFORMAT));
472 /* Downgrade WAVE_FORMAT_EXTENSIBLE KSDATAFORMAT_SUBTYPE_PCM
473 * to smaller yet compatible WAVE_FORMAT_PCM structure */
474 if (wf2->wf.wFormatTag == WAVE_FORMAT_EXTENSIBLE)
475 wf2->wf.wFormatTag = WAVE_FORMAT_PCM;
478 /**************************************************************************
479 * CoreAudio_GetDevCaps [internal]
481 BOOL CoreAudio_GetDevCaps (void)
485 AudioDeviceID devId = CoreAudio_DefaultDevice.outputDeviceID;
487 char name[MAXPNAMELEN];
489 propertySize = MAXPNAMELEN;
490 status = AudioDeviceGetProperty(devId, 0 , FALSE, kAudioDevicePropertyDeviceName, &propertySize, name);
492 ERR("AudioHardwareGetProperty for kAudioDevicePropertyDeviceName return %s\n", wine_dbgstr_fourcc(status));
496 memcpy(CoreAudio_DefaultDevice.ds_desc.szDesc, name, sizeof(name));
497 strcpy(CoreAudio_DefaultDevice.ds_desc.szDrvname, "winecoreaudio.drv");
498 MultiByteToWideChar(CP_UNIXCP, 0, name, sizeof(name),
499 CoreAudio_DefaultDevice.out_caps.szPname,
500 sizeof(CoreAudio_DefaultDevice.out_caps.szPname) / sizeof(WCHAR));
501 memcpy(CoreAudio_DefaultDevice.dev_name, name, 32);
503 propertySize = sizeof(CoreAudio_DefaultDevice.streamDescription);
504 status = AudioDeviceGetProperty(devId, 0, FALSE , kAudioDevicePropertyStreamFormat, &propertySize, &CoreAudio_DefaultDevice.streamDescription);
505 if (status != noErr) {
506 ERR("AudioHardwareGetProperty for kAudioDevicePropertyStreamFormat return %s\n", wine_dbgstr_fourcc(status));
510 TRACE("Device Stream Description mSampleRate : %f\n mFormatID : %s\n"
511 "mFormatFlags : %lX\n mBytesPerPacket : %lu\n mFramesPerPacket : %lu\n"
512 "mBytesPerFrame : %lu\n mChannelsPerFrame : %lu\n mBitsPerChannel : %lu\n",
513 CoreAudio_DefaultDevice.streamDescription.mSampleRate,
514 wine_dbgstr_fourcc(CoreAudio_DefaultDevice.streamDescription.mFormatID),
515 CoreAudio_DefaultDevice.streamDescription.mFormatFlags,
516 CoreAudio_DefaultDevice.streamDescription.mBytesPerPacket,
517 CoreAudio_DefaultDevice.streamDescription.mFramesPerPacket,
518 CoreAudio_DefaultDevice.streamDescription.mBytesPerFrame,
519 CoreAudio_DefaultDevice.streamDescription.mChannelsPerFrame,
520 CoreAudio_DefaultDevice.streamDescription.mBitsPerChannel);
522 CoreAudio_DefaultDevice.out_caps.wMid = 0xcafe;
523 CoreAudio_DefaultDevice.out_caps.wPid = 0x0001;
525 CoreAudio_DefaultDevice.out_caps.vDriverVersion = 0x0001;
526 CoreAudio_DefaultDevice.out_caps.dwFormats = 0x00000000;
527 CoreAudio_DefaultDevice.out_caps.wReserved1 = 0;
528 CoreAudio_DefaultDevice.out_caps.dwSupport = WAVECAPS_VOLUME;
529 CoreAudio_DefaultDevice.out_caps.dwSupport |= WAVECAPS_LRVOLUME;
531 CoreAudio_DefaultDevice.out_caps.wChannels = 2;
532 CoreAudio_DefaultDevice.out_caps.dwFormats|= WAVE_FORMAT_4S16;
534 TRACE_(coreaudio)("out dwFormats = %08x, dwSupport = %08x\n",
535 CoreAudio_DefaultDevice.out_caps.dwFormats, CoreAudio_DefaultDevice.out_caps.dwSupport);
540 /******************************************************************
543 * Initialize CoreAudio_DefaultDevice
545 LONG CoreAudio_WaveInit(void)
550 CFStringRef messageThreadPortName;
551 CFMessagePortRef port_ReceiveInMessageThread;
556 /* number of sound cards */
557 AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &propertySize, NULL);
558 propertySize /= sizeof(AudioDeviceID);
559 TRACE("sound cards : %lu\n", propertySize);
561 /* Get the output device */
562 propertySize = sizeof(CoreAudio_DefaultDevice.outputDeviceID);
563 status = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &propertySize, &CoreAudio_DefaultDevice.outputDeviceID);
565 ERR("AudioHardwareGetProperty return %s for kAudioHardwarePropertyDefaultOutputDevice\n", wine_dbgstr_fourcc(status));
568 if (CoreAudio_DefaultDevice.outputDeviceID == kAudioDeviceUnknown) {
569 ERR("AudioHardwareGetProperty: CoreAudio_DefaultDevice.outputDeviceID == kAudioDeviceUnknown\n");
573 if ( ! CoreAudio_GetDevCaps() )
576 CoreAudio_DefaultDevice.interface_name=HeapAlloc(GetProcessHeap(),0,strlen(CoreAudio_DefaultDevice.dev_name)+1);
577 strcpy(CoreAudio_DefaultDevice.interface_name, CoreAudio_DefaultDevice.dev_name);
579 for (i = 0; i < MAX_WAVEOUTDRV; ++i)
581 static const WCHAR wszWaveOutFormat[] =
582 {'C','o','r','e','A','u','d','i','o',' ','W','a','v','e','O','u','t',' ','%','d',0};
584 list_init(&WOutDev[i].instances);
585 WOutDev[i].cadev = &CoreAudio_DefaultDevice;
587 memset(&WOutDev[i].caps, 0, sizeof(WOutDev[i].caps));
589 WOutDev[i].caps.wMid = 0xcafe; /* Manufac ID */
590 WOutDev[i].caps.wPid = 0x0001; /* Product ID */
591 snprintfW(WOutDev[i].caps.szPname, sizeof(WOutDev[i].caps.szPname)/sizeof(WCHAR), wszWaveOutFormat, i);
592 snprintf(WOutDev[i].interface_name, sizeof(WOutDev[i].interface_name), "winecoreaudio: %d", i);
594 WOutDev[i].caps.vDriverVersion = 0x0001;
595 WOutDev[i].caps.dwFormats = 0x00000000;
596 WOutDev[i].caps.dwSupport = WAVECAPS_VOLUME;
598 WOutDev[i].caps.wChannels = 2;
599 /* WOutDev[i].caps.dwSupport |= WAVECAPS_LRVOLUME; */ /* FIXME */
601 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96M08;
602 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96S08;
603 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96M16;
604 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96S16;
605 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48M08;
606 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48S08;
607 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48M16;
608 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48S16;
609 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4M08;
610 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4S08;
611 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4S16;
612 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4M16;
613 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2M08;
614 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2S08;
615 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2M16;
616 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2S16;
617 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1M08;
618 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1S08;
619 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1M16;
620 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1S16;
622 WOutDev[i].device_volume = 0xffffffff;
624 WOutDev[i].lock = 0; /* initialize the mutex */
627 /* FIXME: implement sample rate conversion on input */
628 inputSampleRate = AudioUnit_GetInputDeviceSampleRate();
630 for (i = 0; i < MAX_WAVEINDRV; ++i)
632 static const WCHAR wszWaveInFormat[] =
633 {'C','o','r','e','A','u','d','i','o',' ','W','a','v','e','I','n',' ','%','d',0};
635 memset(&WInDev[i], 0, sizeof(WInDev[i]));
638 /* Establish preconditions for widOpen */
639 WInDev[i].state = WINE_WS_CLOSED;
640 WInDev[i].lock = 0; /* initialize the mutex */
642 /* Fill in capabilities. widGetDevCaps can be called at any time. */
643 WInDev[i].caps.wMid = 0xcafe; /* Manufac ID */
644 WInDev[i].caps.wPid = 0x0001; /* Product ID */
645 WInDev[i].caps.vDriverVersion = 0x0001;
647 snprintfW(WInDev[i].caps.szPname, sizeof(WInDev[i].caps.szPname)/sizeof(WCHAR), wszWaveInFormat, i);
648 snprintf(WInDev[i].interface_name, sizeof(WInDev[i].interface_name), "winecoreaudio in: %d", i);
650 if (inputSampleRate == 96000)
652 WInDev[i].caps.dwFormats |= WAVE_FORMAT_96M08;
653 WInDev[i].caps.dwFormats |= WAVE_FORMAT_96S08;
654 WInDev[i].caps.dwFormats |= WAVE_FORMAT_96M16;
655 WInDev[i].caps.dwFormats |= WAVE_FORMAT_96S16;
657 if (inputSampleRate == 48000)
659 WInDev[i].caps.dwFormats |= WAVE_FORMAT_48M08;
660 WInDev[i].caps.dwFormats |= WAVE_FORMAT_48S08;
661 WInDev[i].caps.dwFormats |= WAVE_FORMAT_48M16;
662 WInDev[i].caps.dwFormats |= WAVE_FORMAT_48S16;
664 if (inputSampleRate == 44100)
666 WInDev[i].caps.dwFormats |= WAVE_FORMAT_4M08;
667 WInDev[i].caps.dwFormats |= WAVE_FORMAT_4S08;
668 WInDev[i].caps.dwFormats |= WAVE_FORMAT_4M16;
669 WInDev[i].caps.dwFormats |= WAVE_FORMAT_4S16;
671 if (inputSampleRate == 22050)
673 WInDev[i].caps.dwFormats |= WAVE_FORMAT_2M08;
674 WInDev[i].caps.dwFormats |= WAVE_FORMAT_2S08;
675 WInDev[i].caps.dwFormats |= WAVE_FORMAT_2M16;
676 WInDev[i].caps.dwFormats |= WAVE_FORMAT_2S16;
678 if (inputSampleRate == 11025)
680 WInDev[i].caps.dwFormats |= WAVE_FORMAT_1M08;
681 WInDev[i].caps.dwFormats |= WAVE_FORMAT_1S08;
682 WInDev[i].caps.dwFormats |= WAVE_FORMAT_1M16;
683 WInDev[i].caps.dwFormats |= WAVE_FORMAT_1S16;
686 WInDev[i].caps.wChannels = 2;
689 /* create mach messages handler */
691 messageThreadPortName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL,
692 CFSTR("WaveMessagePort.%d.%lu"), getpid(), (unsigned long)random());
693 if (!messageThreadPortName)
695 ERR("Can't create message thread port name\n");
699 port_ReceiveInMessageThread = CFMessagePortCreateLocal(kCFAllocatorDefault, messageThreadPortName,
700 &wodMessageHandler, NULL, NULL);
701 if (!port_ReceiveInMessageThread)
703 ERR("Can't create message thread local port\n");
704 CFRelease(messageThreadPortName);
708 Port_SendToMessageThread = CFMessagePortCreateRemote(kCFAllocatorDefault, messageThreadPortName);
709 CFRelease(messageThreadPortName);
710 if (!Port_SendToMessageThread)
712 ERR("Can't create port for sending to message thread\n");
713 CFRelease(port_ReceiveInMessageThread);
717 /* Cannot WAIT for any events because we are called from the loader (which has a lock on loading stuff) */
718 /* We might want to wait for this thread to be created -- but we cannot -- not here at least */
719 /* Instead track the thread so we can clean it up later */
722 ERR("Message thread already started -- expect problems\n");
724 hThread = CreateThread(NULL, 0, messageThread, (LPVOID)port_ReceiveInMessageThread, 0, NULL);
727 ERR("Can't create message thread\n");
728 CFRelease(port_ReceiveInMessageThread);
729 CFRelease(Port_SendToMessageThread);
730 Port_SendToMessageThread = NULL;
734 /* The message thread is responsible for releasing port_ReceiveInMessageThread. */
739 void CoreAudio_WaveRelease(void)
741 /* Stop CFRunLoop in messageThread */
744 if (!Port_SendToMessageThread)
747 CFMessagePortSendRequest(Port_SendToMessageThread, kStopLoopMessage, NULL, 0.0, 0.0, NULL, NULL);
748 CFRelease(Port_SendToMessageThread);
749 Port_SendToMessageThread = NULL;
751 /* Wait for the thread to finish and clean it up */
752 /* This rids us of any quick start/shutdown driver crashes */
753 WaitForSingleObject(hThread, INFINITE);
754 CloseHandle(hThread);
758 /*======================================================================*
759 * Low level WAVE OUT implementation *
760 *======================================================================*/
762 /**************************************************************************
763 * wodNotifyClient [internal]
765 static DWORD wodNotifyClient(WINE_WAVEOUT_INSTANCE* wwo, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
767 TRACE_(coreaudio)("wMsg = 0x%04x dwParm1 = %04x dwParam2 = %04x\n", wMsg, dwParam1, dwParam2);
773 if (wwo->wFlags != DCB_NULL &&
774 !DriverCallback(wwo->waveDesc.dwCallback, wwo->wFlags,
775 (HDRVR)wwo->waveDesc.hWave, wMsg, wwo->waveDesc.dwInstance,
778 ERR("can't notify client !\n");
779 return MMSYSERR_ERROR;
783 ERR("Unknown callback message %u\n", wMsg);
784 return MMSYSERR_INVALPARAM;
786 return MMSYSERR_NOERROR;
790 /**************************************************************************
791 * wodGetDevCaps [internal]
793 static DWORD wodGetDevCaps(WORD wDevID, LPWAVEOUTCAPSW lpCaps, DWORD dwSize)
795 TRACE("(%u, %p, %u);\n", wDevID, lpCaps, dwSize);
797 if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
799 if (wDevID >= MAX_WAVEOUTDRV)
801 TRACE("MAX_WAVOUTDRV reached !\n");
802 return MMSYSERR_BADDEVICEID;
805 TRACE("dwSupport=(0x%x), dwFormats=(0x%x)\n", WOutDev[wDevID].caps.dwSupport, WOutDev[wDevID].caps.dwFormats);
806 memcpy(lpCaps, &WOutDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
807 return MMSYSERR_NOERROR;
810 /**************************************************************************
813 static DWORD wodOpen(WORD wDevID, WINE_WAVEOUT_INSTANCE** pInstance, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
815 WINE_WAVEOUT_INSTANCE* wwo;
817 AudioStreamBasicDescription streamFormat;
818 AudioUnit audioUnit = NULL;
819 BOOL auInited = FALSE;
821 TRACE("(%u, %p, %p, %08x);\n", wDevID, pInstance, lpDesc, dwFlags);
824 WARN("Invalid Parameter !\n");
825 return MMSYSERR_INVALPARAM;
827 if (wDevID >= MAX_WAVEOUTDRV) {
828 TRACE("MAX_WAVOUTDRV reached !\n");
829 return MMSYSERR_BADDEVICEID;
832 TRACE("Format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
833 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
834 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
836 if (!supportedFormat(lpDesc->lpFormat))
838 WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
839 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
840 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
841 return WAVERR_BADFORMAT;
844 if (dwFlags & WAVE_FORMAT_QUERY)
846 TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
847 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
848 lpDesc->lpFormat->nSamplesPerSec);
849 return MMSYSERR_NOERROR;
852 /* nBlockAlign and nAvgBytesPerSec are output variables for dsound */
853 if (lpDesc->lpFormat->nBlockAlign != lpDesc->lpFormat->nChannels*lpDesc->lpFormat->wBitsPerSample/8) {
854 lpDesc->lpFormat->nBlockAlign = lpDesc->lpFormat->nChannels*lpDesc->lpFormat->wBitsPerSample/8;
855 WARN("Fixing nBlockAlign\n");
857 if (lpDesc->lpFormat->nAvgBytesPerSec!= lpDesc->lpFormat->nSamplesPerSec*lpDesc->lpFormat->nBlockAlign) {
858 lpDesc->lpFormat->nAvgBytesPerSec = lpDesc->lpFormat->nSamplesPerSec*lpDesc->lpFormat->nBlockAlign;
859 WARN("Fixing nAvgBytesPerSec\n");
862 /* We proceed in three phases:
863 * o Allocate the device instance, marking it as opening
864 * o Create, configure, and start the Audio Unit. To avoid deadlock,
865 * this has to be done without holding wwo->lock.
866 * o If that was successful, finish setting up our instance and add it
867 * to the device's list.
868 * Otherwise, clean up and deallocate the instance.
870 wwo = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*wwo));
872 return MMSYSERR_NOMEM;
875 wwo->state = WINE_WS_OPENING;
877 if (!AudioUnit_CreateDefaultAudioUnit((void *) wwo, &audioUnit))
879 ERR("CoreAudio_CreateDefaultAudioUnit(0x%04x) failed\n", wDevID);
880 ret = MMSYSERR_ERROR;
884 streamFormat.mFormatID = kAudioFormatLinearPCM;
885 streamFormat.mFormatFlags = kLinearPCMFormatFlagIsPacked;
886 /* FIXME check for 32bits float -> kLinearPCMFormatFlagIsFloat */
887 if (lpDesc->lpFormat->wBitsPerSample != 8)
888 streamFormat.mFormatFlags |= kLinearPCMFormatFlagIsSignedInteger;
889 # ifdef WORDS_BIGENDIAN
890 streamFormat.mFormatFlags |= kLinearPCMFormatFlagIsBigEndian; /* FIXME Wave format is little endian */
893 streamFormat.mSampleRate = lpDesc->lpFormat->nSamplesPerSec;
894 streamFormat.mChannelsPerFrame = lpDesc->lpFormat->nChannels;
895 streamFormat.mFramesPerPacket = 1;
896 streamFormat.mBitsPerChannel = lpDesc->lpFormat->wBitsPerSample;
897 streamFormat.mBytesPerFrame = streamFormat.mBitsPerChannel * streamFormat.mChannelsPerFrame / 8;
898 streamFormat.mBytesPerPacket = streamFormat.mBytesPerFrame * streamFormat.mFramesPerPacket;
900 ret = AudioUnit_InitializeWithStreamDescription(audioUnit, &streamFormat);
903 ret = WAVERR_BADFORMAT; /* FIXME return an error based on the OSStatus */
908 AudioUnit_SetVolume(audioUnit, LOWORD(WOutDev[wDevID].device_volume) / 65535.0f,
909 HIWORD(WOutDev[wDevID].device_volume) / 65535.0f);
911 /* Our render callback CoreAudio_woAudioUnitIOProc may be called before
912 * AudioOutputUnitStart returns. Core Audio will grab its own internal
913 * lock before calling it and the callback grabs wwo->lock. This would
914 * deadlock if we were holding wwo->lock.
915 * Also, the callback has to safely do nothing in that case, because
916 * wwo hasn't been completely filled out, yet. This is assured by state
917 * being WINE_WS_OPENING. */
918 ret = AudioOutputUnitStart(audioUnit);
921 ERR("AudioOutputUnitStart failed: %08x\n", ret);
922 ret = MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
927 OSSpinLockLock(&wwo->lock);
928 assert(wwo->state == WINE_WS_OPENING);
930 wwo->audioUnit = audioUnit;
931 wwo->streamDescription = streamFormat;
933 wwo->state = WINE_WS_PLAYING;
935 wwo->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
937 wwo->waveDesc = *lpDesc;
938 copyFormat(lpDesc->lpFormat, &wwo->format);
940 WOutDev[wDevID].trace_on = TRACE_ON(wave);
941 WOutDev[wDevID].warn_on = WARN_ON(wave);
942 WOutDev[wDevID].err_on = ERR_ON(wave);
944 OSSpinLockUnlock(&wwo->lock);
946 OSSpinLockLock(&WOutDev[wDevID].lock);
947 list_add_head(&WOutDev[wDevID].instances, &wwo->entry);
948 OSSpinLockUnlock(&WOutDev[wDevID].lock);
951 TRACE("opened instance %p\n", wwo);
953 ret = wodNotifyClient(wwo, WOM_OPEN, 0L, 0L);
961 AudioUnitUninitialize(audioUnit);
962 AudioUnit_CloseAudioUnit(audioUnit);
965 OSSpinLockLock(&wwo->lock);
966 assert(wwo->state == WINE_WS_OPENING);
967 /* OSSpinLockUnlock(&wwo->lock); *//* No need, about to free */
968 HeapFree(GetProcessHeap(), 0, wwo);
973 /**************************************************************************
974 * wodClose [internal]
976 static DWORD wodClose(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo)
978 DWORD ret = MMSYSERR_NOERROR;
980 TRACE("(%u, %p);\n", wDevID, wwo);
982 if (wDevID >= MAX_WAVEOUTDRV)
984 WARN("bad device ID !\n");
985 return MMSYSERR_BADDEVICEID;
988 OSSpinLockLock(&wwo->lock);
991 OSSpinLockUnlock(&wwo->lock);
992 WARN("buffers still playing !\n");
993 ret = WAVERR_STILLPLAYING;
997 AudioUnit audioUnit = wwo->audioUnit;
999 /* sanity check: this should not happen since the device must have been reset before */
1000 if (wwo->lpQueuePtr || wwo->lpPlayPtr) ERR("out of sync\n");
1002 wwo->state = WINE_WS_CLOSING; /* mark the device as closing */
1003 wwo->audioUnit = NULL;
1005 OSSpinLockUnlock(&wwo->lock);
1007 err = AudioUnitUninitialize(audioUnit);
1009 ERR("AudioUnitUninitialize return %s\n", wine_dbgstr_fourcc(err));
1010 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1013 if ( !AudioUnit_CloseAudioUnit(audioUnit) )
1015 ERR("Can't close AudioUnit\n");
1016 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1019 OSSpinLockLock(&WOutDev[wDevID].lock);
1020 list_remove(&wwo->entry);
1021 OSSpinLockUnlock(&WOutDev[wDevID].lock);
1023 ret = wodNotifyClient(wwo, WOM_CLOSE, 0L, 0L);
1025 HeapFree(GetProcessHeap(), 0, wwo);
1031 /**************************************************************************
1032 * wodPrepare [internal]
1034 static DWORD wodPrepare(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1036 TRACE("(%u, %p, %p, %08x);\n", wDevID, wwo, lpWaveHdr, dwSize);
1038 if (wDevID >= MAX_WAVEOUTDRV) {
1039 WARN("bad device ID !\n");
1040 return MMSYSERR_BADDEVICEID;
1043 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1044 return WAVERR_STILLPLAYING;
1046 lpWaveHdr->dwFlags |= WHDR_PREPARED;
1047 lpWaveHdr->dwFlags &= ~WHDR_DONE;
1049 return MMSYSERR_NOERROR;
1052 /**************************************************************************
1053 * wodUnprepare [internal]
1055 static DWORD wodUnprepare(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1057 TRACE("(%u, %p, %p, %08x);\n", wDevID, wwo, lpWaveHdr, dwSize);
1059 if (wDevID >= MAX_WAVEOUTDRV) {
1060 WARN("bad device ID !\n");
1061 return MMSYSERR_BADDEVICEID;
1064 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1065 return WAVERR_STILLPLAYING;
1067 lpWaveHdr->dwFlags &= ~WHDR_PREPARED;
1068 lpWaveHdr->dwFlags |= WHDR_DONE;
1070 return MMSYSERR_NOERROR;
1074 /**************************************************************************
1075 * wodHelper_CheckForLoopBegin [internal]
1077 * Check if the new waveheader is the beginning of a loop, and set up
1079 * This is called with the WAVEOUT_INSTANCE lock held.
1080 * Call from AudioUnit IO thread can't use Wine debug channels.
1082 static void wodHelper_CheckForLoopBegin(WINE_WAVEOUT_INSTANCE* wwo)
1084 LPWAVEHDR lpWaveHdr = wwo->lpPlayPtr;
1086 if (lpWaveHdr->dwFlags & WHDR_BEGINLOOP)
1090 if (WOutDev[wwo->woID].warn_on)
1091 fprintf(stderr, "warn:winecoreaudio:wodHelper_CheckForLoopBegin Already in a loop. Discarding loop on this header (%p)\n", lpWaveHdr);
1095 if (WOutDev[wwo->woID].trace_on)
1096 fprintf(stderr, "trace:winecoreaudio:wodHelper_CheckForLoopBegin Starting loop (%dx) with %p\n", lpWaveHdr->dwLoops, lpWaveHdr);
1098 wwo->lpLoopPtr = lpWaveHdr;
1099 /* Windows does not touch WAVEHDR.dwLoops,
1100 * so we need to make an internal copy */
1101 wwo->dwLoops = lpWaveHdr->dwLoops;
1107 /**************************************************************************
1108 * wodHelper_PlayPtrNext [internal]
1110 * Advance the play pointer to the next waveheader, looping if required.
1111 * This is called with the WAVEOUT_INSTANCE lock held.
1112 * Call from AudioUnit IO thread can't use Wine debug channels.
1114 static void wodHelper_PlayPtrNext(WINE_WAVEOUT_INSTANCE* wwo)
1116 BOOL didLoopBack = FALSE;
1118 wwo->dwPartialOffset = 0;
1119 if ((wwo->lpPlayPtr->dwFlags & WHDR_ENDLOOP) && wwo->lpLoopPtr)
1121 /* We're at the end of a loop, loop if required */
1122 if (wwo->dwLoops > 1)
1125 wwo->lpPlayPtr = wwo->lpLoopPtr;
1130 wwo->lpLoopPtr = NULL;
1135 /* We didn't loop back. Advance to the next wave header */
1136 wwo->lpPlayPtr = wwo->lpPlayPtr->lpNext;
1139 wodHelper_CheckForLoopBegin(wwo);
1143 /* Send the "done" notification for each WAVEHDR in a list. The list must be
1144 * free-standing. It should not be part of a device instance's queue.
1145 * This function must be called with the WAVEOUT_INSTANCE lock *not* held.
1146 * Furthermore, it does not lock it, itself. That's because the callback to the
1147 * application may prompt the application to operate on the device, and we don't
1150 static void wodHelper_NotifyDoneForList(WINE_WAVEOUT_INSTANCE* wwo, LPWAVEHDR lpWaveHdr)
1154 LPWAVEHDR lpNext = lpWaveHdr->lpNext;
1156 lpWaveHdr->lpNext = NULL;
1157 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1158 lpWaveHdr->dwFlags |= WHDR_DONE;
1159 wodNotifyClient(wwo, WOM_DONE, (DWORD)lpWaveHdr, 0);
1165 /* if force is TRUE then notify the client that all the headers were completed
1167 static void wodHelper_NotifyCompletions(WINE_WAVEOUT_INSTANCE* wwo, BOOL force)
1169 LPWAVEHDR lpFirstDoneWaveHdr = NULL;
1171 OSSpinLockLock(&wwo->lock);
1173 /* First, excise all of the done headers from the queue into
1174 * a free-standing list. */
1177 lpFirstDoneWaveHdr = wwo->lpQueuePtr;
1178 wwo->lpQueuePtr = NULL;
1182 LPWAVEHDR lpWaveHdr;
1183 LPWAVEHDR lpLastDoneWaveHdr = NULL;
1185 /* Start from lpQueuePtr and keep notifying until:
1186 * - we hit an unwritten wavehdr
1187 * - we hit the beginning of a running loop
1188 * - we hit a wavehdr which hasn't finished playing
1191 lpWaveHdr = wwo->lpQueuePtr;
1193 lpWaveHdr != wwo->lpPlayPtr &&
1194 lpWaveHdr != wwo->lpLoopPtr;
1195 lpWaveHdr = lpWaveHdr->lpNext
1198 if (!lpFirstDoneWaveHdr)
1199 lpFirstDoneWaveHdr = lpWaveHdr;
1200 lpLastDoneWaveHdr = lpWaveHdr;
1203 if (lpLastDoneWaveHdr)
1205 wwo->lpQueuePtr = lpLastDoneWaveHdr->lpNext;
1206 lpLastDoneWaveHdr->lpNext = NULL;
1210 OSSpinLockUnlock(&wwo->lock);
1212 /* Now, send the "done" notification for each header in our list. */
1213 wodHelper_NotifyDoneForList(wwo, lpFirstDoneWaveHdr);
1217 /**************************************************************************
1218 * wodWrite [internal]
1221 static DWORD wodWrite(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1225 TRACE("(%u, %p, %p, %lu, %08X);\n", wDevID, wwo, lpWaveHdr, (unsigned long)lpWaveHdr->dwBufferLength, dwSize);
1227 /* first, do the sanity checks... */
1228 if (wDevID >= MAX_WAVEOUTDRV)
1230 WARN("bad dev ID !\n");
1231 return MMSYSERR_BADDEVICEID;
1234 if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
1236 TRACE("unprepared\n");
1237 return WAVERR_UNPREPARED;
1240 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1242 TRACE("still playing\n");
1243 return WAVERR_STILLPLAYING;
1246 lpWaveHdr->dwFlags &= ~WHDR_DONE;
1247 lpWaveHdr->dwFlags |= WHDR_INQUEUE;
1248 lpWaveHdr->lpNext = 0;
1250 OSSpinLockLock(&wwo->lock);
1251 /* insert buffer at the end of queue */
1252 for (wh = &(wwo->lpQueuePtr); *wh; wh = &((*wh)->lpNext))
1256 if (!wwo->lpPlayPtr)
1258 wwo->lpPlayPtr = lpWaveHdr;
1260 wodHelper_CheckForLoopBegin(wwo);
1262 wwo->dwPartialOffset = 0;
1264 OSSpinLockUnlock(&wwo->lock);
1266 return MMSYSERR_NOERROR;
1269 /**************************************************************************
1270 * wodPause [internal]
1272 static DWORD wodPause(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo)
1276 TRACE("(%u, %p);!\n", wDevID, wwo);
1278 if (wDevID >= MAX_WAVEOUTDRV)
1280 WARN("bad device ID !\n");
1281 return MMSYSERR_BADDEVICEID;
1284 /* The order of the following operations is important since we can't hold
1285 * the mutex while we make an Audio Unit call. Stop the Audio Unit before
1286 * setting the PAUSED state. In wodRestart, the order is reversed. This
1287 * guarantees that we can't get into a situation where the state is
1288 * PLAYING but the Audio Unit isn't running. Although we can be in PAUSED
1289 * state with the Audio Unit still running, that's harmless because the
1290 * render callback will just produce silence.
1292 status = AudioOutputUnitStop(wwo->audioUnit);
1294 WARN("AudioOutputUnitStop return %s\n", wine_dbgstr_fourcc(status));
1296 OSSpinLockLock(&wwo->lock);
1297 if (wwo->state == WINE_WS_PLAYING)
1298 wwo->state = WINE_WS_PAUSED;
1299 OSSpinLockUnlock(&wwo->lock);
1301 return MMSYSERR_NOERROR;
1304 /**************************************************************************
1305 * wodRestart [internal]
1307 static DWORD wodRestart(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo)
1311 TRACE("(%u, %p);\n", wDevID, wwo);
1313 if (wDevID >= MAX_WAVEOUTDRV )
1315 WARN("bad device ID !\n");
1316 return MMSYSERR_BADDEVICEID;
1319 /* The order of the following operations is important since we can't hold
1320 * the mutex while we make an Audio Unit call. Set the PLAYING
1321 * state before starting the Audio Unit. In wodPause, the order is
1322 * reversed. This guarantees that we can't get into a situation where
1323 * the state is PLAYING but the Audio Unit isn't running.
1324 * Although we can be in PAUSED state with the Audio Unit still running,
1325 * that's harmless because the render callback will just produce silence.
1327 OSSpinLockLock(&wwo->lock);
1328 if (wwo->state == WINE_WS_PAUSED)
1329 wwo->state = WINE_WS_PLAYING;
1330 OSSpinLockUnlock(&wwo->lock);
1332 status = AudioOutputUnitStart(wwo->audioUnit);
1334 ERR("AudioOutputUnitStart return %s\n", wine_dbgstr_fourcc(status));
1335 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1338 return MMSYSERR_NOERROR;
1341 /**************************************************************************
1342 * wodReset [internal]
1344 static DWORD wodReset(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo)
1347 LPWAVEHDR lpSavedQueuePtr;
1349 TRACE("(%u, %p);\n", wDevID, wwo);
1351 if (wDevID >= MAX_WAVEOUTDRV)
1353 WARN("bad device ID !\n");
1354 return MMSYSERR_BADDEVICEID;
1357 OSSpinLockLock(&wwo->lock);
1359 if (wwo->state == WINE_WS_CLOSING || wwo->state == WINE_WS_OPENING)
1361 OSSpinLockUnlock(&wwo->lock);
1362 WARN("resetting a closed device\n");
1363 return MMSYSERR_INVALHANDLE;
1366 lpSavedQueuePtr = wwo->lpQueuePtr;
1367 wwo->lpPlayPtr = wwo->lpQueuePtr = wwo->lpLoopPtr = NULL;
1368 wwo->state = WINE_WS_PLAYING;
1369 wwo->dwPlayedTotal = 0;
1371 wwo->dwPartialOffset = 0; /* Clear partial wavehdr */
1373 OSSpinLockUnlock(&wwo->lock);
1375 status = AudioOutputUnitStart(wwo->audioUnit);
1378 ERR( "AudioOutputUnitStart return %s\n", wine_dbgstr_fourcc(status));
1379 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1382 /* Now, send the "done" notification for each header in our list. */
1383 /* Do this last so the reset operation is effectively complete before the
1384 * app does whatever it's going to do in response to these notifications. */
1385 wodHelper_NotifyDoneForList(wwo, lpSavedQueuePtr);
1387 return MMSYSERR_NOERROR;
1390 /**************************************************************************
1391 * wodBreakLoop [internal]
1393 static DWORD wodBreakLoop(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo)
1395 TRACE("(%u, %p);\n", wDevID, wwo);
1397 if (wDevID >= MAX_WAVEOUTDRV)
1399 WARN("bad device ID !\n");
1400 return MMSYSERR_BADDEVICEID;
1403 OSSpinLockLock(&wwo->lock);
1405 if (wwo->lpLoopPtr != NULL)
1407 /* ensure exit at end of current loop */
1411 OSSpinLockUnlock(&wwo->lock);
1413 return MMSYSERR_NOERROR;
1416 /**************************************************************************
1417 * wodGetPosition [internal]
1419 static DWORD wodGetPosition(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, LPMMTIME lpTime, DWORD uSize)
1423 TRACE("(%u, %p, %p, %u);\n", wDevID, wwo, lpTime, uSize);
1425 if (wDevID >= MAX_WAVEOUTDRV)
1427 WARN("bad device ID !\n");
1428 return MMSYSERR_BADDEVICEID;
1431 /* if null pointer to time structure return error */
1432 if (lpTime == NULL) return MMSYSERR_INVALPARAM;
1434 OSSpinLockLock(&wwo->lock);
1435 val = wwo->dwPlayedTotal;
1436 OSSpinLockUnlock(&wwo->lock);
1438 return bytes_to_mmtime(lpTime, val, &wwo->format);
1441 /**************************************************************************
1442 * wodGetVolume [internal]
1444 static DWORD wodGetVolume(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, LPDWORD lpdwVol)
1446 if (wDevID >= MAX_WAVEOUTDRV)
1448 WARN("bad device ID !\n");
1449 return MMSYSERR_BADDEVICEID;
1452 TRACE("(%u, %p, %p);\n", wDevID, wwo, lpdwVol);
1459 AudioUnit_GetVolume(wwo->audioUnit, &left, &right);
1460 *lpdwVol = (WORD)(left * 0xFFFFl) + ((WORD)(right * 0xFFFFl) << 16);
1463 *lpdwVol = WOutDev[wDevID].device_volume;
1465 return MMSYSERR_NOERROR;
1468 /**************************************************************************
1469 * wodSetVolume [internal]
1471 static DWORD wodSetVolume(WORD wDevID, WINE_WAVEOUT_INSTANCE* wwo, DWORD dwParam)
1476 if (wDevID >= MAX_WAVEOUTDRV)
1478 WARN("bad device ID !\n");
1479 return MMSYSERR_BADDEVICEID;
1482 left = LOWORD(dwParam) / 65535.0f;
1483 right = HIWORD(dwParam) / 65535.0f;
1485 TRACE("(%u, %p, %08x);\n", wDevID, wwo, dwParam);
1488 AudioUnit_SetVolume(wwo->audioUnit, left, right);
1491 OSSpinLockLock(&WOutDev[wDevID].lock);
1492 LIST_FOR_EACH_ENTRY(wwo, &WOutDev[wDevID].instances, WINE_WAVEOUT_INSTANCE, entry)
1493 AudioUnit_SetVolume(wwo->audioUnit, left, right);
1494 OSSpinLockUnlock(&WOutDev[wDevID].lock);
1496 WOutDev[wDevID].device_volume = dwParam;
1499 return MMSYSERR_NOERROR;
1502 /**************************************************************************
1503 * wodGetNumDevs [internal]
1505 static DWORD wodGetNumDevs(void)
1508 return MAX_WAVEOUTDRV;
1511 /**************************************************************************
1512 * wodDevInterfaceSize [internal]
1514 static DWORD wodDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
1516 TRACE("(%u, %p)\n", wDevID, dwParam1);
1518 *dwParam1 = MultiByteToWideChar(CP_UNIXCP, 0, WOutDev[wDevID].cadev->interface_name, -1,
1519 NULL, 0 ) * sizeof(WCHAR);
1520 return MMSYSERR_NOERROR;
1523 /**************************************************************************
1524 * wodDevInterface [internal]
1526 static DWORD wodDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
1529 if (dwParam2 >= MultiByteToWideChar(CP_UNIXCP, 0, WOutDev[wDevID].cadev->interface_name, -1,
1530 NULL, 0 ) * sizeof(WCHAR))
1532 MultiByteToWideChar(CP_UNIXCP, 0, WOutDev[wDevID].cadev->interface_name, -1,
1533 dwParam1, dwParam2 / sizeof(WCHAR));
1534 return MMSYSERR_NOERROR;
1536 return MMSYSERR_INVALPARAM;
1539 /**************************************************************************
1540 * widDsCreate [internal]
1542 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
1544 TRACE("(%d,%p)\n",wDevID,drv);
1546 FIXME("DirectSound not implemented\n");
1547 FIXME("The (slower) DirectSound HEL mode will be used instead.\n");
1548 return MMSYSERR_NOTSUPPORTED;
1551 /**************************************************************************
1552 * wodDsDesc [internal]
1554 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc)
1556 /* The DirectSound HEL will automatically wrap a non-DirectSound-capable
1557 * driver in a DirectSound adaptor, thus allowing the driver to be used by
1558 * DirectSound clients. However, it only does this if we respond
1559 * successfully to the DRV_QUERYDSOUNDDESC message. It's enough to fill in
1560 * the driver and device names of the description output parameter. */
1561 *desc = WOutDev[wDevID].cadev->ds_desc;
1562 return MMSYSERR_NOERROR;
1565 /**************************************************************************
1566 * wodMessage (WINECOREAUDIO.7)
1568 DWORD WINAPI CoreAudio_wodMessage(UINT wDevID, UINT wMsg, DWORD_PTR dwUser,
1569 DWORD_PTR dwParam1, DWORD_PTR dwParam2)
1571 WINE_WAVEOUT_INSTANCE* wwo = (WINE_WAVEOUT_INSTANCE*)dwUser;
1573 TRACE("(%u, %s, %p, %p, %p);\n",
1574 wDevID, getMessage(wMsg), (void*)dwUser, (void*)dwParam1, (void*)dwParam2);
1582 /* FIXME: Pretend this is supported */
1584 case WODM_OPEN: return wodOpen(wDevID, (WINE_WAVEOUT_INSTANCE**)dwUser, (LPWAVEOPENDESC) dwParam1, dwParam2);
1585 case WODM_CLOSE: return wodClose(wDevID, wwo);
1586 case WODM_WRITE: return wodWrite(wDevID, wwo, (LPWAVEHDR) dwParam1, dwParam2);
1587 case WODM_PAUSE: return wodPause(wDevID, wwo);
1588 case WODM_GETPOS: return wodGetPosition(wDevID, wwo, (LPMMTIME) dwParam1, dwParam2);
1589 case WODM_BREAKLOOP: return wodBreakLoop(wDevID, wwo);
1590 case WODM_PREPARE: return wodPrepare(wDevID, wwo, (LPWAVEHDR)dwParam1, dwParam2);
1591 case WODM_UNPREPARE: return wodUnprepare(wDevID, wwo, (LPWAVEHDR)dwParam1, dwParam2);
1593 case WODM_GETDEVCAPS: return wodGetDevCaps(wDevID, (LPWAVEOUTCAPSW) dwParam1, dwParam2);
1594 case WODM_GETNUMDEVS: return wodGetNumDevs();
1598 case WODM_GETPLAYBACKRATE:
1599 case WODM_SETPLAYBACKRATE: return MMSYSERR_NOTSUPPORTED;
1600 case WODM_GETVOLUME: return wodGetVolume(wDevID, wwo, (LPDWORD)dwParam1);
1601 case WODM_SETVOLUME: return wodSetVolume(wDevID, wwo, dwParam1);
1602 case WODM_RESTART: return wodRestart(wDevID, wwo);
1603 case WODM_RESET: return wodReset(wDevID, wwo);
1605 case DRV_QUERYDEVICEINTERFACESIZE: return wodDevInterfaceSize (wDevID, (LPDWORD)dwParam1);
1606 case DRV_QUERYDEVICEINTERFACE: return wodDevInterface (wDevID, (PWCHAR)dwParam1, dwParam2);
1607 case DRV_QUERYDSOUNDIFACE: return wodDsCreate (wDevID, (PIDSDRIVER*)dwParam1);
1608 case DRV_QUERYDSOUNDDESC: return wodDsDesc (wDevID, (PDSDRIVERDESC)dwParam1);
1611 FIXME("unknown message %d!\n", wMsg);
1614 return MMSYSERR_NOTSUPPORTED;
1617 /*======================================================================*
1618 * Low level DSOUND implementation *
1619 *======================================================================*/
1621 typedef struct IDsDriverImpl IDsDriverImpl;
1622 typedef struct IDsDriverBufferImpl IDsDriverBufferImpl;
1624 struct IDsDriverImpl
1626 /* IUnknown fields */
1627 const IDsDriverVtbl *lpVtbl;
1629 /* IDsDriverImpl fields */
1631 IDsDriverBufferImpl*primary;
1634 struct IDsDriverBufferImpl
1636 /* IUnknown fields */
1637 const IDsDriverBufferVtbl *lpVtbl;
1639 /* IDsDriverBufferImpl fields */
1646 CoreAudio IO threaded callback,
1647 we can't call Wine debug channels, critical section or anything using NtCurrentTeb here.
1649 OSStatus CoreAudio_woAudioUnitIOProc(void *inRefCon,
1650 AudioUnitRenderActionFlags *ioActionFlags,
1651 const AudioTimeStamp *inTimeStamp,
1653 UInt32 inNumberFrames,
1654 AudioBufferList *ioData)
1657 WINE_WAVEOUT_INSTANCE* wwo = (WINE_WAVEOUT_INSTANCE*)inRefCon;
1660 unsigned int dataNeeded = ioData->mBuffers[0].mDataByteSize;
1661 unsigned int dataProvided = 0;
1663 OSSpinLockLock(&wwo->lock);
1665 /* We might have been called before wwo has been completely filled out by
1666 * wodOpen, or while it's being closed in wodClose. We have to do nothing
1667 * in that case. The check of wwo->state below ensures that. */
1668 while (dataNeeded > 0 && wwo->state == WINE_WS_PLAYING && wwo->lpPlayPtr)
1670 unsigned int available = wwo->lpPlayPtr->dwBufferLength - wwo->dwPartialOffset;
1671 unsigned int toCopy;
1673 if (available >= dataNeeded)
1674 toCopy = dataNeeded;
1680 memcpy((char*)ioData->mBuffers[0].mData + dataProvided,
1681 wwo->lpPlayPtr->lpData + wwo->dwPartialOffset, toCopy);
1682 wwo->dwPartialOffset += toCopy;
1683 wwo->dwPlayedTotal += toCopy;
1684 dataProvided += toCopy;
1685 dataNeeded -= toCopy;
1686 available -= toCopy;
1691 wodHelper_PlayPtrNext(wwo);
1695 ioData->mBuffers[0].mDataByteSize = dataProvided;
1697 OSSpinLockUnlock(&wwo->lock);
1699 /* We can't provide any more wave data. Fill the rest with silence. */
1703 *ioActionFlags |= kAudioUnitRenderAction_OutputIsSilence;
1704 memset((char*)ioData->mBuffers[0].mData + dataProvided, 0, dataNeeded);
1705 dataProvided += dataNeeded;
1709 /* We only fill buffer 0. Set any others that might be requested to 0. */
1710 for (buffer = 1; buffer < ioData->mNumberBuffers; buffer++)
1712 memset(ioData->mBuffers[buffer].mData, 0, ioData->mBuffers[buffer].mDataByteSize);
1715 if (needNotify) wodSendNotifyCompletionsMessage(wwo);
1720 /*======================================================================*
1721 * Low level WAVE IN implementation *
1722 *======================================================================*/
1724 /**************************************************************************
1725 * widNotifyClient [internal]
1727 static DWORD widNotifyClient(WINE_WAVEIN* wwi, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
1729 TRACE("wMsg = 0x%04x dwParm1 = %04X dwParam2 = %04X\n", wMsg, dwParam1, dwParam2);
1736 if (wwi->wFlags != DCB_NULL &&
1737 !DriverCallback(wwi->waveDesc.dwCallback, wwi->wFlags,
1738 (HDRVR)wwi->waveDesc.hWave, wMsg, wwi->waveDesc.dwInstance,
1739 dwParam1, dwParam2))
1741 WARN("can't notify client !\n");
1742 return MMSYSERR_ERROR;
1746 FIXME("Unknown callback message %u\n", wMsg);
1747 return MMSYSERR_INVALPARAM;
1749 return MMSYSERR_NOERROR;
1753 /**************************************************************************
1754 * widHelper_NotifyCompletions [internal]
1756 static void widHelper_NotifyCompletions(WINE_WAVEIN* wwi)
1758 LPWAVEHDR lpWaveHdr;
1759 LPWAVEHDR lpFirstDoneWaveHdr = NULL;
1760 LPWAVEHDR lpLastDoneWaveHdr = NULL;
1762 OSSpinLockLock(&wwi->lock);
1764 /* First, excise all of the done headers from the queue into
1765 * a free-standing list. */
1767 /* Start from lpQueuePtr and keep notifying until:
1768 * - we hit an unfilled wavehdr
1769 * - we hit the end of the list
1772 lpWaveHdr = wwi->lpQueuePtr;
1774 lpWaveHdr->dwBytesRecorded >= lpWaveHdr->dwBufferLength;
1775 lpWaveHdr = lpWaveHdr->lpNext
1778 if (!lpFirstDoneWaveHdr)
1779 lpFirstDoneWaveHdr = lpWaveHdr;
1780 lpLastDoneWaveHdr = lpWaveHdr;
1783 if (lpLastDoneWaveHdr)
1785 wwi->lpQueuePtr = lpLastDoneWaveHdr->lpNext;
1786 lpLastDoneWaveHdr->lpNext = NULL;
1789 OSSpinLockUnlock(&wwi->lock);
1791 /* Now, send the "done" notification for each header in our list. */
1792 lpWaveHdr = lpFirstDoneWaveHdr;
1795 LPWAVEHDR lpNext = lpWaveHdr->lpNext;
1797 lpWaveHdr->lpNext = NULL;
1798 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1799 lpWaveHdr->dwFlags |= WHDR_DONE;
1800 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
1807 /**************************************************************************
1808 * widGetDevCaps [internal]
1810 static DWORD widGetDevCaps(WORD wDevID, LPWAVEINCAPSW lpCaps, DWORD dwSize)
1812 TRACE("(%u, %p, %u);\n", wDevID, lpCaps, dwSize);
1814 if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
1816 if (wDevID >= MAX_WAVEINDRV)
1818 TRACE("MAX_WAVEINDRV reached !\n");
1819 return MMSYSERR_BADDEVICEID;
1822 memcpy(lpCaps, &WInDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
1823 return MMSYSERR_NOERROR;
1827 /**************************************************************************
1828 * widHelper_DestroyAudioBufferList [internal]
1829 * Convenience function to dispose of our audio buffers
1831 static void widHelper_DestroyAudioBufferList(AudioBufferList* list)
1836 for (i = 0; i < list->mNumberBuffers; i++)
1838 if (list->mBuffers[i].mData)
1839 HeapFree(GetProcessHeap(), 0, list->mBuffers[i].mData);
1841 HeapFree(GetProcessHeap(), 0, list);
1846 #define AUDIOBUFFERLISTSIZE(numBuffers) (offsetof(AudioBufferList, mBuffers) + (numBuffers) * sizeof(AudioBuffer))
1848 /**************************************************************************
1849 * widHelper_AllocateAudioBufferList [internal]
1850 * Convenience function to allocate our audio buffers
1852 static AudioBufferList* widHelper_AllocateAudioBufferList(UInt32 numChannels, UInt32 bitsPerChannel, UInt32 bufferFrames, BOOL interleaved)
1855 UInt32 channelsPerFrame;
1856 UInt32 bytesPerFrame;
1857 UInt32 bytesPerBuffer;
1858 AudioBufferList* list;
1863 /* For interleaved audio, we allocate one buffer for all channels. */
1865 channelsPerFrame = numChannels;
1869 numBuffers = numChannels;
1870 channelsPerFrame = 1;
1873 bytesPerFrame = bitsPerChannel * channelsPerFrame / 8;
1874 bytesPerBuffer = bytesPerFrame * bufferFrames;
1876 list = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, AUDIOBUFFERLISTSIZE(numBuffers));
1880 list->mNumberBuffers = numBuffers;
1881 for (i = 0; i < numBuffers; ++i)
1883 list->mBuffers[i].mNumberChannels = channelsPerFrame;
1884 list->mBuffers[i].mDataByteSize = bytesPerBuffer;
1885 list->mBuffers[i].mData = HeapAlloc(GetProcessHeap(), 0, bytesPerBuffer);
1886 if (list->mBuffers[i].mData == NULL)
1888 widHelper_DestroyAudioBufferList(list);
1896 /**************************************************************************
1897 * widOpen [internal]
1899 static DWORD widOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
1904 TRACE("(%u, %p, %08X);\n", wDevID, lpDesc, dwFlags);
1907 WARN("Invalid Parameter !\n");
1908 return MMSYSERR_INVALPARAM;
1910 if (wDevID >= MAX_WAVEINDRV)
1912 TRACE ("MAX_WAVEINDRV reached !\n");
1913 return MMSYSERR_BADDEVICEID;
1916 TRACE("Format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
1917 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1918 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
1920 if (!supportedFormat(lpDesc->lpFormat) ||
1921 lpDesc->lpFormat->nSamplesPerSec != AudioUnit_GetInputDeviceSampleRate()
1924 WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
1925 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1926 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
1927 return WAVERR_BADFORMAT;
1930 if (dwFlags & WAVE_FORMAT_QUERY)
1932 TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
1933 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1934 lpDesc->lpFormat->nSamplesPerSec);
1935 return MMSYSERR_NOERROR;
1938 /* nBlockAlign and nAvgBytesPerSec are output variables for dsound */
1939 if (lpDesc->lpFormat->nBlockAlign != lpDesc->lpFormat->nChannels*lpDesc->lpFormat->wBitsPerSample/8) {
1940 lpDesc->lpFormat->nBlockAlign = lpDesc->lpFormat->nChannels*lpDesc->lpFormat->wBitsPerSample/8;
1941 WARN("Fixing nBlockAlign\n");
1943 if (lpDesc->lpFormat->nAvgBytesPerSec!= lpDesc->lpFormat->nSamplesPerSec*lpDesc->lpFormat->nBlockAlign) {
1944 lpDesc->lpFormat->nAvgBytesPerSec = lpDesc->lpFormat->nSamplesPerSec*lpDesc->lpFormat->nBlockAlign;
1945 WARN("Fixing nAvgBytesPerSec\n");
1948 wwi = &WInDev[wDevID];
1949 if (!OSSpinLockTry(&wwi->lock))
1950 return MMSYSERR_ALLOCATED;
1952 if (wwi->state != WINE_WS_CLOSED)
1954 OSSpinLockUnlock(&wwi->lock);
1955 return MMSYSERR_ALLOCATED;
1958 wwi->state = WINE_WS_STOPPED;
1959 wwi->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
1961 wwi->waveDesc = *lpDesc;
1962 copyFormat(lpDesc->lpFormat, &wwi->format);
1964 wwi->dwTotalRecorded = 0;
1966 wwi->trace_on = TRACE_ON(wave);
1967 wwi->warn_on = WARN_ON(wave);
1968 wwi->err_on = ERR_ON(wave);
1970 if (!AudioUnit_CreateInputUnit(wwi, &wwi->audioUnit,
1971 wwi->format.wf.nChannels, wwi->format.wf.nSamplesPerSec,
1972 wwi->format.wBitsPerSample, &frameCount))
1974 OSSpinLockUnlock(&wwi->lock);
1975 ERR("AudioUnit_CreateInputUnit failed\n");
1976 return MMSYSERR_ERROR;
1979 /* Allocate our audio buffers */
1980 wwi->bufferList = widHelper_AllocateAudioBufferList(wwi->format.wf.nChannels,
1981 wwi->format.wBitsPerSample, frameCount, TRUE);
1982 if (wwi->bufferList == NULL)
1984 AudioUnitUninitialize(wwi->audioUnit);
1985 AudioUnit_CloseAudioUnit(wwi->audioUnit);
1986 OSSpinLockUnlock(&wwi->lock);
1987 ERR("Failed to allocate buffer list\n");
1988 return MMSYSERR_NOMEM;
1991 /* Keep a copy of the buffer list structure (but not the buffers themselves)
1992 * in case AudioUnitRender clobbers the original, as it tends to do. */
1993 wwi->bufferListCopy = HeapAlloc(GetProcessHeap(), 0, AUDIOBUFFERLISTSIZE(wwi->bufferList->mNumberBuffers));
1994 if (wwi->bufferListCopy == NULL)
1996 widHelper_DestroyAudioBufferList(wwi->bufferList);
1997 AudioUnitUninitialize(wwi->audioUnit);
1998 AudioUnit_CloseAudioUnit(wwi->audioUnit);
1999 OSSpinLockUnlock(&wwi->lock);
2000 ERR("Failed to allocate buffer list copy\n");
2001 return MMSYSERR_NOMEM;
2003 memcpy(wwi->bufferListCopy, wwi->bufferList, AUDIOBUFFERLISTSIZE(wwi->bufferList->mNumberBuffers));
2005 OSSpinLockUnlock(&wwi->lock);
2007 return widNotifyClient(wwi, WIM_OPEN, 0L, 0L);
2011 /**************************************************************************
2012 * widClose [internal]
2014 static DWORD widClose(WORD wDevID)
2016 DWORD ret = MMSYSERR_NOERROR;
2020 TRACE("(%u);\n", wDevID);
2022 if (wDevID >= MAX_WAVEINDRV)
2024 WARN("bad device ID !\n");
2025 return MMSYSERR_BADDEVICEID;
2028 wwi = &WInDev[wDevID];
2029 OSSpinLockLock(&wwi->lock);
2030 if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2032 WARN("Device already closed.\n");
2033 ret = MMSYSERR_INVALHANDLE;
2035 else if (wwi->lpQueuePtr)
2037 WARN("Buffers in queue.\n");
2038 ret = WAVERR_STILLPLAYING;
2042 wwi->state = WINE_WS_CLOSING;
2045 OSSpinLockUnlock(&wwi->lock);
2047 if (ret != MMSYSERR_NOERROR)
2051 /* Clean up and close the audio unit. This has to be done without
2052 * wwi->lock being held to avoid deadlock. AudioUnitUninitialize will
2053 * grab an internal Core Audio lock while waiting for the device work
2054 * thread to exit. Meanwhile the device work thread may be holding
2055 * that lock and trying to grab the wwi->lock in the callback. */
2056 err = AudioUnitUninitialize(wwi->audioUnit);
2058 ERR("AudioUnitUninitialize return %s\n", wine_dbgstr_fourcc(err));
2060 if (!AudioUnit_CloseAudioUnit(wwi->audioUnit))
2061 ERR("Can't close AudioUnit\n");
2064 OSSpinLockLock(&wwi->lock);
2065 assert(wwi->state == WINE_WS_CLOSING);
2067 /* Dellocate our audio buffers */
2068 widHelper_DestroyAudioBufferList(wwi->bufferList);
2069 wwi->bufferList = NULL;
2070 HeapFree(GetProcessHeap(), 0, wwi->bufferListCopy);
2071 wwi->bufferListCopy = NULL;
2073 wwi->audioUnit = NULL;
2074 wwi->state = WINE_WS_CLOSED;
2075 OSSpinLockUnlock(&wwi->lock);
2077 ret = widNotifyClient(wwi, WIM_CLOSE, 0L, 0L);
2083 /**************************************************************************
2084 * widAddBuffer [internal]
2086 static DWORD widAddBuffer(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
2088 DWORD ret = MMSYSERR_NOERROR;
2091 TRACE("(%u, %p, %08X);\n", wDevID, lpWaveHdr, dwSize);
2093 if (wDevID >= MAX_WAVEINDRV)
2095 WARN("invalid device ID\n");
2096 return MMSYSERR_INVALHANDLE;
2098 if (!(lpWaveHdr->dwFlags & WHDR_PREPARED))
2100 TRACE("never been prepared !\n");
2101 return WAVERR_UNPREPARED;
2103 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
2105 TRACE("header already in use !\n");
2106 return WAVERR_STILLPLAYING;
2109 wwi = &WInDev[wDevID];
2110 OSSpinLockLock(&wwi->lock);
2112 if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2114 WARN("Trying to add buffer to closed device.\n");
2115 ret = MMSYSERR_INVALHANDLE;
2121 lpWaveHdr->dwFlags |= WHDR_INQUEUE;
2122 lpWaveHdr->dwFlags &= ~WHDR_DONE;
2123 lpWaveHdr->dwBytesRecorded = 0;
2124 lpWaveHdr->lpNext = NULL;
2126 /* insert buffer at end of queue */
2127 for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext))
2132 OSSpinLockUnlock(&wwi->lock);
2138 /**************************************************************************
2139 * widStart [internal]
2141 static DWORD widStart(WORD wDevID)
2143 DWORD ret = MMSYSERR_NOERROR;
2146 TRACE("(%u);\n", wDevID);
2147 if (wDevID >= MAX_WAVEINDRV)
2149 WARN("invalid device ID\n");
2150 return MMSYSERR_INVALHANDLE;
2153 /* The order of the following operations is important since we can't hold
2154 * the mutex while we make an Audio Unit call. Set the PLAYING state
2155 * before starting the Audio Unit. In widStop, the order is reversed.
2156 * This guarantees that we can't get into a situation where the state is
2157 * PLAYING but the Audio Unit isn't running. Although we can be in STOPPED
2158 * state with the Audio Unit still running, that's harmless because the
2159 * input callback will just throw away the sound data.
2161 wwi = &WInDev[wDevID];
2162 OSSpinLockLock(&wwi->lock);
2164 if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2166 WARN("Trying to start closed device.\n");
2167 ret = MMSYSERR_INVALHANDLE;
2170 wwi->state = WINE_WS_PLAYING;
2172 OSSpinLockUnlock(&wwi->lock);
2174 if (ret == MMSYSERR_NOERROR)
2176 /* Start pulling for audio data */
2177 OSStatus err = AudioOutputUnitStart(wwi->audioUnit);
2179 ERR("Failed to start AU: %08lx\n", err);
2181 TRACE("Recording started...\n");
2188 /**************************************************************************
2189 * widStop [internal]
2191 static DWORD widStop(WORD wDevID)
2193 DWORD ret = MMSYSERR_NOERROR;
2195 WAVEHDR* lpWaveHdr = NULL;
2198 TRACE("(%u);\n", wDevID);
2199 if (wDevID >= MAX_WAVEINDRV)
2201 WARN("invalid device ID\n");
2202 return MMSYSERR_INVALHANDLE;
2205 wwi = &WInDev[wDevID];
2207 /* The order of the following operations is important since we can't hold
2208 * the mutex while we make an Audio Unit call. Stop the Audio Unit before
2209 * setting the STOPPED state. In widStart, the order is reversed. This
2210 * guarantees that we can't get into a situation where the state is
2211 * PLAYING but the Audio Unit isn't running. Although we can be in STOPPED
2212 * state with the Audio Unit still running, that's harmless because the
2213 * input callback will just throw away the sound data.
2215 err = AudioOutputUnitStop(wwi->audioUnit);
2217 WARN("Failed to stop AU: %08lx\n", err);
2219 TRACE("Recording stopped.\n");
2221 OSSpinLockLock(&wwi->lock);
2223 if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2225 WARN("Trying to stop closed device.\n");
2226 ret = MMSYSERR_INVALHANDLE;
2228 else if (wwi->state != WINE_WS_STOPPED)
2230 wwi->state = WINE_WS_STOPPED;
2231 /* If there's a buffer in progress, it's done. Remove it from the
2232 * queue so that we can return it to the app, below. */
2233 if (wwi->lpQueuePtr)
2235 lpWaveHdr = wwi->lpQueuePtr;
2236 wwi->lpQueuePtr = lpWaveHdr->lpNext;
2240 OSSpinLockUnlock(&wwi->lock);
2244 lpWaveHdr->lpNext = NULL;
2245 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2246 lpWaveHdr->dwFlags |= WHDR_DONE;
2247 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2253 /**************************************************************************
2254 * widGetPos [internal]
2256 static DWORD widGetPos(WORD wDevID, LPMMTIME lpTime, UINT size)
2261 TRACE("(%u);\n", wDevID);
2262 if (wDevID >= MAX_WAVEINDRV)
2264 WARN("invalid device ID\n");
2265 return MMSYSERR_INVALHANDLE;
2268 wwi = &WInDev[wDevID];
2270 OSSpinLockLock(&WInDev[wDevID].lock);
2271 val = wwi->dwTotalRecorded;
2272 OSSpinLockUnlock(&WInDev[wDevID].lock);
2274 return bytes_to_mmtime(lpTime, val, &wwi->format);
2277 /**************************************************************************
2278 * widReset [internal]
2280 static DWORD widReset(WORD wDevID)
2282 DWORD ret = MMSYSERR_NOERROR;
2284 WAVEHDR* lpWaveHdr = NULL;
2286 TRACE("(%u);\n", wDevID);
2287 if (wDevID >= MAX_WAVEINDRV)
2289 WARN("invalid device ID\n");
2290 return MMSYSERR_INVALHANDLE;
2293 wwi = &WInDev[wDevID];
2294 OSSpinLockLock(&wwi->lock);
2296 if (wwi->state == WINE_WS_CLOSED || wwi->state == WINE_WS_CLOSING)
2298 WARN("Trying to reset a closed device.\n");
2299 ret = MMSYSERR_INVALHANDLE;
2303 lpWaveHdr = wwi->lpQueuePtr;
2304 wwi->lpQueuePtr = NULL;
2305 wwi->state = WINE_WS_STOPPED;
2306 wwi->dwTotalRecorded = 0;
2309 OSSpinLockUnlock(&wwi->lock);
2311 if (ret == MMSYSERR_NOERROR)
2313 OSStatus err = AudioOutputUnitStop(wwi->audioUnit);
2315 WARN("Failed to stop AU: %08lx\n", err);
2317 TRACE("Recording stopped.\n");
2322 WAVEHDR* lpNext = lpWaveHdr->lpNext;
2324 lpWaveHdr->lpNext = NULL;
2325 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2326 lpWaveHdr->dwFlags |= WHDR_DONE;
2327 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2336 /**************************************************************************
2337 * widGetNumDevs [internal]
2339 static DWORD widGetNumDevs(void)
2341 return MAX_WAVEINDRV;
2345 /**************************************************************************
2346 * widDevInterfaceSize [internal]
2348 static DWORD widDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
2350 TRACE("(%u, %p)\n", wDevID, dwParam1);
2352 *dwParam1 = MultiByteToWideChar(CP_UNIXCP, 0, WInDev[wDevID].interface_name, -1,
2353 NULL, 0 ) * sizeof(WCHAR);
2354 return MMSYSERR_NOERROR;
2358 /**************************************************************************
2359 * widDevInterface [internal]
2361 static DWORD widDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
2363 if (dwParam2 >= MultiByteToWideChar(CP_UNIXCP, 0, WInDev[wDevID].interface_name, -1,
2364 NULL, 0 ) * sizeof(WCHAR))
2366 MultiByteToWideChar(CP_UNIXCP, 0, WInDev[wDevID].interface_name, -1,
2367 dwParam1, dwParam2 / sizeof(WCHAR));
2368 return MMSYSERR_NOERROR;
2370 return MMSYSERR_INVALPARAM;
2374 /**************************************************************************
2375 * widDsCreate [internal]
2377 static DWORD widDsCreate(UINT wDevID, PIDSCDRIVER* drv)
2379 TRACE("(%d,%p)\n",wDevID,drv);
2381 FIXME("DirectSoundCapture not implemented\n");
2382 FIXME("The (slower) DirectSound HEL mode will be used instead.\n");
2383 return MMSYSERR_NOTSUPPORTED;
2386 /**************************************************************************
2387 * widDsDesc [internal]
2389 static DWORD widDsDesc(UINT wDevID, PDSDRIVERDESC desc)
2391 /* The DirectSound HEL will automatically wrap a non-DirectSound-capable
2392 * driver in a DirectSound adaptor, thus allowing the driver to be used by
2393 * DirectSound clients. However, it only does this if we respond
2394 * successfully to the DRV_QUERYDSOUNDDESC message. It's enough to fill in
2395 * the driver and device names of the description output parameter. */
2396 memset(desc, 0, sizeof(*desc));
2397 lstrcpynA(desc->szDrvname, "winecoreaudio.drv", sizeof(desc->szDrvname) - 1);
2398 lstrcpynA(desc->szDesc, WInDev[wDevID].interface_name, sizeof(desc->szDesc) - 1);
2399 return MMSYSERR_NOERROR;
2403 /**************************************************************************
2404 * widMessage (WINECOREAUDIO.6)
2406 DWORD WINAPI CoreAudio_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2407 DWORD dwParam1, DWORD dwParam2)
2409 TRACE("(%u, %04X, %08X, %08X, %08X);\n",
2410 wDevID, wMsg, dwUser, dwParam1, dwParam2);
2418 /* FIXME: Pretend this is supported */
2420 case WIDM_OPEN: return widOpen (wDevID, (LPWAVEOPENDESC)dwParam1, dwParam2);
2421 case WIDM_CLOSE: return widClose (wDevID);
2422 case WIDM_ADDBUFFER: return widAddBuffer (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2423 case WIDM_PREPARE: return MMSYSERR_NOTSUPPORTED;
2424 case WIDM_UNPREPARE: return MMSYSERR_NOTSUPPORTED;
2425 case WIDM_GETDEVCAPS: return widGetDevCaps (wDevID, (LPWAVEINCAPSW)dwParam1, dwParam2);
2426 case WIDM_GETNUMDEVS: return widGetNumDevs ();
2427 case WIDM_RESET: return widReset (wDevID);
2428 case WIDM_START: return widStart (wDevID);
2429 case WIDM_STOP: return widStop (wDevID);
2430 case WIDM_GETPOS: return widGetPos (wDevID, (LPMMTIME)dwParam1, (UINT)dwParam2 );
2431 case DRV_QUERYDEVICEINTERFACESIZE: return widDevInterfaceSize (wDevID, (LPDWORD)dwParam1);
2432 case DRV_QUERYDEVICEINTERFACE: return widDevInterface (wDevID, (PWCHAR)dwParam1, dwParam2);
2433 case DRV_QUERYDSOUNDIFACE: return widDsCreate (wDevID, (PIDSCDRIVER*)dwParam1);
2434 case DRV_QUERYDSOUNDDESC: return widDsDesc (wDevID, (PDSDRIVERDESC)dwParam1);
2436 FIXME("unknown message %d!\n", wMsg);
2439 return MMSYSERR_NOTSUPPORTED;
2443 OSStatus CoreAudio_wiAudioUnitIOProc(void *inRefCon,
2444 AudioUnitRenderActionFlags *ioActionFlags,
2445 const AudioTimeStamp *inTimeStamp,
2447 UInt32 inNumberFrames,
2448 AudioBufferList *ioData)
2450 WINE_WAVEIN* wwi = (WINE_WAVEIN*)inRefCon;
2451 OSStatus err = noErr;
2452 BOOL needNotify = FALSE;
2453 WAVEHDR* lpStorePtr;
2454 unsigned int dataToStore;
2455 unsigned int dataStored = 0;
2459 fprintf(stderr, "trace:wave:CoreAudio_wiAudioUnitIOProc (ioActionFlags = %08lx, "
2460 "inTimeStamp = { %f, %x%08x, %f, %x%08x, %08lx }, inBusNumber = %lu, inNumberFrames = %lu)\n",
2461 *ioActionFlags, inTimeStamp->mSampleTime, (DWORD)(inTimeStamp->mHostTime >>32),
2462 (DWORD)inTimeStamp->mHostTime, inTimeStamp->mRateScalar, (DWORD)(inTimeStamp->mWordClockTime >> 32),
2463 (DWORD)inTimeStamp->mWordClockTime, inTimeStamp->mFlags, inBusNumber, inNumberFrames);
2465 /* Render into audio buffer */
2466 /* FIXME: implement sample rate conversion on input. This will require
2467 * a different render strategy. We'll need to buffer the sound data
2468 * received here and pass it off to an AUConverter in another thread. */
2469 err = AudioUnitRender(wwi->audioUnit, ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, wwi->bufferList);
2473 fprintf(stderr, "err:wave:CoreAudio_wiAudioUnitIOProc AudioUnitRender failed with error %li\n", err);
2477 /* Copy from audio buffer to the wavehdrs */
2478 dataToStore = wwi->bufferList->mBuffers[0].mDataByteSize;
2480 OSSpinLockLock(&wwi->lock);
2482 lpStorePtr = wwi->lpQueuePtr;
2484 /* We might have been called while the waveIn device is being closed in
2485 * widClose. We have to do nothing in that case. The check of wwi->state
2486 * below ensures that. */
2487 while (dataToStore > 0 && wwi->state == WINE_WS_PLAYING && lpStorePtr)
2489 unsigned int room = lpStorePtr->dwBufferLength - lpStorePtr->dwBytesRecorded;
2490 unsigned int toCopy;
2493 fprintf(stderr, "trace:wave:CoreAudio_wiAudioUnitIOProc Looking to store %u bytes to wavehdr %p, which has room for %u\n",
2494 dataToStore, lpStorePtr, room);
2496 if (room >= dataToStore)
2497 toCopy = dataToStore;
2503 memcpy(lpStorePtr->lpData + lpStorePtr->dwBytesRecorded,
2504 (char*)wwi->bufferList->mBuffers[0].mData + dataStored, toCopy);
2505 lpStorePtr->dwBytesRecorded += toCopy;
2506 wwi->dwTotalRecorded += toCopy;
2507 dataStored += toCopy;
2508 dataToStore -= toCopy;
2514 lpStorePtr = lpStorePtr->lpNext;
2519 OSSpinLockUnlock(&wwi->lock);
2521 /* Restore the audio buffer list structure from backup, in case
2522 * AudioUnitRender clobbered it. (It modifies mDataByteSize and may even
2523 * give us a different mData buffer to avoid a copy.) */
2524 memcpy(wwi->bufferList, wwi->bufferListCopy, AUDIOBUFFERLISTSIZE(wwi->bufferList->mNumberBuffers));
2526 if (needNotify) wodSendNotifyInputCompletionsMessage(wwi);
2532 /**************************************************************************
2533 * widMessage (WINECOREAUDIO.6)
2535 DWORD WINAPI CoreAudio_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2536 DWORD dwParam1, DWORD dwParam2)
2538 FIXME("(%u, %04X, %08X, %08X, %08X): CoreAudio support not compiled into wine\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2539 return MMSYSERR_NOTENABLED;
2542 /**************************************************************************
2543 * wodMessage (WINECOREAUDIO.7)
2545 DWORD WINAPI CoreAudio_wodMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2546 DWORD dwParam1, DWORD dwParam2)
2548 FIXME("(%u, %04X, %08X, %08X, %08X): CoreAudio support not compiled into wine\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2549 return MMSYSERR_NOTENABLED;