Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / html / HTMLTrackElement.cpp
1 /*
2  * Copyright (C) 2011 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
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "config.h"
27 #include "core/html/HTMLTrackElement.h"
28
29 #include "HTMLNames.h"
30 #include "bindings/v8/ExceptionStatePlaceholder.h"
31 #include "core/events/Event.h"
32 #include "core/frame/csp/ContentSecurityPolicy.h"
33 #include "core/html/HTMLMediaElement.h"
34 #include "platform/Logging.h"
35
36 using namespace std;
37
38 namespace WebCore {
39
40 using namespace HTMLNames;
41
42 #if !LOG_DISABLED
43 static String urlForLoggingTrack(const KURL& url)
44 {
45     static const unsigned maximumURLLengthForLogging = 128;
46
47     if (url.string().length() < maximumURLLengthForLogging)
48         return url.string();
49     return url.string().substring(0, maximumURLLengthForLogging) + "...";
50 }
51 #endif
52
53 inline HTMLTrackElement::HTMLTrackElement(Document& document)
54     : HTMLElement(trackTag, document)
55     , m_loadTimer(this, &HTMLTrackElement::loadTimerFired)
56 {
57     WTF_LOG(Media, "HTMLTrackElement::HTMLTrackElement - %p", this);
58     ScriptWrappable::init(this);
59 }
60
61 HTMLTrackElement::~HTMLTrackElement()
62 {
63 #if !ENABLE(OILPAN)
64     if (m_track)
65         m_track->clearTrackElement();
66 #endif
67 }
68
69 PassRefPtrWillBeRawPtr<HTMLTrackElement> HTMLTrackElement::create(Document& document)
70 {
71     return adoptRefWillBeRefCountedGarbageCollected(new HTMLTrackElement(document));
72 }
73
74 Node::InsertionNotificationRequest HTMLTrackElement::insertedInto(ContainerNode* insertionPoint)
75 {
76     WTF_LOG(Media, "HTMLTrackElement::insertedInto");
77
78     // Since we've moved to a new parent, we may now be able to load.
79     scheduleLoad();
80
81     HTMLElement::insertedInto(insertionPoint);
82     HTMLMediaElement* parent = mediaElement();
83     if (insertionPoint == parent)
84         parent->didAddTrackElement(this);
85     return InsertionDone;
86 }
87
88 void HTMLTrackElement::removedFrom(ContainerNode* insertionPoint)
89 {
90     if (!parentNode() && isHTMLMediaElement(*insertionPoint))
91         toHTMLMediaElement(insertionPoint)->didRemoveTrackElement(this);
92     HTMLElement::removedFrom(insertionPoint);
93 }
94
95 void HTMLTrackElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
96 {
97     if (name == srcAttr) {
98         if (!value.isEmpty())
99             scheduleLoad();
100         else if (m_track)
101             m_track->removeAllCues();
102
103     // 4.8.10.12.3 Sourcing out-of-band text tracks
104     // As the kind, label, and srclang attributes are set, changed, or removed, the text track must update accordingly...
105     } else if (name == kindAttr) {
106         track()->setKind(value.lower());
107     } else if (name == labelAttr) {
108         track()->setLabel(value);
109     } else if (name == srclangAttr) {
110         track()->setLanguage(value);
111     } else if (name == idAttr) {
112         track()->setId(value);
113     } else if (name == defaultAttr) {
114         track()->setIsDefault(!value.isNull());
115     }
116
117     HTMLElement::parseAttribute(name, value);
118 }
119
120 const AtomicString& HTMLTrackElement::kind()
121 {
122     return track()->kind();
123 }
124
125 void HTMLTrackElement::setKind(const AtomicString& kind)
126 {
127     setAttribute(kindAttr, kind);
128 }
129
130 LoadableTextTrack* HTMLTrackElement::ensureTrack()
131 {
132     if (!m_track) {
133         // kind, label and language are updated by parseAttribute
134         m_track = LoadableTextTrack::create(this);
135     }
136     return m_track.get();
137 }
138
139 TextTrack* HTMLTrackElement::track()
140 {
141     return ensureTrack();
142 }
143
144 bool HTMLTrackElement::isURLAttribute(const Attribute& attribute) const
145 {
146     return attribute.name() == srcAttr || HTMLElement::isURLAttribute(attribute);
147 }
148
149 void HTMLTrackElement::scheduleLoad()
150 {
151     WTF_LOG(Media, "HTMLTrackElement::scheduleLoad");
152
153     // 1. If another occurrence of this algorithm is already running for this text track and its track element,
154     // abort these steps, letting that other algorithm take care of this element.
155     if (m_loadTimer.isActive())
156         return;
157
158     // 2. If the text track's text track mode is not set to one of hidden or showing, abort these steps.
159     if (ensureTrack()->mode() != TextTrack::hiddenKeyword() && ensureTrack()->mode() != TextTrack::showingKeyword())
160         return;
161
162     // 3. If the text track's track element does not have a media element as a parent, abort these steps.
163     if (!mediaElement())
164         return;
165
166     // 4. Run the remainder of these steps asynchronously, allowing whatever caused these steps to run to continue.
167     m_loadTimer.startOneShot(0, FROM_HERE);
168 }
169
170 void HTMLTrackElement::loadTimerFired(Timer<HTMLTrackElement>*)
171 {
172     if (!fastHasAttribute(srcAttr))
173         return;
174
175     WTF_LOG(Media, "HTMLTrackElement::loadTimerFired");
176
177     // 6. Set the text track readiness state to loading.
178     setReadyState(HTMLTrackElement::LOADING);
179
180     // 7. Let URL be the track URL of the track element.
181     KURL url = getNonEmptyURLAttribute(srcAttr);
182
183     // 8. If the track element's parent is a media element then let CORS mode be the state of the parent media
184     // element's crossorigin content attribute. Otherwise, let CORS mode be No CORS.
185     if (!canLoadUrl(url)) {
186         didCompleteLoad(HTMLTrackElement::Failure);
187         return;
188     }
189
190     ensureTrack()->scheduleLoad(url);
191 }
192
193 bool HTMLTrackElement::canLoadUrl(const KURL& url)
194 {
195     HTMLMediaElement* parent = mediaElement();
196     if (!parent)
197         return false;
198
199     // 4.8.10.12.3 Sourcing out-of-band text tracks
200
201     // 4. Download: If URL is not the empty string, perform a potentially CORS-enabled fetch of URL, with the
202     // mode being the state of the media element's crossorigin content attribute, the origin being the
203     // origin of the media element's Document, and the default origin behaviour set to fail.
204     if (url.isEmpty())
205         return false;
206
207     if (!document().contentSecurityPolicy()->allowMediaFromSource(url)) {
208         WTF_LOG(Media, "HTMLTrackElement::canLoadUrl(%s) -> rejected by Content Security Policy", urlForLoggingTrack(url).utf8().data());
209         return false;
210     }
211
212     return true;
213 }
214
215 void HTMLTrackElement::didCompleteLoad(LoadStatus status)
216 {
217     // 4.8.10.12.3 Sourcing out-of-band text tracks (continued)
218
219     // 4. Download: ...
220     // If the fetching algorithm fails for any reason (network error, the server returns an error
221     // code, a cross-origin check fails, etc), or if URL is the empty string or has the wrong origin
222     // as determined by the condition at the start of this step, or if the fetched resource is not in
223     // a supported format, then queue a task to first change the text track readiness state to failed
224     // to load and then fire a simple event named error at the track element; and then, once that task
225     // is queued, move on to the step below labeled monitoring.
226
227     if (status == Failure) {
228         setReadyState(HTMLTrackElement::TRACK_ERROR);
229         dispatchEvent(Event::create(EventTypeNames::error), IGNORE_EXCEPTION);
230         return;
231     }
232
233     // If the fetching algorithm does not fail, then the final task that is queued by the networking
234     // task source must run the following steps:
235     //     1. Change the text track readiness state to loaded.
236     setReadyState(HTMLTrackElement::LOADED);
237
238     //     2. If the file was successfully processed, fire a simple event named load at the
239     //        track element.
240     dispatchEvent(Event::create(EventTypeNames::load), IGNORE_EXCEPTION);
241 }
242
243 // NOTE: The values in the TextTrack::ReadinessState enum must stay in sync with those in HTMLTrackElement::ReadyState.
244 COMPILE_ASSERT(HTMLTrackElement::NONE == static_cast<HTMLTrackElement::ReadyState>(TextTrack::NotLoaded), TextTrackEnumNotLoaded_Is_Wrong_Should_Be_HTMLTrackElementEnumNONE);
245 COMPILE_ASSERT(HTMLTrackElement::LOADING == static_cast<HTMLTrackElement::ReadyState>(TextTrack::Loading), TextTrackEnumLoadingIsWrong_ShouldBe_HTMLTrackElementEnumLOADING);
246 COMPILE_ASSERT(HTMLTrackElement::LOADED == static_cast<HTMLTrackElement::ReadyState>(TextTrack::Loaded), TextTrackEnumLoaded_Is_Wrong_Should_Be_HTMLTrackElementEnumLOADED);
247 COMPILE_ASSERT(HTMLTrackElement::TRACK_ERROR == static_cast<HTMLTrackElement::ReadyState>(TextTrack::FailedToLoad), TextTrackEnumFailedToLoad_Is_Wrong_Should_Be_HTMLTrackElementEnumTRACK_ERROR);
248
249 void HTMLTrackElement::setReadyState(ReadyState state)
250 {
251     ensureTrack()->setReadinessState(static_cast<TextTrack::ReadinessState>(state));
252     if (HTMLMediaElement* parent = mediaElement())
253         return parent->textTrackReadyStateChanged(m_track.get());
254 }
255
256 HTMLTrackElement::ReadyState HTMLTrackElement::readyState()
257 {
258     return static_cast<ReadyState>(ensureTrack()->readinessState());
259 }
260
261 const AtomicString& HTMLTrackElement::mediaElementCrossOriginAttribute() const
262 {
263     if (HTMLMediaElement* parent = mediaElement())
264         return parent->fastGetAttribute(HTMLNames::crossoriginAttr);
265
266     return nullAtom;
267 }
268
269 HTMLMediaElement* HTMLTrackElement::mediaElement() const
270 {
271     Element* parent = parentElement();
272     if (isHTMLMediaElement(parent))
273         return toHTMLMediaElement(parent);
274     return 0;
275 }
276
277 void HTMLTrackElement::trace(Visitor* visitor)
278 {
279     visitor->trace(m_track);
280     HTMLElement::trace(visitor);
281 }
282
283 }