Title: [268161] trunk
Revision
268161
Author
cdu...@apple.com
Date
2020-10-07 16:31:25 -0700 (Wed, 07 Oct 2020)

Log Message

Constructing a AudioWorkletNode should construct an AudioWorkletProcessor on the Worklet thread
https://bugs.webkit.org/show_bug.cgi?id=217442

Reviewed by Geoffrey Garen.

LayoutTests/imported/w3c:

Rebaseline WPT tests now that we are passing more checks.

* web-platform-tests/webaudio/the-audio-api/the-audiocontext-interface/processing-after-resume.https-expected.txt:
* web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/audioworklet-messageport.https-expected.txt:
* web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/audioworkletglobalscope-timing-info.https-expected.txt:
* web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/audioworkletprocessor-options.https-expected.txt:
* web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/processor-construction-port.https-expected.txt:
* web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/suspended-context-messageport.https-expected.txt:

Source/WebCore:

Constructing a AudioWorkletNode should construct an AudioWorkletProcessor on the Worklet thread:
- https://www.w3.org/TR/webaudio/#AudioWorkletNode-constructors (Step 13)

No new tests, rebaselined existing tests.

* Modules/webaudio/AudioWorklet.cpp:
(WebCore::AudioWorklet::createProcessor):
Add createProcessor() function to AudioWorklet which takes care of hopping to the worklet thread
in order to call createProcessor() on the AudioWorkletGlobalScope.

* Modules/webaudio/AudioWorklet.h:

* Modules/webaudio/AudioWorkletGlobalScope.cpp:
(WebCore::AudioWorkletGlobalScope::createProcessor):
Construct an AudioWorkletProcessor, as specified here:
- https://www.w3.org/TR/webaudio/#AudioWorkletProcessor-instantiation

(WebCore::AudioWorkletGlobalScope::takePendingProcessorConstructionData):
A function to take the pending ProcessorConstructionData. This construction
data gets initialized in createProcessor() and gets consumed by
AudioWorkletProcessor::create().

* Modules/webaudio/AudioWorkletGlobalScope.h:

* Modules/webaudio/AudioWorkletNode.cpp:
(WebCore::AudioWorkletNode::create):
Improve AudioWorkletNode constructor to actually cause the construction of
the AudioWorkletProcessor on the worklet thread, passing it the options and
the MessagePort. This is as per the specification here:
- https://www.w3.org/TR/webaudio/#AudioWorkletNode-constructors

(WebCore::AudioWorkletNode::AudioWorkletNode):
(WebCore::AudioWorkletNode::~AudioWorkletNode):

(WebCore::AudioWorkletNode::setProcessor):
Once the AudioWorkletProcessor is created on the worklet thread, this gets
called so that the AudioWorkletNode has a reference to the processor. This
will be needed later on once AudioWorkletNode::process() starts doing audio
processing through the AudioWorkletProcessor.

(WebCore::AudioWorkletNode::process):
Improve comment.

* Modules/webaudio/AudioWorkletNode.h:
* Modules/webaudio/AudioWorkletNode.idl:
Pass the global object to the constructor. It is needed now that the constructor
serializes script values to pass them to the worklet thread.

* Modules/webaudio/AudioWorkletNodeOptions.idl:
Add [JSGenerateToJSObject] to AudioWorkletNodeOptions dictionary so that a
convertDictionaryToJS() function gets generated for this dictionary. This function
is called by the AudioWorkletNode constructor.

* Modules/webaudio/AudioWorkletProcessor.cpp:
(WebCore::AudioWorkletProcessor::create):
(WebCore::AudioWorkletProcessor::AudioWorkletProcessor):
* Modules/webaudio/AudioWorkletProcessor.h:
(WebCore::AudioWorkletProcessor::name const):
(WebCore::AudioWorkletProcessor::port):
Implement AudioWorkletProcessor constructor so that its retrieves the pending
construction data from the AudioWorkletGlobalScope and properly initializes
its name and port. The specification for this is here:
- https://www.w3.org/TR/webaudio/#dom-audioworkletprocessor-audioworkletprocessor

* Modules/webaudio/AudioWorkletProcessor.idl:
Indicate that the constructor may throw an exception as per the specification:
- https://www.w3.org/TR/webaudio/#dom-audioworkletprocessor-audioworkletprocessor (Step 1)
Also pass the ScriptExecutionContext to the constructor since the constructor
needs to retrieve the pending construction data from it:
- https://www.w3.org/TR/webaudio/#dom-audioworkletprocessor-audioworkletprocessor (Step 1)

* Modules/webaudio/AudioWorkletProcessorConstructionData.h:

(WebCore::AudioWorkletProcessorConstructionData::AudioWorkletProcessorConstructionData):
(WebCore::AudioWorkletProcessorConstructionData::name const):
(WebCore::AudioWorkletProcessorConstructionData::port const):
Add class to wrap the AudioWorkletProcess's construction data:
- https://www.w3.org/TR/webaudio/#pending-processor-construction-data

* Modules/webaudio/AudioWorkletThread.h:
Move ThreadSafeRefCounted from this class to the parent class (WorkerOrWorkletThread)
since WorkerMessagePortChannelProvider needs to protect a WorkerOrWorkletThread now.

* WebCore.xcodeproj/project.pbxproj:
Add new header to project.

* bindings/js/JSDOMGlobalObject.cpp:
(WebCore::toJSDOMGlobalObject):
Properly handle WorkletGlobalScope.

* dom/MessagePort.cpp:
(WebCore::MessagePort::disentangle):
(WebCore::MessagePort::disentanglePorts):
(WebCore::MessagePort::entanglePorts):
(WebCore::MessagePort::entangle):
* dom/MessagePort.h:
Tweak MessagePort API to support disentangling/entangling a single
MessagePort. Previously we had to pass an array of ports.

* dom/ScriptExecutionContext.cpp:
(WebCore::ScriptExecutionContext::createdMessagePort):
(WebCore::ScriptExecutionContext::destroyedMessagePort):
Tweak assertions to handle AudioWorkletGlobalScopes.

* dom/messageports/MessagePortChannelProvider.cpp:
(WebCore::MessagePortChannelProvider::fromContext):
* dom/messageports/MessageWithMessagePorts.h:
* dom/messageports/WorkerMessagePortChannelProvider.cpp:
(WebCore::WorkerMessagePortChannelProvider::WorkerMessagePortChannelProvider):
(WebCore::WorkerMessagePortChannelProvider::takeAllMessagesForPort):
(WebCore::WorkerMessagePortChannelProvider::checkRemotePortForActivity):
* dom/messageports/WorkerMessagePortChannelProvider.h:
Update WorkerMessagePortChannelProvider to use WorkerOrWorkletScope instead
or WorkerGlobalScope. This allows us to reuse this class for AudioWorklets
so that MessagePort communication between the main thread and the worklet
thread now works.

* workers/WorkerOrWorkletThread.h:
Move ThreadSafeRefCounted from subclasses to this class so that
WorkerMessagePortChannelProvider can protect a WorkerOrWorkletThread.

* workers/WorkerThread.h:
* worklets/WorkletGlobalScope.cpp:
(WebCore::WorkletGlobalScope::notifyFinished):
Only evaluate the script if we have not already evaluated it in this worklet.
I am assuming this is needed because we are not treating the script as a module
yet (due to lack of support in workers). Without this changes, the worklet's
script would get in a bad state when importing several times the same module
(which is something the WPT tests do).

(WebCore::WorkletGlobalScope::messagePortChannelProvider):
Instantiate WorkerMessagePortChannelProvider if needed. This is needed for
MessagePort communication is AudioWorklets.

* worklets/WorkletGlobalScope.h:

LayoutTests:

Unskip a few tests that are no longer timing out.

* TestExpectations:

Modified Paths

Added Paths

Diff

Modified: trunk/LayoutTests/ChangeLog (268160 => 268161)


--- trunk/LayoutTests/ChangeLog	2020-10-07 22:49:20 UTC (rev 268160)
+++ trunk/LayoutTests/ChangeLog	2020-10-07 23:31:25 UTC (rev 268161)
@@ -1,3 +1,14 @@
+2020-10-07  Chris Dumez  <cdu...@apple.com>
+
+        Constructing a AudioWorkletNode should construct an AudioWorkletProcessor on the Worklet thread
+        https://bugs.webkit.org/show_bug.cgi?id=217442
+
+        Reviewed by Geoffrey Garen.
+
+        Unskip a few tests that are no longer timing out.
+
+        * TestExpectations:
+
 2020-10-07  Tyler Wilcock  <twilc...@protonmail.com>
 
         background-clip:var(--a) invalidates -webkit-background-clip:text when --a:text

Modified: trunk/LayoutTests/TestExpectations (268160 => 268161)


--- trunk/LayoutTests/TestExpectations	2020-10-07 22:49:20 UTC (rev 268160)
+++ trunk/LayoutTests/TestExpectations	2020-10-07 23:31:25 UTC (rev 268161)
@@ -320,20 +320,15 @@
 imported/w3c/web-platform-tests/webaudio/the-audio-api/the-mediastreamaudiosourcenode-interface/mediastreamaudiosourcenode-routing.html [ Skip ]
 
 # These webaudio tests are timing out due to lack for support for AudioWorklet.
-imported/w3c/web-platform-tests/webaudio/the-audio-api/the-audiocontext-interface/processing-after-resume.https.html [ Skip ]
-imported/w3c/web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/audioworklet-messageport.https.html [ Skip ]
 imported/w3c/web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/audioworklet-postmessage-sharedarraybuffer.https.html [ Skip ]
-imported/w3c/web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/audioworkletglobalscope-timing-info.https.html [ Skip ]
 imported/w3c/web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/audioworkletnode-automatic-pull.https.html [ Skip ]
 imported/w3c/web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/audioworkletnode-onerror.https.html [ Skip ]
 imported/w3c/web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/audioworkletnode-output-channel-count.https.html [ Skip ]
-imported/w3c/web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/audioworkletprocessor-options.https.html [ Skip ]
 imported/w3c/web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/audioworkletprocessor-process-frozen-array.https.html [ Skip ]
 imported/w3c/web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/audioworkletprocessor-process-zero-outputs.https.html [ Skip ]
 imported/w3c/web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/audioworkletprocessor-promises.https.html [ Skip ]
 imported/w3c/web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/process-getter.https.html [ Skip ]
 imported/w3c/web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/process-parameters.https.html [ Skip ]
-imported/w3c/web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/suspended-context-messageport.https.html [ Skip ]
 imported/w3c/web-platform-tests/webaudio/the-audio-api/the-channelmergernode-interface/active-processing.https.html [ Skip ]
 imported/w3c/web-platform-tests/webaudio/the-audio-api/the-convolvernode-interface/active-processing.https.html [ Skip ]
 imported/w3c/web-platform-tests/webaudio/the-audio-api/the-mediaelementaudiosourcenode-interface/cors-check.https.html [ Skip ]

Modified: trunk/LayoutTests/imported/w3c/ChangeLog (268160 => 268161)


--- trunk/LayoutTests/imported/w3c/ChangeLog	2020-10-07 22:49:20 UTC (rev 268160)
+++ trunk/LayoutTests/imported/w3c/ChangeLog	2020-10-07 23:31:25 UTC (rev 268161)
@@ -1,3 +1,19 @@
+2020-10-07  Chris Dumez  <cdu...@apple.com>
+
+        Constructing a AudioWorkletNode should construct an AudioWorkletProcessor on the Worklet thread
+        https://bugs.webkit.org/show_bug.cgi?id=217442
+
+        Reviewed by Geoffrey Garen.
+
+        Rebaseline WPT tests now that we are passing more checks.
+
+        * web-platform-tests/webaudio/the-audio-api/the-audiocontext-interface/processing-after-resume.https-expected.txt:
+        * web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/audioworklet-messageport.https-expected.txt:
+        * web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/audioworkletglobalscope-timing-info.https-expected.txt:
+        * web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/audioworkletprocessor-options.https-expected.txt:
+        * web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/processor-construction-port.https-expected.txt:
+        * web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/suspended-context-messageport.https-expected.txt:
+
 2020-10-07  Noam Rosenthal  <n...@webkit.org>
 
         clip-path: path() ignores page zooming (Command-+)

Modified: trunk/LayoutTests/imported/w3c/web-platform-tests/webaudio/the-audio-api/the-audiocontext-interface/processing-after-resume.https-expected.txt (268160 => 268161)


--- trunk/LayoutTests/imported/w3c/web-platform-tests/webaudio/the-audio-api/the-audiocontext-interface/processing-after-resume.https-expected.txt	2020-10-07 22:49:20 UTC (rev 268160)
+++ trunk/LayoutTests/imported/w3c/web-platform-tests/webaudio/the-audio-api/the-audiocontext-interface/processing-after-resume.https-expected.txt	2020-10-07 23:31:25 UTC (rev 268161)
@@ -1,5 +1,3 @@
 
-Harness Error (TIMEOUT), message = null
+PASS Test consistency of processing after resume()
 
-TIMEOUT Test consistency of processing after resume() Test timed out
-

Modified: trunk/LayoutTests/imported/w3c/web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/audioworklet-messageport.https-expected.txt (268160 => 268161)


--- trunk/LayoutTests/imported/w3c/web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/audioworklet-messageport.https-expected.txt	2020-10-07 22:49:20 UTC (rev 268160)
+++ trunk/LayoutTests/imported/w3c/web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/audioworklet-messageport.https-expected.txt	2020-10-07 23:31:25 UTC (rev 268161)
@@ -1,9 +1,13 @@
 
-Harness Error (TIMEOUT), message = null
-
 PASS # AUDIT TASK RUNNER STARTED.
-TIMEOUT Executing "Test postMessage from AudioWorkletProcessor to AudioWorkletNode" Test timed out
-NOTRUN Executing "Test postMessage from AudioWorkletNode to AudioWorkletProcessor"
-NOTRUN Audit report
+PASS Executing "Test postMessage from AudioWorkletProcessor to AudioWorkletNode"
+PASS Executing "Test postMessage from AudioWorkletNode to AudioWorkletProcessor"
+PASS Audit report
 PASS > [Test postMessage from AudioWorkletProcessor to AudioWorkletNode]
+PASS   The initial message from PortProcessor is equal to created.
+PASS < [Test postMessage from AudioWorkletProcessor to AudioWorkletNode] All assertions passed. (total 1 assertions)
+PASS > [Test postMessage from AudioWorkletNode to AudioWorkletProcessor]
+PASS   The response from PortProcessor is equal to hello.
+PASS < [Test postMessage from AudioWorkletNode to AudioWorkletProcessor] All assertions passed. (total 1 assertions)
+PASS # AUDIT TASK RUNNER FINISHED: 2 tasks ran successfully.
 

Modified: trunk/LayoutTests/imported/w3c/web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/audioworkletglobalscope-timing-info.https-expected.txt (268160 => 268161)


--- trunk/LayoutTests/imported/w3c/web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/audioworkletglobalscope-timing-info.https-expected.txt	2020-10-07 22:49:20 UTC (rev 268160)
+++ trunk/LayoutTests/imported/w3c/web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/audioworkletglobalscope-timing-info.https-expected.txt	2020-10-07 23:31:25 UTC (rev 268161)
@@ -1,8 +1,16 @@
 
-Harness Error (TIMEOUT), message = null
-
 PASS # AUDIT TASK RUNNER STARTED.
-TIMEOUT Executing "Check the timing information from AudioWorkletProcessor" Test timed out
-NOTRUN Audit report
+PASS Executing "Check the timing information from AudioWorkletProcessor"
+PASS Audit report
 PASS > [Check the timing information from AudioWorkletProcessor]
+PASS   currentFrame from the processor at 0 is equal to 0.
+PASS   currentTime from the processor at 0 is equal to 0.
+PASS   currentFrame from the processor at 128 is equal to 128.
+PASS   currentTime from the processor at 0.0026666666666666666 is equal to 0.0026666666666666666.
+PASS   currentFrame from the processor at 256 is equal to 256.
+PASS   currentTime from the processor at 0.005333333333333333 is equal to 0.005333333333333333.
+PASS   currentFrame from the processor at 384 is equal to 384.
+PASS   currentTime from the processor at 0.008 is equal to 0.008.
+PASS < [Check the timing information from AudioWorkletProcessor] All assertions passed. (total 8 assertions)
+PASS # AUDIT TASK RUNNER FINISHED: 1 tasks ran successfully.
 

Modified: trunk/LayoutTests/imported/w3c/web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/audioworkletprocessor-options.https-expected.txt (268160 => 268161)


--- trunk/LayoutTests/imported/w3c/web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/audioworkletprocessor-options.https-expected.txt	2020-10-07 22:49:20 UTC (rev 268160)
+++ trunk/LayoutTests/imported/w3c/web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/audioworkletprocessor-options.https-expected.txt	2020-10-07 23:31:25 UTC (rev 268161)
@@ -1,9 +1,16 @@
 
-Harness Error (TIMEOUT), message = null
-
 PASS # AUDIT TASK RUNNER STARTED.
-TIMEOUT Executing "valid-processor-data" Test timed out
-NOTRUN Executing "empty-option"
-NOTRUN Audit report
+PASS Executing "valid-processor-data"
+PASS Executing "empty-option"
+PASS Audit report
 PASS > [valid-processor-data]
+PASS   |description| field in processorOptions from processor("foo") is equal to the field in node constructor options ("foo").
+PASS   |payload| array in processorOptions from processor([0,1,2,3]) is identical to the array the array in node constructor options ([0,1,2,3]).
+PASS < [valid-processor-data] All assertions passed. (total 2 assertions)
+PASS > [empty-option]
+PASS   Number of properties in data from processor is equal to 2.
+PASS   |numberOfInputs| field in data from processor is equal to 1.
+PASS   |numberOfOutputs| field in data from processor is identical to the array 1.
+PASS < [empty-option] All assertions passed. (total 3 assertions)
+PASS # AUDIT TASK RUNNER FINISHED: 2 tasks ran successfully.
 

Modified: trunk/LayoutTests/imported/w3c/web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/processor-construction-port.https-expected.txt (268160 => 268161)


--- trunk/LayoutTests/imported/w3c/web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/processor-construction-port.https-expected.txt	2020-10-07 22:49:20 UTC (rev 268160)
+++ trunk/LayoutTests/imported/w3c/web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/processor-construction-port.https-expected.txt	2020-10-07 23:31:25 UTC (rev 268161)
@@ -1,8 +1,8 @@
 
 Harness Error (TIMEOUT), message = null
 
-TIMEOUT super() after new AudioWorkletProcessor() Test timed out
-NOTRUN new AudioWorkletProcessor() after super()
-NOTRUN new AudioWorkletProcessor() after new AudioWorkletProcessor()
-NOTRUN Singleton AudioWorkletProcessor
+PASS super() after new AudioWorkletProcessor()
+PASS new AudioWorkletProcessor() after super()
+PASS new AudioWorkletProcessor() after new AudioWorkletProcessor()
+TIMEOUT Singleton AudioWorkletProcessor Test timed out
 

Modified: trunk/LayoutTests/imported/w3c/web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/suspended-context-messageport.https-expected.txt (268160 => 268161)


--- trunk/LayoutTests/imported/w3c/web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/suspended-context-messageport.https-expected.txt	2020-10-07 22:49:20 UTC (rev 268160)
+++ trunk/LayoutTests/imported/w3c/web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/suspended-context-messageport.https-expected.txt	2020-10-07 23:31:25 UTC (rev 268161)
@@ -1,7 +1,5 @@
 
-Harness Error (TIMEOUT), message = null
+PASS realtime suspended
+PASS offline before start
+FAIL offline on complete promise_test: Unhandled rejection with value: object "InvalidStateError: Context is closed"
 
-TIMEOUT realtime suspended Test timed out
-NOTRUN offline before start
-NOTRUN offline on complete
-

Modified: trunk/Source/WebCore/ChangeLog (268160 => 268161)


--- trunk/Source/WebCore/ChangeLog	2020-10-07 22:49:20 UTC (rev 268160)
+++ trunk/Source/WebCore/ChangeLog	2020-10-07 23:31:25 UTC (rev 268161)
@@ -1,5 +1,148 @@
 2020-10-07  Chris Dumez  <cdu...@apple.com>
 
+        Constructing a AudioWorkletNode should construct an AudioWorkletProcessor on the Worklet thread
+        https://bugs.webkit.org/show_bug.cgi?id=217442
+
+        Reviewed by Geoffrey Garen.
+
+        Constructing a AudioWorkletNode should construct an AudioWorkletProcessor on the Worklet thread:
+        - https://www.w3.org/TR/webaudio/#AudioWorkletNode-constructors (Step 13)
+
+        No new tests, rebaselined existing tests.
+
+        * Modules/webaudio/AudioWorklet.cpp:
+        (WebCore::AudioWorklet::createProcessor):
+        Add createProcessor() function to AudioWorklet which takes care of hopping to the worklet thread
+        in order to call createProcessor() on the AudioWorkletGlobalScope.
+
+        * Modules/webaudio/AudioWorklet.h:
+
+        * Modules/webaudio/AudioWorkletGlobalScope.cpp:
+        (WebCore::AudioWorkletGlobalScope::createProcessor):
+        Construct an AudioWorkletProcessor, as specified here:
+        - https://www.w3.org/TR/webaudio/#AudioWorkletProcessor-instantiation
+
+        (WebCore::AudioWorkletGlobalScope::takePendingProcessorConstructionData):
+        A function to take the pending ProcessorConstructionData. This construction
+        data gets initialized in createProcessor() and gets consumed by
+        AudioWorkletProcessor::create().
+
+        * Modules/webaudio/AudioWorkletGlobalScope.h:
+
+        * Modules/webaudio/AudioWorkletNode.cpp:
+        (WebCore::AudioWorkletNode::create):
+        Improve AudioWorkletNode constructor to actually cause the construction of
+        the AudioWorkletProcessor on the worklet thread, passing it the options and
+        the MessagePort. This is as per the specification here:
+        - https://www.w3.org/TR/webaudio/#AudioWorkletNode-constructors
+
+        (WebCore::AudioWorkletNode::AudioWorkletNode):
+        (WebCore::AudioWorkletNode::~AudioWorkletNode):
+
+        (WebCore::AudioWorkletNode::setProcessor):
+        Once the AudioWorkletProcessor is created on the worklet thread, this gets
+        called so that the AudioWorkletNode has a reference to the processor. This
+        will be needed later on once AudioWorkletNode::process() starts doing audio
+        processing through the AudioWorkletProcessor.
+
+        (WebCore::AudioWorkletNode::process):
+        Improve comment.
+
+        * Modules/webaudio/AudioWorkletNode.h:
+        * Modules/webaudio/AudioWorkletNode.idl:
+        Pass the global object to the constructor. It is needed now that the constructor
+        serializes script values to pass them to the worklet thread.
+
+        * Modules/webaudio/AudioWorkletNodeOptions.idl:
+        Add [JSGenerateToJSObject] to AudioWorkletNodeOptions dictionary so that a
+        convertDictionaryToJS() function gets generated for this dictionary. This function
+        is called by the AudioWorkletNode constructor.
+
+        * Modules/webaudio/AudioWorkletProcessor.cpp:
+        (WebCore::AudioWorkletProcessor::create):
+        (WebCore::AudioWorkletProcessor::AudioWorkletProcessor):
+        * Modules/webaudio/AudioWorkletProcessor.h:
+        (WebCore::AudioWorkletProcessor::name const):
+        (WebCore::AudioWorkletProcessor::port):
+        Implement AudioWorkletProcessor constructor so that its retrieves the pending
+        construction data from the AudioWorkletGlobalScope and properly initializes
+        its name and port. The specification for this is here:
+        - https://www.w3.org/TR/webaudio/#dom-audioworkletprocessor-audioworkletprocessor
+
+        * Modules/webaudio/AudioWorkletProcessor.idl:
+        Indicate that the constructor may throw an exception as per the specification:
+        - https://www.w3.org/TR/webaudio/#dom-audioworkletprocessor-audioworkletprocessor (Step 1)
+        Also pass the ScriptExecutionContext to the constructor since the constructor
+        needs to retrieve the pending construction data from it:
+        - https://www.w3.org/TR/webaudio/#dom-audioworkletprocessor-audioworkletprocessor (Step 1)
+
+        * Modules/webaudio/AudioWorkletProcessorConstructionData.h:
+
+        (WebCore::AudioWorkletProcessorConstructionData::AudioWorkletProcessorConstructionData):
+        (WebCore::AudioWorkletProcessorConstructionData::name const):
+        (WebCore::AudioWorkletProcessorConstructionData::port const):
+        Add class to wrap the AudioWorkletProcess's construction data:
+        - https://www.w3.org/TR/webaudio/#pending-processor-construction-data
+
+        * Modules/webaudio/AudioWorkletThread.h:
+        Move ThreadSafeRefCounted from this class to the parent class (WorkerOrWorkletThread)
+        since WorkerMessagePortChannelProvider needs to protect a WorkerOrWorkletThread now.
+
+        * WebCore.xcodeproj/project.pbxproj:
+        Add new header to project.
+
+        * bindings/js/JSDOMGlobalObject.cpp:
+        (WebCore::toJSDOMGlobalObject):
+        Properly handle WorkletGlobalScope.
+
+        * dom/MessagePort.cpp:
+        (WebCore::MessagePort::disentangle):
+        (WebCore::MessagePort::disentanglePorts):
+        (WebCore::MessagePort::entanglePorts):
+        (WebCore::MessagePort::entangle):
+        * dom/MessagePort.h:
+        Tweak MessagePort API to support disentangling/entangling a single
+        MessagePort. Previously we had to pass an array of ports.
+
+        * dom/ScriptExecutionContext.cpp:
+        (WebCore::ScriptExecutionContext::createdMessagePort):
+        (WebCore::ScriptExecutionContext::destroyedMessagePort):
+        Tweak assertions to handle AudioWorkletGlobalScopes.
+
+        * dom/messageports/MessagePortChannelProvider.cpp:
+        (WebCore::MessagePortChannelProvider::fromContext):
+        * dom/messageports/MessageWithMessagePorts.h:
+        * dom/messageports/WorkerMessagePortChannelProvider.cpp:
+        (WebCore::WorkerMessagePortChannelProvider::WorkerMessagePortChannelProvider):
+        (WebCore::WorkerMessagePortChannelProvider::takeAllMessagesForPort):
+        (WebCore::WorkerMessagePortChannelProvider::checkRemotePortForActivity):
+        * dom/messageports/WorkerMessagePortChannelProvider.h:
+        Update WorkerMessagePortChannelProvider to use WorkerOrWorkletScope instead
+        or WorkerGlobalScope. This allows us to reuse this class for AudioWorklets
+        so that MessagePort communication between the main thread and the worklet
+        thread now works.
+
+        * workers/WorkerOrWorkletThread.h:
+        Move ThreadSafeRefCounted from subclasses to this class so that
+        WorkerMessagePortChannelProvider can protect a WorkerOrWorkletThread.
+
+        * workers/WorkerThread.h:
+        * worklets/WorkletGlobalScope.cpp:
+        (WebCore::WorkletGlobalScope::notifyFinished):
+        Only evaluate the script if we have not already evaluated it in this worklet.
+        I am assuming this is needed because we are not treating the script as a module
+        yet (due to lack of support in workers). Without this changes, the worklet's
+        script would get in a bad state when importing several times the same module
+        (which is something the WPT tests do).
+
+        (WebCore::WorkletGlobalScope::messagePortChannelProvider):
+        Instantiate WorkerMessagePortChannelProvider if needed. This is needed for
+        MessagePort communication is AudioWorklets.
+
+        * worklets/WorkletGlobalScope.h:
+
+2020-10-07  Chris Dumez  <cdu...@apple.com>
+
         Crash under JSAudioWorkletProcessorConstructor::~JSAudioWorkletProcessorConstructor()
         https://bugs.webkit.org/show_bug.cgi?id=217448
         <rdar://problem/70059902>

Modified: trunk/Source/WebCore/Modules/webaudio/AudioWorklet.cpp (268160 => 268161)


--- trunk/Source/WebCore/Modules/webaudio/AudioWorklet.cpp	2020-10-07 22:49:20 UTC (rev 268160)
+++ trunk/Source/WebCore/Modules/webaudio/AudioWorklet.cpp	2020-10-07 23:31:25 UTC (rev 268161)
@@ -31,8 +31,11 @@
 #if ENABLE(WEB_AUDIO)
 #include "AudioWorklet.h"
 
+#include "AudioWorkletGlobalScope.h"
 #include "AudioWorkletMessagingProxy.h"
+#include "AudioWorkletNode.h"
 #include "BaseAudioContext.h"
+#include "WorkerRunLoop.h"
 #include <wtf/IsoMallocInlines.h>
 
 namespace WebCore {
@@ -71,6 +74,19 @@
     return m_audioContext.get();
 }
 
+void AudioWorklet::createProcessor(const String& name, TransferredMessagePort port, Ref<SerializedScriptValue>&& options, AudioWorkletNode& node)
+{
+    auto* proxy = this->proxy();
+    ASSERT(proxy);
+    if (!proxy)
+        return;
+
+    proxy->postTaskForModeToWorkletGlobalScope([name = name.isolatedCopy(), port, options = WTFMove(options), node = makeRef(node)](ScriptExecutionContext& context) mutable {
+        node->setProcessor(downcast<AudioWorkletGlobalScope>(context).createProcessor(name, port, WTFMove(options)));
+        callOnMainThread([node = WTFMove(node)] { });
+    }, WorkerRunLoop::defaultMode());
+}
+
 } // namespace WebCore
 
 #endif // ENABLE(WEB_AUDIO)

Modified: trunk/Source/WebCore/Modules/webaudio/AudioWorklet.h (268160 => 268161)


--- trunk/Source/WebCore/Modules/webaudio/AudioWorklet.h	2020-10-07 22:49:20 UTC (rev 268160)
+++ trunk/Source/WebCore/Modules/webaudio/AudioWorklet.h	2020-10-07 23:31:25 UTC (rev 268161)
@@ -29,11 +29,13 @@
 #pragma once
 
 #if ENABLE(WEB_AUDIO)
+#include "MessagePort.h"
 #include "Worklet.h"
 #include <wtf/WeakPtr.h>
 
 namespace WebCore {
 
+class AudioWorkletNode;
 class BaseAudioContext;
 class AudioWorkletMessagingProxy;
 
@@ -45,6 +47,8 @@
     AudioWorkletMessagingProxy* proxy() const;
     BaseAudioContext* audioContext() const;
 
+    void createProcessor(const String& name, TransferredMessagePort, Ref<SerializedScriptValue>&&, AudioWorkletNode&);
+
 private:
     explicit AudioWorklet(BaseAudioContext&);
 

Modified: trunk/Source/WebCore/Modules/webaudio/AudioWorkletGlobalScope.cpp (268160 => 268161)


--- trunk/Source/WebCore/Modules/webaudio/AudioWorkletGlobalScope.cpp	2020-10-07 22:49:20 UTC (rev 268160)
+++ trunk/Source/WebCore/Modules/webaudio/AudioWorkletGlobalScope.cpp	2020-10-07 23:31:25 UTC (rev 268161)
@@ -34,6 +34,8 @@
 #include "AudioParamDescriptor.h"
 #include "AudioWorklet.h"
 #include "AudioWorkletMessagingProxy.h"
+#include "AudioWorkletProcessorConstructionData.h"
+#include "JSAudioWorkletProcessor.h"
 #include "JSAudioWorkletProcessorConstructor.h"
 #include "JSDOMConvert.h"
 #include <wtf/CrossThreadCopier.h>
@@ -109,6 +111,35 @@
     return { };
 }
 
+RefPtr<AudioWorkletProcessor> AudioWorkletGlobalScope::createProcessor(const String& name, TransferredMessagePort port, Ref<SerializedScriptValue>&& options)
+{
+    auto constructor = m_processorConstructorMap.get(name);
+    ASSERT(constructor);
+    if (!constructor)
+        return nullptr;
+
+    JSC::JSObject* jsConstructor = constructor->callbackData()->callback();
+    auto* globalObject = jsConstructor->globalObject();
+    JSC::VM& vm = globalObject->vm();
+    auto scope = DECLARE_THROW_SCOPE(vm);
+    JSC::JSLockHolder lock { globalObject };
+
+    m_pendingProcessorConstructionData = makeUnique<AudioWorkletProcessorConstructionData>(String { name }, MessagePort::entangle(*this, WTFMove(port)));
+
+    JSC::MarkedArgumentBuffer args;
+    auto arg = options->deserialize(*globalObject, globalObject, SerializationErrorMode::NonThrowing);
+    RETURN_IF_EXCEPTION(scope, nullptr);
+    args.append(arg);
+    ASSERT(!args.hasOverflowed());
+
+    auto* object = JSC::construct(globalObject, jsConstructor, args, "Failed to construct AudioWorkletProcessor");
+    ASSERT(!!scope.exception() == !object);
+    RETURN_IF_EXCEPTION(scope, nullptr);
+
+    auto& jsProcessor = *JSC::jsCast<JSAudioWorkletProcessor*>(object);
+    return &jsProcessor.wrapped();
+}
+
 void AudioWorkletGlobalScope::prepareForTermination()
 {
     if (auto* defaultTaskGroup = this->defaultTaskGroup())
@@ -132,6 +163,11 @@
     thread().runLoop().postTask(WTFMove(task));
 }
 
+std::unique_ptr<AudioWorkletProcessorConstructionData> AudioWorkletGlobalScope::takePendingProcessorConstructionData()
+{
+    return std::exchange(m_pendingProcessorConstructionData, nullptr);
+}
+
 } // namespace WebCore
 
 #endif // ENABLE(WEB_AUDIO)

Modified: trunk/Source/WebCore/Modules/webaudio/AudioWorkletGlobalScope.h (268160 => 268161)


--- trunk/Source/WebCore/Modules/webaudio/AudioWorkletGlobalScope.h	2020-10-07 22:49:20 UTC (rev 268160)
+++ trunk/Source/WebCore/Modules/webaudio/AudioWorkletGlobalScope.h	2020-10-07 23:31:25 UTC (rev 268161)
@@ -30,10 +30,13 @@
 
 #if ENABLE(WEB_AUDIO)
 #include "AudioWorkletThread.h"
+#include "MessagePort.h"
 #include "WorkletGlobalScope.h"
 
 namespace WebCore {
 
+class AudioWorkletProcessorConstructionData;
+class AudioWorkletProcessor;
 class AudioWorkletThread;
 class JSAudioWorkletProcessorConstructor;
 
@@ -49,6 +52,7 @@
     ~AudioWorkletGlobalScope();
 
     ExceptionOr<void> registerProcessor(String&& name, Ref<JSAudioWorkletProcessorConstructor>&&);
+    RefPtr<AudioWorkletProcessor> createProcessor(const String& name, TransferredMessagePort, Ref<SerializedScriptValue>&& options);
 
     void setCurrentFrame(float currentFrame) { m_currentFrame = currentFrame; }
     size_t currentFrame() const { return m_currentFrame; }
@@ -62,6 +66,8 @@
 
     void postTask(Task&&) final;
 
+    std::unique_ptr<AudioWorkletProcessorConstructionData> takePendingProcessorConstructionData();
+
 private:
     AudioWorkletGlobalScope(AudioWorkletThread&, const WorkletParameters&);
 
@@ -72,6 +78,7 @@
     size_t m_currentFrame { 0 };
     const float m_sampleRate;
     HashMap<String, RefPtr<JSAudioWorkletProcessorConstructor>> m_processorConstructorMap;
+    std::unique_ptr<AudioWorkletProcessorConstructionData> m_pendingProcessorConstructionData;
 };
 
 } // namespace WebCore

Modified: trunk/Source/WebCore/Modules/webaudio/AudioWorkletNode.cpp (268160 => 268161)


--- trunk/Source/WebCore/Modules/webaudio/AudioWorkletNode.cpp	2020-10-07 22:49:20 UTC (rev 268160)
+++ trunk/Source/WebCore/Modules/webaudio/AudioWorkletNode.cpp	2020-10-07 23:31:25 UTC (rev 268161)
@@ -35,10 +35,17 @@
 #include "AudioNodeOutput.h"
 #include "AudioParam.h"
 #include "AudioParamMap.h"
+#include "AudioWorklet.h"
+#include "AudioWorkletMessagingProxy.h"
 #include "AudioWorkletNodeOptions.h"
+#include "AudioWorkletProcessor.h"
 #include "BaseAudioContext.h"
+#include "JSAudioWorkletNodeOptions.h"
 #include "MessageChannel.h"
 #include "MessagePort.h"
+#include "SerializedScriptValue.h"
+#include "WorkerRunLoop.h"
+#include <_javascript_Core/JSLock.h>
 #include <wtf/IsoMallocInlines.h>
 
 namespace WebCore {
@@ -45,7 +52,7 @@
 
 WTF_MAKE_ISO_ALLOCATED_IMPL(AudioWorkletNode);
 
-ExceptionOr<Ref<AudioWorkletNode>> AudioWorkletNode::create(BaseAudioContext& context, String&& name, AudioWorkletNodeOptions&& options)
+ExceptionOr<Ref<AudioWorkletNode>> AudioWorkletNode::create(JSC::JSGlobalObject& globalObject, BaseAudioContext& context, String&& name, AudioWorkletNodeOptions&& options)
 {
     if (!options.numberOfInputs && !options.numberOfOutputs)
         return Exception { NotSupportedError, "Number of inputs and outputs cannot both be 0"_s };
@@ -69,10 +76,20 @@
         return Exception { InvalidStateError, "Context is closed"_s };
 
     auto messageChannel = MessageChannel::create(*context.scriptExecutionContext());
-    // FIXME: Pass messageChannel's port2 to the AudioWorkletProcessor.
+    auto nodeMessagePort = messageChannel->port1();
+    auto processorMessagePort = messageChannel->port2();
 
+    RefPtr<SerializedScriptValue> serializedOptions;
+    {
+        auto lock = JSC::JSLockHolder { &globalObject };
+        auto* jsOptions = convertDictionaryToJS(globalObject, *JSC::jsCast<JSDOMGlobalObject*>(&globalObject), options);
+        serializedOptions = SerializedScriptValue::create(globalObject, jsOptions, SerializationErrorMode::NonThrowing);
+        if (!serializedOptions)
+            serializedOptions = SerializedScriptValue::nullValue();
+    }
+
     auto parameterData = WTFMove(options.parameterData);
-    auto node = adoptRef(*new AudioWorkletNode(context, WTFMove(name), WTFMove(options), *messageChannel->port1()));
+    auto node = adoptRef(*new AudioWorkletNode(context, name, WTFMove(options), *nodeMessagePort));
 
     auto result = node->handleAudioNodeOptions(options, { 2, ChannelCountMode::Max, ChannelInterpretation::Speakers });
     if (result.hasException())
@@ -90,15 +107,18 @@
         }
     }
 
+    context.audioWorklet().createProcessor(name, processorMessagePort->disentangle(), serializedOptions.releaseNonNull(), node);
+
     return node;
 }
 
-AudioWorkletNode::AudioWorkletNode(BaseAudioContext& context, String&& name, AudioWorkletNodeOptions&& options, Ref<MessagePort>&& port)
+AudioWorkletNode::AudioWorkletNode(BaseAudioContext& context, const String& name, AudioWorkletNodeOptions&& options, Ref<MessagePort>&& port)
     : AudioNode(context, NodeTypeWorklet)
-    , m_name(WTFMove(name))
+    , m_name(name)
     , m_parameters(AudioParamMap::create())
     , m_port(WTFMove(port))
 {
+    ASSERT(isMainThread());
     for (unsigned i = 0; i < options.numberOfInputs; ++i)
         addInput();
     for (unsigned i = 0; i < options.numberOfOutputs; ++i)
@@ -109,14 +129,30 @@
 
 AudioWorkletNode::~AudioWorkletNode()
 {
+    ASSERT(isMainThread());
+    {
+        auto locker = holdLock(m_processorLock);
+        if (m_processor) {
+            if (auto* workletProxy = context().audioWorklet().proxy())
+                workletProxy->postTaskForModeToWorkletGlobalScope([m_processor = WTFMove(m_processor)](ScriptExecutionContext&) { }, WorkerRunLoop::defaultMode());
+        }
+    }
     uninitialize();
 }
 
+void AudioWorkletNode::setProcessor(RefPtr<AudioWorkletProcessor>&& processor)
+{
+    ASSERT(!isMainThread());
+    auto locker = holdLock(m_processorLock);
+    m_processor = WTFMove(processor);
+}
+
 void AudioWorkletNode::process(size_t framesToProcess)
 {
+    ASSERT(!isMainThread());
     UNUSED_PARAM(framesToProcess);
 
-    // FIXME: Do actual processing.
+    // FIXME: Do actual processing via m_processor.
     for (unsigned i = 0; i < numberOfOutputs(); ++i)
         output(i)->bus()->zero();
 }

Modified: trunk/Source/WebCore/Modules/webaudio/AudioWorkletNode.h (268160 => 268161)


--- trunk/Source/WebCore/Modules/webaudio/AudioWorkletNode.h	2020-10-07 22:49:20 UTC (rev 268160)
+++ trunk/Source/WebCore/Modules/webaudio/AudioWorkletNode.h	2020-10-07 23:31:25 UTC (rev 268161)
@@ -31,10 +31,12 @@
 #if ENABLE(WEB_AUDIO)
 
 #include "AudioNode.h"
+#include <wtf/Lock.h>
 
 namespace WebCore {
 
 class AudioParamMap;
+class AudioWorkletProcessor;
 class MessagePort;
 
 struct AudioWorkletNodeOptions;
@@ -42,14 +44,16 @@
 class AudioWorkletNode : public AudioNode {
     WTF_MAKE_ISO_ALLOCATED(AudioWorkletNode);
 public:
-    static ExceptionOr<Ref<AudioWorkletNode>> create(BaseAudioContext&, String&& name, AudioWorkletNodeOptions&&);
+    static ExceptionOr<Ref<AudioWorkletNode>> create(JSC::JSGlobalObject&, BaseAudioContext&, String&& name, AudioWorkletNodeOptions&&);
     ~AudioWorkletNode();
 
     AudioParamMap& parameters() { return m_parameters.get(); }
     MessagePort& port() { return m_port.get(); }
 
+    void setProcessor(RefPtr<AudioWorkletProcessor>&&);
+
 private:
-    AudioWorkletNode(BaseAudioContext&, String&& name, AudioWorkletNodeOptions&&, Ref<MessagePort>&&);
+    AudioWorkletNode(BaseAudioContext&, const String& name, AudioWorkletNodeOptions&&, Ref<MessagePort>&&);
 
     // AudioNode.
     void process(size_t framesToProcess) final;
@@ -60,6 +64,8 @@
     String m_name;
     Ref<AudioParamMap> m_parameters;
     Ref<MessagePort> m_port;
+    Lock m_processorLock;
+    RefPtr<AudioWorkletProcessor> m_processor; // Should only be used on the rendering thread.
 };
 
 } // namespace WebCore

Modified: trunk/Source/WebCore/Modules/webaudio/AudioWorkletNode.idl (268160 => 268161)


--- trunk/Source/WebCore/Modules/webaudio/AudioWorkletNode.idl	2020-10-07 22:49:20 UTC (rev 268160)
+++ trunk/Source/WebCore/Modules/webaudio/AudioWorkletNode.idl	2020-10-07 23:31:25 UTC (rev 268161)
@@ -33,7 +33,7 @@
     JSGenerateToJSObject,
     SecureContext
 ] interface AudioWorkletNode : AudioNode {
-    constructor (BaseAudioContext context, DOMString name, optional AudioWorkletNodeOptions options);
+    [CallWith=GlobalObject] constructor (BaseAudioContext context, DOMString name, optional AudioWorkletNodeOptions options);
     readonly attribute AudioParamMap parameters;
     readonly attribute MessagePort port;
     attribute EventHandler onprocessorerror;

Modified: trunk/Source/WebCore/Modules/webaudio/AudioWorkletNodeOptions.idl (268160 => 268161)


--- trunk/Source/WebCore/Modules/webaudio/AudioWorkletNodeOptions.idl	2020-10-07 22:49:20 UTC (rev 268160)
+++ trunk/Source/WebCore/Modules/webaudio/AudioWorkletNodeOptions.idl	2020-10-07 23:31:25 UTC (rev 268161)
@@ -29,6 +29,7 @@
 [
     Conditional=WEB_AUDIO,
     EnabledBySetting=AudioWorklet,
+    JSGenerateToJSObject
 ] dictionary AudioWorkletNodeOptions : AudioNodeOptions {
     unsigned long numberOfInputs = 1;
     unsigned long numberOfOutputs = 1;

Modified: trunk/Source/WebCore/Modules/webaudio/AudioWorkletProcessor.cpp (268160 => 268161)


--- trunk/Source/WebCore/Modules/webaudio/AudioWorkletProcessor.cpp	2020-10-07 22:49:20 UTC (rev 268160)
+++ trunk/Source/WebCore/Modules/webaudio/AudioWorkletProcessor.cpp	2020-10-07 23:31:25 UTC (rev 268161)
@@ -31,12 +31,30 @@
 #if ENABLE(WEB_AUDIO)
 #include "AudioWorkletProcessor.h"
 
+#include "AudioWorkletGlobalScope.h"
+#include "AudioWorkletProcessorConstructionData.h"
+#include "MessagePort.h"
+
 namespace WebCore {
 
-AudioWorkletProcessor::AudioWorkletProcessor()
+ExceptionOr<Ref<AudioWorkletProcessor>> AudioWorkletProcessor::create(ScriptExecutionContext& context)
 {
+    auto constructionData = downcast<AudioWorkletGlobalScope>(context).takePendingProcessorConstructionData();
+    if (!constructionData)
+        return Exception { TypeError, "No pending construction data for this worklet processor"_s };
+
+    return adoptRef(*new AudioWorkletProcessor(*constructionData));
 }
 
+AudioWorkletProcessor::~AudioWorkletProcessor() = default;
+
+AudioWorkletProcessor::AudioWorkletProcessor(const AudioWorkletProcessorConstructionData& constructionData)
+    : m_name(constructionData.name())
+    , m_port(constructionData.port())
+{
+    ASSERT(!isMainThread());
+}
+
 } // namespace WebCore
 
 #endif // ENABLE(WEB_AUDIO)

Modified: trunk/Source/WebCore/Modules/webaudio/AudioWorkletProcessor.h (268160 => 268161)


--- trunk/Source/WebCore/Modules/webaudio/AudioWorkletProcessor.h	2020-10-07 22:49:20 UTC (rev 268160)
+++ trunk/Source/WebCore/Modules/webaudio/AudioWorkletProcessor.h	2020-10-07 23:31:25 UTC (rev 268161)
@@ -29,24 +29,30 @@
 #pragma once
 
 #if ENABLE(WEB_AUDIO)
+#include "ExceptionOr.h"
+#include <wtf/Forward.h>
 #include <wtf/Ref.h>
-#include <wtf/RefCounted.h>
+#include <wtf/ThreadSafeRefCounted.h>
 
 namespace WebCore {
 
+class AudioWorkletProcessorConstructionData;
 class MessagePort;
+class ScriptExecutionContext;
 
-class AudioWorkletProcessor : public RefCounted<AudioWorkletProcessor> {
+class AudioWorkletProcessor : public ThreadSafeRefCounted<AudioWorkletProcessor> {
 public:
-    static Ref<AudioWorkletProcessor> create()
-    {
-        return adoptRef(*new AudioWorkletProcessor);
-    }
+    static ExceptionOr<Ref<AudioWorkletProcessor>> create(ScriptExecutionContext&);
+    ~AudioWorkletProcessor();
 
-    MessagePort* port() { return nullptr; }
+    const String& name() const { return m_name; }
+    MessagePort& port() { return m_port.get(); }
 
 private:
-    AudioWorkletProcessor();
+    explicit AudioWorkletProcessor(const AudioWorkletProcessorConstructionData&);
+
+    String m_name;
+    Ref<MessagePort> m_port;
 };
 
 } // namespace WebCore

Modified: trunk/Source/WebCore/Modules/webaudio/AudioWorkletProcessor.idl (268160 => 268161)


--- trunk/Source/WebCore/Modules/webaudio/AudioWorkletProcessor.idl	2020-10-07 22:49:20 UTC (rev 268160)
+++ trunk/Source/WebCore/Modules/webaudio/AudioWorkletProcessor.idl	2020-10-07 23:31:25 UTC (rev 268161)
@@ -31,6 +31,6 @@
     Exposed=AudioWorklet,
     ImplementationLacksVTable
 ] interface AudioWorkletProcessor {
-    constructor();
+    [CallWith=ScriptExecutionContext, MayThrowException] constructor();
     readonly attribute MessagePort port;
 };

Copied: trunk/Source/WebCore/Modules/webaudio/AudioWorkletProcessorConstructionData.h (from rev 268159, trunk/Source/WebCore/Modules/webaudio/AudioWorkletProcessor.h) (0 => 268161)


--- trunk/Source/WebCore/Modules/webaudio/AudioWorkletProcessorConstructionData.h	                        (rev 0)
+++ trunk/Source/WebCore/Modules/webaudio/AudioWorkletProcessorConstructionData.h	2020-10-07 23:31:25 UTC (rev 268161)
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2020 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1.  Redistributions of source code must retain the above copyright
+ *     notice, this list of conditions and the following disclaimer.
+ * 2.  Redistributions in binary form must reproduce the above copyright
+ *     notice, this list of conditions and the following disclaimer in the
+ *     documentation and/or other materials provided with the distribution.
+ * 3.  Neither the name of Apple Inc. ("Apple") nor the names of
+ *     its contributors may be used to endorse or promote products derived
+ *     from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#pragma once
+
+#if ENABLE(WEB_AUDIO)
+
+#include "MessagePort.h"
+#include <wtf/Ref.h>
+#include <wtf/text/WTFString.h>
+
+namespace WebCore {
+
+class AudioWorkletProcessorConstructionData {
+    WTF_MAKE_FAST_ALLOCATED;
+public:
+    AudioWorkletProcessorConstructionData(String&& name, Ref<MessagePort>&& port)
+        : m_name(WTFMove(name))
+        , m_port(WTFMove(port))
+    { }
+
+    const String& name() const { return m_name; }
+    MessagePort& port() const { return m_port.get(); }
+
+private:
+    String m_name;
+    Ref<MessagePort> m_port;
+};
+
+} // namespace WebCore
+
+#endif // ENABLE(WEB_AUDIO)

Modified: trunk/Source/WebCore/Modules/webaudio/AudioWorkletThread.h (268160 => 268161)


--- trunk/Source/WebCore/Modules/webaudio/AudioWorkletThread.h	2020-10-07 22:49:20 UTC (rev 268160)
+++ trunk/Source/WebCore/Modules/webaudio/AudioWorkletThread.h	2020-10-07 23:31:25 UTC (rev 268161)
@@ -34,7 +34,6 @@
 #include "WorkletParameters.h"
 #include <wtf/Forward.h>
 #include <wtf/Lock.h>
-#include <wtf/ThreadSafeRefCounted.h>
 #include <wtf/Threading.h>
 
 namespace WebCore {
@@ -42,7 +41,7 @@
 class AudioWorkletGlobalScope;
 class AudioWorkletMessagingProxy;
 
-class AudioWorkletThread : public ThreadSafeRefCounted<AudioWorkletThread>, public WorkerOrWorkletThread {
+class AudioWorkletThread : public WorkerOrWorkletThread {
 public:
     static Ref<AudioWorkletThread> create(AudioWorkletMessagingProxy& messagingProxy, const WorkletParameters& parameters)
     {

Modified: trunk/Source/WebCore/WebCore.xcodeproj/project.pbxproj (268160 => 268161)


--- trunk/Source/WebCore/WebCore.xcodeproj/project.pbxproj	2020-10-07 22:49:20 UTC (rev 268160)
+++ trunk/Source/WebCore/WebCore.xcodeproj/project.pbxproj	2020-10-07 23:31:25 UTC (rev 268161)
@@ -2445,6 +2445,7 @@
 		8321507E1F27EA1B0095B136 /* NavigatorBeacon.h in Headers */ = {isa = PBXBuildFile; fileRef = 8321507B1F27EA150095B136 /* NavigatorBeacon.h */; };
 		8326BF8E24D35C33001F8A85 /* OverSampleType.h in Headers */ = {isa = PBXBuildFile; fileRef = 8326BF8924D35C20001F8A85 /* OverSampleType.h */; };
 		8326BF8F24D35C39001F8A85 /* WaveShaperOptions.h in Headers */ = {isa = PBXBuildFile; fileRef = 8326BF8C24D35C20001F8A85 /* WaveShaperOptions.h */; };
+		83274FCF252E26B7001E35DC /* AudioWorkletProcessorConstructionData.h in Headers */ = {isa = PBXBuildFile; fileRef = 83274FCD252E26A8001E35DC /* AudioWorkletProcessorConstructionData.h */; };
 		832B843419D8E55100B26055 /* SVGAnimateElementBase.h in Headers */ = {isa = PBXBuildFile; fileRef = 832B843319D8E55100B26055 /* SVGAnimateElementBase.h */; };
 		833AE52924D386F200017C4B /* OfflineAudioCompletionEventInit.h in Headers */ = {isa = PBXBuildFile; fileRef = 833AE52824D386E100017C4B /* OfflineAudioCompletionEventInit.h */; };
 		833B9E321F508D8500E0E428 /* JSFileSystemDirectoryEntry.h in Headers */ = {isa = PBXBuildFile; fileRef = 833B9E2F1F508D8000E0E428 /* JSFileSystemDirectoryEntry.h */; };
@@ -10610,6 +10611,7 @@
 		8326BF8B24D35C20001F8A85 /* OverSampleType.idl */ = {isa = PBXFileReference; lastKnownFileType = text; path = OverSampleType.idl; sourceTree = "<group>"; };
 		8326BF8C24D35C20001F8A85 /* WaveShaperOptions.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = WaveShaperOptions.h; sourceTree = "<group>"; };
 		8326BF8D24D35C21001F8A85 /* WaveShaperOptions.idl */ = {isa = PBXFileReference; lastKnownFileType = text; path = WaveShaperOptions.idl; sourceTree = "<group>"; };
+		83274FCD252E26A8001E35DC /* AudioWorkletProcessorConstructionData.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AudioWorkletProcessorConstructionData.h; sourceTree = "<group>"; };
 		8329A4171EC25B2B008ED4BE /* DocumentAndElementEventHandlers.idl */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = DocumentAndElementEventHandlers.idl; sourceTree = "<group>"; };
 		8329DCC21C7A6AE300730B33 /* HTMLHyperlinkElementUtils.idl */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = HTMLHyperlinkElementUtils.idl; sourceTree = "<group>"; };
 		832B843319D8E55100B26055 /* SVGAnimateElementBase.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SVGAnimateElementBase.h; sourceTree = "<group>"; };
@@ -28575,6 +28577,8 @@
 				6FB47E612277425A00C7BCB0 /* LayoutIntegrationLine.h */,
 				E4D33F42252C50A800837D05 /* LayoutIntegrationLineIterator.cpp */,
 				E4D33F3F252C4B8200837D05 /* LayoutIntegrationLineIterator.h */,
+				E4D33F43252C50E200837D05 /* LayoutIntegrationLineIteratorLegacyPath.h */,
+				E4D33F45252C50FB00837D05 /* LayoutIntegrationLineIteratorModernPath.h */,
 				E4ABABDE2360893D00FA4345 /* LayoutIntegrationLineLayout.cpp */,
 				E4ABABDB236088FD00FA4345 /* LayoutIntegrationLineLayout.h */,
 				E4312AB524B3265600678349 /* LayoutIntegrationPagination.cpp */,
@@ -28582,8 +28586,6 @@
 				6FCE1A1822618AB3004F0343 /* LayoutIntegrationRun.h */,
 				E4A664C72521B779007081DC /* LayoutIntegrationRunIterator.cpp */,
 				E4A664C62521B778007081DC /* LayoutIntegrationRunIterator.h */,
-				E4D33F43252C50E200837D05 /* LayoutIntegrationLineIteratorLegacyPath.h */,
-				E4D33F45252C50FB00837D05 /* LayoutIntegrationLineIteratorModernPath.h */,
 				E4A664C52521B778007081DC /* LayoutIntegrationRunIteratorLegacyPath.h */,
 				E4A664C42521B777007081DC /* LayoutIntegrationRunIteratorModernPath.h */,
 			);
@@ -30020,6 +30022,7 @@
 				83BB8B5B2526775500D89F0B /* AudioWorkletProcessor.cpp */,
 				83BB8B5D2526775500D89F0B /* AudioWorkletProcessor.h */,
 				83BB8B5E2526775600D89F0B /* AudioWorkletProcessor.idl */,
+				83274FCD252E26A8001E35DC /* AudioWorkletProcessorConstructionData.h */,
 				83726EF8252679B200C6114E /* AudioWorkletProcessorConstructor.h */,
 				83726EFA252679B300C6114E /* AudioWorkletProcessorConstructor.idl */,
 				83FC994A252557E800177618 /* AudioWorkletThread.cpp */,
@@ -30636,6 +30639,7 @@
 				83B9870925225F7200A939F1 /* AudioWorkletNode.h in Headers */,
 				83B9870A25225F7600A939F1 /* AudioWorkletNodeOptions.h in Headers */,
 				83BB8B5F2526776400D89F0B /* AudioWorkletProcessor.h in Headers */,
+				83274FCF252E26B7001E35DC /* AudioWorkletProcessorConstructionData.h in Headers */,
 				83726EFB252679C500C6114E /* AudioWorkletProcessorConstructor.h in Headers */,
 				83FC994B252557EA00177618 /* AudioWorkletThread.h in Headers */,
 				7EE6846112D26E3800E79415 /* AuthenticationChallenge.h in Headers */,
@@ -31547,7 +31551,6 @@
 				371F4FFC0D25E7F300ECE0D5 /* FontRanges.h in Headers */,
 				C2AB0AF71E6B3C6C001348C5 /* FontSelectionAlgorithm.h in Headers */,
 				B2C3DA6B0D006CD600EF6F26 /* FontSelector.h in Headers */,
-				E4D33F46252C50FC00837D05 /* LayoutIntegrationLineIteratorModernPath.h in Headers */,
 				E419041F1CC6486B00C35F5D /* FontSelectorClient.h in Headers */,
 				F48D2A6C215623B400C6752B /* FontShadow.h in Headers */,
 				4A6E9FC813C17D570046A7F8 /* FontTaggedSettings.h in Headers */,
@@ -32928,6 +32931,9 @@
 				E403B7A2251B11930019E800 /* LayoutIntegrationCoverage.h in Headers */,
 				E451C6342394058F00993190 /* LayoutIntegrationInlineContent.h in Headers */,
 				6FB47E632277425A00C7BCB0 /* LayoutIntegrationLine.h in Headers */,
+				E4D33F41252C4B8300837D05 /* LayoutIntegrationLineIterator.h in Headers */,
+				E4D33F44252C50E200837D05 /* LayoutIntegrationLineIteratorLegacyPath.h in Headers */,
+				E4D33F46252C50FC00837D05 /* LayoutIntegrationLineIteratorModernPath.h in Headers */,
 				E4ABABDD236088FE00FA4345 /* LayoutIntegrationLineLayout.h in Headers */,
 				E403B7A3251B11C10019E800 /* LayoutIntegrationPagination.h in Headers */,
 				6FCE1A1A22618ABD004F0343 /* LayoutIntegrationRun.h in Headers */,
@@ -33039,7 +33045,6 @@
 				49D5DC2C0F423A73008F20FD /* Matrix3DTransformOperation.h in Headers */,
 				49E911C70EF86D47009D0CAF /* MatrixTransformOperation.h in Headers */,
 				5CBC8DAD1AAA302200E1C803 /* MediaAccessibilitySoftLink.h in Headers */,
-				E4D33F41252C4B8300837D05 /* LayoutIntegrationLineIterator.h in Headers */,
 				931BCC611124DFCB00BE70DD /* MediaCanStartListener.h in Headers */,
 				CDCC9BCF22387E9A00FFB51C /* MediaCapabilitiesDecodingInfo.h in Headers */,
 				CDCC9BD122387EAA00FFB51C /* MediaCapabilitiesEncodingInfo.h in Headers */,
@@ -34522,7 +34527,6 @@
 				0F1A0C38229A481800D37ADB /* VelocityData.h in Headers */,
 				DF4E38E025279595002A7481 /* VersionChecks.h in Headers */,
 				BCA257151293C010007A263D /* VerticalPositionCache.h in Headers */,
-				E4D33F44252C50E200837D05 /* LayoutIntegrationLineIteratorLegacyPath.h in Headers */,
 				52B0D4C01C57FD660077CE53 /* VideoFullscreenChangeObserver.h in Headers */,
 				3FBC4AF4189881560046EE38 /* VideoFullscreenInterfaceAVKit.h in Headers */,
 				52B0D4C21C57FF910077CE53 /* VideoFullscreenInterfaceMac.h in Headers */,

Modified: trunk/Source/WebCore/bindings/js/JSDOMGlobalObject.cpp (268160 => 268161)


--- trunk/Source/WebCore/bindings/js/JSDOMGlobalObject.cpp	2020-10-07 22:49:20 UTC (rev 268160)
+++ trunk/Source/WebCore/bindings/js/JSDOMGlobalObject.cpp	2020-10-07 23:31:25 UTC (rev 268161)
@@ -48,6 +48,7 @@
 #include "StructuredClone.h"
 #include "WebCoreJSClientData.h"
 #include "WorkerGlobalScope.h"
+#include "WorkletGlobalScope.h"
 #include <_javascript_Core/BuiltinNames.h>
 #include <_javascript_Core/CodeBlock.h>
 #include <_javascript_Core/JSInternalPromise.h>
@@ -345,6 +346,9 @@
     if (is<WorkerGlobalScope>(context))
         return downcast<WorkerGlobalScope>(context).script()->workerGlobalScopeWrapper();
 
+    if (is<WorkletGlobalScope>(context))
+        return downcast<WorkletGlobalScope>(context).script()->workletGlobalScopeWrapper();
+
     ASSERT_NOT_REACHED();
     return nullptr;
 }

Modified: trunk/Source/WebCore/dom/MessagePort.cpp (268160 => 268161)


--- trunk/Source/WebCore/dom/MessagePort.cpp	2020-10-07 22:49:20 UTC (rev 268160)
+++ trunk/Source/WebCore/dom/MessagePort.cpp	2020-10-07 23:31:25 UTC (rev 268161)
@@ -165,7 +165,7 @@
     return { };
 }
 
-void MessagePort::disentangle()
+TransferredMessagePort MessagePort::disentangle()
 {
     ASSERT(m_entangled);
     m_entangled = false;
@@ -180,6 +180,8 @@
     m_scriptExecutionContext->willDestroyDestructionObserver(*this);
 
     m_scriptExecutionContext = nullptr;
+
+    return { identifier(), remoteIdentifier() };
 }
 
 void MessagePort::registerLocalActivity()
@@ -378,10 +380,8 @@
     // Passed-in ports passed validity checks, so we can disentangle them.
     TransferredMessagePortArray portArray;
     portArray.reserveInitialCapacity(ports.size());
-    for (auto& port : ports) {
-        portArray.uncheckedAppend({ port->identifier(), port->remoteIdentifier() });
-        port->disentangle();
-    }
+    for (auto& port : ports)
+        portArray.uncheckedAppend(port->disentangle());
 
     return portArray;
 }
@@ -395,14 +395,18 @@
 
     Vector<RefPtr<MessagePort>> ports;
     ports.reserveInitialCapacity(transferredPorts.size());
-    for (auto& transferredPort : transferredPorts) {
-        auto port = MessagePort::create(context, transferredPort.first, transferredPort.second);
-        port->entangle();
-        ports.uncheckedAppend(WTFMove(port));
-    }
+    for (auto& transferredPort : transferredPorts)
+        ports.uncheckedAppend(MessagePort::entangle(context, WTFMove(transferredPort)));
     return ports;
 }
 
+Ref<MessagePort> MessagePort::entangle(ScriptExecutionContext& context, TransferredMessagePort&& transferredPort)
+{
+    auto port = MessagePort::create(context, transferredPort.first, transferredPort.second);
+    port->entangle();
+    return port;
+}
+
 bool MessagePort::addEventListener(const AtomString& eventType, Ref<EventListener>&& listener, const AddEventListenerOptions& options)
 {
     if (eventType == eventNames().messageEvent) {

Modified: trunk/Source/WebCore/dom/MessagePort.h (268160 => 268161)


--- trunk/Source/WebCore/dom/MessagePort.h	2020-10-07 22:49:20 UTC (rev 268160)
+++ trunk/Source/WebCore/dom/MessagePort.h	2020-10-07 23:31:25 UTC (rev 268161)
@@ -92,6 +92,9 @@
 
     void dispatchEvent(Event&) final;
 
+    TransferredMessagePort disentangle();
+    static Ref<MessagePort> entangle(ScriptExecutionContext&, TransferredMessagePort&&);
+
 private:
     explicit MessagePort(ScriptExecutionContext&, const MessagePortIdentifier& local, const MessagePortIdentifier& remote);
 
@@ -104,8 +107,6 @@
     void stop() final { close(); }
     bool virtualHasPendingActivity() const final;
 
-    void disentangle();
-
     void registerLocalActivity();
 
     // A port starts out its life entangled, and remains entangled until it is closed or is cloned.

Modified: trunk/Source/WebCore/dom/ScriptExecutionContext.cpp (268160 => 268161)


--- trunk/Source/WebCore/dom/ScriptExecutionContext.cpp	2020-10-07 22:49:20 UTC (rev 268160)
+++ trunk/Source/WebCore/dom/ScriptExecutionContext.cpp	2020-10-07 23:31:25 UTC (rev 268161)
@@ -28,6 +28,8 @@
 #include "config.h"
 #include "ScriptExecutionContext.h"
 
+#include "AudioWorkletGlobalScope.h"
+#include "AudioWorkletThread.h"
 #include "CachedScript.h"
 #include "CommonVM.h"
 #include "DOMTimer.h"
@@ -205,7 +207,11 @@
 void ScriptExecutionContext::createdMessagePort(MessagePort& messagePort)
 {
     ASSERT((is<Document>(*this) && isMainThread())
-        || (is<WorkerGlobalScope>(*this) && downcast<WorkerGlobalScope>(*this).thread().thread() == &Thread::current()));
+        || (is<WorkerGlobalScope>(*this) && downcast<WorkerGlobalScope>(*this).thread().thread() == &Thread::current())
+#if ENABLE(WEB_AUDIO)
+        || (is<AudioWorkletGlobalScope>(*this) && downcast<AudioWorkletGlobalScope>(*this).thread().thread() == &Thread::current())
+#endif
+        );
 
     m_messagePorts.add(&messagePort);
 }
@@ -213,8 +219,11 @@
 void ScriptExecutionContext::destroyedMessagePort(MessagePort& messagePort)
 {
     ASSERT((is<Document>(*this) && isMainThread())
-        || (is<WorkerGlobalScope>(*this) && downcast<WorkerGlobalScope>(*this).thread().thread() == &Thread::current()));
-
+        || (is<WorkerGlobalScope>(*this) && downcast<WorkerGlobalScope>(*this).thread().thread() == &Thread::current())
+#if ENABLE(WEB_AUDIO)
+        || (is<AudioWorkletGlobalScope>(*this) && downcast<AudioWorkletGlobalScope>(*this).thread().thread() == &Thread::current())
+#endif
+        );
     m_messagePorts.remove(&messagePort);
 }
 

Modified: trunk/Source/WebCore/dom/messageports/MessagePortChannelProvider.cpp (268160 => 268161)


--- trunk/Source/WebCore/dom/messageports/MessagePortChannelProvider.cpp	2020-10-07 22:49:20 UTC (rev 268160)
+++ trunk/Source/WebCore/dom/messageports/MessagePortChannelProvider.cpp	2020-10-07 23:31:25 UTC (rev 268161)
@@ -29,6 +29,7 @@
 #include "Document.h"
 #include "MessagePortChannelProviderImpl.h"
 #include "WorkerGlobalScope.h"
+#include "WorkletGlobalScope.h"
 #include <wtf/MainThread.h>
 
 namespace WebCore {
@@ -59,6 +60,9 @@
     if (is<Document>(context))
         return downcast<Document>(context).messagePortChannelProvider();
 
+    if (is<WorkletGlobalScope>(context))
+        return downcast<WorkletGlobalScope>(context).messagePortChannelProvider();
+
     return downcast<WorkerGlobalScope>(context).messagePortChannelProvider();
 }
 

Modified: trunk/Source/WebCore/dom/messageports/MessageWithMessagePorts.h (268160 => 268161)


--- trunk/Source/WebCore/dom/messageports/MessageWithMessagePorts.h	2020-10-07 22:49:20 UTC (rev 268160)
+++ trunk/Source/WebCore/dom/messageports/MessageWithMessagePorts.h	2020-10-07 23:31:25 UTC (rev 268161)
@@ -33,7 +33,8 @@
 
 // When a message port is transferred, it is represented by a pair of identifiers.
 // The first identifier is the port being transferred and the second is its remote port.
-typedef Vector<std::pair<WebCore::MessagePortIdentifier, WebCore::MessagePortIdentifier>> TransferredMessagePortArray;
+using TransferredMessagePort = std::pair<WebCore::MessagePortIdentifier, WebCore::MessagePortIdentifier>;
+using TransferredMessagePortArray = Vector<TransferredMessagePort>;
 
 struct MessageWithMessagePorts {
     RefPtr<SerializedScriptValue> message;

Modified: trunk/Source/WebCore/dom/messageports/WorkerMessagePortChannelProvider.cpp (268160 => 268161)


--- trunk/Source/WebCore/dom/messageports/WorkerMessagePortChannelProvider.cpp	2020-10-07 22:49:20 UTC (rev 268160)
+++ trunk/Source/WebCore/dom/messageports/WorkerMessagePortChannelProvider.cpp	2020-10-07 23:31:25 UTC (rev 268161)
@@ -27,7 +27,7 @@
 #include "WorkerMessagePortChannelProvider.h"
 
 #include "MessagePort.h"
-#include "WorkerGlobalScope.h"
+#include "WorkerOrWorkletGlobalScope.h"
 #include "WorkerThread.h"
 #include <wtf/MainThread.h>
 #include <wtf/RunLoop.h>
@@ -34,7 +34,7 @@
 
 namespace WebCore {
 
-WorkerMessagePortChannelProvider::WorkerMessagePortChannelProvider(WorkerGlobalScope& scope)
+WorkerMessagePortChannelProvider::WorkerMessagePortChannelProvider(WorkerOrWorkletGlobalScope& scope)
     : m_scope(scope)
 {
 }
@@ -91,10 +91,9 @@
     uint64_t callbackIdentifier = ++m_lastCallbackIdentifier;
     m_takeAllMessagesCallbacks.add(callbackIdentifier, WTFMove(callback));
 
-    callOnMainThread([this, workerThread = makeRef(m_scope.thread()), callbackIdentifier, identifier]() mutable {
+    callOnMainThread([this, workerThread = makeRefPtr(m_scope.workerOrWorkletThread()), callbackIdentifier, identifier]() mutable {
         MessagePortChannelProvider::singleton().takeAllMessagesForPort(identifier, [this, workerThread = WTFMove(workerThread), callbackIdentifier](Vector<MessageWithMessagePorts>&& messages, Function<void()>&& completionHandler) {
-            workerThread->runLoop().postTaskForMode([this, callbackIdentifier, messages = WTFMove(messages), completionHandler = WTFMove(completionHandler)](auto& scope) mutable {
-                ASSERT_UNUSED(scope, this == &downcast<WorkerGlobalScope>(scope).messagePortChannelProvider());
+            workerThread->runLoop().postTaskForMode([this, callbackIdentifier, messages = WTFMove(messages), completionHandler = WTFMove(completionHandler)](auto&) mutable {
                 m_takeAllMessagesCallbacks.take(callbackIdentifier)(WTFMove(messages), [completionHandler = WTFMove(completionHandler)]() mutable {
                     callOnMainThread(WTFMove(completionHandler));
                 });
@@ -108,10 +107,9 @@
     uint64_t callbackIdentifier = ++m_lastCallbackIdentifier;
     m_activityCallbacks.add(callbackIdentifier, WTFMove(callback));
 
-    callOnMainThread([this, workerThread = makeRef(m_scope.thread()), callbackIdentifier, remoteTarget]() mutable {
+    callOnMainThread([this, workerThread = makeRefPtr(m_scope.workerOrWorkletThread()), callbackIdentifier, remoteTarget]() mutable {
         MessagePortChannelProvider::singleton().checkRemotePortForActivity(remoteTarget, [this, workerThread = WTFMove(workerThread), callbackIdentifier](auto hasActivity) {
-            workerThread->runLoop().postTaskForMode([this, callbackIdentifier, hasActivity](auto& scope) mutable {
-                ASSERT_UNUSED(scope, this == &downcast<WorkerGlobalScope>(scope).messagePortChannelProvider());
+            workerThread->runLoop().postTaskForMode([this, callbackIdentifier, hasActivity](auto&) mutable {
                 m_activityCallbacks.take(callbackIdentifier)(hasActivity);
             }, WorkerRunLoop::defaultMode());
         });

Modified: trunk/Source/WebCore/dom/messageports/WorkerMessagePortChannelProvider.h (268160 => 268161)


--- trunk/Source/WebCore/dom/messageports/WorkerMessagePortChannelProvider.h	2020-10-07 22:49:20 UTC (rev 268160)
+++ trunk/Source/WebCore/dom/messageports/WorkerMessagePortChannelProvider.h	2020-10-07 23:31:25 UTC (rev 268161)
@@ -32,12 +32,12 @@
 
 namespace WebCore {
 
-class WorkerGlobalScope;
+class WorkerOrWorkletGlobalScope;
 
 class WorkerMessagePortChannelProvider final : public MessagePortChannelProvider {
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    explicit WorkerMessagePortChannelProvider(WorkerGlobalScope&);
+    explicit WorkerMessagePortChannelProvider(WorkerOrWorkletGlobalScope&);
     ~WorkerMessagePortChannelProvider();
 
 private:
@@ -49,7 +49,7 @@
     void takeAllMessagesForPort(const MessagePortIdentifier&, CompletionHandler<void(Vector<MessageWithMessagePorts>&&, Function<void()>&&)>&&) final;
     void checkRemotePortForActivity(const MessagePortIdentifier& remoteTarget, CompletionHandler<void(HasActivity)>&& callback) final;
 
-    WorkerGlobalScope& m_scope;
+    WorkerOrWorkletGlobalScope& m_scope;
 
     uint64_t m_lastCallbackIdentifier { 0 };
     HashMap<uint64_t, CompletionHandler<void(Vector<MessageWithMessagePorts>&&, Function<void()>&&)>> m_takeAllMessagesCallbacks;

Modified: trunk/Source/WebCore/workers/WorkerOrWorkletThread.h (268160 => 268161)


--- trunk/Source/WebCore/workers/WorkerOrWorkletThread.h	2020-10-07 22:49:20 UTC (rev 268160)
+++ trunk/Source/WebCore/workers/WorkerOrWorkletThread.h	2020-10-07 23:31:25 UTC (rev 268161)
@@ -25,6 +25,8 @@
 
 #pragma once
 
+#include <wtf/ThreadSafeRefCounted.h>
+
 namespace WTF {
 class Thread;
 }
@@ -34,7 +36,7 @@
 class WorkerLoaderProxy;
 class WorkerRunLoop;
 
-class WorkerOrWorkletThread {
+class WorkerOrWorkletThread : public ThreadSafeRefCounted<WorkerOrWorkletThread> {
 public:
     virtual ~WorkerOrWorkletThread() = default;
 

Modified: trunk/Source/WebCore/workers/WorkerThread.h (268160 => 268161)


--- trunk/Source/WebCore/workers/WorkerThread.h	2020-10-07 22:49:20 UTC (rev 268160)
+++ trunk/Source/WebCore/workers/WorkerThread.h	2020-10-07 23:31:25 UTC (rev 268161)
@@ -76,7 +76,7 @@
     WorkerParameters isolatedCopy() const;
 };
 
-class WorkerThread : public ThreadSafeRefCounted<WorkerThread>, public WorkerOrWorkletThread {
+class WorkerThread : public WorkerOrWorkletThread {
 public:
     virtual ~WorkerThread();
 

Modified: trunk/Source/WebCore/worklets/WorkletGlobalScope.cpp (268160 => 268161)


--- trunk/Source/WebCore/worklets/WorkletGlobalScope.cpp	2020-10-07 22:49:20 UTC (rev 268160)
+++ trunk/Source/WebCore/worklets/WorkletGlobalScope.cpp	2020-10-07 23:31:25 UTC (rev 268161)
@@ -34,6 +34,7 @@
 #include "SecurityOriginPolicy.h"
 #include "Settings.h"
 #include "WorkerEventLoop.h"
+#include "WorkerMessagePortChannelProvider.h"
 #include "WorkerScriptLoader.h"
 #include "WorkletParameters.h"
 #include <_javascript_Core/Exception.h>
@@ -227,10 +228,14 @@
     }
 
     // FIXME: This should really be run as a module script but we don't support this in workers yet.
-    NakedPtr<JSC::Exception> exception;
-    m_script->evaluate(ScriptSourceCode(m_scriptLoader->script(), URL(m_scriptLoader->responseURL())), exception);
-    if (exception)
-        m_script->setException(exception);
+    URL moduleURL(m_scriptLoader->responseURL());
+    auto addResult = m_evaluatedModules.add(moduleURL);
+    if (addResult.isNewEntry) {
+        NakedPtr<JSC::Exception> exception;
+        m_script->evaluate(ScriptSourceCode(m_scriptLoader->script(), WTFMove(moduleURL)), exception);
+        if (exception)
+            m_script->setException(exception);
+    }
 
     didCompleteScriptFetchJob(WTFMove(completedJob), { });
 }
@@ -244,4 +249,11 @@
     processNextScriptFetchJobIfNeeded();
 }
 
+MessagePortChannelProvider& WorkletGlobalScope::messagePortChannelProvider()
+{
+    if (!m_messagePortChannelProvider)
+        m_messagePortChannelProvider = makeUnique<WorkerMessagePortChannelProvider>(*this);
+    return *m_messagePortChannelProvider;
+}
+
 } // namespace WebCore

Modified: trunk/Source/WebCore/worklets/WorkletGlobalScope.h (268160 => 268161)


--- trunk/Source/WebCore/worklets/WorkletGlobalScope.h	2020-10-07 22:49:20 UTC (rev 268160)
+++ trunk/Source/WebCore/worklets/WorkletGlobalScope.h	2020-10-07 23:31:25 UTC (rev 268161)
@@ -48,7 +48,9 @@
 namespace WebCore {
 
 class EventLoopTaskGroup;
+class MessagePortChannelProvider;
 class WorkerEventLoop;
+class WorkerMessagePortChannelProvider;
 class WorkerScriptLoader;
 
 struct WorkletParameters;
@@ -71,6 +73,8 @@
     virtual bool isAudioWorkletGlobalScope() const { return false; }
 #endif
 
+    MessagePortChannelProvider& messagePortChannelProvider();
+
     EventLoopTaskGroup& eventLoop() final;
 
     const URL& url() const final { return m_url; }
@@ -176,8 +180,11 @@
     JSC::RuntimeFlags m_jsRuntimeFlags;
     Optional<ScriptSourceCode> m_code;
 
+    std::unique_ptr<WorkerMessagePortChannelProvider> m_messagePortChannelProvider;
+
     RefPtr<WorkerScriptLoader> m_scriptLoader;
     Deque<ScriptFetchJob> m_scriptFetchJobs;
+    HashSet<URL> m_evaluatedModules;
 
     bool m_isClosing { false };
 };
_______________________________________________
webkit-changes mailing list
webkit-changes@lists.webkit.org
https://lists.webkit.org/mailman/listinfo/webkit-changes

Reply via email to