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