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