Keep track of per-column information inside the listview.
[wine] / dlls / winmm / wineaudioio / audio.c
1 /* -*- tab-width: 8; c-basic-offset: 4 -*- */
2 /*
3  * Wine Driver for Libaudioio
4  * Derived from the Wine OSS Sample Driver
5  * Copyright 1994 Martin Ayotte
6  *           1999 Eric Pouech (async playing in waveOut/waveIn)
7  *           2000 Eric Pouech (loops in waveOut)
8  *           2002 Robert Lunnon (Modifications for libaudioio)
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with this library; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23  *
24  *
25  * Note large hacks done to effectively  disable DSound altogether
26  *  Also Input is not yet working (Lots more work to be done there)
27   * But this does make a reasonable output driver for solaris untill the arts driver comes up to speed
28  */
29
30 /*
31  * FIXME:
32  *      pause in waveOut does not work correctly
33  *      full duplex (in/out) is not working (device is opened twice for Out
34  *      and In) (OSS is known for its poor duplex capabilities, alsa is
35  *      better)
36  */
37
38 /*#define EMULATE_SB16*/
39
40 #include "config.h"
41
42 #include <stdlib.h>
43 #include <stdio.h>
44 #include <string.h>
45 #ifdef HAVE_UNISTD_H
46 # include <unistd.h>
47 #endif
48 #include <errno.h>
49 #include <fcntl.h>
50 #ifdef HAVE_SYS_IOCTL_H
51 # include <sys/ioctl.h>
52 #endif
53 #ifdef HAVE_SYS_MMAN_H
54 # include <sys/mman.h>
55 #endif
56 #ifdef HAVE_LIBAUDIOIO_H
57 #include <libaudioio.h>
58 #endif
59 #include "windef.h"
60 #include "wingdi.h"
61 #include "winerror.h"
62 #include "wine/winuser16.h"
63 #include "mmddk.h"
64 #include "dsound.h"
65 #include "dsdriver.h"
66 #include "wine/debug.h"
67
68 WINE_DEFAULT_DEBUG_CHANNEL(wave);
69
70 #ifdef HAVE_LIBAUDIOIO
71
72 /* Allow 1% deviation for sample rates (some ES137x cards) */
73 #define NEAR_MATCH(rate1,rate2) (((100*((int)(rate1)-(int)(rate2)))/(rate1))==0)
74
75 #define SOUND_DEV "/dev/audio"
76 #define DEFAULT_FRAGMENT_SIZE 4096
77
78
79
80 #define MAX_WAVEOUTDRV  (1)
81 #define MAX_WAVEINDRV   (1)
82
83 /* state diagram for waveOut writing:
84  *
85  * +---------+-------------+---------------+---------------------------------+
86  * |  state  |  function   |     event     |            new state            |
87  * +---------+-------------+---------------+---------------------------------+
88  * |         | open()      |               | STOPPED                         |
89  * | PAUSED  | write()     |               | PAUSED                          |
90  * | STOPPED | write()     | <thrd create> | PLAYING                         |
91  * | PLAYING | write()     | HEADER        | PLAYING                         |
92  * | (other) | write()     | <error>       |                                 |
93  * | (any)   | pause()     | PAUSING       | PAUSED                          |
94  * | PAUSED  | restart()   | RESTARTING    | PLAYING (if no thrd => STOPPED) |
95  * | (any)   | reset()     | RESETTING     | STOPPED                         |
96  * | (any)   | close()     | CLOSING       | CLOSED                          |
97  * +---------+-------------+---------------+---------------------------------+
98  */
99
100 /* states of the playing device */
101 #define WINE_WS_PLAYING         0
102 #define WINE_WS_PAUSED          1
103 #define WINE_WS_STOPPED         2
104 #define WINE_WS_CLOSED          3
105
106 /* events to be send to device */
107 #define WINE_WM_PAUSING         (WM_USER + 1)
108 #define WINE_WM_RESTARTING      (WM_USER + 2)
109 #define WINE_WM_RESETTING       (WM_USER + 3)
110 #define WINE_WM_CLOSING         (WM_USER + 4)
111 #define WINE_WM_HEADER          (WM_USER + 5)
112
113 #define WINE_WM_FIRST WINE_WM_PAUSING
114 #define WINE_WM_LAST WINE_WM_HEADER
115
116 typedef struct {
117     int msg;
118     DWORD param;
119 } WWO_MSG;
120
121 typedef struct {
122     int                         unixdev;
123     volatile int                state;                  /* one of the WINE_WS_ manifest constants */
124     DWORD                       dwFragmentSize;         /* size of OSS buffer fragment */
125     WAVEOPENDESC                waveDesc;
126     WORD                        wFlags;
127     PCMWAVEFORMAT               format;
128     LPWAVEHDR                   lpQueuePtr;             /* start of queued WAVEHDRs (waiting to be notified) */
129     LPWAVEHDR                   lpPlayPtr;              /* start of not yet fully played buffers */
130     LPWAVEHDR                   lpLoopPtr;              /* pointer of first buffer in loop, if any */
131     DWORD                       dwLoops;                /* private copy of loop counter */
132
133     DWORD                       dwLastFragDone;         /* time in ms, when last played fragment will be actually played */
134     DWORD                       dwPlayedTotal;          /* number of bytes played since opening */
135
136     /* info on current lpQueueHdr->lpWaveHdr */
137     DWORD                       dwOffCurrHdr;           /* offset in lpPlayPtr->lpData for fragments */
138     DWORD                       dwRemain;               /* number of bytes to write to end the current fragment  */
139
140     /* synchronization stuff */
141     HANDLE                      hThread;
142     DWORD                       dwThreadID;
143     HANDLE                      hEvent;
144 #define WWO_RING_BUFFER_SIZE    30
145     WWO_MSG                     messages[WWO_RING_BUFFER_SIZE];
146     int                         msg_tosave;
147     int                         msg_toget;
148     HANDLE                      msg_event;
149     CRITICAL_SECTION            msg_crst;
150     WAVEOUTCAPSA                caps;
151
152     /* DirectSound stuff */
153     LPBYTE                      mapping;
154     DWORD                       maplen;
155 } WINE_WAVEOUT;
156
157 typedef struct {
158     int                         unixdev;
159     volatile int                state;
160     DWORD                       dwFragmentSize;         /* OpenSound '/dev/dsp' give us that size */
161     WAVEOPENDESC                waveDesc;
162     WORD                        wFlags;
163     PCMWAVEFORMAT               format;
164     LPWAVEHDR                   lpQueuePtr;
165     DWORD                       dwTotalRecorded;
166     WAVEINCAPSA                 caps;
167     BOOL                        bTriggerSupport;
168
169     /* synchronization stuff */
170     HANDLE                      hThread;
171     DWORD                       dwThreadID;
172     HANDLE                      hEvent;
173 } WINE_WAVEIN;
174
175 static WINE_WAVEOUT     WOutDev   [MAX_WAVEOUTDRV];
176 static WINE_WAVEIN      WInDev    [MAX_WAVEINDRV ];
177
178 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv);
179
180 /*======================================================================*
181  *                  Low level WAVE implementation                       *
182  *======================================================================*/
183 SampleSpec_t spec[2];
184
185
186
187 LONG LIBAUDIOIO_WaveInit(void)
188 {
189     int         audio;
190     int         smplrate;
191     int         samplesize = 16;
192     int         dsp_stereo = 1;
193     int         bytespersmpl;
194     int         caps;
195     int         mask;
196         int     i;
197
198         int audio_fd;
199         int mode;
200     TRACE("Init ENTERED rate = %d\n",spec[PLAYBACK].rate);
201        spec[RECORD].channels=spec[PLAYBACK].channels=2;
202         spec[RECORD].max_blocks=spec[PLAYBACK].max_blocks=16;
203         spec[RECORD].rate=spec[PLAYBACK].rate=44100;
204         spec[RECORD].encoding=spec[PLAYBACK].encoding= ENCODE_PCM;
205         spec[RECORD].precision=spec[PLAYBACK].precision=16 ;
206         spec[RECORD].endian=spec[PLAYBACK].endian=ENDIAN_INTEL;
207         spec[RECORD].disable_threads=spec[PLAYBACK].disable_threads=1;
208         spec[RECORD].type=spec[PLAYBACK].type=TYPE_SIGNED; /* in 16 bit mode this is what typical PC hardware expects */
209
210         mode = O_WRONLY|O_NDELAY;
211
212         /* start with output device */
213
214         /* initialize all device handles to -1 */
215         for (i = 0; i < MAX_WAVEOUTDRV; ++i)
216         {
217                 WOutDev[i].unixdev = -1;
218         }
219
220     /* FIXME: only one device is supported */
221     memset(&WOutDev[0].caps, 0, sizeof(WOutDev[0].caps));
222
223
224
225     /* FIXME: some programs compare this string against the content of the registry
226      * for MM drivers. The names have to match in order for the program to work
227      * (e.g. MS win9x mplayer.exe)
228      */
229 #ifdef EMULATE_SB16
230     WOutDev[0].caps.wMid = 0x0002;
231     WOutDev[0].caps.wPid = 0x0104;
232     strcpy(WOutDev[0].caps.szPname, "SB16 Wave Out");
233 #else
234     WOutDev[0].caps.wMid = 0x00FF;      /* Manufac ID */
235     WOutDev[0].caps.wPid = 0x0001;      /* Product ID */
236     /*    strcpy(WOutDev[0].caps.szPname, "OpenSoundSystem WAVOUT Driver");*/
237     strcpy(WOutDev[0].caps.szPname, "CS4236/37/38");
238 #endif
239     WOutDev[0].caps.vDriverVersion = 0x0100;
240     WOutDev[0].caps.dwFormats = 0x00000000;
241     WOutDev[0].caps.dwSupport = WAVECAPS_VOLUME;
242
243     /*
244      * Libaudioio works differently, you tell it what spec audio you want to write and it
245      * Guarantees to match it by converting to the final format on the fly
246      *So we dont need to read  back and compare
247      */
248
249     bytespersmpl = spec[PLAYBACK].precision/8;
250
251     WOutDev[0].caps.wChannels = spec[PLAYBACK].channels;
252
253
254 /* Fixme: Libaudioio 0.2 doesn't support balance yet (Libaudioio 0.3 does so this must be fixed later)*/
255
256 /*    if (WOutDev[0].caps.wChannels > 1) WOutDev[0].caps.dwSupport |= WAVECAPS_LRVOLUME;*/
257     TRACE("Init sammplerate= %d\n",spec[PLAYBACK].rate);
258
259     smplrate = spec[PLAYBACK].rate;
260 /*
261  * We have set up the data format to be 16 bit signed in intel format
262  * For Big Endian machines libaudioio will convert the data to bigendian for us
263  */
264
265             WOutDev[0].caps.dwFormats |= WAVE_FORMAT_4M16;
266             if (WOutDev[0].caps.wChannels > 1)
267                 WOutDev[0].caps.dwFormats |= WAVE_FORMAT_4S16;
268
269 /* Don't understand this yet, but I dont think this functionality is portable, leave here for future evaluation
270  *   if (IOCTL(audio, SNDCTL_DSP_GETCAPS, caps) == 0) {
271  *      TRACE("OSS dsp out caps=%08X\n", caps);
272  *      if ((caps & DSP_CAP_REALTIME) && !(caps & DSP_CAP_BATCH)) {
273  *          WOutDev[0].caps.dwSupport |= WAVECAPS_SAMPLEACCURATE;
274  *      }
275  */     /* well, might as well use the DirectSound cap flag for something */
276 /*      if ((caps & DSP_CAP_TRIGGER) && (caps & DSP_CAP_MMAP) &&
277  *          !(caps & DSP_CAP_BATCH))
278  *          WOutDev[0].caps.dwSupport |= WAVECAPS_DIRECTSOUND;
279  *   }
280  */
281
282
283 /*
284  * Note that libaudioio audio capture is not proven yet, in our open call
285  * set the spec for input audio the same as for output
286  */
287     TRACE("out dwFormats = %08lX, dwSupport = %08lX\n",
288           WOutDev[0].caps.dwFormats, WOutDev[0].caps.dwSupport);
289
290         for (i = 0; i < MAX_WAVEINDRV; ++i)
291         {
292                 WInDev[i].unixdev = -1;
293         }
294
295         memset(&WInDev[0].caps, 0, sizeof(WInDev[0].caps));
296
297
298
299 #ifdef EMULATE_SB16
300     WInDev[0].caps.wMid = 0x0002;
301     WInDev[0].caps.wPid = 0x0004;
302     strcpy(WInDev[0].caps.szPname, "SB16 Wave In");
303 #else
304     WInDev[0].caps.wMid = 0x00FF;       /* Manufac ID */
305     WInDev[0].caps.wPid = 0x0001;       /* Product ID */
306     strcpy(WInDev[0].caps.szPname, "OpenSoundSystem WAVIN Driver");
307 #endif
308     WInDev[0].caps.dwFormats = 0x00000000;
309     WInDev[0].caps.wChannels = spec[RECORD].channels;
310
311     WInDev[0].bTriggerSupport = TRUE;    /* Maybe :-) */
312
313     bytespersmpl = spec[RECORD].precision/8;
314     smplrate = spec[RECORD].rate;
315
316             WInDev[0].caps.dwFormats |= WAVE_FORMAT_4M16;
317             if (WInDev[0].caps.wChannels > 1)
318                 WInDev[0].caps.dwFormats |= WAVE_FORMAT_4S16;
319
320
321     TRACE("in dwFormats = %08lX\n", WInDev[0].caps.dwFormats);
322
323     return 0;
324 }
325
326 /**************************************************************************
327  *                      LIBAUDIOIO_NotifyClient                 [internal]
328  */
329 static DWORD LIBAUDIOIO_NotifyClient(UINT wDevID, WORD wMsg, DWORD dwParam1, DWORD dwParam2)
330 {
331     TRACE("wDevID = %04X wMsg = 0x%04x dwParm1 = %04lX dwParam2 = %04lX\n",wDevID, wMsg, dwParam1, dwParam2);
332
333     switch (wMsg) {
334     case WOM_OPEN:
335     case WOM_CLOSE:
336     case WOM_DONE:
337         if (wDevID >= MAX_WAVEOUTDRV) return MCIERR_INTERNAL;
338
339         if (WOutDev[wDevID].wFlags != DCB_NULL &&
340             !DriverCallback(WOutDev[wDevID].waveDesc.dwCallback,
341                             WOutDev[wDevID].wFlags,
342                             WOutDev[wDevID].waveDesc.hWave,
343                             wMsg,
344                             WOutDev[wDevID].waveDesc.dwInstance,
345                             dwParam1,
346                             dwParam2)) {
347             WARN("can't notify client !\n");
348             return MMSYSERR_NOERROR;
349         }
350         break;
351
352     case WIM_OPEN:
353     case WIM_CLOSE:
354     case WIM_DATA:
355         if (wDevID >= MAX_WAVEINDRV) return MCIERR_INTERNAL;
356
357         if (WInDev[wDevID].wFlags != DCB_NULL &&
358             !DriverCallback(WInDev[wDevID].waveDesc.dwCallback,
359                             WInDev[wDevID].wFlags,
360                             WInDev[wDevID].waveDesc.hWave,
361                             wMsg,
362                             WInDev[wDevID].waveDesc.dwInstance,
363                             dwParam1,
364                             dwParam2)) {
365             WARN("can't notify client !\n");
366             return MMSYSERR_NOERROR;
367         }
368         break;
369     default:
370         FIXME("Unknown CB message %u\n", wMsg);
371         break;
372     }
373     return 0;
374 }
375
376 /*======================================================================*
377  *                  Low level WAVE OUT implementation                   *
378  *======================================================================*/
379
380 /**************************************************************************
381  *                              wodPlayer_WriteFragments        [internal]
382  *
383  * wodPlayer helper. Writes as many fragments as it can to unixdev.
384  * Returns TRUE in case of buffer underrun.
385  */
386 static  BOOL    wodPlayer_WriteFragments(WINE_WAVEOUT* wwo)
387 {
388     LPWAVEHDR           lpWaveHdr;
389     LPBYTE              lpData;
390     int                 count;
391
392 TRACE("wodPlayer_WriteFragments sammplerate= %d\n",spec[PLAYBACK].rate);
393     for (;;) {
394
395
396 /*
397  * Libaudioio doesn't buffer the same way as linux, you can write data is any block size
398  *And libaudioio just tracks the number of blocks in the streams queue to control latency
399  */
400
401         if (!AudioIOCheckWriteReady()) return FALSE;   /*  Returns false if you have execeeded your specified latency (No space left)*/
402
403         lpWaveHdr = wwo->lpPlayPtr;
404         if (!lpWaveHdr) {
405             if (wwo->dwRemain > 0 &&            /* still data to send to complete current fragment */
406                 wwo->dwLastFragDone &&          /* first fragment has been played */
407                 AudioIOCheckUnderrun()) {   /* done with all waveOutWrite()' fragments */
408                 /* FIXME: should do better handling here */
409                 WARN("Oooch, buffer underrun !\n");
410                 return TRUE; /* force resetting of waveOut device */
411             }
412             return FALSE;       /* wait a bit */
413         }
414
415         if (wwo->dwOffCurrHdr == 0) {
416             TRACE("Starting a new wavehdr %p of %ld bytes\n", lpWaveHdr, lpWaveHdr->dwBufferLength);
417             if (lpWaveHdr->dwFlags & WHDR_BEGINLOOP) {
418                 if (wwo->lpLoopPtr) {
419                     WARN("Already in a loop. Discarding loop on this header (%p)\n", lpWaveHdr);
420                 } else {
421                     TRACE("Starting loop (%ldx) with %p\n", lpWaveHdr->dwLoops, lpWaveHdr);
422                     wwo->lpLoopPtr = lpWaveHdr;
423                     /* Windows does not touch WAVEHDR.dwLoops,
424                      * so we need to make an internal copy */
425                     wwo->dwLoops = lpWaveHdr->dwLoops;
426                 }
427             }
428         }
429
430         lpData = lpWaveHdr->lpData;
431
432         /* finish current wave hdr ? */
433         if (wwo->dwOffCurrHdr + wwo->dwRemain >= lpWaveHdr->dwBufferLength) {
434             DWORD       toWrite = lpWaveHdr->dwBufferLength - wwo->dwOffCurrHdr;
435
436             /* write end of current wave hdr */
437             count = AudioIOWrite(lpData + wwo->dwOffCurrHdr, toWrite);
438             TRACE("write(%p[%5lu], %5lu) => %d\n", lpData, wwo->dwOffCurrHdr, toWrite, count);
439
440             if (count > 0 || toWrite == 0) {
441                 DWORD   tc = GetTickCount();
442
443                 if (wwo->dwLastFragDone /* + guard time ?? */ < tc)
444                     wwo->dwLastFragDone = tc;
445                 wwo->dwLastFragDone += (toWrite * 1000) / wwo->format.wf.nAvgBytesPerSec;
446
447                 lpWaveHdr->reserved = wwo->dwLastFragDone;
448                 TRACE("Tagging hdr %p with %08lx\n", lpWaveHdr, wwo->dwLastFragDone);
449
450                 /* WAVEHDR written, go to next one */
451                 if ((lpWaveHdr->dwFlags & WHDR_ENDLOOP) && wwo->lpLoopPtr) {
452                     if (--wwo->dwLoops > 0) {
453                         wwo->lpPlayPtr = wwo->lpLoopPtr;
454                     } else {
455                         /* last one played */
456                         if (wwo->lpLoopPtr != lpWaveHdr && (lpWaveHdr->dwFlags & WHDR_BEGINLOOP)) {
457                             FIXME("Correctly handled case ? (ending loop buffer also starts a new loop)\n");
458                             /* shall we consider the END flag for the closing loop or for
459                              * the opening one or for both ???
460                              * code assumes for closing loop only
461                              */
462                             wwo->lpLoopPtr = lpWaveHdr;
463                         } else {
464                             wwo->lpLoopPtr = NULL;
465                         }
466                         wwo->lpPlayPtr = lpWaveHdr->lpNext;
467                     }
468                 } else {
469                     wwo->lpPlayPtr = lpWaveHdr->lpNext;
470                 }
471                 wwo->dwOffCurrHdr = 0;
472                 if ((wwo->dwRemain -= count) == 0) {
473                     wwo->dwRemain = wwo->dwFragmentSize;
474                 }
475             }
476             continue; /* try to go to use next wavehdr */
477         }  else {
478             count = AudioIOWrite( lpData + wwo->dwOffCurrHdr, wwo->dwRemain);
479             TRACE("write(%p[%5lu], %5lu) => %d\n", lpData, wwo->dwOffCurrHdr, wwo->dwRemain, count);
480             if (count > 0) {
481                 DWORD   tc = GetTickCount();
482
483                 if (wwo->dwLastFragDone /* + guard time ?? */ < tc)
484                     wwo->dwLastFragDone = tc;
485                 wwo->dwLastFragDone += (wwo->dwRemain * 1000) / wwo->format.wf.nAvgBytesPerSec;
486
487                 TRACE("Tagging frag with %08lx\n", wwo->dwLastFragDone);
488
489                 wwo->dwOffCurrHdr += count;
490                 wwo->dwRemain = wwo->dwFragmentSize;
491             }
492         }
493     }
494
495 }
496
497 int wodPlayer_Message(WINE_WAVEOUT *wwo, int msg, DWORD param)
498 {
499     TRACE("wodPlayerMessage sammplerate= %d  msg=%d\n",spec[PLAYBACK].rate,msg);
500     EnterCriticalSection(&wwo->msg_crst);
501     if ((wwo->msg_tosave == wwo->msg_toget) /* buffer overflow ? */
502     &&  (wwo->messages[wwo->msg_toget].msg))
503     {
504         ERR("buffer overflow !?\n");
505         LeaveCriticalSection(&wwo->msg_crst);
506         return 0;
507     }
508
509     wwo->messages[wwo->msg_tosave].msg = msg;
510     wwo->messages[wwo->msg_tosave].param = param;
511     wwo->msg_tosave++;
512     if (wwo->msg_tosave > WWO_RING_BUFFER_SIZE-1)
513         wwo->msg_tosave = 0;
514     LeaveCriticalSection(&wwo->msg_crst);
515     /* signal a new message */
516     SetEvent(wwo->msg_event);
517     return 1;
518 }
519
520 int wodPlayer_RetrieveMessage(WINE_WAVEOUT *wwo, int *msg, DWORD *param)
521 {
522     EnterCriticalSection(&wwo->msg_crst);
523
524     if (wwo->msg_toget == wwo->msg_tosave) /* buffer empty ? */
525     {
526         LeaveCriticalSection(&wwo->msg_crst);
527         return 0;
528     }
529
530     *msg = wwo->messages[wwo->msg_toget].msg;
531     wwo->messages[wwo->msg_toget].msg = 0;
532     *param = wwo->messages[wwo->msg_toget].param;
533     wwo->msg_toget++;
534     if (wwo->msg_toget > WWO_RING_BUFFER_SIZE-1)
535         wwo->msg_toget = 0;
536     LeaveCriticalSection(&wwo->msg_crst);
537     return 1;
538 }
539
540 /**************************************************************************
541  *                              wodPlayer_Notify                [internal]
542  *
543  * wodPlayer helper. Notifies (and remove from queue) all the wavehdr which content
544  * have been played (actually to speaker, not to unixdev fd).
545  */
546 static  void    wodPlayer_Notify(WINE_WAVEOUT* wwo, WORD uDevID, BOOL force)
547 {
548     LPWAVEHDR           lpWaveHdr;
549     DWORD               tc = GetTickCount();
550
551     while (wwo->lpQueuePtr &&
552            (force ||
553             (wwo->lpQueuePtr != wwo->lpPlayPtr && wwo->lpQueuePtr != wwo->lpLoopPtr))) {
554         lpWaveHdr = wwo->lpQueuePtr;
555
556         if (lpWaveHdr->reserved > tc && !force) break;
557
558         wwo->dwPlayedTotal += lpWaveHdr->dwBufferLength;
559         wwo->lpQueuePtr = lpWaveHdr->lpNext;
560
561         lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
562         lpWaveHdr->dwFlags |= WHDR_DONE;
563
564         TRACE("Notifying client with %p\n", lpWaveHdr);
565         if (LIBAUDIOIO_NotifyClient(uDevID, WOM_DONE, (DWORD)lpWaveHdr, 0) != MMSYSERR_NOERROR) {
566             WARN("can't notify client !\n");
567         }
568     }
569 }
570
571 /**************************************************************************
572  *                              wodPlayer_Reset                 [internal]
573  *
574  * wodPlayer helper. Resets current output stream.
575  */
576 static  void    wodPlayer_Reset(WINE_WAVEOUT* wwo, WORD uDevID, BOOL reset)
577 {
578     /* updates current notify list */
579     wodPlayer_Notify(wwo, uDevID, FALSE);
580
581     /* flush all possible output */
582 /*
583  *FIXME In the original code I think this aborted IO. With Libaudioio you have to wait
584  * The following function just blocks untill I/O is complete
585  * There is possibly a way to abort the blocks buffered in streams
586  * but this approach seems to work OK
587  */
588         AudioIOFlush();
589
590
591
592     wwo->dwOffCurrHdr = 0;
593     wwo->dwRemain = wwo->dwFragmentSize;
594     if (reset) {
595         /* empty notify list */
596         wodPlayer_Notify(wwo, uDevID, TRUE);
597
598         wwo->lpPlayPtr = wwo->lpQueuePtr = wwo->lpLoopPtr = NULL;
599         wwo->state = WINE_WS_STOPPED;
600         wwo->dwPlayedTotal = 0;
601     } else {
602         /* FIXME: this is not accurate when looping, but can be do better ? */
603         wwo->lpPlayPtr = (wwo->lpLoopPtr) ? wwo->lpLoopPtr : wwo->lpQueuePtr;
604         wwo->state = WINE_WS_PAUSED;
605     }
606 }
607
608 /**************************************************************************
609  *                              wodPlayer                       [internal]
610  */
611 static  DWORD   CALLBACK        wodPlayer(LPVOID pmt)
612 {
613     WORD                uDevID = (DWORD)pmt;
614     WINE_WAVEOUT*       wwo = (WINE_WAVEOUT*)&WOutDev[uDevID];
615     WAVEHDR*            lpWaveHdr;
616     DWORD               dwSleepTime;
617     int                 msg;
618     DWORD               param;
619     DWORD               tc;
620     BOOL                had_msg;
621
622     wwo->state = WINE_WS_STOPPED;
623
624     wwo->dwLastFragDone = 0;
625     wwo->dwOffCurrHdr = 0;
626     wwo->dwRemain = wwo->dwFragmentSize;
627     wwo->lpQueuePtr = wwo->lpPlayPtr = wwo->lpLoopPtr = NULL;
628     wwo->dwPlayedTotal = 0;
629
630     TRACE("imhere[0]\n");
631     SetEvent(wwo->hEvent);
632
633     for (;;) {
634         /* wait for dwSleepTime or an event in thread's queue
635          * FIXME:
636          * - is wait time calculation optimal ?
637          * - these 100 ms parts should be changed, but Eric reports
638          *   that the wodPlayer thread might lock up if we use INFINITE
639          *   (strange !), so I better don't change that now... */
640         if (wwo->state != WINE_WS_PLAYING)
641             dwSleepTime = 100;
642         else
643         {
644             tc = GetTickCount();
645             if (tc < wwo->dwLastFragDone)
646             {
647                 /* calculate sleep time depending on when the last fragment
648                    will be played */
649                 dwSleepTime = (wwo->dwLastFragDone - tc)*7/10;
650                 if (dwSleepTime > 100)
651                     dwSleepTime = 100;
652             }
653             else
654                 dwSleepTime = 0;
655         }
656
657         TRACE("imhere[1] tc = %08lx\n", GetTickCount());
658         if (dwSleepTime)
659             WaitForSingleObject(wwo->msg_event, dwSleepTime);
660         TRACE("imhere[2] (q=%p p=%p) tc = %08lx\n", wwo->lpQueuePtr,
661               wwo->lpPlayPtr, GetTickCount());
662         had_msg = FALSE;
663         while (wodPlayer_RetrieveMessage(wwo, &msg, &param)) {
664             had_msg = TRUE;
665             switch (msg) {
666             case WINE_WM_PAUSING:
667                 wodPlayer_Reset(wwo, uDevID, FALSE);
668                 wwo->state = WINE_WS_PAUSED;
669                 SetEvent(wwo->hEvent);
670                 break;
671             case WINE_WM_RESTARTING:
672                 wwo->state = WINE_WS_PLAYING;
673                 SetEvent(wwo->hEvent);
674                 break;
675             case WINE_WM_HEADER:
676                 lpWaveHdr = (LPWAVEHDR)param;
677
678                 /* insert buffer at the end of queue */
679                 {
680                     LPWAVEHDR*  wh;
681                     for (wh = &(wwo->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
682                     *wh = lpWaveHdr;
683                 }
684                 if (!wwo->lpPlayPtr) wwo->lpPlayPtr = lpWaveHdr;
685                 if (wwo->state == WINE_WS_STOPPED)
686                     wwo->state = WINE_WS_PLAYING;
687                 break;
688             case WINE_WM_RESETTING:
689                 wodPlayer_Reset(wwo, uDevID, TRUE);
690                 SetEvent(wwo->hEvent);
691                 break;
692             case WINE_WM_CLOSING:
693                 /* sanity check: this should not happen since the device must have been reset before */
694                 if (wwo->lpQueuePtr || wwo->lpPlayPtr) ERR("out of sync\n");
695                 wwo->hThread = 0;
696                 wwo->state = WINE_WS_CLOSED;
697                 SetEvent(wwo->hEvent);
698                 ExitThread(0);
699                 /* shouldn't go here */
700             default:
701                 FIXME("unknown message %d\n", msg);
702                 break;
703             }
704             if (wwo->state == WINE_WS_PLAYING) {
705                 wodPlayer_WriteFragments(wwo);
706             }
707             wodPlayer_Notify(wwo, uDevID, FALSE);
708         }
709
710         if (!had_msg) { /* if we've received a msg we've just done this so we
711                            won't repeat it */
712             if (wwo->state == WINE_WS_PLAYING) {
713                 wodPlayer_WriteFragments(wwo);
714             }
715             wodPlayer_Notify(wwo, uDevID, FALSE);
716         }
717     }
718     ExitThread(0);
719     /* just for not generating compilation warnings... should never be executed */
720     return 0;
721 }
722
723 /**************************************************************************
724  *                      wodGetDevCaps                           [internal]
725  */
726 static DWORD wodGetDevCaps(WORD wDevID, LPWAVEOUTCAPSA lpCaps, DWORD dwSize)
727 {
728     TRACE("(%u, %p, %lu);\n", wDevID, lpCaps, dwSize);
729
730     if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
731
732     if (wDevID >= MAX_WAVEOUTDRV) {
733         TRACE("MAX_WAVOUTDRV reached !\n");
734         return MMSYSERR_BADDEVICEID;
735     }
736
737     memcpy(lpCaps, &WOutDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
738     return MMSYSERR_NOERROR;
739 }
740
741 /**************************************************************************
742  *                              wodOpen                         [internal]
743  */
744 static DWORD wodOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
745 {
746     int                 audio;
747     int                 format;
748     int                 sample_rate;
749     int                 dsp_stereo;
750     int                 fragment_size;
751     int                 audio_fragment;
752     WINE_WAVEOUT*       wwo;
753
754     TRACE("(%u, %p, %08lX);\n", wDevID, lpDesc, dwFlags);
755     if (lpDesc == NULL) {
756         WARN("Invalid Parameter !\n");
757         return MMSYSERR_INVALPARAM;
758     }
759     if (wDevID >= MAX_WAVEOUTDRV) {
760         TRACE("MAX_WAVOUTDRV reached !\n");
761         return MMSYSERR_BADDEVICEID;
762     }
763
764     /* only PCM format is supported so far... */
765     if (lpDesc->lpFormat->wFormatTag != WAVE_FORMAT_PCM ||
766         lpDesc->lpFormat->nChannels == 0 ||
767         lpDesc->lpFormat->nSamplesPerSec == 0) {
768         WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
769              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
770              lpDesc->lpFormat->nSamplesPerSec);
771         return WAVERR_BADFORMAT;
772     }
773
774     if (dwFlags & WAVE_FORMAT_QUERY) {
775         TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
776              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
777              lpDesc->lpFormat->nSamplesPerSec);
778         return MMSYSERR_NOERROR;
779     }
780
781     wwo = &WOutDev[wDevID];
782
783     if ((dwFlags & WAVE_DIRECTSOUND) && !(wwo->caps.dwSupport & WAVECAPS_DIRECTSOUND))
784         /* not supported, ignore it */
785         dwFlags &= ~WAVE_DIRECTSOUND;
786
787     if (access(SOUND_DEV, 0) != 0)
788         return MMSYSERR_NOTENABLED;
789
790         audio = AudioIOOpenX( O_WRONLY|O_NDELAY,&spec[PLAYBACK],&spec[PLAYBACK]);
791
792     if (audio == -1) {
793         WARN("can't open sound device %s (%s)!\n", SOUND_DEV, strerror(errno));
794         return MMSYSERR_ALLOCATED;
795     }
796  /*   fcntl(audio, F_SETFD, 1); *//* set close on exec flag - Dunno about this (RL)*/
797     wwo->unixdev = audio;
798     wwo->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
799
800     memcpy(&wwo->waveDesc, lpDesc,           sizeof(WAVEOPENDESC));
801     memcpy(&wwo->format,   lpDesc->lpFormat, sizeof(PCMWAVEFORMAT));
802
803     if (wwo->format.wBitsPerSample == 0) {
804         WARN("Resetting zeroed wBitsPerSample\n");
805         wwo->format.wBitsPerSample = 8 *
806             (wwo->format.wf.nAvgBytesPerSec /
807              wwo->format.wf.nSamplesPerSec) /
808             wwo->format.wf.nChannels;
809     }
810
811     if (dwFlags & WAVE_DIRECTSOUND) {
812         if (wwo->caps.dwSupport & WAVECAPS_SAMPLEACCURATE)
813             /* we have realtime DirectSound, fragments just waste our time,
814              * but a large buffer is good, so choose 64KB (32 * 2^11) */
815             audio_fragment = 0x0020000B;
816         else
817             /* to approximate realtime, we must use small fragments,
818              * let's try to fragment the above 64KB (256 * 2^8) */
819             audio_fragment = 0x01000008;
820     } else {
821         /* shockwave player uses only 4 1k-fragments at a rate of 22050 bytes/sec
822          * thus leading to 46ms per fragment, and a turnaround time of 185ms
823          */
824         /* 16 fragments max, 2^10=1024 bytes per fragment */
825         audio_fragment = 0x000F000A;
826     }
827     sample_rate = wwo->format.wf.nSamplesPerSec;
828     dsp_stereo = (wwo->format.wf.nChannels > 1) ? 1 : 0;
829
830
831
832     /*Set the sample rate*/
833     spec[PLAYBACK].rate=sample_rate;
834
835     /*And the size and signedness*/
836     spec[PLAYBACK].precision=(wwo->format.wBitsPerSample );
837     if (spec[PLAYBACK].precision==16) spec[PLAYBACK].type=TYPE_SIGNED; else spec[PLAYBACK].type=TYPE_UNSIGNED;
838     spec[PLAYBACK].channels=(wwo->format.wf.nChannels);
839     spec[PLAYBACK].encoding=ENCODE_PCM;
840     spec[PLAYBACK].endian=ENDIAN_INTEL;
841     spec[PLAYBACK].max_blocks=16;  /*FIXME This is the libaudioio equivalent to fragments, it controls latency*/
842
843         audio = AudioIOOpenX( O_WRONLY|O_NDELAY,&spec[PLAYBACK],&spec[PLAYBACK]);
844
845     if (audio == -1) {
846         WARN("can't open sound device %s (%s)!\n", SOUND_DEV, strerror(errno));
847         return MMSYSERR_ALLOCATED;
848     }
849  /*   fcntl(audio, F_SETFD, 1); *//* set close on exec flag */
850     wwo->unixdev = audio;
851
852
853     /* even if we set fragment size above, read it again, just in case */
854
855     wwo->dwFragmentSize = DEFAULT_FRAGMENT_SIZE;
856
857     wwo->msg_toget = 0;
858     wwo->msg_tosave = 0;
859     wwo->msg_event = CreateEventA(NULL, FALSE, FALSE, NULL);
860     memset(wwo->messages, 0, sizeof(WWO_MSG)*WWO_RING_BUFFER_SIZE);
861     InitializeCriticalSection(&wwo->msg_crst);
862
863     if (!(dwFlags & WAVE_DIRECTSOUND)) {
864         wwo->hEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
865         wwo->hThread = CreateThread(NULL, 0, wodPlayer, (LPVOID)(DWORD)wDevID, 0, &(wwo->dwThreadID));
866         WaitForSingleObject(wwo->hEvent, INFINITE);
867     } else {
868         wwo->hEvent = INVALID_HANDLE_VALUE;
869         wwo->hThread = INVALID_HANDLE_VALUE;
870         wwo->dwThreadID = 0;
871     }
872
873     TRACE("fd=%d fragmentSize=%ld\n",
874           wwo->unixdev, wwo->dwFragmentSize);
875     if (wwo->dwFragmentSize % wwo->format.wf.nBlockAlign)
876         ERR("Fragment doesn't contain an integral number of data blocks\n");
877
878     TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%lu, nSamplesPerSec=%lu, nChannels=%u nBlockAlign=%u!\n",
879           wwo->format.wBitsPerSample, wwo->format.wf.nAvgBytesPerSec,
880           wwo->format.wf.nSamplesPerSec, wwo->format.wf.nChannels,
881           wwo->format.wf.nBlockAlign);
882
883     if (LIBAUDIOIO_NotifyClient(wDevID, WOM_OPEN, 0L, 0L) != MMSYSERR_NOERROR) {
884         WARN("can't notify client !\n");
885         return MMSYSERR_INVALPARAM;
886     }
887     return MMSYSERR_NOERROR;
888 }
889
890 /**************************************************************************
891  *                              wodClose                        [internal]
892  */
893 static DWORD wodClose(WORD wDevID)
894 {
895     DWORD               ret = MMSYSERR_NOERROR;
896     WINE_WAVEOUT*       wwo;
897
898     TRACE("(%u);\n", wDevID);
899
900     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].unixdev == -1) {
901         WARN("bad device ID !\n");
902         return MMSYSERR_BADDEVICEID;
903     }
904
905     wwo = &WOutDev[wDevID];
906     if (wwo->lpQueuePtr) {
907         WARN("buffers still playing !\n");
908         ret = WAVERR_STILLPLAYING;
909     } else {
910         TRACE("imhere[3-close]\n");
911         if (wwo->hEvent != INVALID_HANDLE_VALUE) {
912             wodPlayer_Message(wwo, WINE_WM_CLOSING, 0);
913             WaitForSingleObject(wwo->hEvent, INFINITE);
914             CloseHandle(wwo->hEvent);
915         }
916         if (wwo->mapping) {
917             munmap(wwo->mapping, wwo->maplen);
918             wwo->mapping = NULL;
919         }
920
921         AudioIOClose();
922         wwo->unixdev = -1;
923         wwo->dwFragmentSize = 0;
924         if (LIBAUDIOIO_NotifyClient(wDevID, WOM_CLOSE, 0L, 0L) != MMSYSERR_NOERROR) {
925             WARN("can't notify client !\n");
926             ret = MMSYSERR_INVALPARAM;
927         }
928     }
929     return ret;
930 }
931
932 /**************************************************************************
933  *                              wodWrite                        [internal]
934  *
935  */
936 static DWORD wodWrite(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
937 {
938     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
939
940     /* first, do the sanity checks... */
941     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].unixdev == -1) {
942         WARN("bad dev ID !\n");
943         return MMSYSERR_BADDEVICEID;
944     }
945
946     if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
947         return WAVERR_UNPREPARED;
948
949     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
950         return WAVERR_STILLPLAYING;
951
952     lpWaveHdr->dwFlags &= ~WHDR_DONE;
953     lpWaveHdr->dwFlags |= WHDR_INQUEUE;
954     lpWaveHdr->lpNext = 0;
955
956     TRACE("imhere[3-HEADER]\n");
957     wodPlayer_Message(&WOutDev[wDevID], WINE_WM_HEADER, (DWORD)lpWaveHdr);
958
959     return MMSYSERR_NOERROR;
960 }
961
962 /**************************************************************************
963  *                              wodPrepare                      [internal]
964  */
965 static DWORD wodPrepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
966 {
967     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
968
969     if (wDevID >= MAX_WAVEOUTDRV) {
970         WARN("bad device ID !\n");
971         return MMSYSERR_BADDEVICEID;
972     }
973
974     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
975         return WAVERR_STILLPLAYING;
976
977     lpWaveHdr->dwFlags |= WHDR_PREPARED;
978     lpWaveHdr->dwFlags &= ~WHDR_DONE;
979     return MMSYSERR_NOERROR;
980 }
981
982 /**************************************************************************
983  *                              wodUnprepare                    [internal]
984  */
985 static DWORD wodUnprepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
986 {
987     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
988
989     if (wDevID >= MAX_WAVEOUTDRV) {
990         WARN("bad device ID !\n");
991         return MMSYSERR_BADDEVICEID;
992     }
993
994     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
995         return WAVERR_STILLPLAYING;
996
997     lpWaveHdr->dwFlags &= ~WHDR_PREPARED;
998     lpWaveHdr->dwFlags |= WHDR_DONE;
999
1000     return MMSYSERR_NOERROR;
1001 }
1002
1003 /**************************************************************************
1004  *                      wodPause                                [internal]
1005  */
1006 static DWORD wodPause(WORD wDevID)
1007 {
1008     TRACE("(%u);!\n", wDevID);
1009
1010     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].unixdev == -1) {
1011         WARN("bad device ID !\n");
1012         return MMSYSERR_BADDEVICEID;
1013     }
1014
1015     TRACE("imhere[3-PAUSING]\n");
1016     wodPlayer_Message(&WOutDev[wDevID], WINE_WM_PAUSING, 0);
1017     WaitForSingleObject(WOutDev[wDevID].hEvent, INFINITE);
1018
1019     return MMSYSERR_NOERROR;
1020 }
1021
1022 /**************************************************************************
1023  *                      wodRestart                              [internal]
1024  */
1025 static DWORD wodRestart(WORD wDevID)
1026 {
1027     TRACE("(%u);\n", wDevID);
1028
1029     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].unixdev == -1) {
1030         WARN("bad device ID !\n");
1031         return MMSYSERR_BADDEVICEID;
1032     }
1033
1034     if (WOutDev[wDevID].state == WINE_WS_PAUSED) {
1035         TRACE("imhere[3-RESTARTING]\n");
1036         wodPlayer_Message(&WOutDev[wDevID], WINE_WM_RESTARTING, 0);
1037         WaitForSingleObject(WOutDev[wDevID].hEvent, INFINITE);
1038     }
1039
1040     /* FIXME: is NotifyClient with WOM_DONE right ? (Comet Busters 1.3.3 needs this notification) */
1041     /* FIXME: Myst crashes with this ... hmm -MM
1042        if (LIBAUDIOIO_NotifyClient(wDevID, WOM_DONE, 0L, 0L) != MMSYSERR_NOERROR) {
1043        WARN("can't notify client !\n");
1044        return MMSYSERR_INVALPARAM;
1045        }
1046     */
1047
1048     return MMSYSERR_NOERROR;
1049 }
1050
1051 /**************************************************************************
1052  *                      wodReset                                [internal]
1053  */
1054 static DWORD wodReset(WORD wDevID)
1055 {
1056     TRACE("(%u);\n", wDevID);
1057
1058     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].unixdev == -1) {
1059         WARN("bad device ID !\n");
1060         return MMSYSERR_BADDEVICEID;
1061     }
1062
1063     TRACE("imhere[3-RESET]\n");
1064     wodPlayer_Message(&WOutDev[wDevID], WINE_WM_RESETTING, 0);
1065     WaitForSingleObject(WOutDev[wDevID].hEvent, INFINITE);
1066
1067     return MMSYSERR_NOERROR;
1068 }
1069
1070
1071 /**************************************************************************
1072  *                              wodGetPosition                  [internal]
1073  */
1074 static DWORD wodGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
1075 {
1076     int                 time;
1077     DWORD               val;
1078     WINE_WAVEOUT*       wwo;
1079
1080     TRACE("(%u, %p, %lu);\n", wDevID, lpTime, uSize);
1081
1082     if (wDevID >= MAX_WAVEOUTDRV || WOutDev[wDevID].unixdev == -1) {
1083         WARN("bad device ID !\n");
1084         return MMSYSERR_BADDEVICEID;
1085     }
1086
1087     if (lpTime == NULL) return MMSYSERR_INVALPARAM;
1088
1089     wwo = &WOutDev[wDevID];
1090     val = wwo->dwPlayedTotal;
1091
1092     TRACE("wType=%04X wBitsPerSample=%u nSamplesPerSec=%lu nChannels=%u nAvgBytesPerSec=%lu\n",
1093           lpTime->wType, wwo->format.wBitsPerSample,
1094           wwo->format.wf.nSamplesPerSec, wwo->format.wf.nChannels,
1095           wwo->format.wf.nAvgBytesPerSec);
1096     TRACE("dwTotalPlayed=%lu\n", val);
1097
1098     switch (lpTime->wType) {
1099     case TIME_BYTES:
1100         lpTime->u.cb = val;
1101         TRACE("TIME_BYTES=%lu\n", lpTime->u.cb);
1102         break;
1103     case TIME_SAMPLES:
1104         lpTime->u.sample = val * 8 / wwo->format.wBitsPerSample;
1105         TRACE("TIME_SAMPLES=%lu\n", lpTime->u.sample);
1106         break;
1107     case TIME_SMPTE:
1108         time = val / (wwo->format.wf.nAvgBytesPerSec / 1000);
1109         lpTime->u.smpte.hour = time / 108000;
1110         time -= lpTime->u.smpte.hour * 108000;
1111         lpTime->u.smpte.min = time / 1800;
1112         time -= lpTime->u.smpte.min * 1800;
1113         lpTime->u.smpte.sec = time / 30;
1114         time -= lpTime->u.smpte.sec * 30;
1115         lpTime->u.smpte.frame = time;
1116         lpTime->u.smpte.fps = 30;
1117         TRACE("TIME_SMPTE=%02u:%02u:%02u:%02u\n",
1118               lpTime->u.smpte.hour, lpTime->u.smpte.min,
1119               lpTime->u.smpte.sec, lpTime->u.smpte.frame);
1120         break;
1121     default:
1122         FIXME("Format %d not supported ! use TIME_MS !\n", lpTime->wType);
1123         lpTime->wType = TIME_MS;
1124     case TIME_MS:
1125         lpTime->u.ms = val / (wwo->format.wf.nAvgBytesPerSec / 1000);
1126         TRACE("TIME_MS=%lu\n", lpTime->u.ms);
1127         break;
1128     }
1129     return MMSYSERR_NOERROR;
1130 }
1131
1132 /**************************************************************************
1133  *                              wodGetVolume                    [internal]
1134  */
1135 static DWORD wodGetVolume(WORD wDevID, LPDWORD lpdwVol)
1136 {
1137     int         mixer;
1138     int         vol,bal;
1139     DWORD       left, right;
1140
1141     TRACE("(%u, %p);\n", wDevID, lpdwVol);
1142
1143     if (lpdwVol == NULL)
1144         return MMSYSERR_NOTENABLED;
1145
1146      vol=AudioIOGetPlaybackVolume();
1147      bal=AudioIOGetPlaybackBalance();
1148
1149
1150      if(bal<0) {
1151         left = vol;
1152         right=-(vol*(-100+bal)/100);
1153      }
1154       else
1155      {
1156         right = vol;
1157         left=(vol*(100-bal)/100);
1158      }
1159
1160     *lpdwVol = ((left * 0xFFFFl) / 100) + (((right * 0xFFFFl) / 100) << 16);
1161     return MMSYSERR_NOERROR;
1162 }
1163
1164
1165 /**************************************************************************
1166  *                              wodSetVolume                    [internal]
1167  */
1168 static DWORD wodSetVolume(WORD wDevID, DWORD dwParam)
1169 {
1170     int         mixer;
1171     int         volume,bal;
1172     DWORD       left, right;
1173
1174     TRACE("(%u, %08lX);\n", wDevID, dwParam);
1175
1176     left  = (LOWORD(dwParam) * 100) / 0xFFFFl;
1177     right = (HIWORD(dwParam) * 100) / 0xFFFFl;
1178     volume = max(left , right );
1179     bal=min(left,right);
1180     bal=bal*100/volume;
1181     if(right>left) bal=-100+bal; else bal=100-bal;
1182
1183     AudioIOSetPlaybackVolume(volume);
1184     AudioIOSetPlaybackBalance(bal);
1185
1186     return MMSYSERR_NOERROR;
1187 }
1188
1189 /**************************************************************************
1190  *                              wodGetNumDevs                   [internal]
1191  */
1192 static  DWORD   wodGetNumDevs(void)
1193 {
1194     DWORD       ret = 1;
1195
1196     /* FIXME: For now, only one sound device (SOUND_DEV) is allowed */
1197     int audio = open(SOUND_DEV, O_WRONLY|O_NDELAY, 0);
1198
1199     if (audio == -1) {
1200         if (errno != EBUSY)
1201             ret = 0;
1202     } else {
1203         close(audio);
1204
1205     }
1206     TRACE("NumDrivers = %d\n",ret);
1207     return ret;
1208 }
1209
1210 /**************************************************************************
1211  *                              wodMessage (WINEAUDIOIO.@)
1212  */
1213 DWORD WINAPI LIBAUDIOIO_wodMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
1214                             DWORD dwParam1, DWORD dwParam2)
1215 {
1216     TRACE("(%u, %04X, %08lX, %08lX, %08lX);\n",
1217           wDevID, wMsg, dwUser, dwParam1, dwParam2);
1218
1219     switch (wMsg) {
1220     case DRVM_INIT:
1221     case DRVM_EXIT:
1222     case DRVM_ENABLE:
1223     case DRVM_DISABLE:
1224         /* FIXME: Pretend this is supported */
1225         return 0;
1226     case WODM_OPEN:             return wodOpen          (wDevID, (LPWAVEOPENDESC)dwParam1,      dwParam2);
1227     case WODM_CLOSE:            return wodClose         (wDevID);
1228     case WODM_WRITE:            return wodWrite         (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
1229     case WODM_PAUSE:            return wodPause         (wDevID);
1230     case WODM_GETPOS:           return wodGetPosition   (wDevID, (LPMMTIME)dwParam1,            dwParam2);
1231     case WODM_BREAKLOOP:        return MMSYSERR_NOTSUPPORTED;
1232     case WODM_PREPARE:          return wodPrepare       (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
1233     case WODM_UNPREPARE:        return wodUnprepare     (wDevID, (LPWAVEHDR)dwParam1,           dwParam2);
1234     case WODM_GETDEVCAPS:       return wodGetDevCaps    (wDevID, (LPWAVEOUTCAPSA)dwParam1,      dwParam2);
1235     case WODM_GETNUMDEVS:       return wodGetNumDevs    ();
1236     case WODM_GETPITCH:         return MMSYSERR_NOTSUPPORTED;
1237     case WODM_SETPITCH:         return MMSYSERR_NOTSUPPORTED;
1238     case WODM_GETPLAYBACKRATE:  return MMSYSERR_NOTSUPPORTED;
1239     case WODM_SETPLAYBACKRATE:  return MMSYSERR_NOTSUPPORTED;
1240     case WODM_GETVOLUME:        return wodGetVolume     (wDevID, (LPDWORD)dwParam1);
1241     case WODM_SETVOLUME:        return wodSetVolume     (wDevID, dwParam1);
1242     case WODM_RESTART:          return wodRestart       (wDevID);
1243     case WODM_RESET:            return wodReset         (wDevID);
1244
1245     case DRV_QUERYDSOUNDIFACE:  return wodDsCreate(wDevID, (PIDSDRIVER*)dwParam1);
1246     default:
1247         FIXME("unknown message %d!\n", wMsg);
1248     }
1249     return MMSYSERR_NOTSUPPORTED;
1250 }
1251
1252 /*======================================================================*
1253  *                  Low level DSOUND implementation                     *
1254  *              While I have tampered somewhat with this code it is wholely unlikely that it works
1255  *              Elsewhere the driver returns Not Implemented for DIrectSound
1256  *              While it may be possible to map the sound device on Solaris
1257  *              Doing so would bypass the libaudioio library and therefore break any conversions
1258  *              that the libaudioio sample specification converter is doing
1259  *              **** All this is untested so far
1260  *======================================================================*/
1261
1262 typedef struct IDsDriverImpl IDsDriverImpl;
1263 typedef struct IDsDriverBufferImpl IDsDriverBufferImpl;
1264
1265 struct IDsDriverImpl
1266 {
1267     /* IUnknown fields */
1268     ICOM_VFIELD(IDsDriver);
1269     DWORD               ref;
1270     /* IDsDriverImpl fields */
1271     UINT                wDevID;
1272     IDsDriverBufferImpl*primary;
1273 };
1274
1275 struct IDsDriverBufferImpl
1276 {
1277     /* IUnknown fields */
1278     ICOM_VFIELD(IDsDriverBuffer);
1279     DWORD               ref;
1280     /* IDsDriverBufferImpl fields */
1281     IDsDriverImpl*      drv;
1282     DWORD               buflen;
1283 };
1284
1285 static HRESULT DSDB_MapPrimary(IDsDriverBufferImpl *dsdb)
1286 {
1287     WINE_WAVEOUT *wwo = &(WOutDev[dsdb->drv->wDevID]);
1288     if (!wwo->mapping) {
1289         wwo->mapping = mmap(NULL, wwo->maplen, PROT_WRITE, MAP_SHARED,
1290                             wwo->unixdev, 0);
1291         if (wwo->mapping == (LPBYTE)-1) {
1292             ERR("(%p): Could not map sound device for direct access (errno=%d)\n", dsdb, errno);
1293             return DSERR_GENERIC;
1294         }
1295         TRACE("(%p): sound device has been mapped for direct access at %p, size=%ld\n", dsdb, wwo->mapping, wwo->maplen);
1296
1297         /* for some reason, es1371 and sblive! sometimes have junk in here. */
1298         memset(wwo->mapping,0,wwo->maplen); /* clear it, or we get junk noise */
1299     }
1300     return DS_OK;
1301 }
1302
1303 static HRESULT DSDB_UnmapPrimary(IDsDriverBufferImpl *dsdb)
1304 {
1305     WINE_WAVEOUT *wwo = &(WOutDev[dsdb->drv->wDevID]);
1306     if (wwo->mapping) {
1307         if (munmap(wwo->mapping, wwo->maplen) < 0) {
1308             ERR("(%p): Could not unmap sound device (errno=%d)\n", dsdb, errno);
1309             return DSERR_GENERIC;
1310         }
1311         wwo->mapping = NULL;
1312         TRACE("(%p): sound device unmapped\n", dsdb);
1313     }
1314     return DS_OK;
1315 }
1316
1317 static HRESULT WINAPI IDsDriverBufferImpl_QueryInterface(PIDSDRIVERBUFFER iface, REFIID riid, LPVOID *ppobj)
1318 {
1319     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
1320     FIXME("(): stub!\n");
1321     return DSERR_UNSUPPORTED;
1322 }
1323
1324 static ULONG WINAPI IDsDriverBufferImpl_AddRef(PIDSDRIVERBUFFER iface)
1325 {
1326     ICOM_THIS(IDsDriverBufferImpl,iface);
1327     This->ref++;
1328     return This->ref;
1329 }
1330
1331 static ULONG WINAPI IDsDriverBufferImpl_Release(PIDSDRIVERBUFFER iface)
1332 {
1333     ICOM_THIS(IDsDriverBufferImpl,iface);
1334     if (--This->ref)
1335         return This->ref;
1336     if (This == This->drv->primary)
1337         This->drv->primary = NULL;
1338     DSDB_UnmapPrimary(This);
1339     HeapFree(GetProcessHeap(),0,This);
1340     return 0;
1341 }
1342
1343 static HRESULT WINAPI IDsDriverBufferImpl_Lock(PIDSDRIVERBUFFER iface,
1344                                                LPVOID*ppvAudio1,LPDWORD pdwLen1,
1345                                                LPVOID*ppvAudio2,LPDWORD pdwLen2,
1346                                                DWORD dwWritePosition,DWORD dwWriteLen,
1347                                                DWORD dwFlags)
1348 {
1349     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
1350     /* since we (GetDriverDesc flags) have specified DSDDESC_DONTNEEDPRIMARYLOCK,
1351      * and that we don't support secondary buffers, this method will never be called */
1352     TRACE("(%p): stub\n",iface);
1353     return DSERR_UNSUPPORTED;
1354 }
1355
1356 static HRESULT WINAPI IDsDriverBufferImpl_Unlock(PIDSDRIVERBUFFER iface,
1357                                                  LPVOID pvAudio1,DWORD dwLen1,
1358                                                  LPVOID pvAudio2,DWORD dwLen2)
1359 {
1360     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
1361     TRACE("(%p): stub\n",iface);
1362     return DSERR_UNSUPPORTED;
1363 }
1364
1365 static HRESULT WINAPI IDsDriverBufferImpl_SetFormat(PIDSDRIVERBUFFER iface,
1366                                                     LPWAVEFORMATEX pwfx)
1367 {
1368     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
1369
1370     TRACE("(%p,%p)\n",iface,pwfx);
1371     /* On our request (GetDriverDesc flags), DirectSound has by now used
1372      * waveOutClose/waveOutOpen to set the format...
1373      * unfortunately, this means our mmap() is now gone...
1374      * so we need to somehow signal to our DirectSound implementation
1375      * that it should completely recreate this HW buffer...
1376      * this unexpected error code should do the trick... */
1377     return DSERR_BUFFERLOST;
1378 }
1379
1380 static HRESULT WINAPI IDsDriverBufferImpl_SetFrequency(PIDSDRIVERBUFFER iface, DWORD dwFreq)
1381 {
1382     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
1383     TRACE("(%p,%ld): stub\n",iface,dwFreq);
1384     return DSERR_UNSUPPORTED;
1385 }
1386
1387 static HRESULT WINAPI IDsDriverBufferImpl_SetVolumePan(PIDSDRIVERBUFFER iface, PDSVOLUMEPAN pVolPan)
1388 {
1389     /* ICOM_THIS(IDsDriverBufferImpl,iface); */
1390     FIXME("(%p,%p): stub!\n",iface,pVolPan);
1391     return DSERR_UNSUPPORTED;
1392 }
1393
1394 static HRESULT WINAPI IDsDriverBufferImpl_SetPosition(PIDSDRIVERBUFFER iface, DWORD dwNewPos)
1395 {
1396     /* ICOM_THIS(IDsDriverImpl,iface); */
1397     TRACE("(%p,%ld): stub\n",iface,dwNewPos);
1398     return DSERR_UNSUPPORTED;
1399 }
1400
1401 static HRESULT WINAPI IDsDriverBufferImpl_GetPosition(PIDSDRIVERBUFFER iface,
1402                                                       LPDWORD lpdwPlay, LPDWORD lpdwWrite)
1403 {
1404     ICOM_THIS(IDsDriverBufferImpl,iface);
1405 #if 0
1406     count_info info;
1407 #endif
1408     DWORD ptr;
1409
1410     TRACE("(%p)\n",iface);
1411     if (WOutDev[This->drv->wDevID].unixdev == -1) {
1412         ERR("device not open, but accessing?\n");
1413         return DSERR_UNINITIALIZED;
1414     }
1415     /*Libaudioio doesn't support this (Yet anyway)*/
1416      return DSERR_UNSUPPORTED;
1417
1418 }
1419
1420 static HRESULT WINAPI IDsDriverBufferImpl_Play(PIDSDRIVERBUFFER iface, DWORD dwRes1, DWORD dwRes2, DWORD dwFlags)
1421 {
1422     ICOM_THIS(IDsDriverBufferImpl,iface);
1423 #if 0
1424     int enable = PCM_ENABLE_OUTPUT;
1425     TRACE("(%p,%lx,%lx,%lx)\n",iface,dwRes1,dwRes2,dwFlags);
1426     if (ioctl(WOutDev[This->drv->wDevID].unixdev, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
1427         ERR("ioctl failed (%d)\n", errno);
1428         return DSERR_GENERIC;
1429     }
1430 #endif
1431     return DS_OK;
1432 }
1433
1434 static HRESULT WINAPI IDsDriverBufferImpl_Stop(PIDSDRIVERBUFFER iface)
1435 {
1436     ICOM_THIS(IDsDriverBufferImpl,iface);
1437     int enable = 0;
1438 #if 0
1439     TRACE("(%p)\n",iface);
1440     /* no more playing */
1441     if (ioctl(WOutDev[This->drv->wDevID].unixdev, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
1442         ERR("ioctl failed (%d)\n", errno);
1443         return DSERR_GENERIC;
1444     }
1445 #endif
1446 #if 0
1447     /* the play position must be reset to the beginning of the buffer */
1448     if (ioctl(WOutDev[This->drv->wDevID].unixdev, SNDCTL_DSP_RESET, 0) < 0) {
1449         ERR("ioctl failed (%d)\n", errno);
1450         return DSERR_GENERIC;
1451     }
1452 #endif
1453     /* Most OSS drivers just can't stop the playback without closing the device...
1454      * so we need to somehow signal to our DirectSound implementation
1455      * that it should completely recreate this HW buffer...
1456      * this unexpected error code should do the trick... */
1457     return DSERR_BUFFERLOST;
1458 }
1459
1460 static ICOM_VTABLE(IDsDriverBuffer) dsdbvt =
1461 {
1462     ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
1463     IDsDriverBufferImpl_QueryInterface,
1464     IDsDriverBufferImpl_AddRef,
1465     IDsDriverBufferImpl_Release,
1466     IDsDriverBufferImpl_Lock,
1467     IDsDriverBufferImpl_Unlock,
1468     IDsDriverBufferImpl_SetFormat,
1469     IDsDriverBufferImpl_SetFrequency,
1470     IDsDriverBufferImpl_SetVolumePan,
1471     IDsDriverBufferImpl_SetPosition,
1472     IDsDriverBufferImpl_GetPosition,
1473     IDsDriverBufferImpl_Play,
1474     IDsDriverBufferImpl_Stop
1475 };
1476
1477 static HRESULT WINAPI IDsDriverImpl_QueryInterface(PIDSDRIVER iface, REFIID riid, LPVOID *ppobj)
1478 {
1479     /* ICOM_THIS(IDsDriverImpl,iface); */
1480     FIXME("(%p): stub!\n",iface);
1481     return DSERR_UNSUPPORTED;
1482 }
1483
1484 static ULONG WINAPI IDsDriverImpl_AddRef(PIDSDRIVER iface)
1485 {
1486     ICOM_THIS(IDsDriverImpl,iface);
1487     This->ref++;
1488     return This->ref;
1489 }
1490
1491 static ULONG WINAPI IDsDriverImpl_Release(PIDSDRIVER iface)
1492 {
1493     ICOM_THIS(IDsDriverImpl,iface);
1494     if (--This->ref)
1495         return This->ref;
1496     HeapFree(GetProcessHeap(),0,This);
1497     return 0;
1498 }
1499
1500 static HRESULT WINAPI IDsDriverImpl_GetDriverDesc(PIDSDRIVER iface, PDSDRIVERDESC pDesc)
1501 {
1502     ICOM_THIS(IDsDriverImpl,iface);
1503     TRACE("(%p,%p)\n",iface,pDesc);
1504     pDesc->dwFlags = DSDDESC_DOMMSYSTEMOPEN | DSDDESC_DOMMSYSTEMSETFORMAT |
1505         DSDDESC_USESYSTEMMEMORY | DSDDESC_DONTNEEDPRIMARYLOCK;
1506     strcpy(pDesc->szDesc,"WineOSS DirectSound Driver");
1507     strcpy(pDesc->szDrvName,"wineoss.drv");
1508     pDesc->dnDevNode            = WOutDev[This->wDevID].waveDesc.dnDevNode;
1509     pDesc->wVxdId               = 0;
1510     pDesc->wReserved            = 0;
1511     pDesc->ulDeviceNum          = This->wDevID;
1512     pDesc->dwHeapType           = DSDHEAP_NOHEAP;
1513     pDesc->pvDirectDrawHeap     = NULL;
1514     pDesc->dwMemStartAddress    = 0;
1515     pDesc->dwMemEndAddress      = 0;
1516     pDesc->dwMemAllocExtra      = 0;
1517     pDesc->pvReserved1          = NULL;
1518     pDesc->pvReserved2          = NULL;
1519     return DS_OK;
1520 }
1521
1522 static HRESULT WINAPI IDsDriverImpl_Open(PIDSDRIVER iface)
1523 {
1524     ICOM_THIS(IDsDriverImpl,iface);
1525     int enable = 0;
1526
1527     TRACE("(%p)\n",iface);
1528     /* make sure the card doesn't start playing before we want it to */
1529 #if 0
1530     if (ioctl(WOutDev[This->wDevID].unixdev, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
1531         ERR("ioctl failed (%d)\n", errno);
1532         return DSERR_GENERIC;
1533     }
1534 #endif
1535     return DS_OK;
1536 }
1537
1538 static HRESULT WINAPI IDsDriverImpl_Close(PIDSDRIVER iface)
1539 {
1540     ICOM_THIS(IDsDriverImpl,iface);
1541     TRACE("(%p)\n",iface);
1542     if (This->primary) {
1543         ERR("problem with DirectSound: primary not released\n");
1544         return DSERR_GENERIC;
1545     }
1546     return DS_OK;
1547 }
1548
1549 static HRESULT WINAPI IDsDriverImpl_GetCaps(PIDSDRIVER iface, PDSDRIVERCAPS pCaps)
1550 {
1551     /* ICOM_THIS(IDsDriverImpl,iface); */
1552     TRACE("(%p,%p)\n",iface,pCaps);
1553     memset(pCaps, 0, sizeof(*pCaps));
1554     /* FIXME: need to check actual capabilities */
1555     pCaps->dwFlags = DSCAPS_PRIMARYMONO | DSCAPS_PRIMARYSTEREO |
1556         DSCAPS_PRIMARY8BIT | DSCAPS_PRIMARY16BIT;
1557     pCaps->dwPrimaryBuffers = 1;
1558     /* the other fields only apply to secondary buffers, which we don't support
1559      * (unless we want to mess with wavetable synthesizers and MIDI) */
1560     return DS_OK;
1561 }
1562
1563 static HRESULT WINAPI IDsDriverImpl_CreateSoundBuffer(PIDSDRIVER iface,
1564                                                       LPWAVEFORMATEX pwfx,
1565                                                       DWORD dwFlags, DWORD dwCardAddress,
1566                                                       LPDWORD pdwcbBufferSize,
1567                                                       LPBYTE *ppbBuffer,
1568                                                       LPVOID *ppvObj)
1569 {
1570     ICOM_THIS(IDsDriverImpl,iface);
1571     IDsDriverBufferImpl** ippdsdb = (IDsDriverBufferImpl**)ppvObj;
1572     HRESULT err;
1573 #if 0
1574     audio_buf_info info;
1575 #endif
1576     int enable = 0;
1577
1578     TRACE("(%p,%p,%lx,%lx)\n",iface,pwfx,dwFlags,dwCardAddress);
1579     /* we only support primary buffers */
1580     if (!(dwFlags & DSBCAPS_PRIMARYBUFFER))
1581         return DSERR_UNSUPPORTED;
1582     if (This->primary)
1583         return DSERR_ALLOCATED;
1584     if (dwFlags & (DSBCAPS_CTRLFREQUENCY | DSBCAPS_CTRLPAN))
1585         return DSERR_CONTROLUNAVAIL;
1586
1587     *ippdsdb = (IDsDriverBufferImpl*)HeapAlloc(GetProcessHeap(),0,sizeof(IDsDriverBufferImpl));
1588     if (*ippdsdb == NULL)
1589         return DSERR_OUTOFMEMORY;
1590     ICOM_VTBL(*ippdsdb) = &dsdbvt;
1591     (*ippdsdb)->ref     = 1;
1592     (*ippdsdb)->drv     = This;
1593
1594     /* check how big the DMA buffer is now */
1595 #if 0
1596     if (ioctl(WOutDev[This->wDevID].unixdev, SNDCTL_DSP_GETOSPACE, &info) < 0) {
1597         ERR("ioctl failed (%d)\n", errno);
1598         HeapFree(GetProcessHeap(),0,*ippdsdb);
1599         *ippdsdb = NULL;
1600         return DSERR_GENERIC;
1601     }
1602 #endif
1603     WOutDev[This->wDevID].maplen =64*1024; /* Map 64 K at a time */
1604
1605 #if 0
1606     (*ippdsdb)->buflen = info.fragstotal * info.fragsize;
1607 #endif
1608     /* map the DMA buffer */
1609     err = DSDB_MapPrimary(*ippdsdb);
1610     if (err != DS_OK) {
1611         HeapFree(GetProcessHeap(),0,*ippdsdb);
1612         *ippdsdb = NULL;
1613         return err;
1614     }
1615
1616     /* primary buffer is ready to go */
1617     *pdwcbBufferSize    = WOutDev[This->wDevID].maplen;
1618     *ppbBuffer          = WOutDev[This->wDevID].mapping;
1619
1620     /* some drivers need some extra nudging after mapping */
1621 #if 0
1622     if (ioctl(WOutDev[This->wDevID].unixdev, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
1623         ERR("ioctl failed (%d)\n", errno);
1624         return DSERR_GENERIC;
1625     }
1626 #endif
1627
1628     This->primary = *ippdsdb;
1629
1630     return DS_OK;
1631 }
1632
1633 static HRESULT WINAPI IDsDriverImpl_DuplicateSoundBuffer(PIDSDRIVER iface,
1634                                                          PIDSDRIVERBUFFER pBuffer,
1635                                                          LPVOID *ppvObj)
1636 {
1637     /* ICOM_THIS(IDsDriverImpl,iface); */
1638     TRACE("(%p,%p): stub\n",iface,pBuffer);
1639     return DSERR_INVALIDCALL;
1640 }
1641
1642 static ICOM_VTABLE(IDsDriver) dsdvt =
1643 {
1644     ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
1645     IDsDriverImpl_QueryInterface,
1646     IDsDriverImpl_AddRef,
1647     IDsDriverImpl_Release,
1648     IDsDriverImpl_GetDriverDesc,
1649     IDsDriverImpl_Open,
1650     IDsDriverImpl_Close,
1651     IDsDriverImpl_GetCaps,
1652     IDsDriverImpl_CreateSoundBuffer,
1653     IDsDriverImpl_DuplicateSoundBuffer
1654 };
1655
1656 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
1657 {
1658     IDsDriverImpl** idrv = (IDsDriverImpl**)drv;
1659
1660     /* the HAL isn't much better than the HEL if we can't do mmap() */
1661     if (!(WOutDev[wDevID].caps.dwSupport & WAVECAPS_DIRECTSOUND)) {
1662         ERR("DirectSound flag not set\n");
1663         MESSAGE("This sound card's driver does not support direct access\n");
1664         MESSAGE("The (slower) DirectSound HEL mode will be used instead.\n");
1665         return MMSYSERR_NOTSUPPORTED;
1666     }
1667
1668     *idrv = (IDsDriverImpl*)HeapAlloc(GetProcessHeap(),0,sizeof(IDsDriverImpl));
1669     if (!*idrv)
1670         return MMSYSERR_NOMEM;
1671     ICOM_VTBL(*idrv)    = &dsdvt;
1672     (*idrv)->ref        = 1;
1673
1674     (*idrv)->wDevID     = wDevID;
1675     (*idrv)->primary    = NULL;
1676     return MMSYSERR_NOERROR;
1677 }
1678
1679 /*======================================================================*
1680  *                  Low level WAVE IN implementation                    *
1681  *======================================================================*/
1682
1683 /**************************************************************************
1684  *                      widGetDevCaps                           [internal]
1685  */
1686 static DWORD widGetDevCaps(WORD wDevID, LPWAVEINCAPSA lpCaps, DWORD dwSize)
1687 {
1688     TRACE("(%u, %p, %lu);\n", wDevID, lpCaps, dwSize);
1689
1690     if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
1691
1692     if (wDevID >= MAX_WAVEINDRV) {
1693         TRACE("MAX_WAVINDRV reached !\n");
1694         return MMSYSERR_BADDEVICEID;
1695     }
1696
1697     memcpy(lpCaps, &WInDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
1698     return MMSYSERR_NOERROR;
1699 }
1700
1701 /**************************************************************************
1702  *                              widRecorder                     [internal]
1703  */
1704 static  DWORD   CALLBACK        widRecorder(LPVOID pmt)
1705 {
1706     WORD                uDevID = (DWORD)pmt;
1707     WINE_WAVEIN*        wwi = (WINE_WAVEIN*)&WInDev[uDevID];
1708     WAVEHDR*            lpWaveHdr;
1709     DWORD               dwSleepTime;
1710     MSG                 msg;
1711     DWORD               bytesRead;
1712
1713
1714         int fragments;
1715         int fragsize;
1716         int fragstotal;
1717         int bytes;
1718
1719
1720     int xs;
1721
1722         LPVOID          buffer = HeapAlloc(GetProcessHeap(),
1723                                            HEAP_ZERO_MEMORY,
1724                                        wwi->dwFragmentSize);
1725
1726     LPVOID              pOffset = buffer;
1727
1728     PeekMessageA(&msg, 0, 0, 0, 0);
1729     wwi->state = WINE_WS_STOPPED;
1730     wwi->dwTotalRecorded = 0;
1731
1732     SetEvent(wwi->hEvent);
1733
1734
1735         /* make sleep time to be # of ms to output a fragment */
1736     dwSleepTime = (wwi->dwFragmentSize * 1000) / wwi->format.wf.nAvgBytesPerSec;
1737     TRACE("sleeptime=%ld ms\n", dwSleepTime);
1738
1739     for (; ; ) {
1740         /* wait for dwSleepTime or an event in thread's queue */
1741         /* FIXME: could improve wait time depending on queue state,
1742          * ie, number of queued fragments
1743          */
1744
1745         if (wwi->lpQueuePtr != NULL && wwi->state == WINE_WS_PLAYING)
1746         {
1747             lpWaveHdr = wwi->lpQueuePtr;
1748
1749             bytes=fragsize=AudioIORecordingAvailable();
1750        fragments=fragstotal=1;
1751
1752             TRACE("info={frag=%d fsize=%d ftotal=%d bytes=%d}\n", fragments, fragsize, fragstotal, bytes);
1753
1754
1755             /* read all the fragments accumulated so far */
1756             while ((fragments > 0) && (wwi->lpQueuePtr))
1757             {
1758                 fragments --;
1759
1760                 if (lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded >= wwi->dwFragmentSize)
1761                 {
1762                     /* directly read fragment in wavehdr */
1763                     bytesRead = AudioIORead(
1764                                      lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded,
1765                                      wwi->dwFragmentSize);
1766
1767                     TRACE("bytesRead=%ld (direct)\n", bytesRead);
1768                     if (bytesRead != (DWORD) -1)
1769                     {
1770                         /* update number of bytes recorded in current buffer and by this device */
1771                         lpWaveHdr->dwBytesRecorded += bytesRead;
1772                         wwi->dwTotalRecorded       += bytesRead;
1773
1774                         /* buffer is full. notify client */
1775                         if (lpWaveHdr->dwBytesRecorded == lpWaveHdr->dwBufferLength)
1776                         {
1777                             /* must copy the value of next waveHdr, because we have no idea of what
1778                              * will be done with the content of lpWaveHdr in callback
1779                              */
1780                             LPWAVEHDR   lpNext = lpWaveHdr->lpNext;
1781
1782                             lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1783                             lpWaveHdr->dwFlags |=  WHDR_DONE;
1784
1785                             if (LIBAUDIOIO_NotifyClient(uDevID, WIM_DATA,
1786                                                  (DWORD)lpWaveHdr, 0) != MMSYSERR_NOERROR)
1787                             {
1788                                 WARN("can't notify client !\n");
1789                             }
1790                             lpWaveHdr = wwi->lpQueuePtr = lpNext;
1791                         }
1792                     }
1793                 }
1794                 else
1795                 {
1796                     /* read the fragment in a local buffer */
1797                     bytesRead = AudioIORead( buffer, wwi->dwFragmentSize);
1798                     pOffset = buffer;
1799
1800                     TRACE("bytesRead=%ld (local)\n", bytesRead);
1801
1802                     /* copy data in client buffers */
1803                     while (bytesRead != (DWORD) -1 && bytesRead > 0)
1804                     {
1805                         DWORD dwToCopy = min (bytesRead, lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded);
1806
1807                         memcpy(lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded,
1808                                pOffset,
1809                                dwToCopy);
1810
1811                         /* update number of bytes recorded in current buffer and by this device */
1812                         lpWaveHdr->dwBytesRecorded += dwToCopy;
1813                         wwi->dwTotalRecorded += dwToCopy;
1814                         bytesRead -= dwToCopy;
1815                         pOffset   += dwToCopy;
1816
1817                         /* client buffer is full. notify client */
1818                         if (lpWaveHdr->dwBytesRecorded == lpWaveHdr->dwBufferLength)
1819                         {
1820                             /* must copy the value of next waveHdr, because we have no idea of what
1821                              * will be done with the content of lpWaveHdr in callback
1822                              */
1823                             LPWAVEHDR   lpNext = lpWaveHdr->lpNext;
1824                             TRACE("lpNext=%p\n", lpNext);
1825
1826                             lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1827                             lpWaveHdr->dwFlags |=  WHDR_DONE;
1828
1829                             if (LIBAUDIOIO_NotifyClient(uDevID, WIM_DATA,
1830                                                  (DWORD)lpWaveHdr, 0) != MMSYSERR_NOERROR)
1831                             {
1832                                 WARN("can't notify client !\n");
1833                             }
1834
1835                             wwi->lpQueuePtr = lpWaveHdr = lpNext;
1836                             if (!lpNext && bytesRead) {
1837                                 /* no more buffer to copy data to, but we did read more.
1838                                  * what hasn't been copied will be dropped
1839                                  */
1840                                 WARN("buffer under run! %lu bytes dropped.\n", bytesRead);
1841                                 wwi->lpQueuePtr = NULL;
1842                                 break;
1843                             }
1844                         }
1845                     }
1846                 }
1847             }
1848         }
1849
1850         MsgWaitForMultipleObjects(0, NULL, FALSE, dwSleepTime, QS_POSTMESSAGE);
1851
1852         while (PeekMessageA(&msg, 0, WINE_WM_FIRST, WINE_WM_LAST, PM_REMOVE)) {
1853
1854             TRACE("msg=0x%x wParam=0x%x lParam=0x%lx\n", msg.message, msg.wParam, msg.lParam);
1855             switch (msg.message) {
1856             case WINE_WM_PAUSING:
1857                 wwi->state = WINE_WS_PAUSED;
1858
1859                 AudioIORecordingPause();
1860                 SetEvent(wwi->hEvent);
1861                 break;
1862             case WINE_WM_RESTARTING:
1863             {
1864
1865                 wwi->state = WINE_WS_PLAYING;
1866
1867                 if (wwi->bTriggerSupport)
1868                 {
1869                     /* start the recording */
1870                     AudioIORecordingResume();
1871                 }
1872                 else
1873                 {
1874                     unsigned char data[4];
1875                     /* read 4 bytes to start the recording */
1876                     AudioIORead( data, 4);
1877                 }
1878
1879                 SetEvent(wwi->hEvent);
1880                 break;
1881             }
1882             case WINE_WM_HEADER:
1883                 lpWaveHdr = (LPWAVEHDR)msg.lParam;
1884                 lpWaveHdr->lpNext = 0;
1885
1886                 /* insert buffer at the end of queue */
1887                 {
1888                     LPWAVEHDR*  wh;
1889                     for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
1890                     *wh = lpWaveHdr;
1891                 }
1892                 break;
1893             case WINE_WM_RESETTING:
1894                 wwi->state = WINE_WS_STOPPED;
1895                 /* return all buffers to the app */
1896                 for (lpWaveHdr = wwi->lpQueuePtr; lpWaveHdr; lpWaveHdr = lpWaveHdr->lpNext) {
1897                     TRACE("reset %p %p\n", lpWaveHdr, lpWaveHdr->lpNext);
1898                     lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1899                     lpWaveHdr->dwFlags |= WHDR_DONE;
1900
1901                     if (LIBAUDIOIO_NotifyClient(uDevID, WIM_DATA,
1902                                          (DWORD)lpWaveHdr, 0) != MMSYSERR_NOERROR) {
1903                         WARN("can't notify client !\n");
1904                     }
1905                 }
1906                 wwi->lpQueuePtr = NULL;
1907                 SetEvent(wwi->hEvent);
1908                 break;
1909             case WINE_WM_CLOSING:
1910                 wwi->hThread = 0;
1911                 wwi->state = WINE_WS_CLOSED;
1912                 SetEvent(wwi->hEvent);
1913                 HeapFree(GetProcessHeap(), 0, buffer);
1914                 ExitThread(0);
1915                 /* shouldn't go here */
1916             default:
1917                 FIXME("unknown message %d\n", msg.message);
1918                 break;
1919             }
1920         }
1921   }
1922     ExitThread(0);
1923     /* just for not generating compilation warnings... should never be executed */
1924     return 0;
1925 }
1926
1927
1928 /**************************************************************************
1929  *                              widOpen                         [internal]
1930  */
1931 static DWORD widOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
1932 {
1933     int                 audio;
1934     int                 fragment_size;
1935     int                 sample_rate;
1936     int                 format;
1937     int                 dsp_stereo;
1938     WINE_WAVEIN*        wwi;
1939     int                 audio_fragment;
1940
1941     TRACE("(%u, %p, %08lX);\n", wDevID, lpDesc, dwFlags);
1942     if (lpDesc == NULL) {
1943         WARN("Invalid Parameter !\n");
1944         return MMSYSERR_INVALPARAM;
1945     }
1946     if (wDevID >= MAX_WAVEINDRV) return MMSYSERR_BADDEVICEID;
1947
1948     /* only PCM format is supported so far... */
1949     if (lpDesc->lpFormat->wFormatTag != WAVE_FORMAT_PCM ||
1950         lpDesc->lpFormat->nChannels == 0 ||
1951         lpDesc->lpFormat->nSamplesPerSec == 0) {
1952         WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
1953              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1954              lpDesc->lpFormat->nSamplesPerSec);
1955         return WAVERR_BADFORMAT;
1956     }
1957
1958     if (dwFlags & WAVE_FORMAT_QUERY) {
1959         TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%ld !\n",
1960              lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1961              lpDesc->lpFormat->nSamplesPerSec);
1962         return MMSYSERR_NOERROR;
1963     }
1964
1965     if (access(SOUND_DEV,0) != 0) return MMSYSERR_NOTENABLED;
1966     audio = AudioIOOpenX( O_RDONLY|O_NDELAY, &spec[RECORD],&spec[RECORD]);
1967     if (audio == -1) {
1968         WARN("can't open sound device %s (%s)!\n", SOUND_DEV, strerror(errno));
1969         return MMSYSERR_ALLOCATED;
1970     }
1971     fcntl(audio, F_SETFD, 1); /* set close on exec flag */
1972
1973     wwi = &WInDev[wDevID];
1974     if (wwi->lpQueuePtr) {
1975         WARN("Should have an empty queue (%p)\n", wwi->lpQueuePtr);
1976         wwi->lpQueuePtr = NULL;
1977     }
1978     wwi->unixdev = audio;
1979     wwi->dwTotalRecorded = 0;
1980     wwi->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
1981
1982     memcpy(&wwi->waveDesc, lpDesc,           sizeof(WAVEOPENDESC));
1983     memcpy(&wwi->format,   lpDesc->lpFormat, sizeof(PCMWAVEFORMAT));
1984
1985     if (wwi->format.wBitsPerSample == 0) {
1986         WARN("Resetting zeroed wBitsPerSample\n");
1987         wwi->format.wBitsPerSample = 8 *
1988             (wwi->format.wf.nAvgBytesPerSec /
1989              wwi->format.wf.nSamplesPerSec) /
1990             wwi->format.wf.nChannels;
1991     }
1992
1993     spec[RECORD].rate=sample_rate = wwi->format.wf.nSamplesPerSec;
1994     dsp_stereo = ((spec[RECORD].channels=wwi->format.wf.nChannels) > 1) ? TRUE : FALSE;
1995     spec[RECORD].precision= wwi->format.wBitsPerSample;
1996     spec[RECORD].type=(spec[RECORD].precision==16)?TYPE_SIGNED:TYPE_UNSIGNED;
1997
1998     /* This is actually hand tuned to work so that my SB Live:
1999      * - does not skip
2000      * - does not buffer too much
2001      * when sending with the Shoutcast winamp plugin
2002      */
2003     /* 7 fragments max, 2^10 = 1024 bytes per fragment */
2004     audio_fragment = 0x0007000A;
2005     fragment_size=4096;
2006     if (fragment_size == -1) {
2007         AudioIOClose();
2008         wwi->unixdev = -1;
2009         return MMSYSERR_NOTENABLED;
2010     }
2011     wwi->dwFragmentSize = fragment_size;
2012
2013     TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%lu, nSamplesPerSec=%lu, nChannels=%u nBlockAlign=%u!\n",
2014           wwi->format.wBitsPerSample, wwi->format.wf.nAvgBytesPerSec,
2015           wwi->format.wf.nSamplesPerSec, wwi->format.wf.nChannels,
2016           wwi->format.wf.nBlockAlign);
2017
2018     wwi->hEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
2019     wwi->hThread = CreateThread(NULL, 0, widRecorder, (LPVOID)(DWORD)wDevID, 0, &(wwi->dwThreadID));
2020     WaitForSingleObject(wwi->hEvent, INFINITE);
2021
2022    if (LIBAUDIOIO_NotifyClient(wDevID, WIM_OPEN, 0L, 0L) != MMSYSERR_NOERROR) {
2023         WARN("can't notify client !\n");
2024         return MMSYSERR_INVALPARAM;
2025     }
2026     return MMSYSERR_NOERROR;
2027 }
2028
2029 /**************************************************************************
2030  *                              widClose                        [internal]
2031  */
2032 static DWORD widClose(WORD wDevID)
2033 {
2034     WINE_WAVEIN*        wwi;
2035
2036     TRACE("(%u);\n", wDevID);
2037     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].unixdev == -1) {
2038         WARN("can't close !\n");
2039         return MMSYSERR_INVALHANDLE;
2040     }
2041
2042     wwi = &WInDev[wDevID];
2043
2044     if (wwi->lpQueuePtr != NULL) {
2045         WARN("still buffers open !\n");
2046         return WAVERR_STILLPLAYING;
2047     }
2048
2049     PostThreadMessageA(wwi->dwThreadID, WINE_WM_CLOSING, 0, 0);
2050     WaitForSingleObject(wwi->hEvent, INFINITE);
2051     CloseHandle(wwi->hEvent);
2052     AudioIOClose();
2053     wwi->unixdev = -1;
2054     wwi->dwFragmentSize = 0;
2055     if (LIBAUDIOIO_NotifyClient(wDevID, WIM_CLOSE, 0L, 0L) != MMSYSERR_NOERROR) {
2056         WARN("can't notify client !\n");
2057         return MMSYSERR_INVALPARAM;
2058     }
2059     return MMSYSERR_NOERROR;
2060 }
2061
2062 /**************************************************************************
2063  *                              widAddBuffer            [internal]
2064  */
2065 static DWORD widAddBuffer(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
2066 {
2067     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
2068
2069     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].unixdev == -1) {
2070         WARN("can't do it !\n");
2071         return MMSYSERR_INVALHANDLE;
2072     }
2073     if (!(lpWaveHdr->dwFlags & WHDR_PREPARED)) {
2074         TRACE("never been prepared !\n");
2075         return WAVERR_UNPREPARED;
2076     }
2077     if (lpWaveHdr->dwFlags & WHDR_INQUEUE) {
2078         TRACE("header already in use !\n");
2079         return WAVERR_STILLPLAYING;
2080     }
2081
2082     lpWaveHdr->dwFlags |= WHDR_INQUEUE;
2083     lpWaveHdr->dwFlags &= ~WHDR_DONE;
2084     lpWaveHdr->dwBytesRecorded = 0;
2085         lpWaveHdr->lpNext = NULL;
2086
2087     PostThreadMessageA(WInDev[wDevID].dwThreadID, WINE_WM_HEADER, 0, (DWORD)lpWaveHdr);
2088     return MMSYSERR_NOERROR;
2089 }
2090
2091 /**************************************************************************
2092  *                              widPrepare                      [internal]
2093  */
2094 static DWORD widPrepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
2095 {
2096     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
2097
2098     if (wDevID >= MAX_WAVEINDRV) return MMSYSERR_INVALHANDLE;
2099
2100     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
2101         return WAVERR_STILLPLAYING;
2102
2103     lpWaveHdr->dwFlags |= WHDR_PREPARED;
2104     lpWaveHdr->dwFlags &= ~(WHDR_INQUEUE|WHDR_DONE);
2105     lpWaveHdr->dwBytesRecorded = 0;
2106     TRACE("header prepared !\n");
2107     return MMSYSERR_NOERROR;
2108 }
2109
2110 /**************************************************************************
2111  *                              widUnprepare                    [internal]
2112  */
2113 static DWORD widUnprepare(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
2114 {
2115     TRACE("(%u, %p, %08lX);\n", wDevID, lpWaveHdr, dwSize);
2116     if (wDevID >= MAX_WAVEINDRV) return MMSYSERR_INVALHANDLE;
2117
2118     if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
2119         return WAVERR_STILLPLAYING;
2120
2121     lpWaveHdr->dwFlags &= ~(WHDR_PREPARED|WHDR_INQUEUE);
2122     lpWaveHdr->dwFlags |= WHDR_DONE;
2123
2124     return MMSYSERR_NOERROR;
2125 }
2126
2127 /**************************************************************************
2128  *                      widStart                                [internal]
2129  */
2130 static DWORD widStart(WORD wDevID)
2131 {
2132     TRACE("(%u);\n", wDevID);
2133     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].unixdev == -1) {
2134         WARN("can't start recording !\n");
2135         return MMSYSERR_INVALHANDLE;
2136     }
2137
2138     PostThreadMessageA(WInDev[wDevID].dwThreadID, WINE_WM_RESTARTING, 0, 0);
2139     WaitForSingleObject(WInDev[wDevID].hEvent, INFINITE);
2140     return MMSYSERR_NOERROR;
2141 }
2142
2143 /**************************************************************************
2144  *                      widStop                                 [internal]
2145  */
2146 static DWORD widStop(WORD wDevID)
2147 {
2148     TRACE("(%u);\n", wDevID);
2149     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].unixdev == -1) {
2150         WARN("can't stop !\n");
2151         return MMSYSERR_INVALHANDLE;
2152     }
2153     /* FIXME: reset aint stop */
2154     PostThreadMessageA(WInDev[wDevID].dwThreadID, WINE_WM_RESETTING, 0, 0);
2155     WaitForSingleObject(WInDev[wDevID].hEvent, INFINITE);
2156
2157     return MMSYSERR_NOERROR;
2158 }
2159
2160 /**************************************************************************
2161  *                      widReset                                [internal]
2162  */
2163 static DWORD widReset(WORD wDevID)
2164 {
2165     TRACE("(%u);\n", wDevID);
2166     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].unixdev == -1) {
2167         WARN("can't reset !\n");
2168         return MMSYSERR_INVALHANDLE;
2169     }
2170     PostThreadMessageA(WInDev[wDevID].dwThreadID, WINE_WM_RESETTING, 0, 0);
2171     WaitForSingleObject(WInDev[wDevID].hEvent, INFINITE);
2172     return MMSYSERR_NOERROR;
2173 }
2174
2175 /**************************************************************************
2176  *                              widGetPosition                  [internal]
2177  */
2178 static DWORD widGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
2179 {
2180     int                 time;
2181     WINE_WAVEIN*        wwi;
2182
2183     TRACE("(%u, %p, %lu);\n", wDevID, lpTime, uSize);
2184
2185     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].unixdev == -1) {
2186         WARN("can't get pos !\n");
2187         return MMSYSERR_INVALHANDLE;
2188     }
2189     if (lpTime == NULL) return MMSYSERR_INVALPARAM;
2190
2191     wwi = &WInDev[wDevID];
2192
2193     TRACE("wType=%04X !\n", lpTime->wType);
2194     TRACE("wBitsPerSample=%u\n", wwi->format.wBitsPerSample);
2195     TRACE("nSamplesPerSec=%lu\n", wwi->format.wf.nSamplesPerSec);
2196     TRACE("nChannels=%u\n", wwi->format.wf.nChannels);
2197     TRACE("nAvgBytesPerSec=%lu\n", wwi->format.wf.nAvgBytesPerSec);
2198     switch (lpTime->wType) {
2199     case TIME_BYTES:
2200         lpTime->u.cb = wwi->dwTotalRecorded;
2201         TRACE("TIME_BYTES=%lu\n", lpTime->u.cb);
2202         break;
2203     case TIME_SAMPLES:
2204         lpTime->u.sample = wwi->dwTotalRecorded * 8 /
2205             wwi->format.wBitsPerSample;
2206         TRACE("TIME_SAMPLES=%lu\n", lpTime->u.sample);
2207         break;
2208     case TIME_SMPTE:
2209         time = wwi->dwTotalRecorded /
2210             (wwi->format.wf.nAvgBytesPerSec / 1000);
2211         lpTime->u.smpte.hour = time / 108000;
2212         time -= lpTime->u.smpte.hour * 108000;
2213         lpTime->u.smpte.min = time / 1800;
2214         time -= lpTime->u.smpte.min * 1800;
2215         lpTime->u.smpte.sec = time / 30;
2216         time -= lpTime->u.smpte.sec * 30;
2217         lpTime->u.smpte.frame = time;
2218         lpTime->u.smpte.fps = 30;
2219         TRACE("TIME_SMPTE=%02u:%02u:%02u:%02u\n",
2220               lpTime->u.smpte.hour, lpTime->u.smpte.min,
2221               lpTime->u.smpte.sec, lpTime->u.smpte.frame);
2222         break;
2223     case TIME_MS:
2224         lpTime->u.ms = wwi->dwTotalRecorded /
2225             (wwi->format.wf.nAvgBytesPerSec / 1000);
2226         TRACE("TIME_MS=%lu\n", lpTime->u.ms);
2227         break;
2228     default:
2229         FIXME("format not supported (%u) ! use TIME_MS !\n", lpTime->wType);
2230         lpTime->wType = TIME_MS;
2231     }
2232     return MMSYSERR_NOERROR;
2233 }
2234
2235 /**************************************************************************
2236  *                              widMessage (WINEAUDIOIO.@)
2237  */
2238 DWORD WINAPI LIBAUDIOIO_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2239                             DWORD dwParam1, DWORD dwParam2)
2240 {
2241     TRACE("(%u, %04X, %08lX, %08lX, %08lX);\n",
2242           wDevID, wMsg, dwUser, dwParam1, dwParam2);
2243
2244     switch (wMsg) {
2245     case DRVM_INIT:
2246     case DRVM_EXIT:
2247     case DRVM_ENABLE:
2248     case DRVM_DISABLE:
2249         /* FIXME: Pretend this is supported */
2250         return 0;
2251     case WIDM_OPEN:             return widOpen       (wDevID, (LPWAVEOPENDESC)dwParam1, dwParam2);
2252     case WIDM_CLOSE:            return widClose      (wDevID);
2253     case WIDM_ADDBUFFER:        return widAddBuffer  (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2254     case WIDM_PREPARE:          return widPrepare    (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2255     case WIDM_UNPREPARE:        return widUnprepare  (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2256     case WIDM_GETDEVCAPS:       return widGetDevCaps (wDevID, (LPWAVEINCAPSA)dwParam1, dwParam2);
2257     case WIDM_GETNUMDEVS:       return wodGetNumDevs ();        /* same number of devices in output as in input */
2258     case WIDM_GETPOS:           return widGetPosition(wDevID, (LPMMTIME)dwParam1, dwParam2);
2259     case WIDM_RESET:            return widReset      (wDevID);
2260     case WIDM_START:            return widStart      (wDevID);
2261     case WIDM_STOP:             return widStop       (wDevID);
2262     default:
2263         FIXME("unknown message %u!\n", wMsg);
2264     }
2265     return MMSYSERR_NOTSUPPORTED;
2266 }
2267
2268 #else /* HAVE_LIBAUDIOIO */
2269
2270 /**************************************************************************
2271  *                              wodMessage (WINEAUDIOIO.@)
2272  */
2273 DWORD WINAPI LIBAUDIOIO_wodMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2274                             DWORD dwParam1, DWORD dwParam2)
2275 {
2276     FIXME("(%u, %04X, %08lX, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2277     return MMSYSERR_NOTENABLED;
2278 }
2279
2280 /**************************************************************************
2281  *                              widMessage (WINEAUDIOIO.@)
2282  */
2283 DWORD WINAPI LIBAUDIOIO_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2284                             DWORD dwParam1, DWORD dwParam2)
2285 {
2286     FIXME("(%u, %04X, %08lX, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2287     return MMSYSERR_NOTENABLED;
2288 }
2289
2290 #endif /* HAVE_LIBAUDIOIO */