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