msvcrt: Simplify platform checks for exception handling functions.
[wine.git] / dlls / winmm / playsound.c
blob2ba2ad1e8dc0a2b88de3ac84d66a44a3e902664a
1 /* -*- tab-width: 8; c-basic-offset: 4 -*- */
3 /*
4 * MMSYSTEM functions
6 * Copyright 1993 Martin Ayotte
7 * 1998-2002 Eric Pouech
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.
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.
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
24 #include <stdarg.h>
25 #include <string.h>
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"
36 #include "wine/debug.h"
38 WINE_DEFAULT_DEBUG_CHANNEL(winmm);
40 typedef struct tagWINE_PLAYSOUND
42 unsigned bLoop : 1,
43 bAlloc : 1;
44 LPCWSTR pszSound;
45 HMODULE hMod;
46 DWORD fdwSound;
47 HWAVEOUT hWave;
48 } WINE_PLAYSOUND;
50 static WINE_PLAYSOUND *PlaySoundCurrent;
51 static BOOL bPlaySoundStop;
53 static HMMIO get_mmioFromFile(LPCWSTR lpszName)
55 HMMIO ret;
56 WCHAR buf[256];
57 LPWSTR dummy;
59 ret = mmioOpenW((LPWSTR)lpszName, NULL,
60 MMIO_ALLOCBUF | MMIO_READ | MMIO_DENYWRITE);
61 if (ret != 0) return ret;
62 if (SearchPathW(NULL, lpszName, L".wav", ARRAY_SIZE(buf), buf, &dummy))
64 return mmioOpenW(buf, NULL,
65 MMIO_ALLOCBUF | MMIO_READ | MMIO_DENYWRITE);
67 return 0;
70 static HMMIO get_mmioFromProfile(UINT uFlags, LPCWSTR lpszName)
72 WCHAR str[128];
73 LPWSTR ptr;
74 HMMIO hmmio;
75 HKEY hRegSnd, hRegApp, hScheme, hSnd;
76 DWORD err, type, count;
78 TRACE("searching in SystemSound list for %s\n", debugstr_w(lpszName));
79 GetProfileStringW(L"Sounds", lpszName, L"", str, ARRAY_SIZE(str));
80 if (!*str)
82 if (uFlags & SND_NODEFAULT) goto next;
83 GetProfileStringW(L"Sounds", L"Default", L"", str, ARRAY_SIZE(str));
84 if (!*str) goto next;
86 for (ptr = str; *ptr && *ptr != ','; ptr++);
87 if (*ptr) *ptr = 0;
88 hmmio = mmioOpenW(str, NULL, MMIO_ALLOCBUF | MMIO_READ | MMIO_DENYWRITE);
89 if (hmmio != 0) return hmmio;
90 next:
91 /* we look up the registry under
92 * HKCU\AppEvents\Schemes\Apps\.Default
93 * HKCU\AppEvents\Schemes\Apps\<AppName>
95 if (RegOpenKeyW(HKEY_CURRENT_USER, L"AppEvents\\Schemes\\Apps", &hRegSnd) != 0) goto none;
96 if (uFlags & SND_APPLICATION)
98 DWORD len;
100 err = 1; /* error */
101 len = GetModuleFileNameW(0, str, ARRAY_SIZE(str));
102 if (len > 0 && len < ARRAY_SIZE(str))
104 for (ptr = str + lstrlenW(str) - 1; ptr >= str; ptr--)
106 if (*ptr == '.') *ptr = 0;
107 if (*ptr == '\\')
109 err = RegOpenKeyW(hRegSnd, ptr+1, &hRegApp);
110 break;
115 else
117 err = RegOpenKeyW(hRegSnd, L".Default", &hRegApp);
119 RegCloseKey(hRegSnd);
120 if (err != 0) goto none;
121 err = RegOpenKeyW(hRegApp, lpszName, &hScheme);
122 RegCloseKey(hRegApp);
123 if (err != 0) goto none;
124 /* what's the difference between .Current and .Default ? */
125 err = RegOpenKeyW(hScheme, L".Default", &hSnd);
126 if (err != 0)
128 err = RegOpenKeyW(hScheme, L".Current", &hSnd);
129 RegCloseKey(hScheme);
130 if (err != 0)
131 goto none;
133 count = sizeof(str);
134 err = RegQueryValueExW(hSnd, NULL, 0, &type, (LPBYTE)str, &count);
135 RegCloseKey(hSnd);
136 if (err != 0 || !*str) goto none;
137 hmmio = mmioOpenW(str, NULL, MMIO_ALLOCBUF | MMIO_READ | MMIO_DENYWRITE);
138 if (hmmio) return hmmio;
139 none:
140 WARN("can't find SystemSound=%s !\n", debugstr_w(lpszName));
141 return 0;
144 struct playsound_data
146 HANDLE hEvent;
147 LONG dwEventCount;
150 static void CALLBACK PlaySound_Callback(HWAVEOUT hwo, UINT uMsg,
151 DWORD_PTR dwInstance,
152 DWORD_PTR dwParam1, DWORD_PTR dwParam2)
154 struct playsound_data* s = (struct playsound_data*)dwInstance;
156 switch (uMsg) {
157 case WOM_OPEN:
158 case WOM_CLOSE:
159 break;
160 case WOM_DONE:
161 InterlockedIncrement(&s->dwEventCount);
162 TRACE("Returning waveHdr=%Ix\n", dwParam1);
163 SetEvent(s->hEvent);
164 break;
165 default:
166 ERR("Unknown uMsg=%d\n", uMsg);
170 static void PlaySound_WaitDone(struct playsound_data* s)
172 for (;;) {
173 if (InterlockedDecrement(&s->dwEventCount) >= 0) break;
174 InterlockedIncrement(&s->dwEventCount);
176 WaitForSingleObject(s->hEvent, INFINITE);
180 static BOOL PlaySound_IsString(DWORD fdwSound, const void* psz)
182 /* SND_RESOURCE is 0x40004 while
183 * SND_MEMORY is 0x00004
185 switch (fdwSound & (SND_RESOURCE|SND_ALIAS_ID|SND_FILENAME))
187 case SND_RESOURCE: return HIWORD(psz) != 0; /* by name or by ID ? */
188 case SND_ALIAS_ID:
189 case SND_MEMORY: return FALSE;
190 case SND_ALIAS:
191 case SND_FILENAME:
192 case SND_ALIAS|SND_FILENAME:
193 case 0: return TRUE;
194 default: FIXME("WTF\n"); return FALSE;
198 static void PlaySound_Free(WINE_PLAYSOUND* wps)
200 EnterCriticalSection(&WINMM_cs);
201 PlaySoundCurrent = NULL;
202 SetEvent(psLastEvent);
203 LeaveCriticalSection(&WINMM_cs);
204 if (wps->bAlloc) free((void*)wps->pszSound);
205 free(wps);
208 static WINE_PLAYSOUND* PlaySound_Alloc(const void* pszSound, HMODULE hmod,
209 DWORD fdwSound, BOOL bUnicode)
211 WINE_PLAYSOUND* wps;
213 wps = calloc(1, sizeof(*wps));
214 if (!wps) return NULL;
216 wps->hMod = hmod;
217 wps->fdwSound = fdwSound;
218 if (PlaySound_IsString(fdwSound, pszSound))
220 if (bUnicode)
222 if (fdwSound & SND_ASYNC)
224 wps->pszSound = wcsdup(pszSound);
225 if (!wps->pszSound) goto oom_error;
226 wps->bAlloc = TRUE;
228 else
229 wps->pszSound = pszSound;
231 else
233 UNICODE_STRING usBuffer;
234 RtlCreateUnicodeStringFromAsciiz(&usBuffer, pszSound);
235 wps->pszSound = usBuffer.Buffer;
236 if (!wps->pszSound) goto oom_error;
237 wps->bAlloc = TRUE;
240 else
241 wps->pszSound = pszSound;
243 return wps;
244 oom_error:
245 if (wps->bAlloc) free((void*)wps->pszSound);
246 free(wps);
247 return NULL;
250 static DWORD WINAPI proc_PlaySound(LPVOID arg)
252 WINE_PLAYSOUND* wps = 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 LONG r;
265 s.hEvent = 0;
267 TRACE("SoundName=%s !\n", debugstr_w(wps->pszSound));
269 /* if resource, grab it */
270 if ((wps->fdwSound & SND_RESOURCE) == SND_RESOURCE) {
271 HRSRC hRes;
272 HGLOBAL hGlob;
274 if ((hRes = FindResourceW(wps->hMod, wps->pszSound, L"WAVE")) == 0 ||
275 (hGlob = LoadResource(wps->hMod, hRes)) == 0)
276 goto errCleanUp;
277 if ((data = LockResource(hGlob)) == NULL) {
278 FreeResource(hGlob);
279 goto errCleanUp;
281 FreeResource(hGlob);
282 } else
283 data = (void*)wps->pszSound;
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;
290 memset(&mminfo, 0, sizeof(mminfo));
291 mminfo.fccIOProc = FOURCC_MEM;
292 mminfo.pchBuffer = 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);
297 if (!hmmio && wps->fdwSound & SND_ALIAS)
299 if ((wps->fdwSound & SND_ALIAS_ID) == SND_ALIAS_ID)
301 wps->fdwSound &= ~(SND_ALIAS_ID ^ SND_ALIAS);
302 if (wps->pszSound == (LPCWSTR)SND_ALIAS_SYSTEMASTERISK)
303 wps->pszSound = L"SystemAsterisk";
304 else if (wps->pszSound == (LPCWSTR)SND_ALIAS_SYSTEMDEFAULT)
305 wps->pszSound = L"SystemDefault";
306 else if (wps->pszSound == (LPCWSTR)SND_ALIAS_SYSTEMEXCLAMATION)
307 wps->pszSound = L"SystemExclamation";
308 else if (wps->pszSound == (LPCWSTR)SND_ALIAS_SYSTEMEXIT)
309 wps->pszSound = L"SystemExit";
310 else if (wps->pszSound == (LPCWSTR)SND_ALIAS_SYSTEMHAND)
311 wps->pszSound = L"SystemHand";
312 else if (wps->pszSound == (LPCWSTR)SND_ALIAS_SYSTEMQUESTION)
313 wps->pszSound = L"SystemQuestion";
314 else if (wps->pszSound == (LPCWSTR)SND_ALIAS_SYSTEMSTART)
315 wps->pszSound = L"SystemStart";
316 else if (wps->pszSound == (LPCWSTR)SND_ALIAS_SYSTEMWELCOME)
317 wps->pszSound = L"SystemWelcome";
318 else goto errCleanUp;
320 hmmio = get_mmioFromProfile(wps->fdwSound, wps->pszSound);
321 if (!hmmio)
323 wps->fdwSound &= ~SND_ALIAS;
324 wps->fdwSound |= SND_FILENAME;
327 if (!hmmio && wps->fdwSound & SND_FILENAME)
329 hmmio = get_mmioFromFile(wps->pszSound);
331 if (!(wps->fdwSound & (SND_FILENAME|SND_ALIAS|SND_MEMORY)))
333 if ((hmmio = get_mmioFromProfile(wps->fdwSound | SND_NODEFAULT, wps->pszSound)) == 0)
335 if ((hmmio = get_mmioFromFile(wps->pszSound)) == 0)
337 hmmio = get_mmioFromProfile(wps->fdwSound, wps->pszSound);
341 if (hmmio == 0) goto errCleanUp;
343 if (mmioDescend(hmmio, &ckMainRIFF, NULL, 0))
344 goto errCleanUp;
346 TRACE("ParentChunk ckid=%.4s fccType=%.4s cksize=%08lX\n",
347 (LPSTR)&ckMainRIFF.ckid, (LPSTR)&ckMainRIFF.fccType, ckMainRIFF.cksize);
349 if ((ckMainRIFF.ckid != FOURCC_RIFF) ||
350 (ckMainRIFF.fccType != mmioFOURCC('W', 'A', 'V', 'E')))
351 goto errCleanUp;
353 mmckInfo.ckid = mmioFOURCC('f', 'm', 't', ' ');
354 if (mmioDescend(hmmio, &mmckInfo, &ckMainRIFF, MMIO_FINDCHUNK))
355 goto errCleanUp;
357 TRACE("Chunk Found ckid=%.4s fccType=%08lx cksize=%08lX\n",
358 (LPSTR)&mmckInfo.ckid, mmckInfo.fccType, mmckInfo.cksize);
360 lpWaveFormat = malloc(mmckInfo.cksize);
361 if (!lpWaveFormat)
362 goto errCleanUp;
363 r = mmioRead(hmmio, (HPSTR)lpWaveFormat, mmckInfo.cksize);
364 if (r < 0 || r < sizeof(PCMWAVEFORMAT))
365 goto errCleanUp;
367 TRACE("wFormatTag=%04X !\n", lpWaveFormat->wFormatTag);
368 TRACE("nChannels=%d\n", lpWaveFormat->nChannels);
369 TRACE("nSamplesPerSec=%ld\n", lpWaveFormat->nSamplesPerSec);
370 TRACE("nAvgBytesPerSec=%ld\n", lpWaveFormat->nAvgBytesPerSec);
371 TRACE("nBlockAlign=%d\n", lpWaveFormat->nBlockAlign);
372 TRACE("wBitsPerSample=%u !\n", lpWaveFormat->wBitsPerSample);
374 /* move to end of 'fmt ' chunk */
375 mmioAscend(hmmio, &mmckInfo, 0);
377 mmckInfo.ckid = mmioFOURCC('d', 'a', 't', 'a');
378 if (mmioDescend(hmmio, &mmckInfo, &ckMainRIFF, MMIO_FINDCHUNK))
379 goto errCleanUp;
381 TRACE("Chunk Found ckid=%.4s fccType=%08lx cksize=%08lX\n",
382 (LPSTR)&mmckInfo.ckid, mmckInfo.fccType, mmckInfo.cksize);
384 s.hEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
385 if (!s.hEvent || bPlaySoundStop)
386 goto errCleanUp;
388 if (waveOutOpen(&hWave, WAVE_MAPPER, lpWaveFormat, (DWORD_PTR)PlaySound_Callback,
389 (DWORD_PTR)&s, CALLBACK_FUNCTION) != MMSYSERR_NOERROR)
390 goto errCleanUp;
392 /* make it so that 3 buffers per second are needed */
393 bufsize = (((lpWaveFormat->nAvgBytesPerSec / 3) - 1) / lpWaveFormat->nBlockAlign + 1) *
394 lpWaveFormat->nBlockAlign;
395 waveHdr = malloc(2 * sizeof(WAVEHDR) + 2 * bufsize);
396 if (!waveHdr)
397 goto errCleanUp;
398 waveHdr[0].lpData = (char*)waveHdr + 2 * sizeof(WAVEHDR);
399 waveHdr[1].lpData = (char*)waveHdr + 2 * sizeof(WAVEHDR) + bufsize;
400 waveHdr[0].dwUser = waveHdr[1].dwUser = 0L;
401 waveHdr[0].dwLoops = waveHdr[1].dwLoops = 0L;
402 waveHdr[0].dwFlags = waveHdr[1].dwFlags = 0L;
403 waveHdr[0].dwBufferLength = waveHdr[1].dwBufferLength = bufsize;
404 if (waveOutPrepareHeader(hWave, &waveHdr[0], sizeof(WAVEHDR)) ||
405 waveOutPrepareHeader(hWave, &waveHdr[1], sizeof(WAVEHDR))) {
406 goto errCleanUp;
409 wps->hWave = hWave;
410 s.dwEventCount = 1L; /* for first buffer */
411 index = 0;
413 do {
414 left = mmckInfo.cksize;
416 mmioSeek(hmmio, mmckInfo.dwDataOffset, SEEK_SET);
417 while (left)
419 if (bPlaySoundStop)
421 wps->bLoop = FALSE;
422 break;
424 count = mmioRead(hmmio, waveHdr[index].lpData, min(bufsize, left));
425 if (count < 1) break;
426 left -= count;
427 waveHdr[index].dwBufferLength = count;
428 if (waveOutWrite(hWave, &waveHdr[index], sizeof(WAVEHDR)) == MMSYSERR_NOERROR) {
429 index ^= 1;
430 PlaySound_WaitDone(&s);
432 else {
433 ERR("Aborting play loop, waveOutWrite error\n");
434 wps->bLoop = FALSE;
435 break;
438 bRet = TRUE;
439 } while (wps->bLoop);
441 PlaySound_WaitDone(&s); /* to balance first buffer */
442 waveOutReset(hWave);
444 waveOutUnprepareHeader(hWave, &waveHdr[0], sizeof(WAVEHDR));
445 waveOutUnprepareHeader(hWave, &waveHdr[1], sizeof(WAVEHDR));
447 errCleanUp:
448 TRACE("Done playing=%s => %s!\n", debugstr_w(wps->pszSound), bRet ? "ok" : "ko");
449 free(lpWaveFormat);
450 if (hWave)
452 EnterCriticalSection(&WINMM_cs);
453 /* the CS prevents a concurrent waveOutReset */
454 wps->hWave = 0;
455 LeaveCriticalSection(&WINMM_cs);
456 while (waveOutClose(hWave) == WAVERR_STILLPLAYING)
457 Sleep(100);
459 CloseHandle(s.hEvent);
460 free(waveHdr);
461 if (hmmio) mmioClose(hmmio, 0);
463 PlaySound_Free(wps);
465 return bRet;
468 static BOOL MULTIMEDIA_PlaySound(const void* pszSound, HMODULE hmod, DWORD fdwSound, BOOL bUnicode)
470 WINE_PLAYSOUND* wps = NULL;
472 TRACE("pszSound='%p' hmod=%p fdwSound=%08lX\n",
473 pszSound, hmod, fdwSound);
475 /* SND_NOWAIT is ignored in w95/2k/xp. */
476 if ((fdwSound & SND_NOSTOP) && PlaySoundCurrent != NULL)
477 return FALSE;
479 /* alloc internal structure, if we need to play something */
480 if (pszSound && !(fdwSound & SND_PURGE))
482 if (!(wps = PlaySound_Alloc(pszSound, hmod, fdwSound, bUnicode)))
483 return FALSE;
486 EnterCriticalSection(&WINMM_cs);
487 /* since several threads can enter PlaySound in parallel, we're not
488 * sure, at this point, that another thread didn't start a new playsound
490 while (PlaySoundCurrent != NULL)
492 ResetEvent(psLastEvent);
493 /* FIXME: doc says we have to stop all instances of pszSound if it's non
494 * NULL... as of today, we stop all playing instances */
495 bPlaySoundStop = TRUE;
496 if(PlaySoundCurrent->hWave)
497 waveOutReset(PlaySoundCurrent->hWave);
499 LeaveCriticalSection(&WINMM_cs);
500 WaitForSingleObject(psLastEvent, INFINITE);
501 EnterCriticalSection(&WINMM_cs);
503 bPlaySoundStop = FALSE;
506 PlaySoundCurrent = wps;
507 LeaveCriticalSection(&WINMM_cs);
509 if (!wps) return TRUE;
511 if (fdwSound & SND_ASYNC)
513 HANDLE handle;
514 wps->bLoop = (fdwSound & SND_LOOP) != 0;
515 if ((handle = CreateThread(NULL, 0, proc_PlaySound, wps, 0, NULL)) != 0) {
516 SetThreadPriority(handle, THREAD_PRIORITY_TIME_CRITICAL);
517 CloseHandle(handle);
518 return TRUE;
521 else return proc_PlaySound(wps);
523 /* error cases */
524 PlaySound_Free(wps);
525 return FALSE;
528 /**************************************************************************
529 * PlaySoundA [WINMM.@]
531 BOOL WINAPI PlaySoundA(LPCSTR pszSoundA, HMODULE hmod, DWORD fdwSound)
533 return MULTIMEDIA_PlaySound(pszSoundA, hmod, fdwSound, FALSE);
536 /**************************************************************************
537 * PlaySoundW [WINMM.@]
539 BOOL WINAPI PlaySoundW(LPCWSTR pszSoundW, HMODULE hmod, DWORD fdwSound)
541 return MULTIMEDIA_PlaySound(pszSoundW, hmod, fdwSound, TRUE);
544 /**************************************************************************
545 * sndPlaySoundA [WINMM.@]
547 BOOL WINAPI sndPlaySoundA(LPCSTR pszSoundA, UINT uFlags)
549 uFlags &= SND_RESOURCE|SND_ALIAS_ID|SND_FILENAME|SND_ASYNC|SND_LOOP|SND_MEMORY|SND_NODEFAULT|SND_NOSTOP|SND_SYNC;
550 return MULTIMEDIA_PlaySound(pszSoundA, 0, uFlags, FALSE);
553 /**************************************************************************
554 * sndPlaySoundW [WINMM.@]
556 BOOL WINAPI sndPlaySoundW(LPCWSTR pszSound, UINT uFlags)
558 uFlags &= SND_RESOURCE|SND_ALIAS_ID|SND_FILENAME|SND_ASYNC|SND_LOOP|SND_MEMORY|SND_NODEFAULT|SND_NOSTOP|SND_SYNC;
559 return MULTIMEDIA_PlaySound(pszSound, 0, uFlags, TRUE);
562 /**************************************************************************
563 * mmsystemGetVersion [WINMM.@]
565 UINT WINAPI mmsystemGetVersion(void)
567 TRACE("3.10 (Win95?)\n");
568 return 0x030a;