Add object detection, tracking, mobile notifications, and search to any security camera.
more accurate timeline
roryclear8184e3d095db
diff --git a/clearcam/FileServer.m b/clearcam/FileServer.mindex ae59df6..79f6478 100644--- a/clearcam/FileServer.m+++ b/clearcam/FileServer.m@@ -11,6 +11,7 @@@interface FileServer ()@property (nonatomic, strong) NSString *basePath;@property (nonatomic, strong) NSMutableDictionary *durationCache;+@property (nonatomic, strong) NSMutableDictionary *timeDifferenceCache;@end@implementation FileServer@@ -96,7 +97,7 @@if ([filePath isEqualToString:@"/"]) filePath = @"";// Handle /get-segments API endpoint- if ([filePath isEqualToString:@"get-segments"]) {+ if ([filePath isEqualToString:@"get-segments"]) { //TODO, this gets very slow I think, just use a txt fileNSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsPath error:nil];NSPredicate *mp4Filter = [NSPredicate predicateWithFormat:@"SELF ENDSWITH '.mp4'"];@@ -116,16 +117,17 @@return [@(num1) compare:@(num2)];}];- // Exclude the last segment from the list- if (sortedFiles.count > 0) {- sortedFiles = [sortedFiles subarrayWithRange:NSMakeRange(0, sortedFiles.count - 1)];+ if (sortedFiles.count > 1) { // Exclude last 2 files+ sortedFiles = [sortedFiles subarrayWithRange:NSMakeRange(0, sortedFiles.count - 2)];}// Prepare JSON responseNSMutableArray *responseArray = [NSMutableArray array];+ NSString *lastFile = nil;for (NSString *file in sortedFiles) {NSString *filePath = [documentsPath stringByAppendingPathComponent:file];+ // Retrieve cached duration or calculate itNSNumber *cachedDuration = self.durationCache[file];Float64 duration;if (cachedDuration) {@@ -142,12 +144,48 @@}}- if (isfinite(duration)) {- [responseArray addObject:@{- @"url": file,- @"duration": @(duration)- }];+ // Retrieve cached timeDifference or calculate it+ Float64 timeDifference = 0;+ if (lastFile) {+ NSNumber *cachedTimeDifference = self.timeDifferenceCache[lastFile];+ if (cachedTimeDifference) {+ timeDifference = [cachedTimeDifference doubleValue];+ } else {+ // Extract timestamps+ NSRegularExpression *timestampRegex = [NSRegularExpression regularExpressionWithPattern:@"_(\\d{2}:\\d{2}:\\d{2}:\\d{3})\\.mp4$"+ options:0+ error:nil];+ NSTextCheckingResult *lastMatch = [timestampRegex firstMatchInString:lastFile options:0 range:NSMakeRange(0, lastFile.length)];+ NSTextCheckingResult *currentMatch = [timestampRegex firstMatchInString:file options:0 range:NSMakeRange(0, file.length)];++ NSString *lastTimestamp = lastMatch ? [lastFile substringWithRange:[lastMatch rangeAtIndex:1]] : nil;+ NSString *currentTimestamp = currentMatch ? [file substringWithRange:[currentMatch rangeAtIndex:1]] : nil;++ if (lastTimestamp && currentTimestamp) {+ NSDateFormatter *formatter = [[NSDateFormatter alloc] init];+ [formatter setDateFormat:@"HH:mm:ss:SSS"];+ NSDate *lastDate = [formatter dateFromString:lastTimestamp];+ NSDate *currentDate = [formatter dateFromString:currentTimestamp];++ if (lastDate && currentDate) {+ timeDifference = [currentDate timeIntervalSinceDate:lastDate];+ self.timeDifferenceCache[lastFile] = @(timeDifference);+ }+ }+ }+ }++ // Prepare segment data+ NSMutableDictionary *segmentData = [@{+ @"url": file,+ @"duration": @(duration)+ } mutableCopy];+ if (timeDifference > 0) {+ segmentData[@"timeDifference"] = @(timeDifference);}++ [responseArray addObject:segmentData];+ lastFile = file; // Update last file}// Send JSON response@@ -159,6 +197,7 @@}+NSString *fullPath = [basePath stringByAppendingPathComponent:filePath];BOOL isDirectory = NO;if (![[NSFileManager defaultManager] fileExistsAtPath:fullPath isDirectory:&isDirectory]) {diff --git a/clearcam/ViewController.m b/clearcam/ViewController.mindex b749c0c..425b39e 100644--- a/clearcam/ViewController.m+++ b/clearcam/ViewController.m@@ -106,7 +106,7 @@ NSMutableDictionary *classColorMap;- (void)startNewRecording {NSDateFormatter *formatter = [[NSDateFormatter alloc] init];- [formatter setDateFormat:@"yyyy-MM-dd_HH:mm:ss"];+ [formatter setDateFormat:@"yyyy-MM-dd_HH:mm:ss:SSS"];NSString *timestamp = [formatter stringFromDate:[NSDate date]];NSString *segNumberString = [NSString stringWithFormat:@"_%05ld_", (long)self.seg_number];self.seg_number += 1;diff --git a/player.html b/player.htmlindex c214db3..74c8638 100644--- a/player.html+++ b/player.html@@ -89,7 +89,6 @@let currentSegment = 0;let isPlaying = false;let isScrubbing = false;-async function fetchSegments() {try {const response = await fetch('/get-segments');@@ -98,27 +97,25 @@if (Array.isArray(newSegments)) {const oldTotalDuration = totalDuration;- // Calculate cumulativeStart correctly by summing durations of previous segments+ // Calculate cumulativeStart with lost frames adjustmentlet cumulativeStart = 0;segments = newSegments.map((segment, index) => {- // Store the cumulative start for the current segment- const currentCumulativeStart = cumulativeStart;-- // Update cumulativeStart for the next segment by adding the current segment's duration- cumulativeStart += segment.duration;+ const timeDifference = segment.timeDifference || segment.duration;+ const lostFrames = timeDifference - segment.duration;- // Log for debugging- //console.log(`Segment ${index}: cumulativeStart = ${currentCumulativeStart}`);+ // Store cumulativeStart including lost frames+ const currentCumulativeStart = cumulativeStart;+ cumulativeStart += timeDifference; // Add full time difference to cumulative start- // Return the segment with the updated cumulativeStartreturn {...segment,- cumulativeStart: currentCumulativeStart+ cumulativeStart: currentCumulativeStart,+ lostFrames: lostFrames > 0 ? lostFrames : 0,};});- // Calculate total duration- totalDuration = segments.reduce((sum, seg) => sum + seg.duration, 0);+ // Calculate total duration including lost frames+ totalDuration = segments.reduce((sum, seg) => sum + (seg.timeDifference || seg.duration), 0);// If total duration changed, update the timeline and preload next segmentif (totalDuration !== oldTotalDuration) {@@ -135,7 +132,7 @@}}-+function formatTime(seconds) {const minutes = Math.floor(seconds / 60);const secs = Math.floor(seconds % 60).toString().padStart(2, '0');@@ -143,6 +140,7 @@}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)}`;@@ -167,6 +165,7 @@updateTimeline();}+function startScrubbing(e) {isScrubbing = true;scrub(e);@@ -242,7 +241,7 @@progress.addEventListener("mousedown", startScrubbing);progress.addEventListener("touchstart", startScrubbing);- setInterval(fetchSegments, 3000);+ setInterval(fetchSegments, 1000);videoPlayer1.addEventListener("timeupdate", updateTimeline);videoPlayer2.addEventListener("timeupdate", updateTimeline);