push c22b4aa826b27f0c6bc5101b378e6e68716a85d9
[wine/hacks.git] / dlls / winecoreaudio.drv / audio.c
blob1d5df0281923c42b4df0cb8f1b479bde58414eba
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>
58 Due to AudioUnit headers conflict define some needed types.
61 typedef void *AudioUnit;
63 /* From AudioUnit/AUComponents.h */
64 enum
66 kAudioUnitRenderAction_OutputIsSilence = (1 << 4),
67 /* provides hint on return from Render(): if set the buffer contains all zeroes */
69 typedef UInt32 AudioUnitRenderActionFlags;
71 typedef long ComponentResult;
72 extern ComponentResult
73 AudioUnitRender( AudioUnit ci,
74 AudioUnitRenderActionFlags * ioActionFlags,
75 const AudioTimeStamp * inTimeStamp,
76 UInt32 inOutputBusNumber,
77 UInt32 inNumberFrames,
78 AudioBufferList * ioData) AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER;
80 /* only allow 10 output devices through this driver, this ought to be adequate */
81 #define MAX_WAVEOUTDRV (1)
82 #define MAX_WAVEINDRV (1)
84 /* state diagram for waveOut writing:
86 * +---------+-------------+---------------+---------------------------------+
87 * | state | function | event | new state |
88 * +---------+-------------+---------------+---------------------------------+
89 * | | open() | | STOPPED |
90 * | PAUSED | write() | | PAUSED |
91 * | STOPPED | write() | <thrd create> | PLAYING |
92 * | PLAYING | write() | HEADER | PLAYING |
93 * | (other) | write() | <error> | |
94 * | (any) | pause() | PAUSING | PAUSED |
95 * | PAUSED | restart() | RESTARTING | PLAYING (if no thrd => STOPPED) |
96 * | (any) | reset() | RESETTING | STOPPED |
97 * | (any) | close() | CLOSING | CLOSED |
98 * +---------+-------------+---------------+---------------------------------+
101 /* states of the playing device */
102 #define WINE_WS_PLAYING 0
103 #define WINE_WS_PAUSED 1
104 #define WINE_WS_STOPPED 2
105 #define WINE_WS_CLOSED 3
107 typedef struct tagCoreAudio_Device {
108 char dev_name[32];
109 char mixer_name[32];
110 unsigned open_count;
111 char* interface_name;
113 WAVEOUTCAPSW out_caps;
114 WAVEINCAPSW in_caps;
115 DWORD in_caps_support;
116 int sample_rate;
117 int stereo;
118 int format;
119 unsigned audio_fragment;
120 BOOL full_duplex;
121 BOOL bTriggerSupport;
122 BOOL bOutputEnabled;
123 BOOL bInputEnabled;
124 DSDRIVERDESC ds_desc;
125 DSDRIVERCAPS ds_caps;
126 DSCDRIVERCAPS dsc_caps;
127 GUID ds_guid;
128 GUID dsc_guid;
130 AudioDeviceID outputDeviceID;
131 AudioDeviceID inputDeviceID;
132 AudioStreamBasicDescription streamDescription;
133 } CoreAudio_Device;
135 /* for now use the default device */
136 static CoreAudio_Device CoreAudio_DefaultDevice;
138 typedef struct {
139 volatile int state; /* one of the WINE_WS_ manifest constants */
140 CoreAudio_Device *cadev;
141 WAVEOPENDESC waveDesc;
142 WORD wFlags;
143 PCMWAVEFORMAT format;
144 DWORD woID;
145 AudioUnit audioUnit;
146 AudioStreamBasicDescription streamDescription;
148 WAVEOUTCAPSW caps;
149 char interface_name[32];
150 LPWAVEHDR lpQueuePtr; /* start of queued WAVEHDRs (waiting to be notified) */
151 LPWAVEHDR lpPlayPtr; /* start of not yet fully played buffers */
152 DWORD dwPartialOffset; /* Offset of not yet written bytes in lpPlayPtr */
154 LPWAVEHDR lpLoopPtr; /* pointer of first buffer in loop, if any */
155 DWORD dwLoops; /* private copy of loop counter */
157 DWORD dwPlayedTotal; /* number of bytes actually played since opening */
158 DWORD dwWrittenTotal; /* number of bytes written to OSS buffer since opening */
160 DWORD tickCountMS; /* time in MS of last AudioUnit callback */
162 OSSpinLock lock; /* synchronization stuff */
164 BOOL trace_on;
165 BOOL warn_on;
166 BOOL err_on;
167 } WINE_WAVEOUT;
169 typedef struct {
170 /* This device's device number */
171 DWORD wiID;
173 /* Access to the following fields is synchronized across threads. */
174 volatile int state;
175 LPWAVEHDR lpQueuePtr;
176 DWORD dwTotalRecorded;
178 /* Synchronization mechanism to protect above fields */
179 OSSpinLock lock;
181 /* Capabilities description */
182 WAVEINCAPSW caps;
183 char interface_name[32];
185 /* Record the arguments used when opening the device. */
186 WAVEOPENDESC waveDesc;
187 WORD wFlags;
188 PCMWAVEFORMAT format;
190 AudioUnit audioUnit;
191 AudioBufferList*bufferList;
192 AudioBufferList*bufferListCopy;
194 /* Record state of debug channels at open. Used to control fprintf's since
195 * we can't use Wine debug channel calls in non-Wine AudioUnit threads. */
196 BOOL trace_on;
197 BOOL warn_on;
198 BOOL err_on;
200 /* These fields aren't used. */
201 #if 0
202 CoreAudio_Device *cadev;
204 AudioStreamBasicDescription streamDescription;
205 #endif
206 } WINE_WAVEIN;
208 static WINE_WAVEOUT WOutDev [MAX_WAVEOUTDRV];
209 static WINE_WAVEIN WInDev [MAX_WAVEINDRV];
211 static HANDLE hThread = NULL; /* Track the thread we create so we can clean it up later */
212 static CFMessagePortRef Port_SendToMessageThread;
214 static void wodHelper_PlayPtrNext(WINE_WAVEOUT* wwo);
215 static void wodHelper_NotifyDoneForList(WINE_WAVEOUT* wwo, LPWAVEHDR lpWaveHdr);
216 static void wodHelper_NotifyCompletions(WINE_WAVEOUT* wwo, BOOL force);
217 static void widHelper_NotifyCompletions(WINE_WAVEIN* wwi);
219 extern int AudioUnit_CreateDefaultAudioUnit(void *wwo, AudioUnit *au);
220 extern int AudioUnit_CloseAudioUnit(AudioUnit au);
221 extern int AudioUnit_InitializeWithStreamDescription(AudioUnit au, AudioStreamBasicDescription *streamFormat);
223 extern OSStatus AudioOutputUnitStart(AudioUnit au);
224 extern OSStatus AudioOutputUnitStop(AudioUnit au);
225 extern OSStatus AudioUnitUninitialize(AudioUnit au);
227 extern int AudioUnit_SetVolume(AudioUnit au, float left, float right);
228 extern int AudioUnit_GetVolume(AudioUnit au, float *left, float *right);
230 extern int AudioUnit_GetInputDeviceSampleRate(void);
232 extern int AudioUnit_CreateInputUnit(void* wwi, AudioUnit* out_au,
233 WORD nChannels, DWORD nSamplesPerSec, WORD wBitsPerSample,
234 UInt32* outFrameCount);
236 OSStatus CoreAudio_woAudioUnitIOProc(void *inRefCon,
237 AudioUnitRenderActionFlags *ioActionFlags,
238 const AudioTimeStamp *inTimeStamp,
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 if (!Port_SendToMessageThread)
353 return;
355 buffer = (UInt32) wwo->woID;
357 data = CFDataCreate(kCFAllocatorDefault, (UInt8 *)&buffer, sizeof(buffer));
358 if (!data)
359 return;
361 CFMessagePortSendRequest(Port_SendToMessageThread, kWaveOutNotifyCompletionsMessage, data, 0.0, 0.0, NULL, NULL);
362 CFRelease(data);
365 /**************************************************************************
366 * wodSendNotifyInputCompletionsMessage [internal]
367 * Call from AudioUnit IO thread can't use Wine debug channels.
369 static void wodSendNotifyInputCompletionsMessage(WINE_WAVEIN* wwi)
371 CFDataRef data;
372 UInt32 buffer;
374 if (!Port_SendToMessageThread)
375 return;
377 buffer = (UInt32) wwi->wiID;
379 data = CFDataCreate(kCFAllocatorDefault, (UInt8 *)&buffer, sizeof(buffer));
380 if (!data)
381 return;
383 CFMessagePortSendRequest(Port_SendToMessageThread, kWaveInNotifyCompletionsMessage, data, 0.0, 0.0, NULL, NULL);
384 CFRelease(data);
387 static DWORD bytes_to_mmtime(LPMMTIME lpTime, DWORD position,
388 PCMWAVEFORMAT* format)
390 TRACE("wType=%04X wBitsPerSample=%u nSamplesPerSec=%u nChannels=%u nAvgBytesPerSec=%u\n",
391 lpTime->wType, format->wBitsPerSample, format->wf.nSamplesPerSec,
392 format->wf.nChannels, format->wf.nAvgBytesPerSec);
393 TRACE("Position in bytes=%u\n", position);
395 switch (lpTime->wType) {
396 case TIME_SAMPLES:
397 lpTime->u.sample = position / (format->wBitsPerSample / 8 * format->wf.nChannels);
398 TRACE("TIME_SAMPLES=%u\n", lpTime->u.sample);
399 break;
400 case TIME_MS:
401 lpTime->u.ms = 1000.0 * position / (format->wBitsPerSample / 8 * format->wf.nChannels * format->wf.nSamplesPerSec);
402 TRACE("TIME_MS=%u\n", lpTime->u.ms);
403 break;
404 case TIME_SMPTE:
405 lpTime->u.smpte.fps = 30;
406 position = position / (format->wBitsPerSample / 8 * format->wf.nChannels);
407 position += (format->wf.nSamplesPerSec / lpTime->u.smpte.fps) - 1; /* round up */
408 lpTime->u.smpte.sec = position / format->wf.nSamplesPerSec;
409 position -= lpTime->u.smpte.sec * format->wf.nSamplesPerSec;
410 lpTime->u.smpte.min = lpTime->u.smpte.sec / 60;
411 lpTime->u.smpte.sec -= 60 * lpTime->u.smpte.min;
412 lpTime->u.smpte.hour = lpTime->u.smpte.min / 60;
413 lpTime->u.smpte.min -= 60 * lpTime->u.smpte.hour;
414 lpTime->u.smpte.fps = 30;
415 lpTime->u.smpte.frame = position * lpTime->u.smpte.fps / format->wf.nSamplesPerSec;
416 TRACE("TIME_SMPTE=%02u:%02u:%02u:%02u\n",
417 lpTime->u.smpte.hour, lpTime->u.smpte.min,
418 lpTime->u.smpte.sec, lpTime->u.smpte.frame);
419 break;
420 default:
421 WARN("Format %d not supported, using TIME_BYTES !\n", lpTime->wType);
422 lpTime->wType = TIME_BYTES;
423 /* fall through */
424 case TIME_BYTES:
425 lpTime->u.cb = position;
426 TRACE("TIME_BYTES=%u\n", lpTime->u.cb);
427 break;
429 return MMSYSERR_NOERROR;
432 /**************************************************************************
433 * CoreAudio_GetDevCaps [internal]
435 BOOL CoreAudio_GetDevCaps (void)
437 OSStatus status;
438 UInt32 propertySize;
439 AudioDeviceID devId = CoreAudio_DefaultDevice.outputDeviceID;
441 char name[MAXPNAMELEN];
443 propertySize = MAXPNAMELEN;
444 status = AudioDeviceGetProperty(devId, 0 , FALSE, kAudioDevicePropertyDeviceName, &propertySize, name);
445 if (status) {
446 ERR("AudioHardwareGetProperty for kAudioDevicePropertyDeviceName return %c%c%c%c\n", (char) (status >> 24),
447 (char) (status >> 16),
448 (char) (status >> 8),
449 (char) status);
450 return FALSE;
453 memcpy(CoreAudio_DefaultDevice.ds_desc.szDesc, name, sizeof(name));
454 strcpy(CoreAudio_DefaultDevice.ds_desc.szDrvname, "winecoreaudio.drv");
455 MultiByteToWideChar(CP_UNIXCP, 0, name, sizeof(name),
456 CoreAudio_DefaultDevice.out_caps.szPname,
457 sizeof(CoreAudio_DefaultDevice.out_caps.szPname) / sizeof(WCHAR));
458 memcpy(CoreAudio_DefaultDevice.dev_name, name, 32);
460 propertySize = sizeof(CoreAudio_DefaultDevice.streamDescription);
461 status = AudioDeviceGetProperty(devId, 0, FALSE , kAudioDevicePropertyStreamFormat, &propertySize, &CoreAudio_DefaultDevice.streamDescription);
462 if (status != noErr) {
463 ERR("AudioHardwareGetProperty for kAudioDevicePropertyStreamFormat return %c%c%c%c\n", (char) (status >> 24),
464 (char) (status >> 16),
465 (char) (status >> 8),
466 (char) status);
467 return FALSE;
470 TRACE("Device Stream Description mSampleRate : %f\n mFormatID : %c%c%c%c\n"
471 "mFormatFlags : %lX\n mBytesPerPacket : %lu\n mFramesPerPacket : %lu\n"
472 "mBytesPerFrame : %lu\n mChannelsPerFrame : %lu\n mBitsPerChannel : %lu\n",
473 CoreAudio_DefaultDevice.streamDescription.mSampleRate,
474 (char) (CoreAudio_DefaultDevice.streamDescription.mFormatID >> 24),
475 (char) (CoreAudio_DefaultDevice.streamDescription.mFormatID >> 16),
476 (char) (CoreAudio_DefaultDevice.streamDescription.mFormatID >> 8),
477 (char) CoreAudio_DefaultDevice.streamDescription.mFormatID,
478 CoreAudio_DefaultDevice.streamDescription.mFormatFlags,
479 CoreAudio_DefaultDevice.streamDescription.mBytesPerPacket,
480 CoreAudio_DefaultDevice.streamDescription.mFramesPerPacket,
481 CoreAudio_DefaultDevice.streamDescription.mBytesPerFrame,
482 CoreAudio_DefaultDevice.streamDescription.mChannelsPerFrame,
483 CoreAudio_DefaultDevice.streamDescription.mBitsPerChannel);
485 CoreAudio_DefaultDevice.out_caps.wMid = 0xcafe;
486 CoreAudio_DefaultDevice.out_caps.wPid = 0x0001;
488 CoreAudio_DefaultDevice.out_caps.vDriverVersion = 0x0001;
489 CoreAudio_DefaultDevice.out_caps.dwFormats = 0x00000000;
490 CoreAudio_DefaultDevice.out_caps.wReserved1 = 0;
491 CoreAudio_DefaultDevice.out_caps.dwSupport = WAVECAPS_VOLUME;
492 CoreAudio_DefaultDevice.out_caps.dwSupport |= WAVECAPS_LRVOLUME;
494 CoreAudio_DefaultDevice.out_caps.wChannels = 2;
495 CoreAudio_DefaultDevice.out_caps.dwFormats|= WAVE_FORMAT_4S16;
497 return TRUE;
500 /******************************************************************
501 * CoreAudio_WaveInit
503 * Initialize CoreAudio_DefaultDevice
505 LONG CoreAudio_WaveInit(void)
507 OSStatus status;
508 UInt32 propertySize;
509 int i;
510 CFStringRef messageThreadPortName;
511 CFMessagePortRef port_ReceiveInMessageThread;
512 int inputSampleRate;
514 TRACE("()\n");
516 /* number of sound cards */
517 AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &propertySize, NULL);
518 propertySize /= sizeof(AudioDeviceID);
519 TRACE("sound cards : %lu\n", propertySize);
521 /* Get the output device */
522 propertySize = sizeof(CoreAudio_DefaultDevice.outputDeviceID);
523 status = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &propertySize, &CoreAudio_DefaultDevice.outputDeviceID);
524 if (status) {
525 ERR("AudioHardwareGetProperty return %c%c%c%c for kAudioHardwarePropertyDefaultOutputDevice\n", (char) (status >> 24),
526 (char) (status >> 16),
527 (char) (status >> 8),
528 (char) status);
529 return DRV_FAILURE;
531 if (CoreAudio_DefaultDevice.outputDeviceID == kAudioDeviceUnknown) {
532 ERR("AudioHardwareGetProperty: CoreAudio_DefaultDevice.outputDeviceID == kAudioDeviceUnknown\n");
533 return DRV_FAILURE;
536 if ( ! CoreAudio_GetDevCaps() )
537 return DRV_FAILURE;
539 CoreAudio_DefaultDevice.interface_name=HeapAlloc(GetProcessHeap(),0,strlen(CoreAudio_DefaultDevice.dev_name)+1);
540 strcpy(CoreAudio_DefaultDevice.interface_name, CoreAudio_DefaultDevice.dev_name);
542 for (i = 0; i < MAX_WAVEOUTDRV; ++i)
544 static const WCHAR wszWaveOutFormat[] =
545 {'C','o','r','e','A','u','d','i','o',' ','W','a','v','e','I','n',' ','%','d',0};
547 WOutDev[i].state = WINE_WS_CLOSED;
548 WOutDev[i].cadev = &CoreAudio_DefaultDevice;
549 WOutDev[i].woID = i;
551 memset(&WOutDev[i].caps, 0, sizeof(WOutDev[i].caps));
553 WOutDev[i].caps.wMid = 0xcafe; /* Manufac ID */
554 WOutDev[i].caps.wPid = 0x0001; /* Product ID */
555 snprintfW(WOutDev[i].caps.szPname, sizeof(WOutDev[i].caps.szPname)/sizeof(WCHAR), wszWaveOutFormat, i);
556 snprintf(WOutDev[i].interface_name, sizeof(WOutDev[i].interface_name), "winecoreaudio: %d", i);
558 WOutDev[i].caps.vDriverVersion = 0x0001;
559 WOutDev[i].caps.dwFormats = 0x00000000;
560 WOutDev[i].caps.dwSupport = WAVECAPS_VOLUME;
562 WOutDev[i].caps.wChannels = 2;
563 /* WOutDev[i].caps.dwSupport |= WAVECAPS_LRVOLUME; */ /* FIXME */
565 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96M08;
566 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96S08;
567 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96M16;
568 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_96S16;
569 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48M08;
570 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48S08;
571 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48M16;
572 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_48S16;
573 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4M08;
574 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4S08;
575 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4S16;
576 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4M16;
577 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2M08;
578 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2S08;
579 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2M16;
580 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2S16;
581 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1M08;
582 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1S08;
583 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1M16;
584 WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1S16;
586 WOutDev[i].lock = 0; /* initialize the mutex */
589 /* FIXME: implement sample rate conversion on input */
590 inputSampleRate = AudioUnit_GetInputDeviceSampleRate();
592 for (i = 0; i < MAX_WAVEINDRV; ++i)
594 static const WCHAR wszWaveInFormat[] =
595 {'C','o','r','e','A','u','d','i','o',' ','W','a','v','e','I','n',' ','%','d',0};
597 memset(&WInDev[i], 0, sizeof(WInDev[i]));
598 WInDev[i].wiID = i;
600 /* Establish preconditions for widOpen */
601 WInDev[i].state = WINE_WS_CLOSED;
602 WInDev[i].lock = 0; /* initialize the mutex */
604 /* Fill in capabilities. widGetDevCaps can be called at any time. */
605 WInDev[i].caps.wMid = 0xcafe; /* Manufac ID */
606 WInDev[i].caps.wPid = 0x0001; /* Product ID */
607 WInDev[i].caps.vDriverVersion = 0x0001;
609 snprintfW(WInDev[i].caps.szPname, sizeof(WInDev[i].caps.szPname)/sizeof(WCHAR), wszWaveInFormat, i);
610 snprintf(WInDev[i].interface_name, sizeof(WInDev[i].interface_name), "winecoreaudio in: %d", i);
612 if (inputSampleRate == 96000)
614 WInDev[i].caps.dwFormats |= WAVE_FORMAT_96M08;
615 WInDev[i].caps.dwFormats |= WAVE_FORMAT_96S08;
616 WInDev[i].caps.dwFormats |= WAVE_FORMAT_96M16;
617 WInDev[i].caps.dwFormats |= WAVE_FORMAT_96S16;
619 if (inputSampleRate == 48000)
621 WInDev[i].caps.dwFormats |= WAVE_FORMAT_48M08;
622 WInDev[i].caps.dwFormats |= WAVE_FORMAT_48S08;
623 WInDev[i].caps.dwFormats |= WAVE_FORMAT_48M16;
624 WInDev[i].caps.dwFormats |= WAVE_FORMAT_48S16;
626 if (inputSampleRate == 44100)
628 WInDev[i].caps.dwFormats |= WAVE_FORMAT_4M08;
629 WInDev[i].caps.dwFormats |= WAVE_FORMAT_4S08;
630 WInDev[i].caps.dwFormats |= WAVE_FORMAT_4M16;
631 WInDev[i].caps.dwFormats |= WAVE_FORMAT_4S16;
633 if (inputSampleRate == 22050)
635 WInDev[i].caps.dwFormats |= WAVE_FORMAT_2M08;
636 WInDev[i].caps.dwFormats |= WAVE_FORMAT_2S08;
637 WInDev[i].caps.dwFormats |= WAVE_FORMAT_2M16;
638 WInDev[i].caps.dwFormats |= WAVE_FORMAT_2S16;
640 if (inputSampleRate == 11025)
642 WInDev[i].caps.dwFormats |= WAVE_FORMAT_1M08;
643 WInDev[i].caps.dwFormats |= WAVE_FORMAT_1S08;
644 WInDev[i].caps.dwFormats |= WAVE_FORMAT_1M16;
645 WInDev[i].caps.dwFormats |= WAVE_FORMAT_1S16;
648 WInDev[i].caps.wChannels = 2;
651 /* create mach messages handler */
652 srandomdev();
653 messageThreadPortName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL,
654 CFSTR("WaveMessagePort.%d.%lu"), getpid(), (unsigned long)random());
655 if (!messageThreadPortName)
657 ERR("Can't create message thread port name\n");
658 return DRV_FAILURE;
661 port_ReceiveInMessageThread = CFMessagePortCreateLocal(kCFAllocatorDefault, messageThreadPortName,
662 &wodMessageHandler, NULL, NULL);
663 if (!port_ReceiveInMessageThread)
665 ERR("Can't create message thread local port\n");
666 CFRelease(messageThreadPortName);
667 return DRV_FAILURE;
670 Port_SendToMessageThread = CFMessagePortCreateRemote(kCFAllocatorDefault, messageThreadPortName);
671 CFRelease(messageThreadPortName);
672 if (!Port_SendToMessageThread)
674 ERR("Can't create port for sending to message thread\n");
675 CFRelease(port_ReceiveInMessageThread);
676 return DRV_FAILURE;
679 /* Cannot WAIT for any events because we are called from the loader (which has a lock on loading stuff) */
680 /* We might want to wait for this thread to be created -- but we cannot -- not here at least */
681 /* Instead track the thread so we can clean it up later */
682 if ( hThread )
684 ERR("Message thread already started -- expect problems\n");
686 hThread = CreateThread(NULL, 0, messageThread, (LPVOID)port_ReceiveInMessageThread, 0, NULL);
687 if ( !hThread )
689 ERR("Can't create message thread\n");
690 CFRelease(port_ReceiveInMessageThread);
691 CFRelease(Port_SendToMessageThread);
692 Port_SendToMessageThread = NULL;
693 return DRV_FAILURE;
696 /* The message thread is responsible for releasing port_ReceiveInMessageThread. */
698 return DRV_SUCCESS;
701 void CoreAudio_WaveRelease(void)
703 /* Stop CFRunLoop in messageThread */
704 TRACE("()\n");
706 if (!Port_SendToMessageThread)
707 return;
709 CFMessagePortSendRequest(Port_SendToMessageThread, kStopLoopMessage, NULL, 0.0, 0.0, NULL, NULL);
710 CFRelease(Port_SendToMessageThread);
711 Port_SendToMessageThread = NULL;
713 /* Wait for the thread to finish and clean it up */
714 /* This rids us of any quick start/shutdown driver crashes */
715 WaitForSingleObject(hThread, INFINITE);
716 CloseHandle(hThread);
717 hThread = NULL;
720 /*======================================================================*
721 * Low level WAVE OUT implementation *
722 *======================================================================*/
724 /**************************************************************************
725 * wodNotifyClient [internal]
727 static DWORD wodNotifyClient(WINE_WAVEOUT* wwo, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
729 switch (wMsg) {
730 case WOM_OPEN:
731 case WOM_CLOSE:
732 case WOM_DONE:
733 if (wwo->wFlags != DCB_NULL &&
734 !DriverCallback(wwo->waveDesc.dwCallback, wwo->wFlags,
735 (HDRVR)wwo->waveDesc.hWave, wMsg, wwo->waveDesc.dwInstance,
736 dwParam1, dwParam2))
738 return MMSYSERR_ERROR;
740 break;
741 default:
742 return MMSYSERR_INVALPARAM;
744 return MMSYSERR_NOERROR;
748 /**************************************************************************
749 * wodGetDevCaps [internal]
751 static DWORD wodGetDevCaps(WORD wDevID, LPWAVEOUTCAPSW lpCaps, DWORD dwSize)
753 TRACE("(%u, %p, %u);\n", wDevID, lpCaps, dwSize);
755 if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
757 if (wDevID >= MAX_WAVEOUTDRV)
759 TRACE("MAX_WAVOUTDRV reached !\n");
760 return MMSYSERR_BADDEVICEID;
763 TRACE("dwSupport=(0x%x), dwFormats=(0x%x)\n", WOutDev[wDevID].caps.dwSupport, WOutDev[wDevID].caps.dwFormats);
764 memcpy(lpCaps, &WOutDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
765 return MMSYSERR_NOERROR;
768 /**************************************************************************
769 * wodOpen [internal]
771 static DWORD wodOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
773 WINE_WAVEOUT* wwo;
774 DWORD retval;
775 DWORD ret;
776 AudioStreamBasicDescription streamFormat;
778 TRACE("(%u, %p, %08x);\n", wDevID, lpDesc, dwFlags);
779 if (lpDesc == NULL)
781 WARN("Invalid Parameter !\n");
782 return MMSYSERR_INVALPARAM;
784 if (wDevID >= MAX_WAVEOUTDRV) {
785 TRACE("MAX_WAVOUTDRV reached !\n");
786 return MMSYSERR_BADDEVICEID;
789 TRACE("Format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
790 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
791 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
793 if (lpDesc->lpFormat->wFormatTag != WAVE_FORMAT_PCM ||
794 lpDesc->lpFormat->nChannels == 0 ||
795 lpDesc->lpFormat->nSamplesPerSec == 0
798 WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
799 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
800 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
801 return WAVERR_BADFORMAT;
804 if (dwFlags & WAVE_FORMAT_QUERY)
806 TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
807 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
808 lpDesc->lpFormat->nSamplesPerSec);
809 return MMSYSERR_NOERROR;
812 wwo = &WOutDev[wDevID];
813 if (!OSSpinLockTry(&wwo->lock))
814 return MMSYSERR_ALLOCATED;
816 if (wwo->state != WINE_WS_CLOSED)
818 OSSpinLockUnlock(&wwo->lock);
819 return MMSYSERR_ALLOCATED;
822 if (!AudioUnit_CreateDefaultAudioUnit((void *) wwo, &wwo->audioUnit))
824 ERR("CoreAudio_CreateDefaultAudioUnit(%p) failed\n", wwo);
825 OSSpinLockUnlock(&wwo->lock);
826 return MMSYSERR_ERROR;
829 if ((dwFlags & WAVE_DIRECTSOUND) &&
830 !(wwo->caps.dwSupport & WAVECAPS_DIRECTSOUND))
831 /* not supported, ignore it */
832 dwFlags &= ~WAVE_DIRECTSOUND;
834 streamFormat.mFormatID = kAudioFormatLinearPCM;
835 streamFormat.mFormatFlags = kLinearPCMFormatFlagIsPacked;
836 /* FIXME check for 32bits float -> kLinearPCMFormatFlagIsFloat */
837 if (lpDesc->lpFormat->wBitsPerSample != 8)
838 streamFormat.mFormatFlags |= kLinearPCMFormatFlagIsSignedInteger;
839 # ifdef WORDS_BIGENDIAN
840 streamFormat.mFormatFlags |= kLinearPCMFormatFlagIsBigEndian; /* FIXME Wave format is little endian */
841 # endif
843 streamFormat.mSampleRate = lpDesc->lpFormat->nSamplesPerSec;
844 streamFormat.mChannelsPerFrame = lpDesc->lpFormat->nChannels;
845 streamFormat.mFramesPerPacket = 1;
846 streamFormat.mBitsPerChannel = lpDesc->lpFormat->wBitsPerSample;
847 streamFormat.mBytesPerFrame = streamFormat.mBitsPerChannel * streamFormat.mChannelsPerFrame / 8;
848 streamFormat.mBytesPerPacket = streamFormat.mBytesPerFrame * streamFormat.mFramesPerPacket;
850 ret = AudioUnit_InitializeWithStreamDescription(wwo->audioUnit, &streamFormat);
851 if (!ret)
853 AudioUnit_CloseAudioUnit(wwo->audioUnit);
854 OSSpinLockUnlock(&wwo->lock);
855 return WAVERR_BADFORMAT; /* FIXME return an error based on the OSStatus */
857 wwo->streamDescription = streamFormat;
859 ret = AudioOutputUnitStart(wwo->audioUnit);
860 if (ret)
862 ERR("AudioOutputUnitStart failed: %08x\n", ret);
863 AudioUnitUninitialize(wwo->audioUnit);
864 AudioUnit_CloseAudioUnit(wwo->audioUnit);
865 OSSpinLockUnlock(&wwo->lock);
866 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
869 wwo->state = WINE_WS_STOPPED;
871 wwo->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
873 wwo->waveDesc = *lpDesc;
874 memcpy(&wwo->format, lpDesc->lpFormat, sizeof(PCMWAVEFORMAT));
876 if (wwo->format.wBitsPerSample == 0) {
877 WARN("Resetting zeroed wBitsPerSample\n");
878 wwo->format.wBitsPerSample = 8 *
879 (wwo->format.wf.nAvgBytesPerSec /
880 wwo->format.wf.nSamplesPerSec) /
881 wwo->format.wf.nChannels;
884 wwo->dwPlayedTotal = 0;
885 wwo->dwWrittenTotal = 0;
887 wwo->trace_on = TRACE_ON(wave);
888 wwo->warn_on = WARN_ON(wave);
889 wwo->err_on = ERR_ON(wave);
891 OSSpinLockUnlock(&wwo->lock);
893 retval = wodNotifyClient(wwo, WOM_OPEN, 0L, 0L);
895 return retval;
898 /**************************************************************************
899 * wodClose [internal]
901 static DWORD wodClose(WORD wDevID)
903 DWORD ret = MMSYSERR_NOERROR;
904 WINE_WAVEOUT* wwo;
906 TRACE("(%u);\n", wDevID);
908 if (wDevID >= MAX_WAVEOUTDRV)
910 WARN("bad device ID !\n");
911 return MMSYSERR_BADDEVICEID;
914 wwo = &WOutDev[wDevID];
915 OSSpinLockLock(&wwo->lock);
916 if (wwo->lpQueuePtr)
918 WARN("buffers still playing !\n");
919 OSSpinLockUnlock(&wwo->lock);
920 ret = WAVERR_STILLPLAYING;
921 } else
923 OSStatus err;
924 /* sanity check: this should not happen since the device must have been reset before */
925 if (wwo->lpQueuePtr || wwo->lpPlayPtr) ERR("out of sync\n");
927 wwo->state = WINE_WS_CLOSED; /* mark the device as closed */
929 OSSpinLockUnlock(&wwo->lock);
931 err = AudioUnitUninitialize(wwo->audioUnit);
932 if (err) {
933 ERR("AudioUnitUninitialize return %c%c%c%c\n", (char) (err >> 24),
934 (char) (err >> 16),
935 (char) (err >> 8),
936 (char) err);
937 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
940 if ( !AudioUnit_CloseAudioUnit(wwo->audioUnit) )
942 ERR("Can't close AudioUnit\n");
943 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
946 ret = wodNotifyClient(wwo, WOM_CLOSE, 0L, 0L);
949 return ret;
952 /**************************************************************************
953 * wodPrepare [internal]
955 static DWORD wodPrepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
957 TRACE("(%u, %p, %08x);\n", wDevID, lpWaveHdr, dwSize);
959 if (wDevID >= MAX_WAVEOUTDRV) {
960 WARN("bad device ID !\n");
961 return MMSYSERR_BADDEVICEID;
964 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
965 return WAVERR_STILLPLAYING;
967 lpWaveHdr->dwFlags |= WHDR_PREPARED;
968 lpWaveHdr->dwFlags &= ~WHDR_DONE;
970 return MMSYSERR_NOERROR;
973 /**************************************************************************
974 * wodUnprepare [internal]
976 static DWORD wodUnprepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
978 TRACE("(%u, %p, %08x);\n", wDevID, lpWaveHdr, dwSize);
980 if (wDevID >= MAX_WAVEOUTDRV) {
981 WARN("bad device ID !\n");
982 return MMSYSERR_BADDEVICEID;
985 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
986 return WAVERR_STILLPLAYING;
988 lpWaveHdr->dwFlags &= ~WHDR_PREPARED;
989 lpWaveHdr->dwFlags |= WHDR_DONE;
991 return MMSYSERR_NOERROR;
995 /**************************************************************************
996 * wodHelper_CheckForLoopBegin [internal]
998 * Check if the new waveheader is the beginning of a loop, and set up
999 * state if so.
1000 * This is called with the WAVEOUT lock held.
1001 * Call from AudioUnit IO thread can't use Wine debug channels.
1003 static void wodHelper_CheckForLoopBegin(WINE_WAVEOUT* wwo)
1005 LPWAVEHDR lpWaveHdr = wwo->lpPlayPtr;
1007 if (lpWaveHdr->dwFlags & WHDR_BEGINLOOP)
1009 if (wwo->lpLoopPtr)
1011 if (wwo->warn_on)
1012 fprintf(stderr, "warn:winecoreaudio:wodHelper_CheckForLoopBegin Already in a loop. Discarding loop on this header (%p)\n", lpWaveHdr);
1014 else
1016 if (wwo->trace_on)
1017 fprintf(stderr, "trace:winecoreaudio:wodHelper_CheckForLoopBegin Starting loop (%dx) with %p\n", lpWaveHdr->dwLoops, lpWaveHdr);
1019 wwo->lpLoopPtr = lpWaveHdr;
1020 /* Windows does not touch WAVEHDR.dwLoops,
1021 * so we need to make an internal copy */
1022 wwo->dwLoops = lpWaveHdr->dwLoops;
1028 /**************************************************************************
1029 * wodHelper_PlayPtrNext [internal]
1031 * Advance the play pointer to the next waveheader, looping if required.
1032 * This is called with the WAVEOUT lock held.
1033 * Call from AudioUnit IO thread can't use Wine debug channels.
1035 static void wodHelper_PlayPtrNext(WINE_WAVEOUT* wwo)
1037 BOOL didLoopBack = FALSE;
1039 wwo->dwPartialOffset = 0;
1040 if ((wwo->lpPlayPtr->dwFlags & WHDR_ENDLOOP) && wwo->lpLoopPtr)
1042 /* We're at the end of a loop, loop if required */
1043 if (wwo->dwLoops > 1)
1045 wwo->dwLoops--;
1046 wwo->lpPlayPtr = wwo->lpLoopPtr;
1047 didLoopBack = TRUE;
1049 else
1051 wwo->lpLoopPtr = NULL;
1054 if (!didLoopBack)
1056 /* We didn't loop back. Advance to the next wave header */
1057 wwo->lpPlayPtr = wwo->lpPlayPtr->lpNext;
1059 if (!wwo->lpPlayPtr)
1060 wwo->state = WINE_WS_STOPPED;
1061 else
1062 wodHelper_CheckForLoopBegin(wwo);
1066 /* Send the "done" notification for each WAVEHDR in a list. The list must be
1067 * free-standing. It should not be part of a device's queue.
1068 * This function must be called with the WAVEOUT lock *not* held. Furthermore,
1069 * it does not lock it, itself. That's because the callback to the application
1070 * may prompt the application to operate on the device, and we don't want to
1071 * deadlock.
1073 static void wodHelper_NotifyDoneForList(WINE_WAVEOUT* wwo, LPWAVEHDR lpWaveHdr)
1075 while (lpWaveHdr)
1077 LPWAVEHDR lpNext = lpWaveHdr->lpNext;
1079 lpWaveHdr->lpNext = NULL;
1080 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1081 lpWaveHdr->dwFlags |= WHDR_DONE;
1082 wodNotifyClient(wwo, WOM_DONE, (DWORD)lpWaveHdr, 0);
1084 lpWaveHdr = lpNext;
1088 /* if force is TRUE then notify the client that all the headers were completed
1090 static void wodHelper_NotifyCompletions(WINE_WAVEOUT* wwo, BOOL force)
1092 LPWAVEHDR lpFirstDoneWaveHdr = NULL;
1094 OSSpinLockLock(&wwo->lock);
1096 /* First, excise all of the done headers from the queue into
1097 * a free-standing list. */
1098 if (force)
1100 lpFirstDoneWaveHdr = wwo->lpQueuePtr;
1101 wwo->lpQueuePtr = NULL;
1103 else
1105 LPWAVEHDR lpWaveHdr;
1106 LPWAVEHDR lpLastDoneWaveHdr = NULL;
1108 /* Start from lpQueuePtr and keep notifying until:
1109 * - we hit an unwritten wavehdr
1110 * - we hit the beginning of a running loop
1111 * - we hit a wavehdr which hasn't finished playing
1113 for (
1114 lpWaveHdr = wwo->lpQueuePtr;
1115 lpWaveHdr &&
1116 lpWaveHdr != wwo->lpPlayPtr &&
1117 lpWaveHdr != wwo->lpLoopPtr;
1118 lpWaveHdr = lpWaveHdr->lpNext
1121 if (!lpFirstDoneWaveHdr)
1122 lpFirstDoneWaveHdr = lpWaveHdr;
1123 lpLastDoneWaveHdr = lpWaveHdr;
1126 if (lpLastDoneWaveHdr)
1128 wwo->lpQueuePtr = lpLastDoneWaveHdr->lpNext;
1129 lpLastDoneWaveHdr->lpNext = NULL;
1133 OSSpinLockUnlock(&wwo->lock);
1135 /* Now, send the "done" notification for each header in our list. */
1136 wodHelper_NotifyDoneForList(wwo, lpFirstDoneWaveHdr);
1140 /**************************************************************************
1141 * wodWrite [internal]
1144 static DWORD wodWrite(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1146 LPWAVEHDR*wh;
1147 WINE_WAVEOUT *wwo;
1149 TRACE("(%u, %p, %08X);\n", wDevID, lpWaveHdr, dwSize);
1151 /* first, do the sanity checks... */
1152 if (wDevID >= MAX_WAVEOUTDRV)
1154 WARN("bad dev ID !\n");
1155 return MMSYSERR_BADDEVICEID;
1158 wwo = &WOutDev[wDevID];
1160 if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
1162 TRACE("unprepared\n");
1163 return WAVERR_UNPREPARED;
1166 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1168 TRACE("still playing\n");
1169 return WAVERR_STILLPLAYING;
1172 lpWaveHdr->dwFlags &= ~WHDR_DONE;
1173 lpWaveHdr->dwFlags |= WHDR_INQUEUE;
1174 lpWaveHdr->lpNext = 0;
1176 OSSpinLockLock(&wwo->lock);
1177 /* insert buffer at the end of queue */
1178 for (wh = &(wwo->lpQueuePtr); *wh; wh = &((*wh)->lpNext))
1179 /* Do nothing */;
1180 *wh = lpWaveHdr;
1182 if (!wwo->lpPlayPtr)
1184 wwo->lpPlayPtr = lpWaveHdr;
1186 if (wwo->state == WINE_WS_STOPPED)
1187 wwo->state = WINE_WS_PLAYING;
1189 wodHelper_CheckForLoopBegin(wwo);
1191 wwo->dwPartialOffset = 0;
1193 OSSpinLockUnlock(&wwo->lock);
1195 return MMSYSERR_NOERROR;
1198 /**************************************************************************
1199 * wodPause [internal]
1201 static DWORD wodPause(WORD wDevID)
1203 OSStatus status;
1205 TRACE("(%u);!\n", wDevID);
1207 if (wDevID >= MAX_WAVEOUTDRV)
1209 WARN("bad device ID !\n");
1210 return MMSYSERR_BADDEVICEID;
1213 /* The order of the following operations is important since we can't hold
1214 * the mutex while we make an Audio Unit call. Stop the Audio Unit before
1215 * setting the PAUSED state. In wodRestart, the order is reversed. This
1216 * guarantees that we can't get into a situation where the state is
1217 * PLAYING or STOPPED but the Audio Unit isn't running. Although we can
1218 * be in PAUSED state with the Audio Unit still running, that's harmless
1219 * because the render callback will just produce silence.
1221 status = AudioOutputUnitStop(WOutDev[wDevID].audioUnit);
1222 if (status) {
1223 WARN("AudioOutputUnitStop return %c%c%c%c\n",
1224 (char) (status >> 24), (char) (status >> 16), (char) (status >> 8), (char) status);
1227 OSSpinLockLock(&WOutDev[wDevID].lock);
1228 if (WOutDev[wDevID].state == WINE_WS_PLAYING || WOutDev[wDevID].state == WINE_WS_STOPPED)
1229 WOutDev[wDevID].state = WINE_WS_PAUSED;
1230 OSSpinLockUnlock(&WOutDev[wDevID].lock);
1232 return MMSYSERR_NOERROR;
1235 /**************************************************************************
1236 * wodRestart [internal]
1238 static DWORD wodRestart(WORD wDevID)
1240 OSStatus status;
1242 TRACE("(%u);\n", wDevID);
1244 if (wDevID >= MAX_WAVEOUTDRV )
1246 WARN("bad device ID !\n");
1247 return MMSYSERR_BADDEVICEID;
1250 /* The order of the following operations is important since we can't hold
1251 * the mutex while we make an Audio Unit call. Set the PLAYING/STOPPED
1252 * state before starting the Audio Unit. In wodPause, the order is
1253 * reversed. This guarantees that we can't get into a situation where
1254 * the state is PLAYING or STOPPED but the Audio Unit isn't running.
1255 * Although we can be in PAUSED state with the Audio Unit still running,
1256 * that's harmless because the render callback will just produce silence.
1258 OSSpinLockLock(&WOutDev[wDevID].lock);
1259 if (WOutDev[wDevID].state == WINE_WS_PAUSED)
1261 if (WOutDev[wDevID].lpPlayPtr)
1262 WOutDev[wDevID].state = WINE_WS_PLAYING;
1263 else
1264 WOutDev[wDevID].state = WINE_WS_STOPPED;
1266 OSSpinLockUnlock(&WOutDev[wDevID].lock);
1268 status = AudioOutputUnitStart(WOutDev[wDevID].audioUnit);
1269 if (status) {
1270 ERR("AudioOutputUnitStart return %c%c%c%c\n",
1271 (char) (status >> 24), (char) (status >> 16), (char) (status >> 8), (char) status);
1272 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1275 return MMSYSERR_NOERROR;
1278 /**************************************************************************
1279 * wodReset [internal]
1281 static DWORD wodReset(WORD wDevID)
1283 WINE_WAVEOUT* wwo;
1284 OSStatus status;
1285 LPWAVEHDR lpSavedQueuePtr;
1287 TRACE("(%u);\n", wDevID);
1289 if (wDevID >= MAX_WAVEOUTDRV)
1291 WARN("bad device ID !\n");
1292 return MMSYSERR_BADDEVICEID;
1295 wwo = &WOutDev[wDevID];
1297 OSSpinLockLock(&wwo->lock);
1299 if (wwo->state == WINE_WS_CLOSED)
1301 OSSpinLockUnlock(&wwo->lock);
1302 WARN("resetting a closed device\n");
1303 return MMSYSERR_INVALHANDLE;
1306 lpSavedQueuePtr = wwo->lpQueuePtr;
1307 wwo->lpPlayPtr = wwo->lpQueuePtr = wwo->lpLoopPtr = NULL;
1308 wwo->state = WINE_WS_STOPPED;
1309 wwo->dwPlayedTotal = wwo->dwWrittenTotal = 0;
1311 wwo->dwPartialOffset = 0; /* Clear partial wavehdr */
1313 OSSpinLockUnlock(&wwo->lock);
1315 status = AudioOutputUnitStart(wwo->audioUnit);
1317 if (status) {
1318 ERR( "AudioOutputUnitStart return %c%c%c%c\n",
1319 (char) (status >> 24), (char) (status >> 16), (char) (status >> 8), (char) status);
1320 return MMSYSERR_ERROR; /* FIXME return an error based on the OSStatus */
1323 /* Now, send the "done" notification for each header in our list. */
1324 /* Do this last so the reset operation is effectively complete before the
1325 * app does whatever it's going to do in response to these notifications. */
1326 wodHelper_NotifyDoneForList(wwo, lpSavedQueuePtr);
1328 return MMSYSERR_NOERROR;
1331 /**************************************************************************
1332 * wodGetPosition [internal]
1334 static DWORD wodGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
1336 DWORD val;
1337 WINE_WAVEOUT* wwo;
1339 TRACE("(%u, %p, %u);\n", wDevID, lpTime, uSize);
1341 if (wDevID >= MAX_WAVEOUTDRV)
1343 WARN("bad device ID !\n");
1344 return MMSYSERR_BADDEVICEID;
1347 /* if null pointer to time structure return error */
1348 if (lpTime == NULL) return MMSYSERR_INVALPARAM;
1350 wwo = &WOutDev[wDevID];
1352 OSSpinLockLock(&WOutDev[wDevID].lock);
1353 val = wwo->dwPlayedTotal;
1354 OSSpinLockUnlock(&WOutDev[wDevID].lock);
1356 return bytes_to_mmtime(lpTime, val, &wwo->format);
1359 /**************************************************************************
1360 * wodGetVolume [internal]
1362 static DWORD wodGetVolume(WORD wDevID, LPDWORD lpdwVol)
1364 float left;
1365 float right;
1367 if (wDevID >= MAX_WAVEOUTDRV)
1369 WARN("bad device ID !\n");
1370 return MMSYSERR_BADDEVICEID;
1373 TRACE("(%u, %p);\n", wDevID, lpdwVol);
1375 AudioUnit_GetVolume(WOutDev[wDevID].audioUnit, &left, &right);
1377 *lpdwVol = ((WORD) left * 0xFFFFl) + (((WORD) right * 0xFFFFl) << 16);
1379 return MMSYSERR_NOERROR;
1382 /**************************************************************************
1383 * wodSetVolume [internal]
1385 static DWORD wodSetVolume(WORD wDevID, DWORD dwParam)
1387 float left;
1388 float right;
1390 if (wDevID >= MAX_WAVEOUTDRV)
1392 WARN("bad device ID !\n");
1393 return MMSYSERR_BADDEVICEID;
1396 left = LOWORD(dwParam) / 65535.0f;
1397 right = HIWORD(dwParam) / 65535.0f;
1399 TRACE("(%u, %08x);\n", wDevID, dwParam);
1401 AudioUnit_SetVolume(WOutDev[wDevID].audioUnit, left, right);
1403 return MMSYSERR_NOERROR;
1406 /**************************************************************************
1407 * wodGetNumDevs [internal]
1409 static DWORD wodGetNumDevs(void)
1411 TRACE("\n");
1412 return MAX_WAVEOUTDRV;
1415 /**************************************************************************
1416 * wodDevInterfaceSize [internal]
1418 static DWORD wodDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
1420 TRACE("(%u, %p)\n", wDevID, dwParam1);
1422 *dwParam1 = MultiByteToWideChar(CP_UNIXCP, 0, WOutDev[wDevID].cadev->interface_name, -1,
1423 NULL, 0 ) * sizeof(WCHAR);
1424 return MMSYSERR_NOERROR;
1427 /**************************************************************************
1428 * wodDevInterface [internal]
1430 static DWORD wodDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
1432 TRACE("\n");
1433 if (dwParam2 >= MultiByteToWideChar(CP_UNIXCP, 0, WOutDev[wDevID].cadev->interface_name, -1,
1434 NULL, 0 ) * sizeof(WCHAR))
1436 MultiByteToWideChar(CP_UNIXCP, 0, WOutDev[wDevID].cadev->interface_name, -1,
1437 dwParam1, dwParam2 / sizeof(WCHAR));
1438 return MMSYSERR_NOERROR;
1440 return MMSYSERR_INVALPARAM;
1443 /**************************************************************************
1444 * widDsCreate [internal]
1446 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
1448 TRACE("(%d,%p)\n",wDevID,drv);
1450 FIXME("DirectSound not implemented\n");
1451 FIXME("The (slower) DirectSound HEL mode will be used instead.\n");
1452 return MMSYSERR_NOTSUPPORTED;
1455 /**************************************************************************
1456 * wodDsDesc [internal]
1458 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc)
1460 /* The DirectSound HEL will automatically wrap a non-DirectSound-capable
1461 * driver in a DirectSound adaptor, thus allowing the driver to be used by
1462 * DirectSound clients. However, it only does this if we respond
1463 * successfully to the DRV_QUERYDSOUNDDESC message. It's enough to fill in
1464 * the driver and device names of the description output parameter. */
1465 *desc = WOutDev[wDevID].cadev->ds_desc;
1466 return MMSYSERR_NOERROR;
1469 /**************************************************************************
1470 * wodMessage (WINECOREAUDIO.7)
1472 DWORD WINAPI CoreAudio_wodMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
1473 DWORD dwParam1, DWORD dwParam2)
1475 TRACE("(%u, %s, %08x, %08x, %08x);\n",
1476 wDevID, getMessage(wMsg), dwUser, dwParam1, dwParam2);
1478 switch (wMsg) {
1479 case DRVM_INIT:
1480 case DRVM_EXIT:
1481 case DRVM_ENABLE:
1482 case DRVM_DISABLE:
1484 /* FIXME: Pretend this is supported */
1485 return 0;
1486 case WODM_OPEN: return wodOpen(wDevID, (LPWAVEOPENDESC) dwParam1, dwParam2);
1487 case WODM_CLOSE: return wodClose(wDevID);
1488 case WODM_WRITE: return wodWrite(wDevID, (LPWAVEHDR) dwParam1, dwParam2);
1489 case WODM_PAUSE: return wodPause(wDevID);
1490 case WODM_GETPOS: return wodGetPosition(wDevID, (LPMMTIME) dwParam1, dwParam2);
1491 case WODM_BREAKLOOP: return MMSYSERR_NOTSUPPORTED;
1492 case WODM_PREPARE: return wodPrepare(wDevID, (LPWAVEHDR)dwParam1, dwParam2);
1493 case WODM_UNPREPARE: return wodUnprepare(wDevID, (LPWAVEHDR)dwParam1, dwParam2);
1495 case WODM_GETDEVCAPS: return wodGetDevCaps(wDevID, (LPWAVEOUTCAPSW) dwParam1, dwParam2);
1496 case WODM_GETNUMDEVS: return wodGetNumDevs();
1498 case WODM_GETPITCH:
1499 case WODM_SETPITCH:
1500 case WODM_GETPLAYBACKRATE:
1501 case WODM_SETPLAYBACKRATE: return MMSYSERR_NOTSUPPORTED;
1502 case WODM_GETVOLUME: return wodGetVolume(wDevID, (LPDWORD)dwParam1);
1503 case WODM_SETVOLUME: return wodSetVolume(wDevID, dwParam1);
1504 case WODM_RESTART: return wodRestart(wDevID);
1505 case WODM_RESET: return wodReset(wDevID);
1507 case DRV_QUERYDEVICEINTERFACESIZE: return wodDevInterfaceSize (wDevID, (LPDWORD)dwParam1);
1508 case DRV_QUERYDEVICEINTERFACE: return wodDevInterface (wDevID, (PWCHAR)dwParam1, dwParam2);
1509 case DRV_QUERYDSOUNDIFACE: return wodDsCreate (wDevID, (PIDSDRIVER*)dwParam1);
1510 case DRV_QUERYDSOUNDDESC: return wodDsDesc (wDevID, (PDSDRIVERDESC)dwParam1);
1512 default:
1513 FIXME("unknown message %d!\n", wMsg);
1516 return MMSYSERR_NOTSUPPORTED;
1519 /*======================================================================*
1520 * Low level DSOUND implementation *
1521 *======================================================================*/
1523 typedef struct IDsDriverImpl IDsDriverImpl;
1524 typedef struct IDsDriverBufferImpl IDsDriverBufferImpl;
1526 struct IDsDriverImpl
1528 /* IUnknown fields */
1529 const IDsDriverVtbl *lpVtbl;
1530 DWORD ref;
1531 /* IDsDriverImpl fields */
1532 UINT wDevID;
1533 IDsDriverBufferImpl*primary;
1536 struct IDsDriverBufferImpl
1538 /* IUnknown fields */
1539 const IDsDriverBufferVtbl *lpVtbl;
1540 DWORD ref;
1541 /* IDsDriverBufferImpl fields */
1542 IDsDriverImpl* drv;
1543 DWORD buflen;
1548 CoreAudio IO threaded callback,
1549 we can't call Wine debug channels, critical section or anything using NtCurrentTeb here.
1551 OSStatus CoreAudio_woAudioUnitIOProc(void *inRefCon,
1552 AudioUnitRenderActionFlags *ioActionFlags,
1553 const AudioTimeStamp *inTimeStamp,
1554 UInt32 inBusNumber,
1555 UInt32 inNumberFrames,
1556 AudioBufferList *ioData)
1558 UInt32 buffer;
1559 WINE_WAVEOUT *wwo = (WINE_WAVEOUT *) inRefCon;
1560 int needNotify = 0;
1562 unsigned int dataNeeded = ioData->mBuffers[0].mDataByteSize;
1563 unsigned int dataProvided = 0;
1565 OSSpinLockLock(&wwo->lock);
1567 while (dataNeeded > 0 && wwo->state == WINE_WS_PLAYING && wwo->lpPlayPtr)
1569 unsigned int available = wwo->lpPlayPtr->dwBufferLength - wwo->dwPartialOffset;
1570 unsigned int toCopy;
1572 if (available >= dataNeeded)
1573 toCopy = dataNeeded;
1574 else
1575 toCopy = available;
1577 if (toCopy > 0)
1579 memcpy((char*)ioData->mBuffers[0].mData + dataProvided,
1580 wwo->lpPlayPtr->lpData + wwo->dwPartialOffset, toCopy);
1581 wwo->dwPartialOffset += toCopy;
1582 wwo->dwPlayedTotal += toCopy;
1583 dataProvided += toCopy;
1584 dataNeeded -= toCopy;
1585 available -= toCopy;
1588 if (available == 0)
1590 wodHelper_PlayPtrNext(wwo);
1591 needNotify = 1;
1594 ioData->mBuffers[0].mDataByteSize = dataProvided;
1596 OSSpinLockUnlock(&wwo->lock);
1598 /* We can't provide any more wave data. Fill the rest with silence. */
1599 if (dataNeeded > 0)
1601 if (!dataProvided)
1602 *ioActionFlags |= kAudioUnitRenderAction_OutputIsSilence;
1603 memset((char*)ioData->mBuffers[0].mData + dataProvided, 0, dataNeeded);
1604 dataProvided += dataNeeded;
1605 dataNeeded = 0;
1608 /* We only fill buffer 0. Set any others that might be requested to 0. */
1609 for (buffer = 1; buffer < ioData->mNumberBuffers; buffer++)
1611 memset(ioData->mBuffers[buffer].mData, 0, ioData->mBuffers[buffer].mDataByteSize);
1614 if (needNotify) wodSendNotifyCompletionsMessage(wwo);
1615 return noErr;
1619 /*======================================================================*
1620 * Low level WAVE IN implementation *
1621 *======================================================================*/
1623 /**************************************************************************
1624 * widNotifyClient [internal]
1626 static DWORD widNotifyClient(WINE_WAVEIN* wwi, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
1628 TRACE("wMsg = 0x%04x dwParm1 = %04X dwParam2 = %04X\n", wMsg, dwParam1, dwParam2);
1630 switch (wMsg)
1632 case WIM_OPEN:
1633 case WIM_CLOSE:
1634 case WIM_DATA:
1635 if (wwi->wFlags != DCB_NULL &&
1636 !DriverCallback(wwi->waveDesc.dwCallback, wwi->wFlags,
1637 (HDRVR)wwi->waveDesc.hWave, wMsg, wwi->waveDesc.dwInstance,
1638 dwParam1, dwParam2))
1640 WARN("can't notify client !\n");
1641 return MMSYSERR_ERROR;
1643 break;
1644 default:
1645 FIXME("Unknown callback message %u\n", wMsg);
1646 return MMSYSERR_INVALPARAM;
1648 return MMSYSERR_NOERROR;
1652 /**************************************************************************
1653 * widHelper_NotifyCompletions [internal]
1655 static void widHelper_NotifyCompletions(WINE_WAVEIN* wwi)
1657 LPWAVEHDR lpWaveHdr;
1658 LPWAVEHDR lpFirstDoneWaveHdr = NULL;
1659 LPWAVEHDR lpLastDoneWaveHdr = NULL;
1661 OSSpinLockLock(&wwi->lock);
1663 /* First, excise all of the done headers from the queue into
1664 * a free-standing list. */
1666 /* Start from lpQueuePtr and keep notifying until:
1667 * - we hit an unfilled wavehdr
1668 * - we hit the end of the list
1670 for (
1671 lpWaveHdr = wwi->lpQueuePtr;
1672 lpWaveHdr &&
1673 lpWaveHdr->dwBytesRecorded >= lpWaveHdr->dwBufferLength;
1674 lpWaveHdr = lpWaveHdr->lpNext
1677 if (!lpFirstDoneWaveHdr)
1678 lpFirstDoneWaveHdr = lpWaveHdr;
1679 lpLastDoneWaveHdr = lpWaveHdr;
1682 if (lpLastDoneWaveHdr)
1684 wwi->lpQueuePtr = lpLastDoneWaveHdr->lpNext;
1685 lpLastDoneWaveHdr->lpNext = NULL;
1688 OSSpinLockUnlock(&wwi->lock);
1690 /* Now, send the "done" notification for each header in our list. */
1691 lpWaveHdr = lpFirstDoneWaveHdr;
1692 while (lpWaveHdr)
1694 LPWAVEHDR lpNext = lpWaveHdr->lpNext;
1696 lpWaveHdr->lpNext = NULL;
1697 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1698 lpWaveHdr->dwFlags |= WHDR_DONE;
1699 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
1701 lpWaveHdr = lpNext;
1706 /**************************************************************************
1707 * widGetDevCaps [internal]
1709 static DWORD widGetDevCaps(WORD wDevID, LPWAVEINCAPSW lpCaps, DWORD dwSize)
1711 TRACE("(%u, %p, %u);\n", wDevID, lpCaps, dwSize);
1713 if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
1715 if (wDevID >= MAX_WAVEINDRV)
1717 TRACE("MAX_WAVEINDRV reached !\n");
1718 return MMSYSERR_BADDEVICEID;
1721 memcpy(lpCaps, &WInDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
1722 return MMSYSERR_NOERROR;
1726 /**************************************************************************
1727 * widHelper_DestroyAudioBufferList [internal]
1728 * Convenience function to dispose of our audio buffers
1730 static void widHelper_DestroyAudioBufferList(AudioBufferList* list)
1732 if (list)
1734 UInt32 i;
1735 for (i = 0; i < list->mNumberBuffers; i++)
1737 if (list->mBuffers[i].mData)
1738 HeapFree(GetProcessHeap(), 0, list->mBuffers[i].mData);
1740 HeapFree(GetProcessHeap(), 0, list);
1745 #define AUDIOBUFFERLISTSIZE(numBuffers) (offsetof(AudioBufferList, mBuffers) + (numBuffers) * sizeof(AudioBuffer))
1747 /**************************************************************************
1748 * widHelper_AllocateAudioBufferList [internal]
1749 * Convenience function to allocate our audio buffers
1751 static AudioBufferList* widHelper_AllocateAudioBufferList(UInt32 numChannels, UInt32 bitsPerChannel, UInt32 bufferFrames, BOOL interleaved)
1753 UInt32 numBuffers;
1754 UInt32 channelsPerFrame;
1755 UInt32 bytesPerFrame;
1756 UInt32 bytesPerBuffer;
1757 AudioBufferList* list;
1758 UInt32 i;
1760 if (interleaved)
1762 /* For interleaved audio, we allocate one buffer for all channels. */
1763 numBuffers = 1;
1764 channelsPerFrame = numChannels;
1766 else
1768 numBuffers = numChannels;
1769 channelsPerFrame = 1;
1772 bytesPerFrame = bitsPerChannel * channelsPerFrame / 8;
1773 bytesPerBuffer = bytesPerFrame * bufferFrames;
1775 list = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, AUDIOBUFFERLISTSIZE(numBuffers));
1776 if (list == NULL)
1777 return NULL;
1779 list->mNumberBuffers = numBuffers;
1780 for (i = 0; i < numBuffers; ++i)
1782 list->mBuffers[i].mNumberChannels = channelsPerFrame;
1783 list->mBuffers[i].mDataByteSize = bytesPerBuffer;
1784 list->mBuffers[i].mData = HeapAlloc(GetProcessHeap(), 0, bytesPerBuffer);
1785 if (list->mBuffers[i].mData == NULL)
1787 widHelper_DestroyAudioBufferList(list);
1788 return NULL;
1791 return list;
1795 /**************************************************************************
1796 * widOpen [internal]
1798 static DWORD widOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
1800 WINE_WAVEIN* wwi;
1801 UInt32 frameCount;
1803 TRACE("(%u, %p, %08X);\n", wDevID, lpDesc, dwFlags);
1804 if (lpDesc == NULL)
1806 WARN("Invalid Parameter !\n");
1807 return MMSYSERR_INVALPARAM;
1809 if (wDevID >= MAX_WAVEINDRV)
1811 TRACE ("MAX_WAVEINDRV reached !\n");
1812 return MMSYSERR_BADDEVICEID;
1815 TRACE("Format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
1816 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1817 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
1819 if (lpDesc->lpFormat->wFormatTag != WAVE_FORMAT_PCM ||
1820 lpDesc->lpFormat->nChannels == 0 ||
1821 lpDesc->lpFormat->nSamplesPerSec == 0 ||
1822 lpDesc->lpFormat->nSamplesPerSec != AudioUnit_GetInputDeviceSampleRate()
1825 WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
1826 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1827 lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
1828 return WAVERR_BADFORMAT;
1831 if (dwFlags & WAVE_FORMAT_QUERY)
1833 TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
1834 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1835 lpDesc->lpFormat->nSamplesPerSec);
1836 return MMSYSERR_NOERROR;
1839 wwi = &WInDev[wDevID];
1840 if (!OSSpinLockTry(&wwi->lock))
1841 return MMSYSERR_ALLOCATED;
1843 if (wwi->state != WINE_WS_CLOSED)
1845 OSSpinLockUnlock(&wwi->lock);
1846 return MMSYSERR_ALLOCATED;
1849 wwi->state = WINE_WS_STOPPED;
1850 wwi->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
1852 wwi->waveDesc = *lpDesc;
1853 memcpy(&wwi->format, lpDesc->lpFormat, sizeof(PCMWAVEFORMAT));
1855 if (wwi->format.wBitsPerSample == 0)
1857 WARN("Resetting zeroed wBitsPerSample\n");
1858 wwi->format.wBitsPerSample = 8 *
1859 (wwi->format.wf.nAvgBytesPerSec /
1860 wwi->format.wf.nSamplesPerSec) /
1861 wwi->format.wf.nChannels;
1864 wwi->dwTotalRecorded = 0;
1866 wwi->trace_on = TRACE_ON(wave);
1867 wwi->warn_on = WARN_ON(wave);
1868 wwi->err_on = ERR_ON(wave);
1870 if (!AudioUnit_CreateInputUnit(wwi, &wwi->audioUnit,
1871 wwi->format.wf.nChannels, wwi->format.wf.nSamplesPerSec,
1872 wwi->format.wBitsPerSample, &frameCount))
1874 ERR("AudioUnit_CreateInputUnit failed\n");
1875 OSSpinLockUnlock(&wwi->lock);
1876 return MMSYSERR_ERROR;
1879 /* Allocate our audio buffers */
1880 wwi->bufferList = widHelper_AllocateAudioBufferList(wwi->format.wf.nChannels,
1881 wwi->format.wBitsPerSample, frameCount, TRUE);
1882 if (wwi->bufferList == NULL)
1884 ERR("Failed to allocate buffer list\n");
1885 AudioUnitUninitialize(wwi->audioUnit);
1886 AudioUnit_CloseAudioUnit(wwi->audioUnit);
1887 OSSpinLockUnlock(&wwi->lock);
1888 return MMSYSERR_NOMEM;
1891 /* Keep a copy of the buffer list structure (but not the buffers themselves)
1892 * in case AudioUnitRender clobbers the original, as it won't to do. */
1893 wwi->bufferListCopy = HeapAlloc(GetProcessHeap(), 0, AUDIOBUFFERLISTSIZE(wwi->bufferList->mNumberBuffers));
1894 if (wwi->bufferListCopy == NULL)
1896 ERR("Failed to allocate buffer list copy\n");
1897 widHelper_DestroyAudioBufferList(wwi->bufferList);
1898 AudioUnitUninitialize(wwi->audioUnit);
1899 AudioUnit_CloseAudioUnit(wwi->audioUnit);
1900 OSSpinLockUnlock(&wwi->lock);
1901 return MMSYSERR_NOMEM;
1903 memcpy(wwi->bufferListCopy, wwi->bufferList, AUDIOBUFFERLISTSIZE(wwi->bufferList->mNumberBuffers));
1905 OSSpinLockUnlock(&wwi->lock);
1907 return widNotifyClient(wwi, WIM_OPEN, 0L, 0L);
1911 /**************************************************************************
1912 * widClose [internal]
1914 static DWORD widClose(WORD wDevID)
1916 DWORD ret = MMSYSERR_NOERROR;
1917 WINE_WAVEIN* wwi;
1919 TRACE("(%u);\n", wDevID);
1921 if (wDevID >= MAX_WAVEINDRV)
1923 WARN("bad device ID !\n");
1924 return MMSYSERR_BADDEVICEID;
1927 wwi = &WInDev[wDevID];
1928 OSSpinLockLock(&wwi->lock);
1929 if (wwi->state == WINE_WS_CLOSED)
1931 WARN("Device already closed.\n");
1932 ret = MMSYSERR_INVALHANDLE;
1934 else if (wwi->lpQueuePtr)
1936 WARN("Buffers in queue.\n");
1937 ret = WAVERR_STILLPLAYING;
1939 else
1941 wwi->state = WINE_WS_CLOSED;
1944 OSSpinLockUnlock(&wwi->lock);
1946 if (ret == MMSYSERR_NOERROR)
1948 OSStatus err = AudioUnitUninitialize(wwi->audioUnit);
1949 if (err)
1951 ERR("AudioUnitUninitialize return %c%c%c%c\n", (char) (err >> 24),
1952 (char) (err >> 16),
1953 (char) (err >> 8),
1954 (char) err);
1957 if (!AudioUnit_CloseAudioUnit(wwi->audioUnit))
1959 ERR("Can't close AudioUnit\n");
1962 /* Dellocate our audio buffers */
1963 widHelper_DestroyAudioBufferList(wwi->bufferList);
1964 wwi->bufferList = NULL;
1965 HeapFree(GetProcessHeap(), 0, wwi->bufferListCopy);
1966 wwi->bufferListCopy = NULL;
1968 ret = widNotifyClient(wwi, WIM_CLOSE, 0L, 0L);
1971 return ret;
1975 /**************************************************************************
1976 * widAddBuffer [internal]
1978 static DWORD widAddBuffer(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1980 DWORD ret = MMSYSERR_NOERROR;
1981 WINE_WAVEIN* wwi;
1983 TRACE("(%u, %p, %08X);\n", wDevID, lpWaveHdr, dwSize);
1985 if (wDevID >= MAX_WAVEINDRV)
1987 WARN("invalid device ID\n");
1988 return MMSYSERR_INVALHANDLE;
1990 if (!(lpWaveHdr->dwFlags & WHDR_PREPARED))
1992 TRACE("never been prepared !\n");
1993 return WAVERR_UNPREPARED;
1995 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1997 TRACE("header already in use !\n");
1998 return WAVERR_STILLPLAYING;
2001 wwi = &WInDev[wDevID];
2002 OSSpinLockLock(&wwi->lock);
2004 if (wwi->state == WINE_WS_CLOSED)
2006 WARN("Trying to add buffer to closed device.\n");
2007 ret = MMSYSERR_INVALHANDLE;
2009 else
2011 LPWAVEHDR* wh;
2013 lpWaveHdr->dwFlags |= WHDR_INQUEUE;
2014 lpWaveHdr->dwFlags &= ~WHDR_DONE;
2015 lpWaveHdr->dwBytesRecorded = 0;
2016 lpWaveHdr->lpNext = NULL;
2018 /* insert buffer at end of queue */
2019 for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext))
2020 /* Do nothing */;
2021 *wh = lpWaveHdr;
2024 OSSpinLockUnlock(&wwi->lock);
2026 return ret;
2030 /**************************************************************************
2031 * widStart [internal]
2033 static DWORD widStart(WORD wDevID)
2035 DWORD ret = MMSYSERR_NOERROR;
2036 WINE_WAVEIN* wwi;
2038 TRACE("(%u);\n", wDevID);
2039 if (wDevID >= MAX_WAVEINDRV)
2041 WARN("invalid device ID\n");
2042 return MMSYSERR_INVALHANDLE;
2045 /* The order of the following operations is important since we can't hold
2046 * the mutex while we make an Audio Unit call. Set the PLAYING state
2047 * before starting the Audio Unit. In widStop, the order is reversed.
2048 * This guarantees that we can't get into a situation where the state is
2049 * PLAYING but the Audio Unit isn't running. Although we can be in STOPPED
2050 * state with the Audio Unit still running, that's harmless because the
2051 * input callback will just throw away the sound data.
2053 wwi = &WInDev[wDevID];
2054 OSSpinLockLock(&wwi->lock);
2056 if (wwi->state == WINE_WS_CLOSED)
2058 WARN("Trying to start closed device.\n");
2059 ret = MMSYSERR_INVALHANDLE;
2061 else
2062 wwi->state = WINE_WS_PLAYING;
2064 OSSpinLockUnlock(&wwi->lock);
2066 if (ret == MMSYSERR_NOERROR)
2068 /* Start pulling for audio data */
2069 OSStatus err = AudioOutputUnitStart(wwi->audioUnit);
2070 if (err != noErr)
2071 ERR("Failed to start AU: %08lx\n", err);
2073 TRACE("Recording started...\n");
2076 return ret;
2080 /**************************************************************************
2081 * widStop [internal]
2083 static DWORD widStop(WORD wDevID)
2085 DWORD ret = MMSYSERR_NOERROR;
2086 WINE_WAVEIN* wwi;
2087 WAVEHDR* lpWaveHdr = NULL;
2088 OSStatus err;
2090 TRACE("(%u);\n", wDevID);
2091 if (wDevID >= MAX_WAVEINDRV)
2093 WARN("invalid device ID\n");
2094 return MMSYSERR_INVALHANDLE;
2097 wwi = &WInDev[wDevID];
2099 /* The order of the following operations is important since we can't hold
2100 * the mutex while we make an Audio Unit call. Stop the Audio Unit before
2101 * setting the STOPPED state. In widStart, the order is reversed. This
2102 * guarantees that we can't get into a situation where the state is
2103 * PLAYING but the Audio Unit isn't running. Although we can be in STOPPED
2104 * state with the Audio Unit still running, that's harmless because the
2105 * input callback will just throw away the sound data.
2107 err = AudioOutputUnitStop(wwi->audioUnit);
2108 if (err != noErr)
2109 WARN("Failed to stop AU: %08lx\n", err);
2111 TRACE("Recording stopped.\n");
2113 OSSpinLockLock(&wwi->lock);
2115 if (wwi->state == WINE_WS_CLOSED)
2117 WARN("Trying to stop closed device.\n");
2118 ret = MMSYSERR_INVALHANDLE;
2120 else if (wwi->state != WINE_WS_STOPPED)
2122 wwi->state = WINE_WS_STOPPED;
2123 /* If there's a buffer in progress, it's done. Remove it from the
2124 * queue so that we can return it to the app, below. */
2125 if (wwi->lpQueuePtr)
2127 lpWaveHdr = wwi->lpQueuePtr;
2128 wwi->lpQueuePtr = lpWaveHdr->lpNext;
2132 OSSpinLockUnlock(&wwi->lock);
2134 if (lpWaveHdr)
2136 lpWaveHdr->lpNext = NULL;
2137 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2138 lpWaveHdr->dwFlags |= WHDR_DONE;
2139 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2142 return ret;
2145 /**************************************************************************
2146 * widGetPos [internal]
2148 static DWORD widGetPos(WORD wDevID, LPMMTIME lpTime, UINT size)
2150 DWORD val;
2151 WINE_WAVEIN* wwi;
2153 TRACE("(%u);\n", wDevID);
2154 if (wDevID >= MAX_WAVEINDRV)
2156 WARN("invalid device ID\n");
2157 return MMSYSERR_INVALHANDLE;
2160 wwi = &WInDev[wDevID];
2162 OSSpinLockLock(&WInDev[wDevID].lock);
2163 val = wwi->dwTotalRecorded;
2164 OSSpinLockUnlock(&WInDev[wDevID].lock);
2166 return bytes_to_mmtime(lpTime, val, &wwi->format);
2169 /**************************************************************************
2170 * widReset [internal]
2172 static DWORD widReset(WORD wDevID)
2174 DWORD ret = MMSYSERR_NOERROR;
2175 WINE_WAVEIN* wwi;
2176 WAVEHDR* lpWaveHdr = NULL;
2178 TRACE("(%u);\n", wDevID);
2179 if (wDevID >= MAX_WAVEINDRV)
2181 WARN("invalid device ID\n");
2182 return MMSYSERR_INVALHANDLE;
2185 wwi = &WInDev[wDevID];
2186 OSSpinLockLock(&wwi->lock);
2188 if (wwi->state == WINE_WS_CLOSED)
2190 WARN("Trying to reset a closed device.\n");
2191 ret = MMSYSERR_INVALHANDLE;
2193 else
2195 lpWaveHdr = wwi->lpQueuePtr;
2196 wwi->lpQueuePtr = NULL;
2197 wwi->state = WINE_WS_STOPPED;
2198 wwi->dwTotalRecorded = 0;
2201 OSSpinLockUnlock(&wwi->lock);
2203 if (ret == MMSYSERR_NOERROR)
2205 OSStatus err = AudioOutputUnitStop(wwi->audioUnit);
2206 if (err != noErr)
2207 WARN("Failed to stop AU: %08lx\n", err);
2209 TRACE("Recording stopped.\n");
2212 while (lpWaveHdr)
2214 WAVEHDR* lpNext = lpWaveHdr->lpNext;
2216 lpWaveHdr->lpNext = NULL;
2217 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2218 lpWaveHdr->dwFlags |= WHDR_DONE;
2219 widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
2221 lpWaveHdr = lpNext;
2224 return ret;
2228 /**************************************************************************
2229 * widGetNumDevs [internal]
2231 static DWORD widGetNumDevs(void)
2233 return MAX_WAVEINDRV;
2237 /**************************************************************************
2238 * widDevInterfaceSize [internal]
2240 static DWORD widDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
2242 TRACE("(%u, %p)\n", wDevID, dwParam1);
2244 *dwParam1 = MultiByteToWideChar(CP_UNIXCP, 0, WInDev[wDevID].interface_name, -1,
2245 NULL, 0 ) * sizeof(WCHAR);
2246 return MMSYSERR_NOERROR;
2250 /**************************************************************************
2251 * widDevInterface [internal]
2253 static DWORD widDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
2255 if (dwParam2 >= MultiByteToWideChar(CP_UNIXCP, 0, WInDev[wDevID].interface_name, -1,
2256 NULL, 0 ) * sizeof(WCHAR))
2258 MultiByteToWideChar(CP_UNIXCP, 0, WInDev[wDevID].interface_name, -1,
2259 dwParam1, dwParam2 / sizeof(WCHAR));
2260 return MMSYSERR_NOERROR;
2262 return MMSYSERR_INVALPARAM;
2266 /**************************************************************************
2267 * widDsCreate [internal]
2269 static DWORD widDsCreate(UINT wDevID, PIDSCDRIVER* drv)
2271 TRACE("(%d,%p)\n",wDevID,drv);
2273 FIXME("DirectSoundCapture not implemented\n");
2274 FIXME("The (slower) DirectSound HEL mode will be used instead.\n");
2275 return MMSYSERR_NOTSUPPORTED;
2278 /**************************************************************************
2279 * widDsDesc [internal]
2281 static DWORD widDsDesc(UINT wDevID, PDSDRIVERDESC desc)
2283 /* The DirectSound HEL will automatically wrap a non-DirectSound-capable
2284 * driver in a DirectSound adaptor, thus allowing the driver to be used by
2285 * DirectSound clients. However, it only does this if we respond
2286 * successfully to the DRV_QUERYDSOUNDDESC message. It's enough to fill in
2287 * the driver and device names of the description output parameter. */
2288 memset(desc, 0, sizeof(*desc));
2289 lstrcpynA(desc->szDrvname, "winecoreaudio.drv", sizeof(desc->szDrvname) - 1);
2290 lstrcpynA(desc->szDesc, WInDev[wDevID].interface_name, sizeof(desc->szDesc) - 1);
2291 return MMSYSERR_NOERROR;
2295 /**************************************************************************
2296 * widMessage (WINECOREAUDIO.6)
2298 DWORD WINAPI CoreAudio_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2299 DWORD dwParam1, DWORD dwParam2)
2301 TRACE("(%u, %04X, %08X, %08X, %08X);\n",
2302 wDevID, wMsg, dwUser, dwParam1, dwParam2);
2304 switch (wMsg)
2306 case DRVM_INIT:
2307 case DRVM_EXIT:
2308 case DRVM_ENABLE:
2309 case DRVM_DISABLE:
2310 /* FIXME: Pretend this is supported */
2311 return 0;
2312 case WIDM_OPEN: return widOpen (wDevID, (LPWAVEOPENDESC)dwParam1, dwParam2);
2313 case WIDM_CLOSE: return widClose (wDevID);
2314 case WIDM_ADDBUFFER: return widAddBuffer (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2315 case WIDM_PREPARE: return MMSYSERR_NOTSUPPORTED;
2316 case WIDM_UNPREPARE: return MMSYSERR_NOTSUPPORTED;
2317 case WIDM_GETDEVCAPS: return widGetDevCaps (wDevID, (LPWAVEINCAPSW)dwParam1, dwParam2);
2318 case WIDM_GETNUMDEVS: return widGetNumDevs ();
2319 case WIDM_RESET: return widReset (wDevID);
2320 case WIDM_START: return widStart (wDevID);
2321 case WIDM_STOP: return widStop (wDevID);
2322 case WIDM_GETPOS: return widGetPos (wDevID, (LPMMTIME)dwParam1, (UINT)dwParam2 );
2323 case DRV_QUERYDEVICEINTERFACESIZE: return widDevInterfaceSize (wDevID, (LPDWORD)dwParam1);
2324 case DRV_QUERYDEVICEINTERFACE: return widDevInterface (wDevID, (PWCHAR)dwParam1, dwParam2);
2325 case DRV_QUERYDSOUNDIFACE: return widDsCreate (wDevID, (PIDSCDRIVER*)dwParam1);
2326 case DRV_QUERYDSOUNDDESC: return widDsDesc (wDevID, (PDSDRIVERDESC)dwParam1);
2327 default:
2328 FIXME("unknown message %d!\n", wMsg);
2331 return MMSYSERR_NOTSUPPORTED;
2335 OSStatus CoreAudio_wiAudioUnitIOProc(void *inRefCon,
2336 AudioUnitRenderActionFlags *ioActionFlags,
2337 const AudioTimeStamp *inTimeStamp,
2338 UInt32 inBusNumber,
2339 UInt32 inNumberFrames,
2340 AudioBufferList *ioData)
2342 WINE_WAVEIN* wwi = (WINE_WAVEIN*)inRefCon;
2343 OSStatus err = noErr;
2344 BOOL needNotify = FALSE;
2345 WAVEHDR* lpStorePtr;
2346 unsigned int dataToStore;
2347 unsigned int dataStored = 0;
2350 if (wwi->trace_on)
2351 fprintf(stderr, "trace:wave:CoreAudio_wiAudioUnitIOProc (ioActionFlags = %08lx, "
2352 "inTimeStamp = { %f, %x%08x, %f, %x%08x, %08lx }, inBusNumber = %lu, inNumberFrames = %lu)\n",
2353 *ioActionFlags, inTimeStamp->mSampleTime, (DWORD)(inTimeStamp->mHostTime >>32),
2354 (DWORD)inTimeStamp->mHostTime, inTimeStamp->mRateScalar, (DWORD)(inTimeStamp->mWordClockTime >> 32),
2355 (DWORD)inTimeStamp->mWordClockTime, inTimeStamp->mFlags, inBusNumber, inNumberFrames);
2357 /* Render into audio buffer */
2358 /* FIXME: implement sample rate conversion on input. This will require
2359 * a different render strategy. We'll need to buffer the sound data
2360 * received here and pass it off to an AUConverter in another thread. */
2361 err = AudioUnitRender(wwi->audioUnit, ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, wwi->bufferList);
2362 if (err)
2364 if (wwi->err_on)
2365 fprintf(stderr, "err:wave:CoreAudio_wiAudioUnitIOProc AudioUnitRender failed with error %li\n", err);
2366 return err;
2369 /* Copy from audio buffer to the wavehdrs */
2370 dataToStore = wwi->bufferList->mBuffers[0].mDataByteSize;
2372 OSSpinLockLock(&wwi->lock);
2374 lpStorePtr = wwi->lpQueuePtr;
2376 while (dataToStore > 0 && wwi->state == WINE_WS_PLAYING && lpStorePtr)
2378 unsigned int room = lpStorePtr->dwBufferLength - lpStorePtr->dwBytesRecorded;
2379 unsigned int toCopy;
2381 if (wwi->trace_on)
2382 fprintf(stderr, "trace:wave:CoreAudio_wiAudioUnitIOProc Looking to store %u bytes to wavehdr %p, which has room for %u\n",
2383 dataToStore, lpStorePtr, room);
2385 if (room >= dataToStore)
2386 toCopy = dataToStore;
2387 else
2388 toCopy = room;
2390 if (toCopy > 0)
2392 memcpy(lpStorePtr->lpData + lpStorePtr->dwBytesRecorded,
2393 (char*)wwi->bufferList->mBuffers[0].mData + dataStored, toCopy);
2394 lpStorePtr->dwBytesRecorded += toCopy;
2395 wwi->dwTotalRecorded += toCopy;
2396 dataStored += toCopy;
2397 dataToStore -= toCopy;
2398 room -= toCopy;
2401 if (room == 0)
2403 lpStorePtr = lpStorePtr->lpNext;
2404 needNotify = TRUE;
2408 OSSpinLockUnlock(&wwi->lock);
2410 /* Restore the audio buffer list structure from backup, in case
2411 * AudioUnitRender clobbered it. (It modifies mDataByteSize and may even
2412 * give us a different mData buffer to avoid a copy.) */
2413 memcpy(wwi->bufferList, wwi->bufferListCopy, AUDIOBUFFERLISTSIZE(wwi->bufferList->mNumberBuffers));
2415 if (needNotify) wodSendNotifyInputCompletionsMessage(wwi);
2416 return err;
2419 #else
2421 /**************************************************************************
2422 * widMessage (WINECOREAUDIO.6)
2424 DWORD WINAPI CoreAudio_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2425 DWORD dwParam1, DWORD dwParam2)
2427 FIXME("(%u, %04X, %08X, %08X, %08X): CoreAudio support not compiled into wine\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2428 return MMSYSERR_NOTENABLED;
2431 /**************************************************************************
2432 * wodMessage (WINECOREAUDIO.7)
2434 DWORD WINAPI CoreAudio_wodMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2435 DWORD dwParam1, DWORD dwParam2)
2437 FIXME("(%u, %04X, %08X, %08X, %08X): CoreAudio support not compiled into wine\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2438 return MMSYSERR_NOTENABLED;
2441 #endif