server: Don't round up the header size for image mappings.
[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         if (wwo->hThread)
1212             SetThreadPriority(wwo->hThread, THREAD_PRIORITY_TIME_CRITICAL);
1213         WaitForSingleObject(wwo->hStartUpEvent, INFINITE);
1214         CloseHandle(wwo->hStartUpEvent);
1215     } else {
1216         wwo->hThread = INVALID_HANDLE_VALUE;
1217         wwo->dwThreadID = 0;
1218     }
1219     wwo->hStartUpEvent = INVALID_HANDLE_VALUE;
1220
1221     TRACE("stream=0x%lx, dwBufferSize=%ld\n",
1222           (long)wwo->play_stream, wwo->dwBufferSize);
1223
1224     TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%lu, nSamplesPerSec=%lu, nChannels=%u nBlockAlign=%u!\n",
1225           wwo->format.wBitsPerSample, wwo->format.wf.nAvgBytesPerSec,
1226           wwo->format.wf.nSamplesPerSec, wwo->format.wf.nChannels,
1227           wwo->format.wf.nBlockAlign);
1228
1229     return wodNotifyClient(wwo, WOM_OPEN, 0L, 0L);
1230 }
1231
1232 /**************************************************************************
1233  *                              wodClose                        [internal]
1234  */
1235 static DWORD wodClose(WORD wDevID)
1236 {
1237     DWORD               ret = MMSYSERR_NOERROR;
1238     WINE_WAVEOUT*       wwo;
1239
1240     TRACE("(%u);\n", wDevID);
1241
1242     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].play_stream  ==
1243         (arts_stream_t*)-1)
1244     {
1245         WARN("bad device ID !\n");
1246         return MMSYSERR_BADDEVICEID;
1247     }
1248
1249     wwo = &WOutDev[wDevID];
1250     if (wwo->lpQueuePtr) {
1251         WARN("buffers still playing !\n");
1252         ret = WAVERR_STILLPLAYING;
1253     } else {
1254         TRACE("imhere[3-close]\n");
1255         if (wwo->hThread != INVALID_HANDLE_VALUE) {
1256             ARTS_AddRingMessage(&wwo->msgRing, WINE_WM_CLOSING, 0, TRUE);
1257         }
1258
1259         ARTS_DestroyRingMessage(&wwo->msgRing);
1260
1261         ARTS_CloseWaveOutDevice(wwo);   /* close the stream and clean things up */
1262
1263         ret = wodNotifyClient(wwo, WOM_CLOSE, 0L, 0L);
1264     }
1265     return ret;
1266 }
1267
1268 /**************************************************************************
1269  *                              wodWrite                        [internal]
1270  *
1271  */
1272 static DWORD wodWrite(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1273 {
1274     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
1275
1276     /* first, do the sanity checks... */
1277     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].play_stream ==
1278                 (arts_stream_t*)-1)
1279     {
1280         WARN("bad dev ID !\n");
1281         return MMSYSERR_BADDEVICEID;
1282     }
1283
1284     if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
1285     {
1286         TRACE("unprepared\n");
1287         return WAVERR_UNPREPARED;
1288     }
1289
1290     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1291     {
1292         TRACE("still playing\n");
1293         return WAVERR_STILLPLAYING;
1294     }
1295
1296     lpWaveHdr->dwFlags &= ~WHDR_DONE;
1297     lpWaveHdr->dwFlags |= WHDR_INQUEUE;
1298     lpWaveHdr->lpNext = 0;
1299
1300     TRACE("adding ring message\n");
1301     ARTS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_HEADER, (DWORD)lpWaveHdr, FALSE);
1302
1303     return MMSYSERR_NOERROR;
1304 }
1305
1306 /**************************************************************************
1307  *                      wodPause                                [internal]
1308  */
1309 static DWORD wodPause(WORD wDevID)
1310 {
1311     TRACE("(%u);!\n", wDevID);
1312
1313     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].play_stream ==
1314                 (arts_stream_t*)-1)
1315     {
1316         WARN("bad device ID !\n");
1317         return MMSYSERR_BADDEVICEID;
1318     }
1319
1320     TRACE("imhere[3-PAUSING]\n");
1321     ARTS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_PAUSING, 0, TRUE);
1322
1323     return MMSYSERR_NOERROR;
1324 }
1325
1326 /**************************************************************************
1327  *                      wodRestart                              [internal]
1328  */
1329 static DWORD wodRestart(WORD wDevID)
1330 {
1331     TRACE("(%u);\n", wDevID);
1332
1333     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].play_stream ==
1334                 (arts_stream_t*)-1)
1335     {
1336         WARN("bad device ID !\n");
1337         return MMSYSERR_BADDEVICEID;
1338     }
1339
1340     if (WOutDev[wDevID].state == WINE_WS_PAUSED) {
1341         TRACE("imhere[3-RESTARTING]\n");
1342         ARTS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESTARTING, 0, TRUE);
1343     }
1344
1345     /* FIXME: is NotifyClient with WOM_DONE right ? (Comet Busters 1.3.3 needs this notification) */
1346     /* FIXME: Myst crashes with this ... hmm -MM
1347        return wodNotifyClient(wwo, WOM_DONE, 0L, 0L);
1348     */
1349
1350     return MMSYSERR_NOERROR;
1351 }
1352
1353 /**************************************************************************
1354  *                      wodReset                                [internal]
1355  */
1356 static DWORD wodReset(WORD wDevID)
1357 {
1358     TRACE("(%u);\n", wDevID);
1359
1360     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].play_stream ==
1361         (arts_stream_t*)-1)
1362     {
1363         WARN("bad device ID !\n");
1364         return MMSYSERR_BADDEVICEID;
1365     }
1366
1367     TRACE("imhere[3-RESET]\n");
1368     ARTS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
1369
1370     return MMSYSERR_NOERROR;
1371 }
1372
1373 /**************************************************************************
1374  *                              wodGetPosition                  [internal]
1375  */
1376 static DWORD wodGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
1377 {
1378     WINE_WAVEOUT*       wwo;
1379
1380     TRACE("(%u, %p, %lu);\n", wDevID, lpTime, uSize);
1381
1382     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].play_stream ==
1383         (arts_stream_t*)-1)
1384     {
1385         WARN("bad device ID !\n");
1386         return MMSYSERR_BADDEVICEID;
1387     }
1388
1389     if (lpTime == NULL) return MMSYSERR_INVALPARAM;
1390
1391     wwo = &WOutDev[wDevID];
1392     ARTS_AddRingMessage(&wwo->msgRing, WINE_WM_UPDATE, 0, TRUE);
1393
1394     return bytes_to_mmtime(lpTime, wwo->dwPlayedTotal, &wwo->format);
1395 }
1396
1397 /**************************************************************************
1398  *                              wodBreakLoop                    [internal]
1399  */
1400 static DWORD wodBreakLoop(WORD wDevID)
1401 {
1402     TRACE("(%u);\n", wDevID);
1403
1404     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].play_stream ==
1405                 (arts_stream_t*)-1)
1406     {
1407         WARN("bad device ID !\n");
1408         return MMSYSERR_BADDEVICEID;
1409     }
1410     ARTS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_BREAKLOOP, 0, TRUE);
1411     return MMSYSERR_NOERROR;
1412 }
1413
1414 /**************************************************************************
1415  *                              wodGetVolume                    [internal]
1416  */
1417 static DWORD wodGetVolume(WORD wDevID, LPDWORD lpdwVol)
1418 {
1419     DWORD left, right;
1420
1421     left = WOutDev[wDevID].volume_left;
1422     right = WOutDev[wDevID].volume_right;
1423
1424     TRACE("(%u, %p);\n", wDevID, lpdwVol);
1425
1426     *lpdwVol = ((left * 0xFFFFl) / 100) + (((right * 0xFFFFl) / 100) <<
1427                 16);
1428
1429     return MMSYSERR_NOERROR;
1430 }
1431
1432 /**************************************************************************
1433  *                              wodSetVolume                    [internal]
1434  */
1435 static DWORD wodSetVolume(WORD wDevID, DWORD dwParam)
1436 {
1437     DWORD left, right;
1438
1439     left  = (LOWORD(dwParam) * 100) / 0xFFFFl;
1440     right = (HIWORD(dwParam) * 100) / 0xFFFFl;
1441
1442     TRACE("(%u, %08lX);\n", wDevID, dwParam);
1443
1444     WOutDev[wDevID].volume_left = left;
1445     WOutDev[wDevID].volume_right = right;
1446
1447     return MMSYSERR_NOERROR;
1448 }
1449
1450 /**************************************************************************
1451  *                              wodGetNumDevs                   [internal]
1452  */
1453 static  DWORD   wodGetNumDevs(void)
1454 {
1455     return MAX_WAVEOUTDRV;
1456 }
1457
1458 /**************************************************************************
1459  *                              wodDevInterfaceSize             [internal]
1460  */
1461 static DWORD wodDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
1462 {
1463     TRACE("(%u, %p)\n", wDevID, dwParam1);
1464                                                                                                        
1465     *dwParam1 = MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].interface_name, -1,
1466                                     NULL, 0 ) * sizeof(WCHAR);
1467     return MMSYSERR_NOERROR;
1468 }
1469                                                                                                        
1470 /**************************************************************************
1471  *                              wodDevInterface                 [internal]
1472  */
1473 static DWORD wodDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
1474 {
1475     if (dwParam2 >= MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].interface_name, -1,
1476                                         NULL, 0 ) * sizeof(WCHAR))
1477     {
1478         MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].interface_name, -1,
1479                             dwParam1, dwParam2 / sizeof(WCHAR));
1480         return MMSYSERR_NOERROR;
1481     }
1482     return MMSYSERR_INVALPARAM;
1483 }
1484                                                                                                        
1485 /**************************************************************************
1486  *                              wodMessage (WINEARTS.@)
1487  */
1488 DWORD WINAPI ARTS_wodMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
1489                             DWORD dwParam1, DWORD dwParam2)
1490 {
1491     TRACE("(%u, %04X, %08lX, %08lX, %08lX);\n",
1492           wDevID, wMsg, dwUser, dwParam1, dwParam2);
1493
1494     switch (wMsg) {
1495     case DRVM_INIT:
1496     case DRVM_EXIT:
1497     case DRVM_ENABLE:
1498     case DRVM_DISABLE:
1499         /* FIXME: Pretend this is supported */
1500         return 0;
1501     case WODM_OPEN:             return wodOpen          (wDevID, (LPWAVEOPENDESC)dwParam1,      dwParam2);
1502     case WODM_CLOSE:            return wodClose         (wDevID);
1503     case WODM_WRITE:            return wodWrite         (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
1504     case WODM_PAUSE:            return wodPause         (wDevID);
1505     case WODM_GETPOS:           return wodGetPosition   (wDevID, (LPMMTIME)dwParam1,            dwParam2);
1506     case WODM_BREAKLOOP:        return wodBreakLoop     (wDevID);
1507     case WODM_PREPARE:          return MMSYSERR_NOTSUPPORTED;
1508     case WODM_UNPREPARE:        return MMSYSERR_NOTSUPPORTED;
1509     case WODM_GETDEVCAPS:       return wodGetDevCaps    (wDevID, (LPWAVEOUTCAPSW)dwParam1,      dwParam2);
1510     case WODM_GETNUMDEVS:       return wodGetNumDevs    ();
1511     case WODM_GETPITCH:         return MMSYSERR_NOTSUPPORTED;
1512     case WODM_SETPITCH:         return MMSYSERR_NOTSUPPORTED;
1513     case WODM_GETPLAYBACKRATE:  return MMSYSERR_NOTSUPPORTED;
1514     case WODM_SETPLAYBACKRATE:  return MMSYSERR_NOTSUPPORTED;
1515     case WODM_GETVOLUME:        return wodGetVolume     (wDevID, (LPDWORD)dwParam1);
1516     case WODM_SETVOLUME:        return wodSetVolume     (wDevID, dwParam1);
1517     case WODM_RESTART:          return wodRestart       (wDevID);
1518     case WODM_RESET:            return wodReset         (wDevID);
1519
1520     case DRV_QUERYDEVICEINTERFACESIZE: return wodDevInterfaceSize       (wDevID, (LPDWORD)dwParam1);
1521     case DRV_QUERYDEVICEINTERFACE:     return wodDevInterface           (wDevID, (PWCHAR)dwParam1, dwParam2);
1522     case DRV_QUERYDSOUNDIFACE:  return wodDsCreate      (wDevID, (PIDSDRIVER*)dwParam1);
1523     case DRV_QUERYDSOUNDDESC:   return wodDsDesc        (wDevID, (PDSDRIVERDESC)dwParam1);
1524     default:
1525         FIXME("unknown message %d!\n", wMsg);
1526     }
1527     return MMSYSERR_NOTSUPPORTED;
1528 }
1529
1530 /*======================================================================*
1531  *                  Low level WAVE IN implementation                    *
1532  *======================================================================*/
1533
1534 /**************************************************************************
1535  *                              widGetNumDevs                   [internal]
1536  */
1537 static  DWORD   widGetNumDevs(void)
1538 {
1539     TRACE("%d\n", MAX_WAVEINDRV);
1540     return MAX_WAVEINDRV;
1541 }
1542
1543 /**************************************************************************
1544  *                              widDevInterfaceSize             [internal]
1545  */
1546 static DWORD widDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
1547 {
1548     TRACE("(%u, %p)\n", wDevID, dwParam1);
1549                                                                                                        
1550                                                                                                        
1551     *dwParam1 = MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
1552                                     NULL, 0 ) * sizeof(WCHAR);
1553     return MMSYSERR_NOERROR;
1554 }
1555
1556 /**************************************************************************
1557  *                              widDevInterface                 [internal]
1558  */
1559 static DWORD widDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
1560 {
1561     if (dwParam2 >= MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
1562                                         NULL, 0 ) * sizeof(WCHAR))
1563     {
1564         MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
1565                             dwParam1, dwParam2 / sizeof(WCHAR));
1566         return MMSYSERR_NOERROR;
1567     }
1568     return MMSYSERR_INVALPARAM;
1569 }
1570
1571 /**************************************************************************
1572  *                      widNotifyClient                 [internal]
1573  */
1574 static DWORD widNotifyClient(WINE_WAVEIN* wwi, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
1575 {
1576     TRACE("wMsg = 0x%04x dwParm1 = %04lX dwParam2 = %04lX\n", wMsg, dwParam1, dwParam2);
1577
1578     switch (wMsg) {
1579     case WIM_OPEN:
1580     case WIM_CLOSE:
1581     case WIM_DATA:
1582         if (wwi->wFlags != DCB_NULL &&
1583             !DriverCallback(wwi->waveDesc.dwCallback, wwi->wFlags,
1584                             (HDRVR)wwi->waveDesc.hWave, wMsg,
1585                             wwi->waveDesc.dwInstance, dwParam1, dwParam2)) {
1586             WARN("can't notify client !\n");
1587             return MMSYSERR_ERROR;
1588         }
1589         break;
1590     default:
1591         FIXME("Unknown callback message %u\n", wMsg);
1592         return MMSYSERR_INVALPARAM;
1593     }
1594     return MMSYSERR_NOERROR;
1595 }
1596
1597 /**************************************************************************
1598  *                      widGetDevCaps                           [internal]
1599  */
1600 static DWORD widGetDevCaps(WORD wDevID, LPWAVEINCAPSW lpCaps, DWORD dwSize)
1601 {
1602     TRACE("(%u, %p, %lu);\n", wDevID, lpCaps, dwSize);
1603
1604     if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
1605
1606     if (wDevID >= MAX_WAVEINDRV) {
1607         TRACE("MAX_WAVINDRV reached !\n");
1608         return MMSYSERR_BADDEVICEID;
1609     }
1610
1611     memcpy(lpCaps, &WInDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
1612     return MMSYSERR_NOERROR;
1613 }
1614
1615 /**************************************************************************
1616  *                              widRecorder                     [internal]
1617  */
1618 static  DWORD   CALLBACK        widRecorder(LPVOID pmt)
1619 {
1620     WORD                uDevID = (DWORD)pmt;
1621     WINE_WAVEIN*        wwi = (WINE_WAVEIN*)&WInDev[uDevID];
1622     WAVEHDR*            lpWaveHdr;
1623     DWORD               dwSleepTime;
1624     DWORD               bytesRead;
1625     int                 dwBufferSpace;
1626     enum win_wm_message msg;
1627     DWORD               param;
1628     HANDLE              ev;
1629
1630     SetEvent(wwi->hStartUpEvent);
1631
1632     /* make sleep time to be # of ms to record one packet */
1633     dwSleepTime = ((1 << (wwi->packetSettings & 0xFFFF)) * 1000) / wwi->format.wf.nAvgBytesPerSec;
1634     TRACE("sleeptime=%ld ms\n", dwSleepTime);
1635
1636     for(;;) {
1637         /* Oddly enough, dwBufferSpace is sometimes negative.... 
1638          * 
1639          * NOTE: If you remove this call to arts_stream_get() and
1640          * remove the && (dwBufferSpace > 0) the code will still
1641          * function correctly. I don't know which way is
1642          * faster/better.
1643          */
1644         dwBufferSpace = arts_stream_get(wwi->record_stream, ARTS_P_BUFFER_SPACE);
1645         TRACE("wwi->lpQueuePtr=(%p), wwi->state=(%d), dwBufferSpace=(%d)\n",wwi->lpQueuePtr,wwi->state,dwBufferSpace);
1646
1647         /* read all data is arts input buffer. */
1648         if ((wwi->lpQueuePtr != NULL) && (wwi->state == WINE_WS_PLAYING) && (dwBufferSpace > 0))
1649         {
1650             lpWaveHdr = wwi->lpQueuePtr;
1651                 
1652             TRACE("read as much as we can\n");
1653             while(wwi->lpQueuePtr)
1654             {
1655                 TRACE("attempt to read %ld bytes\n",lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded);
1656                 bytesRead = arts_read(wwi->record_stream,
1657                                       lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded,
1658                                       lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded);
1659                 TRACE("bytesRead=%ld\n",bytesRead);
1660                 if (bytesRead==0) break;
1661                 
1662                 lpWaveHdr->dwBytesRecorded      += bytesRead;
1663                 wwi->dwRecordedTotal            += bytesRead;
1664
1665                 /* buffer full. notify client */
1666                 if (lpWaveHdr->dwBytesRecorded >= lpWaveHdr->dwBufferLength)
1667                 {
1668                     /* must copy the value of next waveHdr, because we have no idea of what
1669                      * will be done with the content of lpWaveHdr in callback
1670                      */
1671                     LPWAVEHDR   lpNext = lpWaveHdr->lpNext;
1672
1673                     TRACE("waveHdr full.\n");
1674                     
1675                     lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1676                     lpWaveHdr->dwFlags |=  WHDR_DONE;
1677                     
1678                     widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
1679                     lpWaveHdr = wwi->lpQueuePtr = lpNext;
1680                 }
1681             }
1682         }
1683
1684         /* wait for dwSleepTime or an event in thread's queue */
1685         WaitForSingleObject(wwi->msgRing.msg_event, dwSleepTime);
1686
1687         while (ARTS_RetrieveRingMessage(&wwi->msgRing, &msg, &param, &ev))
1688         {
1689             TRACE("msg=%s param=0x%lx\n",wodPlayerCmdString[msg - WM_USER - 1], param);
1690             switch(msg) {
1691             case WINE_WM_PAUSING:
1692                 wwi->state = WINE_WS_PAUSED;
1693
1694                 /* Put code here to "pause" arts recording
1695                  */
1696
1697                 SetEvent(ev);
1698                 break;
1699             case WINE_WM_STARTING:
1700                 wwi->state = WINE_WS_PLAYING;
1701
1702                 /* Put code here to "start" arts recording
1703                  */
1704
1705                 SetEvent(ev);
1706                 break;
1707             case WINE_WM_HEADER:
1708                 lpWaveHdr = (LPWAVEHDR)param;
1709                 /* insert buffer at end of queue */
1710                 {
1711                     LPWAVEHDR* wh;
1712                     int num_headers = 0;
1713                     for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext))
1714                     {
1715                         num_headers++;
1716
1717                     }
1718                     *wh=lpWaveHdr;
1719                 }
1720                 break;
1721             case WINE_WM_STOPPING:
1722                 if (wwi->state != WINE_WS_STOPPED)
1723                 {
1724
1725                     /* Put code here to "stop" arts recording
1726                      */
1727
1728                     /* return current buffer to app */
1729                     lpWaveHdr = wwi->lpQueuePtr;
1730                     if (lpWaveHdr)
1731                     {
1732                         LPWAVEHDR lpNext = lpWaveHdr->lpNext;
1733                         TRACE("stop %p %p\n", lpWaveHdr, lpWaveHdr->lpNext);
1734                         lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1735                         lpWaveHdr->dwFlags |= WHDR_DONE;
1736                         widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
1737                         wwi->lpQueuePtr = lpNext;
1738                     }
1739                 }
1740                 wwi->state = WINE_WS_STOPPED;
1741                 SetEvent(ev);
1742                 break;
1743             case WINE_WM_RESETTING:
1744                 wwi->state = WINE_WS_STOPPED;
1745                 wwi->dwRecordedTotal = 0;
1746
1747                 /* return all buffers to the app */
1748                 for (lpWaveHdr = wwi->lpQueuePtr; lpWaveHdr; lpWaveHdr = lpWaveHdr->lpNext) {
1749                     TRACE("reset %p %p\n", lpWaveHdr, lpWaveHdr->lpNext);
1750                     lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1751                     lpWaveHdr->dwFlags |= WHDR_DONE;
1752
1753                     widNotifyClient(wwi, WIM_DATA, (DWORD)lpWaveHdr, 0);
1754                 }
1755                 wwi->lpQueuePtr = NULL; 
1756                 SetEvent(ev);
1757                 break;
1758             case WINE_WM_CLOSING:
1759                 wwi->hThread = 0;
1760                 wwi->state = WINE_WS_CLOSED;
1761                 SetEvent(ev);
1762                 ExitThread(0);
1763                 /* shouldn't go here */
1764             default:
1765                 FIXME("unknown message %d\n", msg);
1766                 break;
1767             }
1768         }
1769     }
1770     ExitThread(0);
1771     /* just for not generating compilation warnings... should never be executed */
1772     return 0;
1773 }
1774
1775 /**************************************************************************
1776  *                              widOpen                         [internal]
1777  */
1778 static DWORD widOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
1779 {
1780     WINE_WAVEIN*        wwi;
1781
1782     TRACE("(%u, %p %08lX);\n",wDevID, lpDesc, dwFlags);
1783     if (lpDesc == NULL) {
1784         WARN("Invalid Parametr (lpDesc == NULL)!\n");
1785         return MMSYSERR_INVALPARAM;
1786     }
1787
1788     if (wDevID >= MAX_WAVEINDRV) {
1789         TRACE ("MAX_WAVEINDRV reached !\n");
1790         return MMSYSERR_BADDEVICEID;
1791     }
1792
1793     /* if this device is already open tell the app that it is allocated */
1794     if(WInDev[wDevID].record_stream != (arts_stream_t*)-1)
1795     {
1796         TRACE("device already allocated\n");
1797         return MMSYSERR_ALLOCATED;
1798     }
1799
1800     /* only PCM format is support so far... */
1801     if (lpDesc->lpFormat->wFormatTag != WAVE_FORMAT_PCM ||
1802         lpDesc->lpFormat->nChannels == 0 ||
1803         lpDesc->lpFormat->nSamplesPerSec < DSBFREQUENCY_MIN ||
1804         lpDesc->lpFormat->nSamplesPerSec > DSBFREQUENCY_MAX ||
1805         (lpDesc->lpFormat->wBitsPerSample!=8 && lpDesc->lpFormat->wBitsPerSample!=16)) {
1806         WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
1807              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1808              lpDesc->lpFormat->nSamplesPerSec);
1809         return WAVERR_BADFORMAT;
1810     }
1811
1812     if (dwFlags & WAVE_FORMAT_QUERY) {
1813         TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
1814              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1815              lpDesc->lpFormat->nSamplesPerSec);
1816         return MMSYSERR_NOERROR;
1817     }
1818
1819     wwi = &WInDev[wDevID];
1820
1821     /* direct sound not supported, ignore the flag */
1822     dwFlags &= ~WAVE_DIRECTSOUND;
1823
1824     wwi->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
1825     
1826     memcpy(&wwi->waveDesc, lpDesc,           sizeof(WAVEOPENDESC));
1827     memcpy(&wwi->format,   lpDesc->lpFormat, sizeof(PCMWAVEFORMAT));
1828
1829     if (wwi->format.wBitsPerSample == 0) {
1830         WARN("Resetting zerod wBitsPerSample\n");
1831         wwi->format.wBitsPerSample = 8 *
1832             (wwi->format.wf.nAvgBytesPerSec /
1833              wwi->format.wf.nSamplesPerSec) /
1834             wwi->format.wf.nChannels;
1835     }
1836
1837     wwi->record_stream = arts_record_stream(wwi->format.wf.nSamplesPerSec,
1838                                             wwi->format.wBitsPerSample,
1839                                             wwi->format.wf.nChannels,
1840                                             "winearts");
1841     TRACE("(wwi->record_stream=%p)\n",wwi->record_stream);
1842     wwi->state = WINE_WS_STOPPED;
1843
1844     wwi->packetSettings = arts_stream_set(wwi->record_stream, ARTS_P_PACKET_SETTINGS, WAVEIN_PACKET_SETTINGS);
1845     TRACE("Tried to set ARTS_P_PACKET_SETTINGS to (%x), actually set to (%x)\n", WAVEIN_PACKET_SETTINGS, wwi->packetSettings);
1846     TRACE("Buffer size is now (%d)\n", arts_stream_get(wwi->record_stream, ARTS_P_BUFFER_SIZE));
1847
1848     if (wwi->lpQueuePtr) {
1849         WARN("Should have an empty queue (%p)\n", wwi->lpQueuePtr);
1850         wwi->lpQueuePtr = NULL;
1851     }
1852     arts_stream_set(wwi->record_stream, ARTS_P_BLOCKING, 0);    /* disable blocking on this stream */
1853
1854     if(!wwi->record_stream) return MMSYSERR_ALLOCATED;
1855
1856     wwi->dwRecordedTotal = 0;
1857     wwi->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
1858
1859     ARTS_InitRingMessage(&wwi->msgRing);
1860
1861     /* create recorder thread */
1862     if (!(dwFlags & WAVE_DIRECTSOUND)) {
1863         wwi->hStartUpEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
1864         wwi->hThread = CreateThread(NULL, 0, widRecorder, (LPVOID)(DWORD)wDevID, 0, &(wwi->dwThreadID));
1865         if (wwi->hThread)
1866             SetThreadPriority(wwi->hThread, THREAD_PRIORITY_TIME_CRITICAL);
1867         WaitForSingleObject(wwi->hStartUpEvent, INFINITE);
1868         CloseHandle(wwi->hStartUpEvent);
1869     } else {
1870         wwi->hThread = INVALID_HANDLE_VALUE;
1871         wwi->dwThreadID = 0;
1872     }
1873     wwi->hStartUpEvent = INVALID_HANDLE_VALUE;
1874
1875     TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%lu, nSamplesPerSec=%lu, nChannels=%u nBlockAlign=%u!\n",
1876           wwi->format.wBitsPerSample, wwi->format.wf.nAvgBytesPerSec,
1877           wwi->format.wf.nSamplesPerSec, wwi->format.wf.nChannels,
1878           wwi->format.wf.nBlockAlign);
1879     return widNotifyClient(wwi, WIM_OPEN, 0L, 0L);
1880 }
1881
1882 /**************************************************************************
1883  *                              widClose                        [internal]
1884  */
1885 static DWORD widClose(WORD wDevID)
1886 {
1887     WINE_WAVEIN*        wwi;
1888
1889     TRACE("(%u);\n", wDevID);
1890     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].state == WINE_WS_CLOSED) {
1891         WARN("can't close !\n");
1892         return MMSYSERR_INVALHANDLE;
1893     }
1894
1895     wwi = &WInDev[wDevID];
1896
1897     if (wwi->lpQueuePtr != NULL) {
1898         WARN("still buffers open !\n");
1899         return WAVERR_STILLPLAYING;
1900     }
1901
1902     ARTS_AddRingMessage(&wwi->msgRing, WINE_WM_CLOSING, 0, TRUE);
1903     ARTS_CloseWaveInDevice(wwi);
1904     wwi->state = WINE_WS_CLOSED;
1905     ARTS_DestroyRingMessage(&wwi->msgRing);
1906     return widNotifyClient(wwi, WIM_CLOSE, 0L, 0L);
1907 }
1908
1909 /**************************************************************************
1910  *                              widAddBuffer            [internal]
1911  */
1912 static DWORD widAddBuffer(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1913 {
1914     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
1915
1916     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].state == WINE_WS_CLOSED) {
1917         WARN("can't do it !\n");
1918         return MMSYSERR_INVALHANDLE;
1919     }
1920     if (!(lpWaveHdr->dwFlags & WHDR_PREPARED)) {
1921         TRACE("never been prepared !\n");
1922         return WAVERR_UNPREPARED;
1923     }
1924     if (lpWaveHdr->dwFlags & WHDR_INQUEUE) {
1925         TRACE("header already in use !\n");
1926         return WAVERR_STILLPLAYING;
1927     }
1928
1929     lpWaveHdr->dwFlags |= WHDR_INQUEUE;
1930     lpWaveHdr->dwFlags &= ~WHDR_DONE;
1931     lpWaveHdr->dwBytesRecorded = 0;
1932     lpWaveHdr->lpNext = NULL;
1933
1934     ARTS_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_HEADER, (DWORD)lpWaveHdr, FALSE);
1935     return MMSYSERR_NOERROR;
1936 }
1937
1938 /**************************************************************************
1939  *                      widStart                                [internal]
1940  */
1941 static DWORD widStart(WORD wDevID)
1942 {
1943     TRACE("(%u);\n", wDevID);
1944     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].state == WINE_WS_CLOSED) {
1945         WARN("can't start recording !\n");
1946         return MMSYSERR_INVALHANDLE;
1947     }
1948
1949     ARTS_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_STARTING, 0, TRUE);
1950     return MMSYSERR_NOERROR;
1951 }
1952
1953 /**************************************************************************
1954  *                      widStop                                 [internal]
1955  */
1956 static DWORD widStop(WORD wDevID)
1957 {
1958     TRACE("(%u);\n", wDevID);
1959     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].state == WINE_WS_CLOSED) {
1960         WARN("can't stop !\n");
1961         return MMSYSERR_INVALHANDLE;
1962     }
1963
1964     ARTS_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_STOPPING, 0, TRUE);
1965
1966     return MMSYSERR_NOERROR;
1967 }
1968
1969 /**************************************************************************
1970  *                      widReset                                [internal]
1971  */
1972 static DWORD widReset(WORD wDevID)
1973 {
1974     TRACE("(%u);\n", wDevID);
1975     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].state == WINE_WS_CLOSED) {
1976         WARN("can't reset !\n");
1977         return MMSYSERR_INVALHANDLE;
1978     }
1979     ARTS_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
1980     return MMSYSERR_NOERROR;
1981 }
1982
1983 /**************************************************************************
1984  *                              widMessage (WINEARTS.6)
1985  */
1986 DWORD WINAPI ARTS_widMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
1987                             DWORD dwParam1, DWORD dwParam2)
1988 {
1989     TRACE("(%u, %04X, %08lX, %08lX, %08lX);\n",
1990           wDevID, wMsg, dwUser, dwParam1, dwParam2);
1991     switch (wMsg) {
1992     case DRVM_INIT:
1993     case DRVM_EXIT:
1994     case DRVM_ENABLE:
1995     case DRVM_DISABLE:
1996         /* FIXME: Pretend this is supported */
1997         return 0;
1998     case WIDM_OPEN:             return widOpen          (wDevID, (LPWAVEOPENDESC)dwParam1,      dwParam2);
1999     case WIDM_CLOSE:            return widClose         (wDevID);
2000     case WIDM_ADDBUFFER:        return widAddBuffer     (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2001     case WIDM_PREPARE:          return MMSYSERR_NOTSUPPORTED;
2002     case WIDM_UNPREPARE:        return MMSYSERR_NOTSUPPORTED;
2003     case WIDM_GETDEVCAPS:       return widGetDevCaps    (wDevID, (LPWAVEINCAPSW)dwParam1,       dwParam2);
2004     case WIDM_GETNUMDEVS:       return widGetNumDevs    ();
2005     case WIDM_RESET:            return widReset         (wDevID);
2006     case WIDM_START:            return widStart         (wDevID);
2007     case WIDM_STOP:             return widStop          (wDevID);
2008     case DRV_QUERYDEVICEINTERFACESIZE: return widDevInterfaceSize       (wDevID, (LPDWORD)dwParam1);
2009     case DRV_QUERYDEVICEINTERFACE:     return widDevInterface           (wDevID, (PWCHAR)dwParam1, dwParam2);
2010     default:
2011         FIXME("unknown message %d!\n", wMsg);
2012     }
2013     return MMSYSERR_NOTSUPPORTED;
2014 }
2015
2016 /*======================================================================*
2017  *                  Low level DSOUND implementation                     *
2018  *======================================================================*/
2019 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
2020 {
2021     /* we can't perform memory mapping as we don't have a file stream
2022         interface with arts like we do with oss */
2023     MESSAGE("This sound card's driver does not support direct access\n");
2024     MESSAGE("The (slower) DirectSound HEL mode will be used instead.\n");
2025     return MMSYSERR_NOTSUPPORTED;
2026 }
2027
2028 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc)
2029 {
2030     memset(desc, 0, sizeof(*desc));
2031     strcpy(desc->szDesc, "Wine aRts DirectSound Driver");
2032     strcpy(desc->szDrvname, "winearts.drv");
2033     return MMSYSERR_NOERROR;
2034 }
2035
2036 #else /* !HAVE_ARTS */
2037
2038 /**************************************************************************
2039  *                              wodMessage (WINEARTS.@)
2040  */
2041 DWORD WINAPI ARTS_wodMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2042                             DWORD dwParam1, DWORD dwParam2)
2043 {
2044     FIXME("(%u, %04X, %08lX, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2045     return MMSYSERR_NOTENABLED;
2046 }
2047
2048 /**************************************************************************
2049  *                              widMessage (WINEARTS.6)
2050  */
2051 DWORD WINAPI ARTS_widMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
2052                             DWORD dwParam1, DWORD dwParam2)
2053 {
2054     FIXME("(%u, %04X, %08lX, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2055     return MMSYSERR_NOTENABLED;
2056 }
2057
2058 #endif /* HAVE_ARTS */