winspool: Start support for XcvMonitor and XcvPort in OpenPrinter.
[wine] / dlls / winmm / playsound.c
1 /* -*- tab-width: 8; c-basic-offset: 4 -*- */
2
3 /*
4  * MMSYTEM functions
5  *
6  * Copyright 1993      Martin Ayotte
7  *           1998-2002 Eric Pouech
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22  */
23
24 #include <stdarg.h>
25 #include <string.h>
26
27 #include "windef.h"
28 #include "winbase.h"
29 #include "mmsystem.h"
30 #include "wingdi.h"
31 #include "winuser.h"
32 #include "winreg.h"
33 #include "winemm.h"
34 #include "winternl.h"
35
36 #include "wine/debug.h"
37
38 WINE_DEFAULT_DEBUG_CHANNEL(winmm);
39
40 static HMMIO    get_mmioFromFile(LPCWSTR lpszName)
41 {
42     HMMIO       ret;
43     WCHAR       buf[256];
44     LPWSTR      dummy;
45
46     ret = mmioOpenW((LPWSTR)lpszName, NULL,
47                     MMIO_ALLOCBUF | MMIO_READ | MMIO_DENYWRITE);
48     if (ret != 0) return ret;
49     if (SearchPathW(NULL, lpszName, NULL, sizeof(buf)/sizeof(buf[0]), buf, &dummy))
50     {
51         return mmioOpenW(buf, NULL,
52                          MMIO_ALLOCBUF | MMIO_READ | MMIO_DENYWRITE);
53     }
54     return 0;
55 }
56
57 static HMMIO    get_mmioFromProfile(UINT uFlags, LPCWSTR lpszName)
58 {
59     WCHAR       str[128];
60     LPWSTR      ptr;
61     HMMIO       hmmio;
62     HKEY        hRegSnd, hRegApp, hScheme, hSnd;
63     DWORD       err, type, count;
64
65     static const WCHAR  wszSounds[] = {'S','o','u','n','d','s',0};
66     static const WCHAR  wszDefault[] = {'D','e','f','a','u','l','t',0};
67     static const WCHAR  wszKey[] = {'A','p','p','E','v','e','n','t','s','\\',
68                                     'S','c','h','e','m','e','s','\\',
69                                     'A','p','p','s',0};
70     static const WCHAR  wszDotDefault[] = {'.','D','e','f','a','u','l','t',0};
71     static const WCHAR  wszDotCurrent[] = {'.','C','u','r','r','e','n','t',0};
72     static const WCHAR  wszNull[] = {0};
73
74     TRACE("searching in SystemSound list for %s\n", debugstr_w(lpszName));
75     GetProfileStringW(wszSounds, lpszName, wszNull, str, sizeof(str)/sizeof(str[0]));
76     if (lstrlenW(str) == 0)
77     {
78         if (uFlags & SND_NODEFAULT) goto next;
79         GetProfileStringW(wszSounds, wszDefault, wszNull, str, sizeof(str)/sizeof(str[0]));
80         if (lstrlenW(str) == 0) goto next;
81     }
82     for (ptr = str; *ptr && *ptr != ','; ptr++);
83     if (*ptr) *ptr = 0;
84     hmmio = mmioOpenW(str, NULL, MMIO_ALLOCBUF | MMIO_READ | MMIO_DENYWRITE);
85     if (hmmio != 0) return hmmio;
86  next:
87     /* we look up the registry under
88      *      HKCU\AppEvents\Schemes\Apps\.Default
89      *      HKCU\AppEvents\Schemes\Apps\<AppName>
90      */
91     if (RegOpenKeyW(HKEY_CURRENT_USER, wszKey, &hRegSnd) != 0) goto none;
92     if (uFlags & SND_APPLICATION)
93     {
94         DWORD len;
95
96         err = 1; /* error */
97         len = GetModuleFileNameW(0, str, sizeof(str)/sizeof(str[0]));
98         if (len > 0 && len < sizeof(str)/sizeof(str[0]))
99         {
100             for (ptr = str + lstrlenW(str) - 1; ptr >= str; ptr--)
101             {
102                 if (*ptr == '.') *ptr = 0;
103                 if (*ptr == '\\')
104                 {
105                     err = RegOpenKeyW(hRegSnd, ptr+1, &hRegApp);
106                     break;
107                 }
108             }
109         }
110     }
111     else
112     {
113         err = RegOpenKeyW(hRegSnd, wszDotDefault, &hRegApp);
114     }
115     RegCloseKey(hRegSnd);
116     if (err != 0) goto none;
117     err = RegOpenKeyW(hRegApp, lpszName, &hScheme);
118     RegCloseKey(hRegApp);
119     if (err != 0) goto none;
120     /* what's the difference between .Current and .Default ? */
121     err = RegOpenKeyW(hScheme, wszDotDefault, &hSnd);
122     if (err != 0)
123     {
124         err = RegOpenKeyW(hScheme, wszDotCurrent, &hSnd);
125         RegCloseKey(hScheme);
126         if (err != 0)
127             goto none;
128     }
129     count = sizeof(str)/sizeof(str[0]);
130     err = RegQueryValueExW(hSnd, NULL, 0, &type, (LPBYTE)str, &count);
131     RegCloseKey(hSnd);
132     if (err != 0 || !*str) goto none;
133     hmmio = mmioOpenW(str, NULL, MMIO_ALLOCBUF | MMIO_READ | MMIO_DENYWRITE);
134     if (hmmio) return hmmio;
135  none:
136     WARN("can't find SystemSound='%s' !\n", debugstr_w(lpszName));
137     return 0;
138 }
139
140 struct playsound_data
141 {
142     HANDLE      hEvent;
143     LONG        dwEventCount;
144 };
145
146 static void CALLBACK PlaySound_Callback(HWAVEOUT hwo, UINT uMsg,
147                                         DWORD dwInstance,
148                                         DWORD dwParam1, DWORD dwParam2)
149 {
150     struct playsound_data*      s = (struct playsound_data*)dwInstance;
151
152     switch (uMsg) {
153     case WOM_OPEN:
154     case WOM_CLOSE:
155         break;
156     case WOM_DONE:
157         InterlockedIncrement(&s->dwEventCount);
158         TRACE("Returning waveHdr=%x\n", dwParam1);
159         SetEvent(s->hEvent);
160         break;
161     default:
162         ERR("Unknown uMsg=%d\n", uMsg);
163     }
164 }
165
166 static void PlaySound_WaitDone(struct playsound_data* s)
167 {
168     for (;;) {
169         ResetEvent(s->hEvent);
170         if (InterlockedDecrement(&s->dwEventCount) >= 0) break;
171         InterlockedIncrement(&s->dwEventCount);
172
173         WaitForSingleObject(s->hEvent, INFINITE);
174     }
175 }
176
177 static BOOL PlaySound_IsString(DWORD fdwSound, const void* psz)
178 {
179     /* SND_RESOURCE is 0x40004 while
180      * SND_MEMORY is 0x00004
181      */
182     switch (fdwSound & (SND_RESOURCE|SND_ALIAS|SND_FILENAME))
183     {
184     case SND_RESOURCE:  return HIWORD(psz) != 0; /* by name or by ID ? */
185     case SND_MEMORY:    return FALSE;
186     case SND_ALIAS:     /* what about ALIAS_ID ??? */
187     case SND_FILENAME:
188     case 0:             return TRUE;
189     default:            FIXME("WTF\n"); return FALSE;
190     }
191 }
192
193 static void     PlaySound_Free(WINE_PLAYSOUND* wps)
194 {
195     WINE_PLAYSOUND**    p;
196
197     EnterCriticalSection(&WINMM_IData.cs);
198     for (p = &WINMM_IData.lpPlaySound; *p && *p != wps; p = &((*p)->lpNext));
199     if (*p) *p = (*p)->lpNext;
200     if (WINMM_IData.lpPlaySound == NULL) SetEvent(WINMM_IData.psLastEvent);
201     LeaveCriticalSection(&WINMM_IData.cs);
202     if (wps->bAlloc) HeapFree(GetProcessHeap(), 0, (void*)wps->pszSound);
203     if (wps->hThread) CloseHandle(wps->hThread);
204     HeapFree(GetProcessHeap(), 0, wps);
205 }
206
207 static WINE_PLAYSOUND*  PlaySound_Alloc(const void* pszSound, HMODULE hmod,
208                                         DWORD fdwSound, BOOL bUnicode)
209 {
210     WINE_PLAYSOUND* wps;
211
212     wps = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*wps));
213     if (!wps) return NULL;
214
215     wps->hMod = hmod;
216     wps->fdwSound = fdwSound;
217     if (PlaySound_IsString(fdwSound, pszSound))
218     {
219         if (bUnicode)
220         {
221             if (fdwSound & SND_ASYNC)
222             {
223                 LPWSTR sound = HeapAlloc(GetProcessHeap(), 0,
224                                          (lstrlenW(pszSound)+1) * sizeof(WCHAR));
225                 if (!sound) goto oom_error;
226                 wps->pszSound = lstrcpyW(sound, pszSound);
227                 wps->bAlloc = TRUE;
228             }
229             else
230                 wps->pszSound = pszSound;
231         }
232         else
233         {
234             UNICODE_STRING usBuffer;
235             RtlCreateUnicodeStringFromAsciiz(&usBuffer, pszSound);
236             wps->pszSound = usBuffer.Buffer;
237             if (!wps->pszSound) goto oom_error;
238             wps->bAlloc = TRUE;
239         }
240     }
241     else
242         wps->pszSound = pszSound;
243
244     return wps;
245  oom_error:
246     PlaySound_Free(wps);
247     return NULL;
248 }
249
250 static DWORD WINAPI proc_PlaySound(LPVOID arg)
251 {
252     WINE_PLAYSOUND*     wps = (WINE_PLAYSOUND*)arg;
253     BOOL                bRet = FALSE;
254     HMMIO               hmmio = 0;
255     MMCKINFO            ckMainRIFF;
256     MMCKINFO            mmckInfo;
257     LPWAVEFORMATEX      lpWaveFormat = NULL;
258     HWAVEOUT            hWave = 0;
259     LPWAVEHDR           waveHdr = NULL;
260     INT                 count, bufsize, left, index;
261     struct playsound_data       s;
262     void*               data;
263
264     s.hEvent = 0;
265
266     TRACE("SoundName='%s' !\n", debugstr_w(wps->pszSound));
267
268     /* if resource, grab it */
269     if ((wps->fdwSound & SND_RESOURCE) == SND_RESOURCE) {
270         static const WCHAR wszWave[] = {'W','A','V','E',0};
271         HRSRC   hRes;
272         HGLOBAL hGlob;
273
274         if ((hRes = FindResourceW(wps->hMod, wps->pszSound, wszWave)) == 0 ||
275             (hGlob = LoadResource(wps->hMod, hRes)) == 0)
276             goto errCleanUp;
277         if ((data = LockResource(hGlob)) == NULL) {
278             FreeResource(hGlob);
279             goto errCleanUp;
280         }
281         FreeResource(hGlob);
282     } else
283         data = (void*)wps->pszSound;
284
285     /* construct an MMIO stream (either in memory, or from a file */
286     if (wps->fdwSound & SND_MEMORY)
287     { /* NOTE: SND_RESOURCE has the SND_MEMORY bit set */
288         MMIOINFO        mminfo;
289
290         memset(&mminfo, 0, sizeof(mminfo));
291         mminfo.fccIOProc = FOURCC_MEM;
292         mminfo.pchBuffer = (LPSTR)data;
293         mminfo.cchBuffer = -1; /* FIXME: when a resource, could grab real size */
294         TRACE("Memory sound %p\n", data);
295         hmmio = mmioOpenW(NULL, &mminfo, MMIO_READ);
296     }
297     else if (wps->fdwSound & SND_ALIAS)
298     {
299         hmmio = get_mmioFromProfile(wps->fdwSound, wps->pszSound);
300     }
301     else if (wps->fdwSound & SND_FILENAME)
302     {
303         hmmio = get_mmioFromFile(wps->pszSound);
304     }
305     else
306     {
307         if ((hmmio = get_mmioFromProfile(wps->fdwSound | SND_NODEFAULT, wps->pszSound)) == 0)
308         {
309             if ((hmmio = get_mmioFromFile(wps->pszSound)) == 0)
310             {
311                 hmmio = get_mmioFromProfile(wps->fdwSound, wps->pszSound);
312             }
313         }
314     }
315     if (hmmio == 0) goto errCleanUp;
316
317     if (mmioDescend(hmmio, &ckMainRIFF, NULL, 0))
318         goto errCleanUp;
319
320     TRACE("ParentChunk ckid=%.4s fccType=%.4s cksize=%08X\n",
321           (LPSTR)&ckMainRIFF.ckid, (LPSTR)&ckMainRIFF.fccType, ckMainRIFF.cksize);
322
323     if ((ckMainRIFF.ckid != FOURCC_RIFF) ||
324         (ckMainRIFF.fccType != mmioFOURCC('W', 'A', 'V', 'E')))
325         goto errCleanUp;
326
327     mmckInfo.ckid = mmioFOURCC('f', 'm', 't', ' ');
328     if (mmioDescend(hmmio, &mmckInfo, &ckMainRIFF, MMIO_FINDCHUNK))
329         goto errCleanUp;
330
331     TRACE("Chunk Found ckid=%.4s fccType=%08x cksize=%08X\n",
332           (LPSTR)&mmckInfo.ckid, mmckInfo.fccType, mmckInfo.cksize);
333
334     lpWaveFormat = HeapAlloc(GetProcessHeap(), 0, mmckInfo.cksize);
335     if (mmioRead(hmmio, (HPSTR)lpWaveFormat, mmckInfo.cksize) < sizeof(WAVEFORMAT))
336         goto errCleanUp;
337
338     TRACE("wFormatTag=%04X !\n",        lpWaveFormat->wFormatTag);
339     TRACE("nChannels=%d\n",             lpWaveFormat->nChannels);
340     TRACE("nSamplesPerSec=%d\n",        lpWaveFormat->nSamplesPerSec);
341     TRACE("nAvgBytesPerSec=%d\n",       lpWaveFormat->nAvgBytesPerSec);
342     TRACE("nBlockAlign=%d\n",           lpWaveFormat->nBlockAlign);
343     TRACE("wBitsPerSample=%u !\n",      lpWaveFormat->wBitsPerSample);
344
345     /* move to end of 'fmt ' chunk */
346     mmioAscend(hmmio, &mmckInfo, 0);
347
348     mmckInfo.ckid = mmioFOURCC('d', 'a', 't', 'a');
349     if (mmioDescend(hmmio, &mmckInfo, &ckMainRIFF, MMIO_FINDCHUNK))
350         goto errCleanUp;
351
352     TRACE("Chunk Found ckid=%.4s fccType=%08x cksize=%08X\n",
353           (LPSTR)&mmckInfo.ckid, mmckInfo.fccType, mmckInfo.cksize);
354
355     s.hEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
356
357     if (waveOutOpen(&hWave, WAVE_MAPPER, lpWaveFormat, (DWORD)PlaySound_Callback,
358                     (DWORD)&s, CALLBACK_FUNCTION) != MMSYSERR_NOERROR)
359         goto errCleanUp;
360
361     /* make it so that 3 buffers per second are needed */
362     bufsize = (((lpWaveFormat->nAvgBytesPerSec / 3) - 1) / lpWaveFormat->nBlockAlign + 1) *
363         lpWaveFormat->nBlockAlign;
364     waveHdr = HeapAlloc(GetProcessHeap(), 0, 2 * sizeof(WAVEHDR) + 2 * bufsize);
365     waveHdr[0].lpData = (char*)waveHdr + 2 * sizeof(WAVEHDR);
366     waveHdr[1].lpData = (char*)waveHdr + 2 * sizeof(WAVEHDR) + bufsize;
367     waveHdr[0].dwUser = waveHdr[1].dwUser = 0L;
368     waveHdr[0].dwLoops = waveHdr[1].dwLoops = 0L;
369     waveHdr[0].dwFlags = waveHdr[1].dwFlags = 0L;
370     waveHdr[0].dwBufferLength = waveHdr[1].dwBufferLength = bufsize;
371     if (waveOutPrepareHeader(hWave, &waveHdr[0], sizeof(WAVEHDR)) ||
372         waveOutPrepareHeader(hWave, &waveHdr[1], sizeof(WAVEHDR))) {
373         goto errCleanUp;
374     }
375
376     s.dwEventCount = 1L; /* for first buffer */
377     index = 0;
378
379     do {
380         left = mmckInfo.cksize;
381
382         mmioSeek(hmmio, mmckInfo.dwDataOffset, SEEK_SET);
383         while (left)
384         {
385             if (WaitForSingleObject(WINMM_IData.psStopEvent, 0) == WAIT_OBJECT_0)
386             {
387                 wps->bLoop = FALSE;
388                 break;
389             }
390             count = mmioRead(hmmio, waveHdr[index].lpData, min(bufsize, left));
391             if (count < 1) break;
392             left -= count;
393             waveHdr[index].dwBufferLength = count;
394             waveHdr[index].dwFlags &= ~WHDR_DONE;
395             if (waveOutWrite(hWave, &waveHdr[index], sizeof(WAVEHDR)) == MMSYSERR_NOERROR) {
396                 index ^= 1;
397                 PlaySound_WaitDone(&s);
398             }
399             else FIXME("Couldn't play header\n");
400         }
401         bRet = TRUE;
402     } while (wps->bLoop);
403
404     PlaySound_WaitDone(&s); /* for last buffer */
405     waveOutReset(hWave);
406
407     waveOutUnprepareHeader(hWave, &waveHdr[0], sizeof(WAVEHDR));
408     waveOutUnprepareHeader(hWave, &waveHdr[1], sizeof(WAVEHDR));
409
410 errCleanUp:
411     TRACE("Done playing='%s' => %s!\n", debugstr_w(wps->pszSound), bRet ? "ok" : "ko");
412     CloseHandle(s.hEvent);
413     HeapFree(GetProcessHeap(), 0, waveHdr);
414     HeapFree(GetProcessHeap(), 0, lpWaveFormat);
415     if (hWave)          while (waveOutClose(hWave) == WAVERR_STILLPLAYING) Sleep(100);
416     if (hmmio)          mmioClose(hmmio, 0);
417
418     PlaySound_Free(wps);
419
420     return bRet;
421 }
422
423 static BOOL MULTIMEDIA_PlaySound(const void* pszSound, HMODULE hmod, DWORD fdwSound, BOOL bUnicode)
424 {
425     WINE_PLAYSOUND*     wps = NULL;
426
427     TRACE("pszSound='%p' hmod=%p fdwSound=%08X\n",
428           pszSound, hmod, fdwSound);
429
430     /* FIXME? I see no difference between SND_NOWAIT and SND_NOSTOP !
431      * there could be one if several sounds can be played at once...
432      */
433     if ((fdwSound & (SND_NOWAIT | SND_NOSTOP)) && WINMM_IData.lpPlaySound != NULL)
434         return FALSE;
435
436     /* alloc internal structure, if we need to play something */
437     if (pszSound && !(fdwSound & SND_PURGE))
438     {
439         if (!(wps = PlaySound_Alloc(pszSound, hmod, fdwSound, bUnicode)))
440             return FALSE;
441     }
442
443     EnterCriticalSection(&WINMM_IData.cs);
444     /* since several threads can enter PlaySound in parallel, we're not
445      * sure, at this point, that another thread didn't start a new playsound
446      */
447     while (WINMM_IData.lpPlaySound != NULL)
448     {
449         ResetEvent(WINMM_IData.psLastEvent);
450         /* FIXME: doc says we have to stop all instances of pszSound if it's non
451          * NULL... as of today, we stop all playing instances */
452         SetEvent(WINMM_IData.psStopEvent);
453
454         LeaveCriticalSection(&WINMM_IData.cs);
455         WaitForSingleObject(WINMM_IData.psLastEvent, INFINITE);
456         EnterCriticalSection(&WINMM_IData.cs);
457
458         ResetEvent(WINMM_IData.psStopEvent);
459     }
460
461     if (wps) wps->lpNext = WINMM_IData.lpPlaySound;
462     WINMM_IData.lpPlaySound = wps;
463     LeaveCriticalSection(&WINMM_IData.cs);
464
465     if (!pszSound || (fdwSound & SND_PURGE)) return TRUE;
466
467     if (fdwSound & SND_ASYNC)
468     {
469         DWORD       id;
470         HANDLE      handle;
471         wps->bLoop = (fdwSound & SND_LOOP) ? TRUE : FALSE;
472         if ((handle = CreateThread(NULL, 0, proc_PlaySound, wps, 0, &id)) != 0) {
473             wps->hThread = handle;
474             SetThreadPriority(handle, THREAD_PRIORITY_TIME_CRITICAL);
475             return TRUE;
476         }
477     }
478     else return proc_PlaySound(wps);
479
480     /* error cases */
481     PlaySound_Free(wps);
482     return FALSE;
483 }
484
485 /**************************************************************************
486  *                              PlaySoundA              [WINMM.@]
487  */
488 BOOL WINAPI PlaySoundA(LPCSTR pszSoundA, HMODULE hmod, DWORD fdwSound)
489 {
490     return MULTIMEDIA_PlaySound(pszSoundA, hmod, fdwSound, FALSE);
491 }
492
493 /**************************************************************************
494  *                              PlaySoundW              [WINMM.@]
495  */
496 BOOL WINAPI PlaySoundW(LPCWSTR pszSoundW, HMODULE hmod, DWORD fdwSound)
497 {
498     return MULTIMEDIA_PlaySound(pszSoundW, hmod, fdwSound, TRUE);
499 }
500
501 /**************************************************************************
502  *                              sndPlaySoundA           [WINMM.@]
503  */
504 BOOL WINAPI sndPlaySoundA(LPCSTR pszSoundA, UINT uFlags)
505 {
506     uFlags &= SND_ASYNC|SND_LOOP|SND_MEMORY|SND_NODEFAULT|SND_NOSTOP|SND_SYNC;
507     return MULTIMEDIA_PlaySound(pszSoundA, 0, uFlags, FALSE);
508 }
509
510 /**************************************************************************
511  *                              sndPlaySoundW           [WINMM.@]
512  */
513 BOOL WINAPI sndPlaySoundW(LPCWSTR pszSound, UINT uFlags)
514 {
515     uFlags &= SND_ASYNC|SND_LOOP|SND_MEMORY|SND_NODEFAULT|SND_NOSTOP|SND_SYNC;
516     return MULTIMEDIA_PlaySound(pszSound, 0, uFlags, TRUE);
517 }
518
519 /**************************************************************************
520  *                              mmsystemGetVersion      [WINMM.@]
521  */
522 UINT WINAPI mmsystemGetVersion(void)
523 {
524     TRACE("3.10 (Win95?)\n");
525     return 0x030a;
526 }