Cannot assign to videoZoomFactor of AVCaptureDevice - ios

Hi I'm trying to set the zoomFactor of my camera to 1.0 so it display as much of what a camera could take in as possible as I realized that the iPhone's camera app can "see" more than what my camera can see built using AVFoundation.
However, when trying to set the videoZoomFactor to 1.0 I got this error
"Cannot assign to videoZoomFactor in device"
I'm not sure why it happened and searching through the internet doesn't yield any result therefore I'm asking for help here.
if device.position == .Back{
device.lockForConfiguration(nil)
device.videoZoomFactor = CGFloat(1.0)
device.unlockForConfiguration()
inputCameraBack = AVCaptureDeviceInput(device: device as! AVCaptureDevice, error: nil)
}

You probably have solved your problem by now but the issue appears to be caused bydevice not being cast to an AVCaptureDevice when you set the videoZoomFactor.
First cast it then set the videoZoomFactor then create the AVCaptureDeviceInput with your AVCaptureDevice.

Related

Changing ARSCNView background

iOS 13.1.3 on iPad Pro
Seem like there is a a same problem on previous iOS versions.
Using AVCaptureDevice as SCNScene background content
My app uses front cam to create AR face in iOS. At first tour, my app uses default SCNView with camera input. After first tour, I am setting ARSCNView background to a UIImage. After setting this I can't go back to previous state by setting scnview.scene.background to nil or inputdevice.
How can I take it back to previous state that shows camera input?
First, I set like below which is shown successfully.
sceneView.scene.background.contents = UIImage(named: "bruin.jpeg")
Then after 15 seconds, I set it with the code below but I get stable image not video preview layer.
DispatchQueue.main.async {
let captureDevice = AVCaptureDevice.default(.builtInWideAngleCamera,
for: .video,
position: .front)!
self.sceneView.scene.background.contents = captureDevice
}
I get this error in output:
// SceneKit Error: Could not get pixel buffer (CVPixelBufferRef)

Using AVCaptureDevice as SCNScene background content

During the SceneKit: What's New presentation at WWCD2017 (44:19) it was stated that we can now use AVCaptureDevice as background content for SCNScene.
Snippet from the presentation:
let captureDevice: AVCaptureDevice = ...
scene.background.contents = captureDevice
However the following code
let captureDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back)!
scene.background.contents = captureDevice
produces an error:
[SceneKit] Error: Cannot get pixel buffer (CVPixelBufferRef)
I also tried to create and start AVCaptureSession and then use the device, but it gives the same result.
What might be an issue here?
Edit
This bug seems to be fixed in iOS 11.2
Original answer
this appears to be a bug in SceneKit.
If that works for you a workaround would be to use an ARSCNView. It gives you access to all the SceneKit APIs, and it automatically draws the video feed as the scene's background.

AVCaptureStillImageOutput connection withType returns nil connection

I'm using the AVCaptureStillImageOutput to capture a photo on iOS.
To capture the photo I'm calling captureStillImageAsynchronously.
This requires a connection so I use:
let connection = stillImageOutput.connection(withMediaType: AVMediaTypeVideo)
However on certain devices namely iPad 2 on iOS 9.3.5 I see that the connection returned is nil.
I also tried iterating through all connections using:
stillImageOutput.connections
This shows there are no connections available.
Has anyone else encountered this issue? Is there another better way to obtain the connection? I realize I'm using a deprecated class however the new method is not available on iOS 9 and we still need to support this platform. BTW the camera app itself appears to work just fine on this device.
Also just noticed that canAddInput on AVCaptureSession is returning false.
The input is obtained as follows:
guard let captureDevices = AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo) as? [AVCaptureDevice],
let captureDevice = captureDevices.first(where: { $0.position == .back }),
let captureDeviceInput = try? AVCaptureDeviceInput(device: captureDevice) else {
return
}

issue while taking photo wtth flash On using AVCapturePhotoOutput

I am working on camera app. i am using AVCapturePhotoOutput for ios 10.x device and AVCaptureStillImageOutput for below 10.x devices.
I am using below capture settings while capturing Photo
let settings = AVCapturePhotoSettings()
let previewPixelType = settings.availablePreviewPhotoPixelFormatTypes.first!
let previewFormat = [kCVPixelBufferPixelFormatTypeKey as String: previewPixelType,
kCVPixelBufferWidthKey as String: 1080,
kCVPixelBufferHeightKey as String: 1080,
]
settings.previewPhotoFormat = previewFormat
settings.isHighResolutionPhotoEnabled = true
settings.flashMode = .on
settings.isAutoStillImageStabilizationEnabled = true
self.captureOutputPhoto?.capturePhoto(with: settings, delegate: self)
when i am try to capture photo using above setting
captureOutput:didFinishProcessingPhotoSampleBuffer:previewPhotoSampleBuffer:resolvedSettings:bracketSettings:error
above delegate throws error first time. I am beginner for AVCapturePhotoSettings. the problem is occurs after every successful photo capture with flash mode.
From Apple documentation:
You may not enable image stabilization if the flash mode is
on
. (Enabling the flash takes priority over the
isAutoStillImageStabilizationEnabled
setting.)
Not sure, if it should throw error, but you can try to remove this string
settings.isAutoStillImageStabilizationEnabled = true
captureOutput:didFinishProcessingPhotoSampleBuffer:previewPhotoSampleBuffer:resolvedSettings:bracketSettings:error:, an Objective-C delegate method, whose Swift version is photoOutput(_:didFinishProcessingPhoto:previewPhoto:resolvedSettings:bracketSettings:error:), is deprecated.
Instead implement the Swift method photoOutput(_:didFinishProcessingPhoto:error:).
I'm using this method for handling the flash settings. AVCaptureDevice is basically the camera that you are using and the AVCaptureFlashMode is the flash mode you want to use.
func changeFlashSettings(device: AVCaptureDevice, mode: AVCaptureFlashMode) {
do {
try device.lockForConfiguration()
device.flashMode = mode
device.unlockForConfiguration()
} catch {
print("Change Flash Configuration Error: \(error)")
}
}
With this you can set the flash setting to on, off or auto. Hope this helps.

Knowing resolution of AVCaptureSession's session presets

I'm accessing the camera in iOS and using session presets as so:
captureSession.sessionPreset = AVCaptureSessionPresetMedium;
Pretty standard stuff. However, I'd like to know ahead of time the resolution of the video I'll be getting due to this preset (especially because depending on the device it'll be different). I know there are tables online you can look this up (such as here: http://cmgresearch.blogspot.com/2010/10/augmented-reality-on-iphone-with-ios40.html ). But I'd like to be able to get this programmatically so that I'm not just relying on magic numbers.
So, something like this (theoretically):
[captureSession resolutionForPreset:AVCaptureSessionPresetMedium];
which might return a CGSize of { width: 360, height: 480}. I have not been able to find any such API, so far I've had to resort to waiting to get my first captured image and querying it then (which for other reasons in my program flow is not good).
I am no AVFoundation pro, but I think the way to go is:
captureSession.sessionPreset = AVCaptureSessionPresetMedium;
AVCaptureInput *input = [captureSession.inputs objectAtIndex:0]; // maybe search the input in array
AVCaptureInputPort *port = [input.ports objectAtIndex:0];
CMFormatDescriptionRef formatDescription = port.formatDescription;
CMVideoDimensions dimensions = CMVideoFormatDescriptionGetDimensions(formatDescription);
I'm not sure about the last step and I didn't try it myself. Just found that in the documentation and think it should work.
Searching for CMVideoDimensions in Xcode you'll find the RosyWriter example project. Have a look at that code (I don't have time to do that now).
You can programmatically get the resolution from activeFormat before capture begins, though not before adding inputs and outputs: https://developer.apple.com/library/ios/documentation/AVFoundation/Reference/AVCaptureDevice_Class/index.html#//apple_ref/occ/instp/AVCaptureDevice/activeFormat
private func getCaptureResolution() -> CGSize {
// Define default resolution
var resolution = CGSize(width: 0, height: 0)
// Get cur video device
let curVideoDevice = useBackCamera ? backCameraDevice : frontCameraDevice
// Set if video portrait orientation
let portraitOrientation = orientation == .Portrait || orientation == .PortraitUpsideDown
// Get video dimensions
if let formatDescription = curVideoDevice?.activeFormat.formatDescription {
let dimensions = CMVideoFormatDescriptionGetDimensions(formatDescription)
resolution = CGSize(width: CGFloat(dimensions.width), height: CGFloat(dimensions.height))
if (portraitOrientation) {
resolution = CGSize(width: resolution.height, height: resolution.width)
}
}
// Return resolution
return resolution
}
FYI, I attach here an official reply from Apple.
This is a follow-up to Bug ID# 13201137.
Engineering has determined that this issue behaves as intended based on the following information:
There are several problems with the included code:
1) The AVCaptureSession has no inputs.
2) The AVCaptureSession has no outputs.
Without at least one input (added to the session using [AVCaptureSession addInput:]) and a compatible output (added using [AVCaptureSession addOutput:]), there will be no active connections, therefore, the session won't actually run in the input device. It doesn't need to -- there are no outputs to which to deliver any camera data.
3) The JAViewController class assumes that the video port's -formatDescription property will be non nil as soon as [AVCaptureSession startRunning] returns.
There is no guarantee that the format description will be updated with the new camera format as soon as startRunning returns. -startRunning starts up the camera and returns when it is completely up and running, but doesn't wait for video frames to be actively flowing through the capture pipeline, which is when the format description would be updated.
You're just querying too fast. If you waited a few milliseconds more, it would be there. But the right way to do this is to listen for the AVCaptureInputPortFormatDescriptionDidChangeNotification.
4) Your JAViewController class creates a PVCameraInfo object in retrieveCameraInfo: and asks it a question, then lets it fall out of scope, where it is released and dealloc'ed.
Therefore, the session doesn't have long enough to run to satisfy your dimensions request. You stop the camera too quickly.
We consider this issue closed. If you have any questions or concern regarding this issue, please update your report directly (http://bugreport.apple.com).
Thank you for taking the time to notify us of this issue.
Best Regards,
Developer Bug Reporting Team
Apple Worldwide Developer Relations
According to Apple, there's no API for that. It stinks, I've had the same problem.
May be you can provide a list of all posible preset resolutions for every iPhone model and check which device model the app is running on? - using something like this...
[[UIDevice currentDevice] platformType] // ex: UIDevice4GiPhone
[[UIDevice currentDevice] platformString] // ex: #"iPhone 4G"
However, you have to update the list for each newer device model. Hope this helps :)
if preset is .photo, the return size is for still photo size, not preview video size
if preset is not .photo, the return size is for video size, not for captured photo size.
if self.session.sessionPreset != .photo {
// return video size, not captured photo size
let format = videoDevice.activeFormat
let formatDescription = format.formatDescription
let dimensions = CMVideoFormatDescriptionGetDimensions(formatDescription)
} else {
// other way to get video size
}
Answer of #Christian Beer is a good way for specified preset.
My way is a good for active preset.
The best way to do what you want (get a known video or image format) is to set the format of the capture device.
First find the capture device you want to use:
if #available(iOS 10.0, *) {
captureDevice = defaultCamera()
} else {
let devices = AVCaptureDevice.devices()
// Loop through all the capture devices on this phone
for device in devices {
// Make sure this particular device supports video
if ((device as AnyObject).hasMediaType(AVMediaType.video)) {
// Finally check the position and confirm we've got the back camera
if((device as AnyObject).position == AVCaptureDevice.Position.back) {
captureDevice = device as AVCaptureDevice
}
}
}
}
self.autoLevelWindowCenter = ALCWindow.frame
if captureDevice != nil && currentUser != nil {
beginSession()
}
}
func defaultCamera() -> AVCaptureDevice? {
if #available(iOS 10.0, *) { // only use the wide angle camera never dual camera
if let device = AVCaptureDevice.default(AVCaptureDevice.DeviceType.builtInWideAngleCamera,
for: AVMediaType.video,
position: .back) {
return device
} else {
return nil
}
} else {
return nil
}
}
Then find the formats that that device can use:
let options = captureDevice!.formats
var supportable = options.first as! AVCaptureDevice.Format
for format in options {
let testFormat = format
let description = testFormat.description
if (description.contains("60 fps") && description.contains("1280x 720")){
supportable = testFormat
}
}
You can do more complex parsing of the formats, but you might not care.
Then just set the device to that format:
do {
try captureDevice?.lockForConfiguration()
captureDevice!.activeFormat = supportable
// setup other capture device stuff like autofocus, frame rate, ISO, shutter speed, etc.
try captureSession.addInput(AVCaptureDeviceInput(device: captureDevice!))
// add the device to an active CaptureSession
}
You may want to look at the AVFoundation docs and tutorial on AVCaptureSession as there are lots of things you can do with the output as well. For example, you can convert the result to .mp4 using AVAssetExportSession so that you can post it on YouTube, etc.
Hope this helps
Apple is using 4:3 ratio for the iPhone camera.
You can you this ratio to get the frame size of the captured video by fixing either the width or height constraint of the AVCaptureVideoPreviewLayer and set the aspect ratio constraint to 4:3.
In the left image, the width was fixed to 300px and the height was retrieved by setting the 4:3 ratio, and it was 400px.
In the right image, the height was fixed to 300px and width was retrieved by setting the 3:4 ratio, and it was 225px.

Resources