File: audio_worklet_global_scope.cc

package info (click to toggle)
chromium 139.0.7258.138-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,120,676 kB
  • sloc: cpp: 35,100,869; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (305 lines) | stat: -rw-r--r-- 12,540 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "third_party/blink/renderer/modules/webaudio/audio_worklet_global_scope.h"

#include <memory>
#include <utility>

#include "base/auto_reset.h"
#include "third_party/blink/renderer/bindings/core/v8/idl_types.h"
#include "third_party/blink/renderer/bindings/core/v8/native_value_traits_impl.h"
#include "third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.h"
#include "third_party/blink/renderer/bindings/core/v8/serialization/unpacked_serialized_script_value.h"
#include "third_party/blink/renderer/bindings/core/v8/worker_or_worklet_script_controller.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_audio_worklet_processor.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_blink_audio_worklet_process_callback.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_blink_audio_worklet_processor_constructor.h"
#include "third_party/blink/renderer/core/workers/global_scope_creation_params.h"
#include "third_party/blink/renderer/core/workers/worker_backing_thread.h"
#include "third_party/blink/renderer/core/workers/worker_thread.h"
#include "third_party/blink/renderer/modules/webaudio/audio_worklet_object_proxy.h"
#include "third_party/blink/renderer/modules/webaudio/audio_worklet_processor.h"
#include "third_party/blink/renderer/modules/webaudio/audio_worklet_processor_definition.h"
#include "third_party/blink/renderer/modules/webaudio/cross_thread_audio_worklet_processor_info.h"
#include "third_party/blink/renderer/platform/audio/denormal_disabler.h"
#include "third_party/blink/renderer/platform/bindings/callback_method_retriever.h"
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"
#include "third_party/blink/renderer/platform/wtf/text/strcat.h"

namespace blink {

AudioWorkletGlobalScope::AudioWorkletGlobalScope(
    std::unique_ptr<GlobalScopeCreationParams> creation_params,
    WorkerThread* thread)
    : WorkletGlobalScope(std::move(creation_params),
                         thread->GetWorkerReportingProxy(),
                         thread) {
  // Disable denormals for performance.
  DenormalModifier::DisableDenormals();

  // Audio is prone to jank introduced by e.g. the garbage collector. Workers
  // are generally put in a background mode (as they are non-visible). Audio is
  // an exception here, requiring low-latency behavior similar to any visible
  // state.
  GetThread()->GetWorkerBackingThread().SetForegrounded();
}

AudioWorkletGlobalScope::~AudioWorkletGlobalScope() = default;

void AudioWorkletGlobalScope::Dispose() {
  DCHECK(IsContextThread());
  object_proxy_ = nullptr;
  is_closing_ = true;
  WorkletGlobalScope::Dispose();
}

void AudioWorkletGlobalScope::registerProcessor(
    const String& name,
    V8BlinkAudioWorkletProcessorConstructor* processor_ctor,
    ExceptionState& exception_state) {
  DCHECK(IsContextThread());

  // 1. If name is an empty string, throw a NotSupportedError.
  if (name.empty()) {
    exception_state.ThrowDOMException(DOMExceptionCode::kNotSupportedError,
                                      "The processor name cannot be empty.");
    return;
  }

  // 2. If name already exists as a key in the node name to processor
  //    constructor map, throw a NotSupportedError.
  if (processor_definition_map_.Contains(name)) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kNotSupportedError,
        StrCat({"An AudioWorkletProcessor with name:\"", name,
                "\" is already registered."}));
    return;
  }

  // 3. If the result of IsConstructor(argument=processorCtor) is false, throw
  //    a TypeError .
  if (!processor_ctor->IsConstructor()) {
    exception_state.ThrowTypeError(
        StrCat({"The provided class definition of \"", name,
                "\" AudioWorkletProcessor is not a constructor."}));
    return;
  }

  // 4. Let prototype be the result of Get(O=processorCtor, P="prototype").
  // 5. If the result of Type(argument=prototype) is not Object, throw a
  //    TypeError .
  CallbackMethodRetriever retriever(processor_ctor);
  retriever.GetPrototypeObject(exception_state);
  if (exception_state.HadException()) {
    return;
  }

  // The sufficient information to build a AudioWorkletProcessorDefinition
  // is collected. The rest of registration process is optional.
  // (i.e. parameterDescriptors)
  AudioWorkletProcessorDefinition* definition =
      AudioWorkletProcessorDefinition::Create(name, processor_ctor);

  // 6. Let parameterDescriptorsValue be the result of Get(O=processorCtor,
  //    P="parameterDescriptors").
  v8::Isolate* isolate = processor_ctor->GetIsolate();
  v8::Local<v8::Context> current_context = isolate->GetCurrentContext();
  v8::Local<v8::Value> v8_parameter_descriptors;
  {
    TryRethrowScope rethrow_scope(isolate, exception_state);
    if (!processor_ctor->CallbackObject()
             ->Get(current_context,
                   V8AtomicString(isolate, "parameterDescriptors"))
             .ToLocal(&v8_parameter_descriptors)) {
      return;
    }
  }

  // 7. If parameterDescriptorsValue is not undefined, execute the following
  //    steps:
  if (!v8_parameter_descriptors->IsNullOrUndefined()) {
    // 7.1. Let parameterDescriptorSequence be the result of the conversion
    //      from parameterDescriptorsValue to an IDL value of type
    //      sequence<AudioParamDescriptor>.
    const HeapVector<Member<AudioParamDescriptor>>& given_param_descriptors =
        NativeValueTraits<IDLSequence<AudioParamDescriptor>>::NativeValue(
            isolate, v8_parameter_descriptors, exception_state);
    if (exception_state.HadException()) {
      return;
    }

    // 7.2. Let paramNames be an empty Array.
    HeapVector<Member<AudioParamDescriptor>> sanitized_param_descriptors;

    // 7.3. For each descriptor of parameterDescriptorSequence:
    HashSet<String> sanitized_names;
    for (const auto& given_descriptor : given_param_descriptors) {
      const String new_param_name = given_descriptor->name();
      if (!sanitized_names.insert(new_param_name).is_new_entry) {
        exception_state.ThrowDOMException(
            DOMExceptionCode::kNotSupportedError,
            StrCat(
                {"Found a duplicate name \"", new_param_name,
                 "\" in parameterDescriptors() from the AudioWorkletProcessor "
                 "definition of \"",
                 name, "\"."}));
        return;
      }

      // 7.3.3 - 7.3.6. Inspect default value range within [minValue, maxValue].
      float default_value = given_descriptor->defaultValue();
      float min_value = given_descriptor->minValue();
      float max_value = given_descriptor->maxValue();
      if ((default_value < min_value) || (default_value > max_value)) {
        exception_state.ThrowDOMException(
            DOMExceptionCode::kInvalidStateError,
            StrCat({"The default value, ", String::Number(default_value),
                    ", in \"", new_param_name,
                    "\" parameterDescriptors() from the AudioWorkletProcessor "
                    "is out of the range [",
                    String::Number(min_value), ", ", String::Number(max_value),
                    "]."}));
        return;
      }

      sanitized_param_descriptors.push_back(given_descriptor);
    }

    definition->SetAudioParamDescriptors(sanitized_param_descriptors);
  }

  // 8. Append the key-value pair name → processorCtor to node name to
  //    processor constructor map of the associated AudioWorkletGlobalScope.
  processor_definition_map_.Set(name, definition);

  // 9. Queue a media element task to append the key-value pair name →
  // parameterDescriptorSequence to the node name to parameter descriptor map
  // of the associated BaseAudioContext.
  if (object_proxy_) {
    // TODO(crbug.com/1223178): `object_proxy_` is designed to outlive the
    // global scope, so we don't need to null check but the unit test is not
    // able to replicate the cross-thread messaging logic yet, so we skip this
    // call in unit tests.
    object_proxy_->SynchronizeProcessorInfoList();
  }
}

AudioWorkletProcessor* AudioWorkletGlobalScope::CreateProcessor(
    const String& name,
    MessagePortChannel message_port_channel,
    scoped_refptr<SerializedScriptValue> node_options) {
  DCHECK(IsContextThread());

  // The registered definition is already checked by AudioWorkletNode
  // construction process, so the `definition` here must be valid.
  AudioWorkletProcessorDefinition* definition = FindDefinition(name);
  DCHECK(definition);

  ScriptState* script_state = ScriptController()->GetScriptState();
  ScriptState::Scope scope(script_state);

  // V8 object instance construction: this construction process is here to make
  // the AudioWorkletProcessor class a thin wrapper of v8::Object instance.
  v8::Isolate* isolate = script_state->GetIsolate();
  v8::TryCatch try_catch(isolate);
  try_catch.SetVerbose(true);  // Route errors/exceptions to the dev console.

  DCHECK(!processor_creation_params_);
  // There is no way to pass additional constructor arguments that are not
  // described in Web IDL, the static constructor will look up
  // `processor_creation_params_` in the global scope to perform the
  // construction properly.
  base::AutoReset<std::unique_ptr<ProcessorCreationParams>>
      processor_creation_extra_param(
          &processor_creation_params_,
          std::make_unique<ProcessorCreationParams>(
              name, std::move(message_port_channel)));

  // Make sure that the transferred `node_options` is deserializable.
  // See https://crbug.com/1429681 for details.
  if (!node_options->CanDeserializeIn(this)) {
    AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>(
        mojom::blink::ConsoleMessageSource::kOther,
        mojom::blink::ConsoleMessageLevel::kWarning,
        "Transferred AudioWorkletNodeOptions could not be deserialized because "
        "it contains an object of a type not available in "
        "AudioWorkletGlobalScope. See https://crbug.com/1429681 for details."));
    return nullptr;
  }

  UnpackedSerializedScriptValue* unpacked_node_options =
      MakeGarbageCollected<UnpackedSerializedScriptValue>(
          std::move(node_options));
  ScriptValue deserialized_options(
      isolate, unpacked_node_options->Deserialize(isolate));

  ScriptValue instance;
  if (!definition->ConstructorFunction()->Construct(deserialized_options)
          .To(&instance)) {
    return nullptr;
  }

  // ToImplWithTypeCheck() may return nullptr when the type does not match.
  AudioWorkletProcessor* processor =
      V8AudioWorkletProcessor::ToWrappable(isolate, instance.V8Value());

  return processor;
}

AudioWorkletProcessorDefinition* AudioWorkletGlobalScope::FindDefinition(
    const String& name) {
  const auto it = processor_definition_map_.find(name);
  if (it == processor_definition_map_.end()) {
    return nullptr;
  }
  return it->value.Get();
}

unsigned AudioWorkletGlobalScope::NumberOfRegisteredDefinitions() {
  return processor_definition_map_.size();
}

std::unique_ptr<Vector<CrossThreadAudioWorkletProcessorInfo>>
AudioWorkletGlobalScope::WorkletProcessorInfoListForSynchronization() {
  auto processor_info_list =
      std::make_unique<Vector<CrossThreadAudioWorkletProcessorInfo>>();
  for (auto definition_entry : processor_definition_map_) {
    if (!definition_entry.value->IsSynchronized()) {
      definition_entry.value->MarkAsSynchronized();
      processor_info_list->emplace_back(*definition_entry.value);
    }
  }
  return processor_info_list;
}

std::unique_ptr<ProcessorCreationParams>
AudioWorkletGlobalScope::GetProcessorCreationParams() {
  return std::move(processor_creation_params_);
}

void AudioWorkletGlobalScope::SetCurrentFrame(size_t current_frame) {
  current_frame_ = current_frame;
}

void AudioWorkletGlobalScope::SetSampleRate(float sample_rate) {
  sample_rate_ = sample_rate;
}

double AudioWorkletGlobalScope::currentTime() const {
  return sample_rate_ > 0.0 ? current_frame_ / static_cast<double>(sample_rate_)
                            : 0.0;
}

void AudioWorkletGlobalScope::SetObjectProxy(
    AudioWorkletObjectProxy& object_proxy) {
  object_proxy_ = &object_proxy;
}

void AudioWorkletGlobalScope::Trace(Visitor* visitor) const {
  visitor->Trace(processor_definition_map_);
  WorkletGlobalScope::Trace(visitor);
}

}  // namespace blink