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