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