save old text color during a call of DrawCaptionTempW
[wine/kumbayo.git] / dlls / winenas.drv / audio.c
blobf37ed6138abc75b4a6cc68ff18e055f2a9d994bf
1 /* -*- tab-width: 8; c-basic-offset: 4 -*- */
2 /*
3 * Wine Driver for NAS Network Audio System
4 * http://radscan.com/nas.html
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)
12 * Copyright 2002 Nicolas Escuder <n.escuder@alineanet.com>
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.
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.
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
28 /* NOTE:
29 * with nas we cannot stop the audio that is already in
30 * the servers buffer.
32 * FIXME:
33 * pause in waveOut does not work correctly in loop mode
37 #include "config.h"
39 #include <stdlib.h>
40 #include <stdarg.h>
41 #include <stdio.h>
42 #include <string.h>
43 #ifdef HAVE_UNISTD_H
44 # include <unistd.h>
45 #endif
46 #ifdef HAVE_SYS_TIME_H
47 # include <sys/time.h>
48 #endif
49 #include <fcntl.h>
50 #include <math.h>
52 #define FRAG_SIZE 1024
53 #define FRAG_COUNT 10
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
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"
88 WINE_DEFAULT_DEBUG_CHANNEL(wave);
90 /* Allow 1% deviation for sample rates (some ES137x cards) */
91 #define NEAR_MATCH(rate1,rate2) (((100*((int)(rate1)-(int)(rate2)))/(rate1))==0)
93 #ifdef HAVE_NAS
95 static AuServer *AuServ;
97 #define MAX_WAVEOUTDRV (1)
99 /* state diagram for waveOut writing:
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 * +---------+-------------+---------------+---------------------------------+
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
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
128 typedef struct {
129 enum win_wm_message msg; /* message identifier */
130 DWORD param; /* parameter for this message */
131 HANDLE hEvent; /* if message is synchronous, handle of event for synchro */
132 } RING_MSG;
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
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;
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;
156 int open;
157 AuServer *AuServ;
158 AuDeviceID AuDev;
159 AuFlowID AuFlow;
160 BOOL FlowStarted;
162 DWORD writeBytes;
163 DWORD freeBytes;
164 DWORD sendBytes;
166 DWORD BufferSize; /* size of whole buffer in bytes */
168 char* SoundBuffer;
169 long BufferUsed;
171 DWORD volume_left; /* volume control information */
172 DWORD volume_right;
174 LPWAVEHDR lpQueuePtr; /* start of queued WAVEHDRs (waiting to be notified) */
175 LPWAVEHDR lpPlayPtr; /* start of not yet fully played buffers */
177 LPWAVEHDR lpLoopPtr; /* pointer of first buffer in loop, if any */
178 DWORD dwLoops; /* private copy of loop counter */
180 DWORD PlayedTotal; /* number of bytes actually played since opening */
181 DWORD WrittenTotal; /* number of bytes written to the audio device since opening */
183 /* synchronization stuff */
184 HANDLE hStartUpEvent;
185 HANDLE hThread;
186 DWORD dwThreadID;
187 MSG_RING msgRing;
188 } WINE_WAVEOUT;
190 static WINE_WAVEOUT WOutDev [MAX_WAVEOUTDRV];
192 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv);
193 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc);
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);
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);
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",
220 static const char * const nas_elementnotify_kinds[] = {
221 "LowWater",
222 "HighWater",
223 "State",
224 "Unknown"
227 static const char * const nas_states[] = {
228 "Stop",
229 "Start",
230 "Pause",
231 "Any"
234 static const char * const nas_reasons[] = {
235 "User",
236 "Underrun",
237 "Overrun",
238 "EOF",
239 "Watermark",
240 "Hardware",
241 "Any"
244 static const char* nas_reason(unsigned int reason)
246 if (reason > 6) reason = 6;
247 return nas_reasons[reason];
250 static const char* nas_elementnotify_kind(unsigned int kind)
252 if (kind > 2) kind = 3;
253 return nas_elementnotify_kinds[kind];
257 #if 0
258 static const char* nas_event_type(unsigned int type)
260 static const char * const nas_event_types[] =
262 "Undefined",
263 "Undefined",
264 "ElementNotify",
265 "GrabNotify",
266 "MonitorNotify",
267 "BucketNotify",
268 "DeviceNotify"
271 if (type > 6) type = 0;
272 return nas_event_types[type];
274 #endif
277 static const char* nas_state(unsigned int state)
279 if (state > 3) state = 3;
280 return nas_states[state];
283 static DWORD bytes_to_mmtime(LPMMTIME lpTime, DWORD position,
284 PCMWAVEFORMAT* format)
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);
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;
325 return MMSYSERR_NOERROR;
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)
337 short *d_out = (short *)bufout;
338 short *d_in = (short *)bufin;
339 int i, v;
342 TRACE("length == %d, nChannels == %d\n", length, nChannels);
345 if (right == -1) right = left;
347 for(i = 0; i < length; i+=(nChannels))
349 v = (int) ((*(d_in++) * left) / 100);
350 *(d_out++) = (v>32767) ? 32767 : ((v<-32768) ? -32768 : v);
351 if(nChannels == 2)
353 v = (int) ((*(d_in++) * right) / 100);
354 *(d_out++) = (v>32767) ? 32767 : ((v<-32768) ? -32768 : v);
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)
363 char *d_out = (char *)bufout;
364 char *d_in = (char *)bufin;
365 int i, v;
368 TRACE("length == %d, nChannels == %d\n", length, nChannels);
371 if (right == -1) right = left;
373 for(i = 0; i < length; i+=(nChannels))
375 v = (char) ((*(d_in++) * left) / 100);
376 *(d_out++) = (v>255) ? 255 : ((v<0) ? 0 : v);
377 if(nChannels == 2)
379 v = (char) ((*(d_in++) * right) / 100);
380 *(d_out++) = (v>255) ? 255 : ((v<0) ? 0 : v);
384 #endif
386 /******************************************************************
387 * NAS_CloseDevice
390 static void NAS_CloseDevice(WINE_WAVEOUT* wwo)
392 TRACE("NAS_CloseDevice\n");
393 nas_close(wwo);
396 /******************************************************************
397 * NAS_WaveClose
399 LONG NAS_WaveClose(void)
401 nas_end(); /* free up nas server */
402 return 1;
405 /******************************************************************
406 * NAS_WaveInit
408 * Initialize internal structures from NAS server info
410 LONG NAS_WaveInit(void)
412 int i;
413 if (!nas_init()) return MMSYSERR_ERROR;
415 /* initialize all device handles to -1 */
416 for (i = 0; i < MAX_WAVEOUTDRV; ++i)
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 */
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;
432 WOutDev[i].caps.wChannels = 2;
433 WOutDev[i].caps.dwSupport |= WAVECAPS_LRVOLUME;
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;
450 return 0;
453 /******************************************************************
454 * NAS_InitRingMessage
456 * Initialize the ring of messages for passing between driver's caller and playback/record
457 * thread
459 static int NAS_InitRingMessage(MSG_RING* mr)
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;
471 /******************************************************************
472 * NAS_DestroyRingMessage
475 static int NAS_DestroyRingMessage(MSG_RING* mr)
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;
484 /******************************************************************
485 * NAS_AddRingMessage
487 * Inserts a new message into the ring (should be called from DriverProc derivated routines)
489 static int NAS_AddRingMessage(MSG_RING* mr, enum win_wm_message msg, DWORD param, BOOL wait)
491 HANDLE hEvent = INVALID_HANDLE_VALUE;
493 EnterCriticalSection(&mr->msg_crst);
494 if ((mr->msg_toget == ((mr->msg_tosave + 1) % mr->ring_buffer_size)))
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.
504 if (mr->msg_tosave < mr->msg_toget)
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)
510 mr->msg_toget += NAS_RING_BUFFER_INCREMENT;
513 if (wait)
515 hEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
516 if (hEvent == INVALID_HANDLE_VALUE)
518 ERR("can't create event !?\n");
519 LeaveCriticalSection(&mr->msg_crst);
520 return 0;
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");
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;
528 mr->messages[mr->msg_toget].msg = msg;
529 mr->messages[mr->msg_toget].param = param;
530 mr->messages[mr->msg_toget].hEvent = hEvent;
532 else
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;
540 LeaveCriticalSection(&mr->msg_crst);
542 SetEvent(mr->msg_event); /* signal a new message */
544 if (wait)
546 /* wait for playback/record thread to have processed the message */
547 WaitForSingleObject(hEvent, INFINITE);
548 CloseHandle(hEvent);
551 return 1;
554 /******************************************************************
555 * NAS_RetrieveRingMessage
557 * Get a message from the ring. Should be called by the playback/record thread.
559 static int NAS_RetrieveRingMessage(MSG_RING* mr,
560 enum win_wm_message *msg, DWORD *param, HANDLE *hEvent)
562 EnterCriticalSection(&mr->msg_crst);
564 if (mr->msg_toget == mr->msg_tosave) /* buffer empty ? */
566 LeaveCriticalSection(&mr->msg_crst);
567 return 0;
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;
579 /*======================================================================*
580 * Low level WAVE OUT implementation *
581 *======================================================================*/
583 /**************************************************************************
584 * wodNotifyClient [internal]
586 static DWORD wodNotifyClient(WINE_WAVEOUT* wwo, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
588 TRACE("wMsg = 0x%04x dwParm1 = %04X dwParam2 = %04X\n", wMsg, dwParam1, dwParam2);
590 switch (wMsg) {
591 case WOM_OPEN:
592 case WOM_CLOSE:
593 case WOM_DONE:
594 if (wwo->wFlags != DCB_NULL &&
595 !DriverCallback(wwo->waveDesc.dwCallback, wwo->wFlags, (HDRVR)wwo->waveDesc.hWave,
596 wMsg, wwo->waveDesc.dwInstance, dwParam1, dwParam2)) {
597 WARN("can't notify client !\n");
598 return MMSYSERR_ERROR;
600 break;
601 default:
602 FIXME("Unknown callback message %u\n", wMsg);
603 return MMSYSERR_INVALPARAM;
605 return MMSYSERR_NOERROR;
608 /**************************************************************************
609 * wodUpdatePlayedTotal [internal]
612 static BOOL wodUpdatePlayedTotal(WINE_WAVEOUT* wwo)
614 wwo->PlayedTotal = wwo->WrittenTotal;
615 return TRUE;
618 /**************************************************************************
619 * wodPlayer_BeginWaveHdr [internal]
621 * Makes the specified lpWaveHdr the currently playing wave header.
622 * If the specified wave header is a begin loop and we're not already in
623 * a loop, setup the loop.
625 static void wodPlayer_BeginWaveHdr(WINE_WAVEOUT* wwo, LPWAVEHDR lpWaveHdr)
627 wwo->lpPlayPtr = lpWaveHdr;
629 if (!lpWaveHdr) return;
631 if (lpWaveHdr->dwFlags & WHDR_BEGINLOOP) {
632 if (wwo->lpLoopPtr) {
633 WARN("Already in a loop. Discarding loop on this header (%p)\n", lpWaveHdr);
634 TRACE("Already in a loop. Discarding loop on this header (%p)\n", lpWaveHdr);
635 } else {
636 TRACE("Starting loop (%dx) with %p\n", lpWaveHdr->dwLoops, lpWaveHdr);
637 wwo->lpLoopPtr = lpWaveHdr;
638 /* Windows does not touch WAVEHDR.dwLoops,
639 * so we need to make an internal copy */
640 wwo->dwLoops = lpWaveHdr->dwLoops;
645 /**************************************************************************
646 * wodPlayer_PlayPtrNext [internal]
648 * Advance the play pointer to the next waveheader, looping if required.
650 static LPWAVEHDR wodPlayer_PlayPtrNext(WINE_WAVEOUT* wwo)
652 LPWAVEHDR lpWaveHdr = wwo->lpPlayPtr;
654 if ((lpWaveHdr->dwFlags & WHDR_ENDLOOP) && wwo->lpLoopPtr) {
655 /* We're at the end of a loop, loop if required */
656 if (--wwo->dwLoops > 0) {
657 wwo->lpPlayPtr = wwo->lpLoopPtr;
658 } else {
659 /* Handle overlapping loops correctly */
660 if (wwo->lpLoopPtr != lpWaveHdr && (lpWaveHdr->dwFlags & WHDR_BEGINLOOP)) {
661 FIXME("Correctly handled case ? (ending loop buffer also starts a new loop)\n");
662 /* shall we consider the END flag for the closing loop or for
663 * the opening one or for both ???
664 * code assumes for closing loop only
666 } else {
667 lpWaveHdr = lpWaveHdr->lpNext;
669 wwo->lpLoopPtr = NULL;
670 wodPlayer_BeginWaveHdr(wwo, lpWaveHdr);
672 } else {
673 /* We're not in a loop. Advance to the next wave header */
674 wodPlayer_BeginWaveHdr(wwo, lpWaveHdr = lpWaveHdr->lpNext);
676 return lpWaveHdr;
679 /**************************************************************************
680 * wodPlayer_NotifyCompletions [internal]
682 * Notifies and remove from queue all wavehdrs which have been played to
683 * the speaker (ie. they have cleared the audio device). If force is true,
684 * we notify all wavehdrs and remove them all from the queue even if they
685 * are unplayed or part of a loop.
687 static DWORD wodPlayer_NotifyCompletions(WINE_WAVEOUT* wwo, BOOL force)
689 LPWAVEHDR lpWaveHdr;
691 /* Start from lpQueuePtr and keep notifying until:
692 * - we hit an unwritten wavehdr
693 * - we hit the beginning of a running loop
694 * - we hit a wavehdr which hasn't finished playing
696 wodUpdatePlayedTotal(wwo);
698 while ((lpWaveHdr = wwo->lpQueuePtr) && (force || (lpWaveHdr != wwo->lpPlayPtr &&
699 lpWaveHdr != wwo->lpLoopPtr && lpWaveHdr->reserved <= wwo->PlayedTotal))) {
701 wwo->lpQueuePtr = lpWaveHdr->lpNext;
703 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
704 lpWaveHdr->dwFlags |= WHDR_DONE;
706 wodNotifyClient(wwo, WOM_DONE, (DWORD)lpWaveHdr, 0);
708 return (lpWaveHdr && lpWaveHdr != wwo->lpPlayPtr && lpWaveHdr != wwo->lpLoopPtr) ?
709 1 : 1;
712 /**************************************************************************
713 * wodPlayer_Reset [internal]
715 * wodPlayer helper. Resets current output stream.
717 static void wodPlayer_Reset(WINE_WAVEOUT* wwo, BOOL reset)
719 wodUpdatePlayedTotal(wwo);
720 wodPlayer_NotifyCompletions(wwo, FALSE); /* updates current notify list */
722 /* we aren't able to flush any data that has already been written */
723 /* to nas, otherwise we would do the flushing here */
725 nas_free(wwo);
727 if (reset) {
728 enum win_wm_message msg;
729 DWORD param;
730 HANDLE ev;
732 /* remove any buffer */
733 wodPlayer_NotifyCompletions(wwo, TRUE);
735 wwo->lpPlayPtr = wwo->lpQueuePtr = wwo->lpLoopPtr = NULL;
736 wwo->state = WINE_WS_STOPPED;
737 wwo->PlayedTotal = wwo->WrittenTotal = 0;
739 /* remove any existing message in the ring */
740 EnterCriticalSection(&wwo->msgRing.msg_crst);
742 /* return all pending headers in queue */
743 while (NAS_RetrieveRingMessage(&wwo->msgRing, &msg, &param, &ev))
745 TRACE("flushing msg\n");
746 if (msg != WINE_WM_HEADER)
748 FIXME("shouldn't have headers left\n");
749 SetEvent(ev);
750 continue;
752 ((LPWAVEHDR)param)->dwFlags &= ~WHDR_INQUEUE;
753 ((LPWAVEHDR)param)->dwFlags |= WHDR_DONE;
755 wodNotifyClient(wwo, WOM_DONE, param, 0);
757 ResetEvent(wwo->msgRing.msg_event);
758 LeaveCriticalSection(&wwo->msgRing.msg_crst);
759 } else {
760 if (wwo->lpLoopPtr) {
761 /* complicated case, not handled yet (could imply modifying the loop counter */
762 FIXME("Pausing while in loop isn't correctly handled yet, except strange results\n");
763 wwo->lpPlayPtr = wwo->lpLoopPtr;
764 wwo->WrittenTotal = wwo->PlayedTotal; /* this is wrong !!! */
765 } else {
766 /* the data already written is going to be played, so take */
767 /* this fact into account here */
768 wwo->PlayedTotal = wwo->WrittenTotal;
770 wwo->state = WINE_WS_PAUSED;
774 /**************************************************************************
775 * wodPlayer_ProcessMessages [internal]
777 static void wodPlayer_ProcessMessages(WINE_WAVEOUT* wwo)
779 LPWAVEHDR lpWaveHdr;
780 enum win_wm_message msg;
781 DWORD param;
782 HANDLE ev;
784 while (NAS_RetrieveRingMessage(&wwo->msgRing, &msg, &param, &ev)) {
785 TRACE("Received %s %x\n", wodPlayerCmdString[msg - WM_USER - 1], param);
786 switch (msg) {
787 case WINE_WM_PAUSING:
788 wodPlayer_Reset(wwo, FALSE);
789 SetEvent(ev);
790 break;
791 case WINE_WM_RESTARTING:
792 wwo->state = WINE_WS_PLAYING;
793 SetEvent(ev);
794 break;
795 case WINE_WM_HEADER:
796 lpWaveHdr = (LPWAVEHDR)param;
798 /* insert buffer at the end of queue */
800 LPWAVEHDR* wh;
801 for (wh = &(wwo->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
802 *wh = lpWaveHdr;
804 if (!wwo->lpPlayPtr)
805 wodPlayer_BeginWaveHdr(wwo,lpWaveHdr);
806 if (wwo->state == WINE_WS_STOPPED)
807 wwo->state = WINE_WS_PLAYING;
808 break;
809 case WINE_WM_RESETTING:
810 wodPlayer_Reset(wwo, TRUE);
811 SetEvent(ev);
812 break;
813 case WINE_WM_UPDATE:
814 wodUpdatePlayedTotal(wwo);
815 SetEvent(ev);
816 break;
817 case WINE_WM_BREAKLOOP:
818 if (wwo->state == WINE_WS_PLAYING && wwo->lpLoopPtr != NULL) {
819 /* ensure exit at end of current loop */
820 wwo->dwLoops = 1;
822 SetEvent(ev);
823 break;
824 case WINE_WM_CLOSING:
825 /* sanity check: this should not happen since the device must have been reset before */
826 if (wwo->lpQueuePtr || wwo->lpPlayPtr) ERR("out of sync\n");
827 wwo->hThread = 0;
828 wwo->state = WINE_WS_CLOSED;
829 SetEvent(ev);
830 ExitThread(0);
831 /* shouldn't go here */
832 default:
833 FIXME("unknown message %d\n", msg);
834 break;
839 /**************************************************************************
840 * wodPlayer [internal]
842 static DWORD CALLBACK wodPlayer(LPVOID pmt)
844 WORD uDevID = (DWORD)pmt;
845 WINE_WAVEOUT* wwo = (WINE_WAVEOUT*)&WOutDev[uDevID];
847 wwo->state = WINE_WS_STOPPED;
848 SetEvent(wwo->hStartUpEvent);
850 for (;;) {
852 if (wwo->FlowStarted) {
853 AuHandleEvents(wwo->AuServ);
855 if (wwo->state == WINE_WS_PLAYING && wwo->freeBytes && wwo->BufferUsed)
856 nas_send_buffer(wwo);
859 if (wwo->BufferUsed <= FRAG_SIZE && wwo->writeBytes > 0)
860 wodPlayer_NotifyCompletions(wwo, FALSE);
862 WaitForSingleObject(wwo->msgRing.msg_event, 20);
863 wodPlayer_ProcessMessages(wwo);
865 while(wwo->lpPlayPtr) {
866 wwo->lpPlayPtr->reserved = wwo->WrittenTotal + wwo->lpPlayPtr->dwBufferLength;
867 nas_add_buffer(wwo);
868 wodPlayer_PlayPtrNext(wwo);
874 /**************************************************************************
875 * wodGetDevCaps [internal]
877 static DWORD wodGetDevCaps(WORD wDevID, LPWAVEOUTCAPSW lpCaps, DWORD dwSize)
879 TRACE("(%u, %p, %u);\n", wDevID, lpCaps, dwSize);
881 if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
883 if (wDevID >= MAX_WAVEOUTDRV) {
884 TRACE("MAX_WAVOUTDRV reached !\n");
885 return MMSYSERR_BADDEVICEID;
888 memcpy(lpCaps, &WOutDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
889 return MMSYSERR_NOERROR;
892 /**************************************************************************
893 * wodOpen [internal]
895 static DWORD wodOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
897 WINE_WAVEOUT* wwo;
899 TRACE("wodOpen (%u, %p, %08X);\n", wDevID, lpDesc, dwFlags);
901 if (lpDesc == NULL) {
902 WARN("Invalid Parameter !\n");
903 return MMSYSERR_INVALPARAM;
905 if (wDevID >= MAX_WAVEOUTDRV) {
906 TRACE("MAX_WAVOUTDRV reached !\n");
907 return MMSYSERR_BADDEVICEID;
910 /* if this device is already open tell the app that it is allocated */
912 wwo = &WOutDev[wDevID];
914 if(wwo->open)
916 TRACE("device already allocated\n");
917 return MMSYSERR_ALLOCATED;
921 /* only PCM format is supported so far... */
922 if (lpDesc->lpFormat->wFormatTag != WAVE_FORMAT_PCM ||
923 lpDesc->lpFormat->nChannels == 0 ||
924 lpDesc->lpFormat->nSamplesPerSec == 0 ||
925 (lpDesc->lpFormat->wBitsPerSample!=8 && lpDesc->lpFormat->wBitsPerSample!=16)) {
926 WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
927 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
928 lpDesc->lpFormat->nSamplesPerSec);
929 return WAVERR_BADFORMAT;
932 if (dwFlags & WAVE_FORMAT_QUERY) {
933 TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
934 lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
935 lpDesc->lpFormat->nSamplesPerSec);
936 return MMSYSERR_NOERROR;
939 /* direct sound not supported, ignore the flag */
940 dwFlags &= ~WAVE_DIRECTSOUND;
942 wwo->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
944 memcpy(&wwo->waveDesc, lpDesc, sizeof(WAVEOPENDESC));
945 memcpy(&wwo->format, lpDesc->lpFormat, sizeof(PCMWAVEFORMAT));
947 if (wwo->format.wBitsPerSample == 0) {
948 WARN("Resetting zeroed wBitsPerSample\n");
949 wwo->format.wBitsPerSample = 8 *
950 (wwo->format.wf.nAvgBytesPerSec /
951 wwo->format.wf.nSamplesPerSec) /
952 wwo->format.wf.nChannels;
955 if (!nas_open(wwo))
956 return MMSYSERR_ALLOCATED;
958 NAS_InitRingMessage(&wwo->msgRing);
960 /* create player thread */
961 if (!(dwFlags & WAVE_DIRECTSOUND)) {
962 wwo->hStartUpEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
963 wwo->hThread = CreateThread(NULL, 0, wodPlayer, (LPVOID)(DWORD)wDevID, 0, &(wwo->dwThreadID));
964 if (wwo->hThread)
965 SetThreadPriority(wwo->hThread, THREAD_PRIORITY_TIME_CRITICAL);
966 WaitForSingleObject(wwo->hStartUpEvent, INFINITE);
967 CloseHandle(wwo->hStartUpEvent);
968 } else {
969 wwo->hThread = INVALID_HANDLE_VALUE;
970 wwo->dwThreadID = 0;
972 wwo->hStartUpEvent = INVALID_HANDLE_VALUE;
974 TRACE("stream=0x%lx, BufferSize=%d\n", (long)wwo->AuServ, wwo->BufferSize);
976 TRACE("wBitsPerSample=%u nAvgBytesPerSec=%u nSamplesPerSec=%u nChannels=%u nBlockAlign=%u\n",
977 wwo->format.wBitsPerSample, wwo->format.wf.nAvgBytesPerSec,
978 wwo->format.wf.nSamplesPerSec, wwo->format.wf.nChannels,
979 wwo->format.wf.nBlockAlign);
981 return wodNotifyClient(wwo, WOM_OPEN, 0L, 0L);
984 /**************************************************************************
985 * wodClose [internal]
987 static DWORD wodClose(WORD wDevID)
989 DWORD ret = MMSYSERR_NOERROR;
990 WINE_WAVEOUT* wwo;
992 TRACE("(%u);\n", wDevID);
994 if (wDevID >= MAX_WAVEOUTDRV || AuServ == NULL)
996 WARN("bad device ID !\n");
997 return MMSYSERR_BADDEVICEID;
1000 wwo = &WOutDev[wDevID];
1001 if (wwo->lpQueuePtr) {
1002 WARN("buffers still playing !\n");
1003 ret = WAVERR_STILLPLAYING;
1004 } else {
1005 TRACE("imhere[3-close]\n");
1006 if (wwo->hThread != INVALID_HANDLE_VALUE) {
1007 NAS_AddRingMessage(&wwo->msgRing, WINE_WM_CLOSING, 0, TRUE);
1010 NAS_DestroyRingMessage(&wwo->msgRing);
1012 NAS_CloseDevice(wwo); /* close the stream and clean things up */
1014 ret = wodNotifyClient(wwo, WOM_CLOSE, 0L, 0L);
1016 return ret;
1019 /**************************************************************************
1020 * wodWrite [internal]
1023 static DWORD wodWrite(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1025 TRACE("(%u, %p, %08X);\n", wDevID, lpWaveHdr, dwSize);
1027 /* first, do the sanity checks... */
1028 if (wDevID >= MAX_WAVEOUTDRV || AuServ == NULL)
1030 WARN("bad dev ID !\n");
1031 return MMSYSERR_BADDEVICEID;
1034 if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
1036 TRACE("unprepared\n");
1037 return WAVERR_UNPREPARED;
1040 if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
1042 TRACE("still playing\n");
1043 return WAVERR_STILLPLAYING;
1046 lpWaveHdr->dwFlags &= ~WHDR_DONE;
1047 lpWaveHdr->dwFlags |= WHDR_INQUEUE;
1048 lpWaveHdr->lpNext = 0;
1050 TRACE("adding ring message\n");
1051 NAS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_HEADER, (DWORD)lpWaveHdr, FALSE);
1053 return MMSYSERR_NOERROR;
1056 /**************************************************************************
1057 * wodPause [internal]
1059 static DWORD wodPause(WORD wDevID)
1061 TRACE("(%u);!\n", wDevID);
1063 if (wDevID >= MAX_WAVEOUTDRV || AuServ == NULL)
1065 WARN("bad device ID !\n");
1066 return MMSYSERR_BADDEVICEID;
1069 TRACE("imhere[3-PAUSING]\n");
1070 NAS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_PAUSING, 0, TRUE);
1072 return MMSYSERR_NOERROR;
1075 /**************************************************************************
1076 * wodRestart [internal]
1078 static DWORD wodRestart(WORD wDevID)
1080 TRACE("(%u);\n", wDevID);
1082 if (wDevID >= MAX_WAVEOUTDRV || AuServ == NULL)
1084 WARN("bad device ID !\n");
1085 return MMSYSERR_BADDEVICEID;
1088 if (WOutDev[wDevID].state == WINE_WS_PAUSED) {
1089 TRACE("imhere[3-RESTARTING]\n");
1090 NAS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESTARTING, 0, TRUE);
1093 /* FIXME: is NotifyClient with WOM_DONE right ? (Comet Busters 1.3.3 needs this notification) */
1094 /* FIXME: Myst crashes with this ... hmm -MM
1095 return wodNotifyClient(wwo, WOM_DONE, 0L, 0L);
1098 return MMSYSERR_NOERROR;
1101 /**************************************************************************
1102 * wodReset [internal]
1104 static DWORD wodReset(WORD wDevID)
1106 TRACE("(%u);\n", wDevID);
1108 if (wDevID >= MAX_WAVEOUTDRV || AuServ == NULL)
1110 WARN("bad device ID !\n");
1111 return MMSYSERR_BADDEVICEID;
1114 TRACE("imhere[3-RESET]\n");
1115 NAS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
1117 return MMSYSERR_NOERROR;
1120 /**************************************************************************
1121 * wodGetPosition [internal]
1123 static DWORD wodGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
1125 WINE_WAVEOUT* wwo;
1127 TRACE("%u, %p, %u);\n", wDevID, lpTime, uSize);
1129 if (wDevID >= MAX_WAVEOUTDRV || AuServ == NULL)
1131 WARN("bad device ID !\n");
1132 return MMSYSERR_BADDEVICEID;
1135 if (lpTime == NULL) return MMSYSERR_INVALPARAM;
1137 wwo = &WOutDev[wDevID];
1138 #if 0
1139 NAS_AddRingMessage(&wwo->msgRing, WINE_WM_UPDATE, 0, TRUE);
1140 #endif
1142 return bytes_to_mmtime(lpTime, wwo->WrittenTotal, &wwo->format);
1145 /**************************************************************************
1146 * wodBreakLoop [internal]
1148 static DWORD wodBreakLoop(WORD wDevID)
1150 TRACE("(%u);\n", wDevID);
1152 if (wDevID >= MAX_WAVEOUTDRV || AuServ == NULL)
1154 WARN("bad device ID !\n");
1155 return MMSYSERR_BADDEVICEID;
1157 NAS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_BREAKLOOP, 0, TRUE);
1158 return MMSYSERR_NOERROR;
1161 /**************************************************************************
1162 * wodGetVolume [internal]
1164 static DWORD wodGetVolume(WORD wDevID, LPDWORD lpdwVol)
1166 DWORD left, right;
1168 left = WOutDev[wDevID].volume_left;
1169 right = WOutDev[wDevID].volume_right;
1171 TRACE("(%u, %p);\n", wDevID, lpdwVol);
1173 *lpdwVol = ((left * 0xFFFFl) / 100) + (((right * 0xFFFFl) / 100) << 16);
1175 return MMSYSERR_NOERROR;
1178 /**************************************************************************
1179 * wodSetVolume [internal]
1181 static DWORD wodSetVolume(WORD wDevID, DWORD dwParam)
1183 DWORD left, right;
1185 left = (LOWORD(dwParam) * 100) / 0xFFFFl;
1186 right = (HIWORD(dwParam) * 100) / 0xFFFFl;
1188 TRACE("(%u, %08X);\n", wDevID, dwParam);
1190 WOutDev[wDevID].volume_left = left;
1191 WOutDev[wDevID].volume_right = right;
1193 return MMSYSERR_NOERROR;
1196 /**************************************************************************
1197 * wodGetNumDevs [internal]
1199 static DWORD wodGetNumDevs(void)
1201 return MAX_WAVEOUTDRV;
1204 /**************************************************************************
1205 * wodMessage (WINENAS.@)
1207 DWORD WINAPI NAS_wodMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
1208 DWORD dwParam1, DWORD dwParam2)
1210 TRACE("(%u, %04X, %08X, %08X, %08X);\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
1212 switch (wMsg) {
1213 case DRVM_INIT:
1214 case DRVM_EXIT:
1215 case DRVM_ENABLE:
1216 case DRVM_DISABLE:
1217 /* FIXME: Pretend this is supported */
1218 return 0;
1219 case WODM_OPEN: return wodOpen (wDevID, (LPWAVEOPENDESC)dwParam1, dwParam2);
1220 case WODM_CLOSE: return wodClose (wDevID);
1221 case WODM_WRITE: return wodWrite (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
1222 case WODM_PAUSE: return wodPause (wDevID);
1223 case WODM_GETPOS: return wodGetPosition (wDevID, (LPMMTIME)dwParam1, dwParam2);
1224 case WODM_BREAKLOOP: return wodBreakLoop (wDevID);
1225 case WODM_PREPARE: return MMSYSERR_NOTSUPPORTED;
1226 case WODM_UNPREPARE: return MMSYSERR_NOTSUPPORTED;
1227 case WODM_GETDEVCAPS: return wodGetDevCaps (wDevID, (LPWAVEOUTCAPSW)dwParam1, dwParam2);
1228 case WODM_GETNUMDEVS: return wodGetNumDevs ();
1229 case WODM_GETPITCH: return MMSYSERR_NOTSUPPORTED;
1230 case WODM_SETPITCH: return MMSYSERR_NOTSUPPORTED;
1231 case WODM_GETPLAYBACKRATE: return MMSYSERR_NOTSUPPORTED;
1232 case WODM_SETPLAYBACKRATE: return MMSYSERR_NOTSUPPORTED;
1233 case WODM_GETVOLUME: return wodGetVolume (wDevID, (LPDWORD)dwParam1);
1234 case WODM_SETVOLUME: return wodSetVolume (wDevID, dwParam1);
1235 case WODM_RESTART: return wodRestart (wDevID);
1236 case WODM_RESET: return wodReset (wDevID);
1238 case DRV_QUERYDSOUNDIFACE: return wodDsCreate (wDevID, (PIDSDRIVER*)dwParam1);
1239 case DRV_QUERYDSOUNDDESC: return wodDsDesc (wDevID, (PDSDRIVERDESC)dwParam1);
1240 default:
1241 FIXME("unknown message %d!\n", wMsg);
1243 return MMSYSERR_NOTSUPPORTED;
1246 /*======================================================================*
1247 * Low level DSOUND implementation *
1248 *======================================================================*/
1249 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
1251 /* we can't perform memory mapping as we don't have a file stream
1252 interface with nas like we do with oss */
1253 MESSAGE("This sound card s driver does not support direct access\n");
1254 MESSAGE("The (slower) DirectSound HEL mode will be used instead.\n");
1255 return MMSYSERR_NOTSUPPORTED;
1258 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc)
1260 memset(desc, 0, sizeof(*desc));
1261 strcpy(desc->szDesc, "Wine NAS DirectSound Driver");
1262 strcpy(desc->szDrvname, "winenas.drv");
1263 return MMSYSERR_NOERROR;
1266 static int nas_init(void) {
1267 TRACE("NAS INIT\n");
1268 if (!(AuServ = AuOpenServer(NULL, 0, NULL, 0, NULL, NULL)))
1269 return 0;
1271 return 1;
1274 static int nas_finddev(WINE_WAVEOUT* wwo) {
1275 int i;
1277 for (i = 0; i < AuServerNumDevices(wwo->AuServ); i++) {
1278 if ((AuDeviceKind(AuServerDevice(wwo->AuServ, i)) ==
1279 AuComponentKindPhysicalOutput) &&
1280 AuDeviceNumTracks(AuServerDevice(wwo->AuServ, i)) == wwo->format.wf.nChannels)
1282 wwo->AuDev = AuDeviceIdentifier(AuServerDevice(wwo->AuServ, i));
1283 break;
1287 if (wwo->AuDev == AuNone)
1288 return 0;
1289 return 1;
1292 static int nas_open(WINE_WAVEOUT* wwo) {
1293 AuElement elements[3];
1295 if (!wwo->AuServ)
1296 return 0;
1298 if (!nas_finddev(wwo))
1299 return 0;
1301 if (!(wwo->AuFlow = AuCreateFlow(wwo->AuServ, NULL)))
1302 return 0;
1304 wwo->BufferSize = FRAG_SIZE * FRAG_COUNT;
1306 AuMakeElementImportClient(&elements[0], wwo->format.wf.nSamplesPerSec,
1307 wwo->format.wBitsPerSample == 16 ? AuFormatLinearSigned16LSB : AuFormatLinearUnsigned8,
1308 wwo->format.wf.nChannels, AuTrue, wwo->BufferSize, wwo->BufferSize / 2, 0, NULL);
1310 AuMakeElementExportDevice(&elements[1], 0, wwo->AuDev, wwo->format.wf.nSamplesPerSec,
1311 AuUnlimitedSamples, 0, NULL);
1313 AuSetElements(wwo->AuServ, wwo->AuFlow, AuTrue, 2, elements, NULL);
1315 AuRegisterEventHandler(wwo->AuServ, AuEventHandlerIDMask, 0, wwo->AuFlow,
1316 event_handler, (AuPointer) wwo);
1319 wwo->PlayedTotal = 0;
1320 wwo->WrittenTotal = 0;
1321 wwo->open = 1;
1323 wwo->BufferUsed = 0;
1324 wwo->writeBytes = 0;
1325 wwo->freeBytes = 0;
1326 wwo->sendBytes = 0;
1327 wwo->SoundBuffer = NULL;
1328 wwo->FlowStarted = 0;
1330 AuStartFlow(wwo->AuServ, wwo->AuFlow, NULL);
1331 AuPauseFlow(wwo->AuServ, wwo->AuFlow, NULL);
1332 wwo->FlowStarted = 1;
1334 return 1;
1337 static AuBool
1338 event_handler(AuServer* aud, AuEvent* ev, AuEventHandlerRec* hnd)
1340 WINE_WAVEOUT *wwo = (WINE_WAVEOUT *)hnd->data;
1341 switch (ev->type) {
1343 case AuEventTypeElementNotify: {
1344 AuElementNotifyEvent* event = (AuElementNotifyEvent *)ev;
1347 switch (event->kind) {
1348 case AuElementNotifyKindLowWater:
1349 wwo->freeBytes += event->num_bytes;
1350 if (wwo->writeBytes > 0)
1351 wwo->sendBytes += event->num_bytes;
1352 if (wwo->freeBytes && wwo->BufferUsed)
1353 nas_send_buffer(wwo);
1354 break;
1356 case AuElementNotifyKindState:
1357 TRACE("ev: kind %s state %s->%s reason %s numbytes %ld freeB %u\n",
1358 nas_elementnotify_kind(event->kind),
1359 nas_state(event->prev_state),
1360 nas_state(event->cur_state),
1361 nas_reason(event->reason),
1362 event->num_bytes, wwo->freeBytes);
1364 if (event->cur_state == AuStatePause && event->reason != AuReasonUser) {
1365 wwo->freeBytes += event->num_bytes;
1366 if (wwo->writeBytes > 0)
1367 wwo->sendBytes += event->num_bytes;
1368 if (wwo->sendBytes > wwo->writeBytes)
1369 wwo->sendBytes = wwo->writeBytes;
1370 if (wwo->freeBytes && wwo->BufferUsed)
1371 nas_send_buffer(wwo);
1373 break;
1377 return AuTrue;
1380 static void
1381 buffer_resize(WINE_WAVEOUT* wwo, int len)
1383 void *newbuf = malloc(wwo->BufferUsed + len);
1384 void *oldbuf = wwo->SoundBuffer;
1385 memcpy(newbuf, oldbuf, wwo->BufferUsed);
1386 wwo->SoundBuffer = newbuf;
1387 free(oldbuf);
1390 static int nas_add_buffer(WINE_WAVEOUT* wwo) {
1391 int len = wwo->lpPlayPtr->dwBufferLength;
1393 buffer_resize(wwo, len);
1394 memcpy(wwo->SoundBuffer + wwo->BufferUsed, wwo->lpPlayPtr->lpData, len);
1395 wwo->BufferUsed += len;
1396 wwo->WrittenTotal += len;
1397 return len;
1400 static int nas_send_buffer(WINE_WAVEOUT* wwo) {
1401 int oldb , len;
1402 char *ptr, *newdata;
1403 newdata = NULL;
1404 oldb = len = 0;
1406 if (wwo->freeBytes <= 0)
1407 return 0;
1409 if (wwo->SoundBuffer == NULL || wwo->BufferUsed == 0) {
1410 return 0;
1413 if (wwo->BufferUsed <= wwo->freeBytes) {
1414 len = wwo->BufferUsed;
1415 ptr = wwo->SoundBuffer;
1416 } else {
1417 len = wwo->freeBytes;
1418 ptr = malloc(len);
1419 memcpy(ptr,wwo->SoundBuffer,len);
1420 newdata = malloc(wwo->BufferUsed - len);
1421 memcpy(newdata, wwo->SoundBuffer + len, wwo->BufferUsed - len);
1424 TRACE("envoye de %d bytes / %lu bytes / freeBytes %u\n", len, wwo->BufferUsed, wwo->freeBytes);
1426 AuWriteElement(wwo->AuServ, wwo->AuFlow, 0, len, ptr, AuFalse, NULL);
1428 wwo->BufferUsed -= len;
1429 wwo->freeBytes -= len;
1430 wwo->writeBytes += len;
1432 free(ptr);
1434 wwo->SoundBuffer = NULL;
1436 if (newdata != NULL)
1437 wwo->SoundBuffer = newdata;
1439 return len;
1442 static int nas_free(WINE_WAVEOUT* wwo)
1445 if (!wwo->FlowStarted && wwo->BufferUsed) {
1446 AuStartFlow(wwo->AuServ, wwo->AuFlow, NULL);
1447 wwo->FlowStarted = 1;
1450 while (wwo->BufferUsed || wwo->writeBytes != wwo->sendBytes) {
1451 if (wwo->freeBytes)
1452 nas_send_buffer(wwo);
1453 AuHandleEvents(wwo->AuServ);
1456 AuFlush(wwo->AuServ);
1457 return TRUE;
1460 static int nas_close(WINE_WAVEOUT* wwo)
1462 AuEvent ev;
1464 nas_free(wwo);
1466 AuStopFlow(wwo->AuServ, wwo->AuFlow, NULL);
1467 AuDestroyFlow(wwo->AuServ, wwo->AuFlow, NULL);
1468 AuFlush(wwo->AuServ);
1469 AuNextEvent(wwo->AuServ, AuTrue, &ev);
1470 AuDispatchEvent(wwo->AuServ, &ev);
1472 wwo->AuFlow = 0;
1473 wwo->open = 0;
1474 wwo->BufferUsed = 0;
1475 wwo->freeBytes = 0;
1476 wwo->SoundBuffer = NULL;
1477 return 1;
1480 static int nas_end(void)
1482 if (AuServ)
1484 AuCloseServer(AuServ);
1485 AuServ = 0;
1487 return 1;
1490 #else /* !HAVE_NAS */
1492 /**************************************************************************
1493 * wodMessage (WINENAS.@)
1495 DWORD WINAPI NAS_wodMessage(WORD wDevID, WORD wMsg, DWORD dwUser, DWORD dwParam1, DWORD dwParam2)
1497 FIXME("(%u, %04X, %08X, %08X, %08X):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
1498 return MMSYSERR_NOTENABLED;
1500 #endif