Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions packages/core/src/runtime/bridge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ function createMockDeps() {
onPause: vi.fn(),
onSeek: vi.fn(),
onSetMuted: vi.fn(),
onSetVolume: vi.fn(),
onSetMediaOutputMuted: vi.fn(),
onSetPlaybackRate: vi.fn(),
onEnablePickMode: vi.fn(),
Expand Down Expand Up @@ -56,6 +57,29 @@ describe("installRuntimeControlBridge", () => {
expect(deps.onSetMuted).toHaveBeenCalledWith(true);
});

it("dispatches set-volume command", () => {
const deps = createMockDeps();
const handler = installRuntimeControlBridge(deps);
handler(makeControlMessage("set-volume", { volume: 0.5 }));
expect(deps.onSetVolume).toHaveBeenCalledWith(0.5);
});

it("clamps set-volume to [0, 1]", () => {
const deps = createMockDeps();
const handler = installRuntimeControlBridge(deps);
handler(makeControlMessage("set-volume", { volume: 1.5 }));
expect(deps.onSetVolume).toHaveBeenCalledWith(1);
handler(makeControlMessage("set-volume", { volume: -0.5 }));
expect(deps.onSetVolume).toHaveBeenCalledWith(0);
});

it("defaults volume to 1 when absent", () => {
const deps = createMockDeps();
const handler = installRuntimeControlBridge(deps);
handler(makeControlMessage("set-volume"));
expect(deps.onSetVolume).toHaveBeenCalledWith(1);
});

it("dispatches set-media-output-muted command", () => {
const deps = createMockDeps();
const handler = installRuntimeControlBridge(deps);
Expand Down
5 changes: 5 additions & 0 deletions packages/core/src/runtime/bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ type BridgeDeps = {
onPause: () => void;
onSeek: (frame: number, seekMode: "drag" | "commit") => void;
onSetMuted: (muted: boolean) => void;
onSetVolume: (volume: number) => void;
onSetMediaOutputMuted: (muted: boolean) => void;
onSetPlaybackRate: (rate: number) => void;
onEnablePickMode: () => void;
Expand Down Expand Up @@ -40,6 +41,10 @@ export function installRuntimeControlBridge(deps: BridgeDeps): (event: MessageEv
deps.onSetMuted(Boolean(data.muted));
return;
}
if (action === "set-volume") {
deps.onSetVolume(Math.max(0, Math.min(1, Number(data.volume ?? 1))));
return;
}
if (action === "set-media-output-muted") {
deps.onSetMediaOutputMuted(Boolean(data.muted));
return;
Expand Down
11 changes: 11 additions & 0 deletions packages/core/src/runtime/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1296,6 +1296,7 @@ export function initSandboxRuntimeModular(): void {
playbackRate: state.playbackRate,
outputMuted: state.mediaOutputMuted,
userMuted: state.bridgeMuted,
userVolume: state.bridgeVolume,
onAutoplayBlocked: () => {
if (state.mediaAutoplayBlockedPosted) return;
state.mediaAutoplayBlockedPosted = true;
Expand Down Expand Up @@ -1555,6 +1556,16 @@ export function initSandboxRuntimeModular(): void {
el.muted = effective;
}
},
onSetVolume: (volume) => {
state.bridgeVolume = volume;
const mediaEls = document.querySelectorAll("video, audio");
for (const el of mediaEls) {
if (!(el instanceof HTMLMediaElement)) continue;
const parsed = parseFloat(el.dataset.volume ?? "");
const clipVolume = Number.isFinite(parsed) ? parsed : 1;
el.volume = clipVolume * volume;
}
},
onSetMediaOutputMuted: (muted) => {
state.mediaOutputMuted = muted;
const effective = muted || state.bridgeMuted;
Expand Down
24 changes: 24 additions & 0 deletions packages/core/src/runtime/media.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,30 @@ describe("syncRuntimeMedia", () => {
expect(clip.el.volume).toBe(0.7);
});

it("applies userVolume as a multiplier on clip volume", () => {
const clip = createMockClip({ start: 0, end: 10, volume: 0.8 });
syncRuntimeMedia({
clips: [clip],
timeSeconds: 5,
playing: false,
playbackRate: 1,
userVolume: 0.5,
});
expect(clip.el.volume).toBeCloseTo(0.4);
});

it("applies userVolume to clips without explicit volume (default 1)", () => {
const clip = createMockClip({ start: 0, end: 10 });
syncRuntimeMedia({
clips: [clip],
timeSeconds: 5,
playing: false,
playbackRate: 1,
userVolume: 0.3,
});
expect(clip.el.volume).toBeCloseTo(0.3);
});

it("hard-syncs on the first active tick (sub-composition activation, mediaStart offsets)", () => {
const clip = createMockClip({ start: 0, end: 10, mediaStart: 0 });
Object.defineProperty(clip.el, "currentTime", { value: 0, writable: true });
Expand Down
8 changes: 7 additions & 1 deletion packages/core/src/runtime/media.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,11 @@ export function syncRuntimeMedia(params: {
* before the next bridge message lands.
*/
userMuted?: boolean;
/**
* User's volume preference (0–1, set via `onSetVolume`). Multiplied with the
* per-clip author volume so `data-volume="0.5"` at user volume 0.8 yields 0.4.
*/
userVolume?: number;
/**
* Invoked at most once when a media element's `play()` promise rejects with
* `NotAllowedError`. The caller is expected to latch and post a single
Expand All @@ -142,7 +147,8 @@ export function syncRuntimeMedia(params: {
relTime = clip.mediaStart + ((relTime - clip.mediaStart) % loopLength);
}
}
if (clip.volume != null) el.volume = clip.volume;
const userVol = params.userVolume ?? 1;
el.volume = (clip.volume ?? 1) * userVol;
if (shouldMute) el.muted = true;
// Ensure full preload for every active media element. Streaming
// formats (MP3) may arrive with preload="metadata", which only
Expand Down
2 changes: 2 additions & 0 deletions packages/core/src/runtime/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export type RuntimeState = {
parityModeEnabled: boolean;
canonicalFps: number;
bridgeMuted: boolean;
bridgeVolume: number;
/**
* Internal mute of audible media output, owned by the audio-ownership
* protocol between the parent (`<hyperframes-player>`) and this runtime.
Expand Down Expand Up @@ -78,6 +79,7 @@ export function createRuntimeState(): RuntimeState {
parityModeEnabled: true,
canonicalFps: 30,
bridgeMuted: false,
bridgeVolume: 1,
mediaOutputMuted: false,
mediaAutoplayBlockedPosted: false,
playbackRate: 1,
Expand Down
2 changes: 2 additions & 0 deletions packages/core/src/runtime/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export type RuntimeBridgeControlAction =
| "pause"
| "seek"
| "set-muted"
| "set-volume"
| "set-media-output-muted"
| "set-playback-rate"
| "enable-pick-mode"
Expand All @@ -23,6 +24,7 @@ export type RuntimeBridgeControlMessage = {
action: RuntimeBridgeControlAction;
frame?: number;
muted?: boolean;
volume?: number;
playbackRate?: number;
seekMode?: "drag" | "commit";
};
Expand Down
139 changes: 138 additions & 1 deletion packages/player/src/controls.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
import { PLAY_ICON, PAUSE_ICON } from "./styles.js";
import {
PLAY_ICON,
PAUSE_ICON,
VOLUME_HIGH_ICON,
VOLUME_LOW_ICON,
VOLUME_MUTED_ICON,
} from "./styles.js";

export interface ControlsCallbacks {
onPlay: () => void;
onPause: () => void;
onSeek: (fraction: number) => void;
onSpeedChange: (speed: number) => void;
onMuteToggle: () => void;
onVolumeChange: (volume: number) => void;
}

/** Default logarithmic speed presets — each step roughly doubles/halves. */
Expand Down Expand Up @@ -38,6 +46,8 @@ export function createControls(
updateTime: (current: number, duration: number) => void;
updatePlaying: (playing: boolean) => void;
updateSpeed: (speed: number) => void;
updateMuted: (muted: boolean) => void;
updateVolume: (volume: number) => void;
show: () => void;
hide: () => void;
destroy: () => void;
Expand Down Expand Up @@ -94,23 +104,135 @@ export function createControls(
speedWrap.appendChild(speedMenu);
speedWrap.appendChild(speedBtn);

const volumeWrap = document.createElement("div");
volumeWrap.className = "hfp-volume-wrap";

const muteBtn = document.createElement("button");
muteBtn.className = "hfp-mute-btn";
muteBtn.type = "button";
muteBtn.innerHTML = VOLUME_HIGH_ICON;
muteBtn.setAttribute("aria-label", "Mute");

const volumeSliderWrap = document.createElement("div");
volumeSliderWrap.className = "hfp-volume-slider-wrap";

const volumeSlider = document.createElement("div");
volumeSlider.className = "hfp-volume-slider";
volumeSlider.setAttribute("role", "slider");
volumeSlider.setAttribute("aria-label", "Volume");
volumeSlider.setAttribute("aria-valuemin", "0");
volumeSlider.setAttribute("aria-valuemax", "100");
volumeSlider.setAttribute("aria-valuenow", "100");
volumeSlider.tabIndex = 0;
const volumeFill = document.createElement("div");
volumeFill.className = "hfp-volume-fill";
volumeFill.style.width = "100%";
volumeSlider.appendChild(volumeFill);
volumeSliderWrap.appendChild(volumeSlider);

volumeWrap.appendChild(volumeSliderWrap);
volumeWrap.appendChild(muteBtn);

controls.appendChild(playBtn);
controls.appendChild(scrubber);
controls.appendChild(time);
controls.appendChild(volumeWrap);
controls.appendChild(speedWrap);
parent.appendChild(controls);

let isPlaying = false;
let isMuted = false;
let currentVolume = 1;
let hideTimeout: ReturnType<typeof setTimeout> | null = null;
let speedIndex = presets.indexOf(1); // start at 1x
if (speedIndex === -1) speedIndex = 0;

const getVolumeIcon = (muted: boolean, volume: number): string => {
if (muted) return VOLUME_MUTED_ICON;
if (volume === 0) return VOLUME_LOW_ICON;
if (volume < 0.5) return VOLUME_LOW_ICON;
return VOLUME_HIGH_ICON;
};

playBtn.addEventListener("click", (e) => {
e.stopPropagation();
if (isPlaying) callbacks.onPause();
else callbacks.onPlay();
});

muteBtn.addEventListener("click", (e) => {
e.stopPropagation();
callbacks.onMuteToggle();
});

let volumeScrubbing = false;

const handleVolumeAt = (clientX: number) => {
const rect = volumeSlider.getBoundingClientRect();
const fraction = Math.max(0, Math.min(1, (clientX - rect.left) / rect.width));
currentVolume = fraction;
volumeFill.style.width = `${fraction * 100}%`;
volumeSlider.setAttribute("aria-valuenow", String(Math.round(fraction * 100)));
if (isMuted && fraction > 0) callbacks.onMuteToggle();
muteBtn.innerHTML = getVolumeIcon(isMuted, fraction);
callbacks.onVolumeChange(fraction);
};

volumeSlider.addEventListener("mousedown", (e) => {
e.stopPropagation();
volumeScrubbing = true;
handleVolumeAt(e.clientX);
});
const onVolumeMouseMove = (e: MouseEvent) => {
if (volumeScrubbing) handleVolumeAt(e.clientX);
};
const onVolumeMouseUp = () => {
volumeScrubbing = false;
};
document.addEventListener("mousemove", onVolumeMouseMove);
document.addEventListener("mouseup", onVolumeMouseUp);

volumeSlider.addEventListener(
"touchstart",
(e) => {
volumeScrubbing = true;
const touch = e.touches[0];
if (touch) handleVolumeAt(touch.clientX);
},
{ passive: true },
);
const onVolumeTouchMove = (e: TouchEvent) => {
if (volumeScrubbing) {
const touch = e.touches[0];
if (touch) handleVolumeAt(touch.clientX);
}
};
const onVolumeTouchEnd = () => {
volumeScrubbing = false;
};
document.addEventListener("touchmove", onVolumeTouchMove, { passive: true });
document.addEventListener("touchend", onVolumeTouchEnd);

const VOLUME_STEP = 0.05;
volumeSlider.addEventListener("keydown", (e) => {
let newVol = currentVolume;
if (e.key === "ArrowRight" || e.key === "ArrowUp") {
newVol = Math.min(1, currentVolume + VOLUME_STEP);
} else if (e.key === "ArrowLeft" || e.key === "ArrowDown") {
newVol = Math.max(0, currentVolume - VOLUME_STEP);
} else {
return;
}
e.preventDefault();
e.stopPropagation();
currentVolume = newVol;
volumeFill.style.width = `${newVol * 100}%`;
volumeSlider.setAttribute("aria-valuenow", String(Math.round(newVol * 100)));
if (isMuted && newVol > 0) callbacks.onMuteToggle();
muteBtn.innerHTML = getVolumeIcon(isMuted, newVol);
callbacks.onVolumeChange(newVol);
});

const setActiveOption = (speed: number) => {
for (const opt of speedMenu.querySelectorAll(".hfp-speed-option")) {
opt.classList.toggle("hfp-active", (opt as HTMLElement).dataset.speed === String(speed));
Expand Down Expand Up @@ -221,6 +343,17 @@ export function createControls(
speedBtn.textContent = formatSpeed(speed);
setActiveOption(speed);
},
updateMuted(muted: boolean) {
isMuted = muted;
muteBtn.innerHTML = getVolumeIcon(muted, currentVolume);
muteBtn.setAttribute("aria-label", muted ? "Unmute" : "Mute");
},
updateVolume(volume: number) {
currentVolume = volume;
volumeFill.style.width = `${volume * 100}%`;
volumeSlider.setAttribute("aria-valuenow", String(Math.round(volume * 100)));
muteBtn.innerHTML = getVolumeIcon(isMuted, volume);
},
show() {
controls.style.display = "";
},
Expand All @@ -232,6 +365,10 @@ export function createControls(
document.removeEventListener("mouseup", onMouseUp);
document.removeEventListener("touchmove", onTouchMove);
document.removeEventListener("touchend", onTouchEnd);
document.removeEventListener("mousemove", onVolumeMouseMove);
document.removeEventListener("mouseup", onVolumeMouseUp);
document.removeEventListener("touchmove", onVolumeTouchMove);
document.removeEventListener("touchend", onVolumeTouchEnd);
document.removeEventListener("click", onDocClick);
if (hideTimeout) clearTimeout(hideTimeout);
},
Expand Down
Loading
Loading