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