2008-11-04 Anders Carlsson <andersca@apple.com>
[webkit/qt.git] / WebCore / html / HTMLMediaElement.cpp
blobf86c44d0cd8b44d61e8dad25c86194f4bd3aaaaf
1 /*
2 * Copyright (C) 2007, 2008 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
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
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.
26 #include "config.h"
28 #if ENABLE(VIDEO)
29 #include "HTMLMediaElement.h"
31 #include "CSSHelper.h"
32 #include "CSSPropertyNames.h"
33 #include "CSSValueKeywords.h"
34 #include "Event.h"
35 #include "EventNames.h"
36 #include "ExceptionCode.h"
37 #include "HTMLDocument.h"
38 #include "HTMLNames.h"
39 #include "HTMLSourceElement.h"
40 #include "HTMLVideoElement.h"
41 #include <limits>
42 #include "MediaError.h"
43 #include "MediaList.h"
44 #include "MediaQueryEvaluator.h"
45 #include "MIMETypeRegistry.h"
46 #include "MediaPlayer.h"
47 #include "RenderVideo.h"
48 #include "SystemTime.h"
49 #include "TimeRanges.h"
50 #include <wtf/MathExtras.h>
52 using namespace std;
54 namespace WebCore {
56 using namespace HTMLNames;
58 HTMLMediaElement::HTMLMediaElement(const QualifiedName& tagName, Document* doc)
59 : HTMLElement(tagName, doc)
60 , m_loadTimer(this, &HTMLMediaElement::loadTimerFired)
61 , m_asyncEventTimer(this, &HTMLMediaElement::asyncEventTimerFired)
62 , m_progressEventTimer(this, &HTMLMediaElement::progressEventTimerFired)
63 , m_defaultPlaybackRate(1.0f)
64 , m_networkState(EMPTY)
65 , m_readyState(DATA_UNAVAILABLE)
66 , m_begun(false)
67 , m_loadedFirstFrame(false)
68 , m_autoplaying(true)
69 , m_currentLoop(0)
70 , m_volume(1.0f)
71 , m_muted(false)
72 , m_paused(true)
73 , m_seeking(false)
74 , m_currentTimeDuringSeek(0)
75 , m_previousProgress(0)
76 , m_previousProgressTime(numeric_limits<double>::max())
77 , m_sentStalledEvent(false)
78 , m_bufferingRate(0)
79 , m_loadNestingLevel(0)
80 , m_terminateLoadBelowNestingLevel(0)
81 , m_pausedInternal(false)
82 , m_inActiveDocument(true)
83 , m_player(0)
85 document()->registerForDocumentActivationCallbacks(this);
88 HTMLMediaElement::~HTMLMediaElement()
90 document()->unregisterForDocumentActivationCallbacks(this);
93 bool HTMLMediaElement::checkDTD(const Node* newChild)
95 return newChild->hasTagName(sourceTag) || HTMLElement::checkDTD(newChild);
98 void HTMLMediaElement::attributeChanged(Attribute* attr, bool preserveDecls)
100 HTMLElement::attributeChanged(attr, preserveDecls);
102 const QualifiedName& attrName = attr->name();
103 if (attrName == srcAttr) {
104 // 3.14.9.2.
105 // change to src attribute triggers load()
106 if (inDocument() && m_networkState == EMPTY)
107 scheduleLoad();
108 } if (attrName == controlsAttr) {
109 if (!isVideo() && attached() && (controls() != (renderer() != 0))) {
110 detach();
111 attach();
113 if (renderer())
114 renderer()->updateFromElement();
118 bool HTMLMediaElement::rendererIsNeeded(RenderStyle* style)
120 return controls() ? HTMLElement::rendererIsNeeded(style) : false;
123 RenderObject* HTMLMediaElement::createRenderer(RenderArena* arena, RenderStyle*)
125 return new (arena) RenderMedia(this);
128 void HTMLMediaElement::insertedIntoDocument()
130 HTMLElement::insertedIntoDocument();
131 if (!src().isEmpty())
132 scheduleLoad();
135 void HTMLMediaElement::removedFromDocument()
137 // FIXME: pause() may invoke load() which seem like a strange thing to do as a side effect
138 // of removing an element. This might need to be fixed in the spec.
139 ExceptionCode ec;
140 pause(ec);
141 HTMLElement::removedFromDocument();
144 void HTMLMediaElement::attach()
146 ASSERT(!attached());
148 HTMLElement::attach();
150 if (renderer())
151 renderer()->updateFromElement();
154 void HTMLMediaElement::recalcStyle(StyleChange change)
156 HTMLElement::recalcStyle(change);
158 if (renderer())
159 renderer()->updateFromElement();
162 void HTMLMediaElement::scheduleLoad()
164 m_loadTimer.startOneShot(0);
167 void HTMLMediaElement::initAndDispatchProgressEvent(const AtomicString& eventName)
169 bool totalKnown = m_player && m_player->totalBytesKnown();
170 unsigned loaded = m_player ? m_player->bytesLoaded() : 0;
171 unsigned total = m_player ? m_player->totalBytes() : 0;
172 dispatchProgressEvent(eventName, totalKnown, loaded, total);
173 if (renderer())
174 renderer()->updateFromElement();
177 void HTMLMediaElement::dispatchEventAsync(const AtomicString& eventName)
179 m_asyncEventsToDispatch.append(eventName);
180 if (!m_asyncEventTimer.isActive())
181 m_asyncEventTimer.startOneShot(0);
184 void HTMLMediaElement::loadTimerFired(Timer<HTMLMediaElement>*)
186 ExceptionCode ec;
187 load(ec);
190 void HTMLMediaElement::asyncEventTimerFired(Timer<HTMLMediaElement>*)
192 Vector<AtomicString> asyncEventsToDispatch;
193 m_asyncEventsToDispatch.swap(asyncEventsToDispatch);
194 unsigned count = asyncEventsToDispatch.size();
195 for (unsigned n = 0; n < count; ++n)
196 dispatchEventForType(asyncEventsToDispatch[n], false, true);
199 String serializeTimeOffset(float time)
201 String timeString = String::number(time);
202 // FIXME serialize time offset values properly (format not specified yet)
203 timeString.append("s");
204 return timeString;
207 float parseTimeOffset(const String& timeString, bool* ok = 0)
209 const UChar* characters = timeString.characters();
210 unsigned length = timeString.length();
212 if (length && characters[length - 1] == 's')
213 length--;
215 // FIXME parse time offset values (format not specified yet)
216 float val = charactersToFloat(characters, length, ok);
217 return val;
220 float HTMLMediaElement::getTimeOffsetAttribute(const QualifiedName& name, float valueOnError) const
222 bool ok;
223 String timeString = getAttribute(name);
224 float result = parseTimeOffset(timeString, &ok);
225 if (ok)
226 return result;
227 return valueOnError;
230 void HTMLMediaElement::setTimeOffsetAttribute(const QualifiedName& name, float value)
232 setAttribute(name, serializeTimeOffset(value));
235 PassRefPtr<MediaError> HTMLMediaElement::error() const
237 return m_error;
240 KURL HTMLMediaElement::src() const
242 return document()->completeURL(getAttribute(srcAttr));
245 void HTMLMediaElement::setSrc(const String& url)
247 setAttribute(srcAttr, url);
250 String HTMLMediaElement::currentSrc() const
252 return m_currentSrc;
255 HTMLMediaElement::NetworkState HTMLMediaElement::networkState() const
257 return m_networkState;
260 float HTMLMediaElement::bufferingRate()
262 if (!m_player)
263 return 0;
264 return m_bufferingRate;
265 //return m_player->dataRate();
268 void HTMLMediaElement::load(ExceptionCode& ec)
270 String mediaSrc;
272 // 3.14.9.4. Loading the media resource
273 // 1
274 // if an event generated during load() ends up re-entering load(), terminate previous instances
275 m_loadNestingLevel++;
276 m_terminateLoadBelowNestingLevel = m_loadNestingLevel;
278 m_progressEventTimer.stop();
279 m_sentStalledEvent = false;
280 m_bufferingRate = 0;
282 m_loadTimer.stop();
284 // 2
285 if (m_begun) {
286 m_begun = false;
287 m_error = MediaError::create(MediaError::MEDIA_ERR_ABORTED);
288 initAndDispatchProgressEvent(eventNames().abortEvent);
289 if (m_loadNestingLevel < m_terminateLoadBelowNestingLevel)
290 goto end;
293 // 3
294 m_error = 0;
295 m_loadedFirstFrame = false;
296 m_autoplaying = true;
298 // 4
299 setPlaybackRate(defaultPlaybackRate(), ec);
301 // 5
302 if (networkState() != EMPTY) {
303 m_networkState = EMPTY;
304 m_readyState = DATA_UNAVAILABLE;
305 m_paused = true;
306 m_seeking = false;
307 if (m_player) {
308 m_player->pause();
309 m_player->seek(0);
311 m_currentLoop = 0;
312 dispatchEventForType(eventNames().emptiedEvent, false, true);
313 if (m_loadNestingLevel < m_terminateLoadBelowNestingLevel)
314 goto end;
317 // 6
318 mediaSrc = pickMedia();
319 if (mediaSrc.isEmpty()) {
320 ec = INVALID_STATE_ERR;
321 goto end;
324 // 7
325 m_networkState = LOADING;
327 // 8
328 m_currentSrc = mediaSrc;
330 // 9
331 m_begun = true;
332 dispatchProgressEvent(eventNames().loadstartEvent, false, 0, 0);
333 if (m_loadNestingLevel < m_terminateLoadBelowNestingLevel)
334 goto end;
336 // 10, 11, 12, 13
337 m_player.clear();
338 m_player.set(new MediaPlayer(this));
339 updateVolume();
340 m_player->load(m_currentSrc);
341 if (m_loadNestingLevel < m_terminateLoadBelowNestingLevel)
342 goto end;
344 if (renderer())
345 renderer()->updateFromElement();
347 // 14
348 m_previousProgressTime = WebCore::currentTime();
349 m_previousProgress = 0;
350 if (m_begun)
351 // 350ms is not magic, it is in the spec!
352 m_progressEventTimer.startRepeating(0.350);
353 end:
354 ASSERT(m_loadNestingLevel);
355 m_loadNestingLevel--;
358 void HTMLMediaElement::mediaPlayerNetworkStateChanged(MediaPlayer*)
360 if (!m_begun || m_networkState == EMPTY)
361 return;
363 m_terminateLoadBelowNestingLevel = m_loadNestingLevel;
365 MediaPlayer::NetworkState state = m_player->networkState();
367 // 3.14.9.4. Loading the media resource
368 // 14
369 if (state == MediaPlayer::LoadFailed) {
370 //delete m_player;
371 //m_player = 0;
372 // FIXME better error handling
373 m_error = MediaError::create(MediaError::MEDIA_ERR_NETWORK);
374 m_begun = false;
375 m_progressEventTimer.stop();
376 m_bufferingRate = 0;
378 initAndDispatchProgressEvent(eventNames().errorEvent);
379 if (m_loadNestingLevel < m_terminateLoadBelowNestingLevel)
380 return;
382 m_networkState = EMPTY;
384 if (isVideo())
385 static_cast<HTMLVideoElement*>(this)->updatePosterImage();
387 dispatchEventForType(eventNames().emptiedEvent, false, true);
388 return;
391 if (state >= MediaPlayer::Loading && m_networkState < LOADING)
392 m_networkState = LOADING;
394 if (state >= MediaPlayer::LoadedMetaData && m_networkState < LOADED_METADATA) {
395 m_player->seek(effectiveStart());
396 m_networkState = LOADED_METADATA;
398 dispatchEventForType(eventNames().durationchangeEvent, false, true);
399 if (m_loadNestingLevel < m_terminateLoadBelowNestingLevel)
400 return;
402 dispatchEventForType(eventNames().loadedmetadataEvent, false, true);
403 if (m_loadNestingLevel < m_terminateLoadBelowNestingLevel)
404 return;
407 if (state >= MediaPlayer::LoadedFirstFrame && m_networkState < LOADED_FIRST_FRAME) {
408 m_networkState = LOADED_FIRST_FRAME;
410 setReadyState(CAN_SHOW_CURRENT_FRAME);
412 if (isVideo())
413 static_cast<HTMLVideoElement*>(this)->updatePosterImage();
415 if (m_loadNestingLevel < m_terminateLoadBelowNestingLevel)
416 return;
418 m_loadedFirstFrame = true;
419 if (renderer()) {
420 ASSERT(!renderer()->isImage());
421 static_cast<RenderVideo*>(renderer())->videoSizeChanged();
424 dispatchEventForType(eventNames().loadedfirstframeEvent, false, true);
425 if (m_loadNestingLevel < m_terminateLoadBelowNestingLevel)
426 return;
428 dispatchEventForType(eventNames().canshowcurrentframeEvent, false, true);
429 if (m_loadNestingLevel < m_terminateLoadBelowNestingLevel)
430 return;
433 // 15
434 if (state == MediaPlayer::Loaded && m_networkState < LOADED) {
435 m_begun = false;
436 m_networkState = LOADED;
437 m_progressEventTimer.stop();
438 m_bufferingRate = 0;
439 initAndDispatchProgressEvent(eventNames().loadEvent);
443 void HTMLMediaElement::mediaPlayerReadyStateChanged(MediaPlayer*)
445 MediaPlayer::ReadyState state = m_player->readyState();
446 setReadyState((ReadyState)state);
449 void HTMLMediaElement::setReadyState(ReadyState state)
451 // 3.14.9.6. The ready states
452 if (m_readyState == state)
453 return;
455 bool wasActivelyPlaying = activelyPlaying();
456 m_readyState = state;
458 if (state >= CAN_PLAY)
459 m_seeking = false;
461 if (networkState() == EMPTY)
462 return;
464 if (state == DATA_UNAVAILABLE) {
465 dispatchEventForType(eventNames().dataunavailableEvent, false, true);
466 if (wasActivelyPlaying) {
467 dispatchEventForType(eventNames().timeupdateEvent, false, true);
468 dispatchEventForType(eventNames().waitingEvent, false, true);
470 } else if (state == CAN_SHOW_CURRENT_FRAME) {
471 if (m_loadedFirstFrame)
472 dispatchEventForType(eventNames().canshowcurrentframeEvent, false, true);
473 if (wasActivelyPlaying) {
474 dispatchEventForType(eventNames().timeupdateEvent, false, true);
475 dispatchEventForType(eventNames().waitingEvent, false, true);
477 } else if (state == CAN_PLAY) {
478 dispatchEventForType(eventNames().canplayEvent, false, true);
479 } else if (state == CAN_PLAY_THROUGH) {
480 dispatchEventForType(eventNames().canplaythroughEvent, false, true);
481 if (m_autoplaying && m_paused && autoplay()) {
482 m_paused = false;
483 dispatchEventForType(eventNames().playEvent, false, true);
486 updatePlayState();
489 void HTMLMediaElement::progressEventTimerFired(Timer<HTMLMediaElement>*)
491 ASSERT(m_player);
492 unsigned progress = m_player->bytesLoaded();
493 double time = WebCore::currentTime();
494 double timedelta = time - m_previousProgressTime;
495 if (timedelta)
496 m_bufferingRate = (float)(0.8 * m_bufferingRate + 0.2 * ((float)(progress - m_previousProgress)) / timedelta);
498 if (progress == m_previousProgress) {
499 if (timedelta > 3.0 && !m_sentStalledEvent) {
500 m_bufferingRate = 0;
501 initAndDispatchProgressEvent(eventNames().stalledEvent);
502 m_sentStalledEvent = true;
504 } else {
505 initAndDispatchProgressEvent(eventNames().progressEvent);
506 m_previousProgress = progress;
507 m_previousProgressTime = time;
508 m_sentStalledEvent = false;
512 void HTMLMediaElement::seek(float time, ExceptionCode& ec)
514 // 3.14.9.8. Seeking
515 // 1
516 if (networkState() < LOADED_METADATA) {
517 ec = INVALID_STATE_ERR;
518 return;
521 // 2
522 float minTime;
523 if (currentLoop() == 0)
524 minTime = effectiveStart();
525 else
526 minTime = effectiveLoopStart();
528 // 3
529 float maxTime = currentLoop() == playCount() - 1 ? effectiveEnd() : effectiveLoopEnd();
531 // 4
532 time = min(time, maxTime);
534 // 5
535 time = max(time, minTime);
537 // 6
538 RefPtr<TimeRanges> seekableRanges = seekable();
539 if (!seekableRanges->contain(time)) {
540 ec = INDEX_SIZE_ERR;
541 return;
544 // 7
545 m_currentTimeDuringSeek = time;
547 // 8
548 m_seeking = true;
550 // 9
551 dispatchEventForType(eventNames().timeupdateEvent, false, true);
553 // 10
554 // As soon as the user agent has established whether or not the media data for the new playback position is available,
555 // and, if it is, decoded enough data to play back that position, the seeking DOM attribute must be set to false.
556 if (m_player) {
557 m_player->setEndTime(maxTime);
558 m_player->seek(time);
562 HTMLMediaElement::ReadyState HTMLMediaElement::readyState() const
564 return m_readyState;
567 bool HTMLMediaElement::seeking() const
569 return m_seeking;
572 // playback state
573 float HTMLMediaElement::currentTime() const
575 if (!m_player)
576 return 0;
577 if (m_seeking)
578 return m_currentTimeDuringSeek;
579 return m_player->currentTime();
582 void HTMLMediaElement::setCurrentTime(float time, ExceptionCode& ec)
584 seek(time, ec);
587 float HTMLMediaElement::duration() const
589 return m_player ? m_player->duration() : 0;
592 bool HTMLMediaElement::paused() const
594 return m_paused;
597 float HTMLMediaElement::defaultPlaybackRate() const
599 return m_defaultPlaybackRate;
602 void HTMLMediaElement::setDefaultPlaybackRate(float rate, ExceptionCode& ec)
604 if (rate == 0.0f) {
605 ec = NOT_SUPPORTED_ERR;
606 return;
608 if (m_defaultPlaybackRate != rate) {
609 m_defaultPlaybackRate = rate;
610 dispatchEventAsync(eventNames().ratechangeEvent);
614 float HTMLMediaElement::playbackRate() const
616 return m_player ? m_player->rate() : 0;
619 void HTMLMediaElement::setPlaybackRate(float rate, ExceptionCode& ec)
621 if (rate == 0.0f) {
622 ec = NOT_SUPPORTED_ERR;
623 return;
625 if (m_player && m_player->rate() != rate) {
626 m_player->setRate(rate);
627 dispatchEventAsync(eventNames().ratechangeEvent);
631 bool HTMLMediaElement::ended() const
633 return endedPlayback();
636 bool HTMLMediaElement::autoplay() const
638 return hasAttribute(autoplayAttr);
641 void HTMLMediaElement::setAutoplay(bool b)
643 setBooleanAttribute(autoplayAttr, b);
646 void HTMLMediaElement::play(ExceptionCode& ec)
648 // 3.14.9.7. Playing the media resource
649 if (!m_player || networkState() == EMPTY) {
650 ec = 0;
651 load(ec);
652 if (ec)
653 return;
655 ExceptionCode unused;
656 if (endedPlayback()) {
657 m_currentLoop = 0;
658 seek(effectiveStart(), unused);
660 setPlaybackRate(defaultPlaybackRate(), unused);
662 if (m_paused) {
663 m_paused = false;
664 dispatchEventAsync(eventNames().playEvent);
667 m_autoplaying = false;
669 updatePlayState();
672 void HTMLMediaElement::pause(ExceptionCode& ec)
674 // 3.14.9.7. Playing the media resource
675 if (!m_player || networkState() == EMPTY) {
676 ec = 0;
677 load(ec);
678 if (ec)
679 return;
682 if (!m_paused) {
683 m_paused = true;
684 dispatchEventAsync(eventNames().timeupdateEvent);
685 dispatchEventAsync(eventNames().pauseEvent);
688 m_autoplaying = false;
690 updatePlayState();
693 unsigned HTMLMediaElement::playCount() const
695 bool ok;
696 unsigned count = getAttribute(playcountAttr).string().toUInt(&ok);
697 return (count > 0 && ok) ? count : 1;
700 void HTMLMediaElement::setPlayCount(unsigned count, ExceptionCode& ec)
702 if (!count) {
703 ec = INDEX_SIZE_ERR;
704 return;
706 setAttribute(playcountAttr, String::number(count));
707 checkIfSeekNeeded();
710 float HTMLMediaElement::start() const
712 return getTimeOffsetAttribute(startAttr, 0);
715 void HTMLMediaElement::setStart(float time)
717 setTimeOffsetAttribute(startAttr, time);
718 checkIfSeekNeeded();
721 float HTMLMediaElement::end() const
723 return getTimeOffsetAttribute(endAttr, std::numeric_limits<float>::infinity());
726 void HTMLMediaElement::setEnd(float time)
728 setTimeOffsetAttribute(endAttr, time);
729 checkIfSeekNeeded();
732 float HTMLMediaElement::loopStart() const
734 return getTimeOffsetAttribute(loopstartAttr, start());
737 void HTMLMediaElement::setLoopStart(float time)
739 setTimeOffsetAttribute(loopstartAttr, time);
740 checkIfSeekNeeded();
743 float HTMLMediaElement::loopEnd() const
745 return getTimeOffsetAttribute(loopendAttr, end());
748 void HTMLMediaElement::setLoopEnd(float time)
750 setTimeOffsetAttribute(loopendAttr, time);
751 checkIfSeekNeeded();
754 unsigned HTMLMediaElement::currentLoop() const
756 return m_currentLoop;
759 void HTMLMediaElement::setCurrentLoop(unsigned currentLoop)
761 m_currentLoop = currentLoop;
764 bool HTMLMediaElement::controls() const
766 return hasAttribute(controlsAttr);
769 void HTMLMediaElement::setControls(bool b)
771 setBooleanAttribute(controlsAttr, b);
774 float HTMLMediaElement::volume() const
776 return m_volume;
779 void HTMLMediaElement::setVolume(float vol, ExceptionCode& ec)
781 if (vol < 0.0f || vol > 1.0f) {
782 ec = INDEX_SIZE_ERR;
783 return;
786 if (m_volume != vol) {
787 m_volume = vol;
788 updateVolume();
789 dispatchEventAsync(eventNames().volumechangeEvent);
793 bool HTMLMediaElement::muted() const
795 return m_muted;
798 void HTMLMediaElement::setMuted(bool muted)
800 if (m_muted != muted) {
801 m_muted = muted;
802 updateVolume();
803 dispatchEventAsync(eventNames().volumechangeEvent);
807 bool HTMLMediaElement::canPlay() const
809 return paused() || ended() || networkState() < LOADED_METADATA;
812 String HTMLMediaElement::pickMedia()
814 // 3.14.9.2. Location of the media resource
815 String mediaSrc = getAttribute(srcAttr);
816 if (mediaSrc.isEmpty()) {
817 for (Node* n = firstChild(); n; n = n->nextSibling()) {
818 if (n->hasTagName(sourceTag)) {
819 HTMLSourceElement* source = static_cast<HTMLSourceElement*>(n);
820 if (!source->hasAttribute(srcAttr))
821 continue;
822 if (source->hasAttribute(mediaAttr)) {
823 MediaQueryEvaluator screenEval("screen", document()->frame(), renderer() ? renderer()->style() : 0);
824 RefPtr<MediaList> media = MediaList::createAllowingDescriptionSyntax(source->media());
825 if (!screenEval.eval(media.get()))
826 continue;
828 if (source->hasAttribute(typeAttr)) {
829 String type = source->type().stripWhiteSpace();
831 // "type" can have parameters after a semi-colon, strip them before checking with the type registry
832 int semi = type.find(';');
833 if (semi != -1)
834 type = type.left(semi).stripWhiteSpace();
836 if (!MIMETypeRegistry::isSupportedMediaMIMEType(type))
837 continue;
839 mediaSrc = source->src().string();
840 break;
844 if (!mediaSrc.isEmpty())
845 mediaSrc = document()->completeURL(mediaSrc).string();
846 return mediaSrc;
849 void HTMLMediaElement::checkIfSeekNeeded()
851 // 3.14.9.5. Offsets into the media resource
852 // 1
853 if (playCount() <= m_currentLoop)
854 m_currentLoop = playCount() - 1;
856 // 2
857 if (networkState() <= LOADING)
858 return;
860 // 3
861 ExceptionCode ec;
862 float time = currentTime();
863 if (!m_currentLoop && time < effectiveStart())
864 seek(effectiveStart(), ec);
866 // 4
867 if (m_currentLoop && time < effectiveLoopStart())
868 seek(effectiveLoopStart(), ec);
870 // 5
871 if (m_currentLoop < playCount() - 1 && time > effectiveLoopEnd()) {
872 seek(effectiveLoopStart(), ec);
873 m_currentLoop++;
876 // 6
877 if (m_currentLoop == playCount() - 1 && time > effectiveEnd())
878 seek(effectiveEnd(), ec);
880 updatePlayState();
883 void HTMLMediaElement::mediaPlayerTimeChanged(MediaPlayer*)
885 if (readyState() >= CAN_PLAY)
886 m_seeking = false;
888 if (m_currentLoop < playCount() - 1 && currentTime() >= effectiveLoopEnd()) {
889 ExceptionCode ec;
890 seek(effectiveLoopStart(), ec);
891 m_currentLoop++;
892 dispatchEventForType(eventNames().timeupdateEvent, false, true);
895 if (m_currentLoop == playCount() - 1 && currentTime() >= effectiveEnd()) {
896 dispatchEventForType(eventNames().timeupdateEvent, false, true);
897 dispatchEventForType(eventNames().endedEvent, false, true);
900 updatePlayState();
903 void HTMLMediaElement::mediaPlayerRepaint(MediaPlayer*)
905 if (renderer())
906 renderer()->repaint();
909 PassRefPtr<TimeRanges> HTMLMediaElement::buffered() const
911 // FIXME real ranges support
912 if (!m_player || !m_player->maxTimeBuffered())
913 return TimeRanges::create();
914 return TimeRanges::create(0, m_player->maxTimeBuffered());
917 PassRefPtr<TimeRanges> HTMLMediaElement::played() const
919 // FIXME track played
920 return TimeRanges::create();
923 PassRefPtr<TimeRanges> HTMLMediaElement::seekable() const
925 // FIXME real ranges support
926 if (!m_player || !m_player->maxTimeSeekable())
927 return TimeRanges::create();
928 return TimeRanges::create(0, m_player->maxTimeSeekable());
931 float HTMLMediaElement::effectiveStart() const
933 if (!m_player)
934 return 0;
935 return min(start(), m_player->duration());
938 float HTMLMediaElement::effectiveEnd() const
940 if (!m_player)
941 return 0;
942 return min(max(end(), max(start(), loopStart())), m_player->duration());
945 float HTMLMediaElement::effectiveLoopStart() const
947 if (!m_player)
948 return 0;
949 return min(loopStart(), m_player->duration());
952 float HTMLMediaElement::effectiveLoopEnd() const
954 if (!m_player)
955 return 0;
956 return min(max(start(), max(loopStart(), loopEnd())), m_player->duration());
959 bool HTMLMediaElement::activelyPlaying() const
961 return !paused() && readyState() >= CAN_PLAY && !endedPlayback(); // && !stoppedDueToErrors() && !pausedForUserInteraction();
964 bool HTMLMediaElement::endedPlayback() const
966 return networkState() >= LOADED_METADATA && currentTime() >= effectiveEnd() && currentLoop() == playCount() - 1;
969 void HTMLMediaElement::updateVolume()
971 if (!m_player)
972 return;
974 m_player->setVolume(m_muted ? 0 : m_volume);
976 if (renderer())
977 renderer()->updateFromElement();
980 void HTMLMediaElement::updatePlayState()
982 if (!m_player)
983 return;
985 if (m_pausedInternal) {
986 if (!m_player->paused())
987 m_player->pause();
988 return;
991 m_player->setEndTime(currentLoop() == playCount() - 1 ? effectiveEnd() : effectiveLoopEnd());
993 bool shouldBePlaying = activelyPlaying() && currentTime() < effectiveEnd();
994 if (shouldBePlaying && m_player->paused())
995 m_player->play();
996 else if (!shouldBePlaying && !m_player->paused())
997 m_player->pause();
999 if (renderer())
1000 renderer()->updateFromElement();
1003 void HTMLMediaElement::setPausedInternal(bool b)
1005 m_pausedInternal = b;
1006 updatePlayState();
1009 void HTMLMediaElement::documentWillBecomeInactive()
1011 // 3.14.9.4. Loading the media resource
1012 // 14
1013 if (m_begun) {
1014 // For simplicity cancel the incomplete load by deleting the player
1015 m_player.clear();
1016 m_progressEventTimer.stop();
1018 m_error = MediaError::create(MediaError::MEDIA_ERR_ABORTED);
1019 m_begun = false;
1020 initAndDispatchProgressEvent(eventNames().abortEvent);
1021 if (m_networkState >= LOADING) {
1022 m_networkState = EMPTY;
1023 m_readyState = DATA_UNAVAILABLE;
1024 dispatchEventForType(eventNames().emptiedEvent, false, true);
1027 m_inActiveDocument = false;
1028 // Stop the playback without generating events
1029 setPausedInternal(true);
1031 if (renderer())
1032 renderer()->updateFromElement();
1035 void HTMLMediaElement::documentDidBecomeActive()
1037 m_inActiveDocument = true;
1038 setPausedInternal(false);
1040 if (m_error && m_error->code() == MediaError::MEDIA_ERR_ABORTED) {
1041 // Restart the load if it was aborted in the middle by moving the document to the page cache.
1042 // This behavior is not specified but it seems like a sensible thing to do.
1043 ExceptionCode ec;
1044 load(ec);
1047 if (renderer())
1048 renderer()->updateFromElement();
1051 void HTMLMediaElement::defaultEventHandler(Event* event)
1053 if (renderer() && renderer()->isMedia())
1054 static_cast<RenderMedia*>(renderer())->forwardEvent(event);
1055 if (event->defaultHandled())
1056 return;
1057 HTMLElement::defaultEventHandler(event);
1062 #endif