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