kernel: Use a standard LoadLibrary call to load the main exe.
[wine] / dlls / winmm / winenas / audio.c
1 /* -*- tab-width: 8; c-basic-offset: 4 -*- */
2 /*
3  * Wine Driver for NAS Network Audio System
4  *   http://radscan.com/nas.html
5  *
6  * Copyright 1994 Martin Ayotte
7  *           1999 Eric Pouech (async playing in waveOut/waveIn)
8  *           2000 Eric Pouech (loops in waveOut)
9  *           2002 Chris Morgan (aRts version of this file)
10  *           2002 Nicolas Escuder (NAS version of this file)
11  *
12  * Copyright 2002 Nicolas Escuder <n.escuder@alineanet.com>
13  *
14  * This library is free software; you can redistribute it and/or
15  * modify it under the terms of the GNU Lesser General Public
16  * License as published by the Free Software Foundation; either
17  * version 2.1 of the License, or (at your option) any later version.
18  *
19  * This library is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
22  * Lesser General Public License for more details.
23  *
24  * You should have received a copy of the GNU Lesser General Public
25  * License along with this library; if not, write to the Free Software
26  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
27  */
28 /* NOTE:
29  *    with nas we cannot stop the audio that is already in
30  *    the servers buffer.
31  *
32  * FIXME:
33  *      pause in waveOut does not work correctly in loop mode
34  *
35  */
36
37 #include "config.h"
38
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 #ifdef HAVE_SYS_TIME_H
47 # include <sys/time.h>
48 #endif
49 #include <fcntl.h>
50 #include <math.h>
51
52 #define FRAG_SIZE  1024
53 #define FRAG_COUNT 10
54
55 /* avoid type conflicts */
56 #define INT8 X_INT8
57 #define INT16 X_INT16
58 #define INT32 X_INT32
59 #define BOOL X_BOOL
60 #define BYTE X_BYTE
61 #ifdef HAVE_AUDIO_AUDIOLIB_H
62 #include <audio/audiolib.h>
63 #endif
64 #ifdef HAVE_AUDIO_SOUNDLIB_H
65 #include <audio/soundlib.h>
66 #endif
67 #undef INT8
68 #undef INT16
69 #undef INT32
70 #undef BOOL
71 #undef BYTE
72
73 #include "windef.h"
74 #include "winbase.h"
75 #include "wingdi.h"
76 #include "winuser.h"
77 #include "winerror.h"
78 #include "mmddk.h"
79 #include "dsound.h"
80 #include "dsdriver.h"
81 #include "nas.h"
82 #include "wine/unicode.h"
83 #include "wine/debug.h"
84
85 WINE_DEFAULT_DEBUG_CHANNEL(wave);
86
87 /* Allow 1% deviation for sample rates (some ES137x cards) */
88 #define NEAR_MATCH(rate1,rate2) (((100*((int)(rate1)-(int)(rate2)))/(rate1))==0)
89
90 #ifdef HAVE_NAS
91
92 static AuServer         *AuServ;
93
94 #define MAX_WAVEOUTDRV  (1)
95
96 /* state diagram for waveOut writing:
97  *
98  * +---------+-------------+---------------+---------------------------------+
99  * |  state  |  function   |     event     |            new state            |
100  * +---------+-------------+---------------+---------------------------------+
101  * |         | open()      |               | STOPPED                         |
102  * | PAUSED  | write()     |               | PAUSED                          |
103  * | STOPPED | write()     | <thrd create> | PLAYING                         |
104  * | PLAYING | write()     | HEADER        | PLAYING                         |
105  * | (other) | write()     | <error>       |                                 |
106  * | (any)   | pause()     | PAUSING       | PAUSED                          |
107  * | PAUSED  | restart()   | RESTARTING    | PLAYING (if no thrd => STOPPED) |
108  * | (any)   | reset()     | RESETTING     | STOPPED                         |
109  * | (any)   | close()     | CLOSING       | CLOSED                          |
110  * +---------+-------------+---------------+---------------------------------+
111  */
112
113 /* states of the playing device */
114 #define WINE_WS_PLAYING         0
115 #define WINE_WS_PAUSED          1
116 #define WINE_WS_STOPPED         2
117 #define WINE_WS_CLOSED          3
118
119 /* events to be send to device */
120 enum win_wm_message {
121     WINE_WM_PAUSING = WM_USER + 1, WINE_WM_RESTARTING, WINE_WM_RESETTING, WINE_WM_HEADER,
122     WINE_WM_UPDATE, WINE_WM_BREAKLOOP, WINE_WM_CLOSING
123 };
124
125 typedef struct {
126     enum win_wm_message         msg;    /* message identifier */
127     DWORD                       param;  /* parameter for this message */
128     HANDLE                      hEvent; /* if message is synchronous, handle of event for synchro */
129 } RING_MSG;
130
131 /* implement an in-process message ring for better performance
132  * (compared to passing thru the server)
133  * this ring will be used by the input (resp output) record (resp playback) routine
134  */
135 #define NAS_RING_BUFFER_INCREMENT      64
136 typedef struct {
137     RING_MSG                    * messages;
138     int                         ring_buffer_size;
139     int                         msg_tosave;
140     int                         msg_toget;
141     HANDLE                      msg_event;
142     CRITICAL_SECTION            msg_crst;
143 } MSG_RING;
144
145 typedef struct {
146     volatile int                state;                  /* one of the WINE_WS_ manifest constants */
147     WAVEOPENDESC                waveDesc;
148     WORD                        wFlags;
149     PCMWAVEFORMAT               format;
150     WAVEOUTCAPSW                caps;
151     int                         Id;
152
153     int                         open;
154     AuServer                    *AuServ;
155     AuDeviceID                  AuDev;
156     AuFlowID                    AuFlow;
157     BOOL                        FlowStarted;
158
159     DWORD                       writeBytes;
160     DWORD                       freeBytes;
161     DWORD                       sendBytes;
162
163     DWORD                       BufferSize;           /* size of whole buffer in bytes */
164
165     char*                       SoundBuffer;
166     long                        BufferUsed;
167
168     DWORD                       volume_left;            /* volume control information */
169     DWORD                       volume_right;
170
171     LPWAVEHDR                   lpQueuePtr;             /* start of queued WAVEHDRs (waiting to be notified) */
172     LPWAVEHDR                   lpPlayPtr;              /* start of not yet fully played buffers */
173
174     LPWAVEHDR                   lpLoopPtr;              /* pointer of first buffer in loop, if any */
175     DWORD                       dwLoops;                /* private copy of loop counter */
176
177     DWORD                       PlayedTotal;            /* number of bytes actually played since opening */
178     DWORD                       WrittenTotal;         /* number of bytes written to the audio device since opening */
179
180     /* synchronization stuff */
181     HANDLE                      hStartUpEvent;
182     HANDLE                      hThread;
183     DWORD                       dwThreadID;
184     MSG_RING                    msgRing;
185 } WINE_WAVEOUT;
186
187 static WINE_WAVEOUT     WOutDev   [MAX_WAVEOUTDRV];
188
189 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv);
190 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc);
191
192
193 /* NASFUNC */
194 static AuBool event_handler(AuServer* aud, AuEvent* ev, AuEventHandlerRec* hnd);
195 static int nas_init(void);
196 static int nas_end(void);
197
198 static int nas_finddev(WINE_WAVEOUT* wwo);
199 static int nas_open(WINE_WAVEOUT* wwo);
200 static int nas_free(WINE_WAVEOUT* wwo);
201 static int nas_close(WINE_WAVEOUT* wwo);
202 static void buffer_resize(WINE_WAVEOUT* wwo, int len);
203 static int nas_add_buffer(WINE_WAVEOUT* wwo);
204 static int nas_send_buffer(WINE_WAVEOUT* wwo);
205
206 /* These strings used only for tracing */
207 static const char * const wodPlayerCmdString[] = {
208     "WINE_WM_PAUSING",
209     "WINE_WM_RESTARTING",
210     "WINE_WM_RESETTING",
211     "WINE_WM_HEADER",
212     "WINE_WM_UPDATE",
213     "WINE_WM_BREAKLOOP",
214     "WINE_WM_CLOSING",
215 };
216
217 static const char * const nas_elementnotify_kinds[] = {
218         "LowWater",
219         "HighWater",
220         "State",
221         "Unknown"
222 };
223
224 static const char * const nas_states[] = {
225         "Stop",
226         "Start",
227         "Pause",
228         "Any"
229 };
230
231 static const char * const nas_reasons[] = {
232         "User",
233         "Underrun",
234         "Overrun",
235         "EOF",
236         "Watermark",
237         "Hardware",
238         "Any"
239 };
240
241 static const char* nas_reason(unsigned int reason)
242 {
243         if (reason > 6) reason = 6;
244         return nas_reasons[reason];
245 }
246
247 static const char* nas_elementnotify_kind(unsigned int kind)
248 {
249         if (kind > 2) kind = 3;
250         return nas_elementnotify_kinds[kind];
251 }
252
253
254 #if 0
255 static const char* nas_event_type(unsigned int type)
256 {
257         static const char * const nas_event_types[] =
258         {
259             "Undefined",
260             "Undefined",
261             "ElementNotify",
262             "GrabNotify",
263             "MonitorNotify",
264             "BucketNotify",
265             "DeviceNotify"
266         };
267
268         if (type > 6) type = 0;
269         return nas_event_types[type];
270 }
271 #endif
272
273
274 static const char* nas_state(unsigned int state)
275 {
276         if (state > 3) state = 3;
277         return nas_states[state];
278 }
279
280 static DWORD bytes_to_mmtime(LPMMTIME lpTime, DWORD position,
281                              PCMWAVEFORMAT* format)
282 {
283     TRACE("wType=%04X wBitsPerSample=%u nSamplesPerSec=%lu nChannels=%u nAvgBytesPerSec=%lu\n",
284           lpTime->wType, format->wBitsPerSample, format->wf.nSamplesPerSec,
285           format->wf.nChannels, format->wf.nAvgBytesPerSec);
286     TRACE("Position in bytes=%lu\n", position);
287
288     switch (lpTime->wType) {
289     case TIME_SAMPLES:
290         lpTime->u.sample = position / (format->wBitsPerSample / 8 * format->wf.nChannels);
291         TRACE("TIME_SAMPLES=%lu\n", lpTime->u.sample);
292         break;
293     case TIME_MS:
294         lpTime->u.ms = 1000.0 * position / (format->wBitsPerSample / 8 * format->wf.nChannels * format->wf.nSamplesPerSec);
295         TRACE("TIME_MS=%lu\n", lpTime->u.ms);
296         break;
297     case TIME_SMPTE:
298         lpTime->u.smpte.fps = 30;
299         position = position / (format->wBitsPerSample / 8 * format->wf.nChannels);
300         position += (format->wf.nSamplesPerSec / lpTime->u.smpte.fps) - 1; /* round up */
301         lpTime->u.smpte.sec = position / format->wf.nSamplesPerSec;
302         position -= lpTime->u.smpte.sec * format->wf.nSamplesPerSec;
303         lpTime->u.smpte.min = lpTime->u.smpte.sec / 60;
304         lpTime->u.smpte.sec -= 60 * lpTime->u.smpte.min;
305         lpTime->u.smpte.hour = lpTime->u.smpte.min / 60;
306         lpTime->u.smpte.min -= 60 * lpTime->u.smpte.hour;
307         lpTime->u.smpte.fps = 30;
308         lpTime->u.smpte.frame = position * lpTime->u.smpte.fps / format->wf.nSamplesPerSec;
309         TRACE("TIME_SMPTE=%02u:%02u:%02u:%02u\n",
310               lpTime->u.smpte.hour, lpTime->u.smpte.min,
311               lpTime->u.smpte.sec, lpTime->u.smpte.frame);
312         break;
313     default:
314         WARN("Format %d not supported, using TIME_BYTES !\n", lpTime->wType);
315         lpTime->wType = TIME_BYTES;
316         /* fall through */
317     case TIME_BYTES:
318         lpTime->u.cb = position;
319         TRACE("TIME_BYTES=%lu\n", lpTime->u.cb);
320         break;
321     }
322     return MMSYSERR_NOERROR;
323 }
324
325 /*======================================================================*
326  *                  Low level WAVE implementation                       *
327  *======================================================================*/
328 #if 0
329 /* Volume functions derived from Alsaplayer source */
330 /* length is the number of 16 bit samples */
331 static void volume_effect16(void *bufin, void* bufout, int length, int left,
332                             int right, int nChannels)
333 {
334   short *d_out = (short *)bufout;
335   short *d_in = (short *)bufin;
336   int i, v;
337
338 /*
339   TRACE("length == %d, nChannels == %d\n", length, nChannels);
340 */
341
342   if (right == -1) right = left;
343
344   for(i = 0; i < length; i+=(nChannels))
345   {
346     v = (int) ((*(d_in++) * left) / 100);
347     *(d_out++) = (v>32767) ? 32767 : ((v<-32768) ? -32768 : v);
348     if(nChannels == 2)
349     {
350       v = (int) ((*(d_in++) * right) / 100);
351       *(d_out++) = (v>32767) ? 32767 : ((v<-32768) ? -32768 : v);
352     }
353   }
354 }
355
356 /* length is the number of 8 bit samples */
357 static void volume_effect8(void *bufin, void* bufout, int length, int left,
358                            int right, int nChannels)
359 {
360   char *d_out = (char *)bufout;
361   char *d_in = (char *)bufin;
362   int i, v;
363
364 /*
365   TRACE("length == %d, nChannels == %d\n", length, nChannels);
366 */
367
368   if (right == -1) right = left;
369
370   for(i = 0; i < length; i+=(nChannels))
371   {
372     v = (char) ((*(d_in++) * left) / 100);
373     *(d_out++) = (v>255) ? 255 : ((v<0) ? 0 : v);
374     if(nChannels == 2)
375     {
376       v = (char) ((*(d_in++) * right) / 100);
377       *(d_out++) = (v>255) ? 255 : ((v<0) ? 0 : v);
378     }
379   }
380 }
381 #endif
382
383 /******************************************************************
384  *              NAS_CloseDevice
385  *
386  */
387 static void NAS_CloseDevice(WINE_WAVEOUT* wwo)
388 {
389   TRACE("NAS_CloseDevice\n");
390   nas_close(wwo);
391 }
392
393 /******************************************************************
394  *              NAS_WaveClose
395  */
396 LONG            NAS_WaveClose(void)
397 {
398     nas_end();    /* free up nas server */
399     return 1;
400 }
401
402 /******************************************************************
403  *              NAS_WaveInit
404  *
405  * Initialize internal structures from NAS server info
406  */
407 LONG NAS_WaveInit(void)
408 {
409     int         i;
410     if (!nas_init()) return MMSYSERR_ERROR;
411
412     /* initialize all device handles to -1 */
413     for (i = 0; i < MAX_WAVEOUTDRV; ++i)
414     {
415         static const WCHAR ini[] = {'N','A','S',' ','W','A','V','E','O','U','T',' ','D','r','i','v','e','r',0};
416         memset(&WOutDev[i].caps, 0, sizeof(WOutDev[i].caps)); /* zero out caps values */
417
418         WOutDev[i].AuServ = AuServ;
419         WOutDev[i].AuDev = AuNone;
420         WOutDev[i].Id = i;
421         WOutDev[i].caps.wMid = 0x00FF;  /* Manufac ID */
422         WOutDev[i].caps.wPid = 0x0001;  /* Product ID */
423         strcpyW(WOutDev[i].caps.szPname, ini);
424         WOutDev[i].AuFlow = 0;
425         WOutDev[i].caps.vDriverVersion = 0x0100;
426         WOutDev[i].caps.dwFormats = 0x00000000;
427         WOutDev[i].caps.dwSupport = WAVECAPS_VOLUME;
428
429         WOutDev[i].caps.wChannels = 2;
430         WOutDev[i].caps.dwSupport |= WAVECAPS_LRVOLUME;
431
432         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4M08;
433         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4S08;
434         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4S16;
435         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4M16;
436         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2M08;
437         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2S08;
438         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2M16;
439         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2S16;
440         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1M08;
441         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1S08;
442         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1M16;
443         WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1S16;
444     }
445
446
447     return 0;
448 }
449
450 /******************************************************************
451  *              NAS_InitRingMessage
452  *
453  * Initialize the ring of messages for passing between driver's caller and playback/record
454  * thread
455  */
456 static int NAS_InitRingMessage(MSG_RING* mr)
457 {
458     mr->msg_toget = 0;
459     mr->msg_tosave = 0;
460     mr->msg_event = CreateEventW(NULL, FALSE, FALSE, NULL);
461     mr->ring_buffer_size = NAS_RING_BUFFER_INCREMENT;
462     mr->messages = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,mr->ring_buffer_size * sizeof(RING_MSG));
463     InitializeCriticalSection(&mr->msg_crst);
464     return 0;
465 }
466
467 /******************************************************************
468  *              NAS_DestroyRingMessage
469  *
470  */
471 static int NAS_DestroyRingMessage(MSG_RING* mr)
472 {
473     CloseHandle(mr->msg_event);
474     HeapFree(GetProcessHeap(),0,mr->messages);
475     DeleteCriticalSection(&mr->msg_crst);
476     return 0;
477 }
478
479 /******************************************************************
480  *              NAS_AddRingMessage
481  *
482  * Inserts a new message into the ring (should be called from DriverProc derivated routines)
483  */
484 static int NAS_AddRingMessage(MSG_RING* mr, enum win_wm_message msg, DWORD param, BOOL wait)
485 {
486     HANDLE      hEvent = INVALID_HANDLE_VALUE;
487
488     EnterCriticalSection(&mr->msg_crst);
489     if ((mr->msg_toget == ((mr->msg_tosave + 1) % mr->ring_buffer_size)))
490     {
491         int old_ring_buffer_size = mr->ring_buffer_size;
492         mr->ring_buffer_size += NAS_RING_BUFFER_INCREMENT;
493         TRACE("omr->ring_buffer_size=%d\n",mr->ring_buffer_size);
494         mr->messages = HeapReAlloc(GetProcessHeap(),0,mr->messages, mr->ring_buffer_size * sizeof(RING_MSG));
495         /* Now we need to rearrange the ring buffer so that the new
496            buffers just allocated are in between mr->msg_tosave and
497            mr->msg_toget.
498         */
499         if (mr->msg_tosave < mr->msg_toget)
500         {
501             memmove(&(mr->messages[mr->msg_toget + NAS_RING_BUFFER_INCREMENT]),
502                     &(mr->messages[mr->msg_toget]),
503                     sizeof(RING_MSG)*(old_ring_buffer_size - mr->msg_toget)
504                     );
505             mr->msg_toget += NAS_RING_BUFFER_INCREMENT;
506         }
507     }
508     if (wait)
509     {
510         hEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
511         if (hEvent == INVALID_HANDLE_VALUE)
512         {
513             ERR("can't create event !?\n");
514             LeaveCriticalSection(&mr->msg_crst);
515             return 0;
516         }
517         if (mr->msg_toget != mr->msg_tosave && mr->messages[mr->msg_toget].msg != WINE_WM_HEADER)
518             FIXME("two fast messages in the queue!!!!\n");
519
520         /* fast messages have to be added at the start of the queue */
521         mr->msg_toget = (mr->msg_toget + mr->ring_buffer_size - 1) % mr->ring_buffer_size;
522
523         mr->messages[mr->msg_toget].msg = msg;
524         mr->messages[mr->msg_toget].param = param;
525         mr->messages[mr->msg_toget].hEvent = hEvent;
526     }
527     else
528     {
529         mr->messages[mr->msg_tosave].msg = msg;
530         mr->messages[mr->msg_tosave].param = param;
531         mr->messages[mr->msg_tosave].hEvent = INVALID_HANDLE_VALUE;
532         mr->msg_tosave = (mr->msg_tosave + 1) % mr->ring_buffer_size;
533     }
534
535     LeaveCriticalSection(&mr->msg_crst);
536
537     SetEvent(mr->msg_event);    /* signal a new message */
538
539     if (wait)
540     {
541         /* wait for playback/record thread to have processed the message */
542         WaitForSingleObject(hEvent, INFINITE);
543         CloseHandle(hEvent);
544     }
545
546     return 1;
547 }
548
549 /******************************************************************
550  *              NAS_RetrieveRingMessage
551  *
552  * Get a message from the ring. Should be called by the playback/record thread.
553  */
554 static int NAS_RetrieveRingMessage(MSG_RING* mr,
555                                    enum win_wm_message *msg, DWORD *param, HANDLE *hEvent)
556 {
557     EnterCriticalSection(&mr->msg_crst);
558
559     if (mr->msg_toget == mr->msg_tosave) /* buffer empty ? */
560     {
561         LeaveCriticalSection(&mr->msg_crst);
562         return 0;
563     }
564
565     *msg = mr->messages[mr->msg_toget].msg;
566     mr->messages[mr->msg_toget].msg = 0;
567     *param = mr->messages[mr->msg_toget].param;
568     *hEvent = mr->messages[mr->msg_toget].hEvent;
569     mr->msg_toget = (mr->msg_toget + 1) % mr->ring_buffer_size;
570     LeaveCriticalSection(&mr->msg_crst);
571     return 1;
572 }
573
574 /*======================================================================*
575  *                  Low level WAVE OUT implementation                   *
576  *======================================================================*/
577
578 /**************************************************************************
579  *                      wodNotifyClient                 [internal]
580  */
581 static DWORD wodNotifyClient(WINE_WAVEOUT* wwo, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
582 {
583     TRACE("wMsg = 0x%04x dwParm1 = %04lX dwParam2 = %04lX\n", wMsg, dwParam1, dwParam2);
584
585     switch (wMsg) {
586     case WOM_OPEN:
587     case WOM_CLOSE:
588     case WOM_DONE:
589         if (wwo->wFlags != DCB_NULL &&
590             !DriverCallback(wwo->waveDesc.dwCallback, wwo->wFlags, (HDRVR)wwo->waveDesc.hWave,
591                             wMsg, wwo->waveDesc.dwInstance, dwParam1, dwParam2)) {
592             WARN("can't notify client !\n");
593             return MMSYSERR_ERROR;
594         }
595         break;
596     default:
597         FIXME("Unknown callback message %u\n", wMsg);
598         return MMSYSERR_INVALPARAM;
599     }
600     return MMSYSERR_NOERROR;
601 }
602
603 /**************************************************************************
604  *                              wodUpdatePlayedTotal    [internal]
605  *
606  */
607 static BOOL wodUpdatePlayedTotal(WINE_WAVEOUT* wwo)
608 {
609     wwo->PlayedTotal = wwo->WrittenTotal;
610     return TRUE;
611 }
612
613 /**************************************************************************
614  *                              wodPlayer_BeginWaveHdr          [internal]
615  *
616  * Makes the specified lpWaveHdr the currently playing wave header.
617  * If the specified wave header is a begin loop and we're not already in
618  * a loop, setup the loop.
619  */
620 static void wodPlayer_BeginWaveHdr(WINE_WAVEOUT* wwo, LPWAVEHDR lpWaveHdr)
621 {
622     wwo->lpPlayPtr = lpWaveHdr;
623
624     if (!lpWaveHdr) return;
625
626     if (lpWaveHdr->dwFlags & WHDR_BEGINLOOP) {
627         if (wwo->lpLoopPtr) {
628             WARN("Already in a loop. Discarding loop on this header (%p)\n", lpWaveHdr);
629             TRACE("Already in a loop. Discarding loop on this header (%p)\n", lpWaveHdr);
630         } else {
631             TRACE("Starting loop (%ldx) with %p\n", lpWaveHdr->dwLoops, lpWaveHdr);
632             wwo->lpLoopPtr = lpWaveHdr;
633             /* Windows does not touch WAVEHDR.dwLoops,
634              * so we need to make an internal copy */
635             wwo->dwLoops = lpWaveHdr->dwLoops;
636         }
637     }
638 }
639
640 /**************************************************************************
641  *                              wodPlayer_PlayPtrNext           [internal]
642  *
643  * Advance the play pointer to the next waveheader, looping if required.
644  */
645 static LPWAVEHDR wodPlayer_PlayPtrNext(WINE_WAVEOUT* wwo)
646 {
647     LPWAVEHDR lpWaveHdr = wwo->lpPlayPtr;
648
649     if ((lpWaveHdr->dwFlags & WHDR_ENDLOOP) && wwo->lpLoopPtr) {
650         /* We're at the end of a loop, loop if required */
651         if (--wwo->dwLoops > 0) {
652             wwo->lpPlayPtr = wwo->lpLoopPtr;
653         } else {
654             /* Handle overlapping loops correctly */
655             if (wwo->lpLoopPtr != lpWaveHdr && (lpWaveHdr->dwFlags & WHDR_BEGINLOOP)) {
656                 FIXME("Correctly handled case ? (ending loop buffer also starts a new loop)\n");
657                 /* shall we consider the END flag for the closing loop or for
658                  * the opening one or for both ???
659                  * code assumes for closing loop only
660                  */
661             } else {
662                 lpWaveHdr = lpWaveHdr->lpNext;
663             }
664             wwo->lpLoopPtr = NULL;
665             wodPlayer_BeginWaveHdr(wwo, lpWaveHdr);
666         }
667     } else {
668         /* We're not in a loop.  Advance to the next wave header */
669         wodPlayer_BeginWaveHdr(wwo, lpWaveHdr = lpWaveHdr->lpNext);
670     }
671     return lpWaveHdr;
672 }
673
674 /**************************************************************************
675  *                              wodPlayer_NotifyCompletions     [internal]
676  *
677  * Notifies and remove from queue all wavehdrs which have been played to
678  * the speaker (ie. they have cleared the audio device).  If force is true,
679  * we notify all wavehdrs and remove them all from the queue even if they
680  * are unplayed or part of a loop.
681  */
682 static DWORD wodPlayer_NotifyCompletions(WINE_WAVEOUT* wwo, BOOL force)
683 {
684     LPWAVEHDR           lpWaveHdr;
685
686     /* Start from lpQueuePtr and keep notifying until:
687      * - we hit an unwritten wavehdr
688      * - we hit the beginning of a running loop
689      * - we hit a wavehdr which hasn't finished playing
690      */
691     wodUpdatePlayedTotal(wwo);
692
693     while ((lpWaveHdr = wwo->lpQueuePtr) && (force || (lpWaveHdr != wwo->lpPlayPtr &&
694             lpWaveHdr != wwo->lpLoopPtr && lpWaveHdr->reserved <= wwo->PlayedTotal))) {
695
696         wwo->lpQueuePtr = lpWaveHdr->lpNext;
697
698         lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
699         lpWaveHdr->dwFlags |= WHDR_DONE;
700
701         wodNotifyClient(wwo, WOM_DONE, (DWORD)lpWaveHdr, 0);
702     }
703     return  (lpWaveHdr && lpWaveHdr != wwo->lpPlayPtr && lpWaveHdr != wwo->lpLoopPtr) ?
704             1 : 1;
705 }
706
707 /**************************************************************************
708  *                              wodPlayer_Reset                 [internal]
709  *
710  * wodPlayer helper. Resets current output stream.
711  */
712 static  void    wodPlayer_Reset(WINE_WAVEOUT* wwo, BOOL reset)
713 {
714     wodUpdatePlayedTotal(wwo);
715     wodPlayer_NotifyCompletions(wwo, FALSE); /* updates current notify list */
716
717     /* we aren't able to flush any data that has already been written */
718     /* to nas, otherwise we would do the flushing here */
719
720     nas_free(wwo);
721
722     if (reset) {
723         enum win_wm_message     msg;
724         DWORD                   param;
725         HANDLE                  ev;
726
727         /* remove any buffer */
728         wodPlayer_NotifyCompletions(wwo, TRUE);
729
730         wwo->lpPlayPtr = wwo->lpQueuePtr = wwo->lpLoopPtr = NULL;
731         wwo->state = WINE_WS_STOPPED;
732         wwo->PlayedTotal = wwo->WrittenTotal = 0;
733
734         /* remove any existing message in the ring */
735         EnterCriticalSection(&wwo->msgRing.msg_crst);
736
737         /* return all pending headers in queue */
738         while (NAS_RetrieveRingMessage(&wwo->msgRing, &msg, &param, &ev))
739         {
740             TRACE("flushing msg\n");
741             if (msg != WINE_WM_HEADER)
742             {
743                 FIXME("shouldn't have headers left\n");
744                 SetEvent(ev);
745                 continue;
746             }
747             ((LPWAVEHDR)param)->dwFlags &= ~WHDR_INQUEUE;
748             ((LPWAVEHDR)param)->dwFlags |= WHDR_DONE;
749
750             wodNotifyClient(wwo, WOM_DONE, param, 0);
751         }
752         ResetEvent(wwo->msgRing.msg_event);
753         LeaveCriticalSection(&wwo->msgRing.msg_crst);
754     } else {
755         if (wwo->lpLoopPtr) {
756             /* complicated case, not handled yet (could imply modifying the loop counter */
757             FIXME("Pausing while in loop isn't correctly handled yet, except strange results\n");
758             wwo->lpPlayPtr = wwo->lpLoopPtr;
759             wwo->WrittenTotal = wwo->PlayedTotal; /* this is wrong !!! */
760         } else {
761             /* the data already written is going to be played, so take */
762             /* this fact into account here */
763             wwo->PlayedTotal = wwo->WrittenTotal;
764         }
765         wwo->state = WINE_WS_PAUSED;
766     }
767 }
768
769 /**************************************************************************
770  *                    wodPlayer_ProcessMessages                 [internal]
771  */
772 static void wodPlayer_ProcessMessages(WINE_WAVEOUT* wwo)
773 {
774     LPWAVEHDR           lpWaveHdr;
775     enum win_wm_message msg;
776     DWORD               param;
777     HANDLE              ev;
778
779     while (NAS_RetrieveRingMessage(&wwo->msgRing, &msg, &param, &ev)) {
780         TRACE("Received %s %lx\n", wodPlayerCmdString[msg - WM_USER - 1], param);
781         switch (msg) {
782         case WINE_WM_PAUSING:
783             wodPlayer_Reset(wwo, FALSE);
784             SetEvent(ev);
785             break;
786         case WINE_WM_RESTARTING:
787             wwo->state = WINE_WS_PLAYING;
788             SetEvent(ev);
789             break;
790         case WINE_WM_HEADER:
791             lpWaveHdr = (LPWAVEHDR)param;
792
793             /* insert buffer at the end of queue */
794             {
795                 LPWAVEHDR*      wh;
796                 for (wh = &(wwo->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
797                 *wh = lpWaveHdr;
798             }
799             if (!wwo->lpPlayPtr)
800                 wodPlayer_BeginWaveHdr(wwo,lpWaveHdr);
801             if (wwo->state == WINE_WS_STOPPED)
802                 wwo->state = WINE_WS_PLAYING;
803             break;
804         case WINE_WM_RESETTING:
805             wodPlayer_Reset(wwo, TRUE);
806             SetEvent(ev);
807             break;
808         case WINE_WM_UPDATE:
809             wodUpdatePlayedTotal(wwo);
810             SetEvent(ev);
811             break;
812         case WINE_WM_BREAKLOOP:
813             if (wwo->state == WINE_WS_PLAYING && wwo->lpLoopPtr != NULL) {
814                 /* ensure exit at end of current loop */
815                 wwo->dwLoops = 1;
816             }
817             SetEvent(ev);
818             break;
819         case WINE_WM_CLOSING:
820             /* sanity check: this should not happen since the device must have been reset before */
821             if (wwo->lpQueuePtr || wwo->lpPlayPtr) ERR("out of sync\n");
822             wwo->hThread = 0;
823             wwo->state = WINE_WS_CLOSED;
824             SetEvent(ev);
825             ExitThread(0);
826             /* shouldn't go here */
827         default:
828             FIXME("unknown message %d\n", msg);
829             break;
830         }
831     }
832 }
833
834 /**************************************************************************
835  *                              wodPlayer                       [internal]
836  */
837 static  DWORD   CALLBACK        wodPlayer(LPVOID pmt)
838 {
839     WORD          uDevID = (DWORD)pmt;
840     WINE_WAVEOUT* wwo = (WINE_WAVEOUT*)&WOutDev[uDevID];
841
842     wwo->state = WINE_WS_STOPPED;
843     SetEvent(wwo->hStartUpEvent);
844
845     for (;;) {
846
847         if (wwo->FlowStarted) {
848            AuHandleEvents(wwo->AuServ);
849
850            if (wwo->state == WINE_WS_PLAYING && wwo->freeBytes && wwo->BufferUsed)
851               nas_send_buffer(wwo);
852         }
853
854         if (wwo->BufferUsed <= FRAG_SIZE && wwo->writeBytes > 0)
855            wodPlayer_NotifyCompletions(wwo, FALSE);
856
857         WaitForSingleObject(wwo->msgRing.msg_event, 20);
858         wodPlayer_ProcessMessages(wwo);
859
860         while(wwo->lpPlayPtr) {
861            wwo->lpPlayPtr->reserved = wwo->WrittenTotal + wwo->lpPlayPtr->dwBufferLength;
862            nas_add_buffer(wwo);
863            wodPlayer_PlayPtrNext(wwo);
864         }
865
866     }
867 }
868
869 /**************************************************************************
870  *                      wodGetDevCaps                           [internal]
871  */
872 static DWORD wodGetDevCaps(WORD wDevID, LPWAVEOUTCAPSW lpCaps, DWORD dwSize)
873 {
874     TRACE("(%u, %p, %lu);\n", wDevID, lpCaps, dwSize);
875
876     if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
877
878     if (wDevID >= MAX_WAVEOUTDRV) {
879         TRACE("MAX_WAVOUTDRV reached !\n");
880         return MMSYSERR_BADDEVICEID;
881     }
882
883     memcpy(lpCaps, &WOutDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
884     return MMSYSERR_NOERROR;
885 }
886
887 /**************************************************************************
888  *                              wodOpen                         [internal]
889  */
890 static DWORD wodOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
891 {
892     WINE_WAVEOUT*       wwo;
893
894     TRACE("wodOpen (%u, %p, %08lX);\n", wDevID, lpDesc, dwFlags);
895
896     if (lpDesc == NULL) {
897         WARN("Invalid Parameter !\n");
898         return MMSYSERR_INVALPARAM;
899     }
900     if (wDevID >= MAX_WAVEOUTDRV) {
901         TRACE("MAX_WAVOUTDRV reached !\n");
902         return MMSYSERR_BADDEVICEID;
903     }
904
905     /* if this device is already open tell the app that it is allocated */
906
907     wwo = &WOutDev[wDevID];
908
909     if(wwo->open)
910     {
911       TRACE("device already allocated\n");
912       return MMSYSERR_ALLOCATED;
913     }
914
915
916     /* only PCM format is supported so far... */
917     if (lpDesc->lpFormat->wFormatTag != WAVE_FORMAT_PCM ||
918         lpDesc->lpFormat->nChannels == 0 ||
919         lpDesc->lpFormat->nSamplesPerSec == 0 ||
920         (lpDesc->lpFormat->wBitsPerSample!=8 && lpDesc->lpFormat->wBitsPerSample!=16)) {
921         WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
922              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
923              lpDesc->lpFormat->nSamplesPerSec);
924         return WAVERR_BADFORMAT;
925     }
926
927     if (dwFlags & WAVE_FORMAT_QUERY) {
928         TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
929              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
930              lpDesc->lpFormat->nSamplesPerSec);
931         return MMSYSERR_NOERROR;
932     }
933
934     /* direct sound not supported, ignore the flag */
935     dwFlags &= ~WAVE_DIRECTSOUND;
936
937     wwo->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
938
939     memcpy(&wwo->waveDesc, lpDesc,           sizeof(WAVEOPENDESC));
940     memcpy(&wwo->format,   lpDesc->lpFormat, sizeof(PCMWAVEFORMAT));
941
942     if (wwo->format.wBitsPerSample == 0) {
943         WARN("Resetting zeroed wBitsPerSample\n");
944         wwo->format.wBitsPerSample = 8 *
945             (wwo->format.wf.nAvgBytesPerSec /
946              wwo->format.wf.nSamplesPerSec) /
947             wwo->format.wf.nChannels;
948     }
949
950     if (!nas_open(wwo))
951        return MMSYSERR_ALLOCATED;
952
953     NAS_InitRingMessage(&wwo->msgRing);
954
955     /* create player thread */
956     if (!(dwFlags & WAVE_DIRECTSOUND)) {
957         wwo->hStartUpEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
958         wwo->hThread = CreateThread(NULL, 0, wodPlayer, (LPVOID)(DWORD)wDevID, 0, &(wwo->dwThreadID));
959         if (wwo->hThread)
960             SetThreadPriority(wwo->hThread, THREAD_PRIORITY_TIME_CRITICAL);
961         WaitForSingleObject(wwo->hStartUpEvent, INFINITE);
962         CloseHandle(wwo->hStartUpEvent);
963     } else {
964         wwo->hThread = INVALID_HANDLE_VALUE;
965         wwo->dwThreadID = 0;
966     }
967     wwo->hStartUpEvent = INVALID_HANDLE_VALUE;
968
969     TRACE("stream=0x%lx, BufferSize=%ld\n", (long)wwo->AuServ, wwo->BufferSize);
970
971     TRACE("wBitsPerSample=%u nAvgBytesPerSec=%lu nSamplesPerSec=%lu nChannels=%u nBlockAlign=%u\n",
972           wwo->format.wBitsPerSample, wwo->format.wf.nAvgBytesPerSec,
973           wwo->format.wf.nSamplesPerSec, wwo->format.wf.nChannels,
974           wwo->format.wf.nBlockAlign);
975
976     return wodNotifyClient(wwo, WOM_OPEN, 0L, 0L);
977 }
978
979 /**************************************************************************
980  *                              wodClose                        [internal]
981  */
982 static DWORD wodClose(WORD wDevID)
983 {
984     DWORD               ret = MMSYSERR_NOERROR;
985     WINE_WAVEOUT*       wwo;
986
987     TRACE("(%u);\n", wDevID);
988
989     if (wDevID >= MAX_WAVEOUTDRV || AuServ  == NULL)
990     {
991         WARN("bad device ID !\n");
992         return MMSYSERR_BADDEVICEID;
993     }
994
995     wwo = &WOutDev[wDevID];
996     if (wwo->lpQueuePtr) {
997         WARN("buffers still playing !\n");
998         ret = WAVERR_STILLPLAYING;
999     } else {
1000         TRACE("imhere[3-close]\n");
1001         if (wwo->hThread != INVALID_HANDLE_VALUE) {
1002             NAS_AddRingMessage(&wwo->msgRing, WINE_WM_CLOSING, 0, TRUE);
1003         }
1004
1005         NAS_DestroyRingMessage(&wwo->msgRing);
1006
1007         NAS_CloseDevice(wwo);   /* close the stream and clean things up */
1008
1009         ret = wodNotifyClient(wwo, WOM_CLOSE, 0L, 0L);
1010     }
1011     return ret;
1012 }
1013
1014 /**************************************************************************
1015  *                              wodWrite                        [internal]
1016  *
1017  */
1018 static DWORD wodWrite(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1019 {
1020     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
1021
1022     /* first, do the sanity checks... */
1023     if (wDevID >= MAX_WAVEOUTDRV || AuServ == NULL)
1024     {
1025         WARN("bad dev ID !\n");
1026         return MMSYSERR_BADDEVICEID;
1027     }
1028
1029     if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
1030     {
1031         TRACE("unprepared\n");
1032         return WAVERR_UNPREPARED;
1033     }
1034
1035     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1036     {
1037         TRACE("still playing\n");
1038         return WAVERR_STILLPLAYING;
1039     }
1040
1041     lpWaveHdr->dwFlags &= ~WHDR_DONE;
1042     lpWaveHdr->dwFlags |= WHDR_INQUEUE;
1043     lpWaveHdr->lpNext = 0;
1044
1045     TRACE("adding ring message\n");
1046     NAS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_HEADER, (DWORD)lpWaveHdr, FALSE);
1047
1048     return MMSYSERR_NOERROR;
1049 }
1050
1051 /**************************************************************************
1052  *                      wodPause                                [internal]
1053  */
1054 static DWORD wodPause(WORD wDevID)
1055 {
1056     TRACE("(%u);!\n", wDevID);
1057
1058     if (wDevID >= MAX_WAVEOUTDRV || AuServ == NULL)
1059     {
1060         WARN("bad device ID !\n");
1061         return MMSYSERR_BADDEVICEID;
1062     }
1063
1064     TRACE("imhere[3-PAUSING]\n");
1065     NAS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_PAUSING, 0, TRUE);
1066
1067     return MMSYSERR_NOERROR;
1068 }
1069
1070 /**************************************************************************
1071  *                      wodRestart                              [internal]
1072  */
1073 static DWORD wodRestart(WORD wDevID)
1074 {
1075     TRACE("(%u);\n", wDevID);
1076
1077     if (wDevID >= MAX_WAVEOUTDRV || AuServ == NULL)
1078     {
1079         WARN("bad device ID !\n");
1080         return MMSYSERR_BADDEVICEID;
1081     }
1082
1083     if (WOutDev[wDevID].state == WINE_WS_PAUSED) {
1084         TRACE("imhere[3-RESTARTING]\n");
1085         NAS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESTARTING, 0, TRUE);
1086     }
1087
1088     /* FIXME: is NotifyClient with WOM_DONE right ? (Comet Busters 1.3.3 needs this notification) */
1089     /* FIXME: Myst crashes with this ... hmm -MM
1090        return wodNotifyClient(wwo, WOM_DONE, 0L, 0L);
1091     */
1092
1093     return MMSYSERR_NOERROR;
1094 }
1095
1096 /**************************************************************************
1097  *                      wodReset                                [internal]
1098  */
1099 static DWORD wodReset(WORD wDevID)
1100 {
1101     TRACE("(%u);\n", wDevID);
1102
1103     if (wDevID >= MAX_WAVEOUTDRV || AuServ == NULL)
1104     {
1105         WARN("bad device ID !\n");
1106         return MMSYSERR_BADDEVICEID;
1107     }
1108
1109     TRACE("imhere[3-RESET]\n");
1110     NAS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
1111
1112     return MMSYSERR_NOERROR;
1113 }
1114
1115 /**************************************************************************
1116  *                              wodGetPosition                  [internal]
1117  */
1118 static DWORD wodGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
1119 {
1120     WINE_WAVEOUT*       wwo;
1121
1122     TRACE("%u, %p, %lu);\n", wDevID, lpTime, uSize);
1123
1124     if (wDevID >= MAX_WAVEOUTDRV || AuServ == NULL)
1125     {
1126         WARN("bad device ID !\n");
1127         return MMSYSERR_BADDEVICEID;
1128     }
1129
1130     if (lpTime == NULL) return MMSYSERR_INVALPARAM;
1131
1132     wwo = &WOutDev[wDevID];
1133 #if 0
1134     NAS_AddRingMessage(&wwo->msgRing, WINE_WM_UPDATE, 0, TRUE);
1135 #endif
1136
1137     return bytes_to_mmtime(lpTime, wwo->WrittenTotal, &wwo->format);
1138 }
1139
1140 /**************************************************************************
1141  *                              wodBreakLoop                    [internal]
1142  */
1143 static DWORD wodBreakLoop(WORD wDevID)
1144 {
1145     TRACE("(%u);\n", wDevID);
1146
1147     if (wDevID >= MAX_WAVEOUTDRV || AuServ == NULL)
1148     {
1149         WARN("bad device ID !\n");
1150         return MMSYSERR_BADDEVICEID;
1151     }
1152     NAS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_BREAKLOOP, 0, TRUE);
1153     return MMSYSERR_NOERROR;
1154 }
1155
1156 /**************************************************************************
1157  *                              wodGetVolume                    [internal]
1158  */
1159 static DWORD wodGetVolume(WORD wDevID, LPDWORD lpdwVol)
1160 {
1161     DWORD left, right;
1162
1163     left = WOutDev[wDevID].volume_left;
1164     right = WOutDev[wDevID].volume_right;
1165
1166     TRACE("(%u, %p);\n", wDevID, lpdwVol);
1167
1168     *lpdwVol = ((left * 0xFFFFl) / 100) + (((right * 0xFFFFl) / 100) << 16);
1169
1170     return MMSYSERR_NOERROR;
1171 }
1172
1173 /**************************************************************************
1174  *                              wodSetVolume                    [internal]
1175  */
1176 static DWORD wodSetVolume(WORD wDevID, DWORD dwParam)
1177 {
1178     DWORD left, right;
1179
1180     left  = (LOWORD(dwParam) * 100) / 0xFFFFl;
1181     right = (HIWORD(dwParam) * 100) / 0xFFFFl;
1182
1183     TRACE("(%u, %08lX);\n", wDevID, dwParam);
1184
1185     WOutDev[wDevID].volume_left = left;
1186     WOutDev[wDevID].volume_right = right;
1187
1188     return MMSYSERR_NOERROR;
1189 }
1190
1191 /**************************************************************************
1192  *                              wodGetNumDevs                   [internal]
1193  */
1194 static  DWORD   wodGetNumDevs(void)
1195 {
1196     return MAX_WAVEOUTDRV;
1197 }
1198
1199 /**************************************************************************
1200  *                              wodMessage (WINENAS.@)
1201  */
1202 DWORD WINAPI NAS_wodMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
1203                             DWORD dwParam1, DWORD dwParam2)
1204 {
1205     TRACE("(%u, %04X, %08lX, %08lX, %08lX);\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
1206
1207     switch (wMsg) {
1208     case DRVM_INIT:
1209     case DRVM_EXIT:
1210     case DRVM_ENABLE:
1211     case DRVM_DISABLE:
1212         /* FIXME: Pretend this is supported */
1213         return 0;
1214     case WODM_OPEN:             return wodOpen          (wDevID, (LPWAVEOPENDESC)dwParam1,      dwParam2);
1215     case WODM_CLOSE:            return wodClose         (wDevID);
1216     case WODM_WRITE:            return wodWrite         (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
1217     case WODM_PAUSE:            return wodPause         (wDevID);
1218     case WODM_GETPOS:           return wodGetPosition   (wDevID, (LPMMTIME)dwParam1,            dwParam2);
1219     case WODM_BREAKLOOP:        return wodBreakLoop     (wDevID);
1220     case WODM_PREPARE:          return MMSYSERR_NOTSUPPORTED;
1221     case WODM_UNPREPARE:        return MMSYSERR_NOTSUPPORTED;
1222     case WODM_GETDEVCAPS:       return wodGetDevCaps    (wDevID, (LPWAVEOUTCAPSW)dwParam1,      dwParam2);
1223     case WODM_GETNUMDEVS:       return wodGetNumDevs    ();
1224     case WODM_GETPITCH:         return MMSYSERR_NOTSUPPORTED;
1225     case WODM_SETPITCH:         return MMSYSERR_NOTSUPPORTED;
1226     case WODM_GETPLAYBACKRATE:  return MMSYSERR_NOTSUPPORTED;
1227     case WODM_SETPLAYBACKRATE:  return MMSYSERR_NOTSUPPORTED;
1228     case WODM_GETVOLUME:        return wodGetVolume     (wDevID, (LPDWORD)dwParam1);
1229     case WODM_SETVOLUME:        return wodSetVolume     (wDevID, dwParam1);
1230     case WODM_RESTART:          return wodRestart       (wDevID);
1231     case WODM_RESET:            return wodReset         (wDevID);
1232
1233     case DRV_QUERYDSOUNDIFACE:  return wodDsCreate      (wDevID, (PIDSDRIVER*)dwParam1);
1234     case DRV_QUERYDSOUNDDESC:   return wodDsDesc        (wDevID, (PDSDRIVERDESC)dwParam1);
1235     default:
1236         FIXME("unknown message %d!\n", wMsg);
1237     }
1238     return MMSYSERR_NOTSUPPORTED;
1239 }
1240
1241 /*======================================================================*
1242  *                  Low level DSOUND implementation                     *
1243  *======================================================================*/
1244 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
1245 {
1246     /* we can't perform memory mapping as we don't have a file stream
1247         interface with nas like we do with oss */
1248     MESSAGE("This sound card s driver does not support direct access\n");
1249     MESSAGE("The (slower) DirectSound HEL mode will be used instead.\n");
1250     return MMSYSERR_NOTSUPPORTED;
1251 }
1252
1253 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc)
1254 {
1255     memset(desc, 0, sizeof(*desc));
1256     strcpy(desc->szDesc, "Wine NAS DirectSound Driver");
1257     strcpy(desc->szDrvname, "winenas.drv");
1258     return MMSYSERR_NOERROR;
1259 }
1260
1261 static int nas_init(void) {
1262     TRACE("NAS INIT\n");
1263     if (!(AuServ = AuOpenServer(NULL, 0, NULL, 0, NULL, NULL)))
1264        return 0;
1265
1266     return 1;
1267 }
1268
1269 static int nas_finddev(WINE_WAVEOUT* wwo) {
1270    int i;
1271
1272     for (i = 0; i < AuServerNumDevices(wwo->AuServ); i++) {
1273         if ((AuDeviceKind(AuServerDevice(wwo->AuServ, i)) ==
1274              AuComponentKindPhysicalOutput) &&
1275              AuDeviceNumTracks(AuServerDevice(wwo->AuServ, i)) == wwo->format.wf.nChannels)
1276         {
1277             wwo->AuDev = AuDeviceIdentifier(AuServerDevice(wwo->AuServ, i));
1278             break;
1279         }
1280     }
1281
1282     if (wwo->AuDev == AuNone)
1283        return 0;
1284     return 1;
1285 }
1286
1287 static int nas_open(WINE_WAVEOUT* wwo) {
1288     AuElement elements[3];
1289
1290     if (!wwo->AuServ)
1291        return 0;
1292
1293     if (!nas_finddev(wwo))
1294        return 0;
1295
1296     if (!(wwo->AuFlow = AuCreateFlow(wwo->AuServ, NULL)))
1297        return 0;
1298
1299     wwo->BufferSize = FRAG_SIZE * FRAG_COUNT;
1300
1301     AuMakeElementImportClient(&elements[0], wwo->format.wf.nSamplesPerSec,
1302            wwo->format.wBitsPerSample == 16 ? AuFormatLinearSigned16LSB : AuFormatLinearUnsigned8,
1303            wwo->format.wf.nChannels, AuTrue, wwo->BufferSize, wwo->BufferSize / 2, 0, NULL);
1304
1305     AuMakeElementExportDevice(&elements[1], 0, wwo->AuDev, wwo->format.wf.nSamplesPerSec,
1306                               AuUnlimitedSamples, 0, NULL);
1307
1308     AuSetElements(wwo->AuServ, wwo->AuFlow, AuTrue, 2, elements, NULL);
1309
1310     AuRegisterEventHandler(wwo->AuServ, AuEventHandlerIDMask, 0, wwo->AuFlow,
1311                            event_handler, (AuPointer) wwo);
1312
1313
1314     wwo->PlayedTotal = 0;
1315     wwo->WrittenTotal = 0;
1316     wwo->open = 1;
1317
1318     wwo->BufferUsed = 0;
1319     wwo->writeBytes = 0;
1320     wwo->freeBytes = 0;
1321     wwo->sendBytes = 0;
1322     wwo->SoundBuffer = NULL;
1323     wwo->FlowStarted = 0;
1324
1325     AuStartFlow(wwo->AuServ, wwo->AuFlow, NULL);
1326     AuPauseFlow(wwo->AuServ, wwo->AuFlow, NULL);
1327     wwo->FlowStarted = 1;
1328
1329     return 1;
1330 }
1331
1332 static AuBool
1333 event_handler(AuServer* aud, AuEvent* ev, AuEventHandlerRec* hnd)
1334 {
1335   WINE_WAVEOUT *wwo = (WINE_WAVEOUT *)hnd->data;
1336         switch (ev->type) {
1337
1338         case AuEventTypeElementNotify: {
1339                 AuElementNotifyEvent* event = (AuElementNotifyEvent *)ev;
1340
1341
1342                 switch (event->kind) {
1343                    case AuElementNotifyKindLowWater:
1344                      wwo->freeBytes += event->num_bytes;
1345                      if (wwo->writeBytes > 0)
1346                         wwo->sendBytes += event->num_bytes;
1347                     if (wwo->freeBytes && wwo->BufferUsed)
1348                         nas_send_buffer(wwo);
1349                    break;
1350
1351                    case AuElementNotifyKindState:
1352                      TRACE("ev: kind %s state %s->%s reason %s numbytes %ld freeB %lu\n",
1353                                      nas_elementnotify_kind(event->kind),
1354                                      nas_state(event->prev_state),
1355                                      nas_state(event->cur_state),
1356                                      nas_reason(event->reason),
1357                                      event->num_bytes, wwo->freeBytes);
1358
1359                      if (event->cur_state ==  AuStatePause && event->reason != AuReasonUser) {
1360                         wwo->freeBytes += event->num_bytes;
1361                         if (wwo->writeBytes > 0)
1362                            wwo->sendBytes += event->num_bytes;
1363                         if (wwo->sendBytes > wwo->writeBytes)
1364                            wwo->sendBytes = wwo->writeBytes;
1365                        if (wwo->freeBytes && wwo->BufferUsed)
1366                            nas_send_buffer(wwo);
1367                      }
1368                    break;
1369                 }
1370            }
1371         }
1372         return AuTrue;
1373 }
1374
1375 static void
1376 buffer_resize(WINE_WAVEOUT* wwo, int len)
1377 {
1378         void *newbuf = malloc(wwo->BufferUsed + len);
1379         void *oldbuf = wwo->SoundBuffer;
1380         memcpy(newbuf, oldbuf, wwo->BufferUsed);
1381         wwo->SoundBuffer = newbuf;
1382         if (oldbuf != NULL)
1383            free(oldbuf);
1384 }
1385
1386 static int nas_add_buffer(WINE_WAVEOUT* wwo) {
1387     int len = wwo->lpPlayPtr->dwBufferLength;
1388
1389     buffer_resize(wwo, len);
1390     memcpy(wwo->SoundBuffer + wwo->BufferUsed, wwo->lpPlayPtr->lpData, len);
1391     wwo->BufferUsed += len;
1392     wwo->WrittenTotal += len;
1393     return len;
1394 }
1395
1396 static int nas_send_buffer(WINE_WAVEOUT* wwo) {
1397   int oldb , len;
1398   char *ptr, *newdata;
1399   newdata = NULL;
1400   oldb = len = 0;
1401
1402   if (wwo->freeBytes <= 0)
1403      return 0;
1404
1405   if (wwo->SoundBuffer == NULL || wwo->BufferUsed == 0) {
1406      return 0;
1407   }
1408
1409   if (wwo->BufferUsed <= wwo->freeBytes) {
1410      len = wwo->BufferUsed;
1411      ptr = wwo->SoundBuffer;
1412   } else {
1413      len = wwo->freeBytes;
1414      ptr = malloc(len);
1415      memcpy(ptr,wwo->SoundBuffer,len);
1416      newdata = malloc(wwo->BufferUsed - len);
1417      memcpy(newdata, wwo->SoundBuffer + len, wwo->BufferUsed - len);
1418   }
1419
1420  TRACE("envoye de %d bytes / %lu bytes / freeBytes %lu\n", len, wwo->BufferUsed, wwo->freeBytes);
1421
1422  AuWriteElement(wwo->AuServ, wwo->AuFlow, 0, len, ptr, AuFalse, NULL);
1423
1424  wwo->BufferUsed -= len;
1425  wwo->freeBytes -= len;
1426  wwo->writeBytes += len;
1427
1428  free(ptr);
1429
1430  wwo->SoundBuffer = NULL;
1431
1432  if (newdata != NULL)
1433     wwo->SoundBuffer = newdata;
1434
1435  return len;
1436 }
1437
1438 static int nas_free(WINE_WAVEOUT* wwo)
1439 {
1440
1441   if (!wwo->FlowStarted && wwo->BufferUsed) {
1442      AuStartFlow(wwo->AuServ, wwo->AuFlow, NULL);
1443      wwo->FlowStarted = 1;
1444   }
1445
1446   while (wwo->BufferUsed || wwo->writeBytes != wwo->sendBytes) {
1447     if (wwo->freeBytes)
1448        nas_send_buffer(wwo);
1449     AuHandleEvents(wwo->AuServ);
1450   }
1451
1452   AuFlush(wwo->AuServ);
1453   return TRUE;
1454 }
1455
1456 static int nas_close(WINE_WAVEOUT* wwo)
1457 {
1458   AuEvent ev;
1459
1460   nas_free(wwo);
1461
1462   AuStopFlow(wwo->AuServ, wwo->AuFlow, NULL);
1463   AuDestroyFlow(wwo->AuServ, wwo->AuFlow, NULL);
1464   AuFlush(wwo->AuServ);
1465   AuNextEvent(wwo->AuServ, AuTrue, &ev);
1466   AuDispatchEvent(wwo->AuServ, &ev);
1467
1468   wwo->AuFlow = 0;
1469   wwo->open = 0;
1470   wwo->BufferUsed = 0;
1471   wwo->freeBytes = 0;
1472   wwo->SoundBuffer = NULL;
1473   return 1;
1474 }
1475
1476 static int nas_end(void)
1477 {
1478   if (AuServ)
1479   {
1480     AuCloseServer(AuServ);
1481     AuServ = 0;
1482   }
1483   return 1;
1484 }
1485
1486 #else /* !HAVE_NAS */
1487
1488 /**************************************************************************
1489  *                              wodMessage (WINENAS.@)
1490  */
1491 DWORD WINAPI NAS_wodMessage(WORD wDevID, WORD wMsg, DWORD dwUser, DWORD dwParam1, DWORD dwParam2)
1492 {
1493     FIXME("(%u, %04X, %08lX, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
1494     return MMSYSERR_NOTENABLED;
1495 }
1496 #endif