Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(306)

Side by Side Diff: Source/modules/webaudio/OfflineAudioContext.cpp

Issue 1140723003: Implement suspend() and resume() for OfflineAudioContext (Closed) Base URL: https://chromium.googlesource.com/chromium/blink.git@master
Patch Set: Using raw pointer again with the manual reference management. Created 5 years, 5 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 /* 1 /*
2 * Copyright (C) 2012, Google Inc. All rights reserved. 2 * Copyright (C) 2012, Google Inc. All rights reserved.
3 * 3 *
4 * Redistribution and use in source and binary forms, with or without 4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions 5 * modification, are permitted provided that the following conditions
6 * are met: 6 * are met:
7 * 1. Redistributions of source code must retain the above copyright 7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer. 8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright 9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the 10 * notice, this list of conditions and the following disclaimer in the
(...skipping 14 matching lines...) Expand all
25 #include "config.h" 25 #include "config.h"
26 #if ENABLE(WEB_AUDIO) 26 #if ENABLE(WEB_AUDIO)
27 #include "modules/webaudio/OfflineAudioContext.h" 27 #include "modules/webaudio/OfflineAudioContext.h"
28 28
29 #include "bindings/core/v8/ExceptionMessages.h" 29 #include "bindings/core/v8/ExceptionMessages.h"
30 #include "bindings/core/v8/ExceptionState.h" 30 #include "bindings/core/v8/ExceptionState.h"
31 #include "bindings/core/v8/ScriptState.h" 31 #include "bindings/core/v8/ScriptState.h"
32 #include "core/dom/Document.h" 32 #include "core/dom/Document.h"
33 #include "core/dom/ExceptionCode.h" 33 #include "core/dom/ExceptionCode.h"
34 #include "core/dom/ExecutionContext.h" 34 #include "core/dom/ExecutionContext.h"
35 #include "modules/webaudio/OfflineAudioCompletionEvent.h"
36 #include "modules/webaudio/OfflineAudioDestinationNode.h"
37 #include "platform/Task.h"
38 #include "platform/ThreadSafeFunctional.h"
35 #include "platform/audio/AudioUtilities.h" 39 #include "platform/audio/AudioUtilities.h"
40 #include "public/platform/Platform.h"
41
36 42
37 namespace blink { 43 namespace blink {
38 44
39 OfflineAudioContext* OfflineAudioContext::create(ExecutionContext* context, unsi gned numberOfChannels, size_t numberOfFrames, float sampleRate, ExceptionState& exceptionState) 45 OfflineAudioContext* OfflineAudioContext::create(ExecutionContext* context, unsi gned numberOfChannels, size_t numberOfFrames, float sampleRate, ExceptionState& exceptionState)
40 { 46 {
41 // FIXME: add support for workers. 47 // FIXME: add support for workers.
42 if (!context || !context->isDocument()) { 48 if (!context || !context->isDocument()) {
43 exceptionState.throwDOMException( 49 exceptionState.throwDOMException(
44 NotSupportedError, 50 NotSupportedError,
45 "Workers are not supported."); 51 "Workers are not supported.");
(...skipping 40 matching lines...) Expand 10 before | Expand all | Expand 10 after
86 + ", " + String::number(sampleRate) 92 + ", " + String::number(sampleRate)
87 + ")"); 93 + ")");
88 } 94 }
89 95
90 audioContext->suspendIfNeeded(); 96 audioContext->suspendIfNeeded();
91 return audioContext; 97 return audioContext;
92 } 98 }
93 99
94 OfflineAudioContext::OfflineAudioContext(Document* document, unsigned numberOfCh annels, size_t numberOfFrames, float sampleRate) 100 OfflineAudioContext::OfflineAudioContext(Document* document, unsigned numberOfCh annels, size_t numberOfFrames, float sampleRate)
95 : AbstractAudioContext(document, numberOfChannels, numberOfFrames, sampleRat e) 101 : AbstractAudioContext(document, numberOfChannels, numberOfFrames, sampleRat e)
102 , m_isRenderingStarted(false)
103 , m_totalRenderFrames(numberOfFrames)
96 { 104 {
97 } 105 }
98 106
99 OfflineAudioContext::~OfflineAudioContext() 107 OfflineAudioContext::~OfflineAudioContext()
100 { 108 {
109 // Reject all the remaining suspends and delete the raw pointer.
110 for (ScheduledSuspendContainer* suspendContainer : m_suspendContainers) {
111 suspendContainer->rejectPromise(InvalidStateError,
112 "Offline audio context is going away");
113
114 delete suspendContainer;
115 }
116
117 // TODO(hongchan): is this necessary?
118 m_suspendContainers.clear();
119 }
120
121 DEFINE_TRACE(OfflineAudioContext)
122 {
123 visitor->trace(m_completeResolver);
124 AbstractAudioContext::trace(visitor);
125 }
126
127 bool OfflineAudioContext::shouldSuspendNow()
128 {
129 ASSERT(!isMainThread());
130
131 // If there is any scheduled suspend at |currentSampleFrame|, the context
132 // should be suspended.
133 if (!m_scheduledSuspends.contains(currentSampleFrame()))
134 return false;
135
136 return true;
137 }
138
139 void OfflineAudioContext::resolvePendingSuspendPromises()
140 {
141 ASSERT(!isMainThread());
142
143 // Find a suspend scheduled at |currentSampleFrame| and resolve the
144 // associated promise on the main thread.
145 SuspendContainerMap::iterator it = m_scheduledSuspends.find(currentSampleFra me());
146 if (it == m_scheduledSuspends.end())
147 return;
148
149 ScheduledSuspendContainer* suspendContainer = it->value;
150 m_scheduledSuspends.remove(it);
151
152 // Passing a raw pointer |suspendContainer| is safe here because it is
153 // created and destructed on the main thread. Also it is guaranteed to
154 // be alive until the task is finished somewhere else.
hiroshige 2015/07/22 17:32:12 How about: Passing a raw pointer |suspendContainer
hongchan 2015/07/22 20:36:35 Done.
155 Platform::current()->mainThread()->postTask(FROM_HERE,
156 threadSafeBind(&OfflineAudioContext::resolveSuspendContainerOnMainThread , this,
157 AllowCrossThreadAccess(suspendContainer)));
158 }
159
160 void OfflineAudioContext::fireCompletionEvent()
161 {
162 ASSERT(isMainThread());
163
164 // We set the state to closed here so that the oncomplete event handler sees
165 // that the context has been closed.
166 setContextState(Closed);
167
168 AudioBuffer* renderedBuffer = renderTarget();
169
170 ASSERT(renderedBuffer);
171 if (!renderedBuffer)
172 return;
173
174 // Avoid firing the event if the document has already gone away.
175 if (executionContext()) {
176 // Call the offline rendering completion event listener and resolve the
177 // promise too.
178 dispatchEvent(OfflineAudioCompletionEvent::create(renderedBuffer));
179 m_completeResolver->resolve(renderedBuffer);
180 } else {
181 // The resolver should be rejected when the execution context is gone.
182 m_completeResolver->reject(DOMException::create(InvalidStateError,
183 "the execution context does not exist"));
184 }
101 } 185 }
102 186
103 ScriptPromise OfflineAudioContext::startOfflineRendering(ScriptState* scriptStat e) 187 ScriptPromise OfflineAudioContext::startOfflineRendering(ScriptState* scriptStat e)
104 { 188 {
189 ASSERT(isMainThread());
190
105 // Calling close() on an OfflineAudioContext is not supported/allowed, 191 // Calling close() on an OfflineAudioContext is not supported/allowed,
106 // but it might well have been stopped by its execution context. 192 // but it might well have been closed by its execution context.
107 if (isContextClosed()) { 193 if (isContextClosed()) {
108 return ScriptPromise::rejectWithDOMException( 194 return ScriptPromise::rejectWithDOMException(
109 scriptState, 195 scriptState,
110 DOMException::create( 196 DOMException::create(
111 InvalidStateError, 197 InvalidStateError,
112 "cannot call startRendering on an OfflineAudioContext in a stopp ed state.")); 198 "cannot call startRendering on an OfflineAudioContext in a close d state."));
113 } 199 }
114 200
115 if (m_offlineResolver) { 201 if (m_completeResolver) {
116 // Can't call startRendering more than once. Return a rejected promise now. 202 // Can't call startRendering more than once. Return a rejected promise now.
117 return ScriptPromise::rejectWithDOMException( 203 return ScriptPromise::rejectWithDOMException(
118 scriptState, 204 scriptState,
119 DOMException::create( 205 DOMException::create(
120 InvalidStateError, 206 InvalidStateError,
121 "cannot call startRendering more than once")); 207 "cannot call startRendering more than once"));
122 } 208 }
123 209
124 m_offlineResolver = ScriptPromiseResolver::create(scriptState); 210 // If the context is not in the suspended state, reject the promise.
125 startRendering(); 211 if (contextState() != AudioContextState::Suspended) {
126 return m_offlineResolver->promise(); 212 return ScriptPromise::rejectWithDOMException(
213 scriptState,
214 DOMException::create(
215 InvalidStateError,
216 "cannot startRendering when an OfflineAudioContext is not in a s uspended state"));
217 }
218
219 m_completeResolver = ScriptPromiseResolver::create(scriptState);
220
221 // Start rendering and return the promise.
222 ASSERT(!m_isRenderingStarted);
223 m_isRenderingStarted = true;
224 setContextState(Running);
225 destinationHandler().startRendering();
226
227 return m_completeResolver->promise();
127 } 228 }
128 229
129 ScriptPromise OfflineAudioContext::closeContext(ScriptState* scriptState) 230 ScriptPromise OfflineAudioContext::closeContext(ScriptState* scriptState)
130 { 231 {
131 return ScriptPromise::rejectWithDOMException( 232 return ScriptPromise::rejectWithDOMException(
132 scriptState, 233 scriptState,
133 DOMException::create(InvalidAccessError, "cannot close an OfflineAudioCo ntext.")); 234 DOMException::create(InvalidAccessError, "cannot close an OfflineAudioCo ntext."));
134 } 235 }
135 236
136 ScriptPromise OfflineAudioContext::suspendContext(ScriptState* scriptState) 237 ScriptPromise OfflineAudioContext::suspendContext(ScriptState* scriptState)
137 { 238 {
138 return ScriptPromise::rejectWithDOMException( 239 // This CANNOT be called on OfflineAudioContext; it is to implement the pure
139 scriptState, 240 // virtual interface from AbstractAudioContext.
140 DOMException::create( 241 RELEASE_ASSERT_NOT_REACHED();
141 InvalidAccessError, 242
142 "cannot suspend an OfflineAudioContext")); 243 return ScriptPromise();
244 }
245
246 ScriptPromise OfflineAudioContext::suspendContext(ScriptState* scriptState, doub le when)
247 {
248 ASSERT(isMainThread());
249
250 RefPtrWillBeRawPtr<ScriptPromiseResolver> resolver = ScriptPromiseResolver:: create(scriptState);
251 ScriptPromise promise = resolver->promise();
252
253 // The render thread does not exist; reject the promise.
254 if (!destinationHandler().offlineRenderThread()) {
255 resolver->reject(DOMException::create(InvalidStateError,
256 "the rendering is already finished"));
257 return promise;
258 }
259
260 // The specified suspend time is negative; reject the promise.
261 if (when < 0) {
262 resolver->reject(DOMException::create(InvalidStateError,
263 "negative suspend time (" + String::number(when) + ") is not allowed "));
264 return promise;
265 }
266
267 // Quantize the suspend time to the render quantum boundary.
268 size_t quantizedFrame = destinationHandler().quantizeTimeToRenderQuantum(whe n);
269
270 // The suspend time should be earlier than the total render frame. If the
271 // requested suspension time is equal to the total render frame, the promise
272 // will be rejected.
273 if (m_totalRenderFrames <= quantizedFrame) {
274 resolver->reject(DOMException::create(InvalidStateError,
275 "cannot schedule a suspend at frame " + String::number(quantizedFram e) +
276 " (" + String::number(when) + " seconds) " +
277 "because it is greater than or equal to the total render duration of " +
278 String::number(m_totalRenderFrames) + " frames"));
279 return promise;
280 }
281
282 ScheduledSuspendContainer* suspendContainer = ScheduledSuspendContainer::cre ate(resolver);
283
284 // Basic checks are passed; store the object to maintain the ownership.
285 m_suspendContainers.add(suspendContainer);
286
287 // Validate the suspend and add it if necessary on the render thread.
288 // Note that passing a raw pointer |suspendContainer| is safe here as well
289 // with the same reason in |resolvePendingSuspendPromises|.
290 destinationHandler().offlineRenderThread()->postTask(FROM_HERE,
291 threadSafeBind(&OfflineAudioContext::validateSuspendContainerOnRenderThr ead, this,
hiroshige 2015/07/22 17:51:17 IIUC, 1. OfflineAudioContext is GarbageCollected.
292 AllowCrossThreadAccess(suspendContainer),
293 when,
294 quantizedFrame));
295
296 return promise;
143 } 297 }
144 298
145 ScriptPromise OfflineAudioContext::resumeContext(ScriptState* scriptState) 299 ScriptPromise OfflineAudioContext::resumeContext(ScriptState* scriptState)
146 { 300 {
147 return ScriptPromise::rejectWithDOMException( 301 ASSERT(isMainThread());
148 scriptState, 302
149 DOMException::create( 303 RefPtrWillBeRawPtr<ScriptPromiseResolver> resolver = ScriptPromiseResolver:: create(scriptState);
150 InvalidAccessError, 304 ScriptPromise promise = resolver->promise();
151 "cannot resume an OfflineAudioContext")); 305
306 // If the context is not in a suspended state, reject the promise.
307 if (contextState() != AudioContextState::Suspended) {
308 resolver->reject(DOMException::create(InvalidStateError,
309 "cannot resume a context that is not suspended"));
310 return promise;
311 }
312
313 // If the rendering has not started, reject the promise.
314 if (!m_isRenderingStarted) {
315 resolver->reject(DOMException::create(InvalidStateError,
316 "cannot resume a context that has not started"));
317 return promise;
318 }
319
320 // If the context is suspended, resume rendering by setting the state to
321 // "Running." and calling startRendering(). Note that resuming is possible
322 // only after the rendering started.
323 setContextState(Running);
324 destinationHandler().startRendering();
325
326 // Resolve the promise immediately.
327 resolver->resolve();
328
329 return promise;
330 }
331
332 OfflineAudioDestinationHandler& OfflineAudioContext::destinationHandler()
333 {
334 return static_cast<OfflineAudioDestinationHandler&>(destination()->audioDest inationHandler());
335 }
336
337 void OfflineAudioContext::validateSuspendContainerOnRenderThread(ScheduledSuspen dContainer* suspendContainer, double suspendTime, size_t suspendFrame)
338 {
339 ASSERT(!isMainThread());
340
341 bool shouldBeRejected = false;
342 String errorMessage;
343
344 // The specified suspend time is in the past; reject the promise. We cannot
345 // reject the promise in here, so set the error message before posting the
346 // rejection task to the main thread.
347 if (suspendFrame < currentSampleFrame()) {
348 shouldBeRejected = true;
349 errorMessage = "cannot schedule a suspend at frame " +
350 String::number(suspendFrame) + " (" + String::number(suspendTime) +
351 " seconds) because it is earlier than the current frame of " +
352 String::number(currentSampleFrame()) + " (" +
353 String::number(currentTime()) + " seconds)";
354 } else if (m_scheduledSuspends.contains(suspendFrame)) {
355 // If there is a duplicate suspension at the same quantized frame,
356 // reject the promise. The rejection of promise should happen in the
357 // main thread, so we post a task to it. Here we simply set the error
358 // message and post a task to the main thread.
359 shouldBeRejected = true;
360 errorMessage = "cannot schedule more than one suspend at frame " +
361 String::number(suspendFrame) + " (" +
362 String::number(suspendTime) + " seconds)";
363 }
364
365 // Reject the promise if necessary on the main thread.
366 // Note that passing a raw pointer |suspendContainer| is safe here as well
367 // with the same reason in |resolvePendingSuspendPromises|.
368 if (shouldBeRejected) {
369 Platform::current()->mainThread()->postTask(FROM_HERE,
370 threadSafeBind(&OfflineAudioContext::rejectSuspendContainerOnMainThr ead, this,
371 AllowCrossThreadAccess(suspendContainer),
372 errorMessage.isolatedCopy()));
hiroshige 2015/07/22 17:32:12 .isolatedCopy() is not needed because it is called
hongchan 2015/07/22 20:36:35 Done.
373 return;
374 }
375
376 // If the validation check passes, we can add the container safely here in
377 // the render thread.
378 m_scheduledSuspends.add(suspendFrame, suspendContainer);
379 }
380
381 void OfflineAudioContext::rejectSuspendContainerOnMainThread(ScheduledSuspendCon tainer* suspendContainer, const String& errorMessage)
382 {
383 ASSERT(isMainThread());
384
hiroshige 2015/07/22 17:32:12 Please add RELEASE_ASSERT before dereferencing |su
hongchan 2015/07/22 20:36:35 Done.
385 suspendContainer->rejectPromise(InvalidStateError, errorMessage);
386
387 // Remove the container out of the set and delete the raw pointer.
388 m_suspendContainers.remove(suspendContainer);
389 delete suspendContainer;
390 }
391
392 void OfflineAudioContext::resolveSuspendContainerOnMainThread(ScheduledSuspendCo ntainer* suspendContainer)
393 {
394 ASSERT(isMainThread());
395
396 // Suspend the context first. This will fire onstatechange event.
397 setContextState(Suspended);
398
hiroshige 2015/07/22 17:32:12 ditto.
hongchan 2015/07/22 20:36:35 Done.
399 suspendContainer->resolvePromise();
400
401 // Remove the container out of the set and delete the raw pointer.
402 m_suspendContainers.remove(suspendContainer);
403 delete suspendContainer;
404 }
405
406 ScheduledSuspendContainer::ScheduledSuspendContainer(PassRefPtrWillBeRawPtr<Scri ptPromiseResolver> resolver)
407 : m_resolver(resolver)
408 {
409 ASSERT(isMainThread());
410 }
411
412 ScheduledSuspendContainer::~ScheduledSuspendContainer()
413 {
414 ASSERT(isMainThread());
415 }
416
417 ScheduledSuspendContainer* ScheduledSuspendContainer::create(PassRefPtrWillBeRaw Ptr<ScriptPromiseResolver> resolver)
418 {
419 return new ScheduledSuspendContainer(resolver);
420 }
421
422 void ScheduledSuspendContainer::resolvePromise()
423 {
424 ASSERT(isMainThread());
425
426 m_resolver->resolve();
427 }
428
429 void ScheduledSuspendContainer::rejectPromise(ExceptionCode errorCode, const Str ing& errorMessage)
430 {
431 ASSERT(isMainThread());
432
433 m_resolver->reject(DOMException::create(errorCode, errorMessage));
152 } 434 }
153 435
154 } // namespace blink 436 } // namespace blink
155 437
156 #endif // ENABLE(WEB_AUDIO) 438 #endif // ENABLE(WEB_AUDIO)
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698