2 * Copyright (C) 2013 Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above
11 * copyright notice, this list of conditions and the following disclaimer
12 * in the documentation and/or other materials provided with the
14 * * Neither the name of Google Inc. nor the names of its
15 * contributors may be used to endorse or promote products derived from
16 * this software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 #include "modules/mediasource/MediaSourceBase.h"
34 #include "bindings/v8/ExceptionState.h"
35 #include "bindings/v8/ExceptionStatePlaceholder.h"
36 #include "core/dom/ExceptionCode.h"
37 #include "core/events/Event.h"
38 #include "core/events/GenericEventQueue.h"
39 #include "core/html/TimeRanges.h"
40 #include "modules/mediasource/MediaSourceRegistry.h"
41 #include "platform/Logging.h"
42 #include "platform/TraceEvent.h"
43 #include "public/platform/WebMediaSource.h"
44 #include "public/platform/WebSourceBuffer.h"
45 #include "wtf/text/WTFString.h"
47 using blink::WebMediaSource;
48 using blink::WebSourceBuffer;
52 DEFINE_GC_INFO(MediaSourceBase);
54 MediaSourceBase::MediaSourceBase(ExecutionContext* context)
55 : ActiveDOMObject(context)
56 , m_readyState(closedKeyword())
57 , m_asyncEventQueue(GenericEventQueue::create(this))
58 , m_attachedElement(0)
62 MediaSourceBase::~MediaSourceBase()
66 const AtomicString& MediaSourceBase::openKeyword()
68 DEFINE_STATIC_LOCAL(const AtomicString, open, ("open", AtomicString::ConstructFromLiteral));
72 const AtomicString& MediaSourceBase::closedKeyword()
74 DEFINE_STATIC_LOCAL(const AtomicString, closed, ("closed", AtomicString::ConstructFromLiteral));
78 const AtomicString& MediaSourceBase::endedKeyword()
80 DEFINE_STATIC_LOCAL(const AtomicString, ended, ("ended", AtomicString::ConstructFromLiteral));
84 void MediaSourceBase::setWebMediaSourceAndOpen(PassOwnPtr<WebMediaSource> webMediaSource)
86 TRACE_EVENT_ASYNC_END0("media", "MediaSourceBase::attachToElement", this);
87 ASSERT(webMediaSource);
88 ASSERT(!m_webMediaSource);
89 ASSERT(m_attachedElement);
90 m_webMediaSource = webMediaSource;
91 setReadyState(openKeyword());
94 void MediaSourceBase::addedToRegistry()
96 setPendingActivity(this);
99 void MediaSourceBase::removedFromRegistry()
101 unsetPendingActivity(this);
104 double MediaSourceBase::duration() const
106 return isClosed() ? std::numeric_limits<float>::quiet_NaN() : m_webMediaSource->duration();
109 PassRefPtr<TimeRanges> MediaSourceBase::buffered() const
111 // Implements MediaSource algorithm for HTMLMediaElement.buffered.
112 // https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#htmlmediaelement-extensions
113 Vector<RefPtr<TimeRanges> > ranges = activeRanges();
115 // 1. If activeSourceBuffers.length equals 0 then return an empty TimeRanges object and abort these steps.
116 if (ranges.isEmpty())
117 return TimeRanges::create();
119 // 2. Let active ranges be the ranges returned by buffered for each SourceBuffer object in activeSourceBuffers.
120 // 3. Let highest end time be the largest range end time in the active ranges.
121 double highestEndTime = -1;
122 for (size_t i = 0; i < ranges.size(); ++i) {
123 unsigned length = ranges[i]->length();
125 highestEndTime = std::max(highestEndTime, ranges[i]->end(length - 1, ASSERT_NO_EXCEPTION));
128 // Return an empty range if all ranges are empty.
129 if (highestEndTime < 0)
130 return TimeRanges::create();
132 // 4. Let intersection ranges equal a TimeRange object containing a single range from 0 to highest end time.
133 RefPtr<TimeRanges> intersectionRanges = TimeRanges::create(0, highestEndTime);
135 // 5. For each SourceBuffer object in activeSourceBuffers run the following steps:
136 bool ended = readyState() == endedKeyword();
137 for (size_t i = 0; i < ranges.size(); ++i) {
138 // 5.1 Let source ranges equal the ranges returned by the buffered attribute on the current SourceBuffer.
139 TimeRanges* sourceRanges = ranges[i].get();
141 // 5.2 If readyState is "ended", then set the end time on the last range in source ranges to highest end time.
142 if (ended && sourceRanges->length())
143 sourceRanges->add(sourceRanges->start(sourceRanges->length() - 1, ASSERT_NO_EXCEPTION), highestEndTime);
145 // 5.3 Let new intersection ranges equal the the intersection between the intersection ranges and the source ranges.
146 // 5.4 Replace the ranges in intersection ranges with the new intersection ranges.
147 intersectionRanges->intersectWith(sourceRanges);
150 return intersectionRanges.release();
153 void MediaSourceBase::setDuration(double duration, ExceptionState& exceptionState)
155 // 2.1 http://www.w3.org/TR/media-source/#widl-MediaSource-duration
156 // 1. If the value being set is negative or NaN then throw an InvalidAccessError
157 // exception and abort these steps.
158 if (duration < 0.0 || std::isnan(duration)) {
159 exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
163 // 2. If the readyState attribute is not "open" then throw an InvalidStateError
164 // exception and abort these steps.
166 exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
170 // 3. If the updating attribute equals true on any SourceBuffer in sourceBuffers,
171 // then throw an InvalidStateError exception and abort these steps.
173 exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
177 // 4. Run the duration change algorithm with new duration set to the value being
178 // assigned to this attribute.
179 // Synchronously process duration change algorithm to enforce any required
180 // seek is started prior to returning.
181 m_attachedElement->durationChanged(duration);
182 m_webMediaSource->setDuration(duration);
185 void MediaSourceBase::setReadyState(const AtomicString& state)
187 ASSERT(state == openKeyword() || state == closedKeyword() || state == endedKeyword());
189 AtomicString oldState = readyState();
190 WTF_LOG(Media, "MediaSourceBase::setReadyState() %p : %s -> %s", this, oldState.ascii().data(), state.ascii().data());
192 if (state == closedKeyword()) {
193 m_webMediaSource.clear();
194 m_attachedElement = 0;
197 if (oldState == state)
200 m_readyState = state;
202 onReadyStateChange(oldState, state);
205 void MediaSourceBase::endOfStream(const AtomicString& error, ExceptionState& exceptionState)
207 DEFINE_STATIC_LOCAL(const AtomicString, network, ("network", AtomicString::ConstructFromLiteral));
208 DEFINE_STATIC_LOCAL(const AtomicString, decode, ("decode", AtomicString::ConstructFromLiteral));
210 if (error == network) {
211 endOfStreamInternal(blink::WebMediaSource::EndOfStreamStatusNetworkError, exceptionState);
212 } else if (error == decode) {
213 endOfStreamInternal(blink::WebMediaSource::EndOfStreamStatusDecodeError, exceptionState);
215 ASSERT_NOT_REACHED(); // IDL enforcement should prevent this case.
216 exceptionState.throwTypeError("parameter 1 is not a valid enum value.");
220 void MediaSourceBase::endOfStream(ExceptionState& exceptionState)
222 endOfStreamInternal(blink::WebMediaSource::EndOfStreamStatusNoError, exceptionState);
225 void MediaSourceBase::endOfStreamInternal(const blink::WebMediaSource::EndOfStreamStatus eosStatus, ExceptionState& exceptionState)
227 // 2.2 http://www.w3.org/TR/media-source/#widl-MediaSource-endOfStream-void-EndOfStreamError-error
228 // 1. If the readyState attribute is not in the "open" state then throw an
229 // InvalidStateError exception and abort these steps.
231 exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
235 // 2. If the updating attribute equals true on any SourceBuffer in sourceBuffers, then throw an
236 // InvalidStateError exception and abort these steps.
238 exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
242 // 3. Run the end of stream algorithm with the error parameter set to error.
243 // 1. Change the readyState attribute value to "ended".
244 // 2. Queue a task to fire a simple event named sourceended at the MediaSource.
245 setReadyState(endedKeyword());
247 // 3. Do various steps based on |eosStatus|.
248 m_webMediaSource->markEndOfStream(eosStatus);
251 bool MediaSourceBase::isOpen() const
253 return readyState() == openKeyword();
256 bool MediaSourceBase::isClosed() const
258 return readyState() == closedKeyword();
261 void MediaSourceBase::close()
263 setReadyState(closedKeyword());
266 bool MediaSourceBase::attachToElement(HTMLMediaElement* element)
268 if (m_attachedElement)
273 TRACE_EVENT_ASYNC_BEGIN0("media", "MediaSourceBase::attachToElement", this);
274 m_attachedElement = element;
278 void MediaSourceBase::openIfInEndedState()
280 if (m_readyState != endedKeyword())
283 setReadyState(openKeyword());
284 m_webMediaSource->unmarkEndOfStream();
287 bool MediaSourceBase::hasPendingActivity() const
289 return m_attachedElement || m_webMediaSource
290 || m_asyncEventQueue->hasPendingEvents()
291 || ActiveDOMObject::hasPendingActivity();
294 void MediaSourceBase::stop()
296 m_asyncEventQueue->close();
298 setReadyState(closedKeyword());
299 m_webMediaSource.clear();
302 PassOwnPtr<WebSourceBuffer> MediaSourceBase::createWebSourceBuffer(const String& type, const Vector<String>& codecs, ExceptionState& exceptionState)
304 WebSourceBuffer* webSourceBuffer = 0;
305 switch (m_webMediaSource->addSourceBuffer(type, codecs, &webSourceBuffer)) {
306 case WebMediaSource::AddStatusOk:
307 return adoptPtr(webSourceBuffer);
308 case WebMediaSource::AddStatusNotSupported:
309 ASSERT(!webSourceBuffer);
310 // 2.2 https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#widl-MediaSource-addSourceBuffer-SourceBuffer-DOMString-type
311 // Step 2: If type contains a MIME type ... that is not supported with the types
312 // specified for the other SourceBuffer objects in sourceBuffers, then throw
313 // a NotSupportedError exception and abort these steps.
314 exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
316 case WebMediaSource::AddStatusReachedIdLimit:
317 ASSERT(!webSourceBuffer);
318 // 2.2 https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#widl-MediaSource-addSourceBuffer-SourceBuffer-DOMString-type
319 // Step 3: If the user agent can't handle any more SourceBuffer objects then throw
320 // a QuotaExceededError exception and abort these steps.
321 exceptionState.throwUninformativeAndGenericDOMException(QuotaExceededError);
325 ASSERT_NOT_REACHED();
329 void MediaSourceBase::scheduleEvent(const AtomicString& eventName)
331 ASSERT(m_asyncEventQueue);
333 RefPtr<Event> event = Event::create(eventName);
334 event->setTarget(this);
336 m_asyncEventQueue->enqueueEvent(event.release());
339 ExecutionContext* MediaSourceBase::executionContext() const
341 return ActiveDOMObject::executionContext();
344 URLRegistry& MediaSourceBase::registry() const
346 return MediaSourceRegistry::registry();