[Mac] in-band cues sometimes have incorrect duration
[WebKit-https.git] / Source / WebCore / platform / graphics / avfoundation / MediaPlayerPrivateAVFoundation.cpp
1 /*
2  * Copyright (C) 2011, 2012 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
24  */
25
26 #include "config.h"
27
28 #if ENABLE(VIDEO) && USE(AVFOUNDATION)
29
30 #include "MediaPlayerPrivateAVFoundation.h"
31
32 #include "DocumentLoader.h"
33 #include "Frame.h"
34 #include "FrameView.h"
35 #include "GraphicsContext.h"
36 #include "InbandTextTrackPrivateAVF.h"
37 #include "InbandTextTrackPrivateClient.h"
38 #include "KURL.h"
39 #include "Logging.h"
40 #include "PlatformLayer.h"
41 #include "SoftLinking.h"
42 #include "TimeRanges.h"
43 #include <CoreMedia/CoreMedia.h>
44 #include <wtf/MainThread.h>
45 #include <wtf/UnusedParam.h>
46
47 using namespace std;
48
49 namespace WebCore {
50
51 MediaPlayerPrivateAVFoundation::MediaPlayerPrivateAVFoundation(MediaPlayer* player)
52     : m_player(player)
53     , m_queuedNotifications()
54     , m_queueMutex()
55     , m_networkState(MediaPlayer::Empty)
56     , m_readyState(MediaPlayer::HaveNothing)
57     , m_preload(MediaPlayer::Auto)
58     , m_cachedMaxTimeLoaded(0)
59     , m_cachedMaxTimeSeekable(0)
60     , m_cachedMinTimeSeekable(0)
61     , m_cachedDuration(MediaPlayer::invalidTime())
62     , m_reportedDuration(MediaPlayer::invalidTime())
63     , m_maxTimeLoadedAtLastDidLoadingProgress(MediaPlayer::invalidTime())
64     , m_seekTo(MediaPlayer::invalidTime())
65     , m_requestedRate(1)
66     , m_delayCallbacks(0)
67     , m_mainThreadCallPending(false)
68     , m_assetIsPlayable(false)
69     , m_visible(false)
70     , m_loadingMetadata(false)
71     , m_isAllowedToRender(false)
72     , m_cachedHasAudio(false)
73     , m_cachedHasVideo(false)
74     , m_cachedHasCaptions(false)
75     , m_ignoreLoadStateChanges(false)
76     , m_haveReportedFirstVideoFrame(false)
77     , m_playWhenFramesAvailable(false)
78 #if HAVE(AVFOUNDATION_TEXT_TRACK_SUPPORT)
79     , m_inbandTrackConfigurationPending(false)
80 #endif
81 {
82     LOG(Media, "MediaPlayerPrivateAVFoundation::MediaPlayerPrivateAVFoundation(%p)", this);
83 }
84
85 MediaPlayerPrivateAVFoundation::~MediaPlayerPrivateAVFoundation()
86 {
87     LOG(Media, "MediaPlayerPrivateAVFoundation::~MediaPlayerPrivateAVFoundation(%p)", this);
88     setIgnoreLoadStateChanges(true);
89     cancelCallOnMainThread(mainThreadCallback, this);
90 }
91
92 MediaPlayerPrivateAVFoundation::MediaRenderingMode MediaPlayerPrivateAVFoundation::currentRenderingMode() const
93 {
94 #if USE(ACCELERATED_COMPOSITING)
95     if (platformLayer())
96         return MediaRenderingToLayer;
97 #endif
98
99     if (hasContextRenderer())
100         return MediaRenderingToContext;
101
102     return MediaRenderingNone;
103 }
104
105 MediaPlayerPrivateAVFoundation::MediaRenderingMode MediaPlayerPrivateAVFoundation::preferredRenderingMode() const
106 {
107     if (!m_player->visible() || !m_player->frameView() || assetStatus() == MediaPlayerAVAssetStatusUnknown)
108         return MediaRenderingNone;
109
110 #if USE(ACCELERATED_COMPOSITING)
111     if (supportsAcceleratedRendering() && m_player->mediaPlayerClient()->mediaPlayerRenderingCanBeAccelerated(m_player))
112         return MediaRenderingToLayer;
113 #endif
114
115     return MediaRenderingToContext;
116 }
117
118 void MediaPlayerPrivateAVFoundation::setUpVideoRendering()
119 {
120     if (!isReadyForVideoSetup())
121         return;
122
123     MediaRenderingMode currentMode = currentRenderingMode();
124     MediaRenderingMode preferredMode = preferredRenderingMode();
125
126     if (preferredMode == MediaRenderingNone)
127         preferredMode = MediaRenderingToContext;
128
129     if (currentMode == preferredMode && currentMode != MediaRenderingNone)
130         return;
131
132     LOG(Media, "MediaPlayerPrivateAVFoundation::setUpVideoRendering(%p) - current mode = %d, preferred mode = %d", 
133         this, static_cast<int>(currentMode), static_cast<int>(preferredMode));
134
135     if (currentMode != MediaRenderingNone)  
136         tearDownVideoRendering();
137
138     switch (preferredMode) {
139     case MediaRenderingNone:
140     case MediaRenderingToContext:
141         createContextVideoRenderer();
142         break;
143         
144 #if USE(ACCELERATED_COMPOSITING)
145     case MediaRenderingToLayer:
146         createVideoLayer();
147         break;
148 #endif
149     }
150
151 #if USE(ACCELERATED_COMPOSITING)
152     // If using a movie layer, inform the client so the compositing tree is updated.
153     if (currentMode == MediaRenderingToLayer || preferredMode == MediaRenderingToLayer) {
154         LOG(Media, "MediaPlayerPrivateAVFoundation::setUpVideoRendering(%p) - calling mediaPlayerRenderingModeChanged()", this);
155         m_player->mediaPlayerClient()->mediaPlayerRenderingModeChanged(m_player);
156     }
157 #endif
158 }
159
160 void MediaPlayerPrivateAVFoundation::tearDownVideoRendering()
161 {
162     LOG(Media, "MediaPlayerPrivateAVFoundation::tearDownVideoRendering(%p)", this);
163
164     destroyContextVideoRenderer();
165
166 #if USE(ACCELERATED_COMPOSITING)
167     if (platformLayer())
168         destroyVideoLayer();
169 #endif
170 }
171
172 bool MediaPlayerPrivateAVFoundation::hasSetUpVideoRendering() const
173 {
174     return hasLayerRenderer() || hasContextRenderer();
175 }
176
177 void MediaPlayerPrivateAVFoundation::load(const String& url)
178 {
179     LOG(Media, "MediaPlayerPrivateAVFoundation::load(%p)", this);
180
181     if (m_networkState != MediaPlayer::Loading) {
182         m_networkState = MediaPlayer::Loading;
183         m_player->networkStateChanged();
184     }
185     if (m_readyState != MediaPlayer::HaveNothing) {
186         m_readyState = MediaPlayer::HaveNothing;
187         m_player->readyStateChanged();
188     }
189
190     m_assetURL = url;
191
192     // Don't do any more work if the url is empty.
193     if (!url.length())
194         return;
195
196     setPreload(m_preload);
197 }
198
199 void MediaPlayerPrivateAVFoundation::playabilityKnown()
200 {
201     LOG(Media, "MediaPlayerPrivateAVFoundation::playabilityKnown(%p)", this);
202
203     if (m_assetIsPlayable)
204         return;
205
206     // Nothing more to do if we already have all of the item's metadata.
207     if (assetStatus() > MediaPlayerAVAssetStatusLoading) {
208         LOG(Media, "MediaPlayerPrivateAVFoundation::playabilityKnown(%p) - all metadata loaded", this);
209         return;
210     }
211
212     // At this point we are supposed to load metadata. It is OK to ask the asset to load the same 
213     // information multiple times, because if it has already been loaded the completion handler 
214     // will just be called synchronously.
215     m_loadingMetadata = true;
216     beginLoadingMetadata();
217 }
218
219 void MediaPlayerPrivateAVFoundation::prepareToPlay()
220 {
221     LOG(Media, "MediaPlayerPrivateAVFoundation::prepareToPlay(%p)", this);
222
223     setPreload(MediaPlayer::Auto);
224 }
225
226 void MediaPlayerPrivateAVFoundation::play()
227 {
228     LOG(Media, "MediaPlayerPrivateAVFoundation::play(%p)", this);
229
230     // If the file has video, don't request playback until the first frame of video is ready to display
231     // or the audio may start playing before we can render video.
232     if (!m_cachedHasVideo || hasAvailableVideoFrame())
233         platformPlay();
234     else
235         m_playWhenFramesAvailable = true;
236 }
237
238 void MediaPlayerPrivateAVFoundation::pause()
239 {
240     LOG(Media, "MediaPlayerPrivateAVFoundation::pause(%p)", this);
241     m_playWhenFramesAvailable = false;
242     platformPause();
243 }
244
245 float MediaPlayerPrivateAVFoundation::duration() const
246 {
247     if (m_cachedDuration != MediaPlayer::invalidTime())
248         return m_cachedDuration;
249
250     float duration = platformDuration();
251     if (!duration || duration == MediaPlayer::invalidTime())
252         return 0;
253
254     m_cachedDuration = duration;
255     LOG(Media, "MediaPlayerPrivateAVFoundation::duration(%p) - caching %f", this, m_cachedDuration);
256     return m_cachedDuration;
257 }
258
259 void MediaPlayerPrivateAVFoundation::seek(float time)
260 {
261     if (!metaDataAvailable())
262         return;
263
264     if (time > duration())
265         time = duration();
266
267     if (currentTime() == time)
268         return;
269
270 #if HAVE(AVFOUNDATION_TEXT_TRACK_SUPPORT)
271     if (currentTrack())
272         currentTrack()->beginSeeking();
273 #endif
274     
275     LOG(Media, "MediaPlayerPrivateAVFoundation::seek(%p) - seeking to %f", this, time);
276     m_seekTo = time;
277
278     seekToTime(time);
279 }
280
281 void MediaPlayerPrivateAVFoundation::setRate(float rate)
282 {
283     LOG(Media, "MediaPlayerPrivateAVFoundation::setRate(%p) - seting to %f", this, rate);
284     m_requestedRate = rate;
285
286     updateRate();
287 }
288
289 bool MediaPlayerPrivateAVFoundation::paused() const
290 {
291     if (!metaDataAvailable())
292         return true;
293
294     return rate() == 0;
295 }
296
297 bool MediaPlayerPrivateAVFoundation::seeking() const
298 {
299     if (!metaDataAvailable())
300         return false;
301
302     return m_seekTo != MediaPlayer::invalidTime();
303 }
304
305 IntSize MediaPlayerPrivateAVFoundation::naturalSize() const
306 {
307     if (!metaDataAvailable())
308         return IntSize();
309
310     // In spite of the name of this method, return the natural size transformed by the 
311     // initial movie scale because the spec says intrinsic size is:
312     //
313     //    ... the dimensions of the resource in CSS pixels after taking into account the resource's 
314     //    dimensions, aspect ratio, clean aperture, resolution, and so forth, as defined for the 
315     //    format used by the resource
316
317     return m_cachedNaturalSize;
318 }
319
320 void MediaPlayerPrivateAVFoundation::setNaturalSize(IntSize size)
321 {
322     LOG(Media, "MediaPlayerPrivateAVFoundation:setNaturalSize(%p) - size = %d x %d", this, size.width(), size.height());
323
324     IntSize oldSize = m_cachedNaturalSize;
325     m_cachedNaturalSize = size;
326     if (oldSize != m_cachedNaturalSize)
327         m_player->sizeChanged();
328 }
329
330 void MediaPlayerPrivateAVFoundation::setHasVideo(bool b)
331 {
332     if (m_cachedHasVideo != b) {
333         m_cachedHasVideo = b;
334         m_player->characteristicChanged();
335     }
336 }
337
338 void MediaPlayerPrivateAVFoundation::setHasAudio(bool b)
339 {
340     if (m_cachedHasAudio != b) {
341         m_cachedHasAudio = b;
342         m_player->characteristicChanged();
343     }
344 }
345
346 void MediaPlayerPrivateAVFoundation::setHasClosedCaptions(bool b)
347 {
348     if (m_cachedHasCaptions != b) {
349         m_cachedHasCaptions = b;
350         m_player->characteristicChanged();
351     }
352 }
353
354 PassRefPtr<TimeRanges> MediaPlayerPrivateAVFoundation::buffered() const
355 {
356     if (!m_cachedLoadedTimeRanges)
357         m_cachedLoadedTimeRanges = platformBufferedTimeRanges();
358
359     return m_cachedLoadedTimeRanges->copy();
360 }
361
362 double MediaPlayerPrivateAVFoundation::maxTimeSeekableDouble() const
363 {
364     if (!metaDataAvailable())
365         return 0;
366
367     if (!m_cachedMaxTimeSeekable)
368         m_cachedMaxTimeSeekable = platformMaxTimeSeekable();
369
370     LOG(Media, "MediaPlayerPrivateAVFoundation::maxTimeSeekable(%p) - returning %f", this, m_cachedMaxTimeSeekable);
371     return m_cachedMaxTimeSeekable;   
372 }
373
374 double MediaPlayerPrivateAVFoundation::minTimeSeekable() const
375 {
376     if (!metaDataAvailable())
377         return 0;
378
379     if (!m_cachedMinTimeSeekable)
380         m_cachedMinTimeSeekable = platformMinTimeSeekable();
381
382     LOG(Media, "MediaPlayerPrivateAVFoundation::minTimeSeekable(%p) - returning %f", this, m_cachedMinTimeSeekable);
383     return m_cachedMinTimeSeekable;
384 }
385
386 float MediaPlayerPrivateAVFoundation::maxTimeLoaded() const
387 {
388     if (!metaDataAvailable())
389         return 0;
390
391     if (!m_cachedMaxTimeLoaded)
392         m_cachedMaxTimeLoaded = platformMaxTimeLoaded();
393
394     return m_cachedMaxTimeLoaded;   
395 }
396
397 bool MediaPlayerPrivateAVFoundation::didLoadingProgress() const
398 {
399     if (!duration() || !totalBytes())
400         return false;
401     float currentMaxTimeLoaded = maxTimeLoaded();
402     bool didLoadingProgress = currentMaxTimeLoaded != m_maxTimeLoadedAtLastDidLoadingProgress;
403     m_maxTimeLoadedAtLastDidLoadingProgress = currentMaxTimeLoaded;
404
405     return didLoadingProgress;
406 }
407
408 bool MediaPlayerPrivateAVFoundation::isReadyForVideoSetup() const
409 {
410     // AVFoundation will not return true for firstVideoFrameAvailable until
411     // an AVPlayerLayer has been added to the AVPlayerItem, so allow video setup
412     // here if a video track to trigger allocation of a AVPlayerLayer.
413     return (m_isAllowedToRender || m_cachedHasVideo) && m_readyState >= MediaPlayer::HaveMetadata && m_player->visible();
414 }
415
416 void MediaPlayerPrivateAVFoundation::prepareForRendering()
417 {
418     if (m_isAllowedToRender)
419         return;
420     m_isAllowedToRender = true;
421
422     setUpVideoRendering();
423
424     if (currentRenderingMode() == MediaRenderingToLayer || preferredRenderingMode() == MediaRenderingToLayer)
425         m_player->mediaPlayerClient()->mediaPlayerRenderingModeChanged(m_player);
426 }
427
428 bool MediaPlayerPrivateAVFoundation::supportsFullscreen() const
429 {
430 #if ENABLE(FULLSCREEN_API)
431     return true;
432 #else
433     // FIXME: WebVideoFullscreenController assumes a QTKit/QuickTime media engine
434     return false;
435 #endif
436 }
437
438 void MediaPlayerPrivateAVFoundation::updateStates()
439 {
440     if (m_ignoreLoadStateChanges)
441         return;
442
443     MediaPlayer::NetworkState oldNetworkState = m_networkState;
444     MediaPlayer::ReadyState oldReadyState = m_readyState;
445
446     if (m_loadingMetadata)
447         m_networkState = MediaPlayer::Loading;
448     else {
449         // -loadValuesAsynchronouslyForKeys:completionHandler: has invoked its handler; test status of keys and determine state.
450         AssetStatus assetStatus = this->assetStatus();
451         ItemStatus itemStatus = playerItemStatus();
452         
453         m_assetIsPlayable = (assetStatus == MediaPlayerAVAssetStatusPlayable);
454         if (m_readyState < MediaPlayer::HaveMetadata && assetStatus > MediaPlayerAVAssetStatusLoading) {
455             if (m_assetIsPlayable) {
456                 if (assetStatus >= MediaPlayerAVAssetStatusLoaded)
457                     m_readyState = MediaPlayer::HaveMetadata;
458                 if (itemStatus <= MediaPlayerAVPlayerItemStatusUnknown) {
459                     if (assetStatus == MediaPlayerAVAssetStatusFailed || m_preload > MediaPlayer::MetaData || isLiveStream()) {
460                         // The asset is playable but doesn't support inspection prior to playback (eg. streaming files),
461                         // or we are supposed to prepare for playback immediately, so create the player item now.
462                         m_networkState = MediaPlayer::Loading;
463                         prepareToPlay();
464                     } else
465                         m_networkState = MediaPlayer::Idle;
466                 }
467             } else {
468                 // FIX ME: fetch the error associated with the @"playable" key to distinguish between format 
469                 // and network errors.
470                 m_networkState = MediaPlayer::FormatError;
471             }
472         }
473         
474         if (assetStatus >= MediaPlayerAVAssetStatusLoaded && itemStatus > MediaPlayerAVPlayerItemStatusUnknown) {
475             switch (itemStatus) {
476             case MediaPlayerAVPlayerItemStatusDoesNotExist:
477             case MediaPlayerAVPlayerItemStatusUnknown:
478             case MediaPlayerAVPlayerItemStatusFailed:
479                 break;
480
481             case MediaPlayerAVPlayerItemStatusPlaybackLikelyToKeepUp:
482             case MediaPlayerAVPlayerItemStatusPlaybackBufferFull:
483                 // If the status becomes PlaybackBufferFull, loading stops and the status will not
484                 // progress to LikelyToKeepUp. Set the readyState to  HAVE_ENOUGH_DATA, on the
485                 // presumption that if the playback buffer is full, playback will probably not stall.
486                 m_readyState = MediaPlayer::HaveEnoughData;
487                 break;
488
489             case MediaPlayerAVPlayerItemStatusReadyToPlay:
490                 // If the readyState is already HaveEnoughData, don't go lower because of this state change.
491                 if (m_readyState == MediaPlayer::HaveEnoughData)
492                     break;
493
494             case MediaPlayerAVPlayerItemStatusPlaybackBufferEmpty:
495                 if (maxTimeLoaded() > currentTime())
496                     m_readyState = MediaPlayer::HaveFutureData;
497                 else
498                     m_readyState = MediaPlayer::HaveCurrentData;
499                 break;
500             }
501
502             if (itemStatus == MediaPlayerAVPlayerItemStatusPlaybackBufferFull)
503                 m_networkState = MediaPlayer::Idle;
504             else if (itemStatus == MediaPlayerAVPlayerItemStatusFailed)
505                 m_networkState = MediaPlayer::DecodeError;
506             else if (itemStatus != MediaPlayerAVPlayerItemStatusPlaybackBufferFull && itemStatus >= MediaPlayerAVPlayerItemStatusReadyToPlay)
507                 m_networkState = (maxTimeLoaded() == duration()) ? MediaPlayer::Loaded : MediaPlayer::Loading;
508         }
509     }
510
511     if (isReadyForVideoSetup() && currentRenderingMode() != preferredRenderingMode())
512         setUpVideoRendering();
513
514     if (!m_haveReportedFirstVideoFrame && m_cachedHasVideo && hasAvailableVideoFrame()) {
515         if (m_readyState < MediaPlayer::HaveCurrentData)
516             m_readyState = MediaPlayer::HaveCurrentData;
517         m_haveReportedFirstVideoFrame = true;
518         m_player->firstVideoFrameAvailable();
519     }
520
521     if (m_networkState != oldNetworkState)
522         m_player->networkStateChanged();
523
524     if (m_readyState != oldReadyState)
525         m_player->readyStateChanged();
526
527     if (m_playWhenFramesAvailable && hasAvailableVideoFrame()) {
528         m_playWhenFramesAvailable = false;
529         platformPlay();
530     }
531
532 #if !LOG_DISABLED
533     if (m_networkState != oldNetworkState || oldReadyState != m_readyState) {
534         LOG(Media, "MediaPlayerPrivateAVFoundation::updateStates(%p) - entered with networkState = %i, readyState = %i,  exiting with networkState = %i, readyState = %i",
535             this, static_cast<int>(oldNetworkState), static_cast<int>(oldReadyState), static_cast<int>(m_networkState), static_cast<int>(m_readyState));
536     }
537 #endif
538 }
539
540 void MediaPlayerPrivateAVFoundation::setSize(const IntSize&) 
541
542 }
543
544 void MediaPlayerPrivateAVFoundation::setVisible(bool visible)
545 {
546     if (m_visible == visible)
547         return;
548
549     m_visible = visible;
550     if (visible)
551         setUpVideoRendering();
552     
553     platformSetVisible(visible);
554 }
555
556 void MediaPlayerPrivateAVFoundation::acceleratedRenderingStateChanged()
557 {
558     // Set up or change the rendering path if necessary.
559     setUpVideoRendering();
560 }
561
562 void MediaPlayerPrivateAVFoundation::metadataLoaded()
563 {
564     m_loadingMetadata = false;
565     tracksChanged();
566 }
567
568 void MediaPlayerPrivateAVFoundation::rateChanged()
569 {
570     m_player->rateChanged();
571 }
572
573 void MediaPlayerPrivateAVFoundation::loadedTimeRangesChanged()
574 {
575     m_cachedLoadedTimeRanges = 0;
576     m_cachedMaxTimeLoaded = 0;
577     invalidateCachedDuration();
578 }
579
580 void MediaPlayerPrivateAVFoundation::seekableTimeRangesChanged()
581 {
582     m_cachedMaxTimeSeekable = 0;
583     m_cachedMinTimeSeekable = 0;
584 }
585
586 void MediaPlayerPrivateAVFoundation::timeChanged(double time)
587 {
588     LOG(Media, "MediaPlayerPrivateAVFoundation::timeChanged(%p) - time = %f", this, time);
589     UNUSED_PARAM(time);
590 }
591
592 void MediaPlayerPrivateAVFoundation::seekCompleted(bool finished)
593 {
594     LOG(Media, "MediaPlayerPrivateAVFoundation::seekCompleted(%p) - finished = %d", this, finished);
595     UNUSED_PARAM(finished);
596
597 #if HAVE(AVFOUNDATION_TEXT_TRACK_SUPPORT)
598     if (currentTrack())
599         currentTrack()->endSeeking();
600 #endif
601
602     m_seekTo = MediaPlayer::invalidTime();
603     updateStates();
604     m_player->timeChanged();
605 }
606
607 void MediaPlayerPrivateAVFoundation::didEnd()
608 {
609     // Hang onto the current time and use it as duration from now on since we are definitely at
610     // the end of the movie. Do this because the initial duration is sometimes an estimate.
611     float now = currentTime();
612     if (now > 0)
613         m_cachedDuration = now;
614
615     updateStates();
616     m_player->timeChanged();
617 }
618
619 void MediaPlayerPrivateAVFoundation::invalidateCachedDuration()
620 {
621     LOG(Media, "MediaPlayerPrivateAVFoundation::invalidateCachedDuration(%p)", this);
622     
623     m_cachedDuration = MediaPlayer::invalidTime();
624
625     // For some media files, reported duration is estimated and updated as media is loaded
626     // so report duration changed when the estimate is upated.
627     float duration = this->duration();
628     if (duration != m_reportedDuration) {
629         if (m_reportedDuration != MediaPlayer::invalidTime())
630             m_player->durationChanged();
631         m_reportedDuration = duration;
632     }
633     
634 }
635
636 void MediaPlayerPrivateAVFoundation::repaint()
637 {
638     m_player->repaint();
639 }
640
641 MediaPlayer::MovieLoadType MediaPlayerPrivateAVFoundation::movieLoadType() const
642 {
643     if (!metaDataAvailable() || assetStatus() == MediaPlayerAVAssetStatusUnknown)
644         return MediaPlayer::Unknown;
645
646     if (isLiveStream())
647         return MediaPlayer::LiveStream;
648
649     return MediaPlayer::Download;
650 }
651
652 void MediaPlayerPrivateAVFoundation::setPreload(MediaPlayer::Preload preload)
653 {
654     m_preload = preload;
655     if (!m_assetURL.length())
656         return;
657
658     setDelayCallbacks(true);
659
660     if (m_preload >= MediaPlayer::MetaData && assetStatus() == MediaPlayerAVAssetStatusDoesNotExist) {
661         createAVAssetForURL(m_assetURL);
662         checkPlayability();
663     }
664
665     // Don't force creation of the player and player item unless we already know that the asset is playable. If we aren't
666     // there yet, or if we already know it is not playable, creating them now won't help.
667     if (m_preload == MediaPlayer::Auto && m_assetIsPlayable) {
668         createAVPlayerItem();
669         createAVPlayer();
670     }
671
672     setDelayCallbacks(false);
673 }
674
675 void MediaPlayerPrivateAVFoundation::setDelayCallbacks(bool delay) const
676 {
677     MutexLocker lock(m_queueMutex);
678     if (delay)
679         ++m_delayCallbacks;
680     else {
681         ASSERT(m_delayCallbacks);
682         --m_delayCallbacks;
683     }
684 }
685
686 void MediaPlayerPrivateAVFoundation::mainThreadCallback(void* context)
687 {
688     LOG(Media, "MediaPlayerPrivateAVFoundation::mainThreadCallback(%p)", context);
689     MediaPlayerPrivateAVFoundation* player = static_cast<MediaPlayerPrivateAVFoundation*>(context);
690     player->clearMainThreadPendingFlag();
691     player->dispatchNotification();
692 }
693
694 void MediaPlayerPrivateAVFoundation::clearMainThreadPendingFlag()
695 {
696     MutexLocker lock(m_queueMutex);
697     m_mainThreadCallPending = false;
698 }
699
700 void MediaPlayerPrivateAVFoundation::scheduleMainThreadNotification(Notification::Type type, double time)
701 {
702     scheduleMainThreadNotification(Notification(type, time));
703 }
704
705 void MediaPlayerPrivateAVFoundation::scheduleMainThreadNotification(Notification::Type type, bool finished)
706 {
707     scheduleMainThreadNotification(Notification(type, finished));
708 }
709
710 #if !LOG_DISABLED
711 static const char* notificationName(MediaPlayerPrivateAVFoundation::Notification& notification)
712 {
713 #define DEFINE_TYPE_STRING_CASE(type) case MediaPlayerPrivateAVFoundation::Notification::type: return #type;
714     switch (notification.type()) {
715         FOR_EACH_MEDIAPLAYERPRIVATEAVFOUNDATION_NOTIFICATION_TYPE(DEFINE_TYPE_STRING_CASE)
716         default: return "";
717     }
718 #undef DEFINE_TYPE_STRING_CASE
719 }
720 #endif // !LOG_DISABLED
721     
722
723 void MediaPlayerPrivateAVFoundation::scheduleMainThreadNotification(Notification notification)
724 {
725     LOG(Media, "MediaPlayerPrivateAVFoundation::scheduleMainThreadNotification(%p) - notification %s", this, notificationName(notification));
726     m_queueMutex.lock();
727
728     // It is important to always process the properties in the order that we are notified, 
729     // so always go through the queue because notifications happen on different threads.
730     m_queuedNotifications.append(notification);
731
732     bool delayDispatch = m_delayCallbacks || !isMainThread();
733     if (delayDispatch && !m_mainThreadCallPending) {
734         m_mainThreadCallPending = true;
735         callOnMainThread(mainThreadCallback, this);
736     }
737
738     m_queueMutex.unlock();
739
740     if (delayDispatch) {
741         LOG(Media, "MediaPlayerPrivateAVFoundation::scheduleMainThreadNotification(%p) - early return", this);
742         return;
743     }
744
745     dispatchNotification();
746 }
747
748 void MediaPlayerPrivateAVFoundation::dispatchNotification()
749 {
750     ASSERT(isMainThread());
751
752     Notification notification = Notification();
753     {
754         MutexLocker lock(m_queueMutex);
755         
756         if (m_queuedNotifications.isEmpty())
757             return;
758         
759         if (!m_delayCallbacks) {
760             // Only dispatch one notification callback per invocation because they can cause recursion.
761             notification = m_queuedNotifications.first();
762             m_queuedNotifications.remove(0);
763         }
764         
765         if (!m_queuedNotifications.isEmpty() && !m_mainThreadCallPending)
766             callOnMainThread(mainThreadCallback, this);
767         
768         if (!notification.isValid())
769             return;
770     }
771
772     LOG(Media, "MediaPlayerPrivateAVFoundation::dispatchNotification(%p) - dispatching %s", this, notificationName(notification));
773
774     switch (notification.type()) {
775     case Notification::ItemDidPlayToEndTime:
776         didEnd();
777         break;
778     case Notification::ItemTracksChanged:
779         tracksChanged();
780         updateStates();
781         break;
782     case Notification::ItemStatusChanged:
783         updateStates();
784         break;
785     case Notification::ItemSeekableTimeRangesChanged:
786         seekableTimeRangesChanged();
787         updateStates();
788         break;
789     case Notification::ItemLoadedTimeRangesChanged:
790         loadedTimeRangesChanged();
791         updateStates();
792         break;
793     case Notification::ItemPresentationSizeChanged:
794         sizeChanged();
795         updateStates();
796         break;
797     case Notification::ItemIsPlaybackLikelyToKeepUpChanged:
798         updateStates();
799         break;
800     case Notification::ItemIsPlaybackBufferEmptyChanged:
801         updateStates();
802         break;
803     case Notification::ItemIsPlaybackBufferFullChanged:
804         updateStates();
805         break;
806     case Notification::PlayerRateChanged:
807         updateStates();
808         rateChanged();
809         break;
810     case Notification::PlayerTimeChanged:
811         timeChanged(notification.time());
812         break;
813     case Notification::SeekCompleted:
814         seekCompleted(notification.finished());
815         break;
816     case Notification::AssetMetadataLoaded:
817         metadataLoaded();
818         updateStates();
819         break;
820     case Notification::AssetPlayabilityKnown:
821         updateStates();
822         playabilityKnown();
823         break;
824     case Notification::DurationChanged:
825         invalidateCachedDuration();
826         break;
827     case Notification::ContentsNeedsDisplay:
828         contentsNeedsDisplay();
829         break;
830     case Notification::InbandTracksNeedConfiguration:
831 #if HAVE(AVFOUNDATION_TEXT_TRACK_SUPPORT)
832         m_inbandTrackConfigurationPending = false;
833         configureInbandTracks();
834 #endif
835         break;
836
837     case Notification::None:
838         ASSERT_NOT_REACHED();
839         break;
840     }
841 }
842
843 #if HAVE(AVFOUNDATION_TEXT_TRACK_SUPPORT)
844 void MediaPlayerPrivateAVFoundation::configureInbandTracks()
845 {
846     RefPtr<InbandTextTrackPrivateAVF> trackToEnable;
847
848     // AVFoundation can only emit cues for one track at a time, so enable the first track that is showing, or the first that
849     // is hidden if none are showing. Otherwise disable all tracks.
850     for (unsigned i = 0; i < m_textTracks.size(); ++i) {
851         RefPtr<InbandTextTrackPrivateAVF> track = m_textTracks[i];
852         if (track->mode() == InbandTextTrackPrivate::Showing) {
853             trackToEnable = track;
854             break;
855         }
856         if (track->mode() == InbandTextTrackPrivate::Hidden)
857             trackToEnable = track;
858     }
859
860     setCurrentTrack(trackToEnable.get());
861 }
862
863 void MediaPlayerPrivateAVFoundation::trackModeChanged()
864 {
865     if (m_inbandTrackConfigurationPending)
866         return;
867     m_inbandTrackConfigurationPending = true;
868     scheduleMainThreadNotification(Notification::InbandTracksNeedConfiguration);
869 }
870 #endif
871
872 } // namespace WebCore
873
874 #endif