AVCaptureDevice exception in setting WhiteBalance

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:

  *** -[AVCaptureDevice temperatureAndTintValuesForDeviceWhiteBalanceGains:] whiteBalanceGains contain an out-of-range value - red, green, and blue gain

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

  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?

AVCaptureDevice exception in setting WhiteBalance
 
 
Q