Changes in crossover-wine-src-6.1.0 except for configure
[wine/hacks.git] / dlls / winecoreaudio.drv / audio.c
blob670fab4e7d6975e0c6fc355ba3e4510f437a116c
1 /*
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
25 #include "config.h"
27 #include <stdlib.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <string.h>
31 #ifdef HAVE_UNISTD_H
32 # include <unistd.h>
33 #endif
34 #include <fcntl.h>
36 #include "windef.h"
37 #include "winbase.h"
38 #include "winnls.h"
39 #include "wingdi.h"
40 #include "winerror.h"
41 #include "mmddk.h"
42 #include "dsound.h"
43 #include "dsdriver.h"
44 #include "coreaudio.h"
45 #include "wine/unicode.h"
46 #include "wine/library.h"
47 #include "wine/debug.h"
49 WINE_DEFAULT_DEBUG_CHANNEL(wave);
52 #if defined(HAVE_COREAUDIO_COREAUDIO_H) && defined(HAVE_AUDIOUNIT_AUDIOUNIT_H)
53 #include <CoreAudio/CoreAudio.h>
54 #include <CoreFoundation/CoreFoundation.h>
55 #include <libkern/OSAtomic.h>
57 WINE_DECLARE_DEBUG_CHANNEL(coreaudio);
60 Due to AudioUnit headers conflict define some needed types.
63 typedef void *AudioUnit;
65 /* From AudioUnit/AUComponents.h */
66 enum
68 kAudioUnitRenderAction_OutputIsSilence = (1 << 4),
69 /* provides hint on return from Render(): if set the buffer contains all zeroes */
71 typedef UInt32 AudioUnitRenderActionFlags;
73 typedef long ComponentResult;
74 extern ComponentResult
75 AudioUnitRender( AudioUnit ci,
76 AudioUnitRenderActionFlags * ioActionFlags,
77 const AudioTimeStamp * inTimeStamp,
78 UInt32 inOutputBusNumber,
79 UInt32 inNumberFrames,
80 AudioBufferList * ioData) AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER;
82 /* only allow 10 output devices through this driver, this ought to be adequate */
83 #define MAX_WAVEOUTDRV (1)
84 #define MAX_WAVEINDRV (1)
86 /* state diagram for waveOut writing:
88 * +---------+-------------+---------------+---------------------------------+
89 * | state | function | event | new state |
90 * +---------+-------------+---------------+---------------------------------+
91 * | | open() | | STOPPED |
92 * | PAUSED | write() | | PAUSED |
93 * | STOPPED | write() | <thrd create> | PLAYING |
94 * | PLAYING | write() | HEADER | PLAYING |
95 * | (other) | write() | <error> | |
96 * | (any) | pause() | PAUSING | PAUSED |
97 * | PAUSED | restart() | RESTARTING | PLAYING (if no thrd => STOPPED) |
98 * | (any) | reset() | RESETTING | STOPPED |
99 * | (any) | close() | CLOSING | CLOSED |
100 * +---------+-------------+---------------+---------------------------------+
103 /* states of the playing device */
104 #define WINE_WS_PLAYING 0
105 #define WINE_WS_PAUSED 1
106 #define WINE_WS_STOPPED 2
107 #define WINE_WS_CLOSED 3
109 typedef struct tagCoreAudio_Device {
110 char dev_name[32];
111 char mixer_name[32];
112 unsigned open_count;
113 char* interface_name;
115 WAVEOUTCAPSW out_caps;
116 WAVEINCAPSW in_caps;
117 DWORD in_caps_support;
118 int sample_rate;
119 int stereo;
120 int format;
121 unsigned audio_fragment;
122 BOOL full_duplex;
123 BOOL bTriggerSupport;
124 BOOL bOutputEnabled;
125 BOOL bInputEnabled;
126 DSDRIVERDESC ds_desc;
127 DSDRIVERCAPS ds_caps;
128 DSCDRIVERCAPS dsc_caps;
129 GUID ds_guid;
130 GUID dsc_guid;
132 AudioDeviceID outputDeviceID;
133 AudioDeviceID inputDeviceID;
134 AudioStreamBasicDescription streamDescription;
135 } CoreAudio_Device;
137 /* for now use the default device */
138 static CoreAudio_Device CoreAudio_DefaultDevice;
140 typedef struct {
141 volatile int state; /* one of the WINE_WS_ manifest constants */
142 CoreAudio_Device *cadev;
143 WAVEOPENDESC waveDesc;
144 WORD wFlags;
145 PCMWAVEFORMAT format;
146 DWORD woID;
147 AudioUnit audioUnit;
148 AudioStreamBasicDescription streamDescription;
150 WAVEOUTCAPSW caps;
151 char interface_name[32];
152 LPWAVEHDR lpQueuePtr; /* start of queued WAVEHDRs (waiting to be notified) */
153 LPWAVEHDR lpPlayPtr; /* start of not yet fully played buffers */
154 DWORD dwPartialOffset; /* Offset of not yet written bytes in lpPlayPtr */
156 LPWAVEHDR lpLoopPtr; /* pointer of first buffer in loop, if any */
157 DWORD dwLoops; /* private copy of loop counter */
159 DWORD dwPlayedTotal; /* number of bytes actually played since opening */
160 DWORD dwWrittenTotal; /* number of bytes written to OSS buffer since opening */
162 DWORD tickCountMS; /* time in MS of last AudioUnit callback */
164 OSSpinLock lock; /* synchronization stuff */
166 BOOL trace_on;
167 BOOL warn_on;
168 BOOL err_on;
169 } WINE_WAVEOUT;
171 typedef struct {
172 /* This device's device number */
173 DWORD wiID;
175 /* Access to the following fields is synchronized across threads. */
176 volatile int state;
177 LPWAVEHDR lpQueuePtr;
178 DWORD dwTotalRecorded;
180 /* Synchronization mechanism to protect above fields */
181 OSSpinLock lock;
183 /* Capabilities description */
184 WAVEINCAPSW caps;
185 char interface_name[32];
187 /* Record the arguments used when opening the device. */
188 WAVEOPENDESC waveDesc;
189 WORD wFlags;
190 PCMWAVEFORMAT format;
192 AudioUnit audioUnit;
193 AudioBufferList*bufferList;
195 /* Record state of debug channels at open. Used to control fprintf's since
196 * we can't use Wine debug channel calls in non-Wine AudioUnit threads. */
197 BOOL trace_on;
198 BOOL warn_on;
199 BOOL err_on;
201 /* These fields aren't used. */
202 #if 0
203 CoreAudio_Device *cadev;
205 AudioStreamBasicDescription streamDescription;
206 #endif
207 } WINE_WAVEIN;
209 static WINE_WAVEOUT WOutDev [MAX_WAVEOUTDRV];
210 static WINE_WAVEIN WInDev [MAX_WAVEINDRV];
212 static HANDLE hThread = NULL; /* Track the thread we create so we can clean it up later */
213 static CFMessagePortRef Port_SendToMessageThread;
215 static void wodHelper_PlayPtrNext(WINE_WAVEOUT* wwo);
216 static void wodHelper_NotifyCompletions(WINE_WAVEOUT* wwo, BOOL force);
217 static void widHelper_NotifyCompletions(WINE_WAVEIN* wwi);
219 extern int AudioUnit_CreateDefaultAudioUnit(void *wwo, AudioUnit *au);
220 extern int AudioUnit_CloseAudioUnit(AudioUnit au);
221 extern int AudioUnit_InitializeWithStreamDescription(AudioUnit au, AudioStreamBasicDescription *streamFormat);
223 extern OSStatus AudioOutputUnitStart(AudioUnit au);
224 extern OSStatus AudioOutputUnitStop(AudioUnit au);
225 extern OSStatus AudioUnitUninitialize(AudioUnit au);
227 extern int AudioUnit_SetVolume(AudioUnit au, float left, float right);
228 extern int AudioUnit_GetVolume(AudioUnit au, float *left, float *right);
230 extern int AudioUnit_GetInputDeviceSampleRate(void);
232 extern int AudioUnit_CreateInputUnit(void* wwi, AudioUnit* out_au,
233 WORD nChannels, DWORD nSamplesPerSec, WORD wBitsPerSample,
234 UInt32* outFrameCount);
236 OSStatus CoreAudio_woAudioUnitIOProc(void *inRefCon,
237 AudioUnitRenderActionFlags *ioActionFlags,
238 const AudioTimeStamp *inTimeStamp,
239 UInt32 inBusNumber,
240 UInt32 inNumberFrames,
241 AudioBufferList *ioData);
242 OSStatus CoreAudio_wiAudioUnitIOProc(void *inRefCon,
243 AudioUnitRenderActionFlags *ioActionFlags,
244 const AudioTimeStamp *inTimeStamp,
245 UInt32 inBusNumber,
246 UInt32 inNumberFrames,
247 AudioBufferList *ioData);
249 /* These strings used only for tracing */
251 static const char * getMessage(UINT msg)
253 static char unknown[32];
254 #define MSG_TO_STR(x) case x: return #x
255 switch(msg) {
256 MSG_TO_STR(DRVM_INIT);
257 MSG_TO_STR(DRVM_EXIT);
258 MSG_TO_STR(DRVM_ENABLE);
259 MSG_TO_STR(DRVM_DISABLE);
260 MSG_TO_STR(WIDM_OPEN);
261 MSG_TO_STR(WIDM_CLOSE);
262 MSG_TO_STR(WIDM_ADDBUFFER);
263 MSG_TO_STR(WIDM_PREPARE);
264 MSG_TO_STR(WIDM_UNPREPARE);
265 MSG_TO_STR(WIDM_GETDEVCAPS);
266 MSG_TO_STR(WIDM_GETNUMDEVS);
267 MSG_TO_STR(WIDM_GETPOS);
268 MSG_TO_STR(WIDM_RESET);
269 MSG_TO_STR(WIDM_START);
270 MSG_TO_STR(WIDM_STOP);
271 MSG_TO_STR(WODM_OPEN);
272 MSG_TO_STR(WODM_CLOSE);
273 MSG_TO_STR(WODM_WRITE);
274 MSG_TO_STR(WODM_PAUSE);
275 MSG_TO_STR(WODM_GETPOS);
276 MSG_TO_STR(WODM_BREAKLOOP);
277 MSG_TO_STR(WODM_PREPARE);
278 MSG_TO_STR(WODM_UNPREPARE);
279 MSG_TO_STR(WODM_GETDEVCAPS);
280 MSG_TO_STR(WODM_GETNUMDEVS);
281 MSG_TO_STR(WODM_GETPITCH);
282 MSG_TO_STR(WODM_SETPITCH);
283 MSG_TO_STR(WODM_GETPLAYBACKRATE);
284 MSG_TO_STR(WODM_SETPLAYBACKRATE);
285 MSG_TO_STR(WODM_GETVOLUME);
286 MSG_TO_STR(WODM_SETVOLUME);
287 MSG_TO_STR(WODM_RESTART);
288 MSG_TO_STR(WODM_RESET);
289 MSG_TO_STR(DRV_QUERYDEVICEINTERFACESIZE);
290 MSG_TO_STR(DRV_QUERYDEVICEINTERFACE);
291 MSG_TO_STR(DRV_QUERYDSOUNDIFACE);
292 MSG_TO_STR(DRV_QUERYDSOUNDDESC);
294 #undef MSG_TO_STR
295 sprintf(unknown, "UNKNOWN(0x%04x)", msg);
296 return unknown;
299 #define kStopLoopMessage 0
300 #define kWaveOutNotifyCompletionsMessage 1
301 #define kWaveInNotifyCompletionsMessage 2
303 /* Mach Message Handling */
304 static CFDataRef wodMessageHandler(CFMessagePortRef port_ReceiveInMessageThread, SInt32 msgid, CFDataRef data, void *info)
306 UInt32 *buffer = NULL;
308 switch (msgid)
310 case kWaveOutNotifyCompletionsMessage:
311 buffer = (UInt32 *) CFDataGetBytePtr(data);
312 wodHelper_NotifyCompletions(&WOutDev[buffer[0]], FALSE);
313 break;
314 case kWaveInNotifyCompletionsMessage:
315 buffer = (UInt32 *) CFDataGetBytePtr(data);
316 widHelper_NotifyCompletions(&WInDev[buffer[0]]);
317 break;
318 default:
319 CFRunLoopStop(CFRunLoopGetCurrent());
320 break;
323 return NULL;
326 static DWORD WINAPI messageThread(LPVOID p)
328 CFMessagePortRef port_ReceiveInMessageThread = (CFMessagePortRef) p;
329 CFRunLoopSourceRef source;
331 source = CFMessagePortCreateRunLoopSource(kCFAllocatorDefault, port_ReceiveInMessageThread, (CFIndex)0);
332 CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
334 CFRunLoopRun();
336 CFRunLoopSourceInvalidate(source);
337 CFRelease(source);
338 CFRelease(port_ReceiveInMessageThread);
340 return 0;
343 /**************************************************************************
344 * wodSendNotifyCompletionsMessage [internal]
345 * Call from AudioUnit IO thread can't use Wine debug channels.
347 static void wodSendNotifyCompletionsMessage(WINE_WAVEOUT* wwo)
349 CFDataRef data;
350 UInt32 buffer;
352 buffer = (UInt32) wwo->woID;
354 data = CFDataCreate(kCFAllocatorDefault, (UInt8 *)&buffer, sizeof(buffer));
355 if (!data)
356 return;
358 CFMessagePortSendRequest(Port_SendToMessageThread, kWaveOutNotifyCompletionsMessage, data, 0.0, 0.0, NULL, NULL);
359 CFRelease(data);
362 /**************************************************************************
363 * wodSendNotifyInputCompletionsMessage [internal]
364 * Call from AudioUnit IO thread can't use Wine debug channels.
366 static void wodSendNotifyInputCompletionsMessage(WINE_WAVEIN* wwi)
368 CFDataRef data;
369 UInt32 buffer;
371 buffer = (UInt32) wwi->wiID;
373 data = CFDataCreate(kCFAllocatorDefault, (UInt8 *)&buffer, sizeof(buffer));
374 if (!data)
375 return;
377 CFMessagePortSendRequest(Port_SendToMessageThread, kWaveInNotifyCompletionsMessage, data, 0.0, 0.0, NULL, NULL);
378 CFRelease(data);
381 static DWORD bytes_to_mmtime(LPMMTIME lpTime, DWORD position,
382 PCMWAVEFORMAT* format)
384 TRACE("wType=%04X wBitsPerSample=%u nSamplesPerSec=%u nChannels=%u nAvgBytesPerSec=%u\n",
385 lpTime->wType, format->wBitsPerSample, format->wf.nSamplesPerSec,
386 format->wf.nChannels, format->wf.nAvgBytesPerSec);
387 TRACE("Position in bytes=%u\n", position);
389 switch (lpTime->wType) {
390 case TIME_SAMPLES:
391 lpTime->u.sample = position / (format->wBitsPerSample / 8 * format->wf.nChannels);
392 TRACE("TIME_SAMPLES=%u\n", lpTime->u.sample);
393 break;
394 case TIME_MS:
395 lpTime->u.ms = 1000.0 * position / (format->wBitsPerSample / 8 * format->wf.nChannels * format->wf.nSamplesPerSec);
396 TRACE("TIME_MS=%u\n", lpTime->u.ms);
397 break;
398 case TIME_SMPTE:
399 lpTime->u.smpte.fps = 30;
400 position = position / (format->wBitsPerSample / 8 * format->wf.nChannels);
401 position += (format->wf.nSamplesPerSec / lpTime->u.smpte.fps) - 1; /* round up */
402 lpTime->u.smpte.sec = position / format->wf.nSamplesPerSec;
403 position -= lpTime->u.smpte.sec * format->wf.nSamplesPerSec;
404 lpTime->u.smpte.min = lpTime->u.smpte.sec / 60;
405 lpTime->u.smpte.sec -= 60 * lpTime->u.smpte.min;
406 lpTime->u.smpte.hour = lpTime->u.smpte.min / 60;
407 lpTime->u.smpte.min -= 60 * lpTime->u.smpte.hour;
408 lpTime->u.smpte.fps = 30;
409 lpTime->u.smpte.frame = position * lpTime->u.smpte.fps / format->wf.nSamplesPerSec;
410 TRACE("TIME_SMPTE=%02u:%02u:%02u:%02u\n",
411 lpTime->u.smpte.hour, lpTime->u.smpte.min,
412 lpTime->u.smpte.sec, lpTime->u.smpte.frame);
413 break;
414 default:
415 WARN("Format %d not supported, using TIME_BYTES !\n", lpTime->wType);
416 lpTime->wType = TIME_BYTES;
417 /* fall through */
418 case TIME_BYTES:
419 lpTime->u.cb = position;
420 TRACE("TIME_BYTES=%u\n", lpTime->u.cb);
421 break;
423 return MMSYSERR_NOERROR;
426 /**************************************************************************
427 * CoreAudio_GetDevCaps [internal]
429 BOOL CoreAudio_GetDevCaps (void)
431 OSStatus status;
432 UInt32 propertySize;
433 AudioDeviceID devId = CoreAudio_DefaultDevice.outputDeviceID;
435 char name[MAXPNAMELEN];
437 propertySize = MAXPNAMELEN;
438 status = AudioDeviceGetProperty(devId, 0 , FALSE, kAudioDevicePropertyDeviceName, &propertySize, name);
439 if (status) {
440 ERR("AudioHardwareGetProperty for kAudioDevicePropertyDeviceName return %c%c%c%c\n", (char) (status >> 24),
441 (char) (status >> 16),
442 (char) (status >> 8),
443 (char) status);
444 return FALSE;
447 memcpy(CoreAudio_DefaultDevice.ds_desc.szDesc, name, sizeof(name));
448 strcpy(CoreAudio_DefaultDevice.ds_desc.szDrvname, "winecoreaudio.drv");
449 MultiByteToWideChar(CP_ACP, 0, name, sizeof(name),
450 CoreAudio_DefaultDevice.out_caps.szPname,
451 sizeof(CoreAudio_DefaultDevice.out_caps.szPname) / sizeof(WCHAR));
452 memcpy(CoreAudio_DefaultDevice.dev_name, name, 32);
454 propertySize = sizeof(CoreAudio_DefaultDevice.streamDescription);
455 status = AudioDeviceGetProperty(devId, 0, FALSE , kAudioDevicePropertyStreamFormat, &propertySize, &CoreAudio_DefaultDevice.streamDescription);
456 if (status != noErr) {
457 ERR("AudioHardwareGetProperty for kAudioDevicePropertyStreamFormat return %c%c%c%c\n", (char) (status >> 24),
458 (char) (status >> 16),
459 (char) (status >> 8),
460 (char) status);
461 return FALSE;
464 TRACE("Device Stream Description mSampleRate : %f\n mFormatID : %c%c%c%c\n"
465 "mFormatFlags : %lX\n mBytesPerPacket : %lu\n mFramesPerPacket : %lu\n"
466 "mBytesPerFrame : %lu\n mChannelsPerFrame : %lu\n mBitsPerChannel : %lu\n",
467 CoreAudio_DefaultDevice.streamDescription.mSampleRate,
468 (char) (CoreAudio_DefaultDevice.streamDescription.mFormatID >> 24),
469 (char) (CoreAudio_DefaultDevice.streamDescription.mFormatID >> 16),
470 (char) (CoreAudio_DefaultDevice.streamDescription.mFormatID >> 8),
471 (char) CoreAudio_DefaultDevice.streamDescription.mFormatID,
472 CoreAudio_DefaultDevice.streamDescription.mFormatFlags,
473 CoreAudio_DefaultDevice.streamDescription.mBytesPerPacket,
474 CoreAudio_DefaultDevice.streamDescription.mFramesPerPacket,
475 CoreAudio_DefaultDevice.streamDescription.mBytesPerFrame,
476 CoreAudio_DefaultDevice.streamDescription.mChannelsPerFrame,
477 CoreAudio_DefaultDevice.streamDescription.mBitsPerChannel);
479 CoreAudio_DefaultDevice.out_caps.wMid = 0xcafe;
480 CoreAudio_DefaultDevice.out_caps.wPid = 0x0001;
482 CoreAudio_DefaultDevice.out_caps.vDriverVersion = 0x0001;
483 CoreAudio_DefaultDevice.out_caps.dwFormats = 0x00000000;
484 CoreAudio_DefaultDevice.out_caps.wReserved1 = 0;
485 CoreAudio_DefaultDevice.out_caps.dwSupport = WAVECAPS_VOLUME;
486 CoreAudio_DefaultDevice.out_caps.dwSupport |= WAVECAPS_LRVOLUME;
488 CoreAudio_DefaultDevice.out_caps.wChannels = 2;
489 CoreAudio_DefaultDevice.out_caps.dwFormats|= WAVE_FORMAT_4S16;
491 TRACE_(coreaudio)("out dwFormats = %08x, dwSupport = %08x\n",
492 CoreAudio_DefaultDevice.out_caps.dwFormats, CoreAudio_DefaultDevice.out_caps.dwSupport);
494 return TRUE;
497 /******************************************************************
498 * CoreAudio_WaveInit
500 * Initialize CoreAudio_DefaultDevice
502 LONG CoreAudio_WaveInit(void)
504 OSStatus status;
505 UInt32 propertySize;
506 CHAR szPname[MAXPNAMELEN];
507 int i;
508 CFStringRef messageThreadPortName;
509 CFMessagePortRef port_ReceiveInMessageThread;
510 int inputSampleRate;
512 TRACE("()\n");
514 /* number of sound cards */
515 AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &propertySize, NULL);
516 propertySize /= sizeof(AudioDeviceID);
517 TRACE("sound cards : %lu\n", propertySize);
519 /* Get the output device */
520 propertySize = sizeof(CoreAudio_DefaultDevice.outputDeviceID);
521 status = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &propertySize, &CoreAudio_DefaultDevice.outputDeviceID);
522 if (status) {
523 ERR("AudioHardwareGetProperty return %c%c%c%c for kAudioHardwarePropertyDefaultOutputDevice\n", (char) (status >> 24),
524 (char) (status >> 16),
525 (char) (status >> 8),
526 (char) status);
527 return 1;
529 if (CoreAudio_DefaultDevice.outputDeviceID == kAudioDeviceUnknown) {
530 ERR("AudioHardwareGetProperty: CoreAudio_DefaultDevice.outputDeviceID == kAudioDeviceUnknown\n");
531 return 1;
534 if ( ! CoreAudio_GetDevCaps() )
535 return 1;
537 CoreAudio_DefaultDevice.interface_name=HeapAlloc(GetProcessHeap(),0,strlen(CoreAudio_DefaultDevice.dev_name)+1);
538 sprintf(CoreAudio_DefaultDevice.interface_name, "%s", CoreAudio_DefaultDevice.dev_name);
540 for (i = 0; i < MAX_WAVEOUTDRV; ++i)
542 WOutDev[i].state = WINE_WS_CLOSED;
543 WOutDev[i].cadev = &CoreAudio_DefaultDevice;
544 WOutDev[i].woID = i;
546 memset(&WOutDev[i].caps, 0, sizeof(WOutDev[i].caps));
548 WOutDev[i].caps.wMid = 0xcafe; /* Manufac ID */
549 WOutDev[i].caps.wPid = 0x0001; /* Product ID */
550 snprintf(szPname, sizeof(szPname), "CoreAudio WaveOut %d", i);
551 MultiByteToWideChar(CP_ACP, 0, szPname, -1, WOutDev[i].caps.szPname, sizeof(WOutDev[i].caps.szPname)/sizeof(WCHAR));
552 snprintf(WOutDev[i].interface_name, sizeof(WOutDev[i].interface_name), "winecoreaudio: %d", i);
554 WOutDev[i].caps.vDriverVersion = 0x0001;
555 WOutDev[i].caps.dwFormats = 0x00000000;
556 WOutDev[i].caps.dwSupport = WAVECAPS_VOLUME;
558 WOutDev[i].caps.wChannels = 2;
559 /* WOutDev[i].caps.dwSupport |= WAVECAPS_LRVOLUME; */ /* FIXME */
561 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96M08;
562 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96S08;
563 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96M16;
564 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96S16;
565 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48M08;
566 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48S08;
567 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48M16;
568 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48S16;
569 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4M08;
570 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4S08;
571 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4S16;
572 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4M16;
573 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2M08;
574 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2S08;
575 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2M16;
576 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2S16;
577 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1M08;
578 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1S08;
579 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1M16;
580 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1S16;
582 WOutDev[i].lock = 0; /* initialize the mutex */
585 /* FIXME: implement sample rate conversion on input */
586 inputSampleRate = AudioUnit_GetInputDeviceSampleRate();
588 for (i = 0; i < MAX_WAVEINDRV; ++i)
590 memset(&WInDev[i], 0, sizeof(WInDev[i]));
591 WInDev[i].wiID = i;
593 /* Establish preconditions for widOpen */
594 WInDev[i].state = WINE_WS_CLOSED;
595 WInDev[i].lock = 0; /* initialize the mutex */
597 /* Fill in capabilities. widGetDevCaps can be called at any time. */
598 WInDev[i].caps.wMid = 0xcafe; /* Manufac ID */
599 WInDev[i].caps.wPid = 0x0001; /* Product ID */
600 WInDev[i].caps.vDriverVersion = 0x0001;
602 snprintf(szPname, sizeof(szPname), "CoreAudio WaveIn %d", i);
603 MultiByteToWideChar(CP_ACP, 0, szPname, -1, WInDev[i].caps.szPname, sizeof(WInDev[i].caps.szPname)/sizeof(WCHAR));
604 snprintf(WInDev[i].interface_name, sizeof(WInDev[i].interface_name), "winecoreaudio in: %d", i);
606 if (inputSampleRate == 96000)
608 WInDev[i].caps.dwFormats |= WAVE_FORMAT_96M08;
609 WInDev[i].caps.dwFormats |= WAVE_FORMAT_96S08;
610 WInDev[i].caps.dwFormats |= WAVE_FORMAT_96M16;
611 WInDev[i].caps.dwFormats |= WAVE_FORMAT_96S16;
613 if (inputSampleRate == 48000)
615 WInDev[i].caps.dwFormats |= WAVE_FORMAT_48M08;
616 WInDev[i].caps.dwFormats |= WAVE_FORMAT_48S08;
617 WInDev[i].caps.dwFormats |= WAVE_FORMAT_48M16;
618 WInDev[i].caps.dwFormats |= WAVE_FORMAT_48S16;
620 if (inputSampleRate == 44100)
622 WInDev[i].caps.dwFormats |= WAVE_FORMAT_4M08;
623 WInDev[i].caps.dwFormats |= WAVE_FORMAT_4S08;
624 WInDev[i].caps.dwFormats |= WAVE_FORMAT_4M16;
625 WInDev[i].caps.dwFormats |= WAVE_FORMAT_4S16;
627 if (inputSampleRate == 22050)
629 WInDev[i].caps.dwFormats |= WAVE_FORMAT_2M08;
630 WInDev[i].caps.dwFormats |= WAVE_FORMAT_2S08;
631 WInDev[i].caps.dwFormats |= WAVE_FORMAT_2M16;
632 WInDev[i].caps.dwFormats |= WAVE_FORMAT_2S16;
634 if (inputSampleRate == 11025)
636 WInDev[i].caps.dwFormats |= WAVE_FORMAT_1M08;
637 WInDev[i].caps.dwFormats |= WAVE_FORMAT_1S08;
638 WInDev[i].caps.dwFormats |= WAVE_FORMAT_1M16;
639 WInDev[i].caps.dwFormats |= WAVE_FORMAT_1S16;
642 WInDev[i].caps.wChannels = 2;
645 /* create mach messages handler */
646 srandomdev();
647 messageThreadPortName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL,
648 CFSTR("WaveMessagePort.%d.%lu"), getpid(), (unsigned long)random());
649 if (!messageThreadPortName)
651 ERR("Can't create message thread port name\n");
652 return 1;
655 port_ReceiveInMessageThread = CFMessagePortCreateLocal(kCFAllocatorDefault, messageThreadPortName,
656 &wodMessageHandler, NULL, NULL);
657 if (!port_ReceiveInMessageThread)
659 ERR("Can't create message thread local port\n");
660 CFRelease(messageThreadPortName);
661 return 1;
664 Port_SendToMessageThread = CFMessagePortCreateRemote(kCFAllocatorDefault, messageThreadPortName);
665 CFRelease(messageThreadPortName);
666 if (!Port_SendToMessageThread)
668 ERR("Can't create port for sending to message thread\n");
669 CFRelease(port_ReceiveInMessageThread);
670 return 1;
673 /* Cannot WAIT for any events because we are called from the loader (which has a lock on loading stuff) */
674 /* We might want to wait for this thread to be created -- but we cannot -- not here at least */
675 /* Instead track the thread so we can clean it up later */
676 if ( hThread )
678 ERR("Message thread already started -- expect problems\n");
680 hThread = CreateThread(NULL, 0, messageThread, (LPVOID)port_ReceiveInMessageThread, 0, NULL);
681 if ( !hThread )
683 ERR("Can't create message thread\n");
684 CFRelease(port_ReceiveInMessageThread);
685 CFRelease(Port_SendToMessageThread);
686 Port_SendToMessageThread = NULL;
687 return 1;
690 /* The message thread is responsible for releasing port_ReceiveInMessageThread. */
692 return 0;
695 void CoreAudio_WaveRelease(void)
697 /* Stop CFRunLoop in messageThread */
698 TRACE("()\n");
700 CFMessagePortSendRequest(Port_SendToMessageThread, kStopLoopMessage, NULL, 0.0, 0.0, NULL, NULL);
701 CFRelease(Port_SendToMessageThread);
702 Port_SendToMessageThread = NULL;
704 /* Wait for the thread to finish and clean it up */
705 /* This rids us of any quick start/shutdown driver crashes */
706 WaitForSingleObject(hThread, INFINITE);
707 CloseHandle(hThread);
708 hThread = NULL;
711 /*======================================================================*
712 * Low level WAVE OUT implementation *
713 *======================================================================*/
715 /**************************************************************************
716 * wodNotifyClient [internal]
718 static DWORD wodNotifyClient(WINE_WAVEOUT* wwo, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
720 TRACE_(coreaudio)("wMsg = 0x%04x dwParm1 = %04x dwParam2 = %04x\n", wMsg, dwParam1, dwParam2);
722 switch (wMsg) {
723 case WOM_OPEN:
724 case WOM_CLOSE:
725 case WOM_DONE:
726 if (wwo->wFlags != DCB_NULL &&
727 !DriverCallback(wwo->waveDesc.dwCallback, wwo->wFlags,
728 (HDRVR)wwo->waveDesc.hWave, wMsg, wwo->waveDesc.dwInstance,
729 dwParam1, dwParam2))
731 ERR("can't notify client !\n");
732 return MMSYSERR_ERROR;
734 break;
735 default:
736 ERR("Unknown callback message %u\n", wMsg);
737 return MMSYSERR_INVALPARAM;
739 return MMSYSERR_NOERROR;
743 /**************************************************************************
744 * wodGetDevCaps [internal]
746 static DWORD wodGetDevCaps(WORD wDevID, LPWAVEOUTCAPSW lpCaps, DWORD dwSize)
748 TRACE("(%u, %p, %u);\n", wDevID, lpCaps, dwSize);
750 if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
752 if (wDevID >= MAX_WAVEOUTDRV)
754 TRACE("MAX_WAVOUTDRV reached !\n");
755 return MMSYSERR_BADDEVICEID;
758 TRACE("dwSupport=(0x%x), dwFormats=(0x%x)\n", WOutDev[wDevID].caps.dwSupport, WOutDev[wDevID].caps.dwFormats);
759 memcpy(lpCaps, &WOutDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
760 return MMSYSERR_NOERROR;
763 /**************************************************************************
764 * wodOpen [internal]
766 static DWORD wodOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
768 WINE_WAVEOUT* wwo;
769 DWORD retval;
770 DWORD ret;
771 AudioStreamBasicDescription streamFormat;
773 TRACE("(%u, %p, %08x);\n", wDevID, lpDesc, dwFlags);
774 if (lpDesc == NULL)
776 WARN("Invalid Parameter !\n");
777 return MMSYSERR_INVALPARAM;
779 if (wDevID >= MAX_WAVEOUTDRV) {
780 TRACE("MAX_WAVOUTDRV reached !\n");
781 return MMSYSERR_BADDEVICEID;
784 TRACE("Format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
785 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
786 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
788 if (lpDesc->lpFormat->wFormatTag != WAVE_FORMAT_PCM ||
789 lpDesc->lpFormat->nChannels == 0 ||
790 lpDesc->lpFormat->nSamplesPerSec == 0
793 WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
794 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
795 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
796 return WAVERR_BADFORMAT;
799 if (dwFlags & WAVE_FORMAT_QUERY)
801 TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
802 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
803 lpDesc->lpFormat->nSamplesPerSec);
804 return MMSYSERR_NOERROR;
807 wwo = &WOutDev[wDevID];
808 if (!OSSpinLockTry(&wwo->lock))
809 return MMSYSERR_ALLOCATED;
811 if (wwo->state != WINE_WS_CLOSED)
813 OSSpinLockUnlock(&wwo->lock);
814 return MMSYSERR_ALLOCATED;
817 if (!AudioUnit_CreateDefaultAudioUnit((void *) wwo, &wwo->audioUnit))
819 ERR("CoreAudio_CreateDefaultAudioUnit(%p) failed\n", wwo);
820 OSSpinLockUnlock(&wwo->lock);
821 return MMSYSERR_ERROR;
824 if ((dwFlags & WAVE_DIRECTSOUND) &&
825 !(wwo->caps.dwSupport & WAVECAPS_DIRECTSOUND))
826 /* not supported, ignore it */
827 dwFlags &= ~WAVE_DIRECTSOUND;
829 streamFormat.mFormatID = kAudioFormatLinearPCM;
830 streamFormat.mFormatFlags = kLinearPCMFormatFlagIsPacked;
831 /* FIXME check for 32bits float -> kLinearPCMFormatFlagIsFloat */
832 if (lpDesc->lpFormat->wBitsPerSample != 8)
833 streamFormat.mFormatFlags |= kLinearPCMFormatFlagIsSignedInteger;
834 # ifdef WORDS_BIGENDIAN
835 streamFormat.mFormatFlags |= kLinearPCMFormatFlagIsBigEndian; /* FIXME Wave format is little endian */
836 # endif
838 streamFormat.mSampleRate = lpDesc->lpFormat->nSamplesPerSec;
839 streamFormat.mChannelsPerFrame = lpDesc->lpFormat->nChannels;
840 streamFormat.mFramesPerPacket = 1;
841 streamFormat.mBitsPerChannel = lpDesc->lpFormat->wBitsPerSample;
842 streamFormat.mBytesPerFrame = streamFormat.mBitsPerChannel * streamFormat.mChannelsPerFrame / 8;
843 streamFormat.mBytesPerPacket = streamFormat.mBytesPerFrame * streamFormat.mFramesPerPacket;
845 ret = AudioUnit_InitializeWithStreamDescription(wwo->audioUnit, &streamFormat);
846 if (!ret)
848 AudioUnit_CloseAudioUnit(wwo->audioUnit);
849 OSSpinLockUnlock(&wwo->lock);
850 return WAVERR_BADFORMAT; /* FIXME return an error based on the OSStatus */
852 wwo->streamDescription = streamFormat;
854 ret = AudioOutputUnitStart(wwo->audioUnit);
855 if (ret)
857 ERR("AudioOutputUnitStart failed: %08x\n", ret);
858 AudioUnitUninitialize(wwo->audioUnit);
859 AudioUnit_CloseAudioUnit(wwo->audioUnit);
860 OSSpinLockUnlock(&wwo->lock);
861 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
864 wwo->state = WINE_WS_STOPPED;
866 wwo->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
868 memcpy(&wwo->waveDesc, lpDesc, sizeof(WAVEOPENDESC));
869 memcpy(&wwo->format, lpDesc->lpFormat, sizeof(PCMWAVEFORMAT));
871 if (wwo->format.wBitsPerSample == 0) {
872 WARN("Resetting zeroed wBitsPerSample\n");
873 wwo->format.wBitsPerSample = 8 *
874 (wwo->format.wf.nAvgBytesPerSec /
875 wwo->format.wf.nSamplesPerSec) /
876 wwo->format.wf.nChannels;
879 wwo->dwPlayedTotal = 0;
880 wwo->dwWrittenTotal = 0;
882 wwo->trace_on = TRACE_ON(wave);
883 wwo->warn_on = WARN_ON(wave);
884 wwo->err_on = ERR_ON(wave);
886 OSSpinLockUnlock(&wwo->lock);
888 retval = wodNotifyClient(wwo, WOM_OPEN, 0L, 0L);
890 return retval;
893 /**************************************************************************
894 * wodClose [internal]
896 static DWORD wodClose(WORD wDevID)
898 DWORD ret = MMSYSERR_NOERROR;
899 WINE_WAVEOUT* wwo;
901 TRACE("(%u);\n", wDevID);
903 if (wDevID >= MAX_WAVEOUTDRV)
905 WARN("bad device ID !\n");
906 return MMSYSERR_BADDEVICEID;
909 wwo = &WOutDev[wDevID];
910 OSSpinLockLock(&wwo->lock);
911 if (wwo->lpQueuePtr)
913 WARN("buffers still playing !\n");
914 OSSpinLockUnlock(&wwo->lock);
915 ret = WAVERR_STILLPLAYING;
916 } else
918 OSStatus err;
919 /* sanity check: this should not happen since the device must have been reset before */
920 if (wwo->lpQueuePtr || wwo->lpPlayPtr) ERR("out of sync\n");
922 wwo->state = WINE_WS_CLOSED; /* mark the device as closed */
924 OSSpinLockUnlock(&wwo->lock);
926 err = AudioUnitUninitialize(wwo->audioUnit);
927 if (err) {
928 ERR("AudioUnitUninitialize return %c%c%c%c\n", (char) (err >> 24),
929 (char) (err >> 16),
930 (char) (err >> 8),
931 (char) err);
932 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
935 if ( !AudioUnit_CloseAudioUnit(wwo->audioUnit) )
937 ERR("Can't close AudioUnit\n");
938 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
941 ret = wodNotifyClient(wwo, WOM_CLOSE, 0L, 0L);
944 return ret;
947 /**************************************************************************
948 * wodPrepare [internal]
950 static DWORD wodPrepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
952 TRACE("(%u, %p, %08x);\n", wDevID, lpWaveHdr, dwSize);
954 if (wDevID >= MAX_WAVEOUTDRV) {
955 WARN("bad device ID !\n");
956 return MMSYSERR_BADDEVICEID;
959 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
960 return WAVERR_STILLPLAYING;
962 lpWaveHdr->dwFlags |= WHDR_PREPARED;
963 lpWaveHdr->dwFlags &= ~WHDR_DONE;
965 return MMSYSERR_NOERROR;
968 /**************************************************************************
969 * wodUnprepare [internal]
971 static DWORD wodUnprepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
973 TRACE("(%u, %p, %08x);\n", wDevID, lpWaveHdr, dwSize);
975 if (wDevID >= MAX_WAVEOUTDRV) {
976 WARN("bad device ID !\n");
977 return MMSYSERR_BADDEVICEID;
980 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
981 return WAVERR_STILLPLAYING;
983 lpWaveHdr->dwFlags &= ~WHDR_PREPARED;
984 lpWaveHdr->dwFlags |= WHDR_DONE;
986 return MMSYSERR_NOERROR;
990 /**************************************************************************
991 * wodHelper_CheckForLoopBegin [internal]
993 * Check if the new waveheader is the beginning of a loop, and set up
994 * state if so.
995 * This is called with the WAVEOUT lock held.
996 * Call from AudioUnit IO thread can't use Wine debug channels.
998 static void wodHelper_CheckForLoopBegin(WINE_WAVEOUT* wwo)
1000 LPWAVEHDR lpWaveHdr = wwo->lpPlayPtr;
1002 if (lpWaveHdr->dwFlags & WHDR_BEGINLOOP)
1004 if (wwo->lpLoopPtr)
1006 if (wwo->warn_on)
1007 fprintf(stderr, "warn:winecoreaudio:wodHelper_CheckForLoopBegin Already in a loop. Discarding loop on this header (%p)\n", lpWaveHdr);
1009 else
1011 if (wwo->trace_on)
1012 fprintf(stderr, "trace:winecoreaudio:wodHelper_CheckForLoopBegin Starting loop (%dx) with %p\n", lpWaveHdr->dwLoops, lpWaveHdr);
1014 wwo->lpLoopPtr = lpWaveHdr;
1015 /* Windows does not touch WAVEHDR.dwLoops,
1016 * so we need to make an internal copy */
1017 wwo->dwLoops = lpWaveHdr->dwLoops;
1023 /**************************************************************************
1024 * wodHelper_PlayPtrNext [internal]
1026 * Advance the play pointer to the next waveheader, looping if required.
1027 * This is called with the WAVEOUT lock held.
1028 * Call from AudioUnit IO thread can't use Wine debug channels.
1030 static void wodHelper_PlayPtrNext(WINE_WAVEOUT* wwo)
1032 BOOL didLoopBack = FALSE;
1034 wwo->dwPartialOffset = 0;
1035 if ((wwo->lpPlayPtr->dwFlags & WHDR_ENDLOOP) && wwo->lpLoopPtr)
1037 /* We're at the end of a loop, loop if required */
1038 if (wwo->dwLoops > 1)
1040 wwo->dwLoops--;
1041 wwo->lpPlayPtr = wwo->lpLoopPtr;
1042 didLoopBack = TRUE;
1044 else
1046 wwo->lpLoopPtr = NULL;
1049 if (!didLoopBack)
1051 /* We didn't loop back. Advance to the next wave header */
1052 wwo->lpPlayPtr = wwo->lpPlayPtr->lpNext;
1054 if (!wwo->lpPlayPtr)
1055 wwo->state = WINE_WS_STOPPED;
1056 else
1057 wodHelper_CheckForLoopBegin(wwo);
1061 /* if force is TRUE then notify the client that all the headers were completed
1063 static void wodHelper_NotifyCompletions(WINE_WAVEOUT* wwo, BOOL force)
1065 LPWAVEHDR lpWaveHdr;
1066 LPWAVEHDR lpFirstDoneWaveHdr = NULL;
1068 OSSpinLockLock(&wwo->lock);
1070 /* First, excise all of the done headers from the queue into
1071 * a free-standing list. */
1072 if (force)
1074 lpFirstDoneWaveHdr = wwo->lpQueuePtr;
1075 wwo->lpQueuePtr = NULL;
1077 else
1079 LPWAVEHDR lpLastDoneWaveHdr = NULL;
1081 /* Start from lpQueuePtr and keep notifying until:
1082 * - we hit an unwritten wavehdr
1083 * - we hit the beginning of a running loop
1084 * - we hit a wavehdr which hasn't finished playing
1086 for (
1087 lpWaveHdr = wwo->lpQueuePtr;
1088 lpWaveHdr &&
1089 lpWaveHdr != wwo->lpPlayPtr &&
1090 lpWaveHdr != wwo->lpLoopPtr;
1091 lpWaveHdr = lpWaveHdr->lpNext
1094 if (!lpFirstDoneWaveHdr)
1095 lpFirstDoneWaveHdr = lpWaveHdr;
1096 lpLastDoneWaveHdr = lpWaveHdr;
1099 if (lpLastDoneWaveHdr)
1101 wwo->lpQueuePtr = lpLastDoneWaveHdr->lpNext;
1102 lpLastDoneWaveHdr->lpNext = NULL;
1106 OSSpinLockUnlock(&wwo->lock);
1108 /* Now, send the "done" notification for each header in our list. */
1109 for (lpWaveHdr = lpFirstDoneWaveHdr; lpWaveHdr; lpWaveHdr = lpWaveHdr->lpNext)
1111 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1112 lpWaveHdr->dwFlags |= WHDR_DONE;
1114 wodNotifyClient(wwo, WOM_DONE, (DWORD)lpWaveHdr, 0);
1119 /**************************************************************************
1120 * wodWrite [internal]
1123 static DWORD wodWrite(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1125 LPWAVEHDR*wh;
1126 WINE_WAVEOUT *wwo;
1128 TRACE("(%u, %p, %08X);\n", wDevID, lpWaveHdr, dwSize);
1130 /* first, do the sanity checks... */
1131 if (wDevID >= MAX_WAVEOUTDRV)
1133 WARN("bad dev ID !\n");
1134 return MMSYSERR_BADDEVICEID;
1137 wwo = &WOutDev[wDevID];
1139 if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
1141 TRACE("unprepared\n");
1142 return WAVERR_UNPREPARED;
1145 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1147 TRACE("still playing\n");
1148 return WAVERR_STILLPLAYING;
1151 lpWaveHdr->dwFlags &= ~WHDR_DONE;
1152 lpWaveHdr->dwFlags |= WHDR_INQUEUE;
1153 lpWaveHdr->lpNext = 0;
1155 OSSpinLockLock(&wwo->lock);
1156 /* insert buffer at the end of queue */
1157 for (wh = &(wwo->lpQueuePtr); *wh; wh = &((*wh)->lpNext))
1158 /* Do nothing */;
1159 *wh = lpWaveHdr;
1161 if (!wwo->lpPlayPtr)
1163 wwo->lpPlayPtr = lpWaveHdr;
1165 if (wwo->state == WINE_WS_STOPPED)
1166 wwo->state = WINE_WS_PLAYING;
1168 wodHelper_CheckForLoopBegin(wwo);
1170 wwo->dwPartialOffset = 0;
1172 OSSpinLockUnlock(&wwo->lock);
1174 return MMSYSERR_NOERROR;
1177 /**************************************************************************
1178 * wodPause [internal]
1180 static DWORD wodPause(WORD wDevID)
1182 OSStatus status;
1184 TRACE("(%u);!\n", wDevID);
1186 if (wDevID >= MAX_WAVEOUTDRV)
1188 WARN("bad device ID !\n");
1189 return MMSYSERR_BADDEVICEID;
1192 /* The order of the following operations is important since we can't hold
1193 * the mutex while we make an Audio Unit call. Stop the Audio Unit before
1194 * setting the PAUSED state. In wodRestart, the order is reversed. This
1195 * guarantees that we can't get into a situation where the state is
1196 * PLAYING or STOPPED but the Audio Unit isn't running. Although we can
1197 * be in PAUSED state with the Audio Unit still running, that's harmless
1198 * because the render callback will just produce silence.
1200 status = AudioOutputUnitStop(WOutDev[wDevID].audioUnit);
1201 if (status) {
1202 WARN("AudioOutputUnitStop return %c%c%c%c\n",
1203 (char) (status >> 24), (char) (status >> 16), (char) (status >> 8), (char) status);
1206 OSSpinLockLock(&WOutDev[wDevID].lock);
1207 if (WOutDev[wDevID].state == WINE_WS_PLAYING || WOutDev[wDevID].state == WINE_WS_STOPPED)
1208 WOutDev[wDevID].state = WINE_WS_PAUSED;
1209 OSSpinLockUnlock(&WOutDev[wDevID].lock);
1211 return MMSYSERR_NOERROR;
1214 /**************************************************************************
1215 * wodRestart [internal]
1217 static DWORD wodRestart(WORD wDevID)
1219 OSStatus status;
1221 TRACE("(%u);\n", wDevID);
1223 if (wDevID >= MAX_WAVEOUTDRV )
1225 WARN("bad device ID !\n");
1226 return MMSYSERR_BADDEVICEID;
1229 /* The order of the following operations is important since we can't hold
1230 * the mutex while we make an Audio Unit call. Set the PLAYING/STOPPED
1231 * state before starting the Audio Unit. In wodPause, the order is
1232 * reversed. This guarantees that we can't get into a situation where
1233 * the state is PLAYING or STOPPED but the Audio Unit isn't running.
1234 * Although we can be in PAUSED state with the Audio Unit still running,
1235 * that's harmless because the render callback will just produce silence.
1237 OSSpinLockLock(&WOutDev[wDevID].lock);
1238 if (WOutDev[wDevID].state == WINE_WS_PAUSED)
1240 if (WOutDev[wDevID].lpPlayPtr)
1241 WOutDev[wDevID].state = WINE_WS_PLAYING;
1242 else
1243 WOutDev[wDevID].state = WINE_WS_STOPPED;
1245 OSSpinLockUnlock(&WOutDev[wDevID].lock);
1247 status = AudioOutputUnitStart(WOutDev[wDevID].audioUnit);
1248 if (status) {
1249 ERR("AudioOutputUnitStart return %c%c%c%c\n",
1250 (char) (status >> 24), (char) (status >> 16), (char) (status >> 8), (char) status);
1251 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1254 return MMSYSERR_NOERROR;
1257 /**************************************************************************
1258 * wodReset [internal]
1260 static DWORD wodReset(WORD wDevID)
1262 WINE_WAVEOUT* wwo;
1263 OSStatus status;
1265 TRACE("(%u);\n", wDevID);
1267 if (wDevID >= MAX_WAVEOUTDRV)
1269 WARN("bad device ID !\n");
1270 return MMSYSERR_BADDEVICEID;
1273 wwo = &WOutDev[wDevID];
1275 /* updates current notify list */
1276 /* if resetting, remove all wave headers and notify client that all headers were completed */
1277 wodHelper_NotifyCompletions(wwo, TRUE);
1279 OSSpinLockLock(&wwo->lock);
1281 wwo->lpPlayPtr = wwo->lpQueuePtr = wwo->lpLoopPtr = NULL;
1282 wwo->state = WINE_WS_STOPPED;
1283 wwo->dwPlayedTotal = wwo->dwWrittenTotal = 0;
1285 wwo->dwPartialOffset = 0; /* Clear partial wavehdr */
1287 OSSpinLockUnlock(&wwo->lock);
1289 status = AudioOutputUnitStart(wwo->audioUnit);
1291 if (status) {
1292 ERR( "AudioOutputUnitStart return %c%c%c%c\n",
1293 (char) (status >> 24), (char) (status >> 16), (char) (status >> 8), (char) status);
1294 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1297 return MMSYSERR_NOERROR;
1300 /**************************************************************************
1301 * wodGetPosition [internal]
1303 static DWORD wodGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
1305 DWORD val;
1306 WINE_WAVEOUT* wwo;
1308 TRACE("(%u, %p, %u);\n", wDevID, lpTime, uSize);
1310 if (wDevID >= MAX_WAVEOUTDRV)
1312 WARN("bad device ID !\n");
1313 return MMSYSERR_BADDEVICEID;
1316 /* if null pointer to time structure return error */
1317 if (lpTime == NULL) return MMSYSERR_INVALPARAM;
1319 wwo = &WOutDev[wDevID];
1321 OSSpinLockLock(&WOutDev[wDevID].lock);
1322 val = wwo->dwPlayedTotal;
1323 OSSpinLockUnlock(&WOutDev[wDevID].lock);
1325 return bytes_to_mmtime(lpTime, val, &wwo->format);
1328 /**************************************************************************
1329 * wodGetVolume [internal]
1331 static DWORD wodGetVolume(WORD wDevID, LPDWORD lpdwVol)
1333 float left;
1334 float right;
1336 if (wDevID >= MAX_WAVEOUTDRV)
1338 WARN("bad device ID !\n");
1339 return MMSYSERR_BADDEVICEID;
1342 TRACE("(%u, %p);\n", wDevID, lpdwVol);
1344 AudioUnit_GetVolume(WOutDev[wDevID].audioUnit, &left, &right);
1346 *lpdwVol = ((WORD) left * 0xFFFFl) + (((WORD) right * 0xFFFFl) << 16);
1348 return MMSYSERR_NOERROR;
1351 /**************************************************************************
1352 * wodSetVolume [internal]
1354 static DWORD wodSetVolume(WORD wDevID, DWORD dwParam)
1356 float left;
1357 float right;
1359 if (wDevID >= MAX_WAVEOUTDRV)
1361 WARN("bad device ID !\n");
1362 return MMSYSERR_BADDEVICEID;
1365 left = LOWORD(dwParam) / 65535.0f;
1366 right = HIWORD(dwParam) / 65535.0f;
1368 TRACE("(%u, %08x);\n", wDevID, dwParam);
1370 AudioUnit_SetVolume(WOutDev[wDevID].audioUnit, left, right);
1372 return MMSYSERR_NOERROR;
1375 /**************************************************************************
1376 * wodGetNumDevs [internal]
1378 static DWORD wodGetNumDevs(void)
1380 TRACE("\n");
1381 return MAX_WAVEOUTDRV;
1384 /**************************************************************************
1385 * wodDevInterfaceSize [internal]
1387 static DWORD wodDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
1389 TRACE("(%u, %p)\n", wDevID, dwParam1);
1391 *dwParam1 = MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].cadev->interface_name, -1,
1392 NULL, 0 ) * sizeof(WCHAR);
1393 return MMSYSERR_NOERROR;
1396 /**************************************************************************
1397 * wodDevInterface [internal]
1399 static DWORD wodDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
1401 TRACE("\n");
1402 if (dwParam2 >= MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].cadev->interface_name, -1,
1403 NULL, 0 ) * sizeof(WCHAR))
1405 MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].cadev->interface_name, -1,
1406 dwParam1, dwParam2 / sizeof(WCHAR));
1407 return MMSYSERR_NOERROR;
1409 return MMSYSERR_INVALPARAM;
1412 /**************************************************************************
1413 * wodMessage (WINECOREAUDIO.7)
1415 DWORD WINAPI CoreAudio_wodMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
1416 DWORD dwParam1, DWORD dwParam2)
1418 TRACE("(%u, %s, %08x, %08x, %08x);\n",
1419 wDevID, getMessage(wMsg), dwUser, dwParam1, dwParam2);
1421 switch (wMsg) {
1422 case DRVM_INIT:
1423 case DRVM_EXIT:
1424 case DRVM_ENABLE:
1425 case DRVM_DISABLE:
1427 /* FIXME: Pretend this is supported */
1428 return 0;
1429 case WODM_OPEN: return wodOpen(wDevID, (LPWAVEOPENDESC) dwParam1, dwParam2);
1430 case WODM_CLOSE: return wodClose(wDevID);
1431 case WODM_WRITE: return wodWrite(wDevID, (LPWAVEHDR) dwParam1, dwParam2);
1432 case WODM_PAUSE: return wodPause(wDevID);
1433 case WODM_GETPOS: return wodGetPosition(wDevID, (LPMMTIME) dwParam1, dwParam2);
1434 case WODM_BREAKLOOP: return MMSYSERR_NOTSUPPORTED;
1435 case WODM_PREPARE: return wodPrepare(wDevID, (LPWAVEHDR)dwParam1, dwParam2);
1436 case WODM_UNPREPARE: return wodUnprepare(wDevID, (LPWAVEHDR)dwParam1, dwParam2);
1438 case WODM_GETDEVCAPS: return wodGetDevCaps(wDevID, (LPWAVEOUTCAPSW) dwParam1, dwParam2);
1439 case WODM_GETNUMDEVS: return wodGetNumDevs();
1441 case WODM_GETPITCH:
1442 case WODM_SETPITCH:
1443 case WODM_GETPLAYBACKRATE:
1444 case WODM_SETPLAYBACKRATE: return MMSYSERR_NOTSUPPORTED;
1445 case WODM_GETVOLUME: return wodGetVolume(wDevID, (LPDWORD)dwParam1);
1446 case WODM_SETVOLUME: return wodSetVolume(wDevID, dwParam1);
1447 case WODM_RESTART: return wodRestart(wDevID);
1448 case WODM_RESET: return wodReset(wDevID);
1450 case DRV_QUERYDEVICEINTERFACESIZE: return wodDevInterfaceSize (wDevID, (LPDWORD)dwParam1);
1451 case DRV_QUERYDEVICEINTERFACE: return wodDevInterface (wDevID, (PWCHAR)dwParam1, dwParam2);
1452 case DRV_QUERYDSOUNDIFACE:
1453 case DRV_QUERYDSOUNDDESC:
1454 return MMSYSERR_NOTSUPPORTED;
1456 default:
1457 FIXME("unknown message %d!\n", wMsg);
1460 return MMSYSERR_NOTSUPPORTED;
1463 /*======================================================================*
1464 * Low level DSOUND implementation *
1465 *======================================================================*/
1467 typedef struct IDsDriverImpl IDsDriverImpl;
1468 typedef struct IDsDriverBufferImpl IDsDriverBufferImpl;
1470 struct IDsDriverImpl
1472 /* IUnknown fields */
1473 const IDsDriverVtbl *lpVtbl;
1474 DWORD ref;
1475 /* IDsDriverImpl fields */
1476 UINT wDevID;
1477 IDsDriverBufferImpl*primary;
1480 struct IDsDriverBufferImpl
1482 /* IUnknown fields */
1483 const IDsDriverBufferVtbl *lpVtbl;
1484 DWORD ref;
1485 /* IDsDriverBufferImpl fields */
1486 IDsDriverImpl* drv;
1487 DWORD buflen;
1492 CoreAudio IO threaded callback,
1493 we can't call Wine debug channels, critical section or anything using NtCurrentTeb here.
1495 OSStatus CoreAudio_woAudioUnitIOProc(void *inRefCon,
1496 AudioUnitRenderActionFlags *ioActionFlags,
1497 const AudioTimeStamp *inTimeStamp,
1498 UInt32 inBusNumber,
1499 UInt32 inNumberFrames,
1500 AudioBufferList *ioData)
1502 UInt32 buffer;
1503 WINE_WAVEOUT *wwo = (WINE_WAVEOUT *) inRefCon;
1504 int needNotify = 0;
1506 unsigned int dataNeeded = ioData->mBuffers[0].mDataByteSize;
1507 unsigned int dataProvided = 0;
1509 OSSpinLockLock(&wwo->lock);
1511 while (dataNeeded > 0 && wwo->state == WINE_WS_PLAYING && wwo->lpPlayPtr)
1513 unsigned int available = wwo->lpPlayPtr->dwBufferLength - wwo->dwPartialOffset;
1514 unsigned int toCopy;
1516 if (available >= dataNeeded)
1517 toCopy = dataNeeded;
1518 else
1519 toCopy = available;
1521 if (toCopy > 0)
1523 memcpy((char*)ioData->mBuffers[0].mData + dataProvided,
1524 wwo->lpPlayPtr->lpData + wwo->dwPartialOffset, toCopy);
1525 wwo->dwPartialOffset += toCopy;
1526 wwo->dwPlayedTotal += toCopy;
1527 dataProvided += toCopy;
1528 dataNeeded -= toCopy;
1529 available -= toCopy;
1532 if (available == 0)
1534 wodHelper_PlayPtrNext(wwo);
1535 needNotify = 1;
1539 OSSpinLockUnlock(&wwo->lock);
1541 /* We can't provide any more wave data. Fill the rest with silence. */
1542 if (dataNeeded > 0)
1544 if (!dataProvided)
1545 *ioActionFlags |= kAudioUnitRenderAction_OutputIsSilence;
1546 memset((char*)ioData->mBuffers[0].mData + dataProvided, 0, dataNeeded);
1547 dataProvided += dataNeeded;
1548 dataNeeded = 0;
1551 /* We only fill buffer 0. Set any others that might be requested to 0. */
1552 for (buffer = 1; buffer < ioData->mNumberBuffers; buffer++)
1554 memset(ioData->mBuffers[buffer].mData, 0, ioData->mBuffers[buffer].mDataByteSize);
1557 if (needNotify) wodSendNotifyCompletionsMessage(wwo);
1558 return noErr;
1562 /*======================================================================*
1563 * Low level WAVE IN implementation *
1564 *======================================================================*/
1566 /**************************************************************************
1567 * widNotifyClient [internal]
1569 static DWORD widNotifyClient(WINE_WAVEIN* wwi, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
1571 TRACE("wMsg = 0x%04x dwParm1 = %04X dwParam2 = %04X\n", wMsg, dwParam1, dwParam2);
1573 switch (wMsg)
1575 case WIM_OPEN:
1576 case WIM_CLOSE:
1577 case WIM_DATA:
1578 if (wwi->wFlags != DCB_NULL &&
1579 !DriverCallback(wwi->waveDesc.dwCallback, wwi->wFlags,
1580 (HDRVR)wwi->waveDesc.hWave, wMsg, wwi->waveDesc.dwInstance,
1581 dwParam1, dwParam2))
1583 WARN("can't notify client !\n");
1584 return MMSYSERR_ERROR;
1586 break;
1587 default:
1588 FIXME("Unknown callback message %u\n", wMsg);
1589 return MMSYSERR_INVALPARAM;
1591 return MMSYSERR_NOERROR;
1595 /**************************************************************************
1596 * widHelper_NotifyCompletions [internal]
1598 static void widHelper_NotifyCompletions(WINE_WAVEIN* wwi)
1600 LPWAVEHDR lpWaveHdr;
1601 LPWAVEHDR lpFirstDoneWaveHdr = NULL;
1602 LPWAVEHDR lpLastDoneWaveHdr = NULL;
1604 OSSpinLockLock(&wwi->lock);
1606 /* First, excise all of the done headers from the queue into
1607 * a free-standing list. */
1609 /* Start from lpQueuePtr and keep notifying until:
1610 * - we hit an unfilled wavehdr
1611 * - we hit the end of the list
1613 for (
1614 lpWaveHdr = wwi->lpQueuePtr;
1615 lpWaveHdr &&
1616 lpWaveHdr->dwBytesRecorded >= lpWaveHdr->dwBufferLength;
1617 lpWaveHdr = lpWaveHdr->lpNext
1620 if (!lpFirstDoneWaveHdr)
1621 lpFirstDoneWaveHdr = lpWaveHdr;
1622 lpLastDoneWaveHdr = lpWaveHdr;
1625 if (lpLastDoneWaveHdr)
1627 wwi->lpQueuePtr = lpLastDoneWaveHdr->lpNext;
1628 lpLastDoneWaveHdr->lpNext = NULL;
1631 OSSpinLockUnlock(&wwi->lock);
1633 /* Now, send the "done" notification for each header in our list. */
1634 for (lpWaveHdr = lpFirstDoneWaveHdr; lpWaveHdr; lpWaveHdr = lpWaveHdr->lpNext)
1636 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1637 lpWaveHdr->dwFlags |= WHDR_DONE;
1639 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
1644 /**************************************************************************
1645 * widGetDevCaps [internal]
1647 static DWORD widGetDevCaps(WORD wDevID, LPWAVEINCAPSW lpCaps, DWORD dwSize)
1649 TRACE("(%u, %p, %u);\n", wDevID, lpCaps, dwSize);
1651 if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
1653 if (wDevID >= MAX_WAVEINDRV)
1655 TRACE("MAX_WAVEINDRV reached !\n");
1656 return MMSYSERR_BADDEVICEID;
1659 memcpy(lpCaps, &WInDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
1660 return MMSYSERR_NOERROR;
1664 /**************************************************************************
1665 * widHelper_DestroyAudioBufferList [internal]
1666 * Convenience function to dispose of our audio buffers
1668 static void widHelper_DestroyAudioBufferList(AudioBufferList* list)
1670 if (list)
1672 UInt32 i;
1673 for (i = 0; i < list->mNumberBuffers; i++)
1675 if (list->mBuffers[i].mData)
1676 HeapFree(GetProcessHeap(), 0, list->mBuffers[i].mData);
1678 HeapFree(GetProcessHeap(), 0, list);
1683 /**************************************************************************
1684 * widHelper_AllocateAudioBufferList [internal]
1685 * Convenience function to allocate our audio buffers
1687 static AudioBufferList* widHelper_AllocateAudioBufferList(UInt32 numChannels, UInt32 size)
1689 AudioBufferList* list;
1690 UInt32 i;
1692 list = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(AudioBufferList) + numChannels * sizeof(AudioBuffer));
1693 if (list == NULL)
1694 return NULL;
1696 list->mNumberBuffers = numChannels;
1697 for (i = 0; i < numChannels; ++i)
1699 list->mBuffers[i].mNumberChannels = 1;
1700 list->mBuffers[i].mDataByteSize = size;
1701 list->mBuffers[i].mData = HeapAlloc(GetProcessHeap(), 0, size);
1702 if (list->mBuffers[i].mData == NULL)
1704 widHelper_DestroyAudioBufferList(list);
1705 return NULL;
1708 return list;
1712 /**************************************************************************
1713 * widOpen [internal]
1715 static DWORD widOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
1717 WINE_WAVEIN* wwi;
1718 UInt32 frameCount;
1719 UInt32 bytesPerFrame;
1721 TRACE("(%u, %p, %08X);\n", wDevID, lpDesc, dwFlags);
1722 if (lpDesc == NULL)
1724 WARN("Invalid Parameter !\n");
1725 return MMSYSERR_INVALPARAM;
1727 if (wDevID >= MAX_WAVEINDRV)
1729 TRACE ("MAX_WAVEINDRV reached !\n");
1730 return MMSYSERR_BADDEVICEID;
1733 TRACE("Format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
1734 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1735 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
1737 if (lpDesc->lpFormat->wFormatTag != WAVE_FORMAT_PCM ||
1738 lpDesc->lpFormat->nChannels == 0 ||
1739 lpDesc->lpFormat->nSamplesPerSec == 0
1742 WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
1743 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1744 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
1745 return WAVERR_BADFORMAT;
1748 if (dwFlags & WAVE_FORMAT_QUERY)
1750 TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
1751 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1752 lpDesc->lpFormat->nSamplesPerSec);
1753 return MMSYSERR_NOERROR;
1756 wwi = &WInDev[wDevID];
1757 if (!OSSpinLockTry(&wwi->lock))
1758 return MMSYSERR_ALLOCATED;
1760 if (wwi->state != WINE_WS_CLOSED)
1762 OSSpinLockUnlock(&wwi->lock);
1763 return MMSYSERR_ALLOCATED;
1766 wwi->state = WINE_WS_STOPPED;
1767 wwi->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
1769 memcpy(&wwi->waveDesc, lpDesc, sizeof(WAVEOPENDESC));
1770 memcpy(&wwi->format, lpDesc->lpFormat, sizeof(PCMWAVEFORMAT));
1772 if (wwi->format.wBitsPerSample == 0)
1774 WARN("Resetting zeroed wBitsPerSample\n");
1775 wwi->format.wBitsPerSample = 8 *
1776 (wwi->format.wf.nAvgBytesPerSec /
1777 wwi->format.wf.nSamplesPerSec) /
1778 wwi->format.wf.nChannels;
1781 wwi->dwTotalRecorded = 0;
1783 wwi->trace_on = TRACE_ON(wave);
1784 wwi->warn_on = WARN_ON(wave);
1785 wwi->err_on = ERR_ON(wave);
1787 if (!AudioUnit_CreateInputUnit(wwi, &wwi->audioUnit,
1788 wwi->format.wf.nChannels, wwi->format.wf.nSamplesPerSec,
1789 wwi->format.wBitsPerSample, &frameCount))
1791 ERR("AudioUnit_CreateInputUnit failed\n");
1792 OSSpinLockUnlock(&wwi->lock);
1793 return MMSYSERR_ERROR;
1796 /* Allocate our audio buffers */
1797 /* For interleaved audio, we allocate one buffer for all channels. */
1798 bytesPerFrame = wwi->format.wBitsPerSample * wwi->format.wf.nChannels / 8;
1799 wwi->bufferList = widHelper_AllocateAudioBufferList(1, wwi->format.wf.nChannels * frameCount * bytesPerFrame);
1800 if (wwi->bufferList == NULL)
1802 ERR("Failed to allocate buffer list\n");
1803 AudioUnitUninitialize(wwi->audioUnit);
1804 AudioUnit_CloseAudioUnit(wwi->audioUnit);
1805 OSSpinLockUnlock(&wwi->lock);
1806 return MMSYSERR_NOMEM;
1809 OSSpinLockUnlock(&wwi->lock);
1811 return widNotifyClient(wwi, WIM_OPEN, 0L, 0L);
1815 /**************************************************************************
1816 * widClose [internal]
1818 static DWORD widClose(WORD wDevID)
1820 DWORD ret = MMSYSERR_NOERROR;
1821 WINE_WAVEIN* wwi;
1823 TRACE("(%u);\n", wDevID);
1825 if (wDevID >= MAX_WAVEINDRV)
1827 WARN("bad device ID !\n");
1828 return MMSYSERR_BADDEVICEID;
1831 wwi = &WInDev[wDevID];
1832 OSSpinLockLock(&wwi->lock);
1833 if (wwi->state == WINE_WS_CLOSED)
1835 WARN("Device already closed.\n");
1836 ret = MMSYSERR_INVALHANDLE;
1838 else if (wwi->lpQueuePtr)
1840 WARN("Buffers in queue.\n");
1841 ret = WAVERR_STILLPLAYING;
1843 else
1845 wwi->state = WINE_WS_CLOSED;
1848 OSSpinLockUnlock(&wwi->lock);
1850 if (ret == MMSYSERR_NOERROR)
1852 OSStatus err = AudioUnitUninitialize(wwi->audioUnit);
1853 if (err)
1855 ERR("AudioUnitUninitialize return %c%c%c%c\n", (char) (err >> 24),
1856 (char) (err >> 16),
1857 (char) (err >> 8),
1858 (char) err);
1861 if (!AudioUnit_CloseAudioUnit(wwi->audioUnit))
1863 ERR("Can't close AudioUnit\n");
1866 /* Dellocate our audio buffers */
1867 widHelper_DestroyAudioBufferList(wwi->bufferList);
1868 wwi->bufferList = NULL;
1870 ret = widNotifyClient(wwi, WIM_CLOSE, 0L, 0L);
1873 return ret;
1877 /**************************************************************************
1878 * widAddBuffer [internal]
1880 static DWORD widAddBuffer(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1882 DWORD ret = MMSYSERR_NOERROR;
1883 WINE_WAVEIN* wwi;
1885 TRACE("(%u, %p, %08X);\n", wDevID, lpWaveHdr, dwSize);
1887 if (wDevID >= MAX_WAVEINDRV)
1889 WARN("invalid device ID\n");
1890 return MMSYSERR_INVALHANDLE;
1892 if (!(lpWaveHdr->dwFlags & WHDR_PREPARED))
1894 TRACE("never been prepared !\n");
1895 return WAVERR_UNPREPARED;
1897 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1899 TRACE("header already in use !\n");
1900 return WAVERR_STILLPLAYING;
1903 wwi = &WInDev[wDevID];
1904 OSSpinLockLock(&wwi->lock);
1906 if (wwi->state == WINE_WS_CLOSED)
1908 WARN("Trying to add buffer to closed device.\n");
1909 ret = MMSYSERR_INVALHANDLE;
1911 else
1913 LPWAVEHDR* wh;
1915 lpWaveHdr->dwFlags |= WHDR_INQUEUE;
1916 lpWaveHdr->dwFlags &= ~WHDR_DONE;
1917 lpWaveHdr->dwBytesRecorded = 0;
1918 lpWaveHdr->lpNext = NULL;
1920 /* insert buffer at end of queue */
1921 for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext))
1922 /* Do nothing */;
1923 *wh = lpWaveHdr;
1926 OSSpinLockUnlock(&wwi->lock);
1928 return ret;
1932 /**************************************************************************
1933 * widStart [internal]
1935 static DWORD widStart(WORD wDevID)
1937 DWORD ret = MMSYSERR_NOERROR;
1938 WINE_WAVEIN* wwi;
1940 TRACE("(%u);\n", wDevID);
1941 if (wDevID >= MAX_WAVEINDRV)
1943 WARN("invalid device ID\n");
1944 return MMSYSERR_INVALHANDLE;
1947 /* The order of the following operations is important since we can't hold
1948 * the mutex while we make an Audio Unit call. Set the PLAYING state
1949 * before starting the Audio Unit. In widStop, the order is reversed.
1950 * This guarantees that we can't get into a situation where the state is
1951 * PLAYING but the Audio Unit isn't running. Although we can be in STOPPED
1952 * state with the Audio Unit still running, that's harmless because the
1953 * input callback will just throw away the sound data.
1955 wwi = &WInDev[wDevID];
1956 OSSpinLockLock(&wwi->lock);
1958 if (wwi->state == WINE_WS_CLOSED)
1960 WARN("Trying to start closed device.\n");
1961 ret = MMSYSERR_INVALHANDLE;
1963 else
1964 wwi->state = WINE_WS_PLAYING;
1966 OSSpinLockUnlock(&wwi->lock);
1968 if (ret == MMSYSERR_NOERROR)
1970 /* Start pulling for audio data */
1971 OSStatus err = AudioOutputUnitStart(wwi->audioUnit);
1972 if (err != noErr)
1973 ERR("Failed to start AU: %08lx\n", err);
1975 TRACE("Recording started...\n");
1978 return ret;
1982 /**************************************************************************
1983 * widStop [internal]
1985 static DWORD widStop(WORD wDevID)
1987 DWORD ret = MMSYSERR_NOERROR;
1988 WINE_WAVEIN* wwi;
1989 WAVEHDR* lpWaveHdr = NULL;
1990 OSStatus err;
1992 TRACE("(%u);\n", wDevID);
1993 if (wDevID >= MAX_WAVEINDRV)
1995 WARN("invalid device ID\n");
1996 return MMSYSERR_INVALHANDLE;
1999 wwi = &WInDev[wDevID];
2001 /* The order of the following operations is important since we can't hold
2002 * the mutex while we make an Audio Unit call. Stop the Audio Unit before
2003 * setting the STOPPED state. In widStart, the order is reversed. This
2004 * guarantees that we can't get into a situation where the state is
2005 * PLAYING but the Audio Unit isn't running. Although we can be in STOPPED
2006 * state with the Audio Unit still running, that's harmless because the
2007 * input callback will just throw away the sound data.
2009 err = AudioOutputUnitStop(wwi->audioUnit);
2010 if (err != noErr)
2011 WARN("Failed to stop AU: %08lx\n", err);
2013 TRACE("Recording stopped.\n");
2015 OSSpinLockLock(&wwi->lock);
2017 if (wwi->state == WINE_WS_CLOSED)
2019 WARN("Trying to stop closed device.\n");
2020 ret = MMSYSERR_INVALHANDLE;
2022 else if (wwi->state != WINE_WS_STOPPED)
2024 wwi->state = WINE_WS_STOPPED;
2025 /* If there's a buffer in progress, it's done. Remove it from the
2026 * queue so that we can return it to the app, below. */
2027 if (wwi->lpQueuePtr)
2029 lpWaveHdr = wwi->lpQueuePtr;
2030 wwi->lpQueuePtr = lpWaveHdr->lpNext;
2034 OSSpinLockUnlock(&wwi->lock);
2036 if (lpWaveHdr)
2038 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2039 lpWaveHdr->dwFlags |= WHDR_DONE;
2040 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2043 return ret;
2047 /**************************************************************************
2048 * widReset [internal]
2050 static DWORD widReset(WORD wDevID)
2052 DWORD ret = MMSYSERR_NOERROR;
2053 WINE_WAVEIN* wwi;
2054 WAVEHDR* lpWaveHdr = NULL;
2056 TRACE("(%u);\n", wDevID);
2057 if (wDevID >= MAX_WAVEINDRV)
2059 WARN("invalid device ID\n");
2060 return MMSYSERR_INVALHANDLE;
2063 wwi = &WInDev[wDevID];
2064 OSSpinLockLock(&wwi->lock);
2066 if (wwi->state == WINE_WS_CLOSED)
2068 WARN("Trying to reset a closed device.\n");
2069 ret = MMSYSERR_INVALHANDLE;
2071 else
2073 lpWaveHdr = wwi->lpQueuePtr;
2074 wwi->lpQueuePtr = NULL;
2075 wwi->state = WINE_WS_STOPPED;
2076 wwi->dwTotalRecorded = 0;
2079 OSSpinLockUnlock(&wwi->lock);
2081 if (ret == MMSYSERR_NOERROR)
2083 OSStatus err = AudioOutputUnitStop(wwi->audioUnit);
2084 if (err != noErr)
2085 WARN("Failed to stop AU: %08lx\n", err);
2087 TRACE("Recording stopped.\n");
2090 while (lpWaveHdr)
2092 WAVEHDR* lpNext = lpWaveHdr->lpNext;
2094 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2095 lpWaveHdr->dwFlags |= WHDR_DONE;
2096 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2098 lpWaveHdr = lpNext;
2101 return ret;
2105 /**************************************************************************
2106 * widGetNumDevs [internal]
2108 static DWORD widGetNumDevs(void)
2110 return MAX_WAVEINDRV;
2114 /**************************************************************************
2115 * widDevInterfaceSize [internal]
2117 static DWORD widDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
2119 TRACE("(%u, %p)\n", wDevID, dwParam1);
2121 *dwParam1 = MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
2122 NULL, 0 ) * sizeof(WCHAR);
2123 return MMSYSERR_NOERROR;
2127 /**************************************************************************
2128 * widDevInterface [internal]
2130 static DWORD widDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
2132 if (dwParam2 >= MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
2133 NULL, 0 ) * sizeof(WCHAR))
2135 MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
2136 dwParam1, dwParam2 / sizeof(WCHAR));
2137 return MMSYSERR_NOERROR;
2139 return MMSYSERR_INVALPARAM;
2143 /**************************************************************************
2144 * widMessage (WINECOREAUDIO.6)
2146 DWORD WINAPI CoreAudio_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2147 DWORD dwParam1, DWORD dwParam2)
2149 TRACE("(%u, %04X, %08X, %08X, %08X);\n",
2150 wDevID, wMsg, dwUser, dwParam1, dwParam2);
2152 switch (wMsg)
2154 case DRVM_INIT:
2155 case DRVM_EXIT:
2156 case DRVM_ENABLE:
2157 case DRVM_DISABLE:
2158 /* FIXME: Pretend this is supported */
2159 return 0;
2160 case WIDM_OPEN: return widOpen (wDevID, (LPWAVEOPENDESC)dwParam1, dwParam2);
2161 case WIDM_CLOSE: return widClose (wDevID);
2162 case WIDM_ADDBUFFER: return widAddBuffer (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2163 case WIDM_PREPARE: return MMSYSERR_NOTSUPPORTED;
2164 case WIDM_UNPREPARE: return MMSYSERR_NOTSUPPORTED;
2165 case WIDM_GETDEVCAPS: return widGetDevCaps (wDevID, (LPWAVEINCAPSW)dwParam1, dwParam2);
2166 case WIDM_GETNUMDEVS: return widGetNumDevs ();
2167 case WIDM_RESET: return widReset (wDevID);
2168 case WIDM_START: return widStart (wDevID);
2169 case WIDM_STOP: return widStop (wDevID);
2170 case DRV_QUERYDEVICEINTERFACESIZE: return widDevInterfaceSize (wDevID, (LPDWORD)dwParam1);
2171 case DRV_QUERYDEVICEINTERFACE: return widDevInterface (wDevID, (PWCHAR)dwParam1, dwParam2);
2172 default:
2173 FIXME("unknown message %d!\n", wMsg);
2176 return MMSYSERR_NOTSUPPORTED;
2180 OSStatus CoreAudio_wiAudioUnitIOProc(void *inRefCon,
2181 AudioUnitRenderActionFlags *ioActionFlags,
2182 const AudioTimeStamp *inTimeStamp,
2183 UInt32 inBusNumber,
2184 UInt32 inNumberFrames,
2185 AudioBufferList *ioData)
2187 WINE_WAVEIN* wwi = (WINE_WAVEIN*)inRefCon;
2188 OSStatus err = noErr;
2189 BOOL needNotify = FALSE;
2190 WAVEHDR* lpStorePtr;
2191 unsigned int dataToStore;
2192 unsigned int dataStored = 0;
2195 if (wwi->trace_on)
2196 fprintf(stderr, "trace:wave:CoreAudio_wiAudioUnitIOProc (ioActionFlags = %08lx, "
2197 "inTimeStamp = { %f, %x%08x, %f, %x%08x, %08lx }, inBusNumber = %lu, inNumberFrames = %lu)\n",
2198 *ioActionFlags, inTimeStamp->mSampleTime, (DWORD)(inTimeStamp->mHostTime >>32),
2199 (DWORD)inTimeStamp->mHostTime, inTimeStamp->mRateScalar, (DWORD)(inTimeStamp->mWordClockTime >> 32),
2200 (DWORD)inTimeStamp->mWordClockTime, inTimeStamp->mFlags, inBusNumber, inNumberFrames);
2202 /* Render into audio buffer */
2203 /* FIXME: implement sample rate conversion on input. This will require
2204 * a different render strategy. We'll need to buffer the sound data
2205 * received here and pass it off to an AUConverter in another thread. */
2206 err = AudioUnitRender(wwi->audioUnit, ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, wwi->bufferList);
2207 if (err)
2209 if (wwi->err_on)
2210 fprintf(stderr, "err:wave:CoreAudio_wiAudioUnitIOProc AudioUnitRender failed with error %li\n", err);
2211 return err;
2214 /* Copy from audio buffer to the wavehdrs */
2215 dataToStore = wwi->bufferList->mBuffers[0].mDataByteSize;
2217 OSSpinLockLock(&wwi->lock);
2219 lpStorePtr = wwi->lpQueuePtr;
2221 while (dataToStore > 0 && wwi->state == WINE_WS_PLAYING && lpStorePtr)
2223 unsigned int room = lpStorePtr->dwBufferLength - lpStorePtr->dwBytesRecorded;
2224 unsigned int toCopy;
2226 if (wwi->trace_on)
2227 fprintf(stderr, "trace:wave:CoreAudio_wiAudioUnitIOProc Looking to store %u bytes to wavehdr %p, which has room for %u\n",
2228 dataToStore, lpStorePtr, room);
2230 if (room >= dataToStore)
2231 toCopy = dataToStore;
2232 else
2233 toCopy = room;
2235 if (toCopy > 0)
2237 memcpy(lpStorePtr->lpData + lpStorePtr->dwBytesRecorded,
2238 (char*)wwi->bufferList->mBuffers[0].mData + dataStored, toCopy);
2239 lpStorePtr->dwBytesRecorded += toCopy;
2240 wwi->dwTotalRecorded += toCopy;
2241 dataStored += toCopy;
2242 dataToStore -= toCopy;
2243 room -= toCopy;
2246 if (room == 0)
2248 lpStorePtr = lpStorePtr->lpNext;
2249 needNotify = TRUE;
2253 OSSpinLockUnlock(&wwi->lock);
2255 if (needNotify) wodSendNotifyInputCompletionsMessage(wwi);
2256 return err;
2259 #else
2261 /**************************************************************************
2262 * widMessage (WINECOREAUDIO.6)
2264 DWORD WINAPI CoreAudio_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2265 DWORD dwParam1, DWORD dwParam2)
2267 FIXME("(%u, %04X, %08X, %08X, %08X): CoreAudio support not compiled into wine\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2268 return MMSYSERR_NOTENABLED;
2271 /**************************************************************************
2272 * wodMessage (WINECOREAUDIO.7)
2274 DWORD WINAPI CoreAudio_wodMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2275 DWORD dwParam1, DWORD dwParam2)
2277 FIXME("(%u, %04X, %08X, %08X, %08X): CoreAudio support not compiled into wine\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2278 return MMSYSERR_NOTENABLED;
2281 #endif