~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~ [ freetext search ] ~ [ file search ] ~

Wine Cross Reference
wine/dlls/wineesd.drv/audio.c

Version: ~ [ wine-1.1.33 ] ~ [ wine-1.1.32 ] ~ [ wine-1.1.31 ] ~ [ wine-1.1.30 ] ~ [ wine-1.1.29 ] ~ [ wine-1.1.28 ] ~ [ wine-1.1.27 ] ~ [ wine-1.1.26 ] ~ [ wine-1.1.25 ] ~ [ wine-1.1.24 ] ~ [ wine-1.1.23 ] ~ [ wine-1.1.22 ] ~ [ wine-1.1.21 ] ~ [ wine-1.1.20 ] ~ [ wine-1.1.19 ] ~ [ wine-1.1.18 ] ~ [ wine-1.1.17 ] ~ [ wine-1.1.16 ] ~ [ wine-1.1.15 ] ~ [ wine-1.1.14 ] ~ [ wine-1.1.13 ] ~ [ wine-1.1.12 ] ~ [ wine-1.1.11 ] ~ [ wine-1.1.10 ] ~ [ wine-1.1.9 ] ~ [ wine-1.1.8 ] ~ [ wine-1.1.7 ] ~ [ wine-1.0.1 ] ~ [ wine-1.1.6 ] ~ [ wine-1.1.5 ] ~ [ wine-1.1.4 ] ~ [ wine-1.1.3 ] ~ [ wine-1.1.2 ] ~ [ wine-1.1.1 ] ~ [ wine-1.1.0 ] ~ [ wine-1.0 ] ~

  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 WINE_WAVEOUT     WOutDev   [MAX_WAVEOUTDRV];
218 static WINE_WAVEIN      WInDev    [MAX_WAVEINDRV];
219 
220 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv);
221 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc);
222 
223 /* These strings used only for tracing */
224 static const char *wodPlayerCmdString[] = {
225     "WINE_WM_PAUSING",
226     "WINE_WM_RESTARTING",
227     "WINE_WM_RESETTING",
228     "WINE_WM_HEADER",
229     "WINE_WM_UPDATE",
230     "WINE_WM_BREAKLOOP",
231     "WINE_WM_CLOSING",
232     "WINE_WM_STARTING",
233     "WINE_WM_STOPPING",
234 };
235 
236 /*======================================================================*
237  *                  Low level WAVE implementation                       *
238  *======================================================================*/
239 
240 /* Volume functions derived from Alsaplayer source */
241 /* length is the number of 16 bit samples */
242 static void volume_effect16(void *bufin, void* bufout, int length, int left,
243                 int right, int  nChannels)
244 {
245   short *d_out = bufout;
246   short *d_in = bufin;
247   int i, v;
248 
249 /*
250   TRACE("length == %d, nChannels == %d\n", length, nChannels);
251 */
252 
253   if (right == -1) right = left;
254 
255   for(i = 0; i < length; i+=(nChannels))
256   {
257     v = (int) ((*(d_in++) * left) / 100);
258     *(d_out++) = (v>32767) ? 32767 : ((v<-32768) ? -32768 : v);
259     if(nChannels == 2)
260     {
261       v = (int) ((*(d_in++) * right) / 100);
262       *(d_out++) = (v>32767) ? 32767 : ((v<-32768) ? -32768 : v);
263     }
264   }
265 }
266 
267 /* length is the number of 8 bit samples */
268 static void volume_effect8(void *bufin, void* bufout, int length, int left,
269                 int right, int  nChannels)
270 {
271   BYTE *d_out = bufout;
272   BYTE *d_in = bufin;
273   int i, v;
274 
275 /*
276   TRACE("length == %d, nChannels == %d\n", length, nChannels);
277 */
278 
279   if (right == -1) right = left;
280 
281   for(i = 0; i < length; i+=(nChannels))
282   {
283     v = (BYTE) ((*(d_in++) * left) / 100);
284     *(d_out++) = (v>255) ? 255 : ((v<0) ? 0 : v);
285     if(nChannels == 2)
286     {
287       v = (BYTE) ((*(d_in++) * right) / 100);
288       *(d_out++) = (v>255) ? 255 : ((v<0) ? 0 : v);
289     }
290   }
291 }
292 
293 static DWORD bytes_to_mmtime(LPMMTIME lpTime, DWORD position,
294                              WAVEFORMATPCMEX* format)
295 {
296     TRACE("wType=%04X wBitsPerSample=%u nSamplesPerSec=%u nChannels=%u nAvgBytesPerSec=%u\n",
297           lpTime->wType, format->Format.wBitsPerSample, format->Format.nSamplesPerSec,
298           format->Format.nChannels, format->Format.nAvgBytesPerSec);
299     TRACE("Position in bytes=%u\n", position);
300 
301     switch (lpTime->wType) {
302     case TIME_SAMPLES:
303         lpTime->u.sample = position / (format->Format.wBitsPerSample / 8 * format->Format.nChannels);
304         TRACE("TIME_SAMPLES=%u\n", lpTime->u.sample);
305         break;
306     case TIME_MS:
307         lpTime->u.ms = 1000.0 * position / (format->Format.wBitsPerSample / 8 * format->Format.nChannels * format->Format.nSamplesPerSec);
308         TRACE("TIME_MS=%u\n", lpTime->u.ms);
309         break;
310     case TIME_SMPTE:
311         lpTime->u.smpte.fps = 30;
312         position = position / (format->Format.wBitsPerSample / 8 * format->Format.nChannels);
313         position += (format->Format.nSamplesPerSec / lpTime->u.smpte.fps) - 1; /* round up */
314         lpTime->u.smpte.sec = position / format->Format.nSamplesPerSec;
315         position -= lpTime->u.smpte.sec * format->Format.nSamplesPerSec;
316         lpTime->u.smpte.min = lpTime->u.smpte.sec / 60;
317         lpTime->u.smpte.sec -= 60 * lpTime->u.smpte.min;
318         lpTime->u.smpte.hour = lpTime->u.smpte.min / 60;
319         lpTime->u.smpte.min -= 60 * lpTime->u.smpte.hour;
320         lpTime->u.smpte.fps = 30;
321         lpTime->u.smpte.frame = position * lpTime->u.smpte.fps / format->Format.nSamplesPerSec;
322         TRACE("TIME_SMPTE=%02u:%02u:%02u:%02u\n",
323               lpTime->u.smpte.hour, lpTime->u.smpte.min,
324               lpTime->u.smpte.sec, lpTime->u.smpte.frame);
325         break;
326     default:
327         WARN("Format %d not supported, using TIME_BYTES !\n", lpTime->wType);
328         lpTime->wType = TIME_BYTES;
329         /* fall through */
330     case TIME_BYTES:
331         lpTime->u.cb = position;
332         TRACE("TIME_BYTES=%u\n", lpTime->u.cb);
333         break;
334     }
335     return MMSYSERR_NOERROR;
336 }
337 
338 static BOOL supportedFormat(LPWAVEFORMATEX wf)
339 {
340     TRACE("(%p)\n",wf);
341                                                                                 
342     if (wf->nSamplesPerSec<DSBFREQUENCY_MIN||wf->nSamplesPerSec>DSBFREQUENCY_MAX)
343         return FALSE;
344                                                                                 
345     if (wf->wFormatTag == WAVE_FORMAT_PCM) {
346         if (wf->nChannels >= 1 && wf->nChannels <= MAX_CHANNELS) {
347             if (wf->wBitsPerSample==8||wf->wBitsPerSample==16)
348                 return TRUE;
349         }
350     } else if (wf->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
351         WAVEFORMATEXTENSIBLE * wfex = (WAVEFORMATEXTENSIBLE *)wf;
352                                                                                 
353         if (wf->cbSize == 22 && IsEqualGUID(&wfex->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM)) {
354             if (wf->nChannels >=1 && wf->nChannels <= MAX_CHANNELS) {
355                 if (wf->wBitsPerSample==wfex->Samples.wValidBitsPerSample) {
356                     if (wf->wBitsPerSample==8||wf->wBitsPerSample==16)
357                         return TRUE;
358                 } else
359                     WARN("wBitsPerSample != wValidBitsPerSample not supported yet\n");
360             }
361         } else
362             WARN("only KSDATAFORMAT_SUBTYPE_PCM supported\n");
363     } else
364         WARN("only WAVE_FORMAT_PCM and WAVE_FORMAT_EXTENSIBLE supported\n");
365                                                                                 
366     return FALSE;
367 }
368 
369 static void copy_format(LPWAVEFORMATEX wf1, LPWAVEFORMATPCMEX wf2)
370 {
371     ZeroMemory(wf2, sizeof(wf2));
372     if (wf1->wFormatTag == WAVE_FORMAT_PCM)
373         memcpy(wf2, wf1, sizeof(PCMWAVEFORMAT));
374     else if (wf1->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
375         memcpy(wf2, wf1, sizeof(WAVEFORMATPCMEX));
376     else
377         memcpy(wf2, wf1, sizeof(WAVEFORMATEX) + wf1->cbSize);
378 }
379 
380 /******************************************************************
381  *              ESD_CloseWaveOutDevice
382  *
383  */
384 static void     ESD_CloseWaveOutDevice(WINE_WAVEOUT* wwo)
385 {
386         esd_close(wwo->esd_fd);         /* close the esd socket fd */
387         wwo->esd_fd = -1;
388 
389   /* free up the buffer we use for volume and reset the size */
390   HeapFree(GetProcessHeap(), 0, wwo->sound_buffer);
391   wwo->sound_buffer = NULL;
392   wwo->buffer_size = 0;
393 }
394 
395 /******************************************************************
396  *              ESD_CloseWaveInDevice
397  *
398  */
399 static void     ESD_CloseWaveInDevice(WINE_WAVEIN* wwi)
400 {
401         esd_close(wwi->esd_fd);         /* close the esd socket fd */
402         wwi->esd_fd = -1;
403 }
404 
405 /******************************************************************
406  *              ESD_WaveClose
407  */
408 LONG            ESD_WaveClose(void)
409 {
410     int iDevice;
411 
412     /* close all open devices */
413     for(iDevice = 0; iDevice < MAX_WAVEOUTDRV; iDevice++)
414     {
415       if(WOutDev[iDevice].esd_fd != -1)
416       {
417         ESD_CloseWaveOutDevice(&WOutDev[iDevice]);
418       }
419     }
420 
421     for(iDevice = 0; iDevice < MAX_WAVEINDRV; iDevice++)
422     {
423       if(WInDev[iDevice].esd_fd != -1)
424       {
425         ESD_CloseWaveInDevice(&WInDev[iDevice]);
426       }
427     }
428 
429     return 1;
430 }
431 
432 /******************************************************************
433  *              ESD_WaveInit
434  *
435  * Initialize internal structures from ESD server info
436  */
437 LONG ESD_WaveInit(void)
438 {
439     int         i;
440     int         fd;
441 
442     TRACE("called\n");
443 
444     /* Testing whether the esd host is alive. */
445     if ((fd = esd_open_sound(NULL)) < 0)
446     {
447         WARN("esd_open_sound() failed (%d)\n", errno);
448         return -1;
449     }
450     esd_close(fd);
451 
452     /* initialize all device handles to -1 */
453     for (i = 0; i < MAX_WAVEOUTDRV; ++i)
454     {
455         static const WCHAR ini[] = {'E','s','o','u','n','D',' ','W','a','v','e','O','u','t','D','r','i','v','e','r',0};
456 
457         WOutDev[i].esd_fd = -1;
458         memset(&WOutDev[i].caps, 0, sizeof(WOutDev[i].caps)); /* zero out
459                                                         caps values */
460         WOutDev[i].caps.wMid = 0x00FF;  /* Manufacturer ID */
461         WOutDev[i].caps.wPid = 0x0001;  /* Product ID */
462         lstrcpyW(WOutDev[i].caps.szPname, ini);
463         snprintf(WOutDev[i].interface_name, sizeof(WOutDev[i].interface_name), "wineesd: %d", i);
464 
465         WOutDev[i].caps.vDriverVersion = 0x0100;
466         WOutDev[i].caps.dwFormats = 0x00000000;
467         WOutDev[i].caps.dwSupport = WAVECAPS_VOLUME;
468 
469         WOutDev[i].caps.wChannels = 2;
470         WOutDev[i].caps.dwSupport |= WAVECAPS_LRVOLUME;
471 
472         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4M08;
473         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4S08;
474         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4S16;
475         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4M16;
476         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2M08;
477         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2S08;
478         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2M16;
479         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2S16;
480         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1M08;
481         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1S08;
482         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1M16;
483         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1S16;
484     }
485 
486     for (i = 0; i < MAX_WAVEINDRV; ++i)
487     {
488         static const WCHAR ini[] = {'E','s','o','u','n','D',' ','W','a','v','e','I','n','D','r','i','v','e','r',0};
489 
490         WInDev[i].esd_fd = -1;
491         memset(&WInDev[i].caps, 0, sizeof(WInDev[i].caps)); /* zero out
492                                                         caps values */
493         WInDev[i].caps.wMid = 0x00FF;
494         WInDev[i].caps.wPid = 0x0001;
495         lstrcpyW(WInDev[i].caps.szPname, ini);
496         snprintf(WInDev[i].interface_name, sizeof(WInDev[i].interface_name), "wineesd: %d", i);
497 
498         WInDev[i].caps.vDriverVersion = 0x0100;
499         WInDev[i].caps.dwFormats = 0x00000000;
500 
501         WInDev[i].caps.wChannels = 2;
502 
503         WInDev[i].caps.dwFormats |= WAVE_FORMAT_4M08;
504         WInDev[i].caps.dwFormats |= WAVE_FORMAT_4S08;
505         WInDev[i].caps.dwFormats |= WAVE_FORMAT_4S16;
506         WInDev[i].caps.dwFormats |= WAVE_FORMAT_4M16;
507         WInDev[i].caps.dwFormats |= WAVE_FORMAT_2M08;
508         WInDev[i].caps.dwFormats |= WAVE_FORMAT_2S08;
509         WInDev[i].caps.dwFormats |= WAVE_FORMAT_2M16;
510         WInDev[i].caps.dwFormats |= WAVE_FORMAT_2S16;
511         WInDev[i].caps.dwFormats |= WAVE_FORMAT_1M08;
512         WInDev[i].caps.dwFormats |= WAVE_FORMAT_1S08;
513         WInDev[i].caps.dwFormats |= WAVE_FORMAT_1M16;
514         WInDev[i].caps.dwFormats |= WAVE_FORMAT_1S16;
515 
516         WInDev[i].caps.wReserved1 = 0;
517     }
518     return 0;
519 }
520 
521 /******************************************************************
522  *              ESD_InitRingMessage
523  *
524  * Initialize the ring of messages for passing between driver's caller and playback/record
525  * thread
526  */
527 static int ESD_InitRingMessage(ESD_MSG_RING* mr)
528 {
529     mr->msg_toget = 0;
530     mr->msg_tosave = 0;
531 #ifdef USE_PIPE_SYNC
532     if (pipe(mr->msg_pipe) < 0) {
533         mr->msg_pipe[0] = -1;
534         mr->msg_pipe[1] = -1;
535         ERR("could not create pipe, error=%s\n", strerror(errno));
536     }
537 #else
538     mr->msg_event = CreateEventW(NULL, FALSE, FALSE, NULL);
539 #endif
540     mr->ring_buffer_size = ESD_RING_BUFFER_INCREMENT;
541     mr->messages = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,mr->ring_buffer_size * sizeof(RING_MSG));
542     InitializeCriticalSection(&mr->msg_crst);
543     mr->msg_crst.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": ESD_MSG_RING.msg_crst");
544     return 0;
545 }
546 
547 /******************************************************************
548  *              ESD_DestroyRingMessage
549  *
550  */
551 static int ESD_DestroyRingMessage(ESD_MSG_RING* mr)
552 {
553 #ifdef USE_PIPE_SYNC
554     close(mr->msg_pipe[0]);
555     close(mr->msg_pipe[1]);
556 #else
557     CloseHandle(mr->msg_event);
558 #endif
559     HeapFree(GetProcessHeap(),0,mr->messages);
560     mr->messages=NULL;
561     mr->msg_crst.DebugInfo->Spare[0] = 0;
562     DeleteCriticalSection(&mr->msg_crst);
563     return 0;
564 }
565 
566 /******************************************************************
567  *              ESD_AddRingMessage
568  *
569  * Inserts a new message into the ring (should be called from DriverProc derived routines)
570  */
571 static int ESD_AddRingMessage(ESD_MSG_RING* mr, enum win_wm_message msg, DWORD param, BOOL wait)
572 {
573     HANDLE      hEvent = INVALID_HANDLE_VALUE;
574 
575     EnterCriticalSection(&mr->msg_crst);
576     if ((mr->msg_toget == ((mr->msg_tosave + 1) % mr->ring_buffer_size)))
577     {
578         int old_ring_buffer_size = mr->ring_buffer_size;
579         mr->ring_buffer_size += ESD_RING_BUFFER_INCREMENT;
580         TRACE("mr->ring_buffer_size=%d\n",mr->ring_buffer_size);
581         mr->messages = HeapReAlloc(GetProcessHeap(),0,mr->messages, mr->ring_buffer_size * sizeof(RING_MSG));
582         /* Now we need to rearrange the ring buffer so that the new
583            buffers just allocated are in between mr->msg_tosave and
584            mr->msg_toget.
585         */
586         if (mr->msg_tosave < mr->msg_toget)
587         {
588             memmove(&(mr->messages[mr->msg_toget + ESD_RING_BUFFER_INCREMENT]),
589                     &(mr->messages[mr->msg_toget]),
590                     sizeof(RING_MSG)*(old_ring_buffer_size - mr->msg_toget)
591                     );
592             mr->msg_toget += ESD_RING_BUFFER_INCREMENT;
593         }
594     }
595     if (wait)
596     {
597         hEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
598         if (hEvent == INVALID_HANDLE_VALUE)
599         {
600             ERR("can't create event !?\n");
601             LeaveCriticalSection(&mr->msg_crst);
602             return 0;
603         }
604         if (mr->msg_toget != mr->msg_tosave && mr->messages[mr->msg_toget].msg != WINE_WM_HEADER)
605             FIXME("two fast messages in the queue!!!!\n");
606 
607         /* fast messages have to be added at the start of the queue */
608         mr->msg_toget = (mr->msg_toget + mr->ring_buffer_size - 1) % mr->ring_buffer_size;
609 
610         mr->messages[mr->msg_toget].msg = msg;
611         mr->messages[mr->msg_toget].param = param;
612         mr->messages[mr->msg_toget].hEvent = hEvent;
613     }
614     else
615     {
616         mr->messages[mr->msg_tosave].msg = msg;
617         mr->messages[mr->msg_tosave].param = param;
618         mr->messages[mr->msg_tosave].hEvent = INVALID_HANDLE_VALUE;
619         mr->msg_tosave = (mr->msg_tosave + 1) % mr->ring_buffer_size;
620     }
621 
622     LeaveCriticalSection(&mr->msg_crst);
623 
624     /* signal a new message */
625     SIGNAL_OMR(mr);
626     if (wait)
627     {
628         /* wait for playback/record thread to have processed the message */
629         WaitForSingleObject(hEvent, INFINITE);
630         CloseHandle(hEvent);
631     }
632 
633     return 1;
634 }
635 
636 /******************************************************************
637  *              ESD_RetrieveRingMessage
638  *
639  * Get a message from the ring. Should be called by the playback/record thread.
640  */
641 static int ESD_RetrieveRingMessage(ESD_MSG_RING* mr, enum win_wm_message *msg,
642                                    DWORD_PTR *param, HANDLE *hEvent)
643 {
644     EnterCriticalSection(&mr->msg_crst);
645 
646     if (mr->msg_toget == mr->msg_tosave) /* buffer empty ? */
647     {
648         LeaveCriticalSection(&mr->msg_crst);
649         return 0;
650     }
651 
652     *msg = mr->messages[mr->msg_toget].msg;
653     mr->messages[mr->msg_toget].msg = 0;
654     *param = mr->messages[mr->msg_toget].param;
655     *hEvent = mr->messages[mr->msg_toget].hEvent;
656     mr->msg_toget = (mr->msg_toget + 1) % mr->ring_buffer_size;
657     CLEAR_OMR(mr);
658     LeaveCriticalSection(&mr->msg_crst);
659     return 1;
660 }
661 
662 /*======================================================================*
663  *                  Low level WAVE OUT implementation                   *
664  *======================================================================*/
665 
666 /**************************************************************************
667  *                      wodNotifyClient                 [internal]
668  */
669 static DWORD wodNotifyClient(WINE_WAVEOUT* wwo, WORD wMsg, DWORD_PTR dwParam1,
670                              DWORD_PTR dwParam2)
671 {
672     TRACE("wMsg = 0x%04x dwParm1 = %08lX dwParam2 = %08lX\n", wMsg, dwParam1, dwParam2);
673 
674     switch (wMsg) {
675     case WOM_OPEN:
676     case WOM_CLOSE:
677     case WOM_DONE:
678         if (wwo->wFlags != DCB_NULL &&
679             !DriverCallback(wwo->waveDesc.dwCallback, wwo->wFlags, (HDRVR)wwo->waveDesc.hWave,
680                             wMsg, wwo->waveDesc.dwInstance, dwParam1, dwParam2)) {
681             WARN("can't notify client !\n");
682             return MMSYSERR_ERROR;
683         }
684         break;
685     default:
686         FIXME("Unknown callback message %u\n", wMsg);
687         return MMSYSERR_INVALPARAM;
688     }
689     return MMSYSERR_NOERROR;
690 }
691 
692 /**************************************************************************
693  *                              wodUpdatePlayedTotal    [internal]
694  *
695  */
696 static BOOL wodUpdatePlayedTotal(WINE_WAVEOUT* wwo)
697 {
698     /* total played is the bytes written less the bytes to write ;-) */
699     wwo->dwPlayedTotal = wwo->dwWrittenTotal;
700 
701     return TRUE;
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  * Writes the maximum number of bytes possible to the DSP and returns
798  * the number of bytes written.
799  */
800 static int wodPlayer_WriteMaxFrags(WINE_WAVEOUT* wwo, DWORD* bytes)
801 {
802     /* Only attempt to write to free bytes */
803     DWORD dwLength = wwo->lpPlayPtr->dwBufferLength - wwo->dwPartialOffset;
804     int toWrite = min(dwLength, *bytes);
805     int written;
806 
807     TRACE("Writing wavehdr %p.%u[%u]\n",
808           wwo->lpPlayPtr, wwo->dwPartialOffset, wwo->lpPlayPtr->dwBufferLength);
809 
810     /* see if our buffer isn't large enough for the data we are writing */
811     if(wwo->buffer_size < toWrite)
812     {
813       if(wwo->sound_buffer)
814       {
815         wwo->sound_buffer = HeapReAlloc(GetProcessHeap(), 0, wwo->sound_buffer, toWrite);
816         wwo->buffer_size = toWrite;
817       }
818     }
819 
820     /* if we don't have a buffer then get one */
821     if(!wwo->sound_buffer)
822     {
823       /* allocate some memory for the buffer */
824       wwo->sound_buffer = HeapAlloc(GetProcessHeap(), 0, toWrite);
825       wwo->buffer_size = toWrite;
826     }
827 
828     /* if we don't have a buffer then error out */
829     if(!wwo->sound_buffer)
830     {
831       ERR("error allocating sound_buffer memory\n");
832       return 0;
833     }
834 
835     TRACE("toWrite == %d\n", toWrite);
836 
837     /* apply volume to the bits */
838     /* for single channel audio streams we only use the LEFT volume */
839     if(wwo->waveFormat.Format.wBitsPerSample == 16)
840     {
841       /* apply volume to the buffer we are about to send */
842       /* divide toWrite(bytes) by 2 as volume processes by 16 bits */
843       volume_effect16(wwo->lpPlayPtr->lpData + wwo->dwPartialOffset,
844                 wwo->sound_buffer, toWrite>>1, wwo->volume_left,
845                 wwo->volume_right, wwo->waveFormat.Format.nChannels);
846     } else if(wwo->waveFormat.Format.wBitsPerSample == 8)
847     {
848       /* apply volume to the buffer we are about to send */
849       volume_effect8(wwo->lpPlayPtr->lpData + wwo->dwPartialOffset,
850                 wwo->sound_buffer, toWrite, wwo->volume_left,
851                 wwo->volume_right, wwo->waveFormat.Format.nChannels);
852     } else
853     {
854       FIXME("unsupported wwo->format.wBitsPerSample of %d\n",
855         wwo->waveFormat.Format.wBitsPerSample);
856     }
857 
858     /* send the audio data to esd for playing */
859     written = write(wwo->esd_fd, wwo->sound_buffer, toWrite);
860 
861     TRACE("written = %d\n", written);
862 
863     if (written <= 0) 
864     {
865       *bytes = 0; /* apparently esd is actually full */
866       return written; /* if we wrote nothing just return */
867     }
868 
869     if (written >= dwLength)
870         wodPlayer_PlayPtrNext(wwo);   /* If we wrote all current wavehdr, skip to the next one */
871     else
872         wwo->dwPartialOffset += written;    /* Remove the amount written */
873 
874     if (written < toWrite)
875         *bytes = 0;
876     else
877         *bytes -= written;
878 
879     wwo->dwWrittenTotal += written; /* update stats on this wave device */
880 
881     return written; /* return the number of bytes written */
882 }
883 
884 
885 /**************************************************************************
886  *                              wodPlayer_NotifyCompletions     [internal]
887  *
888  * Notifies and remove from queue all wavehdrs which have been played to
889  * the speaker (ie. they have cleared the audio device).  If force is true,
890  * we notify all wavehdrs and remove them all from the queue even if they
891  * are unplayed or part of a loop.
892  */
893 static DWORD wodPlayer_NotifyCompletions(WINE_WAVEOUT* wwo, BOOL force)
894 {
895     LPWAVEHDR           lpWaveHdr;
896 
897     if (wwo->lpQueuePtr) {
898         TRACE("lpWaveHdr=(%p), lpPlayPtr=(%p), lpLoopPtr=(%p), reserved=(%ld), dwWrittenTotal=(%d), force=(%d)\n",
899               wwo->lpQueuePtr,
900               wwo->lpPlayPtr,
901               wwo->lpLoopPtr,
902               wwo->lpQueuePtr->reserved,
903               wwo->dwWrittenTotal,
904               force);
905     } else {
906         TRACE("lpWaveHdr=(%p), lpPlayPtr=(%p), lpLoopPtr=(%p),  dwWrittenTotal=(%d), force=(%d)\n",
907               wwo->lpQueuePtr,
908               wwo->lpPlayPtr,
909               wwo->lpLoopPtr,
910               wwo->dwWrittenTotal,
911               force);
912     }
913 
914     /* Start from lpQueuePtr and keep notifying until:
915      * - we hit an unwritten wavehdr
916      * - we hit the beginning of a running loop
917      * - we hit a wavehdr which hasn't finished playing
918      */
919     while ((lpWaveHdr = wwo->lpQueuePtr) &&
920            (force ||
921             (lpWaveHdr != wwo->lpPlayPtr &&
922              lpWaveHdr != wwo->lpLoopPtr &&
923              lpWaveHdr->reserved <= wwo->dwWrittenTotal))) {
924 
925         wwo->lpQueuePtr = lpWaveHdr->lpNext;
926 
927         lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
928         lpWaveHdr->dwFlags |= WHDR_DONE;
929 
930         wodNotifyClient(wwo, WOM_DONE, (DWORD_PTR)lpWaveHdr, 0);
931     }
932     return  (lpWaveHdr && lpWaveHdr != wwo->lpPlayPtr && lpWaveHdr != wwo->lpLoopPtr) ?
933         wodPlayer_NotifyWait(wwo, lpWaveHdr) : INFINITE;
934 }
935 
936 /**************************************************************************
937  *                              wodPlayer_Reset                 [internal]
938  *
939  * wodPlayer helper. Resets current output stream.
940  */
941 static  void    wodPlayer_Reset(WINE_WAVEOUT* wwo, BOOL reset)
942 {
943     wodUpdatePlayedTotal(wwo);
944 
945     wodPlayer_NotifyCompletions(wwo, FALSE); /* updates current notify list */
946 
947     /* we aren't able to flush any data that has already been written */
948     /* to esd, otherwise we would do the flushing here */
949 
950     if (reset) {
951         enum win_wm_message     msg;
952         DWORD_PTR               param;
953         HANDLE                  ev;
954 
955         /* remove any buffer */
956         wodPlayer_NotifyCompletions(wwo, TRUE);
957 
958         wwo->lpPlayPtr = wwo->lpQueuePtr = wwo->lpLoopPtr = NULL;
959         wwo->state = WINE_WS_STOPPED;
960         wwo->dwPlayedTotal = wwo->dwWrittenTotal = 0;
961 
962         wwo->dwPartialOffset = 0;        /* Clear partial wavehdr */
963 
964         /* remove any existing message in the ring */
965         EnterCriticalSection(&wwo->msgRing.msg_crst);
966 
967         /* return all pending headers in queue */
968         while (ESD_RetrieveRingMessage(&wwo->msgRing, &msg, &param, &ev))
969         {
970             TRACE("flushing msg\n");
971             if (msg != WINE_WM_HEADER)
972             {
973                 FIXME("shouldn't have headers left\n");
974                 SetEvent(ev);
975                 continue;
976             }
977             ((LPWAVEHDR)param)->dwFlags &= ~WHDR_INQUEUE;
978             ((LPWAVEHDR)param)->dwFlags |= WHDR_DONE;
979 
980             wodNotifyClient(wwo, WOM_DONE, param, 0);
981         }
982         RESET_OMR(&wwo->msgRing);
983         LeaveCriticalSection(&wwo->msgRing.msg_crst);
984     } else {
985         if (wwo->lpLoopPtr) {
986             /* complicated case, not handled yet (could imply modifying the loop counter */
987             FIXME("Pausing while in loop isn't correctly handled yet, except strange results\n");
988             wwo->lpPlayPtr = wwo->lpLoopPtr;
989             wwo->dwPartialOffset = 0;
990             wwo->dwWrittenTotal = wwo->dwPlayedTotal; /* this is wrong !!! */
991         } else {
992             /* the data already written is going to be played, so take */
993             /* this fact into account here */
994             wwo->dwPlayedTotal = wwo->dwWrittenTotal;
995         }
996         wwo->state = WINE_WS_PAUSED;
997     }
998 }
999 
1000 /**************************************************************************
1001  *                    wodPlayer_ProcessMessages                 [internal]
1002  */
1003 static void wodPlayer_ProcessMessages(WINE_WAVEOUT* wwo)
1004 {
1005     LPWAVEHDR           lpWaveHdr;
1006     enum win_wm_message msg;
1007     DWORD_PTR           param;
1008     HANDLE              ev;
1009 
1010     while (ESD_RetrieveRingMessage(&wwo->msgRing, &msg, &param, &ev)) {
1011         TRACE("Received %s %lx\n", wodPlayerCmdString[msg - WM_USER - 1], param);
1012         switch (msg) {
1013         case WINE_WM_PAUSING:
1014             wodPlayer_Reset(wwo, FALSE);
1015             SetEvent(ev);
1016             break;
1017         case WINE_WM_RESTARTING:
1018             wwo->state = WINE_WS_PLAYING;
1019             SetEvent(ev);
1020             break;
1021         case WINE_WM_HEADER:
1022             lpWaveHdr = (LPWAVEHDR)param;
1023 
1024             /* insert buffer at the end of queue */
1025             {
1026                 LPWAVEHDR*      wh;
1027                 for (wh = &(wwo->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
1028                 *wh = lpWaveHdr;
1029             }
1030             if (!wwo->lpPlayPtr)
1031                 wodPlayer_BeginWaveHdr(wwo,lpWaveHdr);
1032             if (wwo->state == WINE_WS_STOPPED)
1033                 wwo->state = WINE_WS_PLAYING;
1034             break;
1035         case WINE_WM_RESETTING:
1036             wodPlayer_Reset(wwo, TRUE);
1037             SetEvent(ev);
1038             break;
1039         case WINE_WM_UPDATE:
1040             wodUpdatePlayedTotal(wwo);
1041             SetEvent(ev);
1042             break;
1043         case WINE_WM_BREAKLOOP:
1044             if (wwo->state == WINE_WS_PLAYING && wwo->lpLoopPtr != NULL) {
1045                 /* ensure exit at end of current loop */
1046                 wwo->dwLoops = 1;
1047             }
1048             SetEvent(ev);
1049             break;
1050         case WINE_WM_CLOSING:
1051             /* sanity check: this should not happen since the device must have been reset before */
1052             if (wwo->lpQueuePtr || wwo->lpPlayPtr) ERR("out of sync\n");
1053             wwo->hThread = 0;
1054             wwo->state = WINE_WS_CLOSED;
1055             SetEvent(ev);
1056             ExitThread(0);
1057             /* shouldn't go here */
1058         default:
1059             FIXME("unknown message %d\n", msg);
1060             break;
1061         }
1062     }
1063 }
1064 
1065 /**************************************************************************
1066  *                           wodPlayer_FeedDSP                  [internal]
1067  * Feed as much sound data as we can into the DSP and return the number of
1068  * milliseconds before it will be necessary to feed the DSP again.
1069  */
1070 static DWORD wodPlayer_FeedDSP(WINE_WAVEOUT* wwo)
1071 {
1072     DWORD       availInQ;
1073 
1074     wodUpdatePlayedTotal(wwo);
1075     /* better way to set availInQ? */
1076     availInQ = ESD_BUF_SIZE;
1077     TRACE("availInQ = %d\n", availInQ);
1078 
1079     /* input queue empty */
1080     if (!wwo->lpPlayPtr) {
1081         TRACE("Run out of wavehdr:s... flushing\n");
1082         return INFINITE;
1083     }
1084 
1085 #if 0
1086     /* no more room... no need to try to feed */
1087     if(!availInQ)
1088     {
1089         TRACE("no more room, no need to try to feed\n");
1090         return wwo->dwSleepTime;
1091     }
1092 #endif
1093 
1094     /* Feed from partial wavehdr */
1095     if (wwo->lpPlayPtr && wwo->dwPartialOffset != 0)
1096     {
1097         TRACE("feeding from partial wavehdr\n");
1098         wodPlayer_WriteMaxFrags(wwo, &availInQ);
1099     }
1100 
1101     /* Feed wavehdrs until we run out of wavehdrs or DSP space */
1102     if (!wwo->dwPartialOffset)
1103     {
1104         while(wwo->lpPlayPtr && availInQ)
1105         {
1106             TRACE("feeding waveheaders until we run out of space\n");
1107             /* note the value that dwPlayedTotal will return when this wave finishes playing */
1108             wwo->lpPlayPtr->reserved = wwo->dwWrittenTotal + wwo->lpPlayPtr->dwBufferLength;
1109             TRACE("reserved=(%ld) dwWrittenTotal=(%d) dwBufferLength=(%d)\n",
1110                   wwo->lpPlayPtr->reserved,
1111                   wwo->dwWrittenTotal,
1112                   wwo->lpPlayPtr->dwBufferLength
1113                 );
1114             wodPlayer_WriteMaxFrags(wwo, &availInQ);
1115         }
1116     }
1117 
1118     if (!wwo->lpPlayPtr) {
1119         TRACE("Ran out of wavehdrs\n");
1120         return INFINITE;
1121     }
1122 
1123     return wwo->dwSleepTime;
1124 }
1125 
1126 
1127 /**************************************************************************
1128  *                              wodPlayer                       [internal]
1129  */
1130 static  DWORD   CALLBACK        wodPlayer(LPVOID pmt)
1131 {
1132     WORD          uDevID = (DWORD_PTR)pmt;
1133     WINE_WAVEOUT* wwo = &WOutDev[uDevID];
1134     DWORD         dwNextFeedTime = INFINITE;   /* Time before DSP needs feeding */
1135     DWORD         dwNextNotifyTime = INFINITE; /* Time before next wave completion */
1136     DWORD         dwSleepTime;
1137 
1138     wwo->state = WINE_WS_STOPPED;
1139     SetEvent(wwo->hStartUpEvent);
1140 
1141     for (;;) {
1142         /** Wait for the shortest time before an action is required.  If there
1143          *  are no pending actions, wait forever for a command.
1144          */
1145         dwSleepTime = min(dwNextFeedTime, dwNextNotifyTime);
1146         TRACE("waiting %ums (%u,%u)\n", dwSleepTime, dwNextFeedTime, dwNextNotifyTime);
1147         WAIT_OMR(&wwo->msgRing, dwSleepTime);
1148         wodPlayer_ProcessMessages(wwo);
1149         if (wwo->state == WINE_WS_PLAYING) {
1150             dwNextFeedTime = wodPlayer_FeedDSP(wwo);
1151             dwNextNotifyTime = wodPlayer_NotifyCompletions(wwo, FALSE);
1152         } else {
1153             dwNextFeedTime = dwNextNotifyTime = INFINITE;
1154         }
1155     }
1156 
1157     return 0;
1158 }
1159 
1160 /**************************************************************************
1161  *                      wodGetDevCaps                           [internal]
1162  */
1163 static DWORD wodGetDevCaps(WORD wDevID, LPWAVEOUTCAPSW lpCaps, DWORD dwSize)
1164 {
1165     TRACE("(%u, %p, %u);\n", wDevID, lpCaps, dwSize);
1166 
1167     if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
1168 
1169     if (wDevID >= MAX_WAVEOUTDRV) {
1170         TRACE("MAX_WAVOUTDRV reached !\n");
1171         return MMSYSERR_BADDEVICEID;
1172     }
1173 
1174     memcpy(lpCaps, &WOutDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
1175     return MMSYSERR_NOERROR;
1176 }
1177 
1178 /**************************************************************************
1179  *                              wodOpen                         [internal]
1180  */
1181 static DWORD wodOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
1182 {
1183     WINE_WAVEOUT*       wwo;
1184     /* output to esound... */
1185     int                 out_bits = ESD_BITS8, out_channels = ESD_MONO, out_rate;
1186     int                 out_mode = ESD_STREAM, out_func = ESD_PLAY;
1187     esd_format_t        out_format;
1188 
1189     TRACE("(%u, %p, %08X);\n", wDevID, lpDesc, dwFlags);
1190     if (lpDesc == NULL) {
1191         WARN("Invalid Parameter !\n");
1192         return MMSYSERR_INVALPARAM;
1193     }
1194     if (wDevID >= MAX_WAVEOUTDRV) {
1195         TRACE("MAX_WAVOUTDRV reached !\n");
1196         return MMSYSERR_BADDEVICEID;
1197     }
1198 
1199     /* if this device is already open tell the app that it is allocated */
1200     if(WOutDev[wDevID].esd_fd != -1)
1201     {
1202       TRACE("device already allocated\n");
1203       return MMSYSERR_ALLOCATED;
1204     }
1205 
1206     /* only PCM format is supported so far... */
1207     if (!supportedFormat(lpDesc->lpFormat)) {
1208         WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
1209              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1210              lpDesc->lpFormat->nSamplesPerSec);
1211         return WAVERR_BADFORMAT;
1212     }
1213 
1214     if (dwFlags & WAVE_FORMAT_QUERY) {
1215         TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
1216              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1217              lpDesc->lpFormat->nSamplesPerSec);
1218         return MMSYSERR_NOERROR;
1219     }
1220 
1221     wwo = &WOutDev[wDevID];
1222 
1223     /* direct sound not supported, ignore the flag */
1224     dwFlags &= ~WAVE_DIRECTSOUND;
1225 
1226     wwo->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
1227 
1228     wwo->waveDesc = *lpDesc;
1229     copy_format(lpDesc->lpFormat, &wwo->waveFormat);
1230 
1231     if (wwo->waveFormat.Format.wBitsPerSample == 0) {
1232         WARN("Resetting zeroed wBitsPerSample\n");
1233         wwo->waveFormat.Format.wBitsPerSample = 8 *
1234             (wwo->waveFormat.Format.nAvgBytesPerSec /
1235              wwo->waveFormat.Format.nSamplesPerSec) /
1236             wwo->waveFormat.Format.nChannels;
1237     }
1238 
1239     if (wwo->waveFormat.Format.wBitsPerSample == 8)
1240         out_bits = ESD_BITS8;
1241     else if (wwo->waveFormat.Format.wBitsPerSample == 16)
1242         out_bits = ESD_BITS16;
1243 
1244     wwo->bytes_per_frame = (wwo->waveFormat.Format.wBitsPerSample * wwo->waveFormat.Format.nChannels) / 8;
1245 
1246     if (wwo->waveFormat.Format.nChannels == 1)
1247         out_channels = ESD_MONO;
1248     else if (wwo->waveFormat.Format.nChannels == 2)
1249         out_channels = ESD_STEREO;
1250 
1251     out_format = out_bits | out_channels | out_mode | out_func;
1252     out_rate = (int) wwo->waveFormat.Format.nSamplesPerSec;
1253         TRACE("esd output format = 0x%08x, rate = %d\n", out_format, out_rate);
1254 
1255     wwo->esd_fd = esd_play_stream(out_format, out_rate, NULL, "wineesd");
1256 
1257     /* clear these so we don't have any confusion ;-) */
1258     wwo->sound_buffer = 0;
1259     wwo->buffer_size = 0;
1260 
1261     if(wwo->esd_fd < 0) return MMSYSERR_ALLOCATED;
1262 
1263     wwo->dwBufferSize = ESD_BUF_SIZE;
1264     TRACE("Buffer size is now (%d)\n",wwo->dwBufferSize);
1265 
1266     wwo->dwPlayedTotal = 0;
1267     wwo->dwWrittenTotal = 0;
1268 
1269     wwo->dwSleepTime = (1024 * 1000 * BUFFER_REFILL_THRESHOLD) / wwo->waveFormat.Format.nAvgBytesPerSec;
1270 
1271     /* Initialize volume to full level */
1272     wwo->volume_left = 100;
1273     wwo->volume_right = 100;
1274 
1275     ESD_InitRingMessage(&wwo->msgRing);
1276 
1277     /* create player thread */
1278     if (!(dwFlags & WAVE_DIRECTSOUND)) {
1279         wwo->hStartUpEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
1280         wwo->hThread = CreateThread(NULL, 0, wodPlayer, (LPVOID)(DWORD_PTR)wDevID,
1281                                     0, &(wwo->dwThreadID));
1282         WaitForSingleObject(wwo->hStartUpEvent, INFINITE);
1283         CloseHandle(wwo->hStartUpEvent);
1284     } else {
1285         wwo->hThread = INVALID_HANDLE_VALUE;
1286         wwo->dwThreadID = 0;
1287     }
1288     wwo->hStartUpEvent = INVALID_HANDLE_VALUE;
1289 
1290     TRACE("esd=0x%lx, dwBufferSize=%d\n",
1291           (long)wwo->esd_fd, wwo->dwBufferSize);
1292 
1293     TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%u, nSamplesPerSec=%u, nChannels=%u nBlockAlign=%u!\n",
1294           wwo->waveFormat.Format.wBitsPerSample, wwo->waveFormat.Format.nAvgBytesPerSec,
1295           wwo->waveFormat.Format.nSamplesPerSec, wwo->waveFormat.Format.nChannels,
1296           wwo->waveFormat.Format.nBlockAlign);
1297 
1298     return wodNotifyClient(wwo, WOM_OPEN, 0L, 0L);
1299 }
1300 
1301 /**************************************************************************
1302  *                              wodClose                        [internal]
1303  */
1304 static DWORD wodClose(WORD wDevID)
1305 {
1306     DWORD               ret = MMSYSERR_NOERROR;
1307     WINE_WAVEOUT*       wwo;
1308 
1309     TRACE("(%u);\n", wDevID);
1310 
1311     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].esd_fd == -1) {
1312         WARN("bad device ID !\n");
1313         return MMSYSERR_BADDEVICEID;
1314     }
1315 
1316     wwo = &WOutDev[wDevID];
1317     if (wwo->lpQueuePtr) {
1318         WARN("buffers still playing !\n");
1319         ret = WAVERR_STILLPLAYING;
1320     } else {
1321         TRACE("imhere[3-close]\n");
1322         if (wwo->hThread != INVALID_HANDLE_VALUE) {
1323             ESD_AddRingMessage(&wwo->msgRing, WINE_WM_CLOSING, 0, TRUE);
1324         }
1325 
1326         ESD_DestroyRingMessage(&wwo->msgRing);
1327 
1328         ESD_CloseWaveOutDevice(wwo);    /* close the stream and clean things up */
1329 
1330         ret = wodNotifyClient(wwo, WOM_CLOSE, 0L, 0L);
1331     }
1332     return ret;
1333 }
1334 
1335 /**************************************************************************
1336  *                              wodWrite                        [internal]
1337  *
1338  */
1339 static DWORD wodWrite(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1340 {
1341     TRACE("(%u, %p, %08X);\n", wDevID, lpWaveHdr, dwSize);
1342 
1343     /* first, do the sanity checks... */
1344     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].esd_fd == -1) {
1345         WARN("bad dev ID !\n");
1346         return MMSYSERR_BADDEVICEID;
1347     }
1348 
1349     if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
1350     {
1351         TRACE("unprepared\n");
1352         return WAVERR_UNPREPARED;
1353     }
1354 
1355     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1356     {
1357         TRACE("still playing\n");
1358         return WAVERR_STILLPLAYING;
1359     }
1360 
1361     lpWaveHdr->dwFlags &= ~WHDR_DONE;
1362     lpWaveHdr->dwFlags |= WHDR_INQUEUE;
1363     lpWaveHdr->lpNext = 0;
1364 
1365     TRACE("adding ring message\n");
1366     ESD_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_HEADER,
1367                        (DWORD_PTR)lpWaveHdr, FALSE);
1368 
1369     return MMSYSERR_NOERROR;
1370 }
1371 
1372 /**************************************************************************
1373  *                      wodPause                                [internal]
1374  */
1375 static DWORD wodPause(WORD wDevID)
1376 {
1377     TRACE("(%u);!\n", wDevID);
1378 
1379     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].esd_fd == -1) {
1380         WARN("bad device ID !\n");
1381         return MMSYSERR_BADDEVICEID;
1382     }
1383 
1384     TRACE("imhere[3-PAUSING]\n");
1385     ESD_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_PAUSING, 0, TRUE);
1386 
1387     return MMSYSERR_NOERROR;
1388 }
1389 
1390 /**************************************************************************
1391  *                      wodRestart                              [internal]
1392  */
1393 static DWORD wodRestart(WORD wDevID)
1394 {
1395     TRACE("(%u);\n", wDevID);
1396 
1397     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].esd_fd == -1) {
1398         WARN("bad device ID !\n");
1399         return MMSYSERR_BADDEVICEID;
1400     }
1401 
1402     if (WOutDev[wDevID].state == WINE_WS_PAUSED) {
1403         TRACE("imhere[3-RESTARTING]\n");
1404         ESD_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESTARTING, 0, TRUE);
1405     }
1406 
1407     /* FIXME: is NotifyClient with WOM_DONE right ? (Comet Busters 1.3.3 needs this notification) */
1408     /* FIXME: Myst crashes with this ... hmm -MM
1409        return wodNotifyClient(wwo, WOM_DONE, 0L, 0L);
1410     */
1411 
1412     return MMSYSERR_NOERROR;
1413 }
1414 
1415 /**************************************************************************
1416  *                      wodReset                                [internal]
1417  */
1418 static DWORD wodReset(WORD wDevID)
1419 {
1420     TRACE("(%u);\n", wDevID);
1421 
1422     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].esd_fd == -1) {
1423         WARN("bad device ID !\n");
1424         return MMSYSERR_BADDEVICEID;
1425     }
1426 
1427     TRACE("imhere[3-RESET]\n");
1428     ESD_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
1429 
1430     return MMSYSERR_NOERROR;
1431 }
1432 
1433 /**************************************************************************
1434  *                              wodGetPosition                  [internal]
1435  */
1436 static DWORD wodGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
1437 {
1438     WINE_WAVEOUT*       wwo;
1439 
1440     TRACE("(%u, %p, %u);\n", wDevID, lpTime, uSize);
1441 
1442     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].esd_fd == -1) {
1443         WARN("bad device ID !\n");
1444         return MMSYSERR_BADDEVICEID;
1445     }
1446 
1447     if (lpTime == NULL) {
1448         WARN("invalid parameter: lpTime == NULL\n");
1449         return MMSYSERR_INVALPARAM;
1450     }
1451 
1452     wwo = &WOutDev[wDevID];
1453     ESD_AddRingMessage(&wwo->msgRing, WINE_WM_UPDATE, 0, TRUE);
1454 
1455     return bytes_to_mmtime(lpTime, wwo->dwPlayedTotal, &wwo->waveFormat);
1456 }
1457 
1458 /**************************************************************************
1459  *                              wodBreakLoop                    [internal]
1460  */
1461 static DWORD wodBreakLoop(WORD wDevID)
1462 {
1463     TRACE("(%u);\n", wDevID);
1464 
1465     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].esd_fd == -1) {
1466         WARN("bad device ID !\n");
1467         return MMSYSERR_BADDEVICEID;
1468     }
1469     ESD_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_BREAKLOOP, 0, TRUE);
1470     return MMSYSERR_NOERROR;
1471 }
1472 
1473 /**************************************************************************
1474  *                              wodGetVolume                    [internal]
1475  */
1476 static DWORD wodGetVolume(WORD wDevID, LPDWORD lpdwVol)
1477 {
1478     DWORD left, right;
1479 
1480     left = WOutDev[wDevID].volume_left;
1481     right = WOutDev[wDevID].volume_right;
1482 
1483     TRACE("(%u, %p);\n", wDevID, lpdwVol);
1484 
1485     *lpdwVol = ((left * 0xFFFFl) / 100) + (((right * 0xFFFFl) / 100) <<
1486                 16);
1487 
1488     return MMSYSERR_NOERROR;
1489 }
1490 
1491 /**************************************************************************
1492  *                              wodSetVolume                    [internal]
1493  */
1494 static DWORD wodSetVolume(WORD wDevID, DWORD dwParam)
1495 {
1496     DWORD left, right;
1497 
1498     left  = (LOWORD(dwParam) * 100) / 0xFFFFl;
1499     right = (HIWORD(dwParam) * 100) / 0xFFFFl;
1500 
1501     TRACE("(%u, %08X);\n", wDevID, dwParam);
1502 
1503     WOutDev[wDevID].volume_left = left;
1504     WOutDev[wDevID].volume_right = right;
1505 
1506     return MMSYSERR_NOERROR;
1507 }
1508 
1509 /**************************************************************************
1510  *                              wodGetNumDevs                   [internal]
1511  */
1512 static  DWORD   wodGetNumDevs(void)
1513 {
1514     return MAX_WAVEOUTDRV;
1515 }
1516 
1517 /**************************************************************************
1518  *                              wodDevInterfaceSize             [internal]
1519  */
1520 static DWORD wodDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
1521 {
1522     TRACE("(%u, %p)\n", wDevID, dwParam1);
1523  
1524     *dwParam1 = MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].interface_name, -1,
1525                                     NULL, 0 ) * sizeof(WCHAR);
1526     return MMSYSERR_NOERROR;
1527 }
1528  
1529 /**************************************************************************
1530  *                              wodDevInterface                 [internal]
1531  */
1532 static DWORD wodDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
1533 {
1534     if (dwParam2 >= MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].interface_name, -1,
1535                                         NULL, 0 ) * sizeof(WCHAR))
1536     {
1537         MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].interface_name, -1,
1538                             dwParam1, dwParam2 / sizeof(WCHAR));
1539         return MMSYSERR_NOERROR;
1540     }
1541     return MMSYSERR_INVALPARAM;
1542 }
1543  
1544 /**************************************************************************
1545  *                              wodMessage (WINEESD.@)
1546  */
1547 DWORD WINAPI ESD_wodMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
1548                             DWORD_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->esd_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].esd_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     wwi->bytes_per_frame = (wwi->waveFormat.Format.wBitsPerSample * wwi->waveFormat.Format.nChannels) / 8;
1899 
1900     if (wwi->waveFormat.Format.nChannels == 1)
1901         in_channels = ESD_MONO;
1902     else if (wwi->waveFormat.Format.nChannels == 2)
1903         in_channels = ESD_STEREO;
1904 
1905     in_format = in_bits | in_channels | in_mode | in_func;
1906     in_rate = (int) wwi->waveFormat.Format.nSamplesPerSec;
1907         TRACE("esd input format = 0x%08x, rate = %d\n", in_format, in_rate);
1908 
1909 #ifdef WID_USE_ESDMON
1910     wwi->esd_fd = esd_monitor_stream(in_format, in_rate, NULL, "wineesd");
1911 #else
1912     wwi->esd_fd = esd_record_stream(in_format, in_rate, NULL, "wineesd");
1913 #endif
1914     TRACE("(wwi->esd_fd=%d)\n",wwi->esd_fd);
1915     wwi->state = WINE_WS_STOPPED;
1916 
1917     if (wwi->lpQueuePtr) {
1918         WARN("Should have an empty queue (%p)\n", wwi->lpQueuePtr);
1919         wwi->lpQueuePtr = NULL;
1920     }
1921 
1922     if(wwi->esd_fd < 0) return MMSYSERR_ALLOCATED;
1923 
1924     /* Set the esd socket O_NONBLOCK, so we can stop recording smoothly */
1925     mode = fcntl(wwi->esd_fd, F_GETFL);
1926     mode |= O_NONBLOCK;
1927     fcntl(wwi->esd_fd, F_SETFL, mode);
1928 
1929     wwi->dwRecordedTotal = 0;
1930     wwi->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
1931 
1932     ESD_InitRingMessage(&wwi->msgRing);
1933 
1934     /* create recorder thread */
1935     if (!(dwFlags & WAVE_DIRECTSOUND)) {
1936         wwi->hStartUpEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
1937         wwi->hThread = CreateThread(NULL, 0, widRecorder, (LPVOID)(DWORD_PTR)wDevID,
1938                                     0, &(wwi->dwThreadID));
1939         WaitForSingleObject(wwi->hStartUpEvent, INFINITE);
1940         CloseHandle(wwi->hStartUpEvent);
1941     } else {
1942         wwi->hThread = INVALID_HANDLE_VALUE;
1943         wwi->dwThreadID = 0;
1944     }
1945     wwi->hStartUpEvent = INVALID_HANDLE_VALUE;
1946 
1947     TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%u, nSamplesPerSec=%u, nChannels=%u nBlockAlign=%u!\n",
1948           wwi->waveFormat.Format.wBitsPerSample, wwi->waveFormat.Format.nAvgBytesPerSec,
1949           wwi->waveFormat.Format.nSamplesPerSec, wwi->waveFormat.Format.nChannels,
1950           wwi->waveFormat.Format.nBlockAlign);
1951     return widNotifyClient(wwi, WIM_OPEN, 0L, 0L);
1952 }
1953 
1954 /**************************************************************************
1955  *                              widClose                        [internal]
1956  */
1957 static DWORD widClose(WORD wDevID)
1958 {
1959     WINE_WAVEIN*        wwi;
1960 
1961     TRACE("(%u);\n", wDevID);
1962     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].state == WINE_WS_CLOSED) {
1963         WARN("can't close !\n");
1964         return MMSYSERR_INVALHANDLE;
1965     }
1966 
1967     wwi = &WInDev[wDevID];
1968 
1969     if (wwi->lpQueuePtr != NULL) {
1970         WARN("still buffers open !\n");
1971         return WAVERR_STILLPLAYING;
1972     }
1973 
1974     ESD_AddRingMessage(&wwi->msgRing, WINE_WM_CLOSING, 0, TRUE);
1975     ESD_CloseWaveInDevice(wwi);
1976     wwi->state = WINE_WS_CLOSED;
1977     ESD_DestroyRingMessage(&wwi->msgRing);
1978     return widNotifyClient(wwi, WIM_CLOSE, 0L, 0L);
1979 }
1980 
1981 /**************************************************************************
1982  *                              widAddBuffer            [internal]
1983  */
1984 static DWORD widAddBuffer(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1985 {
1986     TRACE("(%u, %p, %08X);\n", wDevID, lpWaveHdr, dwSize);
1987 
1988     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].state == WINE_WS_CLOSED) {
1989         WARN("can't do it !\n");
1990         return MMSYSERR_INVALHANDLE;
1991     }
1992     if (!(lpWaveHdr->dwFlags & WHDR_PREPARED)) {
1993         TRACE("never been prepared !\n");
1994         return WAVERR_UNPREPARED;
1995     }
1996     if (lpWaveHdr->dwFlags & WHDR_INQUEUE) {
1997         TRACE("header already in use !\n");
1998         return WAVERR_STILLPLAYING;
1999     }
2000 
2001     lpWaveHdr->dwFlags |= WHDR_INQUEUE;
2002     lpWaveHdr->dwFlags &= ~WHDR_DONE;
2003     lpWaveHdr->dwBytesRecorded = 0;
2004     lpWaveHdr->lpNext = NULL;
2005 
2006     ESD_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_HEADER,
2007                        (DWORD_PTR)lpWaveHdr, FALSE);
2008     return MMSYSERR_NOERROR;
2009 }
2010 
2011 /**************************************************************************
2012  *                      widStart                                [internal]
2013  */
2014 static DWORD widStart(WORD wDevID)
2015 {
2016     TRACE("(%u);\n", wDevID);
2017     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].state == WINE_WS_CLOSED) {
2018         WARN("can't start recording !\n");
2019         return MMSYSERR_INVALHANDLE;
2020     }
2021 
2022     ESD_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_STARTING, 0, TRUE);
2023     return MMSYSERR_NOERROR;
2024 }
2025 
2026 /**************************************************************************
2027  *                      widStop                                 [internal]
2028  */
2029 static DWORD widStop(WORD wDevID)
2030 {
2031     TRACE("(%u);\n", wDevID);
2032     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].state == WINE_WS_CLOSED) {
2033         WARN("can't stop !\n");
2034         return MMSYSERR_INVALHANDLE;
2035     }
2036 
2037     ESD_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_STOPPING, 0, TRUE);
2038 
2039     return MMSYSERR_NOERROR;
2040 }
2041 
2042 /**************************************************************************
2043  *                      widReset                                [internal]
2044  */
2045 static DWORD widReset(WORD wDevID)
2046 {
2047     TRACE("(%u);\n", wDevID);
2048     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].state == WINE_WS_CLOSED) {
2049         WARN("can't reset !\n");
2050         return MMSYSERR_INVALHANDLE;
2051     }
2052     ESD_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
2053     return MMSYSERR_NOERROR;
2054 }
2055 
2056 /**************************************************************************
2057  *                              widMessage (WINEESD.6)
2058  */
2059 DWORD WINAPI ESD_widMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
2060                             DWORD_PTR dwParam1, DWORD_PTR dwParam2)
2061 {
2062     TRACE("(%u, %04X, %08X, %08lX, %08lX);\n",
2063           wDevID, wMsg, dwUser, dwParam1, dwParam2);
2064     switch (wMsg) {
2065     case DRVM_INIT:
2066     case DRVM_EXIT:
2067     case DRVM_ENABLE:
2068     case DRVM_DISABLE:
2069         /* FIXME: Pretend this is supported */
2070         return 0;
2071     case WIDM_OPEN:             return widOpen          (wDevID, (LPWAVEOPENDESC)dwParam1,      dwParam2);
2072     case WIDM_CLOSE:            return widClose         (wDevID);
2073     case WIDM_ADDBUFFER:        return widAddBuffer     (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2074     case WIDM_PREPARE:          return MMSYSERR_NOTSUPPORTED;
2075     case WIDM_UNPREPARE:        return MMSYSERR_NOTSUPPORTED;
2076     case WIDM_GETDEVCAPS:       return widGetDevCaps    (wDevID, (LPWAVEINCAPSW)dwParam1,       dwParam2);
2077     case WIDM_GETNUMDEVS:       return widGetNumDevs    ();
2078     case WIDM_RESET:            return widReset         (wDevID);
2079     case WIDM_START:            return widStart         (wDevID);
2080     case WIDM_STOP:             return widStop          (wDevID);
2081     case DRV_QUERYDEVICEINTERFACESIZE: return widDevInterfaceSize       (wDevID, (LPDWORD)dwParam1);
2082     case DRV_QUERYDEVICEINTERFACE:     return widDevInterface           (wDevID, (PWCHAR)dwParam1, dwParam2);
2083     default:
2084         FIXME("unknown message %d!\n", wMsg);
2085     }
2086     return MMSYSERR_NOTSUPPORTED;
2087 }
2088 
2089 /*======================================================================*
2090  *                  Low level DSOUND implementation                     *
2091  *======================================================================*/
2092 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
2093 {
2094     /* we can't perform memory mapping as we don't have a file stream
2095         interface with esd like we do with oss */
2096     MESSAGE("This sound card's driver does not support direct access\n");
2097     MESSAGE("The (slower) DirectSound HEL mode will be used instead.\n");
2098     return MMSYSERR_NOTSUPPORTED;
2099 }
2100 
2101 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc)
2102 {
2103     memset(desc, 0, sizeof(*desc));
2104     strcpy(desc->szDesc, "Wine EsounD DirectSound Driver");
2105     strcpy(desc->szDrvname, "wineesd.drv");
2106     return MMSYSERR_NOERROR;
2107 }
2108 
2109 #else /* !HAVE_ESD */
2110 
2111 /**************************************************************************
2112  *                              wodMessage (WINEESD.@)
2113  */
2114 DWORD WINAPI ESD_wodMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2115                             DWORD_PTR dwParam1, DWORD_PTR dwParam2)
2116 {
2117     FIXME("(%u, %04X, %08X, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2118     return MMSYSERR_NOTENABLED;
2119 }
2120 
2121 /**************************************************************************
2122  *                              widMessage (WINEESD.6)
2123  */
2124 DWORD WINAPI ESD_widMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
2125                             DWORD_PTR dwParam1, DWORD_PTR dwParam2)
2126 {
2127     FIXME("(%u, %04X, %08X, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2128     return MMSYSERR_NOTENABLED;
2129 }
2130 
2131 #endif /* HAVE_ESD */
2132 

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~ [ freetext search ] ~ [ file search ] ~

This page was automatically generated by the LXR engine.
Visit the LXR main site for more information.