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