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

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: Bring ToT Created 5 years, 4 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_scheduledSuspendContainers.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_scheduledSuspendContainers.find(current SampleFrame());
146 if (it == m_scheduledSuspendContainers.end())
147 return;
148
149 ScheduledSuspendContainer* suspendContainer = it->value;
150 m_scheduledSuspendContainers.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 be
154 // alive until:
155 // - the raw pointer is passed back to the main thread and
156 // resolveSuspendContainerOnMainThread()/rejectSuspendContainerOnMainThrea d()
157 // is called on the main thread, or
158 // - OfflineAudioContext is destructed.
159 Platform::current()->mainThread()->postTask(FROM_HERE,
160 threadSafeBind(&OfflineAudioContext::resolveSuspendContainerOnMainThread , this,
161 AllowCrossThreadAccess(suspendContainer)));
162 }
163
164 void OfflineAudioContext::fireCompletionEvent()
165 {
166 ASSERT(isMainThread());
167
168 // We set the state to closed here so that the oncomplete event handler sees
169 // that the context has been closed.
170 setContextState(Closed);
171
172 AudioBuffer* renderedBuffer = renderTarget();
173
174 ASSERT(renderedBuffer);
175 if (!renderedBuffer)
176 return;
177
178 // Avoid firing the event if the document has already gone away.
179 if (executionContext()) {
180 // Call the offline rendering completion event listener and resolve the
181 // promise too.
182 dispatchEvent(OfflineAudioCompletionEvent::create(renderedBuffer));
183 m_completeResolver->resolve(renderedBuffer);
184 } else {
185 // The resolver should be rejected when the execution context is gone.
186 m_completeResolver->reject(DOMException::create(InvalidStateError,
187 "the execution context does not exist"));
188 }
101 } 189 }
102 190
103 ScriptPromise OfflineAudioContext::startOfflineRendering(ScriptState* scriptStat e) 191 ScriptPromise OfflineAudioContext::startOfflineRendering(ScriptState* scriptStat e)
104 { 192 {
193 ASSERT(isMainThread());
194
105 // Calling close() on an OfflineAudioContext is not supported/allowed, 195 // Calling close() on an OfflineAudioContext is not supported/allowed,
106 // but it might well have been stopped by its execution context. 196 // but it might well have been closed by its execution context.
107 if (isContextClosed()) { 197 if (isContextClosed()) {
108 return ScriptPromise::rejectWithDOMException( 198 return ScriptPromise::rejectWithDOMException(
109 scriptState, 199 scriptState,
110 DOMException::create( 200 DOMException::create(
111 InvalidStateError, 201 InvalidStateError,
112 "cannot call startRendering on an OfflineAudioContext in a stopp ed state.")); 202 "cannot call startRendering on an OfflineAudioContext in a close d state."));
113 } 203 }
114 204
115 if (m_offlineResolver) { 205 if (m_completeResolver) {
116 // Can't call startRendering more than once. Return a rejected promise now. 206 // Can't call startRendering more than once. Return a rejected promise now.
117 return ScriptPromise::rejectWithDOMException( 207 return ScriptPromise::rejectWithDOMException(
118 scriptState, 208 scriptState,
119 DOMException::create( 209 DOMException::create(
120 InvalidStateError, 210 InvalidStateError,
121 "cannot call startRendering more than once")); 211 "cannot call startRendering more than once"));
122 } 212 }
123 213
124 m_offlineResolver = ScriptPromiseResolver::create(scriptState); 214 // If the context is not in the suspended state, reject the promise.
125 startRendering(); 215 if (contextState() != AudioContextState::Suspended) {
126 return m_offlineResolver->promise(); 216 return ScriptPromise::rejectWithDOMException(
217 scriptState,
218 DOMException::create(
219 InvalidStateError,
220 "cannot startRendering when an OfflineAudioContext is not in a s uspended state"));
221 }
222
223 m_completeResolver = ScriptPromiseResolver::create(scriptState);
224
225 // Start rendering and return the promise.
226 ASSERT(!m_isRenderingStarted);
227 m_isRenderingStarted = true;
228 setContextState(Running);
229 destinationHandler().startRendering();
230
231 return m_completeResolver->promise();
127 } 232 }
128 233
129 ScriptPromise OfflineAudioContext::closeContext(ScriptState* scriptState) 234 ScriptPromise OfflineAudioContext::closeContext(ScriptState* scriptState)
130 { 235 {
131 return ScriptPromise::rejectWithDOMException( 236 return ScriptPromise::rejectWithDOMException(
132 scriptState, 237 scriptState,
133 DOMException::create(InvalidAccessError, "cannot close an OfflineAudioCo ntext.")); 238 DOMException::create(InvalidAccessError, "cannot close an OfflineAudioCo ntext."));
134 } 239 }
135 240
136 ScriptPromise OfflineAudioContext::suspendContext(ScriptState* scriptState) 241 ScriptPromise OfflineAudioContext::suspendContext(ScriptState* scriptState)
137 { 242 {
138 return ScriptPromise::rejectWithDOMException( 243 // This CANNOT be called on OfflineAudioContext; it is to implement the pure
139 scriptState, 244 // virtual interface from AbstractAudioContext.
140 DOMException::create( 245 RELEASE_ASSERT_NOT_REACHED();
141 InvalidAccessError, 246
142 "cannot suspend an OfflineAudioContext")); 247 return ScriptPromise();
248 }
249
250 ScriptPromise OfflineAudioContext::suspendContext(ScriptState* scriptState, doub le when)
251 {
252 ASSERT(isMainThread());
253
254 RefPtrWillBeRawPtr<ScriptPromiseResolver> resolver = ScriptPromiseResolver:: create(scriptState);
255 ScriptPromise promise = resolver->promise();
256
257 // The render thread does not exist; reject the promise.
258 if (!destinationHandler().offlineRenderThread()) {
259 resolver->reject(DOMException::create(InvalidStateError,
260 "the rendering is already finished"));
261 return promise;
262 }
263
264 // The specified suspend time is negative; reject the promise.
265 if (when < 0) {
266 resolver->reject(DOMException::create(InvalidStateError,
267 "negative suspend time (" + String::number(when) + ") is not allowed "));
268 return promise;
269 }
270
271 // Quantize the suspend time to the render quantum boundary.
272 size_t quantizedFrame = destinationHandler().quantizeTimeToRenderQuantum(whe n);
273
274 // The suspend time should be earlier than the total render frame. If the
275 // requested suspension time is equal to the total render frame, the promise
276 // will be rejected.
277 if (m_totalRenderFrames <= quantizedFrame) {
278 resolver->reject(DOMException::create(InvalidStateError,
279 "cannot schedule a suspend at frame " + String::number(quantizedFram e) +
280 " (" + String::number(when) + " seconds) " +
281 "because it is greater than or equal to the total render duration of " +
282 String::number(m_totalRenderFrames) + " frames"));
283 return promise;
284 }
285
286 ScheduledSuspendContainer* suspendContainer = ScheduledSuspendContainer::cre ate(resolver);
287
288 // Basic checks are passed; store the object to maintain the ownership.
289 m_suspendContainers.add(suspendContainer);
290
291 // Validate the suspend and add it if necessary on the render thread.
292 // Note that passing a raw pointer |suspendContainer| is safe here as well
293 // with the same reason in |resolvePendingSuspendPromises|.
294 destinationHandler().offlineRenderThread()->postTask(FROM_HERE,
295 threadSafeBind(&OfflineAudioContext::validateSuspendContainerOnRenderThr ead, this,
296 AllowCrossThreadAccess(suspendContainer),
297 when,
298 quantizedFrame));
299
300 return promise;
143 } 301 }
144 302
145 ScriptPromise OfflineAudioContext::resumeContext(ScriptState* scriptState) 303 ScriptPromise OfflineAudioContext::resumeContext(ScriptState* scriptState)
146 { 304 {
147 return ScriptPromise::rejectWithDOMException( 305 ASSERT(isMainThread());
148 scriptState, 306
149 DOMException::create( 307 RefPtrWillBeRawPtr<ScriptPromiseResolver> resolver = ScriptPromiseResolver:: create(scriptState);
150 InvalidAccessError, 308 ScriptPromise promise = resolver->promise();
151 "cannot resume an OfflineAudioContext")); 309
310 // If the context is not in a suspended state, reject the promise.
311 if (contextState() != AudioContextState::Suspended) {
312 resolver->reject(DOMException::create(InvalidStateError,
313 "cannot resume a context that is not suspended"));
314 return promise;
315 }
316
317 // If the rendering has not started, reject the promise.
318 if (!m_isRenderingStarted) {
319 resolver->reject(DOMException::create(InvalidStateError,
320 "cannot resume a context that has not started"));
321 return promise;
322 }
323
324 // If the context is suspended, resume rendering by setting the state to
325 // "Running." and calling startRendering(). Note that resuming is possible
326 // only after the rendering started.
327 setContextState(Running);
328 destinationHandler().startRendering();
329
330 // Resolve the promise immediately.
331 resolver->resolve();
332
333 return promise;
334 }
335
336 OfflineAudioDestinationHandler& OfflineAudioContext::destinationHandler()
337 {
338 return static_cast<OfflineAudioDestinationHandler&>(destination()->audioDest inationHandler());
339 }
340
341 void OfflineAudioContext::validateSuspendContainerOnRenderThread(ScheduledSuspen dContainer* suspendContainer, double suspendTime, size_t suspendFrame)
342 {
343 ASSERT(!isMainThread());
344
345 bool shouldBeRejected = false;
346 String errorMessage;
347
348 // The specified suspend time is in the past; reject the promise. We cannot
349 // reject the promise in here, so set the error message before posting the
350 // rejection task to the main thread.
351 if (suspendFrame < currentSampleFrame()) {
352 shouldBeRejected = true;
353 errorMessage = "cannot schedule a suspend at frame " +
354 String::number(suspendFrame) + " (" + String::number(suspendTime) +
355 " seconds) because it is earlier than the current frame of " +
356 String::number(currentSampleFrame()) + " (" +
357 String::number(currentTime()) + " seconds)";
358 } else if (m_scheduledSuspendContainers.contains(suspendFrame)) {
359 // If there is a duplicate suspension at the same quantized frame,
360 // reject the promise. The rejection of promise should happen in the
361 // main thread, so we post a task to it. Here we simply set the error
362 // message and post a task to the main thread.
363 shouldBeRejected = true;
364 errorMessage = "cannot schedule more than one suspend at frame " +
365 String::number(suspendFrame) + " (" +
366 String::number(suspendTime) + " seconds)";
367 }
368
369 // Reject the promise if necessary on the main thread.
370 // Note that passing a raw pointer |suspendContainer| is safe here as well
371 // with the same reason in |resolvePendingSuspendPromises|.
372 if (shouldBeRejected) {
373 Platform::current()->mainThread()->postTask(FROM_HERE,
374 threadSafeBind(&OfflineAudioContext::rejectSuspendContainerOnMainThr ead, this,
375 AllowCrossThreadAccess(suspendContainer),
376 errorMessage));
377 return;
378 }
379
380 // If the validation check passes, we can add the container safely here in
381 // the render thread.
382 m_scheduledSuspendContainers.add(suspendFrame, suspendContainer);
383 }
384
385 void OfflineAudioContext::rejectSuspendContainerOnMainThread(ScheduledSuspendCon tainer* suspendContainer, const String& errorMessage)
386 {
387 ASSERT(isMainThread());
388 RELEASE_ASSERT(suspendContainer);
389
390 suspendContainer->rejectPromise(InvalidStateError, errorMessage);
391
392 // Remove the container out of the set and delete the raw pointer.
393 m_suspendContainers.remove(suspendContainer);
394 delete suspendContainer;
395 }
396
397 void OfflineAudioContext::resolveSuspendContainerOnMainThread(ScheduledSuspendCo ntainer* suspendContainer)
398 {
399 ASSERT(isMainThread());
400 RELEASE_ASSERT(suspendContainer);
401
402 // Suspend the context first. This will fire onstatechange event.
403 setContextState(Suspended);
404
405 suspendContainer->resolvePromise();
406
407 // Remove the container out of the set and delete the raw pointer.
408 m_suspendContainers.remove(suspendContainer);
409 delete suspendContainer;
410 }
411
412 ScheduledSuspendContainer::ScheduledSuspendContainer(PassRefPtrWillBeRawPtr<Scri ptPromiseResolver> resolver)
413 : m_resolver(resolver)
414 {
415 ASSERT(isMainThread());
416 }
417
418 ScheduledSuspendContainer::~ScheduledSuspendContainer()
419 {
420 ASSERT(isMainThread());
421 }
422
423 ScheduledSuspendContainer* ScheduledSuspendContainer::create(PassRefPtrWillBeRaw Ptr<ScriptPromiseResolver> resolver)
424 {
425 return new ScheduledSuspendContainer(resolver);
426 }
427
428 void ScheduledSuspendContainer::resolvePromise()
429 {
430 ASSERT(isMainThread());
431
432 m_resolver->resolve();
433 }
434
435 void ScheduledSuspendContainer::rejectPromise(ExceptionCode errorCode, const Str ing& errorMessage)
436 {
437 ASSERT(isMainThread());
438
439 m_resolver->reject(DOMException::create(errorCode, errorMessage));
152 } 440 }
153 441
154 } // namespace blink 442 } // namespace blink
155 443
156 #endif // ENABLE(WEB_AUDIO) 444 #endif // ENABLE(WEB_AUDIO)
OLDNEW
« no previous file with comments | « Source/modules/webaudio/OfflineAudioContext.h ('k') | Source/modules/webaudio/OfflineAudioContext.idl » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698