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