summaryrefslogtreecommitdiffstats
path: root/widget/windows/nsSound.cpp
blob: c1871747053aecabcb82804e5b3a2178e617437a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "nscore.h"
#include "plstr.h"
#include <stdio.h>
#include "nsString.h"
#include <windows.h>

// mmsystem.h is needed to build with WIN32_LEAN_AND_MEAN
#include <mmsystem.h>

#include "HeadlessSound.h"
#include "nsSound.h"
#include "nsIURL.h"
#include "nsNetUtil.h"
#include "nsIChannel.h"
#include "nsContentUtils.h"
#include "nsCRT.h"
#include "nsIObserverService.h"

#include "mozilla/Logging.h"
#include "prtime.h"

#include "nsNativeCharsetUtils.h"
#include "nsThreadUtils.h"
#include "mozilla/ClearOnShutdown.h"
#include "gfxPlatform.h"

using mozilla::LogLevel;

static mozilla::LazyLogModule gWin32SoundLog("nsSound");

// Hackaround for bug 1644240
// When we call PlaySound for the first time in the process, winmm.dll creates
// a new thread and starts a message loop in winmm!mciwindow.  After that,
// every call of PlaySound communicates with that thread via Window messages.
// It seems that Warsaw application hooks USER32!GetMessageA, and there is
// a timing window where they free their trampoline region without reverting
// the hook on USER32!GetMessageA, resulting in crash when winmm!mciwindow
// receives a message because it tries to jump to a freed buffer.
// Based on the crash reports, it happened on all versions of Windows x64, and
// the possible condition was wslbdhm64.dll was loaded but wslbscrwh64.dll was
// unloaded.  Therefore we suppress playing a sound under such a condition.
static bool ShouldSuppressPlaySound() {
#if defined(_M_AMD64)
  if (::GetModuleHandle(L"wslbdhm64.dll") &&
      !::GetModuleHandle(L"wslbscrwh64.dll")) {
    return true;
  }
#endif  // defined(_M_AMD64)
  return false;
}

class nsSoundPlayer : public mozilla::Runnable {
 public:
  explicit nsSoundPlayer(const nsAString& aSoundName)
      : mozilla::Runnable("nsSoundPlayer"),
        mSoundName(aSoundName),
        mSoundData(nullptr) {}

  nsSoundPlayer(const uint8_t* aData, size_t aSize)
      : mozilla::Runnable("nsSoundPlayer"), mSoundName(u""_ns) {
    MOZ_ASSERT(aSize > 0, "Size should not be zero");
    MOZ_ASSERT(aData, "Data shoud not be null");

    // We will disptach nsSoundPlayer to playerthread, so keep a data copy
    mSoundData = new uint8_t[aSize];
    memcpy(mSoundData, aData, aSize);
  }

  NS_DECL_NSIRUNNABLE

 protected:
  ~nsSoundPlayer();

  nsString mSoundName;
  uint8_t* mSoundData;
};

NS_IMETHODIMP
nsSoundPlayer::Run() {
  if (ShouldSuppressPlaySound()) {
    return NS_OK;
  }

  MOZ_ASSERT(!mSoundName.IsEmpty() || mSoundData,
             "Sound name or sound data should be specified");
  DWORD flags = SND_NODEFAULT | SND_ASYNC;

  if (mSoundData) {
    flags |= SND_MEMORY;
    ::PlaySoundW(reinterpret_cast<LPCWSTR>(mSoundData), nullptr, flags);
  } else {
    flags |= SND_ALIAS;
    ::PlaySoundW(mSoundName.get(), nullptr, flags);
  }
  return NS_OK;
}

nsSoundPlayer::~nsSoundPlayer() { delete[] mSoundData; }

mozilla::StaticRefPtr<nsISound> nsSound::sInstance;

/* static */
already_AddRefed<nsISound> nsSound::GetInstance() {
  if (!sInstance) {
    if (gfxPlatform::IsHeadless()) {
      sInstance = new mozilla::widget::HeadlessSound();
    } else {
      RefPtr<nsSound> sound = new nsSound();
      nsresult rv = sound->CreatePlayerThread();
      if (NS_WARN_IF(NS_FAILED(rv))) {
        return nullptr;
      }
      sInstance = sound.forget();
    }
    ClearOnShutdown(&sInstance);
  }

  RefPtr<nsISound> service = sInstance;
  return service.forget();
}

#ifndef SND_PURGE
// Not available on Windows CE, and according to MSDN
// doesn't do anything on recent windows either.
#  define SND_PURGE 0
#endif

NS_IMPL_ISUPPORTS(nsSound, nsISound, nsIStreamLoaderObserver, nsIObserver)

nsSound::nsSound() : mInited(false) {}

nsSound::~nsSound() {}

void nsSound::PurgeLastSound() {
  // Halt any currently playing sound.
  if (mSoundPlayer) {
    if (mPlayerThread) {
      mPlayerThread->Dispatch(
          NS_NewRunnableFunction("nsSound::PurgeLastSound",
                                 [player = std::move(mSoundPlayer)]() {
                                   // Capture move mSoundPlayer to lambda then
                                   // PlaySoundW(nullptr, nullptr, SND_PURGE)
                                   // will be called before freeing the
                                   // nsSoundPlayer.
                                   if (ShouldSuppressPlaySound()) {
                                     return;
                                   }
                                   ::PlaySoundW(nullptr, nullptr, SND_PURGE);
                                 }),
          NS_DISPATCH_NORMAL);
    }
  }
}

NS_IMETHODIMP nsSound::Beep() {
  ::MessageBeep(0);

  return NS_OK;
}

NS_IMETHODIMP nsSound::OnStreamComplete(nsIStreamLoader* aLoader,
                                        nsISupports* context, nsresult aStatus,
                                        uint32_t dataLen, const uint8_t* data) {
  MOZ_ASSERT(mPlayerThread, "player thread should not be null ");
  // print a load error on bad status
  if (NS_FAILED(aStatus)) {
#ifdef DEBUG
    if (aLoader) {
      nsCOMPtr<nsIRequest> request;
      nsCOMPtr<nsIChannel> channel;
      aLoader->GetRequest(getter_AddRefs(request));
      if (request) channel = do_QueryInterface(request);
      if (channel) {
        nsCOMPtr<nsIURI> uri;
        channel->GetURI(getter_AddRefs(uri));
        if (uri) {
          nsAutoCString uriSpec;
          uri->GetSpec(uriSpec);
          MOZ_LOG(gWin32SoundLog, LogLevel::Info,
                  ("Failed to load %s\n", uriSpec.get()));
        }
      }
    }
#endif
    return aStatus;
  }

  PurgeLastSound();

  if (data && dataLen > 0) {
    MOZ_ASSERT(!mSoundPlayer, "mSoundPlayer should be null");
    mSoundPlayer = new nsSoundPlayer(data, dataLen);
    MOZ_ASSERT(mSoundPlayer, "Could not create player");

    nsresult rv = mPlayerThread->Dispatch(mSoundPlayer, NS_DISPATCH_NORMAL);
    if (NS_WARN_IF(FAILED(rv))) {
      return rv;
    }
  }

  return NS_OK;
}

NS_IMETHODIMP nsSound::Play(nsIURL* aURL) {
  nsresult rv;

#ifdef DEBUG_SOUND
  char* url;
  aURL->GetSpec(&url);
  MOZ_LOG(gWin32SoundLog, LogLevel::Info, ("%s\n", url));
#endif

  nsCOMPtr<nsIStreamLoader> loader;
  rv = NS_NewStreamLoader(
      getter_AddRefs(loader), aURL,
      this,  // aObserver
      nsContentUtils::GetSystemPrincipal(),
      nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL,
      nsIContentPolicy::TYPE_OTHER);
  return rv;
}

nsresult nsSound::CreatePlayerThread() {
  if (mPlayerThread) {
    return NS_OK;
  }
  if (NS_WARN_IF(NS_FAILED(NS_NewNamedThread("PlayEventSound",
                                             getter_AddRefs(mPlayerThread))))) {
    return NS_ERROR_FAILURE;
  }

  // Add an observer for shutdown event to release the thread at that time
  nsCOMPtr<nsIObserverService> observerService =
      mozilla::services::GetObserverService();
  if (!observerService) {
    return NS_ERROR_FAILURE;
  }

  observerService->AddObserver(this, "xpcom-shutdown-threads", false);
  return NS_OK;
}

NS_IMETHODIMP
nsSound::Observe(nsISupports* aSubject, const char* aTopic,
                 const char16_t* aData) {
  if (!strcmp(aTopic, "xpcom-shutdown-threads")) {
    PurgeLastSound();

    if (mPlayerThread) {
      mPlayerThread->Shutdown();
      mPlayerThread = nullptr;
    }
  }

  return NS_OK;
}

NS_IMETHODIMP nsSound::Init() {
  if (mInited) {
    return NS_OK;
  }

  MOZ_ASSERT(mPlayerThread, "player thread should not be null ");
  // This call halts a sound if it was still playing.
  // We have to use the sound library for something to make sure
  // it is initialized.
  // If we wait until the first sound is played, there will
  // be a time lag as the library gets loaded.
  // This should be done in player thread otherwise it will block main thread
  // at the first time loading sound library.
  mPlayerThread->Dispatch(
      NS_NewRunnableFunction("nsSound::Init",
                             []() {
                               if (ShouldSuppressPlaySound()) {
                                 return;
                               }
                               ::PlaySoundW(nullptr, nullptr, SND_PURGE);
                             }),
      NS_DISPATCH_NORMAL);

  mInited = true;

  return NS_OK;
}

NS_IMETHODIMP nsSound::PlayEventSound(uint32_t aEventId) {
  MOZ_ASSERT(mPlayerThread, "player thread should not be null ");
  PurgeLastSound();

  const wchar_t* sound = nullptr;
  switch (aEventId) {
    case EVENT_NEW_MAIL_RECEIVED:
      sound = L"MailBeep";
      break;
    case EVENT_ALERT_DIALOG_OPEN:
      sound = L"SystemExclamation";
      break;
    case EVENT_CONFIRM_DIALOG_OPEN:
      sound = L"SystemQuestion";
      break;
    case EVENT_MENU_EXECUTE:
      sound = L"MenuCommand";
      break;
    case EVENT_MENU_POPUP:
      sound = L"MenuPopup";
      break;
    case EVENT_EDITOR_MAX_LEN:
      sound = L".Default";
      break;
    default:
      // Win32 plays no sounds at NS_SYSSOUND_PROMPT_DIALOG and
      // NS_SYSSOUND_SELECT_DIALOG.
      return NS_OK;
  }
  NS_ASSERTION(sound, "sound is null");
  MOZ_ASSERT(!mSoundPlayer, "mSoundPlayer should be null");
  mSoundPlayer = new nsSoundPlayer(nsDependentString(sound));
  MOZ_ASSERT(mSoundPlayer, "Could not create player");
  nsresult rv = mPlayerThread->Dispatch(mSoundPlayer, NS_DISPATCH_NORMAL);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }
  return NS_OK;
}