1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4  * License, v. 2.0. If a copy of the MPL was not distributed with this
5  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 #ifndef mozilla_dom_HTMLMediaElement_h
7 #define mozilla_dom_HTMLMediaElement_h
8 
9 #include "nsGenericHTMLElement.h"
10 #include "AudioChannelService.h"
11 #include "MediaEventSource.h"
12 #include "SeekTarget.h"
13 #include "MediaDecoderOwner.h"
14 #include "MediaElementEventRunners.h"
15 #include "MediaPlaybackDelayPolicy.h"
16 #include "MediaPromiseDefs.h"
17 #include "TelemetryProbesReporter.h"
18 #include "nsCycleCollectionParticipant.h"
19 #include "Visibility.h"
20 #include "mozilla/CORSMode.h"
21 #include "DecoderTraits.h"
22 #include "mozilla/Attributes.h"
23 #include "mozilla/StateWatching.h"
24 #include "mozilla/WeakPtr.h"
25 #include "mozilla/dom/DecoderDoctorNotificationBinding.h"
26 #include "mozilla/dom/HTMLMediaElementBinding.h"
27 #include "mozilla/dom/MediaDebugInfoBinding.h"
28 #include "mozilla/dom/MediaKeys.h"
29 #include "mozilla/dom/TextTrackManager.h"
30 #include "nsGkAtoms.h"
31 #include "PrincipalChangeObserver.h"
32 #include "nsStubMutationObserver.h"
33 #include "MediaSegment.h"  // for PrincipalHandle, GraphTime
34 
35 #include <utility>
36 
37 // X.h on Linux #defines CurrentTime as 0L, so we have to #undef it here.
38 #ifdef CurrentTime
39 #  undef CurrentTime
40 #endif
41 
42 // Define to output information on decoding and painting framerate
43 /* #define DEBUG_FRAME_RATE 1 */
44 
45 typedef uint16_t nsMediaNetworkState;
46 typedef uint16_t nsMediaReadyState;
47 typedef uint32_t SuspendTypes;
48 typedef uint32_t AudibleChangedReasons;
49 
50 class nsIStreamListener;
51 
52 namespace mozilla {
53 class AbstractThread;
54 class ChannelMediaDecoder;
55 class DecoderDoctorDiagnostics;
56 class DOMMediaStream;
57 class ErrorResult;
58 class FirstFrameVideoOutput;
59 class MediaResource;
60 class MediaDecoder;
61 class MediaInputPort;
62 class MediaTrack;
63 class MediaTrackGraph;
64 class MediaStreamWindowCapturer;
65 struct SharedDummyTrack;
66 class VideoFrameContainer;
67 class VideoOutput;
68 namespace dom {
69 class MediaKeys;
70 class TextTrack;
71 class TimeRanges;
72 class WakeLock;
73 class MediaStreamTrack;
74 class MediaStreamTrackSource;
75 class MediaTrack;
76 class VideoStreamTrack;
77 }  // namespace dom
78 }  // namespace mozilla
79 
80 class AudioDeviceInfo;
81 class nsIChannel;
82 class nsIHttpChannel;
83 class nsILoadGroup;
84 class nsIRunnable;
85 class nsISerialEventTarget;
86 class nsITimer;
87 class nsRange;
88 
89 namespace mozilla {
90 namespace dom {
91 
92 // Number of milliseconds between timeupdate events as defined by spec
93 #define TIMEUPDATE_MS 250
94 
95 class MediaError;
96 class MediaSource;
97 class PlayPromise;
98 class Promise;
99 class TextTrackList;
100 class AudioTrackList;
101 class VideoTrackList;
102 
103 enum class StreamCaptureType : uint8_t { CAPTURE_ALL_TRACKS, CAPTURE_AUDIO };
104 
105 enum class StreamCaptureBehavior : uint8_t {
106   CONTINUE_WHEN_ENDED,
107   FINISH_WHEN_ENDED
108 };
109 
110 class HTMLMediaElement : public nsGenericHTMLElement,
111                          public MediaDecoderOwner,
112                          public PrincipalChangeObserver<MediaStreamTrack>,
113                          public SupportsWeakPtr,
114                          public nsStubMutationObserver,
115                          public TelemetryProbesReporterOwner {
116  public:
117   typedef mozilla::TimeStamp TimeStamp;
118   typedef mozilla::layers::ImageContainer ImageContainer;
119   typedef mozilla::VideoFrameContainer VideoFrameContainer;
120   typedef mozilla::MediaResource MediaResource;
121   typedef mozilla::MediaDecoderOwner MediaDecoderOwner;
122   typedef mozilla::MetadataTags MetadataTags;
123 
124   // Helper struct to keep track of the MediaStreams returned by
125   // mozCaptureStream(). For each OutputMediaStream, dom::MediaTracks get
126   // captured into MediaStreamTracks which get added to
127   // OutputMediaStream::mStream.
128   struct OutputMediaStream {
129     OutputMediaStream(RefPtr<DOMMediaStream> aStream, bool aCapturingAudioOnly,
130                       bool aFinishWhenEnded);
131     ~OutputMediaStream();
132 
133     RefPtr<DOMMediaStream> mStream;
134     nsTArray<RefPtr<MediaStreamTrack>> mLiveTracks;
135     const bool mCapturingAudioOnly;
136     const bool mFinishWhenEnded;
137     // If mFinishWhenEnded is true, this is the URI of the first resource
138     // mStream got tracks for.
139     nsCOMPtr<nsIURI> mFinishWhenEndedLoadingSrc;
140     // If mFinishWhenEnded is true, this is the first MediaStream mStream got
141     // tracks for.
142     RefPtr<DOMMediaStream> mFinishWhenEndedAttrStream;
143     // If mFinishWhenEnded is true, this is the MediaSource being played.
144     RefPtr<MediaSource> mFinishWhenEndedMediaSource;
145   };
146 
147   NS_DECL_NSIMUTATIONOBSERVER_CONTENTREMOVED
148 
GetCORSMode()149   CORSMode GetCORSMode() { return mCORSMode; }
150 
151   explicit HTMLMediaElement(
152       already_AddRefed<mozilla::dom::NodeInfo>&& aNodeInfo);
153   void Init();
154 
155   // `eMandatory`: `timeupdate` occurs according to the spec requirement.
156   // Eg.
157   // https://html.spec.whatwg.org/multipage/media.html#seeking:event-media-timeupdate
158   // `ePeriodic` : `timeupdate` occurs regularly and should follow the rule
159   // of not dispatching that event within 250 ms. Eg.
160   // https://html.spec.whatwg.org/multipage/media.html#offsets-into-the-media-resource:event-media-timeupdate
161   enum class TimeupdateType : bool {
162     eMandatory = false,
163     ePeriodic = true,
164   };
165 
166   // This is used for event runner creation. Currently only timeupdate needs
167   // that, but it can be used to extend for other events in the future if
168   // necessary.
169   enum class EventFlag : uint8_t {
170     eNone = 0,
171     eMandatory = 1,
172   };
173 
174   /**
175    * This is used when the browser is constructing a video element to play
176    * a channel that we've already started loading. The src attribute and
177    * <source> children are ignored.
178    * @param aChannel the channel to use
179    * @param aListener returns a stream listener that should receive
180    * notifications for the stream
181    */
182   nsresult LoadWithChannel(nsIChannel* aChannel, nsIStreamListener** aListener);
183 
184   // nsISupports
185   NS_DECL_ISUPPORTS_INHERITED
186   NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(HTMLMediaElement,
187                                            nsGenericHTMLElement)
188   NS_IMPL_FROMNODE_HELPER(HTMLMediaElement,
189                           IsAnyOfHTMLElements(nsGkAtoms::video,
190                                               nsGkAtoms::audio))
191 
192   NS_DECL_ADDSIZEOFEXCLUDINGTHIS
193 
194   // EventTarget
195   void GetEventTargetParent(EventChainPreVisitor& aVisitor) override;
196 
197   void NodeInfoChanged(Document* aOldDoc) override;
198 
199   virtual bool ParseAttribute(int32_t aNamespaceID, nsAtom* aAttribute,
200                               const nsAString& aValue,
201                               nsIPrincipal* aMaybeScriptedPrincipal,
202                               nsAttrValue& aResult) override;
203 
204   virtual nsresult BindToTree(BindContext&, nsINode& aParent) override;
205   virtual void UnbindFromTree(bool aNullParent = true) override;
206   virtual void DoneCreatingElement() override;
207 
208   virtual bool IsHTMLFocusable(bool aWithMouse, bool* aIsFocusable,
209                                int32_t* aTabIndex) override;
210   virtual int32_t TabIndexDefault() override;
211 
212   // Called by the video decoder object, on the main thread,
213   // when it has read the metadata containing video dimensions,
214   // etc.
215   virtual void MetadataLoaded(const MediaInfo* aInfo,
216                               UniquePtr<const MetadataTags> aTags) final;
217 
218   // Called by the decoder object, on the main thread,
219   // when it has read the first frame of the video or audio.
220   void FirstFrameLoaded() final;
221 
222   // Called by the video decoder object, on the main thread,
223   // when the resource has a network error during loading.
224   void NetworkError(const MediaResult& aError) final;
225 
226   // Called by the video decoder object, on the main thread, when the
227   // resource has a decode error during metadata loading or decoding.
228   void DecodeError(const MediaResult& aError) final;
229 
230   // Called by the decoder object, on the main thread, when the
231   // resource has a decode issue during metadata loading or decoding, but can
232   // continue decoding.
233   void DecodeWarning(const MediaResult& aError) final;
234 
235   // Return true if error attribute is not null.
236   bool HasError() const final;
237 
238   // Called by the video decoder object, on the main thread, when the
239   // resource load has been cancelled.
240   void LoadAborted() final;
241 
242   // Called by the video decoder object, on the main thread,
243   // when the video playback has ended.
244   void PlaybackEnded() final;
245 
246   // Called by the video decoder object, on the main thread,
247   // when the resource has started seeking.
248   void SeekStarted() final;
249 
250   // Called by the video decoder object, on the main thread,
251   // when the resource has completed seeking.
252   void SeekCompleted() final;
253 
254   // Called by the video decoder object, on the main thread,
255   // when the resource has aborted seeking.
256   void SeekAborted() final;
257 
258   // Called by the media stream, on the main thread, when the download
259   // has been suspended by the cache or because the element itself
260   // asked the decoder to suspend the download.
261   void DownloadSuspended() final;
262 
263   // Called by the media stream, on the main thread, when the download
264   // has been resumed by the cache or because the element itself
265   // asked the decoder to resumed the download.
266   void DownloadResumed();
267 
268   // Called to indicate the download is progressing.
269   void DownloadProgressed() final;
270 
271   // Called by the media decoder to indicate whether the media cache has
272   // suspended the channel.
273   void NotifySuspendedByCache(bool aSuspendedByCache) final;
274 
275   // Return true if the media element is actually invisible to users.
276   bool IsActuallyInvisible() const override;
277 
278   // Return true if the element is in the view port.
279   bool IsInViewPort() const;
280 
281   // Called by the media decoder and the video frame to get the
282   // ImageContainer containing the video data.
283   VideoFrameContainer* GetVideoFrameContainer() final;
284   layers::ImageContainer* GetImageContainer();
285 
286   /**
287    * Call this to reevaluate whether we should start/stop due to our owner
288    * document being active, inactive, visible or hidden.
289    */
290   void NotifyOwnerDocumentActivityChanged();
291 
292   // Called when the media element enters or leaves the fullscreen.
293   void NotifyFullScreenChanged();
294 
295   bool IsInFullScreen() const;
296 
297   // From PrincipalChangeObserver<MediaStreamTrack>.
298   void PrincipalChanged(MediaStreamTrack* aTrack) override;
299 
300   void UpdateSrcStreamVideoPrincipal(const PrincipalHandle& aPrincipalHandle);
301 
302   // Called after the MediaStream we're playing rendered a frame to aContainer
303   // with a different principalHandle than the previous frame.
304   void PrincipalHandleChangedForVideoFrameContainer(
305       VideoFrameContainer* aContainer,
306       const PrincipalHandle& aNewPrincipalHandle) override;
307 
308   // Dispatch events
309   void DispatchAsyncEvent(const nsAString& aName) final;
310   void DispatchAsyncEvent(RefPtr<nsMediaEventRunner> aRunner);
311 
312   // Triggers a recomputation of readyState.
UpdateReadyState()313   void UpdateReadyState() override {
314     mWatchManager.ManualNotify(&HTMLMediaElement::UpdateReadyStateInternal);
315   }
316 
317   // Dispatch events that were raised while in the bfcache
318   nsresult DispatchPendingMediaEvents();
319 
320   // Return true if we can activate autoplay assuming enough data has arrived.
321   bool CanActivateAutoplay();
322 
323   // Notify that state has changed that might cause an autoplay element to
324   // start playing.
325   // If the element is 'autoplay' and is ready to play back (not paused,
326   // autoplay pref enabled, etc), it should start playing back.
327   void CheckAutoplayDataReady();
328 
329   // Check if the media element had crossorigin set when loading started
330   bool ShouldCheckAllowOrigin();
331 
332   // Returns true if the currently loaded resource is CORS same-origin with
333   // respect to the document.
334   bool IsCORSSameOrigin();
335 
336   // Is the media element potentially playing as defined by the HTML 5
337   // specification.
338   // http://www.whatwg.org/specs/web-apps/current-work/#potentially-playing
339   bool IsPotentiallyPlaying() const;
340 
341   // Has playback ended as defined by the HTML 5 specification.
342   // http://www.whatwg.org/specs/web-apps/current-work/#ended
343   bool IsPlaybackEnded() const;
344 
345   // principal of the currently playing resource. Anything accessing the
346   // contents of this element must have a principal that subsumes this
347   // principal. Returns null if nothing is playing.
348   already_AddRefed<nsIPrincipal> GetCurrentPrincipal();
349 
350   // Return true if the loading of this resource required cross-origin
351   // redirects.
352   bool HadCrossOriginRedirects();
353 
354   // Principal of the currently playing video resource. Anything accessing the
355   // image container of this element must have a principal that subsumes this
356   // principal. If there are no live video tracks but content has been rendered
357   // to the image container, we return the last video principal we had. Should
358   // the image container be empty with no live video tracks, we return nullptr.
359   already_AddRefed<nsIPrincipal> GetCurrentVideoPrincipal();
360 
361   // called to notify that the principal of the decoder's media resource has
362   // changed.
363   void NotifyDecoderPrincipalChanged() final;
364 
365   void GetEMEInfo(dom::EMEDebugInfo& aInfo);
366 
367   // Update the visual size of the media. Called from the decoder on the
368   // main thread when/if the size changes.
369   virtual void UpdateMediaSize(const nsIntSize& aSize);
370   // Like UpdateMediaSize, but only updates the size if no size has yet
371   // been set.
372   void UpdateInitialMediaSize(const nsIntSize& aSize);
373 
374   void Invalidate(bool aImageSizeChanged, Maybe<nsIntSize>& aNewIntrinsicSize,
375                   bool aForceInvalidate) override;
376 
377   // Returns the CanPlayStatus indicating if we can handle the
378   // full MIME type including the optional codecs parameter.
379   static CanPlayStatus GetCanPlay(const nsAString& aType,
380                                   DecoderDoctorDiagnostics* aDiagnostics);
381 
382   /**
383    * Called when a child source element is added to this media element. This
384    * may queue a task to run the select resource algorithm if appropriate.
385    */
386   void NotifyAddedSource();
387 
388   /**
389    * Called when there's been an error fetching the resource. This decides
390    * whether it's appropriate to fire an error event.
391    */
392   void NotifyLoadError(const nsACString& aErrorDetails = nsCString());
393 
394   /**
395    * Called by one of our associated MediaTrackLists (audio/video) when a
396    * MediaTrack is added.
397    */
398   void NotifyMediaTrackAdded(dom::MediaTrack* aTrack);
399 
400   /**
401    * Called by one of our associated MediaTrackLists (audio/video) when a
402    * MediaTrack is removed.
403    */
404   void NotifyMediaTrackRemoved(dom::MediaTrack* aTrack);
405 
406   /**
407    * Called by one of our associated MediaTrackLists (audio/video) when an
408    * AudioTrack is enabled or a VideoTrack is selected.
409    */
410   void NotifyMediaTrackEnabled(dom::MediaTrack* aTrack);
411 
412   /**
413    * Called by one of our associated MediaTrackLists (audio/video) when an
414    * AudioTrack is disabled or a VideoTrack is unselected.
415    */
416   void NotifyMediaTrackDisabled(dom::MediaTrack* aTrack);
417 
418   /**
419    * Returns the current load ID. Asynchronous events store the ID that was
420    * current when they were enqueued, and if it has changed when they come to
421    * fire, they consider themselves cancelled, and don't fire.
422    */
GetCurrentLoadID()423   uint32_t GetCurrentLoadID() { return mCurrentLoadID; }
424 
425   /**
426    * Returns the load group for this media element's owner document.
427    * XXX XBL2 issue.
428    */
429   already_AddRefed<nsILoadGroup> GetDocumentLoadGroup();
430 
431   /**
432    * Returns true if the media has played or completed a seek.
433    * Used by video frame to determine whether to paint the poster.
434    */
GetPlayedOrSeeked()435   bool GetPlayedOrSeeked() const { return mHasPlayedOrSeeked; }
436 
437   nsresult CopyInnerTo(Element* aDest);
438 
439   /**
440    * Sets the Accept header on the HTTP channel to the required
441    * video or audio MIME types.
442    */
443   virtual nsresult SetAcceptHeader(nsIHttpChannel* aChannel) = 0;
444 
445   /**
446    * Sets the required request headers on the HTTP channel for
447    * video or audio requests.
448    */
449   void SetRequestHeaders(nsIHttpChannel* aChannel);
450 
451   /**
452    * Asynchronously awaits a stable state, whereupon aRunnable runs on the main
453    * thread. This adds an event which run aRunnable to the appshell's list of
454    * sections synchronous the next time control returns to the event loop.
455    */
456   void RunInStableState(nsIRunnable* aRunnable);
457 
458   /**
459    * Fires a timeupdate event. If aPeriodic is true, the event will only
460    * be fired if we've not fired a timeupdate event (for any reason) in the
461    * last 250ms, as required by the spec when the current time is periodically
462    * increasing during playback.
463    */
464   void FireTimeUpdate(TimeupdateType aType);
465 
MaybeQueueTimeupdateEvent()466   void MaybeQueueTimeupdateEvent() final {
467     FireTimeUpdate(TimeupdateType::ePeriodic);
468   }
469 
470   const TimeStamp& LastTimeupdateDispatchTime() const;
471   void UpdateLastTimeupdateDispatchTime();
472 
473   // WebIDL
474 
475   MediaError* GetError() const;
476 
GetSrc(nsAString & aSrc)477   void GetSrc(nsAString& aSrc) { GetURIAttr(nsGkAtoms::src, nullptr, aSrc); }
SetSrc(const nsAString & aSrc,ErrorResult & aError)478   void SetSrc(const nsAString& aSrc, ErrorResult& aError) {
479     SetHTMLAttr(nsGkAtoms::src, aSrc, aError);
480   }
SetSrc(const nsAString & aSrc,nsIPrincipal * aTriggeringPrincipal,ErrorResult & aError)481   void SetSrc(const nsAString& aSrc, nsIPrincipal* aTriggeringPrincipal,
482               ErrorResult& aError) {
483     SetHTMLAttr(nsGkAtoms::src, aSrc, aTriggeringPrincipal, aError);
484   }
485 
486   void GetCurrentSrc(nsAString& aCurrentSrc);
487 
GetCrossOrigin(nsAString & aResult)488   void GetCrossOrigin(nsAString& aResult) {
489     // Null for both missing and invalid defaults is ok, since we
490     // always parse to an enum value, so we don't need an invalid
491     // default, and we _want_ the missing default to be null.
492     GetEnumAttr(nsGkAtoms::crossorigin, nullptr, aResult);
493   }
SetCrossOrigin(const nsAString & aCrossOrigin,ErrorResult & aError)494   void SetCrossOrigin(const nsAString& aCrossOrigin, ErrorResult& aError) {
495     SetOrRemoveNullableStringAttr(nsGkAtoms::crossorigin, aCrossOrigin, aError);
496   }
497 
NetworkState()498   uint16_t NetworkState() const { return mNetworkState; }
499 
500   void NotifyXPCOMShutdown() final;
501 
502   // Called by media decoder when the audible state changed or when input is
503   // a media stream.
504   void SetAudibleState(bool aAudible) final;
505 
506   // Notify agent when the MediaElement changes its audible state.
507   void NotifyAudioPlaybackChanged(AudibleChangedReasons aReason);
508 
GetPreload(nsAString & aValue)509   void GetPreload(nsAString& aValue) {
510     if (mSrcAttrStream) {
511       nsGkAtoms::none->ToString(aValue);
512       return;
513     }
514     GetEnumAttr(nsGkAtoms::preload, nullptr, aValue);
515   }
SetPreload(const nsAString & aValue,ErrorResult & aRv)516   void SetPreload(const nsAString& aValue, ErrorResult& aRv) {
517     if (mSrcAttrStream) {
518       return;
519     }
520     SetHTMLAttr(nsGkAtoms::preload, aValue, aRv);
521   }
522 
523   already_AddRefed<TimeRanges> Buffered() const;
524 
525   void Load();
526 
527   void CanPlayType(const nsAString& aType, nsAString& aResult);
528 
ReadyState()529   uint16_t ReadyState() const { return mReadyState; }
530 
531   bool Seeking() const;
532 
533   double CurrentTime() const;
534 
535   void SetCurrentTime(double aCurrentTime, ErrorResult& aRv);
SetCurrentTime(double aCurrentTime)536   void SetCurrentTime(double aCurrentTime) {
537     SetCurrentTime(aCurrentTime, IgnoreErrors());
538   }
539 
540   void FastSeek(double aTime, ErrorResult& aRv);
541 
542   already_AddRefed<Promise> SeekToNextFrame(ErrorResult& aRv);
543 
544   double Duration() const;
545 
HasAudio()546   bool HasAudio() const { return mMediaInfo.HasAudio(); }
547 
IsVideo()548   virtual bool IsVideo() const { return false; }
549 
HasVideo()550   bool HasVideo() const { return mMediaInfo.HasVideo(); }
551 
IsEncrypted()552   bool IsEncrypted() const override { return mIsEncrypted; }
553 
Paused()554   bool Paused() const { return mPaused; }
555 
DefaultPlaybackRate()556   double DefaultPlaybackRate() const {
557     if (mSrcAttrStream) {
558       return 1.0;
559     }
560     return mDefaultPlaybackRate;
561   }
562 
563   void SetDefaultPlaybackRate(double aDefaultPlaybackRate, ErrorResult& aRv);
564 
PlaybackRate()565   double PlaybackRate() const {
566     if (mSrcAttrStream) {
567       return 1.0;
568     }
569     return mPlaybackRate;
570   }
571 
572   void SetPlaybackRate(double aPlaybackRate, ErrorResult& aRv);
573 
574   already_AddRefed<TimeRanges> Played();
575 
576   already_AddRefed<TimeRanges> Seekable() const;
577 
578   bool Ended();
579 
Autoplay()580   bool Autoplay() const { return GetBoolAttr(nsGkAtoms::autoplay); }
581 
SetAutoplay(bool aValue,ErrorResult & aRv)582   void SetAutoplay(bool aValue, ErrorResult& aRv) {
583     SetHTMLBoolAttr(nsGkAtoms::autoplay, aValue, aRv);
584   }
585 
Loop()586   bool Loop() const { return GetBoolAttr(nsGkAtoms::loop); }
587 
SetLoop(bool aValue,ErrorResult & aRv)588   void SetLoop(bool aValue, ErrorResult& aRv) {
589     SetHTMLBoolAttr(nsGkAtoms::loop, aValue, aRv);
590   }
591 
592   already_AddRefed<Promise> Play(ErrorResult& aRv);
Play()593   void Play() {
594     IgnoredErrorResult dummy;
595     RefPtr<Promise> toBeIgnored = Play(dummy);
596   }
597 
598   void Pause(ErrorResult& aRv);
Pause()599   void Pause() { Pause(IgnoreErrors()); }
600 
Controls()601   bool Controls() const { return GetBoolAttr(nsGkAtoms::controls); }
602 
SetControls(bool aValue,ErrorResult & aRv)603   void SetControls(bool aValue, ErrorResult& aRv) {
604     SetHTMLBoolAttr(nsGkAtoms::controls, aValue, aRv);
605   }
606 
Volume()607   double Volume() const { return mVolume; }
608 
609   void SetVolume(double aVolume, ErrorResult& aRv);
610 
Muted()611   bool Muted() const { return mMuted & MUTED_BY_CONTENT; }
612   void SetMuted(bool aMuted);
613 
DefaultMuted()614   bool DefaultMuted() const { return GetBoolAttr(nsGkAtoms::muted); }
615 
SetDefaultMuted(bool aMuted,ErrorResult & aRv)616   void SetDefaultMuted(bool aMuted, ErrorResult& aRv) {
617     SetHTMLBoolAttr(nsGkAtoms::muted, aMuted, aRv);
618   }
619 
MozAllowCasting()620   bool MozAllowCasting() const { return mAllowCasting; }
621 
SetMozAllowCasting(bool aShow)622   void SetMozAllowCasting(bool aShow) { mAllowCasting = aShow; }
623 
MozIsCasting()624   bool MozIsCasting() const { return mIsCasting; }
625 
SetMozIsCasting(bool aShow)626   void SetMozIsCasting(bool aShow) { mIsCasting = aShow; }
627 
628   // Returns whether a call to Play() would be rejected with NotAllowedError.
629   // This assumes "worst case" for unknowns. So if prompting for permission is
630   // enabled and no permission is stored, this behaves as if the user would
631   // opt to block.
632   bool AllowedToPlay() const;
633 
634   already_AddRefed<MediaSource> GetMozMediaSourceObject() const;
635 
636   // Returns a promise which will be resolved after collecting debugging
637   // data from decoder/reader/MDSM. Used for debugging purposes.
638   already_AddRefed<Promise> MozRequestDebugInfo(ErrorResult& aRv);
639 
640   // Enables DecoderDoctorLogger logging. Used for debugging purposes.
641   static void MozEnableDebugLog(const GlobalObject&);
642 
643   // Returns a promise which will be resolved after collecting debugging
644   // log associated with this element. Used for debugging purposes.
645   already_AddRefed<Promise> MozRequestDebugLog(ErrorResult& aRv);
646 
647   // For use by mochitests. Enabling pref "media.test.video-suspend"
648   void SetVisible(bool aVisible);
649 
650   // For use by mochitests. Enabling pref "media.test.video-suspend"
651   bool HasSuspendTaint() const;
652 
653   // For use by mochitests.
654   bool IsVideoDecodingSuspended() const;
655 
656   // These functions return accumulated time, which are used for the telemetry
657   // usage. Return -1 for error.
658   double TotalPlayTime() const;
659   double InvisiblePlayTime() const;
660   double VideoDecodeSuspendedTime() const;
661 
662   // Test methods for decoder doctor.
663   void SetFormatDiagnosticsReportForMimeType(const nsAString& aMimeType,
664                                              DecoderDoctorReportType aType);
665   void SetDecodeError(const nsAString& aError, ErrorResult& aRv);
666   void SetAudioSinkFailedStartup();
667 
668   // Synchronously, return the next video frame and mark the element unable to
669   // participate in decode suspending.
670   //
671   // This function is synchronous for cases where decoding has been suspended
672   // and JS needs a frame to use in, eg., nsLayoutUtils::SurfaceFromElement()
673   // via drawImage().
674   already_AddRefed<layers::Image> GetCurrentImage();
675 
676   already_AddRefed<DOMMediaStream> GetSrcObject() const;
677   void SetSrcObject(DOMMediaStream& aValue);
678   void SetSrcObject(DOMMediaStream* aValue);
679 
MozPreservesPitch()680   bool MozPreservesPitch() const { return mPreservesPitch; }
681   void SetMozPreservesPitch(bool aPreservesPitch);
682 
683   MediaKeys* GetMediaKeys() const;
684 
685   already_AddRefed<Promise> SetMediaKeys(MediaKeys* mediaKeys,
686                                          ErrorResult& aRv);
687 
688   mozilla::dom::EventHandlerNonNull* GetOnencrypted();
689   void SetOnencrypted(mozilla::dom::EventHandlerNonNull* aCallback);
690 
691   mozilla::dom::EventHandlerNonNull* GetOnwaitingforkey();
692   void SetOnwaitingforkey(mozilla::dom::EventHandlerNonNull* aCallback);
693 
694   void DispatchEncrypted(const nsTArray<uint8_t>& aInitData,
695                          const nsAString& aInitDataType) override;
696 
697   bool IsEventAttributeNameInternal(nsAtom* aName) override;
698 
699   bool ContainsRestrictedContent();
700 
701   void NotifyWaitingForKey() override;
702 
703   already_AddRefed<DOMMediaStream> CaptureAudio(ErrorResult& aRv,
704                                                 MediaTrackGraph* aGraph);
705 
706   already_AddRefed<DOMMediaStream> MozCaptureStream(ErrorResult& aRv);
707 
708   already_AddRefed<DOMMediaStream> MozCaptureStreamUntilEnded(ErrorResult& aRv);
709 
MozAudioCaptured()710   bool MozAudioCaptured() const { return mAudioCaptured; }
711 
712   void MozGetMetadata(JSContext* aCx, JS::MutableHandle<JSObject*> aResult,
713                       ErrorResult& aRv);
714 
715   double MozFragmentEnd();
716 
717   AudioTrackList* AudioTracks();
718 
719   VideoTrackList* VideoTracks();
720 
721   TextTrackList* GetTextTracks();
722 
723   already_AddRefed<TextTrack> AddTextTrack(TextTrackKind aKind,
724                                            const nsAString& aLabel,
725                                            const nsAString& aLanguage);
726 
AddTextTrack(TextTrack * aTextTrack)727   void AddTextTrack(TextTrack* aTextTrack) {
728     GetOrCreateTextTrackManager()->AddTextTrack(aTextTrack);
729   }
730 
731   void RemoveTextTrack(TextTrack* aTextTrack, bool aPendingListOnly = false) {
732     if (mTextTrackManager) {
733       mTextTrackManager->RemoveTextTrack(aTextTrack, aPendingListOnly);
734     }
735   }
736 
NotifyCueAdded(TextTrackCue & aCue)737   void NotifyCueAdded(TextTrackCue& aCue) {
738     if (mTextTrackManager) {
739       mTextTrackManager->NotifyCueAdded(aCue);
740     }
741   }
NotifyCueRemoved(TextTrackCue & aCue)742   void NotifyCueRemoved(TextTrackCue& aCue) {
743     if (mTextTrackManager) {
744       mTextTrackManager->NotifyCueRemoved(aCue);
745     }
746   }
NotifyCueUpdated(TextTrackCue * aCue)747   void NotifyCueUpdated(TextTrackCue* aCue) {
748     if (mTextTrackManager) {
749       mTextTrackManager->NotifyCueUpdated(aCue);
750     }
751   }
752 
753   void NotifyCueDisplayStatesChanged();
754 
IsBlessed()755   bool IsBlessed() const { return mIsBlessed; }
756 
757   // A method to check whether we are currently playing.
758   bool IsCurrentlyPlaying() const;
759 
760   // Returns true if the media element is being destroyed. Used in
761   // dormancy checks to prevent dormant processing for an element
762   // that will soon be gone.
763   bool IsBeingDestroyed();
764 
765   void OnVisibilityChange(Visibility aNewVisibility);
766 
767   // Begin testing only methods
768   float ComputedVolume() const;
769   bool ComputedMuted() const;
770 
771   // Return true if the media has been suspended media due to an inactive
772   // document or prohibiting by the docshell.
773   bool IsSuspendedByInactiveDocOrDocShell() const;
774   // End testing only methods
775 
776   void SetMediaInfo(const MediaInfo& aInfo);
777   MediaInfo GetMediaInfo() const override;
778 
779   // Gives access to the decoder's frame statistics, if present.
780   FrameStatistics* GetFrameStatistics() const override;
781 
782   void DispatchAsyncTestingEvent(const nsAString& aName) override;
783 
784   AbstractThread* AbstractMainThread() const final;
785 
786   // Telemetry: to record the usage of a {visible / invisible} video element as
787   // the source of {drawImage(), createPattern(), createImageBitmap() and
788   // captureStream()} APIs.
789   enum class CallerAPI {
790     DRAW_IMAGE,
791     CREATE_PATTERN,
792     CREATE_IMAGEBITMAP,
793     CAPTURE_STREAM,
794   };
795   void MarkAsContentSource(CallerAPI aAPI);
796 
797   Document* GetDocument() const override;
798 
799   already_AddRefed<GMPCrashHelper> CreateGMPCrashHelper() override;
800 
MainThreadEventTarget()801   nsISerialEventTarget* MainThreadEventTarget() {
802     return mMainThreadEventTarget;
803   }
804 
805   // Set the sink id (of the output device) that the audio will play. If aSinkId
806   // is empty the default device will be set.
807   already_AddRefed<Promise> SetSinkId(const nsAString& aSinkId,
808                                       ErrorResult& aRv);
809   // Get the sink id of the device that audio is being played. Initial value is
810   // empty and the default device is being used.
GetSinkId(nsString & aSinkId)811   void GetSinkId(nsString& aSinkId) {
812     MOZ_ASSERT(NS_IsMainThread());
813     aSinkId = mSink.first;
814   }
815 
816   // This is used to notify MediaElementAudioSourceNode that media element is
817   // allowed to play when media element is used as a source for web audio, so
818   // that we can start AudioContext if it was not allowed to start.
819   RefPtr<GenericNonExclusivePromise> GetAllowedToPlayPromise();
820 
GetShowPosterFlag()821   bool GetShowPosterFlag() const { return mShowPoster; }
822 
823   bool IsAudible() const;
824 
825   // Return key system in use if we have one, otherwise return nothing.
826   Maybe<nsAutoString> GetKeySystem() const override;
827 
828  protected:
829   virtual ~HTMLMediaElement();
830 
831   class AudioChannelAgentCallback;
832   class ChannelLoader;
833   class ErrorSink;
834   class MediaElementTrackSource;
835   class MediaLoadListener;
836   class MediaStreamRenderer;
837   class MediaStreamTrackListener;
838   class ShutdownObserver;
839   class TitleChangeObserver;
840   class MediaControlKeyListener;
841 
842   MediaDecoderOwner::NextFrameStatus NextFrameStatus();
843 
844   void SetDecoder(MediaDecoder* aDecoder);
845 
846   void PlayInternal(bool aHandlingUserInput);
847 
848   // See spec, https://html.spec.whatwg.org/#internal-pause-steps
849   void PauseInternal();
850 
851   /** Use this method to change the mReadyState member, so required
852    * events can be fired.
853    */
854   void ChangeReadyState(nsMediaReadyState aState);
855 
856   /**
857    * Use this method to change the mNetworkState member, so required
858    * actions will be taken during the transition.
859    */
860   void ChangeNetworkState(nsMediaNetworkState aState);
861 
862   /**
863    * The MediaElement will be responsible for creating and releasing the audio
864    * wakelock depending on the playing and audible state.
865    */
866   virtual void WakeLockRelease();
867   virtual void UpdateWakeLock();
868 
869   void CreateAudioWakeLockIfNeeded();
870   void ReleaseAudioWakeLockIfExists();
871   RefPtr<WakeLock> mWakeLock;
872 
873   /**
874    * Logs a warning message to the web console to report various failures.
875    * aMsg is the localized message identifier, aParams is the parameters to
876    * be substituted into the localized message, and aParamCount is the number
877    * of parameters in aParams.
878    */
879   void ReportLoadError(const char* aMsg, const nsTArray<nsString>& aParams =
880                                              nsTArray<nsString>());
881 
882   /**
883    * Log message to web console.
884    */
885   void ReportToConsole(
886       uint32_t aErrorFlags, const char* aMsg,
887       const nsTArray<nsString>& aParams = nsTArray<nsString>()) const;
888 
889   /**
890    * Changes mHasPlayedOrSeeked to aValue. If mHasPlayedOrSeeked changes
891    * we'll force a reflow so that the video frame gets reflowed to reflect
892    * the poster hiding or showing immediately.
893    */
894   void SetPlayedOrSeeked(bool aValue);
895 
896   /**
897    * Initialize the media element for playback of aStream
898    */
899   void SetupSrcMediaStreamPlayback(DOMMediaStream* aStream);
900   /**
901    * Stop playback on mSrcStream.
902    */
903   void EndSrcMediaStreamPlayback();
904   /**
905    * Ensure we're playing mSrcStream if and only if we're not paused.
906    */
907   enum { REMOVING_SRC_STREAM = 0x1 };
908   void UpdateSrcMediaStreamPlaying(uint32_t aFlags = 0);
909 
910   /**
911    * Ensure currentTime progresses if and only if we're potentially playing
912    * mSrcStream. Called by the watch manager while we're playing mSrcStream, and
913    * one of the inputs to the potentially playing algorithm changes.
914    */
915   void UpdateSrcStreamPotentiallyPlaying();
916 
917   /**
918    * mSrcStream's graph's CurrentTime() has been updated. It might be time to
919    * fire "timeupdate".
920    */
921   void UpdateSrcStreamTime();
922 
923   /**
924    * Called after a tail dispatch when playback of mSrcStream ended, to comply
925    * with the spec where we must start reporting true for the ended attribute
926    * after the event loop returns to step 1. A MediaStream could otherwise be
927    * manipulated to end a HTMLMediaElement synchronously.
928    */
929   void UpdateSrcStreamReportPlaybackEnded();
930 
931   /**
932    * Called by our DOMMediaStream::TrackListener when a new MediaStreamTrack has
933    * been added to the playback stream of |mSrcStream|.
934    */
935   void NotifyMediaStreamTrackAdded(const RefPtr<MediaStreamTrack>& aTrack);
936 
937   /**
938    * Called by our DOMMediaStream::TrackListener when a MediaStreamTrack in
939    * |mSrcStream|'s playback stream has ended.
940    */
941   void NotifyMediaStreamTrackRemoved(const RefPtr<MediaStreamTrack>& aTrack);
942 
943   /**
944    * Convenience method to get in a single list all enabled AudioTracks and, if
945    * this is a video element, the selected VideoTrack.
946    */
947   void GetAllEnabledMediaTracks(nsTArray<RefPtr<MediaTrack>>& aTracks);
948 
949   /**
950    * Enables or disables all tracks forwarded from mSrcStream to all
951    * OutputMediaStreams. We do this for muting the tracks when pausing,
952    * and unmuting when playing the media element again.
953    */
954   void SetCapturedOutputStreamsEnabled(bool aEnabled);
955 
956   /**
957    * Returns true if output tracks should be muted, based on the state of this
958    * media element.
959    */
960   enum class OutputMuteState { Muted, Unmuted };
961   OutputMuteState OutputTracksMuted();
962 
963   /**
964    * Sets the muted state of all output track sources. They are muted when we're
965    * paused and unmuted otherwise.
966    */
967   void UpdateOutputTracksMuting();
968 
969   /**
970    * Create a new MediaStreamTrack for the TrackSource corresponding to aTrack
971    * and add it to the DOMMediaStream in aOutputStream. This automatically sets
972    * the output track to enabled or disabled depending on our current playing
973    * state.
974    */
975   enum class AddTrackMode { ASYNC, SYNC };
976   void AddOutputTrackSourceToOutputStream(
977       MediaElementTrackSource* aSource, OutputMediaStream& aOutputStream,
978       AddTrackMode aMode = AddTrackMode::ASYNC);
979 
980   /**
981    * Creates output track sources when this media element is captured, tracks
982    * exist, playback is not ended and readyState is >= HAVE_METADATA.
983    */
984   void UpdateOutputTrackSources();
985 
986   /**
987    * Returns an DOMMediaStream containing the played contents of this
988    * element. When aBehavior is FINISH_WHEN_ENDED, when this element ends
989    * playback we will finish the stream and not play any more into it.  When
990    * aType is CONTINUE_WHEN_ENDED, ending playback does not finish the stream.
991    * The stream will never finish.
992    *
993    * When aType is CAPTURE_AUDIO, we stop playout of audio and instead route it
994    * to the DOMMediaStream. Volume and mute state will be applied to the audio
995    * reaching the stream. No video tracks will be captured in this case.
996    */
997   already_AddRefed<DOMMediaStream> CaptureStreamInternal(
998       StreamCaptureBehavior aFinishBehavior,
999       StreamCaptureType aStreamCaptureType, MediaTrackGraph* aGraph);
1000 
1001   /**
1002    * Initialize a decoder as a clone of an existing decoder in another
1003    * element.
1004    * mLoadingSrc must already be set.
1005    */
1006   nsresult InitializeDecoderAsClone(ChannelMediaDecoder* aOriginal);
1007 
1008   /**
1009    * Call Load() and FinishDecoderSetup() on the decoder. It also handle
1010    * resource cloning if DecoderType is ChannelMediaDecoder.
1011    */
1012   template <typename DecoderType, typename... LoadArgs>
1013   nsresult SetupDecoder(DecoderType* aDecoder, LoadArgs&&... aArgs);
1014 
1015   /**
1016    * Initialize a decoder to load the given channel. The decoder's stream
1017    * listener is returned via aListener.
1018    * mLoadingSrc must already be set.
1019    */
1020   nsresult InitializeDecoderForChannel(nsIChannel* aChannel,
1021                                        nsIStreamListener** aListener);
1022 
1023   /**
1024    * Finish setting up the decoder after Load() has been called on it.
1025    * Called by InitializeDecoderForChannel/InitializeDecoderAsClone.
1026    */
1027   nsresult FinishDecoderSetup(MediaDecoder* aDecoder);
1028 
1029   /**
1030    * Call this after setting up mLoadingSrc and mDecoder.
1031    */
1032   void AddMediaElementToURITable();
1033   /**
1034    * Call this before modifying mLoadingSrc.
1035    */
1036   void RemoveMediaElementFromURITable();
1037   /**
1038    * Call this to find a media element with the same NodePrincipal and
1039    * mLoadingSrc set to aURI, and with a decoder on which Load() has been
1040    * called.
1041    */
1042   HTMLMediaElement* LookupMediaElementURITable(nsIURI* aURI);
1043 
1044   /**
1045    * Shutdown and clear mDecoder and maintain associated invariants.
1046    */
1047   void ShutdownDecoder();
1048   /**
1049    * Execute the initial steps of the load algorithm that ensure existing
1050    * loads are aborted, the element is emptied, and a new load ID is
1051    * created.
1052    */
1053   void AbortExistingLoads();
1054 
1055   /**
1056    * This is the dedicated media source failure steps.
1057    * Called when all potential resources are exhausted. Changes network
1058    * state to NETWORK_NO_SOURCE, and sends error event with code
1059    * MEDIA_ERR_SRC_NOT_SUPPORTED.
1060    */
1061   void NoSupportedMediaSourceError(
1062       const nsACString& aErrorDetails = nsCString());
1063 
1064   /**
1065    * Per spec, Failed with elements: Queue a task, using the DOM manipulation
1066    * task source, to fire a simple event named error at the candidate element.
1067    * So dispatch |QueueLoadFromSourceTask| to main thread to make sure the task
1068    * will be executed later than loadstart event.
1069    */
1070   void DealWithFailedElement(nsIContent* aSourceElement);
1071 
1072   /**
1073    * Attempts to load resources from the <source> children. This is a
1074    * substep of the resource selection algorithm. Do not call this directly,
1075    * call QueueLoadFromSourceTask() instead.
1076    */
1077   void LoadFromSourceChildren();
1078 
1079   /**
1080    * Asynchronously awaits a stable state, and then causes
1081    * LoadFromSourceChildren() to be called on the main threads' event loop.
1082    */
1083   void QueueLoadFromSourceTask();
1084 
1085   /**
1086    * Runs the media resource selection algorithm.
1087    */
1088   void SelectResource();
1089 
1090   /**
1091    * A wrapper function that allows us to cleanly reset flags after a call
1092    * to SelectResource()
1093    */
1094   void SelectResourceWrapper();
1095 
1096   /**
1097    * Asynchronously awaits a stable state, and then causes SelectResource()
1098    * to be run on the main thread's event loop.
1099    */
1100   void QueueSelectResourceTask();
1101 
1102   /**
1103    * When loading a new source on an existing media element, make sure to reset
1104    * everything that is accessible using the media element API.
1105    */
1106   void ResetState();
1107 
1108   /**
1109    * The resource-fetch algorithm step of the load algorithm.
1110    */
1111   MediaResult LoadResource();
1112 
1113   /**
1114    * Selects the next <source> child from which to load a resource. Called
1115    * during the resource selection algorithm. Stores the return value in
1116    * mSourceLoadCandidate before returning.
1117    */
1118   Element* GetNextSource();
1119 
1120   /**
1121    * Changes mDelayingLoadEvent, and will call BlockOnLoad()/UnblockOnLoad()
1122    * on the owning document, so it can delay the load event firing.
1123    */
1124   void ChangeDelayLoadStatus(bool aDelay);
1125 
1126   /**
1127    * If we suspended downloading after the first frame, unsuspend now.
1128    */
1129   void StopSuspendingAfterFirstFrame();
1130 
1131   /**
1132    * Called when our channel is redirected to another channel.
1133    * Updates our mChannel reference to aNewChannel.
1134    */
1135   nsresult OnChannelRedirect(nsIChannel* aChannel, nsIChannel* aNewChannel,
1136                              uint32_t aFlags);
1137 
1138   /**
1139    * Call this to reevaluate whether we should be holding a self-reference.
1140    */
1141   void AddRemoveSelfReference();
1142 
1143   /**
1144    * Called when "xpcom-shutdown" event is received.
1145    */
1146   void NotifyShutdownEvent();
1147 
1148   /**
1149    * Possible values of the 'preload' attribute.
1150    */
1151   enum PreloadAttrValue : uint8_t {
1152     PRELOAD_ATTR_EMPTY,     // set to ""
1153     PRELOAD_ATTR_NONE,      // set to "none"
1154     PRELOAD_ATTR_METADATA,  // set to "metadata"
1155     PRELOAD_ATTR_AUTO       // set to "auto"
1156   };
1157 
1158   /**
1159    * The preloading action to perform. These dictate how we react to the
1160    * preload attribute. See mPreloadAction.
1161    */
1162   enum PreloadAction {
1163     PRELOAD_UNDEFINED = 0,  // not determined - used only for initialization
1164     PRELOAD_NONE = 1,       // do not preload
1165     PRELOAD_METADATA = 2,   // preload only the metadata (and first frame)
1166     PRELOAD_ENOUGH = 3      // preload enough data to allow uninterrupted
1167                             // playback
1168   };
1169 
1170   /**
1171    * The guts of Load(). Load() acts as a wrapper around this which sets
1172    * mIsDoingExplicitLoad to true so that when script calls 'load()'
1173    * preload-none will be automatically upgraded to preload-metadata.
1174    */
1175   void DoLoad();
1176 
1177   /**
1178    * Suspends the load of mLoadingSrc, so that it can be resumed later
1179    * by ResumeLoad(). This is called when we have a media with a 'preload'
1180    * attribute value of 'none', during the resource selection algorithm.
1181    */
1182   void SuspendLoad();
1183 
1184   /**
1185    * Resumes a previously suspended load (suspended by SuspendLoad(uri)).
1186    * Will continue running the resource selection algorithm.
1187    * Sets mPreloadAction to aAction.
1188    */
1189   void ResumeLoad(PreloadAction aAction);
1190 
1191   /**
1192    * Handle a change to the preload attribute. Should be called whenever the
1193    * value (or presence) of the preload attribute changes. The change in
1194    * attribute value may cause a change in the mPreloadAction of this
1195    * element. If there is a change then this method will initiate any
1196    * behaviour that is necessary to implement the action.
1197    */
1198   void UpdatePreloadAction();
1199 
1200   /**
1201    * Fire progress events if needed according to the time and byte constraints
1202    * outlined in the specification. aHaveNewProgress is true if progress has
1203    * just been detected.  Otherwise the method is called as a result of the
1204    * progress timer.
1205    */
1206   void CheckProgress(bool aHaveNewProgress);
1207   static void ProgressTimerCallback(nsITimer* aTimer, void* aClosure);
1208   /**
1209    * Start timer to update download progress.
1210    */
1211   void StartProgressTimer();
1212   /**
1213    * Start sending progress and/or stalled events.
1214    */
1215   void StartProgress();
1216   /**
1217    * Stop progress information timer and events.
1218    */
1219   void StopProgress();
1220 
1221   /**
1222    * Dispatches an error event to a child source element.
1223    */
1224   void DispatchAsyncSourceError(nsIContent* aSourceElement);
1225 
1226   /**
1227    * Resets the media element for an error condition as per aErrorCode.
1228    * aErrorCode must be one of WebIDL HTMLMediaElement error codes.
1229    */
1230   void Error(uint16_t aErrorCode,
1231              const nsACString& aErrorDetails = nsCString());
1232 
1233   /**
1234    * Returns the URL spec of the currentSrc.
1235    **/
1236   void GetCurrentSpec(nsCString& aString);
1237 
1238   /**
1239    * Process any media fragment entries in the URI
1240    */
1241   void ProcessMediaFragmentURI();
1242 
1243   /**
1244    * Mute or unmute the audio and change the value that the |muted| map.
1245    */
1246   void SetMutedInternal(uint32_t aMuted);
1247   /**
1248    * Update the volume of the output audio stream to match the element's
1249    * current mMuted/mVolume/mAudioChannelFaded state.
1250    */
1251   void SetVolumeInternal();
1252 
1253   /**
1254    * Suspend or resume element playback and resource download.  When we suspend
1255    * playback, event delivery would also be suspended (and events queued) until
1256    * the element is resumed.
1257    */
1258   void SuspendOrResumeElement(bool aSuspendElement);
1259 
1260   // Get the HTMLMediaElement object if the decoder is being used from an
1261   // HTML media element, and null otherwise.
GetMediaElement()1262   HTMLMediaElement* GetMediaElement() final { return this; }
1263 
1264   // Return true if decoding should be paused
GetPaused()1265   bool GetPaused() final { return Paused(); }
1266 
1267   // Seeks to aTime seconds. aSeekType can be Exact to seek to exactly the
1268   // seek target, or PrevSyncPoint if a quicker but less precise seek is
1269   // desired, and we'll seek to the sync point (keyframe and/or start of the
1270   // next block of audio samples) preceeding seek target.
1271   void Seek(double aTime, SeekTarget::Type aSeekType, ErrorResult& aRv);
1272 
1273   // Update the audio channel playing state
1274   void UpdateAudioChannelPlayingState();
1275 
1276   // Adds to the element's list of pending text tracks each text track
1277   // in the element's list of text tracks whose text track mode is not disabled
1278   // and whose text track readiness state is loading.
1279   void PopulatePendingTextTrackList();
1280 
1281   // Gets a reference to the MediaElement's TextTrackManager. If the
1282   // MediaElement doesn't yet have one then it will create it.
1283   TextTrackManager* GetOrCreateTextTrackManager();
1284 
1285   // Recomputes ready state and fires events as necessary based on current
1286   // state.
1287   void UpdateReadyStateInternal();
1288 
1289   // Create or destroy the captured stream.
1290   void AudioCaptureTrackChange(bool aCapture);
1291 
1292   // If the network state is empty and then we would trigger DoLoad().
1293   void MaybeDoLoad();
1294 
1295   // Anything we need to check after played success and not related with spec.
1296   void UpdateCustomPolicyAfterPlayed();
1297 
1298   // Returns a StreamCaptureType populated with the right bits, depending on the
1299   // tracks this HTMLMediaElement has.
1300   StreamCaptureType CaptureTypeForElement();
1301 
1302   // True if this element can be captured, false otherwise.
1303   bool CanBeCaptured(StreamCaptureType aCaptureType);
1304 
1305   using nsGenericHTMLElement::DispatchEvent;
1306   // For nsAsyncEventRunner.
1307   nsresult DispatchEvent(const nsAString& aName);
1308 
1309   already_AddRefed<nsMediaEventRunner> GetEventRunner(
1310       const nsAString& aName, EventFlag aFlag = EventFlag::eNone);
1311 
1312   // This method moves the mPendingPlayPromises into a temperate object. So the
1313   // mPendingPlayPromises is cleared after this method call.
1314   nsTArray<RefPtr<PlayPromise>> TakePendingPlayPromises();
1315 
1316   // This method snapshots the mPendingPlayPromises by TakePendingPlayPromises()
1317   // and queues a task to resolve them.
1318   void AsyncResolvePendingPlayPromises();
1319 
1320   // This method snapshots the mPendingPlayPromises by TakePendingPlayPromises()
1321   // and queues a task to reject them.
1322   void AsyncRejectPendingPlayPromises(nsresult aError);
1323 
1324   // This method snapshots the mPendingPlayPromises by TakePendingPlayPromises()
1325   // and queues a task to resolve them also to dispatch a "playing" event.
1326   void NotifyAboutPlaying();
1327 
1328   already_AddRefed<Promise> CreateDOMPromise(ErrorResult& aRv) const;
1329 
1330   // Pass information for deciding the video decode mode to decoder.
1331   void NotifyDecoderActivityChanges() const;
1332 
1333   // Constructs an AudioTrack in mAudioTrackList if aInfo reports that audio is
1334   // available, and a VideoTrack in mVideoTrackList if aInfo reports that video
1335   // is available.
1336   void ConstructMediaTracks(const MediaInfo* aInfo);
1337 
1338   // Removes all MediaTracks from mAudioTrackList and mVideoTrackList and fires
1339   // "removetrack" on the lists accordingly.
1340   // Note that by spec, this should not fire "removetrack". However, it appears
1341   // other user agents do, per
1342   // https://wpt.fyi/results/media-source/mediasource-avtracks.html.
1343   void RemoveMediaTracks();
1344 
1345   // Mark the decoder owned by the element as tainted so that the
1346   // suspend-video-decoder is disabled.
1347   void MarkAsTainted();
1348 
1349   virtual nsresult AfterSetAttr(int32_t aNameSpaceID, nsAtom* aName,
1350                                 const nsAttrValue* aValue,
1351                                 const nsAttrValue* aOldValue,
1352                                 nsIPrincipal* aMaybeScriptedPrincipal,
1353                                 bool aNotify) override;
1354   virtual nsresult OnAttrSetButNotChanged(int32_t aNamespaceID, nsAtom* aName,
1355                                           const nsAttrValueOrString& aValue,
1356                                           bool aNotify) override;
1357 
1358   bool DetachExistingMediaKeys();
1359   bool TryRemoveMediaKeysAssociation();
1360   void RemoveMediaKeys();
1361   bool AttachNewMediaKeys();
1362   bool TryMakeAssociationWithCDM(CDMProxy* aProxy);
1363   void MakeAssociationWithCDMResolved();
1364   void SetCDMProxyFailure(const MediaResult& aResult);
1365   void ResetSetMediaKeysTempVariables();
1366 
1367   void PauseIfShouldNotBePlaying();
1368 
1369   WatchManager<HTMLMediaElement> mWatchManager;
1370 
1371   // When the play is not allowed, dispatch related events which are used for
1372   // testing or changing control UI.
1373   void DispatchEventsWhenPlayWasNotAllowed();
1374 
1375   // When the doc is blocked permanantly, we would dispatch event to notify
1376   // front-end side to show blocking icon.
1377   void MaybeNotifyAutoplayBlocked();
1378 
1379   // Dispatch event for video control when video gets blocked in order to show
1380   // the click-to-play icon.
1381   void DispatchBlockEventForVideoControl();
1382 
1383   // When playing state change, we have to notify MediaControl in the chrome
1384   // process in order to keep its playing state correct.
1385   void NotifyMediaControlPlaybackStateChanged();
1386 
1387   // Clear the timer when we want to continue listening to the media control
1388   // key events.
1389   void ClearStopMediaControlTimerIfNeeded();
1390 
1391   // Sets a secondary renderer for mSrcStream, so this media element can be
1392   // rendered in Picture-in-Picture mode when playing a MediaStream. A null
1393   // aContainer will unset the secondary renderer. aFirstFrameOutput allows
1394   // for injecting a listener of the callers choice for rendering the first
1395   // frame.
1396   void SetSecondaryMediaStreamRenderer(
1397       VideoFrameContainer* aContainer,
1398       FirstFrameVideoOutput* aFirstFrameOutput = nullptr);
1399 
1400   // This function is used to update the status of media control when the media
1401   // changes its status of being used in the Picture-in-Picture mode.
1402   void UpdateMediaControlAfterPictureInPictureModeChanged();
1403 
1404   // The current decoder. Load() has been called on this decoder.
1405   // At most one of mDecoder and mSrcStream can be non-null.
1406   RefPtr<MediaDecoder> mDecoder;
1407 
1408   // The DocGroup-specific nsISerialEventTarget of this HTML element on the main
1409   // thread.
1410   nsCOMPtr<nsISerialEventTarget> mMainThreadEventTarget;
1411 
1412   // The DocGroup-specific AbstractThread::MainThread() of this HTML element.
1413   RefPtr<AbstractThread> mAbstractMainThread;
1414 
1415   // A reference to the VideoFrameContainer which contains the current frame
1416   // of video to display.
1417   RefPtr<VideoFrameContainer> mVideoFrameContainer;
1418 
1419   // Holds a reference to the MediaStream that has been set in the src
1420   // attribute.
1421   RefPtr<DOMMediaStream> mSrcAttrStream;
1422 
1423   // Holds the triggering principal for the src attribute.
1424   nsCOMPtr<nsIPrincipal> mSrcAttrTriggeringPrincipal;
1425 
1426   // Holds a reference to the MediaStream that we're actually playing.
1427   // At most one of mDecoder and mSrcStream can be non-null.
1428   RefPtr<DOMMediaStream> mSrcStream;
1429 
1430   // The MediaStreamRenderer handles rendering of our selected video track, and
1431   // enabled audio tracks, while mSrcStream is set.
1432   RefPtr<MediaStreamRenderer> mMediaStreamRenderer;
1433 
1434   // The secondary MediaStreamRenderer handles rendering of our selected video
1435   // track to a secondary VideoFrameContainer, while mSrcStream is set.
1436   RefPtr<MediaStreamRenderer> mSecondaryMediaStreamRenderer;
1437 
1438   // True once PlaybackEnded() is called and we're playing a MediaStream.
1439   // Reset to false if we start playing mSrcStream again.
1440   Watchable<bool> mSrcStreamPlaybackEnded = {
1441       false, "HTMLMediaElement::mSrcStreamPlaybackEnded"};
1442 
1443   // Mirrors mSrcStreamPlaybackEnded after a tail dispatch when set to true,
1444   // but may be be forced to false directly. To accomodate when an application
1445   // ends playback synchronously by manipulating mSrcStream or its tracks,
1446   // e.g., through MediaStream.removeTrack(), or MediaStreamTrack.stop().
1447   bool mSrcStreamReportPlaybackEnded = false;
1448 
1449   // Holds a reference to the stream connecting this stream to the window
1450   // capture sink.
1451   UniquePtr<MediaStreamWindowCapturer> mStreamWindowCapturer;
1452 
1453   // Holds references to the DOM wrappers for the MediaStreams that we're
1454   // writing to.
1455   nsTArray<OutputMediaStream> mOutputStreams;
1456 
1457   // Mapping for output tracks, from dom::MediaTrack ids to the
1458   // MediaElementTrackSource that represents the source of all corresponding
1459   // MediaStreamTracks captured from this element.
1460   nsRefPtrHashtable<nsStringHashKey, MediaElementTrackSource>
1461       mOutputTrackSources;
1462 
1463   // The currently selected video stream track.
1464   RefPtr<VideoStreamTrack> mSelectedVideoStreamTrack;
1465 
1466   const RefPtr<ShutdownObserver> mShutdownObserver;
1467 
1468   const RefPtr<TitleChangeObserver> mTitleChangeObserver;
1469 
1470   // Holds a reference to the MediaSource, if any, referenced by the src
1471   // attribute on the media element.
1472   RefPtr<MediaSource> mSrcMediaSource;
1473 
1474   // Holds a reference to the MediaSource supplying data for playback.  This
1475   // may either match mSrcMediaSource or come from Source element children.
1476   // This is set when and only when mLoadingSrc corresponds to an object url
1477   // that resolved to a MediaSource.
1478   RefPtr<MediaSource> mMediaSource;
1479 
1480   RefPtr<ChannelLoader> mChannelLoader;
1481 
1482   // Points to the child source elements, used to iterate through the children
1483   // when selecting a resource to load.  This is the previous sibling of the
1484   // child considered the current 'candidate' in:
1485   // https://html.spec.whatwg.org/multipage/media.html#concept-media-load-algorithm
1486   //
1487   // mSourcePointer == nullptr, we will next try to load |GetFirstChild()|.
1488   // mSourcePointer == GetLastChild(), we've exhausted all sources, waiting
1489   // for new elements to be appended.
1490   nsCOMPtr<nsIContent> mSourcePointer;
1491 
1492   // Points to the document whose load we're blocking. This is the document
1493   // we're bound to when loading starts.
1494   nsCOMPtr<Document> mLoadBlockedDoc;
1495 
1496   // This is used to help us block/resume the event delivery.
1497   class EventBlocker;
1498   RefPtr<EventBlocker> mEventBlocker;
1499 
1500   // Media loading flags. See:
1501   //   http://www.whatwg.org/specs/web-apps/current-work/#video)
1502   nsMediaNetworkState mNetworkState = HTMLMediaElement_Binding::NETWORK_EMPTY;
1503   Watchable<nsMediaReadyState> mReadyState = {
1504       HTMLMediaElement_Binding::HAVE_NOTHING, "HTMLMediaElement::mReadyState"};
1505 
1506   enum LoadAlgorithmState {
1507     // No load algorithm instance is waiting for a source to be added to the
1508     // media in order to continue loading.
1509     NOT_WAITING,
1510     // We've run the load algorithm, and we tried all source children of the
1511     // media element, and failed to load any successfully. We're waiting for
1512     // another source element to be added to the media element, and will try
1513     // to load any such element when its added.
1514     WAITING_FOR_SOURCE
1515   };
1516 
1517   // The current media load ID. This is incremented every time we start a
1518   // new load. Async events note the ID when they're first sent, and only fire
1519   // if the ID is unchanged when they come to fire.
1520   uint32_t mCurrentLoadID = 0;
1521 
1522   // Denotes the waiting state of a load algorithm instance. When the load
1523   // algorithm is waiting for a source element child to be added, this is set
1524   // to WAITING_FOR_SOURCE, otherwise it's NOT_WAITING.
1525   LoadAlgorithmState mLoadWaitStatus = NOT_WAITING;
1526 
1527   // Current audio volume
1528   double mVolume = 1.0;
1529 
1530   // True if the audio track is not silent.
1531   bool mIsAudioTrackAudible = false;
1532 
1533   enum MutedReasons {
1534     MUTED_BY_CONTENT = 0x01,
1535     MUTED_BY_INVALID_PLAYBACK_RATE = 0x02,
1536     MUTED_BY_AUDIO_CHANNEL = 0x04,
1537     MUTED_BY_AUDIO_TRACK = 0x08
1538   };
1539 
1540   uint32_t mMuted = 0;
1541 
1542   UniquePtr<const MetadataTags> mTags;
1543 
1544   // URI of the resource we're attempting to load. This stores the value we
1545   // return in the currentSrc attribute. Use GetCurrentSrc() to access the
1546   // currentSrc attribute.
1547   // This is always the original URL we're trying to load --- before
1548   // redirects etc.
1549   nsCOMPtr<nsIURI> mLoadingSrc;
1550 
1551   // The triggering principal for the current source.
1552   nsCOMPtr<nsIPrincipal> mLoadingSrcTriggeringPrincipal;
1553 
1554   // Stores the current preload action for this element. Initially set to
1555   // PRELOAD_UNDEFINED, its value is changed by calling
1556   // UpdatePreloadAction().
1557   PreloadAction mPreloadAction = PRELOAD_UNDEFINED;
1558 
1559   // Time that the last timeupdate event was queued. Read/Write from the
1560   // main thread only.
1561   TimeStamp mQueueTimeUpdateRunnerTime;
1562 
1563   // Time that the last timeupdate event was fired. Read/Write from the
1564   // main thread only.
1565   TimeStamp mLastTimeUpdateDispatchTime;
1566 
1567   // Time that the last progress event was fired. Read/Write from the
1568   // main thread only.
1569   TimeStamp mProgressTime;
1570 
1571   // Time that data was last read from the media resource. Used for
1572   // computing if the download has stalled and to rate limit progress events
1573   // when data is arriving slower than PROGRESS_MS.
1574   // Read/Write from the main thread only.
1575   TimeStamp mDataTime;
1576 
1577   // Media 'currentTime' value when the last timeupdate event was queued.
1578   // Read/Write from the main thread only.
1579   double mLastCurrentTime = 0.0;
1580 
1581   // Logical start time of the media resource in seconds as obtained
1582   // from any media fragments. A negative value indicates that no
1583   // fragment time has been set. Read/Write from the main thread only.
1584   double mFragmentStart = -1.0;
1585 
1586   // Logical end time of the media resource in seconds as obtained
1587   // from any media fragments. A negative value indicates that no
1588   // fragment time has been set. Read/Write from the main thread only.
1589   double mFragmentEnd = -1.0;
1590 
1591   // The defaultPlaybackRate attribute gives the desired speed at which the
1592   // media resource is to play, as a multiple of its intrinsic speed.
1593   double mDefaultPlaybackRate = 1.0;
1594 
1595   // The playbackRate attribute gives the speed at which the media resource
1596   // plays, as a multiple of its intrinsic speed. If it is not equal to the
1597   // defaultPlaybackRate, then the implication is that the user is using a
1598   // feature such as fast forward or slow motion playback.
1599   double mPlaybackRate = 1.0;
1600 
1601   // True if pitch correction is applied when playbackRate is set to a
1602   // non-intrinsic value.
1603   bool mPreservesPitch = true;
1604 
1605   // Reference to the source element last returned by GetNextSource().
1606   // This is the child source element which we're trying to load from.
1607   nsCOMPtr<nsIContent> mSourceLoadCandidate;
1608 
1609   // Range of time played.
1610   RefPtr<TimeRanges> mPlayed;
1611 
1612   // Timer used for updating progress events.
1613   nsCOMPtr<nsITimer> mProgressTimer;
1614 
1615   // Encrypted Media Extension media keys.
1616   RefPtr<MediaKeys> mMediaKeys;
1617   RefPtr<MediaKeys> mIncomingMediaKeys;
1618   // The dom promise is used for HTMLMediaElement::SetMediaKeys.
1619   RefPtr<DetailedPromise> mSetMediaKeysDOMPromise;
1620   // Used to indicate if the MediaKeys attaching operation is on-going or not.
1621   bool mAttachingMediaKey = false;
1622   MozPromiseRequestHolder<SetCDMPromise> mSetCDMRequest;
1623 
1624   // Stores the time at the start of the current 'played' range.
1625   double mCurrentPlayRangeStart = 1.0;
1626 
1627   // True if loadeddata has been fired.
1628   bool mLoadedDataFired = false;
1629 
1630   // Indicates whether current playback is a result of user action
1631   // (ie. calling of the Play method), or automatic playback due to
1632   // the 'autoplay' attribute being set. A true value indicates the
1633   // latter case.
1634   // The 'autoplay' HTML attribute indicates that the video should
1635   // start playing when loaded. The 'autoplay' attribute of the object
1636   // is a mirror of the HTML attribute. These are different from this
1637   // 'mAutoplaying' flag, which indicates whether the current playback
1638   // is a result of the autoplay attribute.
1639   bool mAutoplaying = true;
1640 
1641   // Playback of the video is paused either due to calling the
1642   // 'Pause' method, or playback not yet having started.
1643   Watchable<bool> mPaused = {true, "HTMLMediaElement::mPaused"};
1644 
1645   // The following two fields are here for the private storage of the builtin
1646   // video controls, and control 'casting' of the video to external devices
1647   // (TVs, projectors etc.)
1648   // True if casting is currently allowed
1649   bool mAllowCasting = false;
1650   // True if currently casting this video
1651   bool mIsCasting = false;
1652 
1653   // Set while there are some OutputMediaStreams this media element's enabled
1654   // and selected tracks are captured into. When set, all tracks are captured
1655   // into the graph of this dummy track.
1656   // NB: This is a SharedDummyTrack to allow non-default graphs (AudioContexts
1657   // with an explicit sampleRate defined) to capture this element. When
1658   // cross-graph tracks are supported, this can become a bool.
1659   Watchable<RefPtr<SharedDummyTrack>> mTracksCaptured;
1660 
1661   // True if the sound is being captured.
1662   bool mAudioCaptured = false;
1663 
1664   // If TRUE then the media element was actively playing before the currently
1665   // in progress seeking. If FALSE then the media element is either not seeking
1666   // or was not actively playing before the current seek. Used to decide whether
1667   // to raise the 'waiting' event as per 4.7.1.8 in HTML 5 specification.
1668   bool mPlayingBeforeSeek = false;
1669 
1670   // True if this element is suspended because the document is inactive or the
1671   // inactive docshell is not allowing media to play.
1672   bool mSuspendedByInactiveDocOrDocshell = false;
1673 
1674   // True if we're running the "load()" method.
1675   bool mIsRunningLoadMethod = false;
1676 
1677   // True if we're running or waiting to run queued tasks due to an explicit
1678   // call to "load()".
1679   bool mIsDoingExplicitLoad = false;
1680 
1681   // True if we're loading the resource from the child source elements.
1682   bool mIsLoadingFromSourceChildren = false;
1683 
1684   // True if we're delaying the "load" event. They are delayed until either
1685   // an error occurs, or the first frame is loaded.
1686   bool mDelayingLoadEvent = false;
1687 
1688   // True when we've got a task queued to call SelectResource(),
1689   // or while we're running SelectResource().
1690   bool mIsRunningSelectResource = false;
1691 
1692   // True when we already have select resource call queued
1693   bool mHaveQueuedSelectResource = false;
1694 
1695   // True if we suspended the decoder because we were paused,
1696   // preloading metadata is enabled, autoplay was not enabled, and we loaded
1697   // the first frame.
1698   bool mSuspendedAfterFirstFrame = false;
1699 
1700   // True if we are allowed to suspend the decoder because we were paused,
1701   // preloading metdata was enabled, autoplay was not enabled, and we loaded
1702   // the first frame.
1703   bool mAllowSuspendAfterFirstFrame = true;
1704 
1705   // True if we've played or completed a seek. We use this to determine
1706   // when the poster frame should be shown.
1707   bool mHasPlayedOrSeeked = false;
1708 
1709   // True if we've added a reference to ourselves to keep the element
1710   // alive while no-one is referencing it but the element may still fire
1711   // events of its own accord.
1712   bool mHasSelfReference = false;
1713 
1714   // True if we've received a notification that the engine is shutting
1715   // down.
1716   bool mShuttingDown = false;
1717 
1718   // True if we've suspended a load in the resource selection algorithm
1719   // due to loading a preload:none media. When true, the resource we'll
1720   // load when the user initiates either playback or an explicit load is
1721   // stored in mPreloadURI.
1722   bool mSuspendedForPreloadNone = false;
1723 
1724   // True if we've connected mSrcStream to the media element output.
1725   bool mSrcStreamIsPlaying = false;
1726 
1727   // True if we should set nsIClassOfService::UrgentStart to the channel to
1728   // get the response ASAP for better user responsiveness.
1729   bool mUseUrgentStartForChannel = false;
1730 
1731   // The CORS mode when loading the media element
1732   CORSMode mCORSMode = CORS_NONE;
1733 
1734   // Info about the played media.
1735   MediaInfo mMediaInfo;
1736 
1737   // True if the media has encryption information.
1738   bool mIsEncrypted = false;
1739 
1740   enum WaitingForKeyState {
1741     NOT_WAITING_FOR_KEY = 0,
1742     WAITING_FOR_KEY = 1,
1743     WAITING_FOR_KEY_DISPATCHED = 2
1744   };
1745 
1746   // True when the CDM cannot decrypt the current block due to lacking a key.
1747   // Note: the "waitingforkey" event is not dispatched until all decoded data
1748   // has been rendered.
1749   WaitingForKeyState mWaitingForKey = NOT_WAITING_FOR_KEY;
1750 
1751   // Listens for waitingForKey events from the owned decoder.
1752   MediaEventListener mWaitingForKeyListener;
1753 
1754   // Init Data that needs to be sent in 'encrypted' events in MetadataLoaded().
1755   EncryptionInfo mPendingEncryptedInitData;
1756 
1757   // True if the media's channel's download has been suspended.
1758   Watchable<bool> mDownloadSuspendedByCache = {
1759       false, "HTMLMediaElement::mDownloadSuspendedByCache"};
1760 
1761   // Disable the video playback by track selection. This flag might not be
1762   // enough if we ever expand the ability of supporting multi-tracks video
1763   // playback.
1764   bool mDisableVideo = false;
1765 
1766   RefPtr<TextTrackManager> mTextTrackManager;
1767 
1768   RefPtr<AudioTrackList> mAudioTrackList;
1769 
1770   RefPtr<VideoTrackList> mVideoTrackList;
1771 
1772   UniquePtr<MediaStreamTrackListener> mMediaStreamTrackListener;
1773 
1774   // The principal guarding mVideoFrameContainer access when playing a
1775   // MediaStream.
1776   nsCOMPtr<nsIPrincipal> mSrcStreamVideoPrincipal;
1777 
1778   // True if the autoplay media was blocked because it hadn't loaded metadata
1779   // yet.
1780   bool mBlockedAsWithoutMetadata = false;
1781 
1782   // This promise is used to notify MediaElementAudioSourceNode that media
1783   // element is allowed to play when MediaElement is used as a source for web
1784   // audio.
1785   MozPromiseHolder<GenericNonExclusivePromise> mAllowedToPlayPromise;
1786 
1787   // True if media has ever been blocked for autoplay, it's used to notify front
1788   // end to show the correct blocking icon when the document goes back from
1789   // bfcache.
1790   bool mHasEverBeenBlockedForAutoplay = false;
1791 
1792   // True if we have dispatched a task for text track changed, will be unset
1793   // when we starts processing text track changed.
1794   // https://html.spec.whatwg.org/multipage/media.html#pending-text-track-change-notification-flag
1795   bool mPendingTextTrackChanged = false;
1796 
1797  public:
1798   // This function will be called whenever a text track that is in a media
1799   // element's list of text tracks has its text track mode change value
1800   void NotifyTextTrackModeChanged();
1801 
1802  private:
1803   friend class nsMediaEventRunner;
1804   friend class nsResolveOrRejectPendingPlayPromisesRunner;
1805 
1806   already_AddRefed<PlayPromise> CreatePlayPromise(ErrorResult& aRv) const;
1807 
MaybeBeginCloningVisually()1808   virtual void MaybeBeginCloningVisually(){};
1809 
1810   uint32_t GetPreloadDefault() const;
1811   uint32_t GetPreloadDefaultAuto() const;
1812 
1813   /**
1814    * This function is called by AfterSetAttr and OnAttrSetButNotChanged.
1815    * It will not be called if the value is being unset.
1816    *
1817    * @param aNamespaceID the namespace of the attr being set
1818    * @param aName the localname of the attribute being set
1819    * @param aNotify Whether we plan to notify document observers.
1820    */
1821   void AfterMaybeChangeAttr(int32_t aNamespaceID, nsAtom* aName, bool aNotify);
1822 
1823   // True if Init() has been called after construction
1824   bool mInitialized = false;
1825 
1826   // True if user has called load(), seek() or element has started playing
1827   // before. It's *only* use for `click-to-play` blocking autoplay policy.
1828   // In addition, we would reset this once media aborts current load.
1829   bool mIsBlessed = false;
1830 
1831   // True if the first frame has been successfully loaded.
1832   Watchable<bool> mFirstFrameLoaded = {false,
1833                                        "HTMLMediaElement::mFirstFrameLoaded"};
1834 
1835   // Media elements also have a default playback start position, which must
1836   // initially be set to zero seconds. This time is used to allow the element to
1837   // be seeked even before the media is loaded.
1838   double mDefaultPlaybackStartPosition = 0.0;
1839 
1840   // True if media element has been marked as 'tainted' and can't
1841   // participate in video decoder suspending.
1842   bool mHasSuspendTaint = false;
1843 
1844   // True if media element has been forced into being considered 'hidden'.
1845   // For use by mochitests. Enabling pref "media.test.video-suspend"
1846   bool mForcedHidden = false;
1847 
1848   Visibility mVisibilityState = Visibility::Untracked;
1849 
1850   UniquePtr<ErrorSink> mErrorSink;
1851 
1852   // This wrapper will handle all audio channel related stuffs, eg. the
1853   // operations of tab audio indicator, Fennec's media control. Note:
1854   // mAudioChannelWrapper might be null after GC happened.
1855   RefPtr<AudioChannelAgentCallback> mAudioChannelWrapper;
1856 
1857   // A list of pending play promises. The elements are pushed during the play()
1858   // method call and are resolved/rejected during further playback steps.
1859   nsTArray<RefPtr<PlayPromise>> mPendingPlayPromises;
1860 
1861   // A list of already-dispatched but not yet run
1862   // nsResolveOrRejectPendingPlayPromisesRunners.
1863   // Runners whose Run() method is called remove themselves from this list.
1864   // We keep track of these because the load algorithm resolves/rejects all
1865   // already-dispatched pending play promises.
1866   nsTArray<nsResolveOrRejectPendingPlayPromisesRunner*>
1867       mPendingPlayPromisesRunners;
1868 
1869   // A pending seek promise which is created at Seek() method call and is
1870   // resolved/rejected at AsyncResolveSeekDOMPromiseIfExists()/
1871   // AsyncRejectSeekDOMPromiseIfExists() methods.
1872   RefPtr<dom::Promise> mSeekDOMPromise;
1873 
1874   // Return true if the docshell is inactive and explicitly wants to stop media
1875   // playing in that shell.
1876   bool ShouldBeSuspendedByInactiveDocShell() const;
1877 
1878   // For debugging bug 1407148.
1879   void AssertReadyStateIsNothing();
1880 
1881   // Contains the unique id of the sink device and the device info.
1882   // The initial value is ("", nullptr) and the default output device is used.
1883   // It can contain an invalid id and info if the device has been
1884   // unplugged. It can be set to ("", nullptr). It follows the spec attribute:
1885   // https://w3c.github.io/mediacapture-output/#htmlmediaelement-extensions
1886   // Read/Write from the main thread only.
1887   std::pair<nsString, RefPtr<AudioDeviceInfo>> mSink;
1888 
1889   // This flag is used to control when the user agent is to show a poster frame
1890   // for a video element instead of showing the video contents.
1891   // https://html.spec.whatwg.org/multipage/media.html#show-poster-flag
1892   bool mShowPoster;
1893 
1894   // We may delay starting playback of a media for an unvisited tab until it's
1895   // going to foreground. We would create ResumeDelayedMediaPlaybackAgent to
1896   // handle related operations at the time whenever delaying media playback is
1897   // needed.
1898   void CreateResumeDelayedMediaPlaybackAgentIfNeeded();
1899   void ClearResumeDelayedMediaPlaybackAgentIfNeeded();
1900   RefPtr<ResumeDelayedPlaybackAgent> mResumeDelayedPlaybackAgent;
1901   MozPromiseRequestHolder<ResumeDelayedPlaybackAgent::ResumePromise>
1902       mResumePlaybackRequest;
1903 
1904   // Return true if we have already a decoder or a src stream and don't have any
1905   // error.
1906   bool IsPlayable() const;
1907 
1908   // Return true if the media qualifies for being controlled by media control
1909   // keys.
1910   bool ShouldStartMediaControlKeyListener() const;
1911 
1912   // Start the listener if media fits the requirement of being able to be
1913   // controlled be media control keys.
1914   void StartMediaControlKeyListenerIfNeeded();
1915 
1916   // It's used to listen media control key, by which we would play or pause
1917   // media element.
1918   RefPtr<MediaControlKeyListener> mMediaControlKeyListener;
1919 
1920   // Method to update audio stream name
1921   void UpdateStreamName();
1922 
1923   // Return true if the media element is being used in picture in picture mode.
1924   bool IsBeingUsedInPictureInPictureMode() const;
1925 
1926   // Return true if we should queue a 'timeupdate' event runner to main thread.
1927   bool ShouldQueueTimeupdateAsyncTask(TimeupdateType aType) const;
1928 };
1929 
1930 // Check if the context is chrome or has the debugger or tabs permission
1931 bool HasDebuggerOrTabsPrivilege(JSContext* aCx, JSObject* aObj);
1932 
1933 }  // namespace dom
1934 }  // namespace mozilla
1935 
1936 #endif  // mozilla_dom_HTMLMediaElement_h
1937