Implement A->W call for GetNamedSecurityInfo.
[wine] / dlls / winmm / winearts / audio.c
1 /* -*- tab-width: 8; c-basic-offset: 4 -*- */
2 /*
3  * Wine Driver for aRts Sound Server
4  *   http://www.arts-project.org
5  *
6  * Copyright 1994 Martin Ayotte
7  *           1999 Eric Pouech (async playing in waveOut/waveIn)
8  *           2000 Eric Pouech (loops in waveOut)
9  *           2002 Chris Morgan (aRts version of this file)
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with this library; if not, write to the Free Software
23  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
24  */
25 /* NOTE:
26  *    with arts we cannot stop the audio that is already in
27  *    the servers buffer, so to reduce delays during starting
28  *    and stoppping of audio streams adjust the
29  *    audio buffer size in the kde control center or in the
30  *    artsd startup script
31  *
32  * FIXME:
33  *      pause in waveOut does not work correctly in loop mode
34  *
35  *      does something need to be done in for WaveIn DirectSound?
36  */
37
38 /*#define EMULATE_SB16*/
39
40 #include "config.h"
41 #include "wine/port.h"
42
43 #include <math.h>
44 #include <stdlib.h>
45 #include <stdarg.h>
46 #include <stdio.h>
47 #include <string.h>
48 #ifdef HAVE_UNISTD_H
49 # include <unistd.h>
50 #endif
51 #include <fcntl.h>
52 #include "windef.h"
53 #include "winbase.h"
54 #include "wingdi.h"
55 #include "winerror.h"
56 #include "wine/winuser16.h"
57 #include "mmddk.h"
58 #include "dsound.h"
59 #include "dsdriver.h"
60 #include "arts.h"
61 #include "wine/debug.h"
62
63 WINE_DEFAULT_DEBUG_CHANNEL(wave);
64
65 #ifdef HAVE_ARTS
66
67 #include <artsc.h>
68
69 /* The following four #defines allow you to fine-tune the packet
70  * settings in arts for better low-latency support. You must also
71  * adjust the latency in the KDE arts control panel. I recommend 4
72  * fragments, 1024 bytes.
73  *
74  * The following is from the ARTS documentation and explains what CCCC
75  * and SSSS mean:
76  * 
77  * @li ARTS_P_PACKET_SETTINGS (rw) This is a way to configure packet
78  * size & packet count at the same time.  The format is 0xCCCCSSSS,
79  * where 2^SSSS is the packet size, and CCCC is the packet count. Note
80  * that when writing this, you don't necessarily get the settings you
81  * requested.
82  */
83 #define WAVEOUT_PACKET_CCCC 0x000C
84 #define WAVEOUT_PACKET_SSSS 0x0008
85 #define WAVEIN_PACKET_CCCC  0x000C
86 #define WAVEIN_PACKET_SSSS  0x0008
87
88 #define BUFFER_REFILL_THRESHOLD 4
89
90 #define WAVEOUT_PACKET_SETTINGS ((WAVEOUT_PACKET_CCCC << 16) | (WAVEOUT_PACKET_SSSS))
91 #define WAVEIN_PACKET_SETTINGS  ((WAVEIN_PACKET_CCCC << 16) | (WAVEIN_PACKET_SSSS))
92
93 #define MAX_WAVEOUTDRV  (10)
94 #define MAX_WAVEINDRV   (10)
95
96 /* state diagram for waveOut writing:
97  *
98  * +---------+-------------+---------------+---------------------------------+
99  * |  state  |  function   |     event     |            new state            |
100  * +---------+-------------+---------------+---------------------------------+
101  * |         | open()      |               | STOPPED                         |
102  * | PAUSED  | write()     |               | PAUSED                          |
103  * | STOPPED | write()     | <thrd create> | PLAYING                         |
104  * | PLAYING | write()     | HEADER        | PLAYING                         |
105  * | (other) | write()     | <error>       |                                 |
106  * | (any)   | pause()     | PAUSING       | PAUSED                          |
107  * | PAUSED  | restart()   | RESTARTING    | PLAYING (if no thrd => STOPPED) |
108  * | (any)   | reset()     | RESETTING     | STOPPED                         |
109  * | (any)   | close()     | CLOSING       | CLOSED                          |
110  * +---------+-------------+---------------+---------------------------------+
111  */
112
113 /* states of the playing device */
114 #define WINE_WS_PLAYING         0
115 #define WINE_WS_PAUSED          1
116 #define WINE_WS_STOPPED         2
117 #define WINE_WS_CLOSED          3
118
119 /* events to be send to device */
120 enum win_wm_message {
121     WINE_WM_PAUSING = WM_USER + 1, WINE_WM_RESTARTING, WINE_WM_RESETTING, WINE_WM_HEADER,
122     WINE_WM_UPDATE, WINE_WM_BREAKLOOP, WINE_WM_CLOSING, WINE_WM_STARTING, WINE_WM_STOPPING
123 };
124
125 typedef struct {
126     enum win_wm_message         msg;    /* message identifier */
127     DWORD                       param;  /* parameter for this message */
128     HANDLE                      hEvent; /* if message is synchronous, handle of event for synchro */
129 } RING_MSG;
130
131 /* implement an in-process message ring for better performance
132  * (compared to passing thru the server)
133  * this ring will be used by the input (resp output) record (resp playback) routine
134  */
135 #define ARTS_RING_BUFFER_INCREMENT      64
136 typedef struct {
137     RING_MSG                    * messages;
138     int                         ring_buffer_size;
139     int                         msg_tosave;
140     int                         msg_toget;
141     HANDLE                      msg_event;
142     CRITICAL_SECTION            msg_crst;
143 } ARTS_MSG_RING;
144
145 typedef struct {
146     volatile int                state;                  /* one of the WINE_WS_ manifest constants */
147     WAVEOPENDESC                waveDesc;
148     WORD                        wFlags;
149     PCMWAVEFORMAT               format;
150     WAVEOUTCAPSA                caps;
151     char                        interface_name[32];
152
153     DWORD                       dwSleepTime;            /* Num of milliseconds to sleep between filling the dsp buffers */
154
155     /* arts information */
156     arts_stream_t               play_stream;            /* the stream structure we get from arts when opening a stream for playing */
157     DWORD                       dwBufferSize;           /* size of whole buffer in bytes */
158     int                         packetSettings;
159
160     char*                       sound_buffer;
161     long                        buffer_size;
162
163     DWORD                       volume_left;            /* volume control information */
164     DWORD                       volume_right;
165
166     LPWAVEHDR                   lpQueuePtr;             /* start of queued WAVEHDRs (waiting to be notified) */
167     LPWAVEHDR                   lpPlayPtr;              /* start of not yet fully played buffers */
168     DWORD                       dwPartialOffset;        /* Offset of not yet written bytes in lpPlayPtr */
169
170     LPWAVEHDR                   lpLoopPtr;              /* pointer of first buffer in loop, if any */
171     DWORD                       dwLoops;                /* private copy of loop counter */
172
173     DWORD                       dwPlayedTotal;          /* number of bytes actually played since opening */
174     DWORD                       dwWrittenTotal;         /* number of bytes written to the audio device since opening */
175
176     /* synchronization stuff */
177     HANDLE                      hStartUpEvent;
178     HANDLE                      hThread;
179     DWORD                       dwThreadID;
180     ARTS_MSG_RING               msgRing;
181 } WINE_WAVEOUT;
182
183 typedef struct {
184     volatile int                state;                  /* one of the WINE_WS_ manifest constants */
185     WAVEOPENDESC                waveDesc;
186     WORD                        wFlags;
187     PCMWAVEFORMAT               format;
188     WAVEINCAPSA                 caps;
189     char                        interface_name[32];
190
191     /* arts information */
192     arts_stream_t               record_stream;          /* the stream structure we get from arts when opening a stream for recording */
193     int                         packetSettings;
194
195     LPWAVEHDR                   lpQueuePtr;
196     DWORD                       dwRecordedTotal;
197
198     /* synchronization stuff */
199     HANDLE                      hStartUpEvent;
200     HANDLE                      hThread;
201     DWORD                       dwThreadID;
202     ARTS_MSG_RING               msgRing;
203 } WINE_WAVEIN;
204
205 static WINE_WAVEOUT     WOutDev   [MAX_WAVEOUTDRV];
206 static WINE_WAVEIN      WInDev    [MAX_WAVEINDRV];
207
208 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv);
209 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc);
210 static DWORD wodDsGuid(UINT wDevID, LPGUID pGuid);
211
212 /* These strings used only for tracing */
213 static const char *wodPlayerCmdString[] = {
214     "WINE_WM_PAUSING",
215     "WINE_WM_RESTARTING",
216     "WINE_WM_RESETTING",
217     "WINE_WM_HEADER",
218     "WINE_WM_UPDATE",
219     "WINE_WM_BREAKLOOP",
220     "WINE_WM_CLOSING",
221     "WINE_WM_STARTING",
222     "WINE_WM_STOPPING",
223 };
224
225 static DWORD bytes_to_mmtime(LPMMTIME lpTime, DWORD position,
226                              PCMWAVEFORMAT* format)
227 {
228     TRACE("wType=%04X wBitsPerSample=%u nSamplesPerSec=%lu nChannels=%u nAvgBytesPerSec=%lu\n",
229           lpTime->wType, format->wBitsPerSample, format->wf.nSamplesPerSec,
230           format->wf.nChannels, format->wf.nAvgBytesPerSec);
231     TRACE("Position in bytes=%lu\n", position);
232
233     switch (lpTime->wType) {
234     case TIME_SAMPLES:
235         lpTime->u.sample = position / (format->wBitsPerSample / 8 * format->wf.nChannels);
236         TRACE("TIME_SAMPLES=%lu\n", lpTime->u.sample);
237         break;
238     case TIME_MS:
239         lpTime->u.ms = 1000.0 * position / (format->wBitsPerSample / 8 * format->wf.nChannels * format->wf.nSamplesPerSec);
240         TRACE("TIME_MS=%lu\n", lpTime->u.ms);
241         break;
242     case TIME_SMPTE:
243         position = position / (format->wBitsPerSample / 8 * format->wf.nChannels);
244         lpTime->u.smpte.sec = position / format->wf.nSamplesPerSec;
245         position -= lpTime->u.smpte.sec * format->wf.nSamplesPerSec;
246         lpTime->u.smpte.min = lpTime->u.smpte.sec / 60;
247         lpTime->u.smpte.sec -= 60 * lpTime->u.smpte.min;
248         lpTime->u.smpte.hour = lpTime->u.smpte.min / 60;
249         lpTime->u.smpte.min -= 60 * lpTime->u.smpte.hour;
250         lpTime->u.smpte.fps = 30;
251         lpTime->u.smpte.frame = position * lpTime->u.smpte.fps / format->wf.nSamplesPerSec;
252         position -= lpTime->u.smpte.frame * format->wf.nSamplesPerSec / lpTime->u.smpte.fps;
253         if (position != 0)
254         {
255             /* Round up */
256             lpTime->u.smpte.frame++;
257         }
258         TRACE("TIME_SMPTE=%02u:%02u:%02u:%02u\n",
259               lpTime->u.smpte.hour, lpTime->u.smpte.min,
260               lpTime->u.smpte.sec, lpTime->u.smpte.frame);
261         break;
262     default:
263         FIXME("Format %d not supported ! use TIME_BYTES !\n", lpTime->wType);
264         lpTime->wType = TIME_BYTES;
265         /* fall through */
266     case TIME_BYTES:
267         lpTime->u.cb = position;
268         TRACE("TIME_BYTES=%lu\n", lpTime->u.cb);
269         break;
270     }
271     return MMSYSERR_NOERROR;
272 }
273
274 /*======================================================================*
275  *                  Low level WAVE implementation                       *
276  *======================================================================*/
277
278 /* Volume functions derived from Alsaplayer source */
279 /* length is the number of 16 bit samples */
280 void volume_effect16(void *bufin, void* bufout, int length, int left,
281                 int right, int  nChannels)
282 {
283   short *d_out = (short *)bufout;
284   short *d_in = (short *)bufin;
285   int i, v;
286
287 /*
288   TRACE("length == %d, nChannels == %d\n", length, nChannels);
289 */
290
291   if (right == -1) right = left;
292
293   for(i = 0; i < length; i+=(nChannels))
294   {
295     v = (int) ((*(d_in++) * left) / 100);
296     *(d_out++) = (v>32767) ? 32767 : ((v<-32768) ? -32768 : v);
297     if(nChannels == 2)
298     {
299       v = (int) ((*(d_in++) * right) / 100);
300       *(d_out++) = (v>32767) ? 32767 : ((v<-32768) ? -32768 : v);
301     }
302   }
303 }
304
305 /* length is the number of 8 bit samples */
306 void volume_effect8(void *bufin, void* bufout, int length, int left,
307                 int right, int  nChannels)
308 {
309   BYTE *d_out = (BYTE *)bufout;
310   BYTE *d_in = (BYTE *)bufin;
311   int i, v;
312
313 /*
314   TRACE("length == %d, nChannels == %d\n", length, nChannels);
315 */
316
317   if (right == -1) right = left;
318
319   for(i = 0; i < length; i+=(nChannels))
320   {
321     v = (BYTE) ((*(d_in++) * left) / 100);
322     *(d_out++) = (v>255) ? 255 : ((v<0) ? 0 : v);
323     if(nChannels == 2)
324     {
325       v = (BYTE) ((*(d_in++) * right) / 100);
326       *(d_out++) = (v>255) ? 255 : ((v<0) ? 0 : v);
327     }
328   }
329 }
330
331 /******************************************************************
332  *              ARTS_CloseWaveOutDevice
333  *
334  */
335 void            ARTS_CloseWaveOutDevice(WINE_WAVEOUT* wwo)
336 {
337   arts_close_stream(wwo->play_stream);  /* close the arts stream */
338   wwo->play_stream = (arts_stream_t*)-1;
339
340   /* free up the buffer we use for volume and reset the size */
341   if(wwo->sound_buffer)
342   {
343     HeapFree(GetProcessHeap(), 0, wwo->sound_buffer);
344     wwo->sound_buffer = NULL;
345   }
346
347   wwo->buffer_size = 0;
348 }
349
350 /******************************************************************
351  *              ARTS_CloseWaveInDevice
352  *
353  */
354 void            ARTS_CloseWaveInDevice(WINE_WAVEIN* wwi)
355 {
356   arts_close_stream(wwi->record_stream);        /* close the arts stream */
357   wwi->record_stream = (arts_stream_t*)-1;
358 }
359
360 /******************************************************************
361  *              ARTS_Init
362  */
363 static int      ARTS_Init(void)
364 {
365   return arts_init();  /* initialize arts and return errorcode */
366 }
367
368 /******************************************************************
369  *              ARTS_WaveClose
370  */
371 LONG            ARTS_WaveClose(void)
372 {
373     int iDevice;
374
375     /* close all open devices */
376     for(iDevice = 0; iDevice < MAX_WAVEOUTDRV; iDevice++)
377     {
378       if(WOutDev[iDevice].play_stream != (arts_stream_t*)-1)
379       {
380         ARTS_CloseWaveOutDevice(&WOutDev[iDevice]);
381       }
382     }
383
384     for(iDevice = 0; iDevice < MAX_WAVEINDRV; iDevice++)
385     {
386       if(WInDev[iDevice].record_stream != (arts_stream_t*)-1)
387       {
388         ARTS_CloseWaveInDevice(&WInDev[iDevice]);
389       }
390     }
391
392     arts_free();    /* free up arts */
393     return 1;
394 }
395
396 /******************************************************************
397  *              ARTS_WaveInit
398  *
399  * Initialize internal structures from ARTS server info
400  */
401 LONG ARTS_WaveInit(void)
402 {
403     int         i;
404     int         errorcode;
405
406     TRACE("called\n");
407
408     if ((errorcode = ARTS_Init()) < 0)
409     {
410         WARN("arts_init() failed (%d)\n", errorcode);
411         return -1;
412     }
413
414     /* initialize all device handles to -1 */
415     for (i = 0; i < MAX_WAVEOUTDRV; ++i)
416     {
417         WOutDev[i].play_stream = (arts_stream_t*)-1;
418         memset(&WOutDev[i].caps, 0, sizeof(WOutDev[i].caps)); /* zero out
419                                                         caps values */
420     /* FIXME: some programs compare this string against the content of the registry
421      * for MM drivers. The names have to match in order for the program to work
422      * (e.g. MS win9x mplayer.exe)
423      */
424 #ifdef EMULATE_SB16
425         WOutDev[i].caps.wMid = 0x0002;
426         WOutDev[i].caps.wPid = 0x0104;
427         strcpy(WOutDev[i].caps.szPname, "SB16 Wave Out");
428 #else
429         WOutDev[i].caps.wMid = 0x00FF;  /* Manufac ID */
430         WOutDev[i].caps.wPid = 0x0001;  /* Product ID */
431     /*    strcpy(WOutDev[i].caps.szPname, "OpenSoundSystem WAVOUT Driver");*/
432         strcpy(WOutDev[i].caps.szPname, "CS4236/37/38");
433 #endif
434         snprintf(WOutDev[i].interface_name, sizeof(WOutDev[i].interface_name), "winearts: %d", i);
435
436         WOutDev[i].caps.vDriverVersion = 0x0100;
437         WOutDev[i].caps.dwFormats = 0x00000000;
438         WOutDev[i].caps.dwSupport = WAVECAPS_VOLUME;
439
440         WOutDev[i].caps.wChannels = 2;
441         WOutDev[i].caps.dwSupport |= WAVECAPS_LRVOLUME;
442
443         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4M08;
444         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4S08;
445         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4S16;
446         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4M16;
447         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2M08;
448         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2S08;
449         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2M16;
450         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2S16;
451         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1M08;
452         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1S08;
453         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1M16;
454         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1S16;
455     }
456
457     for (i = 0; i < MAX_WAVEINDRV; ++i)
458     {
459         WInDev[i].record_stream = (arts_stream_t*)-1;
460         memset(&WInDev[i].caps, 0, sizeof(WInDev[i].caps)); /* zero out
461                                                         caps values */
462     /* FIXME: some programs compare this string against the content of the registry
463      * for MM drivers. The names have to match in order for the program to work
464      * (e.g. MS win9x mplayer.exe)
465      */
466 #ifdef EMULATE_SB16
467         WInDev[i].caps.wMid = 0x0002;
468         WInDev[i].caps.wPid = 0x0104;
469         strcpy(WInDev[i].caps.szPname, "SB16 Wave In");
470 #else
471         WInDev[i].caps.wMid = 0x00FF;
472         WInDev[i].caps.wPid = 0x0001;
473         strcpy(WInDev[i].caps.szPname,"CS4236/37/38");
474 #endif
475         snprintf(WInDev[i].interface_name, sizeof(WInDev[i].interface_name), "winearts: %d", i);
476
477         WInDev[i].caps.vDriverVersion = 0x0100;
478         WInDev[i].caps.dwFormats = 0x00000000;
479
480         WInDev[i].caps.wChannels = 2;
481
482         WInDev[i].caps.dwFormats |= WAVE_FORMAT_4M08;
483         WInDev[i].caps.dwFormats |= WAVE_FORMAT_4S08;
484         WInDev[i].caps.dwFormats |= WAVE_FORMAT_4S16;
485         WInDev[i].caps.dwFormats |= WAVE_FORMAT_4M16;
486         WInDev[i].caps.dwFormats |= WAVE_FORMAT_2M08;
487         WInDev[i].caps.dwFormats |= WAVE_FORMAT_2S08;
488         WInDev[i].caps.dwFormats |= WAVE_FORMAT_2M16;
489         WInDev[i].caps.dwFormats |= WAVE_FORMAT_2S16;
490         WInDev[i].caps.dwFormats |= WAVE_FORMAT_1M08;
491         WInDev[i].caps.dwFormats |= WAVE_FORMAT_1S08;
492         WInDev[i].caps.dwFormats |= WAVE_FORMAT_1M16;
493         WInDev[i].caps.dwFormats |= WAVE_FORMAT_1S16;
494
495         WInDev[i].caps.wReserved1 = 0;
496     }
497     return 0;
498 }
499
500 /******************************************************************
501  *              ARTS_InitRingMessage
502  *
503  * Initialize the ring of messages for passing between driver's caller and playback/record
504  * thread
505  */
506 static int ARTS_InitRingMessage(ARTS_MSG_RING* mr)
507 {
508     mr->msg_toget = 0;
509     mr->msg_tosave = 0;
510     mr->msg_event = CreateEventA(NULL, FALSE, FALSE, NULL);
511     mr->ring_buffer_size = ARTS_RING_BUFFER_INCREMENT;
512     mr->messages = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,mr->ring_buffer_size * sizeof(RING_MSG));
513     InitializeCriticalSection(&mr->msg_crst);
514     return 0;
515 }
516
517 /******************************************************************
518  *              ARTS_DestroyRingMessage
519  *
520  */
521 static int ARTS_DestroyRingMessage(ARTS_MSG_RING* mr)
522 {
523     CloseHandle(mr->msg_event);
524     HeapFree(GetProcessHeap(),0,mr->messages);
525     mr->messages=NULL;
526     DeleteCriticalSection(&mr->msg_crst);
527     return 0;
528 }
529
530 /******************************************************************
531  *              ARTS_AddRingMessage
532  *
533  * Inserts a new message into the ring (should be called from DriverProc derivated routines)
534  */
535 static int ARTS_AddRingMessage(ARTS_MSG_RING* mr, enum win_wm_message msg, DWORD param, BOOL wait)
536 {
537     HANDLE      hEvent = INVALID_HANDLE_VALUE;
538
539     EnterCriticalSection(&mr->msg_crst);
540     if ((mr->msg_toget == ((mr->msg_tosave + 1) % mr->ring_buffer_size)))
541     {
542         int old_ring_buffer_size = mr->ring_buffer_size;
543         mr->ring_buffer_size += ARTS_RING_BUFFER_INCREMENT;
544         TRACE("mr->ring_buffer_size=%d\n",mr->ring_buffer_size);
545         mr->messages = HeapReAlloc(GetProcessHeap(),0,mr->messages, mr->ring_buffer_size * sizeof(RING_MSG));
546         /* Now we need to rearrange the ring buffer so that the new
547            buffers just allocated are in between mr->msg_tosave and
548            mr->msg_toget.
549         */
550         if (mr->msg_tosave < mr->msg_toget)
551         {
552             memmove(&(mr->messages[mr->msg_toget + ARTS_RING_BUFFER_INCREMENT]),
553                     &(mr->messages[mr->msg_toget]),
554                     sizeof(RING_MSG)*(old_ring_buffer_size - mr->msg_toget)
555                     );
556             mr->msg_toget += ARTS_RING_BUFFER_INCREMENT;
557         }
558     }
559     if (wait)
560     {
561         hEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
562         if (hEvent == INVALID_HANDLE_VALUE)
563         {
564             ERR("can't create event !?\n");
565             LeaveCriticalSection(&mr->msg_crst);
566             return 0;
567         }
568         if (mr->msg_toget != mr->msg_tosave && mr->messages[mr->msg_toget].msg != WINE_WM_HEADER)
569             FIXME("two fast messages in the queue!!!!\n");
570
571         /* fast messages have to be added at the start of the queue */
572         mr->msg_toget = (mr->msg_toget + mr->ring_buffer_size - 1) % mr->ring_buffer_size;
573
574         mr->messages[mr->msg_toget].msg = msg;
575         mr->messages[mr->msg_toget].param = param;
576         mr->messages[mr->msg_toget].hEvent = hEvent;
577     }
578     else
579     {
580         mr->messages[mr->msg_tosave].msg = msg;
581         mr->messages[mr->msg_tosave].param = param;
582         mr->messages[mr->msg_tosave].hEvent = INVALID_HANDLE_VALUE;
583         mr->msg_tosave = (mr->msg_tosave + 1) % mr->ring_buffer_size;
584     }
585
586     LeaveCriticalSection(&mr->msg_crst);
587
588     SetEvent(mr->msg_event);    /* signal a new message */
589
590     if (wait)
591     {
592         /* wait for playback/record thread to have processed the message */
593         WaitForSingleObject(hEvent, INFINITE);
594         CloseHandle(hEvent);
595     }
596
597     return 1;
598 }
599
600 /******************************************************************
601  *              ARTS_RetrieveRingMessage
602  *
603  * Get a message from the ring. Should be called by the playback/record thread.
604  */
605 static int ARTS_RetrieveRingMessage(ARTS_MSG_RING* mr,
606                                    enum win_wm_message *msg, DWORD *param, HANDLE *hEvent)
607 {
608     EnterCriticalSection(&mr->msg_crst);
609
610     if (mr->msg_toget == mr->msg_tosave) /* buffer empty ? */
611     {
612         LeaveCriticalSection(&mr->msg_crst);
613         return 0;
614     }
615
616     *msg = mr->messages[mr->msg_toget].msg;
617     mr->messages[mr->msg_toget].msg = 0;
618     *param = mr->messages[mr->msg_toget].param;
619     *hEvent = mr->messages[mr->msg_toget].hEvent;
620     mr->msg_toget = (mr->msg_toget + 1) % mr->ring_buffer_size;
621     LeaveCriticalSection(&mr->msg_crst);
622     return 1;
623 }
624
625 /*======================================================================*
626  *                  Low level WAVE OUT implementation                   *
627  *======================================================================*/
628
629 /**************************************************************************
630  *                      wodNotifyClient                 [internal]
631  */
632 static DWORD wodNotifyClient(WINE_WAVEOUT* wwo, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
633 {
634     TRACE("wMsg = 0x%04x dwParm1 = %04lX dwParam2 = %04lX\n", wMsg, dwParam1, dwParam2);
635
636     switch (wMsg) {
637     case WOM_OPEN:
638     case WOM_CLOSE:
639     case WOM_DONE:
640         if (wwo->wFlags != DCB_NULL &&
641             !DriverCallback(wwo->waveDesc.dwCallback, wwo->wFlags, (HDRVR)wwo->waveDesc.hWave,
642                             wMsg, wwo->waveDesc.dwInstance, dwParam1, dwParam2)) {
643             WARN("can't notify client !\n");
644             return MMSYSERR_ERROR;
645         }
646         break;
647     default:
648         FIXME("Unknown callback message %u\n", wMsg);
649         return MMSYSERR_INVALPARAM;
650     }
651     return MMSYSERR_NOERROR;
652 }
653
654 /**************************************************************************
655  *                              wodUpdatePlayedTotal    [internal]
656  *
657  */
658 static BOOL wodUpdatePlayedTotal(WINE_WAVEOUT* wwo)
659 {
660     /* total played is the bytes written less the bytes to write ;-) */
661     wwo->dwPlayedTotal = wwo->dwWrittenTotal -
662         (wwo->dwBufferSize -
663         arts_stream_get(wwo->play_stream, ARTS_P_BUFFER_SPACE));
664
665     return TRUE;
666 }
667
668 /**************************************************************************
669  *                              wodPlayer_BeginWaveHdr          [internal]
670  *
671  * Makes the specified lpWaveHdr the currently playing wave header.
672  * If the specified wave header is a begin loop and we're not already in
673  * a loop, setup the loop.
674  */
675 static void wodPlayer_BeginWaveHdr(WINE_WAVEOUT* wwo, LPWAVEHDR lpWaveHdr)
676 {
677     wwo->lpPlayPtr = lpWaveHdr;
678
679     if (!lpWaveHdr) return;
680
681     if (lpWaveHdr->dwFlags & WHDR_BEGINLOOP) {
682         if (wwo->lpLoopPtr) {
683             WARN("Already in a loop. Discarding loop on this header (%p)\n", lpWaveHdr);
684             TRACE("Already in a loop. Discarding loop on this header (%p)\n", lpWaveHdr);
685         } else {
686             TRACE("Starting loop (%ldx) with %p\n", lpWaveHdr->dwLoops, lpWaveHdr);
687             wwo->lpLoopPtr = lpWaveHdr;
688             /* Windows does not touch WAVEHDR.dwLoops,
689              * so we need to make an internal copy */
690             wwo->dwLoops = lpWaveHdr->dwLoops;
691         }
692     }
693     wwo->dwPartialOffset = 0;
694 }
695
696 /**************************************************************************
697  *                              wodPlayer_PlayPtrNext           [internal]
698  *
699  * Advance the play pointer to the next waveheader, looping if required.
700  */
701 static LPWAVEHDR wodPlayer_PlayPtrNext(WINE_WAVEOUT* wwo)
702 {
703     LPWAVEHDR lpWaveHdr = wwo->lpPlayPtr;
704
705     wwo->dwPartialOffset = 0;
706     if ((lpWaveHdr->dwFlags & WHDR_ENDLOOP) && wwo->lpLoopPtr) {
707         /* We're at the end of a loop, loop if required */
708         if (--wwo->dwLoops > 0) {
709             wwo->lpPlayPtr = wwo->lpLoopPtr;
710         } else {
711             /* Handle overlapping loops correctly */
712             if (wwo->lpLoopPtr != lpWaveHdr && (lpWaveHdr->dwFlags & WHDR_BEGINLOOP)) {
713                 FIXME("Correctly handled case ? (ending loop buffer also starts a new loop)\n");
714                 /* shall we consider the END flag for the closing loop or for
715                  * the opening one or for both ???
716                  * code assumes for closing loop only
717                  */
718             } else {
719                 lpWaveHdr = lpWaveHdr->lpNext;
720             }
721             wwo->lpLoopPtr = NULL;
722             wodPlayer_BeginWaveHdr(wwo, lpWaveHdr);
723         }
724     } else {
725         /* We're not in a loop.  Advance to the next wave header */
726         wodPlayer_BeginWaveHdr(wwo, lpWaveHdr = lpWaveHdr->lpNext);
727     }
728
729     return lpWaveHdr;
730 }
731
732 /**************************************************************************
733  *                           wodPlayer_NotifyWait               [internal]
734  * Returns the number of milliseconds to wait before attempting to notify
735  * completion of the specified wavehdr.
736  * This is based on the number of bytes remaining to be written in the
737  * wave.
738  */
739 static DWORD wodPlayer_NotifyWait(const WINE_WAVEOUT* wwo, LPWAVEHDR lpWaveHdr)
740 {
741     DWORD dwMillis;
742
743     if(lpWaveHdr->reserved < wwo->dwPlayedTotal)
744     {
745         dwMillis = 1;
746     }
747     else
748     {
749         dwMillis = (lpWaveHdr->reserved - wwo->dwPlayedTotal) * 1000 / wwo->format.wf.nAvgBytesPerSec;
750         if(!dwMillis) dwMillis = 1;
751     }
752
753     TRACE("dwMillis = %ld\n", dwMillis);
754
755     return dwMillis;
756 }
757
758
759 /**************************************************************************
760  *                           wodPlayer_WriteMaxFrags            [internal]
761  * Writes the maximum number of bytes possible to the DSP and returns
762  * the number of bytes written.
763  */
764 static int wodPlayer_WriteMaxFrags(WINE_WAVEOUT* wwo, DWORD* bytes)
765 {
766     /* Only attempt to write to free bytes */
767     DWORD dwLength = wwo->lpPlayPtr->dwBufferLength - wwo->dwPartialOffset;
768     int toWrite = min(dwLength, *bytes);
769     int written;
770
771     TRACE("Writing wavehdr %p.%lu[%lu]\n",
772           wwo->lpPlayPtr, wwo->dwPartialOffset, wwo->lpPlayPtr->dwBufferLength);
773
774     /* see if our buffer isn't large enough for the data we are writing */
775     if(wwo->buffer_size < toWrite)
776     {
777       if(wwo->sound_buffer)
778       {
779         wwo->sound_buffer = HeapReAlloc(GetProcessHeap(), 0, wwo->sound_buffer, toWrite);
780         wwo->buffer_size = toWrite;
781       }
782     }
783
784     /* if we don't have a buffer then get one */
785     if(!wwo->sound_buffer)
786     {
787       /* allocate some memory for the buffer */
788       wwo->sound_buffer = HeapAlloc(GetProcessHeap(), 0, toWrite);
789       wwo->buffer_size = toWrite;
790     }
791
792     /* if we don't have a buffer then error out */
793     if(!wwo->sound_buffer)
794     {
795       ERR("error allocating sound_buffer memory\n");
796       return 0;
797     }
798
799     TRACE("toWrite == %d\n", toWrite);
800
801     /* apply volume to the bits */
802     /* for single channel audio streams we only use the LEFT volume */
803     if(wwo->format.wBitsPerSample == 16)
804     {
805       /* apply volume to the buffer we are about to send */
806       /* divide toWrite(bytes) by 2 as volume processes by 16 bits */
807       volume_effect16(wwo->lpPlayPtr->lpData + wwo->dwPartialOffset,
808                 wwo->sound_buffer, toWrite>>1, wwo->volume_left,
809                 wwo->volume_right, wwo->format.wf.nChannels);
810     } else if(wwo->format.wBitsPerSample == 8)
811     {
812       /* apply volume to the buffer we are about to send */
813       volume_effect8(wwo->lpPlayPtr->lpData + wwo->dwPartialOffset,
814                 wwo->sound_buffer, toWrite, wwo->volume_left,
815                 wwo->volume_right, wwo->format.wf.nChannels);
816     } else
817     {
818       FIXME("unsupported wwo->format.wBitsPerSample of %d\n",
819         wwo->format.wBitsPerSample);
820     }
821
822     /* send the audio data to arts for playing */
823     written = arts_write(wwo->play_stream, wwo->sound_buffer, toWrite);
824
825     TRACE("written = %d\n", written);
826
827     if (written <= 0) 
828     {
829       *bytes = 0; /* apparently arts is actually full */
830       return written; /* if we wrote nothing just return */
831     }
832
833     if (written >= dwLength)
834         wodPlayer_PlayPtrNext(wwo);   /* If we wrote all current wavehdr, skip to the next one */
835     else
836         wwo->dwPartialOffset += written;    /* Remove the amount written */
837
838     if (written < toWrite)
839         *bytes = 0;
840     else
841         *bytes -= written;
842
843     wwo->dwWrittenTotal += written; /* update stats on this wave device */
844
845     return written; /* return the number of bytes written */
846 }
847
848
849 /**************************************************************************
850  *                              wodPlayer_NotifyCompletions     [internal]
851  *
852  * Notifies and remove from queue all wavehdrs which have been played to
853  * the speaker (ie. they have cleared the audio device).  If force is true,
854  * we notify all wavehdrs and remove them all from the queue even if they
855  * are unplayed or part of a loop.
856  */
857 static DWORD wodPlayer_NotifyCompletions(WINE_WAVEOUT* wwo, BOOL force)
858 {
859     LPWAVEHDR           lpWaveHdr;
860
861     if (wwo->lpQueuePtr) {
862         TRACE("lpWaveHdr=(%p), lpPlayPtr=(%p), lpLoopPtr=(%p), reserved=(%ld), dwWrittenTotal=(%ld), force=(%d)\n", 
863               wwo->lpQueuePtr,
864               wwo->lpPlayPtr,
865               wwo->lpLoopPtr,
866               wwo->lpQueuePtr->reserved,
867               wwo->dwWrittenTotal,
868               force);
869     } else {
870         TRACE("lpWaveHdr=(%p), lpPlayPtr=(%p), lpLoopPtr=(%p),  dwWrittenTotal=(%ld), force=(%d)\n", 
871               wwo->lpQueuePtr,
872               wwo->lpPlayPtr,
873               wwo->lpLoopPtr,
874               wwo->dwWrittenTotal,
875               force);
876     }
877
878     /* Start from lpQueuePtr and keep notifying until:
879      * - we hit an unwritten wavehdr
880      * - we hit the beginning of a running loop
881      * - we hit a wavehdr which hasn't finished playing
882      */
883     while ((lpWaveHdr = wwo->lpQueuePtr) &&
884            (force ||
885             (lpWaveHdr != wwo->lpPlayPtr &&
886              lpWaveHdr != wwo->lpLoopPtr &&
887              lpWaveHdr->reserved <= wwo->dwWrittenTotal))) {
888
889         wwo->lpQueuePtr = lpWaveHdr->lpNext;
890
891         lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
892         lpWaveHdr->dwFlags |= WHDR_DONE;
893
894         wodNotifyClient(wwo, WOM_DONE, (DWORD)lpWaveHdr, 0);
895     }
896     return  (lpWaveHdr && lpWaveHdr != wwo->lpPlayPtr && lpWaveHdr != wwo->lpLoopPtr) ?
897         wodPlayer_NotifyWait(wwo, lpWaveHdr) : INFINITE;
898 }
899
900 /**************************************************************************
901  *                              wodPlayer_Reset                 [internal]
902  *
903  * wodPlayer helper. Resets current output stream.
904  */
905 static  void    wodPlayer_Reset(WINE_WAVEOUT* wwo, BOOL reset)
906 {
907     wodUpdatePlayedTotal(wwo);
908
909     wodPlayer_NotifyCompletions(wwo, FALSE); /* updates current notify list */
910
911     /* we aren't able to flush any data that has already been written */
912     /* to arts, otherwise we would do the flushing here */
913
914     if (reset) {
915         enum win_wm_message     msg;
916         DWORD                   param;
917         HANDLE                  ev;
918
919         /* remove any buffer */
920         wodPlayer_NotifyCompletions(wwo, TRUE);
921
922         wwo->lpPlayPtr = wwo->lpQueuePtr = wwo->lpLoopPtr = NULL;
923         wwo->state = WINE_WS_STOPPED;
924         wwo->dwPlayedTotal = wwo->dwWrittenTotal = 0;
925
926         wwo->dwPartialOffset = 0;        /* Clear partial wavehdr */
927
928         /* remove any existing message in the ring */
929         EnterCriticalSection(&wwo->msgRing.msg_crst);
930
931         /* return all pending headers in queue */
932         while (ARTS_RetrieveRingMessage(&wwo->msgRing, &msg, &param, &ev))
933         {
934             TRACE("flushing msg\n");
935             if (msg != WINE_WM_HEADER)
936             {
937                 FIXME("shouldn't have headers left\n");
938                 SetEvent(ev);
939                 continue;
940             }
941             ((LPWAVEHDR)param)->dwFlags &= ~WHDR_INQUEUE;
942             ((LPWAVEHDR)param)->dwFlags |= WHDR_DONE;
943
944             wodNotifyClient(wwo, WOM_DONE, param, 0);
945         }
946         ResetEvent(wwo->msgRing.msg_event);
947         LeaveCriticalSection(&wwo->msgRing.msg_crst);
948     } else {
949         if (wwo->lpLoopPtr) {
950             /* complicated case, not handled yet (could imply modifying the loop counter */
951             FIXME("Pausing while in loop isn't correctly handled yet, except strange results\n");
952             wwo->lpPlayPtr = wwo->lpLoopPtr;
953             wwo->dwPartialOffset = 0;
954             wwo->dwWrittenTotal = wwo->dwPlayedTotal; /* this is wrong !!! */
955         } else {
956             /* the data already written is going to be played, so take */
957             /* this fact into account here */
958             wwo->dwPlayedTotal = wwo->dwWrittenTotal;
959         }
960         wwo->state = WINE_WS_PAUSED;
961     }
962 }
963
964 /**************************************************************************
965  *                    wodPlayer_ProcessMessages                 [internal]
966  */
967 static void wodPlayer_ProcessMessages(WINE_WAVEOUT* wwo)
968 {
969     LPWAVEHDR           lpWaveHdr;
970     enum win_wm_message msg;
971     DWORD               param;
972     HANDLE              ev;
973
974     while (ARTS_RetrieveRingMessage(&wwo->msgRing, &msg, &param, &ev)) {
975         TRACE("Received %s %lx\n", wodPlayerCmdString[msg - WM_USER - 1], param);
976         switch (msg) {
977         case WINE_WM_PAUSING:
978             wodPlayer_Reset(wwo, FALSE);
979             SetEvent(ev);
980             break;
981         case WINE_WM_RESTARTING:
982             wwo->state = WINE_WS_PLAYING;
983             SetEvent(ev);
984             break;
985         case WINE_WM_HEADER:
986             lpWaveHdr = (LPWAVEHDR)param;
987
988             /* insert buffer at the end of queue */
989             {
990                 LPWAVEHDR*      wh;
991                 for (wh = &(wwo->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
992                 *wh = lpWaveHdr;
993             }
994             if (!wwo->lpPlayPtr)
995                 wodPlayer_BeginWaveHdr(wwo,lpWaveHdr);
996             if (wwo->state == WINE_WS_STOPPED)
997                 wwo->state = WINE_WS_PLAYING;
998             break;
999         case WINE_WM_RESETTING:
1000             wodPlayer_Reset(wwo, TRUE);
1001             SetEvent(ev);
1002             break;
1003         case WINE_WM_UPDATE:
1004             wodUpdatePlayedTotal(wwo);
1005             SetEvent(ev);
1006             break;
1007         case WINE_WM_BREAKLOOP:
1008             if (wwo->state == WINE_WS_PLAYING && wwo->lpLoopPtr != NULL) {
1009                 /* ensure exit at end of current loop */
1010                 wwo->dwLoops = 1;
1011             }
1012             SetEvent(ev);
1013             break;
1014         case WINE_WM_CLOSING:
1015             /* sanity check: this should not happen since the device must have been reset before */
1016             if (wwo->lpQueuePtr || wwo->lpPlayPtr) ERR("out of sync\n");
1017             wwo->hThread = 0;
1018             wwo->state = WINE_WS_CLOSED;
1019             SetEvent(ev);
1020             ExitThread(0);
1021             /* shouldn't go here */
1022         default:
1023             FIXME("unknown message %d\n", msg);
1024             break;
1025         }
1026     }
1027 }
1028
1029 /**************************************************************************
1030  *                           wodPlayer_FeedDSP                  [internal]
1031  * Feed as much sound data as we can into the DSP and return the number of
1032  * milliseconds before it will be necessary to feed the DSP again.
1033  */
1034 static DWORD wodPlayer_FeedDSP(WINE_WAVEOUT* wwo)
1035 {
1036     DWORD       availInQ;
1037
1038     wodUpdatePlayedTotal(wwo);
1039     availInQ = arts_stream_get(wwo->play_stream, ARTS_P_BUFFER_SPACE);
1040     TRACE("availInQ = %ld\n", availInQ);
1041
1042     /* input queue empty */
1043     if (!wwo->lpPlayPtr) {
1044         TRACE("Run out of wavehdr:s... flushing\n");
1045         return INFINITE;
1046     }
1047
1048     /* no more room... no need to try to feed */
1049     if(!availInQ)
1050     {
1051         TRACE("no more room, no need to try to feed\n");
1052         return wwo->dwSleepTime;
1053     }
1054
1055     /* Feed from partial wavehdr */
1056     if (wwo->lpPlayPtr && wwo->dwPartialOffset != 0)
1057     {
1058         TRACE("feeding from partial wavehdr\n");
1059         wodPlayer_WriteMaxFrags(wwo, &availInQ);
1060     }
1061
1062     /* Feed wavehdrs until we run out of wavehdrs or DSP space */
1063     if (!wwo->dwPartialOffset)
1064     {
1065         while(wwo->lpPlayPtr && availInQ)
1066         {
1067             TRACE("feeding waveheaders until we run out of space\n");
1068             /* note the value that dwPlayedTotal will return when this wave finishes playing */
1069             wwo->lpPlayPtr->reserved = wwo->dwWrittenTotal + wwo->lpPlayPtr->dwBufferLength;
1070             TRACE("reserved=(%ld) dwWrittenTotal=(%ld) dwBufferLength=(%ld)\n",
1071                   wwo->lpPlayPtr->reserved,
1072                   wwo->dwWrittenTotal,
1073                   wwo->lpPlayPtr->dwBufferLength
1074                 );
1075             wodPlayer_WriteMaxFrags(wwo, &availInQ);
1076         }
1077     }
1078
1079     if (!wwo->lpPlayPtr) {
1080         TRACE("Ran out of wavehdrs\n");
1081         return INFINITE;
1082     }
1083
1084     return wwo->dwSleepTime;
1085 }
1086
1087
1088 /**************************************************************************
1089  *                              wodPlayer                       [internal]
1090  */
1091 static  DWORD   CALLBACK        wodPlayer(LPVOID pmt)
1092 {
1093     WORD          uDevID = (DWORD)pmt;
1094     WINE_WAVEOUT* wwo = (WINE_WAVEOUT*)&WOutDev[uDevID];
1095     DWORD         dwNextFeedTime = INFINITE;   /* Time before DSP needs feeding */
1096     DWORD         dwNextNotifyTime = INFINITE; /* Time before next wave completion */
1097     DWORD         dwSleepTime;
1098
1099     wwo->state = WINE_WS_STOPPED;
1100     SetEvent(wwo->hStartUpEvent);
1101
1102     for (;;) {
1103         /** Wait for the shortest time before an action is required.  If there
1104          *  are no pending actions, wait forever for a command.
1105          */
1106         dwSleepTime = min(dwNextFeedTime, dwNextNotifyTime);
1107         TRACE("waiting %lums (%lu,%lu)\n", dwSleepTime, dwNextFeedTime, dwNextNotifyTime);
1108         WaitForSingleObject(wwo->msgRing.msg_event, dwSleepTime);
1109         wodPlayer_ProcessMessages(wwo);
1110         if (wwo->state == WINE_WS_PLAYING) {
1111             dwNextFeedTime = wodPlayer_FeedDSP(wwo);
1112             dwNextNotifyTime = wodPlayer_NotifyCompletions(wwo, FALSE);
1113         } else {
1114             dwNextFeedTime = dwNextNotifyTime = INFINITE;
1115         }
1116     }
1117 }
1118
1119 /**************************************************************************
1120  *                      wodGetDevCaps                           [internal]
1121  */
1122 static DWORD wodGetDevCaps(WORD wDevID, LPWAVEOUTCAPSA lpCaps, DWORD dwSize)
1123 {
1124     TRACE("(%u, %p, %lu);\n", wDevID, lpCaps, dwSize);
1125
1126     if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
1127
1128     if (wDevID >= MAX_WAVEOUTDRV) {
1129         TRACE("MAX_WAVOUTDRV reached !\n");
1130         return MMSYSERR_BADDEVICEID;
1131     }
1132
1133     memcpy(lpCaps, &WOutDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
1134     return MMSYSERR_NOERROR;
1135 }
1136
1137 /**************************************************************************
1138  *                              wodOpen                         [internal]
1139  */
1140 static DWORD wodOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
1141 {
1142     WINE_WAVEOUT*       wwo;
1143
1144     TRACE("(%u, %p, %08lX);\n", wDevID, lpDesc, dwFlags);
1145     if (lpDesc == NULL) {
1146         WARN("Invalid Parameter !\n");
1147         return MMSYSERR_INVALPARAM;
1148     }
1149     if (wDevID >= MAX_WAVEOUTDRV) {
1150         TRACE("MAX_WAVOUTDRV reached !\n");
1151         return MMSYSERR_BADDEVICEID;
1152     }
1153
1154     /* if this device is already open tell the app that it is allocated */
1155     if(WOutDev[wDevID].play_stream != (arts_stream_t*)-1)
1156     {
1157       TRACE("device already allocated\n");
1158       return MMSYSERR_ALLOCATED;
1159     }
1160
1161     /* only PCM format is supported so far... */
1162     if (lpDesc->lpFormat->wFormatTag != WAVE_FORMAT_PCM ||
1163         lpDesc->lpFormat->nChannels == 0 ||
1164         lpDesc->lpFormat->nSamplesPerSec < DSBFREQUENCY_MIN ||
1165         lpDesc->lpFormat->nSamplesPerSec > DSBFREQUENCY_MAX ||
1166         (lpDesc->lpFormat->wBitsPerSample!=8 && lpDesc->lpFormat->wBitsPerSample!=16)) {
1167         WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
1168              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1169              lpDesc->lpFormat->nSamplesPerSec);
1170         return WAVERR_BADFORMAT;
1171     }
1172
1173     if (dwFlags & WAVE_FORMAT_QUERY) {
1174         TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
1175              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1176              lpDesc->lpFormat->nSamplesPerSec);
1177         return MMSYSERR_NOERROR;
1178     }
1179
1180     wwo = &WOutDev[wDevID];
1181
1182     /* direct sound not supported, ignore the flag */
1183     dwFlags &= ~WAVE_DIRECTSOUND;
1184
1185     wwo->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
1186
1187     memcpy(&wwo->waveDesc, lpDesc,           sizeof(WAVEOPENDESC));
1188     memcpy(&wwo->format,   lpDesc->lpFormat, sizeof(PCMWAVEFORMAT));
1189
1190     if (wwo->format.wBitsPerSample == 0) {
1191         WARN("Resetting zeroed wBitsPerSample\n");
1192         wwo->format.wBitsPerSample = 8 *
1193             (wwo->format.wf.nAvgBytesPerSec /
1194              wwo->format.wf.nSamplesPerSec) /
1195             wwo->format.wf.nChannels;
1196     }
1197
1198     wwo->play_stream = arts_play_stream(wwo->format.wf.nSamplesPerSec,
1199         wwo->format.wBitsPerSample, wwo->format.wf.nChannels, "winearts");
1200
1201     /* clear these so we don't have any confusion ;-) */
1202     wwo->sound_buffer = 0;
1203     wwo->buffer_size = 0;
1204
1205     arts_stream_set(wwo->play_stream, ARTS_P_BLOCKING, 0);    /* disable blocking on this stream */
1206
1207     if(!wwo->play_stream) return MMSYSERR_ALLOCATED;
1208
1209     /* Try to set the packet settings from constant and store the value that it
1210        was actually set to for future use */
1211     wwo->packetSettings = arts_stream_set(wwo->play_stream, ARTS_P_PACKET_SETTINGS, WAVEOUT_PACKET_SETTINGS);
1212     TRACE("Tried to set ARTS_P_PACKET_SETTINGS to (%x), actually set to (%x)\n", WAVEOUT_PACKET_SETTINGS, wwo->packetSettings);
1213
1214     wwo->dwBufferSize = arts_stream_get(wwo->play_stream, ARTS_P_BUFFER_SIZE);
1215     TRACE("Buffer size is now (%ld)\n",wwo->dwBufferSize);
1216
1217     wwo->dwPlayedTotal = 0;
1218     wwo->dwWrittenTotal = 0;
1219
1220     wwo->dwSleepTime = ((1 << (wwo->packetSettings & 0xFFFF)) * 1000 * BUFFER_REFILL_THRESHOLD) / wwo->format.wf.nAvgBytesPerSec;
1221
1222     /* Initialize volume to full level */
1223     wwo->volume_left = 100;
1224     wwo->volume_right = 100;
1225
1226     ARTS_InitRingMessage(&wwo->msgRing);
1227
1228     /* create player thread */
1229     if (!(dwFlags & WAVE_DIRECTSOUND)) {
1230         wwo->hStartUpEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
1231         wwo->hThread = CreateThread(NULL, 0, wodPlayer, (LPVOID)(DWORD)wDevID, 0, &(wwo->dwThreadID));
1232         WaitForSingleObject(wwo->hStartUpEvent, INFINITE);
1233         CloseHandle(wwo->hStartUpEvent);
1234     } else {
1235         wwo->hThread = INVALID_HANDLE_VALUE;
1236         wwo->dwThreadID = 0;
1237     }
1238     wwo->hStartUpEvent = INVALID_HANDLE_VALUE;
1239
1240     TRACE("stream=0x%lx, dwBufferSize=%ld\n",
1241           (long)wwo->play_stream, wwo->dwBufferSize);
1242
1243     TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%lu, nSamplesPerSec=%lu, nChannels=%u nBlockAlign=%u!\n",
1244           wwo->format.wBitsPerSample, wwo->format.wf.nAvgBytesPerSec,
1245           wwo->format.wf.nSamplesPerSec, wwo->format.wf.nChannels,
1246           wwo->format.wf.nBlockAlign);
1247
1248     return wodNotifyClient(wwo, WOM_OPEN, 0L, 0L);
1249 }
1250
1251 /**************************************************************************
1252  *                              wodClose                        [internal]
1253  */
1254 static DWORD wodClose(WORD wDevID)
1255 {
1256     DWORD               ret = MMSYSERR_NOERROR;
1257     WINE_WAVEOUT*       wwo;
1258
1259     TRACE("(%u);\n", wDevID);
1260
1261     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].play_stream  ==
1262         (arts_stream_t*)-1)
1263     {
1264         WARN("bad device ID !\n");
1265         return MMSYSERR_BADDEVICEID;
1266     }
1267
1268     wwo = &WOutDev[wDevID];
1269     if (wwo->lpQueuePtr) {
1270         WARN("buffers still playing !\n");
1271         ret = WAVERR_STILLPLAYING;
1272     } else {
1273         TRACE("imhere[3-close]\n");
1274         if (wwo->hThread != INVALID_HANDLE_VALUE) {
1275             ARTS_AddRingMessage(&wwo->msgRing, WINE_WM_CLOSING, 0, TRUE);
1276         }
1277
1278         ARTS_DestroyRingMessage(&wwo->msgRing);
1279
1280         ARTS_CloseWaveOutDevice(wwo);   /* close the stream and clean things up */
1281
1282         ret = wodNotifyClient(wwo, WOM_CLOSE, 0L, 0L);
1283     }
1284     return ret;
1285 }
1286
1287 /**************************************************************************
1288  *                              wodWrite                        [internal]
1289  *
1290  */
1291 static DWORD wodWrite(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1292 {
1293     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
1294
1295     /* first, do the sanity checks... */
1296     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].play_stream ==
1297                 (arts_stream_t*)-1)
1298     {
1299         WARN("bad dev ID !\n");
1300         return MMSYSERR_BADDEVICEID;
1301     }
1302
1303     if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
1304     {
1305         TRACE("unprepared\n");
1306         return WAVERR_UNPREPARED;
1307     }
1308
1309     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1310     {
1311         TRACE("still playing\n");
1312         return WAVERR_STILLPLAYING;
1313     }
1314
1315     lpWaveHdr->dwFlags &= ~WHDR_DONE;
1316     lpWaveHdr->dwFlags |= WHDR_INQUEUE;
1317     lpWaveHdr->lpNext = 0;
1318
1319     TRACE("adding ring message\n");
1320     ARTS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_HEADER, (DWORD)lpWaveHdr, FALSE);
1321
1322     return MMSYSERR_NOERROR;
1323 }
1324
1325 /**************************************************************************
1326  *                              wodPrepare                      [internal]
1327  */
1328 static DWORD wodPrepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1329 {
1330     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
1331
1332     if (wDevID >= MAX_WAVEOUTDRV) {
1333         WARN("bad device ID !\n");
1334         return MMSYSERR_BADDEVICEID;
1335     }
1336
1337     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1338         return WAVERR_STILLPLAYING;
1339
1340     lpWaveHdr->dwFlags |= WHDR_PREPARED;
1341     lpWaveHdr->dwFlags &= ~WHDR_DONE;
1342     return MMSYSERR_NOERROR;
1343 }
1344
1345 /**************************************************************************
1346  *                              wodUnprepare                    [internal]
1347  */
1348 static DWORD wodUnprepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1349 {
1350     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
1351
1352     if (wDevID >= MAX_WAVEOUTDRV) {
1353         WARN("bad device ID !\n");
1354         return MMSYSERR_BADDEVICEID;
1355     }
1356
1357     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1358         return WAVERR_STILLPLAYING;
1359
1360     lpWaveHdr->dwFlags &= ~WHDR_PREPARED;
1361     lpWaveHdr->dwFlags |= WHDR_DONE;
1362
1363     return MMSYSERR_NOERROR;
1364 }
1365
1366 /**************************************************************************
1367  *                      wodPause                                [internal]
1368  */
1369 static DWORD wodPause(WORD wDevID)
1370 {
1371     TRACE("(%u);!\n", wDevID);
1372
1373     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].play_stream ==
1374                 (arts_stream_t*)-1)
1375     {
1376         WARN("bad device ID !\n");
1377         return MMSYSERR_BADDEVICEID;
1378     }
1379
1380     TRACE("imhere[3-PAUSING]\n");
1381     ARTS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_PAUSING, 0, TRUE);
1382
1383     return MMSYSERR_NOERROR;
1384 }
1385
1386 /**************************************************************************
1387  *                      wodRestart                              [internal]
1388  */
1389 static DWORD wodRestart(WORD wDevID)
1390 {
1391     TRACE("(%u);\n", wDevID);
1392
1393     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].play_stream ==
1394                 (arts_stream_t*)-1)
1395     {
1396         WARN("bad device ID !\n");
1397         return MMSYSERR_BADDEVICEID;
1398     }
1399
1400     if (WOutDev[wDevID].state == WINE_WS_PAUSED) {
1401         TRACE("imhere[3-RESTARTING]\n");
1402         ARTS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESTARTING, 0, TRUE);
1403     }
1404
1405     /* FIXME: is NotifyClient with WOM_DONE right ? (Comet Busters 1.3.3 needs this notification) */
1406     /* FIXME: Myst crashes with this ... hmm -MM
1407        return wodNotifyClient(wwo, WOM_DONE, 0L, 0L);
1408     */
1409
1410     return MMSYSERR_NOERROR;
1411 }
1412
1413 /**************************************************************************
1414  *                      wodReset                                [internal]
1415  */
1416 static DWORD wodReset(WORD wDevID)
1417 {
1418     TRACE("(%u);\n", wDevID);
1419
1420     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].play_stream ==
1421         (arts_stream_t*)-1)
1422     {
1423         WARN("bad device ID !\n");
1424         return MMSYSERR_BADDEVICEID;
1425     }
1426
1427     TRACE("imhere[3-RESET]\n");
1428     ARTS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
1429
1430     return MMSYSERR_NOERROR;
1431 }
1432
1433 /**************************************************************************
1434  *                              wodGetPosition                  [internal]
1435  */
1436 static DWORD wodGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
1437 {
1438     WINE_WAVEOUT*       wwo;
1439
1440     TRACE("(%u, %p, %lu);\n", wDevID, lpTime, uSize);
1441
1442     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].play_stream ==
1443         (arts_stream_t*)-1)
1444     {
1445         WARN("bad device ID !\n");
1446         return MMSYSERR_BADDEVICEID;
1447     }
1448
1449     if (lpTime == NULL) return MMSYSERR_INVALPARAM;
1450
1451     wwo = &WOutDev[wDevID];
1452     ARTS_AddRingMessage(&wwo->msgRing, WINE_WM_UPDATE, 0, TRUE);
1453
1454     return bytes_to_mmtime(lpTime, wwo->dwPlayedTotal, &wwo->format);
1455 }
1456
1457 /**************************************************************************
1458  *                              wodBreakLoop                    [internal]
1459  */
1460 static DWORD wodBreakLoop(WORD wDevID)
1461 {
1462     TRACE("(%u);\n", wDevID);
1463
1464     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].play_stream ==
1465                 (arts_stream_t*)-1)
1466     {
1467         WARN("bad device ID !\n");
1468         return MMSYSERR_BADDEVICEID;
1469     }
1470     ARTS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_BREAKLOOP, 0, TRUE);
1471     return MMSYSERR_NOERROR;
1472 }
1473
1474 /**************************************************************************
1475  *                              wodGetVolume                    [internal]
1476  */
1477 static DWORD wodGetVolume(WORD wDevID, LPDWORD lpdwVol)
1478 {
1479     DWORD left, right;
1480
1481     left = WOutDev[wDevID].volume_left;
1482     right = WOutDev[wDevID].volume_right;
1483
1484     TRACE("(%u, %p);\n", wDevID, lpdwVol);
1485
1486     *lpdwVol = ((left * 0xFFFFl) / 100) + (((right * 0xFFFFl) / 100) <<
1487                 16);
1488
1489     return MMSYSERR_NOERROR;
1490 }
1491
1492 /**************************************************************************
1493  *                              wodSetVolume                    [internal]
1494  */
1495 static DWORD wodSetVolume(WORD wDevID, DWORD dwParam)
1496 {
1497     DWORD left, right;
1498
1499     left  = (LOWORD(dwParam) * 100) / 0xFFFFl;
1500     right = (HIWORD(dwParam) * 100) / 0xFFFFl;
1501
1502     TRACE("(%u, %08lX);\n", wDevID, dwParam);
1503
1504     WOutDev[wDevID].volume_left = left;
1505     WOutDev[wDevID].volume_right = right;
1506
1507     return MMSYSERR_NOERROR;
1508 }
1509
1510 /**************************************************************************
1511  *                              wodGetNumDevs                   [internal]
1512  */
1513 static  DWORD   wodGetNumDevs(void)
1514 {
1515     return MAX_WAVEOUTDRV;
1516 }
1517
1518 /**************************************************************************
1519  *                              wodDevInterfaceSize             [internal]
1520  */
1521 static DWORD wodDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
1522 {
1523     TRACE("(%u, %p)\n", wDevID, dwParam1);
1524                                                                                                        
1525     *dwParam1 = MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].interface_name, -1,
1526                                     NULL, 0 ) * sizeof(WCHAR);
1527     return MMSYSERR_NOERROR;
1528 }
1529                                                                                                        
1530 /**************************************************************************
1531  *                              wodDevInterface                 [internal]
1532  */
1533 static DWORD wodDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
1534 {
1535     if (dwParam2 >= MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].interface_name, -1,
1536                                         NULL, 0 ) * sizeof(WCHAR))
1537     {
1538         MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].interface_name, -1,
1539                             dwParam1, dwParam2 / sizeof(WCHAR));
1540         return MMSYSERR_NOERROR;
1541     }
1542     return MMSYSERR_INVALPARAM;
1543 }
1544                                                                                                        
1545 /**************************************************************************
1546  *                              wodMessage (WINEARTS.@)
1547  */
1548 DWORD WINAPI ARTS_wodMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
1549                             DWORD dwParam1, DWORD dwParam2)
1550 {
1551     TRACE("(%u, %04X, %08lX, %08lX, %08lX);\n",
1552           wDevID, wMsg, dwUser, dwParam1, dwParam2);
1553
1554     switch (wMsg) {
1555     case DRVM_INIT:
1556     case DRVM_EXIT:
1557     case DRVM_ENABLE:
1558     case DRVM_DISABLE:
1559         /* FIXME: Pretend this is supported */
1560         return 0;
1561     case WODM_OPEN:             return wodOpen          (wDevID, (LPWAVEOPENDESC)dwParam1,      dwParam2);
1562     case WODM_CLOSE:            return wodClose         (wDevID);
1563     case WODM_WRITE:            return wodWrite         (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
1564     case WODM_PAUSE:            return wodPause         (wDevID);
1565     case WODM_GETPOS:           return wodGetPosition   (wDevID, (LPMMTIME)dwParam1,            dwParam2);
1566     case WODM_BREAKLOOP:        return wodBreakLoop     (wDevID);
1567     case WODM_PREPARE:          return wodPrepare       (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
1568     case WODM_UNPREPARE:        return wodUnprepare     (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
1569     case WODM_GETDEVCAPS:       return wodGetDevCaps    (wDevID, (LPWAVEOUTCAPSA)dwParam1,      dwParam2);
1570     case WODM_GETNUMDEVS:       return wodGetNumDevs    ();
1571     case WODM_GETPITCH:         return MMSYSERR_NOTSUPPORTED;
1572     case WODM_SETPITCH:         return MMSYSERR_NOTSUPPORTED;
1573     case WODM_GETPLAYBACKRATE:  return MMSYSERR_NOTSUPPORTED;
1574     case WODM_SETPLAYBACKRATE:  return MMSYSERR_NOTSUPPORTED;
1575     case WODM_GETVOLUME:        return wodGetVolume     (wDevID, (LPDWORD)dwParam1);
1576     case WODM_SETVOLUME:        return wodSetVolume     (wDevID, dwParam1);
1577     case WODM_RESTART:          return wodRestart       (wDevID);
1578     case WODM_RESET:            return wodReset         (wDevID);
1579
1580     case DRV_QUERYDEVICEINTERFACESIZE: return wodDevInterfaceSize       (wDevID, (LPDWORD)dwParam1);
1581     case DRV_QUERYDEVICEINTERFACE:     return wodDevInterface           (wDevID, (PWCHAR)dwParam1, dwParam2);
1582     case DRV_QUERYDSOUNDIFACE:  return wodDsCreate      (wDevID, (PIDSDRIVER*)dwParam1);
1583     case DRV_QUERYDSOUNDDESC:   return wodDsDesc        (wDevID, (PDSDRIVERDESC)dwParam1);
1584     case DRV_QUERYDSOUNDGUID:   return wodDsGuid        (wDevID, (LPGUID)dwParam1);
1585     default:
1586         FIXME("unknown message %d!\n", wMsg);
1587     }
1588     return MMSYSERR_NOTSUPPORTED;
1589 }
1590
1591 /*======================================================================*
1592  *                  Low level WAVE IN implementation                    *
1593  *======================================================================*/
1594
1595 /**************************************************************************
1596  *                              widGetNumDevs                   [internal]
1597  */
1598 static  DWORD   widGetNumDevs(void)
1599 {
1600     TRACE("%d \n",MAX_WAVEINDRV);
1601     return MAX_WAVEINDRV;
1602 }
1603
1604 /**************************************************************************
1605  *                              widDevInterfaceSize             [internal]
1606  */
1607 static DWORD widDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
1608 {
1609     TRACE("(%u, %p)\n", wDevID, dwParam1);
1610                                                                                                        
1611                                                                                                        
1612     *dwParam1 = MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
1613                                     NULL, 0 ) * sizeof(WCHAR);
1614     return MMSYSERR_NOERROR;
1615 }
1616
1617 /**************************************************************************
1618  *                              widDevInterface                 [internal]
1619  */
1620 static DWORD widDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
1621 {
1622     if (dwParam2 >= MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
1623                                         NULL, 0 ) * sizeof(WCHAR))
1624     {
1625         MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
1626                             dwParam1, dwParam2 / sizeof(WCHAR));
1627         return MMSYSERR_NOERROR;
1628     }
1629     return MMSYSERR_INVALPARAM;
1630 }
1631
1632 /**************************************************************************
1633  *                      widNotifyClient                 [internal]
1634  */
1635 static DWORD widNotifyClient(WINE_WAVEIN* wwi, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
1636 {
1637     TRACE("wMsg = 0x%04x dwParm1 = %04lX dwParam2 = %04lX\n", wMsg, dwParam1, dwParam2);
1638
1639     switch (wMsg) {
1640     case WIM_OPEN:
1641     case WIM_CLOSE:
1642     case WIM_DATA:
1643         if (wwi->wFlags != DCB_NULL &&
1644             !DriverCallback(wwi->waveDesc.dwCallback, wwi->wFlags,
1645                             (HDRVR)wwi->waveDesc.hWave, wMsg,
1646                             wwi->waveDesc.dwInstance, dwParam1, dwParam2)) {
1647             WARN("can't notify client !\n");
1648             return MMSYSERR_ERROR;
1649         }
1650         break;
1651     default:
1652         FIXME("Unknown callback message %u\n", wMsg);
1653         return MMSYSERR_INVALPARAM;
1654     }
1655     return MMSYSERR_NOERROR;
1656 }
1657
1658 /**************************************************************************
1659  *                      widGetDevCaps                           [internal]
1660  */
1661 static DWORD widGetDevCaps(WORD wDevID, LPWAVEINCAPSA lpCaps, DWORD dwSize)
1662 {
1663     TRACE("(%u, %p, %lu);\n", wDevID, lpCaps, dwSize);
1664
1665     if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
1666
1667     if (wDevID >= MAX_WAVEINDRV) {
1668         TRACE("MAX_WAVINDRV reached !\n");
1669         return MMSYSERR_BADDEVICEID;
1670     }
1671
1672     memcpy(lpCaps, &WInDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
1673     return MMSYSERR_NOERROR;
1674 }
1675
1676 /**************************************************************************
1677  *                              widRecorder                     [internal]
1678  */
1679 static  DWORD   CALLBACK        widRecorder(LPVOID pmt)
1680 {
1681     WORD                uDevID = (DWORD)pmt;
1682     WINE_WAVEIN*        wwi = (WINE_WAVEIN*)&WInDev[uDevID];
1683     WAVEHDR*            lpWaveHdr;
1684     DWORD               dwSleepTime;
1685     DWORD               bytesRead;
1686     int                 dwBufferSpace;
1687     enum win_wm_message msg;
1688     DWORD               param;
1689     HANDLE              ev;
1690
1691     SetEvent(wwi->hStartUpEvent);
1692
1693     /* make sleep time to be # of ms to record one packet */
1694     dwSleepTime = ((1 << (wwi->packetSettings & 0xFFFF)) * 1000) / wwi->format.wf.nAvgBytesPerSec;
1695     TRACE("sleeptime=%ld ms\n", dwSleepTime);
1696
1697     for(;;) {
1698         /* Oddly enough, dwBufferSpace is sometimes negative.... 
1699          * 
1700          * NOTE: If you remove this call to arts_stream_get() and
1701          * remove the && (dwBufferSpace > 0) the code will still
1702          * function correctly. I don't know which way is
1703          * faster/better.
1704          */
1705         dwBufferSpace = arts_stream_get(wwi->record_stream, ARTS_P_BUFFER_SPACE);
1706         TRACE("wwi->lpQueuePtr=(%p), wwi->state=(%d), dwBufferSpace=(%d)\n",wwi->lpQueuePtr,wwi->state,dwBufferSpace);
1707
1708         /* read all data is arts input buffer. */
1709         if ((wwi->lpQueuePtr != NULL) && (wwi->state == WINE_WS_PLAYING) && (dwBufferSpace > 0))
1710         {
1711             lpWaveHdr = wwi->lpQueuePtr;
1712                 
1713             TRACE("read as much as we can\n");
1714             while(wwi->lpQueuePtr)
1715             {
1716                 TRACE("attempt to read %ld bytes\n",lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded);
1717                 bytesRead = arts_read(wwi->record_stream,
1718                                       lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded,
1719                                       lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded);
1720                 TRACE("bytesRead=%ld\n",bytesRead);
1721                 if (bytesRead==0) break;
1722                 
1723                 lpWaveHdr->dwBytesRecorded      += bytesRead;
1724                 wwi->dwRecordedTotal            += bytesRead;
1725
1726                 /* buffer full. notify client */
1727                 if (lpWaveHdr->dwBytesRecorded >= lpWaveHdr->dwBufferLength)
1728                 {
1729                     /* must copy the value of next waveHdr, because we have no idea of what
1730                      * will be done with the content of lpWaveHdr in callback
1731                      */
1732                     LPWAVEHDR   lpNext = lpWaveHdr->lpNext;
1733
1734                     TRACE("waveHdr full.\n");
1735                     
1736                     lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1737                     lpWaveHdr->dwFlags |=  WHDR_DONE;
1738                     
1739                     widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
1740                     lpWaveHdr = wwi->lpQueuePtr = lpNext;
1741                 }
1742             }
1743         }
1744
1745         /* wait for dwSleepTime or an event in thread's queue */
1746         WaitForSingleObject(wwi->msgRing.msg_event, dwSleepTime);
1747
1748         while (ARTS_RetrieveRingMessage(&wwi->msgRing, &msg, &param, &ev))
1749         {
1750             TRACE("msg=%s param=0x%lx\n",wodPlayerCmdString[msg - WM_USER - 1], param);
1751             switch(msg) {
1752             case WINE_WM_PAUSING:
1753                 wwi->state = WINE_WS_PAUSED;
1754
1755                 /* Put code here to "pause" arts recording
1756                  */
1757
1758                 SetEvent(ev);
1759                 break;
1760             case WINE_WM_STARTING:
1761                 wwi->state = WINE_WS_PLAYING;
1762
1763                 /* Put code here to "start" arts recording
1764                  */
1765
1766                 SetEvent(ev);
1767                 break;
1768             case WINE_WM_HEADER:
1769                 lpWaveHdr = (LPWAVEHDR)param;
1770                 /* insert buffer at end of queue */
1771                 {
1772                     LPWAVEHDR* wh;
1773                     int num_headers = 0;
1774                     for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext))
1775                     {
1776                         num_headers++;
1777
1778                     }
1779                     *wh=lpWaveHdr;
1780                 }
1781                 break;
1782             case WINE_WM_STOPPING:
1783                 if (wwi->state != WINE_WS_STOPPED)
1784                 {
1785
1786                     /* Put code here to "stop" arts recording
1787                      */
1788
1789                     /* return current buffer to app */
1790                     lpWaveHdr = wwi->lpQueuePtr;
1791                     if (lpWaveHdr)
1792                     {
1793                         LPWAVEHDR lpNext = lpWaveHdr->lpNext;
1794                         TRACE("stop %p %p\n", lpWaveHdr, lpWaveHdr->lpNext);
1795                         lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1796                         lpWaveHdr->dwFlags |= WHDR_DONE;
1797                         widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
1798                         wwi->lpQueuePtr = lpNext;
1799                     }
1800                 }
1801                 wwi->state = WINE_WS_STOPPED;
1802                 SetEvent(ev);
1803                 break;
1804             case WINE_WM_RESETTING:
1805                 wwi->state = WINE_WS_STOPPED;
1806                 wwi->dwRecordedTotal = 0;
1807
1808                 /* return all buffers to the app */
1809                 for (lpWaveHdr = wwi->lpQueuePtr; lpWaveHdr; lpWaveHdr = lpWaveHdr->lpNext) {
1810                     TRACE("reset %p %p\n", lpWaveHdr, lpWaveHdr->lpNext);
1811                     lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1812                     lpWaveHdr->dwFlags |= WHDR_DONE;
1813
1814                     widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
1815                 }
1816                 wwi->lpQueuePtr = NULL; 
1817                 SetEvent(ev);
1818                 break;
1819             case WINE_WM_CLOSING:
1820                 wwi->hThread = 0;
1821                 wwi->state = WINE_WS_CLOSED;
1822                 SetEvent(ev);
1823                 ExitThread(0);
1824                 /* shouldn't go here */
1825             default:
1826                 FIXME("unknown message %d\n", msg);
1827                 break;
1828             }
1829         }
1830     }
1831     ExitThread(0);
1832     /* just for not generating compilation warnings... should never be executed */
1833     return 0;
1834 }
1835
1836 /**************************************************************************
1837  *                              widOpen                         [internal]
1838  */
1839 static DWORD widOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
1840 {
1841     WINE_WAVEIN*        wwi;
1842
1843     TRACE("(%u, %p %08lX);\n",wDevID, lpDesc, dwFlags);
1844     if (lpDesc == NULL) {
1845         WARN("Invalid Parametr (lpDesc == NULL)!\n");
1846         return MMSYSERR_INVALPARAM;
1847     }
1848
1849     if (wDevID >= MAX_WAVEINDRV) {
1850         TRACE ("MAX_WAVEINDRV reached !\n");
1851         return MMSYSERR_BADDEVICEID;
1852     }
1853
1854     /* if this device is already open tell the app that it is allocated */
1855     if(WInDev[wDevID].record_stream != (arts_stream_t*)-1)
1856     {
1857         TRACE("device already allocated\n");
1858         return MMSYSERR_ALLOCATED;
1859     }
1860
1861     /* only PCM format is support so far... */
1862     if (lpDesc->lpFormat->wFormatTag != WAVE_FORMAT_PCM ||
1863         lpDesc->lpFormat->nChannels == 0 ||
1864         lpDesc->lpFormat->nSamplesPerSec < DSBFREQUENCY_MIN ||
1865         lpDesc->lpFormat->nSamplesPerSec > DSBFREQUENCY_MAX ||
1866         (lpDesc->lpFormat->wBitsPerSample!=8 && lpDesc->lpFormat->wBitsPerSample!=16)) {
1867         WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
1868              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1869              lpDesc->lpFormat->nSamplesPerSec);
1870         return WAVERR_BADFORMAT;
1871     }
1872
1873     if (dwFlags & WAVE_FORMAT_QUERY) {
1874         TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
1875              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1876              lpDesc->lpFormat->nSamplesPerSec);
1877         return MMSYSERR_NOERROR;
1878     }
1879
1880     wwi = &WInDev[wDevID];
1881
1882     /* direct sound not supported, ignore the flag */
1883     dwFlags &= ~WAVE_DIRECTSOUND;
1884
1885     wwi->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
1886     
1887     memcpy(&wwi->waveDesc, lpDesc,           sizeof(WAVEOPENDESC));
1888     memcpy(&wwi->format,   lpDesc->lpFormat, sizeof(PCMWAVEFORMAT));
1889
1890     if (wwi->format.wBitsPerSample == 0) {
1891         WARN("Resetting zerod wBitsPerSample\n");
1892         wwi->format.wBitsPerSample = 8 *
1893             (wwi->format.wf.nAvgBytesPerSec /
1894              wwi->format.wf.nSamplesPerSec) /
1895             wwi->format.wf.nChannels;
1896     }
1897
1898     wwi->record_stream = arts_record_stream(wwi->format.wf.nSamplesPerSec,
1899                                             wwi->format.wBitsPerSample,
1900                                             wwi->format.wf.nChannels,
1901                                             "winearts");
1902     TRACE("(wwi->record_stream=%p)\n",wwi->record_stream);
1903     wwi->state = WINE_WS_STOPPED;
1904
1905     wwi->packetSettings = arts_stream_set(wwi->record_stream, ARTS_P_PACKET_SETTINGS, WAVEIN_PACKET_SETTINGS);
1906     TRACE("Tried to set ARTS_P_PACKET_SETTINGS to (%x), actually set to (%x)\n", WAVEIN_PACKET_SETTINGS, wwi->packetSettings);
1907     TRACE("Buffer size is now (%d)\n", arts_stream_get(wwi->record_stream, ARTS_P_BUFFER_SIZE));
1908
1909     if (wwi->lpQueuePtr) {
1910         WARN("Should have an empty queue (%p)\n", wwi->lpQueuePtr);
1911         wwi->lpQueuePtr = NULL;
1912     }
1913     arts_stream_set(wwi->record_stream, ARTS_P_BLOCKING, 0);    /* disable blocking on this stream */
1914
1915     if(!wwi->record_stream) return MMSYSERR_ALLOCATED;
1916
1917     wwi->dwRecordedTotal = 0;
1918     wwi->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
1919
1920     ARTS_InitRingMessage(&wwi->msgRing);
1921
1922     /* create recorder thread */
1923     if (!(dwFlags & WAVE_DIRECTSOUND)) {
1924         wwi->hStartUpEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
1925         wwi->hThread = CreateThread(NULL, 0, widRecorder, (LPVOID)(DWORD)wDevID, 0, &(wwi->dwThreadID));
1926         WaitForSingleObject(wwi->hStartUpEvent, INFINITE);
1927         CloseHandle(wwi->hStartUpEvent);
1928     } else {
1929         wwi->hThread = INVALID_HANDLE_VALUE;
1930         wwi->dwThreadID = 0;
1931     }
1932     wwi->hStartUpEvent = INVALID_HANDLE_VALUE;
1933
1934     TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%lu, nSamplesPerSec=%lu, nChannels=%u nBlockAlign=%u!\n",
1935           wwi->format.wBitsPerSample, wwi->format.wf.nAvgBytesPerSec,
1936           wwi->format.wf.nSamplesPerSec, wwi->format.wf.nChannels,
1937           wwi->format.wf.nBlockAlign);
1938     return widNotifyClient(wwi, WIM_OPEN, 0L, 0L);
1939 }
1940
1941 /**************************************************************************
1942  *                              widClose                        [internal]
1943  */
1944 static DWORD widClose(WORD wDevID)
1945 {
1946     WINE_WAVEIN*        wwi;
1947
1948     TRACE("(%u);\n", wDevID);
1949     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].state == WINE_WS_CLOSED) {
1950         WARN("can't close !\n");
1951         return MMSYSERR_INVALHANDLE;
1952     }
1953
1954     wwi = &WInDev[wDevID];
1955
1956     if (wwi->lpQueuePtr != NULL) {
1957         WARN("still buffers open !\n");
1958         return WAVERR_STILLPLAYING;
1959     }
1960
1961     ARTS_AddRingMessage(&wwi->msgRing, WINE_WM_CLOSING, 0, TRUE);
1962     ARTS_CloseWaveInDevice(wwi);
1963     wwi->state = WINE_WS_CLOSED;
1964     ARTS_DestroyRingMessage(&wwi->msgRing);
1965     return widNotifyClient(wwi, WIM_CLOSE, 0L, 0L);
1966 }
1967
1968 /**************************************************************************
1969  *                              widAddBuffer            [internal]
1970  */
1971 static DWORD widAddBuffer(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1972 {
1973     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
1974
1975     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].state == WINE_WS_CLOSED) {
1976         WARN("can't do it !\n");
1977         return MMSYSERR_INVALHANDLE;
1978     }
1979     if (!(lpWaveHdr->dwFlags & WHDR_PREPARED)) {
1980         TRACE("never been prepared !\n");
1981         return WAVERR_UNPREPARED;
1982     }
1983     if (lpWaveHdr->dwFlags & WHDR_INQUEUE) {
1984         TRACE("header already in use !\n");
1985         return WAVERR_STILLPLAYING;
1986     }
1987
1988     lpWaveHdr->dwFlags |= WHDR_INQUEUE;
1989     lpWaveHdr->dwFlags &= ~WHDR_DONE;
1990     lpWaveHdr->dwBytesRecorded = 0;
1991     lpWaveHdr->lpNext = NULL;
1992
1993     ARTS_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_HEADER, (DWORD)lpWaveHdr, FALSE);
1994     return MMSYSERR_NOERROR;
1995 }
1996
1997 /**************************************************************************
1998  *                              widPrepare                      [internal]
1999  */
2000 static DWORD widPrepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
2001 {
2002     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
2003
2004     if (wDevID >= MAX_WAVEINDRV) return MMSYSERR_INVALHANDLE;
2005
2006     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
2007         return WAVERR_STILLPLAYING;
2008
2009     lpWaveHdr->dwFlags |= WHDR_PREPARED;
2010     lpWaveHdr->dwFlags &= ~WHDR_DONE;
2011     lpWaveHdr->dwBytesRecorded = 0;
2012
2013     return MMSYSERR_NOERROR;
2014 }
2015
2016 /**************************************************************************
2017  *                              widUnprepare                    [internal]
2018  */
2019 static DWORD widUnprepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
2020 {
2021     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
2022     if (wDevID >= MAX_WAVEINDRV) {
2023         WARN("bad device ID !\n");
2024         return MMSYSERR_INVALHANDLE;
2025     }
2026
2027     if (lpWaveHdr->dwFlags & WHDR_INQUEUE) {
2028         TRACE("Still playing...\n");
2029         return WAVERR_STILLPLAYING;
2030     }
2031
2032     lpWaveHdr->dwFlags &= ~WHDR_PREPARED;
2033     lpWaveHdr->dwFlags |= WHDR_DONE;
2034
2035     return MMSYSERR_NOERROR;
2036 }
2037
2038 /**************************************************************************
2039  *                      widStart                                [internal]
2040  */
2041 static DWORD widStart(WORD wDevID)
2042 {
2043     TRACE("(%u);\n", wDevID);
2044     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].state == WINE_WS_CLOSED) {
2045         WARN("can't start recording !\n");
2046         return MMSYSERR_INVALHANDLE;
2047     }
2048
2049     ARTS_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_STARTING, 0, TRUE);
2050     return MMSYSERR_NOERROR;
2051 }
2052
2053 /**************************************************************************
2054  *                      widStop                                 [internal]
2055  */
2056 static DWORD widStop(WORD wDevID)
2057 {
2058     TRACE("(%u);\n", wDevID);
2059     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].state == WINE_WS_CLOSED) {
2060         WARN("can't stop !\n");
2061         return MMSYSERR_INVALHANDLE;
2062     }
2063
2064     ARTS_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_STOPPING, 0, TRUE);
2065
2066     return MMSYSERR_NOERROR;
2067 }
2068
2069 /**************************************************************************
2070  *                      widReset                                [internal]
2071  */
2072 static DWORD widReset(WORD wDevID)
2073 {
2074     TRACE("(%u);\n", wDevID);
2075     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].state == WINE_WS_CLOSED) {
2076         WARN("can't reset !\n");
2077         return MMSYSERR_INVALHANDLE;
2078     }
2079     ARTS_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
2080     return MMSYSERR_NOERROR;
2081 }
2082
2083 /**************************************************************************
2084  *                              widMessage (WINEARTS.6)
2085  */
2086 DWORD WINAPI ARTS_widMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
2087                             DWORD dwParam1, DWORD dwParam2)
2088 {
2089     TRACE("(%u, %04X, %08lX, %08lX, %08lX);\n",
2090           wDevID, wMsg, dwUser, dwParam1, dwParam2);
2091     switch (wMsg) {
2092     case DRVM_INIT:
2093     case DRVM_EXIT:
2094     case DRVM_ENABLE:
2095     case DRVM_DISABLE:
2096         /* FIXME: Pretend this is supported */
2097         return 0;
2098     case WIDM_OPEN:             return widOpen          (wDevID, (LPWAVEOPENDESC)dwParam1,      dwParam2);
2099     case WIDM_CLOSE:            return widClose         (wDevID);
2100     case WIDM_ADDBUFFER:        return widAddBuffer     (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2101     case WIDM_PREPARE:          return widPrepare       (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2102     case WIDM_UNPREPARE:        return widUnprepare     (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2103     case WIDM_GETDEVCAPS:       return widGetDevCaps    (wDevID, (LPWAVEINCAPSA)dwParam1,       dwParam2);
2104     case WIDM_GETNUMDEVS:       return widGetNumDevs    ();
2105     case WIDM_RESET:            return widReset         (wDevID);
2106     case WIDM_START:            return widStart         (wDevID);
2107     case WIDM_STOP:             return widStop          (wDevID);
2108     case DRV_QUERYDEVICEINTERFACESIZE: return widDevInterfaceSize       (wDevID, (LPDWORD)dwParam1);
2109     case DRV_QUERYDEVICEINTERFACE:     return widDevInterface           (wDevID, (PWCHAR)dwParam1, dwParam2);
2110     default:
2111         FIXME("unknown message %d!\n", wMsg);
2112     }
2113     return MMSYSERR_NOTSUPPORTED;
2114 }
2115
2116 /*======================================================================*
2117  *                  Low level DSOUND implementation                     *
2118  *======================================================================*/
2119 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
2120 {
2121     /* we can't perform memory mapping as we don't have a file stream
2122         interface with arts like we do with oss */
2123     MESSAGE("This sound card's driver does not support direct access\n");
2124     MESSAGE("The (slower) DirectSound HEL mode will be used instead.\n");
2125     return MMSYSERR_NOTSUPPORTED;
2126 }
2127
2128 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc)
2129 {
2130     memset(desc, 0, sizeof(*desc));
2131     strcpy(desc->szDesc, "Wine aRts DirectSound Driver");
2132     strcpy(desc->szDrvName, "winearts.drv");
2133     return MMSYSERR_NOERROR;
2134 }
2135
2136 static DWORD wodDsGuid(UINT wDevID, LPGUID pGuid)
2137 {
2138     memcpy(pGuid, &DSDEVID_DefaultPlayback, sizeof(GUID));
2139     return MMSYSERR_NOERROR;
2140 }
2141
2142 #else /* !HAVE_ARTS */
2143
2144 /**************************************************************************
2145  *                              wodMessage (WINEARTS.@)
2146  */
2147 DWORD WINAPI ARTS_wodMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2148                             DWORD dwParam1, DWORD dwParam2)
2149 {
2150     FIXME("(%u, %04X, %08lX, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2151     return MMSYSERR_NOTENABLED;
2152 }
2153
2154 /**************************************************************************
2155  *                              widMessage (WINEARTS.6)
2156  */
2157 DWORD WINAPI ARTS_widMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
2158                             DWORD dwParam1, DWORD dwParam2)
2159 {
2160     FIXME("(%u, %04X, %08lX, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2161     return MMSYSERR_NOTENABLED;
2162 }
2163
2164 #endif /* HAVE_ARTS */