winmm: Fix SEEK_END direction of mmio files without buffering.
[wine] / dlls / winmm / waveform.c
1 /*
2  * Copyright 1993      Martin Ayotte
3  *           1998-2002 Eric Pouech
4  *           2011 Andrew Eikum for CodeWeavers
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 #include <stdio.h>
22 #include <stdarg.h>
23 #include <string.h>
24
25 #define NONAMELESSUNION
26 #define NONAMELESSSTRUCT
27 #define COBJMACROS
28 #include "windef.h"
29 #include "winbase.h"
30 #include "wingdi.h"
31 #include "mmsystem.h"
32 #include "mmreg.h"
33 #include "msacm.h"
34 #include "winuser.h"
35 #include "winnls.h"
36 #include "winternl.h"
37
38 #include "winemm.h"
39
40 #include "ole2.h"
41 #include "initguid.h"
42 #include "devpkey.h"
43 #include "mmdeviceapi.h"
44 #include "audioclient.h"
45 #include "audiopolicy.h"
46
47 #include "wine/debug.h"
48
49 WINE_DEFAULT_DEBUG_CHANNEL(winmm);
50
51 /* FIXME: Should be localized */
52 static const WCHAR volumeW[] = {'V','o','l','u','m','e',0};
53 static const WCHAR mastervolumeW[] = {'M','a','s','t','e','r',' ','V','o','l',
54     'u','m','e',0};
55 static const WCHAR muteW[] = {'M','u','t','e',0};
56
57 /* HWAVE (and HMIXER) format:
58  *
59  * XXXX... 1FDD DDDD IIII IIII
60  * X = unused (must be 0)
61  * 1 = the bit is set to 1, to avoid all-zero HWAVEs
62  * F = flow direction (0 = IN, 1 = OUT)
63  * D = index into g_out_mmdevices
64  * I = index in the mmdevice's devices array
65  *
66  * Two reasons that we don't just use pointers:
67  *   - HWAVEs must fit into 16 bits for compatibility with old applications.
68  *   - We must be able to identify bad devices without crashing.
69  */
70
71 #define MAX_DEVICES 256
72
73 typedef struct _WINMM_CBInfo {
74     DWORD_PTR callback;
75     DWORD_PTR user;
76     DWORD flags;
77     HWAVE hwave;
78 } WINMM_CBInfo;
79
80 struct _WINMM_MMDevice;
81 typedef struct _WINMM_MMDevice WINMM_MMDevice;
82
83 typedef struct _WINMM_Device {
84     WINMM_CBInfo cb_info;
85
86     HWAVE handle;
87
88     BOOL open;
89
90     IMMDevice *device;
91     IAudioClient *client;
92     IAudioRenderClient *render;
93     IAudioCaptureClient *capture;
94     IAudioClock *clock;
95     IAudioStreamVolume *volume;
96
97     HACMSTREAM acm_handle;
98     ACMSTREAMHEADER acm_hdr;
99     UINT32 acm_offs;
100
101     WAVEHDR *first, *last, *playing, *loop_start;
102
103     BOOL stopped;
104     DWORD loop_counter;
105     UINT32 bytes_per_frame, samples_per_sec, ofs_bytes, played_frames;
106
107     /* stored in frames of sample rate, *not* AC::GetFrequency */
108     UINT64 last_clock_pos;
109
110     HANDLE event;
111     CRITICAL_SECTION lock;
112
113     WINMM_MMDevice *parent;
114 } WINMM_Device;
115
116 struct _WINMM_MMDevice {
117     WAVEOUTCAPSW out_caps; /* must not be modified outside of WINMM_InitMMDevices*/
118     WAVEINCAPSW in_caps; /* must not be modified outside of WINMM_InitMMDevices*/
119     WCHAR *dev_id;
120
121     ISimpleAudioVolume *volume;
122
123     GUID session;
124
125     /* HMIXER format is the same as the HWAVE format, but the I bits are
126      * replaced by the value of this counter, to keep each HMIXER unique */
127     UINT mixer_count;
128
129     CRITICAL_SECTION lock;
130
131     WINMM_Device *devices[MAX_DEVICES];
132 };
133
134 static WINMM_MMDevice *g_out_mmdevices;
135 static UINT g_outmmdevices_count;
136
137 static WINMM_MMDevice *g_in_mmdevices;
138 static UINT g_inmmdevices_count;
139
140 static IMMDeviceEnumerator *g_devenum;
141
142 #define WINMM_WM_QUIT WM_USER
143
144 static CRITICAL_SECTION g_devthread_lock;
145 static CRITICAL_SECTION_DEBUG g_devthread_lock_debug =
146 {
147     0, 0, &g_devthread_lock,
148     { &g_devthread_lock_debug.ProcessLocksList, &g_devthread_lock_debug.ProcessLocksList },
149       0, 0, { (DWORD_PTR)(__FILE__ ": g_devthread_lock") }
150 };
151 static CRITICAL_SECTION g_devthread_lock = { &g_devthread_lock_debug, -1, 0, 0, 0, 0 };
152 static HANDLE g_devices_thread;
153 static HWND g_devices_hwnd;
154
155 static UINT g_devhandle_count;
156 static HANDLE *g_device_handles;
157 static WINMM_Device **g_handle_devices;
158
159 typedef struct _WINMM_OpenInfo {
160     HWAVE handle;
161     UINT req_device;
162     WAVEFORMATEX *format;
163     DWORD_PTR callback;
164     DWORD_PTR cb_user;
165     DWORD flags;
166 } WINMM_OpenInfo;
167
168 typedef struct _WINMM_ControlDetails {
169     HMIXEROBJ hmix;
170     MIXERCONTROLDETAILS *details;
171     DWORD flags;
172 } WINMM_ControlDetails;
173
174 typedef struct _WINMM_QueryInterfaceInfo {
175     BOOL is_out;
176     UINT index;
177     WCHAR *str;
178     UINT *len_bytes;
179 } WINMM_QueryInterfaceInfo;
180
181 static LRESULT WOD_Open(WINMM_OpenInfo *info);
182 static LRESULT WOD_Close(HWAVEOUT hwave);
183 static LRESULT WID_Open(WINMM_OpenInfo *info);
184 static LRESULT WID_Close(HWAVEIN hwave);
185
186 void WINMM_DeleteWaveform(void)
187 {
188     UINT i, j;
189
190     if(g_devices_hwnd){
191         for(i = 0; i < g_outmmdevices_count; ++i){
192             WINMM_MMDevice *mmdevice = &g_out_mmdevices[i];
193             for(j = 0; j < MAX_DEVICES && mmdevice->devices[j]; ++j){
194                 WINMM_Device *device = mmdevice->devices[j];
195                 SendMessageW(g_devices_hwnd, WODM_CLOSE, (WPARAM)device->handle, 0);
196             }
197         }
198
199         for(i = 0; i < g_inmmdevices_count; ++i){
200             WINMM_MMDevice *mmdevice = &g_in_mmdevices[i];
201             for(j = 0; j < MAX_DEVICES && mmdevice->devices[j]; ++j){
202                 WINMM_Device *device = mmdevice->devices[j];
203                 SendMessageW(g_devices_hwnd, WIDM_CLOSE, (WPARAM)device->handle, 0);
204             }
205         }
206
207         SendMessageW(g_devices_hwnd, WINMM_WM_QUIT, 0, 0);
208
209         for(i = 0; i < g_outmmdevices_count; ++i){
210             WINMM_MMDevice *mmdevice = &g_out_mmdevices[i];
211
212             for(j = 0; j < MAX_DEVICES && mmdevice->devices[j]; ++j){
213                 WINMM_Device *device = mmdevice->devices[j];
214                 if(device->handle)
215                     CloseHandle(device->handle);
216                 DeleteCriticalSection(&device->lock);
217             }
218
219             if(mmdevice->volume)
220                 ISimpleAudioVolume_Release(mmdevice->volume);
221             CoTaskMemFree(mmdevice->dev_id);
222             DeleteCriticalSection(&mmdevice->lock);
223         }
224
225         for(i = 0; i < g_inmmdevices_count; ++i){
226             WINMM_MMDevice *mmdevice = &g_in_mmdevices[i];
227
228             for(j = 0; j < MAX_DEVICES && mmdevice->devices[j]; ++j){
229                 WINMM_Device *device = mmdevice->devices[j];
230                 if(device->handle)
231                     CloseHandle(device->handle);
232                 DeleteCriticalSection(&device->lock);
233             }
234
235             if(mmdevice->volume)
236                 ISimpleAudioVolume_Release(mmdevice->volume);
237             CoTaskMemFree(mmdevice->dev_id);
238             DeleteCriticalSection(&mmdevice->lock);
239         }
240
241         HeapFree(GetProcessHeap(), 0, g_out_mmdevices);
242         HeapFree(GetProcessHeap(), 0, g_in_mmdevices);
243
244         HeapFree(GetProcessHeap(), 0, g_device_handles);
245         HeapFree(GetProcessHeap(), 0, g_handle_devices);
246     }
247
248     DeleteCriticalSection(&g_devthread_lock);
249 }
250
251 static inline HWAVE WINMM_MakeHWAVE(UINT mmdevice, BOOL is_out, UINT device)
252 {
253     return ULongToHandle((1 << 15) | ((!!is_out) << 14) |
254             (mmdevice << 8) | device);
255 }
256
257 static inline void WINMM_DecomposeHWAVE(HWAVE hwave, UINT *mmdevice_index,
258         BOOL *is_out, UINT *device_index, UINT *junk)
259 {
260     ULONG32 l = HandleToULong(hwave);
261     *device_index = l & 0xFF;
262     *mmdevice_index = (l >> 8) & 0x3F;
263     *is_out = (l >> 14) & 0x1;
264     *junk = l >> 15;
265 }
266
267 static void WINMM_InitDevice(WINMM_Device *device,
268         WINMM_MMDevice *parent, HWAVE hwave)
269 {
270     InitializeCriticalSection(&device->lock);
271     device->lock.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": WINMM_Device.lock");
272
273     device->handle = hwave;
274     device->parent = parent;
275 }
276
277 /* finds the first unused Device, marks it as "open", and returns
278  * a pointer to the device
279  *
280  * IMPORTANT: it is the caller's responsibility to release the device's lock
281  * on success
282  */
283 static WINMM_Device *WINMM_FindUnusedDevice(BOOL is_out, UINT mmdevice_index)
284 {
285     WINMM_MMDevice *mmdevice;
286     UINT i;
287
288     if(is_out)
289         mmdevice = &g_out_mmdevices[mmdevice_index];
290     else
291         mmdevice = &g_in_mmdevices[mmdevice_index];
292
293     EnterCriticalSection(&mmdevice->lock);
294     for(i = 0; i < MAX_DEVICES; ++i){
295         WINMM_Device *device = mmdevice->devices[i];
296
297         if(!device){
298             device = mmdevice->devices[i] = HeapAlloc(GetProcessHeap(),
299                     HEAP_ZERO_MEMORY, sizeof(WINMM_Device));
300             if(!device){
301                 LeaveCriticalSection(&mmdevice->lock);
302                 return NULL;
303             }
304
305             WINMM_InitDevice(device, mmdevice,
306                     WINMM_MakeHWAVE(mmdevice_index, is_out, i));
307             EnterCriticalSection(&device->lock);
308         }else
309             EnterCriticalSection(&device->lock);
310
311         if(!device->open){
312             LeaveCriticalSection(&mmdevice->lock);
313             device->open = TRUE;
314             TRACE("Found free device: mmdevice: %u, device id: %u\n",
315                     mmdevice_index, i);
316             return device;
317         }
318
319         LeaveCriticalSection(&device->lock);
320     }
321
322     LeaveCriticalSection(&mmdevice->lock);
323
324     TRACE("All devices in use: mmdevice: %u\n", mmdevice_index);
325
326     return NULL;
327 }
328
329 static inline BOOL WINMM_ValidateAndLock(WINMM_Device *device)
330 {
331     if(!device)
332         return FALSE;
333
334     EnterCriticalSection(&device->lock);
335
336     if(!device->open){
337         LeaveCriticalSection(&device->lock);
338         return FALSE;
339     }
340
341     return TRUE;
342 }
343
344 static WINMM_Device *WINMM_GetDeviceFromHWAVE(HWAVE hwave)
345 {
346     WINMM_MMDevice *mmdevice;
347     WINMM_Device *device;
348     UINT mmdevice_index, device_index, junk;
349     BOOL is_out;
350
351     WINMM_DecomposeHWAVE(hwave, &mmdevice_index, &is_out, &device_index, &junk);
352
353     if(junk != 0x1)
354         return NULL;
355
356     if(mmdevice_index >= (is_out ? g_outmmdevices_count : g_inmmdevices_count))
357         return NULL;
358
359     if(is_out)
360         mmdevice = &g_out_mmdevices[mmdevice_index];
361     else
362         mmdevice = &g_in_mmdevices[mmdevice_index];
363
364     EnterCriticalSection(&mmdevice->lock);
365
366     device = mmdevice->devices[device_index];
367
368     LeaveCriticalSection(&mmdevice->lock);
369
370     return device;
371 }
372
373 /* Note: NotifyClient should never be called while holding the device lock
374  * since the client may call wave* functions from within the callback. */
375 static inline void WINMM_NotifyClient(WINMM_CBInfo *info, WORD msg, DWORD_PTR param1,
376         DWORD_PTR param2)
377 {
378     DriverCallback(info->callback, info->flags, (HDRVR)info->hwave,
379         msg, info->user, param1, param2);
380 }
381
382 static MMRESULT hr2mmr(HRESULT hr)
383 {
384     switch(hr){
385     case S_OK:
386     case AUDCLNT_E_NOT_STOPPED:
387         return MMSYSERR_NOERROR;
388     case AUDCLNT_E_UNSUPPORTED_FORMAT:
389         return WAVERR_BADFORMAT;
390     case AUDCLNT_E_DEVICE_IN_USE:
391         return MMSYSERR_ALLOCATED;
392     case AUDCLNT_E_ENDPOINT_CREATE_FAILED:
393         return MMSYSERR_NOTENABLED;
394     case E_OUTOFMEMORY:
395         return MMSYSERR_NOMEM;
396     case E_POINTER:
397     case E_INVALIDARG:
398         return MMSYSERR_INVALPARAM;
399     case AUDCLNT_E_DEVICE_INVALIDATED: /* DSERR_BUFFERLOST */
400     default:
401         return FAILED(hr) ? MMSYSERR_ERROR : MMSYSERR_NOERROR;
402     }
403 }
404
405 static HRESULT WINMM_GetFriendlyName(IMMDevice *device, WCHAR *out,
406         UINT outlen)
407 {
408     IPropertyStore *ps;
409     PROPVARIANT var;
410     HRESULT hr;
411
412     hr = IMMDevice_OpenPropertyStore(device, STGM_READ, &ps);
413     if(FAILED(hr))
414         return hr;
415
416     PropVariantInit(&var);
417
418     hr = IPropertyStore_GetValue(ps,
419             (PROPERTYKEY*)&DEVPKEY_Device_FriendlyName, &var);
420     if(FAILED(hr)){
421         IPropertyStore_Release(ps);
422         return hr;
423     }
424
425     lstrcpynW(out, var.u.pwszVal, outlen);
426
427     PropVariantClear(&var);
428
429     IPropertyStore_Release(ps);
430
431     return S_OK;
432 }
433
434 static HRESULT WINMM_TestFormat(IAudioClient *client, DWORD rate, DWORD depth,
435         WORD channels)
436 {
437     WAVEFORMATEX fmt, *junk;
438     HRESULT hr;
439
440     fmt.wFormatTag = WAVE_FORMAT_PCM;
441     fmt.nChannels = channels;
442     fmt.nSamplesPerSec = rate;
443     fmt.wBitsPerSample = depth;
444     fmt.nBlockAlign = (channels * depth) / 8;
445     fmt.nAvgBytesPerSec = rate * fmt.nBlockAlign;
446     fmt.cbSize = 0;
447
448     hr = IAudioClient_IsFormatSupported(client, AUDCLNT_SHAREMODE_SHARED,
449             &fmt, &junk);
450     if(SUCCEEDED(hr))
451         CoTaskMemFree(junk);
452
453     return hr;
454 }
455
456 static struct _TestFormat {
457     DWORD flag;
458     DWORD rate;
459     DWORD depth;
460     WORD channels;
461 } formats_to_test[] = {
462     { WAVE_FORMAT_1M08, 11025, 8, 1 },
463     { WAVE_FORMAT_1M16, 11025, 16, 1 },
464     { WAVE_FORMAT_1S08, 11025, 8, 2 },
465     { WAVE_FORMAT_1S16, 11025, 16, 2 },
466     { WAVE_FORMAT_2M08, 22050, 8, 1 },
467     { WAVE_FORMAT_2M16, 22050, 16, 1 },
468     { WAVE_FORMAT_2S08, 22050, 8, 2 },
469     { WAVE_FORMAT_2S16, 22050, 16, 2 },
470     { WAVE_FORMAT_4M08, 44100, 8, 1 },
471     { WAVE_FORMAT_4M16, 44100, 16, 1 },
472     { WAVE_FORMAT_4S08, 44100, 8, 2 },
473     { WAVE_FORMAT_4S16, 44100, 16, 2 },
474     { WAVE_FORMAT_48M08, 48000, 8, 1 },
475     { WAVE_FORMAT_48M16, 48000, 16, 1 },
476     { WAVE_FORMAT_48S08, 48000, 8, 2 },
477     { WAVE_FORMAT_48S16, 48000, 16, 2 },
478     { WAVE_FORMAT_96M08, 96000, 8, 1 },
479     { WAVE_FORMAT_96M16, 96000, 16, 1 },
480     { WAVE_FORMAT_96S08, 96000, 8, 2 },
481     { WAVE_FORMAT_96S16, 96000, 16, 2 },
482     {0}
483 };
484
485 static DWORD WINMM_GetSupportedFormats(IMMDevice *device)
486 {
487     DWORD flags = 0;
488     HRESULT hr;
489     struct _TestFormat *fmt;
490     IAudioClient *client;
491
492     hr = IMMDevice_Activate(device, &IID_IAudioClient,
493             CLSCTX_INPROC_SERVER, NULL, (void**)&client);
494     if(FAILED(hr))
495         return 0;
496
497     for(fmt = formats_to_test; fmt->flag; ++fmt){
498         hr = WINMM_TestFormat(client, fmt->rate, fmt->depth, fmt->channels);
499         if(hr == S_OK)
500             flags |= fmt->flag;
501     }
502
503     IAudioClient_Release(client);
504
505     return flags;
506 }
507
508 static HRESULT WINMM_InitMMDevice(EDataFlow flow, IMMDevice *device,
509         WINMM_MMDevice *dev, UINT index)
510 {
511     HRESULT hr;
512
513     if(flow == eRender){
514         dev->out_caps.wMid = 0xFF;
515         dev->out_caps.wPid = 0xFF;
516         dev->out_caps.vDriverVersion = 0x00010001;
517         dev->out_caps.dwFormats = WINMM_GetSupportedFormats(device);
518         dev->out_caps.wReserved1 = 0;
519         dev->out_caps.dwSupport = WAVECAPS_LRVOLUME | WAVECAPS_VOLUME |
520             WAVECAPS_SAMPLEACCURATE;
521         dev->out_caps.wChannels = 2;
522         dev->out_caps.szPname[0] = '\0';
523
524         hr = WINMM_GetFriendlyName(device, dev->out_caps.szPname,
525                 sizeof(dev->out_caps.szPname) /
526                 sizeof(*dev->out_caps.szPname));
527         if(FAILED(hr))
528             return hr;
529     }else{
530         dev->in_caps.wMid = 0xFF;
531         dev->in_caps.wPid = 0xFF;
532         dev->in_caps.vDriverVersion = 0x00010001;
533         dev->in_caps.dwFormats = WINMM_GetSupportedFormats(device);
534         dev->in_caps.wReserved1 = 0;
535         dev->in_caps.wChannels = 2;
536         dev->in_caps.szPname[0] = '\0';
537
538         hr = WINMM_GetFriendlyName(device, dev->in_caps.szPname,
539                 sizeof(dev->in_caps.szPname) /
540                 sizeof(*dev->in_caps.szPname));
541         if(FAILED(hr))
542             return hr;
543     }
544
545     hr = IMMDevice_GetId(device, &dev->dev_id);
546     if(FAILED(hr))
547         return hr;
548
549     CoCreateGuid(&dev->session);
550
551     InitializeCriticalSection(&dev->lock);
552     dev->lock.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": WINMM_Device.lock");
553
554     return S_OK;
555 }
556
557 static HRESULT WINMM_EnumDevices(WINMM_MMDevice **devices, UINT *devcount,
558         EDataFlow flow, IMMDeviceEnumerator *devenum)
559 {
560     IMMDeviceCollection *devcoll;
561     HRESULT hr;
562
563     hr = IMMDeviceEnumerator_EnumAudioEndpoints(devenum, flow,
564             DEVICE_STATE_ACTIVE, &devcoll);
565     if(FAILED(hr))
566         return hr;
567
568     hr = IMMDeviceCollection_GetCount(devcoll, devcount);
569     if(FAILED(hr)){
570         IMMDeviceCollection_Release(devcoll);
571         return hr;
572     }
573
574     if(*devcount > 0){
575         UINT n, count;
576         IMMDevice *def_dev = NULL;
577
578         *devices = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
579                 sizeof(WINMM_MMDevice) * (*devcount));
580         if(!*devices){
581             IMMDeviceCollection_Release(devcoll);
582             return E_OUTOFMEMORY;
583         }
584
585         count = 0;
586
587         /* make sure that device 0 is the default device */
588         hr = IMMDeviceEnumerator_GetDefaultAudioEndpoint(devenum,
589                 flow, eConsole, &def_dev);
590         if(SUCCEEDED(hr)){
591             WINMM_InitMMDevice(flow, def_dev, &(*devices)[0], 0);
592             count = 1;
593         }
594
595         for(n = 0; n < *devcount; ++n){
596             IMMDevice *device;
597
598             hr = IMMDeviceCollection_Item(devcoll, n, &device);
599             if(SUCCEEDED(hr)){
600                 if(device != def_dev){
601                     WINMM_InitMMDevice(flow, device, &(*devices)[count], count);
602                     ++count;
603                 }
604
605                 IMMDevice_Release(device);
606             }
607         }
608
609         if(def_dev)
610             IMMDevice_Release(def_dev);
611
612         *devcount = count;
613     }
614
615     IMMDeviceCollection_Release(devcoll);
616
617     return S_OK;
618 }
619
620 static HRESULT WINMM_InitMMDevices(void)
621 {
622     HRESULT hr, init_hr;
623     IMMDeviceEnumerator *devenum = NULL;
624
625     if(g_outmmdevices_count || g_inmmdevices_count)
626         return S_FALSE;
627
628     init_hr = CoInitialize(NULL);
629
630     hr = CoCreateInstance(&CLSID_MMDeviceEnumerator, NULL,
631             CLSCTX_INPROC_SERVER, &IID_IMMDeviceEnumerator, (void**)&devenum);
632     if(FAILED(hr))
633         goto exit;
634
635     hr = WINMM_EnumDevices(&g_out_mmdevices, &g_outmmdevices_count, eRender, devenum);
636     if(FAILED(hr)){
637         g_outmmdevices_count = 0;
638         g_inmmdevices_count = 0;
639         goto exit;
640     }
641
642     hr = WINMM_EnumDevices(&g_in_mmdevices, &g_inmmdevices_count, eCapture, devenum);
643     if(FAILED(hr)){
644         g_inmmdevices_count = 0;
645         goto exit;
646     }
647
648 exit:
649     if(devenum)
650         IMMDeviceEnumerator_Release(devenum);
651     if(SUCCEEDED(init_hr))
652         CoUninitialize();
653
654     return hr;
655 }
656
657 static inline BOOL WINMM_IsMapper(UINT device)
658 {
659     return (device == WAVE_MAPPER || device == (UINT16)WAVE_MAPPER);
660 }
661
662 static MMRESULT WINMM_TryDeviceMapping(WINMM_OpenInfo *info, WORD channels,
663         DWORD freq, DWORD bits_per_samp, BOOL is_out)
664 {
665     WINMM_Device *device;
666     WAVEFORMATEX target;
667     MMRESULT mr;
668     UINT i;
669
670     TRACE("format: %u, channels: %u, sample rate: %u, bit depth: %u\n",
671             WAVE_FORMAT_PCM, channels, freq, bits_per_samp);
672
673     target.wFormatTag = WAVE_FORMAT_PCM;
674     target.nChannels = channels;
675     target.nSamplesPerSec = freq;
676     target.wBitsPerSample = bits_per_samp;
677     target.nBlockAlign = (target.nChannels * target.wBitsPerSample) / 8;
678     target.nAvgBytesPerSec = target.nSamplesPerSec * target.nBlockAlign;
679     target.cbSize = 0;
680
681     if(is_out)
682         mr = acmStreamOpen(NULL, NULL, info->format, &target, NULL, 0,
683                 0, ACM_STREAMOPENF_QUERY);
684     else
685         mr = acmStreamOpen(NULL, NULL, &target, info->format, NULL, 0,
686                 0, ACM_STREAMOPENF_QUERY);
687     if(mr != MMSYSERR_NOERROR)
688         return mr;
689
690     /* ACM can convert from src->dst, so try to find a device
691      * that supports dst */
692     if(is_out){
693         if(WINMM_IsMapper(info->req_device)){
694             for(i = 0; i < g_outmmdevices_count; ++i){
695                 WINMM_OpenInfo l_info = *info;
696                 l_info.req_device = i;
697                 l_info.format = &target;
698                 mr = WOD_Open(&l_info);
699                 if(mr == MMSYSERR_NOERROR){
700                     info->handle = l_info.handle;
701                     break;
702                 }
703             }
704         }else{
705             WINMM_OpenInfo l_info = *info;
706             l_info.flags &= ~WAVE_MAPPED;
707             l_info.format = &target;
708             mr = WOD_Open(&l_info);
709             if(mr == MMSYSERR_NOERROR)
710                 info->handle = l_info.handle;
711         }
712     }else{
713         if(WINMM_IsMapper(info->req_device)){
714             for(i = 0; i < g_inmmdevices_count; ++i){
715                 WINMM_OpenInfo l_info = *info;
716                 l_info.req_device = i;
717                 l_info.format = &target;
718                 mr = WID_Open(&l_info);
719                 if(mr == MMSYSERR_NOERROR){
720                     info->handle = l_info.handle;
721                     break;
722                 }
723             }
724         }else{
725             WINMM_OpenInfo l_info = *info;
726             l_info.flags &= ~WAVE_MAPPED;
727             l_info.format = &target;
728             mr = WID_Open(&l_info);
729             if(mr == MMSYSERR_NOERROR)
730                 info->handle = l_info.handle;
731         }
732     }
733     if(mr != MMSYSERR_NOERROR)
734         return WAVERR_BADFORMAT;
735
736     device = WINMM_GetDeviceFromHWAVE(info->handle);
737     if(!device)
738         return MMSYSERR_INVALHANDLE;
739
740     /* set up the ACM stream */
741     if(is_out)
742         mr = acmStreamOpen(&device->acm_handle, NULL, info->format, &target,
743                 NULL, 0, 0, 0);
744     else
745         mr = acmStreamOpen(&device->acm_handle, NULL, &target, info->format,
746                 NULL, 0, 0, 0);
747     if(mr != MMSYSERR_NOERROR){
748         if(is_out)
749             WOD_Close((HWAVEOUT)info->handle);
750         else
751             WID_Close((HWAVEIN)info->handle);
752         return mr;
753     }
754
755     TRACE("Success\n");
756     return MMSYSERR_NOERROR;
757 }
758
759 static MMRESULT WINMM_MapDevice(WINMM_OpenInfo *info, BOOL is_out)
760 {
761     UINT i;
762     MMRESULT mr;
763     WAVEFORMATEXTENSIBLE *fmtex = (WAVEFORMATEXTENSIBLE*)info->format;
764
765     TRACE("(%p, %d)\n", info, is_out);
766
767     /* try to find a direct match */
768     if(is_out){
769         WINMM_OpenInfo l_info = *info;
770         if(WINMM_IsMapper(info->req_device)){
771             for(i = 0; i < g_outmmdevices_count; ++i){
772                 l_info.req_device = i;
773                 mr = WOD_Open(&l_info);
774                 if(mr == MMSYSERR_NOERROR){
775                     info->handle = l_info.handle;
776                     return mr;
777                 }
778             }
779         }else{
780             l_info.flags &= ~WAVE_MAPPED;
781             mr = WOD_Open(&l_info);
782             if(mr == MMSYSERR_NOERROR){
783                 info->handle = l_info.handle;
784                 return mr;
785             }
786         }
787     }else{
788         WINMM_OpenInfo l_info = *info;
789         if(WINMM_IsMapper(info->req_device)){
790             for(i = 0; i < g_inmmdevices_count; ++i){
791                 l_info.req_device = i;
792                 mr = WID_Open(&l_info);
793                 if(mr == MMSYSERR_NOERROR){
794                     info->handle = l_info.handle;
795                     return mr;
796                 }
797             }
798         }else{
799             l_info.flags &= ~WAVE_MAPPED;
800             mr = WID_Open(&l_info);
801             if(mr == MMSYSERR_NOERROR){
802                 info->handle = l_info.handle;
803                 return mr;
804             }
805         }
806     }
807
808     /* no direct match, so set up the ACM stream */
809     if(info->format->wFormatTag != WAVE_FORMAT_PCM &&
810             !(info->format->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
811               IsEqualGUID(&fmtex->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM))){
812         /* convert to PCM format if it's not already */
813         mr = WINMM_TryDeviceMapping(info, info->format->nChannels,
814                 info->format->nSamplesPerSec, 16, is_out);
815         if(mr == MMSYSERR_NOERROR)
816             return mr;
817
818         mr = WINMM_TryDeviceMapping(info, info->format->nChannels,
819                 info->format->nSamplesPerSec, 8, is_out);
820         if(mr == MMSYSERR_NOERROR)
821             return mr;
822     }else{
823         WORD channels;
824
825         /* first try just changing bit depth and channels */
826         channels = info->format->nChannels;
827         mr = WINMM_TryDeviceMapping(info, channels,
828                 info->format->nSamplesPerSec, 16, is_out);
829         if(mr == MMSYSERR_NOERROR)
830             return mr;
831         mr = WINMM_TryDeviceMapping(info, channels,
832                 info->format->nSamplesPerSec, 8, is_out);
833         if(mr == MMSYSERR_NOERROR)
834             return mr;
835
836         channels = (channels == 2) ? 1 : 2;
837         mr = WINMM_TryDeviceMapping(info, channels,
838                 info->format->nSamplesPerSec, 16, is_out);
839         if(mr == MMSYSERR_NOERROR)
840             return mr;
841         mr = WINMM_TryDeviceMapping(info, channels,
842                 info->format->nSamplesPerSec, 8, is_out);
843         if(mr == MMSYSERR_NOERROR)
844             return mr;
845
846         /* that didn't work, so now try different sample rates */
847         channels = info->format->nChannels;
848         mr = WINMM_TryDeviceMapping(info, channels, 96000, 16, is_out);
849         if(mr == MMSYSERR_NOERROR)
850             return mr;
851         mr = WINMM_TryDeviceMapping(info, channels, 48000, 16, is_out);
852         if(mr == MMSYSERR_NOERROR)
853             return mr;
854         mr = WINMM_TryDeviceMapping(info, channels, 44100, 16, is_out);
855         if(mr == MMSYSERR_NOERROR)
856             return mr;
857         mr = WINMM_TryDeviceMapping(info, channels, 22050, 16, is_out);
858         if(mr == MMSYSERR_NOERROR)
859             return mr;
860         mr = WINMM_TryDeviceMapping(info, channels, 11025, 16, is_out);
861         if(mr == MMSYSERR_NOERROR)
862             return mr;
863
864         channels = (channels == 2) ? 1 : 2;
865         mr = WINMM_TryDeviceMapping(info, channels, 96000, 16, is_out);
866         if(mr == MMSYSERR_NOERROR)
867             return mr;
868         mr = WINMM_TryDeviceMapping(info, channels, 48000, 16, is_out);
869         if(mr == MMSYSERR_NOERROR)
870             return mr;
871         mr = WINMM_TryDeviceMapping(info, channels, 44100, 16, is_out);
872         if(mr == MMSYSERR_NOERROR)
873             return mr;
874         mr = WINMM_TryDeviceMapping(info, channels, 22050, 16, is_out);
875         if(mr == MMSYSERR_NOERROR)
876             return mr;
877         mr = WINMM_TryDeviceMapping(info, channels, 11025, 16, is_out);
878         if(mr == MMSYSERR_NOERROR)
879             return mr;
880
881         channels = info->format->nChannels;
882         mr = WINMM_TryDeviceMapping(info, channels, 96000, 8, is_out);
883         if(mr == MMSYSERR_NOERROR)
884             return mr;
885         mr = WINMM_TryDeviceMapping(info, channels, 48000, 8, is_out);
886         if(mr == MMSYSERR_NOERROR)
887             return mr;
888         mr = WINMM_TryDeviceMapping(info, channels, 44100, 8, is_out);
889         if(mr == MMSYSERR_NOERROR)
890             return mr;
891         mr = WINMM_TryDeviceMapping(info, channels, 22050, 8, is_out);
892         if(mr == MMSYSERR_NOERROR)
893             return mr;
894         mr = WINMM_TryDeviceMapping(info, channels, 11025, 8, is_out);
895         if(mr == MMSYSERR_NOERROR)
896             return mr;
897
898         channels = (channels == 2) ? 1 : 2;
899         mr = WINMM_TryDeviceMapping(info, channels, 96000, 8, is_out);
900         if(mr == MMSYSERR_NOERROR)
901             return mr;
902         mr = WINMM_TryDeviceMapping(info, channels, 48000, 8, is_out);
903         if(mr == MMSYSERR_NOERROR)
904             return mr;
905         mr = WINMM_TryDeviceMapping(info, channels, 44100, 8, is_out);
906         if(mr == MMSYSERR_NOERROR)
907             return mr;
908         mr = WINMM_TryDeviceMapping(info, channels, 22050, 8, is_out);
909         if(mr == MMSYSERR_NOERROR)
910             return mr;
911         mr = WINMM_TryDeviceMapping(info, channels, 11025, 8, is_out);
912         if(mr == MMSYSERR_NOERROR)
913             return mr;
914     }
915
916     WARN("Unable to find compatible device!\n");
917     return WAVERR_BADFORMAT;
918 }
919
920 static LRESULT WINMM_OpenDevice(WINMM_Device *device, WINMM_MMDevice *mmdevice,
921         WINMM_OpenInfo *info)
922 {
923     WAVEFORMATEX fmt, *passed_fmt;
924     LRESULT ret = MMSYSERR_NOMEM;
925     HRESULT hr;
926
927     hr = IMMDeviceEnumerator_GetDevice(g_devenum, mmdevice->dev_id,
928             &device->device);
929     if(FAILED(hr)){
930         WARN("Device %s (%s) unavailable: %08x\n",
931                 wine_dbgstr_w(mmdevice->dev_id),
932                 wine_dbgstr_w(mmdevice->out_caps.szPname), hr);
933         ret = MMSYSERR_NODRIVER;
934         goto error;
935     }
936
937     /* this is where winexyz.drv opens the audio device */
938     hr = IMMDevice_Activate(device->device, &IID_IAudioClient,
939             CLSCTX_INPROC_SERVER, NULL, (void**)&device->client);
940     if(FAILED(hr)){
941         WARN("Activate failed: %08x\n", hr);
942         ret = hr2mmr(hr);
943         if(ret == MMSYSERR_ERROR)
944             ret = MMSYSERR_NOTENABLED;
945         goto error;
946     }
947
948     if(info->format->wFormatTag == WAVE_FORMAT_PCM){
949         /* we aren't guaranteed that the struct in lpFormat is a full
950          * WAVEFORMATEX struct, which IAC::IsFormatSupported requires */
951         passed_fmt = &fmt;
952         memcpy(passed_fmt, info->format, sizeof(PCMWAVEFORMAT));
953         passed_fmt->cbSize = 0;
954         if(fmt.wBitsPerSample % 8 != 0){
955             WARN("Fixing bad wBitsPerSample (%u)\n", fmt.wBitsPerSample);
956             fmt.wBitsPerSample = (fmt.wBitsPerSample + 7) & ~7;
957         }
958         /* winmm ignores broken blockalign and avgbytes */
959         if(fmt.nBlockAlign != fmt.nChannels * fmt.wBitsPerSample/8){
960             WARN("Fixing bad nBlockAlign (%u)\n", fmt.nBlockAlign);
961             fmt.nBlockAlign  = fmt.nChannels * fmt.wBitsPerSample/8;
962         }
963         if (fmt.nAvgBytesPerSec != fmt.nSamplesPerSec * fmt.nBlockAlign) {
964             WARN("Fixing bad nAvgBytesPerSec (%u)\n", fmt.nAvgBytesPerSec);
965             fmt.nAvgBytesPerSec  = fmt.nSamplesPerSec * fmt.nBlockAlign;
966         }
967     }else
968         passed_fmt = info->format;
969
970     if(info->flags & WAVE_FORMAT_QUERY){
971         WAVEFORMATEX *closer_fmt = NULL;
972
973         hr = IAudioClient_IsFormatSupported(device->client,
974                 AUDCLNT_SHAREMODE_SHARED, passed_fmt, &closer_fmt);
975         if(closer_fmt)
976             CoTaskMemFree(closer_fmt);
977         ret = hr == S_FALSE ? WAVERR_BADFORMAT : hr2mmr(hr);
978         goto error;
979     }
980
981     /* buffer size = 10 * 100000 (100 ns) = 0.1 seconds */
982     hr = IAudioClient_Initialize(device->client, AUDCLNT_SHAREMODE_SHARED,
983             AUDCLNT_STREAMFLAGS_EVENTCALLBACK | AUDCLNT_STREAMFLAGS_NOPERSIST,
984             10 * 100000, 50000, passed_fmt, &device->parent->session);
985     if(FAILED(hr)){
986         if(hr != AUDCLNT_E_UNSUPPORTED_FORMAT)
987             WARN("Initialize failed: %08x\n", hr);
988         ret = hr2mmr(hr);
989         goto error;
990     }
991
992     hr = IAudioClient_GetService(device->client, &IID_IAudioClock,
993             (void**)&device->clock);
994     if(FAILED(hr)){
995         WARN("GetService failed: %08x\n", hr);
996         goto error;
997     }
998
999     if(!device->event){
1000         device->event = CreateEventW(NULL, FALSE, FALSE, NULL);
1001         if(!device->event){
1002             WARN("CreateEvent failed: %08x\n", hr);
1003             goto error;
1004         }
1005
1006         /* As the devices thread is waiting on g_device_handles, it can
1007          * only be modified from within this same thread. */
1008         if(g_device_handles){
1009             g_device_handles = HeapReAlloc(GetProcessHeap(), 0, g_device_handles,
1010                     sizeof(HANDLE) * (g_devhandle_count + 1));
1011             g_handle_devices = HeapReAlloc(GetProcessHeap(), 0, g_handle_devices,
1012                     sizeof(WINMM_Device *) * (g_devhandle_count + 1));
1013         }else{
1014             g_device_handles = HeapAlloc(GetProcessHeap(), 0, sizeof(HANDLE));
1015             g_handle_devices = HeapAlloc(GetProcessHeap(), 0,
1016                     sizeof(WINMM_Device *));
1017         }
1018         g_device_handles[g_devhandle_count] = device->event;
1019         g_handle_devices[g_devhandle_count] = device;
1020         ++g_devhandle_count;
1021     }
1022
1023     hr = IAudioClient_SetEventHandle(device->client, device->event);
1024     if(FAILED(hr)){
1025         WARN("SetEventHandle failed: %08x\n", hr);
1026         goto error;
1027     }
1028
1029     device->bytes_per_frame = passed_fmt->nBlockAlign;
1030     device->samples_per_sec = passed_fmt->nSamplesPerSec;
1031
1032     device->played_frames = 0;
1033     device->last_clock_pos = 0;
1034     device->ofs_bytes = 0;
1035     device->loop_counter = 0;
1036     device->stopped = TRUE;
1037     device->first = device->last = device->playing = device->loop_start = NULL;
1038
1039     device->cb_info.flags = HIWORD(info->flags & CALLBACK_TYPEMASK);
1040     device->cb_info.callback = info->callback;
1041     device->cb_info.user = info->cb_user;
1042     device->cb_info.hwave = device->handle;
1043
1044     info->handle = device->handle;
1045
1046     return MMSYSERR_NOERROR;
1047
1048 error:
1049     if(device->client){
1050         IAudioClient_Release(device->client);
1051         device->client = NULL;
1052     }
1053     if(device->device){
1054         IMMDevice_Release(device->device);
1055         device->device = NULL;
1056     }
1057
1058     return ret;
1059 }
1060
1061 static LRESULT WOD_Open(WINMM_OpenInfo *info)
1062 {
1063     WINMM_MMDevice *mmdevice;
1064     WINMM_Device *device = NULL;
1065     LRESULT ret;
1066     HRESULT hr;
1067
1068     TRACE("(%u, %p, %08x)\n", info->req_device, info, info->flags);
1069
1070     if(WINMM_IsMapper(info->req_device) || (info->flags & WAVE_MAPPED))
1071         return WINMM_MapDevice(info, TRUE);
1072
1073     if(info->req_device >= g_outmmdevices_count)
1074         return MMSYSERR_BADDEVICEID;
1075
1076     mmdevice = &g_out_mmdevices[info->req_device];
1077
1078     if(!mmdevice->out_caps.szPname[0])
1079         return MMSYSERR_NOTENABLED;
1080
1081     device = WINMM_FindUnusedDevice(TRUE, info->req_device);
1082     if(!device)
1083         return MMSYSERR_ALLOCATED;
1084
1085     ret = WINMM_OpenDevice(device, mmdevice, info);
1086     if((info->flags & WAVE_FORMAT_QUERY) || ret != MMSYSERR_NOERROR)
1087         goto error;
1088     ret = MMSYSERR_ERROR;
1089
1090     hr = IAudioClient_GetService(device->client, &IID_IAudioRenderClient,
1091             (void**)&device->render);
1092     if(FAILED(hr)){
1093         WARN("GetService(RenderClient) failed: %08x\n", hr);
1094         goto error;
1095     }
1096
1097     hr = IAudioClient_GetService(device->client, &IID_IAudioStreamVolume,
1098             (void**)&device->volume);
1099     if(FAILED(hr)){
1100         WARN("GetService(StreamVolume) failed: %08x\n", hr);
1101         goto error;
1102     }
1103
1104     LeaveCriticalSection(&device->lock);
1105
1106     return MMSYSERR_NOERROR;
1107
1108 error:
1109     if(device->device){
1110         IMMDevice_Release(device->device);
1111         device->device = NULL;
1112     }
1113     if(device->client){
1114         IAudioClient_Release(device->client);
1115         device->client = NULL;
1116     }
1117     if(device->render){
1118         IAudioRenderClient_Release(device->render);
1119         device->render = NULL;
1120     }
1121     if(device->volume){
1122         IAudioStreamVolume_Release(device->volume);
1123         device->volume = NULL;
1124     }
1125     if(device->clock){
1126         IAudioClock_Release(device->clock);
1127         device->clock = NULL;
1128     }
1129     device->open = FALSE;
1130     LeaveCriticalSection(&device->lock);
1131     return ret;
1132 }
1133
1134 static LRESULT WID_Open(WINMM_OpenInfo *info)
1135 {
1136     WINMM_MMDevice *mmdevice;
1137     WINMM_Device *device = NULL;
1138     LRESULT ret;
1139     HRESULT hr;
1140
1141     TRACE("(%u, %p, %08x)\n", info->req_device, info, info->flags);
1142
1143     if(WINMM_IsMapper(info->req_device) || info->flags & WAVE_MAPPED)
1144         return WINMM_MapDevice(info, FALSE);
1145
1146     if(info->req_device >= g_inmmdevices_count)
1147         return MMSYSERR_BADDEVICEID;
1148
1149     mmdevice = &g_in_mmdevices[info->req_device];
1150
1151     if(!mmdevice->in_caps.szPname[0])
1152         return MMSYSERR_NOTENABLED;
1153
1154     device = WINMM_FindUnusedDevice(FALSE, info->req_device);
1155     if(!device)
1156         return MMSYSERR_ALLOCATED;
1157
1158     ret = WINMM_OpenDevice(device, mmdevice, info);
1159     if((info->flags & WAVE_FORMAT_QUERY) || ret != MMSYSERR_NOERROR)
1160         goto error;
1161     ret = MMSYSERR_ERROR;
1162
1163     hr = IAudioClient_GetService(device->client, &IID_IAudioCaptureClient,
1164             (void**)&device->capture);
1165     if(FAILED(hr)){
1166         WARN("GetService failed: %08x\n", hr);
1167         goto error;
1168     }
1169
1170     LeaveCriticalSection(&device->lock);
1171
1172     return MMSYSERR_NOERROR;
1173
1174 error:
1175     if(device->device){
1176         IMMDevice_Release(device->device);
1177         device->device = NULL;
1178     }
1179     if(device->client){
1180         IAudioClient_Release(device->client);
1181         device->client = NULL;
1182     }
1183     if(device->capture){
1184         IAudioCaptureClient_Release(device->capture);
1185         device->capture = NULL;
1186     }
1187     if(device->clock){
1188         IAudioClock_Release(device->clock);
1189         device->clock = NULL;
1190     }
1191     device->open = FALSE;
1192     LeaveCriticalSection(&device->lock);
1193     return ret;
1194 }
1195
1196 static HRESULT WINMM_CloseDevice(WINMM_Device *device)
1197 {
1198     device->open = FALSE;
1199
1200     if(!device->stopped){
1201         IAudioClient_Stop(device->client);
1202         device->stopped = TRUE;
1203     }
1204
1205     if(device->acm_handle){
1206         acmStreamClose(device->acm_handle, 0);
1207         device->acm_handle = NULL;
1208     }
1209
1210     IMMDevice_Release(device->device);
1211     device->device = NULL;
1212
1213     IAudioClient_Release(device->client);
1214     device->client = NULL;
1215
1216     IAudioClock_Release(device->clock);
1217     device->clock = NULL;
1218
1219     return S_OK;
1220 }
1221
1222 static LRESULT WOD_Close(HWAVEOUT hwave)
1223 {
1224     WINMM_Device *device = WINMM_GetDeviceFromHWAVE((HWAVE)hwave);
1225
1226     TRACE("(%p)\n", hwave);
1227
1228     if(!WINMM_ValidateAndLock(device))
1229         return MMSYSERR_INVALHANDLE;
1230
1231     WINMM_CloseDevice(device);
1232
1233     IAudioRenderClient_Release(device->render);
1234     device->render = NULL;
1235
1236     IAudioStreamVolume_Release(device->volume);
1237     device->volume = NULL;
1238
1239     LeaveCriticalSection(&device->lock);
1240
1241     return MMSYSERR_NOERROR;
1242 }
1243
1244 static LRESULT WID_Close(HWAVEIN hwave)
1245 {
1246     WINMM_Device *device = WINMM_GetDeviceFromHWAVE((HWAVE)hwave);
1247
1248     TRACE("(%p)\n", hwave);
1249
1250     if(!WINMM_ValidateAndLock(device))
1251         return MMSYSERR_INVALHANDLE;
1252
1253     WINMM_CloseDevice(device);
1254
1255     IAudioCaptureClient_Release(device->capture);
1256     device->capture = NULL;
1257
1258     LeaveCriticalSection(&device->lock);
1259
1260     return MMSYSERR_NOERROR;
1261 }
1262
1263 static LRESULT WINMM_PrepareHeader(HWAVE hwave, WAVEHDR *header)
1264 {
1265     WINMM_Device *device = WINMM_GetDeviceFromHWAVE(hwave);
1266
1267     TRACE("(%p, %p)\n", hwave, header);
1268
1269     if(!WINMM_ValidateAndLock(device))
1270         return MMSYSERR_INVALHANDLE;
1271
1272     if(device->render && device->acm_handle){
1273         ACMSTREAMHEADER *ash;
1274         DWORD size;
1275         MMRESULT mr;
1276
1277         mr = acmStreamSize(device->acm_handle, header->dwBufferLength, &size,
1278                 ACM_STREAMSIZEF_SOURCE);
1279         if(mr != MMSYSERR_NOERROR){
1280             LeaveCriticalSection(&device->lock);
1281             return mr;
1282         }
1283
1284         ash = HeapAlloc(GetProcessHeap(), 0, sizeof(ACMSTREAMHEADER) + size);
1285         if(!ash){
1286             LeaveCriticalSection(&device->lock);
1287             return MMSYSERR_NOMEM;
1288         }
1289
1290         ash->cbStruct = sizeof(*ash);
1291         ash->fdwStatus = 0;
1292         ash->dwUser = (DWORD_PTR)header;
1293         ash->pbSrc = (BYTE*)header->lpData;
1294         ash->cbSrcLength = header->dwBufferLength;
1295         ash->dwSrcUser = header->dwUser;
1296         ash->pbDst = (BYTE*)ash + sizeof(ACMSTREAMHEADER);
1297         ash->cbDstLength = size;
1298         ash->dwDstUser = 0;
1299
1300         mr = acmStreamPrepareHeader(device->acm_handle, ash, 0);
1301         if(mr != MMSYSERR_NOERROR){
1302             HeapFree(GetProcessHeap(), 0, ash);
1303             LeaveCriticalSection(&device->lock);
1304             return mr;
1305         }
1306
1307         header->reserved = (DWORD_PTR)ash;
1308     }
1309
1310     LeaveCriticalSection(&device->lock);
1311
1312     header->dwFlags |= WHDR_PREPARED;
1313     header->dwFlags &= ~WHDR_DONE;
1314
1315     return MMSYSERR_NOERROR;
1316 }
1317
1318 static LRESULT WINMM_UnprepareHeader(HWAVE hwave, WAVEHDR *header)
1319 {
1320     WINMM_Device *device = WINMM_GetDeviceFromHWAVE(hwave);
1321
1322     TRACE("(%p, %p)\n", hwave, header);
1323
1324     if(!WINMM_ValidateAndLock(device))
1325         return MMSYSERR_INVALHANDLE;
1326
1327     if(device->render && device->acm_handle){
1328         ACMSTREAMHEADER *ash = (ACMSTREAMHEADER*)header->reserved;
1329
1330         acmStreamUnprepareHeader(device->acm_handle, ash, 0);
1331
1332         HeapFree(GetProcessHeap(), 0, ash);
1333     }
1334
1335     LeaveCriticalSection(&device->lock);
1336
1337     header->dwFlags &= ~WHDR_PREPARED;
1338     header->dwFlags |= WHDR_DONE;
1339
1340     return MMSYSERR_NOERROR;
1341 }
1342
1343 static UINT32 WINMM_HeaderLenBytes(WINMM_Device *device, WAVEHDR *header)
1344 {
1345     if(device->acm_handle){
1346         ACMSTREAMHEADER *ash = (ACMSTREAMHEADER*)header->reserved;
1347         return ash->cbDstLengthUsed;
1348     }
1349
1350     return header->dwBufferLength;
1351 }
1352
1353 static UINT32 WINMM_HeaderLenFrames(WINMM_Device *device, WAVEHDR *header)
1354 {
1355     return WINMM_HeaderLenBytes(device, header) / device->bytes_per_frame;
1356 }
1357
1358 static WAVEHDR *WOD_MarkDoneHeaders(WINMM_Device *device)
1359 {
1360     HRESULT hr;
1361     WAVEHDR *first = device->first, *queue = first, *last = NULL;
1362     UINT64 clock_freq, clock_pos, clock_frames;
1363     UINT32 nloops, queue_frames = 0;
1364
1365     hr = IAudioClock_GetFrequency(device->clock, &clock_freq);
1366     if(FAILED(hr)){
1367         WARN("GetFrequency failed: %08x\n", hr);
1368         return NULL;
1369     }
1370
1371     hr = IAudioClock_GetPosition(device->clock, &clock_pos, NULL);
1372     if(FAILED(hr)){
1373         WARN("GetPosition failed: %08x\n", hr);
1374         return NULL;
1375     }
1376
1377     clock_frames = (clock_pos * device->samples_per_sec) / clock_freq;
1378
1379     nloops = device->loop_counter;
1380     while(queue &&
1381             (queue_frames += WINMM_HeaderLenFrames(device, queue)) <=
1382                 clock_frames - device->last_clock_pos){
1383         if(!nloops){
1384             last = queue;
1385             device->last_clock_pos += queue_frames;
1386             queue_frames = 0;
1387             queue = device->first = queue->lpNext;
1388         }else{
1389             if(queue->dwFlags & WHDR_BEGINLOOP){
1390                 if(queue->dwFlags & WHDR_ENDLOOP)
1391                     --nloops;
1392                 else
1393                     queue = queue->lpNext;
1394             }else if(queue->dwFlags & WHDR_ENDLOOP){
1395                 queue = device->loop_start;
1396                 --nloops;
1397             }
1398         }
1399     }
1400
1401     if(last){
1402         last->lpNext = NULL;
1403         return first;
1404     }else
1405         return NULL;
1406 }
1407
1408 static void WOD_PushData(WINMM_Device *device)
1409 {
1410     WINMM_CBInfo cb_info;
1411     HRESULT hr;
1412     UINT32 pad, bufsize, avail_frames, queue_frames, written, ofs;
1413     UINT32 queue_bytes, nloops;
1414     BYTE *data;
1415     WAVEHDR *queue, *first = NULL;
1416
1417     TRACE("(%p)\n", device->handle);
1418
1419     EnterCriticalSection(&device->lock);
1420
1421     if(!device->device)
1422         goto exit;
1423
1424     if(!device->first){
1425         if (device->stopped)
1426             goto exit;
1427         device->stopped = TRUE;
1428         device->last_clock_pos = 0;
1429         IAudioClient_Stop(device->client);
1430         IAudioClient_Reset(device->client);
1431         goto exit;
1432     }
1433
1434     hr = IAudioClient_GetBufferSize(device->client, &bufsize);
1435     if(FAILED(hr)){
1436         WARN("GetBufferSize failed: %08x\n", hr);
1437         goto exit;
1438     }
1439
1440     hr = IAudioClient_GetCurrentPadding(device->client, &pad);
1441     if(FAILED(hr)){
1442         WARN("GetCurrentPadding failed: %08x\n", hr);
1443         goto exit;
1444     }
1445
1446     first = WOD_MarkDoneHeaders(device);
1447
1448     /* determine which is larger between the available buffer size and
1449      * the amount of data left in the queue */
1450     avail_frames = bufsize - pad;
1451
1452     queue = device->playing;
1453     ofs = device->ofs_bytes;
1454     queue_frames = 0;
1455     nloops = 0;
1456     while(queue && queue_frames < avail_frames){
1457         queue_bytes = WINMM_HeaderLenBytes(device, queue);
1458         queue_frames += (queue_bytes - ofs) / device->bytes_per_frame;
1459         ofs = 0;
1460
1461         if(queue->dwFlags & WHDR_ENDLOOP && nloops < device->loop_counter){
1462             queue = device->loop_start;
1463             ++nloops;
1464         }else
1465             queue = queue->lpNext;
1466     }
1467
1468     if(queue_frames < avail_frames)
1469         avail_frames = queue_frames;
1470     if(avail_frames == 0)
1471         goto exit;
1472
1473     hr = IAudioRenderClient_GetBuffer(device->render, avail_frames, &data);
1474     if(FAILED(hr)){
1475         WARN("GetBuffer failed: %08x\n", hr);
1476         goto exit;
1477     }
1478
1479     written = 0;
1480     while(device->playing && written < avail_frames){
1481         UINT32 copy_frames, copy_bytes;
1482         BYTE *queue_data;
1483
1484         queue = device->playing;
1485
1486         if(device->acm_handle){
1487             ACMSTREAMHEADER *ash = (ACMSTREAMHEADER*)queue->reserved;
1488             queue_bytes = ash->cbDstLengthUsed;
1489             queue_data = ash->pbDst;
1490         }else{
1491             queue_bytes = queue->dwBufferLength;
1492             queue_data = (BYTE*)queue->lpData;
1493         }
1494
1495         queue_frames = (queue_bytes - device->ofs_bytes) /
1496             device->bytes_per_frame;
1497
1498         copy_frames = queue_frames < (avail_frames - written) ?
1499             queue_frames : avail_frames - written;
1500         copy_bytes = copy_frames * device->bytes_per_frame;
1501
1502         memcpy(data, queue_data + device->ofs_bytes, copy_bytes);
1503
1504         data += copy_bytes;
1505         written += copy_frames;
1506         device->ofs_bytes += copy_bytes;
1507
1508         if(device->ofs_bytes >= queue_bytes){
1509             device->ofs_bytes = 0;
1510
1511             if(!(queue->dwFlags & (WHDR_BEGINLOOP | WHDR_ENDLOOP)))
1512                 device->playing = queue->lpNext;
1513             else{
1514                 if(queue->dwFlags & WHDR_BEGINLOOP){
1515                     device->loop_start = device->playing;
1516                     device->playing = queue->lpNext;
1517                     device->loop_counter = queue->dwLoops;
1518                 }
1519                 if(queue->dwFlags & WHDR_ENDLOOP){
1520                     --device->loop_counter;
1521                     if(device->loop_counter)
1522                         device->playing = device->loop_start;
1523                     else
1524                         device->loop_start = device->playing = queue->lpNext;
1525                 }
1526             }
1527         }
1528     }
1529
1530     hr = IAudioRenderClient_ReleaseBuffer(device->render, avail_frames, 0);
1531     if(FAILED(hr)){
1532         WARN("ReleaseBuffer failed: %08x\n", hr);
1533         goto exit;
1534     }
1535
1536     device->played_frames += avail_frames;
1537
1538 exit:
1539     cb_info = device->cb_info;
1540
1541     LeaveCriticalSection(&device->lock);
1542
1543     while(first){
1544         WAVEHDR *next = first->lpNext;
1545         first->dwFlags &= ~WHDR_INQUEUE;
1546         first->dwFlags |= WHDR_DONE;
1547         WINMM_NotifyClient(&cb_info, WOM_DONE, (DWORD_PTR)first, 0);
1548         first = next;
1549     }
1550 }
1551
1552 static void WID_PullACMData(WINMM_Device *device)
1553 {
1554     UINT32 packet, packet_bytes;
1555     DWORD flags;
1556     BYTE *data;
1557     WAVEHDR *queue;
1558     HRESULT hr;
1559     MMRESULT mr;
1560
1561     if(device->acm_hdr.cbDstLength == 0){
1562         hr = IAudioCaptureClient_GetBuffer(device->capture, &data, &packet,
1563                 &flags, NULL, NULL);
1564         if(hr != S_OK){
1565             if(FAILED(hr))
1566                 WARN("GetBuffer failed: %08x\n", hr);
1567             return;
1568         }
1569
1570         acmStreamSize(device->acm_handle, packet * device->bytes_per_frame,
1571                 &packet_bytes, ACM_STREAMSIZEF_SOURCE);
1572
1573         device->acm_offs = 0;
1574
1575         device->acm_hdr.cbStruct = sizeof(device->acm_hdr);
1576         device->acm_hdr.fdwStatus = 0;
1577         device->acm_hdr.dwUser = 0;
1578         device->acm_hdr.pbSrc = data;
1579         device->acm_hdr.cbSrcLength = packet * device->bytes_per_frame;
1580         device->acm_hdr.cbSrcLengthUsed = 0;
1581         device->acm_hdr.dwSrcUser = 0;
1582         device->acm_hdr.pbDst = HeapAlloc(GetProcessHeap(), 0, packet_bytes);
1583         device->acm_hdr.cbDstLength = packet_bytes;
1584         device->acm_hdr.cbDstLengthUsed = 0;
1585         device->acm_hdr.dwDstUser = 0;
1586
1587         mr = acmStreamPrepareHeader(device->acm_handle, &device->acm_hdr, 0);
1588         if(mr != MMSYSERR_NOERROR){
1589             WARN("acmStreamPrepareHeader failed: %d\n", mr);
1590             return;
1591         }
1592
1593         mr = acmStreamConvert(device->acm_handle, &device->acm_hdr, 0);
1594         if(mr != MMSYSERR_NOERROR){
1595             WARN("acmStreamConvert failed: %d\n", mr);
1596             return;
1597         }
1598
1599         hr = IAudioCaptureClient_ReleaseBuffer(device->capture, packet);
1600         if(FAILED(hr))
1601             WARN("ReleaseBuffer failed: %08x\n", hr);
1602
1603         device->played_frames += packet;
1604     }
1605
1606     queue = device->first;
1607     while(queue){
1608         UINT32 to_copy_bytes;
1609
1610         to_copy_bytes = min(queue->dwBufferLength - queue->dwBytesRecorded,
1611                 device->acm_hdr.cbDstLengthUsed - device->acm_offs);
1612
1613         memcpy(queue->lpData + queue->dwBytesRecorded,
1614                 device->acm_hdr.pbDst + device->acm_offs, to_copy_bytes);
1615
1616         queue->dwBytesRecorded += to_copy_bytes;
1617         device->acm_offs += to_copy_bytes;
1618
1619         if(queue->dwBufferLength - queue->dwBytesRecorded <
1620                 device->bytes_per_frame){
1621             queue->dwFlags &= ~WHDR_INQUEUE;
1622             queue->dwFlags |= WHDR_DONE;
1623             device->first = queue = queue->lpNext;
1624         }
1625
1626         if(device->acm_offs >= device->acm_hdr.cbDstLengthUsed){
1627             acmStreamUnprepareHeader(device->acm_handle, &device->acm_hdr, 0);
1628             HeapFree(GetProcessHeap(), 0, device->acm_hdr.pbDst);
1629             device->acm_hdr.cbDstLength = 0;
1630             device->acm_hdr.cbDstLengthUsed = 0;
1631
1632             /* done with this ACM Header, so try to pull more data */
1633             WID_PullACMData(device);
1634             return;
1635         }
1636     }
1637
1638     /* out of WAVEHDRs to write into, so toss the rest of this packet */
1639     acmStreamUnprepareHeader(device->acm_handle, &device->acm_hdr, 0);
1640     HeapFree(GetProcessHeap(), 0, device->acm_hdr.pbDst);
1641     device->acm_hdr.cbDstLength = 0;
1642     device->acm_hdr.cbDstLengthUsed = 0;
1643 }
1644
1645 static void WID_PullData(WINMM_Device *device)
1646 {
1647     WINMM_CBInfo cb_info;
1648     WAVEHDR *queue, *first = NULL, *last = NULL;
1649     HRESULT hr;
1650
1651     TRACE("(%p)\n", device->handle);
1652
1653     EnterCriticalSection(&device->lock);
1654
1655     if(!device->device || !device->first)
1656         goto exit;
1657
1658     first = device->first;
1659
1660     if(device->acm_handle){
1661         WID_PullACMData(device);
1662         goto exit;
1663     }
1664
1665     while(device->first){
1666         BYTE *data;
1667         UINT32 packet_len, packet;
1668         DWORD flags;
1669
1670         hr = IAudioCaptureClient_GetBuffer(device->capture, &data, &packet_len,
1671                 &flags, NULL, NULL);
1672         if(hr != S_OK){
1673             if(FAILED(hr))
1674                 WARN("GetBuffer failed: %08x\n", hr);
1675             else /* AUDCLNT_S_BUFFER_EMPTY success code */
1676                 IAudioCaptureClient_ReleaseBuffer(device->capture, 0);
1677             goto exit;
1678         }
1679
1680         packet = packet_len;
1681         queue = device->first;
1682         while(queue && packet > 0){
1683             UINT32 to_copy_bytes;
1684
1685             to_copy_bytes = min(packet * device->bytes_per_frame,
1686                     queue->dwBufferLength - queue->dwBytesRecorded);
1687
1688             memcpy(queue->lpData + queue->dwBytesRecorded,
1689                     data + (packet_len - packet) * device->bytes_per_frame,
1690                     to_copy_bytes);
1691
1692             queue->dwBytesRecorded += to_copy_bytes;
1693
1694             if(queue->dwBufferLength - queue->dwBytesRecorded <
1695                     device->bytes_per_frame){
1696                 last = queue;
1697                 device->first = queue = queue->lpNext;
1698             }
1699
1700             packet -= to_copy_bytes / device->bytes_per_frame;
1701         }
1702
1703         hr = IAudioCaptureClient_ReleaseBuffer(device->capture, packet_len);
1704         if(FAILED(hr))
1705             WARN("ReleaseBuffer failed: %08x\n", hr);
1706
1707         if(packet > 0)
1708             WARN("losing %u frames\n", packet);
1709         device->played_frames += packet_len;
1710     }
1711
1712 exit:
1713     cb_info = device->cb_info;
1714
1715     LeaveCriticalSection(&device->lock);
1716
1717     if(last){
1718         last->lpNext = NULL;
1719         while(first){
1720             WAVEHDR *next = first->lpNext;
1721             first->dwFlags &= ~WHDR_INQUEUE;
1722             first->dwFlags |= WHDR_DONE;
1723             WINMM_NotifyClient(&cb_info, WIM_DATA, (DWORD_PTR)first, 0);
1724             first = next;
1725         }
1726     }
1727 }
1728
1729 static MMRESULT WINMM_BeginPlaying(WINMM_Device *device)
1730 {
1731     HRESULT hr;
1732
1733     TRACE("(%p)\n", device->handle);
1734
1735     if(device->render)
1736         /* prebuffer data before starting */
1737         WOD_PushData(device);
1738
1739     if(device->stopped){
1740         device->stopped = FALSE;
1741
1742         hr = IAudioClient_Start(device->client);
1743         if(FAILED(hr) && hr != AUDCLNT_E_NOT_STOPPED){
1744             device->stopped = TRUE;
1745             WARN("Start failed: %08x\n", hr);
1746             return MMSYSERR_ERROR;
1747         }
1748     }
1749
1750     return MMSYSERR_NOERROR;
1751 }
1752
1753 static LRESULT WINMM_Pause(HWAVE hwave)
1754 {
1755     WINMM_Device *device = WINMM_GetDeviceFromHWAVE(hwave);
1756     HRESULT hr;
1757
1758     TRACE("(%p)\n", hwave);
1759
1760     if(!WINMM_ValidateAndLock(device))
1761         return MMSYSERR_INVALHANDLE;
1762
1763     hr = IAudioClient_Stop(device->client);
1764     if(FAILED(hr)){
1765         LeaveCriticalSection(&device->lock);
1766         WARN("Stop failed: %08x\n", hr);
1767         return MMSYSERR_ERROR;
1768     }
1769
1770     device->stopped = FALSE;
1771
1772     LeaveCriticalSection(&device->lock);
1773
1774     return MMSYSERR_NOERROR;
1775 }
1776
1777 static LRESULT WINMM_Reset(HWAVE hwave)
1778 {
1779     WINMM_CBInfo cb_info;
1780     WINMM_Device *device = WINMM_GetDeviceFromHWAVE(hwave);
1781     BOOL is_out;
1782     WAVEHDR *first;
1783     HRESULT hr;
1784
1785     TRACE("(%p)\n", hwave);
1786
1787     if(!WINMM_ValidateAndLock(device))
1788         return MMSYSERR_INVALHANDLE;
1789
1790     hr = IAudioClient_Stop(device->client);
1791     if(FAILED(hr)){
1792         LeaveCriticalSection(&device->lock);
1793         WARN("Stop failed: %08x\n", hr);
1794         return MMSYSERR_ERROR;
1795     }
1796     device->stopped = TRUE;
1797
1798     first = device->first;
1799     device->first = device->last = device->playing = NULL;
1800     device->ofs_bytes = 0;
1801     device->played_frames = 0;
1802     device->loop_counter = 0;
1803     device->last_clock_pos = 0;
1804     IAudioClient_Reset(device->client);
1805
1806     cb_info = device->cb_info;
1807     is_out = device->render != NULL;
1808
1809     LeaveCriticalSection(&device->lock);
1810
1811     while(first){
1812         WAVEHDR *next = first->lpNext;
1813         first->dwFlags &= ~WHDR_INQUEUE;
1814         first->dwFlags |= WHDR_DONE;
1815         if(is_out)
1816             WINMM_NotifyClient(&cb_info, WOM_DONE, (DWORD_PTR)first, 0);
1817         else
1818             WINMM_NotifyClient(&cb_info, WIM_DATA, (DWORD_PTR)first, 0);
1819         first = next;
1820     }
1821
1822     return MMSYSERR_NOERROR;
1823 }
1824
1825 static MMRESULT WINMM_FramesToMMTime(MMTIME *time, UINT32 played_frames,
1826         UINT32 sample_rate, UINT32 bytes_per_frame)
1827 {
1828     switch(time->wType){
1829     case TIME_SAMPLES:
1830         time->u.sample = played_frames;
1831         return MMSYSERR_NOERROR;
1832     case TIME_MS:
1833         time->u.ms = (UINT64)played_frames * 1000 / sample_rate;
1834         return MMSYSERR_NOERROR;
1835     case TIME_SMPTE:
1836         time->u.smpte.fps = 30;
1837         played_frames += sample_rate / time->u.smpte.fps - 1; /* round up */
1838         time->u.smpte.frame = (played_frames % sample_rate) * time->u.smpte.fps / sample_rate;
1839         played_frames /= sample_rate; /* yields seconds */
1840         time->u.smpte.sec = played_frames % 60;
1841         played_frames /= 60;
1842         time->u.smpte.min = played_frames % 60;
1843         time->u.smpte.hour= played_frames / 60;
1844         return MMSYSERR_NOERROR;
1845     default:
1846         time->wType = TIME_BYTES;
1847         /* fall through */
1848     case TIME_BYTES:
1849         time->u.cb = played_frames * bytes_per_frame;
1850         return MMSYSERR_NOERROR;
1851     }
1852 }
1853
1854 static LRESULT WINMM_GetPosition(HWAVE hwave, MMTIME *time)
1855 {
1856     WINMM_Device *device = WINMM_GetDeviceFromHWAVE(hwave);
1857     UINT32 played_frames, sample_rate, bytes_per_frame;
1858
1859     TRACE("(%p, %p)\n", hwave, time);
1860
1861     if(!WINMM_ValidateAndLock(device))
1862         return MMSYSERR_INVALHANDLE;
1863
1864     played_frames = device->played_frames;
1865     sample_rate = device->samples_per_sec;
1866     bytes_per_frame = device->bytes_per_frame;
1867
1868     LeaveCriticalSection(&device->lock);
1869
1870     return WINMM_FramesToMMTime(time, played_frames, sample_rate,
1871             bytes_per_frame);
1872 }
1873
1874 static WINMM_MMDevice *WINMM_GetMixerMMDevice(HMIXEROBJ hmix, DWORD flags,
1875         UINT *mmdev_index)
1876 {
1877     UINT mmdev, dev, junk, *out;
1878     BOOL is_out;
1879
1880     if(!mmdev_index)
1881         out = &mmdev;
1882     else
1883         out = mmdev_index;
1884
1885     switch(flags & 0xF0000000){
1886     case MIXER_OBJECTF_MIXER: /* == 0 */
1887         *out = HandleToULong(hmix);
1888         if(*out < g_outmmdevices_count)
1889             return &g_out_mmdevices[*out];
1890         if(*out - g_outmmdevices_count < g_inmmdevices_count){
1891             *out -= g_outmmdevices_count;
1892             return &g_in_mmdevices[*out];
1893         }
1894         /* fall through -- if it's not a valid mixer device, then
1895          * it could be a valid mixer handle. windows seems to do
1896          * this as well. */
1897     case MIXER_OBJECTF_HMIXER:
1898     case MIXER_OBJECTF_HWAVEOUT:
1899     case MIXER_OBJECTF_HWAVEIN:
1900         WINMM_DecomposeHWAVE((HWAVE)hmix, out, &is_out, &dev, &junk);
1901         if(junk != 0x1 || (is_out && *out >= g_outmmdevices_count) ||
1902                (!is_out && *out >= g_inmmdevices_count))
1903             return NULL;
1904         if(is_out)
1905             return &g_out_mmdevices[*out];
1906         return &g_in_mmdevices[*out];
1907     case MIXER_OBJECTF_WAVEOUT:
1908         *out = HandleToULong(hmix);
1909         if(*out < g_outmmdevices_count)
1910             return &g_out_mmdevices[*out];
1911         return NULL;
1912     case MIXER_OBJECTF_WAVEIN:
1913         *out = HandleToULong(hmix);
1914         if(*out < g_inmmdevices_count)
1915             return &g_in_mmdevices[*out];
1916         return NULL;
1917     }
1918
1919     return NULL;
1920 }
1921
1922 static MMRESULT WINMM_SetupMMDeviceVolume(WINMM_MMDevice *mmdevice)
1923 {
1924     IAudioSessionManager *sesman;
1925     IMMDevice *device;
1926     HRESULT hr;
1927
1928     hr = IMMDeviceEnumerator_GetDevice(g_devenum, mmdevice->dev_id, &device);
1929     if(FAILED(hr)){
1930         WARN("Device %s (%s) unavailable: %08x\n",
1931                 wine_dbgstr_w(mmdevice->dev_id),
1932                 wine_dbgstr_w(mmdevice->out_caps.szPname), hr);
1933         return MMSYSERR_ERROR;
1934     }
1935
1936     hr = IMMDevice_Activate(device, &IID_IAudioSessionManager,
1937             CLSCTX_INPROC_SERVER, NULL, (void**)&sesman);
1938     if(FAILED(hr)){
1939         WARN("Activate failed: %08x\n", hr);
1940         IMMDevice_Release(device);
1941         return MMSYSERR_ERROR;
1942     }
1943
1944     IMMDevice_Release(device);
1945
1946     hr = IAudioSessionManager_GetSimpleAudioVolume(sesman, &mmdevice->session,
1947             FALSE, &mmdevice->volume);
1948     IAudioSessionManager_Release(sesman);
1949     if(FAILED(hr)){
1950         WARN("GetSimpleAudioVolume failed: %08x\n", hr);
1951         return MMSYSERR_ERROR;
1952     }
1953
1954     return MMSYSERR_NOERROR;
1955 }
1956
1957 static LRESULT MXD_GetControlDetails(WINMM_ControlDetails *details)
1958 {
1959     WINMM_MMDevice *mmdevice;
1960     MIXERCONTROLDETAILS *control = details->details;
1961     HRESULT hr;
1962
1963     TRACE("(%p)\n", details->hmix);
1964
1965     mmdevice = WINMM_GetMixerMMDevice(details->hmix, details->flags, NULL);
1966     if(!mmdevice)
1967         return MMSYSERR_INVALHANDLE;
1968
1969     EnterCriticalSection(&mmdevice->lock);
1970
1971     if(!mmdevice->volume){
1972         MMRESULT mr;
1973
1974         mr = WINMM_SetupMMDeviceVolume(mmdevice);
1975         if(mr != MMSYSERR_NOERROR){
1976             LeaveCriticalSection(&mmdevice->lock);
1977             return mr;
1978         }
1979     }
1980
1981     if(control->dwControlID == 0){
1982         float vol;
1983         MIXERCONTROLDETAILS_UNSIGNED *udet;
1984
1985         if(!control->paDetails ||
1986                 control->cbDetails < sizeof(MIXERCONTROLDETAILS_UNSIGNED)){
1987             LeaveCriticalSection(&mmdevice->lock);
1988             return MMSYSERR_INVALPARAM;
1989         }
1990
1991         hr = ISimpleAudioVolume_GetMasterVolume(mmdevice->volume, &vol);
1992         if(FAILED(hr)){
1993             WARN("GetMasterVolume failed: %08x\n", hr);
1994             LeaveCriticalSection(&mmdevice->lock);
1995             return MMSYSERR_ERROR;
1996         }
1997
1998         udet = (MIXERCONTROLDETAILS_UNSIGNED*)control->paDetails;
1999         udet->dwValue = vol * ((unsigned int)0xFFFF);
2000     }else if(control->dwControlID == 1){
2001         BOOL mute;
2002         MIXERCONTROLDETAILS_BOOLEAN *bdet;
2003
2004         if(!control->paDetails ||
2005                 control->cbDetails < sizeof(MIXERCONTROLDETAILS_BOOLEAN)){
2006             LeaveCriticalSection(&mmdevice->lock);
2007             return MMSYSERR_INVALPARAM;
2008         }
2009
2010         hr = ISimpleAudioVolume_GetMute(mmdevice->volume, &mute);
2011         if(FAILED(hr)){
2012             WARN("GetMute failed: %08x\n", hr);
2013             LeaveCriticalSection(&mmdevice->lock);
2014             return MMSYSERR_ERROR;
2015         }
2016
2017         bdet = (MIXERCONTROLDETAILS_BOOLEAN*)control->paDetails;
2018         bdet->fValue = mute;
2019     }else if(control->dwControlID == 2 || control->dwControlID == 3){
2020         FIXME("What should the sw-side mixer controls map to?\n");
2021     }else{
2022         LeaveCriticalSection(&mmdevice->lock);
2023         return MIXERR_INVALCONTROL;
2024     }
2025
2026     LeaveCriticalSection(&mmdevice->lock);
2027
2028     return MMSYSERR_NOERROR;
2029 }
2030
2031 static LRESULT MXD_SetControlDetails(WINMM_ControlDetails *details)
2032 {
2033     WINMM_MMDevice *mmdevice;
2034     MIXERCONTROLDETAILS *control = details->details;
2035     HRESULT hr;
2036
2037     TRACE("(%p)\n", details->hmix);
2038
2039     mmdevice = WINMM_GetMixerMMDevice(details->hmix, details->flags, NULL);
2040     if(!mmdevice)
2041         return MMSYSERR_INVALHANDLE;
2042
2043     EnterCriticalSection(&mmdevice->lock);
2044
2045     if(!mmdevice->volume){
2046         MMRESULT mr;
2047
2048         mr = WINMM_SetupMMDeviceVolume(mmdevice);
2049         if(mr != MMSYSERR_NOERROR){
2050             LeaveCriticalSection(&mmdevice->lock);
2051             return mr;
2052         }
2053     }
2054
2055     if(control->dwControlID == 0){
2056         float vol;
2057         MIXERCONTROLDETAILS_UNSIGNED *udet;
2058
2059         if(!control->paDetails ||
2060                 control->cbDetails < sizeof(MIXERCONTROLDETAILS_UNSIGNED)){
2061             LeaveCriticalSection(&mmdevice->lock);
2062             return MMSYSERR_INVALPARAM;
2063         }
2064
2065         udet = (MIXERCONTROLDETAILS_UNSIGNED*)control->paDetails;
2066
2067         if(udet->dwValue > 65535){
2068             LeaveCriticalSection(&mmdevice->lock);
2069             return MMSYSERR_INVALPARAM;
2070         }
2071
2072         vol = udet->dwValue / 65535.f;
2073
2074         hr = ISimpleAudioVolume_SetMasterVolume(mmdevice->volume, vol, NULL);
2075         if(FAILED(hr)){
2076             WARN("SetMasterVolume failed: %08x\n", hr);
2077             LeaveCriticalSection(&mmdevice->lock);
2078             return MMSYSERR_ERROR;
2079         }
2080     }else if(control->dwControlID == 1){
2081         BOOL mute;
2082         MIXERCONTROLDETAILS_BOOLEAN *bdet;
2083
2084         if(!control->paDetails ||
2085                 control->cbDetails < sizeof(MIXERCONTROLDETAILS_BOOLEAN)){
2086             LeaveCriticalSection(&mmdevice->lock);
2087             return MMSYSERR_INVALPARAM;
2088         }
2089
2090         bdet = (MIXERCONTROLDETAILS_BOOLEAN*)control->paDetails;
2091         mute = bdet->fValue;
2092
2093         hr = ISimpleAudioVolume_SetMute(mmdevice->volume, mute, NULL);
2094         if(FAILED(hr)){
2095             WARN("SetMute failed: %08x\n", hr);
2096             LeaveCriticalSection(&mmdevice->lock);
2097             return MMSYSERR_ERROR;
2098         }
2099     }else if(control->dwControlID == 2 || control->dwControlID == 3){
2100         FIXME("What should the sw-side mixer controls map to?\n");
2101     }else{
2102         LeaveCriticalSection(&mmdevice->lock);
2103         return MIXERR_INVALCONTROL;
2104     }
2105
2106     LeaveCriticalSection(&mmdevice->lock);
2107
2108     return MMSYSERR_NOERROR;
2109 }
2110
2111 static LRESULT DRV_QueryDeviceInterface(WINMM_QueryInterfaceInfo *info)
2112 {
2113     WINMM_MMDevice *mmdevice;
2114     IMMDevice *device;
2115     IPropertyStore *ps;
2116     PROPVARIANT pv;
2117     DWORD len_bytes;
2118     HRESULT hr;
2119
2120     static const PROPERTYKEY deviceinterface_key = {
2121         {0x233164c8, 0x1b2c, 0x4c7d, {0xbc, 0x68, 0xb6, 0x71, 0x68, 0x7a, 0x25, 0x67}}, 1
2122     };
2123
2124     if(WINMM_IsMapper(info->index)){
2125         if(info->str){
2126             if(*info->len_bytes < sizeof(WCHAR))
2127                 return MMSYSERR_INVALPARAM;
2128             *info->str = 0;
2129         }else
2130             *info->len_bytes = sizeof(WCHAR);
2131         return MMSYSERR_NOERROR;
2132     }
2133
2134     if(info->is_out){
2135         if(info->index >= g_outmmdevices_count)
2136             return MMSYSERR_INVALHANDLE;
2137
2138         mmdevice = &g_out_mmdevices[info->index];
2139     }else{
2140         if(info->index >= g_inmmdevices_count)
2141             return MMSYSERR_INVALHANDLE;
2142
2143         mmdevice = &g_in_mmdevices[info->index];
2144     }
2145
2146     hr = IMMDeviceEnumerator_GetDevice(g_devenum, mmdevice->dev_id,
2147             &device);
2148     if(FAILED(hr)){
2149         WARN("Device %s unavailable: %08x\n", wine_dbgstr_w(mmdevice->dev_id), hr);
2150         return MMSYSERR_ERROR;
2151     }
2152
2153     hr = IMMDevice_OpenPropertyStore(device, STGM_READ, &ps);
2154     if(FAILED(hr)){
2155         WARN("OpenPropertyStore failed: %08x\n", hr);
2156         IMMDevice_Release(device);
2157         return MMSYSERR_ERROR;
2158     }
2159
2160     PropVariantInit(&pv);
2161     hr = IPropertyStore_GetValue(ps, &deviceinterface_key, &pv);
2162     if(FAILED(hr)){
2163         WARN("GetValue failed: %08x\n", hr);
2164         IPropertyStore_Release(ps);
2165         IMMDevice_Release(device);
2166         return MMSYSERR_ERROR;
2167     }
2168     if(pv.vt != VT_LPWSTR){
2169         WARN("Got unexpected property type: %u\n", pv.vt);
2170         PropVariantClear(&pv);
2171         IPropertyStore_Release(ps);
2172         IMMDevice_Release(device);
2173         return MMSYSERR_ERROR;
2174     }
2175
2176     len_bytes = (lstrlenW(pv.u.pwszVal) + 1) * sizeof(WCHAR);
2177
2178     if(info->str){
2179         if(len_bytes > *info->len_bytes){
2180             PropVariantClear(&pv);
2181             IPropertyStore_Release(ps);
2182             IMMDevice_Release(device);
2183             return MMSYSERR_INVALPARAM;
2184         }
2185
2186         memcpy(info->str, pv.u.pwszVal, len_bytes);
2187     }else
2188         *info->len_bytes = len_bytes;
2189
2190     PropVariantClear(&pv);
2191     IPropertyStore_Release(ps);
2192     IMMDevice_Release(device);
2193
2194     return MMSYSERR_NOERROR;
2195 }
2196
2197 static LRESULT CALLBACK WINMM_DevicesMsgProc(HWND hwnd, UINT msg, WPARAM wparam,
2198         LPARAM lparam)
2199 {
2200     switch(msg){
2201     case WODM_OPEN:
2202         return WOD_Open((WINMM_OpenInfo*)wparam);
2203     case WODM_CLOSE:
2204         return WOD_Close((HWAVEOUT)wparam);
2205     case WIDM_OPEN:
2206         return WID_Open((WINMM_OpenInfo*)wparam);
2207     case WIDM_CLOSE:
2208         return WID_Close((HWAVEIN)wparam);
2209     case MXDM_GETCONTROLDETAILS:
2210         return MXD_GetControlDetails((WINMM_ControlDetails*)wparam);
2211     case MXDM_SETCONTROLDETAILS:
2212         return MXD_SetControlDetails((WINMM_ControlDetails*)wparam);
2213     case DRV_QUERYDEVICEINTERFACESIZE:
2214     case DRV_QUERYDEVICEINTERFACE:
2215         return DRV_QueryDeviceInterface((WINMM_QueryInterfaceInfo*)wparam);
2216     case WINMM_WM_QUIT:
2217         TRACE("QUIT message received\n");
2218         DestroyWindow(g_devices_hwnd);
2219         g_devices_hwnd = NULL;
2220         IMMDeviceEnumerator_Release(g_devenum);
2221         CoUninitialize();
2222         return 0;
2223     }
2224     return DefWindowProcW(hwnd, msg, wparam, lparam);
2225 }
2226
2227 static DWORD WINAPI WINMM_DevicesThreadProc(void *arg)
2228 {
2229     HANDLE evt = arg;
2230     HRESULT hr;
2231     static const WCHAR messageW[] = {'M','e','s','s','a','g','e',0};
2232
2233     hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
2234     if(FAILED(hr)){
2235         WARN("CoInitializeEx failed: %08x\n", hr);
2236         return 1;
2237     }
2238
2239     hr = WINMM_InitMMDevices();
2240     if(FAILED(hr)){
2241         CoUninitialize();
2242         return 1;
2243     }
2244
2245     hr = CoCreateInstance(&CLSID_MMDeviceEnumerator, NULL,
2246             CLSCTX_INPROC_SERVER, &IID_IMMDeviceEnumerator, (void**)&g_devenum);
2247     if(FAILED(hr)){
2248         WARN("CoCreateInstance failed: %08x\n", hr);
2249         CoUninitialize();
2250         return 1;
2251     }
2252
2253     g_devices_hwnd = CreateWindowW(messageW, NULL, 0, 0, 0, 0, 0,
2254             HWND_MESSAGE, NULL, NULL, NULL);
2255     if(!g_devices_hwnd){
2256         WARN("CreateWindow failed: %d\n", GetLastError());
2257         IMMDeviceEnumerator_Release(g_devenum);
2258         CoUninitialize();
2259         return 1;
2260     }
2261
2262     SetWindowLongPtrW(g_devices_hwnd, GWLP_WNDPROC,
2263             (LONG_PTR)WINMM_DevicesMsgProc);
2264
2265     /* inform caller that the thread is ready to process messages */
2266     SetEvent(evt);
2267     evt = NULL; /* do not use after this point */
2268
2269     while(1){
2270         DWORD wait;
2271         wait = MsgWaitForMultipleObjects(g_devhandle_count, g_device_handles,
2272                 FALSE, INFINITE, QS_ALLINPUT);
2273         if(wait == g_devhandle_count + WAIT_OBJECT_0){
2274             MSG msg;
2275             if(PeekMessageW(&msg, g_devices_hwnd, 0, 0, PM_REMOVE))
2276                 WARN("Unexpected message: 0x%x\n", msg.message);
2277             if(!g_devices_hwnd)
2278                 break;
2279         }else if(wait < g_devhandle_count + WAIT_OBJECT_0){
2280             WINMM_Device *device = g_handle_devices[wait - WAIT_OBJECT_0];
2281             if(device->render)
2282                 WOD_PushData(device);
2283             else
2284                 WID_PullData(device);
2285         }else
2286             WARN("Unexpected MsgWait result 0x%x, GLE: %d\n", wait,
2287                     GetLastError());
2288     }
2289
2290     return 0;
2291 }
2292
2293 static BOOL WINMM_StartDevicesThread(void)
2294 {
2295     HANDLE events[2];
2296     DWORD wait;
2297
2298     EnterCriticalSection(&g_devthread_lock);
2299
2300     if(g_devices_thread){
2301         DWORD wait;
2302
2303         wait = WaitForSingleObject(g_devices_thread, 0);
2304         if(wait == WAIT_TIMEOUT){
2305             LeaveCriticalSection(&g_devthread_lock);
2306             return TRUE;
2307         }
2308         if(wait != WAIT_OBJECT_0){
2309             LeaveCriticalSection(&g_devthread_lock);
2310             return FALSE;
2311         }
2312
2313         g_devices_thread = NULL;
2314         g_devices_hwnd = NULL;
2315     }
2316
2317     TRACE("Starting up devices thread\n");
2318
2319     events[0] = CreateEventW(NULL, FALSE, FALSE, NULL);
2320
2321     g_devices_thread = CreateThread(NULL, 0, WINMM_DevicesThreadProc,
2322             events[0], 0, NULL);
2323     if(!g_devices_thread){
2324         LeaveCriticalSection(&g_devthread_lock);
2325         CloseHandle(events[0]);
2326         return FALSE;
2327     }
2328
2329     events[1] = g_devices_thread;
2330     wait = WaitForMultipleObjects(2, events, FALSE, INFINITE);
2331     CloseHandle(events[0]);
2332     if(wait != WAIT_OBJECT_0){
2333         if(wait == 1 + WAIT_OBJECT_0){
2334             CloseHandle(g_devices_thread);
2335             g_devices_thread = NULL;
2336             g_devices_hwnd = NULL;
2337         }
2338         LeaveCriticalSection(&g_devthread_lock);
2339         return FALSE;
2340     }
2341
2342     LeaveCriticalSection(&g_devthread_lock);
2343
2344     return TRUE;
2345 }
2346
2347 /**************************************************************************
2348  *                              waveOutGetNumDevs               [WINMM.@]
2349  */
2350 UINT WINAPI waveOutGetNumDevs(void)
2351 {
2352     HRESULT hr = WINMM_InitMMDevices();
2353     if(FAILED(hr))
2354         return 0;
2355
2356     TRACE("count: %u\n", g_outmmdevices_count);
2357
2358     return g_outmmdevices_count;
2359 }
2360
2361 /**************************************************************************
2362  *                              waveOutGetDevCapsA              [WINMM.@]
2363  */
2364 UINT WINAPI waveOutGetDevCapsA(UINT_PTR uDeviceID, LPWAVEOUTCAPSA lpCaps,
2365                                UINT uSize)
2366 {
2367     WAVEOUTCAPSW        wocW;
2368     UINT                ret;
2369
2370     TRACE("(%lu, %p, %u)\n", uDeviceID, lpCaps, uSize);
2371
2372     if(!lpCaps)
2373         return MMSYSERR_INVALPARAM;
2374
2375     ret = waveOutGetDevCapsW(uDeviceID, &wocW, sizeof(wocW));
2376
2377     if (ret == MMSYSERR_NOERROR) {
2378         WAVEOUTCAPSA wocA;
2379         wocA.wMid           = wocW.wMid;
2380         wocA.wPid           = wocW.wPid;
2381         wocA.vDriverVersion = wocW.vDriverVersion;
2382         WideCharToMultiByte( CP_ACP, 0, wocW.szPname, -1, wocA.szPname,
2383                              sizeof(wocA.szPname), NULL, NULL );
2384         wocA.dwFormats      = wocW.dwFormats;
2385         wocA.wChannels      = wocW.wChannels;
2386         wocA.dwSupport      = wocW.dwSupport;
2387         memcpy(lpCaps, &wocA, min(uSize, sizeof(wocA)));
2388     }
2389     return ret;
2390 }
2391
2392 /**************************************************************************
2393  *                              waveOutGetDevCapsW              [WINMM.@]
2394  */
2395 UINT WINAPI waveOutGetDevCapsW(UINT_PTR uDeviceID, LPWAVEOUTCAPSW lpCaps,
2396                                UINT uSize)
2397 {
2398     WAVEOUTCAPSW mapper_caps, *caps;
2399     HRESULT hr;
2400
2401     TRACE("(%lu, %p, %u)\n", uDeviceID, lpCaps, uSize);
2402
2403     hr = WINMM_InitMMDevices();
2404     if(FAILED(hr))
2405         return MMSYSERR_NODRIVER;
2406
2407     if (lpCaps == NULL) return MMSYSERR_INVALPARAM;
2408
2409     if(WINMM_IsMapper(uDeviceID)){
2410         /* FIXME: Should be localized */
2411         static const WCHAR mapper_pnameW[] = {'W','i','n','e',' ','S','o','u',
2412             'n','d',' ','M','a','p','p','e','r',0};
2413
2414         mapper_caps.wMid = 0xFF;
2415         mapper_caps.wPid = 0xFF;
2416         mapper_caps.vDriverVersion = 0x00010001;
2417         mapper_caps.dwFormats = 0xFFFFFFFF;
2418         mapper_caps.wReserved1 = 0;
2419         mapper_caps.dwSupport = WAVECAPS_LRVOLUME | WAVECAPS_VOLUME |
2420             WAVECAPS_SAMPLEACCURATE;
2421         mapper_caps.wChannels = 2;
2422         lstrcpyW(mapper_caps.szPname, mapper_pnameW);
2423
2424         caps = &mapper_caps;
2425     }else{
2426         if(uDeviceID >= g_outmmdevices_count)
2427             return MMSYSERR_BADDEVICEID;
2428
2429         caps = &g_out_mmdevices[uDeviceID].out_caps;
2430     }
2431
2432     memcpy(lpCaps, caps, min(uSize, sizeof(*lpCaps)));
2433
2434     return MMSYSERR_NOERROR;
2435 }
2436
2437 /**************************************************************************
2438  *                              waveOutGetErrorTextA    [WINMM.@]
2439  *                              waveInGetErrorTextA     [WINMM.@]
2440  */
2441 UINT WINAPI waveOutGetErrorTextA(UINT uError, LPSTR lpText, UINT uSize)
2442 {
2443     UINT        ret;
2444
2445     if (lpText == NULL) ret = MMSYSERR_INVALPARAM;
2446     else if (uSize == 0) ret = MMSYSERR_NOERROR;
2447     else
2448     {
2449         LPWSTR  xstr = HeapAlloc(GetProcessHeap(), 0, uSize * sizeof(WCHAR));
2450         if (!xstr) ret = MMSYSERR_NOMEM;
2451         else
2452         {
2453             ret = waveOutGetErrorTextW(uError, xstr, uSize);
2454             if (ret == MMSYSERR_NOERROR)
2455                 WideCharToMultiByte(CP_ACP, 0, xstr, -1, lpText, uSize, NULL, NULL);
2456             HeapFree(GetProcessHeap(), 0, xstr);
2457         }
2458     }
2459     return ret;
2460 }
2461
2462 /**************************************************************************
2463  *                              waveOutGetErrorTextW    [WINMM.@]
2464  *                              waveInGetErrorTextW     [WINMM.@]
2465  */
2466 UINT WINAPI waveOutGetErrorTextW(UINT uError, LPWSTR lpText, UINT uSize)
2467 {
2468     UINT        ret = MMSYSERR_BADERRNUM;
2469
2470     if (lpText == NULL) ret = MMSYSERR_INVALPARAM;
2471     else if (uSize == 0) ret = MMSYSERR_NOERROR;
2472     else if (
2473                /* test has been removed because MMSYSERR_BASE is 0, and gcc did emit
2474                 * a warning for the test was always true */
2475                (/*uError >= MMSYSERR_BASE && */ uError <= MMSYSERR_LASTERROR) ||
2476                (uError >= WAVERR_BASE  && uError <= WAVERR_LASTERROR)) {
2477         if (LoadStringW(hWinMM32Instance,
2478                         uError, lpText, uSize) > 0) {
2479             ret = MMSYSERR_NOERROR;
2480         }
2481     }
2482     return ret;
2483 }
2484
2485 /**************************************************************************
2486  *                      waveOutOpen                     [WINMM.@]
2487  * All the args/structs have the same layout as the win16 equivalents
2488  */
2489 MMRESULT WINAPI waveOutOpen(LPHWAVEOUT lphWaveOut, UINT uDeviceID,
2490                        LPCWAVEFORMATEX lpFormat, DWORD_PTR dwCallback,
2491                        DWORD_PTR dwInstance, DWORD dwFlags)
2492 {
2493     LRESULT res;
2494     WINMM_OpenInfo info;
2495     WINMM_CBInfo cb_info;
2496
2497     TRACE("(%p, %u, %p, %lx, %lx, %08x)\n", lphWaveOut, uDeviceID, lpFormat,
2498             dwCallback, dwInstance, dwFlags);
2499
2500     if(!WINMM_StartDevicesThread())
2501         return MMSYSERR_NODRIVER;
2502
2503     if(!lphWaveOut && !(dwFlags & WAVE_FORMAT_QUERY))
2504         return MMSYSERR_INVALPARAM;
2505
2506     res = WINMM_CheckCallback(dwCallback, dwFlags, FALSE);
2507     if(res != MMSYSERR_NOERROR)
2508         return res;
2509
2510     info.format = (WAVEFORMATEX*)lpFormat;
2511     info.callback = dwCallback;
2512     info.cb_user = dwInstance;
2513     info.req_device = uDeviceID;
2514     info.flags = dwFlags;
2515
2516     res = SendMessageW(g_devices_hwnd, WODM_OPEN, (DWORD_PTR)&info, 0);
2517     if(res != MMSYSERR_NOERROR)
2518         return res;
2519
2520     if(lphWaveOut)
2521         *lphWaveOut = (HWAVEOUT)info.handle;
2522
2523     cb_info.flags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
2524     cb_info.callback = dwCallback;
2525     cb_info.user = dwInstance;
2526     cb_info.hwave = info.handle;
2527
2528     WINMM_NotifyClient(&cb_info, WOM_OPEN, 0, 0);
2529
2530     return res;
2531 }
2532
2533 /**************************************************************************
2534  *                              waveOutClose            [WINMM.@]
2535  */
2536 UINT WINAPI waveOutClose(HWAVEOUT hWaveOut)
2537 {
2538     UINT res;
2539     WINMM_Device *device;
2540     WINMM_CBInfo cb_info;
2541
2542     TRACE("(%p)\n", hWaveOut);
2543
2544     device = WINMM_GetDeviceFromHWAVE((HWAVE)hWaveOut);
2545
2546     if(!WINMM_ValidateAndLock(device))
2547         return MMSYSERR_INVALHANDLE;
2548
2549     cb_info = device->cb_info;
2550
2551     LeaveCriticalSection(&device->lock);
2552
2553     res = SendMessageW(g_devices_hwnd, WODM_CLOSE, (WPARAM)hWaveOut, 0);
2554
2555     if(res == MMSYSERR_NOERROR)
2556         WINMM_NotifyClient(&cb_info, WOM_CLOSE, 0, 0);
2557
2558     return res;
2559 }
2560
2561 /**************************************************************************
2562  *                              waveOutPrepareHeader    [WINMM.@]
2563  */
2564 UINT WINAPI waveOutPrepareHeader(HWAVEOUT hWaveOut,
2565                                  WAVEHDR* lpWaveOutHdr, UINT uSize)
2566 {
2567     TRACE("(%p, %p, %u)\n", hWaveOut, lpWaveOutHdr, uSize);
2568
2569     if(!lpWaveOutHdr || uSize < sizeof(WAVEHDR))
2570         return MMSYSERR_INVALPARAM;
2571
2572     if(lpWaveOutHdr->dwFlags & WHDR_INQUEUE)
2573         return WAVERR_STILLPLAYING;
2574
2575     return WINMM_PrepareHeader((HWAVE)hWaveOut, lpWaveOutHdr);
2576 }
2577
2578 /**************************************************************************
2579  *                              waveOutUnprepareHeader  [WINMM.@]
2580  */
2581 UINT WINAPI waveOutUnprepareHeader(HWAVEOUT hWaveOut,
2582                                    LPWAVEHDR lpWaveOutHdr, UINT uSize)
2583 {
2584     TRACE("(%p, %p, %u)\n", hWaveOut, lpWaveOutHdr, uSize);
2585
2586     if(!lpWaveOutHdr || uSize < sizeof(WAVEHDR))
2587         return MMSYSERR_INVALPARAM;
2588     
2589     if(!(lpWaveOutHdr->dwFlags & WHDR_PREPARED))
2590         return MMSYSERR_NOERROR;
2591
2592     if(lpWaveOutHdr->dwFlags & WHDR_INQUEUE)
2593         return WAVERR_STILLPLAYING;
2594
2595     return WINMM_UnprepareHeader((HWAVE)hWaveOut, lpWaveOutHdr);
2596 }
2597
2598 /**************************************************************************
2599  *                              waveOutWrite            [WINMM.@]
2600  */
2601 UINT WINAPI waveOutWrite(HWAVEOUT hWaveOut, WAVEHDR *header, UINT uSize)
2602 {
2603     WINMM_Device *device;
2604     MMRESULT mr;
2605
2606     TRACE("(%p, %p, %u)\n", hWaveOut, header, uSize);
2607
2608     device = WINMM_GetDeviceFromHWAVE((HWAVE)hWaveOut);
2609
2610     if(!WINMM_ValidateAndLock(device))
2611         return MMSYSERR_INVALHANDLE;
2612
2613     if(!header->lpData || !(header->dwFlags & WHDR_PREPARED)){
2614         LeaveCriticalSection(&device->lock);
2615         return WAVERR_UNPREPARED;
2616     }
2617
2618     if(header->dwFlags & WHDR_INQUEUE){
2619         LeaveCriticalSection(&device->lock);
2620         return WAVERR_STILLPLAYING;
2621     }
2622
2623     if(device->acm_handle){
2624         ACMSTREAMHEADER *ash = (ACMSTREAMHEADER*)header->reserved;
2625
2626         ash->cbSrcLength = header->dwBufferLength;
2627         mr = acmStreamConvert(device->acm_handle, ash, 0);
2628         if(mr != MMSYSERR_NOERROR){
2629             LeaveCriticalSection(&device->lock);
2630             return mr;
2631         }
2632     }
2633
2634     if(device->first){
2635         device->last->lpNext = header;
2636         device->last = header;
2637         if(!device->playing)
2638             device->playing = header;
2639     }else{
2640         device->playing = device->first = device->last = header;
2641         if(header->dwFlags & WHDR_BEGINLOOP){
2642             device->loop_counter = header->dwLoops;
2643             device->loop_start = header;
2644         }
2645     }
2646
2647     header->lpNext = NULL;
2648     header->dwFlags &= ~WHDR_DONE;
2649     header->dwFlags |= WHDR_INQUEUE;
2650
2651     mr = WINMM_BeginPlaying(device);
2652
2653     LeaveCriticalSection(&device->lock);
2654
2655     return mr;
2656 }
2657
2658 /**************************************************************************
2659  *                              waveOutBreakLoop        [WINMM.@]
2660  */
2661 UINT WINAPI waveOutBreakLoop(HWAVEOUT hWaveOut)
2662 {
2663     WINMM_Device *device;
2664
2665     TRACE("(%p)\n", hWaveOut);
2666
2667     device = WINMM_GetDeviceFromHWAVE((HWAVE)hWaveOut);
2668
2669     if(!WINMM_ValidateAndLock(device))
2670         return MMSYSERR_INVALHANDLE;
2671
2672     device->loop_counter = 0;
2673
2674     LeaveCriticalSection(&device->lock);
2675
2676     return MMSYSERR_NOERROR;
2677 }
2678
2679 /**************************************************************************
2680  *                              waveOutPause            [WINMM.@]
2681  */
2682 UINT WINAPI waveOutPause(HWAVEOUT hWaveOut)
2683 {
2684     TRACE("(%p)\n", hWaveOut);
2685
2686     return WINMM_Pause((HWAVE)hWaveOut);
2687 }
2688
2689 /**************************************************************************
2690  *                              waveOutReset            [WINMM.@]
2691  */
2692 UINT WINAPI waveOutReset(HWAVEOUT hWaveOut)
2693 {
2694     TRACE("(%p)\n", hWaveOut);
2695
2696     return WINMM_Reset((HWAVE)hWaveOut);
2697 }
2698
2699 /**************************************************************************
2700  *                              waveOutRestart          [WINMM.@]
2701  */
2702 UINT WINAPI waveOutRestart(HWAVEOUT hWaveOut)
2703 {
2704     WINMM_Device *device;
2705     MMRESULT mr;
2706
2707     TRACE("(%p)\n", hWaveOut);
2708
2709     device = WINMM_GetDeviceFromHWAVE((HWAVE)hWaveOut);
2710
2711     if(!WINMM_ValidateAndLock(device))
2712         return MMSYSERR_INVALHANDLE;
2713
2714     device->stopped = TRUE;
2715
2716     mr = WINMM_BeginPlaying(device);
2717
2718     LeaveCriticalSection(&device->lock);
2719
2720     return mr;
2721 }
2722
2723 /**************************************************************************
2724  *                              waveOutGetPosition      [WINMM.@]
2725  */
2726 UINT WINAPI waveOutGetPosition(HWAVEOUT hWaveOut, LPMMTIME lpTime,
2727                                UINT uSize)
2728 {
2729     TRACE("(%p, %p, %u)\n", hWaveOut, lpTime, uSize);
2730
2731     if(!uSize || !lpTime || uSize != sizeof(MMTIME))
2732         return MMSYSERR_INVALPARAM;
2733
2734     return WINMM_GetPosition((HWAVE)hWaveOut, lpTime);
2735 }
2736
2737 /**************************************************************************
2738  *                              waveOutGetPitch         [WINMM.@]
2739  */
2740 UINT WINAPI waveOutGetPitch(HWAVEOUT hWaveOut, LPDWORD lpdw)
2741 {
2742     TRACE("(%p, %p)\n", hWaveOut, lpdw);
2743     return MMSYSERR_NOTSUPPORTED;
2744 }
2745
2746 /**************************************************************************
2747  *                              waveOutSetPitch         [WINMM.@]
2748  */
2749 UINT WINAPI waveOutSetPitch(HWAVEOUT hWaveOut, DWORD dw)
2750 {
2751     TRACE("(%p, %08x)\n", hWaveOut, dw);
2752
2753     return MMSYSERR_NOTSUPPORTED;
2754 }
2755
2756 /**************************************************************************
2757  *                              waveOutGetPlaybackRate  [WINMM.@]
2758  */
2759 UINT WINAPI waveOutGetPlaybackRate(HWAVEOUT hWaveOut, LPDWORD lpdw)
2760 {
2761     TRACE("(%p, %p)\n", hWaveOut, lpdw);
2762
2763     return MMSYSERR_NOTSUPPORTED;
2764 }
2765
2766 /**************************************************************************
2767  *                              waveOutSetPlaybackRate  [WINMM.@]
2768  */
2769 UINT WINAPI waveOutSetPlaybackRate(HWAVEOUT hWaveOut, DWORD dw)
2770 {
2771     TRACE("(%p, %08x)\n", hWaveOut, dw);
2772
2773     return MMSYSERR_NOTSUPPORTED;
2774 }
2775
2776 /**************************************************************************
2777  *                              waveOutGetVolume        [WINMM.@]
2778  */
2779 UINT WINAPI waveOutGetVolume(HWAVEOUT hWaveOut, DWORD *out)
2780 {
2781     WINMM_Device *device;
2782     UINT32 channels;
2783     float *vols;
2784     HRESULT hr;
2785
2786     TRACE("(%p, %p)\n", hWaveOut, out);
2787
2788     if(!out)
2789         return MMSYSERR_INVALPARAM;
2790
2791     device = WINMM_GetDeviceFromHWAVE((HWAVE)hWaveOut);
2792
2793     if(!WINMM_ValidateAndLock(device))
2794         return MMSYSERR_INVALHANDLE;
2795
2796     hr = IAudioStreamVolume_GetChannelCount(device->volume, &channels);
2797     if(FAILED(hr)){
2798         LeaveCriticalSection(&device->lock);
2799         WARN("GetChannelCount failed: %08x\n", hr);
2800         return MMSYSERR_ERROR;
2801     }
2802
2803     vols = HeapAlloc(GetProcessHeap(), 0, sizeof(float) * channels);
2804     if(!vols){
2805         LeaveCriticalSection(&device->lock);
2806         return MMSYSERR_NOMEM;
2807     }
2808
2809     hr = IAudioStreamVolume_GetAllVolumes(device->volume, channels, vols);
2810     if(FAILED(hr)){
2811         LeaveCriticalSection(&device->lock);
2812         HeapFree(GetProcessHeap(), 0, vols);
2813         WARN("GetAllVolumes failed: %08x\n", hr);
2814         return MMSYSERR_ERROR;
2815     }
2816
2817     LeaveCriticalSection(&device->lock);
2818
2819     *out = ((UINT16)(vols[0] * (DWORD)0xFFFF));
2820     if(channels > 1)
2821         *out |= ((UINT16)(vols[1] * (DWORD)0xFFFF)) << 16;
2822
2823     HeapFree(GetProcessHeap(), 0, vols);
2824
2825     return MMSYSERR_NOERROR;
2826 }
2827
2828 /**************************************************************************
2829  *                              waveOutSetVolume        [WINMM.@]
2830  */
2831 UINT WINAPI waveOutSetVolume(HWAVEOUT hWaveOut, DWORD in)
2832 {
2833     WINMM_Device *device;
2834     UINT32 channels;
2835     float *vols;
2836     HRESULT hr;
2837
2838     TRACE("(%p, %08x)\n", hWaveOut, in);
2839
2840     device = WINMM_GetDeviceFromHWAVE((HWAVE)hWaveOut);
2841
2842     if(!WINMM_ValidateAndLock(device))
2843         return MMSYSERR_INVALHANDLE;
2844
2845     hr = IAudioStreamVolume_GetChannelCount(device->volume, &channels);
2846     if(FAILED(hr)){
2847         LeaveCriticalSection(&device->lock);
2848         WARN("GetChannelCount failed: %08x\n", hr);
2849         return MMSYSERR_ERROR;
2850     }
2851
2852     vols = HeapAlloc(GetProcessHeap(), 0, sizeof(float) * channels);
2853     if(!vols){
2854         LeaveCriticalSection(&device->lock);
2855         return MMSYSERR_NOMEM;
2856     }
2857
2858     hr = IAudioStreamVolume_GetAllVolumes(device->volume, channels, vols);
2859     if(FAILED(hr)){
2860         LeaveCriticalSection(&device->lock);
2861         HeapFree(GetProcessHeap(), 0, vols);
2862         WARN("GetAllVolumes failed: %08x\n", hr);
2863         return MMSYSERR_ERROR;
2864     }
2865
2866     vols[0] = (float)((DWORD)(in & 0xFFFF) / (float)0xFFFF);
2867     if(channels > 1)
2868         vols[1] = (float)((DWORD)(in >> 16) / (float)0xFFFF);
2869
2870     hr = IAudioStreamVolume_SetAllVolumes(device->volume, channels, vols);
2871     if(FAILED(hr)){
2872         LeaveCriticalSection(&device->lock);
2873         HeapFree(GetProcessHeap(), 0, vols);
2874         WARN("SetAllVolumes failed: %08x\n", hr);
2875         return MMSYSERR_ERROR;
2876     }
2877
2878     LeaveCriticalSection(&device->lock);
2879
2880     HeapFree(GetProcessHeap(), 0, vols);
2881
2882     return MMSYSERR_NOERROR;
2883 }
2884
2885 /**************************************************************************
2886  *                              waveOutGetID            [WINMM.@]
2887  */
2888 UINT WINAPI waveOutGetID(HWAVEOUT hWaveOut, UINT* lpuDeviceID)
2889 {
2890     WINMM_Device *device;
2891     UINT dev, junk;
2892     BOOL is_out;
2893
2894     TRACE("(%p, %p)\n", hWaveOut, lpuDeviceID);
2895
2896     if(!lpuDeviceID)
2897         return MMSYSERR_INVALPARAM;
2898
2899     device = WINMM_GetDeviceFromHWAVE((HWAVE)hWaveOut);
2900     if(!WINMM_ValidateAndLock(device))
2901         return MMSYSERR_INVALHANDLE;
2902
2903     LeaveCriticalSection(&device->lock);
2904
2905     WINMM_DecomposeHWAVE((HWAVE)hWaveOut, lpuDeviceID, &is_out, &dev, &junk);
2906
2907     return MMSYSERR_NOERROR;
2908 }
2909
2910 static UINT WINMM_QueryInstanceIDSize(UINT device, DWORD_PTR *len, BOOL is_out)
2911 {
2912     UINT count;
2913     WINMM_MMDevice *devices;
2914
2915     TRACE("(%u, %p, %d)\n", device, len, is_out);
2916
2917     if(is_out){
2918         count = g_outmmdevices_count;
2919         devices = g_out_mmdevices;
2920     }else{
2921         count = g_inmmdevices_count;
2922         devices = g_in_mmdevices;
2923     }
2924
2925     if(device >= count)
2926         return MMSYSERR_INVALHANDLE;
2927
2928     *len = (lstrlenW(devices[device].dev_id) + 1) * sizeof(WCHAR);
2929
2930     return MMSYSERR_NOERROR;
2931 }
2932
2933 static UINT WINMM_QueryInstanceID(UINT device, WCHAR *str, DWORD_PTR len,
2934         BOOL is_out)
2935 {
2936     UINT count, id_len;
2937     WINMM_MMDevice *devices;
2938
2939     TRACE("(%u, %p, %d)\n", device, str, is_out);
2940
2941     if(is_out){
2942         count = g_outmmdevices_count;
2943         devices = g_out_mmdevices;
2944     }else{
2945         count = g_inmmdevices_count;
2946         devices = g_in_mmdevices;
2947     }
2948
2949     if(device >= count)
2950         return MMSYSERR_INVALHANDLE;
2951
2952     id_len = (lstrlenW(devices[device].dev_id) + 1) * sizeof(WCHAR);
2953     if(len < id_len)
2954         return MMSYSERR_ERROR;
2955
2956     memcpy(str, devices[device].dev_id, id_len);
2957
2958     return MMSYSERR_NOERROR;
2959 }
2960
2961 static UINT get_device_interface(UINT msg, BOOL is_out, UINT index, WCHAR *out, ULONG *out_len)
2962 {
2963     WINMM_QueryInterfaceInfo info;
2964
2965     if(!WINMM_StartDevicesThread())
2966         return MMSYSERR_NODRIVER;
2967
2968     info.is_out = is_out;
2969     info.index = index;
2970     info.str = out;
2971     info.len_bytes = out_len;
2972
2973     return SendMessageW(g_devices_hwnd, msg, (DWORD_PTR)&info, 0);
2974 }
2975
2976 /**************************************************************************
2977  *                              waveOutMessage          [WINMM.@]
2978  */
2979 UINT WINAPI waveOutMessage(HWAVEOUT hWaveOut, UINT uMessage,
2980                            DWORD_PTR dwParam1, DWORD_PTR dwParam2)
2981 {
2982     TRACE("(%p, %u, %lx, %lx)\n", hWaveOut, uMessage, dwParam1, dwParam2);
2983
2984     switch(uMessage){
2985     case DRV_QUERYFUNCTIONINSTANCEIDSIZE:
2986         return WINMM_QueryInstanceIDSize(HandleToULong(hWaveOut),
2987                 (DWORD_PTR*)dwParam1, TRUE);
2988     case DRV_QUERYFUNCTIONINSTANCEID:
2989         return WINMM_QueryInstanceID(HandleToULong(hWaveOut), (WCHAR*)dwParam1, dwParam2, TRUE);
2990     case DRV_QUERYDEVICEINTERFACESIZE:
2991         return get_device_interface(DRV_QUERYDEVICEINTERFACESIZE, TRUE, HandleToULong(hWaveOut),
2992                 NULL, (ULONG*)dwParam1);
2993     case DRV_QUERYDEVICEINTERFACE:
2994         {
2995             ULONG size = dwParam2;
2996             return get_device_interface(DRV_QUERYDEVICEINTERFACE, TRUE, HandleToULong(hWaveOut),
2997                     (WCHAR*)dwParam1, &size);
2998         }
2999     case DRV_QUERYMAPPABLE:
3000         return MMSYSERR_NOERROR;
3001     case DRVM_MAPPER_PREFERRED_GET:
3002         if(dwParam1) {
3003             if(g_outmmdevices_count > 0)
3004                 /* Device 0 is always the default device */
3005                 *(DWORD *)dwParam1 = 0;
3006             else
3007                 *(DWORD *)dwParam1 = -1;
3008         }
3009
3010         if(dwParam2)
3011             /* Status flags */
3012             *(DWORD *)dwParam2 = 0;
3013
3014         return MMSYSERR_NOERROR;
3015     }
3016
3017     TRACE("Message not supported: %u\n", uMessage);
3018
3019     return MMSYSERR_NOTSUPPORTED;
3020 }
3021
3022 /**************************************************************************
3023  *                              waveInGetNumDevs                [WINMM.@]
3024  */
3025 UINT WINAPI waveInGetNumDevs(void)
3026 {
3027     HRESULT hr = WINMM_InitMMDevices();
3028     if(FAILED(hr))
3029         return 0;
3030
3031     TRACE("count: %u\n", g_inmmdevices_count);
3032
3033     return g_inmmdevices_count;
3034 }
3035
3036 /**************************************************************************
3037  *                              waveInGetDevCapsW               [WINMM.@]
3038  */
3039 UINT WINAPI waveInGetDevCapsW(UINT_PTR uDeviceID, LPWAVEINCAPSW lpCaps, UINT uSize)
3040 {
3041     WAVEINCAPSW mapper_caps, *caps;
3042     HRESULT hr;
3043
3044     TRACE("(%lu, %p, %u)\n", uDeviceID, lpCaps, uSize);
3045
3046     hr = WINMM_InitMMDevices();
3047     if(FAILED(hr))
3048         return MMSYSERR_NODRIVER;
3049
3050     if(!lpCaps)
3051         return MMSYSERR_INVALPARAM;
3052
3053     if(WINMM_IsMapper(uDeviceID)){
3054         /* FIXME: Should be localized */
3055         static const WCHAR mapper_pnameW[] = {'W','i','n','e',' ','S','o','u',
3056             'n','d',' ','M','a','p','p','e','r',0};
3057
3058         mapper_caps.wMid = 0xFF;
3059         mapper_caps.wPid = 0xFF;
3060         mapper_caps.vDriverVersion = 0x00010001;
3061         mapper_caps.dwFormats = 0xFFFFFFFF;
3062         mapper_caps.wReserved1 = 0;
3063         mapper_caps.wChannels = 2;
3064         lstrcpyW(mapper_caps.szPname, mapper_pnameW);
3065
3066         caps = &mapper_caps;
3067     }else{
3068         if(uDeviceID >= g_inmmdevices_count)
3069             return MMSYSERR_BADDEVICEID;
3070
3071         caps = &g_in_mmdevices[uDeviceID].in_caps;
3072     }
3073
3074     memcpy(lpCaps, caps, min(uSize, sizeof(*lpCaps)));
3075
3076     return MMSYSERR_NOERROR;
3077 }
3078
3079 /**************************************************************************
3080  *                              waveInGetDevCapsA               [WINMM.@]
3081  */
3082 UINT WINAPI waveInGetDevCapsA(UINT_PTR uDeviceID, LPWAVEINCAPSA lpCaps, UINT uSize)
3083 {
3084     UINT ret;
3085     WAVEINCAPSW wicW;
3086
3087     TRACE("(%lu, %p, %u)\n", uDeviceID, lpCaps, uSize);
3088
3089     if(!lpCaps)
3090         return MMSYSERR_INVALPARAM;
3091
3092     ret = waveInGetDevCapsW(uDeviceID, &wicW, sizeof(wicW));
3093
3094     if (ret == MMSYSERR_NOERROR) {
3095         WAVEINCAPSA wicA;
3096         wicA.wMid           = wicW.wMid;
3097         wicA.wPid           = wicW.wPid;
3098         wicA.vDriverVersion = wicW.vDriverVersion;
3099         WideCharToMultiByte( CP_ACP, 0, wicW.szPname, -1, wicA.szPname,
3100                              sizeof(wicA.szPname), NULL, NULL );
3101         wicA.dwFormats      = wicW.dwFormats;
3102         wicA.wChannels      = wicW.wChannels;
3103         memcpy(lpCaps, &wicA, min(uSize, sizeof(wicA)));
3104     }
3105     return ret;
3106 }
3107
3108 /**************************************************************************
3109  *                              waveInOpen                      [WINMM.@]
3110  */
3111 MMRESULT WINAPI waveInOpen(HWAVEIN* lphWaveIn, UINT uDeviceID,
3112                            LPCWAVEFORMATEX lpFormat, DWORD_PTR dwCallback,
3113                            DWORD_PTR dwInstance, DWORD dwFlags)
3114 {
3115     LRESULT res;
3116     WINMM_OpenInfo info;
3117     WINMM_CBInfo cb_info;
3118
3119     TRACE("(%p, %x, %p, %lx, %lx, %08x)\n", lphWaveIn, uDeviceID, lpFormat,
3120             dwCallback, dwInstance, dwFlags);
3121
3122     if(!WINMM_StartDevicesThread())
3123         return MMSYSERR_NODRIVER;
3124
3125     if(!lphWaveIn && !(dwFlags & WAVE_FORMAT_QUERY))
3126         return MMSYSERR_INVALPARAM;
3127
3128     res = WINMM_CheckCallback(dwCallback, dwFlags, FALSE);
3129     if(res != MMSYSERR_NOERROR)
3130         return res;
3131
3132     info.format = (WAVEFORMATEX*)lpFormat;
3133     info.callback = dwCallback;
3134     info.cb_user = dwInstance;
3135     info.req_device = uDeviceID;
3136     info.flags = dwFlags;
3137
3138     res = SendMessageW(g_devices_hwnd, WIDM_OPEN, (DWORD_PTR)&info, 0);
3139     if(res != MMSYSERR_NOERROR)
3140         return res;
3141
3142     if(lphWaveIn)
3143         *lphWaveIn = (HWAVEIN)info.handle;
3144
3145     cb_info.flags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
3146     cb_info.callback = dwCallback;
3147     cb_info.user = dwInstance;
3148     cb_info.hwave = info.handle;
3149
3150     WINMM_NotifyClient(&cb_info, WIM_OPEN, 0, 0);
3151
3152     return res;
3153 }
3154
3155 /**************************************************************************
3156  *                              waveInClose                     [WINMM.@]
3157  */
3158 UINT WINAPI waveInClose(HWAVEIN hWaveIn)
3159 {
3160     WINMM_Device *device;
3161     WINMM_CBInfo cb_info;
3162     UINT res;
3163
3164     TRACE("(%p)\n", hWaveIn);
3165
3166     device = WINMM_GetDeviceFromHWAVE((HWAVE)hWaveIn);
3167
3168     if(!WINMM_ValidateAndLock(device))
3169         return MMSYSERR_INVALHANDLE;
3170
3171     cb_info = device->cb_info;
3172
3173     LeaveCriticalSection(&device->lock);
3174
3175     res = SendMessageW(g_devices_hwnd, WIDM_CLOSE, (WPARAM)hWaveIn, 0);
3176
3177     if(res == MMSYSERR_NOERROR)
3178         WINMM_NotifyClient(&cb_info, WIM_CLOSE, 0, 0);
3179
3180     return res;
3181 }
3182
3183 /**************************************************************************
3184  *                              waveInPrepareHeader             [WINMM.@]
3185  */
3186 UINT WINAPI waveInPrepareHeader(HWAVEIN hWaveIn, WAVEHDR* lpWaveInHdr,
3187                                 UINT uSize)
3188 {
3189     TRACE("(%p, %p, %u)\n", hWaveIn, lpWaveInHdr, uSize);
3190
3191     if(!lpWaveInHdr || uSize < sizeof(WAVEHDR))
3192         return MMSYSERR_INVALPARAM;
3193
3194     if(lpWaveInHdr->dwFlags & WHDR_INQUEUE)
3195         return WAVERR_STILLPLAYING;
3196
3197     return WINMM_PrepareHeader((HWAVE)hWaveIn, lpWaveInHdr);
3198 }
3199
3200 /**************************************************************************
3201  *                              waveInUnprepareHeader   [WINMM.@]
3202  */
3203 UINT WINAPI waveInUnprepareHeader(HWAVEIN hWaveIn, WAVEHDR* lpWaveInHdr,
3204                                   UINT uSize)
3205 {
3206     TRACE("(%p, %p, %u)\n", hWaveIn, lpWaveInHdr, uSize);
3207
3208     if(!lpWaveInHdr || uSize < sizeof(WAVEHDR))
3209         return MMSYSERR_INVALPARAM;
3210
3211     if(!(lpWaveInHdr->dwFlags & WHDR_PREPARED))
3212         return MMSYSERR_NOERROR;
3213
3214     if(lpWaveInHdr->dwFlags & WHDR_INQUEUE)
3215         return WAVERR_STILLPLAYING;
3216
3217     return WINMM_UnprepareHeader((HWAVE)hWaveIn, lpWaveInHdr);
3218 }
3219
3220 /**************************************************************************
3221  *                              waveInAddBuffer         [WINMM.@]
3222  */
3223 UINT WINAPI waveInAddBuffer(HWAVEIN hWaveIn, WAVEHDR *header, UINT uSize)
3224 {
3225     WINMM_Device *device;
3226
3227     TRACE("(%p, %p, %u)\n", hWaveIn, header, uSize);
3228
3229     if(!header || uSize < sizeof(WAVEHDR))
3230         return MMSYSERR_INVALPARAM;
3231
3232     if(!(header->dwFlags & WHDR_PREPARED))
3233         return WAVERR_UNPREPARED;
3234
3235     device = WINMM_GetDeviceFromHWAVE((HWAVE)hWaveIn);
3236
3237     if(!WINMM_ValidateAndLock(device))
3238         return MMSYSERR_INVALHANDLE;
3239
3240     if(!device->first)
3241         device->first = device->last = header;
3242     else{
3243         device->last->lpNext = header;
3244         device->last = header;
3245     }
3246
3247     header->dwBytesRecorded = 0;
3248     header->lpNext = NULL;
3249     header->dwFlags &= ~WHDR_DONE;
3250     header->dwFlags |= WHDR_INQUEUE;
3251
3252     LeaveCriticalSection(&device->lock);
3253
3254     return MMSYSERR_NOERROR;
3255 }
3256
3257 /**************************************************************************
3258  *                              waveInReset             [WINMM.@]
3259  */
3260 UINT WINAPI waveInReset(HWAVEIN hWaveIn)
3261 {
3262     TRACE("(%p)\n", hWaveIn);
3263
3264     return WINMM_Reset((HWAVE)hWaveIn);
3265 }
3266
3267 /**************************************************************************
3268  *                              waveInStart             [WINMM.@]
3269  */
3270 UINT WINAPI waveInStart(HWAVEIN hWaveIn)
3271 {
3272     WINMM_Device *device;
3273     MMRESULT mr;
3274
3275     TRACE("(%p)\n", hWaveIn);
3276
3277     device = WINMM_GetDeviceFromHWAVE((HWAVE)hWaveIn);
3278
3279     if(!WINMM_ValidateAndLock(device))
3280         return MMSYSERR_INVALHANDLE;
3281
3282     mr = WINMM_BeginPlaying(device);
3283
3284     LeaveCriticalSection(&device->lock);
3285
3286     return mr;
3287 }
3288
3289 /**************************************************************************
3290  *                              waveInStop              [WINMM.@]
3291  */
3292 UINT WINAPI waveInStop(HWAVEIN hWaveIn)
3293 {
3294     WINMM_CBInfo cb_info;
3295     WINMM_Device *device;
3296     WAVEHDR *buf;
3297     HRESULT hr;
3298
3299     TRACE("(%p)\n", hWaveIn);
3300
3301     device = WINMM_GetDeviceFromHWAVE((HWAVE)hWaveIn);
3302
3303     if(!WINMM_ValidateAndLock(device))
3304         return MMSYSERR_INVALHANDLE;
3305
3306     hr = WINMM_Pause((HWAVE)hWaveIn);
3307     if(FAILED(hr)){
3308         LeaveCriticalSection(&device->lock);
3309         return MMSYSERR_ERROR;
3310     }
3311     device->stopped = TRUE;
3312
3313     buf = device->first;
3314     if(buf && buf->dwBytesRecorded > 0){
3315         device->first = buf->lpNext;
3316     }else
3317         buf = NULL;
3318
3319     cb_info = device->cb_info;
3320
3321     LeaveCriticalSection(&device->lock);
3322
3323     if(buf){
3324         buf->dwFlags &= ~WHDR_INQUEUE;
3325         buf->dwFlags |= WHDR_DONE;
3326         WINMM_NotifyClient(&cb_info, WIM_DATA, (DWORD_PTR)buf, 0);
3327     }
3328
3329     return MMSYSERR_NOERROR;
3330 }
3331
3332 /**************************************************************************
3333  *                              waveInGetPosition       [WINMM.@]
3334  */
3335 UINT WINAPI waveInGetPosition(HWAVEIN hWaveIn, LPMMTIME lpTime,
3336                               UINT uSize)
3337 {
3338     TRACE("(%p, %p, %u)\n", hWaveIn, lpTime, uSize);
3339
3340     if(!uSize || !lpTime || uSize != sizeof(MMTIME))
3341         return MMSYSERR_INVALPARAM;
3342
3343     return WINMM_GetPosition((HWAVE)hWaveIn, lpTime);
3344 }
3345
3346 /**************************************************************************
3347  *                              waveInGetID                     [WINMM.@]
3348  */
3349 UINT WINAPI waveInGetID(HWAVEIN hWaveIn, UINT* lpuDeviceID)
3350 {
3351     UINT dev, junk;
3352     BOOL is_out;
3353     WINMM_Device *device;
3354
3355     TRACE("(%p, %p)\n", hWaveIn, lpuDeviceID);
3356
3357     if(!lpuDeviceID)
3358         return MMSYSERR_INVALPARAM;
3359
3360     device = WINMM_GetDeviceFromHWAVE((HWAVE)hWaveIn);
3361     if(!WINMM_ValidateAndLock(device))
3362         return MMSYSERR_INVALHANDLE;
3363
3364     LeaveCriticalSection(&device->lock);
3365
3366     WINMM_DecomposeHWAVE((HWAVE)hWaveIn, lpuDeviceID, &is_out, &dev, &junk);
3367
3368     return MMSYSERR_NOERROR;
3369 }
3370
3371 /**************************************************************************
3372  *                              waveInMessage           [WINMM.@]
3373  */
3374 UINT WINAPI waveInMessage(HWAVEIN hWaveIn, UINT uMessage,
3375                           DWORD_PTR dwParam1, DWORD_PTR dwParam2)
3376 {
3377     TRACE("(%p, %u, %ld, %ld)\n", hWaveIn, uMessage, dwParam1, dwParam2);
3378
3379     switch(uMessage){
3380     case DRV_QUERYFUNCTIONINSTANCEIDSIZE:
3381         return WINMM_QueryInstanceIDSize(HandleToULong(hWaveIn),
3382                 (DWORD_PTR*)dwParam1, FALSE);
3383     case DRV_QUERYFUNCTIONINSTANCEID:
3384         return WINMM_QueryInstanceID(HandleToULong(hWaveIn), (WCHAR*)dwParam1, dwParam2, FALSE);
3385     case DRV_QUERYDEVICEINTERFACESIZE:
3386         return get_device_interface(DRV_QUERYDEVICEINTERFACESIZE, FALSE, HandleToULong(hWaveIn),
3387                 NULL, (ULONG*)dwParam1);
3388     case DRV_QUERYDEVICEINTERFACE:
3389         {
3390             ULONG size = dwParam2;
3391             return get_device_interface(DRV_QUERYDEVICEINTERFACE, FALSE, HandleToULong(hWaveIn),
3392                     (WCHAR*)dwParam1, &size);
3393         }
3394     case DRV_QUERYMAPPABLE:
3395         return MMSYSERR_NOERROR;
3396     case DRVM_MAPPER_PREFERRED_GET:
3397         if(dwParam1) {
3398             if(g_inmmdevices_count > 0)
3399                 /* Device 0 is always the default device */
3400                 *(DWORD *)dwParam1 = 0;
3401             else
3402                 *(DWORD *)dwParam1 = -1;
3403         }
3404
3405         if(dwParam2)
3406             /* Status flags */
3407             *(DWORD *)dwParam2 = 0;
3408
3409         return MMSYSERR_NOERROR;
3410     }
3411
3412     TRACE("Message not supported: %u\n", uMessage);
3413
3414     return MMSYSERR_NOTSUPPORTED;
3415 }
3416
3417 UINT WINAPI mixerGetNumDevs(void)
3418 {
3419     HRESULT hr;
3420
3421     TRACE("\n");
3422
3423     hr = WINMM_InitMMDevices();
3424     if(FAILED(hr))
3425         return 0;
3426
3427     return g_outmmdevices_count + g_inmmdevices_count;
3428 }
3429
3430 /**************************************************************************
3431  *                              mixerGetDevCapsA                [WINMM.@]
3432  */
3433 UINT WINAPI mixerGetDevCapsA(UINT_PTR uDeviceID, LPMIXERCAPSA lpCaps, UINT uSize)
3434 {
3435     MIXERCAPSW micW;
3436     UINT       ret;
3437
3438     TRACE("(%lu, %p, %u)\n", uDeviceID, lpCaps, uSize);
3439
3440     if(!lpCaps)
3441         return MMSYSERR_INVALPARAM;
3442
3443     ret = mixerGetDevCapsW(uDeviceID, &micW, sizeof(micW));
3444
3445     if (ret == MMSYSERR_NOERROR) {
3446         MIXERCAPSA micA;
3447         micA.wMid           = micW.wMid;
3448         micA.wPid           = micW.wPid;
3449         micA.vDriverVersion = micW.vDriverVersion;
3450         WideCharToMultiByte( CP_ACP, 0, micW.szPname, -1, micA.szPname,
3451                              sizeof(micA.szPname), NULL, NULL );
3452         micA.fdwSupport     = micW.fdwSupport;
3453         micA.cDestinations  = micW.cDestinations;
3454         memcpy(lpCaps, &micA, min(uSize, sizeof(micA)));
3455     }
3456     return ret;
3457 }
3458
3459 /**************************************************************************
3460  *                              mixerGetDevCapsW                [WINMM.@]
3461  */
3462 UINT WINAPI mixerGetDevCapsW(UINT_PTR uDeviceID, LPMIXERCAPSW lpCaps, UINT uSize)
3463 {
3464     WINMM_MMDevice *mmdevice;
3465     MIXERCAPSW caps;
3466     HRESULT hr;
3467
3468     TRACE("(%lu, %p, %u)\n", uDeviceID, lpCaps, uSize);
3469
3470     hr = WINMM_InitMMDevices();
3471     if(FAILED(hr))
3472         return MMSYSERR_NODRIVER;
3473
3474     if(!lpCaps)
3475         return MMSYSERR_INVALPARAM;
3476
3477     if(!uSize)
3478         return MMSYSERR_NOERROR;
3479
3480     if(uDeviceID >= g_outmmdevices_count + g_inmmdevices_count)
3481         return MMSYSERR_BADDEVICEID;
3482
3483     if(uDeviceID < g_outmmdevices_count){
3484         mmdevice = &g_out_mmdevices[uDeviceID];
3485         memcpy(caps.szPname, mmdevice->out_caps.szPname, sizeof(caps.szPname));
3486     }else{
3487         mmdevice = &g_in_mmdevices[uDeviceID - g_outmmdevices_count];
3488         memcpy(caps.szPname, mmdevice->in_caps.szPname, sizeof(caps.szPname));
3489     }
3490
3491     caps.wMid = 0xFF;
3492     caps.wPid = 0xFF;
3493     caps.vDriverVersion = 0x00010001;
3494     caps.fdwSupport = 0;
3495     caps.cDestinations = 1;
3496
3497     memcpy(lpCaps, &caps, uSize);
3498
3499     return MMSYSERR_NOERROR;
3500 }
3501
3502 /**************************************************************************
3503  *                              mixerOpen                       [WINMM.@]
3504  */
3505 UINT WINAPI mixerOpen(LPHMIXER lphMix, UINT uDeviceID, DWORD_PTR dwCallback,
3506                       DWORD_PTR dwInstance, DWORD fdwOpen)
3507 {
3508     WINMM_MMDevice *mmdevice;
3509     MMRESULT mr;
3510     HRESULT hr;
3511
3512     TRACE("(%p, %d, %lx, %lx, %x)\n", lphMix, uDeviceID, dwCallback,
3513             dwInstance, fdwOpen);
3514
3515     hr = WINMM_InitMMDevices();
3516     if(FAILED(hr))
3517         return MMSYSERR_NODRIVER;
3518
3519     if(!lphMix)
3520         return MMSYSERR_INVALPARAM;
3521
3522     mr = WINMM_CheckCallback(dwCallback, fdwOpen, TRUE);
3523     if(mr != MMSYSERR_NOERROR)
3524         return mr;
3525
3526     if(uDeviceID >= g_outmmdevices_count + g_inmmdevices_count)
3527         return MMSYSERR_BADDEVICEID;
3528
3529     if(uDeviceID < g_outmmdevices_count){
3530         mmdevice = &g_out_mmdevices[uDeviceID];
3531         *lphMix = (HMIXER)WINMM_MakeHWAVE(uDeviceID, TRUE,
3532                 mmdevice->mixer_count);
3533     }else{
3534         mmdevice = &g_in_mmdevices[uDeviceID - g_outmmdevices_count];
3535         *lphMix = (HMIXER)WINMM_MakeHWAVE(uDeviceID - g_outmmdevices_count,
3536                 FALSE, mmdevice->mixer_count);
3537     }
3538
3539     ++mmdevice->mixer_count;
3540
3541     return MMSYSERR_NOERROR;
3542 }
3543
3544 /**************************************************************************
3545  *                              mixerClose                      [WINMM.@]
3546  */
3547 UINT WINAPI mixerClose(HMIXER hMix)
3548 {
3549     TRACE("(%p)\n", hMix);
3550
3551     return MMSYSERR_NOERROR;
3552 }
3553
3554 /**************************************************************************
3555  *                              mixerGetID                      [WINMM.@]
3556  */
3557 UINT WINAPI mixerGetID(HMIXEROBJ hmix, LPUINT lpid, DWORD fdwID)
3558 {
3559     WINMM_MMDevice *mmdevice;
3560     HRESULT hr;
3561
3562     TRACE("(%p, %p, %x)\n", hmix, lpid, fdwID);
3563
3564     hr = WINMM_InitMMDevices();
3565     if(FAILED(hr))
3566         return MMSYSERR_NODRIVER;
3567
3568     if(!lpid)
3569         return MMSYSERR_INVALPARAM;
3570
3571     mmdevice = WINMM_GetMixerMMDevice(hmix, fdwID, lpid);
3572     if(!mmdevice)
3573         return MMSYSERR_INVALHANDLE;
3574
3575     if(mmdevice->in_caps.szPname[0] != '\0')
3576         *lpid += g_outmmdevices_count;
3577
3578     return MMSYSERR_NOERROR;
3579 }
3580
3581 /**************************************************************************
3582  *                              mixerGetControlDetailsW         [WINMM.@]
3583  */
3584 UINT WINAPI mixerGetControlDetailsW(HMIXEROBJ hmix, LPMIXERCONTROLDETAILS lpmcdW,
3585                                     DWORD fdwDetails)
3586 {
3587     WINMM_ControlDetails details;
3588     HRESULT hr;
3589
3590     TRACE("(%p, %p, %x)\n", hmix, lpmcdW, fdwDetails);
3591
3592     hr = WINMM_InitMMDevices();
3593     if(FAILED(hr))
3594         return MMSYSERR_NODRIVER;
3595
3596     if(!lpmcdW)
3597         return MMSYSERR_INVALPARAM;
3598
3599     TRACE("dwControlID: %u\n", lpmcdW->dwControlID);
3600
3601     details.hmix = hmix;
3602     details.details = lpmcdW;
3603     details.flags = fdwDetails;
3604
3605     return SendMessageW(g_devices_hwnd, MXDM_GETCONTROLDETAILS,
3606             (DWORD_PTR)&details, 0);
3607 }
3608
3609 /**************************************************************************
3610  *                              mixerGetControlDetailsA [WINMM.@]
3611  */
3612 UINT WINAPI mixerGetControlDetailsA(HMIXEROBJ hmix, LPMIXERCONTROLDETAILS lpmcdA,
3613                                     DWORD fdwDetails)
3614 {
3615     UINT ret = MMSYSERR_NOTSUPPORTED;
3616
3617     TRACE("(%p, %p, %08x)\n", hmix, lpmcdA, fdwDetails);
3618
3619     if (lpmcdA == NULL || lpmcdA->cbStruct != sizeof(*lpmcdA))
3620         return MMSYSERR_INVALPARAM;
3621
3622     switch (fdwDetails & MIXER_GETCONTROLDETAILSF_QUERYMASK) {
3623     case MIXER_GETCONTROLDETAILSF_VALUE:
3624         /* can safely use A structure as it is, no string inside */
3625         ret = mixerGetControlDetailsW(hmix, lpmcdA, fdwDetails);
3626         break;
3627     case MIXER_GETCONTROLDETAILSF_LISTTEXT:
3628         {
3629             MIXERCONTROLDETAILS_LISTTEXTA *pDetailsA = lpmcdA->paDetails;
3630             MIXERCONTROLDETAILS_LISTTEXTW *pDetailsW;
3631             int size = max(1, lpmcdA->cChannels) * sizeof(MIXERCONTROLDETAILS_LISTTEXTW);
3632             unsigned int i;
3633
3634             if (lpmcdA->u.cMultipleItems != 0) {
3635                 size *= lpmcdA->u.cMultipleItems;
3636             }
3637             pDetailsW = HeapAlloc(GetProcessHeap(), 0, size);
3638             lpmcdA->paDetails = pDetailsW;
3639             lpmcdA->cbDetails = sizeof(MIXERCONTROLDETAILS_LISTTEXTW);
3640             /* set up lpmcd->paDetails */
3641             ret = mixerGetControlDetailsW(hmix, lpmcdA, fdwDetails);
3642             /* copy from lpmcd->paDetails back to paDetailsW; */
3643             if (ret == MMSYSERR_NOERROR) {
3644                 for (i = 0; i < lpmcdA->u.cMultipleItems * lpmcdA->cChannels; i++) {
3645                     pDetailsA->dwParam1 = pDetailsW->dwParam1;
3646                     pDetailsA->dwParam2 = pDetailsW->dwParam2;
3647                     WideCharToMultiByte( CP_ACP, 0, pDetailsW->szName, -1,
3648                                          pDetailsA->szName,
3649                                          sizeof(pDetailsA->szName), NULL, NULL );
3650                     pDetailsA++;
3651                     pDetailsW++;
3652                 }
3653                 pDetailsA -= lpmcdA->u.cMultipleItems * lpmcdA->cChannels;
3654                 pDetailsW -= lpmcdA->u.cMultipleItems * lpmcdA->cChannels;
3655             }
3656             HeapFree(GetProcessHeap(), 0, pDetailsW);
3657             lpmcdA->paDetails = pDetailsA;
3658             lpmcdA->cbDetails = sizeof(MIXERCONTROLDETAILS_LISTTEXTA);
3659         }
3660         break;
3661     default:
3662         WARN("Unsupported fdwDetails=0x%08x\n", fdwDetails);
3663     }
3664
3665     return ret;
3666 }
3667
3668 /**************************************************************************
3669  *                              mixerGetLineControlsA   [WINMM.@]
3670  */
3671 UINT WINAPI mixerGetLineControlsA(HMIXEROBJ hmix, LPMIXERLINECONTROLSA lpmlcA,
3672                                   DWORD fdwControls)
3673 {
3674     MIXERLINECONTROLSW  mlcW;
3675     DWORD               ret;
3676     unsigned int        i;
3677
3678     TRACE("(%p, %p, %x)\n", hmix, lpmlcA, fdwControls);
3679
3680     if (lpmlcA == NULL || lpmlcA->cbStruct != sizeof(*lpmlcA) ||
3681         lpmlcA->cbmxctrl != sizeof(MIXERCONTROLA))
3682         return MMSYSERR_INVALPARAM;
3683
3684     mlcW.cbStruct = sizeof(mlcW);
3685     mlcW.dwLineID = lpmlcA->dwLineID;
3686     mlcW.u.dwControlID = lpmlcA->u.dwControlID;
3687     mlcW.u.dwControlType = lpmlcA->u.dwControlType;
3688
3689     /* Debugging on Windows shows for MIXER_GETLINECONTROLSF_ONEBYTYPE only,
3690        the control count is assumed to be 1 - This is relied upon by a game,
3691        "Dynomite Deluze"                                                    */
3692     if (MIXER_GETLINECONTROLSF_ONEBYTYPE == (fdwControls & MIXER_GETLINECONTROLSF_QUERYMASK)) {
3693         mlcW.cControls = 1;
3694     } else {
3695         mlcW.cControls = lpmlcA->cControls;
3696     }
3697     mlcW.cbmxctrl = sizeof(MIXERCONTROLW);
3698     mlcW.pamxctrl = HeapAlloc(GetProcessHeap(), 0,
3699                               mlcW.cControls * mlcW.cbmxctrl);
3700
3701     ret = mixerGetLineControlsW(hmix, &mlcW, fdwControls);
3702
3703     if (ret == MMSYSERR_NOERROR) {
3704         lpmlcA->dwLineID = mlcW.dwLineID;
3705         lpmlcA->u.dwControlID = mlcW.u.dwControlID;
3706         lpmlcA->u.dwControlType = mlcW.u.dwControlType;
3707
3708         for (i = 0; i < mlcW.cControls; i++) {
3709             lpmlcA->pamxctrl[i].cbStruct = sizeof(MIXERCONTROLA);
3710             lpmlcA->pamxctrl[i].dwControlID = mlcW.pamxctrl[i].dwControlID;
3711             lpmlcA->pamxctrl[i].dwControlType = mlcW.pamxctrl[i].dwControlType;
3712             lpmlcA->pamxctrl[i].fdwControl = mlcW.pamxctrl[i].fdwControl;
3713             lpmlcA->pamxctrl[i].cMultipleItems = mlcW.pamxctrl[i].cMultipleItems;
3714             WideCharToMultiByte( CP_ACP, 0, mlcW.pamxctrl[i].szShortName, -1,
3715                                  lpmlcA->pamxctrl[i].szShortName,
3716                                  sizeof(lpmlcA->pamxctrl[i].szShortName), NULL, NULL );
3717             WideCharToMultiByte( CP_ACP, 0, mlcW.pamxctrl[i].szName, -1,
3718                                  lpmlcA->pamxctrl[i].szName,
3719                                  sizeof(lpmlcA->pamxctrl[i].szName), NULL, NULL );
3720             /* sizeof(lpmlcA->pamxctrl[i].Bounds) ==
3721              * sizeof(mlcW.pamxctrl[i].Bounds) */
3722             memcpy(&lpmlcA->pamxctrl[i].Bounds, &mlcW.pamxctrl[i].Bounds,
3723                    sizeof(mlcW.pamxctrl[i].Bounds));
3724             /* sizeof(lpmlcA->pamxctrl[i].Metrics) ==
3725              * sizeof(mlcW.pamxctrl[i].Metrics) */
3726             memcpy(&lpmlcA->pamxctrl[i].Metrics, &mlcW.pamxctrl[i].Metrics,
3727                    sizeof(mlcW.pamxctrl[i].Metrics));
3728         }
3729     }
3730
3731     HeapFree(GetProcessHeap(), 0, mlcW.pamxctrl);
3732
3733     return ret;
3734 }
3735
3736 static UINT WINMM_GetVolumeLineControl(WINMM_MMDevice *mmdevice, DWORD line,
3737         MIXERCONTROLW *ctl, DWORD flags)
3738 {
3739     ctl->dwControlID = (line == 0xFFFF0000) ? 0 : 2;
3740     ctl->dwControlType = MIXERCONTROL_CONTROLTYPE_VOLUME;
3741     ctl->fdwControl = MIXERCONTROL_CONTROLF_UNIFORM;
3742     ctl->cMultipleItems = 0;
3743     lstrcpyW(ctl->szShortName, volumeW);
3744     lstrcpyW(ctl->szName, volumeW);
3745     ctl->Bounds.s1.dwMinimum = 0;
3746     ctl->Bounds.s1.dwMaximum = 0xFFFF;
3747     ctl->Metrics.cSteps = 192;
3748
3749     return MMSYSERR_NOERROR;
3750 }
3751
3752 static UINT WINMM_GetMuteLineControl(WINMM_MMDevice *mmdevice, DWORD line,
3753         MIXERCONTROLW *ctl, DWORD flags)
3754 {
3755     ctl->dwControlID = (line == 0xFFFF0000) ? 1 : 3;
3756     ctl->dwControlType = MIXERCONTROL_CONTROLTYPE_MUTE;
3757     ctl->fdwControl = MIXERCONTROL_CONTROLF_UNIFORM;
3758     ctl->cMultipleItems = 0;
3759     lstrcpyW(ctl->szShortName, muteW);
3760     lstrcpyW(ctl->szName, muteW);
3761     ctl->Bounds.s1.dwMinimum = 0;
3762     ctl->Bounds.s1.dwMaximum = 1;
3763     ctl->Metrics.cSteps = 0;
3764
3765     return MMSYSERR_NOERROR;
3766 }
3767
3768 /**************************************************************************
3769  *                              mixerGetLineControlsW           [WINMM.@]
3770  */
3771 UINT WINAPI mixerGetLineControlsW(HMIXEROBJ hmix, LPMIXERLINECONTROLSW lpmlcW,
3772                                   DWORD fdwControls)
3773 {
3774     WINMM_MMDevice *mmdevice;
3775     HRESULT hr;
3776
3777     TRACE("(%p, %p, %08x)\n", hmix, lpmlcW, fdwControls);
3778
3779     hr = WINMM_InitMMDevices();
3780     if(FAILED(hr))
3781         return MMSYSERR_NODRIVER;
3782
3783     if(fdwControls & ~(MIXER_GETLINECONTROLSF_ALL |
3784                 MIXER_GETLINECONTROLSF_ONEBYID |
3785                 MIXER_GETLINECONTROLSF_ONEBYTYPE |
3786                 MIXER_OBJECTF_HMIXER |
3787                 MIXER_OBJECTF_MIXER)){
3788         WARN("Unknown GetLineControls flag: %x\n", fdwControls);
3789         return MMSYSERR_INVALFLAG;
3790     }
3791
3792     if(!lpmlcW || lpmlcW->cbStruct < sizeof(*lpmlcW) || !lpmlcW->pamxctrl)
3793         return MMSYSERR_INVALPARAM;
3794
3795     TRACE("dwLineID: %u\n", lpmlcW->dwLineID);
3796     TRACE("dwControl: %x\n", lpmlcW->u.dwControlID);
3797     TRACE("cControls: %u\n", lpmlcW->cControls);
3798
3799     mmdevice = WINMM_GetMixerMMDevice(hmix, fdwControls, NULL);
3800     if(!mmdevice)
3801         return MMSYSERR_INVALHANDLE;
3802
3803     switch(fdwControls & MIXER_GETLINECONTROLSF_QUERYMASK){
3804     case MIXER_GETLINECONTROLSF_ALL:
3805         if(lpmlcW->cControls != 2)
3806             return MMSYSERR_INVALPARAM;
3807         if(lpmlcW->cbmxctrl < sizeof(MIXERCONTROLW))
3808             return MMSYSERR_INVALPARAM;
3809         if(lpmlcW->dwLineID != 0 && lpmlcW->dwLineID != 0xFFFF0000)
3810             return MIXERR_INVALLINE;
3811         WINMM_GetVolumeLineControl(mmdevice, lpmlcW->dwLineID,
3812                 &lpmlcW->pamxctrl[0], fdwControls);
3813         WINMM_GetMuteLineControl(mmdevice, lpmlcW->dwLineID,
3814                 &lpmlcW->pamxctrl[1], fdwControls);
3815         return MMSYSERR_NOERROR;
3816     case MIXER_GETLINECONTROLSF_ONEBYID:
3817         if(lpmlcW->cControls != 1)
3818             return MMSYSERR_INVALPARAM;
3819         if(lpmlcW->cbmxctrl < sizeof(MIXERCONTROLW))
3820             return MMSYSERR_INVALPARAM;
3821         if(lpmlcW->dwLineID != 0 && lpmlcW->dwLineID != 0xFFFF0000)
3822             return MIXERR_INVALLINE;
3823         if(lpmlcW->u.dwControlID == 0)
3824             return WINMM_GetVolumeLineControl(mmdevice, lpmlcW->dwLineID,
3825                     lpmlcW->pamxctrl, fdwControls);
3826         if(lpmlcW->u.dwControlID == 1)
3827             return WINMM_GetMuteLineControl(mmdevice, lpmlcW->dwLineID,
3828                     lpmlcW->pamxctrl, fdwControls);
3829         return MMSYSERR_NOTSUPPORTED;
3830     case MIXER_GETLINECONTROLSF_ONEBYTYPE:
3831         if(lpmlcW->cControls != 1)
3832             return MMSYSERR_INVALPARAM;
3833         if(lpmlcW->cbmxctrl < sizeof(MIXERCONTROLW))
3834             return MMSYSERR_INVALPARAM;
3835         if(lpmlcW->dwLineID != 0 && lpmlcW->dwLineID != 0xFFFF0000)
3836             return MIXERR_INVALLINE;
3837         if(lpmlcW->u.dwControlType == MIXERCONTROL_CONTROLTYPE_VOLUME)
3838             return WINMM_GetVolumeLineControl(mmdevice, lpmlcW->dwLineID,
3839                     lpmlcW->pamxctrl, fdwControls);
3840         if(lpmlcW->u.dwControlType == MIXERCONTROL_CONTROLTYPE_MUTE)
3841             return WINMM_GetMuteLineControl(mmdevice, lpmlcW->dwLineID,
3842                     lpmlcW->pamxctrl, fdwControls);
3843         return MMSYSERR_NOTSUPPORTED;
3844     }
3845
3846     return MMSYSERR_NOTSUPPORTED;
3847 }
3848
3849 static UINT WINMM_GetSourceLineInfo(WINMM_MMDevice *mmdevice, UINT mmdev_index,
3850         MIXERLINEW *info, DWORD flags)
3851 {
3852     BOOL is_out = TRUE;
3853     if(mmdevice->in_caps.szPname[0] != '\0')
3854         is_out = FALSE;
3855
3856     if(info->dwSource != 0)
3857         return MIXERR_INVALLINE;
3858
3859     info->dwDestination = 0;
3860     info->dwLineID = 0;
3861     info->fdwLine = MIXERLINE_LINEF_ACTIVE | MIXERLINE_LINEF_SOURCE;
3862     info->cConnections = 0;
3863     info->cControls = 2;
3864     /* volume & mute always affect all channels, so claim 1 channel */
3865     info->cChannels = 1;
3866     info->Target.dwDeviceID = mmdev_index;
3867     info->Target.wMid = ~0;
3868     info->Target.wPid = ~0;
3869     info->Target.vDriverVersion = 0;
3870
3871     lstrcpyW(info->szShortName, volumeW);
3872     lstrcpyW(info->szName, mastervolumeW);
3873
3874     if(is_out){
3875         info->dwComponentType = MIXERLINE_COMPONENTTYPE_SRC_WAVEOUT;
3876         info->Target.dwType = MIXERLINE_TARGETTYPE_WAVEOUT;
3877         memcpy(info->Target.szPname, mmdevice->out_caps.szPname,
3878                 sizeof(info->Target.szPname));
3879     }else{
3880         info->dwComponentType = MIXERLINE_COMPONENTTYPE_SRC_MICROPHONE;
3881         info->Target.dwType = MIXERLINE_TARGETTYPE_UNDEFINED;
3882         info->Target.szPname[0] = '\0';
3883     }
3884
3885     return MMSYSERR_NOERROR;
3886 }
3887
3888 static UINT WINMM_GetDestinationLineInfo(WINMM_MMDevice *mmdevice,
3889         UINT mmdev_index, MIXERLINEW *info, DWORD flags)
3890 {
3891     BOOL is_out = TRUE;
3892     if(mmdevice->in_caps.szPname[0] != '\0')
3893         is_out = FALSE;
3894
3895     if(info->dwDestination != 0)
3896         return MIXERR_INVALLINE;
3897
3898     info->dwSource = 0xFFFFFFFF;
3899     info->dwLineID = 0xFFFF0000;
3900     info->fdwLine = MIXERLINE_LINEF_ACTIVE;
3901     info->cConnections = 1;
3902     info->cControls = 2;
3903
3904     lstrcpyW(info->szShortName, volumeW);
3905     lstrcpyW(info->szName, mastervolumeW);
3906
3907     info->Target.dwDeviceID = mmdev_index;
3908     info->Target.wMid = ~0;
3909     info->Target.wPid = ~0;
3910     info->Target.vDriverVersion = 0;
3911
3912     if(is_out){
3913         info->dwComponentType = MIXERLINE_COMPONENTTYPE_DST_SPEAKERS;
3914         info->cChannels = mmdevice->out_caps.wChannels;
3915         info->Target.dwType = MIXERLINE_TARGETTYPE_UNDEFINED;
3916         info->Target.szPname[0] = '\0';
3917     }else{
3918         info->dwComponentType = MIXERLINE_COMPONENTTYPE_DST_WAVEIN;
3919         info->cChannels = mmdevice->in_caps.wChannels;
3920         info->Target.dwType = MIXERLINE_TARGETTYPE_WAVEIN;
3921         memcpy(info->Target.szPname, mmdevice->in_caps.szPname,
3922                 sizeof(info->Target.szPname));
3923     }
3924
3925     return MMSYSERR_NOERROR;
3926 }
3927
3928 static UINT WINMM_GetComponentTypeLineInfo(WINMM_MMDevice *mmdevice,
3929         UINT mmdev_index, MIXERLINEW *info, DWORD flags)
3930 {
3931     BOOL is_out = TRUE;
3932     if(mmdevice->in_caps.szPname[0] != '\0')
3933         is_out = FALSE;
3934
3935     if(info->dwComponentType == MIXERLINE_COMPONENTTYPE_DST_WAVEIN){
3936         if(is_out)
3937             return MIXERR_INVALLINE;
3938         info->dwDestination = 0;
3939         return WINMM_GetDestinationLineInfo(mmdevice, mmdev_index, info, flags);
3940     }
3941
3942     if(info->dwComponentType == MIXERLINE_COMPONENTTYPE_DST_SPEAKERS){
3943         if(!is_out)
3944             return MIXERR_INVALLINE;
3945         info->dwDestination = 0;
3946         return WINMM_GetDestinationLineInfo(mmdevice, mmdev_index, info, flags);
3947     }
3948
3949     if(info->dwComponentType == MIXERLINE_COMPONENTTYPE_SRC_MICROPHONE){
3950         if(is_out)
3951             return MIXERR_INVALLINE;
3952         info->dwSource = 0;
3953         return WINMM_GetSourceLineInfo(mmdevice, mmdev_index, info, flags);
3954     }
3955
3956     if(info->dwComponentType == MIXERLINE_COMPONENTTYPE_SRC_WAVEOUT){
3957         if(!is_out)
3958             return MIXERR_INVALLINE;
3959         info->dwSource = 0;
3960         return WINMM_GetSourceLineInfo(mmdevice, mmdev_index, info, flags);
3961     }
3962
3963     TRACE("Returning INVALLINE on this component type: %u\n",
3964             info->dwComponentType);
3965
3966     return MIXERR_INVALLINE;
3967 }
3968
3969 static UINT WINMM_GetLineIDLineInfo(WINMM_MMDevice *mmdevice,
3970         UINT mmdev_index, MIXERLINEW *info, DWORD flags)
3971 {
3972     if(info->dwLineID == 0xFFFF0000){
3973         info->dwDestination = 0;
3974         return WINMM_GetDestinationLineInfo(mmdevice, mmdev_index, info, flags);
3975     }
3976
3977     if(info->dwLineID == 0){
3978         info->dwSource = 0;
3979         return WINMM_GetSourceLineInfo(mmdevice, mmdev_index, info, flags);
3980     }
3981
3982     TRACE("Returning INVALLINE on this dwLineID: %u\n", info->dwLineID);
3983     return MIXERR_INVALLINE;
3984 }
3985
3986 /**************************************************************************
3987  *                              mixerGetLineInfoW               [WINMM.@]
3988  */
3989 UINT WINAPI mixerGetLineInfoW(HMIXEROBJ hmix, LPMIXERLINEW lpmliW, DWORD fdwInfo)
3990 {
3991     UINT mmdev_index;
3992     WINMM_MMDevice *mmdevice;
3993     HRESULT hr;
3994
3995     TRACE("(%p, %p, %x)\n", hmix, lpmliW, fdwInfo);
3996
3997     hr = WINMM_InitMMDevices();
3998     if(FAILED(hr))
3999         return MMSYSERR_NODRIVER;
4000
4001     if(!lpmliW || lpmliW->cbStruct < sizeof(MIXERLINEW))
4002         return MMSYSERR_INVALPARAM;
4003
4004     TRACE("dwDestination: %u\n", lpmliW->dwDestination);
4005     TRACE("dwSource: %u\n", lpmliW->dwSource);
4006     TRACE("dwLineID: %u\n", lpmliW->dwLineID);
4007     TRACE("fdwLine: 0x%x\n", lpmliW->fdwLine);
4008     TRACE("dwComponentType: 0x%x\n", lpmliW->dwComponentType);
4009
4010     if(fdwInfo & ~(MIXER_GETLINEINFOF_COMPONENTTYPE |
4011                 MIXER_GETLINEINFOF_DESTINATION |
4012                 MIXER_GETLINEINFOF_LINEID |
4013                 MIXER_GETLINEINFOF_SOURCE |
4014                 MIXER_GETLINEINFOF_TARGETTYPE |
4015                 MIXER_OBJECTF_HMIXER |
4016                 MIXER_OBJECTF_MIXER)){
4017         WARN("Unknown GetLineInfo flag: %x\n", fdwInfo);
4018         return MMSYSERR_INVALFLAG;
4019     }
4020
4021     mmdevice = WINMM_GetMixerMMDevice(hmix, fdwInfo, &mmdev_index);
4022     if(!mmdevice)
4023         return MMSYSERR_INVALHANDLE;
4024
4025     switch(fdwInfo & MIXER_GETLINEINFOF_QUERYMASK){
4026     case MIXER_GETLINEINFOF_DESTINATION:
4027         return WINMM_GetDestinationLineInfo(mmdevice, mmdev_index, lpmliW,
4028                 fdwInfo);
4029     case MIXER_GETLINEINFOF_SOURCE:
4030         return WINMM_GetSourceLineInfo(mmdevice, mmdev_index, lpmliW, fdwInfo);
4031     case MIXER_GETLINEINFOF_COMPONENTTYPE:
4032         return WINMM_GetComponentTypeLineInfo(mmdevice, mmdev_index, lpmliW,
4033                 fdwInfo);
4034     case MIXER_GETLINEINFOF_LINEID:
4035         return WINMM_GetLineIDLineInfo(mmdevice, mmdev_index, lpmliW, fdwInfo);
4036     case MIXER_GETLINEINFOF_TARGETTYPE:
4037         FIXME("TARGETTYPE flag not implemented!\n");
4038         return MIXERR_INVALLINE;
4039     }
4040
4041     TRACE("Returning INVALFLAG on these flags: %x\n", fdwInfo & MIXER_GETLINEINFOF_QUERYMASK);
4042     return MMSYSERR_INVALFLAG;
4043 }
4044
4045 /**************************************************************************
4046  *                              mixerGetLineInfoA               [WINMM.@]
4047  */
4048 UINT WINAPI mixerGetLineInfoA(HMIXEROBJ hmix, LPMIXERLINEA lpmliA,
4049                               DWORD fdwInfo)
4050 {
4051     MIXERLINEW          mliW;
4052     UINT                ret;
4053
4054     TRACE("(%p, %p, %x)\n", hmix, lpmliA, fdwInfo);
4055
4056     if (lpmliA == NULL || lpmliA->cbStruct != sizeof(*lpmliA))
4057         return MMSYSERR_INVALPARAM;
4058
4059     mliW.cbStruct = sizeof(mliW);
4060     switch (fdwInfo & MIXER_GETLINEINFOF_QUERYMASK) {
4061     case MIXER_GETLINEINFOF_COMPONENTTYPE:
4062         mliW.dwComponentType = lpmliA->dwComponentType;
4063         break;
4064     case MIXER_GETLINEINFOF_DESTINATION:
4065         mliW.dwDestination = lpmliA->dwDestination;
4066         break;
4067     case MIXER_GETLINEINFOF_LINEID:
4068         mliW.dwLineID = lpmliA->dwLineID;
4069         break;
4070     case MIXER_GETLINEINFOF_SOURCE:
4071         mliW.dwDestination = lpmliA->dwDestination;
4072         mliW.dwSource = lpmliA->dwSource;
4073         break;
4074     case MIXER_GETLINEINFOF_TARGETTYPE:
4075         mliW.Target.dwType = lpmliA->Target.dwType;
4076         mliW.Target.wMid = lpmliA->Target.wMid;
4077         mliW.Target.wPid = lpmliA->Target.wPid;
4078         mliW.Target.vDriverVersion = lpmliA->Target.vDriverVersion;
4079         MultiByteToWideChar( CP_ACP, 0, lpmliA->Target.szPname, -1, mliW.Target.szPname, sizeof(mliW.Target.szPname)/sizeof(WCHAR));
4080         break;
4081     default:
4082         WARN("Unsupported fdwControls=0x%08x\n", fdwInfo);
4083         return MMSYSERR_INVALFLAG;
4084     }
4085
4086     ret = mixerGetLineInfoW(hmix, &mliW, fdwInfo);
4087
4088     if(ret == MMSYSERR_NOERROR)
4089     {
4090         lpmliA->dwDestination = mliW.dwDestination;
4091         lpmliA->dwSource = mliW.dwSource;
4092         lpmliA->dwLineID = mliW.dwLineID;
4093         lpmliA->fdwLine = mliW.fdwLine;
4094         lpmliA->dwUser = mliW.dwUser;
4095         lpmliA->dwComponentType = mliW.dwComponentType;
4096         lpmliA->cChannels = mliW.cChannels;
4097         lpmliA->cConnections = mliW.cConnections;
4098         lpmliA->cControls = mliW.cControls;
4099         WideCharToMultiByte( CP_ACP, 0, mliW.szShortName, -1, lpmliA->szShortName,
4100                              sizeof(lpmliA->szShortName), NULL, NULL);
4101         WideCharToMultiByte( CP_ACP, 0, mliW.szName, -1, lpmliA->szName,
4102                              sizeof(lpmliA->szName), NULL, NULL );
4103         lpmliA->Target.dwType = mliW.Target.dwType;
4104         lpmliA->Target.dwDeviceID = mliW.Target.dwDeviceID;
4105         lpmliA->Target.wMid = mliW.Target.wMid;
4106         lpmliA->Target.wPid = mliW.Target.wPid;
4107         lpmliA->Target.vDriverVersion = mliW.Target.vDriverVersion;
4108         WideCharToMultiByte( CP_ACP, 0, mliW.Target.szPname, -1, lpmliA->Target.szPname,
4109                              sizeof(lpmliA->Target.szPname), NULL, NULL );
4110     }
4111     return ret;
4112 }
4113
4114 /**************************************************************************
4115  *                              mixerSetControlDetails  [WINMM.@]
4116  */
4117 UINT WINAPI mixerSetControlDetails(HMIXEROBJ hmix, LPMIXERCONTROLDETAILS lpmcd,
4118                                    DWORD fdwDetails)
4119 {
4120     WINMM_ControlDetails details;
4121
4122     TRACE("(%p, %p, %x)\n", hmix, lpmcd, fdwDetails);
4123
4124     if(!WINMM_StartDevicesThread())
4125         return MMSYSERR_NODRIVER;
4126
4127     if((fdwDetails & MIXER_SETCONTROLDETAILSF_QUERYMASK) ==
4128             MIXER_SETCONTROLDETAILSF_CUSTOM)
4129         return MMSYSERR_NOTSUPPORTED;
4130
4131     if(!lpmcd)
4132         return MMSYSERR_INVALPARAM;
4133
4134     TRACE("dwControlID: %u\n", lpmcd->dwControlID);
4135
4136     details.hmix = hmix;
4137     details.details = lpmcd;
4138     details.flags = fdwDetails;
4139
4140     return SendMessageW(g_devices_hwnd, MXDM_SETCONTROLDETAILS,
4141             (DWORD_PTR)&details, 0);
4142 }
4143
4144 /**************************************************************************
4145  *                              mixerMessage            [WINMM.@]
4146  */
4147 DWORD WINAPI mixerMessage(HMIXER hmix, UINT uMsg, DWORD_PTR dwParam1, DWORD_PTR dwParam2)
4148 {
4149     TRACE("(%p, %d, %lx, %lx)\n", hmix, uMsg, dwParam1, dwParam2);
4150
4151     return MMSYSERR_NOTSUPPORTED;
4152 }