/** * Custom HTML element for Movi Player * Usage: * * Note: Custom element names must contain a hyphen per HTML spec. * * Supports native video element properties: * - src, autoplay, controls, loop, muted, playsinline, preload, poster * - width, height, crossorigin * - volume, playbackRate, currentTime, duration, paused, ended */ import type { RendererType } from "../types"; import type { SourceAdapter } from "../source/SourceAdapter"; export declare class MoviElement extends HTMLElement { private canvas; private video; private subtitleOverlay; private player; private isLoading; private _isUnsupported; private eventHandlers; private controlsContainer; private unmuteOverlay; private _userHasUnmuted; private brokenIndicator; private emptyStateIndicator; private coverArtOverlay; private coverArtCanvas; private coverArtBitmap; private _posterCoverBitmap; private _posterCoverUrl; private _posterCoverLoading; private _coverArtBgEl; private _coverArtResolved; private controlsTimeout; private isOverControls; private isSeeking; private pendingSeekTarget; private _pendingSeek; private isDragging; private isTouchDragging; private touchStartX; private touchStartY; private touchStartTime; private gesturePerformed; private clickTimer; private lastSeekTime; private lastSeekSide; private cumulativeSeekAmount; private _seekChainTarget; private _contextMenuVisible; private _contextMenuJustClosed; private lastTouchTime; private _nerdStatsVisible; private _currentManualRotation; private _timelineGenerating; private _timelineCancelled; private _timelineComplete; private _timelineNextIndex; private nerdStatsInterval; private networkSpeedHistory; private static readonly GRAPH_MAX_SAMPLES; private _src; private _sourceAdapter; private _headers; private _audioOnly; private _audioSrc; private _videoQualities; private _audioTracks; private _subtitleTracks; private _autoplay; private _autoplayStarting; private _autoplayPendingVisible; private _autoMutedForAutoplay; private _hasEverPlayed; private _loopRestartInFlight; private _pendingPlay; private _preloadGateActive; private _resumeDialogPending; private _posterTime; private _generatedPosterUrl; private _posterGenId; private _controls; private _loop; private _muted; private _playsinline; private _preload; private _poster; private _volume; private _playbackRate; private _subtitleDelay; private _subtitleSettings; private _ambientMode; private _renderer; private _objectFit; private _currentFit; private _thumb; private _linearMode; private _hdr; private _theme; private _sw; private _swForcedForCurrentSource; private _suppressSwReload; private _fps; private _gesturefs; private _noHotkeys; private _startAt; private _fastSeek; private _doubleTap; private _themeColor; private _bufferSize; private _title; private _showTitle; private _resume; private _stableVolume; private _audioOutputDeviceId; private _audioOutputs; private _audioOutputsBound; private _vr360; private _vrPointerDown; private _vrMoved; private _vrLastX; private _vrLastY; private _vrPinchDist; private _vrSuppressClick; private _vrPadDragging; private _encrypted; private _tokenUrl; private _videoUrl; private _videoId; private _resumeSaveInterval; private _posterSeekActive; private _titleAutoLoaded; private _resumeCheckedWithTitle; private _stripTitleAttr; private _lastDuration; private posterElement; private _ambientWrapper; private ambientWrapperElement; private _ambientRafId; private _lastAmbientSampleTime; private _lastRateChangeTime; private static readonly AMBIENT_RATE_CHANGE_COOLDOWN_MS; private _ambientSampleInterval; private currentAmbientColors; private _contextLostTime; private _contextLostPlaying; private _lastFrameSnapshot; private _snapshotPosterActive; private _snapshotPosterPrev; private _showSnapshotPoster; private _hideSnapshotPoster; private _onVisibilityChange; static get observedAttributes(): string[]; constructor(); private createContextMenu; private createControls; private setupControlHandlers; private seekFromEvent; private seekFromTouchEvent; private setupGestures; /** * 360° look-around for mouse + trackpad. Touch is handled inside * setupGestures (it already owns touchstart/move). These listeners no-op * unless 360° mode is active, and a drag past a few pixels suppresses the * trailing click so dragging never toggles play/pause. */ private setupVRControls; /** * Enable/disable VR rendering and pick the format: * - half: VR180 (front hemisphere) vs full 360°. * - fisheye: equidistant fisheye vs equirectangular. * - sbs: side-by-side stereo (render the left eye) vs mono. * Forwards to the player's renderer and flips the host class (for cursor + * touch-action CSS). There's no toggle button: VR turns on automatically for * sources we know are 360/180 (spherical metadata or the `vr` attribute), the * same way YouTube treats them. */ setVR360(enabled: boolean, half?: boolean, fisheye?: boolean, sbs?: boolean, stereographic?: boolean): void; /** * When a custom/generated poster image is showing and 360° is on, draw the * poster onto the canvas through the equirectangular projection (so it looks * right, not flat-distorted) and hide the flat overlay. No-op for the * decoded-frame poster path (seek/postertime) — that already paints in 360. */ private renderVRPosterIfNeeded; /** * Resolve the VR format for the CURRENT source from spherical metadata * (track.projection) + the live `vr` attribute. Never carries the previous * clip's state over — switching to a normal clip drops back to flat unless * `vr` is still set. * * `vr` attribute tokens (space/comma separated), e.g. `vr="fisheye sbs"`: * (bare) / 360 → full 360°; 180 → VR180; sbs / 3d → side-by-side stereo * (left eye); fisheye → equidistant fisheye (implies 180). * * projection metadata: 0/undefined = none; 1 = equirectangular; * 3 = equirectangular-tile; 4 = half-equirectangular (VR180). Stereo/fisheye * aren't auto-surfaced, so those need the attribute. */ private resolveVRMode; /** Apply the resolved VR format to the renderer (enable OR disable). */ private detectAndApplyVR360; private setupKeyboardShortcuts; private setupContextMenu; private updateContextMenuContent; private setupSubmenuHover; private toggleFullscreen; private _pipWindow; private restorePiPCanvas; private togglePiP; /** Tracks host-driven fullscreen so toggleFullscreen() and the * movi-fullscreen-request event can reflect it correctly even when * document.fullscreenElement is null. */ private _hostFullscreen; private updateFullscreenIcon; private updateFullscreenContextMenu; private applyFullscreenUiState; /** * Public hook for hosts (VS Code extension, embedded apps) that take over * fullscreen via the cancelable `movi-fullscreen-request` event. Call this * whenever the host enters/exits its custom fullscreen so the player's * toolbar icon and right-click context menu reflect the correct state. */ setHostFullscreen(active: boolean): void; private static readonly ASPECT_ICONS; private updateAspectRatioIcon; private static readonly TRACK_ICON_AUDIO; private static readonly TRACK_ICON_SUBTITLE; private static readonly TRACK_ICON_OFF; private static readonly TRACK_ICON_CHECK; private formatAudioBadge; private formatSubtitleBadge; private updateAudioTrackMenu; private updateQualityMenu; /** * Map a video height to its YouTube-style quality badge (HD/4K/8K) or * empty string when the resolution doesn't qualify. */ private _heightBadge; /** * Paint or hide the small badge pill on the gear button itself so the * user can see the active quality tier at a glance — same convention * as YouTube's player. */ private _updateQualityBtnBadge; /** * Render a quality menu for pre-muxed multi-source MP4s (no HLS manifest). * Driven by the cached `_videoQualities` list; switching just swaps the * active URL and lets the existing src-change pipeline reload * the player while preserving currentTime / paused state. */ private renderPremuxedQualityMenu; private _carryAudioEl; private _qualitySwitchInProgress; private _switchResumeTime; private _switchResumeDuration; /** * Swap the active video source and resume playback at the same position. * The src setter pipeline tears down the player; we re-seek once metadata * is available on the new instance. */ private switchPremuxedQuality; private getMaxAllowedRate; /** * Show On-Screen Display (OSD) notification */ private osdTimeout; private showOSD; private static readonly SUBTITLE_SETTINGS_STORAGE_KEY; /** * Returns the kind of subtitle currently active so the customize * panel can show only the options that apply. * * - "vtt" → WebVTT (karaoke-paced from YouTube proxy etc): all * text styling options apply, INCLUDING the backdrop. * - "text" → SRT/ASS/SSA/TTML or muxed text subs: size/color/edge * and shift apply; backdrop doesn't (it's gated to VTT * in CSS). * - "image" → PGS/DVD/DVB or other muxed image subs: only the * subtitle-shift control applies; styling is baked * into the bitmap. * - null → no subtitle selected → no customize gear shown. */ private getActiveSubtitleKind; private static readonly SUBTITLE_EDGE_STYLES; private static readonly SUBTITLE_COLOR_PALETTE; private loadSubtitleSettings; private saveSubtitleSettings; private applySubtitleSettings; /** * Apply one of the public subtitle-customize attributes onto * _subtitleSettings. Returns true if the attribute name matched * (caller can decide whether to call applySubtitleSettings()). * * subtitlesize="150" (50–200, treated as %; also accepts 1.5) * subtitlecolor="#FFEB3B" (any CSS color hex, 3 or 6 digits) * subtitlebg="50" (0–100, treated as %; also accepts 0.5) * subtitleedge="outline" (none | shadow | outline | raised) */ private applySubtitleAttribute; /** * Pick a backdrop RGB that contrasts with the text color so the cue * stays readable regardless of the user's color choice. Dark text on * dark backdrop (or vice versa) would render the subtitle invisible. */ private static contrastBackdropRgb; private renderSubtitleCustomizePanel; private wireSubtitleCustomizePanel; private _showingSubtitleCustomize; private _cuesPanelCues; private _cuesPanelFiltered; private _cuesPanelQuery; private _cuesPanelActiveIdx; private _cuesPanelTimeUpdateUnsub; private _cuesPanelEscHandler; private openCuesPanel; private closeCuesPanel; private renderCuesPanel; private updateCuesPanelActive; private updateSubtitleTrackMenu; /** * True when an actual media source is loaded (plain src, a caller-supplied * SourceAdapter, or the encrypted video URL). Used to gate the controls * auto-hide — in the empty "No Video" state we keep the bar pinned. */ private hasMediaSource; /** * Switch the UI into linear (forward-only) playback: the source has no Range * support and is too big to cache, so seeking is impossible. Hide the * timeline and disable seek + thumbnail previews via the `movi-linear` host * class. Idempotent — safe to call from both the event and the loadEnd * backstop. */ /** * In linear (non-seekable-source) playback only the bytes currently in the * RAM window are reachable, so clamp any seek target to the buffered time * range [bufferStart, bufferEnd]. A small margin keeps the (approximate, * linear byte→time) clamp safely inside the window so the keyframe for the * target is actually present. Returns the time unchanged when not linear. */ private clampToBufferedWindow; private enterLinearMode; /** * Mirror "is the controls bar currently taking up bottom space?" onto a * plain host class so the empty-state placeholder can re-center reliably. * The old approach keyed off `:host:has(.movi-controls-hidden)` / * `:host(:not([controls]))`, but `:has()` is flaky in Safari/Firefox (and * an unsupported selector in a comma list drops the WHOLE rule), which left * the "No Video" text stuck off-center there. `:host(.movi-bar-collapsed)` * is universally supported, so the centering works in every browser. */ private syncBarCollapsedClass; private showControls; /** * Close every bottom-controls dropdown (speed, audio, subtitle, * quality) plus the context menu. Used to enforce one-menu-at-a-time * and to swallow a player-area click when a menu is open. * Pass a `keep` selector to skip closing the menu currently being * opened, otherwise everything goes away. */ private closeAllBottomMenus; /** * Toggle a bottom-bar dropdown with a pop-in / pop-out animation. * Inline display:none stays the truly-hidden terminal state so the * existing dom-presence checks elsewhere keep working — we just clear * it on open, run the CSS transition, and restore it once the exit * transition finishes. */ private setBottomMenuOpen; /** * Strip-mode menu positioning: place the menu just below the anchor * button using viewport-relative position:fixed. The strip CSS drops * the host's `contain: paint` + `container-type` so fixed coords are * actually viewport-relative again (default behaviour) and paint * extends outside the 56px strip box. */ private applyStripFixedMenuPosition; private isBottomMenuOpen; /** * Restart the subtle fade-in on the subtitle dropdown's content area so * toggling between the track list and the customize panel feels like a * crossfade rather than a snap. Removing + re-adding the class with a * forced reflow restarts the CSS animation; without the reflow the * browser deduplicates the class change and the animation never replays. */ private flashSubtitleListFade; /** * Hide the seek OSD pill immediately and reset the chain state. * Used when a relative-seek press lands on the boundary (delta 0) * so the previous chain's "- 25s" cue doesn't keep reading like the * playhead has gone past zero — the cue had served its purpose * before the boundary press, but holding it on screen with no * forward movement is what the user sees as "minus". */ private dismissSeekOSD; /** * Run a relative seek (button / key / double-tap) and surface it * through the OSD. The OSD label tracks the *actual* delta between * the pre-seek time and the clamped target — so pressing left at 5s * with a 10s step shows "- 5s", not "- 10s", and a follow-up press * at 0s suppresses the OSD entirely instead of accumulating phantom * seconds the playhead never travelled. Same on the duration end. * * For rapid chained presses we anchor "before" on the previous * target rather than the (still-stale) playback time, so the cue * tracks where the playhead is *headed* even mid-seek. */ private performRelativeSeek; /** * The Timeline panel (opened with "T") sits just above the controls bar but * is a shadow-root sibling of the controls container, so hovering it never * sets isOverControls — without this the 3s inactivity auto-hide fires while * the user scrubs the storyboard. Gates ONLY the inactivity timer (in * showControls) so the bar stays put while the timeline is open; the * cursor-left-the-controls / cursor-left-the-player hides keep their normal * behavior. Kept out of isAnyMenuOpen(), which also drives click-to-close. */ private isTimelineOpen; /** True when the engine can route output to a chosen device. */ private static audioSinkSupported; /** * List the available audio output devices. Labels may be empty until the * page has been granted audio-device access (the desktop app has it; a bare * web embed may show blank labels until a getUserMedia prompt is accepted). */ getAudioOutputs(): Promise>; /** Current audio output device id ("" = system default). */ getAudioOutput(): string; /** * Route audio to a device. Accepts a concrete deviceId, or — for * convenience — a label substring (case-insensitive); "" / "default" → * the system default. Returns false when unsupported or the device is gone. */ setAudioOutput(deviceId: string): Promise; /** Resolve a deviceId or a label substring to a concrete deviceId. */ private resolveAudioOutputId; /** Apply the `audiooutput` attribute once the player exists. */ private applyAudioOutput; /** * Cache the device list, re-applying any pending attribute selection and * re-rendering the menu. Bound once to `devicechange` so hot-plugging a * headset updates the list live. */ private setupAudioOutputs; /** Refresh the cached device list and re-render the menu if it's open. */ private refreshAudioOutputs; /** * Browsers only expose output device ids/labels after the page holds audio * permission. When the user clicks "Show output devices…" in the (otherwise * locked) submenu, request mic permission — the universal unlock, same as * Google Meet — then re-render with the now-visible devices and re-open the * submenu. Triggered from an explicit click so the prompt has a user * gesture. No-op in the desktop app (devices already visible). */ private unlockAudioOutputs; /** (Re)build the Audio Output submenu from the cached device list. */ private updateAudioOutputMenu; private isAnyMenuOpen; private hideControls; private updateControlsVisibility; private startUIUpdates; private addStyles; private handleContextLost; private handleContextRestored; connectedCallback(): void; disconnectedCallback(): void; attributeChangedCallback(name: string, _oldValue: string | null, newValue: string | null): void; private _lastCanvasW; private _lastCanvasH; private updateCanvasSize; /** * Toggle the LIVE indicator for live (dynamic) adaptive streams. Adds the * `.movi-live` host class (CSS shows the badge + hides the meaningless * wall-clock duration), and marks the badge `.behind` when the viewer has * scrubbed back into the DVR window so it reads grey instead of pulsing red. * Cheap + idempotent — safe to call on every timeupdate. */ private updateLiveState; /** * Paint embedded cover art (audio-only sources). Shows when: * - the player has emitted a coverart bitmap, AND * - there is no active video track (a real video would mask this anyway, * but hiding upfront keeps unnecessary canvas work off the critical * path for plain video files that happen to ship a thumbnail track). * * Layout: blurred fill of the artwork stretched over the full surface, * with the sharp artwork centred and sized to ~60% of the smaller host * dimension. Matches the YouTube Music / Apple Music aesthetic. */ /** * For an audio-only source with a `poster` URL and no embedded album art, * lazily load the poster into an ImageBitmap so updateCoverArtOverlay can * paint it as album art (via the same blurred-backdrop cover-art canvas). * Idempotent: loads once per URL, clears when no longer applicable (source * became video, poster cleared, or embedded art arrived). Re-runs * updateCoverArtOverlay once the bitmap is ready. */ private ensurePosterCoverArt; private updateCoverArtOverlay; /** * After an autoplay attempt, detect the browser blocking audio-with-sound * (AudioContext stuck suspended) and fall back to muted playback so the * video keeps rolling, then surface the "Tap to unmute" pill. No-op when * the user already asked for muted, has deliberately unmuted this session, * there's no audible source, or audio actually started. The AudioContext * resume() kicked off inside play() is async, so we give it a couple of * animation frames to settle before reading the state. */ /** * Kick off autoplay: suppress the centre play overlay through the startup * window, call play(), and run the muted-autoplay fallback. Shared by the * initial load and the deferred (tab-was-hidden) path in _onVisibilityChange. */ private _startAutoplay; private maybeFallbackToMutedAutoplay; private updateMuted; /** * Show a "Tap to unmute" pill when the player is set up to autoplay * muted (browsers block autoplay-with-sound) and the user has asked * for controls. Hides as soon as the player isn't muted, one of the * prerequisite attributes drops, or audio-track discovery proves * there's no audio to surface — reusing the same hasAudibleSource() * check that gates the volume button (see updateAudioTrackMenu). * Before the player is initialized hasAudibleSource() can't be * answered, so we optimistically show the pill on attrs alone and * let updateAudioTrackMenu re-call this once tracks are known. */ private updateUnmuteOverlay; private updateVolume; private updateSubtitleDelay; private updatePlaybackRate; private updateFitMode; private posterObjectFit; /** * Automatically create and initialize MoviPlayer */ private initializePlayer; /** * Set up event handlers for the player */ private setupEventHandlers; /** * Load the video source (automatic when src is set) */ load(): Promise; /** * Play the video */ play(): Promise; /** * Pause the video */ pause(): void; /** * Tear down the internal player and reset transient UI (time, title, * subtitles, timeline) back to the initial, no-source state. Called * internally on every src change so the next source starts clean. Safe to * call when nothing is loaded. * * Note: we deliberately do NOT touch the canvas or the native video * element — the canvas owns a WebGL2 context that the next renderer reuses, * and resetting the