2 * Copyright (C) 2007, 2008, 2009, 2010 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.
29 #include "HTMLMediaElement.h"
31 #include "Attribute.h"
33 #include "ChromeClient.h"
34 #include "ClientRect.h"
35 #include "ClientRectList.h"
36 #include "ContentType.h"
37 #include "CSSPropertyNames.h"
38 #include "CSSValueKeywords.h"
40 #include "EventNames.h"
41 #include "ExceptionCode.h"
43 #include "FrameLoader.h"
44 #include "FrameLoaderClient.h"
45 #include "FrameView.h"
46 #include "HTMLDocument.h"
47 #include "HTMLNames.h"
48 #include "HTMLSourceElement.h"
49 #include "HTMLVideoElement.h"
51 #include "MediaDocument.h"
52 #include "MediaError.h"
53 #include "MediaList.h"
54 #include "MediaPlayer.h"
55 #include "MediaQueryEvaluator.h"
56 #include "MIMETypeRegistry.h"
58 #include "RenderVideo.h"
59 #include "RenderView.h"
60 #include "ScriptEventListener.h"
62 #include "TimeRanges.h"
64 #include <wtf/CurrentTime.h>
65 #include <wtf/MathExtras.h>
66 #include <wtf/text/CString.h>
68 #if USE(ACCELERATED_COMPOSITING)
69 #include "RenderView.h"
70 #include "RenderLayerCompositor.h"
73 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
74 #include "RenderEmbeddedObject.h"
83 static String urlForLogging(const String& url)
85 static const unsigned maximumURLLengthForLogging = 128;
87 if (url.length() < maximumURLLengthForLogging)
89 return url.substring(0, maximumURLLengthForLogging) + "...";
92 static const char *boolString(bool val)
94 return val ? "true" : "false";
98 #ifndef LOG_MEDIA_EVENTS
99 // Default to not logging events because so many are generated they can overwhelm the rest of
101 #define LOG_MEDIA_EVENTS 0
104 #ifndef LOG_CACHED_TIME_WARNINGS
105 // Default to not logging warnings about excessive drift in the cached media time because it adds a
106 // fair amount of overhead and logging.
107 #define LOG_CACHED_TIME_WARNINGS 0
110 static const float invalidMediaTime = -1;
112 using namespace HTMLNames;
114 HTMLMediaElement::HTMLMediaElement(const QualifiedName& tagName, Document* document)
115 : HTMLElement(tagName, document)
116 , ActiveDOMObject(document, this)
117 , m_loadTimer(this, &HTMLMediaElement::loadTimerFired)
118 , m_asyncEventTimer(this, &HTMLMediaElement::asyncEventTimerFired)
119 , m_progressEventTimer(this, &HTMLMediaElement::progressEventTimerFired)
120 , m_playbackProgressTimer(this, &HTMLMediaElement::playbackProgressTimerFired)
121 , m_playedTimeRanges()
122 , m_playbackRate(1.0f)
123 , m_defaultPlaybackRate(1.0f)
124 , m_webkitPreservesPitch(true)
125 , m_networkState(NETWORK_EMPTY)
126 , m_readyState(HAVE_NOTHING)
127 , m_readyStateMaximum(HAVE_NOTHING)
130 , m_previousProgress(0)
131 , m_previousProgressTime(numeric_limits<double>::max())
132 , m_lastTimeUpdateEventWallTime(0)
133 , m_lastTimeUpdateEventMovieTime(numeric_limits<float>::max())
134 , m_loadState(WaitingForSource)
135 , m_currentSourceNode(0)
136 , m_nextChildNodeToConsider(0)
138 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
141 , m_restrictions(NoRestrictions)
142 , m_preload(MediaPlayer::Auto)
143 , m_displayMode(Unknown)
144 , m_processingMediaPlayerCallback(0)
145 , m_cachedTime(invalidMediaTime)
146 , m_cachedTimeWallClockUpdateTime(0)
147 , m_minimumWallClockTimeToCacheMediaTime(0)
149 , m_isWaitingUntilMediaCanStart(false)
150 , m_shouldDelayLoadEvent(false)
151 , m_haveFiredLoadedData(false)
152 , m_inActiveDocument(true)
153 , m_autoplaying(true)
157 , m_sentStalledEvent(false)
158 , m_sentEndEvent(false)
159 , m_pausedInternal(false)
160 , m_sendProgressEvents(true)
161 , m_isFullscreen(false)
162 , m_closedCaptionsVisible(false)
163 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
164 , m_needWidgetUpdate(false)
166 , m_dispatchingCanPlayEvent(false)
167 , m_loadInitiatedByUserGesture(false)
168 , m_completelyLoaded(false)
170 LOG(Media, "HTMLMediaElement::HTMLMediaElement");
171 document->registerForDocumentActivationCallbacks(this);
172 document->registerForMediaVolumeCallbacks(this);
175 HTMLMediaElement::~HTMLMediaElement()
177 LOG(Media, "HTMLMediaElement::~HTMLMediaElement");
178 if (m_isWaitingUntilMediaCanStart)
179 document()->removeMediaCanStartListener(this);
180 setShouldDelayLoadEvent(false);
181 document()->unregisterForDocumentActivationCallbacks(this);
182 document()->unregisterForMediaVolumeCallbacks(this);
185 void HTMLMediaElement::willMoveToNewOwnerDocument()
187 if (m_isWaitingUntilMediaCanStart)
188 document()->removeMediaCanStartListener(this);
189 setShouldDelayLoadEvent(false);
190 document()->unregisterForDocumentActivationCallbacks(this);
191 document()->unregisterForMediaVolumeCallbacks(this);
192 HTMLElement::willMoveToNewOwnerDocument();
195 void HTMLMediaElement::didMoveToNewOwnerDocument()
197 if (m_isWaitingUntilMediaCanStart)
198 document()->addMediaCanStartListener(this);
199 if (m_readyState < HAVE_CURRENT_DATA)
200 setShouldDelayLoadEvent(true);
201 document()->registerForDocumentActivationCallbacks(this);
202 document()->registerForMediaVolumeCallbacks(this);
203 HTMLElement::didMoveToNewOwnerDocument();
206 void HTMLMediaElement::attributeChanged(Attribute* attr, bool preserveDecls)
208 HTMLElement::attributeChanged(attr, preserveDecls);
210 const QualifiedName& attrName = attr->name();
211 if (attrName == srcAttr) {
212 // Trigger a reload, as long as the 'src' attribute is present.
213 if (!getAttribute(srcAttr).isEmpty())
216 else if (attrName == controlsAttr) {
217 #if !ENABLE(PLUGIN_PROXY_FOR_VIDEO)
218 if (!isVideo() && attached() && (controls() != (renderer() != 0))) {
223 renderer()->updateFromElement();
226 m_player->setControls(controls());
231 void HTMLMediaElement::parseMappedAttribute(Attribute* attr)
233 const QualifiedName& attrName = attr->name();
235 if (attrName == preloadAttr) {
236 String value = attr->value();
238 if (equalIgnoringCase(value, "none"))
239 m_preload = MediaPlayer::None;
240 else if (equalIgnoringCase(value, "metadata"))
241 m_preload = MediaPlayer::MetaData;
243 // The spec does not define an "invalid value default" but "auto" is suggested as the
244 // "missing value default", so use it for everything except "none" and "metadata"
245 m_preload = MediaPlayer::Auto;
248 // The attribute must be ignored if the autoplay attribute is present
249 if (!autoplay() && m_player)
250 m_player->setPreload(m_preload);
252 } else if (attrName == onabortAttr)
253 setAttributeEventListener(eventNames().abortEvent, createAttributeEventListener(this, attr));
254 else if (attrName == onbeforeloadAttr)
255 setAttributeEventListener(eventNames().beforeloadEvent, createAttributeEventListener(this, attr));
256 else if (attrName == oncanplayAttr)
257 setAttributeEventListener(eventNames().canplayEvent, createAttributeEventListener(this, attr));
258 else if (attrName == oncanplaythroughAttr)
259 setAttributeEventListener(eventNames().canplaythroughEvent, createAttributeEventListener(this, attr));
260 else if (attrName == ondurationchangeAttr)
261 setAttributeEventListener(eventNames().durationchangeEvent, createAttributeEventListener(this, attr));
262 else if (attrName == onemptiedAttr)
263 setAttributeEventListener(eventNames().emptiedEvent, createAttributeEventListener(this, attr));
264 else if (attrName == onendedAttr)
265 setAttributeEventListener(eventNames().endedEvent, createAttributeEventListener(this, attr));
266 else if (attrName == onerrorAttr)
267 setAttributeEventListener(eventNames().errorEvent, createAttributeEventListener(this, attr));
268 else if (attrName == onloadeddataAttr)
269 setAttributeEventListener(eventNames().loadeddataEvent, createAttributeEventListener(this, attr));
270 else if (attrName == onloadedmetadataAttr)
271 setAttributeEventListener(eventNames().loadedmetadataEvent, createAttributeEventListener(this, attr));
272 else if (attrName == onloadstartAttr)
273 setAttributeEventListener(eventNames().loadstartEvent, createAttributeEventListener(this, attr));
274 else if (attrName == onpauseAttr)
275 setAttributeEventListener(eventNames().pauseEvent, createAttributeEventListener(this, attr));
276 else if (attrName == onplayAttr)
277 setAttributeEventListener(eventNames().playEvent, createAttributeEventListener(this, attr));
278 else if (attrName == onplayingAttr)
279 setAttributeEventListener(eventNames().playingEvent, createAttributeEventListener(this, attr));
280 else if (attrName == onprogressAttr)
281 setAttributeEventListener(eventNames().progressEvent, createAttributeEventListener(this, attr));
282 else if (attrName == onratechangeAttr)
283 setAttributeEventListener(eventNames().ratechangeEvent, createAttributeEventListener(this, attr));
284 else if (attrName == onseekedAttr)
285 setAttributeEventListener(eventNames().seekedEvent, createAttributeEventListener(this, attr));
286 else if (attrName == onseekingAttr)
287 setAttributeEventListener(eventNames().seekingEvent, createAttributeEventListener(this, attr));
288 else if (attrName == onstalledAttr)
289 setAttributeEventListener(eventNames().stalledEvent, createAttributeEventListener(this, attr));
290 else if (attrName == onsuspendAttr)
291 setAttributeEventListener(eventNames().suspendEvent, createAttributeEventListener(this, attr));
292 else if (attrName == ontimeupdateAttr)
293 setAttributeEventListener(eventNames().timeupdateEvent, createAttributeEventListener(this, attr));
294 else if (attrName == onvolumechangeAttr)
295 setAttributeEventListener(eventNames().volumechangeEvent, createAttributeEventListener(this, attr));
296 else if (attrName == onwaitingAttr)
297 setAttributeEventListener(eventNames().waitingEvent, createAttributeEventListener(this, attr));
298 else if (attrName == onwebkitbeginfullscreenAttr)
299 setAttributeEventListener(eventNames().webkitbeginfullscreenEvent, createAttributeEventListener(this, attr));
300 else if (attrName == onwebkitendfullscreenAttr)
301 setAttributeEventListener(eventNames().webkitendfullscreenEvent, createAttributeEventListener(this, attr));
303 HTMLElement::parseMappedAttribute(attr);
306 bool HTMLMediaElement::rendererIsNeeded(RenderStyle* style)
308 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
310 Frame* frame = document()->frame();
316 return controls() ? HTMLElement::rendererIsNeeded(style) : false;
320 RenderObject* HTMLMediaElement::createRenderer(RenderArena* arena, RenderStyle*)
322 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
323 // Setup the renderer if we already have a proxy widget.
324 RenderEmbeddedObject* mediaRenderer = new (arena) RenderEmbeddedObject(this);
326 mediaRenderer->setWidget(m_proxyWidget);
328 Frame* frame = document()->frame();
329 FrameLoader* loader = frame ? frame->loader() : 0;
331 loader->showMediaPlayerProxyPlugin(m_proxyWidget.get());
333 return mediaRenderer;
335 return new (arena) RenderMedia(this);
339 void HTMLMediaElement::insertedIntoDocument()
341 LOG(Media, "HTMLMediaElement::removedFromDocument");
342 HTMLElement::insertedIntoDocument();
343 if (!getAttribute(srcAttr).isEmpty() && m_networkState == NETWORK_EMPTY)
347 void HTMLMediaElement::removedFromDocument()
349 LOG(Media, "HTMLMediaElement::removedFromDocument");
350 if (m_networkState > NETWORK_EMPTY)
351 pause(processingUserGesture());
354 HTMLElement::removedFromDocument();
357 void HTMLMediaElement::attach()
361 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
362 m_needWidgetUpdate = true;
365 HTMLElement::attach();
368 renderer()->updateFromElement();
369 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
370 else if (m_proxyWidget) {
371 Frame* frame = document()->frame();
372 FrameLoader* loader = frame ? frame->loader() : 0;
374 loader->hideMediaPlayerProxyPlugin(m_proxyWidget.get());
379 void HTMLMediaElement::recalcStyle(StyleChange change)
381 HTMLElement::recalcStyle(change);
384 renderer()->updateFromElement();
387 void HTMLMediaElement::scheduleLoad()
389 LOG(Media, "HTMLMediaElement::scheduleLoad");
390 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
391 createMediaPlayerProxy();
394 if (m_loadTimer.isActive())
397 m_loadTimer.startOneShot(0);
400 void HTMLMediaElement::scheduleNextSourceChild()
402 // Schedule the timer to try the next <source> element WITHOUT resetting state ala prepareForLoad.
403 m_loadTimer.startOneShot(0);
406 void HTMLMediaElement::scheduleEvent(const AtomicString& eventName)
409 LOG(Media, "HTMLMediaElement::scheduleEvent - scheduling '%s'", eventName.string().ascii().data());
411 m_pendingEvents.append(Event::create(eventName, false, true));
412 if (!m_asyncEventTimer.isActive())
413 m_asyncEventTimer.startOneShot(0);
416 void HTMLMediaElement::asyncEventTimerFired(Timer<HTMLMediaElement>*)
418 Vector<RefPtr<Event> > pendingEvents;
419 ExceptionCode ec = 0;
421 m_pendingEvents.swap(pendingEvents);
422 unsigned count = pendingEvents.size();
423 for (unsigned ndx = 0; ndx < count; ++ndx) {
425 LOG(Media, "HTMLMediaElement::asyncEventTimerFired - dispatching '%s'", pendingEvents[ndx]->type().string().ascii().data());
427 if (pendingEvents[ndx]->type() == eventNames().canplayEvent) {
428 m_dispatchingCanPlayEvent = true;
429 dispatchEvent(pendingEvents[ndx].release(), ec);
430 m_dispatchingCanPlayEvent = false;
432 dispatchEvent(pendingEvents[ndx].release(), ec);
436 void HTMLMediaElement::loadTimerFired(Timer<HTMLMediaElement>*)
438 if (m_loadState == LoadingFromSourceElement)
439 loadNextSourceChild();
444 PassRefPtr<MediaError> HTMLMediaElement::error() const
449 void HTMLMediaElement::setSrc(const String& url)
451 setAttribute(srcAttr, url);
454 String HTMLMediaElement::currentSrc() const
459 HTMLMediaElement::NetworkState HTMLMediaElement::networkState() const
461 return m_networkState;
464 String HTMLMediaElement::canPlayType(const String& mimeType) const
466 MediaPlayer::SupportsType support = MediaPlayer::supportsType(ContentType(mimeType));
472 case MediaPlayer::IsNotSupported:
475 case MediaPlayer::MayBeSupported:
478 case MediaPlayer::IsSupported:
479 canPlay = "probably";
483 LOG(Media, "HTMLMediaElement::canPlayType(%s) -> %s", mimeType.utf8().data(), canPlay.utf8().data());
488 void HTMLMediaElement::load(bool isUserGesture, ExceptionCode& ec)
490 LOG(Media, "HTMLMediaElement::load(isUserGesture : %s)", boolString(isUserGesture));
492 if (m_restrictions & RequireUserGestureForLoadRestriction && !isUserGesture)
493 ec = INVALID_STATE_ERR;
495 m_loadInitiatedByUserGesture = isUserGesture;
501 void HTMLMediaElement::prepareForLoad()
503 LOG(Media, "HTMLMediaElement::prepareForLoad");
505 // Perform the cleanup required for the resource load algorithm to run.
506 stopPeriodicTimers();
508 m_sentStalledEvent = false;
509 m_haveFiredLoadedData = false;
510 m_completelyLoaded = false;
511 m_displayMode = Unknown;
513 // 1 - Abort any already-running instance of the resource selection algorithm for this element.
514 m_loadState = WaitingForSource;
515 m_currentSourceNode = 0;
517 // 2 - If there are any tasks from the media element's media element event task source in
518 // one of the task queues, then remove those tasks.
519 cancelPendingEventsAndCallbacks();
521 // 3 - If the media element's networkState is set to NETWORK_LOADING or NETWORK_IDLE, queue
522 // a task to fire a simple event named abort at the media element.
523 if (m_networkState == NETWORK_LOADING || m_networkState == NETWORK_IDLE)
524 scheduleEvent(eventNames().abortEvent);
526 #if !ENABLE(PLUGIN_PROXY_FOR_VIDEO)
527 m_player = MediaPlayer::create(this);
530 m_player->cancelLoad();
532 createMediaPlayerProxy();
535 // 4 - If the media element's networkState is not set to NETWORK_EMPTY, then run these substeps
536 if (m_networkState != NETWORK_EMPTY) {
537 m_networkState = NETWORK_EMPTY;
538 m_readyState = HAVE_NOTHING;
539 m_readyStateMaximum = HAVE_NOTHING;
543 invalidateCachedTime();
544 scheduleEvent(eventNames().emptiedEvent);
547 // 5 - Set the playbackRate attribute to the value of the defaultPlaybackRate attribute.
548 setPlaybackRate(defaultPlaybackRate());
550 // 6 - Set the error attribute to null and the autoplaying flag to true.
552 m_autoplaying = true;
554 // 7 - Invoke the media element's resource selection algorithm.
556 // 8 - Note: Playback of any previously playing media resource for this element stops.
558 // The resource selection algorithm
559 // 1 - Set the networkState to NETWORK_NO_SOURCE
560 m_networkState = NETWORK_NO_SOURCE;
562 // 2 - Asynchronously await a stable state.
564 m_playedTimeRanges = TimeRanges::create();
566 m_closedCaptionsVisible = false;
568 // The spec doesn't say to block the load event until we actually run the asynchronous section
569 // algorithm, but do it now because we won't start that until after the timer fires and the
570 // event may have already fired by then.
571 setShouldDelayLoadEvent(true);
574 void HTMLMediaElement::loadInternal()
576 // If we can't start a load right away, start it later.
577 Page* page = document()->page();
578 if (page && !page->canStartMedia()) {
579 if (m_isWaitingUntilMediaCanStart)
581 document()->addMediaCanStartListener(this);
582 m_isWaitingUntilMediaCanStart = true;
586 selectMediaResource();
589 void HTMLMediaElement::selectMediaResource()
591 LOG(Media, "HTMLMediaElement::selectMediaResource");
593 enum Mode { attribute, children };
594 Mode mode = attribute;
596 // 3 - ... the media element has neither a src attribute ...
597 if (!hasAttribute(srcAttr)) {
598 // ... nor a source element child: ...
600 for (node = firstChild(); node; node = node->nextSibling()) {
601 if (node->hasTagName(sourceTag))
606 m_loadState = WaitingForSource;
607 setShouldDelayLoadEvent(false);
609 // ... set the networkState to NETWORK_EMPTY, and abort these steps
610 m_networkState = NETWORK_EMPTY;
612 LOG(Media, "HTMLMediaElement::selectMediaResource, nothing to load");
619 // 4 - Set the media element's delaying-the-load-event flag to true (this delays the load event),
620 // and set its networkState to NETWORK_LOADING.
621 setShouldDelayLoadEvent(true);
622 m_networkState = NETWORK_LOADING;
625 scheduleEvent(eventNames().loadstartEvent);
627 // 6 - If mode is attribute, then run these substeps
628 if (mode == attribute) {
629 // If the src attribute's value is the empty string ... jump down to the failed step below
630 KURL mediaURL = getNonEmptyURLAttribute(srcAttr);
631 if (mediaURL.isEmpty()) {
633 LOG(Media, "HTMLMediaElement::selectMediaResource, empty 'src'");
637 if (isSafeToLoadURL(mediaURL, Complain) && dispatchBeforeLoadEvent(mediaURL.string())) {
638 ContentType contentType("");
639 m_loadState = LoadingFromSrcAttr;
640 loadResource(mediaURL, contentType);
644 LOG(Media, "HTMLMediaElement::selectMediaResource, 'src' not used");
648 // Otherwise, the source elements will be used
649 m_currentSourceNode = 0;
650 loadNextSourceChild();
653 void HTMLMediaElement::loadNextSourceChild()
655 ContentType contentType("");
656 KURL mediaURL = selectNextSourceChild(&contentType, Complain);
657 if (!mediaURL.isValid()) {
658 waitForSourceChange();
662 #if !ENABLE(PLUGIN_PROXY_FOR_VIDEO)
663 // Recreate the media player for the new url
664 m_player = MediaPlayer::create(this);
667 m_loadState = LoadingFromSourceElement;
668 loadResource(mediaURL, contentType);
671 void HTMLMediaElement::loadResource(const KURL& initialURL, ContentType& contentType)
673 ASSERT(isSafeToLoadURL(initialURL, Complain));
675 LOG(Media, "HTMLMediaElement::loadResource(%s, %s)", urlForLogging(initialURL.string()).utf8().data(), contentType.raw().utf8().data());
677 Frame* frame = document()->frame();
680 FrameLoader* loader = frame->loader();
684 KURL url(initialURL);
685 if (!loader->willLoadMediaElementURL(url))
688 // The resource fetch algorithm
689 m_networkState = NETWORK_LOADING;
693 LOG(Media, "HTMLMediaElement::loadResource - m_currentSrc -> %s", urlForLogging(m_currentSrc).utf8().data());
695 if (m_sendProgressEvents)
696 startProgressEventTimer();
699 m_player->setPreload(m_preload);
700 m_player->setPreservesPitch(m_webkitPreservesPitch);
703 m_player->load(m_currentSrc, contentType);
705 // If there is no poster to display, allow the media engine to render video frames as soon as
706 // they are available.
707 updateDisplayState();
710 renderer()->updateFromElement();
713 bool HTMLMediaElement::isSafeToLoadURL(const KURL& url, InvalidSourceAction actionIfInvalid)
715 if (!url.isValid()) {
716 LOG(Media, "HTMLMediaElement::isSafeToLoadURL(%s) -> FALSE because url is invalid", urlForLogging(url.string()).utf8().data());
720 Frame* frame = document()->frame();
721 if (!frame || !document()->securityOrigin()->canDisplay(url)) {
722 if (actionIfInvalid == Complain)
723 FrameLoader::reportLocalLoadFailed(frame, url.string());
724 LOG(Media, "HTMLMediaElement::isSafeToLoadURL(%s) -> FALSE rejected by SecurityOrigin", urlForLogging(url.string()).utf8().data());
731 void HTMLMediaElement::startProgressEventTimer()
733 if (m_progressEventTimer.isActive())
736 m_previousProgressTime = WTF::currentTime();
737 m_previousProgress = 0;
738 // 350ms is not magic, it is in the spec!
739 m_progressEventTimer.startRepeating(0.350);
742 void HTMLMediaElement::waitForSourceChange()
744 LOG(Media, "HTMLMediaElement::waitForSourceChange");
746 stopPeriodicTimers();
747 m_loadState = WaitingForSource;
749 // 6.17 - Waiting: Set the element's networkState attribute to the NETWORK_NO_SOURCE value
750 m_networkState = NETWORK_NO_SOURCE;
752 // 6.18 - Set the element's delaying-the-load-event flag to false. This stops delaying the load event.
753 setShouldDelayLoadEvent(false);
756 void HTMLMediaElement::noneSupported()
758 LOG(Media, "HTMLMediaElement::noneSupported");
760 stopPeriodicTimers();
761 m_loadState = WaitingForSource;
762 m_currentSourceNode = 0;
764 // 5 - Reaching this step indicates that either the URL failed to resolve, or the media
765 // resource failed to load. Set the error attribute to a new MediaError object whose
766 // code attribute is set to MEDIA_ERR_SRC_NOT_SUPPORTED.
767 m_error = MediaError::create(MediaError::MEDIA_ERR_SRC_NOT_SUPPORTED);
769 // 6 - Set the element's networkState attribute to the NETWORK_NO_SOURCE value.
770 m_networkState = NETWORK_NO_SOURCE;
772 // 7 - Queue a task to fire a progress event called error at the media element, in
773 // the context of the fetching process that was used to try to obtain the media
774 // resource in the resource fetch algorithm.
775 scheduleEvent(eventNames().errorEvent);
777 // 8 - Set the element's delaying-the-load-event flag to false. This stops delaying the load event.
778 setShouldDelayLoadEvent(false);
780 // 9 -Abort these steps. Until the load() method is invoked, the element won't attempt to load another resource.
782 updateDisplayState();
785 renderer()->updateFromElement();
788 void HTMLMediaElement::mediaEngineError(PassRefPtr<MediaError> err)
790 LOG(Media, "HTMLMediaElement::mediaEngineError(%d)", static_cast<int>(err->code()));
792 // 1 - The user agent should cancel the fetching process.
793 stopPeriodicTimers();
794 m_loadState = WaitingForSource;
796 // 2 - Set the error attribute to a new MediaError object whose code attribute is
797 // set to MEDIA_ERR_NETWORK/MEDIA_ERR_DECODE.
800 // 3 - Queue a task to fire a simple event named error at the media element.
801 scheduleEvent(eventNames().errorEvent);
803 // 4 - Set the element's networkState attribute to the NETWORK_EMPTY value and queue a
804 // task to fire a simple event called emptied at the element.
805 m_networkState = NETWORK_EMPTY;
806 scheduleEvent(eventNames().emptiedEvent);
808 // 5 - Set the element's delaying-the-load-event flag to false. This stops delaying the load event.
809 setShouldDelayLoadEvent(false);
811 // 6 - Abort the overall resource selection algorithm.
812 m_currentSourceNode = 0;
815 void HTMLMediaElement::cancelPendingEventsAndCallbacks()
817 LOG(Media, "HTMLMediaElement::cancelPendingEventsAndCallbacks");
819 m_pendingEvents.clear();
821 for (Node* node = firstChild(); node; node = node->nextSibling()) {
822 if (node->hasTagName(sourceTag))
823 static_cast<HTMLSourceElement*>(node)->cancelPendingErrorEvent();
827 Document* HTMLMediaElement::mediaPlayerOwningDocument()
829 Document* d = document();
837 void HTMLMediaElement::mediaPlayerNetworkStateChanged(MediaPlayer*)
839 beginProcessingMediaPlayerCallback();
840 setNetworkState(m_player->networkState());
841 endProcessingMediaPlayerCallback();
844 void HTMLMediaElement::setNetworkState(MediaPlayer::NetworkState state)
846 LOG(Media, "HTMLMediaElement::setNetworkState(%d) - current state is %d", static_cast<int>(state), static_cast<int>(m_networkState));
848 if (state == MediaPlayer::Empty) {
849 // Just update the cached state and leave, we can't do anything.
850 m_networkState = NETWORK_EMPTY;
854 if (state == MediaPlayer::FormatError || state == MediaPlayer::NetworkError || state == MediaPlayer::DecodeError) {
855 stopPeriodicTimers();
857 // If we failed while trying to load a <source> element, the movie was never parsed, and there are more
858 // <source> children, schedule the next one
859 if (m_readyState < HAVE_METADATA && m_loadState == LoadingFromSourceElement) {
861 if (m_currentSourceNode)
862 m_currentSourceNode->scheduleErrorEvent();
864 LOG(Media, "HTMLMediaElement::setNetworkState - error event not sent, <source> was removed");
866 if (havePotentialSourceChild()) {
867 LOG(Media, "HTMLMediaElement::setNetworkState - scheduling next <source>");
868 scheduleNextSourceChild();
870 LOG(Media, "HTMLMediaElement::setNetworkState - no more <source> elements, waiting");
871 waitForSourceChange();
877 if (state == MediaPlayer::NetworkError)
878 mediaEngineError(MediaError::create(MediaError::MEDIA_ERR_NETWORK));
879 else if (state == MediaPlayer::DecodeError)
880 mediaEngineError(MediaError::create(MediaError::MEDIA_ERR_DECODE));
881 else if (state == MediaPlayer::FormatError && m_loadState == LoadingFromSrcAttr)
884 updateDisplayState();
888 if (state == MediaPlayer::Idle) {
889 if (m_networkState > NETWORK_IDLE) {
890 m_progressEventTimer.stop();
891 scheduleEvent(eventNames().suspendEvent);
893 m_networkState = NETWORK_IDLE;
896 if (state == MediaPlayer::Loading) {
897 if (m_networkState < NETWORK_LOADING || m_networkState == NETWORK_NO_SOURCE)
898 startProgressEventTimer();
899 m_networkState = NETWORK_LOADING;
902 if (state == MediaPlayer::Loaded) {
903 if (m_networkState != NETWORK_IDLE) {
904 m_progressEventTimer.stop();
906 // Schedule one last progress event so we guarantee that at least one is fired
907 // for files that load very quickly.
908 scheduleEvent(eventNames().progressEvent);
910 m_networkState = NETWORK_IDLE;
911 m_completelyLoaded = true;
915 void HTMLMediaElement::mediaPlayerReadyStateChanged(MediaPlayer*)
917 beginProcessingMediaPlayerCallback();
919 setReadyState(m_player->readyState());
921 endProcessingMediaPlayerCallback();
924 void HTMLMediaElement::setReadyState(MediaPlayer::ReadyState state)
926 LOG(Media, "HTMLMediaElement::setReadyState(%d) - current state is %d,", static_cast<int>(state), static_cast<int>(m_readyState));
928 // Set "wasPotentiallyPlaying" BEFORE updating m_readyState, potentiallyPlaying() uses it
929 bool wasPotentiallyPlaying = potentiallyPlaying();
931 ReadyState oldState = m_readyState;
932 m_readyState = static_cast<ReadyState>(state);
934 if (m_readyState == oldState)
937 if (oldState > m_readyStateMaximum)
938 m_readyStateMaximum = oldState;
940 if (m_networkState == NETWORK_EMPTY)
945 if (wasPotentiallyPlaying && m_readyState < HAVE_FUTURE_DATA)
946 scheduleEvent(eventNames().waitingEvent);
948 // 4.8.10.10 step 14 & 15.
949 if (m_readyState >= HAVE_CURRENT_DATA)
952 if (wasPotentiallyPlaying && m_readyState < HAVE_FUTURE_DATA) {
954 scheduleTimeupdateEvent(false);
955 scheduleEvent(eventNames().waitingEvent);
959 if (m_readyState >= HAVE_METADATA && oldState < HAVE_METADATA) {
960 scheduleEvent(eventNames().durationchangeEvent);
961 scheduleEvent(eventNames().loadedmetadataEvent);
963 renderer()->updateFromElement();
967 bool shouldUpdateDisplayState = false;
969 if (m_readyState >= HAVE_CURRENT_DATA && oldState < HAVE_CURRENT_DATA && !m_haveFiredLoadedData) {
970 m_haveFiredLoadedData = true;
971 shouldUpdateDisplayState = true;
972 scheduleEvent(eventNames().loadeddataEvent);
973 setShouldDelayLoadEvent(false);
976 bool isPotentiallyPlaying = potentiallyPlaying();
977 if (m_readyState == HAVE_FUTURE_DATA && oldState <= HAVE_CURRENT_DATA) {
978 scheduleEvent(eventNames().canplayEvent);
979 if (isPotentiallyPlaying)
980 scheduleEvent(eventNames().playingEvent);
981 shouldUpdateDisplayState = true;
984 if (m_readyState == HAVE_ENOUGH_DATA && oldState < HAVE_ENOUGH_DATA) {
985 if (oldState <= HAVE_CURRENT_DATA)
986 scheduleEvent(eventNames().canplayEvent);
988 scheduleEvent(eventNames().canplaythroughEvent);
990 if (isPotentiallyPlaying && oldState <= HAVE_CURRENT_DATA)
991 scheduleEvent(eventNames().playingEvent);
993 if (m_autoplaying && m_paused && autoplay()) {
995 invalidateCachedTime();
996 scheduleEvent(eventNames().playEvent);
997 scheduleEvent(eventNames().playingEvent);
1000 shouldUpdateDisplayState = true;
1003 if (shouldUpdateDisplayState)
1004 updateDisplayState();
1009 void HTMLMediaElement::progressEventTimerFired(Timer<HTMLMediaElement>*)
1012 if (m_networkState != NETWORK_LOADING)
1015 unsigned progress = m_player->bytesLoaded();
1016 double time = WTF::currentTime();
1017 double timedelta = time - m_previousProgressTime;
1019 if (progress == m_previousProgress) {
1020 if (timedelta > 3.0 && !m_sentStalledEvent) {
1021 scheduleEvent(eventNames().stalledEvent);
1022 m_sentStalledEvent = true;
1025 scheduleEvent(eventNames().progressEvent);
1026 m_previousProgress = progress;
1027 m_previousProgressTime = time;
1028 m_sentStalledEvent = false;
1030 renderer()->updateFromElement();
1034 void HTMLMediaElement::rewind(float timeDelta)
1036 LOG(Media, "HTMLMediaElement::rewind(%f)", timeDelta);
1039 setCurrentTime(max(currentTime() - timeDelta, minTimeSeekable()), e);
1042 void HTMLMediaElement::returnToRealtime()
1044 LOG(Media, "HTMLMediaElement::returnToRealtime");
1046 setCurrentTime(maxTimeSeekable(), e);
1049 void HTMLMediaElement::addPlayedRange(float start, float end)
1051 LOG(Media, "HTMLMediaElement::addPlayedRange(%f, %f)", start, end);
1052 if (!m_playedTimeRanges)
1053 m_playedTimeRanges = TimeRanges::create();
1054 m_playedTimeRanges->add(start, end);
1057 bool HTMLMediaElement::supportsSave() const
1059 return m_player ? m_player->supportsSave() : false;
1062 void HTMLMediaElement::seek(float time, ExceptionCode& ec)
1064 LOG(Media, "HTMLMediaElement::seek(%f)", time);
1068 // 1 - If the media element's readyState is HAVE_NOTHING, then raise an INVALID_STATE_ERR exception.
1069 if (m_readyState == HAVE_NOTHING || !m_player) {
1070 ec = INVALID_STATE_ERR;
1074 // Get the current time before setting m_seeking, m_lastSeekTime is returned once it is set.
1075 refreshCachedTime();
1076 float now = currentTime();
1078 // 2 - If the element's seeking IDL attribute is true, then another instance of this algorithm is
1079 // already running. Abort that other instance of the algorithm without waiting for the step that
1080 // it is running to complete.
1081 // Nothing specific to be done here.
1083 // 3 - Set the seeking IDL attribute to true.
1084 // The flag will be cleared when the engine tells us the time has actually changed.
1087 // 5 - If the new playback position is later than the end of the media resource, then let it be the end
1088 // of the media resource instead.
1089 time = min(time, duration());
1091 // 6 - If the new playback position is less than the earliest possible position, let it be that position instead.
1092 float earliestTime = m_player->startTime();
1093 time = max(time, earliestTime);
1095 // Ask the media engine for the time value in the movie's time scale before comparing with current time. This
1096 // is necessary because if the seek time is not equal to currentTime but the delta is less than the movie's
1097 // time scale, we will ask the media engine to "seek" to the current movie time, which may be a noop and
1098 // not generate a timechanged callback. This means m_seeking will never be cleared and we will never
1099 // fire a 'seeked' event.
1101 float mediaTime = m_player->mediaTimeForTimeValue(time);
1102 if (time != mediaTime)
1103 LOG(Media, "HTMLMediaElement::seek(%f) - media timeline equivalent is %f", time, mediaTime);
1105 time = m_player->mediaTimeForTimeValue(time);
1107 // 7 - If the (possibly now changed) new playback position is not in one of the ranges given in the
1108 // seekable attribute, then let it be the position in one of the ranges given in the seekable attribute
1109 // that is the nearest to the new playback position. ... If there are no ranges given in the seekable
1110 // attribute then set the seeking IDL attribute to false and abort these steps.
1111 RefPtr<TimeRanges> seekableRanges = seekable();
1113 // Short circuit seeking to the current time by just firing the events if no seek is required.
1114 // Don't skip calling the media engine if we are in poster mode because a seek should always
1115 // cancel poster display.
1116 bool noSeekRequired = !seekableRanges->length() || (time == now && displayMode() != Poster);
1117 if (noSeekRequired) {
1119 scheduleEvent(eventNames().seekingEvent);
1120 scheduleTimeupdateEvent(false);
1121 scheduleEvent(eventNames().seekedEvent);
1126 time = seekableRanges->nearest(time);
1129 if (m_lastSeekTime < now)
1130 addPlayedRange(m_lastSeekTime, now);
1132 m_lastSeekTime = time;
1133 m_sentEndEvent = false;
1135 // 8 - Set the current playback position to the given new playback position
1136 m_player->seek(time);
1138 // 9 - Queue a task to fire a simple event named seeking at the element.
1139 scheduleEvent(eventNames().seekingEvent);
1141 // 10 - Queue a task to fire a simple event named timeupdate at the element.
1142 scheduleTimeupdateEvent(false);
1144 // 11-15 are handled, if necessary, when the engine signals a readystate change.
1147 void HTMLMediaElement::finishSeek()
1149 LOG(Media, "HTMLMediaElement::finishSeek");
1151 // 4.8.10.9 Seeking step 14
1154 // 4.8.10.9 Seeking step 15
1155 scheduleEvent(eventNames().seekedEvent);
1157 setDisplayMode(Video);
1160 HTMLMediaElement::ReadyState HTMLMediaElement::readyState() const
1162 return m_readyState;
1165 MediaPlayer::MovieLoadType HTMLMediaElement::movieLoadType() const
1167 return m_player ? m_player->movieLoadType() : MediaPlayer::Unknown;
1170 bool HTMLMediaElement::hasAudio() const
1172 return m_player ? m_player->hasAudio() : false;
1175 bool HTMLMediaElement::seeking() const
1180 void HTMLMediaElement::refreshCachedTime() const
1182 m_cachedTime = m_player->currentTime();
1183 m_cachedTimeWallClockUpdateTime = WTF::currentTime();
1186 void HTMLMediaElement::invalidateCachedTime()
1188 LOG(Media, "HTMLMediaElement::invalidateCachedTime");
1190 // Don't try to cache movie time when playback first starts as the time reported by the engine
1191 // sometimes fluctuates for a short amount of time, so the cached time will be off if we take it
1193 static const double minimumTimePlayingBeforeCacheSnapshot = 0.5;
1195 m_minimumWallClockTimeToCacheMediaTime = WTF::currentTime() + minimumTimePlayingBeforeCacheSnapshot;
1196 m_cachedTime = invalidMediaTime;
1200 float HTMLMediaElement::currentTime() const
1202 #if LOG_CACHED_TIME_WARNINGS
1203 static const double minCachedDeltaForWarning = 0.01;
1210 LOG(Media, "HTMLMediaElement::currentTime - seeking, returning %f", m_lastSeekTime);
1211 return m_lastSeekTime;
1214 if (m_cachedTime != invalidMediaTime && m_paused) {
1215 #if LOG_CACHED_TIME_WARNINGS
1216 float delta = m_cachedTime - m_player->currentTime();
1217 if (delta > minCachedDeltaForWarning)
1218 LOG(Media, "HTMLMediaElement::currentTime - WARNING, cached time is %f seconds off of media time when paused", delta);
1220 return m_cachedTime;
1223 // Is it too soon use a cached time?
1224 double now = WTF::currentTime();
1225 double maximumDurationToCacheMediaTime = m_player->maximumDurationToCacheMediaTime();
1227 if (maximumDurationToCacheMediaTime && m_cachedTime != invalidMediaTime && !m_paused && now > m_minimumWallClockTimeToCacheMediaTime) {
1228 double wallClockDelta = now - m_cachedTimeWallClockUpdateTime;
1230 // Not too soon, use the cached time only if it hasn't expired.
1231 if (wallClockDelta < maximumDurationToCacheMediaTime) {
1232 float adjustedCacheTime = static_cast<float>(m_cachedTime + (m_playbackRate * wallClockDelta));
1234 #if LOG_CACHED_TIME_WARNINGS
1235 float delta = adjustedCacheTime - m_player->currentTime();
1236 if (delta > minCachedDeltaForWarning)
1237 LOG(Media, "HTMLMediaElement::currentTime - WARNING, cached time is %f seconds off of media time when playing", delta);
1239 return adjustedCacheTime;
1243 #if LOG_CACHED_TIME_WARNINGS
1244 if (maximumDurationToCacheMediaTime && now > m_minimumWallClockTimeToCacheMediaTime && m_cachedTime != invalidMediaTime) {
1245 double wallClockDelta = now - m_cachedTimeWallClockUpdateTime;
1246 float delta = m_cachedTime + (m_playbackRate * wallClockDelta) - m_player->currentTime();
1247 LOG(Media, "HTMLMediaElement::currentTime - cached time was %f seconds off of media time when it expired", delta);
1251 refreshCachedTime();
1253 return m_cachedTime;
1256 void HTMLMediaElement::setCurrentTime(float time, ExceptionCode& ec)
1261 float HTMLMediaElement::startTime() const
1265 return m_player->startTime();
1268 float HTMLMediaElement::duration() const
1270 if (m_player && m_readyState >= HAVE_METADATA)
1271 return m_player->duration();
1273 return numeric_limits<float>::quiet_NaN();
1276 bool HTMLMediaElement::paused() const
1281 float HTMLMediaElement::defaultPlaybackRate() const
1283 return m_defaultPlaybackRate;
1286 void HTMLMediaElement::setDefaultPlaybackRate(float rate)
1288 if (m_defaultPlaybackRate != rate) {
1289 m_defaultPlaybackRate = rate;
1290 scheduleEvent(eventNames().ratechangeEvent);
1294 float HTMLMediaElement::playbackRate() const
1296 return m_player ? m_player->rate() : 0;
1299 void HTMLMediaElement::setPlaybackRate(float rate)
1301 LOG(Media, "HTMLMediaElement::setPlaybackRate(%f)", rate);
1303 if (m_playbackRate != rate) {
1304 m_playbackRate = rate;
1305 invalidateCachedTime();
1306 scheduleEvent(eventNames().ratechangeEvent);
1308 if (m_player && potentiallyPlaying() && m_player->rate() != rate)
1309 m_player->setRate(rate);
1312 bool HTMLMediaElement::webkitPreservesPitch() const
1314 return m_webkitPreservesPitch;
1317 void HTMLMediaElement::setWebkitPreservesPitch(bool preservesPitch)
1319 LOG(Media, "HTMLMediaElement::setWebkitPreservesPitch(%s)", boolString(preservesPitch));
1321 m_webkitPreservesPitch = preservesPitch;
1326 m_player->setPreservesPitch(preservesPitch);
1329 bool HTMLMediaElement::ended() const
1331 // 4.8.10.8 Playing the media resource
1332 // The ended attribute must return true if the media element has ended
1333 // playback and the direction of playback is forwards, and false otherwise.
1334 return endedPlayback() && m_playbackRate > 0;
1337 bool HTMLMediaElement::autoplay() const
1339 return hasAttribute(autoplayAttr);
1342 void HTMLMediaElement::setAutoplay(bool b)
1344 LOG(Media, "HTMLMediaElement::setAutoplay(%s)", boolString(b));
1345 setBooleanAttribute(autoplayAttr, b);
1348 String HTMLMediaElement::preload() const
1350 switch (m_preload) {
1351 case MediaPlayer::None:
1354 case MediaPlayer::MetaData:
1357 case MediaPlayer::Auto:
1362 ASSERT_NOT_REACHED();
1366 void HTMLMediaElement::setPreload(const String& preload)
1368 LOG(Media, "HTMLMediaElement::setPreload(%s)", preload.utf8().data());
1369 setAttribute(preloadAttr, preload);
1372 void HTMLMediaElement::play(bool isUserGesture)
1374 LOG(Media, "HTMLMediaElement::play(isUserGesture : %s)", boolString(isUserGesture));
1376 if (m_restrictions & RequireUserGestureForRateChangeRestriction && !isUserGesture)
1379 Document* doc = document();
1380 Settings* settings = doc->settings();
1381 if (settings && settings->needsSiteSpecificQuirks() && m_dispatchingCanPlayEvent && !m_loadInitiatedByUserGesture) {
1382 // It should be impossible to be processing the canplay event while handling a user gesture
1383 // since it is dispatched asynchronously.
1384 ASSERT(!isUserGesture);
1385 String host = doc->baseURL().host();
1386 if (host.endsWith(".npr.org", false) || equalIgnoringCase(host, "npr.org"))
1393 void HTMLMediaElement::playInternal()
1395 LOG(Media, "HTMLMediaElement::playInternal");
1397 // 4.8.10.9. Playing the media resource
1398 if (!m_player || m_networkState == NETWORK_EMPTY)
1401 if (endedPlayback()) {
1402 ExceptionCode unused;
1406 setPlaybackRate(defaultPlaybackRate());
1410 invalidateCachedTime();
1411 scheduleEvent(eventNames().playEvent);
1413 if (m_readyState <= HAVE_CURRENT_DATA)
1414 scheduleEvent(eventNames().waitingEvent);
1415 else if (m_readyState >= HAVE_FUTURE_DATA)
1416 scheduleEvent(eventNames().playingEvent);
1418 m_autoplaying = false;
1423 void HTMLMediaElement::pause(bool isUserGesture)
1425 LOG(Media, "HTMLMediaElement::pause(isUserGesture : %s)", boolString(isUserGesture));
1427 if (m_restrictions & RequireUserGestureForRateChangeRestriction && !isUserGesture)
1434 void HTMLMediaElement::pauseInternal()
1436 LOG(Media, "HTMLMediaElement::pauseInternal");
1438 // 4.8.10.9. Playing the media resource
1439 if (!m_player || m_networkState == NETWORK_EMPTY)
1442 m_autoplaying = false;
1446 scheduleTimeupdateEvent(false);
1447 scheduleEvent(eventNames().pauseEvent);
1453 bool HTMLMediaElement::loop() const
1455 return hasAttribute(loopAttr);
1458 void HTMLMediaElement::setLoop(bool b)
1460 LOG(Media, "HTMLMediaElement::setLoop(%s)", boolString(b));
1461 setBooleanAttribute(loopAttr, b);
1464 bool HTMLMediaElement::controls() const
1466 Frame* frame = document()->frame();
1468 // always show controls when scripting is disabled
1469 if (frame && !frame->script()->canExecuteScripts(NotAboutToExecuteScript))
1472 return hasAttribute(controlsAttr);
1475 void HTMLMediaElement::setControls(bool b)
1477 LOG(Media, "HTMLMediaElement::setControls(%s)", boolString(b));
1478 setBooleanAttribute(controlsAttr, b);
1481 float HTMLMediaElement::volume() const
1486 void HTMLMediaElement::setVolume(float vol, ExceptionCode& ec)
1488 LOG(Media, "HTMLMediaElement::setVolume(%f)", vol);
1490 if (vol < 0.0f || vol > 1.0f) {
1491 ec = INDEX_SIZE_ERR;
1495 if (m_volume != vol) {
1498 scheduleEvent(eventNames().volumechangeEvent);
1502 bool HTMLMediaElement::muted() const
1507 void HTMLMediaElement::setMuted(bool muted)
1509 LOG(Media, "HTMLMediaElement::setMuted(%s)", boolString(muted));
1511 if (m_muted != muted) {
1513 // Avoid recursion when the player reports volume changes.
1514 if (!processingMediaPlayerCallback()) {
1516 m_player->setMuted(m_muted);
1518 renderer()->updateFromElement();
1522 scheduleEvent(eventNames().volumechangeEvent);
1526 void HTMLMediaElement::togglePlayState()
1528 LOG(Media, "HTMLMediaElement::togglePlayState - canPlay() is %s", boolString(canPlay()));
1530 // We can safely call the internal play/pause methods, which don't check restrictions, because
1531 // this method is only called from the built-in media controller
1538 void HTMLMediaElement::beginScrubbing()
1540 LOG(Media, "HTMLMediaElement::beginScrubbing - paused() is %s", boolString(paused()));
1544 // Because a media element stays in non-paused state when it reaches end, playback resumes
1545 // when the slider is dragged from the end to another position unless we pause first. Do
1546 // a "hard pause" so an event is generated, since we want to stay paused after scrubbing finishes.
1547 pause(processingUserGesture());
1549 // Not at the end but we still want to pause playback so the media engine doesn't try to
1550 // continue playing during scrubbing. Pause without generating an event as we will
1551 // unpause after scrubbing finishes.
1552 setPausedInternal(true);
1557 void HTMLMediaElement::endScrubbing()
1559 LOG(Media, "HTMLMediaElement::endScrubbing - m_pausedInternal is %s", boolString(m_pausedInternal));
1561 if (m_pausedInternal)
1562 setPausedInternal(false);
1565 // The spec says to fire periodic timeupdate events (those sent while playing) every
1566 // "15 to 250ms", we choose the slowest frequency
1567 static const double maxTimeupdateEventFrequency = 0.25;
1569 void HTMLMediaElement::startPlaybackProgressTimer()
1571 if (m_playbackProgressTimer.isActive())
1574 m_previousProgressTime = WTF::currentTime();
1575 m_previousProgress = 0;
1576 m_playbackProgressTimer.startRepeating(maxTimeupdateEventFrequency);
1579 void HTMLMediaElement::playbackProgressTimerFired(Timer<HTMLMediaElement>*)
1582 if (!m_playbackRate)
1585 scheduleTimeupdateEvent(true);
1587 // FIXME: deal with cue ranges here
1590 void HTMLMediaElement::scheduleTimeupdateEvent(bool periodicEvent)
1592 double now = WTF::currentTime();
1593 double timedelta = now - m_lastTimeUpdateEventWallTime;
1595 // throttle the periodic events
1596 if (periodicEvent && timedelta < maxTimeupdateEventFrequency)
1599 // Some media engines make multiple "time changed" callbacks at the same time, but we only want one
1600 // event at a given time so filter here
1601 float movieTime = currentTime();
1602 if (movieTime != m_lastTimeUpdateEventMovieTime) {
1603 scheduleEvent(eventNames().timeupdateEvent);
1604 m_lastTimeUpdateEventWallTime = now;
1605 m_lastTimeUpdateEventMovieTime = movieTime;
1609 bool HTMLMediaElement::canPlay() const
1611 return paused() || ended() || m_readyState < HAVE_METADATA;
1614 float HTMLMediaElement::percentLoaded() const
1618 float duration = m_player->duration();
1620 if (!duration || isinf(duration))
1624 RefPtr<TimeRanges> timeRanges = m_player->buffered();
1625 for (unsigned i = 0; i < timeRanges->length(); ++i) {
1626 ExceptionCode ignoredException;
1627 float start = timeRanges->start(i, ignoredException);
1628 float end = timeRanges->end(i, ignoredException);
1629 buffered += end - start;
1631 return buffered / duration;
1634 bool HTMLMediaElement::havePotentialSourceChild()
1636 // Stash the current <source> node and next nodes so we can restore them after checking
1637 // to see there is another potential.
1638 HTMLSourceElement* currentSourceNode = m_currentSourceNode;
1639 Node* nextNode = m_nextChildNodeToConsider;
1641 KURL nextURL = selectNextSourceChild(0, DoNothing);
1643 m_currentSourceNode = currentSourceNode;
1644 m_nextChildNodeToConsider = nextNode;
1646 return nextURL.isValid();
1649 KURL HTMLMediaElement::selectNextSourceChild(ContentType *contentType, InvalidSourceAction actionIfInvalid)
1652 // Don't log if this was just called to find out if there are any valid <source> elements.
1653 bool shouldLog = actionIfInvalid != DoNothing;
1655 LOG(Media, "HTMLMediaElement::selectNextSourceChild(contentType : \"%s\")", contentType ? contentType->raw().utf8().data() : "");
1658 if (m_nextChildNodeToConsider == sourceChildEndOfListValue()) {
1661 LOG(Media, "HTMLMediaElement::selectNextSourceChild -> 0x0000, \"\"");
1668 HTMLSourceElement* source = 0;
1669 bool lookingForStartNode = m_nextChildNodeToConsider;
1670 bool canUse = false;
1672 for (node = firstChild(); !canUse && node; node = node->nextSibling()) {
1673 if (lookingForStartNode && m_nextChildNodeToConsider != node)
1675 lookingForStartNode = false;
1677 if (!node->hasTagName(sourceTag))
1680 source = static_cast<HTMLSourceElement*>(node);
1682 // 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
1683 mediaURL = source->getNonEmptyURLAttribute(srcAttr);
1686 LOG(Media, "HTMLMediaElement::selectNextSourceChild - 'src' is %s", urlForLogging(mediaURL).utf8().data());
1688 if (mediaURL.isEmpty())
1691 if (source->hasAttribute(mediaAttr)) {
1692 MediaQueryEvaluator screenEval("screen", document()->frame(), renderer() ? renderer()->style() : 0);
1693 RefPtr<MediaList> media = MediaList::createAllowingDescriptionSyntax(source->media());
1696 LOG(Media, "HTMLMediaElement::selectNextSourceChild - 'media' is %s", source->media().utf8().data());
1698 if (!screenEval.eval(media.get()))
1702 if (source->hasAttribute(typeAttr)) {
1705 LOG(Media, "HTMLMediaElement::selectNextSourceChild - 'type' is %s", source->type().utf8().data());
1707 if (!MediaPlayer::supportsType(ContentType(source->type())))
1711 // Is it safe to load this url?
1712 if (!isSafeToLoadURL(mediaURL, actionIfInvalid) || !dispatchBeforeLoadEvent(mediaURL.string()))
1715 // Making it this far means the <source> looks reasonable.
1719 if (!canUse && actionIfInvalid == Complain)
1720 source->scheduleErrorEvent();
1725 *contentType = ContentType(source->type());
1726 m_currentSourceNode = source;
1727 m_nextChildNodeToConsider = source->nextSibling();
1728 if (!m_nextChildNodeToConsider)
1729 m_nextChildNodeToConsider = sourceChildEndOfListValue();
1731 m_currentSourceNode = 0;
1732 m_nextChildNodeToConsider = sourceChildEndOfListValue();
1737 LOG(Media, "HTMLMediaElement::selectNextSourceChild -> %p, %s", m_currentSourceNode, canUse ? urlForLogging(mediaURL.string()).utf8().data() : "");
1739 return canUse ? mediaURL : KURL();
1742 void HTMLMediaElement::sourceWasAdded(HTMLSourceElement* source)
1744 LOG(Media, "HTMLMediaElement::sourceWasAdded(%p)", source);
1747 if (source->hasTagName(sourceTag)) {
1748 KURL url = source->getNonEmptyURLAttribute(srcAttr);
1749 LOG(Media, "HTMLMediaElement::sourceWasAdded - 'src' is %s", urlForLogging(url).utf8().data());
1753 // We should only consider a <source> element when there is not src attribute at all.
1754 if (hasAttribute(srcAttr))
1757 // 4.8.8 - If a source element is inserted as a child of a media element that has no src
1758 // attribute and whose networkState has the value NETWORK_EMPTY, the user agent must invoke
1759 // the media element's resource selection algorithm.
1760 if (networkState() == HTMLMediaElement::NETWORK_EMPTY) {
1765 if (m_currentSourceNode && source == m_currentSourceNode->nextSibling()) {
1766 LOG(Media, "HTMLMediaElement::sourceWasAdded - <source> inserted immediately after current source");
1767 m_nextChildNodeToConsider = source;
1771 if (m_nextChildNodeToConsider != sourceChildEndOfListValue())
1774 // 4.8.9.5, resource selection algorithm, source elements section:
1775 // 20 - Wait until the node after pointer is a node other than the end of the list. (This step might wait forever.)
1776 // 21 - Asynchronously await a stable state...
1777 // 22 - Set the element's delaying-the-load-event flag back to true (this delays the load event again, in case
1778 // it hasn't been fired yet).
1779 setShouldDelayLoadEvent(true);
1781 // 23 - Set the networkState back to NETWORK_LOADING.
1782 m_networkState = NETWORK_LOADING;
1784 // 24 - Jump back to the find next candidate step above.
1785 m_nextChildNodeToConsider = source;
1786 scheduleNextSourceChild();
1789 void HTMLMediaElement::sourceWillBeRemoved(HTMLSourceElement* source)
1791 LOG(Media, "HTMLMediaElement::sourceWillBeRemoved(%p)", source);
1794 if (source->hasTagName(sourceTag)) {
1795 KURL url = source->getNonEmptyURLAttribute(srcAttr);
1796 LOG(Media, "HTMLMediaElement::sourceWillBeRemoved - 'src' is %s", urlForLogging(url).utf8().data());
1800 if (source != m_currentSourceNode && source != m_nextChildNodeToConsider)
1803 if (source == m_nextChildNodeToConsider) {
1804 m_nextChildNodeToConsider = m_nextChildNodeToConsider->nextSibling();
1805 if (!m_nextChildNodeToConsider)
1806 m_nextChildNodeToConsider = sourceChildEndOfListValue();
1807 LOG(Media, "HTMLMediaElement::sourceRemoved - m_nextChildNodeToConsider set to %p", m_nextChildNodeToConsider);
1808 } else if (source == m_currentSourceNode) {
1809 // Clear the current source node pointer, but don't change the movie as the spec says:
1810 // 4.8.8 - Dynamically modifying a source element and its attribute when the element is already
1811 // inserted in a video or audio element will have no effect.
1812 m_currentSourceNode = 0;
1813 LOG(Media, "HTMLMediaElement::sourceRemoved - m_currentSourceNode set to 0");
1817 void HTMLMediaElement::mediaPlayerTimeChanged(MediaPlayer*)
1819 LOG(Media, "HTMLMediaElement::mediaPlayerTimeChanged");
1821 beginProcessingMediaPlayerCallback();
1823 invalidateCachedTime();
1825 // 4.8.10.9 step 14 & 15. Needed if no ReadyState change is associated with the seek.
1826 if (m_seeking && m_readyState >= HAVE_CURRENT_DATA)
1829 // Always call scheduleTimeupdateEvent when the media engine reports a time discontinuity,
1830 // it will only queue a 'timeupdate' event if we haven't already posted one at the current
1832 scheduleTimeupdateEvent(false);
1834 float now = currentTime();
1835 float dur = duration();
1836 if (!isnan(dur) && dur && now >= dur) {
1838 ExceptionCode ignoredException;
1839 m_sentEndEvent = false;
1840 seek(0, ignoredException);
1842 if (!m_sentEndEvent) {
1843 m_sentEndEvent = true;
1844 scheduleEvent(eventNames().endedEvent);
1849 m_sentEndEvent = false;
1852 endProcessingMediaPlayerCallback();
1855 void HTMLMediaElement::mediaPlayerVolumeChanged(MediaPlayer*)
1857 LOG(Media, "HTMLMediaElement::mediaPlayerVolumeChanged");
1859 beginProcessingMediaPlayerCallback();
1861 m_volume = m_player->volume();
1863 endProcessingMediaPlayerCallback();
1866 void HTMLMediaElement::mediaPlayerMuteChanged(MediaPlayer*)
1868 LOG(Media, "HTMLMediaElement::mediaPlayerMuteChanged");
1870 beginProcessingMediaPlayerCallback();
1872 setMuted(m_player->muted());
1873 endProcessingMediaPlayerCallback();
1876 void HTMLMediaElement::mediaPlayerDurationChanged(MediaPlayer*)
1878 LOG(Media, "HTMLMediaElement::mediaPlayerDurationChanged");
1880 beginProcessingMediaPlayerCallback();
1881 scheduleEvent(eventNames().durationchangeEvent);
1883 renderer()->updateFromElement();
1884 endProcessingMediaPlayerCallback();
1887 void HTMLMediaElement::mediaPlayerRateChanged(MediaPlayer*)
1889 LOG(Media, "HTMLMediaElement::mediaPlayerRateChanged");
1891 beginProcessingMediaPlayerCallback();
1893 invalidateCachedTime();
1895 // Stash the rate in case the one we tried to set isn't what the engine is
1896 // using (eg. it can't handle the rate we set)
1897 m_playbackRate = m_player->rate();
1898 invalidateCachedTime();
1899 endProcessingMediaPlayerCallback();
1902 void HTMLMediaElement::mediaPlayerPlaybackStateChanged(MediaPlayer*)
1904 LOG(Media, "HTMLMediaElement::mediaPlayerPlaybackStateChanged");
1909 beginProcessingMediaPlayerCallback();
1910 if (m_player->paused())
1914 endProcessingMediaPlayerCallback();
1917 void HTMLMediaElement::mediaPlayerSawUnsupportedTracks(MediaPlayer*)
1919 LOG(Media, "HTMLMediaElement::mediaPlayerSawUnsupportedTracks");
1921 // The MediaPlayer came across content it cannot completely handle.
1922 // This is normally acceptable except when we are in a standalone
1923 // MediaDocument. If so, tell the document what has happened.
1924 if (ownerDocument()->isMediaDocument()) {
1925 MediaDocument* mediaDocument = static_cast<MediaDocument*>(ownerDocument());
1926 mediaDocument->mediaElementSawUnsupportedTracks();
1930 // MediaPlayerPresentation methods
1931 void HTMLMediaElement::mediaPlayerRepaint(MediaPlayer*)
1933 beginProcessingMediaPlayerCallback();
1934 updateDisplayState();
1936 renderer()->repaint();
1937 endProcessingMediaPlayerCallback();
1940 void HTMLMediaElement::mediaPlayerSizeChanged(MediaPlayer*)
1942 LOG(Media, "HTMLMediaElement::mediaPlayerSizeChanged");
1944 beginProcessingMediaPlayerCallback();
1946 renderer()->updateFromElement();
1947 endProcessingMediaPlayerCallback();
1950 #if USE(ACCELERATED_COMPOSITING)
1951 bool HTMLMediaElement::mediaPlayerRenderingCanBeAccelerated(MediaPlayer*)
1953 if (renderer() && renderer()->isVideo()) {
1954 ASSERT(renderer()->view());
1955 return renderer()->view()->compositor()->canAccelerateVideoRendering(toRenderVideo(renderer()));
1960 void HTMLMediaElement::mediaPlayerRenderingModeChanged(MediaPlayer*)
1962 LOG(Media, "HTMLMediaElement::mediaPlayerRenderingModeChanged");
1964 // Kick off a fake recalcStyle that will update the compositing tree.
1965 setNeedsStyleRecalc(SyntheticStyleChange);
1969 void HTMLMediaElement::mediaPlayerEngineUpdated(MediaPlayer*)
1971 beginProcessingMediaPlayerCallback();
1972 LOG(Media, "HTMLMediaElement::mediaPlayerEngineUpdated");
1974 renderer()->updateFromElement();
1975 endProcessingMediaPlayerCallback();
1978 PassRefPtr<TimeRanges> HTMLMediaElement::buffered() const
1981 return TimeRanges::create();
1982 return m_player->buffered();
1985 PassRefPtr<TimeRanges> HTMLMediaElement::played()
1988 float time = currentTime();
1989 if (time > m_lastSeekTime)
1990 addPlayedRange(m_lastSeekTime, time);
1993 if (!m_playedTimeRanges)
1994 m_playedTimeRanges = TimeRanges::create();
1996 return m_playedTimeRanges->copy();
1999 PassRefPtr<TimeRanges> HTMLMediaElement::seekable() const
2001 // FIXME real ranges support
2002 if (!maxTimeSeekable())
2003 return TimeRanges::create();
2004 return TimeRanges::create(minTimeSeekable(), maxTimeSeekable());
2007 bool HTMLMediaElement::potentiallyPlaying() const
2009 // "pausedToBuffer" means the media engine's rate is 0, but only because it had to stop playing
2010 // when it ran out of buffered data. A movie is this state is "potentially playing", modulo the
2011 // checks in couldPlayIfEnoughData().
2012 bool pausedToBuffer = m_readyStateMaximum >= HAVE_FUTURE_DATA && m_readyState < HAVE_FUTURE_DATA;
2013 return (pausedToBuffer || m_readyState >= HAVE_FUTURE_DATA) && couldPlayIfEnoughData();
2016 bool HTMLMediaElement::couldPlayIfEnoughData() const
2018 return !paused() && !endedPlayback() && !stoppedDueToErrors() && !pausedForUserInteraction();
2021 bool HTMLMediaElement::endedPlayback() const
2023 float dur = duration();
2024 if (!m_player || isnan(dur))
2027 // 4.8.10.8 Playing the media resource
2029 // A media element is said to have ended playback when the element's
2030 // readyState attribute is HAVE_METADATA or greater,
2031 if (m_readyState < HAVE_METADATA)
2034 // and the current playback position is the end of the media resource and the direction
2035 // of playback is forwards and the media element does not have a loop attribute specified,
2036 float now = currentTime();
2037 if (m_playbackRate > 0)
2038 return dur > 0 && now >= dur && !loop();
2040 // or the current playback position is the earliest possible position and the direction
2041 // of playback is backwards
2042 if (m_playbackRate < 0)
2048 bool HTMLMediaElement::stoppedDueToErrors() const
2050 if (m_readyState >= HAVE_METADATA && m_error) {
2051 RefPtr<TimeRanges> seekableRanges = seekable();
2052 if (!seekableRanges->contain(currentTime()))
2059 bool HTMLMediaElement::pausedForUserInteraction() const
2061 // return !paused() && m_readyState >= HAVE_FUTURE_DATA && [UA requires a decitions from the user]
2065 float HTMLMediaElement::minTimeSeekable() const
2070 float HTMLMediaElement::maxTimeSeekable() const
2072 return m_player ? m_player->maxTimeSeekable() : 0;
2075 void HTMLMediaElement::updateVolume()
2080 // Avoid recursion when the player reports volume changes.
2081 if (!processingMediaPlayerCallback()) {
2082 Page* page = document()->page();
2083 float volumeMultiplier = page ? page->mediaVolume() : 1;
2085 m_player->setMuted(m_muted);
2086 m_player->setVolume(m_volume * volumeMultiplier);
2090 renderer()->updateFromElement();
2093 void HTMLMediaElement::updatePlayState()
2098 if (m_pausedInternal) {
2099 if (!m_player->paused())
2101 refreshCachedTime();
2102 m_playbackProgressTimer.stop();
2106 bool shouldBePlaying = potentiallyPlaying();
2107 bool playerPaused = m_player->paused();
2109 LOG(Media, "HTMLMediaElement::updatePlayState - shouldBePlaying = %s, playerPaused = %s",
2110 boolString(shouldBePlaying), boolString(playerPaused));
2112 if (shouldBePlaying) {
2113 setDisplayMode(Video);
2114 invalidateCachedTime();
2117 if (!m_isFullscreen && isVideo() && document() && document()->page() && document()->page()->chrome()->requiresFullscreenForVideoPlayback())
2120 // Set rate before calling play in case the rate was set before the media engine was setup.
2121 // The media engine should just stash the rate since it isn't already playing.
2122 m_player->setRate(m_playbackRate);
2126 startPlaybackProgressTimer();
2129 } else { // Should not be playing right now
2132 refreshCachedTime();
2134 m_playbackProgressTimer.stop();
2136 float time = currentTime();
2137 if (time > m_lastSeekTime)
2138 addPlayedRange(m_lastSeekTime, time);
2140 if (couldPlayIfEnoughData())
2141 m_player->prepareToPlay();
2145 renderer()->updateFromElement();
2148 void HTMLMediaElement::setPausedInternal(bool b)
2150 m_pausedInternal = b;
2154 void HTMLMediaElement::stopPeriodicTimers()
2156 m_progressEventTimer.stop();
2157 m_playbackProgressTimer.stop();
2160 void HTMLMediaElement::userCancelledLoad()
2162 LOG(Media, "HTMLMediaElement::userCancelledLoad");
2164 if (m_networkState == NETWORK_EMPTY || m_completelyLoaded)
2167 // If the media data fetching process is aborted by the user:
2169 // 1 - The user agent should cancel the fetching process.
2170 #if !ENABLE(PLUGIN_PROXY_FOR_VIDEO)
2173 stopPeriodicTimers();
2174 m_loadState = WaitingForSource;
2176 // 2 - Set the error attribute to a new MediaError object whose code attribute is set to MEDIA_ERR_ABORTED.
2177 m_error = MediaError::create(MediaError::MEDIA_ERR_ABORTED);
2179 // 3 - Queue a task to fire a simple event named error at the media element.
2180 scheduleEvent(eventNames().abortEvent);
2182 // 4 - If the media element's readyState attribute has a value equal to HAVE_NOTHING, set the
2183 // element's networkState attribute to the NETWORK_EMPTY value and queue a task to fire a
2184 // simple event named emptied at the element. Otherwise, set the element's networkState
2185 // attribute to the NETWORK_IDLE value.
2186 if (m_readyState == HAVE_NOTHING) {
2187 m_networkState = NETWORK_EMPTY;
2188 scheduleEvent(eventNames().emptiedEvent);
2191 m_networkState = NETWORK_IDLE;
2193 // 5 - Set the element's delaying-the-load-event flag to false. This stops delaying the load event.
2194 setShouldDelayLoadEvent(false);
2196 // 6 - Abort the overall resource selection algorithm.
2197 m_currentSourceNode = 0;
2199 // Reset m_readyState since m_player is gone.
2200 m_readyState = HAVE_NOTHING;
2203 bool HTMLMediaElement::canSuspend() const
2208 void HTMLMediaElement::stop()
2210 LOG(Media, "HTMLMediaElement::stop");
2214 m_inActiveDocument = false;
2215 userCancelledLoad();
2217 // Stop the playback without generating events
2218 setPausedInternal(true);
2221 renderer()->updateFromElement();
2223 stopPeriodicTimers();
2224 cancelPendingEventsAndCallbacks();
2227 void HTMLMediaElement::suspend(ReasonForSuspension why)
2229 LOG(Media, "HTMLMediaElement::suspend");
2233 case DocumentWillBecomeInactive:
2236 case JavaScriptDebuggerPaused:
2237 case WillShowDialog:
2238 // Do nothing, we don't pause media playback in these cases.
2243 void HTMLMediaElement::resume()
2245 LOG(Media, "HTMLMediaElement::resume");
2247 m_inActiveDocument = true;
2248 setPausedInternal(false);
2250 if (m_error && m_error->code() == MediaError::MEDIA_ERR_ABORTED) {
2251 // Restart the load if it was aborted in the middle by moving the document to the page cache.
2252 // m_error is only left at MEDIA_ERR_ABORTED when the document becomes inactive (it is set to
2253 // MEDIA_ERR_ABORTED while the abortEvent is being sent, but cleared immediately afterwards).
2254 // This behavior is not specified but it seems like a sensible thing to do.
2256 load(processingUserGesture(), ec);
2260 renderer()->updateFromElement();
2263 bool HTMLMediaElement::hasPendingActivity() const
2265 // Return true when we have pending events so we can't fire events after the JS
2266 // object gets collected.
2267 bool pending = m_pendingEvents.size();
2268 LOG(Media, "HTMLMediaElement::hasPendingActivity -> %s", boolString(pending));
2272 void HTMLMediaElement::mediaVolumeDidChange()
2274 LOG(Media, "HTMLMediaElement::mediaVolumeDidChange");
2278 void HTMLMediaElement::defaultEventHandler(Event* event)
2280 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
2281 RenderObject* r = renderer();
2282 if (!r || !r->isWidget())
2285 Widget* widget = toRenderWidget(r)->widget();
2287 widget->handleEvent(event);
2289 if (renderer() && renderer()->isMedia())
2290 toRenderMedia(renderer())->forwardEvent(event);
2291 if (event->defaultHandled())
2293 HTMLElement::defaultEventHandler(event);
2297 bool HTMLMediaElement::processingUserGesture() const
2299 Frame* frame = document()->frame();
2300 FrameLoader* loader = frame ? frame->loader() : 0;
2302 // return 'true' for safety if we don't know the answer
2303 return loader ? loader->isProcessingUserGesture() : true;
2306 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
2308 void HTMLMediaElement::ensureMediaPlayer()
2311 m_player = MediaPlayer::create(this);
2314 void HTMLMediaElement::deliverNotification(MediaPlayerProxyNotificationType notification)
2316 if (notification == MediaPlayerNotificationPlayPauseButtonPressed) {
2322 m_player->deliverNotification(notification);
2325 void HTMLMediaElement::setMediaPlayerProxy(WebMediaPlayerProxy* proxy)
2327 ensureMediaPlayer();
2328 m_player->setMediaPlayerProxy(proxy);
2331 void HTMLMediaElement::getPluginProxyParams(KURL& url, Vector<String>& names, Vector<String>& values)
2333 Frame* frame = document()->frame();
2334 FrameLoader* loader = frame ? frame->loader() : 0;
2337 KURL posterURL = getNonEmptyURLAttribute(posterAttr);
2338 if (!posterURL.isEmpty() && loader && loader->willLoadMediaElementURL(posterURL)) {
2339 names.append("_media_element_poster_");
2340 values.append(posterURL.string());
2345 names.append("_media_element_controls_");
2346 values.append("true");
2350 if (!isSafeToLoadURL(url, Complain))
2351 url = selectNextSourceChild(0, DoNothing);
2353 m_currentSrc = url.string();
2354 if (url.isValid() && loader && loader->willLoadMediaElementURL(url)) {
2355 names.append("_media_element_src_");
2356 values.append(m_currentSrc);
2360 void HTMLMediaElement::finishParsingChildren()
2362 HTMLElement::finishParsingChildren();
2363 document()->updateStyleIfNeeded();
2364 createMediaPlayerProxy();
2367 void HTMLMediaElement::createMediaPlayerProxy()
2369 ensureMediaPlayer();
2371 if (m_proxyWidget || (inDocument() && !m_needWidgetUpdate))
2374 Frame* frame = document()->frame();
2375 FrameLoader* loader = frame ? frame->loader() : 0;
2379 LOG(Media, "HTMLMediaElement::createMediaPlayerProxy");
2382 Vector<String> paramNames;
2383 Vector<String> paramValues;
2385 getPluginProxyParams(url, paramNames, paramValues);
2387 // Hang onto the proxy widget so it won't be destroyed if the plug-in is set to
2389 m_proxyWidget = loader->subframeLoader()->loadMediaPlayerProxyPlugin(this, url, paramNames, paramValues);
2391 m_needWidgetUpdate = false;
2394 void HTMLMediaElement::updateWidget(bool)
2396 mediaElement->setNeedWidgetUpdate(false);
2398 Vector<String> paramNames;
2399 Vector<String> paramValues;
2402 mediaElement->getPluginProxyParams(kurl, paramNames, paramValues);
2403 SubframeLoader* loader = document()->frame()->loader()->subframeLoader();
2404 loader->loadMediaPlayerProxyPlugin(mediaElement, kurl, paramNames, paramValues);
2407 #endif // ENABLE(PLUGIN_PROXY_FOR_VIDEO)
2409 void HTMLMediaElement::enterFullscreen()
2411 LOG(Media, "HTMLMediaElement::enterFullscreen");
2413 ASSERT(!m_isFullscreen);
2414 m_isFullscreen = true;
2415 if (document() && document()->page()) {
2416 document()->page()->chrome()->client()->enterFullscreenForNode(this);
2417 scheduleEvent(eventNames().webkitbeginfullscreenEvent);
2421 void HTMLMediaElement::exitFullscreen()
2423 LOG(Media, "HTMLMediaElement::exitFullscreen");
2425 ASSERT(m_isFullscreen);
2426 m_isFullscreen = false;
2427 if (document() && document()->page()) {
2428 if (document()->page()->chrome()->requiresFullscreenForVideoPlayback())
2430 document()->page()->chrome()->client()->exitFullscreenForNode(this);
2431 scheduleEvent(eventNames().webkitendfullscreenEvent);
2435 PlatformMedia HTMLMediaElement::platformMedia() const
2437 return m_player ? m_player->platformMedia() : NoPlatformMedia;
2440 #if USE(ACCELERATED_COMPOSITING)
2441 PlatformLayer* HTMLMediaElement::platformLayer() const
2443 return m_player ? m_player->platformLayer() : 0;
2447 bool HTMLMediaElement::hasClosedCaptions() const
2449 return m_player && m_player->hasClosedCaptions();
2452 bool HTMLMediaElement::closedCaptionsVisible() const
2454 return m_closedCaptionsVisible;
2457 void HTMLMediaElement::setClosedCaptionsVisible(bool closedCaptionVisible)
2459 LOG(Media, "HTMLMediaElement::setClosedCaptionsVisible(%s)", boolString(closedCaptionVisible));
2461 if (!m_player ||!hasClosedCaptions())
2464 m_closedCaptionsVisible = closedCaptionVisible;
2465 m_player->setClosedCaptionsVisible(closedCaptionVisible);
2467 renderer()->updateFromElement();
2470 void HTMLMediaElement::setWebkitClosedCaptionsVisible(bool visible)
2472 setClosedCaptionsVisible(visible);
2475 bool HTMLMediaElement::webkitClosedCaptionsVisible() const
2477 return closedCaptionsVisible();
2481 bool HTMLMediaElement::webkitHasClosedCaptions() const
2483 return hasClosedCaptions();
2486 void HTMLMediaElement::mediaCanStart()
2488 LOG(Media, "HTMLMediaElement::mediaCanStart");
2490 ASSERT(m_isWaitingUntilMediaCanStart);
2491 m_isWaitingUntilMediaCanStart = false;
2495 bool HTMLMediaElement::isURLAttribute(Attribute* attribute) const
2497 return attribute->name() == srcAttr;
2500 void HTMLMediaElement::setShouldDelayLoadEvent(bool shouldDelay)
2502 if (m_shouldDelayLoadEvent == shouldDelay)
2505 LOG(Media, "HTMLMediaElement::setShouldDelayLoadEvent(%s)", boolString(shouldDelay));
2507 m_shouldDelayLoadEvent = shouldDelay;
2509 document()->incrementLoadEventDelayCount();
2511 document()->decrementLoadEventDelayCount();