AVCaptureDevice exception in setting WhiteBalance

44 Views Asked by At

I have the following code adapted from AVCamManual sample code to set white balance. I still see crash reports in analytics where exception is raised in setting WB. It is not clear how things are turning out of range despite checks in place.

 *** -[AVCaptureDevice temperatureAndTintValuesForDeviceWhiteBalanceGains:] 
whiteBalanceGains contain an out-of-range value - red, green, and blue gains
must be in the [1, maxWhiteBalanceGain] range

Here is my code, it is not clear how things are turning out of range.

// How can gains be out of range? Any Swift language issue?

public func normalizedGains(gains:AVCaptureDevice.WhiteBalanceGains) -> AVCaptureDevice.WhiteBalanceGains {
  
  var g = gains

   if let device = videoDevice {
      g.redGain = max(1.0, g.redGain)
      g.blueGain = max(1.0, g.blueGain)
      g.greenGain = max(1.0, g.greenGain)
    
      g.redGain = min(device.maxWhiteBalanceGain, g.redGain)
      g.blueGain = min(device.maxWhiteBalanceGain, g.blueGain)
      g.greenGain = min(device.maxWhiteBalanceGain, g.greenGain)
   }

   return g
}

And my code to set WB:

public func setTemperatureAndTint( colorTemperature:Float?, tint:Float?) {

  if let device = videoDevice {
    var tint = tint
    var colorTemperature = colorTemperature
    
    if colorTemperature == nil {
        colorTemperature = device.temperatureAndTintValues(for: device.deviceWhiteBalanceGains).temperature
    }
    
    if tint == nil {
        tint = device.temperatureAndTintValues(for: device.deviceWhiteBalanceGains).tint
    }
    
    let temperatureTint = AVCaptureDevice.WhiteBalanceTemperatureAndTintValues(temperature: colorTemperature!, tint: tint!)
    
    NSLog("Setting tint \(temperatureTint.tint)")
    
    do {
        try device.lockForConfiguration()
        device.setWhiteBalanceModeLocked(with: normalizedGains(gains: device.deviceWhiteBalanceGains(for: temperatureTint)) , completionHandler: nil)
        device.unlockForConfiguration()
        
        wbLockedtoGray = false
    } catch {
        NSLog("Unable to change White balance gain \(error)")
    }
  }
}

Is there anything I am doing wrong?

0

There are 0 best solutions below