Skip to content

Commit 7755948

Browse files
committed
Fix resolution calc on macos. issue: #17
1 parent 62fcea4 commit 7755948

1 file changed

Lines changed: 50 additions & 0 deletions

File tree

src/ccap_imp_apple.mm

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -739,12 +739,62 @@ - (void)flushResolution {
739739

740740
- (BOOL)start {
741741
if (_session && _opened && ![_session isRunning]) {
742+
CGSize targetResolution = _resolution;
742743
CCAP_NSLOG_V(@"ccap: CameraCaptureObjc start");
743744
[_session startRunning];
745+
746+
// If the format was changed by session start, restore it
747+
if (_device && _device.activeFormat && targetResolution.width > 0 && targetResolution.height > 0) {
748+
CMVideoDimensions afterStart = CMVideoFormatDescriptionGetDimensions(_device.activeFormat.formatDescription);
749+
if (afterStart.width != targetResolution.width || afterStart.height != targetResolution.height) {
750+
CCAP_NSLOG_V(@"ccap: Session start changed format from %gx%g, restoring", targetResolution.width, targetResolution.height);
751+
[self setCameraResolution:targetResolution];
752+
}
753+
}
744754
}
745755
return [_session isRunning];
746756
}
747757

758+
- (void)setCameraResolution:(CGSize)targetResolution {
759+
if (!_device) return;
760+
761+
NSError* error = nil;
762+
if ([_device lockForConfiguration:&error]) {
763+
AVCaptureDeviceFormat* bestFormat = nil;
764+
double closestDistance = 1e9;
765+
766+
for (AVCaptureDeviceFormat* format in _device.formats) {
767+
CMVideoDimensions dimensions = CMVideoFormatDescriptionGetDimensions(format.formatDescription);
768+
769+
/// If we find an exact match, use it immediately
770+
if (dimensions.width == targetResolution.width && dimensions.height == targetResolution.height) {
771+
bestFormat = format;
772+
break;
773+
}
774+
775+
/// Otherwise, calculate distance for closest match
776+
double distance = std::abs(dimensions.width - targetResolution.width) + std::abs(dimensions.height - targetResolution.height);
777+
if (distance < closestDistance) {
778+
closestDistance = distance;
779+
bestFormat = format;
780+
}
781+
}
782+
783+
if (bestFormat) {
784+
[_device setActiveFormat:bestFormat];
785+
CMVideoDimensions actualDimensions = CMVideoFormatDescriptionGetDimensions(bestFormat.formatDescription);
786+
CCAP_NSLOG_V(@"ccap: Restored device format to: %dx%d", actualDimensions.width, actualDimensions.height);
787+
788+
// Update internal resolution tracking
789+
_resolution = CGSizeMake(actualDimensions.width, actualDimensions.height);
790+
}
791+
792+
[_device unlockForConfiguration];
793+
} else {
794+
CCAP_NSLOG_W(@"ccap: Failed to lock device for format restoration: %@", error.localizedDescription);
795+
}
796+
}
797+
748798
- (void)stop {
749799
if (_session && [_session isRunning]) {
750800
CCAP_NSLOG_V(@"ccap: CameraCaptureObjc stop");

0 commit comments

Comments
 (0)