winmm: Get rid of psStopEvent which was never used like an event.
[wine/multimedia.git] / dlls / winmm / playsound.c
blob3624124129bf69c02e5db3ea683eb11a0eaa7a95
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 HANDLE hThread;
48 struct tagWINE_PLAYSOUND* lpNext;
49 } WINE_PLAYSOUND;
51 static WINE_PLAYSOUND *PlaySoundList;
52 static BOOL bPlaySoundStop;
54 static HMMIO get_mmioFromFile(LPCWSTR lpszName)
56 HMMIO ret;
57 WCHAR buf[256];
58 LPWSTR dummy;
60 ret = mmioOpenW((LPWSTR)lpszName, NULL,
61 MMIO_ALLOCBUF | MMIO_READ | MMIO_DENYWRITE);
62 if (ret != 0) return ret;
63 if (SearchPathW(NULL, lpszName, NULL, sizeof(buf)/sizeof(buf[0]), buf, &dummy))
65 return mmioOpenW(buf, NULL,
66 MMIO_ALLOCBUF | MMIO_READ | MMIO_DENYWRITE);
68 return 0;
71 static HMMIO get_mmioFromProfile(UINT uFlags, LPCWSTR lpszName)
73 WCHAR str[128];
74 LPWSTR ptr;
75 HMMIO hmmio;
76 HKEY hRegSnd, hRegApp, hScheme, hSnd;
77 DWORD err, type, count;
79 static const WCHAR wszSounds[] = {'S','o','u','n','d','s',0};
80 static const WCHAR wszDefault[] = {'D','e','f','a','u','l','t',0};
81 static const WCHAR wszKey[] = {'A','p','p','E','v','e','n','t','s','\\',
82 'S','c','h','e','m','e','s','\\',
83 'A','p','p','s',0};
84 static const WCHAR wszDotDefault[] = {'.','D','e','f','a','u','l','t',0};
85 static const WCHAR wszDotCurrent[] = {'.','C','u','r','r','e','n','t',0};
86 static const WCHAR wszNull[] = {0};
88 TRACE("searching in SystemSound list for %s\n", debugstr_w(lpszName));
89 GetProfileStringW(wszSounds, lpszName, wszNull, str, sizeof(str)/sizeof(str[0]));
90 if (lstrlenW(str) == 0)
92 if (uFlags & SND_NODEFAULT) goto next;
93 GetProfileStringW(wszSounds, wszDefault, wszNull, str, sizeof(str)/sizeof(str[0]));
94 if (lstrlenW(str) == 0) goto next;
96 for (ptr = str; *ptr && *ptr != ','; ptr++);
97 if (*ptr) *ptr = 0;
98 hmmio = mmioOpenW(str, NULL, MMIO_ALLOCBUF | MMIO_READ | MMIO_DENYWRITE);
99 if (hmmio != 0) return hmmio;
100 next:
101 /* we look up the registry under
102 * HKCU\AppEvents\Schemes\Apps\.Default
103 * HKCU\AppEvents\Schemes\Apps\<AppName>
105 if (RegOpenKeyW(HKEY_CURRENT_USER, wszKey, &hRegSnd) != 0) goto none;
106 if (uFlags & SND_APPLICATION)
108 DWORD len;
110 err = 1; /* error */
111 len = GetModuleFileNameW(0, str, sizeof(str)/sizeof(str[0]));
112 if (len > 0 && len < sizeof(str)/sizeof(str[0]))
114 for (ptr = str + lstrlenW(str) - 1; ptr >= str; ptr--)
116 if (*ptr == '.') *ptr = 0;
117 if (*ptr == '\\')
119 err = RegOpenKeyW(hRegSnd, ptr+1, &hRegApp);
120 break;
125 else
127 err = RegOpenKeyW(hRegSnd, wszDotDefault, &hRegApp);
129 RegCloseKey(hRegSnd);
130 if (err != 0) goto none;
131 err = RegOpenKeyW(hRegApp, lpszName, &hScheme);
132 RegCloseKey(hRegApp);
133 if (err != 0) goto none;
134 /* what's the difference between .Current and .Default ? */
135 err = RegOpenKeyW(hScheme, wszDotDefault, &hSnd);
136 if (err != 0)
138 err = RegOpenKeyW(hScheme, wszDotCurrent, &hSnd);
139 RegCloseKey(hScheme);
140 if (err != 0)
141 goto none;
143 count = sizeof(str)/sizeof(str[0]);
144 err = RegQueryValueExW(hSnd, NULL, 0, &type, (LPBYTE)str, &count);
145 RegCloseKey(hSnd);
146 if (err != 0 || !*str) goto none;
147 hmmio = mmioOpenW(str, NULL, MMIO_ALLOCBUF | MMIO_READ | MMIO_DENYWRITE);
148 if (hmmio) return hmmio;
149 none:
150 WARN("can't find SystemSound=%s !\n", debugstr_w(lpszName));
151 return 0;
154 struct playsound_data
156 HANDLE hEvent;
157 LONG dwEventCount;
160 static void CALLBACK PlaySound_Callback(HWAVEOUT hwo, UINT uMsg,
161 DWORD_PTR dwInstance,
162 DWORD_PTR dwParam1, DWORD_PTR dwParam2)
164 struct playsound_data* s = (struct playsound_data*)dwInstance;
166 switch (uMsg) {
167 case WOM_OPEN:
168 case WOM_CLOSE:
169 break;
170 case WOM_DONE:
171 InterlockedIncrement(&s->dwEventCount);
172 TRACE("Returning waveHdr=%lx\n", dwParam1);
173 SetEvent(s->hEvent);
174 break;
175 default:
176 ERR("Unknown uMsg=%d\n", uMsg);
180 static void PlaySound_WaitDone(struct playsound_data* s)
182 for (;;) {
183 if (InterlockedDecrement(&s->dwEventCount) >= 0) break;
184 InterlockedIncrement(&s->dwEventCount);
186 WaitForSingleObject(s->hEvent, INFINITE);
190 static BOOL PlaySound_IsString(DWORD fdwSound, const void* psz)
192 /* SND_RESOURCE is 0x40004 while
193 * SND_MEMORY is 0x00004
195 switch (fdwSound & (SND_RESOURCE|SND_ALIAS_ID|SND_FILENAME))
197 case SND_RESOURCE: return HIWORD(psz) != 0; /* by name or by ID ? */
198 case SND_ALIAS_ID:
199 case SND_MEMORY: return FALSE;
200 case SND_ALIAS:
201 case SND_FILENAME:
202 case SND_ALIAS|SND_FILENAME:
203 case 0: return TRUE;
204 default: FIXME("WTF\n"); return FALSE;
208 static void PlaySound_Free(WINE_PLAYSOUND* wps)
210 WINE_PLAYSOUND** p;
212 EnterCriticalSection(&WINMM_cs);
213 for (p = &PlaySoundList; *p && *p != wps; p = &((*p)->lpNext));
214 if (*p) *p = (*p)->lpNext;
215 if (PlaySoundList == NULL) SetEvent(psLastEvent);
216 LeaveCriticalSection(&WINMM_cs);
217 if (wps->bAlloc) HeapFree(GetProcessHeap(), 0, (void*)wps->pszSound);
218 if (wps->hThread) CloseHandle(wps->hThread);
219 HeapFree(GetProcessHeap(), 0, wps);
222 static WINE_PLAYSOUND* PlaySound_Alloc(const void* pszSound, HMODULE hmod,
223 DWORD fdwSound, BOOL bUnicode)
225 WINE_PLAYSOUND* wps;
227 wps = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*wps));
228 if (!wps) return NULL;
230 wps->hMod = hmod;
231 wps->fdwSound = fdwSound;
232 if (PlaySound_IsString(fdwSound, pszSound))
234 if (bUnicode)
236 if (fdwSound & SND_ASYNC)
238 LPWSTR sound = HeapAlloc(GetProcessHeap(), 0,
239 (lstrlenW(pszSound)+1) * sizeof(WCHAR));
240 if (!sound) goto oom_error;
241 wps->pszSound = lstrcpyW(sound, pszSound);
242 wps->bAlloc = TRUE;
244 else
245 wps->pszSound = pszSound;
247 else
249 UNICODE_STRING usBuffer;
250 RtlCreateUnicodeStringFromAsciiz(&usBuffer, pszSound);
251 wps->pszSound = usBuffer.Buffer;
252 if (!wps->pszSound) goto oom_error;
253 wps->bAlloc = TRUE;
256 else
257 wps->pszSound = pszSound;
259 return wps;
260 oom_error:
261 PlaySound_Free(wps);
262 return NULL;
265 static DWORD WINAPI proc_PlaySound(LPVOID arg)
267 WINE_PLAYSOUND* wps = arg;
268 BOOL bRet = FALSE;
269 HMMIO hmmio = 0;
270 MMCKINFO ckMainRIFF;
271 MMCKINFO mmckInfo;
272 LPWAVEFORMATEX lpWaveFormat = NULL;
273 HWAVEOUT hWave = 0;
274 LPWAVEHDR waveHdr = NULL;
275 INT count, bufsize, left, index;
276 struct playsound_data s;
277 void* data;
279 s.hEvent = 0;
281 TRACE("SoundName=%s !\n", debugstr_w(wps->pszSound));
283 /* if resource, grab it */
284 if ((wps->fdwSound & SND_RESOURCE) == SND_RESOURCE) {
285 static const WCHAR wszWave[] = {'W','A','V','E',0};
286 HRSRC hRes;
287 HGLOBAL hGlob;
289 if ((hRes = FindResourceW(wps->hMod, wps->pszSound, wszWave)) == 0 ||
290 (hGlob = LoadResource(wps->hMod, hRes)) == 0)
291 goto errCleanUp;
292 if ((data = LockResource(hGlob)) == NULL) {
293 FreeResource(hGlob);
294 goto errCleanUp;
296 FreeResource(hGlob);
297 } else
298 data = (void*)wps->pszSound;
300 /* construct an MMIO stream (either in memory, or from a file */
301 if (wps->fdwSound & SND_MEMORY)
302 { /* NOTE: SND_RESOURCE has the SND_MEMORY bit set */
303 MMIOINFO mminfo;
305 memset(&mminfo, 0, sizeof(mminfo));
306 mminfo.fccIOProc = FOURCC_MEM;
307 mminfo.pchBuffer = data;
308 mminfo.cchBuffer = -1; /* FIXME: when a resource, could grab real size */
309 TRACE("Memory sound %p\n", data);
310 hmmio = mmioOpenW(NULL, &mminfo, MMIO_READ);
312 if (!hmmio && wps->fdwSound & SND_ALIAS)
314 if ((wps->fdwSound & SND_ALIAS_ID) == SND_ALIAS_ID)
316 static const WCHAR wszSystemAsterisk[] = {'S','y','s','t','e','m','A','s','t','e','r','i','s','k',0};
317 static const WCHAR wszSystemDefault[] = {'S','y','s','t','e','m','D','e','f','a','u','l','t',0};
318 static const WCHAR wszSystemExclamation[] = {'S','y','s','t','e','m','E','x','c','l','a','m','a','t','i','o','n',0};
319 static const WCHAR wszSystemExit[] = {'S','y','s','t','e','m','E','x','i','t',0};
320 static const WCHAR wszSystemHand[] = {'S','y','s','t','e','m','H','a','n','d',0};
321 static const WCHAR wszSystemQuestion[] = {'S','y','s','t','e','m','Q','u','e','s','t','i','o','n',0};
322 static const WCHAR wszSystemStart[] = {'S','y','s','t','e','m','S','t','a','r','t',0};
323 static const WCHAR wszSystemWelcome[] = {'S','y','s','t','e','m','W','e','l','c','o','m','e',0};
325 wps->fdwSound &= ~(SND_ALIAS_ID ^ SND_ALIAS);
326 if (wps->pszSound == (LPCWSTR)SND_ALIAS_SYSTEMASTERISK)
327 wps->pszSound = wszSystemAsterisk;
328 else if (wps->pszSound == (LPCWSTR)SND_ALIAS_SYSTEMDEFAULT)
329 wps->pszSound = wszSystemDefault;
330 else if (wps->pszSound == (LPCWSTR)SND_ALIAS_SYSTEMEXCLAMATION)
331 wps->pszSound = wszSystemExclamation;
332 else if (wps->pszSound == (LPCWSTR)SND_ALIAS_SYSTEMEXIT)
333 wps->pszSound = wszSystemExit;
334 else if (wps->pszSound == (LPCWSTR)SND_ALIAS_SYSTEMHAND)
335 wps->pszSound = wszSystemHand;
336 else if (wps->pszSound == (LPCWSTR)SND_ALIAS_SYSTEMQUESTION)
337 wps->pszSound = wszSystemQuestion;
338 else if (wps->pszSound == (LPCWSTR)SND_ALIAS_SYSTEMSTART)
339 wps->pszSound = wszSystemStart;
340 else if (wps->pszSound == (LPCWSTR)SND_ALIAS_SYSTEMWELCOME)
341 wps->pszSound = wszSystemWelcome;
342 else goto errCleanUp;
344 hmmio = get_mmioFromProfile(wps->fdwSound, wps->pszSound);
346 if (!hmmio && wps->fdwSound & SND_FILENAME)
348 hmmio = get_mmioFromFile(wps->pszSound);
350 if (!(wps->fdwSound & (SND_FILENAME|SND_ALIAS|SND_MEMORY)))
352 if ((hmmio = get_mmioFromProfile(wps->fdwSound | SND_NODEFAULT, wps->pszSound)) == 0)
354 if ((hmmio = get_mmioFromFile(wps->pszSound)) == 0)
356 hmmio = get_mmioFromProfile(wps->fdwSound, wps->pszSound);
360 if (hmmio == 0) goto errCleanUp;
362 if (mmioDescend(hmmio, &ckMainRIFF, NULL, 0))
363 goto errCleanUp;
365 TRACE("ParentChunk ckid=%.4s fccType=%.4s cksize=%08X\n",
366 (LPSTR)&ckMainRIFF.ckid, (LPSTR)&ckMainRIFF.fccType, ckMainRIFF.cksize);
368 if ((ckMainRIFF.ckid != FOURCC_RIFF) ||
369 (ckMainRIFF.fccType != mmioFOURCC('W', 'A', 'V', 'E')))
370 goto errCleanUp;
372 mmckInfo.ckid = mmioFOURCC('f', 'm', 't', ' ');
373 if (mmioDescend(hmmio, &mmckInfo, &ckMainRIFF, MMIO_FINDCHUNK))
374 goto errCleanUp;
376 TRACE("Chunk Found ckid=%.4s fccType=%08x cksize=%08X\n",
377 (LPSTR)&mmckInfo.ckid, mmckInfo.fccType, mmckInfo.cksize);
379 lpWaveFormat = HeapAlloc(GetProcessHeap(), 0, mmckInfo.cksize);
380 if (mmioRead(hmmio, (HPSTR)lpWaveFormat, mmckInfo.cksize) < sizeof(PCMWAVEFORMAT))
381 goto errCleanUp;
383 TRACE("wFormatTag=%04X !\n", lpWaveFormat->wFormatTag);
384 TRACE("nChannels=%d\n", lpWaveFormat->nChannels);
385 TRACE("nSamplesPerSec=%d\n", lpWaveFormat->nSamplesPerSec);
386 TRACE("nAvgBytesPerSec=%d\n", lpWaveFormat->nAvgBytesPerSec);
387 TRACE("nBlockAlign=%d\n", lpWaveFormat->nBlockAlign);
388 TRACE("wBitsPerSample=%u !\n", lpWaveFormat->wBitsPerSample);
390 /* move to end of 'fmt ' chunk */
391 mmioAscend(hmmio, &mmckInfo, 0);
393 mmckInfo.ckid = mmioFOURCC('d', 'a', 't', 'a');
394 if (mmioDescend(hmmio, &mmckInfo, &ckMainRIFF, MMIO_FINDCHUNK))
395 goto errCleanUp;
397 TRACE("Chunk Found ckid=%.4s fccType=%08x cksize=%08X\n",
398 (LPSTR)&mmckInfo.ckid, mmckInfo.fccType, mmckInfo.cksize);
400 s.hEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
402 if (waveOutOpen(&hWave, WAVE_MAPPER, lpWaveFormat, (DWORD_PTR)PlaySound_Callback,
403 (DWORD_PTR)&s, CALLBACK_FUNCTION) != MMSYSERR_NOERROR)
404 goto errCleanUp;
406 /* make it so that 3 buffers per second are needed */
407 bufsize = (((lpWaveFormat->nAvgBytesPerSec / 3) - 1) / lpWaveFormat->nBlockAlign + 1) *
408 lpWaveFormat->nBlockAlign;
409 waveHdr = HeapAlloc(GetProcessHeap(), 0, 2 * sizeof(WAVEHDR) + 2 * bufsize);
410 waveHdr[0].lpData = (char*)waveHdr + 2 * sizeof(WAVEHDR);
411 waveHdr[1].lpData = (char*)waveHdr + 2 * sizeof(WAVEHDR) + bufsize;
412 waveHdr[0].dwUser = waveHdr[1].dwUser = 0L;
413 waveHdr[0].dwLoops = waveHdr[1].dwLoops = 0L;
414 waveHdr[0].dwFlags = waveHdr[1].dwFlags = 0L;
415 waveHdr[0].dwBufferLength = waveHdr[1].dwBufferLength = bufsize;
416 if (waveOutPrepareHeader(hWave, &waveHdr[0], sizeof(WAVEHDR)) ||
417 waveOutPrepareHeader(hWave, &waveHdr[1], sizeof(WAVEHDR))) {
418 goto errCleanUp;
421 s.dwEventCount = 1L; /* for first buffer */
422 index = 0;
424 do {
425 left = mmckInfo.cksize;
427 mmioSeek(hmmio, mmckInfo.dwDataOffset, SEEK_SET);
428 while (left)
430 if (bPlaySoundStop)
432 waveOutReset(hWave);
433 wps->bLoop = FALSE;
434 break;
436 count = mmioRead(hmmio, waveHdr[index].lpData, min(bufsize, left));
437 if (count < 1) break;
438 left -= count;
439 waveHdr[index].dwBufferLength = count;
440 if (waveOutWrite(hWave, &waveHdr[index], sizeof(WAVEHDR)) == MMSYSERR_NOERROR) {
441 index ^= 1;
442 PlaySound_WaitDone(&s);
444 else {
445 ERR("Aborting play loop, waveOutWrite error\n");
446 wps->bLoop = FALSE;
447 break;
450 bRet = TRUE;
451 } while (wps->bLoop);
453 PlaySound_WaitDone(&s); /* to balance first buffer */
454 waveOutReset(hWave);
456 waveOutUnprepareHeader(hWave, &waveHdr[0], sizeof(WAVEHDR));
457 waveOutUnprepareHeader(hWave, &waveHdr[1], sizeof(WAVEHDR));
459 errCleanUp:
460 TRACE("Done playing=%s => %s!\n", debugstr_w(wps->pszSound), bRet ? "ok" : "ko");
461 CloseHandle(s.hEvent);
462 HeapFree(GetProcessHeap(), 0, waveHdr);
463 HeapFree(GetProcessHeap(), 0, lpWaveFormat);
464 if (hWave) while (waveOutClose(hWave) == WAVERR_STILLPLAYING) Sleep(100);
465 if (hmmio) mmioClose(hmmio, 0);
467 PlaySound_Free(wps);
469 return bRet;
472 static BOOL MULTIMEDIA_PlaySound(const void* pszSound, HMODULE hmod, DWORD fdwSound, BOOL bUnicode)
474 WINE_PLAYSOUND* wps = NULL;
476 TRACE("pszSound='%p' hmod=%p fdwSound=%08X\n",
477 pszSound, hmod, fdwSound);
479 /* SND_NOWAIT is ignored in w95/2k/xp. */
480 if ((fdwSound & SND_NOSTOP) && PlaySoundList != NULL)
481 return FALSE;
483 /* alloc internal structure, if we need to play something */
484 if (pszSound && !(fdwSound & SND_PURGE))
486 if (!(wps = PlaySound_Alloc(pszSound, hmod, fdwSound, bUnicode)))
487 return FALSE;
490 EnterCriticalSection(&WINMM_cs);
491 /* since several threads can enter PlaySound in parallel, we're not
492 * sure, at this point, that another thread didn't start a new playsound
494 while (PlaySoundList != NULL)
496 ResetEvent(psLastEvent);
497 /* FIXME: doc says we have to stop all instances of pszSound if it's non
498 * NULL... as of today, we stop all playing instances */
499 bPlaySoundStop = TRUE;
501 LeaveCriticalSection(&WINMM_cs);
502 WaitForSingleObject(psLastEvent, INFINITE);
503 EnterCriticalSection(&WINMM_cs);
505 bPlaySoundStop = FALSE;
508 if (wps) wps->lpNext = PlaySoundList;
509 PlaySoundList = wps;
510 LeaveCriticalSection(&WINMM_cs);
512 if (!pszSound || (fdwSound & SND_PURGE)) return TRUE;
514 if (fdwSound & SND_ASYNC)
516 DWORD id;
517 HANDLE handle;
518 wps->bLoop = (fdwSound & SND_LOOP) ? TRUE : FALSE;
519 if ((handle = CreateThread(NULL, 0, proc_PlaySound, wps, 0, &id)) != 0) {
520 wps->hThread = handle;
521 SetThreadPriority(handle, THREAD_PRIORITY_TIME_CRITICAL);
522 return TRUE;
525 else return proc_PlaySound(wps);
527 /* error cases */
528 PlaySound_Free(wps);
529 return FALSE;
532 /**************************************************************************
533 * PlaySoundA [WINMM.@]
535 BOOL WINAPI PlaySoundA(LPCSTR pszSoundA, HMODULE hmod, DWORD fdwSound)
537 return MULTIMEDIA_PlaySound(pszSoundA, hmod, fdwSound, FALSE);
540 /**************************************************************************
541 * PlaySoundW [WINMM.@]
543 BOOL WINAPI PlaySoundW(LPCWSTR pszSoundW, HMODULE hmod, DWORD fdwSound)
545 return MULTIMEDIA_PlaySound(pszSoundW, hmod, fdwSound, TRUE);
548 /**************************************************************************
549 * sndPlaySoundA [WINMM.@]
551 BOOL WINAPI sndPlaySoundA(LPCSTR pszSoundA, UINT uFlags)
553 uFlags &= SND_ASYNC|SND_LOOP|SND_MEMORY|SND_NODEFAULT|SND_NOSTOP|SND_SYNC;
554 return MULTIMEDIA_PlaySound(pszSoundA, 0, uFlags, FALSE);
557 /**************************************************************************
558 * sndPlaySoundW [WINMM.@]
560 BOOL WINAPI sndPlaySoundW(LPCWSTR pszSound, UINT uFlags)
562 uFlags &= SND_ASYNC|SND_LOOP|SND_MEMORY|SND_NODEFAULT|SND_NOSTOP|SND_SYNC;
563 return MULTIMEDIA_PlaySound(pszSound, 0, uFlags, TRUE);
566 /**************************************************************************
567 * mmsystemGetVersion [WINMM.@]
569 UINT WINAPI mmsystemGetVersion(void)
571 TRACE("3.10 (Win95?)\n");
572 return 0x030a;