Add object detection, tracking, mobile notifications, and search to any security camera.
almost streaming
roryclear4eb0e735b053
diff --git a/clearcam/DeviceStreamViewController.h b/clearcam/DeviceStreamViewController.hnew file mode 100644index 0000000..41d5b2a--- /dev/null+++ b/clearcam/DeviceStreamViewController.h@@ -0,0 +1,5 @@+#import <UIKit/UIKit.h>++@interface DeviceStreamViewController : UIViewController+@property (nonatomic, strong) NSString *deviceName; // Property to hold the device name+@enddiff --git a/clearcam/DeviceStreamViewController.m b/clearcam/DeviceStreamViewController.mnew file mode 100644index 0000000..fb2e16d--- /dev/null+++ b/clearcam/DeviceStreamViewController.m@@ -0,0 +1,145 @@+#import "DeviceStreamViewController.h"+#import "StoreManager.h" // For session token+#import <AVFoundation/AVFoundation.h>+#import <Security/Security.h>+#import <CommonCrypto/CommonCryptor.h>++@interface DeviceStreamViewController ()+@property (nonatomic, strong) AVQueuePlayer *player;+@property (nonatomic, strong) AVPlayerLayer *playerLayer;+@property (nonatomic, strong) NSTimer *downloadTimer;+@property (nonatomic, strong) NSData *lastSegmentData;+@property (nonatomic, assign) NSUInteger segmentIndex;+@end++@implementation DeviceStreamViewController++- (void)viewDidLoad {+ [super viewDidLoad];+ self.view.backgroundColor = [UIColor blackColor];++ self.player = [AVQueuePlayer queuePlayerWithItems:@[]];+ self.player.volume = 1.0;++ self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];+ self.playerLayer.frame = self.view.bounds;+ self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;+ [self.view.layer addSublayer:self.playerLayer];++ [self.player play];+ [self downloadAndQueueSegment];+ [self startDownloadTimer];+ NSLog(@"device streaming from = %@",self.deviceName);+}++- (void)startDownloadTimer {+ self.downloadTimer = [NSTimer scheduledTimerWithTimeInterval:1.0+ target:self+ selector:@selector(downloadAndQueueSegment)+ userInfo:nil+ repeats:YES];+}++- (void)downloadAndQueueSegment {+ NSString *urlString = @"";+ NSURL *remoteURL = [NSURL URLWithString:urlString];++ NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithURL:remoteURL+ completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {+ if (error || !data) {+ NSLog(@"β Download error: %@", error.localizedDescription);+ return;+ }++ if ([self.lastSegmentData isEqualToData:data]) {+ NSLog(@"π Same segment, skipping");+ return;+ }++ self.lastSegmentData = data;+ data = [self decryptData:data withKey:@"open_please"];+ NSString *fileName = [NSString stringWithFormat:@"segment_%lu.mp4", (unsigned long)(self.segmentIndex++ % 2)];+ NSString *tempPath = [NSTemporaryDirectory() stringByAppendingPathComponent:fileName];+ NSURL *localURL = [NSURL fileURLWithPath:tempPath];++ if ([data writeToURL:localURL atomically:YES]) {+ NSLog(@"β New segment saved: %@", fileName);+ dispatch_async(dispatch_get_main_queue(), ^{+ AVURLAsset *asset = [AVURLAsset assetWithURL:localURL];+ AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:asset];+ [self.player insertItem:item afterItem:nil];+ });+ } else {+ NSLog(@"β Write failed");+ }+ }];+ [task resume];+}++#define MAGIC_NUMBER 0x4D41474943ULL // "MAGIC" in ASCII as a 64-bit value+#define HEADER_SIZE (sizeof(uint64_t)) // Size of the magic number (8 bytes)+#define AES_BLOCK_SIZE kCCBlockSizeAES128+#define AES_KEY_SIZE kCCKeySizeAES256+- (NSData *)decryptData:(NSData *)encryptedDataWithIv withKey:(NSString *)key {+ if (!encryptedDataWithIv || !key) return nil;+ if (encryptedDataWithIv.length <= AES_BLOCK_SIZE) return nil;++ NSData *ivData = [encryptedDataWithIv subdataWithRange:NSMakeRange(0, AES_BLOCK_SIZE)];+ NSData *cipherData = [encryptedDataWithIv subdataWithRange:NSMakeRange(AES_BLOCK_SIZE, encryptedDataWithIv.length - AES_BLOCK_SIZE)];++ char keyPtr[AES_KEY_SIZE + 1];+ bzero(keyPtr, sizeof(keyPtr));+ if (![key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding]) return nil;++ size_t bufferSize = cipherData.length + AES_BLOCK_SIZE;+ void *buffer = malloc(bufferSize);+ if (!buffer) return nil;++ size_t numBytesDecrypted = 0;+ CCCryptorStatus status = CCCrypt(kCCDecrypt,+ kCCAlgorithmAES,+ kCCOptionPKCS7Padding,+ keyPtr,+ AES_KEY_SIZE,+ ivData.bytes,+ cipherData.bytes,+ cipherData.length,+ buffer,+ bufferSize,+ &numBytesDecrypted);++ if (status != kCCSuccess) {+ free(buffer);+ return nil;+ }++ if (numBytesDecrypted < sizeof(uint64_t) * 2) {+ free(buffer);+ return nil;+ }++ uint64_t magic;+ uint64_t originalLength;+ memcpy(&magic, buffer, sizeof(uint64_t));+ memcpy(&originalLength, buffer + sizeof(uint64_t), sizeof(uint64_t));++ if (magic != MAGIC_NUMBER || originalLength > (numBytesDecrypted - sizeof(uint64_t) * 2)) {+ free(buffer);+ return nil;+ }++ NSData *result = [NSData dataWithBytes:(buffer + sizeof(uint64_t) * 2) length:originalLength];+ free(buffer);+ return result;+}++- (void)viewDidLayoutSubviews {+ [super viewDidLayoutSubviews];+ self.playerLayer.frame = self.view.bounds;+}++- (void)dealloc {+ [self.downloadTimer invalidate];+}++@enddiff --git a/clearcam/LiveViewController.m b/clearcam/LiveViewController.mindex 4df8a75..34eeb1a 100644--- a/clearcam/LiveViewController.m+++ b/clearcam/LiveViewController.m@@ -1,6 +1,6 @@-// LiveViewController.m#import "LiveViewController.h"#import "StoreManager.h"+#import "DeviceStreamViewController.h" // Import DeviceStreamViewController@interface LiveViewController () <UITableViewDelegate, UITableViewDataSource>@property (nonatomic, strong) NSMutableArray<NSString *> *deviceNames;@@ -13,6 +13,8 @@[super viewDidLoad];self.title = @"Live";self.deviceNames = [NSMutableArray array];++self.session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];[self setupTableView];[self fetchLiveDevices];@@ -101,6 +103,11 @@- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {NSString *selectedDevice = self.deviceNames[indexPath.row];NSLog(@"Selected device: %@", selectedDevice);++ DeviceStreamViewController *streamVC = [[DeviceStreamViewController alloc] init];+ streamVC.deviceName = selectedDevice; // Pass the device name+ [self.navigationController pushViewController:streamVC animated:YES];+[tableView deselectRowAtIndexPath:indexPath animated:YES];}diff --git a/clearcam/ViewController.m b/clearcam/ViewController.mindex 037048a..d5830e4 100644--- a/clearcam/ViewController.m+++ b/clearcam/ViewController.m@@ -466,24 +466,24 @@ NSMutableDictionary *classColorMap;AVVideoHeightKey: @(videoHeight),AVVideoScalingModeKey: AVVideoScalingModeResizeAspectFill};-- NSArray<NSString *> *exportPresets = [AVAssetExportSession allExportPresets];- if ([exportPresets containsObject:AVAssetExportPresetHEVCHighestQuality]) {- // HEVC is supported- videoSettings = @{- AVVideoCodecKey: AVVideoCodecTypeHEVC, // Use HEVC (H.265)- AVVideoWidthKey: @(videoWidth),- AVVideoHeightKey: @(videoHeight),- AVVideoScalingModeKey: AVVideoScalingModeResizeAspectFill- };- }-+if (self.isStreaming) {NSMutableDictionary *mutableSettings = [videoSettings mutableCopy];mutableSettings[AVVideoCompressionPropertiesKey] = @{AVVideoAverageBitRateKey: @(500000)};videoSettings = [mutableSettings copy];+ } else {+ NSArray<NSString *> *exportPresets = [AVAssetExportSession allExportPresets];+ if ([exportPresets containsObject:AVAssetExportPresetHEVCHighestQuality]) {+ // HEVC is supported+ videoSettings = @{+ AVVideoCodecKey: AVVideoCodecTypeHEVC, // Use HEVC (H.265)+ AVVideoWidthKey: @(videoWidth),+ AVVideoHeightKey: @(videoHeight),+ AVVideoScalingModeKey: AVVideoScalingModeResizeAspectFill+ };+ }}self.videoWriterInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:videoSettings];@@ -867,18 +867,19 @@ NSMutableDictionary *classColorMap;}}- // Copy or move the video file to the temp path- if ([fileManager copyItemAtURL:self.assetWriter.outputURL toURL:[NSURL fileURLWithPath:tempFilePath] error:&fileError]) {- NSLog(@"β Copied video to temp path for upload: %@", tempFilePath);- } else {- NSLog(@"β Failed to copy video to temp path: %@", fileError);- }-- // Trigger upload if file was successfully copied- if ([fileManager fileExistsAtPath:tempFilePath]) {- [self uploadSegment];- } else {- NSLog(@"β Temp file not found, skipping upload");+ if (self.assetWriter.outputURL) {+ if ([fileManager copyItemAtURL:self.assetWriter.outputURL toURL:[NSURL fileURLWithPath:tempFilePath] error:&fileError]) {+ NSLog(@"β Copied video to temp path for upload: %@", tempFilePath);+ } else {+ NSLog(@"β Failed to copy video to temp path: %@", fileError);+ }++ // Trigger upload if file was successfully copied+ if ([fileManager fileExistsAtPath:tempFilePath]) {+ [self uploadSegment];+ } else {+ NSLog(@"β Temp file not found, skipping upload");+ }}}@@ -1289,7 +1290,7 @@ NSMutableDictionary *classColorMap;if ((uploadLink && ![uploadLink isKindOfClass:[NSNull class]])) {if(self.isStreaming == NO){NSLog(@"π€ Upload link received: %@", uploadLink);- //self.streamLink = uploadLink;+ self.streamLink = uploadLink;self.isStreaming = YES;dispatch_async(dispatch_get_main_queue(), ^{[self refreshView];