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