Files
palemoon27/dom/media/webaudio/AudioDestinationNode.cpp
T
roytam1 1781dca466 import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1211204 - Remove possible false-negative with D3D9 texture memory reporting. r=mattwoodrow (74adbcad19)
- Bug 1200595 - D3D9 TextureData implementation. r=Bas (2624bd59a3)
- Bug 1200595 - MacIOSurface TextureData implementation. r=mattwoodrow (98130b5d6b)
- Bug 1200595 - EGLImage TextureData implementation. r=mattwoodrow (8b732af2da)
- Bug 1200595 - AndroidSurface TextureData implementation. r=mattwoodrow (79443ff5d7)
- Bug 1200595 - SharedSurface TextureData implementation. r=jgilbert (aadc8c5601)
- Bug 1200595 - DIB TextureData implementation. r=Bas (d7bae178ad)
- Bug 1200595 - Merge TextureClient and ClientTexture back into TextureClient. r=mattwoodrow (890d76ff9b)
- Bug 1200595 - Consolidate the TextureClient's destruction logic. r=mattwoodrow (fa9ac2e414)
- Allow asynchronous D3D11 TextureClients on the main thread. (bug 1217665 part 5, r=nical) (cb77fa88cc)
- Implement the direct bitmap drawing model for plugins. (bug 1217665 part 6, r=mattwoodrow) (82f9015e5a)
- Implement the direct DXGI drawing model for plugins. (bug 1217665 part 7, r=mattwoodrow) (cdeeb52a91)
- Implement the DidComposite NPAPI callback. (bug 1217665 part 8, r=mattwoodrow) (4eb2a790ae)
- Add an NPN_GetValue query to find the browser's DXGI adapter. (bug 1217665 part 10, r=aklotz,mattwoodrow) (84af4e525a)
- Create a D3D11 content device even if D2D is blocked. (bug 1217665 part 11, r=jrmuizel) (142441808e)
- Bug 1229665 - Convert widget clip regions to LayoutDevicePixels. r=botond. (edf746b278)
- Bug 1204715 - Move browser/app/profile/extensions/{972ce4c6-7e08-4474-a285-3208198ce6fd} to moz.build. r=mshal (8c6b4709bc)
- Bug 1212773 - Pass a base directory to jar maker, instead of a chrome directory. r=gps (1f644706c6)
- Bustage fix for bug 1210687 on a CLOSED TREE. r=me (4cd7000101)
- Bug 1212773 - Extend jar maker syntax for jar file location. r=gps (8119aa2b98)
- Bug 1164039 - moved TelemetryTimestamps.jsm and tests to toolkit/componets/telemetry/. r=dexter (942145656e)
- Bug 1184705 - Search A/B testing cohort identifier should be recorded in FHR, r=rnewman. (b5cf397cf0)
- Bug 1230047 (part 2) - Make several PaintWindow() functions use LayoutDevice coordinates. r=kats. (246e1321ca)
- Bug 1218454 - part 1 - move DialogValueHolder::Get out-of-line; r=bz (2d65438b37)
- Bug 1218454 - part 2 - don't #include nsContentUtils.h from CallbackObject.h; r=bz (59e3b60749)
- Bug 1205945 part.1 Remove unnecessary member of IMEInputHandler, mLastDispatchedCompositionString r=smichaud (2223df8aec)
- Bug 1205945 part.2 Add DispatchCompositionStartEvent() and move the code of OnStartIMEComposition() into it r=smichaud (25449c2bca)
- Bug 1205945 part.3 Move the code of OnUpdateIMEComposition() into DispatchCompositionChangeEvent() r=smichaud (e85a65f2f7)
- Bug 1205945 part.4 Move the code of OnEndIMEComposition() into DispatchCompositionCommitEvent() r=smichaud (21e6218c06)
- Bug 1205945 part.5 Emulate mSelectedRange at dispatching compositionchange or compositioncommit event until OnSelectionChange() is called r=smichaud (f82baaea8e)
- Bug 1205945 part.6 IMEInputHandler::GetAttributedSubstringFromRange() should return stored composition string if the range is in the composition string r=smichaud (53eabe028b)
- Bug 1205399 - Follow-up to fix build bustage for platforms without OS X 10.10 and -Wswitch enabled. r=mstange (c2e8eda9b5)
- Bug 1220337 - Don't show alternate notification actions on OS X 10.8. r=MattN (5ef8449dcc)
- Bug 1224738 - Fix alternate action index getter name on OS X. r=MattN (a6f83ce706)
- Bug 1225908 - AsmSimdTypeToLaneType. r=bbouvier (f850c10bff)
- Bug 1224389 - Odin: refactor types/signatures/values (r=bbouvier) (31bc615781)
- Bug 1224389 - Odin: simplify AsmJSModule global data allocation (r=bbouvier) (3ba518183a)
- Bug 1222684 - IonMonkey: MIPS: Implement callWithPatch and patchCall. r=luke (0ede7a61c3)
- Bug 1224814 - "TraceLogger: Remove redundant checks in BaselineJIT". r=hv1989 (b3865fbdf0)
- Bug 1228369: Rename CodeOffsetLabel into CodeOffset; r=luke (1d0aba3710)
- Bug 1224389 - Odin: refactor stubs, func-ptrs, and masm use (r=bbouvier) (2834725644)
- Bug 1228340: Get rid of the js_ prefix for CodeSpec, CodeName, NumCodeSpecs; r=jorendorff (8ff2b3bcd5)
- Bug 1176214 - Part 2: Preliminary adjustments. r=waldo (f9e2adca8a)
- Bug 1176214 - Part 3: VM core changes. r=waldo (cf5b24fe18)
- Bug 1176214 - Part 4: VM built-in lib changes. r=waldo (603335d2aa)
- Bug 1176214 - Part 5: Ion changes. r=h4writer (b589713e1c)
- Bug 1176214 - Part 6: Odin changes. r=luke (f1dcb025d2)
- Bug 1176214 - Part 7: Ctypes, shell, xpconnect, etc. r=waldo (bdc78e0558)
- Bug 1199578 - test case. r=waldo (6a94fd455a)
- Bug 1211409 - load/store exclusive for ARM-32. r=jolesen (38efc4882e)
- Bug 1205390 - guard against asm.js compilation not being available. r=me (aeefe98cfd)
- Make test runnable on non-Nightly (no bug) r=me (27930210ed)
- Bug 1176214 - Part 8: jit-test changes. r=bbouvier (31c4f42eea)
- Bug 1176214 - Part 9: tests changes. r=bbouvier (a245687f43)
- Bug 1176214 - Part 10: jsapi-tests changes. r=bbouvier (610e0002a2)
- bug 1198656 remove unnecessary reinterpret_casts r=padenot (bc5a67d521)
- bug 1198656 refactor acquiring the content into an object method r=padenot (b7b062fbf1)
- bug 1198656 clear references in mJSChannels on successful content acquire r=padenot (65e5ee1856)
- bug 1198656 delay AudioBuffer allocation until required r=padenot (57d0fd0d01)
- bug 1199559 remove now unused SetRawChannelContents r=padenot (40685ef783)
- Bug 1203616 - Properly scale the input buffer of a WaveShaperNode before processing it with the curve. r=karlt (12e9592a9e)
- Bug 1186343: Throw an InvalidStateError when we set the curve attribute of a WaveShaperNode with a Float32Array of length less than 2; r=padenot,smaug (df83b21fd0)
- bug 1188244 throw in SetCurve() on OOM r=padenot (17967b7b58)
- Bug 1176214 - Part 11: Changes to DOM, except for WebGL. r=bz, r=clb (c40e5c2a68)
- Bug 1176214 - Part 12: Changes to WebGL. r=bz, r=clb (228c90da3c)
- Bug 1176214 - Part 13: Changes to ipc. r=mrbkap (4b11d4e509)
- Bug 1176214 - Part 14: Changes to netwerk. r=jduell (91568c8444)
- Bug 1176214 - Part 15: Changes to xpcom. r=nfroyd (df8d080070)
- Revert "Bug 1176214 - Part 14: Changes to netwerk. r=jduell" (d0aedbac94)
- improved backport of PM because of newer JS_GetArrayBufferData (9d8188ff5e)
- bug 1199559 write decodeAudioData buffer in a format suitable for direct use by AudioBuffer r=padenot (da00bab1a1)
- bug 1225003 null-check mBuffer in SizeOfExcludingThis() r=padenot (c01d389f10)
- Bug 1225365 - Fix assertion in the nsScriptNameSpaceManager memory reporter. r=bz. (a5605a8923)
- Bug 1229458 - Remove SizeOfIncludingThisMustBeUnshared() from string classes. r=mccr8. (26abcea276)
- Bug 1214506. Ensure OggReader sets proper IDs for its tracks. r=jya (a270b02301)
- bits of Bug 1188812 - Obtain CDM can render capability and store into MediaInfo (321388180e)
- Bug 1226450 - Report audio/video codecs used in HTMLMediaElement and WebAudio via telemetry. r=jya (e722b409b7)
2023-04-11 11:15:29 +08:00

748 lines
21 KiB
C++

/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim:set ts=2 sw=2 sts=2 et cindent: */
/* 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 "AudioDestinationNode.h"
#include "AudioContext.h"
#include "mozilla/dom/AudioDestinationNodeBinding.h"
#include "mozilla/dom/ScriptSettings.h"
#include "mozilla/Preferences.h"
#include "mozilla/Services.h"
#include "AudioChannelAgent.h"
#include "AudioChannelService.h"
#include "AudioNodeEngine.h"
#include "AudioNodeStream.h"
#include "MediaStreamGraph.h"
#include "OfflineAudioCompletionEvent.h"
#include "nsContentUtils.h"
#include "nsIInterfaceRequestorUtils.h"
#include "nsIDocShell.h"
#include "nsIPermissionManager.h"
#include "nsIScriptObjectPrincipal.h"
#include "nsServiceManagerUtils.h"
#include "mozilla/dom/Promise.h"
namespace mozilla {
namespace dom {
static uint8_t gWebAudioOutputKey;
class OfflineDestinationNodeEngine final : public AudioNodeEngine
{
public:
OfflineDestinationNodeEngine(AudioDestinationNode* aNode,
uint32_t aNumberOfChannels,
uint32_t aLength,
float aSampleRate)
: AudioNodeEngine(aNode)
, mWriteIndex(0)
, mNumberOfChannels(aNumberOfChannels)
, mLength(aLength)
, mSampleRate(aSampleRate)
, mBufferAllocated(false)
{
}
virtual void ProcessBlock(AudioNodeStream* aStream,
GraphTime aFrom,
const AudioBlock& aInput,
AudioBlock* aOutput,
bool* aFinished) override
{
// Do this just for the sake of political correctness; this output
// will not go anywhere.
*aOutput = aInput;
// The output buffer is allocated lazily, on the rendering thread.
if (!mBufferAllocated) {
// These allocations might fail if content provides a huge number of
// channels or size, but it's OK since we'll deal with the failure
// gracefully.
mBuffer = ThreadSharedFloatArrayBufferList::
Create(mNumberOfChannels, mLength, fallible);
mBufferAllocated = true;
}
// Handle the case of allocation failure in the input buffer
uint32_t outputChannelCount = mBuffer ? mNumberOfChannels : 0;
// Record our input buffer
MOZ_ASSERT(mWriteIndex < mLength, "How did this happen?");
const uint32_t duration = std::min(WEBAUDIO_BLOCK_SIZE, mLength - mWriteIndex);
const uint32_t inputChannelCount = aInput.ChannelCount();
for (uint32_t i = 0; i < outputChannelCount; ++i) {
float* outputData = mBuffer->GetDataForWrite(i) + mWriteIndex;
if (aInput.IsNull() || i >= inputChannelCount) {
PodZero(outputData, duration);
} else {
const float* inputBuffer = static_cast<const float*>(aInput.mChannelData[i]);
if (duration == WEBAUDIO_BLOCK_SIZE) {
// Use the optimized version of the copy with scale operation
AudioBlockCopyChannelWithScale(inputBuffer, aInput.mVolume,
outputData);
} else {
if (aInput.mVolume == 1.0f) {
PodCopy(outputData, inputBuffer, duration);
} else {
for (uint32_t j = 0; j < duration; ++j) {
outputData[j] = aInput.mVolume * inputBuffer[j];
}
}
}
}
}
mWriteIndex += duration;
if (mWriteIndex >= mLength) {
NS_ASSERTION(mWriteIndex == mLength, "Overshot length");
// Go to finished state. When the graph's current time eventually reaches
// the end of the stream, then the main thread will be notified and we'll
// shut down the AudioContext.
*aFinished = true;
}
}
virtual bool IsActive() const override
{
// Keep processing to track stream time, which is used for all timelines
// associated with the same AudioContext.
return true;
}
class OnCompleteTask final : public nsRunnable
{
public:
OnCompleteTask(AudioContext* aAudioContext, AudioBuffer* aRenderedBuffer)
: mAudioContext(aAudioContext)
, mRenderedBuffer(aRenderedBuffer)
{}
NS_IMETHOD Run() override
{
RefPtr<OfflineAudioCompletionEvent> event =
new OfflineAudioCompletionEvent(mAudioContext, nullptr, nullptr);
event->InitEvent(mRenderedBuffer);
mAudioContext->DispatchTrustedEvent(event);
return NS_OK;
}
private:
RefPtr<AudioContext> mAudioContext;
RefPtr<AudioBuffer> mRenderedBuffer;
};
void FireOfflineCompletionEvent(AudioDestinationNode* aNode)
{
AudioContext* context = aNode->Context();
context->Shutdown();
// Shutdown drops self reference, but the context is still referenced by aNode,
// which is strongly referenced by the runnable that called
// AudioDestinationNode::FireOfflineCompletionEvent.
AutoJSAPI jsapi;
if (NS_WARN_IF(!jsapi.Init(aNode->GetOwner()))) {
return;
}
JSContext* cx = jsapi.cx();
// Create the input buffer
ErrorResult rv;
RefPtr<AudioBuffer> renderedBuffer =
AudioBuffer::Create(context, mNumberOfChannels, mLength, mSampleRate,
mBuffer.forget(), cx, rv);
if (rv.Failed()) {
return;
}
aNode->ResolvePromise(renderedBuffer);
RefPtr<OnCompleteTask> onCompleteTask =
new OnCompleteTask(context, renderedBuffer);
NS_DispatchToMainThread(onCompleteTask);
context->OnStateChanged(nullptr, AudioContextState::Closed);
}
virtual size_t SizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const override
{
size_t amount = AudioNodeEngine::SizeOfExcludingThis(aMallocSizeOf);
if (mBuffer) {
amount += mBuffer->SizeOfIncludingThis(aMallocSizeOf);
}
return amount;
}
virtual size_t SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const override
{
return aMallocSizeOf(this) + SizeOfExcludingThis(aMallocSizeOf);
}
private:
// The input to the destination node is recorded in mBuffer.
// When this buffer fills up with mLength frames, the buffered input is sent
// to the main thread in order to dispatch OfflineAudioCompletionEvent.
RefPtr<ThreadSharedFloatArrayBufferList> mBuffer;
// An index representing the next offset in mBuffer to be written to.
uint32_t mWriteIndex;
uint32_t mNumberOfChannels;
// How many frames the OfflineAudioContext intends to produce.
uint32_t mLength;
float mSampleRate;
bool mBufferAllocated;
};
class InputMutedRunnable final : public nsRunnable
{
public:
InputMutedRunnable(AudioNodeStream* aStream,
bool aInputMuted)
: mStream(aStream)
, mInputMuted(aInputMuted)
{
}
NS_IMETHOD Run() override
{
MOZ_ASSERT(NS_IsMainThread());
RefPtr<AudioNode> node = mStream->Engine()->NodeMainThread();
if (node) {
RefPtr<AudioDestinationNode> destinationNode =
static_cast<AudioDestinationNode*>(node.get());
destinationNode->InputMuted(mInputMuted);
}
return NS_OK;
}
private:
RefPtr<AudioNodeStream> mStream;
bool mInputMuted;
};
class DestinationNodeEngine final : public AudioNodeEngine
{
public:
explicit DestinationNodeEngine(AudioDestinationNode* aNode)
: AudioNodeEngine(aNode)
, mVolume(1.0f)
, mLastInputMuted(true)
, mSuspended(false)
{
MOZ_ASSERT(aNode);
}
virtual void ProcessBlock(AudioNodeStream* aStream,
GraphTime aFrom,
const AudioBlock& aInput,
AudioBlock* aOutput,
bool* aFinished) override
{
*aOutput = aInput;
aOutput->mVolume *= mVolume;
if (mSuspended) {
return;
}
bool newInputMuted = aInput.IsNull() || aInput.IsMuted();
if (newInputMuted != mLastInputMuted) {
mLastInputMuted = newInputMuted;
RefPtr<InputMutedRunnable> runnable =
new InputMutedRunnable(aStream, newInputMuted);
aStream->Graph()->
DispatchToMainThreadAfterStreamStateUpdate(runnable.forget());
}
}
virtual bool IsActive() const override
{
// Keep processing to track stream time, which is used for all timelines
// associated with the same AudioContext. If there are no other engines
// for the AudioContext, then this could return false to suspend the
// stream, but the stream is blocked anyway through
// AudioDestinationNode::SetIsOnlyNodeForContext().
return true;
}
virtual void SetDoubleParameter(uint32_t aIndex, double aParam) override
{
if (aIndex == VOLUME) {
mVolume = aParam;
}
}
virtual void SetInt32Parameter(uint32_t aIndex, int32_t aParam) override
{
if (aIndex == SUSPENDED) {
mSuspended = !!aParam;
if (mSuspended) {
mLastInputMuted = true;
}
}
}
enum Parameters {
VOLUME,
SUSPENDED,
};
virtual size_t SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const override
{
return aMallocSizeOf(this) + SizeOfExcludingThis(aMallocSizeOf);
}
private:
float mVolume;
bool mLastInputMuted;
bool mSuspended;
};
static bool UseAudioChannelAPI()
{
return Preferences::GetBool("media.useAudioChannelAPI");
}
NS_IMPL_CYCLE_COLLECTION_INHERITED(AudioDestinationNode, AudioNode,
mAudioChannelAgent,
mOfflineRenderingPromise)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(AudioDestinationNode)
NS_INTERFACE_MAP_ENTRY(nsIAudioChannelAgentCallback)
NS_INTERFACE_MAP_END_INHERITING(AudioNode)
NS_IMPL_ADDREF_INHERITED(AudioDestinationNode, AudioNode)
NS_IMPL_RELEASE_INHERITED(AudioDestinationNode, AudioNode)
AudioDestinationNode::AudioDestinationNode(AudioContext* aContext,
bool aIsOffline,
AudioChannel aChannel,
uint32_t aNumberOfChannels,
uint32_t aLength, float aSampleRate)
: AudioNode(aContext, aIsOffline ? aNumberOfChannels : 2,
ChannelCountMode::Explicit, ChannelInterpretation::Speakers)
, mFramesToProduce(aLength)
, mAudioChannel(AudioChannel::Normal)
, mIsOffline(aIsOffline)
, mAudioChannelAgentPlaying(false)
, mExtraCurrentTimeSinceLastStartedBlocking(0)
, mExtraCurrentTimeUpdatedSinceLastStableState(false)
, mCaptured(false)
{
MediaStreamGraph* graph = aIsOffline ?
MediaStreamGraph::CreateNonRealtimeInstance(aSampleRate) :
MediaStreamGraph::GetInstance(MediaStreamGraph::AUDIO_THREAD_DRIVER, aChannel);
AudioNodeEngine* engine = aIsOffline ?
new OfflineDestinationNodeEngine(this, aNumberOfChannels,
aLength, aSampleRate) :
static_cast<AudioNodeEngine*>(new DestinationNodeEngine(this));
AudioNodeStream::Flags flags =
AudioNodeStream::NEED_MAIN_THREAD_CURRENT_TIME |
AudioNodeStream::NEED_MAIN_THREAD_FINISHED |
AudioNodeStream::EXTERNAL_OUTPUT;
mStream = AudioNodeStream::Create(aContext, engine, flags, graph);
mStream->AddMainThreadListener(this);
mStream->AddAudioOutput(&gWebAudioOutputKey);
if (!aIsOffline) {
graph->NotifyWhenGraphStarted(mStream);
}
if (aChannel != AudioChannel::Normal) {
ErrorResult rv;
SetMozAudioChannelType(aChannel, rv);
}
}
AudioDestinationNode::~AudioDestinationNode()
{
}
size_t
AudioDestinationNode::SizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const
{
size_t amount = AudioNode::SizeOfExcludingThis(aMallocSizeOf);
// Might be useful in the future:
// - mAudioChannelAgent
return amount;
}
size_t
AudioDestinationNode::SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const
{
return aMallocSizeOf(this) + SizeOfExcludingThis(aMallocSizeOf);
}
void
AudioDestinationNode::DestroyAudioChannelAgent()
{
if (mAudioChannelAgent && !Context()->IsOffline()) {
mAudioChannelAgent->NotifyStoppedPlaying();
mAudioChannelAgent = nullptr;
}
}
void
AudioDestinationNode::DestroyMediaStream()
{
DestroyAudioChannelAgent();
if (!mStream)
return;
mStream->RemoveMainThreadListener(this);
MediaStreamGraph* graph = mStream->Graph();
if (graph->IsNonRealtime()) {
MediaStreamGraph::DestroyNonRealtimeInstance(graph);
}
AudioNode::DestroyMediaStream();
}
void
AudioDestinationNode::NotifyMainThreadStreamFinished()
{
MOZ_ASSERT(mStream->IsFinished());
if (mIsOffline) {
nsCOMPtr<nsIRunnable> runnable =
NS_NewRunnableMethod(this, &AudioDestinationNode::FireOfflineCompletionEvent);
NS_DispatchToCurrentThread(runnable);
}
}
void
AudioDestinationNode::FireOfflineCompletionEvent()
{
OfflineDestinationNodeEngine* engine =
static_cast<OfflineDestinationNodeEngine*>(Stream()->Engine());
engine->FireOfflineCompletionEvent(this);
}
void
AudioDestinationNode::ResolvePromise(AudioBuffer* aRenderedBuffer)
{
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(mIsOffline);
mOfflineRenderingPromise->MaybeResolve(aRenderedBuffer);
}
uint32_t
AudioDestinationNode::MaxChannelCount() const
{
return Context()->MaxChannelCount();
}
void
AudioDestinationNode::SetChannelCount(uint32_t aChannelCount, ErrorResult& aRv)
{
if (aChannelCount > MaxChannelCount()) {
aRv.Throw(NS_ERROR_DOM_INDEX_SIZE_ERR);
return;
}
AudioNode::SetChannelCount(aChannelCount, aRv);
}
void
AudioDestinationNode::Mute()
{
MOZ_ASSERT(Context() && !Context()->IsOffline());
SendDoubleParameterToStream(DestinationNodeEngine::VOLUME, 0.0f);
}
void
AudioDestinationNode::Unmute()
{
MOZ_ASSERT(Context() && !Context()->IsOffline());
SendDoubleParameterToStream(DestinationNodeEngine::VOLUME, 1.0f);
}
void
AudioDestinationNode::Suspend()
{
DestroyAudioChannelAgent();
SendInt32ParameterToStream(DestinationNodeEngine::SUSPENDED, 1);
}
void
AudioDestinationNode::Resume()
{
CreateAudioChannelAgent();
SendInt32ParameterToStream(DestinationNodeEngine::SUSPENDED, 0);
}
void
AudioDestinationNode::OfflineShutdown()
{
MOZ_ASSERT(Context() && Context()->IsOffline(),
"Should only be called on a valid OfflineAudioContext");
MediaStreamGraph::DestroyNonRealtimeInstance(mStream->Graph());
mOfflineRenderingRef.Drop(this);
}
JSObject*
AudioDestinationNode::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto)
{
return AudioDestinationNodeBinding::Wrap(aCx, this, aGivenProto);
}
void
AudioDestinationNode::StartRendering(Promise* aPromise)
{
mOfflineRenderingPromise = aPromise;
mOfflineRenderingRef.Take(this);
mStream->Graph()->StartNonRealtimeProcessing(mFramesToProduce);
}
void
AudioDestinationNode::SetCanPlay(float aVolume, bool aMuted)
{
if (!mStream) {
return;
}
mStream->SetTrackEnabled(AudioNodeStream::AUDIO_TRACK, !aMuted);
mStream->SetAudioOutputVolume(&gWebAudioOutputKey, aVolume);
}
NS_IMETHODIMP
AudioDestinationNode::WindowVolumeChanged(float aVolume, bool aMuted)
{
if (aMuted != mAudioChannelAgentPlaying) {
mAudioChannelAgentPlaying = aMuted;
if (UseAudioChannelAPI()) {
Context()->DispatchTrustedEvent(
!aMuted ? NS_LITERAL_STRING("mozinterruptend")
: NS_LITERAL_STRING("mozinterruptbegin"));
}
}
SetCanPlay(aVolume, aMuted);
return NS_OK;
}
NS_IMETHODIMP
AudioDestinationNode::WindowAudioCaptureChanged()
{
MOZ_ASSERT(mAudioChannelAgent);
if (!mStream || Context()->IsOffline()) {
return NS_OK;
}
bool captured = GetOwner()->GetAudioCaptured();
if (captured != mCaptured) {
if (captured) {
nsCOMPtr<nsPIDOMWindow> window = Context()->GetParentObject();
uint64_t id = window->WindowID();
mCaptureStreamPort =
mStream->Graph()->ConnectToCaptureStream(id, mStream);
} else {
mCaptureStreamPort->Destroy();
}
mCaptured = captured;
}
return NS_OK;
}
AudioChannel
AudioDestinationNode::MozAudioChannelType() const
{
return mAudioChannel;
}
void
AudioDestinationNode::SetMozAudioChannelType(AudioChannel aValue, ErrorResult& aRv)
{
if (Context()->IsOffline()) {
aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
return;
}
if (aValue != mAudioChannel &&
CheckAudioChannelPermissions(aValue)) {
mAudioChannel = aValue;
if (mStream) {
mStream->SetAudioChannelType(mAudioChannel);
}
if (mAudioChannelAgent) {
CreateAudioChannelAgent();
}
}
}
bool
AudioDestinationNode::CheckAudioChannelPermissions(AudioChannel aValue)
{
// Only normal channel doesn't need permission.
if (aValue == AudioChannel::Normal) {
return true;
}
// Maybe this audio channel is equal to the default one.
if (aValue == AudioChannelService::GetDefaultAudioChannel()) {
return true;
}
nsCOMPtr<nsIPermissionManager> permissionManager =
services::GetPermissionManager();
if (!permissionManager) {
return false;
}
nsCOMPtr<nsIScriptObjectPrincipal> sop = do_QueryInterface(GetOwner());
NS_ASSERTION(sop, "Window didn't QI to nsIScriptObjectPrincipal!");
nsCOMPtr<nsIPrincipal> principal = sop->GetPrincipal();
uint32_t perm = nsIPermissionManager::UNKNOWN_ACTION;
nsCString channel;
channel.AssignASCII(AudioChannelValues::strings[uint32_t(aValue)].value,
AudioChannelValues::strings[uint32_t(aValue)].length);
permissionManager->TestExactPermissionFromPrincipal(principal,
nsCString(NS_LITERAL_CSTRING("audio-channel-") + channel).get(),
&perm);
return perm == nsIPermissionManager::ALLOW_ACTION;
}
nsresult
AudioDestinationNode::CreateAudioChannelAgent()
{
if (mIsOffline) {
return NS_OK;
}
nsresult rv = NS_OK;
if (mAudioChannelAgent) {
rv = mAudioChannelAgent->NotifyStoppedPlaying();
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
}
mAudioChannelAgent = new AudioChannelAgent();
rv = mAudioChannelAgent->InitWithWeakCallback(GetOwner(),
static_cast<int32_t>(mAudioChannel),
this);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
rv = WindowAudioCaptureChanged();
NS_WARN_IF(NS_FAILED(rv));
return rv;
}
void
AudioDestinationNode::NotifyStableState()
{
mExtraCurrentTimeUpdatedSinceLastStableState = false;
}
void
AudioDestinationNode::ScheduleStableStateNotification()
{
nsCOMPtr<nsIRunnable> event =
NS_NewRunnableMethod(this, &AudioDestinationNode::NotifyStableState);
// Dispatch will fail if this is called on AudioNode destruction during
// shutdown, in which case failure can be ignored.
nsContentUtils::RunInStableState(event.forget());
}
StreamTime
AudioDestinationNode::ExtraCurrentTime()
{
if (!mStartedBlockingDueToBeingOnlyNode.IsNull() &&
!mExtraCurrentTimeUpdatedSinceLastStableState) {
mExtraCurrentTimeUpdatedSinceLastStableState = true;
// Round to nearest processing block.
double seconds =
(TimeStamp::Now() - mStartedBlockingDueToBeingOnlyNode).ToSeconds();
mExtraCurrentTimeSinceLastStartedBlocking = WEBAUDIO_BLOCK_SIZE *
StreamTime(seconds * Context()->SampleRate() / WEBAUDIO_BLOCK_SIZE + 0.5);
ScheduleStableStateNotification();
}
return mExtraCurrentTimeSinceLastStartedBlocking;
}
void
AudioDestinationNode::SetIsOnlyNodeForContext(bool aIsOnlyNode)
{
if (!mStartedBlockingDueToBeingOnlyNode.IsNull() == aIsOnlyNode) {
// Nothing changed.
return;
}
if (!mStream) {
// DestroyMediaStream has been called, presumably during CC Unlink().
return;
}
if (mIsOffline) {
// Don't block the destination stream for offline AudioContexts, since
// we expect the zero data produced when there are no other nodes to
// show up in its result buffer. Also, we would get confused by adding
// ExtraCurrentTime before StartRendering has even been called.
return;
}
if (aIsOnlyNode) {
mStream->Suspend();
mStartedBlockingDueToBeingOnlyNode = TimeStamp::Now();
// Don't do an update of mExtraCurrentTimeSinceLastStartedBlocking until the next stable state.
mExtraCurrentTimeUpdatedSinceLastStableState = true;
ScheduleStableStateNotification();
} else {
// Force update of mExtraCurrentTimeSinceLastStartedBlocking if necessary
ExtraCurrentTime();
mStream->AdvanceAndResume(mExtraCurrentTimeSinceLastStartedBlocking);
mExtraCurrentTimeSinceLastStartedBlocking = 0;
mStartedBlockingDueToBeingOnlyNode = TimeStamp();
}
}
void
AudioDestinationNode::InputMuted(bool aMuted)
{
MOZ_ASSERT(Context() && !Context()->IsOffline());
if (!mAudioChannelAgent) {
if (aMuted) {
return;
}
CreateAudioChannelAgent();
}
if (aMuted) {
mAudioChannelAgent->NotifyStoppedPlaying();
return;
}
float volume = 0.0;
bool muted = true;
nsresult rv = mAudioChannelAgent->NotifyStartedPlaying(nsIAudioChannelAgent::AUDIO_AGENT_NOTIFY,
&volume, &muted);
if (NS_WARN_IF(NS_FAILED(rv))) {
return;
}
WindowAudioCaptureChanged();
WindowVolumeChanged(volume, muted);
}
} // namespace dom
} // namespace mozilla