kernel32: Added missing include to term.c.
[wine] / dlls / winejack.drv / audio.c
1 /*
2  * Wine Driver for jack Sound Server
3  *   http://jackit.sourceforge.net
4  *
5  * Copyright 1994 Martin Ayotte
6  * Copyright 1999 Eric Pouech (async playing in waveOut/waveIn)
7  * Copyright 2000 Eric Pouech (loops in waveOut)
8  * Copyright 2002 Chris Morgan (jack version of this file)
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with this library; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23  */
24
25 /*
26  * TODO:
27  *  implement audio stream resampling for any arbitrary frequenty
28  *    right now we use the winmm layer to do resampling although it would 
29  *    be nice to have a full set of algorithms to choose from based on cpu 
30  *    time
31  *
32  * FIXME:
33  *  pause in waveOut during loop is not handled correctly
34  */
35
36 #include "config.h"
37
38 #include <stdlib.h>
39 #include <stdarg.h>
40 #include <stdio.h>
41 #include <string.h>
42 #ifdef HAVE_UNISTD_H
43 # include <unistd.h>
44 #endif
45 #include <fcntl.h>
46 #include "windef.h"
47 #include "winbase.h"
48 #include "winnls.h"
49 #include "wingdi.h"
50 #include "winerror.h"
51 #include "mmddk.h"
52 #include "dsound.h"
53 #include "dsdriver.h"
54 #include "jack.h"
55 #include "wine/unicode.h"
56 #include "wine/library.h"
57 #include "wine/debug.h"
58
59 #ifdef HAVE_JACK_JACK_H
60 #include <jack/jack.h>
61 #endif
62
63
64 WINE_DEFAULT_DEBUG_CHANNEL(wave);
65
66 #ifdef SONAME_LIBJACK
67
68 #define MAKE_FUNCPTR(f) static typeof(f) * fp_##f = NULL;
69
70 /* Function pointers for dynamic loading of libjack */
71 /* these are prefixed with "fp_", ie. "fp_jack_client_open" */
72 MAKE_FUNCPTR(jack_activate);
73 MAKE_FUNCPTR(jack_connect);
74 MAKE_FUNCPTR(jack_client_open);
75 MAKE_FUNCPTR(jack_client_close);
76 MAKE_FUNCPTR(jack_deactivate);
77 MAKE_FUNCPTR(jack_set_process_callback);
78 MAKE_FUNCPTR(jack_set_buffer_size_callback);
79 MAKE_FUNCPTR(jack_set_sample_rate_callback);
80 MAKE_FUNCPTR(jack_on_shutdown);
81 MAKE_FUNCPTR(jack_get_sample_rate);
82 MAKE_FUNCPTR(jack_port_register);
83 MAKE_FUNCPTR(jack_port_get_buffer);
84 MAKE_FUNCPTR(jack_get_ports);
85 MAKE_FUNCPTR(jack_port_name);
86 MAKE_FUNCPTR(jack_get_buffer_size);
87 #undef MAKE_FUNCPTR
88
89 /* define the below to work around a bug in jack where closing a port */
90 /* takes a very long time, so to get around this we actually don't */
91 /* close the port when the device is closed but instead mark the */
92 /* corresponding device as unused */
93 #define JACK_CLOSE_HACK    1
94
95 typedef jack_default_audio_sample_t sample_t;
96 typedef jack_nframes_t nframes_t;
97
98 /* only allow 10 output devices through this driver, this ought to be adequate */
99 #define MAX_WAVEOUTDRV  (10)
100 #define MAX_WAVEINDRV   (10)
101
102 /* state diagram for waveOut writing:
103  *
104  * +---------+-------------+---------------+---------------------------------+
105  * |  state  |  function   |     event     |            new state            |
106  * +---------+-------------+---------------+---------------------------------+
107  * |         | open()      |               | STOPPED                         |
108  * | PAUSED  | write()     |               | PAUSED                          |
109  * | STOPPED | write()     | <thrd create> | PLAYING                         |
110  * | PLAYING | write()     | HEADER        | PLAYING                         |
111  * | (other) | write()     | <error>       |                                 |
112  * | (any)   | pause()     | PAUSING       | PAUSED                          |
113  * | PAUSED  | restart()   | RESTARTING    | PLAYING (if no thrd => STOPPED) |
114  * | (any)   | reset()     | RESETTING     | STOPPED                         |
115  * | (any)   | close()     | CLOSING       | CLOSED                          |
116  * +---------+-------------+---------------+---------------------------------+
117  */
118
119 /* states of the playing device */
120 #define WINE_WS_PLAYING   0
121 #define WINE_WS_PAUSED    1
122 #define WINE_WS_STOPPED   2
123 #define WINE_WS_CLOSED    3
124
125 typedef struct {
126     volatile int      state;      /* one of the WINE_WS_ manifest constants */
127     WAVEOPENDESC      waveDesc;
128     WORD              wFlags;
129     PCMWAVEFORMAT     format;
130     WAVEOUTCAPSW      caps;
131     WORD              wDevID;
132     char              interface_name[32];
133
134     jack_port_t*      out_port_l;   /* ports for left and right channels */
135     jack_port_t*      out_port_r;
136     jack_client_t*    client;
137     long              sample_rate;        /* jack server sample rate */
138
139 #if JACK_CLOSE_HACK
140     BOOL              in_use; /* TRUE if this device is in use */
141 #endif
142
143     char*             sound_buffer;
144     unsigned long     buffer_size;
145
146     DWORD             volume_left;
147     DWORD             volume_right;
148
149     LPWAVEHDR         lpQueuePtr;   /* start of queued WAVEHDRs (waiting to be notified) */
150     LPWAVEHDR         lpPlayPtr;    /* start of not yet fully played buffers */
151     DWORD             dwPartialOffset;  /* Offset of not yet written bytes in lpPlayPtr */
152
153     LPWAVEHDR         lpLoopPtr;    /* pointer of first buffer in loop, if any */
154     DWORD             dwLoops;      /* private copy of loop counter */
155     
156     DWORD             dwPlayedTotal;    /* number of bytes actually played since opening */
157     DWORD             dwWrittenTotal;   /* number of bytes written to jack since opening */
158
159     DWORD             bytesInJack; /* bytes that we wrote during the previous JACK_Callback() */
160     DWORD             tickCountMS; /* time in MS of last JACK_Callback() */
161
162     /* synchronization stuff */
163     CRITICAL_SECTION    access_crst;
164 } WINE_WAVEOUT;
165
166 typedef struct {
167     volatile int    state;
168     WAVEOPENDESC    waveDesc;
169     WORD            wFlags;
170     PCMWAVEFORMAT   format;
171     LPWAVEHDR       lpQueuePtr;
172     DWORD           dwTotalRecorded;
173     WAVEINCAPSW     caps;
174     BOOL            bTriggerSupport;
175     WORD              wDevID;
176     char              interface_name[32];
177
178     jack_port_t*      in_port_l;   /* ports for left and right channels */
179     jack_port_t*      in_port_r;
180     jack_client_t*    client;
181     long              sample_rate;        /* jack server sample rate */
182
183 #if JACK_CLOSE_HACK
184     BOOL              in_use; /* TRUE if this device is in use */
185 #endif
186
187     char*             sound_buffer;
188     unsigned long     buffer_size;
189
190     /* synchronization stuff */
191     CRITICAL_SECTION    access_crst;
192 } WINE_WAVEIN;
193
194 static WINE_WAVEOUT WOutDev   [MAX_WAVEOUTDRV];
195 static WINE_WAVEIN  WInDev    [MAX_WAVEINDRV ];
196
197 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv);
198 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc);
199
200 static LPWAVEHDR wodHelper_PlayPtrNext(WINE_WAVEOUT* wwo);
201 static DWORD wodHelper_NotifyCompletions(WINE_WAVEOUT* wwo, BOOL force);
202
203 static int JACK_OpenWaveOutDevice(WINE_WAVEOUT* wwo);
204 static int JACK_OpenWaveInDevice(WINE_WAVEIN* wwi, WORD nChannels);
205
206 #if JACK_CLOSE_HACK
207 static void     JACK_CloseWaveOutDevice(WINE_WAVEOUT* wwo, BOOL close_client);
208 #else
209 static void     JACK_CloseWaveOutDevice(WINE_WAVEOUT* wwo);
210 #endif
211
212 #if JACK_CLOSE_HACK
213 static void     JACK_CloseWaveInDevice(WINE_WAVEIN* wwi, BOOL close_client);
214 #else
215 static void     JACK_CloseWaveInDevice(WINE_WAVEIN* wwi);
216 #endif
217
218 static DWORD bytes_to_mmtime(LPMMTIME lpTime, DWORD position,
219                              PCMWAVEFORMAT* format)
220 {
221     TRACE("wType=%04X wBitsPerSample=%u nSamplesPerSec=%u nChannels=%u nAvgBytesPerSec=%u\n",
222           lpTime->wType, format->wBitsPerSample, format->wf.nSamplesPerSec,
223           format->wf.nChannels, format->wf.nAvgBytesPerSec);
224     TRACE("Position in bytes=%u\n", position);
225
226     switch (lpTime->wType) {
227     case TIME_SAMPLES:
228         lpTime->u.sample = position / (format->wBitsPerSample / 8 * format->wf.nChannels);
229         TRACE("TIME_SAMPLES=%u\n", lpTime->u.sample);
230         break;
231     case TIME_MS:
232         lpTime->u.ms = 1000.0 * position / (format->wBitsPerSample / 8 * format->wf.nChannels * format->wf.nSamplesPerSec);
233         TRACE("TIME_MS=%u\n", lpTime->u.ms);
234         break;
235     case TIME_SMPTE:
236         lpTime->u.smpte.fps = 30;
237         position = position / (format->wBitsPerSample / 8 * format->wf.nChannels);
238         position += (format->wf.nSamplesPerSec / lpTime->u.smpte.fps) - 1; /* round up */
239         lpTime->u.smpte.sec = position / format->wf.nSamplesPerSec;
240         position -= lpTime->u.smpte.sec * format->wf.nSamplesPerSec;
241         lpTime->u.smpte.min = lpTime->u.smpte.sec / 60;
242         lpTime->u.smpte.sec -= 60 * lpTime->u.smpte.min;
243         lpTime->u.smpte.hour = lpTime->u.smpte.min / 60;
244         lpTime->u.smpte.min -= 60 * lpTime->u.smpte.hour;
245         lpTime->u.smpte.fps = 30;
246         lpTime->u.smpte.frame = position * lpTime->u.smpte.fps / format->wf.nSamplesPerSec;
247         TRACE("TIME_SMPTE=%02u:%02u:%02u:%02u\n",
248               lpTime->u.smpte.hour, lpTime->u.smpte.min,
249               lpTime->u.smpte.sec, lpTime->u.smpte.frame);
250         break;
251     default:
252         WARN("Format %d not supported, using TIME_BYTES !\n", lpTime->wType);
253         lpTime->wType = TIME_BYTES;
254         /* fall through */
255     case TIME_BYTES:
256         lpTime->u.cb = position;
257         TRACE("TIME_BYTES=%u\n", lpTime->u.cb);
258         break;
259     }
260     return MMSYSERR_NOERROR;
261 }
262
263
264 /*======================================================================*
265  *                  Low level WAVE implementation                       *
266  *======================================================================*/
267
268 #define SAMPLE_MAX_16BIT  32767.0f
269
270 /* Alsaplayer function that applies volume changes to a buffer */
271 /* (C) Andy Lo A Foe */
272 /* Length is in terms of 32 bit samples */
273 static void volume_effect32(void *buffer, int length, int left, int right)
274 {
275         short *data = buffer;
276         int i, v;
277     
278         if (right == -1) right = left;
279  
280         for(i = 0; i < length; i++) {
281                 v = (int) ((*(data) * left) / 100);
282                 *(data++) = (v>32767) ? 32767 : ((v<-32768) ? -32768 : v);
283                 v = (int) ((*(data) * right) / 100);
284                 *(data++) = (v>32767) ? 32767 : ((v<-32768) ? -32768 : v);
285         }
286 }
287
288 /* move 16 bit mono/stereo to 16 bit stereo */
289 static void sample_move_d16_d16(short *dst, short *src,
290                   unsigned long nsamples, int nChannels)
291 {
292   while(nsamples--)
293   {
294     *dst = *src;
295     dst++;
296
297     if(nChannels == 2) src++;
298
299     *dst = *src;
300     dst++;
301
302     src++;
303   }
304 }
305
306 /* convert from 16 bit to floating point */
307 /* allow for copying of stereo data with alternating left/right */
308 /* channels to a buffer that will hold a single channel stream */
309 /* nsamples is in terms of 16bit samples */
310 /* src_skip is in terms of 16bit samples */
311 static void sample_move_d16_s16 (sample_t *dst, short *src,
312                         unsigned long nsamples, unsigned long src_skip)
313 {
314   /* ALERT: signed sign-extension portability !!! */
315   while (nsamples--)
316   {
317     *dst = (*src) / SAMPLE_MAX_16BIT;
318     dst++;
319     src += src_skip;
320   }
321 }       
322
323 /* convert from floating point to 16 bit */
324 /* allow for copying of a buffer that will hold a single channel stream */
325 /* to stereo data with alternating left/right channels */
326 /* nsamples is in terms of float samples */
327 /* dst_skip is in terms of 16bit samples */
328 static void sample_move_s16_d16 (short *dst, sample_t *src,
329                         unsigned long nsamples, unsigned long dst_skip)
330 {
331   /* ALERT: signed sign-extension portability !!! */
332   while (nsamples--)
333   {
334       *dst = (*src) * SAMPLE_MAX_16BIT;
335 /*      TRACE("src=(%.8f,%p) dst=(%d,%p)\n",*src,src,*dst,dst); */
336       dst += dst_skip;
337       src++;
338   }
339 }       
340
341
342 /* fill dst buffer with nsamples worth of silence */
343 static void sample_silence_dS (sample_t *dst, unsigned long nsamples)
344 {
345   /* ALERT: signed sign-extension portability !!! */
346   while (nsamples--)
347   {
348     *dst = 0;
349     dst++;
350   }
351 }       
352
353 /******************************************************************
354  *    JACK_callback_wwo
355  */
356 /* everytime the jack server wants something from us it calls this 
357 function, so we either deliver it some sound to play or deliver it nothing 
358 to play */
359 static int JACK_callback_wwo (nframes_t nframes, void *arg)
360 {
361   sample_t* out_l;
362   sample_t* out_r;
363   WINE_WAVEOUT* wwo = arg;
364
365   TRACE("wDevID: %u, nframes %u state=%u\n", wwo->wDevID, nframes,wwo->state);
366
367   if(!wwo->client)
368     ERR("client is closed, this is weird...\n");
369
370   out_l = fp_jack_port_get_buffer(wwo->out_port_l, nframes);
371   out_r = fp_jack_port_get_buffer(wwo->out_port_r, nframes);
372
373   if(wwo->state == WINE_WS_PLAYING)
374   {
375     DWORD jackFramesAvailable = nframes;
376     DWORD outputFramesAvailable;
377     DWORD numFramesToWrite;
378
379     long written = 0;
380     char* buffer;
381
382 #if JACK_CLOSE_HACK
383     if(wwo->in_use == FALSE)
384     {
385       /* output silence if nothing is being outputted */
386       sample_silence_dS(out_l, nframes);
387       sample_silence_dS(out_r, nframes);
388
389       return 0;
390     }
391 #endif
392
393     TRACE("wwo.state == WINE_WS_PLAYING\n");
394
395     /* see if our sound_buffer is large enough to hold the number of frames jack requested */
396     /* Note: sound_buffer is always filled with 16-bit stereo data, even for mono mode */
397     if(wwo->buffer_size < (nframes * sizeof(short) * 2))
398     {
399       ERR("for some reason JACK_BufSize() didn't allocate enough memory\n");
400       ERR("allocated %ld bytes, need %d bytes\n", wwo->buffer_size, (nframes * (unsigned)sizeof(short) * 2));
401       return 0;
402     }
403
404     /* while we have jackFramesAvailable and a wave header to be played */
405     while(jackFramesAvailable && wwo->lpPlayPtr)
406     {
407       /* find the amount of audio to be played at this time */
408       outputFramesAvailable = (wwo->lpPlayPtr->dwBufferLength - wwo->dwPartialOffset) / wwo->format.wf.nBlockAlign;
409
410       numFramesToWrite = min(jackFramesAvailable, outputFramesAvailable);
411       TRACE("dwBufferLength=(%d) dwPartialOffset=(%d)\n",wwo->lpPlayPtr->dwBufferLength,wwo->dwPartialOffset);
412       TRACE("outputFramesAvailable == %d, jackFramesAvailable == %d\n", outputFramesAvailable, jackFramesAvailable);
413
414       buffer = wwo->lpPlayPtr->lpData + wwo->dwPartialOffset;
415
416       /* convert from mono to stereo if necessary */
417       /* otherwise just memcpy to the output buffer */
418
419       if(wwo->format.wf.nChannels == 1)
420       {
421         sample_move_d16_d16((short*)wwo->sound_buffer + ((nframes - jackFramesAvailable) * sizeof(short)),
422                             (short*)buffer, numFramesToWrite, wwo->format.wf.nChannels);
423       } else /* just copy the memory over */
424       {
425         memcpy(wwo->sound_buffer + ((nframes - jackFramesAvailable) * wwo->format.wf.nBlockAlign),
426                buffer, numFramesToWrite * wwo->format.wf.nBlockAlign);
427       }
428
429       /* advance to the next wave header if possible, or advance pointer */
430       /* inside of the current header if we haven't completed it */
431       if(numFramesToWrite == outputFramesAvailable)
432       {
433         wodHelper_PlayPtrNext(wwo);            /* we wrote the whole waveheader, skip to the next one*/
434       }
435       else
436       {
437         wwo->dwPartialOffset+=(numFramesToWrite * wwo->format.wf.nBlockAlign); /* else advance by the bytes we took in to write */
438       }
439
440       written+=(numFramesToWrite * wwo->format.wf.nBlockAlign); /* add on what we wrote */
441       jackFramesAvailable-=numFramesToWrite; /* take away what was written in terms of output bytes */
442     }
443
444     wwo->tickCountMS = GetTickCount();    /* record the current time */
445     wwo->dwWrittenTotal+=written; /* update states on wave device */
446     wwo->dwPlayedTotal+=wwo->bytesInJack; /* we must have finished with the last bytes or we wouldn't be back inside of this callback again... */
447     wwo->bytesInJack = written; /* record the bytes inside of jack */
448
449     /* Now that we have finished filling the buffer either until it is full or until */
450     /* we have run out of application sound data to process, apply volume and output */
451     /* the audio to the jack server */
452
453     /* apply volume to the buffer */
454     volume_effect32(wwo->sound_buffer, (nframes - jackFramesAvailable), wwo->volume_left, wwo->volume_right);
455
456     /* convert from stereo 16 bit to single channel 32 bit float */
457     /* for each jack server channel */
458     /* NOTE: we skip over two sample since we want to only get either the left or right channel */
459     sample_move_d16_s16(out_l, (short*)wwo->sound_buffer,     (nframes - jackFramesAvailable), 2);
460     sample_move_d16_s16(out_r, (short*)wwo->sound_buffer + 1, (nframes - jackFramesAvailable), 2);
461
462     /* see if we still have jackBytesLeft here, if we do that means that we
463     ran out of wave data to play and had a buffer underrun, fill in
464     the rest of the space with zero bytes */
465     if(jackFramesAvailable)
466     {
467       ERR("buffer underrun of %d frames\n", jackFramesAvailable);
468       sample_silence_dS(out_l + (nframes - jackFramesAvailable), jackFramesAvailable);
469       sample_silence_dS(out_r + (nframes - jackFramesAvailable), jackFramesAvailable);
470     }
471   }
472   else if(wwo->state == WINE_WS_PAUSED || 
473     wwo->state == WINE_WS_STOPPED ||
474     wwo->state == WINE_WS_CLOSED)
475   {
476       /* output silence if nothing is being outputted */
477       sample_silence_dS(out_l, nframes);
478       sample_silence_dS(out_r, nframes);
479   }
480
481   /* notify the client of completed wave headers */
482   EnterCriticalSection(&wwo->access_crst);
483   wodHelper_NotifyCompletions(wwo, FALSE);
484   LeaveCriticalSection(&wwo->access_crst);
485
486   return 0;
487 }
488
489 /******************************************************************
490  *              JACK_bufsize_wwo
491  *
492  *              Called whenever the jack server changes the max number
493  *              of frames passed to JACK_callback
494  */
495 static int JACK_bufsize_wwo (nframes_t nframes, void *arg)
496 {
497   WINE_WAVEOUT* wwo = arg;
498   DWORD buffer_required;
499   TRACE("wDevID=%d\n",wwo->wDevID);
500   TRACE("the maximum buffer size is now %u frames\n", nframes);
501
502   /* make sure the callback routine has adequate memory */
503     /* see if our buffer is large enough for the data we are writing */
504     /* ie. Buffer_size < (bytes we already wrote + bytes we are going to write in this loop) */
505   EnterCriticalSection(&wwo->access_crst);
506
507   /* wwo->sound_buffer is always filled with 16-bit stereo data, even for mono streams */
508   buffer_required = nframes * sizeof(short) * 2;
509   TRACE("wwo->buffer_size (%ld) buffer_required (%d).\n", wwo->buffer_size,buffer_required);
510   if(wwo->buffer_size < buffer_required)
511   {
512     TRACE("expanding buffer from wwo->buffer_size == %ld, to %d\n",
513       wwo->buffer_size, buffer_required);
514     TRACE("GetProcessHeap() == %p\n", GetProcessHeap());
515     wwo->buffer_size = buffer_required;
516
517     if (wwo->sound_buffer)
518       wwo->sound_buffer = HeapReAlloc(GetProcessHeap(), 0, wwo->sound_buffer, wwo->buffer_size);
519     else
520       wwo->sound_buffer = HeapAlloc(GetProcessHeap(), 0, wwo->buffer_size);
521
522     /* if we don't have a buffer then error out */
523     if(!wwo->sound_buffer)
524     {
525         ERR("error allocating sound_buffer memory\n");
526         LeaveCriticalSection(&wwo->access_crst);
527         return 0;
528     }
529   }
530
531   LeaveCriticalSection(&wwo->access_crst);
532
533   TRACE("ending\n");
534
535   return 0;
536 }
537 /******************************************************************
538  *              JACK_bufsize_wwi
539  *
540  *              Called whenever the jack server changes the max number
541  *              of frames passed to JACK_callback
542  */
543 static int JACK_bufsize_wwi (nframes_t nframes, void *arg)
544 {
545   TRACE("the maximum buffer size is now %u frames\n", nframes);
546   return 0;
547 }
548
549 /******************************************************************
550  *              JACK_srate
551  */
552 static int JACK_srate (nframes_t nframes, void *arg)
553 {
554   TRACE("the sample rate is now %u/sec\n", nframes);
555   return 0;
556 }
557
558
559 /******************************************************************
560  *              JACK_shutdown_wwo
561  */
562 /* if this is called then jack shut down... handle this appropriately */
563 static void JACK_shutdown_wwo(void* arg)
564 {
565   WINE_WAVEOUT* wwo = arg;
566
567   wwo->client = 0; /* reset client */
568
569   TRACE("trying to reconnect after sleeping for a short while...\n");
570   
571   /* lets see if we can't reestablish the connection */
572   Sleep(750); /* pause for a short period of time */
573   if(!JACK_OpenWaveOutDevice(wwo))
574   {
575     ERR("unable to reconnect with jack...\n");
576   }
577 }
578
579 /******************************************************************
580  *              JACK_shutdown_wwi
581  */
582 /* if this is called then jack shut down... handle this appropriately */
583 static void JACK_shutdown_wwi(void* arg)
584 {
585   WINE_WAVEIN* wwi = arg;
586
587   wwi->client = 0; /* reset client */
588
589   TRACE("trying to reconnect after sleeping for a short while...\n");
590   
591   /* lets see if we can't reestablish the connection */
592   Sleep(750); /* pause for a short period of time */
593   if(!JACK_OpenWaveInDevice(wwi,wwi->format.wf.nChannels))
594   {
595     ERR("unable to reconnect with jack...\n");
596   }
597 }
598
599
600 /******************************************************************
601  *              JACK_OpenWaveOutDevice
602  */
603 static int JACK_OpenWaveOutDevice(WINE_WAVEOUT* wwo)
604 {
605   const char** ports;
606   int i;
607   char client_name[64];
608   jack_port_t* out_port_l;
609   jack_port_t* out_port_r;
610   jack_client_t* client;
611   int failed = 0;
612
613   TRACE("creating jack client and setting up callbacks\n");
614
615 #if JACK_CLOSE_HACK
616   /* see if this device is already open */
617         if(wwo->client)
618         {
619           /* if this device is already in use then it is bad for us to be in here */
620           if(wwo->in_use)
621             return 0;
622
623           TRACE("using existing client\n");
624           wwo->in_use = TRUE;
625           return 1;
626         }
627 #endif
628
629         /* zero out the buffer pointer and the size of the buffer */
630         wwo->sound_buffer = 0;
631         wwo->buffer_size = 0;
632
633         /* try to become a client of the JACK server */
634         snprintf(client_name, sizeof(client_name), "wine_jack_out_%d", wwo->wDevID);
635         TRACE("client name '%s'\n", client_name);
636         if ((client = fp_jack_client_open (client_name, JackUseExactName, NULL)) == 0)
637         {
638                 /* jack has problems with shutting down clients, so lets */
639                 /* wait a short while and try once more before we give up */
640                 Sleep(250);
641                 if ((client = fp_jack_client_open (client_name, JackUseExactName, NULL)) == 0)
642                 {
643                   ERR("jack server not running?\n");
644                   return 0;
645                 }
646         }
647                         
648         /* tell the JACK server to call `JACK_callback_wwo()' whenever
649            there is work to be done. */
650         fp_jack_set_process_callback (client, JACK_callback_wwo, wwo);
651         
652         /* tell the JACK server to call `JACK_bufsize_wwo()' whenever   
653            the maximum number of frames that will be passed
654            to `JACK_Callback()' changes */
655         fp_jack_set_buffer_size_callback (client, JACK_bufsize_wwo, wwo);
656
657         /* tell the JACK server to call `srate()' whenever
658            the sample rate of the system changes. */
659         fp_jack_set_sample_rate_callback (client, JACK_srate, wwo);
660
661         /* tell the JACK server to call `jack_shutdown()' if
662            it ever shuts down, either entirely, or if it
663            just decides to stop calling us. */
664         fp_jack_on_shutdown (client, JACK_shutdown_wwo, wwo);
665         
666         /* display the current sample rate. once the client is activated
667            (see below), you should rely on your own sample rate
668            callback (see above) for this value. */
669         wwo->sample_rate = fp_jack_get_sample_rate(client);
670         TRACE("engine sample rate: %lu\n", wwo->sample_rate);
671           
672         /* create the left and right channel output ports */
673         /* jack's ports are all mono so for stereo you need two */
674         out_port_l = fp_jack_port_register (client, "out_l",
675                          JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
676
677         out_port_r = fp_jack_port_register (client, "out_r",
678                          JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
679
680         TRACE("Created ports. (%p) (%p)\n",out_port_l, out_port_r);
681
682         /* save away important values to the WINE_WAVEOUT struct */
683         wwo->client = client;
684         wwo->out_port_l = out_port_l;
685         wwo->out_port_r = out_port_r;
686
687 #if JACK_CLOSE_HACK
688         wwo->in_use = TRUE; /* mark this device as in use since it now is ;-) */
689 #endif
690
691         /* set initial buffer size */
692         JACK_bufsize_wwo (fp_jack_get_buffer_size(client),wwo);
693
694         /* tell the JACK server that we are ready to roll */
695         if (fp_jack_activate (client))
696         {
697           ERR( "cannot activate client\n");
698           return 0;
699         }
700
701         TRACE("jack activate.\n");
702         /* figure out what the ports that we want to output on are */
703         /* NOTE: we do this instead of using stuff like "alsa_pcm:playback_X" because */
704         /*   this way works if names are changed */
705         ports = fp_jack_get_ports(client, NULL, NULL, JackPortIsPhysical|JackPortIsInput);
706
707         /* display a trace of the output ports we found */
708         for(i = 0; ports[i]; i++)
709         {
710           TRACE("ports[%d] = '%s'\n", i, ports[i]);
711         }
712
713         if(!ports)
714         {
715           ERR("jack_get_ports() failed to find 'JackPortIsPhysical|JackPortIsInput'\n");
716         }
717
718         /* connect the ports. Note: you can't do this before
719            the client is activated (this may change in the future).
720         */ 
721         /* we want to connect to two ports so we have stereo output ;-) */
722
723         if(fp_jack_connect(client, fp_jack_port_name(out_port_l), ports[0]))
724         {
725           ERR ("cannot connect to output port %d('%s')\n", 0, ports[0]);
726           failed = 1;
727         }
728
729         if(fp_jack_connect(client, fp_jack_port_name(out_port_r), ports[1]))
730         {
731           ERR ("cannot connect to output port %d('%s')\n", 1, ports[1]);
732           failed = 1;
733         }
734
735         free(ports); /* free the returned array of ports */
736
737         /* if something failed we need to shut the client down and return 0 */
738         if(failed)
739         {
740 #if JACK_CLOSE_HACK
741           JACK_CloseWaveOutDevice(wwo, TRUE);
742 #else
743           JACK_CloseWaveOutDevice(wwo);
744 #endif
745           return 0;
746         }
747
748         return 1; /* return success */
749 }
750
751 /******************************************************************
752  *              JACK_CloseWaveOutDevice
753  *
754  *      Close the connection to the server cleanly.
755  *  If close_client is TRUE we close the client for this device instead of
756  *    just marking the device as in_use(JACK_CLOSE_HACK only)
757  */
758 #if JACK_CLOSE_HACK
759 static void     JACK_CloseWaveOutDevice(WINE_WAVEOUT* wwo, BOOL close_client)
760 #else
761 static void     JACK_CloseWaveOutDevice(WINE_WAVEOUT* wwo)
762 #endif
763 {
764 #if JACK_CLOSE_HACK
765   TRACE("wDevID: %d, close_client (wwo): %d\n", wwo->wDevID, close_client);
766 #else
767   TRACE("wDevID: %d\n", wwo->wDevID);
768 #endif
769
770 #if JACK_CLOSE_HACK
771   if(close_client)
772   {
773 #endif
774     fp_jack_deactivate(wwo->client); /* supposed to help the jack_client_close() to succeed */
775     fp_jack_client_close (wwo->client);
776
777     EnterCriticalSection(&wwo->access_crst);
778     wwo->client = 0; /* reset client */
779     HeapFree(GetProcessHeap(), 0, wwo->sound_buffer); /* free buffer memory */
780     wwo->sound_buffer = 0;
781     wwo->buffer_size = 0; /* zero out size of the buffer */
782     LeaveCriticalSection(&wwo->access_crst);
783 #if JACK_CLOSE_HACK
784   } else
785   {
786     EnterCriticalSection(&wwo->access_crst);
787     TRACE("setting in_use to FALSE\n");
788     wwo->in_use = FALSE;
789     LeaveCriticalSection(&wwo->access_crst);
790   }
791 #endif
792 }
793
794 /******************************************************************
795  *              JACK_CloseWaveInDevice
796  *
797  *      Close the connection to the server cleanly.
798  *  If close_client is TRUE we close the client for this device instead of
799  *    just marking the device as in_use(JACK_CLOSE_HACK only)
800  */
801 #if JACK_CLOSE_HACK
802 static void     JACK_CloseWaveInDevice(WINE_WAVEIN* wwi, BOOL close_client)
803 #else
804 static void     JACK_CloseWaveInDevice(WINE_WAVEIN* wwi)
805 #endif
806 {
807 #if JACK_CLOSE_HACK
808   TRACE("wDevID: %d, close_client (wwi): %d\n", wwi->wDevID, close_client);
809 #else
810   TRACE("wDevID: %d\n", wwi->wDevID);
811 #endif
812
813 #if JACK_CLOSE_HACK
814   if(close_client)
815   {
816 #endif
817     fp_jack_deactivate(wwi->client); /* supposed to help the jack_client_close() to succeed */
818     fp_jack_client_close (wwi->client);
819
820     EnterCriticalSection(&wwi->access_crst);
821     wwi->client = 0; /* reset client */
822     HeapFree(GetProcessHeap(), 0, wwi->sound_buffer); /* free buffer memory */
823     wwi->sound_buffer = 0;
824     wwi->buffer_size = 0; /* zero out size of the buffer */
825     LeaveCriticalSection(&wwi->access_crst);
826 #if JACK_CLOSE_HACK
827   } else
828   {
829     EnterCriticalSection(&wwi->access_crst);
830     TRACE("setting in_use to FALSE\n");
831     wwi->in_use = FALSE;
832     LeaveCriticalSection(&wwi->access_crst);
833   }
834 #endif
835 }
836
837 static int WAVE_loadcount;
838
839 /******************************************************************
840  *              JACK_WaveRelease
841  *
842  *
843  */
844 static LONG JACK_WaveRelease(void)
845
846   int iDevice;
847
848   if (--WAVE_loadcount)
849       return 1;
850   TRACE("closing all open waveout devices\n");
851
852   /* close all open output devices */
853   for(iDevice = 0; iDevice < MAX_WAVEOUTDRV; iDevice++)
854   {
855     TRACE("iDevice == %d\n", iDevice);
856     if(WOutDev[iDevice].client)
857     {
858 #if JACK_CLOSE_HACK
859       JACK_CloseWaveOutDevice(&WOutDev[iDevice], TRUE); /* close the device, FORCE the client to close */
860 #else
861       JACK_CloseWaveOutDevice(&WOutDev[iDevice]); /* close the device, FORCE the client to close */
862 #endif
863       DeleteCriticalSection(&(WOutDev[iDevice].access_crst)); /* delete the critical section */
864     }
865   }
866
867   TRACE("closing all open wavein devices\n");
868
869   /* close all open input devices */
870   for(iDevice = 0; iDevice < MAX_WAVEINDRV; iDevice++)
871   {
872     TRACE("iDevice == %d\n", iDevice);
873     if(WInDev[iDevice].client)
874     {
875 #if JACK_CLOSE_HACK
876       JACK_CloseWaveInDevice(&WInDev[iDevice], TRUE); /* close the device, FORCE the client to close */
877 #else
878       JACK_CloseWaveInDevice(&WInDev[iDevice]); /* close the device, FORCE the client to close */
879 #endif
880       DeleteCriticalSection(&(WInDev[iDevice].access_crst)); /* delete the critical section */
881     }
882   }
883
884   TRACE("returning 1\n");
885
886   return 1;
887 }
888
889 /******************************************************************
890  *              JACK_WaveInit
891  *
892  * Initialize internal structures from JACK server info
893  */
894 static LONG JACK_WaveInit(void)
895 {
896     int i;
897     CHAR szPname[MAXPNAMELEN];
898
899     TRACE("called\n");
900     if (WAVE_loadcount++)
901         return 1;
902
903     /* setup function pointers */
904 #define LOAD_FUNCPTR(f) if((fp_##f = wine_dlsym(jackhandle, #f, NULL, 0)) == NULL) goto sym_not_found;    
905     LOAD_FUNCPTR(jack_activate);
906     LOAD_FUNCPTR(jack_connect);
907     LOAD_FUNCPTR(jack_client_open);
908     LOAD_FUNCPTR(jack_client_close);
909     LOAD_FUNCPTR(jack_deactivate);
910     LOAD_FUNCPTR(jack_set_process_callback);
911     LOAD_FUNCPTR(jack_set_buffer_size_callback);
912     LOAD_FUNCPTR(jack_set_sample_rate_callback);
913     LOAD_FUNCPTR(jack_on_shutdown);
914     LOAD_FUNCPTR(jack_get_sample_rate);
915     LOAD_FUNCPTR(jack_port_register);
916     LOAD_FUNCPTR(jack_port_get_buffer);
917     LOAD_FUNCPTR(jack_get_ports);
918     LOAD_FUNCPTR(jack_port_name);
919     LOAD_FUNCPTR(jack_get_buffer_size);
920 #undef LOAD_FUNCPTR
921
922     /* start with output device */
923
924     for (i = 0; i < MAX_WAVEOUTDRV; ++i)
925     {
926       WOutDev[i].client = 0; /* initialize the client to 0 */
927
928 #if JACK_CLOSE_HACK
929       WOutDev[i].in_use = FALSE;
930       WInDev[i].in_use  = FALSE;
931 #endif
932
933       memset(&WOutDev[i].caps, 0, sizeof(WOutDev[i].caps));
934
935       WOutDev[i].caps.wMid = 0x00FF;    /* Manufac ID */
936       WOutDev[i].caps.wPid = 0x0001;    /* Product ID */
937       snprintf(szPname, sizeof(szPname), "JACK WaveOut %d", i);
938       MultiByteToWideChar(CP_ACP, 0, szPname, -1, WOutDev[i].caps.szPname, sizeof(WOutDev[i].caps.szPname)/sizeof(WCHAR));
939       snprintf(WOutDev[i].interface_name, sizeof(WOutDev[i].interface_name), "winejack: %d", i);
940
941       WOutDev[i].caps.vDriverVersion = 0x0100;
942       WOutDev[i].caps.dwFormats = 0x00000000;
943       WOutDev[i].caps.dwSupport = WAVECAPS_VOLUME;
944     
945       WOutDev[i].caps.wChannels = 2;
946       WOutDev[i].caps.dwSupport |= WAVECAPS_LRVOLUME;
947
948 /* NOTE: we don't support any 8 bit modes so note that */
949 /*      WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4M08;
950       WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4S08; */
951       WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4S16;
952       WOutDev[i].caps.dwFormats |= WAVE_FORMAT_4M16;
953 /*      WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2M08;
954       WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2S08; */
955       WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2M16;
956       WOutDev[i].caps.dwFormats |= WAVE_FORMAT_2S16;
957 /*      WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1M08;
958       WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1S08;*/
959       WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1M16;
960       WOutDev[i].caps.dwFormats |= WAVE_FORMAT_1S16;
961     }
962
963     /* then do input device */
964     for (i = 0; i < MAX_WAVEINDRV; ++i)
965     {
966         /* TODO: we should initialize read stuff here */
967         memset(&WInDev[i].caps, 0, sizeof(WInDev[i].caps));
968
969         WInDev[i].caps.wMid = 0x00FF;
970         WInDev[i].caps.wPid = 0x0001;
971         snprintf(szPname, sizeof(szPname), "JACK WaveIn %d", i);
972         MultiByteToWideChar(CP_ACP, 0, szPname, -1, WInDev[i].caps.szPname, sizeof(WInDev[i].caps.szPname)/sizeof(WCHAR));
973         snprintf(WInDev[i].interface_name, sizeof(WInDev[i].interface_name), "winejack: %d", i);
974
975         WInDev[i].caps.vDriverVersion = 0x0100;
976
977         WInDev[i].caps.wChannels = 0x2;
978         /* NOTE: we don't support any 8 bit modes so note that */
979 /*      WInDev[i].caps.dwFormats |= WAVE_FORMAT_4M08;
980         WInDev[i].caps.dwFormats |= WAVE_FORMAT_4S08; */
981         WInDev[i].caps.dwFormats |= WAVE_FORMAT_4S16;
982         WInDev[i].caps.dwFormats |= WAVE_FORMAT_4M16;
983 /*      WInDev[i].caps.dwFormats |= WAVE_FORMAT_2M08;
984         WInDev[i].caps.dwFormats |= WAVE_FORMAT_2S08; */
985         WInDev[i].caps.dwFormats |= WAVE_FORMAT_2M16;
986         WInDev[i].caps.dwFormats |= WAVE_FORMAT_2S16;
987 /*      WInDev[i].caps.dwFormats |= WAVE_FORMAT_1M08;
988         WInDev[i].caps.dwFormats |= WAVE_FORMAT_1S08;*/
989         WInDev[i].caps.dwFormats |= WAVE_FORMAT_1M16;
990         WInDev[i].caps.dwFormats |= WAVE_FORMAT_1S16;
991         WInDev[i].caps.wReserved1 = 0;
992     }
993     
994     return 1;           /* return success */
995
996 /* error path for function pointer loading errors */
997 sym_not_found:
998     WINE_MESSAGE(
999       "Wine cannot find certain functions that it needs inside the jack"
1000       "library.  To enable Wine to use the jack audio server please "
1001       "install libjack\n");
1002     wine_dlclose(jackhandle, NULL, 0);
1003     jackhandle = NULL;
1004     return FALSE;
1005 }
1006
1007 /*======================================================================*
1008  *                  Low level WAVE OUT implementation                   *
1009  *======================================================================*/
1010
1011 /**************************************************************************
1012  *                      wodNotifyClient                 [internal]
1013  */
1014 static DWORD wodNotifyClient(WINE_WAVEOUT* wwo, WORD wMsg, DWORD_PTR dwParam1,
1015                              DWORD_PTR dwParam2)
1016 {
1017     TRACE("wMsg = %04X dwParm1 = %08lX dwParam2 = %08lX\n", wMsg, dwParam1, dwParam2);
1018
1019     switch (wMsg) {
1020     case WOM_OPEN:
1021     case WOM_CLOSE:
1022     case WOM_DONE:
1023       if (wwo->wFlags != DCB_NULL &&
1024         !DriverCallback(wwo->waveDesc.dwCallback, wwo->wFlags,
1025           (HDRVR)wwo->waveDesc.hWave, wMsg, wwo->waveDesc.dwInstance,
1026           dwParam1, dwParam2))
1027       {
1028         WARN("can't notify client !\n");
1029         return MMSYSERR_ERROR;
1030       }
1031     break;
1032     default:
1033       FIXME("Unknown callback message %u\n", wMsg);
1034         return MMSYSERR_INVALPARAM;
1035     }
1036     return MMSYSERR_NOERROR;
1037 }
1038
1039 /**************************************************************************
1040  *                              wodHelper_BeginWaveHdr          [internal]
1041  *
1042  * Makes the specified lpWaveHdr the currently playing wave header.
1043  * If the specified wave header is a begin loop and we're not already in
1044  * a loop, setup the loop.
1045  */
1046 static void wodHelper_BeginWaveHdr(WINE_WAVEOUT* wwo, LPWAVEHDR lpWaveHdr)
1047 {
1048     EnterCriticalSection(&wwo->access_crst);
1049
1050     wwo->lpPlayPtr = lpWaveHdr;
1051
1052     if (!lpWaveHdr)
1053     {
1054        LeaveCriticalSection(&wwo->access_crst);
1055        return;
1056     }
1057
1058     if (lpWaveHdr->dwFlags & WHDR_BEGINLOOP)
1059     {
1060       if (wwo->lpLoopPtr)
1061       {
1062         WARN("Already in a loop. Discarding loop on this header (%p)\n", lpWaveHdr);
1063         TRACE("Already in a loop. Discarding loop on this header (%p)\n", lpWaveHdr);
1064       } else
1065       {
1066         TRACE("Starting loop (%dx) with %p\n", lpWaveHdr->dwLoops, lpWaveHdr);
1067         wwo->lpLoopPtr = lpWaveHdr;
1068         /* Windows does not touch WAVEHDR.dwLoops,
1069          * so we need to make an internal copy */
1070         wwo->dwLoops = lpWaveHdr->dwLoops;
1071       }
1072     }
1073     wwo->dwPartialOffset = 0;
1074
1075     LeaveCriticalSection(&wwo->access_crst);
1076 }
1077
1078
1079 /**************************************************************************
1080  *                              wodHelper_PlayPtrNext           [internal]
1081  *
1082  * Advance the play pointer to the next waveheader, looping if required.
1083  */
1084 static LPWAVEHDR wodHelper_PlayPtrNext(WINE_WAVEOUT* wwo)
1085 {
1086   LPWAVEHDR lpWaveHdr;
1087
1088   EnterCriticalSection(&wwo->access_crst);
1089
1090   lpWaveHdr = wwo->lpPlayPtr;
1091
1092   wwo->dwPartialOffset = 0;
1093   if ((lpWaveHdr->dwFlags & WHDR_ENDLOOP) && wwo->lpLoopPtr)
1094   {
1095     /* We're at the end of a loop, loop if required */
1096     if (--wwo->dwLoops > 0)
1097     {
1098       wwo->lpPlayPtr = wwo->lpLoopPtr;
1099     } else
1100     {
1101       /* Handle overlapping loops correctly */
1102       if (wwo->lpLoopPtr != lpWaveHdr && (lpWaveHdr->dwFlags & WHDR_BEGINLOOP)) {
1103         FIXME("Correctly handled case ? (ending loop buffer also starts a new loop)\n");
1104         /* shall we consider the END flag for the closing loop or for
1105          * the opening one or for both ???
1106          * code assumes for closing loop only
1107          */
1108       } else
1109       {
1110         lpWaveHdr = lpWaveHdr->lpNext;
1111       }
1112       wwo->lpLoopPtr = NULL;
1113       wodHelper_BeginWaveHdr(wwo, lpWaveHdr);
1114     }
1115   } else
1116   {
1117      /* We're not in a loop.  Advance to the next wave header */
1118     TRACE("not inside of a loop, advancing to next wave header\n");
1119     wodHelper_BeginWaveHdr(wwo, lpWaveHdr = lpWaveHdr->lpNext);
1120   }
1121
1122   LeaveCriticalSection(&wwo->access_crst);
1123
1124   return lpWaveHdr;
1125 }
1126
1127 /* if force is TRUE then notify the client that all the headers were completed */
1128 static DWORD wodHelper_NotifyCompletions(WINE_WAVEOUT* wwo, BOOL force)
1129 {
1130   LPWAVEHDR             lpWaveHdr;
1131   DWORD retval;
1132
1133   TRACE("called\n");
1134
1135   EnterCriticalSection(&wwo->access_crst);
1136
1137   /* Start from lpQueuePtr and keep notifying until:
1138    * - we hit an unwritten wavehdr
1139    * - we hit the beginning of a running loop
1140    * - we hit a wavehdr which hasn't finished playing
1141    */
1142   while ((lpWaveHdr = wwo->lpQueuePtr) &&
1143            (force || 
1144             (lpWaveHdr != wwo->lpPlayPtr &&
1145              lpWaveHdr != wwo->lpLoopPtr)))
1146   {
1147     wwo->lpQueuePtr = lpWaveHdr->lpNext;
1148
1149     lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1150     lpWaveHdr->dwFlags |= WHDR_DONE;
1151     TRACE("notifying client: lpWaveHdr=(%p) lpPlayPtr=(%p) dwFlags=(%d)\n",
1152           lpWaveHdr, wwo->lpPlayPtr, lpWaveHdr->dwFlags);
1153
1154     wodNotifyClient(wwo, WOM_DONE, (DWORD_PTR)lpWaveHdr, 0);
1155   }
1156   TRACE("Not notifying client: lpWaveHdr=(%p) lpPlayPtr=(%p) lpLoopPtr=(%p)\n",
1157         lpWaveHdr, wwo->lpPlayPtr, wwo->lpLoopPtr);
1158   retval = (lpWaveHdr && lpWaveHdr != wwo->lpPlayPtr && lpWaveHdr != 
1159               wwo->lpLoopPtr) ? 0 : INFINITE;
1160
1161   LeaveCriticalSection(&wwo->access_crst);
1162
1163   return retval;
1164 }
1165
1166 /**************************************************************************
1167  *                              wodHelper_Reset                 [internal]
1168  *
1169  * Resets current output stream.
1170  */
1171 static  void  wodHelper_Reset(WINE_WAVEOUT* wwo, BOOL reset)
1172 {
1173     EnterCriticalSection(&wwo->access_crst);
1174  
1175     /* updates current notify list */
1176     wodHelper_NotifyCompletions(wwo, FALSE);
1177
1178     if (reset)
1179     {
1180         /* remove all wave headers and notify client that all headers were completed */
1181         wodHelper_NotifyCompletions(wwo, TRUE);
1182
1183         wwo->lpPlayPtr = wwo->lpQueuePtr = wwo->lpLoopPtr = NULL;
1184         wwo->state = WINE_WS_STOPPED;
1185         wwo->dwPlayedTotal = wwo->dwWrittenTotal = wwo->bytesInJack = 0;
1186
1187         wwo->dwPartialOffset = 0;        /* Clear partial wavehdr */
1188     } else
1189     {
1190         if (wwo->lpLoopPtr)
1191         {
1192             /* complicated case, not handled yet (could imply modifying the loop counter) */
1193             FIXME("Pausing while in loop isn't correctly handled yet, expect strange results\n");
1194             wwo->lpPlayPtr = wwo->lpLoopPtr;
1195             wwo->dwPartialOffset = 0;
1196             wwo->dwWrittenTotal = wwo->dwPlayedTotal; /* this is wrong !!! */
1197         } else
1198         {
1199             LPWAVEHDR   ptr;
1200             DWORD       sz = wwo->dwPartialOffset;
1201
1202             /* reset all the data as if we had written only up to lpPlayedTotal bytes */
1203             /* compute the max size playable from lpQueuePtr */
1204             for (ptr = wwo->lpQueuePtr; ptr != wwo->lpPlayPtr; ptr = ptr->lpNext)
1205             {
1206                 sz += ptr->dwBufferLength;
1207             }
1208
1209             /* because the reset lpPlayPtr will be lpQueuePtr */
1210             if (wwo->dwWrittenTotal > wwo->dwPlayedTotal + sz) ERR("doh\n");
1211             wwo->dwPartialOffset = sz - (wwo->dwWrittenTotal - wwo->dwPlayedTotal);
1212             wwo->dwWrittenTotal = wwo->dwPlayedTotal;
1213             wwo->lpPlayPtr = wwo->lpQueuePtr;
1214         }
1215
1216         wwo->state = WINE_WS_PAUSED;
1217     }
1218  
1219     LeaveCriticalSection(&wwo->access_crst);
1220 }
1221
1222 /**************************************************************************
1223  *                      wodGetDevCaps                           [internal]
1224  */
1225 static DWORD wodGetDevCaps(WORD wDevID, LPWAVEOUTCAPSW lpCaps, DWORD dwSize)
1226 {
1227     TRACE("(%u, %p, %u);\n", wDevID, lpCaps, dwSize);
1228     
1229     if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
1230     
1231     if (wDevID >= MAX_WAVEOUTDRV)
1232     {
1233       TRACE("MAX_WAVOUTDRV reached !\n");
1234       return MMSYSERR_BADDEVICEID;
1235     }
1236
1237     TRACE("dwSupport=(0x%x), dwFormats=(0x%x)\n", WOutDev[wDevID].caps.dwSupport, WOutDev[wDevID].caps.dwFormats);
1238     memcpy(lpCaps, &WOutDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
1239     return MMSYSERR_NOERROR;
1240 }
1241
1242 /**************************************************************************
1243  *                              wodOpen                         [internal]
1244  *
1245  * NOTE: doesn't it seem like there is a race condition if you try to open 
1246  * the same device twice?
1247  */
1248 static DWORD wodOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
1249 {
1250     WINE_WAVEOUT*       wwo;
1251     DWORD retval;
1252
1253     TRACE("(%u, %p, %08X);\n", wDevID, lpDesc, dwFlags);
1254     if (lpDesc == NULL)
1255     {
1256       WARN("Invalid Parameter !\n");
1257       return MMSYSERR_INVALPARAM;
1258     }
1259     if (wDevID >= MAX_WAVEOUTDRV) {
1260       TRACE("MAX_WAVOUTDRV reached !\n");
1261       return MMSYSERR_BADDEVICEID;
1262     }
1263
1264 #if JACK_CLOSE_HACK
1265     if(WOutDev[wDevID].client && WOutDev[wDevID].in_use)
1266 #else
1267     if(WOutDev[wDevID].client)
1268 #endif
1269     {
1270       TRACE("device %d already allocated\n", wDevID);
1271       return MMSYSERR_ALLOCATED;
1272     }
1273
1274     /* Only the PCM format is supported so far...
1275      * Also we only support 16 bit mode.
1276      */
1277     if (lpDesc->lpFormat->wFormatTag != WAVE_FORMAT_PCM ||
1278       lpDesc->lpFormat->nChannels == 0 ||
1279       lpDesc->lpFormat->nSamplesPerSec == 0 ||
1280       lpDesc->lpFormat->wBitsPerSample != 16)
1281     {
1282       WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
1283        lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1284        lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
1285       return WAVERR_BADFORMAT;
1286     }
1287
1288     if (dwFlags & WAVE_FORMAT_QUERY)
1289     {
1290       TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
1291        lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
1292        lpDesc->lpFormat->nSamplesPerSec);
1293       return MMSYSERR_NOERROR;
1294     }
1295
1296     wwo = &WOutDev[wDevID];
1297     wwo->wDevID = wDevID;
1298
1299     /* Set things up before we call JACK_OpenWaveOutDevice because */
1300     /* we will start getting callbacks before JACK_OpenWaveOutDevice */
1301     /* even returns and we want to be initialized before then */
1302     wwo->state = WINE_WS_STOPPED; /* start in a stopped state */
1303     wwo->dwPlayedTotal = 0; /* zero out these totals */
1304     wwo->dwWrittenTotal = 0;
1305     wwo->bytesInJack = 0;
1306     wwo->tickCountMS = 0;
1307
1308     /* Initialize volume to full level */
1309     wwo->volume_left = 100;
1310     wwo->volume_right = 100;
1311
1312     InitializeCriticalSection(&wwo->access_crst); /* initialize the critical section */
1313     EnterCriticalSection(&wwo->access_crst);
1314
1315     dwFlags &= ~WAVE_DIRECTSOUND;  /* direct sound not supported, ignore the flag */
1316
1317     wwo->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
1318
1319     wwo->waveDesc = *lpDesc;
1320     memcpy(&wwo->format,   lpDesc->lpFormat, sizeof(PCMWAVEFORMAT));
1321
1322     /* open up jack ports for this device */
1323     if (!JACK_OpenWaveOutDevice(&WOutDev[wDevID]))
1324     {
1325       ERR("JACK_OpenWaveOutDevice(%d) failed\n", wDevID);
1326       LeaveCriticalSection(&wwo->access_crst);
1327       DeleteCriticalSection(&wwo->access_crst); /* delete the critical section so we can initialize it again from wodOpen() */
1328       return MMSYSERR_ERROR;            /* return unspecified error */
1329     }
1330
1331     LeaveCriticalSection(&wwo->access_crst);
1332
1333     /* display the current wave format */
1334     TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%u, nSamplesPerSec=%u, nChannels=%u nBlockAlign=%u!\n",
1335     wwo->format.wBitsPerSample, wwo->format.wf.nAvgBytesPerSec,
1336     wwo->format.wf.nSamplesPerSec, wwo->format.wf.nChannels,
1337     wwo->format.wf.nBlockAlign);
1338
1339     /* make sure that we have the same sample rate in our audio stream */
1340     /* as we do in the jack server */
1341     if(wwo->format.wf.nSamplesPerSec != wwo->sample_rate)
1342     {
1343       TRACE("error: jack server sample rate is '%ld', wave sample rate is '%d'\n",
1344          wwo->sample_rate, wwo->format.wf.nSamplesPerSec);
1345
1346 #if JACK_CLOSE_HACK
1347       JACK_CloseWaveOutDevice(wwo, FALSE); /* close this device, don't force the client to close */
1348 #else
1349       JACK_CloseWaveOutDevice(wwo); /* close this device */
1350 #endif
1351       DeleteCriticalSection(&wwo->access_crst); /* delete the critical section so we can initialize it again from wodOpen() */
1352       return WAVERR_BADFORMAT;
1353     }
1354
1355     /* check for an invalid number of bits per sample */
1356     if (wwo->format.wBitsPerSample == 0)
1357     {
1358       WARN("Resetting zeroed wBitsPerSample\n");
1359       wwo->format.wBitsPerSample = 8 *
1360       (wwo->format.wf.nAvgBytesPerSec /
1361        wwo->format.wf.nSamplesPerSec) /
1362        wwo->format.wf.nChannels;
1363     }
1364
1365     EnterCriticalSection(&wwo->access_crst);
1366     retval = wodNotifyClient(wwo, WOM_OPEN, 0, 0);
1367     LeaveCriticalSection(&wwo->access_crst);
1368
1369     return retval;
1370 }
1371
1372 /**************************************************************************
1373  *                              wodClose                        [internal]
1374  */
1375 static DWORD wodClose(WORD wDevID)
1376 {
1377     DWORD               ret = MMSYSERR_NOERROR;
1378     WINE_WAVEOUT*       wwo;
1379
1380     TRACE("(%u);\n", wDevID);
1381
1382     if (wDevID >= MAX_WAVEOUTDRV || !WOutDev[wDevID].client)
1383     {
1384       WARN("bad device ID !\n");
1385       return MMSYSERR_BADDEVICEID;
1386     }
1387     
1388     wwo = &WOutDev[wDevID];
1389     if (wwo->lpQueuePtr)
1390     {
1391       WARN("buffers still playing !\n");
1392       ret = WAVERR_STILLPLAYING;
1393     } else
1394     {
1395       /* sanity check: this should not happen since the device must have been reset before */
1396       if (wwo->lpQueuePtr || wwo->lpPlayPtr) ERR("out of sync\n");
1397
1398       wwo->state = WINE_WS_CLOSED; /* mark the device as closed */
1399
1400 #if JACK_CLOSE_HACK
1401       JACK_CloseWaveOutDevice(wwo, FALSE); /* close the jack device, DO NOT force the client to close */
1402 #else
1403       JACK_CloseWaveOutDevice(wwo); /* close the jack device */
1404 #endif
1405       DeleteCriticalSection(&wwo->access_crst); /* delete the critical section so we can initialize it again from wodOpen() */
1406
1407       ret = wodNotifyClient(wwo, WOM_CLOSE, 0, 0);
1408     }
1409
1410     return ret;
1411 }
1412
1413
1414 /**************************************************************************
1415  *                              wodWrite                        [internal]
1416  * 
1417  */
1418 static DWORD wodWrite(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
1419 {
1420     LPWAVEHDR*wh;
1421     WINE_WAVEOUT *wwo;
1422
1423     TRACE("(%u, %p, %08X);\n", wDevID, lpWaveHdr, dwSize);
1424     
1425     /* first, do the sanity checks... */
1426     if (wDevID >= MAX_WAVEOUTDRV || !WOutDev[wDevID].client)
1427     {
1428       WARN("bad dev ID !\n");
1429       return MMSYSERR_BADDEVICEID;
1430     }
1431
1432     wwo = &WOutDev[wDevID];
1433
1434     if (lpWaveHdr->lpData == NULL || !(lpWaveHdr->dwFlags & WHDR_PREPARED))
1435     {
1436       TRACE("unprepared\n");
1437       return WAVERR_UNPREPARED;
1438     }
1439     
1440     if (lpWaveHdr->dwFlags & WHDR_INQUEUE) 
1441     {
1442       TRACE("still playing\n");
1443       return WAVERR_STILLPLAYING;
1444     }
1445
1446     lpWaveHdr->dwFlags &= ~WHDR_DONE;
1447     lpWaveHdr->dwFlags |= WHDR_INQUEUE;
1448     lpWaveHdr->lpNext = 0;
1449
1450     EnterCriticalSection(&wwo->access_crst);
1451
1452     /* insert buffer at the end of queue */
1453     for (wh = &(wwo->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
1454     *wh = lpWaveHdr;
1455
1456     if (!wwo->lpPlayPtr)
1457       wodHelper_BeginWaveHdr(wwo,lpWaveHdr);
1458     if (wwo->state == WINE_WS_STOPPED)
1459       wwo->state = WINE_WS_PLAYING;
1460     LeaveCriticalSection(&wwo->access_crst);
1461
1462     return MMSYSERR_NOERROR;
1463 }
1464
1465 /**************************************************************************
1466  *                      wodPause                                [internal]
1467  */
1468 static DWORD wodPause(WORD wDevID)
1469 {
1470   TRACE("(%u);!\n", wDevID);
1471     
1472   if (wDevID >= MAX_WAVEOUTDRV || !WOutDev[wDevID].client)
1473   {
1474     WARN("bad device ID !\n");
1475     return MMSYSERR_BADDEVICEID;
1476   }
1477     
1478   TRACE("[3-PAUSING]\n");
1479
1480   EnterCriticalSection(&(WOutDev[wDevID].access_crst));
1481   wodHelper_Reset(&WOutDev[wDevID], FALSE);
1482   LeaveCriticalSection(&(WOutDev[wDevID].access_crst));
1483
1484   return MMSYSERR_NOERROR;
1485 }
1486
1487 /**************************************************************************
1488  *                      wodRestart                              [internal]
1489  */
1490 static DWORD wodRestart(WORD wDevID)
1491 {
1492     TRACE("(%u);\n", wDevID);
1493
1494     if (wDevID >= MAX_WAVEOUTDRV || !WOutDev[wDevID].client)
1495     {
1496       WARN("bad device ID !\n");
1497       return MMSYSERR_BADDEVICEID;
1498     }
1499
1500     if (WOutDev[wDevID].state == WINE_WS_PAUSED)
1501     {
1502       EnterCriticalSection(&(WOutDev[wDevID].access_crst));
1503       WOutDev[wDevID].state = WINE_WS_PLAYING;
1504       LeaveCriticalSection(&(WOutDev[wDevID].access_crst));
1505     }
1506     
1507     return MMSYSERR_NOERROR;
1508 }
1509
1510 /**************************************************************************
1511  *                      wodReset                                [internal]
1512  */
1513 static DWORD wodReset(WORD wDevID)
1514 {
1515     TRACE("(%u);\n", wDevID);
1516     
1517     if (wDevID >= MAX_WAVEOUTDRV || !WOutDev[wDevID].client)
1518     {
1519       WARN("bad device ID !\n");
1520       return MMSYSERR_BADDEVICEID;
1521     }
1522
1523     EnterCriticalSection(&(WOutDev[wDevID].access_crst));
1524     wodHelper_Reset(&WOutDev[wDevID], TRUE);
1525     LeaveCriticalSection(&(WOutDev[wDevID].access_crst));
1526
1527     return MMSYSERR_NOERROR;
1528 }
1529
1530 /**************************************************************************
1531  *                              wodGetPosition                  [internal]
1532  */
1533 static DWORD wodGetPosition(WORD wDevID, LPMMTIME lpTime, DWORD uSize)
1534 {
1535     DWORD               val;
1536     WINE_WAVEOUT*       wwo;
1537     DWORD elapsedMS;
1538
1539     TRACE("(%u, %p, %u);\n", wDevID, lpTime, uSize);
1540
1541     if (wDevID >= MAX_WAVEOUTDRV || !WOutDev[wDevID].client)
1542     {
1543       WARN("bad device ID !\n");
1544       return MMSYSERR_BADDEVICEID;
1545     }
1546
1547     /* if null pointer to time structure return error */
1548     if (lpTime == NULL) return MMSYSERR_INVALPARAM;
1549
1550     wwo = &WOutDev[wDevID];
1551
1552     EnterCriticalSection(&(WOutDev[wDevID].access_crst));
1553     val = wwo->dwPlayedTotal;
1554     elapsedMS = GetTickCount() - wwo->tickCountMS;
1555     LeaveCriticalSection(&(WOutDev[wDevID].access_crst));
1556
1557     /* account for the bytes played since the last JACK_Callback() */
1558     val+=((elapsedMS * wwo->format.wf.nAvgBytesPerSec) / 1000);
1559
1560     return bytes_to_mmtime(lpTime, val, &wwo->format);
1561 }
1562
1563 /**************************************************************************
1564  *                              wodBreakLoop                    [internal]
1565  */
1566 static DWORD wodBreakLoop(WORD wDevID)
1567 {
1568   TRACE("(%u);\n", wDevID);
1569
1570   if (wDevID >= MAX_WAVEOUTDRV || !WOutDev[wDevID].client)
1571   {
1572     WARN("bad device ID !\n");
1573     return MMSYSERR_BADDEVICEID;
1574   }
1575
1576   EnterCriticalSection(&(WOutDev[wDevID].access_crst));
1577
1578   if (WOutDev[wDevID].state == WINE_WS_PLAYING && WOutDev[wDevID].lpLoopPtr != NULL)
1579   {
1580     /* ensure exit at end of current loop */
1581     WOutDev[wDevID].dwLoops = 1;
1582   }
1583
1584   LeaveCriticalSection(&(WOutDev[wDevID].access_crst));
1585
1586   return MMSYSERR_NOERROR;
1587 }
1588     
1589 /**************************************************************************
1590  *                              wodGetVolume                    [internal]
1591  */
1592 static DWORD wodGetVolume(WORD wDevID, LPDWORD lpdwVol)
1593 {
1594   DWORD left, right;
1595     
1596   left = WOutDev[wDevID].volume_left;
1597   right = WOutDev[wDevID].volume_right;
1598         
1599   TRACE("(%u, %p);\n", wDevID, lpdwVol);
1600  
1601   *lpdwVol = ((left * 0xFFFFl) / 100) + (((right * 0xFFFFl) / 100) <<
1602               16);
1603     
1604   return MMSYSERR_NOERROR;
1605 }
1606
1607 /**************************************************************************
1608  *                              wodSetVolume                    [internal]
1609  */
1610 static DWORD wodSetVolume(WORD wDevID, DWORD dwParam)
1611 {
1612   DWORD left, right;
1613  
1614   left  = (LOWORD(dwParam) * 100) / 0xFFFFl;
1615   right = (HIWORD(dwParam) * 100) / 0xFFFFl;
1616  
1617   TRACE("(%u, %08X);\n", wDevID, dwParam);
1618
1619   EnterCriticalSection(&(WOutDev[wDevID].access_crst));
1620
1621   WOutDev[wDevID].volume_left = left;
1622   WOutDev[wDevID].volume_right = right;
1623
1624   LeaveCriticalSection(&(WOutDev[wDevID].access_crst));
1625
1626   return MMSYSERR_NOERROR;
1627 }
1628
1629 /**************************************************************************
1630  *                              wodGetNumDevs                   [internal]
1631  */
1632 static DWORD wodGetNumDevs(void)
1633 {
1634   return MAX_WAVEOUTDRV;
1635 }
1636
1637 /**************************************************************************
1638  *                              wodDevInterfaceSize             [internal]
1639  */
1640 static DWORD wodDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
1641 {
1642     TRACE("(%u, %p)\n", wDevID, dwParam1);
1643                                                                                                        
1644     *dwParam1 = MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].interface_name, -1,
1645                                     NULL, 0 ) * sizeof(WCHAR);
1646     return MMSYSERR_NOERROR;
1647 }
1648
1649 /**************************************************************************
1650  *                              wodDevInterface                 [internal]
1651  */
1652 static DWORD wodDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
1653 {
1654     if (dwParam2 >= MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].interface_name, -1,
1655                                         NULL, 0 ) * sizeof(WCHAR))
1656     {
1657         MultiByteToWideChar(CP_ACP, 0, WOutDev[wDevID].interface_name, -1,
1658                             dwParam1, dwParam2 / sizeof(WCHAR));
1659         return MMSYSERR_NOERROR;
1660     }
1661     return MMSYSERR_INVALPARAM;
1662 }
1663
1664 /**************************************************************************
1665  *                              wodMessage (WINEJACK.7)
1666  */
1667 DWORD WINAPI JACK_wodMessage(UINT wDevID, UINT wMsg, DWORD dwUser,
1668                              DWORD_PTR dwParam1, DWORD_PTR dwParam2)
1669 {
1670   TRACE("(%u, %04X, %08X, %08lX, %08lX);\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
1671
1672   switch (wMsg) {
1673   case DRVM_INIT:
1674     return JACK_WaveInit();
1675   case DRVM_EXIT:
1676     return JACK_WaveRelease();
1677   case DRVM_ENABLE:
1678   case DRVM_DISABLE:
1679     /* FIXME: Pretend this is supported */
1680     return 0;
1681   case WODM_OPEN:             return wodOpen(wDevID, (LPWAVEOPENDESC)dwParam1,  dwParam2);
1682   case WODM_CLOSE:            return wodClose(wDevID);
1683   case WODM_WRITE:            return wodWrite(wDevID, (LPWAVEHDR)dwParam1,              dwParam2);
1684   case WODM_PAUSE:            return wodPause(wDevID);
1685   case WODM_GETPOS:           return wodGetPosition(wDevID, (LPMMTIME)dwParam1,                 dwParam2);
1686   case WODM_BREAKLOOP:        return wodBreakLoop(wDevID);
1687   case WODM_PREPARE:          return MMSYSERR_NOTSUPPORTED;
1688   case WODM_UNPREPARE:        return MMSYSERR_NOTSUPPORTED;
1689   case WODM_GETDEVCAPS:       return wodGetDevCaps(wDevID, (LPWAVEOUTCAPSW)dwParam1,    dwParam2);
1690   case WODM_GETNUMDEVS:       return wodGetNumDevs();
1691   case WODM_GETPITCH:         return MMSYSERR_NOTSUPPORTED;
1692   case WODM_SETPITCH:         return MMSYSERR_NOTSUPPORTED;
1693   case WODM_GETPLAYBACKRATE:    return MMSYSERR_NOTSUPPORTED;
1694   case WODM_SETPLAYBACKRATE:    return MMSYSERR_NOTSUPPORTED;
1695   case WODM_GETVOLUME:        return wodGetVolume(wDevID, (LPDWORD)dwParam1);
1696   case WODM_SETVOLUME:        return wodSetVolume(wDevID, dwParam1);
1697   case WODM_RESTART:          return wodRestart(wDevID);
1698   case WODM_RESET:            return wodReset(wDevID);
1699
1700   case DRV_QUERYDEVICEINTERFACESIZE: return wodDevInterfaceSize       (wDevID, (LPDWORD)dwParam1);
1701   case DRV_QUERYDEVICEINTERFACE:     return wodDevInterface           (wDevID, (PWCHAR)dwParam1, dwParam2);
1702   case DRV_QUERYDSOUNDIFACE:    return wodDsCreate(wDevID, (PIDSDRIVER*)dwParam1);
1703   case DRV_QUERYDSOUNDDESC:     return wodDsDesc(wDevID, (PDSDRIVERDESC)dwParam1);
1704   default:
1705     FIXME("unknown message %d!\n", wMsg);
1706     }
1707     return MMSYSERR_NOTSUPPORTED;
1708 }
1709
1710 /*======================================================================*
1711  *                  Low level DSOUND implementation                     *
1712  *======================================================================*/
1713
1714 typedef struct IDsDriverImpl IDsDriverImpl;
1715 typedef struct IDsDriverBufferImpl IDsDriverBufferImpl;
1716
1717 struct IDsDriverImpl
1718 {
1719     /* IUnknown fields */
1720     const IDsDriverVtbl *lpVtbl;
1721     DWORD               ref;
1722     /* IDsDriverImpl fields */
1723     UINT                wDevID;
1724     IDsDriverBufferImpl*primary;
1725 };
1726
1727 struct IDsDriverBufferImpl
1728 {
1729     /* IUnknown fields */
1730     const IDsDriverBufferVtbl *lpVtbl;
1731     DWORD ref;
1732     /* IDsDriverBufferImpl fields */
1733     IDsDriverImpl* drv;
1734     DWORD buflen;
1735 };
1736
1737 static DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
1738 {
1739     /* we can't perform memory mapping as we don't have a file stream 
1740       interface with jack like we do with oss */
1741     MESSAGE("This sound card's driver does not support direct access\n");
1742     MESSAGE("The (slower) DirectSound HEL mode will be used instead.\n");
1743     return MMSYSERR_NOTSUPPORTED;
1744 }
1745
1746 static DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc)
1747 {
1748     memset(desc, 0, sizeof(*desc));
1749     strcpy(desc->szDesc, "Wine jack DirectSound Driver");
1750     strcpy(desc->szDrvname, "winejack.drv");
1751     return MMSYSERR_NOERROR;
1752 }
1753
1754 /*======================================================================*
1755  *                  Low level WAVE IN implementation                    *
1756  *======================================================================*/
1757
1758 /**************************************************************************
1759  *                      widNotifyClient                 [internal]
1760  */
1761 static DWORD widNotifyClient(WINE_WAVEIN* wwi, WORD wMsg, DWORD_PTR dwParam1,
1762                              DWORD_PTR dwParam2)
1763 {
1764     TRACE("wMsg = %04X dwParm1 = %08lX dwParam2 = %08lX\n", wMsg, dwParam1, dwParam2);
1765
1766     switch (wMsg) {
1767     case WIM_OPEN:
1768     case WIM_CLOSE:
1769     case WIM_DATA:
1770       if (wwi->wFlags != DCB_NULL &&
1771         !DriverCallback(wwi->waveDesc.dwCallback, wwi->wFlags,
1772           (HDRVR)wwi->waveDesc.hWave, wMsg, wwi->waveDesc.dwInstance,
1773           dwParam1, dwParam2))
1774       {
1775         WARN("can't notify client !\n");
1776         return MMSYSERR_ERROR;
1777       }
1778     break;
1779     default:
1780       FIXME("Unknown callback message %u\n", wMsg);
1781         return MMSYSERR_INVALPARAM;
1782     }
1783     return MMSYSERR_NOERROR;
1784 }
1785
1786 /******************************************************************
1787  *    JACK_callback_wwi
1788  */
1789 /* everytime the jack server wants something from us it calls this 
1790    function */
1791 static int JACK_callback_wwi (nframes_t nframes, void *arg)
1792 {
1793     sample_t* in_l;
1794     sample_t* in_r = 0;
1795     WINE_WAVEIN* wwi = arg;
1796
1797     TRACE("wDevID: %u, nframes %u\n", wwi->wDevID, nframes);
1798     
1799     if(!wwi->client)
1800         ERR("client is closed, this is weird...\n");
1801
1802     in_l = fp_jack_port_get_buffer(wwi->in_port_l, nframes);
1803
1804     if (wwi->in_port_r)
1805       in_r = fp_jack_port_get_buffer(wwi->in_port_r, nframes);
1806
1807     EnterCriticalSection(&wwi->access_crst);
1808     
1809     if((wwi->lpQueuePtr != NULL) && (wwi->state == WINE_WS_PLAYING))
1810     {
1811         LPWAVEHDR lpWaveHdr = wwi->lpQueuePtr;
1812         nframes_t jackFramesLeft = nframes;
1813
1814 #if JACK_CLOSE_HACK
1815         if(wwi->in_use == FALSE)
1816         {
1817             /* do nothing if nothing is being recorded */
1818             LeaveCriticalSection(&wwi->access_crst);
1819             return 0;
1820         }
1821 #endif
1822         
1823         TRACE("wwi.state == WINE_WS_PLAYING\n");
1824         
1825         while (lpWaveHdr && jackFramesLeft)
1826         {
1827             DWORD waveHdrFramesLeft = (lpWaveHdr->dwBufferLength - lpWaveHdr->dwBytesRecorded) / (sizeof(short) * wwi->format.wf.nChannels); 
1828             DWORD numFrames = min (jackFramesLeft, waveHdrFramesLeft);
1829             
1830             TRACE ("dwBufferLength=(%u) dwBytesRecorded=(%d)\n",   lpWaveHdr->dwBufferLength, lpWaveHdr->dwBytesRecorded);
1831             TRACE ("jackFramesLeft=(%u) waveHdrFramesLeft=(%u)\n", jackFramesLeft, waveHdrFramesLeft);
1832
1833             if (!in_r) {
1834               /* mono */
1835               sample_move_s16_d16((short *)((char *)lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded), in_l+(nframes-jackFramesLeft), numFrames, 1);
1836             } else {
1837               /* stereo */
1838               sample_move_s16_d16((short *)((char *)lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded), 
1839                                   in_l+(nframes-jackFramesLeft), numFrames, 2);
1840               sample_move_s16_d16((short *)((char *)lpWaveHdr->lpData + lpWaveHdr->dwBytesRecorded + sizeof(short)), 
1841                                   in_r+(nframes-jackFramesLeft), numFrames, 2);
1842             }
1843             
1844             lpWaveHdr->dwBytesRecorded += (numFrames * sizeof(short) * wwi->format.wf.nChannels );
1845             jackFramesLeft -= numFrames;
1846
1847             if (lpWaveHdr->dwBytesRecorded >= lpWaveHdr->dwBufferLength)
1848             {
1849                 /* must copy the value of next waveHdr, because we have no idea of what
1850                  * will be done with the content of lpWaveHdr in callback
1851                  */
1852                 LPWAVEHDR       lpNext = lpWaveHdr->lpNext;
1853                                 
1854                 lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
1855                 lpWaveHdr->dwFlags |=  WHDR_DONE;
1856
1857                 TRACE("WaveHdr full. dwBytesRecorded=(%u) dwFlags=(0x%x)\n",lpWaveHdr->dwBytesRecorded,lpWaveHdr->dwFlags);
1858
1859                 widNotifyClient(wwi, WIM_DATA, (DWORD_PTR)lpWaveHdr, 0);
1860
1861                 lpWaveHdr = wwi->lpQueuePtr = lpNext;
1862             }
1863         }
1864         TRACE ("jackFramesLeft=(%u) lpWaveHdr=(%p)\n", jackFramesLeft, lpWaveHdr);
1865         if (jackFramesLeft > 0) { WARN("Record buffer ran out of WaveHdrs\n"); }
1866     }
1867     
1868     LeaveCriticalSection(&wwi->access_crst);
1869
1870     return 0;
1871 }
1872
1873 /******************************************************************
1874  *              JACK_OpenWaveInDevice
1875  */
1876 static int JACK_OpenWaveInDevice(WINE_WAVEIN* wwi, WORD nChannels)
1877 {
1878   const char** ports;
1879   int i;
1880   char client_name[64];
1881   jack_port_t* in_port_l;
1882   jack_port_t* in_port_r = 0;
1883   jack_client_t* client;
1884   int failed = 0;
1885
1886   TRACE("creating jack client and setting up callbacks\n");
1887
1888   if ((nChannels == 0) || (nChannels > 2)) {
1889     ERR ("nChannels = (%d), but we only support mono or stereo.\n", nChannels);
1890     return 0;
1891   }
1892
1893 #if JACK_CLOSE_HACK
1894   /* see if this device is already open */
1895         if(wwi->client)
1896         {
1897           /* if this device is already in use then it is bad for us to be in here */
1898           if(wwi->in_use)
1899             return 0;
1900
1901           TRACE("using existing client\n");
1902           wwi->in_use = TRUE;
1903           return 1;
1904         }
1905 #endif
1906
1907         /* zero out the buffer pointer and the size of the buffer */
1908         wwi->sound_buffer = 0;
1909         wwi->buffer_size = 0;
1910
1911         /* try to become a client of the JACK server */
1912         snprintf(client_name, sizeof(client_name), "wine_jack_in_%d", wwi->wDevID);
1913         TRACE("client name '%s'\n", client_name);
1914         if ((client = fp_jack_client_open (client_name, JackUseExactName, NULL)) == 0)
1915         {
1916                 /* jack has problems with shutting down clients, so lets */
1917                 /* wait a short while and try once more before we give up */
1918                 Sleep(250);
1919                 if ((client = fp_jack_client_open (client_name, JackUseExactName, NULL)) == 0)
1920                 {
1921                   ERR("jack server not running?\n");
1922                   return 0;
1923                 }
1924         }
1925         wwi->client = client;
1926                 
1927         /* tell the JACK server to call `JACK_wwi_callback()' whenever
1928            there is work to be done. */
1929         fp_jack_set_process_callback (client, JACK_callback_wwi, wwi);
1930         
1931         /* tell the JACK server to call `JACK_bufsize_wwi()' whenever   
1932            the maximum number of frames that will be passed
1933            to `JACK_Callback()' changes */
1934         fp_jack_set_buffer_size_callback (client, JACK_bufsize_wwi, wwi);
1935           
1936         /* tell the JACK server to call `srate()' whenever
1937            the sample rate of the system changes. */
1938         fp_jack_set_sample_rate_callback (client, JACK_srate, wwi);
1939
1940         /* tell the JACK server to call `jack_shutdown()' if
1941            it ever shuts down, either entirely, or if it
1942            just decides to stop calling us. */
1943         fp_jack_on_shutdown (client, JACK_shutdown_wwi, wwi);
1944         
1945         /* display the current sample rate. once the client is activated
1946            (see below), you should rely on your own sample rate
1947            callback (see above) for this value. */
1948         wwi->sample_rate = fp_jack_get_sample_rate(client);
1949         TRACE("engine sample rate: %lu\n", wwi->sample_rate);
1950           
1951         /* create the left and right channel output ports */
1952         /* jack's ports are all mono so for stereo you need two */
1953         in_port_l = fp_jack_port_register (client, "in_l",
1954                          JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);
1955         wwi->in_port_l = in_port_l;
1956         TRACE("Created port. (%p)\n", in_port_l);
1957
1958         if (nChannels == 2)
1959         {
1960           in_port_r = fp_jack_port_register (client, "in_r",
1961                            JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0); 
1962           TRACE("Created port. (%p)\n", in_port_r);
1963         } 
1964         wwi->in_port_r = in_port_r;
1965
1966 #if JACK_CLOSE_HACK
1967         wwi->in_use = TRUE; /* mark this device as in use since it now is ;-) */
1968 #endif
1969
1970         TRACE("activating client.\n");
1971         /* tell the JACK server that we are ready to roll */
1972         if (fp_jack_activate (client))
1973         {
1974           ERR( "cannot activate client\n");
1975           return 0;
1976         }
1977         TRACE("activated client.\n");
1978         /* figure out what the ports that we want to output on are */
1979         /* NOTE: we do this instead of using stuff like "alsa_pcm:playback_X" because */
1980         /*   this way works if names are changed */
1981         ports = fp_jack_get_ports(client, NULL, NULL, JackPortIsPhysical|JackPortIsOutput);
1982
1983         /* display a trace of the output ports we found */
1984         for(i = 0; ports[i]; i++)
1985         {
1986           TRACE("ports[%d] = '%s'\n", i, ports[i]);
1987         }
1988
1989         if(!ports)
1990         {
1991           ERR("jack_get_ports() failed to find 'JackPortIsPhysical|JackPortIsOutput'\n");
1992         }
1993
1994         /* connect the ports. Note: you can't do this before
1995            the client is activated (this may change in the future).
1996         */ 
1997         /* we want to connect to two ports so we have stereo input ;-) */
1998
1999         if(fp_jack_connect(client, ports[0], fp_jack_port_name(in_port_l)))
2000         {
2001           ERR ("cannot connect to input port %d('%s')\n", 0, ports[0]);
2002           failed = 1;
2003         }
2004         TRACE("Connected (%s)<->(%s)\n",ports[0],fp_jack_port_name(in_port_l));
2005
2006         if ((nChannels == 2) && in_port_r) {
2007           if(fp_jack_connect(client, ports[1], fp_jack_port_name(in_port_r)))
2008           {
2009             ERR ("cannot connect to input port %d('%s')\n", 1, ports[1]);
2010             failed = 1;
2011           }
2012           TRACE("Connected (%s)<->(%s)\n",ports[1],fp_jack_port_name(in_port_r));
2013         }
2014         free(ports); /* free the returned array of ports */
2015
2016         /* if something failed we need to shut the client down and return 0 */
2017         if(failed)
2018         {
2019 #if JACK_CLOSE_HACK
2020           JACK_CloseWaveInDevice(wwi, TRUE);
2021 #else
2022           JACK_CloseWaveInDevice(wwi);
2023 #endif
2024           return 0;
2025         }
2026
2027         TRACE("return success.\n");
2028         return 1; /* return success */
2029 }
2030
2031 /**************************************************************************
2032  *                      widGetDevCaps                           [internal]
2033  */
2034 static DWORD widGetDevCaps(WORD wDevID, LPWAVEINCAPSW lpCaps, DWORD dwSize)
2035 {
2036     TRACE("(%u, %p, %u);\n", wDevID, lpCaps, dwSize);
2037
2038     if (lpCaps == NULL) return MMSYSERR_NOTENABLED;
2039
2040     if (wDevID >= MAX_WAVEINDRV) {
2041         TRACE("MAX_WAVEINDRV reached !\n");
2042         return MMSYSERR_BADDEVICEID;
2043     }
2044
2045     memcpy(lpCaps, &WInDev[wDevID].caps, min(dwSize, sizeof(*lpCaps)));
2046     return MMSYSERR_NOERROR;
2047 }
2048
2049 /**************************************************************************
2050  *                              widOpen                         [internal]
2051  */
2052 static DWORD widOpen(WORD wDevID, LPWAVEOPENDESC lpDesc, DWORD dwFlags)
2053 {
2054     WINE_WAVEIN*        wwi;
2055     DWORD retval;
2056
2057     TRACE("(%u, %p, %08X);\n", wDevID, lpDesc, dwFlags);
2058     if (lpDesc == NULL)
2059     {
2060         WARN("Invalid Parameter !\n");
2061         return MMSYSERR_INVALPARAM;
2062     }
2063     if (wDevID >= MAX_WAVEINDRV) {
2064         TRACE ("MAX_WAVEINDRV reached !\n");
2065         return MMSYSERR_BADDEVICEID;
2066     }
2067
2068 #if JACK_CLOSE_HACK
2069     if(WInDev[wDevID].client && WOutDev[wDevID].in_use)
2070 #else
2071     if(WInDev[wDevID].client)
2072 #endif
2073     {
2074       TRACE("device %d already allocated\n", wDevID);
2075       return MMSYSERR_ALLOCATED;
2076     }
2077
2078     /* Only the PCM format is supported so far...
2079      * Also we only support 16 bit mode.
2080      */
2081     if (lpDesc->lpFormat->wFormatTag != WAVE_FORMAT_PCM ||
2082       lpDesc->lpFormat->nChannels == 0 ||
2083       lpDesc->lpFormat->nSamplesPerSec == 0 ||
2084       lpDesc->lpFormat->wBitsPerSample!=16)
2085     {
2086       WARN("Bad format: tag=%04X nChannels=%d nSamplesPerSec=%d wBitsPerSample=%d !\n",
2087        lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
2088        lpDesc->lpFormat->nSamplesPerSec, lpDesc->lpFormat->wBitsPerSample);
2089       return WAVERR_BADFORMAT;
2090     }
2091
2092     if (dwFlags & WAVE_FORMAT_QUERY)
2093     {
2094       TRACE("Query format: tag=%04X nChannels=%d nSamplesPerSec=%d !\n",
2095        lpDesc->lpFormat->wFormatTag, lpDesc->lpFormat->nChannels,
2096        lpDesc->lpFormat->nSamplesPerSec);
2097       return MMSYSERR_NOERROR;
2098     }
2099
2100     wwi = &WInDev[wDevID];
2101     wwi->wDevID = wDevID;
2102
2103     /* Set things up before we call JACK_OpenWaveOutDevice because */
2104     /* we will start getting callbacks before JACK_OpenWaveOutDevice */
2105     /* even returns and we want to be initialized before then */
2106     wwi->state = WINE_WS_STOPPED; /* start in a stopped state */
2107
2108     InitializeCriticalSection(&wwi->access_crst); /* initialize the critical section */
2109     EnterCriticalSection(&wwi->access_crst);
2110
2111     /* open up jack ports for this device */
2112     if (!JACK_OpenWaveInDevice(&WInDev[wDevID], lpDesc->lpFormat->nChannels))
2113     {
2114       ERR("JACK_OpenWaveInDevice(%d) failed\n", wDevID);
2115       LeaveCriticalSection(&wwi->access_crst);
2116       DeleteCriticalSection(&wwi->access_crst);
2117       return MMSYSERR_ERROR;            /* return unspecified error */
2118     }
2119
2120     dwFlags &= ~WAVE_DIRECTSOUND;  /* direct sound not supported, ignore the flag */
2121
2122     wwi->wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);
2123
2124     wwi->waveDesc = *lpDesc;
2125     memcpy(&wwi->format,   lpDesc->lpFormat, sizeof(PCMWAVEFORMAT));
2126
2127     LeaveCriticalSection(&wwi->access_crst);
2128
2129     /* display the current wave format */
2130     TRACE("wBitsPerSample=%u, nAvgBytesPerSec=%u, nSamplesPerSec=%u, nChannels=%u nBlockAlign=%u!\n",
2131     wwi->format.wBitsPerSample, wwi->format.wf.nAvgBytesPerSec,
2132     wwi->format.wf.nSamplesPerSec, wwi->format.wf.nChannels,
2133     wwi->format.wf.nBlockAlign);
2134
2135     /* make sure that we have the same sample rate in our audio stream */
2136     /* as we do in the jack server */
2137     if(wwi->format.wf.nSamplesPerSec != wwi->sample_rate)
2138     {
2139       TRACE("error: jack server sample rate is '%ld', wave sample rate is '%d'\n",
2140          wwi->sample_rate, wwi->format.wf.nSamplesPerSec);
2141
2142 #if JACK_CLOSE_HACK
2143       JACK_CloseWaveInDevice(wwi, FALSE); /* close this device, don't force the client to close */
2144 #else
2145       JACK_CloseWaveInDevice(wwi); /* close this device */
2146 #endif
2147       DeleteCriticalSection(&wwi->access_crst);
2148       return WAVERR_BADFORMAT;
2149     }
2150
2151     /* check for an invalid number of bits per sample */
2152     if (wwi->format.wBitsPerSample == 0)
2153     {
2154       WARN("Resetting zeroed wBitsPerSample\n");
2155       wwi->format.wBitsPerSample = 8 *
2156       (wwi->format.wf.nAvgBytesPerSec /
2157        wwi->format.wf.nSamplesPerSec) /
2158        wwi->format.wf.nChannels;
2159     }
2160
2161     TRACE("notify client.\n");
2162     EnterCriticalSection(&wwi->access_crst);
2163     retval = widNotifyClient(wwi, WIM_OPEN, 0, 0);
2164     LeaveCriticalSection(&wwi->access_crst);
2165
2166     return retval;
2167 }
2168 /**************************************************************************
2169  *                              widClose                        [internal]
2170  */
2171 static DWORD widClose(WORD wDevID)
2172 {
2173     DWORD               ret = MMSYSERR_NOERROR;
2174     WINE_WAVEIN*        wwi;
2175
2176     TRACE("(%u);\n", wDevID);
2177
2178     if (wDevID >= MAX_WAVEINDRV || !WInDev[wDevID].client)
2179     {
2180       WARN("bad device ID !\n");
2181       return MMSYSERR_BADDEVICEID;
2182     }
2183     
2184     wwi = &WInDev[wDevID];
2185     if (wwi->lpQueuePtr)
2186     {
2187       WARN("buffers still playing !\n");
2188       ret = WAVERR_STILLPLAYING;
2189     } else
2190     {
2191         /* sanity check: this should not happen since the device must have been reset before */
2192         if (wwi->lpQueuePtr) ERR("out of sync\n");
2193         
2194         wwi->state = WINE_WS_CLOSED; /* mark the device as closed */
2195         
2196 #if JACK_CLOSE_HACK
2197         JACK_CloseWaveInDevice(wwi, FALSE); /* close the jack device, DO NOT force the client to close */
2198 #else
2199         JACK_CloseWaveInDevice(wwi); /* close the jack device */
2200 #endif
2201         DeleteCriticalSection(&wwi->access_crst); /* delete the critical section so we can initialize it again from wodOpen() */
2202
2203         ret = widNotifyClient(wwi, WIM_CLOSE, 0, 0);
2204     }
2205
2206     return ret;
2207 }
2208
2209 /**************************************************************************
2210  *                              widAddBuffer            [internal]
2211  */
2212 static DWORD widAddBuffer(WORD wDevID, LPWAVEHDR lpWaveHdr, DWORD dwSize)
2213 {
2214     WINE_WAVEIN* wwi = &WInDev[wDevID];
2215
2216     TRACE("(%u, %p, %08X);\n", wDevID, lpWaveHdr, dwSize);
2217
2218     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].state == WINE_WS_CLOSED) {
2219                                 WARN("can't do it !\n");
2220                                 return MMSYSERR_INVALHANDLE;
2221     }
2222     if (!(lpWaveHdr->dwFlags & WHDR_PREPARED)) {
2223                                 TRACE("never been prepared !\n");
2224                                 return WAVERR_UNPREPARED;
2225     }
2226     if (lpWaveHdr->dwFlags & WHDR_INQUEUE) {
2227                                 TRACE("header already in use !\n");
2228                                 return WAVERR_STILLPLAYING;
2229     }
2230
2231     lpWaveHdr->dwFlags |= WHDR_INQUEUE;
2232     lpWaveHdr->dwFlags &= ~WHDR_DONE;
2233     lpWaveHdr->dwBytesRecorded = 0;
2234     lpWaveHdr->lpNext = NULL;
2235
2236     EnterCriticalSection(&wwi->access_crst);
2237     /* insert buffer at end of queue */
2238     {
2239         LPWAVEHDR* wh;
2240         for (wh = &(wwi->lpQueuePtr); *wh; wh = &((*wh)->lpNext));
2241         *wh=lpWaveHdr;
2242     }
2243     LeaveCriticalSection(&wwi->access_crst);
2244
2245     return MMSYSERR_NOERROR;
2246 }
2247
2248 /**************************************************************************
2249  *                      widStart                                [internal]
2250  */
2251 static DWORD widStart(WORD wDevID)
2252 {
2253     TRACE("(%u);\n", wDevID);
2254     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].state == WINE_WS_CLOSED) {
2255         WARN("can't start recording !\n");
2256         return MMSYSERR_INVALHANDLE;
2257     }
2258
2259     WInDev[wDevID].state = WINE_WS_PLAYING;
2260     return MMSYSERR_NOERROR;
2261 }
2262
2263 /**************************************************************************
2264  *                      widStop                                 [internal]
2265  */
2266 static DWORD widStop(WORD wDevID)
2267 {
2268     WINE_WAVEIN* wwi = &WInDev[wDevID];
2269
2270     TRACE("(%u);\n", wDevID);
2271     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].state == WINE_WS_CLOSED) {
2272         WARN("can't stop !\n");
2273         return MMSYSERR_INVALHANDLE;
2274     }
2275     
2276     if (wwi->state != WINE_WS_STOPPED)
2277     {
2278         WAVEHDR*                lpWaveHdr;
2279         /* do something here to stop recording ??? */
2280         
2281         /* return current buffer to app */
2282         lpWaveHdr = wwi->lpQueuePtr;
2283         if (lpWaveHdr)
2284         {
2285             LPWAVEHDR   lpNext = lpWaveHdr->lpNext;
2286             TRACE("stop %p %p\n", lpWaveHdr, lpWaveHdr->lpNext);
2287             lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2288             lpWaveHdr->dwFlags |= WHDR_DONE;
2289             widNotifyClient(wwi, WIM_DATA, (DWORD_PTR)lpWaveHdr, 0);
2290             wwi->lpQueuePtr = lpNext;
2291         }
2292     }
2293     wwi->state = WINE_WS_STOPPED;
2294
2295     return MMSYSERR_NOERROR;
2296 }
2297
2298 /**************************************************************************
2299  *                      widReset                                [internal]
2300  */
2301 static DWORD widReset(WORD wDevID)
2302 {
2303     WINE_WAVEIN* wwi = &WInDev[wDevID];
2304     WAVEHDR*            lpWaveHdr;
2305
2306     TRACE("(%u);\n", wDevID);
2307     if (wDevID >= MAX_WAVEINDRV || WInDev[wDevID].state == WINE_WS_CLOSED) {
2308         WARN("can't reset !\n");
2309         return MMSYSERR_INVALHANDLE;
2310     }
2311
2312     wwi->state = WINE_WS_STOPPED;
2313
2314     /* return all buffers to the app */
2315     for (lpWaveHdr = wwi->lpQueuePtr; lpWaveHdr; lpWaveHdr = lpWaveHdr->lpNext) {
2316         TRACE("reset %p %p\n", lpWaveHdr, lpWaveHdr->lpNext);
2317         lpWaveHdr->dwFlags &= ~WHDR_INQUEUE;
2318         lpWaveHdr->dwFlags |= WHDR_DONE;
2319
2320         widNotifyClient(wwi, WIM_DATA, (DWORD_PTR)lpWaveHdr, 0);
2321     }
2322     wwi->lpQueuePtr = NULL;
2323
2324     return MMSYSERR_NOERROR;
2325 }
2326
2327 /**************************************************************************
2328  *                              widGetNumDevs                   [internal]
2329  */
2330 static DWORD widGetNumDevs(void)
2331 {
2332   return MAX_WAVEINDRV;
2333 }
2334
2335 /**************************************************************************
2336  *                              widDevInterfaceSize             [internal]
2337  */
2338 static DWORD widDevInterfaceSize(UINT wDevID, LPDWORD dwParam1)
2339 {
2340     TRACE("(%u, %p)\n", wDevID, dwParam1);
2341                                                                                                        
2342                                                                                                        
2343     *dwParam1 = MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
2344                                     NULL, 0 ) * sizeof(WCHAR);
2345     return MMSYSERR_NOERROR;
2346 }
2347
2348 /**************************************************************************
2349  *                              widDevInterface                 [internal]
2350  */
2351 static DWORD widDevInterface(UINT wDevID, PWCHAR dwParam1, DWORD dwParam2)
2352 {
2353     if (dwParam2 >= MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
2354                                         NULL, 0 ) * sizeof(WCHAR))
2355     {
2356         MultiByteToWideChar(CP_ACP, 0, WInDev[wDevID].interface_name, -1,
2357                             dwParam1, dwParam2 / sizeof(WCHAR));
2358         return MMSYSERR_NOERROR;
2359     }
2360     return MMSYSERR_INVALPARAM;
2361 }
2362
2363 /**************************************************************************
2364  *                              widMessage (WINEJACK.6)
2365  */
2366 DWORD WINAPI JACK_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2367                              DWORD_PTR dwParam1, DWORD_PTR dwParam2)
2368 {
2369   TRACE("(%u, %04X, %08X, %08lX, %08lX);\n", wDevID, wMsg, dwUser, dwParam1, dwParam2);
2370
2371     switch (wMsg) {
2372     case DRVM_INIT:
2373         return JACK_WaveInit();
2374     case DRVM_EXIT:
2375         return JACK_WaveRelease();
2376     case DRVM_ENABLE:
2377     case DRVM_DISABLE:
2378         /* FIXME: Pretend this is supported */
2379         return 0;
2380     case WIDM_OPEN:             return widOpen          (wDevID, (LPWAVEOPENDESC)dwParam1,      dwParam2);
2381     case WIDM_CLOSE:            return widClose         (wDevID);
2382     case WIDM_ADDBUFFER:        return widAddBuffer     (wDevID, (LPWAVEHDR)dwParam1, dwParam2);
2383     case WIDM_PREPARE:          return MMSYSERR_NOTSUPPORTED;
2384     case WIDM_UNPREPARE:        return MMSYSERR_NOTSUPPORTED;
2385     case WIDM_GETDEVCAPS:       return widGetDevCaps    (wDevID, (LPWAVEINCAPSW)dwParam1,       dwParam2);
2386     case WIDM_GETNUMDEVS:       return widGetNumDevs();
2387     case WIDM_RESET:            return widReset         (wDevID);
2388     case WIDM_START:            return widStart         (wDevID);
2389     case WIDM_STOP:             return widStop          (wDevID);
2390     case DRV_QUERYDEVICEINTERFACESIZE: return widDevInterfaceSize       (wDevID, (LPDWORD)dwParam1);
2391     case DRV_QUERYDEVICEINTERFACE:     return widDevInterface           (wDevID, (PWCHAR)dwParam1, dwParam2);
2392     default:
2393         FIXME("unknown message %d!\n", wMsg);
2394     }
2395
2396   return MMSYSERR_NOTSUPPORTED;
2397 }
2398
2399 #else /* !SONAME_LIBJACK */
2400
2401 /**************************************************************************
2402  *                              widMessage (WINEJACK.6)
2403  */
2404 DWORD WINAPI JACK_widMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2405                              DWORD_PTR dwParam1, DWORD_PTR dwParam2)
2406 {
2407   FIXME("(%u, %04X, %08X, %08lX, %08lX):jack support not compiled into wine\n",
2408         wDevID, wMsg, dwUser, dwParam1, dwParam2);
2409   return MMSYSERR_NOTENABLED;
2410 }
2411
2412 /**************************************************************************
2413  *                              wodMessage (WINEJACK.7)
2414  */
2415 DWORD WINAPI JACK_wodMessage(WORD wDevID, WORD wMsg, DWORD dwUser,
2416                              DWORD_PTR dwParam1, DWORD_PTR dwParam2)
2417 {
2418   FIXME("(%u, %04X, %08X, %08lX, %08lX):jack support not compiled into wine\n",
2419         wDevID, wMsg, dwUser, dwParam1, dwParam2);
2420   return MMSYSERR_NOTENABLED;
2421 }
2422
2423 #endif /* SONAME_LIBJACK */