1/*
2 * Copyright (C) 2011, 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
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 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 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#if ENABLE(VIDEO_TRACK)
28#include "HTMLTrackElement.h"
29
30#include "ContentSecurityPolicy.h"
31#include "Event.h"
32#include "HTMLMediaElement.h"
33#include "HTMLNames.h"
34#include "Logging.h"
35#include "RuntimeEnabledFeatures.h"
36#include <wtf/text/CString.h>
37
38namespace WebCore {
39
40using namespace HTMLNames;
41
42#if !LOG_DISABLED
43static String urlForLoggingTrack(const URL& 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
53inline HTMLTrackElement::HTMLTrackElement(const QualifiedName& tagName, Document& document)
54    : HTMLElement(tagName, document)
55    , m_loadTimer(this, &HTMLTrackElement::loadTimerFired)
56{
57    LOG(Media, "HTMLTrackElement::HTMLTrackElement - %p", this);
58    ASSERT(hasTagName(trackTag));
59}
60
61HTMLTrackElement::~HTMLTrackElement()
62{
63    if (m_track)
64        m_track->clearClient();
65}
66
67PassRefPtr<HTMLTrackElement> HTMLTrackElement::create(const QualifiedName& tagName, Document& document)
68{
69    return adoptRef(new HTMLTrackElement(tagName, document));
70}
71
72Node::InsertionNotificationRequest HTMLTrackElement::insertedInto(ContainerNode& insertionPoint)
73{
74    // Since we've moved to a new parent, we may now be able to load.
75    scheduleLoad();
76
77    HTMLElement::insertedInto(insertionPoint);
78    HTMLMediaElement* parent = mediaElement();
79    if (&insertionPoint == parent) {
80        ensureTrack();
81        parent->didAddTextTrack(this);
82    }
83    return InsertionDone;
84}
85
86void HTMLTrackElement::removedFrom(ContainerNode& insertionPoint)
87{
88    if (!parentNode() && isHTMLMediaElement(insertionPoint))
89        toHTMLMediaElement(insertionPoint).didRemoveTextTrack(this);
90    HTMLElement::removedFrom(insertionPoint);
91}
92
93void HTMLTrackElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
94{
95    if (RuntimeEnabledFeatures::sharedFeatures().webkitVideoTrackEnabled()) {
96        if (name == srcAttr) {
97            if (!value.isEmpty())
98                scheduleLoad();
99            else if (m_track)
100                m_track->removeAllCues();
101
102        // 4.8.10.12.3 Sourcing out-of-band text tracks
103        // As the kind, label, and srclang attributes are set, changed, or removed, the text track must update accordingly...
104        } else if (name == kindAttr)
105            track()->setKind(value.lower());
106        else if (name == labelAttr)
107            track()->setLabel(value);
108        else if (name == srclangAttr)
109            track()->setLanguage(value);
110        else if (name == defaultAttr)
111            track()->setIsDefault(!value.isNull());
112    }
113
114    HTMLElement::parseAttribute(name, value);
115}
116
117String HTMLTrackElement::kind()
118{
119    return track()->kind();
120}
121
122void HTMLTrackElement::setKind(const String& kind)
123{
124    setAttribute(kindAttr, kind);
125}
126
127String HTMLTrackElement::srclang() const
128{
129    return getAttribute(srclangAttr);
130}
131
132void HTMLTrackElement::setSrclang(const String& srclang)
133{
134    setAttribute(srclangAttr, srclang);
135}
136
137String HTMLTrackElement::label() const
138{
139    return getAttribute(labelAttr);
140}
141
142void HTMLTrackElement::setLabel(const String& label)
143{
144    setAttribute(labelAttr, label);
145}
146
147bool HTMLTrackElement::isDefault() const
148{
149    return fastHasAttribute(defaultAttr);
150}
151
152void HTMLTrackElement::setIsDefault(bool isDefault)
153{
154    setBooleanAttribute(defaultAttr, isDefault);
155}
156
157LoadableTextTrack& HTMLTrackElement::ensureTrack()
158{
159    if (!m_track) {
160        // The kind attribute is an enumerated attribute, limited only to know values. It defaults to 'subtitles' if missing or invalid.
161        String kind = getAttribute(kindAttr).lower();
162        if (!TextTrack::isValidKindKeyword(kind))
163            kind = TextTrack::subtitlesKeyword();
164        m_track = LoadableTextTrack::create(this, kind, label(), srclang());
165    } else
166        m_track->setTrackElement(this);
167
168    return *m_track;
169}
170
171TextTrack* HTMLTrackElement::track()
172{
173    return &ensureTrack();
174}
175
176bool HTMLTrackElement::isURLAttribute(const Attribute& attribute) const
177{
178    return attribute.name() == srcAttr || HTMLElement::isURLAttribute(attribute);
179}
180
181void HTMLTrackElement::scheduleLoad()
182{
183    // 1. If another occurrence of this algorithm is already running for this text track and its track element,
184    // abort these steps, letting that other algorithm take care of this element.
185    if (m_loadTimer.isActive())
186        return;
187
188    if (!RuntimeEnabledFeatures::sharedFeatures().webkitVideoTrackEnabled())
189        return;
190
191    // 2. If the text track's text track mode is not set to one of hidden or showing, abort these steps.
192    if (ensureTrack().mode() != TextTrack::hiddenKeyword() && ensureTrack().mode() != TextTrack::showingKeyword())
193        return;
194
195    // 3. If the text track's track element does not have a media element as a parent, abort these steps.
196    if (!mediaElement())
197        return;
198
199    // 4. Run the remainder of these steps asynchronously, allowing whatever caused these steps to run to continue.
200    m_loadTimer.startOneShot(0);
201}
202
203void HTMLTrackElement::loadTimerFired(Timer<HTMLTrackElement>&)
204{
205    if (!fastHasAttribute(srcAttr))
206        return;
207
208    // 6. Set the text track readiness state to loading.
209    setReadyState(HTMLTrackElement::LOADING);
210
211    // 7. Let URL be the track URL of the track element.
212    URL url = getNonEmptyURLAttribute(srcAttr);
213
214    // 8. If the track element's parent is a media element then let CORS mode be the state of the parent media
215    // element's crossorigin content attribute. Otherwise, let CORS mode be No CORS.
216    if (!canLoadURL(url)) {
217        didCompleteLoad(HTMLTrackElement::Failure);
218        return;
219    }
220
221    ensureTrack().scheduleLoad(url);
222}
223
224bool HTMLTrackElement::canLoadURL(const URL& url)
225{
226    if (!RuntimeEnabledFeatures::sharedFeatures().webkitVideoTrackEnabled())
227        return false;
228
229    HTMLMediaElement* parent = mediaElement();
230    if (!parent)
231        return false;
232
233    // 4.8.10.12.3 Sourcing out-of-band text tracks
234
235    // 4. Download: If URL is not the empty string, perform a potentially CORS-enabled fetch of URL, with the
236    // mode being the state of the media element's crossorigin content attribute, the origin being the
237    // origin of the media element's Document, and the default origin behaviour set to fail.
238    if (url.isEmpty())
239        return false;
240
241    if (!document().contentSecurityPolicy()->allowMediaFromSource(url)) {
242        LOG(Media, "HTMLTrackElement::canLoadURL(%s) -> rejected by Content Security Policy", urlForLoggingTrack(url).utf8().data());
243        return false;
244    }
245
246    return dispatchBeforeLoadEvent(url.string());
247}
248
249void HTMLTrackElement::didCompleteLoad(LoadStatus status)
250{
251    // 4.8.10.12.3 Sourcing out-of-band text tracks (continued)
252
253    // 4. Download: ...
254    // If the fetching algorithm fails for any reason (network error, the server returns an error
255    // code, a cross-origin check fails, etc), or if URL is the empty string or has the wrong origin
256    // as determined by the condition at the start of this step, or if the fetched resource is not in
257    // a supported format, then queue a task to first change the text track readiness state to failed
258    // to load and then fire a simple event named error at the track element; and then, once that task
259    // is queued, move on to the step below labeled monitoring.
260
261    if (status == Failure) {
262        setReadyState(HTMLTrackElement::TRACK_ERROR);
263        dispatchEvent(Event::create(eventNames().errorEvent, false, false), IGNORE_EXCEPTION);
264        return;
265    }
266
267    // If the fetching algorithm does not fail, then the final task that is queued by the networking
268    // task source must run the following steps:
269    //     1. Change the text track readiness state to loaded.
270    setReadyState(HTMLTrackElement::LOADED);
271
272    //     2. If the file was successfully processed, fire a simple event named load at the
273    //        track element.
274    dispatchEvent(Event::create(eventNames().loadEvent, false, false), IGNORE_EXCEPTION);
275}
276
277// NOTE: The values in the TextTrack::ReadinessState enum must stay in sync with those in HTMLTrackElement::ReadyState.
278COMPILE_ASSERT(HTMLTrackElement::NONE == static_cast<HTMLTrackElement::ReadyState>(TextTrack::NotLoaded), TextTrackEnumNotLoaded_Is_Wrong_Should_Be_HTMLTrackElementEnumNONE);
279COMPILE_ASSERT(HTMLTrackElement::LOADING == static_cast<HTMLTrackElement::ReadyState>(TextTrack::Loading), TextTrackEnumLoadingIsWrong_ShouldBe_HTMLTrackElementEnumLOADING);
280COMPILE_ASSERT(HTMLTrackElement::LOADED == static_cast<HTMLTrackElement::ReadyState>(TextTrack::Loaded), TextTrackEnumLoaded_Is_Wrong_Should_Be_HTMLTrackElementEnumLOADED);
281COMPILE_ASSERT(HTMLTrackElement::TRACK_ERROR == static_cast<HTMLTrackElement::ReadyState>(TextTrack::FailedToLoad), TextTrackEnumFailedToLoad_Is_Wrong_Should_Be_HTMLTrackElementEnumTRACK_ERROR);
282
283void HTMLTrackElement::setReadyState(ReadyState state)
284{
285    ensureTrack().setReadinessState(static_cast<TextTrack::ReadinessState>(state));
286    if (HTMLMediaElement* parent = mediaElement())
287        return parent->textTrackReadyStateChanged(m_track.get());
288}
289
290HTMLTrackElement::ReadyState HTMLTrackElement::readyState()
291{
292    return static_cast<ReadyState>(ensureTrack().readinessState());
293}
294
295const AtomicString& HTMLTrackElement::mediaElementCrossOriginAttribute() const
296{
297    if (HTMLMediaElement* parent = mediaElement())
298        return parent->fastGetAttribute(HTMLNames::crossoriginAttr);
299
300    return nullAtom;
301}
302
303void HTMLTrackElement::textTrackKindChanged(TextTrack* track)
304{
305    if (HTMLMediaElement* parent = mediaElement())
306        return parent->textTrackKindChanged(track);
307}
308
309void HTMLTrackElement::textTrackModeChanged(TextTrack* track)
310{
311    // Since we've moved to a new parent, we may now be able to load.
312    if (readyState() == HTMLTrackElement::NONE)
313        scheduleLoad();
314
315    if (HTMLMediaElement* parent = mediaElement())
316        return parent->textTrackModeChanged(track);
317}
318
319void HTMLTrackElement::textTrackAddCues(TextTrack* track, const TextTrackCueList* cues)
320{
321    if (HTMLMediaElement* parent = mediaElement())
322        return parent->textTrackAddCues(track, cues);
323}
324
325void HTMLTrackElement::textTrackRemoveCues(TextTrack* track, const TextTrackCueList* cues)
326{
327    if (HTMLMediaElement* parent = mediaElement())
328        return parent->textTrackRemoveCues(track, cues);
329}
330
331void HTMLTrackElement::textTrackAddCue(TextTrack* track, PassRefPtr<TextTrackCue> cue)
332{
333    if (HTMLMediaElement* parent = mediaElement())
334        return parent->textTrackAddCue(track, cue);
335}
336
337void HTMLTrackElement::textTrackRemoveCue(TextTrack* track, PassRefPtr<TextTrackCue> cue)
338{
339    if (HTMLMediaElement* parent = mediaElement())
340        return parent->textTrackRemoveCue(track, cue);
341}
342
343HTMLMediaElement* HTMLTrackElement::mediaElement() const
344{
345    Element* parent = parentElement();
346    if (parent && parent->isMediaElement())
347        return toHTMLMediaElement(parentNode());
348
349    return 0;
350}
351
352}
353
354#endif
355