audio.c 110 KB
Newer Older
1
/*
Alexandre Julliard's avatar
Alexandre Julliard committed
2
 * Sample Wine Driver for Open Sound System (featured in Linux and FreeBSD)
Alexandre Julliard's avatar
Alexandre Julliard committed
3 4
 *
 * Copyright 1994 Martin Ayotte
5
 *           1999 Eric Pouech (async playing in waveOut/waveIn)
6
 *	     2000 Eric Pouech (loops in waveOut)
7
 *           2002 Eric Pouech (full duplex)
8 9 10 11 12 13 14 15 16 17 18 19 20
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
21
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
Alexandre Julliard's avatar
Alexandre Julliard committed
22
 */
Alexandre Julliard's avatar
Alexandre Julliard committed
23 24
/*
 * FIXME:
25
 *	pause in waveOut does not work correctly in loop mode
26
 *	Direct Sound Capture driver does not work (not complete yet)
Alexandre Julliard's avatar
Alexandre Julliard committed
27
 */
Alexandre Julliard's avatar
Alexandre Julliard committed
28

29 30
/* an exact wodGetPosition is usually not worth the extra context switches,
 * as we're going to have near fragment accuracy anyway */
31 32
#define EXACT_WODPOSITION
#define EXACT_WIDPOSITION
33

34
#include "config.h"
35
#include "wine/port.h"
36

Alexandre Julliard's avatar
Alexandre Julliard committed
37
#include <stdlib.h>
38
#include <stdarg.h>
39
#include <stdio.h>
40
#include <string.h>
41 42 43
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
Alexandre Julliard's avatar
Alexandre Julliard committed
44
#include <errno.h>
Alexandre Julliard's avatar
Alexandre Julliard committed
45
#include <fcntl.h>
46 47 48
#ifdef HAVE_SYS_IOCTL_H
# include <sys/ioctl.h>
#endif
Patrik Stridvall's avatar
Patrik Stridvall committed
49 50 51
#ifdef HAVE_SYS_MMAN_H
# include <sys/mman.h>
#endif
52 53 54
#ifdef HAVE_POLL_H
#include <poll.h>
#endif
55 56 57 58
#ifdef HAVE_SYS_POLL_H
# include <sys/poll.h>
#endif

59
#include "windef.h"
60
#include "winbase.h"
61
#include "wingdi.h"
62 63
#include "winuser.h"
#include "winnls.h"
64
#include "winerror.h"
65
#include "mmddk.h"
66
#include "mmreg.h"
67
#include "dsound.h"
68 69 70
#include "ks.h"
#include "ksguid.h"
#include "ksmedia.h"
71 72
#include "initguid.h"
#include "dsdriver.h"
73
#include "oss.h"
74
#include "wine/debug.h"
Alexandre Julliard's avatar
Alexandre Julliard committed
75

76 77
#include "audio.h"

78
WINE_DEFAULT_DEBUG_CHANNEL(wave);
79

80
/* Allow 1% deviation for sample rates (some ES137x cards) */
81
#define NEAR_MATCH(rate1,rate2) (((100*((int)(rate1)-(int)(rate2)))/(rate1))==0)
82

Alexandre Julliard's avatar
Alexandre Julliard committed
83
#ifdef HAVE_OSS
Alexandre Julliard's avatar
Alexandre Julliard committed
84

85 86 87 88
WINE_WAVEOUT    WOutDev[MAX_WAVEDRV];
WINE_WAVEIN     WInDev[MAX_WAVEDRV];
unsigned        numOutDev;
unsigned        numInDev;
Alexandre Julliard's avatar
Alexandre Julliard committed
89

90 91
/* state diagram for waveOut writing:
 *
92 93 94 95 96 97 98 99 100 101 102 103 104
 * +---------+-------------+---------------+---------------------------------+
 * |  state  |  function   |     event     |            new state	     |
 * +---------+-------------+---------------+---------------------------------+
 * |	     | open()	   |		   | STOPPED		       	     |
 * | PAUSED  | write()	   | 		   | PAUSED		       	     |
 * | STOPPED | write()	   | <thrd create> | PLAYING		  	     |
 * | PLAYING | write()	   | HEADER        | PLAYING		  	     |
 * | (other) | write()	   | <error>       |		       		     |
 * | (any)   | pause()	   | PAUSING	   | PAUSED		       	     |
 * | PAUSED  | restart()   | RESTARTING    | PLAYING (if no thrd => STOPPED) |
 * | (any)   | reset()	   | RESETTING     | STOPPED		      	     |
 * | (any)   | close()	   | CLOSING	   | CLOSED		      	     |
 * +---------+-------------+---------------+---------------------------------+
105 106
 */

107
/* These strings used only for tracing */
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
static const char * getCmdString(enum win_wm_message msg)
{
    static char unknown[32];
#define MSG_TO_STR(x) case x: return #x
    switch(msg) {
    MSG_TO_STR(WINE_WM_PAUSING);
    MSG_TO_STR(WINE_WM_RESTARTING);
    MSG_TO_STR(WINE_WM_RESETTING);
    MSG_TO_STR(WINE_WM_HEADER);
    MSG_TO_STR(WINE_WM_UPDATE);
    MSG_TO_STR(WINE_WM_BREAKLOOP);
    MSG_TO_STR(WINE_WM_CLOSING);
    MSG_TO_STR(WINE_WM_STARTING);
    MSG_TO_STR(WINE_WM_STOPPING);
    }
#undef MSG_TO_STR
    sprintf(unknown, "UNKNOWN(0x%08x)", msg);
    return unknown;
126
}
127

128
int getEnables(OSS_DEVICE *ossdev)
129
{
130
    return ( (ossdev->bOutputEnabled ? PCM_ENABLE_OUTPUT : 0) |
131 132 133
             (ossdev->bInputEnabled  ? PCM_ENABLE_INPUT  : 0) );
}

134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
static const char * getMessage(UINT msg)
{
    static char unknown[32];
#define MSG_TO_STR(x) case x: return #x
    switch(msg) {
    MSG_TO_STR(DRVM_INIT);
    MSG_TO_STR(DRVM_EXIT);
    MSG_TO_STR(DRVM_ENABLE);
    MSG_TO_STR(DRVM_DISABLE);
    MSG_TO_STR(WIDM_OPEN);
    MSG_TO_STR(WIDM_CLOSE);
    MSG_TO_STR(WIDM_ADDBUFFER);
    MSG_TO_STR(WIDM_PREPARE);
    MSG_TO_STR(WIDM_UNPREPARE);
    MSG_TO_STR(WIDM_GETDEVCAPS);
    MSG_TO_STR(WIDM_GETNUMDEVS);
    MSG_TO_STR(WIDM_GETPOS);
    MSG_TO_STR(WIDM_RESET);
    MSG_TO_STR(WIDM_START);
    MSG_TO_STR(WIDM_STOP);
    MSG_TO_STR(WODM_OPEN);
    MSG_TO_STR(WODM_CLOSE);
    MSG_TO_STR(WODM_WRITE);
    MSG_TO_STR(WODM_PAUSE);
    MSG_TO_STR(WODM_GETPOS);
    MSG_TO_STR(WODM_BREAKLOOP);
    MSG_TO_STR(WODM_PREPARE);
    MSG_TO_STR(WODM_UNPREPARE);
    MSG_TO_STR(WODM_GETDEVCAPS);
    MSG_TO_STR(WODM_GETNUMDEVS);
    MSG_TO_STR(WODM_GETPITCH);
    MSG_TO_STR(WODM_SETPITCH);
    MSG_TO_STR(WODM_GETPLAYBACKRATE);
    MSG_TO_STR(WODM_SETPLAYBACKRATE);
    MSG_TO_STR(WODM_GETVOLUME);
    MSG_TO_STR(WODM_SETVOLUME);
    MSG_TO_STR(WODM_RESTART);
    MSG_TO_STR(WODM_RESET);
    MSG_TO_STR(DRV_QUERYDEVICEINTERFACESIZE);
    MSG_TO_STR(DRV_QUERYDEVICEINTERFACE);
    MSG_TO_STR(DRV_QUERYDSOUNDIFACE);
    MSG_TO_STR(DRV_QUERYDSOUNDDESC);
    }
177
#undef MSG_TO_STR
178 179 180 181
    sprintf(unknown, "UNKNOWN(0x%04x)", msg);
    return unknown;
}

182
static DWORD wodDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
183 184 185
{
    TRACE("(%u, %p)\n", wDevID, dwParam1);

186
    *dwParam1 = MultiByteToWideChar(CP_UNIXCP, 0, WOutDev[wDevID].ossdev.interface_name, -1,
187 188 189 190
                                    NULL, 0 ) * sizeof(WCHAR);
    return MMSYSERR_NOERROR;
}

191
static DWORD wodDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
192
{
193
    if (dwParam2 >= MultiByteToWideChar(CP_UNIXCP, 0, WOutDev[wDevID].ossdev.interface_name, -1,
194 195
                                        NULL, 0 ) * sizeof(WCHAR))
    {
196
        MultiByteToWideChar(CP_UNIXCP, 0, WOutDev[wDevID].ossdev.interface_name, -1,
197 198 199 200 201 202 203 204 205 206 207
                            dwParam1, dwParam2 / sizeof(WCHAR));
	return MMSYSERR_NOERROR;
    }

    return MMSYSERR_INVALPARAM;
}

static DWORD widDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
{
    TRACE("(%u, %p)\n", wDevID, dwParam1);

208
    *dwParam1 = MultiByteToWideChar(CP_UNIXCP, 0, WInDev[wDevID].ossdev.interface_name, -1,
209 210 211 212 213 214
                                    NULL, 0 ) * sizeof(WCHAR);
    return MMSYSERR_NOERROR;
}

static DWORD widDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
{
215
    if (dwParam2 >= MultiByteToWideChar(CP_UNIXCP, 0, WInDev[wDevID].ossdev.interface_name, -1,
216 217
                                        NULL, 0 ) * sizeof(WCHAR))
    {
218
        MultiByteToWideChar(CP_UNIXCP, 0, WInDev[wDevID].ossdev.interface_name, -1,
219 220 221 222 223 224 225
                            dwParam1, dwParam2 / sizeof(WCHAR));
	return MMSYSERR_NOERROR;
    }

    return MMSYSERR_INVALPARAM;
}

226
static DWORD bytes_to_mmtime(LPMMTIME lpTime, DWORD position,
227
                             WAVEFORMATPCMEX* format)
228
{
229
    TRACE("wType=%04X wBitsPerSample=%u nSamplesPerSec=%u nChannels=%u nAvgBytesPerSec=%u\n",
230 231
          lpTime->wType, format->Format.wBitsPerSample, format->Format.nSamplesPerSec,
          format->Format.nChannels, format->Format.nAvgBytesPerSec);
232
    TRACE("Position in bytes=%u\n", position);
233 234 235

    switch (lpTime->wType) {
    case TIME_SAMPLES:
236
        lpTime->u.sample = position / (format->Format.wBitsPerSample / 8 * format->Format.nChannels);
237
        TRACE("TIME_SAMPLES=%u\n", lpTime->u.sample);
238 239
        break;
    case TIME_MS:
240
        lpTime->u.ms = 1000.0 * position / (format->Format.wBitsPerSample / 8 * format->Format.nChannels * format->Format.nSamplesPerSec);
241
        TRACE("TIME_MS=%u\n", lpTime->u.ms);
242 243
        break;
    case TIME_SMPTE:
244
        lpTime->u.smpte.fps = 30;
245
        position = position / (format->Format.wBitsPerSample / 8 * format->Format.nChannels);
246
        position += (format->Format.nSamplesPerSec / lpTime->u.smpte.fps) - 1; /* round up */
247 248
        lpTime->u.smpte.sec = position / format->Format.nSamplesPerSec;
        position -= lpTime->u.smpte.sec * format->Format.nSamplesPerSec;
249 250 251 252 253
        lpTime->u.smpte.min = lpTime->u.smpte.sec / 60;
        lpTime->u.smpte.sec -= 60 * lpTime->u.smpte.min;
        lpTime->u.smpte.hour = lpTime->u.smpte.min / 60;
        lpTime->u.smpte.min -= 60 * lpTime->u.smpte.hour;
        lpTime->u.smpte.fps = 30;
254
        lpTime->u.smpte.frame = position * lpTime->u.smpte.fps / format->Format.nSamplesPerSec;
255 256 257 258 259
        TRACE("TIME_SMPTE=%02u:%02u:%02u:%02u\n",
              lpTime->u.smpte.hour, lpTime->u.smpte.min,
              lpTime->u.smpte.sec, lpTime->u.smpte.frame);
        break;
    default:
260
        WARN("Format %d not supported, using TIME_BYTES !\n", lpTime->wType);
261 262 263 264
        lpTime->wType = TIME_BYTES;
        /* fall through */
    case TIME_BYTES:
        lpTime->u.cb = position;
265
        TRACE("TIME_BYTES=%u\n", lpTime->u.cb);
266 267 268 269 270
        break;
    }
    return MMSYSERR_NOERROR;
}

271 272 273 274 275 276 277 278
static BOOL supportedFormat(LPWAVEFORMATEX wf)
{
    TRACE("(%p)\n",wf);

    if (wf->nSamplesPerSec<DSBFREQUENCY_MIN||wf->nSamplesPerSec>DSBFREQUENCY_MAX)
        return FALSE;

    if (wf->wFormatTag == WAVE_FORMAT_PCM) {
279
        if (wf->nChannels >= 1 && wf->nChannels <= MAX_CHANNELS) {
280
            if (wf->wBitsPerSample==8||wf->wBitsPerSample==16)
281 282
                return TRUE;
        }
283 284 285
    } else if (wf->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
        WAVEFORMATEXTENSIBLE * wfex = (WAVEFORMATEXTENSIBLE *)wf;

286
        if (wf->cbSize == 22 && IsEqualGUID(&wfex->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM)) {
287
            if (wf->nChannels >=1 && wf->nChannels <= MAX_CHANNELS) {
288 289 290 291 292
                if (wf->wBitsPerSample==wfex->Samples.wValidBitsPerSample) {
                    if (wf->wBitsPerSample==8||wf->wBitsPerSample==16)
                        return TRUE;
                } else
                    WARN("wBitsPerSample != wValidBitsPerSample not supported yet\n");
293
            }
294 295 296 297
        } else
            WARN("only KSDATAFORMAT_SUBTYPE_PCM supported\n");
    } else
        WARN("only WAVE_FORMAT_PCM and WAVE_FORMAT_EXTENSIBLE supported\n");
298 299 300 301

    return FALSE;
}

302
void copy_format(LPWAVEFORMATEX wf1, LPWAVEFORMATPCMEX wf2)
303 304 305 306 307 308 309 310 311 312
{
    ZeroMemory(wf2, sizeof(wf2));
    if (wf1->wFormatTag == WAVE_FORMAT_PCM)
        memcpy(wf2, wf1, sizeof(PCMWAVEFORMAT));
    else if (wf1->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
        memcpy(wf2, wf1, sizeof(WAVEFORMATPCMEX));
    else
        memcpy(wf2, wf1, sizeof(WAVEFORMATEX) + wf1->cbSize);
}

313
/*======================================================================*
314
 *                  Low level WAVE implementation			*
315
 *======================================================================*/
316

317 318 319 320 321
/******************************************************************
 *		OSS_RawOpenDevice
 *
 * Low level device opening (from values stored in ossdev)
 */
322
static DWORD      OSS_RawOpenDevice(OSS_DEVICE* ossdev, int strict_format)
323
{
324
    int fd, val, rc;
325
    TRACE("(%p,%d)\n",ossdev,strict_format);
326

327 328 329 330 331
    TRACE("open_access=%s\n",
        ossdev->open_access == O_RDONLY ? "O_RDONLY" :
        ossdev->open_access == O_WRONLY ? "O_WRONLY" :
        ossdev->open_access == O_RDWR ? "O_RDWR" : "Unknown");

332 333
    if ((fd = open(ossdev->dev_name, ossdev->open_access|O_NDELAY, 0)) == -1)
    {
334 335
        WARN("Couldn't open %s (%s)\n", ossdev->dev_name, strerror(errno));
        return (errno == EBUSY) ? MMSYSERR_ALLOCATED : MMSYSERR_ERROR;
336 337 338
    }
    fcntl(fd, F_SETFD, 1); /* set close on exec flag */
    /* turn full duplex on if it has been requested */
339 340
    if (ossdev->open_access == O_RDWR && ossdev->full_duplex) {
        rc = ioctl(fd, SNDCTL_DSP_SETDUPLEX, 0);
341 342 343 344 345
        /* on *BSD, as full duplex is always enabled by default, this ioctl
         * will fail with EINVAL
         * so, we don't consider EINVAL an error here
         */
        if (rc != 0 && errno != EINVAL) {
346
            WARN("ioctl(%s, SNDCTL_DSP_SETDUPLEX) failed (%s)\n", ossdev->dev_name, strerror(errno));
347
            goto error2;
348 349
	}
    }
350

351 352 353 354
    if (ossdev->audio_fragment) {
        rc = ioctl(fd, SNDCTL_DSP_SETFRAGMENT, &ossdev->audio_fragment);
        if (rc != 0) {
	    ERR("ioctl(%s, SNDCTL_DSP_SETFRAGMENT) failed (%s)\n", ossdev->dev_name, strerror(errno));
355
            goto error2;
356
	}
357 358
    }

359
    /* First size and channels then samplerate */
360
    if (ossdev->format>=0)
361 362
    {
        val = ossdev->format;
363 364
        rc = ioctl(fd, SNDCTL_DSP_SETFMT, &ossdev->format);
        if (rc != 0 || val != ossdev->format) {
365 366 367
            TRACE("Can't set format to %d (returned %d)\n", val, ossdev->format);
            if (strict_format)
                goto error;
368
        }
369
    }
370
    if (ossdev->channels>=0)
371
    {
372 373 374 375
        val = ossdev->channels;
        rc = ioctl(fd, SNDCTL_DSP_CHANNELS, &ossdev->channels);
        if (rc != 0 || val != ossdev->channels) {
            TRACE("Can't set channels to %u (returned %d)\n", val, ossdev->channels);
376 377
            if (strict_format)
                goto error;
378
        }
379
    }
380
    if (ossdev->sample_rate>=0)
381 382
    {
        val = ossdev->sample_rate;
383 384
        rc = ioctl(fd, SNDCTL_DSP_SPEED, &ossdev->sample_rate);
        if (rc != 0 || !NEAR_MATCH(val, ossdev->sample_rate)) {
385 386 387
            TRACE("Can't set sample_rate to %u (returned %d)\n", val, ossdev->sample_rate);
            if (strict_format)
                goto error;
388
        }
389
    }
390
    ossdev->fd = fd;
391

392 393 394 395 396 397 398
    ossdev->bOutputEnabled = TRUE;	/* OSS enables by default */
    ossdev->bInputEnabled  = TRUE;	/* OSS enables by default */
    if (ossdev->open_access == O_RDONLY)
        ossdev->bOutputEnabled = FALSE;
    if (ossdev->open_access == O_WRONLY)
        ossdev->bInputEnabled = FALSE;

399 400
    if (ossdev->bTriggerSupport) {
	int trigger;
401
        trigger = getEnables(ossdev);
402 403 404 405 406 407 408 409 410 411
        /* If we do not have full duplex, but they opened RDWR 
        ** (as you have to in order for an mmap to succeed)
        ** then we start out with input off
        */
        if (ossdev->open_access == O_RDWR && !ossdev->full_duplex && 
            ossdev->bInputEnabled && ossdev->bOutputEnabled) {
    	    ossdev->bInputEnabled  = FALSE;
            trigger &= ~PCM_ENABLE_INPUT;
	    ioctl(fd, SNDCTL_DSP_SETTRIGGER, &trigger);
        }
412
    }
413

414
    return MMSYSERR_NOERROR;
415 416 417

error:
    close(fd);
418
    return WAVERR_BADFORMAT;
419
error2:
420 421
    close(fd);
    return MMSYSERR_ERROR;
422
}
423 424 425 426 427 428 429 430

/******************************************************************
 *		OSS_OpenDevice
 *
 * since OSS has poor capabilities in full duplex, we try here to let a program
 * open the device for both waveout and wavein streams...
 * this is hackish, but it's the way OSS interface is done...
 */
431
DWORD OSS_OpenDevice(OSS_DEVICE* ossdev, unsigned req_access,
432
                            int* frag, int strict_format,
433
                            int sample_rate, int channels, int fmt)
434
{
435
    DWORD       ret;
436
    DWORD open_access;
437
    TRACE("(%p,%u,%p,%d,%d,%d,%x)\n",ossdev,req_access,frag,strict_format,sample_rate,channels,fmt);
438

439
    if (ossdev->full_duplex && (req_access == O_RDONLY || req_access == O_WRONLY))
440 441 442 443 444 445 446 447 448
    {
        TRACE("Opening RDWR because full_duplex=%d and req_access=%d\n",
              ossdev->full_duplex,req_access);
        open_access = O_RDWR;
    }
    else
    {
        open_access=req_access;
    }
449

450
    /* FIXME: this should be protected, and it also contains a race with OSS_CloseDevice */
451
    if (ossdev->open_count == 0)
452
    {
453 454 455 456
	if (access(ossdev->dev_name, 0) != 0) return MMSYSERR_NODRIVER;

        ossdev->audio_fragment = (frag) ? *frag : 0;
        ossdev->sample_rate = sample_rate;
457
        ossdev->channels = channels;
458
        ossdev->format = fmt;
459
        ossdev->open_access = open_access;
460
        ossdev->owner_tid = GetCurrentThreadId();
461

462
        if ((ret = OSS_RawOpenDevice(ossdev,strict_format)) != MMSYSERR_NOERROR) return ret;
463 464 465 466 467 468 469 470 471 472 473 474 475
        if (ossdev->full_duplex && ossdev->bTriggerSupport &&
            (req_access == O_RDONLY || req_access == O_WRONLY))
        {
            int enable;
            if (req_access == O_WRONLY)
                ossdev->bInputEnabled=0;
            else
                ossdev->bOutputEnabled=0;
            enable = getEnables(ossdev);
            TRACE("Calling SNDCTL_DSP_SETTRIGGER with %x\n",enable);
            if (ioctl(ossdev->fd, SNDCTL_DSP_SETTRIGGER, &enable) < 0)
                ERR("ioctl(%s, SNDCTL_DSP_SETTRIGGER, %d) failed (%s)\n",ossdev->dev_name, enable, strerror(errno));
        }
476
    }
477
    else
478
    {
479
        /* check we really open with the same parameters */
480
        if (ossdev->open_access != open_access)
481
        {
Robert Reif's avatar
Robert Reif committed
482
            ERR("FullDuplex: Mismatch in access. Your sound device is not full duplex capable.\n");
483
            return WAVERR_BADFORMAT;
484
        }
485

Robert Reif's avatar
Robert Reif committed
486 487
	/* check if the audio parameters are the same */
        if (ossdev->sample_rate != sample_rate ||
488
            ossdev->channels != channels ||
489 490
            ossdev->format != fmt)
        {
491
	    /* This is not a fatal error because MSACM might do the remapping */
492 493
            WARN("FullDuplex: mismatch in PCM parameters for input and output\n"
                 "OSS doesn't allow us different parameters\n"
494
                 "audio_frag(%x/%x) sample_rate(%d/%d) channels(%d/%d) fmt(%d/%d)\n",
495
                 ossdev->audio_fragment, frag ? *frag : 0,
496
                 ossdev->sample_rate, sample_rate,
497
                 ossdev->channels, channels,
498 499 500
                 ossdev->format, fmt);
            return WAVERR_BADFORMAT;
        }
Robert Reif's avatar
Robert Reif committed
501
	/* check if the fragment sizes are the same */
502 503
        if (ossdev->audio_fragment != (frag ? *frag : 0) )
        {
Robert Reif's avatar
Robert Reif committed
504
	    ERR("FullDuplex: Playback and Capture hardware acceleration levels are different.\n"
505 506
	        "Please run winecfg, open \"Audio\" page and set\n"
                "\"Hardware Acceleration\" to \"Emulation\".\n");
Robert Reif's avatar
Robert Reif committed
507 508
	    return WAVERR_BADFORMAT;
	}
509
        if (GetCurrentThreadId() != ossdev->owner_tid)
510 511
        {
            WARN("Another thread is trying to access audio...\n");
512
            return MMSYSERR_ERROR;
513
        }
514 515 516 517 518 519 520 521 522 523 524 525 526
        if (ossdev->full_duplex && ossdev->bTriggerSupport &&
            (req_access == O_RDONLY || req_access == O_WRONLY))
        {
            int enable;
            if (req_access == O_WRONLY)
                ossdev->bOutputEnabled=1;
            else
                ossdev->bInputEnabled=1;
            enable = getEnables(ossdev);
            TRACE("Calling SNDCTL_DSP_SETTRIGGER with %x\n",enable);
            if (ioctl(ossdev->fd, SNDCTL_DSP_SETTRIGGER, &enable) < 0)
                ERR("ioctl(%s, SNDCTL_DSP_SETTRIGGER, %d) failed (%s)\n",ossdev->dev_name, enable, strerror(errno));
        }
527
    }
528

529
    ossdev->open_count++;
530

531
    return MMSYSERR_NOERROR;
532 533 534 535 536 537 538
}

/******************************************************************
 *		OSS_CloseDevice
 *
 *
 */
539
void	OSS_CloseDevice(OSS_DEVICE* ossdev)
540
{
541
    TRACE("(%p)\n",ossdev);
542 543 544 545 546 547
    if (ossdev->open_count>0) {
        ossdev->open_count--;
    } else {
        WARN("OSS_CloseDevice called too many times\n");
    }
    if (ossdev->open_count == 0)
548
    {
549 550 551 552
        fcntl(ossdev->fd, F_SETFL, fcntl(ossdev->fd, F_GETFL) & ~O_NDELAY);
        /* reset the device before we close it in case it is in a bad state */
        ioctl(ossdev->fd, SNDCTL_DSP_RESET, 0);
        if (close(ossdev->fd) != 0) FIXME("Cannot close %d: %s\n", ossdev->fd, strerror(errno));
553
    }
554 555 556 557 558 559 560 561
}

/******************************************************************
 *		OSS_ResetDevice
 *
 * Resets the device. OSS Commercial requires the device to be closed
 * after a SNDCTL_DSP_RESET ioctl call... this function implements
 * this behavior...
562 563
 * FIXME: This causes problems when doing full duplex so we really
 * only reset when not doing full duplex. We need to do this better
564
 * someday.
565
 */
566
static DWORD     OSS_ResetDevice(OSS_DEVICE* ossdev)
567
{
568
    DWORD       ret = MMSYSERR_NOERROR;
569
    int         old_fd = ossdev->fd;
570
    TRACE("(%p)\n", ossdev);
571

572
    if (ossdev->open_count == 1) {
573
	if (ioctl(ossdev->fd, SNDCTL_DSP_RESET, NULL) == -1)
574 575 576 577 578 579 580
	{
	    perror("ioctl SNDCTL_DSP_RESET");
            return -1;
	}
	close(ossdev->fd);
	ret = OSS_RawOpenDevice(ossdev, 1);
	TRACE("Changing fd from %d to %d\n", old_fd, ossdev->fd);
581
    } else
582
	WARN("Not resetting device because it is in full duplex mode!\n");
583

584
    return ret;
585
}
Alexandre Julliard's avatar
Alexandre Julliard committed
586

587 588 589
static const int win_std_oss_fmts[2]={AFMT_U8,AFMT_S16_LE};
static const int win_std_rates[5]={96000,48000,44100,22050,11025};
static const int win_std_formats[2][2][5]=
590 591 592 593 594 595 596 597 598 599
    {{{WAVE_FORMAT_96M08, WAVE_FORMAT_48M08, WAVE_FORMAT_4M08,
       WAVE_FORMAT_2M08,  WAVE_FORMAT_1M08},
      {WAVE_FORMAT_96S08, WAVE_FORMAT_48S08, WAVE_FORMAT_4S08,
       WAVE_FORMAT_2S08,  WAVE_FORMAT_1S08}},
     {{WAVE_FORMAT_96M16, WAVE_FORMAT_48M16, WAVE_FORMAT_4M16,
       WAVE_FORMAT_2M16,  WAVE_FORMAT_1M16},
      {WAVE_FORMAT_96S16, WAVE_FORMAT_48S16, WAVE_FORMAT_4S16,
       WAVE_FORMAT_2S16,  WAVE_FORMAT_1S16}},
    };

600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
static void OSS_Info(int fd)
{
    /* Note that this only reports the formats supported by the hardware.
     * The driver may support other formats and do the conversions in
     * software which is why we don't use this value
     */
    int oss_mask, oss_caps;
    if (ioctl(fd, SNDCTL_DSP_GETFMTS, &oss_mask) >= 0) {
        TRACE("Formats=%08x ( ", oss_mask);
        if (oss_mask & AFMT_MU_LAW) TRACE("AFMT_MU_LAW ");
        if (oss_mask & AFMT_A_LAW) TRACE("AFMT_A_LAW ");
        if (oss_mask & AFMT_IMA_ADPCM) TRACE("AFMT_IMA_ADPCM ");
        if (oss_mask & AFMT_U8) TRACE("AFMT_U8 ");
        if (oss_mask & AFMT_S16_LE) TRACE("AFMT_S16_LE ");
        if (oss_mask & AFMT_S16_BE) TRACE("AFMT_S16_BE ");
        if (oss_mask & AFMT_S8) TRACE("AFMT_S8 ");
        if (oss_mask & AFMT_U16_LE) TRACE("AFMT_U16_LE ");
        if (oss_mask & AFMT_U16_BE) TRACE("AFMT_U16_BE ");
        if (oss_mask & AFMT_MPEG) TRACE("AFMT_MPEG ");
#ifdef AFMT_AC3
        if (oss_mask & AFMT_AC3) TRACE("AFMT_AC3 ");
#endif
#ifdef AFMT_VORBIS
        if (oss_mask & AFMT_VORBIS) TRACE("AFMT_VORBIS ");
#endif
#ifdef AFMT_S32_LE
        if (oss_mask & AFMT_S32_LE) TRACE("AFMT_S32_LE ");
#endif
#ifdef AFMT_S32_BE
        if (oss_mask & AFMT_S32_BE) TRACE("AFMT_S32_BE ");
#endif
#ifdef AFMT_FLOAT
        if (oss_mask & AFMT_FLOAT) TRACE("AFMT_FLOAT ");
#endif
#ifdef AFMT_S24_LE
        if (oss_mask & AFMT_S24_LE) TRACE("AFMT_S24_LE ");
#endif
637
#ifdef AFMT_S24_BE
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
        if (oss_mask & AFMT_S24_BE) TRACE("AFMT_S24_BE ");
#endif
#ifdef AFMT_SPDIF_RAW
        if (oss_mask & AFMT_SPDIF_RAW) TRACE("AFMT_SPDIF_RAW ");
#endif
        TRACE(")\n");
    }
    if (ioctl(fd, SNDCTL_DSP_GETCAPS, &oss_caps) >= 0) {
        TRACE("Caps=%08x\n",oss_caps);
        TRACE("\tRevision: %d\n", oss_caps&DSP_CAP_REVISION);
        TRACE("\tDuplex: %s\n", oss_caps & DSP_CAP_DUPLEX ? "true" : "false");
        TRACE("\tRealtime: %s\n", oss_caps & DSP_CAP_REALTIME ? "true" : "false");
        TRACE("\tBatch: %s\n", oss_caps & DSP_CAP_BATCH ? "true" : "false");
        TRACE("\tCoproc: %s\n", oss_caps & DSP_CAP_COPROC ? "true" : "false");
        TRACE("\tTrigger: %s\n", oss_caps & DSP_CAP_TRIGGER ? "true" : "false");
        TRACE("\tMmap: %s\n", oss_caps & DSP_CAP_MMAP ? "true" : "false");
#ifdef DSP_CAP_MULTI
        TRACE("\tMulti: %s\n", oss_caps & DSP_CAP_MULTI ? "true" : "false");
#endif
#ifdef DSP_CAP_BIND
        TRACE("\tBind: %s\n", oss_caps & DSP_CAP_BIND ? "true" : "false");
#endif
#ifdef DSP_CAP_INPUT
        TRACE("\tInput: %s\n", oss_caps & DSP_CAP_INPUT ? "true" : "false");
#endif
#ifdef DSP_CAP_OUTPUT
        TRACE("\tOutput: %s\n", oss_caps & DSP_CAP_OUTPUT ? "true" : "false");
#endif
#ifdef DSP_CAP_VIRTUAL
        TRACE("\tVirtual: %s\n", oss_caps & DSP_CAP_VIRTUAL ? "true" : "false");
#endif
#ifdef DSP_CAP_ANALOGOUT
        TRACE("\tAnalog Out: %s\n", oss_caps & DSP_CAP_ANALOGOUT ? "true" : "false");
#endif
#ifdef DSP_CAP_ANALOGIN
        TRACE("\tAnalog In: %s\n", oss_caps & DSP_CAP_ANALOGIN ? "true" : "false");
#endif
#ifdef DSP_CAP_DIGITALOUT
        TRACE("\tDigital Out: %s\n", oss_caps & DSP_CAP_DIGITALOUT ? "true" : "false");
#endif
#ifdef DSP_CAP_DIGITALIN
        TRACE("\tDigital In: %s\n", oss_caps & DSP_CAP_DIGITALIN ? "true" : "false");
#endif
#ifdef DSP_CAP_ADMASK
        TRACE("\tA/D Mask: %s\n", oss_caps & DSP_CAP_ADMASK ? "true" : "false");
#endif
#ifdef DSP_CAP_SHADOW
        TRACE("\tShadow: %s\n", oss_caps & DSP_CAP_SHADOW ? "true" : "false");
#endif
#ifdef DSP_CH_MASK
        TRACE("\tChannel Mask: %x\n", oss_caps & DSP_CH_MASK);
#endif
#ifdef DSP_CAP_SLAVE
        TRACE("\tSlave: %s\n", oss_caps & DSP_CAP_SLAVE ? "true" : "false");
#endif
    }
}

Eric Pouech's avatar
Eric Pouech committed
696
/******************************************************************
697 698
 *		OSS_WaveOutInit
 *
Eric Pouech's avatar
Eric Pouech committed
699 700
 *
 */
701
static BOOL OSS_WaveOutInit(OSS_DEVICE* ossdev)
702
{
703
    int rc,arg;
704 705
    int f,c;
    unsigned int r;
706
    BOOL has_mixer = FALSE;
707
    TRACE("(%p) %s\n", ossdev, ossdev->dev_name);
708

709 710 711
    if (OSS_OpenDevice(ossdev, O_WRONLY, NULL, 0,-1,-1,-1) != 0)
        return FALSE;

712
    ioctl(ossdev->fd, SNDCTL_DSP_RESET, 0);
713

714 715 716 717 718 719 720 721 722
#if defined(SNDCTL_MIXERINFO)
    {
        int mixer;
        if ((mixer = open(ossdev->mixer_name, O_RDONLY|O_NDELAY)) >= 0) {
            oss_mixerinfo info;
            info.dev = 0;
            if (ioctl(mixer, SNDCTL_MIXERINFO, &info) >= 0) {
                lstrcpynA(ossdev->ds_desc.szDesc, info.name, sizeof(info.name));
                strcpy(ossdev->ds_desc.szDrvname, "wineoss.drv");
723
                MultiByteToWideChar(CP_UNIXCP, 0, info.name, sizeof(info.name),
724 725 726 727 728 729 730 731 732 733 734 735 736
                                    ossdev->out_caps.szPname,
                                    sizeof(ossdev->out_caps.szPname) / sizeof(WCHAR));
                TRACE("%s: %s\n", ossdev->mixer_name, ossdev->ds_desc.szDesc);
                has_mixer = TRUE;
            } else {
                WARN("%s: cannot read SNDCTL_MIXERINFO!\n", ossdev->mixer_name);
            }
            close(mixer);
        } else {
            WARN("open(%s) failed (%s)\n", ossdev->mixer_name , strerror(errno));
        }
    }
#elif defined(SOUND_MIXER_INFO)
Alexandre Julliard's avatar
Alexandre Julliard committed
737 738 739 740 741
    {
        int mixer;
        if ((mixer = open(ossdev->mixer_name, O_RDONLY|O_NDELAY)) >= 0) {
            mixer_info info;
            if (ioctl(mixer, SOUND_MIXER_INFO, &info) >= 0) {
742
                lstrcpynA(ossdev->ds_desc.szDesc, info.name, sizeof(info.name));
743
                strcpy(ossdev->ds_desc.szDrvname, "wineoss.drv");
744
                MultiByteToWideChar(CP_UNIXCP, 0, info.name, sizeof(info.name),
745 746
                                    ossdev->out_caps.szPname, 
                                    sizeof(ossdev->out_caps.szPname) / sizeof(WCHAR));
747
                TRACE("%s: %s\n", ossdev->mixer_name, ossdev->ds_desc.szDesc);
748
                has_mixer = TRUE;
Alexandre Julliard's avatar
Alexandre Julliard committed
749
            } else {
750 751 752 753 754
                /* FreeBSD up to at least 5.2 provides this ioctl, but does not
                 * implement it properly, and there are probably similar issues
                 * on other platforms, so we warn but try to go ahead.
                 */
                WARN("%s: cannot read SOUND_MIXER_INFO!\n", ossdev->mixer_name);
Alexandre Julliard's avatar
Alexandre Julliard committed
755
            }
756
            close(mixer);
Alexandre Julliard's avatar
Alexandre Julliard committed
757
        } else {
758
            WARN("open(%s) failed (%s)\n", ossdev->mixer_name , strerror(errno));
Alexandre Julliard's avatar
Alexandre Julliard committed
759
        }
760
    }
761
#endif /* SOUND_MIXER_INFO */
762

763 764 765
    if (WINE_TRACE_ON(wave))
        OSS_Info(ossdev->fd);

766 767
    ossdev->out_caps.wMid = 0x00FF; /* Manufac ID */
    ossdev->out_caps.wPid = 0x0001; /* Product ID */
768

769
    ossdev->out_caps.vDriverVersion = 0x0100;
770
    ossdev->out_caps.wChannels = 1;
771
    ossdev->out_caps.dwFormats = 0x00000000;
772
    ossdev->out_caps.wReserved1 = 0;
773
    ossdev->out_caps.dwSupport = has_mixer ? WAVECAPS_VOLUME : 0;
774

775
    /* direct sound caps */
776
    ossdev->ds_caps.dwFlags = DSCAPS_CERTIFIED;
777 778 779 780 781 782
    ossdev->ds_caps.dwFlags |= DSCAPS_SECONDARY8BIT;
    ossdev->ds_caps.dwFlags |= DSCAPS_SECONDARY16BIT;
    ossdev->ds_caps.dwFlags |= DSCAPS_SECONDARYMONO;
    ossdev->ds_caps.dwFlags |= DSCAPS_SECONDARYSTEREO;
    ossdev->ds_caps.dwFlags |= DSCAPS_CONTINUOUSRATE;

783
    ossdev->ds_caps.dwPrimaryBuffers = 1;
784 785
    ossdev->ds_caps.dwMinSecondarySampleRate = DSBFREQUENCY_MIN;
    ossdev->ds_caps.dwMaxSecondarySampleRate = DSBFREQUENCY_MAX;
786

787 788 789 790 791 792 793 794 795 796
    /* We must first set the format and the stereo mode as some sound cards
     * may support 44kHz mono but not 44kHz stereo. Also we must
     * systematically check the return value of these ioctls as they will
     * always succeed (see OSS Linux) but will modify the parameter to match
     * whatever they support. The OSS specs also say we must first set the
     * sample size, then the stereo and then the sample rate.
     */
    for (f=0;f<2;f++) {
        arg=win_std_oss_fmts[f];
        rc=ioctl(ossdev->fd, SNDCTL_DSP_SAMPLESIZE, &arg);
797
        if (rc!=0 || arg!=win_std_oss_fmts[f]) {
798
            TRACE("DSP_SAMPLESIZE: rc=%d returned %d for %d\n",
799
                  rc,arg,win_std_oss_fmts[f]);
800
            continue;
801
        }
802
	if (f == 0)
803 804 805
	    ossdev->ds_caps.dwFlags |= DSCAPS_PRIMARY8BIT;
	else if (f == 1)
	    ossdev->ds_caps.dwFlags |= DSCAPS_PRIMARY16BIT;
806

807
        for (c = 1; c <= MAX_CHANNELS; c++) {
808
            arg=c;
809
            rc=ioctl(ossdev->fd, SNDCTL_DSP_CHANNELS, &arg);
810
            if( rc == -1) break;
811
            if (rc!=0 || arg!=c) {
812
                TRACE("DSP_CHANNELS: rc=%d returned %d for %d\n",rc,arg,c);
813
                continue;
814
            }
815
	    if (c == 1) {
816
		ossdev->ds_caps.dwFlags |= DSCAPS_PRIMARYMONO;
817 818
	    } else if (c == 2) {
                ossdev->out_caps.wChannels = 2;
819 820
                if (has_mixer)
                    ossdev->out_caps.dwSupport|=WAVECAPS_LRVOLUME;
821
		ossdev->ds_caps.dwFlags |= DSCAPS_PRIMARYSTEREO;
822 823
            } else
                ossdev->out_caps.wChannels = c;
824 825 826 827 828

            for (r=0;r<sizeof(win_std_rates)/sizeof(*win_std_rates);r++) {
                arg=win_std_rates[r];
                rc=ioctl(ossdev->fd, SNDCTL_DSP_SPEED, &arg);
                TRACE("DSP_SPEED: rc=%d returned %d for %dx%dx%d\n",
829 830 831
                      rc,arg,win_std_rates[r],win_std_oss_fmts[f],c);
                if (rc==0 && arg!=0 && NEAR_MATCH(arg,win_std_rates[r]) && c < 3)
                    ossdev->out_caps.dwFormats|=win_std_formats[f][c-1][r];
832 833
            }
        }
834
    }
835 836

    if (ioctl(ossdev->fd, SNDCTL_DSP_GETCAPS, &arg) == 0) {
837 838
        if (arg & DSP_CAP_TRIGGER)
            ossdev->bTriggerSupport = TRUE;
839 840 841 842 843
        if ((arg & DSP_CAP_REALTIME) && !(arg & DSP_CAP_BATCH)) {
            ossdev->out_caps.dwSupport |= WAVECAPS_SAMPLEACCURATE;
        }
        /* well, might as well use the DirectSound cap flag for something */
        if ((arg & DSP_CAP_TRIGGER) && (arg & DSP_CAP_MMAP) &&
844
            !(arg & DSP_CAP_BATCH)) {
845
            ossdev->out_caps.dwSupport |= WAVECAPS_DIRECTSOUND;
846 847 848
	} else {
	    ossdev->ds_caps.dwFlags |= DSCAPS_EMULDRIVER;
	}
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
#ifdef DSP_CAP_MULTI    /* not every oss has this */
        /* check for hardware secondary buffer support (multi open) */
        if ((arg & DSP_CAP_MULTI) &&
            (ossdev->out_caps.dwSupport & WAVECAPS_DIRECTSOUND)) {
            TRACE("hardware secondary buffer support available\n");

            ossdev->ds_caps.dwMaxHwMixingAllBuffers = 16;
            ossdev->ds_caps.dwMaxHwMixingStaticBuffers = 0;
            ossdev->ds_caps.dwMaxHwMixingStreamingBuffers = 16;

            ossdev->ds_caps.dwFreeHwMixingAllBuffers = 16;
            ossdev->ds_caps.dwFreeHwMixingStaticBuffers = 0;
            ossdev->ds_caps.dwFreeHwMixingStreamingBuffers = 16;
        }
#endif
864
    }
865
    OSS_CloseDevice(ossdev);
866
    TRACE("out wChannels = %d, dwFormats = %08X, dwSupport = %08X\n",
867 868
          ossdev->out_caps.wChannels, ossdev->out_caps.dwFormats,
          ossdev->out_caps.dwSupport);
869
    return TRUE;
870
}
871

872 873 874 875 876
/******************************************************************
 *		OSS_WaveInInit
 *
 *
 */
877
static BOOL OSS_WaveInInit(OSS_DEVICE* ossdev)
878
{
879
    int rc,arg;
880 881
    int f,c;
    unsigned int r;
882
    TRACE("(%p) %s\n", ossdev, ossdev->dev_name);
883

884
    if (OSS_OpenDevice(ossdev, O_RDONLY, NULL, 0,-1,-1,-1) != 0)
885
        return FALSE;
886

887
    ioctl(ossdev->fd, SNDCTL_DSP_RESET, 0);
888

889 890 891 892 893 894 895
#if defined(SNDCTL_MIXERINFO)
    {
        int mixer;
        if ((mixer = open(ossdev->mixer_name, O_RDONLY|O_NDELAY)) >= 0) {
            oss_mixerinfo info;
            info.dev = 0;
            if (ioctl(mixer, SNDCTL_MIXERINFO, &info) >= 0) {
896
                MultiByteToWideChar(CP_UNIXCP, 0, info.name, -1,
897 898 899 900 901 902 903 904 905 906 907 908
                                    ossdev->in_caps.szPname,
                                    sizeof(ossdev->in_caps.szPname) / sizeof(WCHAR));
                TRACE("%s: %s\n", ossdev->mixer_name, ossdev->ds_desc.szDesc);
            } else {
                WARN("%s: cannot read SNDCTL_MIXERINFO!\n", ossdev->mixer_name);
            }
            close(mixer);
        } else {
            WARN("open(%s) failed (%s)\n", ossdev->mixer_name, strerror(errno));
        }
    }
#elif defined(SOUND_MIXER_INFO)
Alexandre Julliard's avatar
Alexandre Julliard committed
909 910 911 912 913
    {
        int mixer;
        if ((mixer = open(ossdev->mixer_name, O_RDONLY|O_NDELAY)) >= 0) {
            mixer_info info;
            if (ioctl(mixer, SOUND_MIXER_INFO, &info) >= 0) {
914
                MultiByteToWideChar(CP_UNIXCP, 0, info.name, -1,
915 916
                                    ossdev->in_caps.szPname, 
                                    sizeof(ossdev->in_caps.szPname) / sizeof(WCHAR));
917
                TRACE("%s: %s\n", ossdev->mixer_name, ossdev->ds_desc.szDesc);
Alexandre Julliard's avatar
Alexandre Julliard committed
918
            } else {
919 920 921 922 923
                /* FreeBSD up to at least 5.2 provides this ioctl, but does not
                 * implement it properly, and there are probably similar issues
                 * on other platforms, so we warn but try to go ahead.
                 */
                WARN("%s: cannot read SOUND_MIXER_INFO!\n", ossdev->mixer_name);
Alexandre Julliard's avatar
Alexandre Julliard committed
924
            }
925
            close(mixer);
Alexandre Julliard's avatar
Alexandre Julliard committed
926
        } else {
927
            WARN("open(%s) failed (%s)\n", ossdev->mixer_name, strerror(errno));
Alexandre Julliard's avatar
Alexandre Julliard committed
928
        }
929
    }
930
#endif /* SOUND_MIXER_INFO */
931

932 933 934
    if (WINE_TRACE_ON(wave))
        OSS_Info(ossdev->fd);

935 936
    ossdev->in_caps.wMid = 0x00FF; /* Manufac ID */
    ossdev->in_caps.wPid = 0x0001; /* Product ID */
937

938
    ossdev->in_caps.dwFormats = 0x00000000;
939 940
    ossdev->in_caps.wChannels = 1;
    ossdev->in_caps.wReserved1 = 0;
941

942 943 944 945 946 947
    /* direct sound caps */
    ossdev->dsc_caps.dwSize = sizeof(ossdev->dsc_caps);
    ossdev->dsc_caps.dwFlags = 0;
    ossdev->dsc_caps.dwFormats = 0x00000000;
    ossdev->dsc_caps.dwChannels = 1;

948
    /* See the comment in OSS_WaveOutInit for the loop order */
949 950 951
    for (f=0;f<2;f++) {
        arg=win_std_oss_fmts[f];
        rc=ioctl(ossdev->fd, SNDCTL_DSP_SAMPLESIZE, &arg);
952 953 954
        if (rc!=0 || arg!=win_std_oss_fmts[f]) {
            TRACE("DSP_SAMPLESIZE: rc=%d returned 0x%x for 0x%x\n",
                  rc,arg,win_std_oss_fmts[f]);
955
            continue;
956
        }
957

958
        for (c = 1; c <= MAX_CHANNELS; c++) {
959
            arg=c;
960
            rc=ioctl(ossdev->fd, SNDCTL_DSP_CHANNELS, &arg);
961
            if( rc == -1) break;
962
            if (rc!=0 || arg!=c) {
963
                TRACE("DSP_CHANNELS: rc=%d returned %d for %d\n",rc,arg,c);
964
                continue;
965
            }
966 967 968
            if (c > 1) {
                ossdev->in_caps.wChannels = c;
    		ossdev->dsc_caps.dwChannels = c;
969 970 971 972 973
            }

            for (r=0;r<sizeof(win_std_rates)/sizeof(*win_std_rates);r++) {
                arg=win_std_rates[r];
                rc=ioctl(ossdev->fd, SNDCTL_DSP_SPEED, &arg);
974 975 976 977
                TRACE("DSP_SPEED: rc=%d returned %d for %dx%dx%d\n",rc,arg,win_std_rates[r],win_std_oss_fmts[f],c);
                if (rc==0 && NEAR_MATCH(arg,win_std_rates[r]) && c < 3)
                    ossdev->in_caps.dwFormats|=win_std_formats[f][c-1][r];
		    ossdev->dsc_caps.dwFormats|=win_std_formats[f][c-1][r];
978 979
            }
        }
980
    }
981 982 983 984

    if (ioctl(ossdev->fd, SNDCTL_DSP_GETCAPS, &arg) == 0) {
        if (arg & DSP_CAP_TRIGGER)
            ossdev->bTriggerSupport = TRUE;
985
        if ((arg & DSP_CAP_TRIGGER) && (arg & DSP_CAP_MMAP) &&
986 987 988
            !(arg & DSP_CAP_BATCH)) {
	    /* FIXME: enable the next statement if you want to work on the driver */
#if 0
989
            ossdev->in_caps_support |= WAVECAPS_DIRECTSOUND;
990 991
#endif
	}
992 993
	if ((arg & DSP_CAP_REALTIME) && !(arg & DSP_CAP_BATCH))
	    ossdev->in_caps_support |= WAVECAPS_SAMPLEACCURATE;
994
    }
995
    OSS_CloseDevice(ossdev);
996
    TRACE("in wChannels = %d, dwFormats = %08X, in_caps_support = %08X\n",
997
        ossdev->in_caps.wChannels, ossdev->in_caps.dwFormats, ossdev->in_caps_support);
998
    return TRUE;
999
}
1000

1001 1002 1003 1004 1005
/******************************************************************
 *		OSS_WaveFullDuplexInit
 *
 *
 */
1006
static void OSS_WaveFullDuplexInit(OSS_DEVICE* ossdev)
1007
{
1008
    int rc,arg;
1009 1010
    int f,c;
    unsigned int r;
1011
    int caps;
1012
    BOOL has_mixer = FALSE;
1013 1014
    TRACE("(%p) %s\n", ossdev, ossdev->dev_name);

1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
    /* The OSS documentation says we must call SNDCTL_SETDUPLEX
     * *before* checking for SNDCTL_DSP_GETCAPS otherwise we may
     * get the wrong result. This ioctl must even be done before
     * setting the fragment size so that only OSS_RawOpenDevice is
     * in a position to do it. So we set full_duplex speculatively
     * and adjust right after.
     */
    ossdev->full_duplex=1;
    rc=OSS_OpenDevice(ossdev, O_RDWR, NULL, 0,-1,-1,-1);
    ossdev->full_duplex=0;
    if (rc != 0)
1026 1027 1028
        return;

    ioctl(ossdev->fd, SNDCTL_DSP_RESET, 0);
1029

1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
#if defined(SNDCTL_MIXERINFO)
    {
        int mixer;
        if ((mixer = open(ossdev->mixer_name, O_RDWR|O_NDELAY)) >= 0) {
            oss_mixerinfo info;
            info.dev = 0;
            if (ioctl(mixer, SNDCTL_MIXERINFO, &info) >= 0) {
                has_mixer = TRUE;
            } else {
                WARN("%s: cannot read SNDCTL_MIXERINFO!\n", ossdev->mixer_name);
            }
            close(mixer);
        } else {
            WARN("open(%s) failed (%s)\n", ossdev->mixer_name , strerror(errno));
        }
    }
#elif defined(SOUND_MIXER_INFO)
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
    {
        int mixer;
        if ((mixer = open(ossdev->mixer_name, O_RDWR|O_NDELAY)) >= 0) {
            mixer_info info;
            if (ioctl(mixer, SOUND_MIXER_INFO, &info) >= 0) {
                has_mixer = TRUE;
            } else {
                /* FreeBSD up to at least 5.2 provides this ioctl, but does not
                 * implement it properly, and there are probably similar issues
                 * on other platforms, so we warn but try to go ahead.
                 */
                WARN("%s: cannot read SOUND_MIXER_INFO!\n", ossdev->mixer_name);
            }
            close(mixer);
        } else {
            WARN("open(%s) failed (%s)\n", ossdev->mixer_name , strerror(errno));
        }
    }
#endif /* SOUND_MIXER_INFO */

1067 1068
    TRACE("%s\n", ossdev->ds_desc.szDesc);

1069 1070 1071
    if (ioctl(ossdev->fd, SNDCTL_DSP_GETCAPS, &caps) == 0)
        ossdev->full_duplex = (caps & DSP_CAP_DUPLEX);

1072 1073 1074 1075
    ossdev->duplex_out_caps = ossdev->out_caps;

    ossdev->duplex_out_caps.wChannels = 1;
    ossdev->duplex_out_caps.dwFormats = 0x00000000;
1076
    ossdev->duplex_out_caps.dwSupport = has_mixer ? WAVECAPS_VOLUME : 0;
1077

1078 1079
    if (WINE_TRACE_ON(wave))
        OSS_Info(ossdev->fd);
1080

1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
    /* See the comment in OSS_WaveOutInit for the loop order */
    for (f=0;f<2;f++) {
        arg=win_std_oss_fmts[f];
        rc=ioctl(ossdev->fd, SNDCTL_DSP_SAMPLESIZE, &arg);
        if (rc!=0 || arg!=win_std_oss_fmts[f]) {
            TRACE("DSP_SAMPLESIZE: rc=%d returned 0x%x for 0x%x\n",
                  rc,arg,win_std_oss_fmts[f]);
            continue;
        }

1091
        for (c = 1; c <= MAX_CHANNELS; c++) {
1092
            arg=c;
1093
            rc=ioctl(ossdev->fd, SNDCTL_DSP_CHANNELS, &arg);
1094
            if( rc == -1) break;
1095
            if (rc!=0 || arg!=c) {
1096
                TRACE("DSP_CHANNELS: rc=%d returned %d for %d\n",rc,arg,c);
1097 1098
                continue;
            }
1099
	    if (c == 1) {
1100
		ossdev->ds_caps.dwFlags |= DSCAPS_PRIMARYMONO;
1101 1102
	    } else if (c == 2) {
                ossdev->duplex_out_caps.wChannels = 2;
1103 1104
                if (has_mixer)
                    ossdev->duplex_out_caps.dwSupport|=WAVECAPS_LRVOLUME;
1105
		ossdev->ds_caps.dwFlags |= DSCAPS_PRIMARYSTEREO;
1106 1107
            } else
                ossdev->duplex_out_caps.wChannels = c;
1108

1109 1110 1111 1112
            for (r=0;r<sizeof(win_std_rates)/sizeof(*win_std_rates);r++) {
                arg=win_std_rates[r];
                rc=ioctl(ossdev->fd, SNDCTL_DSP_SPEED, &arg);
                TRACE("DSP_SPEED: rc=%d returned %d for %dx%dx%d\n",
1113 1114 1115
                      rc,arg,win_std_rates[r],win_std_oss_fmts[f],c);
                if (rc==0 && arg!=0 && NEAR_MATCH(arg,win_std_rates[r]) && c < 3)
                    ossdev->duplex_out_caps.dwFormats|=win_std_formats[f][c-1][r];
1116 1117 1118
            }
        }
    }
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129

    if (ioctl(ossdev->fd, SNDCTL_DSP_GETCAPS, &arg) == 0) {
        if ((arg & DSP_CAP_REALTIME) && !(arg & DSP_CAP_BATCH)) {
            ossdev->duplex_out_caps.dwSupport |= WAVECAPS_SAMPLEACCURATE;
        }
        /* well, might as well use the DirectSound cap flag for something */
        if ((arg & DSP_CAP_TRIGGER) && (arg & DSP_CAP_MMAP) &&
            !(arg & DSP_CAP_BATCH)) {
            ossdev->duplex_out_caps.dwSupport |= WAVECAPS_DIRECTSOUND;
	}
    }
1130
    OSS_CloseDevice(ossdev);
1131
    TRACE("duplex wChannels = %d, dwFormats = %08X, dwSupport = %08X\n",
1132 1133 1134
          ossdev->duplex_out_caps.wChannels,
          ossdev->duplex_out_caps.dwFormats,
          ossdev->duplex_out_caps.dwSupport);
1135 1136
}

1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
static char* StrDup(const char* str, const char* def)
{
    char* dst;
    if (str==NULL)
        str=def;
    dst=HeapAlloc(GetProcessHeap(),0,strlen(str)+1);
    strcpy(dst, str);
    return dst;
}

1147 1148 1149 1150 1151
/******************************************************************
 *		OSS_WaveInit
 *
 * Initialize internal structures from OSS information
 */
1152
LRESULT OSS_WaveInit(void)
1153
{
1154
    char* str;
1155
    unsigned int i;
1156

1157 1158
    /* FIXME: Remove unneeded members of WOutDev and WInDev */
    TRACE("()\n");
1159

1160 1161
    str=getenv("AUDIODEV");
    if (str!=NULL)
1162
    {
1163 1164
        WOutDev[0].ossdev.dev_name = WInDev[0].ossdev.dev_name = StrDup(str,"");
        WOutDev[0].ossdev.mixer_name = WInDev[0].ossdev.mixer_name = StrDup(getenv("MIXERDEV"),"/dev/mixer");
1165 1166
        for (i = 1; i < MAX_WAVEDRV; ++i)
        {
1167 1168
            WOutDev[i].ossdev.dev_name = WInDev[i].ossdev.dev_name = StrDup("",NULL);
            WOutDev[i].ossdev.mixer_name = WInDev[i].ossdev.mixer_name = StrDup("",NULL);
1169 1170 1171 1172
        }
    }
    else
    {
1173 1174
        WOutDev[0].ossdev.dev_name = WInDev[0].ossdev.dev_name = StrDup("/dev/dsp",NULL);
        WOutDev[0].ossdev.mixer_name = WInDev[0].ossdev.mixer_name = StrDup("/dev/mixer",NULL);
1175 1176
        for (i = 1; i < MAX_WAVEDRV; ++i)
        {
1177
            WOutDev[i].ossdev.dev_name = WInDev[i].ossdev.dev_name = HeapAlloc(GetProcessHeap(),0,11);
1178
            sprintf(WOutDev[i].ossdev.dev_name, "/dev/dsp%u", i);
1179
            WOutDev[i].ossdev.mixer_name = WInDev[i].ossdev.mixer_name = HeapAlloc(GetProcessHeap(),0,13);
1180
            sprintf(WOutDev[i].ossdev.mixer_name, "/dev/mixer%u", i);
1181 1182
        }
    }
1183

1184 1185
    for (i = 0; i < MAX_WAVEDRV; ++i)
    {
1186 1187 1188
        WOutDev[i].ossdev.interface_name = WInDev[i].ossdev.interface_name =
            HeapAlloc(GetProcessHeap(),0,9+strlen(WOutDev[i].ossdev.dev_name)+1);
        sprintf(WOutDev[i].ossdev.interface_name, "wineoss: %s", WOutDev[i].ossdev.dev_name);
1189
    }
1190

Robert Reif's avatar
Robert Reif committed
1191
    /* start with output devices */
1192
    for (i = 0; i < MAX_WAVEDRV; ++i)
1193
    {
1194
        if (*WOutDev[i].ossdev.dev_name == '\0' || OSS_WaveOutInit(&WOutDev[i].ossdev))
1195 1196
        {
            WOutDev[numOutDev].state = WINE_WS_CLOSED;
1197
            WOutDev[numOutDev].volume = 0xffffffff;
1198 1199 1200
            numOutDev++;
        }
    }
1201

Robert Reif's avatar
Robert Reif committed
1202
    /* then do input devices */
1203
    for (i = 0; i < MAX_WAVEDRV; ++i)
1204
    {
1205
        if (*WInDev[i].ossdev.dev_name=='\0' || OSS_WaveInInit(&WInDev[i].ossdev))
1206 1207 1208 1209 1210
        {
            WInDev[numInDev].state = WINE_WS_CLOSED;
            numInDev++;
        }
    }
1211 1212 1213

    /* finish with the full duplex bits */
    for (i = 0; i < MAX_WAVEDRV; i++)
1214 1215
        if (*WOutDev[i].ossdev.dev_name!='\0')
            OSS_WaveFullDuplexInit(&WOutDev[i].ossdev);
1216

1217 1218
    TRACE("%d wave out devices\n", numOutDev);
    for (i = 0; i < numOutDev; i++) {
1219
        TRACE("%u: %s, %s, %s\n", i, WOutDev[i].ossdev.dev_name,
1220
              WOutDev[i].ossdev.mixer_name, WOutDev[i].ossdev.interface_name);
1221 1222 1223 1224
    }

    TRACE("%d wave in devices\n", numInDev);
    for (i = 0; i < numInDev; i++) {
1225
        TRACE("%u: %s, %s, %s\n", i, WInDev[i].ossdev.dev_name,
1226
              WInDev[i].ossdev.mixer_name, WInDev[i].ossdev.interface_name);
1227 1228
    }

1229 1230 1231
    return 0;
}

1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
/******************************************************************
 *		OSS_WaveExit
 *
 * Delete/clear internal structures of OSS information
 */
LRESULT OSS_WaveExit(void)
{
    int i;
    TRACE("()\n");

    for (i = 0; i < MAX_WAVEDRV; ++i)
    {
1244 1245 1246
        HeapFree(GetProcessHeap(), 0, WOutDev[i].ossdev.dev_name);
        HeapFree(GetProcessHeap(), 0, WOutDev[i].ossdev.mixer_name);
        HeapFree(GetProcessHeap(), 0, WOutDev[i].ossdev.interface_name);
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
    }

    ZeroMemory(WOutDev, sizeof(WOutDev));
    ZeroMemory(WInDev, sizeof(WInDev));

    numOutDev = 0;
    numInDev = 0;

    return 0;
}

Eric Pouech's avatar
Eric Pouech committed
1258 1259 1260 1261 1262
/******************************************************************
 *		OSS_InitRingMessage
 *
 * Initialize the ring of messages for passing between driver's caller and playback/record
 * thread
Alexandre Julliard's avatar
Alexandre Julliard committed
1263
 */
1264 1265 1266 1267
static int OSS_InitRingMessage(OSS_MSG_RING* omr)
{
    omr->msg_toget = 0;
    omr->msg_tosave = 0;
1268 1269 1270 1271 1272 1273 1274
#ifdef USE_PIPE_SYNC
    if (pipe(omr->msg_pipe) < 0) {
	omr->msg_pipe[0] = -1;
	omr->msg_pipe[1] = -1;
	ERR("could not create pipe, error=%s\n", strerror(errno));
    }
#else
1275
    omr->msg_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1276
#endif
1277 1278
    omr->ring_buffer_size = OSS_RING_BUFFER_INCREMENT;
    omr->messages = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,omr->ring_buffer_size * sizeof(OSS_MSG));
1279
    InitializeCriticalSection(&omr->msg_crst);
1280
    omr->msg_crst.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": OSS_MSG_RING.msg_crst");
1281 1282 1283
    return 0;
}

1284 1285 1286 1287 1288 1289
/******************************************************************
 *		OSS_DestroyRingMessage
 *
 */
static int OSS_DestroyRingMessage(OSS_MSG_RING* omr)
{
1290 1291 1292 1293
#ifdef USE_PIPE_SYNC
    close(omr->msg_pipe[0]);
    close(omr->msg_pipe[1]);
#else
1294
    CloseHandle(omr->msg_event);
1295
#endif
1296
    HeapFree(GetProcessHeap(),0,omr->messages);
1297
    omr->msg_crst.DebugInfo->Spare[0] = 0;
1298 1299 1300 1301
    DeleteCriticalSection(&omr->msg_crst);
    return 0;
}

Eric Pouech's avatar
Eric Pouech committed
1302 1303 1304
/******************************************************************
 *		OSS_AddRingMessage
 *
Austin English's avatar
Austin English committed
1305
 * Inserts a new message into the ring (should be called from DriverProc derived routines)
Eric Pouech's avatar
Eric Pouech committed
1306 1307
 */
static int OSS_AddRingMessage(OSS_MSG_RING* omr, enum win_wm_message msg, DWORD param, BOOL wait)
1308
{
1309
    HANDLE	hEvent = INVALID_HANDLE_VALUE;
1310 1311

    EnterCriticalSection(&omr->msg_crst);
1312
    if ((omr->msg_toget == ((omr->msg_tosave + 1) % omr->ring_buffer_size)))
1313
    {
1314
	int old_ring_buffer_size = omr->ring_buffer_size;
1315 1316 1317
	omr->ring_buffer_size += OSS_RING_BUFFER_INCREMENT;
	TRACE("omr->ring_buffer_size=%d\n",omr->ring_buffer_size);
	omr->messages = HeapReAlloc(GetProcessHeap(),0,omr->messages, omr->ring_buffer_size * sizeof(OSS_MSG));
1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
	/* Now we need to rearrange the ring buffer so that the new
	   buffers just allocated are in between omr->msg_tosave and
	   omr->msg_toget.
	*/
	if (omr->msg_tosave < omr->msg_toget)
	{
	    memmove(&(omr->messages[omr->msg_toget + OSS_RING_BUFFER_INCREMENT]),
		    &(omr->messages[omr->msg_toget]),
		    sizeof(OSS_MSG)*(old_ring_buffer_size - omr->msg_toget)
		    );
	    omr->msg_toget += OSS_RING_BUFFER_INCREMENT;
	}
1330
    }
1331 1332
    if (wait)
    {
1333
        hEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
1334 1335 1336 1337 1338 1339 1340
        if (hEvent == INVALID_HANDLE_VALUE)
        {
            ERR("can't create event !?\n");
            LeaveCriticalSection(&omr->msg_crst);
            return 0;
        }
        if (omr->msg_toget != omr->msg_tosave && omr->messages[omr->msg_toget].msg != WINE_WM_HEADER)
1341 1342 1343
            FIXME("two fast messages in the queue!!!! toget = %d(%s), tosave=%d(%s)\n",
            omr->msg_toget,getCmdString(omr->messages[omr->msg_toget].msg),
            omr->msg_tosave,getCmdString(omr->messages[omr->msg_tosave].msg));
1344

1345
        /* fast messages have to be added at the start of the queue */
1346
        omr->msg_toget = (omr->msg_toget + omr->ring_buffer_size - 1) % omr->ring_buffer_size;
1347 1348 1349 1350 1351
        omr->messages[omr->msg_toget].msg = msg;
        omr->messages[omr->msg_toget].param = param;
        omr->messages[omr->msg_toget].hEvent = hEvent;
    }
    else
1352
    {
1353 1354 1355
        omr->messages[omr->msg_tosave].msg = msg;
        omr->messages[omr->msg_tosave].param = param;
        omr->messages[omr->msg_tosave].hEvent = INVALID_HANDLE_VALUE;
1356
        omr->msg_tosave = (omr->msg_tosave + 1) % omr->ring_buffer_size;
1357
    }
1358 1359
    LeaveCriticalSection(&omr->msg_crst);
    /* signal a new message */
1360
    SIGNAL_OMR(omr);
1361 1362
    if (wait)
    {
1363
        /* wait for playback/record thread to have processed the message */
1364 1365
        WaitForSingleObject(hEvent, INFINITE);
        CloseHandle(hEvent);
1366 1367 1368 1369
    }
    return 1;
}

Eric Pouech's avatar
Eric Pouech committed
1370 1371 1372 1373 1374
/******************************************************************
 *		OSS_RetrieveRingMessage
 *
 * Get a message from the ring. Should be called by the playback/record thread.
 */
1375
static int OSS_RetrieveRingMessage(OSS_MSG_RING* omr,
1376
                                   enum win_wm_message *msg, DWORD_PTR *param, HANDLE *hEvent)
1377 1378 1379 1380 1381 1382 1383 1384
{
    EnterCriticalSection(&omr->msg_crst);

    if (omr->msg_toget == omr->msg_tosave) /* buffer empty ? */
    {
        LeaveCriticalSection(&omr->msg_crst);
	return 0;
    }
1385

1386 1387 1388 1389
    *msg = omr->messages[omr->msg_toget].msg;
    omr->messages[omr->msg_toget].msg = 0;
    *param = omr->messages[omr->msg_toget].param;
    *hEvent = omr->messages[omr->msg_toget].hEvent;
1390
    omr->msg_toget = (omr->msg_toget + 1) % omr->ring_buffer_size;
1391
    CLEAR_OMR(omr);
1392 1393 1394 1395
    LeaveCriticalSection(&omr->msg_crst);
    return 1;
}

1396 1397 1398 1399 1400 1401 1402 1403
/******************************************************************
 *              OSS_PeekRingMessage
 *
 * Peek at a message from the ring but do not remove it.
 * Should be called by the playback/record thread.
 */
static int OSS_PeekRingMessage(OSS_MSG_RING* omr,
                               enum win_wm_message *msg,
1404
                               DWORD_PTR *param, HANDLE *hEvent)
1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420
{
    EnterCriticalSection(&omr->msg_crst);

    if (omr->msg_toget == omr->msg_tosave) /* buffer empty ? */
    {
	LeaveCriticalSection(&omr->msg_crst);
	return 0;
    }

    *msg = omr->messages[omr->msg_toget].msg;
    *param = omr->messages[omr->msg_toget].param;
    *hEvent = omr->messages[omr->msg_toget].hEvent;
    LeaveCriticalSection(&omr->msg_crst);
    return 1;
}

1421
/*======================================================================*
1422
 *                  Low level WAVE OUT implementation			*
1423 1424 1425
 *======================================================================*/

/**************************************************************************
Eric Pouech's avatar
Eric Pouech committed
1426
 * 			wodNotifyClient			[internal]
1427
 */
1428
static DWORD wodNotifyClient(WINE_WAVEOUT* wwo, WORD wMsg, DWORD_PTR dwParam1, DWORD_PTR dwParam2)
1429
{
1430
    TRACE("wMsg = 0x%04x (%s) dwParm1 = %04lx dwParam2 = %04lx\n", wMsg,
1431 1432
        wMsg == WOM_OPEN ? "WOM_OPEN" : wMsg == WOM_CLOSE ? "WOM_CLOSE" :
        wMsg == WOM_DONE ? "WOM_DONE" : "Unknown", dwParam1, dwParam2);
1433

Eric Pouech's avatar
Eric Pouech committed
1434 1435 1436 1437
    switch (wMsg) {
    case WOM_OPEN:
    case WOM_CLOSE:
    case WOM_DONE:
1438
	if (wwo->wFlags != DCB_NULL &&
1439 1440 1441
	    !DriverCallback(wwo->waveDesc.dwCallback, wwo->wFlags,
			    (HDRVR)wwo->waveDesc.hWave, wMsg,
			    wwo->waveDesc.dwInstance, dwParam1, dwParam2)) {
Eric Pouech's avatar
Eric Pouech committed
1442 1443 1444 1445 1446
	    WARN("can't notify client !\n");
	    return MMSYSERR_ERROR;
	}
	break;
    default:
1447
	FIXME("Unknown callback message %u\n", wMsg);
Eric Pouech's avatar
Eric Pouech committed
1448
        return MMSYSERR_INVALPARAM;
1449
    }
Eric Pouech's avatar
Eric Pouech committed
1450
    return MMSYSERR_NOERROR;
1451 1452
}

Eric Pouech's avatar
Eric Pouech committed
1453 1454 1455 1456
/**************************************************************************
 * 				wodUpdatePlayedTotal	[internal]
 *
 */
1457
static BOOL wodUpdatePlayedTotal(WINE_WAVEOUT* wwo, audio_buf_info* info)
Eric Pouech's avatar
Eric Pouech committed
1458
{
1459
    audio_buf_info dspspace;
1460
    DWORD notplayed;
1461 1462
    if (!info) info = &dspspace;

1463 1464
    if (ioctl(wwo->ossdev.fd, SNDCTL_DSP_GETOSPACE, info) < 0) {
        ERR("ioctl(%s, SNDCTL_DSP_GETOSPACE) failed (%s)\n", wwo->ossdev.dev_name, strerror(errno));
1465 1466
        return FALSE;
    }
1467 1468

    /* GETOSPACE is not always accurate when we're down to the last fragment or two;
1469
    **   we try to accommodate that here by assuming that the dsp is empty by looking
1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481
    **   at the clock rather than the result of GETOSPACE */
    notplayed = wwo->dwBufferSize - info->bytes;
    if (notplayed > 0 && notplayed < (info->fragsize * 2))
    {
        if (wwo->dwProjectedFinishTime && GetTickCount() >= wwo->dwProjectedFinishTime)
        {
            TRACE("Adjusting for a presumed OSS bug and assuming all data has been played.\n");
            wwo->dwPlayedTotal = wwo->dwWrittenTotal;
            return TRUE;
        }
        else
            /* Some OSS drivers will clean up nicely if given a POST, so give 'em the chance... */
1482
            ioctl(wwo->ossdev.fd, SNDCTL_DSP_POST, 0);
1483 1484 1485
    }

    wwo->dwPlayedTotal = wwo->dwWrittenTotal - notplayed;
1486
    return TRUE;
Eric Pouech's avatar
Eric Pouech committed
1487
}
1488 1489 1490 1491 1492 1493 1494 1495

/**************************************************************************
 * 				wodPlayer_BeginWaveHdr          [internal]
 *
 * Makes the specified lpWaveHdr the currently playing wave header.
 * If the specified wave header is a begin loop and we're not already in
 * a loop, setup the loop.
 */
Eric Pouech's avatar
Eric Pouech committed
1496
static void wodPlayer_BeginWaveHdr(WINE_WAVEOUT* wwo, LPWAVEHDR lpWaveHdr)
1497
{
Eric Pouech's avatar
Eric Pouech committed
1498
    wwo->lpPlayPtr = lpWaveHdr;
1499

Eric Pouech's avatar
Eric Pouech committed
1500
    if (!lpWaveHdr) return;
1501 1502 1503 1504 1505

    if (lpWaveHdr->dwFlags & WHDR_BEGINLOOP) {
	if (wwo->lpLoopPtr) {
	    WARN("Already in a loop. Discarding loop on this header (%p)\n", lpWaveHdr);
	} else {
1506
            TRACE("Starting loop (%dx) with %p\n", lpWaveHdr->dwLoops, lpWaveHdr);
1507 1508 1509 1510
	    wwo->lpLoopPtr = lpWaveHdr;
	    /* Windows does not touch WAVEHDR.dwLoops,
	     * so we need to make an internal copy */
	    wwo->dwLoops = lpWaveHdr->dwLoops;
1511
	}
1512
    }
Eric Pouech's avatar
Eric Pouech committed
1513
    wwo->dwPartialOffset = 0;
1514 1515 1516 1517 1518 1519 1520 1521 1522
}

/**************************************************************************
 * 				wodPlayer_PlayPtrNext	        [internal]
 *
 * Advance the play pointer to the next waveheader, looping if required.
 */
static LPWAVEHDR wodPlayer_PlayPtrNext(WINE_WAVEOUT* wwo)
{
Eric Pouech's avatar
Eric Pouech committed
1523
    LPWAVEHDR lpWaveHdr = wwo->lpPlayPtr;
1524

Eric Pouech's avatar
Eric Pouech committed
1525
    wwo->dwPartialOffset = 0;
1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538
    if ((lpWaveHdr->dwFlags & WHDR_ENDLOOP) && wwo->lpLoopPtr) {
	/* We're at the end of a loop, loop if required */
	if (--wwo->dwLoops > 0) {
	    wwo->lpPlayPtr = wwo->lpLoopPtr;
	} else {
	    /* Handle overlapping loops correctly */
	    if (wwo->lpLoopPtr != lpWaveHdr && (lpWaveHdr->dwFlags & WHDR_BEGINLOOP)) {
		FIXME("Correctly handled case ? (ending loop buffer also starts a new loop)\n");
		/* shall we consider the END flag for the closing loop or for
		 * the opening one or for both ???
		 * code assumes for closing loop only
		 */
	    } else {
Eric Pouech's avatar
Eric Pouech committed
1539 1540 1541 1542
                lpWaveHdr = lpWaveHdr->lpNext;
            }
            wwo->lpLoopPtr = NULL;
            wodPlayer_BeginWaveHdr(wwo, lpWaveHdr);
1543
	}
1544 1545
    } else {
	/* We're not in a loop.  Advance to the next wave header */
Eric Pouech's avatar
Eric Pouech committed
1546
	wodPlayer_BeginWaveHdr(wwo, lpWaveHdr = lpWaveHdr->lpNext);
1547
    }
Eric Pouech's avatar
Eric Pouech committed
1548

1549 1550
    return lpWaveHdr;
}
1551

1552 1553 1554 1555 1556 1557 1558 1559 1560 1561
/**************************************************************************
 * 			     wodPlayer_TicksTillEmpty		[internal]
 * Returns the number of ticks until we think the DSP should be empty
 */
static DWORD wodPlayer_TicksTillEmpty(const WINE_WAVEOUT *wwo)
{
    return ((wwo->dwWrittenTotal - wwo->dwPlayedTotal) * 1000)
        / wwo->waveFormat.Format.nAvgBytesPerSec;
}

1562 1563
/**************************************************************************
 * 			     wodPlayer_DSPWait			[internal]
1564
 * Returns the number of milliseconds to wait for the DSP buffer to write
1565
 * one fragment.
1566
 */
1567
static DWORD wodPlayer_DSPWait(const WINE_WAVEOUT *wwo)
1568
{
1569
    /* time for one fragment to be played */
1570
    return wwo->dwFragmentSize * 1000 / wwo->waveFormat.Format.nAvgBytesPerSec;
1571 1572 1573 1574 1575 1576 1577 1578 1579
}

/**************************************************************************
 * 			     wodPlayer_NotifyWait               [internal]
 * Returns the number of milliseconds to wait before attempting to notify
 * completion of the specified wavehdr.
 * This is based on the number of bytes remaining to be written in the
 * wave.
 */
Eric Pouech's avatar
Eric Pouech committed
1580
static DWORD wodPlayer_NotifyWait(const WINE_WAVEOUT* wwo, LPWAVEHDR lpWaveHdr)
1581 1582
{
    DWORD dwMillis;
1583

Eric Pouech's avatar
Eric Pouech committed
1584 1585
    if (lpWaveHdr->reserved < wwo->dwPlayedTotal) {
	dwMillis = 1;
1586
    } else {
1587
	dwMillis = (lpWaveHdr->reserved - wwo->dwPlayedTotal) * 1000 / wwo->waveFormat.Format.nAvgBytesPerSec;
Eric Pouech's avatar
Eric Pouech committed
1588
	if (!dwMillis) dwMillis = 1;
1589
    }
1590

1591 1592
    return dwMillis;
}
1593

1594

1595 1596 1597
/**************************************************************************
 * 			     wodPlayer_WriteMaxFrags            [internal]
 * Writes the maximum number of bytes possible to the DSP and returns
1598
 * TRUE iff the current playPtr has been fully played
1599
 */
1600
static BOOL wodPlayer_WriteMaxFrags(WINE_WAVEOUT* wwo, DWORD* bytes)
1601
{
1602 1603 1604 1605
    DWORD       dwLength = wwo->lpPlayPtr->dwBufferLength - wwo->dwPartialOffset;
    DWORD       toWrite = min(dwLength, *bytes);
    int         written;
    BOOL        ret = FALSE;
Eric Pouech's avatar
Eric Pouech committed
1606

1607
    TRACE("Writing wavehdr %p.%u[%u]/%u\n",
1608 1609 1610 1611
          wwo->lpPlayPtr, wwo->dwPartialOffset, wwo->lpPlayPtr->dwBufferLength, toWrite);

    if (toWrite > 0)
    {
1612
        written = write(wwo->ossdev.fd, wwo->lpPlayPtr->lpData + wwo->dwPartialOffset, toWrite);
1613
        if (written <= 0) {
1614
            TRACE("write(%s, %p, %d) failed (%s) returned %d\n", wwo->ossdev.dev_name,
1615 1616 1617
                wwo->lpPlayPtr->lpData + wwo->dwPartialOffset, toWrite, strerror(errno), written);
            return FALSE;
        }
1618 1619 1620
    }
    else
        written = 0;
Eric Pouech's avatar
Eric Pouech committed
1621 1622 1623 1624

    if (written >= dwLength) {
        /* If we wrote all current wavehdr, skip to the next one */
        wodPlayer_PlayPtrNext(wwo);
1625
        ret = TRUE;
Eric Pouech's avatar
Eric Pouech committed
1626 1627 1628
    } else {
        /* Remove the amount written */
        wwo->dwPartialOffset += written;
1629
    }
Eric Pouech's avatar
Eric Pouech committed
1630 1631
    *bytes -= written;
    wwo->dwWrittenTotal += written;
1632
    TRACE("dwWrittenTotal=%u\n", wwo->dwWrittenTotal);
1633
    return ret;
1634 1635
}

1636

1637
/**************************************************************************
1638
 * 				wodPlayer_NotifyCompletions	[internal]
1639
 *
1640 1641 1642 1643
 * Notifies and remove from queue all wavehdrs which have been played to
 * the speaker (ie. they have cleared the OSS buffer).  If force is true,
 * we notify all wavehdrs and remove them all from the queue even if they
 * are unplayed or part of a loop.
1644
 */
Eric Pouech's avatar
Eric Pouech committed
1645
static DWORD wodPlayer_NotifyCompletions(WINE_WAVEOUT* wwo, BOOL force)
1646 1647
{
    LPWAVEHDR		lpWaveHdr;
1648

1649 1650 1651 1652 1653
    /* Start from lpQueuePtr and keep notifying until:
     * - we hit an unwritten wavehdr
     * - we hit the beginning of a running loop
     * - we hit a wavehdr which hasn't finished playing
     */
1654 1655 1656
#if 0
    while ((lpWaveHdr = wwo->lpQueuePtr) && 
           (force || 
Eric Pouech's avatar
Eric Pouech committed
1657 1658 1659
            (lpWaveHdr != wwo->lpPlayPtr &&
             lpWaveHdr != wwo->lpLoopPtr &&
             lpWaveHdr->reserved <= wwo->dwPlayedTotal))) {
1660

1661 1662
	wwo->lpQueuePtr = lpWaveHdr->lpNext;

1663 1664 1665
	lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
	lpWaveHdr->dwFlags |= WHDR_DONE;

Eric Pouech's avatar
Eric Pouech committed
1666
	wodNotifyClient(wwo, WOM_DONE, (DWORD)lpWaveHdr, 0);
1667
    }
1668 1669 1670 1671 1672 1673 1674 1675 1676
#else
    for (;;)
    {
        lpWaveHdr = wwo->lpQueuePtr;
        if (!lpWaveHdr) {TRACE("Empty queue\n"); break;}
        if (!force)
        {
            if (lpWaveHdr == wwo->lpPlayPtr) {TRACE("play %p\n", lpWaveHdr); break;}
            if (lpWaveHdr == wwo->lpLoopPtr) {TRACE("loop %p\n", lpWaveHdr); break;}
1677
            if (lpWaveHdr->reserved > wwo->dwPlayedTotal) {TRACE("still playing %p (%lu/%u)\n", lpWaveHdr, lpWaveHdr->reserved, wwo->dwPlayedTotal);break;}
1678 1679 1680 1681 1682 1683
        }
	wwo->lpQueuePtr = lpWaveHdr->lpNext;

	lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
	lpWaveHdr->dwFlags |= WHDR_DONE;

1684
	wodNotifyClient(wwo, WOM_DONE, (DWORD_PTR)lpWaveHdr, 0);
1685 1686 1687
    }
#endif
    return  (lpWaveHdr && lpWaveHdr != wwo->lpPlayPtr && lpWaveHdr != wwo->lpLoopPtr) ? 
Eric Pouech's avatar
Eric Pouech committed
1688
        wodPlayer_NotifyWait(wwo, lpWaveHdr) : INFINITE;
1689 1690
}

1691 1692 1693 1694 1695
/**************************************************************************
 * 				wodPlayer_Reset			[internal]
 *
 * wodPlayer helper. Resets current output stream.
 */
Eric Pouech's avatar
Eric Pouech committed
1696
static	void	wodPlayer_Reset(WINE_WAVEOUT* wwo, BOOL reset)
1697
{
1698
    wodUpdatePlayedTotal(wwo, NULL);
1699
    /* updates current notify list */
Eric Pouech's avatar
Eric Pouech committed
1700
    wodPlayer_NotifyCompletions(wwo, FALSE);
1701 1702

    /* flush all possible output */
1703
    if (OSS_ResetDevice(&wwo->ossdev) != MMSYSERR_NOERROR)
1704
    {
1705 1706 1707 1708 1709 1710
	wwo->hThread = 0;
	wwo->state = WINE_WS_STOPPED;
	ExitThread(-1);
    }

    if (reset) {
1711
        enum win_wm_message	msg;
1712
        DWORD_PTR	        param;
1713 1714 1715
        HANDLE		        ev;

	/* remove any buffer */
Eric Pouech's avatar
Eric Pouech committed
1716
	wodPlayer_NotifyCompletions(wwo, TRUE);
1717 1718

	wwo->lpPlayPtr = wwo->lpQueuePtr = wwo->lpLoopPtr = NULL;
1719
	wwo->state = WINE_WS_STOPPED;
1720 1721 1722
	wwo->dwPlayedTotal = wwo->dwWrittenTotal = 0;
        /* Clear partial wavehdr */
        wwo->dwPartialOffset = 0;
1723 1724 1725 1726 1727 1728

        /* remove any existing message in the ring */
        EnterCriticalSection(&wwo->msgRing.msg_crst);
        /* return all pending headers in queue */
        while (OSS_RetrieveRingMessage(&wwo->msgRing, &msg, &param, &ev))
        {
1729
            if (msg != WINE_WM_HEADER)
1730 1731 1732 1733 1734 1735 1736 1737 1738 1739
            {
                FIXME("shouldn't have headers left\n");
                SetEvent(ev);
                continue;
            }
            ((LPWAVEHDR)param)->dwFlags &= ~WHDR_INQUEUE;
            ((LPWAVEHDR)param)->dwFlags |= WHDR_DONE;

            wodNotifyClient(wwo, WOM_DONE, param, 0);
        }
1740
        RESET_OMR(&wwo->msgRing);
1741
        LeaveCriticalSection(&wwo->msgRing.msg_crst);
1742
    } else {
1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763
        if (wwo->lpLoopPtr) {
            /* complicated case, not handled yet (could imply modifying the loop counter */
            FIXME("Pausing while in loop isn't correctly handled yet, except strange results\n");
            wwo->lpPlayPtr = wwo->lpLoopPtr;
            wwo->dwPartialOffset = 0;
            wwo->dwWrittenTotal = wwo->dwPlayedTotal; /* this is wrong !!! */
        } else {
            LPWAVEHDR   ptr;
            DWORD       sz = wwo->dwPartialOffset;

            /* reset all the data as if we had written only up to lpPlayedTotal bytes */
            /* compute the max size playable from lpQueuePtr */
            for (ptr = wwo->lpQueuePtr; ptr != wwo->lpPlayPtr; ptr = ptr->lpNext) {
                sz += ptr->dwBufferLength;
            }
            /* because the reset lpPlayPtr will be lpQueuePtr */
            if (wwo->dwWrittenTotal > wwo->dwPlayedTotal + sz) ERR("grin\n");
            wwo->dwPartialOffset = sz - (wwo->dwWrittenTotal - wwo->dwPlayedTotal);
            wwo->dwWrittenTotal = wwo->dwPlayedTotal;
            wwo->lpPlayPtr = wwo->lpQueuePtr;
        }
1764 1765 1766 1767
	wwo->state = WINE_WS_PAUSED;
    }
}

1768 1769 1770
/**************************************************************************
 * 		      wodPlayer_ProcessMessages			[internal]
 */
Eric Pouech's avatar
Eric Pouech committed
1771
static void wodPlayer_ProcessMessages(WINE_WAVEOUT* wwo)
1772
{
1773
    LPWAVEHDR           lpWaveHdr;
Eric Pouech's avatar
Eric Pouech committed
1774
    enum win_wm_message	msg;
1775
    DWORD_PTR		param;
1776
    HANDLE		ev;
1777

1778
    while (OSS_RetrieveRingMessage(&wwo->msgRing, &msg, &param, &ev)) {
1779
	TRACE("Received %s %lx\n", getCmdString(msg), param);
1780 1781
	switch (msg) {
	case WINE_WM_PAUSING:
Eric Pouech's avatar
Eric Pouech committed
1782
	    wodPlayer_Reset(wwo, FALSE);
1783
	    SetEvent(ev);
1784 1785
	    break;
	case WINE_WM_RESTARTING:
1786
            if (wwo->state == WINE_WS_PAUSED)
1787 1788 1789
            {
                wwo->state = WINE_WS_PLAYING;
            }
1790
	    SetEvent(ev);
1791 1792 1793
	    break;
	case WINE_WM_HEADER:
	    lpWaveHdr = (LPWAVEHDR)param;
1794

1795
	    /* insert buffer at the end of queue */
1796
	    {
1797 1798 1799
		LPWAVEHDR*	wh;
		for (wh = &(wwo->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
		*wh = lpWaveHdr;
1800
	    }
Eric Pouech's avatar
Eric Pouech committed
1801 1802
            if (!wwo->lpPlayPtr)
                wodPlayer_BeginWaveHdr(wwo,lpWaveHdr);
1803 1804 1805 1806
	    if (wwo->state == WINE_WS_STOPPED)
		wwo->state = WINE_WS_PLAYING;
	    break;
	case WINE_WM_RESETTING:
Eric Pouech's avatar
Eric Pouech committed
1807
	    wodPlayer_Reset(wwo, TRUE);
1808
	    SetEvent(ev);
1809
	    break;
Eric Pouech's avatar
Eric Pouech committed
1810
        case WINE_WM_UPDATE:
1811
            wodUpdatePlayedTotal(wwo, NULL);
Eric Pouech's avatar
Eric Pouech committed
1812 1813 1814 1815 1816 1817 1818 1819 1820
	    SetEvent(ev);
            break;
        case WINE_WM_BREAKLOOP:
            if (wwo->state == WINE_WS_PLAYING && wwo->lpLoopPtr != NULL) {
                /* ensure exit at end of current loop */
                wwo->dwLoops = 1;
            }
	    SetEvent(ev);
            break;
1821 1822 1823 1824 1825
	case WINE_WM_CLOSING:
	    /* sanity check: this should not happen since the device must have been reset before */
	    if (wwo->lpQueuePtr || wwo->lpPlayPtr) ERR("out of sync\n");
	    wwo->hThread = 0;
	    wwo->state = WINE_WS_CLOSED;
1826
	    SetEvent(ev);
1827 1828 1829 1830 1831
	    ExitThread(0);
	    /* shouldn't go here */
	default:
	    FIXME("unknown message %d\n", msg);
	    break;
1832
	}
1833 1834
    }
}
1835

1836 1837 1838 1839 1840
/**************************************************************************
 * 			     wodPlayer_FeedDSP			[internal]
 * Feed as much sound data as we can into the DSP and return the number of
 * milliseconds before it will be necessary to feed the DSP again.
 */
Eric Pouech's avatar
Eric Pouech committed
1841
static DWORD wodPlayer_FeedDSP(WINE_WAVEOUT* wwo)
1842 1843
{
    audio_buf_info dspspace;
Eric Pouech's avatar
Eric Pouech committed
1844
    DWORD       availInQ;
1845

1846
    if (!wodUpdatePlayedTotal(wwo, &dspspace)) return INFINITE;
1847
    availInQ = dspspace.bytes;
Eric Pouech's avatar
Eric Pouech committed
1848
    TRACE("fragments=%d/%d, fragsize=%d, bytes=%d\n",
1849
	  dspspace.fragments, dspspace.fragstotal, dspspace.fragsize, dspspace.bytes);
1850

Eric Pouech's avatar
Eric Pouech committed
1851
    /* no more room... no need to try to feed */
1852 1853 1854 1855 1856
    if (dspspace.fragments != 0) {
        /* Feed from partial wavehdr */
        if (wwo->lpPlayPtr && wwo->dwPartialOffset != 0) {
            wodPlayer_WriteMaxFrags(wwo, &availInQ);
        }
1857

1858
        /* Feed wavehdrs until we run out of wavehdrs or DSP space */
1859 1860
        if (wwo->dwPartialOffset == 0 && wwo->lpPlayPtr) {
            do {
1861
                TRACE("Setting time to elapse for %p to %u\n",
1862
                      wwo->lpPlayPtr, wwo->dwWrittenTotal + wwo->lpPlayPtr->dwBufferLength);
1863 1864
                /* note the value that dwPlayedTotal will return when this wave finishes playing */
                wwo->lpPlayPtr->reserved = wwo->dwWrittenTotal + wwo->lpPlayPtr->dwBufferLength;
1865
            } while (wodPlayer_WriteMaxFrags(wwo, &availInQ) && wwo->lpPlayPtr && availInQ > 0);
1866
        }
1867 1868 1869 1870 1871

        if (wwo->bNeedPost) {
            /* OSS doesn't start before it gets either 2 fragments or a SNDCTL_DSP_POST;
             * if it didn't get one, we give it the other */
            if (wwo->dwBufferSize < availInQ + 2 * wwo->dwFragmentSize)
1872
                ioctl(wwo->ossdev.fd, SNDCTL_DSP_POST, 0);
1873 1874
            wwo->bNeedPost = FALSE;
        }
1875 1876
    }

1877
    return wodPlayer_DSPWait(wwo);
1878 1879 1880 1881 1882 1883 1884 1885
}


/**************************************************************************
 * 				wodPlayer			[internal]
 */
static	DWORD	CALLBACK	wodPlayer(LPVOID pmt)
{
1886
    WORD	  uDevID = (DWORD_PTR)pmt;
1887
    WINE_WAVEOUT* wwo = &WOutDev[uDevID];
Eric Pouech's avatar
Eric Pouech committed
1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899
    DWORD         dwNextFeedTime = INFINITE;   /* Time before DSP needs feeding */
    DWORD         dwNextNotifyTime = INFINITE; /* Time before next wave completion */
    DWORD         dwSleepTime;

    wwo->state = WINE_WS_STOPPED;
    SetEvent(wwo->hStartUpEvent);

    for (;;) {
        /** Wait for the shortest time before an action is required.  If there
         *  are no pending actions, wait forever for a command.
         */
        dwSleepTime = min(dwNextFeedTime, dwNextNotifyTime);
1900
        TRACE("waiting %ums (%u,%u)\n", dwSleepTime, dwNextFeedTime, dwNextNotifyTime);
1901
	WAIT_OMR(&wwo->msgRing, dwSleepTime);
Eric Pouech's avatar
Eric Pouech committed
1902 1903 1904
	wodPlayer_ProcessMessages(wwo);
	if (wwo->state == WINE_WS_PLAYING) {
	    dwNextFeedTime = wodPlayer_FeedDSP(wwo);
1905 1906 1907 1908 1909
            if (dwNextFeedTime != INFINITE)
                wwo->dwProjectedFinishTime = GetTickCount() + wodPlayer_TicksTillEmpty(wwo);
            else
                wwo->dwProjectedFinishTime = 0;

Eric Pouech's avatar
Eric Pouech committed
1910
	    dwNextNotifyTime = wodPlayer_NotifyCompletions(wwo, FALSE);
1911 1912 1913 1914 1915 1916
	    if (dwNextFeedTime == INFINITE) {
		/* FeedDSP ran out of data, but before flushing, */
		/* check that a notification didn't give us more */
		wodPlayer_ProcessMessages(wwo);
		if (!wwo->lpPlayPtr) {
		    TRACE("flushing\n");
1917
		    ioctl(wwo->ossdev.fd, SNDCTL_DSP_SYNC, 0);
1918
		    wwo->dwPlayedTotal = wwo->dwWrittenTotal;
1919 1920
                    dwNextNotifyTime = wodPlayer_NotifyCompletions(wwo, FALSE);
		} else {
1921 1922 1923 1924
		    TRACE("recovering\n");
		    dwNextFeedTime = wodPlayer_FeedDSP(wwo);
		}
	    }
1925
	} else {
Eric Pouech's avatar
Eric Pouech committed
1926
	    dwNextFeedTime = dwNextNotifyTime = INFINITE;
1927
	}
1928
    }
1929 1930

    return 0;
1931 1932
}

Alexandre Julliard's avatar
Alexandre Julliard committed
1933
/**************************************************************************
Alexandre Julliard's avatar
Alexandre Julliard committed
1934 1935
 * 			wodGetDevCaps				[internal]
 */
1936
static DWORD wodGetDevCaps(WORD wDevID, LPWAVEOUTCAPSW lpCaps, DWORD dwSize)
Alexandre Julliard's avatar
Alexandre Julliard committed
1937
{
1938
    TRACE("(%u, %p, %u);\n", wDevID, lpCaps, dwSize);
1939

1940 1941 1942 1943
    if (lpCaps == NULL) {
        WARN("not enabled\n");
        return MMSYSERR_NOTENABLED;
    }
1944

1945
    if (wDevID >= numOutDev) {
1946
	WARN("numOutDev reached !\n");
1947 1948 1949
	return MMSYSERR_BADDEVICEID;
    }

1950 1951
    if (WOutDev[wDevID].ossdev.open_access == O_RDWR)
        memcpy(lpCaps, &WOutDev[wDevID].ossdev.duplex_out_caps, min(dwSize, sizeof(*lpCaps)));
1952
    else
1953
        memcpy(lpCaps, &WOutDev[wDevID].ossdev.out_caps, min(dwSize, sizeof(*lpCaps)));
1954

1955
    return MMSYSERR_NOERROR;
Alexandre Julliard's avatar
Alexandre Julliard committed
1956 1957 1958
}

/**************************************************************************
Alexandre Julliard's avatar
Alexandre Julliard committed
1959 1960
 * 				wodOpen				[internal]
 */
1961
static DWORD wodOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
Alexandre Julliard's avatar
Alexandre Julliard committed
1962
{
1963
    int			audio_fragment;
1964
    WINE_WAVEOUT*	wwo;
1965
    audio_buf_info      info;
1966
    DWORD               ret;
1967

1968
    TRACE("(%u, %p[cb=%08lx], %08X);\n", wDevID, lpDesc, lpDesc->dwCallback, dwFlags);
1969
    if (lpDesc == NULL) {
1970
	WARN("Invalid Parameter !\n");
1971 1972
	return MMSYSERR_INVALPARAM;
    }
1973
    if (wDevID >= numOutDev) {
1974
	TRACE("MAX_WAVOUTDRV reached !\n");
1975
	return MMSYSERR_BADDEVICEID;
1976
    }
1977

Eric Pouech's avatar
Eric Pouech committed
1978
    /* only PCM format is supported so far... */
1979
    if (!supportedFormat(lpDesc->lpFormat)) {
1980
	WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
Eric Pouech's avatar
Eric Pouech committed
1981 1982 1983 1984 1985
	     lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
	     lpDesc->lpFormat->nSamplesPerSec);
	return WAVERR_BADFORMAT;
    }

1986
    if (dwFlags & WAVE_FORMAT_QUERY) {
1987
	TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
1988 1989
	     lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
	     lpDesc->lpFormat->nSamplesPerSec);
Eric Pouech's avatar
Eric Pouech committed
1990
	return MMSYSERR_NOERROR;
1991
    }
Eric Pouech's avatar
Eric Pouech committed
1992

1993
    TRACE("OSS_OpenDevice requested this format: %dx%dx%d %s\n",
1994 1995
          lpDesc->lpFormat->nSamplesPerSec,
          lpDesc->lpFormat->wBitsPerSample,
1996 1997 1998 1999
          lpDesc->lpFormat->nChannels,
          lpDesc->lpFormat->wFormatTag == WAVE_FORMAT_PCM ? "WAVE_FORMAT_PCM" :
          lpDesc->lpFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? "WAVE_FORMAT_EXTENSIBLE" :
          "UNSUPPORTED");
2000

2001 2002
    wwo = &WOutDev[wDevID];

2003
    if ((dwFlags & WAVE_DIRECTSOUND) &&
2004
        !(wwo->ossdev.duplex_out_caps.dwSupport & WAVECAPS_DIRECTSOUND))
2005 2006
	/* not supported, ignore it */
	dwFlags &= ~WAVE_DIRECTSOUND;
2007 2008

    if (dwFlags & WAVE_DIRECTSOUND) {
2009
        if (wwo->ossdev.duplex_out_caps.dwSupport & WAVECAPS_SAMPLEACCURATE)
2010 2011 2012 2013 2014 2015 2016
	    /* we have realtime DirectSound, fragments just waste our time,
	     * but a large buffer is good, so choose 64KB (32 * 2^11) */
	    audio_fragment = 0x0020000B;
	else
	    /* to approximate realtime, we must use small fragments,
	     * let's try to fragment the above 64KB (256 * 2^8) */
	    audio_fragment = 0x01000008;
2017
    } else {
2018 2019
	/* A wave device must have a worst case latency of 10 ms so calculate
	 * the largest fragment size less than 10 ms long.
2020
	 */
2021 2022 2023 2024 2025 2026
	int	fsize = lpDesc->lpFormat->nAvgBytesPerSec / 100;	/* 10 ms chunk */
	int	shift = 0;
	while ((1 << shift) <= fsize)
	    shift++;
	shift--;
	audio_fragment = 0x00100000 + shift;	/* 16 fragments of 2^shift */
2027
    }
2028

2029
    TRACE("requesting %d %d byte fragments (%d ms/fragment)\n",
2030
        audio_fragment >> 16, 1 << (audio_fragment & 0xffff),
2031 2032
	((1 << (audio_fragment & 0xffff)) * 1000) / lpDesc->lpFormat->nAvgBytesPerSec);

2033 2034 2035 2036 2037
    if (wwo->state != WINE_WS_CLOSED) {
        WARN("already allocated\n");
        return MMSYSERR_ALLOCATED;
    }

2038 2039
    /* we want to be able to mmap() the device, which means it must be opened readable,
     * otherwise mmap() will fail (at least under Linux) */
2040
    ret = OSS_OpenDevice(&wwo->ossdev,
2041
                         (dwFlags & WAVE_DIRECTSOUND) ? O_RDWR : O_WRONLY,
2042 2043 2044
                         &audio_fragment,
                         (dwFlags & WAVE_DIRECTSOUND) ? 0 : 1,
                         lpDesc->lpFormat->nSamplesPerSec,
2045
                         lpDesc->lpFormat->nChannels,
2046
                         (lpDesc->lpFormat->wBitsPerSample == 16)
2047
                             ? AFMT_S16_LE : AFMT_U8);
2048
    if ((ret==MMSYSERR_NOERROR) && (dwFlags & WAVE_DIRECTSOUND)) {
2049 2050 2051
        lpDesc->lpFormat->nSamplesPerSec=wwo->ossdev.sample_rate;
        lpDesc->lpFormat->nChannels=wwo->ossdev.channels;
        lpDesc->lpFormat->wBitsPerSample=(wwo->ossdev.format == AFMT_U8 ? 8 : 16);
2052 2053
        lpDesc->lpFormat->nBlockAlign=lpDesc->lpFormat->nChannels*lpDesc->lpFormat->wBitsPerSample/8;
        lpDesc->lpFormat->nAvgBytesPerSec=lpDesc->lpFormat->nSamplesPerSec*lpDesc->lpFormat->nBlockAlign;
2054
        TRACE("OSS_OpenDevice returned this format: %dx%dx%d\n",
2055 2056 2057 2058
              lpDesc->lpFormat->nSamplesPerSec,
              lpDesc->lpFormat->wBitsPerSample,
              lpDesc->lpFormat->nChannels);
    }
2059
    if (ret != 0) return ret;
2060
    wwo->state = WINE_WS_STOPPED;
2061 2062 2063

    wwo->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);

2064
    wwo->waveDesc = *lpDesc;
2065
    copy_format(lpDesc->lpFormat, &wwo->waveFormat);
2066

2067
    if (wwo->waveFormat.Format.wBitsPerSample == 0) {
2068
	WARN("Resetting zeroed wBitsPerSample\n");
2069 2070 2071 2072
	wwo->waveFormat.Format.wBitsPerSample = 8 *
	    (wwo->waveFormat.Format.nAvgBytesPerSec /
	     wwo->waveFormat.Format.nSamplesPerSec) /
	    wwo->waveFormat.Format.nChannels;
2073
    }
2074
    /* Read output space info for future reference */
2075 2076 2077
    if (ioctl(wwo->ossdev.fd, SNDCTL_DSP_GETOSPACE, &info) < 0) {
	ERR("ioctl(%s, SNDCTL_DSP_GETOSPACE) failed (%s)\n", wwo->ossdev.dev_name, strerror(errno));
        OSS_CloseDevice(&wwo->ossdev);
2078
	wwo->state = WINE_WS_CLOSED;
2079 2080
	return MMSYSERR_NOTENABLED;
    }
2081

2082
    TRACE("got %d %d byte fragments (%d ms/fragment)\n", info.fragstotal,
2083 2084
        info.fragsize, (info.fragsize * 1000) / (wwo->ossdev.sample_rate *
        wwo->ossdev.channels * (wwo->ossdev.format == AFMT_U8 ? 1 : 2)));
2085

2086 2087
    /* Check that fragsize is correct per our settings above */
    if ((info.fragsize > 1024) && (LOWORD(audio_fragment) <= 10)) {
2088 2089
        /* we've tried to set 1K fragments or less, but it didn't work */
        WARN("fragment size set failed, size is now %d\n", info.fragsize);
2090
    }
Eric Pouech's avatar
Eric Pouech committed
2091

2092 2093 2094
    /* Remember fragsize and total buffer size for future use */
    wwo->dwFragmentSize = info.fragsize;
    wwo->dwBufferSize = info.fragstotal * info.fragsize;
Eric Pouech's avatar
Eric Pouech committed
2095 2096
    wwo->dwPlayedTotal = 0;
    wwo->dwWrittenTotal = 0;
2097
    wwo->bNeedPost = TRUE;
2098

2099
    TRACE("fd=%d fragstotal=%d fragsize=%d BufferSize=%d\n",
2100
          wwo->ossdev.fd, info.fragstotal, info.fragsize, wwo->dwBufferSize);
2101
    if (wwo->dwFragmentSize % wwo->waveFormat.Format.nBlockAlign) {
2102
        ERR("Fragment doesn't contain an integral number of data blocks fragsize=%d BlockAlign=%d\n",wwo->dwFragmentSize,wwo->waveFormat.Format.nBlockAlign);
2103 2104 2105 2106 2107
        /* Some SoundBlaster 16 cards return an incorrect (odd) fragment
         * size for 16 bit sound. This will cause a system crash when we try
         * to write just the specified odd number of bytes. So if we
         * detect something is wrong we'd better fix it.
         */
2108
        wwo->dwFragmentSize-=wwo->dwFragmentSize % wwo->waveFormat.Format.nBlockAlign;
2109 2110
    }

2111
    OSS_InitRingMessage(&wwo->msgRing);
2112

2113
    wwo->hStartUpEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
2114
    wwo->hThread = CreateThread(NULL, 0, wodPlayer, (LPVOID)(DWORD_PTR)wDevID, 0, &(wwo->dwThreadID));
2115 2116
    if (wwo->hThread)
        SetThreadPriority(wwo->hThread, THREAD_PRIORITY_TIME_CRITICAL);
2117 2118
    WaitForSingleObject(wwo->hStartUpEvent, INFINITE);
    CloseHandle(wwo->hStartUpEvent);
2119
    wwo->hStartUpEvent = INVALID_HANDLE_VALUE;
2120

2121
    TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%u, nSamplesPerSec=%u, nChannels=%u nBlockAlign=%u!\n",
2122 2123 2124
	  wwo->waveFormat.Format.wBitsPerSample, wwo->waveFormat.Format.nAvgBytesPerSec,
	  wwo->waveFormat.Format.nSamplesPerSec, wwo->waveFormat.Format.nChannels,
	  wwo->waveFormat.Format.nBlockAlign);
2125

Eric Pouech's avatar
Eric Pouech committed
2126
    return wodNotifyClient(wwo, WOM_OPEN, 0L, 0L);
Alexandre Julliard's avatar
Alexandre Julliard committed
2127 2128 2129
}

/**************************************************************************
Alexandre Julliard's avatar
Alexandre Julliard committed
2130 2131
 * 				wodClose			[internal]
 */
Alexandre Julliard's avatar
Alexandre Julliard committed
2132
static DWORD wodClose(WORD wDevID)
Alexandre Julliard's avatar
Alexandre Julliard committed
2133
{
2134 2135 2136
    DWORD		ret = MMSYSERR_NOERROR;
    WINE_WAVEOUT*	wwo;

2137
    TRACE("(%u);\n", wDevID);
2138

2139
    if (wDevID >= numOutDev || WOutDev[wDevID].state == WINE_WS_CLOSED) {
2140
	WARN("bad device ID !\n");
2141
	return MMSYSERR_BADDEVICEID;
2142
    }
2143

2144 2145
    wwo = &WOutDev[wDevID];
    if (wwo->lpQueuePtr) {
2146
	WARN("buffers still playing !\n");
2147 2148
	ret = WAVERR_STILLPLAYING;
    } else {
2149 2150
	if (wwo->hThread != INVALID_HANDLE_VALUE) {
	    OSS_AddRingMessage(&wwo->msgRing, WINE_WM_CLOSING, 0, TRUE);
2151
	}
2152

2153 2154
        OSS_DestroyRingMessage(&wwo->msgRing);

2155
        OSS_CloseDevice(&wwo->ossdev);
2156
	wwo->state = WINE_WS_CLOSED;
2157
	wwo->dwFragmentSize = 0;
Eric Pouech's avatar
Eric Pouech committed
2158
	ret = wodNotifyClient(wwo, WOM_CLOSE, 0L, 0L);
2159
    }
2160
    return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
2161 2162 2163
}

/**************************************************************************
Alexandre Julliard's avatar
Alexandre Julliard committed
2164
 * 				wodWrite			[internal]
2165
 *
Alexandre Julliard's avatar
Alexandre Julliard committed
2166 2167
 */
static DWORD wodWrite(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
Alexandre Julliard's avatar
Alexandre Julliard committed
2168
{
2169
    TRACE("(%u, %p, %08X);\n", wDevID, lpWaveHdr, dwSize);
2170

2171
    /* first, do the sanity checks... */
2172
    if (wDevID >= numOutDev || WOutDev[wDevID].state == WINE_WS_CLOSED) {
2173
        WARN("bad dev ID !\n");
2174
	return MMSYSERR_BADDEVICEID;
2175
    }
2176 2177

    if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
2178
	return WAVERR_UNPREPARED;
2179 2180

    if (lpWaveHdr->dwFlags & WHDR_INQUEUE)
2181
	return WAVERR_STILLPLAYING;
2182

2183 2184 2185 2186
    lpWaveHdr->dwFlags &= ~WHDR_DONE;
    lpWaveHdr->dwFlags |= WHDR_INQUEUE;
    lpWaveHdr->lpNext = 0;

2187
    if ((lpWaveHdr->dwBufferLength & (WOutDev[wDevID].waveFormat.Format.nBlockAlign - 1)) != 0)
2188
    {
2189
        WARN("WaveHdr length isn't a multiple of the PCM block size: %d %% %d\n",lpWaveHdr->dwBufferLength,WOutDev[wDevID].waveFormat.Format.nBlockAlign);
2190
        lpWaveHdr->dwBufferLength &= ~(WOutDev[wDevID].waveFormat.Format.nBlockAlign - 1);
2191 2192
    }

2193
    OSS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_HEADER, (DWORD_PTR)lpWaveHdr, FALSE);
2194

2195
    return MMSYSERR_NOERROR;
Alexandre Julliard's avatar
Alexandre Julliard committed
2196 2197
}

2198 2199 2200 2201 2202
/**************************************************************************
 * 			wodPause				[internal]
 */
static DWORD wodPause(WORD wDevID)
{
2203
    TRACE("(%u);!\n", wDevID);
2204

2205
    if (wDevID >= numOutDev || WOutDev[wDevID].state == WINE_WS_CLOSED) {
2206
	WARN("bad device ID !\n");
2207 2208
	return MMSYSERR_BADDEVICEID;
    }
2209

2210
    OSS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_PAUSING, 0, TRUE);
2211

2212
    return MMSYSERR_NOERROR;
Alexandre Julliard's avatar
Alexandre Julliard committed
2213 2214 2215
}

/**************************************************************************
Alexandre Julliard's avatar
Alexandre Julliard committed
2216 2217
 * 			wodRestart				[internal]
 */
Alexandre Julliard's avatar
Alexandre Julliard committed
2218
static DWORD wodRestart(WORD wDevID)
Alexandre Julliard's avatar
Alexandre Julliard committed
2219
{
2220
    TRACE("(%u);\n", wDevID);
2221

2222
    if (wDevID >= numOutDev || WOutDev[wDevID].state == WINE_WS_CLOSED) {
2223
	WARN("bad device ID !\n");
2224 2225
	return MMSYSERR_BADDEVICEID;
    }
2226

2227
    OSS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESTARTING, 0, TRUE);
2228

2229 2230
    /* FIXME: is NotifyClient with WOM_DONE right ? (Comet Busters 1.3.3 needs this notification) */
    /* FIXME: Myst crashes with this ... hmm -MM
Eric Pouech's avatar
Eric Pouech committed
2231
       return wodNotifyClient(wwo, WOM_DONE, 0L, 0L);
2232
    */
2233

2234
    return MMSYSERR_NOERROR;
Alexandre Julliard's avatar
Alexandre Julliard committed
2235 2236 2237
}

/**************************************************************************
Alexandre Julliard's avatar
Alexandre Julliard committed
2238 2239
 * 			wodReset				[internal]
 */
Alexandre Julliard's avatar
Alexandre Julliard committed
2240
static DWORD wodReset(WORD wDevID)
Alexandre Julliard's avatar
Alexandre Julliard committed
2241
{
2242
    TRACE("(%u);\n", wDevID);
2243

2244
    if (wDevID >= numOutDev || WOutDev[wDevID].state == WINE_WS_CLOSED) {
2245
	WARN("bad device ID !\n");
2246 2247
	return MMSYSERR_BADDEVICEID;
    }
2248

2249
    OSS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
2250

2251
    return MMSYSERR_NOERROR;
Alexandre Julliard's avatar
Alexandre Julliard committed
2252 2253 2254
}

/**************************************************************************
Alexandre Julliard's avatar
Alexandre Julliard committed
2255 2256
 * 				wodGetPosition			[internal]
 */
2257
static DWORD wodGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
Alexandre Julliard's avatar
Alexandre Julliard committed
2258
{
2259
    WINE_WAVEOUT*	wwo;
2260

2261
    TRACE("(%u, %p, %u);\n", wDevID, lpTime, uSize);
2262

2263
    if (wDevID >= numOutDev || WOutDev[wDevID].state == WINE_WS_CLOSED) {
2264
	WARN("bad device ID !\n");
2265
	return MMSYSERR_BADDEVICEID;
2266
    }
2267

2268 2269 2270 2271
    if (lpTime == NULL) {
	WARN("invalid parameter: lpTime == NULL\n");
	return MMSYSERR_INVALPARAM;
    }
2272

2273
    wwo = &WOutDev[wDevID];
2274
#ifdef EXACT_WODPOSITION
2275 2276
    if (wwo->ossdev.open_access == O_RDWR) {
        if (wwo->ossdev.duplex_out_caps.dwSupport & WAVECAPS_SAMPLEACCURATE)
2277 2278
	    OSS_AddRingMessage(&wwo->msgRing, WINE_WM_UPDATE, 0, TRUE);
    } else {
2279
        if (wwo->ossdev.out_caps.dwSupport & WAVECAPS_SAMPLEACCURATE)
2280 2281
	    OSS_AddRingMessage(&wwo->msgRing, WINE_WM_UPDATE, 0, TRUE);
    }
2282
#endif
2283

2284
    return bytes_to_mmtime(lpTime, wwo->dwPlayedTotal, &wwo->waveFormat);
Alexandre Julliard's avatar
Alexandre Julliard committed
2285 2286
}

Eric Pouech's avatar
Eric Pouech committed
2287 2288 2289 2290 2291 2292
/**************************************************************************
 * 				wodBreakLoop			[internal]
 */
static DWORD wodBreakLoop(WORD wDevID)
{
    TRACE("(%u);\n", wDevID);
2293

2294
    if (wDevID >= numOutDev || WOutDev[wDevID].state == WINE_WS_CLOSED) {
Eric Pouech's avatar
Eric Pouech committed
2295 2296 2297 2298 2299 2300
	WARN("bad device ID !\n");
	return MMSYSERR_BADDEVICEID;
    }
    OSS_AddRingMessage(&WOutDev[wDevID].msgRing, WINE_WM_BREAKLOOP, 0, TRUE);
    return MMSYSERR_NOERROR;
}
2301

Alexandre Julliard's avatar
Alexandre Julliard committed
2302
/**************************************************************************
Alexandre Julliard's avatar
Alexandre Julliard committed
2303 2304
 * 				wodGetVolume			[internal]
 */
Alexandre Julliard's avatar
Alexandre Julliard committed
2305
static DWORD wodGetVolume(WORD wDevID, LPDWORD lpdwVol)
Alexandre Julliard's avatar
Alexandre Julliard committed
2306
{
2307
    int		mixer;
2308 2309
    int		volume;
    DWORD	left, right;
2310
    DWORD	last_left, last_right;
2311

2312
    TRACE("(%u, %p);\n", wDevID, lpdwVol);
2313

2314 2315 2316 2317 2318
    if (lpdwVol == NULL) {
        WARN("not enabled\n");
        return MMSYSERR_NOTENABLED;
    }
    if (wDevID >= numOutDev) {
2319
        WARN("invalid parameter\n");
2320 2321
        return MMSYSERR_INVALPARAM;
    }
2322 2323
    if (WOutDev[wDevID].ossdev.open_access == O_RDWR) {
        if (!(WOutDev[wDevID].ossdev.duplex_out_caps.dwSupport & WAVECAPS_VOLUME)) {
2324 2325 2326 2327
            TRACE("Volume not supported\n");
            return MMSYSERR_NOTSUPPORTED;
        }
    } else {
2328
        if (!(WOutDev[wDevID].ossdev.out_caps.dwSupport & WAVECAPS_VOLUME)) {
2329 2330 2331 2332
            TRACE("Volume not supported\n");
            return MMSYSERR_NOTSUPPORTED;
        }
    }
2333

2334
    if ((mixer = open(WOutDev[wDevID].ossdev.mixer_name, O_RDONLY|O_NDELAY)) < 0) {
2335 2336
        WARN("mixer device not available !\n");
        return MMSYSERR_NOTENABLED;
2337 2338
    }
    if (ioctl(mixer, SOUND_MIXER_READ_PCM, &volume) == -1) {
2339
        close(mixer);
2340
        WARN("ioctl(%s, SOUND_MIXER_READ_PCM) failed (%s)\n",
2341
             WOutDev[wDevID].ossdev.mixer_name, strerror(errno));
2342
        return MMSYSERR_NOTENABLED;
2343 2344
    }
    close(mixer);
2345

2346 2347
    left = LOBYTE(volume);
    right = HIBYTE(volume);
2348
    TRACE("left=%d right=%d !\n", left, right);
2349 2350
    last_left  = (LOWORD(WOutDev[wDevID].volume) * 100) / 0xFFFFl;
    last_right = (HIWORD(WOutDev[wDevID].volume) * 100) / 0xFFFFl;
2351
    TRACE("last_left=%d last_right=%d !\n", last_left, last_right);
2352 2353 2354 2355
    if (last_left == left && last_right == right)
	*lpdwVol = WOutDev[wDevID].volume;
    else
	*lpdwVol = ((left * 0xFFFFl) / 100) + (((right * 0xFFFFl) / 100) << 16);
2356
    return MMSYSERR_NOERROR;
Alexandre Julliard's avatar
Alexandre Julliard committed
2357 2358
}

Alexandre Julliard's avatar
Alexandre Julliard committed
2359
/**************************************************************************
Alexandre Julliard's avatar
Alexandre Julliard committed
2360 2361
 * 				wodSetVolume			[internal]
 */
2362
DWORD wodSetVolume(WORD wDevID, DWORD dwParam)
Alexandre Julliard's avatar
Alexandre Julliard committed
2363
{
2364
    int		mixer;
2365
    int		volume;
2366 2367
    DWORD	left, right;

2368
    TRACE("(%u, %08X);\n", wDevID, dwParam);
2369 2370 2371 2372

    left  = (LOWORD(dwParam) * 100) / 0xFFFFl;
    right = (HIWORD(dwParam) * 100) / 0xFFFFl;
    volume = left + (right << 8);
2373

2374
    if (wDevID >= numOutDev) {
2375 2376
        WARN("invalid parameter: wDevID > %d\n", numOutDev);
        return MMSYSERR_INVALPARAM;
2377
    }
2378 2379
    if (WOutDev[wDevID].ossdev.open_access == O_RDWR) {
        if (!(WOutDev[wDevID].ossdev.duplex_out_caps.dwSupport & WAVECAPS_VOLUME)) {
2380 2381 2382 2383
            TRACE("Volume not supported\n");
            return MMSYSERR_NOTSUPPORTED;
        }
    } else {
2384
        if (!(WOutDev[wDevID].ossdev.out_caps.dwSupport & WAVECAPS_VOLUME)) {
2385 2386 2387 2388
            TRACE("Volume not supported\n");
            return MMSYSERR_NOTSUPPORTED;
        }
    }
2389 2390
    if ((mixer = open(WOutDev[wDevID].ossdev.mixer_name, O_WRONLY|O_NDELAY)) < 0) {
        WARN("open(%s) failed (%s)\n", WOutDev[wDevID].ossdev.mixer_name, strerror(errno));
2391
        return MMSYSERR_NOTENABLED;
2392
    }
Alexandre Julliard's avatar
Alexandre Julliard committed
2393
    if (ioctl(mixer, SOUND_MIXER_WRITE_PCM, &volume) == -1) {
2394
        close(mixer);
2395
        WARN("ioctl(%s, SOUND_MIXER_WRITE_PCM) failed (%s)\n",
2396
            WOutDev[wDevID].ossdev.mixer_name, strerror(errno));
2397
        return MMSYSERR_NOTENABLED;
2398
    }
2399
    TRACE("volume=%04x\n", (unsigned)volume);
2400
    close(mixer);
2401 2402 2403 2404

    /* save requested volume */
    WOutDev[wDevID].volume = dwParam;

2405
    return MMSYSERR_NOERROR;
Alexandre Julliard's avatar
Alexandre Julliard committed
2406 2407
}

Alexandre Julliard's avatar
Alexandre Julliard committed
2408
/**************************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
2409
 * 				wodMessage (WINEOSS.7)
Alexandre Julliard's avatar
Alexandre Julliard committed
2410
 */
2411 2412
DWORD WINAPI OSS_wodMessage(UINT wDevID, UINT wMsg, DWORD_PTR dwUser,
			    DWORD_PTR dwParam1, DWORD_PTR dwParam2)
Alexandre Julliard's avatar
Alexandre Julliard committed
2413
{
2414
    TRACE("(%u, %s, %08lX, %08lX, %08lX);\n",
2415
	  wDevID, getMessage(wMsg), dwUser, dwParam1, dwParam2);
2416

2417
    switch (wMsg) {
2418 2419 2420 2421 2422 2423
    case DRVM_INIT:
    case DRVM_EXIT:
    case DRVM_ENABLE:
    case DRVM_DISABLE:
	/* FIXME: Pretend this is supported */
	return 0;
2424 2425 2426 2427
    case WODM_OPEN:	 	return wodOpen		(wDevID, (LPWAVEOPENDESC)dwParam1,	dwParam2);
    case WODM_CLOSE:	 	return wodClose		(wDevID);
    case WODM_WRITE:	 	return wodWrite		(wDevID, (LPWAVEHDR)dwParam1,		dwParam2);
    case WODM_PAUSE:	 	return wodPause		(wDevID);
2428
    case WODM_GETPOS:	 	return wodGetPosition	(wDevID, (LPMMTIME)dwParam1, 		dwParam2);
Eric Pouech's avatar
Eric Pouech committed
2429
    case WODM_BREAKLOOP: 	return wodBreakLoop     (wDevID);
2430 2431
    case WODM_PREPARE:	 	return MMSYSERR_NOTSUPPORTED;
    case WODM_UNPREPARE: 	return MMSYSERR_NOTSUPPORTED;
2432
    case WODM_GETDEVCAPS:	return wodGetDevCaps	(wDevID, (LPWAVEOUTCAPSW)dwParam1,	dwParam2);
2433
    case WODM_GETNUMDEVS:	return numOutDev;
2434 2435 2436 2437 2438 2439 2440 2441
    case WODM_GETPITCH:	 	return MMSYSERR_NOTSUPPORTED;
    case WODM_SETPITCH:	 	return MMSYSERR_NOTSUPPORTED;
    case WODM_GETPLAYBACKRATE:	return MMSYSERR_NOTSUPPORTED;
    case WODM_SETPLAYBACKRATE:	return MMSYSERR_NOTSUPPORTED;
    case WODM_GETVOLUME:	return wodGetVolume	(wDevID, (LPDWORD)dwParam1);
    case WODM_SETVOLUME:	return wodSetVolume	(wDevID, dwParam1);
    case WODM_RESTART:		return wodRestart	(wDevID);
    case WODM_RESET:		return wodReset		(wDevID);
2442

2443 2444
    case DRV_QUERYDEVICEINTERFACESIZE: return wodDevInterfaceSize      (wDevID, (LPDWORD)dwParam1);
    case DRV_QUERYDEVICEINTERFACE:     return wodDevInterface          (wDevID, (PWCHAR)dwParam1, dwParam2);
2445 2446
    case DRV_QUERYDSOUNDIFACE:	return wodDsCreate	(wDevID, (PIDSDRIVER*)dwParam1);
    case DRV_QUERYDSOUNDDESC:	return wodDsDesc	(wDevID, (PDSDRIVERDESC)dwParam1);
2447
    default:
2448
	FIXME("unknown message %d!\n", wMsg);
2449 2450
    }
    return MMSYSERR_NOTSUPPORTED;
Alexandre Julliard's avatar
Alexandre Julliard committed
2451 2452
}

2453
/*======================================================================*
2454
 *                  Low level WAVE IN implementation			*
2455
 *======================================================================*/
Alexandre Julliard's avatar
Alexandre Julliard committed
2456

Eric Pouech's avatar
Eric Pouech committed
2457 2458 2459
/**************************************************************************
 * 			widNotifyClient			[internal]
 */
2460
static DWORD widNotifyClient(WINE_WAVEIN* wwi, WORD wMsg, DWORD_PTR dwParam1, DWORD_PTR dwParam2)
Eric Pouech's avatar
Eric Pouech committed
2461
{
2462
    TRACE("wMsg = 0x%04x (%s) dwParm1 = %04lx dwParam2 = %04lx\n", wMsg,
2463 2464
        wMsg == WIM_OPEN ? "WIM_OPEN" : wMsg == WIM_CLOSE ? "WIM_CLOSE" :
        wMsg == WIM_DATA ? "WIM_DATA" : "Unknown", dwParam1, dwParam2);
2465

Eric Pouech's avatar
Eric Pouech committed
2466 2467 2468 2469
    switch (wMsg) {
    case WIM_OPEN:
    case WIM_CLOSE:
    case WIM_DATA:
2470
	if (wwi->wFlags != DCB_NULL &&
2471 2472 2473
	    !DriverCallback(wwi->waveDesc.dwCallback, wwi->wFlags,
			    (HDRVR)wwi->waveDesc.hWave, wMsg,
			    wwi->waveDesc.dwInstance, dwParam1, dwParam2)) {
Eric Pouech's avatar
Eric Pouech committed
2474 2475 2476 2477 2478
	    WARN("can't notify client !\n");
	    return MMSYSERR_ERROR;
	}
	break;
    default:
2479
	FIXME("Unknown callback message %u\n", wMsg);
Eric Pouech's avatar
Eric Pouech committed
2480 2481 2482 2483 2484
	return MMSYSERR_INVALPARAM;
    }
    return MMSYSERR_NOERROR;
}

Alexandre Julliard's avatar
Alexandre Julliard committed
2485
/**************************************************************************
Alexandre Julliard's avatar
Alexandre Julliard committed
2486 2487
 * 			widGetDevCaps				[internal]
 */
2488
static DWORD widGetDevCaps(WORD wDevID, LPWAVEINCAPSW lpCaps, DWORD dwSize)
Alexandre Julliard's avatar
Alexandre Julliard committed
2489
{
2490
    TRACE("(%u, %p, %u);\n", wDevID, lpCaps, dwSize);
2491

2492
    if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
2493

2494 2495
    if (wDevID >= numInDev) {
	TRACE("numOutDev reached !\n");
2496
	return MMSYSERR_BADDEVICEID;
2497
    }
2498

2499
    memcpy(lpCaps, &WInDev[wDevID].ossdev.in_caps, min(dwSize, sizeof(*lpCaps)));
2500
    return MMSYSERR_NOERROR;
Alexandre Julliard's avatar
Alexandre Julliard committed
2501 2502
}

2503 2504 2505 2506 2507 2508
/**************************************************************************
 * 				widRecorder_ReadHeaders		[internal]
 */
static void widRecorder_ReadHeaders(WINE_WAVEIN * wwi)
{
    enum win_wm_message tmp_msg;
2509
    DWORD_PTR		tmp_param;
2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530
    HANDLE		tmp_ev;
    WAVEHDR*		lpWaveHdr;

    while (OSS_RetrieveRingMessage(&wwi->msgRing, &tmp_msg, &tmp_param, &tmp_ev)) {
        if (tmp_msg == WINE_WM_HEADER) {
	    LPWAVEHDR*	wh;
	    lpWaveHdr = (LPWAVEHDR)tmp_param;
	    lpWaveHdr->lpNext = 0;

	    if (wwi->lpQueuePtr == 0)
		wwi->lpQueuePtr = lpWaveHdr;
	    else {
	        for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
	        *wh = lpWaveHdr;
	    }
	} else {
            ERR("should only have headers left\n");
        }
    }
}

2531 2532 2533 2534 2535
/**************************************************************************
 * 				widRecorder			[internal]
 */
static	DWORD	CALLBACK	widRecorder(LPVOID pmt)
{
2536
    WORD		uDevID = (DWORD_PTR)pmt;
2537
    WINE_WAVEIN*	wwi = &WInDev[uDevID];
2538 2539 2540
    WAVEHDR*		lpWaveHdr;
    DWORD		dwSleepTime;
    DWORD		bytesRead;
Eric Pouech's avatar
Eric Pouech committed
2541
    LPVOID		buffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, wwi->dwFragmentSize);
2542
    char               *pOffset = buffer;
2543 2544
    audio_buf_info 	info;
    int 		xs;
Eric Pouech's avatar
Eric Pouech committed
2545
    enum win_wm_message msg;
2546
    DWORD_PTR		param;
2547
    HANDLE		ev;
2548
    int                 enable;
2549

2550 2551
    wwi->state = WINE_WS_STOPPED;
    wwi->dwTotalRecorded = 0;
2552
    wwi->dwTotalRead = 0;
2553
    wwi->lpQueuePtr = NULL;
2554

2555
    SetEvent(wwi->hStartUpEvent);
2556

2557
    /* disable input so capture will begin when triggered */
2558 2559 2560 2561
    wwi->ossdev.bInputEnabled = FALSE;
    enable = getEnables(&wwi->ossdev);
    if (ioctl(wwi->ossdev.fd, SNDCTL_DSP_SETTRIGGER, &enable) < 0)
	ERR("ioctl(%s, SNDCTL_DSP_SETTRIGGER) failed (%s)\n", wwi->ossdev.dev_name, strerror(errno));
2562

2563 2564 2565
    /* the soundblaster live needs a micro wake to get its recording started
     * (or GETISPACE will have 0 frags all the time)
     */
2566
    read(wwi->ossdev.fd, &xs, 4);
2567

2568
    /* make sleep time to be # of ms to output a fragment */
2569
    dwSleepTime = (wwi->dwFragmentSize * 1000) / wwi->waveFormat.Format.nAvgBytesPerSec;
2570
    TRACE("sleeptime=%d ms\n", dwSleepTime);
2571

2572
    for (;;) {
2573 2574 2575 2576 2577
	/* wait for dwSleepTime or an event in thread's queue */
	/* FIXME: could improve wait time depending on queue state,
	 * ie, number of queued fragments
	 */

2578
	if (wwi->lpQueuePtr != NULL && wwi->state == WINE_WS_PLAYING)
2579 2580 2581
        {
            lpWaveHdr = wwi->lpQueuePtr;

2582
	    ioctl(wwi->ossdev.fd, SNDCTL_DSP_GETISPACE, &info);
2583 2584 2585 2586 2587 2588 2589
            TRACE("info={frag=%d fsize=%d ftotal=%d bytes=%d}\n", info.fragments, info.fragsize, info.fragstotal, info.bytes);

            /* read all the fragments accumulated so far */
            while ((info.fragments > 0) && (wwi->lpQueuePtr))
            {
                info.fragments --;

2590
                if (lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded >= wwi->dwFragmentSize)
2591 2592
                {
                    /* directly read fragment in wavehdr */
2593
                    bytesRead = read(wwi->ossdev.fd,
2594
		      		     lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded,
2595
                                     wwi->dwFragmentSize);
2596

2597
                    TRACE("bytesRead=%d (direct)\n", bytesRead);
2598
                    if (bytesRead != (DWORD) -1)
2599
		    {
2600 2601
			/* update number of bytes recorded in current buffer and by this device */
                        lpWaveHdr->dwBytesRecorded += bytesRead;
2602 2603
			wwi->dwTotalRead           += bytesRead;
			wwi->dwTotalRecorded = wwi->dwTotalRead;
2604

2605
			/* buffer is full. notify client */
2606
			if (lpWaveHdr->dwBytesRecorded == lpWaveHdr->dwBufferLength)
2607
			{
2608 2609 2610 2611 2612
			    /* must copy the value of next waveHdr, because we have no idea of what
			     * will be done with the content of lpWaveHdr in callback
			     */
			    LPWAVEHDR	lpNext = lpWaveHdr->lpNext;

2613 2614 2615
			    lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
			    lpWaveHdr->dwFlags |=  WHDR_DONE;

2616
			    wwi->lpQueuePtr = lpNext;
2617
			    widNotifyClient(wwi, WIM_DATA, (DWORD_PTR)lpWaveHdr, 0);
2618
			    lpWaveHdr = lpNext;
2619
			}
2620
                    } else {
2621
                        TRACE("read(%s, %p, %d) failed (%s)\n", wwi->ossdev.dev_name,
2622 2623
                            lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded,
                            wwi->dwFragmentSize, strerror(errno));
2624 2625 2626
                    }
                }
                else
2627
		{
2628
                    /* read the fragment in a local buffer */
2629
                    bytesRead = read(wwi->ossdev.fd, buffer, wwi->dwFragmentSize);
2630 2631
                    pOffset = buffer;

2632
                    TRACE("bytesRead=%d (local)\n", bytesRead);
2633

2634
                    if (bytesRead == (DWORD) -1) {
2635
                        TRACE("read(%s, %p, %d) failed (%s)\n", wwi->ossdev.dev_name,
2636 2637 2638 2639
                            buffer, wwi->dwFragmentSize, strerror(errno));
                        continue;
                    }

2640
                    /* copy data in client buffers */
2641 2642 2643 2644 2645 2646 2647 2648 2649 2650
                    while (bytesRead != (DWORD) -1 && bytesRead > 0)
                    {
                        DWORD dwToCopy = min (bytesRead, lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded);

                        memcpy(lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded,
                               pOffset,
                               dwToCopy);

                        /* update number of bytes recorded in current buffer and by this device */
                        lpWaveHdr->dwBytesRecorded += dwToCopy;
2651 2652
                        wwi->dwTotalRead           += dwToCopy;
			wwi->dwTotalRecorded = wwi->dwTotalRead;
2653 2654
                        bytesRead -= dwToCopy;
                        pOffset   += dwToCopy;
2655

2656
                        /* client buffer is full. notify client */
2657
                        if (lpWaveHdr->dwBytesRecorded == lpWaveHdr->dwBufferLength)
2658
                        {
2659 2660 2661 2662 2663 2664
			    /* must copy the value of next waveHdr, because we have no idea of what
			     * will be done with the content of lpWaveHdr in callback
			     */
			    LPWAVEHDR	lpNext = lpWaveHdr->lpNext;
			    TRACE("lpNext=%p\n", lpNext);

2665 2666 2667
                            lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
                            lpWaveHdr->dwFlags |=  WHDR_DONE;

2668
			    wwi->lpQueuePtr = lpNext;
2669
                            widNotifyClient(wwi, WIM_DATA, (DWORD_PTR)lpWaveHdr, 0);
2670

2671
			    lpWaveHdr = lpNext;
2672
			    if (!lpNext && bytesRead) {
2673 2674 2675 2676 2677 2678 2679
				/* before we give up, check for more header messages */
				while (OSS_PeekRingMessage(&wwi->msgRing, &msg, &param, &ev))
				{
				    if (msg == WINE_WM_HEADER) {
					LPWAVEHDR hdr;
					OSS_RetrieveRingMessage(&wwi->msgRing, &msg, &param, &ev);
					hdr = ((LPWAVEHDR)param);
2680
					TRACE("msg = %s, hdr = %p, ev = %p\n", getCmdString(msg), hdr, ev);
2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698
					hdr->lpNext = 0;
					if (lpWaveHdr == 0) {
					    /* new head of queue */
					    wwi->lpQueuePtr = lpWaveHdr = hdr;
					} else {
					    /* insert buffer at the end of queue */
					    LPWAVEHDR*  wh;
					    for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
					    *wh = hdr;
					}
				    } else
					break;
				}

				if (lpWaveHdr == 0) {
                                    /* no more buffer to copy data to, but we did read more.
                                     * what hasn't been copied will be dropped
                                     */
2699
                                    WARN("buffer under run! %u bytes dropped.\n", bytesRead);
2700 2701 2702
                                    wwi->lpQueuePtr = NULL;
                                    break;
				}
2703 2704 2705 2706 2707
                            }
                        }
                    }
                }
            }
2708
	}
2709

2710
	WAIT_OMR(&wwi->msgRing, dwSleepTime);
2711

2712 2713
	while (OSS_RetrieveRingMessage(&wwi->msgRing, &msg, &param, &ev))
	{
2714
            TRACE("msg=%s param=0x%lx\n", getCmdString(msg), param);
2715
	    switch (msg) {
2716 2717
	    case WINE_WM_PAUSING:
		wwi->state = WINE_WS_PAUSED;
2718
                /*FIXME("Device should stop recording\n");*/
2719
		SetEvent(ev);
2720
		break;
2721
	    case WINE_WM_STARTING:
2722
		wwi->state = WINE_WS_PLAYING;
2723

2724
                if (wwi->ossdev.bTriggerSupport)
2725 2726
                {
                    /* start the recording */
2727 2728 2729 2730 2731
		    wwi->ossdev.bInputEnabled = TRUE;
                    enable = getEnables(&wwi->ossdev);
                    if (ioctl(wwi->ossdev.fd, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
		        wwi->ossdev.bInputEnabled = FALSE;
                        ERR("ioctl(%s, SNDCTL_DSP_SETTRIGGER) failed (%s)\n", wwi->ossdev.dev_name, strerror(errno));
2732
		    }
2733 2734 2735 2736 2737
                }
                else
                {
                    unsigned char data[4];
                    /* read 4 bytes to start the recording */
2738
                    read(wwi->ossdev.fd, data, 4);
2739
                }
2740

2741
		SetEvent(ev);
2742 2743
		break;
	    case WINE_WM_HEADER:
2744
		lpWaveHdr = (LPWAVEHDR)param;
2745 2746 2747 2748 2749 2750 2751 2752 2753
		lpWaveHdr->lpNext = 0;

		/* insert buffer at the end of queue */
		{
		    LPWAVEHDR*	wh;
		    for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
		    *wh = lpWaveHdr;
		}
		break;
2754
	    case WINE_WM_STOPPING:
2755 2756
		if (wwi->state != WINE_WS_STOPPED)
		{
2757
                    if (wwi->ossdev.bTriggerSupport)
2758 2759
                    {
                        /* stop the recording */
2760 2761 2762 2763 2764
		        wwi->ossdev.bInputEnabled = FALSE;
                        enable = getEnables(&wwi->ossdev);
                        if (ioctl(wwi->ossdev.fd, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
		            wwi->ossdev.bInputEnabled = FALSE;
                            ERR("ioctl(%s, SNDCTL_DSP_SETTRIGGER) failed (%s)\n", wwi->ossdev.dev_name, strerror(errno));
2765 2766
		        }
                    }
2767 2768 2769 2770

		    /* read any headers in queue */
		    widRecorder_ReadHeaders(wwi);

2771 2772 2773 2774 2775 2776 2777 2778 2779
		    /* return current buffer to app */
		    lpWaveHdr = wwi->lpQueuePtr;
		    if (lpWaveHdr)
		    {
		        LPWAVEHDR	lpNext = lpWaveHdr->lpNext;
		        TRACE("stop %p %p\n", lpWaveHdr, lpWaveHdr->lpNext);
		        lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
		        lpWaveHdr->dwFlags |= WHDR_DONE;
		        wwi->lpQueuePtr = lpNext;
2780
		        widNotifyClient(wwi, WIM_DATA, (DWORD_PTR)lpWaveHdr, 0);
2781 2782
		    }
		}
Robert Reif's avatar
Robert Reif committed
2783
		wwi->state = WINE_WS_STOPPED;
2784 2785
		SetEvent(ev);
		break;
2786
	    case WINE_WM_RESETTING:
2787 2788
		if (wwi->state != WINE_WS_STOPPED)
		{
2789
                    if (wwi->ossdev.bTriggerSupport)
2790 2791
                    {
                        /* stop the recording */
2792 2793 2794 2795 2796
		        wwi->ossdev.bInputEnabled = FALSE;
                        enable = getEnables(&wwi->ossdev);
                        if (ioctl(wwi->ossdev.fd, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
		            wwi->ossdev.bInputEnabled = FALSE;
                            ERR("ioctl(%s, SNDCTL_DSP_SETTRIGGER) failed (%s)\n", wwi->ossdev.dev_name, strerror(errno));
2797 2798 2799
		        }
                    }
		}
2800
		wwi->state = WINE_WS_STOPPED;
Robert Reif's avatar
Robert Reif committed
2801
    		wwi->dwTotalRecorded = 0;
2802
		wwi->dwTotalRead = 0;
2803 2804 2805 2806

		/* read any headers in queue */
		widRecorder_ReadHeaders(wwi);

2807 2808 2809 2810 2811
		/* return all buffers to the app */
		for (lpWaveHdr = wwi->lpQueuePtr; lpWaveHdr; lpWaveHdr = lpWaveHdr->lpNext) {
		    TRACE("reset %p %p\n", lpWaveHdr, lpWaveHdr->lpNext);
		    lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
		    lpWaveHdr->dwFlags |= WHDR_DONE;
2812
                    wwi->lpQueuePtr = lpWaveHdr->lpNext;
2813
		    widNotifyClient(wwi, WIM_DATA, (DWORD_PTR)lpWaveHdr, 0);
2814
		}
2815

2816
		wwi->lpQueuePtr = NULL;
2817
		SetEvent(ev);
2818
		break;
2819 2820 2821
	    case WINE_WM_UPDATE:
		if (wwi->state == WINE_WS_PLAYING) {
		    audio_buf_info tmp_info;
2822 2823
		    if (ioctl(wwi->ossdev.fd, SNDCTL_DSP_GETISPACE, &tmp_info) < 0)
			ERR("ioctl(%s, SNDCTL_DSP_GETISPACE) failed (%s)\n", wwi->ossdev.dev_name, strerror(errno));
2824 2825 2826 2827 2828
		    else
			wwi->dwTotalRecorded = wwi->dwTotalRead + tmp_info.bytes;
		}
		SetEvent(ev);
		break;
2829 2830 2831
	    case WINE_WM_CLOSING:
		wwi->hThread = 0;
		wwi->state = WINE_WS_CLOSED;
2832
		SetEvent(ev);
2833
		HeapFree(GetProcessHeap(), 0, buffer);
2834 2835 2836
		ExitThread(0);
		/* shouldn't go here */
	    default:
2837
		FIXME("unknown message %d\n", msg);
2838 2839 2840 2841 2842 2843
		break;
	    }
	}
    }
    ExitThread(0);
    /* just for not generating compilation warnings... should never be executed */
2844
    return 0;
2845 2846 2847
}


Alexandre Julliard's avatar
Alexandre Julliard committed
2848
/**************************************************************************
Alexandre Julliard's avatar
Alexandre Julliard committed
2849 2850
 * 				widOpen				[internal]
 */
2851
static DWORD widOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
Alexandre Julliard's avatar
Alexandre Julliard committed
2852
{
2853
    WINE_WAVEIN*	wwi;
2854
    audio_buf_info      info;
2855 2856
    int                 audio_fragment;
    DWORD               ret;
2857

2858
    TRACE("(%u, %p, %08X);\n", wDevID, lpDesc, dwFlags);
2859
    if (lpDesc == NULL) {
2860
	WARN("Invalid Parameter !\n");
2861 2862
	return MMSYSERR_INVALPARAM;
    }
2863 2864 2865 2866
    if (wDevID >= numInDev) {
        WARN("bad device id: %d >= %d\n", wDevID, numInDev);
        return MMSYSERR_BADDEVICEID;
    }
2867 2868

    /* only PCM format is supported so far... */
2869
    if (!supportedFormat(lpDesc->lpFormat)) {
2870
	WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
2871 2872 2873 2874 2875 2876
	     lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
	     lpDesc->lpFormat->nSamplesPerSec);
	return WAVERR_BADFORMAT;
    }

    if (dwFlags & WAVE_FORMAT_QUERY) {
2877
	TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
2878 2879 2880 2881 2882
	     lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
	     lpDesc->lpFormat->nSamplesPerSec);
	return MMSYSERR_NOERROR;
    }

2883
    TRACE("OSS_OpenDevice requested this format: %dx%dx%d %s\n",
2884 2885 2886 2887 2888 2889 2890
          lpDesc->lpFormat->nSamplesPerSec,
          lpDesc->lpFormat->wBitsPerSample,
          lpDesc->lpFormat->nChannels,
          lpDesc->lpFormat->wFormatTag == WAVE_FORMAT_PCM ? "WAVE_FORMAT_PCM" :
          lpDesc->lpFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? "WAVE_FORMAT_EXTENSIBLE" :
          "UNSUPPORTED");

2891
    wwi = &WInDev[wDevID];
2892

2893
    if (wwi->state != WINE_WS_CLOSED) return MMSYSERR_ALLOCATED;
2894

2895
    if ((dwFlags & WAVE_DIRECTSOUND) &&
2896
        !(wwi->ossdev.in_caps_support & WAVECAPS_DIRECTSOUND))
2897 2898 2899 2900
	/* not supported, ignore it */
	dwFlags &= ~WAVE_DIRECTSOUND;

    if (dwFlags & WAVE_DIRECTSOUND) {
2901
	TRACE("has DirectSoundCapture driver\n");
2902
        if (wwi->ossdev.in_caps_support & WAVECAPS_SAMPLEACCURATE)
2903 2904 2905 2906 2907 2908 2909 2910
	    /* we have realtime DirectSound, fragments just waste our time,
	     * but a large buffer is good, so choose 64KB (32 * 2^11) */
	    audio_fragment = 0x0020000B;
	else
	    /* to approximate realtime, we must use small fragments,
	     * let's try to fragment the above 64KB (256 * 2^8) */
	    audio_fragment = 0x01000008;
    } else {
2911
	TRACE("doesn't have DirectSoundCapture driver\n");
2912
	if (wwi->ossdev.open_count > 0) {
2913
	    TRACE("Using output device audio_fragment\n");
2914
	    /* FIXME: This may not be optimal for capture but it allows us
2915
	     * to do hardware playback without hardware capture. */
2916
	    audio_fragment = wwi->ossdev.audio_fragment;
2917
	} else {
2918 2919 2920 2921 2922 2923 2924 2925 2926
	    /* A wave device must have a worst case latency of 10 ms so calculate
	     * the largest fragment size less than 10 ms long.
	     */
	    int	fsize = lpDesc->lpFormat->nAvgBytesPerSec / 100;	/* 10 ms chunk */
	    int	shift = 0;
	    while ((1 << shift) <= fsize)
		shift++;
	    shift--;
	    audio_fragment = 0x00100000 + shift;	/* 16 fragments of 2^shift */
2927
	}
2928 2929
    }

2930
    TRACE("requesting %d %d byte fragments (%d ms)\n", audio_fragment >> 16,
2931
	1 << (audio_fragment & 0xffff),
2932
	((1 << (audio_fragment & 0xffff)) * 1000) / lpDesc->lpFormat->nAvgBytesPerSec);
2933

2934
    ret = OSS_OpenDevice(&wwi->ossdev, O_RDONLY, &audio_fragment,
2935
                         1,
2936
                         lpDesc->lpFormat->nSamplesPerSec,
2937
                         lpDesc->lpFormat->nChannels,
2938
                         (lpDesc->lpFormat->wBitsPerSample == 16)
2939 2940
                         ? AFMT_S16_LE : AFMT_U8);
    if (ret != 0) return ret;
2941 2942
    wwi->state = WINE_WS_STOPPED;

2943 2944 2945
    if (wwi->lpQueuePtr) {
	WARN("Should have an empty queue (%p)\n", wwi->lpQueuePtr);
	wwi->lpQueuePtr = NULL;
2946
    }
2947
    wwi->dwTotalRecorded = 0;
2948
    wwi->dwTotalRead = 0;
2949 2950
    wwi->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);

2951
    wwi->waveDesc = *lpDesc;
2952
    copy_format(lpDesc->lpFormat, &wwi->waveFormat);
2953

2954
    if (wwi->waveFormat.Format.wBitsPerSample == 0) {
2955
	WARN("Resetting zeroed wBitsPerSample\n");
2956 2957 2958 2959
	wwi->waveFormat.Format.wBitsPerSample = 8 *
	    (wwi->waveFormat.Format.nAvgBytesPerSec /
	     wwi->waveFormat.Format.nSamplesPerSec) /
	    wwi->waveFormat.Format.nChannels;
2960
    }
2961

2962
    if (ioctl(wwi->ossdev.fd, SNDCTL_DSP_GETISPACE, &info) < 0) {
2963
        ERR("ioctl(%s, SNDCTL_DSP_GETISPACE) failed (%s)\n",
2964 2965
            wwi->ossdev.dev_name, strerror(errno));
        OSS_CloseDevice(&wwi->ossdev);
2966
	wwi->state = WINE_WS_CLOSED;
2967 2968
	return MMSYSERR_NOTENABLED;
    }
2969 2970

    TRACE("got %d %d byte fragments (%d ms/fragment)\n", info.fragstotal,
2971 2972
        info.fragsize, (info.fragsize * 1000) / (wwi->ossdev.sample_rate *
        wwi->ossdev.channels * (wwi->ossdev.format == AFMT_U8 ? 1 : 2)));
2973

2974
    wwi->dwFragmentSize = info.fragsize;
2975

2976 2977
    TRACE("dwFragmentSize=%u\n", wwi->dwFragmentSize);
    TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%u, nSamplesPerSec=%u, nChannels=%u nBlockAlign=%u!\n",
2978 2979 2980
	  wwi->waveFormat.Format.wBitsPerSample, wwi->waveFormat.Format.nAvgBytesPerSec,
	  wwi->waveFormat.Format.nSamplesPerSec, wwi->waveFormat.Format.nChannels,
	  wwi->waveFormat.Format.nBlockAlign);
2981

2982 2983
    OSS_InitRingMessage(&wwi->msgRing);

2984
    wwi->hStartUpEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
2985
    wwi->hThread = CreateThread(NULL, 0, widRecorder, (LPVOID)(DWORD_PTR)wDevID, 0, &(wwi->dwThreadID));
2986 2987
    if (wwi->hThread)
        SetThreadPriority(wwi->hThread, THREAD_PRIORITY_TIME_CRITICAL);
2988 2989 2990
    WaitForSingleObject(wwi->hStartUpEvent, INFINITE);
    CloseHandle(wwi->hStartUpEvent);
    wwi->hStartUpEvent = INVALID_HANDLE_VALUE;
2991

Eric Pouech's avatar
Eric Pouech committed
2992
    return widNotifyClient(wwi, WIM_OPEN, 0L, 0L);
Alexandre Julliard's avatar
Alexandre Julliard committed
2993 2994 2995
}

/**************************************************************************
Alexandre Julliard's avatar
Alexandre Julliard committed
2996 2997
 * 				widClose			[internal]
 */
Alexandre Julliard's avatar
Alexandre Julliard committed
2998
static DWORD widClose(WORD wDevID)
Alexandre Julliard's avatar
Alexandre Julliard committed
2999
{
3000 3001
    WINE_WAVEIN*	wwi;

3002
    TRACE("(%u);\n", wDevID);
3003
    if (wDevID >= numInDev || WInDev[wDevID].state == WINE_WS_CLOSED) {
3004
	WARN("can't close !\n");
3005
	return MMSYSERR_INVALHANDLE;
3006
    }
3007 3008 3009 3010

    wwi = &WInDev[wDevID];

    if (wwi->lpQueuePtr != NULL) {
3011
	WARN("still buffers open !\n");
3012 3013
	return WAVERR_STILLPLAYING;
    }
3014

3015
    OSS_AddRingMessage(&wwi->msgRing, WINE_WM_CLOSING, 0, TRUE);
3016
    OSS_CloseDevice(&wwi->ossdev);
3017
    wwi->state = WINE_WS_CLOSED;
3018
    wwi->dwFragmentSize = 0;
3019
    OSS_DestroyRingMessage(&wwi->msgRing);
Eric Pouech's avatar
Eric Pouech committed
3020
    return widNotifyClient(wwi, WIM_CLOSE, 0L, 0L);
Alexandre Julliard's avatar
Alexandre Julliard committed
3021 3022 3023
}

/**************************************************************************
Alexandre Julliard's avatar
Alexandre Julliard committed
3024 3025 3026
 * 				widAddBuffer		[internal]
 */
static DWORD widAddBuffer(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
Alexandre Julliard's avatar
Alexandre Julliard committed
3027
{
3028
    TRACE("(%u, %p, %08X);\n", wDevID, lpWaveHdr, dwSize);
3029

3030
    if (wDevID >= numInDev || WInDev[wDevID].state == WINE_WS_CLOSED) {
3031
	WARN("can't do it !\n");
3032
	return MMSYSERR_INVALHANDLE;
3033 3034
    }
    if (!(lpWaveHdr->dwFlags & WHDR_PREPARED)) {
3035
	TRACE("never been prepared !\n");
3036 3037 3038
	return WAVERR_UNPREPARED;
    }
    if (lpWaveHdr->dwFlags & WHDR_INQUEUE) {
3039
	TRACE("header already in use !\n");
3040 3041
	return WAVERR_STILLPLAYING;
    }
3042

3043 3044 3045
    lpWaveHdr->dwFlags |= WHDR_INQUEUE;
    lpWaveHdr->dwFlags &= ~WHDR_DONE;
    lpWaveHdr->dwBytesRecorded = 0;
3046
    lpWaveHdr->lpNext = NULL;
3047

3048
    OSS_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_HEADER, (DWORD_PTR)lpWaveHdr, FALSE);
3049
    return MMSYSERR_NOERROR;
Alexandre Julliard's avatar
Alexandre Julliard committed
3050 3051 3052
}

/**************************************************************************
Alexandre Julliard's avatar
Alexandre Julliard committed
3053 3054
 * 			widStart				[internal]
 */
Alexandre Julliard's avatar
Alexandre Julliard committed
3055
static DWORD widStart(WORD wDevID)
Alexandre Julliard's avatar
Alexandre Julliard committed
3056
{
3057
    TRACE("(%u);\n", wDevID);
3058
    if (wDevID >= numInDev || WInDev[wDevID].state == WINE_WS_CLOSED) {
3059
	WARN("can't start recording !\n");
3060
	return MMSYSERR_INVALHANDLE;
3061
    }
3062

3063
    OSS_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_STARTING, 0, TRUE);
3064
    return MMSYSERR_NOERROR;
Alexandre Julliard's avatar
Alexandre Julliard committed
3065 3066 3067
}

/**************************************************************************
Alexandre Julliard's avatar
Alexandre Julliard committed
3068 3069
 * 			widStop					[internal]
 */
Alexandre Julliard's avatar
Alexandre Julliard committed
3070
static DWORD widStop(WORD wDevID)
Alexandre Julliard's avatar
Alexandre Julliard committed
3071
{
3072
    TRACE("(%u);\n", wDevID);
3073
    if (wDevID >= numInDev || WInDev[wDevID].state == WINE_WS_CLOSED) {
3074
	WARN("can't stop !\n");
3075
	return MMSYSERR_INVALHANDLE;
3076
    }
3077 3078

    OSS_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_STOPPING, 0, TRUE);
3079

3080
    return MMSYSERR_NOERROR;
Alexandre Julliard's avatar
Alexandre Julliard committed
3081 3082 3083
}

/**************************************************************************
Alexandre Julliard's avatar
Alexandre Julliard committed
3084 3085
 * 			widReset				[internal]
 */
Alexandre Julliard's avatar
Alexandre Julliard committed
3086
static DWORD widReset(WORD wDevID)
Alexandre Julliard's avatar
Alexandre Julliard committed
3087
{
3088
    TRACE("(%u);\n", wDevID);
3089
    if (wDevID >= numInDev || WInDev[wDevID].state == WINE_WS_CLOSED) {
3090
	WARN("can't reset !\n");
3091
	return MMSYSERR_INVALHANDLE;
3092
    }
3093
    OSS_AddRingMessage(&WInDev[wDevID].msgRing, WINE_WM_RESETTING, 0, TRUE);
3094
    return MMSYSERR_NOERROR;
Alexandre Julliard's avatar
Alexandre Julliard committed
3095 3096 3097
}

/**************************************************************************
Alexandre Julliard's avatar
Alexandre Julliard committed
3098 3099
 * 				widGetPosition			[internal]
 */
3100
static DWORD widGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
Alexandre Julliard's avatar
Alexandre Julliard committed
3101
{
3102
    WINE_WAVEIN*	wwi;
3103

3104
    TRACE("(%u, %p, %u);\n", wDevID, lpTime, uSize);
3105

3106
    if (wDevID >= numInDev || WInDev[wDevID].state == WINE_WS_CLOSED) {
3107
	WARN("can't get pos !\n");
3108
	return MMSYSERR_INVALHANDLE;
3109
    }
3110 3111 3112 3113 3114

    if (lpTime == NULL) {
	WARN("invalid parameter: lpTime == NULL\n");
	return MMSYSERR_INVALPARAM;
    }
3115 3116

    wwi = &WInDev[wDevID];
3117
#ifdef EXACT_WIDPOSITION
3118
    if (wwi->ossdev.in_caps_support & WAVECAPS_SAMPLEACCURATE)
3119
        OSS_AddRingMessage(&(wwi->msgRing), WINE_WM_UPDATE, 0, TRUE);
3120
#endif
3121

3122
    return bytes_to_mmtime(lpTime, wwi->dwTotalRecorded, &wwi->waveFormat);
Alexandre Julliard's avatar
Alexandre Julliard committed
3123 3124 3125
}

/**************************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
3126
 * 				widMessage (WINEOSS.6)
Alexandre Julliard's avatar
Alexandre Julliard committed
3127
 */
3128 3129
DWORD WINAPI OSS_widMessage(WORD wDevID, WORD wMsg, DWORD_PTR dwUser,
			    DWORD_PTR dwParam1, DWORD_PTR dwParam2)
Alexandre Julliard's avatar
Alexandre Julliard committed
3130
{
3131
    TRACE("(%u, %s, %08lX, %08lX, %08lX);\n",
3132
	  wDevID, getMessage(wMsg), dwUser, dwParam1, dwParam2);
3133 3134

    switch (wMsg) {
3135
    case DRVM_INIT:
3136 3137 3138 3139 3140
    case DRVM_EXIT:
    case DRVM_ENABLE:
    case DRVM_DISABLE:
	/* FIXME: Pretend this is supported */
	return 0;
3141 3142 3143
    case WIDM_OPEN:		return widOpen       (wDevID, (LPWAVEOPENDESC)dwParam1, dwParam2);
    case WIDM_CLOSE:		return widClose      (wDevID);
    case WIDM_ADDBUFFER:	return widAddBuffer  (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
3144 3145
    case WIDM_PREPARE:		return MMSYSERR_NOTSUPPORTED;
    case WIDM_UNPREPARE:	return MMSYSERR_NOTSUPPORTED;
3146
    case WIDM_GETDEVCAPS:	return widGetDevCaps (wDevID, (LPWAVEINCAPSW)dwParam1, dwParam2);
3147
    case WIDM_GETNUMDEVS:	return numInDev;
3148
    case WIDM_GETPOS:		return widGetPosition(wDevID, (LPMMTIME)dwParam1, dwParam2);
3149 3150 3151
    case WIDM_RESET:		return widReset      (wDevID);
    case WIDM_START:		return widStart      (wDevID);
    case WIDM_STOP:		return widStop       (wDevID);
3152 3153
    case DRV_QUERYDEVICEINTERFACESIZE: return widDevInterfaceSize      (wDevID, (LPDWORD)dwParam1);
    case DRV_QUERYDEVICEINTERFACE:     return widDevInterface          (wDevID, (PWCHAR)dwParam1, dwParam2);
3154
    case DRV_QUERYDSOUNDIFACE:	return widDsCreate   (wDevID, (PIDSCDRIVER*)dwParam1);
3155
    case DRV_QUERYDSOUNDDESC:	return widDsDesc     (wDevID, (PDSDRIVERDESC)dwParam1);
3156
    default:
3157
	FIXME("unknown message %u!\n", wMsg);
3158 3159
    }
    return MMSYSERR_NOTSUPPORTED;
Alexandre Julliard's avatar
Alexandre Julliard committed
3160 3161
}

Alexandre Julliard's avatar
Alexandre Julliard committed
3162 3163 3164
#else /* !HAVE_OSS */

/**************************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
3165
 * 				wodMessage (WINEOSS.7)
Alexandre Julliard's avatar
Alexandre Julliard committed
3166
 */
3167 3168
DWORD WINAPI OSS_wodMessage(WORD wDevID, WORD wMsg, DWORD_PTR dwUser,
			    DWORD_PTR dwParam1, DWORD_PTR dwParam2)
Alexandre Julliard's avatar
Alexandre Julliard committed
3169
{
3170
    FIXME("(%u, %04X, %08lX, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
3171
    return MMSYSERR_NOTENABLED;
Alexandre Julliard's avatar
Alexandre Julliard committed
3172 3173 3174
}

/**************************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
3175
 * 				widMessage (WINEOSS.6)
Alexandre Julliard's avatar
Alexandre Julliard committed
3176
 */
3177 3178
DWORD WINAPI OSS_widMessage(WORD wDevID, WORD wMsg, DWORD_PTR dwUser,
			    DWORD_PTR dwParam1, DWORD_PTR dwParam2)
Alexandre Julliard's avatar
Alexandre Julliard committed
3179
{
3180
    FIXME("(%u, %04X, %08lX, %08lX, %08lX):stub\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
3181 3182 3183
    return MMSYSERR_NOTENABLED;
}

Alexandre Julliard's avatar
Alexandre Julliard committed
3184
#endif /* HAVE_OSS */