From 71faec97ecf46494652e6c364be3b8e438c42817 Mon Sep 17 00:00:00 2001
From: memdmp <memdmp@estrogen.zone>
Date: Thu, 31 Jul 2025 23:36:42 +0200
Subject: feat: more enhancements

---
 src/lib/Player/Player.svelte | 34 +++++++++++++++++++++++-----------
 1 file changed, 23 insertions(+), 11 deletions(-)

(limited to 'src/lib/Player/Player.svelte')

diff --git a/src/lib/Player/Player.svelte b/src/lib/Player/Player.svelte
index d75ee3c..f3b8fb8 100644
--- a/src/lib/Player/Player.svelte
+++ b/src/lib/Player/Player.svelte
@@ -61,7 +61,7 @@
 		if (canvas && canvas !== lastCanvas) newCanvas(canvas, VideoImplementation);
 	});
 	$effect(() => {
-		if (video) renderPreviewFrame(video, frame);
+		if (video && !playing) renderPreviewFrame(video, frame);
 	});
 	let playbackLoopId = 0;
 	const startPlaybackLoop = (id = ++playbackLoopId) => {
@@ -71,9 +71,18 @@
 
 			if (audio) {
 				const desiredTime = frame / video.fps;
-				// If we get too out of lock-step with audio, we re-sync
-				if (desiredTime < audio.duration && Math.abs(desiredTime - audio.currentTime) > 0.3)
-					audio.currentTime = desiredTime;
+				const timeDelta = Math.abs(desiredTime - audio.currentTime);
+				// If we get too out of lock-step with audio, we re-sync - we assume audio source is accurate*, as to avoid too much jumping
+				// *it may not be
+				if (desiredTime < audio.duration && timeDelta > 0.1) {
+					if (timeDelta > 0.3) {
+						// too out of sync, we trust ourselves more
+						audio.currentTime = desiredTime;
+					} else {
+						// just change the rendered frame and hope its good enough
+						f = audio.currentTime * video.fps;
+					}
+				}
 			}
 
 			if (f > frameCount) {
@@ -87,15 +96,18 @@
 			);
 		}
 	};
-	// State Synchronisation effect & playback starter
+	const startPlaying = () => {
+		if (frame === frameCount && playbackRelativeTo === 0) {
+			frame = 0;
+		}
+		playbackRelativeTo = performance.now();
+		playbackFrameOffset = frame;
+		startPlaybackLoop();
+	};
+	// playback starter
 	$effect(() => {
 		if (playing) {
-			if (frame === frameCount && playbackRelativeTo === 0) {
-				frame = 0;
-			}
-			playbackRelativeTo = performance.now();
-			playbackFrameOffset = frame;
-			startPlaybackLoop();
+			startPlaying();
 		} else playbackRelativeTo = 0;
 	});
 	let loadedFrameTimestamp = false;
-- 
cgit v1.2.3

