ad5d297a7213e51cfba361fc24891b43b37b69bc
[platform/framework/web/crosswalk-tizen.git] /
1 /*
2  * Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012, 2013 Apple Inc. All rights
3  * reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
15  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
18  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #ifndef HTMLMediaElement_h
28 #define HTMLMediaElement_h
29
30 #include "bindings/core/v8/ActiveScriptWrappable.h"
31 #include "bindings/core/v8/ScriptPromise.h"
32 #include "bindings/core/v8/TraceWrapperMember.h"
33 #include "core/CoreExport.h"
34 #include "core/dom/ActiveDOMObject.h"
35 #include "core/dom/ExceptionCode.h"
36 #include "core/events/GenericEventQueue.h"
37 #include "core/html/AutoplayExperimentHelper.h"
38 #include "core/html/HTMLElement.h"
39 #include "core/html/track/TextTrack.h"
40 #include "platform/MIMETypeRegistry.h"
41 #include "platform/Supplementable.h"
42 #include "platform/audio/AudioSourceProvider.h"
43 #include "public/platform/WebAudioSourceProviderClient.h"
44 #include "public/platform/WebMediaPlayerClient.h"
45
46 #include <memory>
47
48 #if defined(TIZEN_VIDEO_MANUAL_ROTATION_SUPPORT)
49 #include "third_party/WebKit/public/web/WebFrameClient.h"
50 #endif
51
52 namespace blink {
53
54 class AudioSourceProviderClient;
55 class AudioTrack;
56 class AudioTrackList;
57 class AutoplayUmaHelper;
58 class ContentType;
59 class CueTimeline;
60 class ElementVisibilityObserver;
61 class EnumerationHistogram;
62 class Event;
63 class ExceptionState;
64 class HTMLSourceElement;
65 class HTMLTrackElement;
66 class KURL;
67 class MediaControls;
68 class MediaError;
69 class MediaStreamDescriptor;
70 class HTMLMediaSource;
71 class ScriptState;
72 class TextTrackContainer;
73 class TextTrackList;
74 class TimeRanges;
75 class URLRegistry;
76 class VideoTrack;
77 class VideoTrackList;
78 class WebAudioSourceProvider;
79 class WebInbandTextTrack;
80 class WebLayer;
81 class WebRemotePlaybackClient;
82
83 class CORE_EXPORT HTMLMediaElement : public HTMLElement,
84                                      public Supplementable<HTMLMediaElement>,
85                                      public ActiveScriptWrappable,
86                                      public ActiveDOMObject,
87                                      private WebMediaPlayerClient {
88   DEFINE_WRAPPERTYPEINFO();
89   USING_GARBAGE_COLLECTED_MIXIN(HTMLMediaElement);
90   USING_PRE_FINALIZER(HTMLMediaElement, dispose);
91
92  public:
93   static MIMETypeRegistry::SupportsType supportsType(const ContentType&);
94
95   enum class RecordMetricsBehavior { DoNotRecord, DoRecord };
96
97   static void setMediaStreamRegistry(URLRegistry*);
98   static bool isMediaStreamURL(const String& url);
99   static bool isHLSURL(const KURL&);
100
101   DECLARE_VIRTUAL_TRACE();
102
103   DECLARE_VIRTUAL_TRACE_WRAPPERS();
104
105   void clearWeakMembers(Visitor*);
106   WebMediaPlayer* webMediaPlayer() const { return m_webMediaPlayer.get(); }
107
108   // Returns true if the loaded media has a video track.
109   // Note that even an audio element can have video track in cases such as
110   // <audio src="video.webm">, in which case this function will return true.
111   bool hasVideo() const;
112   // Returns true if loaded media has an audio track.
113   bool hasAudio() const;
114
115   bool supportsSave() const;
116
117   WebLayer* platformLayer() const;
118
119   enum DelayedActionType {
120     LoadMediaResource = 1 << 0,
121     LoadTextTrackResource = 1 << 1
122   };
123   void scheduleTextTrackResourceLoad();
124
125   bool hasRemoteRoutes() const;
126   bool isPlayingRemotely() const { return m_playingRemotely; }
127
128 #if defined(TIZEN_VIDEO_HOLE)
129   void setPresetDisableVideoHole(bool disable);
130 #endif
131
132   // error state
133   MediaError* error() const;
134
135   // network state
136   void setSrc(const AtomicString&);
137   const KURL& currentSrc() const { return m_currentSrc; }
138   void setSrcObject(MediaStreamDescriptor*);
139   MediaStreamDescriptor* getSrcObject() const { return m_srcObject.get(); }
140
141   enum NetworkState {
142     kNetworkEmpty,
143     kNetworkIdle,
144     kNetworkLoading,
145     kNetworkNoSource
146   };
147   NetworkState getNetworkState() const;
148
149   String preload() const;
150   void setPreload(const AtomicString&);
151   WebMediaPlayer::Preload preloadType() const;
152   String effectivePreload() const;
153   WebMediaPlayer::Preload effectivePreloadType() const;
154
155   TimeRanges* buffered() const;
156   void load();
157   String canPlayType(const String& mimeType) const;
158
159   // ready state
160   enum ReadyState {
161     kHaveNothing,
162     kHaveMetadata,
163     kHaveCurrentData,
164     kHaveFutureData,
165     kHaveEnoughData
166   };
167   ReadyState getReadyState() const;
168   bool seeking() const;
169
170   // playback state
171   double currentTime() const;
172   void setCurrentTime(double);
173   double duration() const;
174   double getStartDate() const;
175   bool paused() const;
176   double defaultPlaybackRate() const;
177   void setDefaultPlaybackRate(double);
178   double playbackRate() const;
179   void setPlaybackRate(double);
180   void updatePlaybackRate();
181   TimeRanges* played();
182   TimeRanges* seekable() const;
183   bool ended() const;
184   bool autoplay() const;
185   bool shouldAutoplay(
186       const RecordMetricsBehavior = RecordMetricsBehavior::DoNotRecord);
187   bool loop() const;
188   void setLoop(bool);
189   ScriptPromise playForBindings(ScriptState*);
190   Nullable<ExceptionCode> play();
191   void pause();
192   void requestRemotePlayback();
193   void requestRemotePlaybackControl();
194   void requestRemotePlaybackStop();
195
196   // statistics
197   unsigned webkitAudioDecodedByteCount() const;
198   unsigned webkitVideoDecodedByteCount() const;
199
200   // media source extensions
201   void closeMediaSource();
202   void durationChanged(double duration, bool requestSeek);
203
204   // controls
205   bool shouldShowControls(
206       const RecordMetricsBehavior = RecordMetricsBehavior::DoNotRecord) const;
207   double volume() const;
208   void setVolume(double, ExceptionState& = ASSERT_NO_EXCEPTION);
209   bool muted() const;
210   void setMuted(bool);
211
212   void togglePlayState();
213
214   AudioTrackList& audioTracks();
215   void audioTrackChanged(AudioTrack*);
216
217   VideoTrackList& videoTracks();
218   void selectedVideoTrackChanged(VideoTrack*);
219
220 #if defined(OS_TIZEN_TV_PRODUCT)
221   TextTrack* findTextTrack(const std::string& info);
222   void addTextTrack(const std::string& info) override;
223   void addCue(const std::string& info,
224               unsigned int id,
225               long long int start_time,
226               long long int end_time) override;
227 #endif
228
229   TextTrack* addTextTrack(const AtomicString& kind,
230                           const AtomicString& label,
231                           const AtomicString& language,
232                           ExceptionState&);
233
234   TextTrackList* textTracks();
235   CueTimeline& cueTimeline();
236
237   void addTextTrack(TextTrack*);
238   void removeTextTrack(TextTrack*);
239   void textTracksChanged();
240   void notifyMediaPlayerOfTextTrackChanges();
241
242   // Implements the "forget the media element's media-resource-specific tracks"
243   // algorithm in the HTML5 spec.
244   void forgetResourceSpecificTracks();
245
246   void didAddTrackElement(HTMLTrackElement*);
247   void didRemoveTrackElement(HTMLTrackElement*);
248
249   void honorUserPreferencesForAutomaticTextTrackSelection();
250
251   bool textTracksAreReady() const;
252   void configureTextTrackDisplay();
253   void updateTextTrackDisplay();
254   double lastSeekTime() const { return m_lastSeekTime; }
255   void textTrackReadyStateChanged(TextTrack*);
256
257   void textTrackModeChanged(TextTrack*);
258   void disableAutomaticTextTrackSelection();
259
260   // EventTarget function.
261   // Both Node (via HTMLElement) and ActiveDOMObject define this method, which
262   // causes an ambiguity error at compile time. This class's constructor
263   // ensures that both implementations return document, so return the result
264   // of one of them here.
265   using HTMLElement::getExecutionContext;
266
267   bool hasSingleSecurityOrigin() const {
268     return webMediaPlayer() && webMediaPlayer()->hasSingleSecurityOrigin();
269   }
270
271   bool isFullscreen() const;
272   void enterFullscreen();
273   void exitFullscreen();
274   virtual bool usesOverlayFullscreenVideo() const { return false; }
275
276 #if defined(TIZEN_VIDEO_MANUAL_ROTATION_SUPPORT)
277   void requestRotateWebMediaPlayer();
278   void onAutoRotateSettingChanged(bool auto_rotate) final;
279 #endif
280
281   bool hasClosedCaptions() const;
282   bool textTracksVisible() const;
283
284   static void setTextTrackKindUserPreferenceForAllMediaElements(Document*);
285   void automaticTrackSelectionForUpdatedUserPreference();
286
287   // Returns the MediaControls, or null if they have not been added yet.
288   // Note that this can be non-null even if there is no controls attribute.
289   MediaControls* mediaControls() const;
290
291   // Notifies the media element that the media controls became visible, so
292   // that text track layout may be updated to avoid overlapping them.
293   void mediaControlsDidBecomeVisible();
294
295   void sourceWasRemoved(HTMLSourceElement*);
296   void sourceWasAdded(HTMLSourceElement*);
297
298   // ScriptWrappable functions.
299   bool hasPendingActivity() const final;
300
301   AudioSourceProviderClient* audioSourceNode() { return m_audioSourceNode; }
302   void setAudioSourceNode(AudioSourceProviderClient*);
303
304   AudioSourceProvider& getAudioSourceProvider() {
305     return m_audioSourceProvider;
306   }
307
308   enum InvalidURLAction { DoNothing, Complain };
309   bool isSafeToLoadURL(const KURL&, InvalidURLAction);
310
311   // Checks to see if current media data is CORS-same-origin as the
312   // specified origin.
313   bool isMediaDataCORSSameOrigin(SecurityOrigin*) const;
314
315   void scheduleEvent(Event*);
316   void scheduleTimeupdateEvent(bool periodicEvent);
317
318   // Returns the "effective media volume" value as specified in the HTML5 spec.
319   double effectiveMediaVolume() const;
320
321   // Predicates also used when dispatching wrapper creation (cf.
322   // [SpecialWrapFor] IDL attribute usage.)
323   virtual bool isHTMLAudioElement() const { return false; }
324   virtual bool isHTMLVideoElement() const { return false; }
325
326   void videoWillBeDrawnToCanvas() const;
327
328 #if defined(OS_TIZEN_TV_PRODUCT)
329   bool setTranslatedURL(const String&);
330   void onDrmError();
331 #endif
332
333   void activatePlayer();
334 #if defined(TIZEN_MULTIMEDIA_SUPPORT)
335   void suspend() override;
336   void resume() override;
337
338   void launchSystemVolumeController();
339   void setSystemVolume(int volume) override { m_systemVolume = volume; }
340   int systemVolume() const { return m_systemVolume; }
341 #endif
342   WebString getContentMIMEType();
343   // Temporary callback for crbug.com/487345,402044
344   void notifyPositionMayHaveChanged(const IntRect&);
345   void updatePositionNotificationRegistration();
346
347 #if defined(S_TERRACE_SUPPORT)
348   WebString dimension() const final;
349 #endif
350
351   WebRemotePlaybackClient* remotePlaybackClient() {
352     return m_remotePlaybackClient;
353   }
354   const WebRemotePlaybackClient* remotePlaybackClient() const {
355     return m_remotePlaybackClient;
356   }
357 #if defined(OS_TIZEN_TV_PRODUCT)
358   void forceSettingOfficialPlaybackPosition() override;
359 #endif
360
361  protected:
362   HTMLMediaElement(const QualifiedName&, Document&);
363   ~HTMLMediaElement() override;
364   void dispose();
365
366   void parseAttribute(const QualifiedName&,
367                       const AtomicString&,
368                       const AtomicString&) override;
369   void finishParsingChildren() final;
370   bool isURLAttribute(const Attribute&) const override;
371   void attachLayoutTree(const AttachContext& = AttachContext()) override;
372
373   void didMoveToNewDocument(Document& oldDocument) override;
374   virtual KURL posterImageURL() const { return KURL(); }
375
376   enum DisplayMode { Unknown, Poster, Video };
377   DisplayMode getDisplayMode() const { return m_displayMode; }
378   virtual void setDisplayMode(DisplayMode mode) { m_displayMode = mode; }
379
380   void recordAutoplayMetric(AutoplayMetrics);
381
382  private:
383   void resetMediaPlayerAndMediaSource();
384
385   bool alwaysCreateUserAgentShadowRoot() const final { return true; }
386   bool areAuthorShadowsAllowed() const final { return false; }
387
388   bool supportsFocus() const final;
389   bool isMouseFocusable() const final;
390   bool layoutObjectIsNeeded(const ComputedStyle&) override;
391   LayoutObject* createLayoutObject(const ComputedStyle&) override;
392   InsertionNotificationRequest insertedInto(ContainerNode*) final;
393   void didNotifySubtreeInsertionsToDocument() override;
394   void removedFrom(ContainerNode*) final;
395   void didRecalcStyle(StyleRecalcChange) final;
396
397   bool canStartSelection() const override { return false; }
398
399   void didBecomeFullscreenElement() final;
400   void willStopBeingFullscreenElement() final;
401   bool isInteractiveContent() const final;
402
403   // ActiveDOMObject functions.
404   void contextDestroyed() final;
405
406   virtual void updateDisplayState() {}
407
408   void setReadyState(ReadyState);
409   void setNetworkState(WebMediaPlayer::NetworkState);
410
411   // WebMediaPlayerClient implementation.
412   void networkStateChanged() final;
413   void readyStateChanged() final;
414   void timeChanged() final;
415   void repaint() final;
416   void durationChanged() final;
417   void sizeChanged() final;
418   void playbackStateChanged() final;
419
420   void setWebLayer(WebLayer*) final;
421   WebMediaPlayer::TrackId addAudioTrack(const WebString&,
422                                         WebMediaPlayerClient::AudioTrackKind,
423                                         const WebString&,
424                                         const WebString&,
425                                         bool) final;
426   void removeAudioTrack(WebMediaPlayer::TrackId) final;
427   WebMediaPlayer::TrackId addVideoTrack(const WebString&,
428                                         WebMediaPlayerClient::VideoTrackKind,
429                                         const WebString&,
430                                         const WebString&,
431                                         bool) final;
432   void removeVideoTrack(WebMediaPlayer::TrackId) final;
433   void addTextTrack(WebInbandTextTrack*) final;
434   void removeTextTrack(WebInbandTextTrack*) final;
435   void mediaSourceOpened(WebMediaSource*) final;
436   void requestSeek(double) final;
437   void remoteRouteAvailabilityChanged(WebRemotePlaybackAvailability) final;
438   void connectedToRemoteDevice() final;
439   void disconnectedFromRemoteDevice() final;
440   bool isAudioElement() { return isHTMLAudioElement(); }
441 #if defined(S_TERRACE_SUPPORT)
442   void setClosedCaptionVisibility(bool visible) final;
443   void requestFullscreen() final;
444   void slideTextTracks();
445   void requestFullscreen() final;
446   WebURL closedCaptionSrc() const final;
447 #endif
448   void cancelledRemotePlaybackRequest() final;
449   void remotePlaybackStarted() final;
450   bool isAutoplayingMuted() final;
451   void requestReload(const WebURL&) final;
452 #if defined(TIZEN_MULTIMEDIA_SUPPORT)
453   void mediaPlayerHidden() final;
454   void mediaPlayerShown() final;
455 #endif
456
457   void loadTimerFired(TimerBase*);
458   void progressEventTimerFired(TimerBase*);
459   void playbackProgressTimerFired(TimerBase*);
460   void startPlaybackProgressTimer();
461   void startProgressEventTimer();
462   void stopPeriodicTimers();
463
464   void seek(double time);
465   void finishSeek();
466   void checkIfSeekNeeded();
467   void addPlayedRange(double start, double end);
468
469   // FIXME: Rename to scheduleNamedEvent for clarity.
470   void scheduleEvent(const AtomicString& eventName);
471
472   // loading
473   void invokeLoadAlgorithm();
474   void invokeResourceSelectionAlgorithm();
475   void loadInternal();
476   void selectMediaResource();
477   void loadResource(const WebMediaPlayerSource&, const ContentType&);
478   void startPlayerLoad(const KURL& playerProvidedUrl = KURL());
479   void setPlayerPreload();
480   WebMediaPlayer::LoadType loadType() const;
481   void scheduleNextSourceChild();
482   void loadSourceFromObject();
483   void loadSourceFromAttribute();
484   void loadNextSourceChild();
485   void clearMediaPlayer();
486   void clearMediaPlayerAndAudioSourceProviderClientWithoutLocking();
487   bool havePotentialSourceChild();
488   void noneSupported();
489   void mediaEngineError(MediaError*);
490   void cancelPendingEventsAndCallbacks();
491   void waitForSourceChange();
492   void setIgnorePreloadNone();
493
494   KURL selectNextSourceChild(ContentType*, InvalidURLAction);
495
496   void mediaLoadingFailed(WebMediaPlayer::NetworkState);
497
498   // deferred loading (preload=none)
499   bool loadIsDeferred() const;
500   void deferLoad();
501   void cancelDeferredLoad();
502   void startDeferredLoad();
503   void executeDeferredLoad();
504   void deferredLoadTimerFired(TimerBase*);
505
506   void markCaptionAndSubtitleTracksAsUnconfigured();
507
508   // This does not check user gesture restrictions.
509   void playInternal();
510
511   // This does not change the buffering strategy.
512   void pauseInternal();
513
514   void allowVideoRendering();
515
516   void updateVolume();
517   void updatePlayState();
518   bool potentiallyPlaying() const;
519   bool stoppedDueToErrors() const;
520   bool couldPlayIfEnoughData() const;
521
522   // Generally the presence of the loop attribute should be considered to mean
523   // playback has not "ended", as "ended" and "looping" are mutually exclusive.
524   // See
525   // https://html.spec.whatwg.org/multipage/embedded-content.html#ended-playback
526   enum class LoopCondition { Included, Ignored };
527   bool endedPlayback(LoopCondition = LoopCondition::Included) const;
528
529   void setShouldDelayLoadEvent(bool);
530
531   double earliestPossiblePosition() const;
532   double currentPlaybackPosition() const;
533   double officialPlaybackPosition() const;
534   void setOfficialPlaybackPosition(double) const;
535   void requireOfficialPlaybackPositionUpdate() const;
536
537   void ensureMediaControls();
538   void configureMediaControls();
539
540   TextTrackContainer& ensureTextTrackContainer();
541
542   EventDispatchHandlingState* preDispatchEventHandler(Event*) final;
543
544   void changeNetworkStateFromLoadingToIdle();
545
546   bool isAutoplaying() const { return m_autoplaying; }
547
548   WebMediaPlayer::CORSMode corsMode() const;
549
550   // Returns the "direction of playback" value as specified in the HTML5 spec.
551   enum DirectionOfPlayback { Backward, Forward };
552   DirectionOfPlayback getDirectionOfPlayback() const;
553
554   // Creates placeholder AudioTrack and/or VideoTrack objects when
555   // WebMemediaPlayer objects advertise they have audio and/or video, but don't
556   // explicitly signal them via addAudioTrack() and addVideoTrack().
557   // FIXME: Remove this once all WebMediaPlayer implementations properly report
558   // their track info.
559   void createPlaceholderTracksIfNecessary();
560
561   // Sets the selected/enabled tracks if they aren't set before we initially
562   // transition to kHaveMetadata.
563   void selectInitialTracksIfNecessary();
564
565   // Return true if and only if a user gesture is required to unlock this
566   // media element for unrestricted autoplay / script control.  Don't confuse
567   // this with isGestureNeededForPlayback().  The latter is usually what one
568   // should use, if checking to see if an action is allowed.
569   bool isLockedPendingUserGesture() const;
570
571   // If the user gesture is required, then this will remove it.  Note that
572   // one should not generally call this method directly; use the one on
573   // m_helper and give it a reason.
574   void unlockUserGesture();
575
576   // Return true if and only if a user gesture is requried for playback.  Even
577   // if isLockedPendingUserGesture() return true, this might return false if
578   // the requirement is currently overridden.  This does not check if a user
579   // gesture is currently being processed.
580   bool isGestureNeededForPlayback() const;
581
582   // Return true if and only if the settings allow autoplay of media on this
583   // frame.
584   bool isAutoplayAllowedPerSettings() const;
585
586   void setNetworkState(NetworkState);
587
588   void audioTracksTimerFired(TimerBase*);
589
590   // TODO(liberato): remove once autoplay gesture override experiment concludes.
591   void triggerAutoplayViewportCheckForTesting();
592
593   void scheduleResolvePlayPromises();
594   void scheduleRejectPlayPromises(ExceptionCode);
595   void scheduleNotifyPlaying();
596   void resolveScheduledPlayPromises();
597   void rejectScheduledPlayPromises();
598   void rejectPlayPromises(ExceptionCode, const String&);
599   void rejectPlayPromisesInternal(ExceptionCode, const String&);
600
601   EnumerationHistogram& showControlsHistogram() const;
602
603   void onVisibilityChangedForAutoplay(bool isVisible);
604
605   UnthrottledThreadTimer<HTMLMediaElement> m_loadTimer;
606   UnthrottledThreadTimer<HTMLMediaElement> m_progressEventTimer;
607   UnthrottledThreadTimer<HTMLMediaElement> m_playbackProgressTimer;
608   UnthrottledThreadTimer<HTMLMediaElement> m_audioTracksTimer;
609   Member<TimeRanges> m_playedTimeRanges;
610   Member<GenericEventQueue> m_asyncEventQueue;
611
612   double m_playbackRate;
613   double m_defaultPlaybackRate;
614   NetworkState m_networkState;
615   ReadyState m_readyState;
616   ReadyState m_readyStateMaximum;
617   KURL m_currentSrc;
618   String m_contentMIMEType;
619   Member<MediaStreamDescriptor> m_srcObject;
620
621   Member<MediaError> m_error;
622
623   double m_volume;
624   double m_lastSeekTime;
625
626   double m_previousProgressTime;
627
628   // Cached duration to suppress duplicate events if duration unchanged.
629   double m_duration;
630
631   // The last time a timeupdate event was sent (wall clock).
632   double m_lastTimeUpdateEventWallTime;
633
634   // The last time a timeupdate event was sent in movie time.
635   double m_lastTimeUpdateEventMediaTime;
636
637   // The default playback start position.
638   double m_defaultPlaybackStartPosition;
639
640   // Loading state.
641   enum LoadState {
642     WaitingForSource,
643     LoadingFromSrcObject,
644     LoadingFromSrcAttr,
645     LoadingFromSourceElement
646   };
647   LoadState m_loadState;
648   Member<HTMLSourceElement> m_currentSourceNode;
649   Member<Node> m_nextChildNodeToConsider;
650
651   // "Deferred loading" state (for preload=none).
652   enum DeferredLoadState {
653     // The load is not deferred.
654     NotDeferred,
655     // The load is deferred, and waiting for the task to set the
656     // delaying-the-load-event flag (to false).
657     WaitingForStopDelayingLoadEventTask,
658     // The load is the deferred, and waiting for a triggering event.
659     WaitingForTrigger,
660     // The load is deferred, and waiting for the task to set the
661     // delaying-the-load-event flag, after which the load will be executed.
662     ExecuteOnStopDelayingLoadEventTask
663   };
664   DeferredLoadState m_deferredLoadState;
665   Timer<HTMLMediaElement> m_deferredLoadTimer;
666
667   std::unique_ptr<WebMediaPlayer> m_webMediaPlayer;
668   WebLayer* m_webLayer;
669
670   DisplayMode m_displayMode;
671
672   Member<HTMLMediaSource> m_mediaSource;
673
674   // Stores "official playback position", updated periodically from "current
675   // playback position". Official playback position should not change while
676   // scripts are running. See setOfficialPlaybackPosition().
677   mutable double m_officialPlaybackPosition;
678   mutable bool m_officialPlaybackPositionNeedsUpdate;
679
680   double m_fragmentEndTime;
681
682   typedef unsigned PendingActionFlags;
683   PendingActionFlags m_pendingActionFlags;
684
685   // FIXME: HTMLMediaElement has way too many state bits.
686   bool m_lockedPendingUserGesture : 1;
687   bool m_playing : 1;
688   bool m_shouldDelayLoadEvent : 1;
689   bool m_haveFiredLoadedData : 1;
690   bool m_autoplaying : 1;
691   bool m_muted : 1;
692   bool m_paused : 1;
693   bool m_seeking : 1;
694
695   // data has not been loaded since sending a "stalled" event
696   bool m_sentStalledEvent : 1;
697
698   bool m_ignorePreloadNone : 1;
699
700   bool m_textTracksVisible : 1;
701   bool m_shouldPerformAutomaticTrackSelection : 1;
702
703   bool m_tracksAreReady : 1;
704   bool m_processingPreferenceChange : 1;
705   bool m_playingRemotely : 1;
706   // Whether this element is in overlay fullscreen mode.
707   bool m_inOverlayFullscreenVideo : 1;
708
709 #if defined(OS_TIZEN_TV_PRODUCT)
710   bool m_hasDrmError : 1;
711 #endif
712
713 #if defined(TIZEN_MULTIMEDIA_SUPPORT)
714   // This is to suppress stuff set to JS. Do not use it for other purposes.
715   bool m_suppressEvents : 1;
716   int m_systemVolume;
717 #endif
718
719   TraceWrapperMember<AudioTrackList> m_audioTracks;
720   TraceWrapperMember<VideoTrackList> m_videoTracks;
721   TraceWrapperMember<TextTrackList> m_textTracks;
722   HeapVector<Member<TextTrack>> m_textTracksWhenResourceSelectionBegan;
723
724   Member<CueTimeline> m_cueTimeline;
725
726   HeapVector<Member<ScriptPromiseResolver>> m_playPromiseResolvers;
727   std::unique_ptr<CancellableTaskFactory> m_playPromiseResolveTask;
728   std::unique_ptr<CancellableTaskFactory> m_playPromiseRejectTask;
729   HeapVector<Member<ScriptPromiseResolver>> m_playPromiseResolveList;
730   HeapVector<Member<ScriptPromiseResolver>> m_playPromiseRejectList;
731   ExceptionCode m_playPromiseErrorCode;
732
733   // This is a weak reference, since m_audioSourceNode holds a reference to us.
734   // TODO(Oilpan): Consider making this a strongly traced pointer with oilpan
735   // where strong cycles are not a problem.
736   GC_PLUGIN_IGNORE("http://crbug.com/404577")
737   WeakMember<AudioSourceProviderClient> m_audioSourceNode;
738
739   // AudioClientImpl wraps an AudioSourceProviderClient.
740   // When the audio format is known, Chromium calls setFormat().
741   class AudioClientImpl final
742       : public GarbageCollectedFinalized<AudioClientImpl>,
743         public WebAudioSourceProviderClient {
744    public:
745     explicit AudioClientImpl(AudioSourceProviderClient* client)
746         : m_client(client) {}
747
748     ~AudioClientImpl() override {}
749
750     // WebAudioSourceProviderClient
751     void setFormat(size_t numberOfChannels, float sampleRate) override;
752
753     DECLARE_TRACE();
754
755    private:
756     Member<AudioSourceProviderClient> m_client;
757   };
758
759   // AudioSourceProviderImpl wraps a WebAudioSourceProvider.
760   // provideInput() calls into Chromium to get a rendered audio stream.
761   class AudioSourceProviderImpl final : public AudioSourceProvider {
762     DISALLOW_NEW();
763
764    public:
765     AudioSourceProviderImpl() : m_webAudioSourceProvider(nullptr) {}
766
767     ~AudioSourceProviderImpl() override {}
768
769     // Wraps the given WebAudioSourceProvider.
770     void wrap(WebAudioSourceProvider*);
771
772     // AudioSourceProvider
773     void setClient(AudioSourceProviderClient*) override;
774     void provideInput(AudioBus*, size_t framesToProcess) override;
775
776     DECLARE_TRACE();
777
778    private:
779     WebAudioSourceProvider* m_webAudioSourceProvider;
780     Member<AudioClientImpl> m_client;
781     Mutex provideInputLock;
782   };
783
784   AudioSourceProviderImpl m_audioSourceProvider;
785
786   class AutoplayHelperClientImpl;
787
788   friend class AutoplayUmaHelper;  // for isAutoplayAllowedPerSettings
789   friend class Internals;
790   friend class TrackDisplayUpdateScope;
791   friend class AutoplayExperimentHelper;
792   friend class MediaControlsTest;
793
794   Member<AutoplayExperimentHelper::Client> m_autoplayHelperClient;
795   Member<AutoplayExperimentHelper> m_autoplayHelper;
796   Member<AutoplayUmaHelper> m_autoplayUmaHelper;
797
798   WebRemotePlaybackClient* m_remotePlaybackClient;
799
800   // class AutoplayVisibilityObserver;
801   Member<ElementVisibilityObserver> m_autoplayVisibilityObserver;
802
803   static URLRegistry* s_mediaStreamRegistry;
804 };
805
806 inline bool isHTMLMediaElement(const HTMLElement& element) {
807   return isHTMLAudioElement(element) || isHTMLVideoElement(element);
808 }
809
810 DEFINE_HTMLELEMENT_TYPE_CASTS_WITH_FUNCTION(HTMLMediaElement);
811
812 }  // namespace blink
813
814 #endif  // HTMLMediaElement_h