import { Controller } from "@hotwired/stimulus" import { WebVttParser } from "player/web_vtt_parser" import { PlaybackCoordinator } from "player/playback_coordinator" import { nextEpisodePromptStart } from "player/next_episode_prompt" const MIN_VALID_DURATION_SECONDS = 60 const SUBTITLE_STARTUP_WINDOW_SECONDS = 5 const SUBTITLE_STARTUP_LOOK_BEHIND_SECONDS = 2 const STREAM_STALL_TIMEOUT_MS = 60000 const BUFFER_AHEAD_SECONDS = 30 const BUFFER_AHEAD_MAX_WAIT_MS = 15000 // After a stall, rebuild a meaningful buffer before resuming so ffmpeg // can catch up and transient upstream dips don't cause immediate // re-stall. 10s absorbs variable-rate sources (RealDebrid links from // torrent swarms, HEVC transcode below 1×) without making the user wait // 30s. The original 30s was raised to fix a userPaused auto-resume bug // that has since been fixed — 10s is sufficient to absorb transcode dips // while keeping the wait tolerable. const REBUFFER_AHEAD_SECONDS = 10 // Stall watchdog timeout for rebuffer stalls (playback already started). // Must be longer than REBUFFER_MAX_WAIT_MS so the deadline (which resumes // with partial buffer) fires before the watchdog (which reconnects). // 20s gives ffmpeg time to accumulate buffer; if no data arrives for 20s // the fetch is truly dead. const REBUFFER_STALL_TIMEOUT_MS = 20000 // Maximum time to wait for the rebuffer gate (REBUFFER_AHEAD_SECONDS) // before resuming with whatever buffer has accumulated. On a slow // or trickling source, data arrives in small bursts that never reach // the gate threshold — without a deadline, the video would sit on // "Buffering" forever. 12s gives ffmpeg time to build buffer even on // a slow source; the stall watchdog handles a genuinely dead source. const REBUFFER_MAX_WAIT_MS = 12000 const MSE_FORWARD_BUFFER_HIGH_SECONDS = 45 const MSE_FORWARD_BUFFER_LOW_SECONDS = 30 const MSE_PENDING_BUFFER_HIGH_BYTES = 16 * 1024 * 1024 const MSE_PENDING_BUFFER_LOW_BYTES = 8 * 1024 * 1024 const MSE_CAPACITY_POLL_MS = 250 const MSE_MIME_TYPE = 'video/mp4; codecs="avc1.640028,mp4a.40.2"' const REMUX_PRESENTATION_PROBE_SECONDS = 0.001 const REMUX_PRESENTATION_PROBE_TIMEOUT_MS = 500 const MAX_REMUX_PRESENTATION_OFFSET_SECONDS = 1 const REMUX_SEEK_TOLERANCE_SECONDS = 0.25 const REMUX_SEEK_TIMEOUT_MS = 500 const INTERACTIVE_SELECTOR = "button, a, input, textarea, select, [contenteditable='true']" const SAFARI_AUTOPLAY_GUIDANCE_KEY = "streamvault:safari-autoplay-guidance-seen" // Remembers the quality menu across page loads; episode changes keep the rung. const QUALITY_STORAGE_KEY = "streamvault:quality" const QUALITY_OPTIONS = [ "auto", "1080p", "720p", "480p" ] export default class extends Controller { static get targets() { return [ "video", "controls", "seekBar", "seekFilled", "seekBuffered", "seekHandle", "playButton", "playIcon", "pauseIcon", "currentTime", "durationDisplay", "volumeIcon", "muteIcon", "startupOverlay", "startupStatus", "autoplayGuidance", "autoplayPlayButton", "seekingOverlay", "seekingOverlayMessage", "sourceInfo", "sourceToggle", "sourceDetails", "sourceUrl", "sourceFilename", "backButton", "audioControls", "audioMenu", "audioOptions", "audioButtonLabel", "subtitleControls", "subtitleMenu", "subtitleOptions", "subtitleButtonLabel", "subtitleOverlay", "quality", "nextEpisodePrompt", "nextEpisodeButton", "nextEpisodeStatus" ] } static get values() { return { streamingUrl: String, source: String, directStreamUrl: String, filename: String, imdbId: String, type: String, directPlayHint: Boolean, season: String, episode: String, resumeAt: String, startSeconds: Number, title: String, duration: Number, posterUrl: String, defaultLanguage: String, preferredLanguages: String, tracksUrl: String, seekUrl: String, subtitlesUrl: String, resumeUrl: String, nextEpisodeUrl: String, nextEpisodePromptSeconds: { type: Number, default: 90 } } } connect() { this.invalidatePlaybackRequest() this.playbackDisconnected = false this.nextEpisode = null this.nextEpisodeRequest = null this.nextEpisodeAbortController = null this.advancingEpisode = false this.progressInterval = null this.uiHideTimer = null this.knownDuration = this.validDuration(this.durationValue) ? this.durationValue : 0 this.isSeeking = false this.isDragging = false this.mouseMoveHandler = this.onMouseMove.bind(this) this.keydownHandler = this.onKeyDown.bind(this) this.videoClickHandler = this.onVideoClick.bind(this) this.documentClickHandler = this.onDocumentClick.bind(this) this.updatePlayIconHandler = this.updatePlayIcon.bind(this) this.timeUpdateHandler = this.onTimeUpdate.bind(this) this.progressHandler = this.onProgress.bind(this) this.volumeChangeHandler = this.updateVolumeIcon.bind(this) this.videoWaitingHandler = () => this.onVideoWaiting() this.videoReadyHandler = () => this.onVideoReady() this.playbackObservationResetHandler = () => { this.playbackObservation = null clearTimeout(this.bufferingOverlayTimer) this.bufferingOverlayTimer = null this.updateNextEpisodePrompt() } // Transcode quality: "auto" lets the server pick (CRF, capped at 1080p). // A fixed rung caps resolution and bitrate; auto mode also steps down a // rung after repeated stalls so a slow link settles instead of looping. this.quality = this.storedQuality() this.autoQuality = this.quality === "auto" this.autoQualityStalls = 0 this.syncQualitySelect() this.audioTracks = [] this.subtitleTracks = [] this.selectedAudioStream = this.currentUrlParam("audio_stream") this.selectedSubtitleStream = this.currentUrlParam("subtitle_stream") this.subtitleCues = [] this.subtitleWindowStart = null this.subtitleWindowEnd = null this.subtitleLoading = false this.subtitleLoadToken = 0 this.subtitleAbortController = null this.subtitleRetryAfter = 0 this.subtitlePrefetches = new Map() this.subtitlePrefetchResults = new Map() this.subtitlePlaybackHoldToken = null this.tracksData = null this.mediaTracksLoaded = false this.directPlayActive = false this.primedDirectPlayUrl = null this.startupOverlayHideTimer = null this.playPromptCleanup = null this.dragMoveHandler = null this.suppressNextSeekClick = false this.suppressSeekClickTimer = null this.mediaSource = null this.sourceBuffer = null this.fetchController = null this.mseFetchEnded = false this.pendingSeekSeconds = null this.remuxLoadToken = 0 this.remuxSeekController = null this.remuxLoadCleanup = null this.stallWatchdogTimer = null this.bufferingOverlayTimer = null this.pendingAppendBuffer = null this.quotaRetryTimer = null this.quotaBlockedAtTime = null this.mseReadPaused = false this.mseQuotaErrorCount = 0 this.systemRebufferPaused = false this.rebufferDeadlineTimer = null this.bufferAheadDeadlineTimer = null this.prematureEndRecoveryTimer = null this.lastProgressTime = 0 this.lastProgressPosition = 0 this.lastBufferEnd = 0 this.lastBufferDataTime = 0 this.lastProgressEventTime = 0 this.progressWatchdogArmed = false this.streamRecoveryActive = false this.playbackStarted = false this.isStalled = false this.playbackObservation = null // True when the user deliberately paused (button/spacebar). The // rebuffer gate in maybeStartPlayback must never auto-resume a // user pause — only a rebuffer pause (buffer ran dry). this.userPaused = false // True once navigateBack has saved progress and aborted the fetch; // suppresses the duplicate save in the beforeunload handler. this.navigatingAway = false this.bufferAheadDeadline = null this.rebufferDeadline = null this.mseSupported = window.MediaSource && MediaSource.isTypeSupported(MSE_MIME_TYPE) this.hlsSessionId = null this.playbackId = globalThis.crypto?.randomUUID?.() || `${Date.now()}-${Math.random().toString(16).slice(2)}` // Show source info this.sourceInfoTarget.classList.remove("hidden") this.sourceUrlTarget.textContent = "Protected RealDebrid source" this.sourceFilenameTarget.textContent = this.filenameValue || "Unknown" this.showOverlayUi() this.element.addEventListener("mousemove", this.mouseMoveHandler) document.addEventListener("keydown", this.keydownHandler) document.addEventListener("click", this.documentClickHandler) // Video event listeners this.videoTarget.addEventListener("click", this.videoClickHandler) this.videoTarget.addEventListener("play", this.updatePlayIconHandler) this.videoTarget.addEventListener("pause", this.updatePlayIconHandler) this.videoTarget.addEventListener("timeupdate", this.timeUpdateHandler) this.videoTarget.addEventListener("progress", this.progressHandler) this.videoTarget.addEventListener("volumechange", this.volumeChangeHandler) this.videoTarget.addEventListener("waiting", this.videoWaitingHandler) this.videoTarget.addEventListener("playing", this.videoReadyHandler) for (const event of ["seeking", "seeked", "emptied"]) { this.videoTarget.addEventListener(event, this.playbackObservationResetHandler) } // canplay is intentionally NOT listened to — it fires when the browser // has just one frame, which hides the buffering overlay prematurely // during a stall. Confirm playback through "playing" or forward motion. this.videoEndedHandler = () => this.onVideoEnded() this.videoTarget.addEventListener("ended", this.videoEndedHandler) this.videoErrorHandler = (e) => this.onVideoError(e) this.videoTarget.addEventListener("error", this.videoErrorHandler) // Resume: transcode streams already start at the resume position // via ffmpeg -ss, so no client-side seek needed. Direct play uses // the native