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