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