1df7786a4d8a7f97f452307ce1be52e9ae3d8ed5
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / modules / mediasource / MediaSourceBase.cpp
1 /*
2  * Copyright (C) 2013 Google Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are
6  * met:
7  *
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
13  * distribution.
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.
17  *
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.
29  */
30
31 #include "config.h"
32 #include "modules/mediasource/MediaSourceBase.h"
33
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"
46
47 using blink::WebMediaSource;
48 using blink::WebSourceBuffer;
49
50 namespace WebCore {
51
52 DEFINE_GC_INFO(MediaSourceBase);
53
54 MediaSourceBase::MediaSourceBase(ExecutionContext* context)
55     : ActiveDOMObject(context)
56     , m_readyState(closedKeyword())
57     , m_asyncEventQueue(GenericEventQueue::create(this))
58     , m_attachedElement(0)
59 {
60 }
61
62 MediaSourceBase::~MediaSourceBase()
63 {
64 }
65
66 const AtomicString& MediaSourceBase::openKeyword()
67 {
68     DEFINE_STATIC_LOCAL(const AtomicString, open, ("open", AtomicString::ConstructFromLiteral));
69     return open;
70 }
71
72 const AtomicString& MediaSourceBase::closedKeyword()
73 {
74     DEFINE_STATIC_LOCAL(const AtomicString, closed, ("closed", AtomicString::ConstructFromLiteral));
75     return closed;
76 }
77
78 const AtomicString& MediaSourceBase::endedKeyword()
79 {
80     DEFINE_STATIC_LOCAL(const AtomicString, ended, ("ended", AtomicString::ConstructFromLiteral));
81     return ended;
82 }
83
84 void MediaSourceBase::setWebMediaSourceAndOpen(PassOwnPtr<WebMediaSource> webMediaSource)
85 {
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());
92 }
93
94 void MediaSourceBase::addedToRegistry()
95 {
96     setPendingActivity(this);
97 }
98
99 void MediaSourceBase::removedFromRegistry()
100 {
101     unsetPendingActivity(this);
102 }
103
104 double MediaSourceBase::duration() const
105 {
106     return isClosed() ? std::numeric_limits<float>::quiet_NaN() : m_webMediaSource->duration();
107 }
108
109 PassRefPtr<TimeRanges> MediaSourceBase::buffered() const
110 {
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();
114
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();
118
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();
124         if (length)
125             highestEndTime = std::max(highestEndTime, ranges[i]->end(length - 1, ASSERT_NO_EXCEPTION));
126     }
127
128     // Return an empty range if all ranges are empty.
129     if (highestEndTime < 0)
130         return TimeRanges::create();
131
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);
134
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();
140
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);
144
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);
148     }
149
150     return intersectionRanges.release();
151 }
152
153 void MediaSourceBase::setDuration(double duration, ExceptionState& exceptionState)
154 {
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);
160         return;
161     }
162
163     // 2. If the readyState attribute is not "open" then throw an InvalidStateError
164     // exception and abort these steps.
165     if (!isOpen()) {
166         exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
167         return;
168     }
169
170     // 3. If the updating attribute equals true on any SourceBuffer in sourceBuffers,
171     // then throw an InvalidStateError exception and abort these steps.
172     if (isUpdating()) {
173         exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
174         return;
175     }
176
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);
183 }
184
185 void MediaSourceBase::setReadyState(const AtomicString& state)
186 {
187     ASSERT(state == openKeyword() || state == closedKeyword() || state == endedKeyword());
188
189     AtomicString oldState = readyState();
190     WTF_LOG(Media, "MediaSourceBase::setReadyState() %p : %s -> %s", this, oldState.ascii().data(), state.ascii().data());
191
192     if (state == closedKeyword()) {
193         m_webMediaSource.clear();
194         m_attachedElement = 0;
195     }
196
197     if (oldState == state)
198         return;
199
200     m_readyState = state;
201
202     onReadyStateChange(oldState, state);
203 }
204
205 void MediaSourceBase::endOfStream(const AtomicString& error, ExceptionState& exceptionState)
206 {
207     DEFINE_STATIC_LOCAL(const AtomicString, network, ("network", AtomicString::ConstructFromLiteral));
208     DEFINE_STATIC_LOCAL(const AtomicString, decode, ("decode", AtomicString::ConstructFromLiteral));
209
210     if (error == network) {
211         endOfStreamInternal(blink::WebMediaSource::EndOfStreamStatusNetworkError, exceptionState);
212     } else if (error == decode) {
213         endOfStreamInternal(blink::WebMediaSource::EndOfStreamStatusDecodeError, exceptionState);
214     } else {
215         ASSERT_NOT_REACHED(); // IDL enforcement should prevent this case.
216         exceptionState.throwTypeError("parameter 1 is not a valid enum value.");
217     }
218 }
219
220 void MediaSourceBase::endOfStream(ExceptionState& exceptionState)
221 {
222     endOfStreamInternal(blink::WebMediaSource::EndOfStreamStatusNoError, exceptionState);
223 }
224
225 void MediaSourceBase::endOfStreamInternal(const blink::WebMediaSource::EndOfStreamStatus eosStatus, ExceptionState& exceptionState)
226 {
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.
230     if (!isOpen()) {
231         exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
232         return;
233     }
234
235     // 2. If the updating attribute equals true on any SourceBuffer in sourceBuffers, then throw an
236     // InvalidStateError exception and abort these steps.
237     if (isUpdating()) {
238         exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
239         return;
240     }
241
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());
246
247     //   3. Do various steps based on |eosStatus|.
248     m_webMediaSource->markEndOfStream(eosStatus);
249 }
250
251 bool MediaSourceBase::isOpen() const
252 {
253     return readyState() == openKeyword();
254 }
255
256 bool MediaSourceBase::isClosed() const
257 {
258     return readyState() == closedKeyword();
259 }
260
261 void MediaSourceBase::close()
262 {
263     setReadyState(closedKeyword());
264 }
265
266 bool MediaSourceBase::attachToElement(HTMLMediaElement* element)
267 {
268     if (m_attachedElement)
269         return false;
270
271     ASSERT(isClosed());
272
273     TRACE_EVENT_ASYNC_BEGIN0("media", "MediaSourceBase::attachToElement", this);
274     m_attachedElement = element;
275     return true;
276 }
277
278 void MediaSourceBase::openIfInEndedState()
279 {
280     if (m_readyState != endedKeyword())
281         return;
282
283     setReadyState(openKeyword());
284     m_webMediaSource->unmarkEndOfStream();
285 }
286
287 bool MediaSourceBase::hasPendingActivity() const
288 {
289     return m_attachedElement || m_webMediaSource
290         || m_asyncEventQueue->hasPendingEvents()
291         || ActiveDOMObject::hasPendingActivity();
292 }
293
294 void MediaSourceBase::stop()
295 {
296     m_asyncEventQueue->close();
297     if (!isClosed())
298         setReadyState(closedKeyword());
299     m_webMediaSource.clear();
300 }
301
302 PassOwnPtr<WebSourceBuffer> MediaSourceBase::createWebSourceBuffer(const String& type, const Vector<String>& codecs, ExceptionState& exceptionState)
303 {
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);
315         return nullptr;
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);
322         return nullptr;
323     }
324
325     ASSERT_NOT_REACHED();
326     return nullptr;
327 }
328
329 void MediaSourceBase::scheduleEvent(const AtomicString& eventName)
330 {
331     ASSERT(m_asyncEventQueue);
332
333     RefPtr<Event> event = Event::create(eventName);
334     event->setTarget(this);
335
336     m_asyncEventQueue->enqueueEvent(event.release());
337 }
338
339 ExecutionContext* MediaSourceBase::executionContext() const
340 {
341     return ActiveDOMObject::executionContext();
342 }
343
344 URLRegistry& MediaSourceBase::registry() const
345 {
346     return MediaSourceRegistry::registry();
347 }
348
349 }