Add object detection, tracking, mobile notifications, and search to any security camera.
dont send all the segments every time
roryclear4bd91c8d4ba9
diff --git a/clearcam/FileServer.m b/clearcam/FileServer.mindex 9209a5b..aebba34 100644--- a/clearcam/FileServer.m+++ b/clearcam/FileServer.m@@ -96,16 +96,60 @@if ([filePath isEqualToString:@"/"]) filePath = @"";// Handle /get-segments API endpoint- if ([filePath isEqualToString:@"get-segments"]) {+ if ([filePath hasPrefix:@"get-segments"]) {+ // Extract the query string if present+ NSString *startParam = nil;+ NSRange queryRange = [filePath rangeOfString:@"?"];+ if (queryRange.location != NSNotFound) {+ NSString *queryString = [filePath substringFromIndex:queryRange.location + 1];+ NSArray *queryItems = [queryString componentsSeparatedByString:@"&"];+ for (NSString *item in queryItems) {+ NSArray *keyValue = [item componentsSeparatedByString:@"="];+ if (keyValue.count == 2 && [keyValue[0] isEqualToString:@"start"]) {+ startParam = keyValue[1];+ break;+ }+ }+ }++ // Default to 0 if "start" is not provided+ NSInteger start = startParam ? [startParam integerValue] : 0;++ NSLog(@"START PARAM = %ld", (long)start);+NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];NSString *segmentsFilePath = [documentsPath stringByAppendingPathComponent:@"segments.txt"];if ([[NSFileManager defaultManager] fileExistsAtPath:segmentsFilePath]) {// Read contents of segments.txtNSData *jsonData = [NSData dataWithContentsOfFile:segmentsFilePath];+ NSError *jsonError = nil;+ NSArray *segmentsArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&jsonError];+ if (jsonError) {+ NSString *httpHeader = @"HTTP/1.1 500 Internal Server Error\r\nContent-Type: application/json\r\n\r\n";+ NSString *errorMessage = [NSString stringWithFormat:@"{\"error\": \"Failed to parse segments.txt: %@\"}", jsonError.localizedDescription];+ send(clientSocket, [httpHeader UTF8String], httpHeader.length, 0);+ send(clientSocket, [errorMessage UTF8String], errorMessage.length, 0);+ return;+ }++ // Slice the array starting from the 'start' index+ if (start >= segmentsArray.count) {+ NSString *httpHeader = @"HTTP/1.1 404 Not Found\r\nContent-Type: application/json\r\n\r\n";+ NSString *errorMessage = @"{\"error\": \"Start index is out of range\"}";+ send(clientSocket, [httpHeader UTF8String], httpHeader.length, 0);+ send(clientSocket, [errorMessage UTF8String], errorMessage.length, 0);+ return;+ }++ NSArray *slicedSegments = [segmentsArray subarrayWithRange:NSMakeRange(start, segmentsArray.count - start)];++ // Convert the sliced array back to JSON+ NSData *slicedJsonData = [NSJSONSerialization dataWithJSONObject:slicedSegments options:0 error:nil];+NSString *httpHeader = @"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n";send(clientSocket, [httpHeader UTF8String], httpHeader.length, 0);- send(clientSocket, jsonData.bytes, jsonData.length, 0);+ send(clientSocket, slicedJsonData.bytes, slicedJsonData.length, 0);return;} else {// If file does not exist, send an empty responsediff --git a/player.html b/player.htmlindex 74c8638..0fa0df6 100644--- a/player.html+++ b/player.html@@ -76,47 +76,50 @@let segments = [];let totalDuration = 0;let retryTimeout = 2000;-+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');+ // Dynamically append the ?start={segments.length} parameter+ const startParam = segments.length; // Start from the current number of segments+ const response = await fetch(`/get-segments?start=${startParam}`);if (response.ok) {const newSegments = await response.json();if (Array.isArray(newSegments)) {const oldTotalDuration = totalDuration;-+// Calculate cumulativeStart with lost frames adjustment- let cumulativeStart = 0;- segments = newSegments.map((segment, index) => {+ let cumulativeStart = totalDuration;+ newSegments.forEach((segment, index) => {const timeDifference = segment.timeDifference || segment.duration;const lostFrames = timeDifference - segment.duration;-+// Store cumulativeStart including lost framesconst currentCumulativeStart = cumulativeStart;cumulativeStart += timeDifference; // Add full time difference to cumulative start-- return {++ segments.push({...segment,cumulativeStart: currentCumulativeStart,lostFrames: lostFrames > 0 ? lostFrames : 0,- };+ });});-+// Calculate total duration including lost framestotalDuration = segments.reduce((sum, seg) => sum + (seg.timeDifference || seg.duration), 0);-+// If total duration changed, update the timeline and preload next segmentif (totalDuration !== oldTotalDuration) {updateTimeline();@@ -131,29 +134,28 @@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() {// Calculate the current time including lost framesconst currentTime = currentVideo.currentTime + segments[currentSegment].cumulativeStart;progressBar.style.width = `${(currentTime / totalDuration) * 100}%`;timeDisplay.innerText = `${formatTime(currentTime)} / ${formatTime(totalDuration)}`;}-+function scrub(e) {const scrubTime = ((e.offsetX || e.touches[0].clientX - progress.getBoundingClientRect().left) / progress.offsetWidth) * totalDuration;-+let targetSegment = segments.findIndex(segment => scrubTime < segment.cumulativeStart + segment.duration);targetSegment = targetSegment === -1 ? segments.length - 1 : targetSegment;-+const targetTime = scrubTime - segments[targetSegment].cumulativeStart;-+if (targetSegment >= 0 && targetSegment < segments.length) {currentSegment = targetSegment;currentVideo.src = segments[currentSegment].url;@@ -161,11 +163,10 @@currentVideo.play();preloadNextSegment();}-+updateTimeline();}--+function startScrubbing(e) {isScrubbing = true;scrub(e);@@ -174,13 +175,13 @@document.addEventListener("touchmove", scrubWhileDragging);document.addEventListener("touchend", stopScrubbing);}-+function scrubWhileDragging(e) {if (isScrubbing) {scrub(e);}}-+function stopScrubbing() {isScrubbing = false;document.removeEventListener("mousemove", scrubWhileDragging);@@ -188,29 +189,29 @@document.removeEventListener("touchmove", scrubWhileDragging);document.removeEventListener("touchend", stopScrubbing);}-+function preloadNextSegment() {if (currentSegment + 1 < segments.length) {nextVideo.src = segments[currentSegment + 1].url;nextVideo.load();}}-+function playSegment() {if (segments.length > 0) {currentVideo.src = segments[currentSegment].url;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].url}`);setTimeout(() => {@@ -219,17 +220,17 @@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 {@@ -237,21 +238,21 @@playPauseBtn.innerText = "Play";}}-+progress.addEventListener("mousedown", startScrubbing);progress.addEventListener("touchstart", startScrubbing);-+setInterval(fetchSegments, 1000);-+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();@@ -262,8 +263,9 @@}isPlaying = !isPlaying;});-+fetchSegments();</script>+</body></html>