Add object detection, tracking, mobile notifications, and search to any security camera.
works with _ format
roryclearb9154a6ac60b
diff --git a/player.html b/player.htmlindex 36281ad..ac7cbaf 100644--- a/player.html+++ b/player.html@@ -62,40 +62,46 @@</div><script>- let segments = ["0.mp4"]; // Initial segment+ let segments = []; // Initially empty, will be populated from the serverconst segmentDuration = 60; // Duration of each segment in seconds- let totalDuration = segments.length * segmentDuration;-+ let totalDuration = 0;+ let retryTimeout = 2000; // Retry interval in milliseconds+const videoPlayer1 = document.getElementById('videoPlayer1');const videoPlayer2 = document.getElementById('videoPlayer2');const playPauseBtn = document.getElementById('playPauseBtn');const progressBar = document.getElementById('progress-bar');const progress = document.getElementById('progress');const timeDisplay = document.getElementById('timeDisplay');-+let currentVideo = videoPlayer1;let nextVideo = videoPlayer2;let currentSegment = 0;let isPlaying = false;let isScrubbing = false;-+async function fetchSegments() {try {const response = await fetch('/get-segments');if (response.ok) {const newSegments = await response.json();-+if (Array.isArray(newSegments)) {const oldTotalDuration = totalDuration;-+// Update segments list and total durationsegments = newSegments;totalDuration = segments.length * segmentDuration;-+// If the total duration changes, update UIif (totalDuration !== oldTotalDuration) {updateTimeline();preloadNextSegment();++ // Start playing the first segment if the list changes+ if (!isPlaying && segments.length > 0) {+ playSegment();+ }}}}@@ -103,44 +109,44 @@console.error('Failed to fetch segments:', error);}}-+function formatTime(seconds) {const minutes = Math.floor(seconds / 60);const secs = Math.floor(seconds % 60).toString().padStart(2, '0');return `${minutes}:${secs}`;}-+function updateTimeline() {const currentTime = currentSegment * segmentDuration + currentVideo.currentTime;progressBar.style.width = `${(currentTime / totalDuration) * 100}%`;timeDisplay.innerText = `${formatTime(currentTime)} / ${formatTime(totalDuration)}`;}-+function scrub(e) {const scrubTime = (e.offsetX / progress.offsetWidth) * totalDuration;const targetSegment = Math.floor(scrubTime / segmentDuration);const targetTime = scrubTime % segmentDuration;-+if (targetSegment >= 0 && targetSegment < segments.length) {currentSegment = targetSegment;currentVideo.src = segments[currentSegment];currentVideo.currentTime = targetTime;currentVideo.play();-+// Preload the next segment after scrubbingpreloadNextSegment();}-+updateTimeline();}-+function startScrubbing(e) {isScrubbing = true;scrub(e);document.addEventListener("mousemove", scrubWhileDragging);document.addEventListener("mouseup", stopScrubbing);}-+function scrubWhileDragging(e) {if (isScrubbing) {const progressRect = progress.getBoundingClientRect();@@ -148,43 +154,54 @@scrub({ offsetX });}}-+function stopScrubbing() {isScrubbing = false;document.removeEventListener("mousemove", scrubWhileDragging);document.removeEventListener("mouseup", stopScrubbing);}-+function preloadNextSegment() {if (currentSegment + 1 < segments.length) {nextVideo.src = segments[currentSegment + 1];nextVideo.load();}}-+function playSegment() {- currentVideo.src = segments[currentSegment];- currentVideo.currentTime = 0;- currentVideo.style.display = "block";- nextVideo.style.display = "none";-- currentVideo.play();- isPlaying = true;- playPauseBtn.innerText = "Pause";-- preloadNextSegment();+ if (segments.length > 0) {+ currentVideo.src = segments[currentSegment];+ currentVideo.currentTime = 0;+ currentVideo.style.display = "block";+ nextVideo.style.display = "none";++ currentVideo.play();+ isPlaying = true;+ playPauseBtn.innerText = "Pause";++ preloadNextSegment();+ }}-++ function retrySegment(videoElement) {+ console.warn(`Retrying segment: ${segments[currentSegment]}`);+ setTimeout(() => {+ videoElement.src = segments[currentSegment];+ videoElement.load();+ videoElement.play();+ }, retryTimeout);+ }+function switchToNextSegment() {if (currentSegment + 1 < segments.length) {currentSegment++;const temp = currentVideo;currentVideo = nextVideo;nextVideo = temp;-+nextVideo.style.display = "none";currentVideo.style.display = "block";-+currentVideo.play();preloadNextSegment();} else {@@ -192,20 +209,23 @@playPauseBtn.innerText = "Play";}}-+progress.addEventListener("mousedown", startScrubbing);document.addEventListener("mouseup", stopScrubbing);-+setInterval(() => {fetchSegments();}, 3000); // Poll every 3 seconds for new segments-+videoPlayer1.addEventListener("timeupdate", updateTimeline);videoPlayer2.addEventListener("timeupdate", updateTimeline);-+videoPlayer1.addEventListener("ended", switchToNextSegment);videoPlayer2.addEventListener("ended", switchToNextSegment);-++ videoPlayer1.addEventListener("error", () => retrySegment(videoPlayer1));+ videoPlayer2.addEventListener("error", () => retrySegment(videoPlayer2));+playPauseBtn.addEventListener("click", () => {if (isPlaying) {currentVideo.pause();@@ -216,8 +236,10 @@}isPlaying = !isPlaying;});-- playSegment();++ // Initially fetch segments and start playing+ fetchSegments();</script>+</body></html>\ No newline at end of filediff --git a/server.py b/server.pyindex 7c84ad2..7da801a 100644--- a/server.py+++ b/server.py@@ -1,4 +1,5 @@import os+import reimport jsonfrom http.server import HTTPServer, SimpleHTTPRequestHandler@@ -13,15 +14,19 @@ class CustomHandler(SimpleHTTPRequestHandler):def handle_get_segments(self):try:- # Find all .mp4 files in the current directory- segments = [f for f in os.listdir('.') if f.endswith('.mp4')]- segments.sort(key=lambda x: int(x.split('.')[0]))+ # Get all .mp4 files in the current directory+ files = [f for f in os.listdir('.') if f.endswith('.mp4')]++ # Sort files:+ # 1. First by numeric value if filename is a simple number like '0.mp4'+ # 2. Then by the number in 'output_YYYY-MM-DD_00000_15/50/18.mp4'+ sorted_files = sorted(files, key=self.sort_key)# Respond with JSONself.send_response(200)self.send_header("Content-Type", "application/json")self.end_headers()- self.wfile.write(json.dumps(segments).encode())+ self.wfile.write(json.dumps(sorted_files).encode())except Exception as e:# Handle errors and send a responseself.send_response(500)@@ -29,8 +34,20 @@ class CustomHandler(SimpleHTTPRequestHandler):self.end_headers()self.wfile.write(f"Error: {str(e)}".encode())+ def sort_key(self, filename):+ # If the filename is in the 'output_YYYY-MM-DD_00000_15/50/18.mp4' format+ match = re.match(r'output_\d{4}-\d{2}-\d{2}_(\d+)', filename)+ if match:+ # Extract the numeric value after 'output_YYYY-MM-DD_'+ return int(match.group(1))+ # If it's a simple '0.mp4' or similar, sort by the numeric part+ try:+ return int(filename.split('.')[0])+ except ValueError:+ return float('inf') # For any other non-numeric names, send to the end+if __name__ == "__main__":# Start the serverserver = HTTPServer(("0.0.0.0", PORT), CustomHandler)print(f"Serving on http://localhost:{PORT}")- server.serve_forever()\ No newline at end of file+ server.serve_forever()