2 * Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012, 2013 Apple 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
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.
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.
27 #include "core/html/HTMLMediaElement.h"
30 #include "HTMLNames.h"
31 #include "RuntimeEnabledFeatures.h"
32 #include "bindings/v8/ExceptionState.h"
33 #include "bindings/v8/ExceptionStatePlaceholder.h"
34 #include "bindings/v8/ScriptController.h"
35 #include "bindings/v8/ScriptEventListener.h"
36 #include "core/css/MediaList.h"
37 #include "core/dom/Attribute.h"
38 #include "core/dom/ExceptionCode.h"
39 #include "core/dom/FullscreenElementStack.h"
40 #include "core/dom/shadow/ShadowRoot.h"
41 #include "core/events/Event.h"
42 #include "core/events/ThreadLocalEventNames.h"
43 #include "core/frame/ContentSecurityPolicy.h"
44 #include "core/frame/Frame.h"
45 #include "core/frame/Settings.h"
46 #include "core/frame/UseCounter.h"
47 #include "core/html/HTMLMediaSource.h"
48 #include "core/html/HTMLSourceElement.h"
49 #include "core/html/HTMLTrackElement.h"
50 #include "core/html/MediaController.h"
51 #include "core/html/MediaError.h"
52 #include "core/html/MediaFragmentURIParser.h"
53 #include "core/html/MediaKeyError.h"
54 #include "core/html/MediaKeyEvent.h"
55 #include "core/html/TimeRanges.h"
56 #include "core/html/shadow/MediaControls.h"
57 #include "core/html/track/InbandTextTrack.h"
58 #include "core/html/track/TextTrackCueList.h"
59 #include "core/html/track/TextTrackList.h"
60 #include "core/loader/FrameLoader.h"
61 #include "core/rendering/RenderLayerCompositor.h"
62 #include "core/rendering/RenderVideo.h"
63 #include "core/rendering/RenderView.h"
64 // FIXME: Remove dependency on modules/encryptedmedia (http://crbug.com/242754).
65 #include "modules/encryptedmedia/MediaKeyNeededEvent.h"
66 #include "modules/encryptedmedia/MediaKeys.h"
67 #include "platform/ContentType.h"
68 #include "platform/Language.h"
69 #include "platform/Logging.h"
70 #include "platform/MIMETypeFromURL.h"
71 #include "platform/MIMETypeRegistry.h"
72 #include "platform/NotImplemented.h"
73 #include "platform/UserGestureIndicator.h"
74 #include "platform/graphics/GraphicsLayer.h"
75 #include "platform/weborigin/SecurityOrigin.h"
76 #include "public/platform/Platform.h"
77 #include "public/platform/WebContentDecryptionModule.h"
78 #include "public/platform/WebInbandTextTrack.h"
79 #include "wtf/CurrentTime.h"
80 #include "wtf/MathExtras.h"
81 #include "wtf/NonCopyingSort.h"
82 #include "wtf/Uint8Array.h"
83 #include "wtf/text/CString.h"
86 #include "platform/audio/AudioSourceProvider.h"
87 #include "modules/webaudio/MediaElementAudioSourceNode.h"
91 using blink::WebInbandTextTrack;
92 using blink::WebMimeRegistry;
97 static String urlForLoggingMedia(const KURL& url)
99 static const unsigned maximumURLLengthForLogging = 128;
101 if (url.string().length() < maximumURLLengthForLogging)
103 return url.string().substring(0, maximumURLLengthForLogging) + "...";
106 static const char* boolString(bool val)
108 return val ? "true" : "false";
112 #ifndef LOG_MEDIA_EVENTS
113 // Default to not logging events because so many are generated they can overwhelm the rest of
115 #define LOG_MEDIA_EVENTS 0
118 #ifndef LOG_CACHED_TIME_WARNINGS
119 // Default to not logging warnings about excessive drift in the cached media time because it adds a
120 // fair amount of overhead and logging.
121 #define LOG_CACHED_TIME_WARNINGS 0
124 // URL protocol used to signal that the media source API is being used.
125 static const char mediaSourceBlobProtocol[] = "blob";
127 using namespace HTMLNames;
130 typedef HashMap<Document*, HashSet<HTMLMediaElement*> > DocumentElementSetMap;
131 static DocumentElementSetMap& documentToElementSetMap()
133 DEFINE_STATIC_LOCAL(DocumentElementSetMap, map, ());
137 static void addElementToDocumentMap(HTMLMediaElement* element, Document* document)
139 DocumentElementSetMap& map = documentToElementSetMap();
140 HashSet<HTMLMediaElement*> set = map.take(document);
142 map.add(document, set);
145 static void removeElementFromDocumentMap(HTMLMediaElement* element, Document* document)
147 DocumentElementSetMap& map = documentToElementSetMap();
148 HashSet<HTMLMediaElement*> set = map.take(document);
151 map.add(document, set);
154 static void throwExceptionForMediaKeyException(MediaPlayer::MediaKeyException exception, ExceptionState& exceptionState)
157 case MediaPlayer::NoError:
159 case MediaPlayer::InvalidPlayerState:
160 exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
162 case MediaPlayer::KeySystemNotSupported:
163 exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
165 case MediaPlayer::InvalidAccess:
166 exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
170 ASSERT_NOT_REACHED();
174 class TrackDisplayUpdateScope {
176 TrackDisplayUpdateScope(HTMLMediaElement* mediaElement)
178 m_mediaElement = mediaElement;
179 m_mediaElement->beginIgnoringTrackDisplayUpdateRequests();
181 ~TrackDisplayUpdateScope()
183 ASSERT(m_mediaElement);
184 m_mediaElement->endIgnoringTrackDisplayUpdateRequests();
188 HTMLMediaElement* m_mediaElement;
191 static bool canLoadURL(const KURL& url, const ContentType& contentType, const String& keySystem)
193 DEFINE_STATIC_LOCAL(const String, codecs, ("codecs"));
195 String contentMIMEType = contentType.type().lower();
196 String contentTypeCodecs = contentType.parameter(codecs);
198 // If the MIME type is missing or is not meaningful, try to figure it out from the URL.
199 if (contentMIMEType.isEmpty() || contentMIMEType == "application/octet-stream" || contentMIMEType == "text/plain") {
200 if (url.protocolIsData())
201 contentMIMEType = mimeTypeFromDataURL(url.string());
204 // If no MIME type is specified, always attempt to load.
205 if (contentMIMEType.isEmpty())
208 // 4.8.10.3 MIME types - In the absence of a specification to the contrary, the MIME type "application/octet-stream"
209 // when used with parameters, e.g. "application/octet-stream;codecs=theora", is a type that the user agent knows
211 if (contentMIMEType != "application/octet-stream" || contentTypeCodecs.isEmpty()) {
212 WebMimeRegistry::SupportsType supported = blink::Platform::current()->mimeRegistry()->supportsMediaMIMEType(contentMIMEType, contentTypeCodecs, keySystem.lower());
213 return supported > WebMimeRegistry::IsNotSupported;
219 WebMimeRegistry::SupportsType HTMLMediaElement::supportsType(const ContentType& contentType, const String& keySystem)
221 DEFINE_STATIC_LOCAL(const String, codecs, ("codecs"));
223 if (!RuntimeEnabledFeatures::mediaEnabled())
224 return WebMimeRegistry::IsNotSupported;
226 String type = contentType.type().lower();
227 // The codecs string is not lower-cased because MP4 values are case sensitive
228 // per http://tools.ietf.org/html/rfc4281#page-7.
229 String typeCodecs = contentType.parameter(codecs);
230 String system = keySystem.lower();
233 return WebMimeRegistry::IsNotSupported;
235 // 4.8.10.3 MIME types - The canPlayType(type) method must return the empty string if type is a type that the
236 // user agent knows it cannot render or is the type "application/octet-stream"
237 if (type == "application/octet-stream")
238 return WebMimeRegistry::IsNotSupported;
240 return blink::Platform::current()->mimeRegistry()->supportsMediaMIMEType(type, typeCodecs, system);
243 URLRegistry* HTMLMediaElement::s_mediaStreamRegistry = 0;
245 void HTMLMediaElement::setMediaStreamRegistry(URLRegistry* registry)
247 ASSERT(!s_mediaStreamRegistry);
248 s_mediaStreamRegistry = registry;
251 bool HTMLMediaElement::isMediaStreamURL(const String& url)
253 return s_mediaStreamRegistry ? s_mediaStreamRegistry->contains(url) : false;
256 HTMLMediaElement::HTMLMediaElement(const QualifiedName& tagName, Document& document)
257 : HTMLElement(tagName, document)
258 , ActiveDOMObject(&document)
259 , m_loadTimer(this, &HTMLMediaElement::loadTimerFired)
260 , m_progressEventTimer(this, &HTMLMediaElement::progressEventTimerFired)
261 , m_playbackProgressTimer(this, &HTMLMediaElement::playbackProgressTimerFired)
262 , m_playedTimeRanges()
263 , m_asyncEventQueue(GenericEventQueue::create(this))
264 , m_playbackRate(1.0f)
265 , m_defaultPlaybackRate(1.0f)
266 , m_networkState(NETWORK_EMPTY)
267 , m_readyState(HAVE_NOTHING)
268 , m_readyStateMaximum(HAVE_NOTHING)
271 , m_previousProgressTime(numeric_limits<double>::max())
272 , m_duration(numeric_limits<double>::quiet_NaN())
273 , m_lastTimeUpdateEventWallTime(0)
274 , m_lastTimeUpdateEventMovieTime(numeric_limits<double>::max())
275 , m_loadState(WaitingForSource)
278 , m_restrictions(NoRestrictions)
279 , m_preload(MediaPlayer::Auto)
280 , m_displayMode(Unknown)
281 , m_cachedTime(MediaPlayer::invalidTime())
282 , m_cachedTimeWallClockUpdateTime(0)
283 , m_minimumWallClockTimeToCacheMediaTime(0)
284 , m_fragmentStartTime(MediaPlayer::invalidTime())
285 , m_fragmentEndTime(MediaPlayer::invalidTime())
286 , m_pendingActionFlags(0)
288 , m_shouldDelayLoadEvent(false)
289 , m_haveFiredLoadedData(false)
291 , m_autoplaying(true)
295 , m_sentStalledEvent(false)
296 , m_sentEndEvent(false)
297 , m_pausedInternal(false)
298 , m_closedCaptionsVisible(false)
299 , m_completelyLoaded(false)
300 , m_havePreparedToPlay(false)
301 , m_tracksAreReady(true)
302 , m_haveVisibleTextTrack(false)
303 , m_processingPreferenceChange(false)
304 , m_lastTextTrackUpdateTime(-1)
306 , m_ignoreTrackDisplayUpdate(0)
307 #if ENABLE(WEB_AUDIO)
308 , m_audioSourceNode(0)
310 , m_emeMode(EmeModeNotSelected)
312 ASSERT(RuntimeEnabledFeatures::mediaEnabled());
314 WTF_LOG(Media, "HTMLMediaElement::HTMLMediaElement");
315 ScriptWrappable::init(this);
317 if (document.settings()) {
318 if (document.settings()->mediaPlaybackRequiresUserGesture())
319 addBehaviorRestriction(RequireUserGestureForPlayRestriction);
320 if (document.settings()->mediaFullscreenRequiresUserGesture())
321 addBehaviorRestriction(RequireUserGestureForFullscreenRestriction);
324 // We must always have a ShadowRoot so children like <source> will not render
325 // as they never have an insertion point.
326 ensureUserAgentShadowRoot();
327 setHasCustomStyleCallbacks();
328 addElementToDocumentMap(this, &document);
331 HTMLMediaElement::~HTMLMediaElement()
333 WTF_LOG(Media, "HTMLMediaElement::~HTMLMediaElement");
335 m_asyncEventQueue->close();
337 setShouldDelayLoadEvent(false);
339 m_textTracks->clearOwner();
341 for (unsigned i = 0; i < m_textTracks->length(); ++i)
342 m_textTracks->item(i)->clearClient();
345 if (m_mediaController) {
346 m_mediaController->removeMediaElement(this);
347 m_mediaController = 0;
352 setMediaKeysInternal(0);
354 removeElementFromDocumentMap(this, &document());
356 // Destroying the player may cause a resource load to be canceled,
357 // which could result in userCancelledLoad() being called back.
358 // Setting m_completelyLoaded ensures that such a call will not cause
359 // us to dispatch an abort event, which would result in a crash.
360 // See http://crbug.com/233654 for more details.
361 m_completelyLoaded = true;
363 // Destroying the player may cause a resource load to be canceled,
364 // which could result in Document::dispatchWindowLoadEvent() being
365 // called via ResourceFetch::didLoadResource() then
366 // FrameLoader::loadDone(). To prevent load event dispatching during
367 // object destruction, we use Document::incrementLoadEventDelayCount().
368 // See http://crbug.com/275223 for more details.
369 document().incrementLoadEventDelayCount();
371 clearMediaPlayerAndAudioSourceProviderClient();
373 document().decrementLoadEventDelayCount();
376 void HTMLMediaElement::didMoveToNewDocument(Document& oldDocument)
378 WTF_LOG(Media, "HTMLMediaElement::didMoveToNewDocument");
380 if (m_shouldDelayLoadEvent) {
381 document().incrementLoadEventDelayCount();
382 // Note: Keeping the load event delay count increment on oldDocument that was added
383 // when m_shouldDelayLoadEvent was set so that destruction of m_player can not
384 // cause load event dispatching in oldDocument.
386 // Incrementing the load event delay count so that destruction of m_player can not
387 // cause load event dispatching in oldDocument.
388 oldDocument.incrementLoadEventDelayCount();
391 removeElementFromDocumentMap(this, &oldDocument);
392 addElementToDocumentMap(this, &document());
394 // FIXME: This is a temporary fix to prevent this object from causing the
395 // MediaPlayer to dereference Frame and FrameLoader pointers from the
396 // previous document. A proper fix would provide a mechanism to allow this
397 // object to refresh the MediaPlayer's Frame and FrameLoader references on
398 // document changes so that playback can be resumed properly.
401 // Decrement the load event delay count on oldDocument now that m_player has been destroyed
402 // and there is no risk of dispatching a load event from within the destructor.
403 oldDocument.decrementLoadEventDelayCount();
405 HTMLElement::didMoveToNewDocument(oldDocument);
408 bool HTMLMediaElement::hasCustomFocusLogic() const
413 bool HTMLMediaElement::supportsFocus() const
415 if (ownerDocument()->isMediaDocument())
418 // If no controls specified, we should still be able to focus the element if it has tabIndex.
419 return controls() || HTMLElement::supportsFocus();
422 bool HTMLMediaElement::isMouseFocusable() const
427 void HTMLMediaElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
429 if (name == srcAttr) {
430 // Trigger a reload, as long as the 'src' attribute is present.
431 if (!value.isNull()) {
432 clearMediaPlayer(LoadMediaResource);
433 scheduleDelayedAction(LoadMediaResource);
435 } else if (name == controlsAttr)
436 configureMediaControls();
437 else if (name == preloadAttr) {
438 if (equalIgnoringCase(value, "none"))
439 m_preload = MediaPlayer::None;
440 else if (equalIgnoringCase(value, "metadata"))
441 m_preload = MediaPlayer::MetaData;
443 // The spec does not define an "invalid value default" but "auto" is suggested as the
444 // "missing value default", so use it for everything except "none" and "metadata"
445 m_preload = MediaPlayer::Auto;
448 // The attribute must be ignored if the autoplay attribute is present
449 if (!autoplay() && m_player)
450 m_player->setPreload(m_preload);
452 } else if (name == mediagroupAttr)
453 setMediaGroup(value);
454 else if (name == onbeforeloadAttr)
455 setAttributeEventListener(EventTypeNames::beforeload, createAttributeEventListener(this, name, value));
457 HTMLElement::parseAttribute(name, value);
460 void HTMLMediaElement::finishParsingChildren()
462 HTMLElement::finishParsingChildren();
464 if (!RuntimeEnabledFeatures::videoTrackEnabled())
467 for (Node* node = firstChild(); node; node = node->nextSibling()) {
468 if (node->hasTagName(trackTag)) {
469 scheduleDelayedAction(LoadTextTrackResource);
475 bool HTMLMediaElement::rendererIsNeeded(const RenderStyle& style)
477 return controls() ? HTMLElement::rendererIsNeeded(style) : false;
480 RenderObject* HTMLMediaElement::createRenderer(RenderStyle*)
482 return new RenderMedia(this);
485 Node::InsertionNotificationRequest HTMLMediaElement::insertedInto(ContainerNode* insertionPoint)
487 WTF_LOG(Media, "HTMLMediaElement::insertedInto");
489 HTMLElement::insertedInto(insertionPoint);
490 if (insertionPoint->inDocument()) {
493 if (!getAttribute(srcAttr).isEmpty() && m_networkState == NETWORK_EMPTY)
494 scheduleDelayedAction(LoadMediaResource);
497 configureMediaControls();
498 return InsertionDone;
501 void HTMLMediaElement::removedFrom(ContainerNode* insertionPoint)
503 WTF_LOG(Media, "HTMLMediaElement::removedFrom");
506 if (insertionPoint->inDocument()) {
507 configureMediaControls();
508 if (m_networkState > NETWORK_EMPTY)
512 HTMLElement::removedFrom(insertionPoint);
515 void HTMLMediaElement::attach(const AttachContext& context)
517 HTMLElement::attach(context);
520 renderer()->updateFromElement();
523 void HTMLMediaElement::didRecalcStyle(StyleRecalcChange)
526 renderer()->updateFromElement();
529 void HTMLMediaElement::scheduleDelayedAction(DelayedActionType actionType)
531 WTF_LOG(Media, "HTMLMediaElement::scheduleDelayedAction");
533 if ((actionType & LoadMediaResource) && !(m_pendingActionFlags & LoadMediaResource)) {
535 m_pendingActionFlags |= LoadMediaResource;
538 if (RuntimeEnabledFeatures::videoTrackEnabled() && (actionType & LoadTextTrackResource))
539 m_pendingActionFlags |= LoadTextTrackResource;
541 if (!m_loadTimer.isActive())
542 m_loadTimer.startOneShot(0);
545 void HTMLMediaElement::scheduleNextSourceChild()
547 // Schedule the timer to try the next <source> element WITHOUT resetting state ala prepareForLoad.
548 m_pendingActionFlags |= LoadMediaResource;
549 m_loadTimer.startOneShot(0);
552 void HTMLMediaElement::scheduleEvent(const AtomicString& eventName)
555 WTF_LOG(Media, "HTMLMediaElement::scheduleEvent - scheduling '%s'", eventName.ascii().data());
557 m_asyncEventQueue->enqueueEvent(Event::createCancelable(eventName));
560 void HTMLMediaElement::loadTimerFired(Timer<HTMLMediaElement>*)
562 RefPtr<HTMLMediaElement> protect(this); // loadNextSourceChild may fire 'beforeload', which can make arbitrary DOM mutations.
564 if (RuntimeEnabledFeatures::videoTrackEnabled() && (m_pendingActionFlags & LoadTextTrackResource))
565 configureTextTracks();
567 if (m_pendingActionFlags & LoadMediaResource) {
568 if (m_loadState == LoadingFromSourceElement)
569 loadNextSourceChild();
574 m_pendingActionFlags = 0;
577 PassRefPtr<MediaError> HTMLMediaElement::error() const
582 void HTMLMediaElement::setSrc(const AtomicString& url)
584 setAttribute(srcAttr, url);
587 HTMLMediaElement::NetworkState HTMLMediaElement::networkState() const
589 return m_networkState;
592 String HTMLMediaElement::canPlayType(const String& mimeType, const String& keySystem) const
594 if (!keySystem.isNull())
595 UseCounter::count(document(), UseCounter::CanPlayTypeKeySystem);
597 WebMimeRegistry::SupportsType support = supportsType(ContentType(mimeType), keySystem);
603 case WebMimeRegistry::IsNotSupported:
604 canPlay = emptyString();
606 case WebMimeRegistry::MayBeSupported:
609 case WebMimeRegistry::IsSupported:
610 canPlay = "probably";
614 WTF_LOG(Media, "HTMLMediaElement::canPlayType(%s, %s) -> %s", mimeType.utf8().data(), keySystem.utf8().data(), canPlay.utf8().data());
619 void HTMLMediaElement::load()
621 RefPtr<HTMLMediaElement> protect(this); // loadInternal may result in a 'beforeload' event, which can make arbitrary DOM mutations.
623 WTF_LOG(Media, "HTMLMediaElement::load()");
625 if (document().settings() && !document().settings()->mediaEnabled())
628 if (UserGestureIndicator::processingUserGesture())
629 removeBehaviorsRestrictionsAfterFirstUserGesture();
636 void HTMLMediaElement::prepareForLoad()
638 WTF_LOG(Media, "HTMLMediaElement::prepareForLoad");
640 // Perform the cleanup required for the resource load algorithm to run.
641 stopPeriodicTimers();
643 m_sentEndEvent = false;
644 m_sentStalledEvent = false;
645 m_haveFiredLoadedData = false;
646 m_completelyLoaded = false;
647 m_havePreparedToPlay = false;
648 m_displayMode = Unknown;
650 // 1 - Abort any already-running instance of the resource selection algorithm for this element.
651 m_loadState = WaitingForSource;
652 m_currentSourceNode = 0;
654 // 2 - If there are any tasks from the media element's media element event task source in
655 // one of the task queues, then remove those tasks.
656 cancelPendingEventsAndCallbacks();
658 // 3 - If the media element's networkState is set to NETWORK_LOADING or NETWORK_IDLE, queue
659 // a task to fire a simple event named abort at the media element.
660 if (m_networkState == NETWORK_LOADING || m_networkState == NETWORK_IDLE)
661 scheduleEvent(EventTypeNames::abort);
667 // 4 - If the media element's networkState is not set to NETWORK_EMPTY, then run these substeps
668 if (m_networkState != NETWORK_EMPTY) {
669 m_networkState = NETWORK_EMPTY;
670 m_readyState = HAVE_NOTHING;
671 m_readyStateMaximum = HAVE_NOTHING;
675 invalidateCachedTime();
676 scheduleEvent(EventTypeNames::emptied);
677 updateMediaController();
678 if (RuntimeEnabledFeatures::videoTrackEnabled())
679 updateActiveTextTrackCues(0);
682 // 5 - Set the playbackRate attribute to the value of the defaultPlaybackRate attribute.
683 setPlaybackRate(defaultPlaybackRate());
685 // 6 - Set the error attribute to null and the autoplaying flag to true.
687 m_autoplaying = true;
689 // 7 - Invoke the media element's resource selection algorithm.
691 // 8 - Note: Playback of any previously playing media resource for this element stops.
693 // The resource selection algorithm
694 // 1 - Set the networkState to NETWORK_NO_SOURCE
695 m_networkState = NETWORK_NO_SOURCE;
697 // 2 - Asynchronously await a stable state.
699 m_playedTimeRanges = TimeRanges::create();
701 m_duration = numeric_limits<double>::quiet_NaN();
703 // The spec doesn't say to block the load event until we actually run the asynchronous section
704 // algorithm, but do it now because we won't start that until after the timer fires and the
705 // event may have already fired by then.
706 setShouldDelayLoadEvent(true);
708 configureMediaControls();
711 void HTMLMediaElement::loadInternal()
713 // Some of the code paths below this function dispatch the BeforeLoad event. This ASSERT helps
714 // us catch those bugs more quickly without needing all the branches to align to actually
715 // trigger the event.
716 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
718 // HTMLMediaElement::textTracksAreReady will need "... the text tracks whose mode was not in the
719 // disabled state when the element's resource selection algorithm last started".
720 if (RuntimeEnabledFeatures::videoTrackEnabled()) {
721 m_textTracksWhenResourceSelectionBegan.clear();
723 for (unsigned i = 0; i < m_textTracks->length(); ++i) {
724 TextTrack* track = m_textTracks->item(i);
725 if (track->mode() != TextTrack::disabledKeyword())
726 m_textTracksWhenResourceSelectionBegan.append(track);
731 selectMediaResource();
734 void HTMLMediaElement::selectMediaResource()
736 WTF_LOG(Media, "HTMLMediaElement::selectMediaResource");
738 enum Mode { attribute, children };
740 // 3 - If the media element has a src attribute, then let mode be attribute.
741 Mode mode = attribute;
742 if (!fastHasAttribute(srcAttr)) {
744 for (node = firstChild(); node; node = node->nextSibling()) {
745 if (node->hasTagName(sourceTag))
749 // Otherwise, if the media element does not have a src attribute but has a source
750 // element child, then let mode be children and let candidate be the first such
751 // source element child in tree order.
754 m_nextChildNodeToConsider = node;
755 m_currentSourceNode = 0;
757 // Otherwise the media element has neither a src attribute nor a source element
758 // child: set the networkState to NETWORK_EMPTY, and abort these steps; the
759 // synchronous section ends.
760 m_loadState = WaitingForSource;
761 setShouldDelayLoadEvent(false);
762 m_networkState = NETWORK_EMPTY;
764 WTF_LOG(Media, "HTMLMediaElement::selectMediaResource, nothing to load");
769 // 4 - Set the media element's delaying-the-load-event flag to true (this delays the load event),
770 // and set its networkState to NETWORK_LOADING.
771 setShouldDelayLoadEvent(true);
772 m_networkState = NETWORK_LOADING;
774 // 5 - Queue a task to fire a simple event named loadstart at the media element.
775 scheduleEvent(EventTypeNames::loadstart);
777 // 6 - If mode is attribute, then run these substeps
778 if (mode == attribute) {
779 m_loadState = LoadingFromSrcAttr;
781 // If the src attribute's value is the empty string ... jump down to the failed step below
782 KURL mediaURL = getNonEmptyURLAttribute(srcAttr);
783 if (mediaURL.isEmpty()) {
784 mediaLoadingFailed(MediaPlayer::FormatError);
785 WTF_LOG(Media, "HTMLMediaElement::selectMediaResource, empty 'src'");
789 if (!isSafeToLoadURL(mediaURL, Complain) || !dispatchBeforeLoadEvent(mediaURL.string())) {
790 mediaLoadingFailed(MediaPlayer::FormatError);
794 // No type or key system information is available when the url comes
795 // from the 'src' attribute so MediaPlayer
796 // will have to pick a media engine based on the file extension.
797 ContentType contentType((String()));
798 loadResource(mediaURL, contentType, String());
799 WTF_LOG(Media, "HTMLMediaElement::selectMediaResource, using 'src' attribute url");
803 // Otherwise, the source elements will be used
804 loadNextSourceChild();
807 void HTMLMediaElement::loadNextSourceChild()
809 ContentType contentType((String()));
811 KURL mediaURL = selectNextSourceChild(&contentType, &keySystem, Complain);
812 if (!mediaURL.isValid()) {
813 waitForSourceChange();
817 // Recreate the media player for the new url
820 m_loadState = LoadingFromSourceElement;
821 loadResource(mediaURL, contentType, keySystem);
824 void HTMLMediaElement::loadResource(const KURL& url, ContentType& contentType, const String& keySystem)
826 ASSERT(isSafeToLoadURL(url, Complain));
828 WTF_LOG(Media, "HTMLMediaElement::loadResource(%s, %s, %s)", urlForLoggingMedia(url).utf8().data(), contentType.raw().utf8().data(), keySystem.utf8().data());
830 Frame* frame = document().frame();
832 mediaLoadingFailed(MediaPlayer::FormatError);
836 // The resource fetch algorithm
837 m_networkState = NETWORK_LOADING;
839 // Set m_currentSrc *before* changing to the cache url, the fact that we are loading from the app
840 // cache is an internal detail not exposed through the media element API.
843 WTF_LOG(Media, "HTMLMediaElement::loadResource - m_currentSrc -> %s", urlForLoggingMedia(m_currentSrc).utf8().data());
845 blink::WebMediaPlayer::LoadType loadType = blink::WebMediaPlayer::LoadTypeURL;
847 startProgressEventTimer();
849 // Reset display mode to force a recalculation of what to show because we are resetting the player.
850 setDisplayMode(Unknown);
853 m_player->setPreload(m_preload);
855 if (fastHasAttribute(mutedAttr))
859 ASSERT(!m_mediaSource);
861 bool attemptLoad = true;
863 if (url.protocolIs(mediaSourceBlobProtocol)) {
864 if (isMediaStreamURL(url.string())) {
865 loadType = blink::WebMediaPlayer::LoadTypeMediaStream;
866 removeBehaviorRestriction(RequireUserGestureForPlayRestriction);
868 m_mediaSource = HTMLMediaSource::lookup(url.string());
871 loadType = blink::WebMediaPlayer::LoadTypeMediaSource;
873 if (!m_mediaSource->attachToElement(this)) {
874 // Forget our reference to the MediaSource, so we leave it alone
875 // while processing remainder of load failure.
883 if (attemptLoad && canLoadURL(url, contentType, keySystem)) {
884 m_player->load(loadType, url);
886 mediaLoadingFailed(MediaPlayer::FormatError);
889 // If there is no poster to display, allow the media engine to render video frames as soon as
890 // they are available.
891 updateDisplayState();
894 renderer()->updateFromElement();
897 static bool trackIndexCompare(TextTrack* a,
900 return a->trackIndex() - b->trackIndex() < 0;
903 static bool eventTimeCueCompare(const std::pair<double, TextTrackCue*>& a,
904 const std::pair<double, TextTrackCue*>& b)
906 // 12 - Sort the tasks in events in ascending time order (tasks with earlier
908 if (a.first != b.first)
909 return a.first - b.first < 0;
911 // If the cues belong to different text tracks, it doesn't make sense to
912 // compare the two tracks by the relative cue order, so return the relative
914 if (a.second->track() != b.second->track())
915 return trackIndexCompare(a.second->track(), b.second->track());
917 // 12 - Further sort tasks in events that have the same time by the
918 // relative text track cue order of the text track cues associated
920 return a.second->cueIndex() - b.second->cueIndex() < 0;
924 void HTMLMediaElement::updateActiveTextTrackCues(double movieTime)
926 // 4.8.10.8 Playing the media resource
928 // If the current playback position changes while the steps are running,
929 // then the user agent must wait for the steps to complete, and then must
930 // immediately rerun the steps.
931 if (ignoreTrackDisplayUpdateRequests())
934 // 1 - Let current cues be a list of cues, initialized to contain all the
935 // cues of all the hidden, showing, or showing by default text tracks of the
936 // media element (not the disabled ones) whose start times are less than or
937 // equal to the current playback position and whose end times are greater
938 // than the current playback position.
941 // The user agent must synchronously unset [the text track cue active] flag
942 // whenever ... the media element's readyState is changed back to HAVE_NOTHING.
943 if (m_readyState != HAVE_NOTHING && m_player)
944 currentCues = m_cueTree.allOverlaps(m_cueTree.createInterval(movieTime, movieTime));
946 CueList previousCues;
949 // 2 - Let other cues be a list of cues, initialized to contain all the cues
950 // of hidden, showing, and showing by default text tracks of the media
951 // element that are not present in current cues.
952 previousCues = m_currentlyActiveCues;
954 // 3 - Let last time be the current playback position at the time this
955 // algorithm was last run for this media element, if this is not the first
957 double lastTime = m_lastTextTrackUpdateTime;
959 // 4 - If the current playback position has, since the last time this
960 // algorithm was run, only changed through its usual monotonic increase
961 // during normal playback, then let missed cues be the list of cues in other
962 // cues whose start times are greater than or equal to last time and whose
963 // end times are less than or equal to the current playback position.
964 // Otherwise, let missed cues be an empty list.
965 if (lastTime >= 0 && m_lastSeekTime < movieTime) {
966 CueList potentiallySkippedCues =
967 m_cueTree.allOverlaps(m_cueTree.createInterval(lastTime, movieTime));
969 for (size_t i = 0; i < potentiallySkippedCues.size(); ++i) {
970 double cueStartTime = potentiallySkippedCues[i].low();
971 double cueEndTime = potentiallySkippedCues[i].high();
973 // Consider cues that may have been missed since the last seek time.
974 if (cueStartTime > max(m_lastSeekTime, lastTime) && cueEndTime < movieTime)
975 missedCues.append(potentiallySkippedCues[i]);
979 m_lastTextTrackUpdateTime = movieTime;
981 // 5 - If the time was reached through the usual monotonic increase of the
982 // current playback position during normal playback, and if the user agent
983 // has not fired a timeupdate event at the element in the past 15 to 250ms
984 // and is not still running event handlers for such an event, then the user
985 // agent must queue a task to fire a simple event named timeupdate at the
986 // element. (In the other cases, such as explicit seeks, relevant events get
987 // fired as part of the overall process of changing the current playback
989 if (!m_seeking && m_lastSeekTime <= lastTime)
990 scheduleTimeupdateEvent(true);
992 // Explicitly cache vector sizes, as their content is constant from here.
993 size_t currentCuesSize = currentCues.size();
994 size_t missedCuesSize = missedCues.size();
995 size_t previousCuesSize = previousCues.size();
997 // 6 - If all of the cues in current cues have their text track cue active
998 // flag set, none of the cues in other cues have their text track cue active
999 // flag set, and missed cues is empty, then abort these steps.
1000 bool activeSetChanged = missedCuesSize;
1002 for (size_t i = 0; !activeSetChanged && i < previousCuesSize; ++i)
1003 if (!currentCues.contains(previousCues[i]) && previousCues[i].data()->isActive())
1004 activeSetChanged = true;
1006 for (size_t i = 0; i < currentCuesSize; ++i) {
1007 currentCues[i].data()->updateDisplayTree(movieTime);
1009 if (!currentCues[i].data()->isActive())
1010 activeSetChanged = true;
1013 if (!activeSetChanged)
1016 // 7 - If the time was reached through the usual monotonic increase of the
1017 // current playback position during normal playback, and there are cues in
1018 // other cues that have their text track cue pause-on-exi flag set and that
1019 // either have their text track cue active flag set or are also in missed
1020 // cues, then immediately pause the media element.
1021 for (size_t i = 0; !m_paused && i < previousCuesSize; ++i) {
1022 if (previousCues[i].data()->pauseOnExit()
1023 && previousCues[i].data()->isActive()
1024 && !currentCues.contains(previousCues[i]))
1028 for (size_t i = 0; !m_paused && i < missedCuesSize; ++i) {
1029 if (missedCues[i].data()->pauseOnExit())
1033 // 8 - Let events be a list of tasks, initially empty. Each task in this
1034 // list will be associated with a text track, a text track cue, and a time,
1035 // which are used to sort the list before the tasks are queued.
1036 Vector<std::pair<double, TextTrackCue*> > eventTasks;
1038 // 8 - Let affected tracks be a list of text tracks, initially empty.
1039 Vector<TextTrack*> affectedTracks;
1041 for (size_t i = 0; i < missedCuesSize; ++i) {
1042 // 9 - For each text track cue in missed cues, prepare an event named enter
1043 // for the TextTrackCue object with the text track cue start time.
1044 eventTasks.append(std::make_pair(missedCues[i].data()->startTime(),
1045 missedCues[i].data()));
1047 // 10 - For each text track [...] in missed cues, prepare an event
1048 // named exit for the TextTrackCue object with the with the later of
1049 // the text track cue end time and the text track cue start time.
1051 // Note: An explicit task is added only if the cue is NOT a zero or
1052 // negative length cue. Otherwise, the need for an exit event is
1053 // checked when these tasks are actually queued below. This doesn't
1054 // affect sorting events before dispatch either, because the exit
1055 // event has the same time as the enter event.
1056 if (missedCues[i].data()->startTime() < missedCues[i].data()->endTime())
1057 eventTasks.append(std::make_pair(missedCues[i].data()->endTime(),
1058 missedCues[i].data()));
1061 for (size_t i = 0; i < previousCuesSize; ++i) {
1062 // 10 - For each text track cue in other cues that has its text
1063 // track cue active flag set prepare an event named exit for the
1064 // TextTrackCue object with the text track cue end time.
1065 if (!currentCues.contains(previousCues[i]))
1066 eventTasks.append(std::make_pair(previousCues[i].data()->endTime(),
1067 previousCues[i].data()));
1070 for (size_t i = 0; i < currentCuesSize; ++i) {
1071 // 11 - For each text track cue in current cues that does not have its
1072 // text track cue active flag set, prepare an event named enter for the
1073 // TextTrackCue object with the text track cue start time.
1074 if (!previousCues.contains(currentCues[i]))
1075 eventTasks.append(std::make_pair(currentCues[i].data()->startTime(),
1076 currentCues[i].data()));
1079 // 12 - Sort the tasks in events in ascending time order (tasks with earlier
1081 nonCopyingSort(eventTasks.begin(), eventTasks.end(), eventTimeCueCompare);
1083 for (size_t i = 0; i < eventTasks.size(); ++i) {
1084 if (!affectedTracks.contains(eventTasks[i].second->track()))
1085 affectedTracks.append(eventTasks[i].second->track());
1087 // 13 - Queue each task in events, in list order.
1088 RefPtr<Event> event;
1090 // Each event in eventTasks may be either an enterEvent or an exitEvent,
1091 // depending on the time that is associated with the event. This
1092 // correctly identifies the type of the event, if the startTime is
1093 // less than the endTime in the cue.
1094 if (eventTasks[i].second->startTime() >= eventTasks[i].second->endTime()) {
1095 event = Event::create(EventTypeNames::enter);
1096 event->setTarget(eventTasks[i].second);
1097 m_asyncEventQueue->enqueueEvent(event.release());
1099 event = Event::create(EventTypeNames::exit);
1100 event->setTarget(eventTasks[i].second);
1101 m_asyncEventQueue->enqueueEvent(event.release());
1103 if (eventTasks[i].first == eventTasks[i].second->startTime())
1104 event = Event::create(EventTypeNames::enter);
1106 event = Event::create(EventTypeNames::exit);
1108 event->setTarget(eventTasks[i].second);
1109 m_asyncEventQueue->enqueueEvent(event.release());
1113 // 14 - Sort affected tracks in the same order as the text tracks appear in
1114 // the media element's list of text tracks, and remove duplicates.
1115 nonCopyingSort(affectedTracks.begin(), affectedTracks.end(), trackIndexCompare);
1117 // 15 - For each text track in affected tracks, in the list order, queue a
1118 // task to fire a simple event named cuechange at the TextTrack object, and, ...
1119 for (size_t i = 0; i < affectedTracks.size(); ++i) {
1120 RefPtr<Event> event = Event::create(EventTypeNames::cuechange);
1121 event->setTarget(affectedTracks[i]);
1123 m_asyncEventQueue->enqueueEvent(event.release());
1125 // ... if the text track has a corresponding track element, to then fire a
1126 // simple event named cuechange at the track element as well.
1127 if (affectedTracks[i]->trackType() == TextTrack::TrackElement) {
1128 RefPtr<Event> event = Event::create(EventTypeNames::cuechange);
1129 HTMLTrackElement* trackElement = static_cast<LoadableTextTrack*>(affectedTracks[i])->trackElement();
1130 ASSERT(trackElement);
1131 event->setTarget(trackElement);
1133 m_asyncEventQueue->enqueueEvent(event.release());
1137 // 16 - Set the text track cue active flag of all the cues in the current
1138 // cues, and unset the text track cue active flag of all the cues in the
1140 for (size_t i = 0; i < currentCuesSize; ++i)
1141 currentCues[i].data()->setIsActive(true);
1143 for (size_t i = 0; i < previousCuesSize; ++i)
1144 if (!currentCues.contains(previousCues[i]))
1145 previousCues[i].data()->setIsActive(false);
1147 // Update the current active cues.
1148 m_currentlyActiveCues = currentCues;
1150 if (activeSetChanged)
1151 updateTextTrackDisplay();
1154 bool HTMLMediaElement::textTracksAreReady() const
1156 // 4.8.10.12.1 Text track model
1158 // The text tracks of a media element are ready if all the text tracks whose mode was not
1159 // in the disabled state when the element's resource selection algorithm last started now
1160 // have a text track readiness state of loaded or failed to load.
1161 for (unsigned i = 0; i < m_textTracksWhenResourceSelectionBegan.size(); ++i) {
1162 if (m_textTracksWhenResourceSelectionBegan[i]->readinessState() == TextTrack::Loading
1163 || m_textTracksWhenResourceSelectionBegan[i]->readinessState() == TextTrack::NotLoaded)
1170 void HTMLMediaElement::textTrackReadyStateChanged(TextTrack* track)
1172 if (m_player && m_textTracksWhenResourceSelectionBegan.contains(track)) {
1173 if (track->readinessState() != TextTrack::Loading)
1174 setReadyState(m_player->readyState());
1176 // The track readiness state might have changed as a result of the user
1177 // clicking the captions button. In this case, a check whether all the
1178 // resources have failed loading should be done in order to hide the CC button.
1179 if (hasMediaControls() && track->readinessState() == TextTrack::FailedToLoad)
1180 mediaControls()->refreshClosedCaptionsButtonVisibility();
1184 void HTMLMediaElement::textTrackModeChanged(TextTrack* track)
1186 if (track->trackType() == TextTrack::TrackElement) {
1187 // 4.8.10.12.3 Sourcing out-of-band text tracks
1188 // ... when a text track corresponding to a track element is created with text track
1189 // mode set to disabled and subsequently changes its text track mode to hidden, showing,
1190 // or showing by default for the first time, the user agent must immediately and synchronously
1191 // run the following algorithm ...
1193 for (Node* node = firstChild(); node; node = node->nextSibling()) {
1194 if (!node->hasTagName(trackTag))
1196 HTMLTrackElement* trackElement = toHTMLTrackElement(node);
1197 if (trackElement->track() != track)
1200 // Mark this track as "configured" so configureTextTracks won't change the mode again.
1201 track->setHasBeenConfigured(true);
1202 if (track->mode() != TextTrack::disabledKeyword()) {
1203 if (trackElement->readyState() == HTMLTrackElement::LOADED)
1204 textTrackAddCues(track, track->cues());
1206 // If this is the first added track, create the list of text tracks.
1208 m_textTracks = TextTrackList::create(this);
1212 } else if (track->trackType() == TextTrack::AddTrack && track->mode() != TextTrack::disabledKeyword())
1213 textTrackAddCues(track, track->cues());
1215 configureTextTrackDisplay(AssumeVisibleChange);
1217 ASSERT(textTracks()->contains(track));
1218 textTracks()->scheduleChangeEvent();
1221 void HTMLMediaElement::textTrackKindChanged(TextTrack* track)
1223 if (track->kind() != TextTrack::captionsKeyword() && track->kind() != TextTrack::subtitlesKeyword() && track->mode() == TextTrack::showingKeyword())
1224 track->setMode(TextTrack::hiddenKeyword());
1227 void HTMLMediaElement::beginIgnoringTrackDisplayUpdateRequests()
1229 ++m_ignoreTrackDisplayUpdate;
1232 void HTMLMediaElement::endIgnoringTrackDisplayUpdateRequests()
1234 ASSERT(m_ignoreTrackDisplayUpdate);
1235 --m_ignoreTrackDisplayUpdate;
1236 if (!m_ignoreTrackDisplayUpdate && m_active)
1237 updateActiveTextTrackCues(currentTime());
1240 void HTMLMediaElement::textTrackAddCues(TextTrack* track, const TextTrackCueList* cues)
1242 WTF_LOG(Media, "HTMLMediaElement::textTrackAddCues");
1243 if (track->mode() == TextTrack::disabledKeyword())
1246 TrackDisplayUpdateScope scope(this);
1247 for (size_t i = 0; i < cues->length(); ++i)
1248 textTrackAddCue(cues->item(i)->track(), cues->item(i));
1251 void HTMLMediaElement::textTrackRemoveCues(TextTrack*, const TextTrackCueList* cues)
1253 WTF_LOG(Media, "HTMLMediaElement::textTrackRemoveCues");
1255 TrackDisplayUpdateScope scope(this);
1256 for (size_t i = 0; i < cues->length(); ++i)
1257 textTrackRemoveCue(cues->item(i)->track(), cues->item(i));
1260 void HTMLMediaElement::textTrackAddCue(TextTrack* track, PassRefPtr<TextTrackCue> cue)
1262 if (track->mode() == TextTrack::disabledKeyword())
1265 // Negative duration cues need be treated in the interval tree as
1266 // zero-length cues.
1267 double endTime = max(cue->startTime(), cue->endTime());
1269 CueInterval interval = m_cueTree.createInterval(cue->startTime(), endTime, cue.get());
1270 if (!m_cueTree.contains(interval))
1271 m_cueTree.add(interval);
1272 updateActiveTextTrackCues(currentTime());
1275 void HTMLMediaElement::textTrackRemoveCue(TextTrack*, PassRefPtr<TextTrackCue> cue)
1277 // Negative duration cues need to be treated in the interval tree as
1278 // zero-length cues.
1279 double endTime = max(cue->startTime(), cue->endTime());
1281 CueInterval interval = m_cueTree.createInterval(cue->startTime(), endTime, cue.get());
1282 m_cueTree.remove(interval);
1284 // Since the cue will be removed from the media element and likely the
1285 // TextTrack might also be destructed, notifying the region of the cue
1286 // removal shouldn't be done.
1287 cue->notifyRegionWhenRemovingDisplayTree(false);
1289 size_t index = m_currentlyActiveCues.find(interval);
1290 if (index != kNotFound) {
1291 m_currentlyActiveCues.remove(index);
1292 cue->setIsActive(false);
1294 cue->removeDisplayTree();
1295 updateActiveTextTrackCues(currentTime());
1297 cue->notifyRegionWhenRemovingDisplayTree(true);
1301 bool HTMLMediaElement::isSafeToLoadURL(const KURL& url, InvalidURLAction actionIfInvalid)
1303 if (!url.isValid()) {
1304 WTF_LOG(Media, "HTMLMediaElement::isSafeToLoadURL(%s) -> FALSE because url is invalid", urlForLoggingMedia(url).utf8().data());
1308 Frame* frame = document().frame();
1309 if (!frame || !document().securityOrigin()->canDisplay(url)) {
1310 if (actionIfInvalid == Complain)
1311 FrameLoader::reportLocalLoadFailed(frame, url.elidedString());
1312 WTF_LOG(Media, "HTMLMediaElement::isSafeToLoadURL(%s) -> FALSE rejected by SecurityOrigin", urlForLoggingMedia(url).utf8().data());
1316 if (!document().contentSecurityPolicy()->allowMediaFromSource(url)) {
1317 WTF_LOG(Media, "HTMLMediaElement::isSafeToLoadURL(%s) -> rejected by Content Security Policy", urlForLoggingMedia(url).utf8().data());
1324 void HTMLMediaElement::startProgressEventTimer()
1326 if (m_progressEventTimer.isActive())
1329 m_previousProgressTime = WTF::currentTime();
1330 // 350ms is not magic, it is in the spec!
1331 m_progressEventTimer.startRepeating(0.350);
1334 void HTMLMediaElement::waitForSourceChange()
1336 WTF_LOG(Media, "HTMLMediaElement::waitForSourceChange");
1338 stopPeriodicTimers();
1339 m_loadState = WaitingForSource;
1341 // 6.17 - Waiting: Set the element's networkState attribute to the NETWORK_NO_SOURCE value
1342 m_networkState = NETWORK_NO_SOURCE;
1344 // 6.18 - Set the element's delaying-the-load-event flag to false. This stops delaying the load event.
1345 setShouldDelayLoadEvent(false);
1347 updateDisplayState();
1350 renderer()->updateFromElement();
1353 void HTMLMediaElement::noneSupported()
1355 WTF_LOG(Media, "HTMLMediaElement::noneSupported");
1357 stopPeriodicTimers();
1358 m_loadState = WaitingForSource;
1359 m_currentSourceNode = 0;
1362 // 6 - Reaching this step indicates that the media resource failed to load or that the given
1363 // URL could not be resolved. In one atomic operation, run the following steps:
1365 // 6.1 - Set the error attribute to a new MediaError object whose code attribute is set to
1366 // MEDIA_ERR_SRC_NOT_SUPPORTED.
1367 m_error = MediaError::create(MediaError::MEDIA_ERR_SRC_NOT_SUPPORTED);
1369 // 6.2 - Forget the media element's media-resource-specific text tracks.
1371 // 6.3 - Set the element's networkState attribute to the NETWORK_NO_SOURCE value.
1372 m_networkState = NETWORK_NO_SOURCE;
1374 // 7 - Queue a task to fire a simple event named error at the media element.
1375 scheduleEvent(EventTypeNames::error);
1379 // 8 - Set the element's delaying-the-load-event flag to false. This stops delaying the load event.
1380 setShouldDelayLoadEvent(false);
1382 // 9 - Abort these steps. Until the load() method is invoked or the src attribute is changed,
1383 // the element won't attempt to load another resource.
1385 updateDisplayState();
1388 renderer()->updateFromElement();
1391 void HTMLMediaElement::mediaEngineError(PassRefPtr<MediaError> err)
1393 WTF_LOG(Media, "HTMLMediaElement::mediaEngineError(%d)", static_cast<int>(err->code()));
1395 // 1 - The user agent should cancel the fetching process.
1396 stopPeriodicTimers();
1397 m_loadState = WaitingForSource;
1399 // 2 - Set the error attribute to a new MediaError object whose code attribute is
1400 // set to MEDIA_ERR_NETWORK/MEDIA_ERR_DECODE.
1403 // 3 - Queue a task to fire a simple event named error at the media element.
1404 scheduleEvent(EventTypeNames::error);
1408 // 4 - Set the element's networkState attribute to the NETWORK_EMPTY value and queue a
1409 // task to fire a simple event called emptied at the element.
1410 m_networkState = NETWORK_EMPTY;
1411 scheduleEvent(EventTypeNames::emptied);
1413 // 5 - Set the element's delaying-the-load-event flag to false. This stops delaying the load event.
1414 setShouldDelayLoadEvent(false);
1416 // 6 - Abort the overall resource selection algorithm.
1417 m_currentSourceNode = 0;
1420 void HTMLMediaElement::cancelPendingEventsAndCallbacks()
1422 WTF_LOG(Media, "HTMLMediaElement::cancelPendingEventsAndCallbacks");
1423 m_asyncEventQueue->cancelAllEvents();
1425 for (Node* node = firstChild(); node; node = node->nextSibling()) {
1426 if (node->hasTagName(sourceTag))
1427 toHTMLSourceElement(node)->cancelPendingErrorEvent();
1431 void HTMLMediaElement::mediaPlayerNetworkStateChanged()
1433 setNetworkState(m_player->networkState());
1436 void HTMLMediaElement::mediaLoadingFailed(MediaPlayer::NetworkState error)
1438 stopPeriodicTimers();
1440 // If we failed while trying to load a <source> element, the movie was never parsed, and there are more
1441 // <source> children, schedule the next one
1442 if (m_readyState < HAVE_METADATA && m_loadState == LoadingFromSourceElement) {
1444 if (m_currentSourceNode)
1445 m_currentSourceNode->scheduleErrorEvent();
1447 WTF_LOG(Media, "HTMLMediaElement::setNetworkState - error event not sent, <source> was removed");
1449 if (havePotentialSourceChild()) {
1450 WTF_LOG(Media, "HTMLMediaElement::setNetworkState - scheduling next <source>");
1451 scheduleNextSourceChild();
1453 WTF_LOG(Media, "HTMLMediaElement::setNetworkState - no more <source> elements, waiting");
1454 waitForSourceChange();
1460 if (error == MediaPlayer::NetworkError && m_readyState >= HAVE_METADATA)
1461 mediaEngineError(MediaError::create(MediaError::MEDIA_ERR_NETWORK));
1462 else if (error == MediaPlayer::DecodeError)
1463 mediaEngineError(MediaError::create(MediaError::MEDIA_ERR_DECODE));
1464 else if ((error == MediaPlayer::FormatError || error == MediaPlayer::NetworkError) && m_loadState == LoadingFromSrcAttr)
1467 updateDisplayState();
1468 if (hasMediaControls())
1469 mediaControls()->reset();
1472 void HTMLMediaElement::setNetworkState(MediaPlayer::NetworkState state)
1474 WTF_LOG(Media, "HTMLMediaElement::setNetworkState(%d) - current state is %d", static_cast<int>(state), static_cast<int>(m_networkState));
1476 if (state == MediaPlayer::Empty) {
1477 // Just update the cached state and leave, we can't do anything.
1478 m_networkState = NETWORK_EMPTY;
1482 if (state == MediaPlayer::FormatError || state == MediaPlayer::NetworkError || state == MediaPlayer::DecodeError) {
1483 mediaLoadingFailed(state);
1487 if (state == MediaPlayer::Idle) {
1488 if (m_networkState > NETWORK_IDLE) {
1489 changeNetworkStateFromLoadingToIdle();
1490 setShouldDelayLoadEvent(false);
1492 m_networkState = NETWORK_IDLE;
1496 if (state == MediaPlayer::Loading) {
1497 if (m_networkState < NETWORK_LOADING || m_networkState == NETWORK_NO_SOURCE)
1498 startProgressEventTimer();
1499 m_networkState = NETWORK_LOADING;
1502 if (state == MediaPlayer::Loaded) {
1503 if (m_networkState != NETWORK_IDLE)
1504 changeNetworkStateFromLoadingToIdle();
1505 m_completelyLoaded = true;
1509 void HTMLMediaElement::changeNetworkStateFromLoadingToIdle()
1511 m_progressEventTimer.stop();
1512 if (hasMediaControls() && m_player->didLoadingProgress())
1513 mediaControls()->bufferingProgressed();
1515 // Schedule one last progress event so we guarantee that at least one is fired
1516 // for files that load very quickly.
1517 scheduleEvent(EventTypeNames::progress);
1518 scheduleEvent(EventTypeNames::suspend);
1519 m_networkState = NETWORK_IDLE;
1522 void HTMLMediaElement::mediaPlayerReadyStateChanged()
1524 setReadyState(m_player->readyState());
1527 void HTMLMediaElement::setReadyState(MediaPlayer::ReadyState state)
1529 WTF_LOG(Media, "HTMLMediaElement::setReadyState(%d) - current state is %d,", static_cast<int>(state), static_cast<int>(m_readyState));
1531 // Set "wasPotentiallyPlaying" BEFORE updating m_readyState, potentiallyPlaying() uses it
1532 bool wasPotentiallyPlaying = potentiallyPlaying();
1534 ReadyState oldState = m_readyState;
1535 ReadyState newState = static_cast<ReadyState>(state);
1537 bool tracksAreReady = !RuntimeEnabledFeatures::videoTrackEnabled() || textTracksAreReady();
1539 if (newState == oldState && m_tracksAreReady == tracksAreReady)
1542 m_tracksAreReady = tracksAreReady;
1545 m_readyState = newState;
1547 // If a media file has text tracks the readyState may not progress beyond HAVE_FUTURE_DATA until
1548 // the text tracks are ready, regardless of the state of the media file.
1549 if (newState <= HAVE_METADATA)
1550 m_readyState = newState;
1552 m_readyState = HAVE_CURRENT_DATA;
1555 if (oldState > m_readyStateMaximum)
1556 m_readyStateMaximum = oldState;
1558 if (m_networkState == NETWORK_EMPTY)
1562 // 4.8.10.9, step 9 note: If the media element was potentially playing immediately before
1563 // it started seeking, but seeking caused its readyState attribute to change to a value
1564 // lower than HAVE_FUTURE_DATA, then a waiting will be fired at the element.
1565 if (wasPotentiallyPlaying && m_readyState < HAVE_FUTURE_DATA)
1566 scheduleEvent(EventTypeNames::waiting);
1568 // 4.8.10.9 steps 12-14
1569 if (m_readyState >= HAVE_CURRENT_DATA)
1572 if (wasPotentiallyPlaying && m_readyState < HAVE_FUTURE_DATA) {
1574 scheduleTimeupdateEvent(false);
1575 scheduleEvent(EventTypeNames::waiting);
1579 if (m_readyState >= HAVE_METADATA && oldState < HAVE_METADATA) {
1580 prepareMediaFragmentURI();
1581 scheduleEvent(EventTypeNames::durationchange);
1583 scheduleEvent(EventTypeNames::resize);
1584 scheduleEvent(EventTypeNames::loadedmetadata);
1585 if (hasMediaControls())
1586 mediaControls()->reset();
1588 renderer()->updateFromElement();
1591 bool shouldUpdateDisplayState = false;
1593 if (m_readyState >= HAVE_CURRENT_DATA && oldState < HAVE_CURRENT_DATA && !m_haveFiredLoadedData) {
1594 m_haveFiredLoadedData = true;
1595 shouldUpdateDisplayState = true;
1596 scheduleEvent(EventTypeNames::loadeddata);
1597 setShouldDelayLoadEvent(false);
1598 applyMediaFragmentURI();
1601 bool isPotentiallyPlaying = potentiallyPlaying();
1602 if (m_readyState == HAVE_FUTURE_DATA && oldState <= HAVE_CURRENT_DATA && tracksAreReady) {
1603 scheduleEvent(EventTypeNames::canplay);
1604 if (isPotentiallyPlaying)
1605 scheduleEvent(EventTypeNames::playing);
1606 shouldUpdateDisplayState = true;
1609 if (m_readyState == HAVE_ENOUGH_DATA && oldState < HAVE_ENOUGH_DATA && tracksAreReady) {
1610 if (oldState <= HAVE_CURRENT_DATA)
1611 scheduleEvent(EventTypeNames::canplay);
1613 scheduleEvent(EventTypeNames::canplaythrough);
1615 if (isPotentiallyPlaying && oldState <= HAVE_CURRENT_DATA)
1616 scheduleEvent(EventTypeNames::playing);
1618 if (m_autoplaying && m_paused && autoplay() && !document().isSandboxed(SandboxAutomaticFeatures) && !userGestureRequiredForPlay()) {
1620 invalidateCachedTime();
1621 scheduleEvent(EventTypeNames::play);
1622 scheduleEvent(EventTypeNames::playing);
1625 shouldUpdateDisplayState = true;
1628 if (shouldUpdateDisplayState) {
1629 updateDisplayState();
1630 if (hasMediaControls())
1631 mediaControls()->refreshClosedCaptionsButtonVisibility();
1635 updateMediaController();
1636 if (RuntimeEnabledFeatures::videoTrackEnabled())
1637 updateActiveTextTrackCues(currentTime());
1640 void HTMLMediaElement::mediaPlayerKeyAdded(const String& keySystem, const String& sessionId)
1642 WTF_LOG(Media, "HTMLMediaElement::mediaPlayerKeyAdded");
1644 MediaKeyEventInit initializer;
1645 initializer.keySystem = keySystem;
1646 initializer.sessionId = sessionId;
1647 initializer.bubbles = false;
1648 initializer.cancelable = false;
1650 RefPtr<Event> event = MediaKeyEvent::create(EventTypeNames::webkitkeyadded, initializer);
1651 event->setTarget(this);
1652 m_asyncEventQueue->enqueueEvent(event.release());
1655 void HTMLMediaElement::mediaPlayerKeyError(const String& keySystem, const String& sessionId, MediaPlayerClient::MediaKeyErrorCode errorCode, unsigned short systemCode)
1657 WTF_LOG(Media, "HTMLMediaElement::mediaPlayerKeyError: sessionID=%s, errorCode=%d, systemCode=%d", sessionId.utf8().data(), errorCode, systemCode);
1659 MediaKeyError::Code mediaKeyErrorCode = MediaKeyError::MEDIA_KEYERR_UNKNOWN;
1660 switch (errorCode) {
1661 case MediaPlayerClient::UnknownError:
1662 mediaKeyErrorCode = MediaKeyError::MEDIA_KEYERR_UNKNOWN;
1664 case MediaPlayerClient::ClientError:
1665 mediaKeyErrorCode = MediaKeyError::MEDIA_KEYERR_CLIENT;
1667 case MediaPlayerClient::ServiceError:
1668 mediaKeyErrorCode = MediaKeyError::MEDIA_KEYERR_SERVICE;
1670 case MediaPlayerClient::OutputError:
1671 mediaKeyErrorCode = MediaKeyError::MEDIA_KEYERR_OUTPUT;
1673 case MediaPlayerClient::HardwareChangeError:
1674 mediaKeyErrorCode = MediaKeyError::MEDIA_KEYERR_HARDWARECHANGE;
1676 case MediaPlayerClient::DomainError:
1677 mediaKeyErrorCode = MediaKeyError::MEDIA_KEYERR_DOMAIN;
1681 MediaKeyEventInit initializer;
1682 initializer.keySystem = keySystem;
1683 initializer.sessionId = sessionId;
1684 initializer.errorCode = MediaKeyError::create(mediaKeyErrorCode);
1685 initializer.systemCode = systemCode;
1686 initializer.bubbles = false;
1687 initializer.cancelable = false;
1689 RefPtr<Event> event = MediaKeyEvent::create(EventTypeNames::webkitkeyerror, initializer);
1690 event->setTarget(this);
1691 m_asyncEventQueue->enqueueEvent(event.release());
1694 void HTMLMediaElement::mediaPlayerKeyMessage(const String& keySystem, const String& sessionId, const unsigned char* message, unsigned messageLength, const KURL& defaultURL)
1696 WTF_LOG(Media, "HTMLMediaElement::mediaPlayerKeyMessage: sessionID=%s", sessionId.utf8().data());
1698 MediaKeyEventInit initializer;
1699 initializer.keySystem = keySystem;
1700 initializer.sessionId = sessionId;
1701 initializer.message = Uint8Array::create(message, messageLength);
1702 initializer.defaultURL = defaultURL;
1703 initializer.bubbles = false;
1704 initializer.cancelable = false;
1706 RefPtr<Event> event = MediaKeyEvent::create(EventTypeNames::webkitkeymessage, initializer);
1707 event->setTarget(this);
1708 m_asyncEventQueue->enqueueEvent(event.release());
1711 // Create a MediaKeyNeededEvent for WD EME.
1712 static PassRefPtr<Event> createNeedKeyEvent(const String& contentType, const unsigned char* initData, unsigned initDataLength)
1714 MediaKeyNeededEventInit initializer;
1715 initializer.contentType = contentType;
1716 initializer.initData = Uint8Array::create(initData, initDataLength);
1717 initializer.bubbles = false;
1718 initializer.cancelable = false;
1720 return MediaKeyNeededEvent::create(EventTypeNames::needkey, initializer);
1723 // Create a 'needkey' MediaKeyEvent for v0.1b EME.
1724 static PassRefPtr<Event> createWebkitNeedKeyEvent(const String& contentType, const unsigned char* initData, unsigned initDataLength)
1726 MediaKeyEventInit webkitInitializer;
1727 webkitInitializer.keySystem = String();
1728 webkitInitializer.sessionId = String();
1729 webkitInitializer.initData = Uint8Array::create(initData, initDataLength);
1730 webkitInitializer.bubbles = false;
1731 webkitInitializer.cancelable = false;
1733 return MediaKeyEvent::create(EventTypeNames::webkitneedkey, webkitInitializer);
1736 bool HTMLMediaElement::mediaPlayerKeyNeeded(const String& contentType, const unsigned char* initData, unsigned initDataLength)
1738 WTF_LOG(Media, "HTMLMediaElement::mediaPlayerKeyNeeded: contentType=%s", contentType.utf8().data());
1740 if (RuntimeEnabledFeatures::encryptedMediaEnabled()) {
1741 // Send event for WD EME.
1742 RefPtr<Event> event = createNeedKeyEvent(contentType, initData, initDataLength);
1743 event->setTarget(this);
1744 m_asyncEventQueue->enqueueEvent(event.release());
1747 if (RuntimeEnabledFeatures::prefixedEncryptedMediaEnabled()) {
1748 // Send event for v0.1b EME.
1749 RefPtr<Event> event = createWebkitNeedKeyEvent(contentType, initData, initDataLength);
1750 event->setTarget(this);
1751 m_asyncEventQueue->enqueueEvent(event.release());
1757 bool HTMLMediaElement::setEmeMode(EmeMode emeMode, ExceptionState& exceptionState)
1759 if (m_emeMode != EmeModeNotSelected && m_emeMode != emeMode) {
1760 exceptionState.throwDOMException(InvalidStateError, "Mixed use of EME prefixed and unprefixed API not allowed.");
1763 m_emeMode = emeMode;
1767 blink::WebContentDecryptionModule* HTMLMediaElement::contentDecryptionModule()
1769 return m_mediaKeys ? m_mediaKeys->contentDecryptionModule() : 0;
1772 void HTMLMediaElement::setMediaKeysInternal(MediaKeys* mediaKeys)
1774 WTF_LOG(Media, "HTMLMediaElement::setMediaKeys");
1775 if (m_mediaKeys == mediaKeys)
1778 ASSERT(m_emeMode = EmeModeUnprefixed);
1781 m_mediaKeys->setMediaElement(0);
1782 m_mediaKeys = mediaKeys;
1784 m_mediaKeys->setMediaElement(this);
1786 // If a player is connected, tell it that the CDM has changed.
1788 m_player->setContentDecryptionModule(contentDecryptionModule());
1791 void HTMLMediaElement::setMediaKeys(MediaKeys* mediaKeys, ExceptionState& exceptionState)
1793 if (!setEmeMode(EmeModeUnprefixed, exceptionState))
1796 setMediaKeysInternal(mediaKeys);
1799 void HTMLMediaElement::progressEventTimerFired(Timer<HTMLMediaElement>*)
1802 if (m_networkState != NETWORK_LOADING)
1805 double time = WTF::currentTime();
1806 double timedelta = time - m_previousProgressTime;
1808 if (m_player->didLoadingProgress()) {
1809 scheduleEvent(EventTypeNames::progress);
1810 m_previousProgressTime = time;
1811 m_sentStalledEvent = false;
1813 renderer()->updateFromElement();
1814 if (hasMediaControls())
1815 mediaControls()->bufferingProgressed();
1816 } else if (timedelta > 3.0 && !m_sentStalledEvent) {
1817 scheduleEvent(EventTypeNames::stalled);
1818 m_sentStalledEvent = true;
1819 setShouldDelayLoadEvent(false);
1823 void HTMLMediaElement::addPlayedRange(double start, double end)
1825 WTF_LOG(Media, "HTMLMediaElement::addPlayedRange(%f, %f)", start, end);
1826 if (!m_playedTimeRanges)
1827 m_playedTimeRanges = TimeRanges::create();
1828 m_playedTimeRanges->add(start, end);
1831 bool HTMLMediaElement::supportsSave() const
1833 return m_player ? m_player->supportsSave() : false;
1836 void HTMLMediaElement::prepareToPlay()
1838 WTF_LOG(Media, "HTMLMediaElement::prepareToPlay(%p)", this);
1839 if (m_havePreparedToPlay)
1841 m_havePreparedToPlay = true;
1842 m_player->prepareToPlay();
1845 void HTMLMediaElement::seek(double time, ExceptionState& exceptionState)
1847 WTF_LOG(Media, "HTMLMediaElement::seek(%f)", time);
1851 // 1 - If the media element's readyState is HAVE_NOTHING, then raise an InvalidStateError exception.
1852 if (m_readyState == HAVE_NOTHING || !m_player) {
1853 exceptionState.throwDOMException(InvalidStateError, "The element's readyState is HAVE_NOTHING.");
1857 // If the media engine has been told to postpone loading data, let it go ahead now.
1858 if (m_preload < MediaPlayer::Auto && m_readyState < HAVE_FUTURE_DATA)
1861 // Get the current time before setting m_seeking, m_lastSeekTime is returned once it is set.
1862 refreshCachedTime();
1863 double now = currentTime();
1865 // 2 - If the element's seeking IDL attribute is true, then another instance of this algorithm is
1866 // already running. Abort that other instance of the algorithm without waiting for the step that
1867 // it is running to complete.
1868 // Nothing specific to be done here.
1870 // 3 - Set the seeking IDL attribute to true.
1871 // The flag will be cleared when the engine tells us the time has actually changed.
1874 // 5 - If the new playback position is later than the end of the media resource, then let it be the end
1875 // of the media resource instead.
1876 time = min(time, duration());
1878 // 6 - If the new playback position is less than the earliest possible position, let it be that position instead.
1879 time = max(time, 0.0);
1881 // Ask the media engine for the time value in the movie's time scale before comparing with current time. This
1882 // is necessary because if the seek time is not equal to currentTime but the delta is less than the movie's
1883 // time scale, we will ask the media engine to "seek" to the current movie time, which may be a noop and
1884 // not generate a timechanged callback. This means m_seeking will never be cleared and we will never
1885 // fire a 'seeked' event.
1887 double mediaTime = m_player->mediaTimeForTimeValue(time);
1888 if (time != mediaTime)
1889 WTF_LOG(Media, "HTMLMediaElement::seek(%f) - media timeline equivalent is %f", time, mediaTime);
1891 time = m_player->mediaTimeForTimeValue(time);
1893 // 7 - If the (possibly now changed) new playback position is not in one of the ranges given in the
1894 // seekable attribute, then let it be the position in one of the ranges given in the seekable attribute
1895 // that is the nearest to the new playback position. ... If there are no ranges given in the seekable
1896 // attribute then set the seeking IDL attribute to false and abort these steps.
1897 RefPtr<TimeRanges> seekableRanges = seekable();
1899 // Short circuit seeking to the current time by just firing the events if no seek is required.
1900 // Don't skip calling the media engine if we are in poster mode because a seek should always
1901 // cancel poster display.
1902 bool noSeekRequired = !seekableRanges->length() || (time == now && displayMode() != Poster);
1904 // Always notify the media engine of a seek if the source is not closed. This ensures that the source is
1905 // always in a flushed state when the 'seeking' event fires.
1906 if (m_mediaSource && m_mediaSource->isClosed())
1907 noSeekRequired = false;
1909 if (noSeekRequired) {
1911 scheduleEvent(EventTypeNames::seeking);
1912 // FIXME: There must be a stable state before timeupdate+seeked are dispatched and seeking
1913 // is reset to false. See http://crbug.com/266631
1914 scheduleTimeupdateEvent(false);
1915 scheduleEvent(EventTypeNames::seeked);
1920 time = seekableRanges->nearest(time);
1923 if (m_lastSeekTime < now)
1924 addPlayedRange(m_lastSeekTime, now);
1926 m_lastSeekTime = time;
1927 m_sentEndEvent = false;
1929 // 8 - Queue a task to fire a simple event named seeking at the element.
1930 scheduleEvent(EventTypeNames::seeking);
1932 // 9 - Set the current playback position to the given new playback position
1933 m_player->seek(time);
1935 // 10-14 are handled, if necessary, when the engine signals a readystate change or otherwise
1936 // satisfies seek completion and signals a time change.
1939 void HTMLMediaElement::finishSeek()
1941 WTF_LOG(Media, "HTMLMediaElement::finishSeek");
1943 // 4.8.10.9 Seeking completion
1944 // 12 - Set the seeking IDL attribute to false.
1947 // 13 - Queue a task to fire a simple event named timeupdate at the element.
1948 scheduleTimeupdateEvent(false);
1950 // 14 - Queue a task to fire a simple event named seeked at the element.
1951 scheduleEvent(EventTypeNames::seeked);
1953 setDisplayMode(Video);
1956 HTMLMediaElement::ReadyState HTMLMediaElement::readyState() const
1958 return m_readyState;
1961 bool HTMLMediaElement::hasAudio() const
1963 return m_player ? m_player->hasAudio() : false;
1966 bool HTMLMediaElement::seeking() const
1971 void HTMLMediaElement::refreshCachedTime() const
1973 m_cachedTime = m_player->currentTime();
1974 m_cachedTimeWallClockUpdateTime = WTF::currentTime();
1977 void HTMLMediaElement::invalidateCachedTime()
1979 WTF_LOG(Media, "HTMLMediaElement::invalidateCachedTime");
1981 // Don't try to cache movie time when playback first starts as the time reported by the engine
1982 // sometimes fluctuates for a short amount of time, so the cached time will be off if we take it
1984 static const double minimumTimePlayingBeforeCacheSnapshot = 0.5;
1986 m_minimumWallClockTimeToCacheMediaTime = WTF::currentTime() + minimumTimePlayingBeforeCacheSnapshot;
1987 m_cachedTime = MediaPlayer::invalidTime();
1991 double HTMLMediaElement::currentTime() const
1993 #if LOG_CACHED_TIME_WARNINGS
1994 static const double minCachedDeltaForWarning = 0.01;
2001 WTF_LOG(Media, "HTMLMediaElement::currentTime - seeking, returning %f", m_lastSeekTime);
2002 return m_lastSeekTime;
2005 if (m_cachedTime != MediaPlayer::invalidTime() && m_paused) {
2006 #if LOG_CACHED_TIME_WARNINGS
2007 double delta = m_cachedTime - m_player->currentTime();
2008 if (delta > minCachedDeltaForWarning)
2009 WTF_LOG(Media, "HTMLMediaElement::currentTime - WARNING, cached time is %f seconds off of media time when paused", delta);
2011 return m_cachedTime;
2014 refreshCachedTime();
2016 return m_cachedTime;
2019 void HTMLMediaElement::setCurrentTime(double time, ExceptionState& exceptionState)
2021 if (m_mediaController) {
2022 exceptionState.throwDOMException(InvalidStateError, "No media controller is available.");
2025 seek(time, exceptionState);
2028 double HTMLMediaElement::duration() const
2030 if (!m_player || m_readyState < HAVE_METADATA)
2031 return numeric_limits<double>::quiet_NaN();
2033 // FIXME: Refactor so m_duration is kept current (in both MSE and
2034 // non-MSE cases) once we have transitioned from HAVE_NOTHING ->
2035 // HAVE_METADATA. Currently, m_duration may be out of date for at least MSE
2036 // case because MediaSourceBase and SourceBuffer do not notify the element
2037 // directly upon duration changes caused by endOfStream, remove, or append
2038 // operations; rather the notification is triggered by the WebMediaPlayer
2039 // implementation observing that the underlying engine has updated duration
2040 // and notifying the element to consult its MediaSource for current
2041 // duration. See http://crbug.com/266644
2044 return m_mediaSource->duration();
2046 return m_player->duration();
2049 bool HTMLMediaElement::paused() const
2054 double HTMLMediaElement::defaultPlaybackRate() const
2056 return m_defaultPlaybackRate;
2059 void HTMLMediaElement::setDefaultPlaybackRate(double rate)
2061 if (m_defaultPlaybackRate != rate) {
2062 m_defaultPlaybackRate = rate;
2063 scheduleEvent(EventTypeNames::ratechange);
2067 double HTMLMediaElement::playbackRate() const
2069 return m_playbackRate;
2072 void HTMLMediaElement::setPlaybackRate(double rate)
2074 WTF_LOG(Media, "HTMLMediaElement::setPlaybackRate(%f)", rate);
2076 if (m_playbackRate != rate) {
2077 m_playbackRate = rate;
2078 invalidateCachedTime();
2079 scheduleEvent(EventTypeNames::ratechange);
2082 if (m_player && potentiallyPlaying() && m_player->rate() != rate && !m_mediaController)
2083 m_player->setRate(rate);
2086 void HTMLMediaElement::updatePlaybackRate()
2088 double effectiveRate = m_mediaController ? m_mediaController->playbackRate() : m_playbackRate;
2089 if (m_player && potentiallyPlaying() && m_player->rate() != effectiveRate)
2090 m_player->setRate(effectiveRate);
2093 bool HTMLMediaElement::ended() const
2095 // 4.8.10.8 Playing the media resource
2096 // The ended attribute must return true if the media element has ended
2097 // playback and the direction of playback is forwards, and false otherwise.
2098 return endedPlayback() && m_playbackRate > 0;
2101 bool HTMLMediaElement::autoplay() const
2103 return fastHasAttribute(autoplayAttr);
2106 String HTMLMediaElement::preload() const
2108 switch (m_preload) {
2109 case MediaPlayer::None:
2112 case MediaPlayer::MetaData:
2115 case MediaPlayer::Auto:
2120 ASSERT_NOT_REACHED();
2124 void HTMLMediaElement::setPreload(const AtomicString& preload)
2126 WTF_LOG(Media, "HTMLMediaElement::setPreload(%s)", preload.utf8().data());
2127 setAttribute(preloadAttr, preload);
2130 void HTMLMediaElement::play()
2132 WTF_LOG(Media, "HTMLMediaElement::play()");
2134 if (userGestureRequiredForPlay() && !UserGestureIndicator::processingUserGesture())
2136 if (UserGestureIndicator::processingUserGesture())
2137 removeBehaviorsRestrictionsAfterFirstUserGesture();
2142 void HTMLMediaElement::playInternal()
2144 WTF_LOG(Media, "HTMLMediaElement::playInternal");
2146 // 4.8.10.9. Playing the media resource
2147 if (!m_player || m_networkState == NETWORK_EMPTY)
2148 scheduleDelayedAction(LoadMediaResource);
2150 if (endedPlayback())
2151 seek(0, IGNORE_EXCEPTION);
2153 if (m_mediaController)
2154 m_mediaController->bringElementUpToSpeed(this);
2158 invalidateCachedTime();
2159 scheduleEvent(EventTypeNames::play);
2161 if (m_readyState <= HAVE_CURRENT_DATA)
2162 scheduleEvent(EventTypeNames::waiting);
2163 else if (m_readyState >= HAVE_FUTURE_DATA)
2164 scheduleEvent(EventTypeNames::playing);
2166 m_autoplaying = false;
2169 updateMediaController();
2172 void HTMLMediaElement::pause()
2174 WTF_LOG(Media, "HTMLMediaElement::pause()");
2176 if (!m_player || m_networkState == NETWORK_EMPTY)
2177 scheduleDelayedAction(LoadMediaResource);
2179 m_autoplaying = false;
2183 scheduleTimeupdateEvent(false);
2184 scheduleEvent(EventTypeNames::pause);
2190 void HTMLMediaElement::closeMediaSource()
2195 m_mediaSource->close();
2199 void HTMLMediaElement::webkitGenerateKeyRequest(const String& keySystem, PassRefPtr<Uint8Array> initData, ExceptionState& exceptionState)
2201 WTF_LOG(Media, "HTMLMediaElement::webkitGenerateKeyRequest");
2203 if (!setEmeMode(EmeModePrefixed, exceptionState))
2206 if (keySystem.isEmpty()) {
2207 exceptionState.throwDOMException(SyntaxError, "The key system provided is empty.");
2212 exceptionState.throwDOMException(InvalidStateError, "No player is available.");
2216 const unsigned char* initDataPointer = 0;
2217 unsigned initDataLength = 0;
2219 initDataPointer = initData->data();
2220 initDataLength = initData->length();
2223 MediaPlayer::MediaKeyException result = m_player->generateKeyRequest(keySystem, initDataPointer, initDataLength);
2224 throwExceptionForMediaKeyException(result, exceptionState);
2227 void HTMLMediaElement::webkitGenerateKeyRequest(const String& keySystem, ExceptionState& exceptionState)
2229 webkitGenerateKeyRequest(keySystem, Uint8Array::create(0), exceptionState);
2232 void HTMLMediaElement::webkitAddKey(const String& keySystem, PassRefPtr<Uint8Array> key, PassRefPtr<Uint8Array> initData, const String& sessionId, ExceptionState& exceptionState)
2234 WTF_LOG(Media, "HTMLMediaElement::webkitAddKey");
2236 if (!setEmeMode(EmeModePrefixed, exceptionState))
2239 if (keySystem.isEmpty()) {
2240 exceptionState.throwDOMException(SyntaxError, "The key system provided is empty.");
2245 exceptionState.throwDOMException(SyntaxError, "The key provided is invalid.");
2249 if (!key->length()) {
2250 exceptionState.throwDOMException(TypeMismatchError, "The key provided is invalid.");
2255 exceptionState.throwDOMException(InvalidStateError, "No player is available.");
2259 const unsigned char* initDataPointer = 0;
2260 unsigned initDataLength = 0;
2262 initDataPointer = initData->data();
2263 initDataLength = initData->length();
2266 MediaPlayer::MediaKeyException result = m_player->addKey(keySystem, key->data(), key->length(), initDataPointer, initDataLength, sessionId);
2267 throwExceptionForMediaKeyException(result, exceptionState);
2270 void HTMLMediaElement::webkitAddKey(const String& keySystem, PassRefPtr<Uint8Array> key, ExceptionState& exceptionState)
2272 webkitAddKey(keySystem, key, Uint8Array::create(0), String(), exceptionState);
2275 void HTMLMediaElement::webkitCancelKeyRequest(const String& keySystem, const String& sessionId, ExceptionState& exceptionState)
2277 WTF_LOG(Media, "HTMLMediaElement::webkitCancelKeyRequest");
2279 if (!setEmeMode(EmeModePrefixed, exceptionState))
2282 if (keySystem.isEmpty()) {
2283 exceptionState.throwDOMException(SyntaxError, "The key system provided is empty.");
2288 exceptionState.throwDOMException(InvalidStateError, "No player is available.");
2292 MediaPlayer::MediaKeyException result = m_player->cancelKeyRequest(keySystem, sessionId);
2293 throwExceptionForMediaKeyException(result, exceptionState);
2296 bool HTMLMediaElement::loop() const
2298 return fastHasAttribute(loopAttr);
2301 void HTMLMediaElement::setLoop(bool b)
2303 WTF_LOG(Media, "HTMLMediaElement::setLoop(%s)", boolString(b));
2304 setBooleanAttribute(loopAttr, b);
2307 bool HTMLMediaElement::controls() const
2309 Frame* frame = document().frame();
2311 // always show controls when scripting is disabled
2312 if (frame && !frame->script().canExecuteScripts(NotAboutToExecuteScript))
2315 // Always show controls when in full screen mode.
2319 return fastHasAttribute(controlsAttr);
2322 void HTMLMediaElement::setControls(bool b)
2324 WTF_LOG(Media, "HTMLMediaElement::setControls(%s)", boolString(b));
2325 setBooleanAttribute(controlsAttr, b);
2328 double HTMLMediaElement::volume() const
2333 void HTMLMediaElement::setVolume(double vol, ExceptionState& exceptionState)
2335 WTF_LOG(Media, "HTMLMediaElement::setVolume(%f)", vol);
2337 if (vol < 0.0f || vol > 1.0f) {
2338 exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::indexOutsideRange("volume", vol, 0.0f, ExceptionMessages::ExclusiveBound, 1.0f, ExceptionMessages::ExclusiveBound));
2342 if (m_volume != vol) {
2345 scheduleEvent(EventTypeNames::volumechange);
2349 bool HTMLMediaElement::muted() const
2354 void HTMLMediaElement::setMuted(bool muted)
2356 WTF_LOG(Media, "HTMLMediaElement::setMuted(%s)", boolString(muted));
2358 if (m_muted != muted) {
2361 m_player->setMuted(m_muted);
2362 if (hasMediaControls())
2363 mediaControls()->changedMute();
2365 scheduleEvent(EventTypeNames::volumechange);
2369 void HTMLMediaElement::beginScrubbing()
2371 WTF_LOG(Media, "HTMLMediaElement::beginScrubbing - paused() is %s", boolString(paused()));
2375 // Because a media element stays in non-paused state when it reaches end, playback resumes
2376 // when the slider is dragged from the end to another position unless we pause first. Do
2377 // a "hard pause" so an event is generated, since we want to stay paused after scrubbing finishes.
2380 // Not at the end but we still want to pause playback so the media engine doesn't try to
2381 // continue playing during scrubbing. Pause without generating an event as we will
2382 // unpause after scrubbing finishes.
2383 setPausedInternal(true);
2388 void HTMLMediaElement::endScrubbing()
2390 WTF_LOG(Media, "HTMLMediaElement::endScrubbing - m_pausedInternal is %s", boolString(m_pausedInternal));
2392 if (m_pausedInternal)
2393 setPausedInternal(false);
2396 // The spec says to fire periodic timeupdate events (those sent while playing) every
2397 // "15 to 250ms", we choose the slowest frequency
2398 static const double maxTimeupdateEventFrequency = 0.25;
2400 void HTMLMediaElement::startPlaybackProgressTimer()
2402 if (m_playbackProgressTimer.isActive())
2405 m_previousProgressTime = WTF::currentTime();
2406 m_playbackProgressTimer.startRepeating(maxTimeupdateEventFrequency);
2409 void HTMLMediaElement::playbackProgressTimerFired(Timer<HTMLMediaElement>*)
2413 if (m_fragmentEndTime != MediaPlayer::invalidTime() && currentTime() >= m_fragmentEndTime && m_playbackRate > 0) {
2414 m_fragmentEndTime = MediaPlayer::invalidTime();
2415 if (!m_mediaController && !m_paused) {
2416 // changes paused to true and fires a simple event named pause at the media element.
2422 scheduleTimeupdateEvent(true);
2424 if (!m_playbackRate)
2427 if (!m_paused && hasMediaControls())
2428 mediaControls()->playbackProgressed();
2430 if (RuntimeEnabledFeatures::videoTrackEnabled())
2431 updateActiveTextTrackCues(currentTime());
2434 void HTMLMediaElement::scheduleTimeupdateEvent(bool periodicEvent)
2436 double now = WTF::currentTime();
2437 double timedelta = now - m_lastTimeUpdateEventWallTime;
2439 // throttle the periodic events
2440 if (periodicEvent && timedelta < maxTimeupdateEventFrequency)
2443 // Some media engines make multiple "time changed" callbacks at the same time, but we only want one
2444 // event at a given time so filter here
2445 double movieTime = currentTime();
2446 if (movieTime != m_lastTimeUpdateEventMovieTime) {
2447 scheduleEvent(EventTypeNames::timeupdate);
2448 m_lastTimeUpdateEventWallTime = now;
2449 m_lastTimeUpdateEventMovieTime = movieTime;
2453 bool HTMLMediaElement::canPlay() const
2455 return paused() || ended() || m_readyState < HAVE_METADATA;
2458 void HTMLMediaElement::mediaPlayerDidAddTrack(WebInbandTextTrack* webTrack)
2460 if (!RuntimeEnabledFeatures::videoTrackEnabled())
2463 // 4.8.10.12.2 Sourcing in-band text tracks
2464 // 1. Associate the relevant data with a new text track and its corresponding new TextTrack object.
2465 RefPtr<InbandTextTrack> textTrack = InbandTextTrack::create(document(), this, webTrack);
2467 // 2. Set the new text track's kind, label, and language based on the semantics of the relevant data,
2468 // as defined by the relevant specification. If there is no label in that data, then the label must
2469 // be set to the empty string.
2470 // 3. Associate the text track list of cues with the rules for updating the text track rendering appropriate
2471 // for the format in question.
2472 // 4. If the new text track's kind is metadata, then set the text track in-band metadata track dispatch type
2473 // as follows, based on the type of the media resource:
2474 // 5. Populate the new text track's list of cues with the cues parsed so far, folllowing the guidelines for exposing
2475 // cues, and begin updating it dynamically as necessary.
2476 // - Thess are all done by the media engine.
2478 // 6. Set the new text track's readiness state to loaded.
2479 textTrack->setReadinessState(TextTrack::Loaded);
2481 // 7. Set the new text track's mode to the mode consistent with the user's preferences and the requirements of
2482 // the relevant specification for the data.
2483 // - This will happen in configureTextTracks()
2484 scheduleDelayedAction(LoadTextTrackResource);
2486 // 8. Add the new text track to the media element's list of text tracks.
2487 // 9. Fire an event with the name addtrack, that does not bubble and is not cancelable, and that uses the TrackEvent
2488 // interface, with the track attribute initialized to the text track's TextTrack object, at the media element's
2489 // textTracks attribute's TextTrackList object.
2490 addTrack(textTrack.get());
2493 void HTMLMediaElement::mediaPlayerDidRemoveTrack(WebInbandTextTrack* webTrack)
2495 if (!RuntimeEnabledFeatures::videoTrackEnabled())
2501 // This cast is safe because we created the InbandTextTrack with the WebInbandTextTrack
2502 // passed to mediaPlayerDidAddTrack.
2503 RefPtr<InbandTextTrack> textTrack = static_cast<InbandTextTrack*>(webTrack->client());
2507 removeTrack(textTrack.get());
2510 void HTMLMediaElement::closeCaptionTracksChanged()
2512 if (hasMediaControls())
2513 mediaControls()->closedCaptionTracksChanged();
2516 void HTMLMediaElement::addTrack(TextTrack* track)
2518 textTracks()->append(track);
2520 closeCaptionTracksChanged();
2523 void HTMLMediaElement::removeTrack(TextTrack* track)
2525 TrackDisplayUpdateScope scope(this);
2526 TextTrackCueList* cues = track->cues();
2528 textTrackRemoveCues(track, cues);
2529 m_textTracks->remove(track);
2531 closeCaptionTracksChanged();
2534 void HTMLMediaElement::removeAllInbandTracks()
2539 TrackDisplayUpdateScope scope(this);
2540 for (int i = m_textTracks->length() - 1; i >= 0; --i) {
2541 TextTrack* track = m_textTracks->item(i);
2543 if (track->trackType() == TextTrack::InBand)
2548 PassRefPtr<TextTrack> HTMLMediaElement::addTextTrack(const AtomicString& kind, const AtomicString& label, const AtomicString& language, ExceptionState& exceptionState)
2550 ASSERT(RuntimeEnabledFeatures::videoTrackEnabled());
2552 // 4.8.10.12.4 Text track API
2553 // The addTextTrack(kind, label, language) method of media elements, when invoked, must run the following steps:
2555 // 1. If kind is not one of the following strings, then throw a SyntaxError exception and abort these steps
2556 if (!TextTrack::isValidKindKeyword(kind)) {
2557 exceptionState.throwDOMException(SyntaxError, "The 'kind' provided ('" + kind + "') is invalid.");
2561 // 2. If the label argument was omitted, let label be the empty string.
2562 // 3. If the language argument was omitted, let language be the empty string.
2563 // 4. Create a new TextTrack object.
2565 // 5. Create a new text track corresponding to the new object, and set its text track kind to kind, its text
2566 // track label to label, its text track language to language...
2567 RefPtr<TextTrack> textTrack = TextTrack::create(document(), this, kind, label, language);
2569 // Note, due to side effects when changing track parameters, we have to
2570 // first append the track to the text track list.
2572 // 6. Add the new text track to the media element's list of text tracks.
2573 addTrack(textTrack.get());
2575 // ... its text track readiness state to the text track loaded state ...
2576 textTrack->setReadinessState(TextTrack::Loaded);
2578 // ... its text track mode to the text track hidden mode, and its text track list of cues to an empty list ...
2579 textTrack->setMode(TextTrack::hiddenKeyword());
2581 return textTrack.release();
2584 TextTrackList* HTMLMediaElement::textTracks()
2586 ASSERT(RuntimeEnabledFeatures::videoTrackEnabled());
2589 m_textTracks = TextTrackList::create(this);
2591 return m_textTracks.get();
2594 void HTMLMediaElement::didAddTrack(HTMLTrackElement* trackElement)
2596 ASSERT(trackElement->hasTagName(trackTag));
2598 if (!RuntimeEnabledFeatures::videoTrackEnabled())
2601 // 4.8.10.12.3 Sourcing out-of-band text tracks
2602 // When a track element's parent element changes and the new parent is a media element,
2603 // then the user agent must add the track element's corresponding text track to the
2604 // media element's list of text tracks ... [continues in TextTrackList::append]
2605 RefPtr<TextTrack> textTrack = trackElement->track();
2609 addTrack(textTrack.get());
2611 // Do not schedule the track loading until parsing finishes so we don't start before all tracks
2612 // in the markup have been added.
2613 if (isFinishedParsingChildren())
2614 scheduleDelayedAction(LoadTextTrackResource);
2616 if (hasMediaControls())
2617 mediaControls()->closedCaptionTracksChanged();
2620 void HTMLMediaElement::didRemoveTrack(HTMLTrackElement* trackElement)
2622 ASSERT(trackElement->hasTagName(trackTag));
2624 if (!RuntimeEnabledFeatures::videoTrackEnabled())
2628 if (trackElement->hasTagName(trackTag)) {
2629 KURL url = trackElement->getNonEmptyURLAttribute(srcAttr);
2630 WTF_LOG(Media, "HTMLMediaElement::didRemoveTrack - 'src' is %s", urlForLoggingMedia(url).utf8().data());
2634 RefPtr<TextTrack> textTrack = trackElement->track();
2638 textTrack->setHasBeenConfigured(false);
2643 // 4.8.10.12.3 Sourcing out-of-band text tracks
2644 // When a track element's parent element changes and the old parent was a media element,
2645 // then the user agent must remove the track element's corresponding text track from the
2646 // media element's list of text tracks.
2647 removeTrack(textTrack.get());
2649 size_t index = m_textTracksWhenResourceSelectionBegan.find(textTrack.get());
2650 if (index != kNotFound)
2651 m_textTracksWhenResourceSelectionBegan.remove(index);
2654 static int textTrackLanguageSelectionScore(const TextTrack& track)
2656 if (track.language().isEmpty())
2659 Vector<AtomicString> languages = userPreferredLanguages();
2660 size_t languageMatchIndex = indexOfBestMatchingLanguageInList(track.language(), languages);
2661 if (languageMatchIndex >= languages.size())
2664 // Matching a track language is more important than matching track type, so this multiplier must be
2665 // greater than the maximum value returned by textTrackSelectionScore.
2666 return (languages.size() - languageMatchIndex) * 10;
2669 static int textTrackSelectionScore(const TextTrack& track, Settings* settings)
2676 if (track.kind() != TextTrack::captionsKeyword() && track.kind() != TextTrack::subtitlesKeyword())
2679 if (track.kind() == TextTrack::subtitlesKeyword() && settings->shouldDisplaySubtitles())
2681 else if (track.kind() == TextTrack::captionsKeyword() && settings->shouldDisplayCaptions())
2684 return trackScore + textTrackLanguageSelectionScore(track);
2687 void HTMLMediaElement::configureTextTrackGroup(const TrackGroup& group)
2689 ASSERT(group.tracks.size());
2691 WTF_LOG(Media, "HTMLMediaElement::configureTextTrackGroup(%d)", group.kind);
2693 Settings* settings = document().settings();
2695 // First, find the track in the group that should be enabled (if any).
2696 Vector<RefPtr<TextTrack> > currentlyEnabledTracks;
2697 RefPtr<TextTrack> trackToEnable;
2698 RefPtr<TextTrack> defaultTrack;
2699 RefPtr<TextTrack> fallbackTrack;
2700 int highestTrackScore = 0;
2701 for (size_t i = 0; i < group.tracks.size(); ++i) {
2702 RefPtr<TextTrack> textTrack = group.tracks[i];
2704 if (m_processingPreferenceChange && textTrack->mode() == TextTrack::showingKeyword())
2705 currentlyEnabledTracks.append(textTrack);
2707 int trackScore = textTrackSelectionScore(*textTrack, settings);
2709 // * If the text track kind is { [subtitles or captions] [descriptions] } and the user has indicated an interest in having a
2710 // track with this text track kind, text track language, and text track label enabled, and there is no
2711 // other text track in the media element's list of text tracks with a text track kind of either subtitles
2712 // or captions whose text track mode is showing
2714 // * If the text track kind is chapters and the text track language is one that the user agent has reason
2715 // to believe is appropriate for the user, and there is no other text track in the media element's list of
2716 // text tracks with a text track kind of chapters whose text track mode is showing
2717 // Let the text track mode be showing.
2718 if (trackScore > highestTrackScore) {
2719 highestTrackScore = trackScore;
2720 trackToEnable = textTrack;
2723 if (!defaultTrack && textTrack->isDefault())
2724 defaultTrack = textTrack;
2725 if (!defaultTrack && !fallbackTrack)
2726 fallbackTrack = textTrack;
2727 } else if (!group.visibleTrack && !defaultTrack && textTrack->isDefault()) {
2728 // * If the track element has a default attribute specified, and there is no other text track in the media
2729 // element's list of text tracks whose text track mode is showing or showing by default
2730 // Let the text track mode be showing by default.
2731 defaultTrack = textTrack;
2735 if (!trackToEnable && defaultTrack)
2736 trackToEnable = defaultTrack;
2738 // If no track matches the user's preferred language and non was marked 'default', enable the first track
2739 // because the user has explicitly stated a preference for this kind of track.
2740 if (!fallbackTrack && m_closedCaptionsVisible && group.kind == TrackGroup::CaptionsAndSubtitles)
2741 fallbackTrack = group.tracks[0];
2743 if (!trackToEnable && fallbackTrack)
2744 trackToEnable = fallbackTrack;
2746 if (currentlyEnabledTracks.size()) {
2747 for (size_t i = 0; i < currentlyEnabledTracks.size(); ++i) {
2748 RefPtr<TextTrack> textTrack = currentlyEnabledTracks[i];
2749 if (textTrack != trackToEnable)
2750 textTrack->setMode(TextTrack::disabledKeyword());
2755 trackToEnable->setMode(TextTrack::showingKeyword());
2758 void HTMLMediaElement::configureTextTracks()
2760 TrackGroup captionAndSubtitleTracks(TrackGroup::CaptionsAndSubtitles);
2761 TrackGroup descriptionTracks(TrackGroup::Description);
2762 TrackGroup chapterTracks(TrackGroup::Chapter);
2763 TrackGroup metadataTracks(TrackGroup::Metadata);
2764 TrackGroup otherTracks(TrackGroup::Other);
2769 for (size_t i = 0; i < m_textTracks->length(); ++i) {
2770 RefPtr<TextTrack> textTrack = m_textTracks->item(i);
2774 String kind = textTrack->kind();
2775 TrackGroup* currentGroup;
2776 if (kind == TextTrack::subtitlesKeyword() || kind == TextTrack::captionsKeyword())
2777 currentGroup = &captionAndSubtitleTracks;
2778 else if (kind == TextTrack::descriptionsKeyword())
2779 currentGroup = &descriptionTracks;
2780 else if (kind == TextTrack::chaptersKeyword())
2781 currentGroup = &chapterTracks;
2782 else if (kind == TextTrack::metadataKeyword())
2783 currentGroup = &metadataTracks;
2785 currentGroup = &otherTracks;
2787 if (!currentGroup->visibleTrack && textTrack->mode() == TextTrack::showingKeyword())
2788 currentGroup->visibleTrack = textTrack;
2789 if (!currentGroup->defaultTrack && textTrack->isDefault())
2790 currentGroup->defaultTrack = textTrack;
2792 // Do not add this track to the group if it has already been automatically configured
2793 // as we only want to call configureTextTrack once per track so that adding another
2794 // track after the initial configuration doesn't reconfigure every track - only those
2795 // that should be changed by the new addition. For example all metadata tracks are
2796 // disabled by default, and we don't want a track that has been enabled by script
2797 // to be disabled automatically when a new metadata track is added later.
2798 if (textTrack->hasBeenConfigured())
2801 if (textTrack->language().length())
2802 currentGroup->hasSrcLang = true;
2803 currentGroup->tracks.append(textTrack);
2806 if (captionAndSubtitleTracks.tracks.size())
2807 configureTextTrackGroup(captionAndSubtitleTracks);
2808 if (descriptionTracks.tracks.size())
2809 configureTextTrackGroup(descriptionTracks);
2810 if (chapterTracks.tracks.size())
2811 configureTextTrackGroup(chapterTracks);
2812 if (metadataTracks.tracks.size())
2813 configureTextTrackGroup(metadataTracks);
2814 if (otherTracks.tracks.size())
2815 configureTextTrackGroup(otherTracks);
2817 if (hasMediaControls())
2818 mediaControls()->closedCaptionTracksChanged();
2821 bool HTMLMediaElement::havePotentialSourceChild()
2823 // Stash the current <source> node and next nodes so we can restore them after checking
2824 // to see there is another potential.
2825 RefPtr<HTMLSourceElement> currentSourceNode = m_currentSourceNode;
2826 RefPtr<Node> nextNode = m_nextChildNodeToConsider;
2828 KURL nextURL = selectNextSourceChild(0, 0, DoNothing);
2830 m_currentSourceNode = currentSourceNode;
2831 m_nextChildNodeToConsider = nextNode;
2833 return nextURL.isValid();
2836 KURL HTMLMediaElement::selectNextSourceChild(ContentType* contentType, String* keySystem, InvalidURLAction actionIfInvalid)
2839 // Don't log if this was just called to find out if there are any valid <source> elements.
2840 bool shouldLog = actionIfInvalid != DoNothing;
2842 WTF_LOG(Media, "HTMLMediaElement::selectNextSourceChild");
2845 if (!m_nextChildNodeToConsider) {
2848 WTF_LOG(Media, "HTMLMediaElement::selectNextSourceChild -> 0x0000, \"\"");
2855 HTMLSourceElement* source = 0;
2858 bool lookingForStartNode = m_nextChildNodeToConsider;
2859 bool canUseSourceElement = false;
2860 bool okToLoadSourceURL;
2862 NodeVector potentialSourceNodes;
2863 getChildNodes(*this, potentialSourceNodes);
2865 for (unsigned i = 0; !canUseSourceElement && i < potentialSourceNodes.size(); ++i) {
2866 node = potentialSourceNodes[i].get();
2867 if (lookingForStartNode && m_nextChildNodeToConsider != node)
2869 lookingForStartNode = false;
2871 if (!node->hasTagName(sourceTag))
2873 if (node->parentNode() != this)
2876 source = toHTMLSourceElement(node);
2878 // If candidate does not have a src attribute, or if its src attribute's value is the empty string ... jump down to the failed step below
2879 mediaURL = source->getNonEmptyURLAttribute(srcAttr);
2882 WTF_LOG(Media, "HTMLMediaElement::selectNextSourceChild - 'src' is %s", urlForLoggingMedia(mediaURL).utf8().data());
2884 if (mediaURL.isEmpty())
2887 type = source->type();
2888 // FIXME(82965): Add support for keySystem in <source> and set system from source.
2889 if (type.isEmpty() && mediaURL.protocolIsData())
2890 type = mimeTypeFromDataURL(mediaURL);
2891 if (!type.isEmpty() || !system.isEmpty()) {
2894 WTF_LOG(Media, "HTMLMediaElement::selectNextSourceChild - 'type' is '%s' - key system is '%s'", type.utf8().data(), system.utf8().data());
2896 if (!supportsType(ContentType(type), system))
2900 // Is it safe to load this url?
2901 okToLoadSourceURL = isSafeToLoadURL(mediaURL, actionIfInvalid) && dispatchBeforeLoadEvent(mediaURL.string());
2903 // A 'beforeload' event handler can mutate the DOM, so check to see if the source element is still a child node.
2904 if (node->parentNode() != this) {
2905 WTF_LOG(Media, "HTMLMediaElement::selectNextSourceChild : 'beforeload' removed current element");
2910 if (!okToLoadSourceURL)
2913 // Making it this far means the <source> looks reasonable.
2914 canUseSourceElement = true;
2917 if (!canUseSourceElement && actionIfInvalid == Complain && source)
2918 source->scheduleErrorEvent();
2921 if (canUseSourceElement) {
2923 *contentType = ContentType(type);
2925 *keySystem = system;
2926 m_currentSourceNode = source;
2927 m_nextChildNodeToConsider = source->nextSibling();
2929 m_currentSourceNode = 0;
2930 m_nextChildNodeToConsider = 0;
2935 WTF_LOG(Media, "HTMLMediaElement::selectNextSourceChild -> %p, %s", m_currentSourceNode.get(), canUseSourceElement ? urlForLoggingMedia(mediaURL).utf8().data() : "");
2937 return canUseSourceElement ? mediaURL : KURL();
2940 void HTMLMediaElement::sourceWasAdded(HTMLSourceElement* source)
2942 WTF_LOG(Media, "HTMLMediaElement::sourceWasAdded(%p)", source);
2945 if (source->hasTagName(sourceTag)) {
2946 KURL url = source->getNonEmptyURLAttribute(srcAttr);
2947 WTF_LOG(Media, "HTMLMediaElement::sourceWasAdded - 'src' is %s", urlForLoggingMedia(url).utf8().data());
2951 // We should only consider a <source> element when there is not src attribute at all.
2952 if (fastHasAttribute(srcAttr))
2955 // 4.8.8 - If a source element is inserted as a child of a media element that has no src
2956 // attribute and whose networkState has the value NETWORK_EMPTY, the user agent must invoke
2957 // the media element's resource selection algorithm.
2958 if (networkState() == HTMLMediaElement::NETWORK_EMPTY) {
2959 scheduleDelayedAction(LoadMediaResource);
2960 m_nextChildNodeToConsider = source;
2964 if (m_currentSourceNode && source == m_currentSourceNode->nextSibling()) {
2965 WTF_LOG(Media, "HTMLMediaElement::sourceWasAdded - <source> inserted immediately after current source");
2966 m_nextChildNodeToConsider = source;
2970 if (m_nextChildNodeToConsider)
2973 // 4.8.9.5, resource selection algorithm, source elements section:
2974 // 21. Wait until the node after pointer is a node other than the end of the list. (This step might wait forever.)
2975 // 22. Asynchronously await a stable state...
2976 // 23. Set the element's delaying-the-load-event flag back to true (this delays the load event again, in case
2977 // it hasn't been fired yet).
2978 setShouldDelayLoadEvent(true);
2980 // 24. Set the networkState back to NETWORK_LOADING.
2981 m_networkState = NETWORK_LOADING;
2983 // 25. Jump back to the find next candidate step above.
2984 m_nextChildNodeToConsider = source;
2985 scheduleNextSourceChild();
2988 void HTMLMediaElement::sourceWasRemoved(HTMLSourceElement* source)
2990 WTF_LOG(Media, "HTMLMediaElement::sourceWasRemoved(%p)", source);
2993 if (source->hasTagName(sourceTag)) {
2994 KURL url = source->getNonEmptyURLAttribute(srcAttr);
2995 WTF_LOG(Media, "HTMLMediaElement::sourceWasRemoved - 'src' is %s", urlForLoggingMedia(url).utf8().data());
2999 if (source != m_currentSourceNode && source != m_nextChildNodeToConsider)
3002 if (source == m_nextChildNodeToConsider) {
3003 if (m_currentSourceNode)
3004 m_nextChildNodeToConsider = m_currentSourceNode->nextSibling();
3005 WTF_LOG(Media, "HTMLMediaElement::sourceRemoved - m_nextChildNodeToConsider set to %p", m_nextChildNodeToConsider.get());
3006 } else if (source == m_currentSourceNode) {
3007 // Clear the current source node pointer, but don't change the movie as the spec says:
3008 // 4.8.8 - Dynamically modifying a source element and its attribute when the element is already
3009 // inserted in a video or audio element will have no effect.
3010 m_currentSourceNode = 0;
3011 WTF_LOG(Media, "HTMLMediaElement::sourceRemoved - m_currentSourceNode set to 0");
3015 void HTMLMediaElement::mediaPlayerTimeChanged()
3017 WTF_LOG(Media, "HTMLMediaElement::mediaPlayerTimeChanged");
3019 if (RuntimeEnabledFeatures::videoTrackEnabled())
3020 updateActiveTextTrackCues(currentTime());
3022 invalidateCachedTime();
3024 // 4.8.10.9 steps 12-14. Needed if no ReadyState change is associated with the seek.
3025 if (m_seeking && m_readyState >= HAVE_CURRENT_DATA && !m_player->seeking())
3028 // Always call scheduleTimeupdateEvent when the media engine reports a time discontinuity,
3029 // it will only queue a 'timeupdate' event if we haven't already posted one at the current
3031 scheduleTimeupdateEvent(false);
3033 double now = currentTime();
3034 double dur = duration();
3036 // When the current playback position reaches the end of the media resource when the direction of
3037 // playback is forwards, then the user agent must follow these steps:
3038 if (!std::isnan(dur) && dur && now >= dur && m_playbackRate > 0) {
3039 // If the media element has a loop attribute specified and does not have a current media controller,
3040 if (loop() && !m_mediaController) {
3041 m_sentEndEvent = false;
3042 // then seek to the earliest possible position of the media resource and abort these steps.
3043 seek(0, IGNORE_EXCEPTION);
3045 // If the media element does not have a current media controller, and the media element
3046 // has still ended playback, and the direction of playback is still forwards, and paused
3048 if (!m_mediaController && !m_paused) {
3049 // changes paused to true and fires a simple event named pause at the media element.
3051 scheduleEvent(EventTypeNames::pause);
3053 // Queue a task to fire a simple event named ended at the media element.
3054 if (!m_sentEndEvent) {
3055 m_sentEndEvent = true;
3056 scheduleEvent(EventTypeNames::ended);
3058 // If the media element has a current media controller, then report the controller state
3059 // for the media element's current media controller.
3060 updateMediaController();
3064 m_sentEndEvent = false;
3069 void HTMLMediaElement::mediaPlayerDurationChanged()
3071 WTF_LOG(Media, "HTMLMediaElement::mediaPlayerDurationChanged");
3072 durationChanged(duration());
3075 void HTMLMediaElement::durationChanged(double duration)
3077 WTF_LOG(Media, "HTMLMediaElement::durationChanged(%f)", duration);
3079 // Abort if duration unchanged.
3080 if (m_duration == duration)
3083 m_duration = duration;
3084 scheduleEvent(EventTypeNames::durationchange);
3086 if (hasMediaControls())
3087 mediaControls()->reset();
3089 renderer()->updateFromElement();
3091 if (currentTime() > duration)
3092 seek(duration, IGNORE_EXCEPTION);
3095 void HTMLMediaElement::mediaPlayerPlaybackStateChanged()
3097 WTF_LOG(Media, "HTMLMediaElement::mediaPlayerPlaybackStateChanged");
3099 if (!m_player || m_pausedInternal)
3102 if (m_player->paused())
3108 void HTMLMediaElement::mediaPlayerRequestFullscreen()
3110 WTF_LOG(Media, "HTMLMediaElement::mediaPlayerRequestFullscreen");
3114 void HTMLMediaElement::mediaPlayerRequestSeek(double time)
3116 // The player is the source of this seek request.
3117 if (m_mediaController) {
3118 m_mediaController->setCurrentTime(time, IGNORE_EXCEPTION);
3121 setCurrentTime(time, IGNORE_EXCEPTION);
3124 // MediaPlayerPresentation methods
3125 void HTMLMediaElement::mediaPlayerRepaint()
3128 m_webLayer->invalidate();
3130 updateDisplayState();
3132 renderer()->repaint();
3135 void HTMLMediaElement::mediaPlayerSizeChanged()
3137 WTF_LOG(Media, "HTMLMediaElement::mediaPlayerSizeChanged");
3139 ASSERT(hasVideo()); // "resize" makes no sense absent video.
3140 if (m_readyState > HAVE_NOTHING && isVideo())
3141 scheduleEvent(EventTypeNames::resize);
3144 renderer()->updateFromElement();
3147 PassRefPtr<TimeRanges> HTMLMediaElement::buffered() const
3150 return TimeRanges::create();
3153 return m_mediaSource->buffered();
3155 return m_player->buffered();
3158 PassRefPtr<TimeRanges> HTMLMediaElement::played()
3161 double time = currentTime();
3162 if (time > m_lastSeekTime)
3163 addPlayedRange(m_lastSeekTime, time);
3166 if (!m_playedTimeRanges)
3167 m_playedTimeRanges = TimeRanges::create();
3169 return m_playedTimeRanges->copy();
3172 PassRefPtr<TimeRanges> HTMLMediaElement::seekable() const
3175 double maxTimeSeekable = m_player->maxTimeSeekable();
3176 if (maxTimeSeekable)
3177 return TimeRanges::create(0, maxTimeSeekable);
3179 return TimeRanges::create();
3182 bool HTMLMediaElement::potentiallyPlaying() const
3184 // "pausedToBuffer" means the media engine's rate is 0, but only because it had to stop playing
3185 // when it ran out of buffered data. A movie is this state is "potentially playing", modulo the
3186 // checks in couldPlayIfEnoughData().
3187 bool pausedToBuffer = m_readyStateMaximum >= HAVE_FUTURE_DATA && m_readyState < HAVE_FUTURE_DATA;
3188 return (pausedToBuffer || m_readyState >= HAVE_FUTURE_DATA) && couldPlayIfEnoughData() && !isBlockedOnMediaController();
3191 bool HTMLMediaElement::couldPlayIfEnoughData() const
3193 return !paused() && !endedPlayback() && !stoppedDueToErrors() && !pausedForUserInteraction();
3196 bool HTMLMediaElement::endedPlayback() const
3198 double dur = duration();
3199 if (!m_player || std::isnan(dur))
3202 // 4.8.10.8 Playing the media resource
3204 // A media element is said to have ended playback when the element's
3205 // readyState attribute is HAVE_METADATA or greater,
3206 if (m_readyState < HAVE_METADATA)
3209 // and the current playback position is the end of the media resource and the direction
3210 // of playback is forwards, Either the media element does not have a loop attribute specified,
3211 // or the media element has a current media controller.
3212 double now = currentTime();
3213 if (m_playbackRate > 0)
3214 return dur > 0 && now >= dur && (!loop() || m_mediaController);
3216 // or the current playback position is the earliest possible position and the direction
3217 // of playback is backwards
3218 if (m_playbackRate < 0)
3224 bool HTMLMediaElement::stoppedDueToErrors() const
3226 if (m_readyState >= HAVE_METADATA && m_error) {
3227 RefPtr<TimeRanges> seekableRanges = seekable();
3228 if (!seekableRanges->contain(currentTime()))
3235 bool HTMLMediaElement::pausedForUserInteraction() const
3237 // return !paused() && m_readyState >= HAVE_FUTURE_DATA && [UA requires a decitions from the user]
3241 void HTMLMediaElement::updateVolume()
3246 double volumeMultiplier = 1;
3247 bool shouldMute = m_muted;
3249 if (m_mediaController) {
3250 volumeMultiplier *= m_mediaController->volume();
3251 shouldMute = m_mediaController->muted();
3254 m_player->setMuted(shouldMute);
3255 m_player->setVolume(m_volume * volumeMultiplier);
3257 if (hasMediaControls())
3258 mediaControls()->changedVolume();
3261 void HTMLMediaElement::updatePlayState()
3266 if (m_pausedInternal) {
3267 if (!m_player->paused())
3269 refreshCachedTime();
3270 m_playbackProgressTimer.stop();
3271 if (hasMediaControls())
3272 mediaControls()->playbackStopped();
3276 bool shouldBePlaying = potentiallyPlaying();
3277 bool playerPaused = m_player->paused();
3279 WTF_LOG(Media, "HTMLMediaElement::updatePlayState - shouldBePlaying = %s, playerPaused = %s",
3280 boolString(shouldBePlaying), boolString(playerPaused));
3282 if (shouldBePlaying) {
3283 setDisplayMode(Video);
3284 invalidateCachedTime();
3287 // Set rate, muted before calling play in case they were set before the media engine was setup.
3288 // The media engine should just stash the rate and muted values since it isn't already playing.
3289 m_player->setRate(m_playbackRate);
3290 m_player->setMuted(m_muted);
3295 if (hasMediaControls())
3296 mediaControls()->playbackStarted();
3297 startPlaybackProgressTimer();
3300 } else { // Should not be playing right now
3303 refreshCachedTime();
3305 m_playbackProgressTimer.stop();
3307 double time = currentTime();
3308 if (time > m_lastSeekTime)
3309 addPlayedRange(m_lastSeekTime, time);
3311 if (couldPlayIfEnoughData())
3314 if (hasMediaControls())
3315 mediaControls()->playbackStopped();
3318 updateMediaController();
3321 renderer()->updateFromElement();
3324 void HTMLMediaElement::setPausedInternal(bool b)
3326 m_pausedInternal = b;
3330 void HTMLMediaElement::stopPeriodicTimers()
3332 m_progressEventTimer.stop();
3333 m_playbackProgressTimer.stop();
3336 void HTMLMediaElement::userCancelledLoad()
3338 WTF_LOG(Media, "HTMLMediaElement::userCancelledLoad");
3340 // If the media data fetching process is aborted by the user:
3342 // 1 - The user agent should cancel the fetching process.
3343 clearMediaPlayer(-1);
3345 if (m_networkState == NETWORK_EMPTY || m_completelyLoaded)
3348 // 2 - Set the error attribute to a new MediaError object whose code attribute is set to MEDIA_ERR_ABORTED.
3349 m_error = MediaError::create(MediaError::MEDIA_ERR_ABORTED);
3351 // 3 - Queue a task to fire a simple event named error at the media element.
3352 scheduleEvent(EventTypeNames::abort);
3356 // 4 - If the media element's readyState attribute has a value equal to HAVE_NOTHING, set the
3357 // element's networkState attribute to the NETWORK_EMPTY value and queue a task to fire a
3358 // simple event named emptied at the element. Otherwise, set the element's networkState
3359 // attribute to the NETWORK_IDLE value.
3360 if (m_readyState == HAVE_NOTHING) {
3361 m_networkState = NETWORK_EMPTY;
3362 scheduleEvent(EventTypeNames::emptied);
3365 m_networkState = NETWORK_IDLE;
3367 // 5 - Set the element's delaying-the-load-event flag to false. This stops delaying the load event.
3368 setShouldDelayLoadEvent(false);
3370 // 6 - Abort the overall resource selection algorithm.
3371 m_currentSourceNode = 0;
3373 // Reset m_readyState since m_player is gone.
3374 m_readyState = HAVE_NOTHING;
3375 updateMediaController();
3376 if (RuntimeEnabledFeatures::videoTrackEnabled())
3377 updateActiveTextTrackCues(0);
3380 void HTMLMediaElement::clearMediaPlayerAndAudioSourceProviderClient()
3382 #if ENABLE(WEB_AUDIO)
3383 if (m_audioSourceNode)
3384 m_audioSourceNode->lock();
3386 if (audioSourceProvider())
3387 audioSourceProvider()->setClient(0);
3392 #if ENABLE(WEB_AUDIO)
3393 if (m_audioSourceNode)
3394 m_audioSourceNode->unlock();
3398 void HTMLMediaElement::clearMediaPlayer(int flags)
3400 removeAllInbandTracks();
3404 setMediaKeysInternal(0);
3406 clearMediaPlayerAndAudioSourceProviderClient();
3408 stopPeriodicTimers();
3411 m_pendingActionFlags &= ~flags;
3412 m_loadState = WaitingForSource;
3415 configureTextTrackDisplay(AssumeNoVisibleChange);
3418 void HTMLMediaElement::stop()
3420 WTF_LOG(Media, "HTMLMediaElement::stop");
3423 userCancelledLoad();
3425 // Stop the playback without generating events
3427 setPausedInternal(true);
3430 renderer()->updateFromElement();
3432 stopPeriodicTimers();
3433 cancelPendingEventsAndCallbacks();
3435 m_asyncEventQueue->close();
3438 bool HTMLMediaElement::hasPendingActivity() const
3440 return (hasAudio() && isPlaying()) || m_asyncEventQueue->hasPendingEvents();
3443 void HTMLMediaElement::contextDestroyed()
3445 if (m_mediaController)
3446 m_mediaController->clearExecutionContext();
3447 ActiveDOMObject::contextDestroyed();
3450 bool HTMLMediaElement::isFullscreen() const
3452 return FullscreenElementStack::isActiveFullScreenElement(this);
3455 void HTMLMediaElement::enterFullscreen()
3457 WTF_LOG(Media, "HTMLMediaElement::enterFullscreen");
3459 if (document().settings() && document().settings()->fullScreenEnabled())
3460 FullscreenElementStack::from(&document())->requestFullScreenForElement(this, 0, FullscreenElementStack::ExemptIFrameAllowFullScreenRequirement);
3463 void HTMLMediaElement::exitFullscreen()
3465 WTF_LOG(Media, "HTMLMediaElement::exitFullscreen");
3467 if (document().settings() && document().settings()->fullScreenEnabled() && isFullscreen())
3468 FullscreenElementStack::from(&document())->webkitCancelFullScreen();
3471 void HTMLMediaElement::didBecomeFullscreenElement()
3473 if (hasMediaControls())
3474 mediaControls()->enteredFullscreen();
3475 if (RuntimeEnabledFeatures::overlayFullscreenVideoEnabled() && isVideo())
3476 document().renderView()->compositor()->setCompositingLayersNeedRebuild(true);
3479 void HTMLMediaElement::willStopBeingFullscreenElement()
3481 if (hasMediaControls())
3482 mediaControls()->exitedFullscreen();
3483 if (RuntimeEnabledFeatures::overlayFullscreenVideoEnabled() && isVideo())
3484 document().renderView()->compositor()->setCompositingLayersNeedRebuild(true);
3487 blink::WebLayer* HTMLMediaElement::platformLayer() const
3492 bool HTMLMediaElement::hasClosedCaptions() const
3494 if (RuntimeEnabledFeatures::videoTrackEnabled() && m_textTracks) {
3495 for (unsigned i = 0; i < m_textTracks->length(); ++i) {
3496 if (m_textTracks->item(i)->readinessState() == TextTrack::FailedToLoad)
3499 if (m_textTracks->item(i)->kind() == TextTrack::captionsKeyword()
3500 || m_textTracks->item(i)->kind() == TextTrack::subtitlesKeyword())
3507 bool HTMLMediaElement::closedCaptionsVisible() const
3509 return m_closedCaptionsVisible;
3512 void HTMLMediaElement::updateTextTrackDisplay()
3514 WTF_LOG(Media, "HTMLMediaElement::updateTextTrackDisplay");
3516 if (!hasMediaControls() && !createMediaControls())
3519 mediaControls()->updateTextTrackDisplay();
3522 void HTMLMediaElement::setClosedCaptionsVisible(bool closedCaptionVisible)
3524 WTF_LOG(Media, "HTMLMediaElement::setClosedCaptionsVisible(%s)", boolString(closedCaptionVisible));
3526 if (!m_player || !hasClosedCaptions())
3529 m_closedCaptionsVisible = closedCaptionVisible;
3531 if (RuntimeEnabledFeatures::videoTrackEnabled()) {
3532 m_processingPreferenceChange = true;
3533 markCaptionAndSubtitleTracksAsUnconfigured();
3534 m_processingPreferenceChange = false;
3536 updateTextTrackDisplay();
3540 unsigned HTMLMediaElement::webkitAudioDecodedByteCount() const
3544 return m_player->audioDecodedByteCount();
3547 unsigned HTMLMediaElement::webkitVideoDecodedByteCount() const
3551 return m_player->videoDecodedByteCount();
3554 bool HTMLMediaElement::isURLAttribute(const Attribute& attribute) const
3556 return attribute.name() == srcAttr || HTMLElement::isURLAttribute(attribute);
3559 void HTMLMediaElement::setShouldDelayLoadEvent(bool shouldDelay)
3561 if (m_shouldDelayLoadEvent == shouldDelay)
3564 WTF_LOG(Media, "HTMLMediaElement::setShouldDelayLoadEvent(%s)", boolString(shouldDelay));
3566 m_shouldDelayLoadEvent = shouldDelay;
3568 document().incrementLoadEventDelayCount();
3570 document().decrementLoadEventDelayCount();
3574 MediaControls* HTMLMediaElement::mediaControls() const
3576 return toMediaControls(userAgentShadowRoot()->firstChild());
3579 bool HTMLMediaElement::hasMediaControls() const
3581 if (ShadowRoot* userAgent = userAgentShadowRoot()) {
3582 Node* node = userAgent->firstChild();
3583 ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isMediaControls());
3590 bool HTMLMediaElement::createMediaControls()
3592 if (hasMediaControls())
3595 RefPtr<MediaControls> mediaControls = MediaControls::create(document());
3599 mediaControls->setMediaController(m_mediaController ? m_mediaController.get() : static_cast<MediaControllerInterface*>(this));
3600 mediaControls->reset();
3602 mediaControls->enteredFullscreen();
3604 ensureUserAgentShadowRoot().appendChild(mediaControls);
3606 if (!controls() || !inDocument())
3607 mediaControls->hide();
3612 void HTMLMediaElement::configureMediaControls()
3614 if (!controls() || !inDocument()) {
3615 if (hasMediaControls())
3616 mediaControls()->hide();
3620 if (!hasMediaControls() && !createMediaControls())
3623 mediaControls()->show();
3626 void HTMLMediaElement::configureTextTrackDisplay(VisibilityChangeAssumption assumption)
3628 ASSERT(m_textTracks);
3629 WTF_LOG(Media, "HTMLMediaElement::configureTextTrackDisplay");
3631 if (m_processingPreferenceChange)
3634 bool haveVisibleTextTrack = false;
3635 for (unsigned i = 0; i < m_textTracks->length(); ++i) {
3636 if (m_textTracks->item(i)->mode() == TextTrack::showingKeyword()) {
3637 haveVisibleTextTrack = true;
3642 if (assumption == AssumeNoVisibleChange
3643 && m_haveVisibleTextTrack == haveVisibleTextTrack) {
3644 updateActiveTextTrackCues(currentTime());
3647 m_haveVisibleTextTrack = haveVisibleTextTrack;
3648 m_closedCaptionsVisible = m_haveVisibleTextTrack;
3650 if (!m_haveVisibleTextTrack && !hasMediaControls())
3652 if (!hasMediaControls() && !createMediaControls())
3655 mediaControls()->changedClosedCaptionsVisibility();
3657 if (RuntimeEnabledFeatures::videoTrackEnabled()) {
3658 updateActiveTextTrackCues(currentTime());
3659 updateTextTrackDisplay();
3663 void HTMLMediaElement::markCaptionAndSubtitleTracksAsUnconfigured()
3668 // Mark all tracks as not "configured" so that configureTextTracks()
3669 // will reconsider which tracks to display in light of new user preferences
3670 // (e.g. default tracks should not be displayed if the user has turned off
3671 // captions and non-default tracks should be displayed based on language
3672 // preferences if the user has turned captions on).
3673 for (unsigned i = 0; i < m_textTracks->length(); ++i) {
3674 RefPtr<TextTrack> textTrack = m_textTracks->item(i);
3675 String kind = textTrack->kind();
3677 if (kind == TextTrack::subtitlesKeyword() || kind == TextTrack::captionsKeyword())
3678 textTrack->setHasBeenConfigured(false);
3680 configureTextTracks();
3684 void* HTMLMediaElement::preDispatchEventHandler(Event* event)
3686 if (event && event->type() == EventTypeNames::webkitfullscreenchange)
3687 configureMediaControls();
3692 void HTMLMediaElement::createMediaPlayer()
3694 #if ENABLE(WEB_AUDIO)
3695 if (m_audioSourceNode)
3696 m_audioSourceNode->lock();
3702 m_player = MediaPlayer::create(this);
3704 if (m_emeMode == EmeModeUnprefixed && m_player)
3705 m_player->setContentDecryptionModule(contentDecryptionModule());
3707 #if ENABLE(WEB_AUDIO)
3708 if (m_audioSourceNode) {
3709 // When creating the player, make sure its AudioSourceProvider knows about the MediaElementAudioSourceNode.
3710 if (audioSourceProvider())
3711 audioSourceProvider()->setClient(m_audioSourceNode);
3713 m_audioSourceNode->unlock();
3718 #if ENABLE(WEB_AUDIO)
3719 void HTMLMediaElement::setAudioSourceNode(MediaElementAudioSourceNode* sourceNode)
3721 m_audioSourceNode = sourceNode;
3723 if (m_audioSourceNode)
3724 m_audioSourceNode->lock();
3726 if (audioSourceProvider())
3727 audioSourceProvider()->setClient(m_audioSourceNode);
3729 if (m_audioSourceNode)
3730 m_audioSourceNode->unlock();
3733 AudioSourceProvider* HTMLMediaElement::audioSourceProvider()
3736 return m_player->audioSourceProvider();
3742 const AtomicString& HTMLMediaElement::mediaGroup() const
3744 return fastGetAttribute(mediagroupAttr);
3747 void HTMLMediaElement::setMediaGroup(const AtomicString& group)
3749 // When a media element is created with a mediagroup attribute, and when a media element's mediagroup
3750 // attribute is set, changed, or removed, the user agent must run the following steps:
3751 // 1. Let m [this] be the media element in question.
3752 // 2. Let m have no current media controller, if it currently has one.
3753 setControllerInternal(0);
3755 // 3. If m's mediagroup attribute is being removed, then abort these steps.
3756 if (group.isNull() || group.isEmpty())
3759 // 4. If there is another media element whose Document is the same as m's Document (even if one or both
3760 // of these elements are not actually in the Document),
3761 HashSet<HTMLMediaElement*> elements = documentToElementSetMap().get(&document());
3762 for (HashSet<HTMLMediaElement*>::iterator i = elements.begin(); i != elements.end(); ++i) {
3766 // and which also has a mediagroup attribute, and whose mediagroup attribute has the same value as
3767 // the new value of m's mediagroup attribute,
3768 if ((*i)->mediaGroup() == group) {
3769 // then let controller be that media element's current media controller.
3770 setControllerInternal((*i)->controller());
3775 // Otherwise, let controller be a newly created MediaController.
3776 setControllerInternal(MediaController::create(Node::executionContext()));
3779 MediaController* HTMLMediaElement::controller() const
3781 return m_mediaController.get();
3784 void HTMLMediaElement::setController(PassRefPtr<MediaController> controller)
3786 // 4.8.10.11.2 Media controllers: controller attribute.
3787 // On setting, it must first remove the element's mediagroup attribute, if any,
3788 removeAttribute(mediagroupAttr);
3789 // and then set the current media controller to the given value.
3790 setControllerInternal(controller);
3793 void HTMLMediaElement::setControllerInternal(PassRefPtr<MediaController> controller)
3795 if (m_mediaController)
3796 m_mediaController->removeMediaElement(this);
3798 m_mediaController = controller;
3800 if (m_mediaController) {
3801 UseCounter::count(document(), UseCounter::HTMLMediaElementControllerNotNull);
3802 m_mediaController->addMediaElement(this);
3805 if (hasMediaControls())
3806 mediaControls()->setMediaController(m_mediaController ? m_mediaController.get() : static_cast<MediaControllerInterface*>(this));
3809 void HTMLMediaElement::updateMediaController()
3811 if (m_mediaController)
3812 m_mediaController->reportControllerState();
3815 bool HTMLMediaElement::isBlocked() const
3817 // A media element is a blocked media element if its readyState attribute is in the
3818 // HAVE_NOTHING state, the HAVE_METADATA state, or the HAVE_CURRENT_DATA state,
3819 if (m_readyState <= HAVE_CURRENT_DATA)
3822 // or if the element has paused for user interaction.
3823 return pausedForUserInteraction();
3826 bool HTMLMediaElement::isBlockedOnMediaController() const
3828 if (!m_mediaController)
3831 // A media element is blocked on its media controller if the MediaController is a blocked
3832 // media controller,
3833 if (m_mediaController->isBlocked())
3836 // or if its media controller position is either before the media resource's earliest possible
3837 // position relative to the MediaController's timeline or after the end of the media resource
3838 // relative to the MediaController's timeline.
3839 double mediaControllerPosition = m_mediaController->currentTime();
3840 if (mediaControllerPosition < 0 || mediaControllerPosition > duration())
3846 void HTMLMediaElement::prepareMediaFragmentURI()
3848 MediaFragmentURIParser fragmentParser(m_currentSrc);
3849 double dur = duration();
3851 double start = fragmentParser.startTime();
3852 if (start != MediaFragmentURIParser::invalidTimeValue() && start > 0) {
3853 m_fragmentStartTime = start;
3854 if (m_fragmentStartTime > dur)
3855 m_fragmentStartTime = dur;
3857 m_fragmentStartTime = MediaPlayer::invalidTime();
3859 double end = fragmentParser.endTime();
3860 if (end != MediaFragmentURIParser::invalidTimeValue() && end > 0 && end > m_fragmentStartTime) {
3861 m_fragmentEndTime = end;
3862 if (m_fragmentEndTime > dur)
3863 m_fragmentEndTime = dur;
3865 m_fragmentEndTime = MediaPlayer::invalidTime();
3867 if (m_fragmentStartTime != MediaPlayer::invalidTime() && m_readyState < HAVE_FUTURE_DATA)
3871 void HTMLMediaElement::applyMediaFragmentURI()
3873 if (m_fragmentStartTime != MediaPlayer::invalidTime()) {
3874 m_sentEndEvent = false;
3875 seek(m_fragmentStartTime, IGNORE_EXCEPTION);
3879 MediaPlayerClient::CORSMode HTMLMediaElement::mediaPlayerCORSMode() const
3881 const AtomicString& crossOriginMode = fastGetAttribute(crossoriginAttr);
3882 if (crossOriginMode.isNull())
3884 if (equalIgnoringCase(crossOriginMode, "use-credentials"))
3885 return UseCredentials;
3889 void HTMLMediaElement::removeBehaviorsRestrictionsAfterFirstUserGesture()
3891 m_restrictions = NoRestrictions;
3894 void HTMLMediaElement::mediaPlayerSetWebLayer(blink::WebLayer* webLayer)
3896 if (webLayer == m_webLayer)
3899 // If either of the layers is null we need to enable or disable compositing. This is done by triggering a style recalc.
3900 if (!m_webLayer || !webLayer)
3901 scheduleLayerUpdate();
3904 GraphicsLayer::unregisterContentsLayer(m_webLayer);
3905 m_webLayer = webLayer;
3907 m_webLayer->setOpaque(m_opaque);
3908 GraphicsLayer::registerContentsLayer(m_webLayer);
3912 void HTMLMediaElement::mediaPlayerSetOpaque(bool opaque)
3916 m_webLayer->setOpaque(m_opaque);
3919 void HTMLMediaElement::mediaPlayerMediaSourceOpened(blink::WebMediaSource* webMediaSource)
3921 m_mediaSource->setWebMediaSourceAndOpen(adoptPtr(webMediaSource));
3924 bool HTMLMediaElement::isInteractiveContent() const
3926 return fastHasAttribute(controlsAttr);