public void OpenCamera()
        {
            if (MyCamera != null)
            {
                MyCamera.StopPreview();
                MyCamera.Release();
                MyCamera = null;
            }

            if (_cameraId >= 0)
            {
                Camera.GetCameraInfo(_cameraId, _cameraInfo);

                MyCamera = Camera.Open(_cameraId);

                Camera.Parameters param = MyCamera.GetParameters();
                param.SetRotation(0);

                MyCamera.SetParameters(param);

                try {
                    if (_surfaceTexture != null)
                    {
                        MyCamera.SetPreviewTexture(_surfaceTexture);
                        MyCamera.StartPreview();
                    }
                } catch (Exception) {
                }
            }

            UpdateRotation();
        }
Exemple #2
0
        private void UpdateCameraAspect()
        {
            try
            {
                Camera.Parameters camParams = camera.GetParameters();
                Camera.CameraInfo info      = new Camera.CameraInfo();
                Camera.GetCameraInfo((int)Android.Hardware.CameraFacing.Back, info);

                Camera.Size size = GetOptimalPreviewSize(camParams.SupportedPreviewSizes, width, height);

                camParams.SetPreviewSize(size.Width, size.Height);

                int rotation = (info.Orientation + 360) % 360;

                camParams.SetRotation(rotation);

                if (camParams.SupportedFocusModes.Contains(Camera.Parameters.FocusModeContinuousPicture))
                {
                    camParams.FocusMode = Camera.Parameters.FocusModeContinuousPicture;
                }

                camera.SetParameters(camParams);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
        private int GetCameraDisplayOrientation()
        {
            int degrees;
            var windowManager = _context.GetSystemService(Context.WindowService).JavaCast <IWindowManager>();
            var display       = windowManager.DefaultDisplay;
            var rotation      = display.Rotation;

            if (ZxingActivity.ScanningOptions.AndroidOptions?.ModifyCameraDisplayOrientationDelegate != null)
            {
                degrees = ZxingActivity.ScanningOptions.AndroidOptions.ModifyCameraDisplayOrientationDelegate.Invoke((int)rotation);
            }
            else
            {
                switch (rotation)
                {
                case SurfaceOrientation.Rotation0:
                    degrees = 0;
                    break;

                case SurfaceOrientation.Rotation90:
                    degrees = 90;
                    break;

                case SurfaceOrientation.Rotation180:
                    degrees = 180;
                    break;

                case SurfaceOrientation.Rotation270:
                    degrees = 270;
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }

            var info = new Camera.CameraInfo();

            Camera.GetCameraInfo(_cameraId, info);

            int correctedDegrees;

            if (info.Facing == CameraFacing.Front)
            {
                correctedDegrees = (info.Orientation + degrees) % 360;
                correctedDegrees = (360 - correctedDegrees) % 360; // compensate the mirror
            }
            else
            {
                // back-facing
                correctedDegrees = (info.Orientation - degrees + 360) % 360;
            }

            return(correctedDegrees);
        }
 // Populate |cameraOrientations| with the first cameras that have each of
 // the facing values.
 private void populateCameraOrientations()
 {
     Camera.CameraInfo info = new Camera.CameraInfo();
     for (int i = 0; i < Camera.NumberOfCameras; ++i)
     {
         Camera.GetCameraInfo(i, info);
         if (cameraOrientations[(int)info.Facing] != -1)
         {
             continue;
         }
         cameraOrientations[(int)info.Facing] = info.Orientation;
     }
 }
Exemple #5
0
        private void OpenCamera()
        {
            try
            {
                var version = Build.VERSION.SdkInt;

                if (version >= BuildVersionCodes.Gingerbread)
                {
                    System.Diagnostics.Debug.WriteLine("Checking Number of cameras...");

                    var numCameras = Camera.NumberOfCameras;
                    var camInfo    = new Camera.CameraInfo();
                    var found      = false;
                    System.Diagnostics.Debug.WriteLine("Found " + numCameras + " cameras...");

                    var whichCamera = CameraFacing.Back;

                    for (var i = 0; i < numCameras; i++)
                    {
                        Camera.GetCameraInfo(i, camInfo);
                        if (camInfo.Facing == whichCamera)
                        {
                            System.Diagnostics.Debug.WriteLine(
                                "Found " + whichCamera + " Camera, opening...");
                            camera   = Camera.Open(i);
                            cameraId = i;
                            found    = true;
                            break;
                        }
                    }

                    if (!found)
                    {
                        System.Diagnostics.Debug.WriteLine(
                            "Finding " + whichCamera + " camera failed, opening camera 0...");
                        camera   = Camera.Open(0);
                        cameraId = 0;
                    }
                }
                else
                {
                    camera = Camera.Open();
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"Setup Error: {ex}");
            }
        }
Exemple #6
0
        int GetCameraDisplayOrientation()
        {
            int degrees;
            var windowManager = context.GetSystemService(Context.WindowService).JavaCast <IWindowManager>();
            var display       = windowManager.DefaultDisplay;
            var rotation      = display.Rotation;

            switch (rotation)
            {
            case SurfaceOrientation.Rotation0:
                degrees = 0;
                break;

            case SurfaceOrientation.Rotation90:
                degrees = 90;
                break;

            case SurfaceOrientation.Rotation180:
                degrees = 180;
                break;

            case SurfaceOrientation.Rotation270:
                degrees = 270;
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            var info = new Camera.CameraInfo();

            Camera.GetCameraInfo(cameraId, info);

            int correctedDegrees;

            if (info.Facing == CameraFacing.Front)
            {
                correctedDegrees = (info.Orientation + degrees) % 360;
                correctedDegrees = (360 - correctedDegrees) % 360;                 // compensate the mirror
            }
            else
            {
                // back-facing
                correctedDegrees = (info.Orientation - degrees + 360) % 360;
            }

            return(correctedDegrees);
        }
        private void OpenCamera(CameraFacing whichCamera)
        {
            try
            {
                var version = Build.VERSION.SdkInt;

                if (version >= BuildVersionCodes.Gingerbread)
                {
                    var numCameras = Camera.NumberOfCameras;
                    var camInfo    = new Camera.CameraInfo();
                    var found      = false;



                    for (var i = 0; i < numCameras; i++)
                    {
                        Camera.GetCameraInfo(i, camInfo);
                        if (camInfo.Facing == whichCamera)
                        {
                            Camera    = Camera.Open(i);
                            _cameraId = i;
                            found     = true;
                            break;
                        }
                    }

                    if (!found)
                    {
                        Camera    = Camera.Open(0);
                        _cameraId = 0;
                    }
                }
                else
                {
                    Camera = Camera.Open();
                }

                //if (Camera != null)
                //    Camera.SetPreviewCallback(_cameraEventListener);
                //else
                //    MobileBarcodeScanner.LogWarn(MobileBarcodeScanner.TAG, "Camera is null :(");
            }
            catch (Exception ex)
            {
                ShutdownCamera();
                // MobileBarcodeScanner.LogError("Setup Error: {0}", ex);
            }
        }
Exemple #8
0
        public BarcodeScannerRenderer(Context context) : base(context)
        {
            cameraInfo = new Camera.CameraInfo();
            Camera.GetCameraInfo(0, cameraInfo);
            cam        = Camera.Open(0);
            parameters = cam.GetParameters();

            Camera.Size size = parameters.PictureSize;
            cheight = size.Height;
            cwidth  = size.Width;

            maxZoom = parameters.MaxZoom;


            cam.SetPreviewCallback(this);
        }
Exemple #9
0
        private void OnOrientationChanged(int orientation)
        {
            if (_camera == null)
            {
                return;
            }

            var info = new Camera.CameraInfo();

            Camera.GetCameraInfo(_cameraId, info);

            orientation = (orientation + 45) / 90 * 90;
            var rotation = info.Facing == Camera.CameraInfo.CameraFacingFront
                ? (info.Orientation - orientation + 360) % 360
                : (info.Orientation + orientation) % 360;

            _currentRotation = rotation;
        }
        int getCameraDisplayOrientation(Activity context)
        {
            var degrees  = 0;
            var display  = context.WindowManager.DefaultDisplay;
            var rotation = display.Rotation;

            switch (rotation)
            {
            case SurfaceOrientation.Rotation0:
                degrees = 0;
                break;

            case SurfaceOrientation.Rotation90:
                degrees = 90;
                break;

            case SurfaceOrientation.Rotation180:
                degrees = 180;
                break;

            case SurfaceOrientation.Rotation270:
                degrees = 270;
                break;
            }

            var info = new Camera.CameraInfo();

            Camera.GetCameraInfo(cameraId, info);

            int correctedDegrees;

            if (info.Facing == CameraFacing.Front)
            {
                correctedDegrees = (info.Orientation + degrees) % 360;
                correctedDegrees = (360 - correctedDegrees) % 360; // compensate the mirror
            }
            else
            {
                // back-facing
                correctedDegrees = (info.Orientation - degrees + 360) % 360;
            }

            return(correctedDegrees);
        }
        /**
         * Selects either front-facing or back-facing camera.
         */
        public void SetCameraFront(bool frontFacing)
        {
            var facing = (int)(frontFacing ? CameraFacing.Front : CameraFacing.Back);

            _cameraId = -1;
            var numberOfCameras = Camera.NumberOfCameras;

            for (var i = 0; i < numberOfCameras; ++i)
            {
                Camera.GetCameraInfo(i, _cameraInfo);
                if ((int)_cameraInfo.Facing == facing)
                {
                    _cameraId = i;
                    break;
                }
            }

            OpenCamera();
        }
Exemple #12
0
        int GetCorrectedCameraDisplayDegrees(int degrees)
        {
            var info = new Camera.CameraInfo();

            Camera.GetCameraInfo(cameraId, info);

            int correctedDegrees;

            if (info.Facing == CameraFacing.Front)
            {
                correctedDegrees = (info.Orientation + degrees) % 360;
                correctedDegrees = (360 - correctedDegrees) % 360; // compensate the mirror
            }
            else
            {
                // back-facing
                correctedDegrees = (info.Orientation - degrees + 360) % 360;
            }

            return(correctedDegrees);
        }
        int getCameraDisplayOrientation(Activity context)
        {
            var degrees = 0;

            var display = context.WindowManager.DefaultDisplay;

            var rotation = display.Rotation;

            switch (rotation)
            {
            case SurfaceOrientation.Rotation0:
                degrees = 0;
                break;

            case SurfaceOrientation.Rotation90:
                degrees = 90;
                break;

            case SurfaceOrientation.Rotation180:
                degrees = 180;
                break;

            case SurfaceOrientation.Rotation270:
                degrees = 270;
                break;
            }


            Camera.CameraInfo info = new Camera.CameraInfo();

            Camera.GetCameraInfo(cameraId, info);

            int correctedDegrees = (360 + info.Orientation - degrees) % 360;

            return(correctedDegrees);
        }
        async Task SetupCamera()
        {
            if (camera != null)
            {
                return;
            }

            await tcsSurfaceReady.Task;

            lastPreviewAnalysis = DateTime.UtcNow.AddMilliseconds(this.scanningOptions.InitialDelayBeforeAnalyzingFrames);
            isAnalyzing         = true;

            CheckCameraPermissions();

            var perf = PerformanceCounter.Start();

            GetExclusiveAccess();

            try {
                var version = Build.VERSION.SdkInt;

                if (version >= BuildVersionCodes.Gingerbread)
                {
                    Android.Util.Log.Debug(MobileBarcodeScanner.TAG, "Checking Number of cameras...");

                    var numCameras = Camera.NumberOfCameras;
                    var camInfo    = new Camera.CameraInfo();
                    var found      = false;
                    Android.Util.Log.Debug(MobileBarcodeScanner.TAG, "Found " + numCameras + " cameras...");

                    var whichCamera = CameraFacing.Back;

                    if (this.scanningOptions.UseFrontCameraIfAvailable.HasValue && this.scanningOptions.UseFrontCameraIfAvailable.Value)
                    {
                        whichCamera = CameraFacing.Front;
                    }

                    for (int i = 0; i < numCameras; i++)
                    {
                        Camera.GetCameraInfo(i, camInfo);
                        if (camInfo.Facing == whichCamera)
                        {
                            Android.Util.Log.Debug(MobileBarcodeScanner.TAG, "Found " + whichCamera + " Camera, opening...");
                            camera   = Camera.Open(i);
                            cameraId = i;
                            found    = true;
                            break;
                        }
                    }

                    if (!found)
                    {
                        Android.Util.Log.Debug(MobileBarcodeScanner.TAG, "Finding " + whichCamera + " camera failed, opening camera 0...");
                        camera   = Camera.Open(0);
                        cameraId = 0;
                    }
                }
                else
                {
                    camera = Camera.Open();
                }

                if (camera != null)
                {
                    camera.SetPreviewCallback(this);
                }
                else
                {
                    MobileBarcodeScanner.LogWarn(MobileBarcodeScanner.TAG, "Camera is null :(");
                    return;
                }
            } catch (Exception ex) {
                ShutdownCamera();
                MobileBarcodeScanner.LogError("Setup Error: {0}", ex);
                return;
            }
            PerformanceCounter.Stop(perf, "Setup Camera took {0}ms");

            perf = PerformanceCounter.Start();

            var parameters = camera.GetParameters();

            parameters.PreviewFormat = ImageFormatType.Nv21;

            // First try continuous video, then auto focus, then fixed
            var supportedFocusModes = parameters.SupportedFocusModes;

            if (Build.VERSION.SdkInt >= BuildVersionCodes.IceCreamSandwich &&
                supportedFocusModes.Contains(Camera.Parameters.FocusModeContinuousPicture))
            {
                parameters.FocusMode = Camera.Parameters.FocusModeContinuousPicture;
            }
            else if (supportedFocusModes.Contains(Camera.Parameters.FocusModeContinuousVideo))
            {
                parameters.FocusMode = Camera.Parameters.FocusModeContinuousVideo;
            }
            else if (supportedFocusModes.Contains(Camera.Parameters.FocusModeAuto))
            {
                parameters.FocusMode = Camera.Parameters.FocusModeAuto;
            }
            else if (supportedFocusModes.Contains(Camera.Parameters.FocusModeFixed))
            {
                parameters.FocusMode = Camera.Parameters.FocusModeFixed;
            }

            var selectedFps = parameters.SupportedPreviewFpsRange.FirstOrDefault();

            if (selectedFps != null)
            {
                // This will make sure we select a range with the lowest minimum FPS
                // and maximum FPS which still has the lowest minimum
                // This should help maximize performance / support for hardware
                foreach (var fpsRange in parameters.SupportedPreviewFpsRange)
                {
                    if (fpsRange [0] <= selectedFps [0] &&
                        fpsRange [1] > selectedFps [1])
                    {
                        selectedFps = fpsRange;
                    }
                }
                parameters.SetPreviewFpsRange(selectedFps [0], selectedFps [1]);
            }

            var availableResolutions = new List <CameraResolution> ();

            foreach (var sps in parameters.SupportedPreviewSizes)
            {
                availableResolutions.Add(new CameraResolution {
                    Width  = sps.Width,
                    Height = sps.Height
                });
            }

            // Try and get a desired resolution from the options selector
            var resolution = scanningOptions.GetResolution(availableResolutions);

            // If the user did not specify a resolution, let's try and find a suitable one
            if (resolution == null)
            {
                // Loop through all supported sizes
                foreach (var sps in parameters.SupportedPreviewSizes)
                {
                    // Find one that's >= 640x360 but <= 1000x1000
                    // This will likely pick the *smallest* size in that range, which should be fine
                    if (sps.Width >= 640 && sps.Width <= 1000 && sps.Height >= 360 && sps.Height <= 1000)
                    {
                        resolution = new CameraResolution {
                            Width  = sps.Width,
                            Height = sps.Height
                        };
                        break;
                    }
                }
            }

            // Google Glass requires this fix to display the camera output correctly
            if (Build.Model.Contains("Glass"))
            {
                resolution = new CameraResolution {
                    Width  = 640,
                    Height = 360
                };
                // Glass requires 30fps
                parameters.SetPreviewFpsRange(30000, 30000);
            }

            // Hopefully a resolution was selected at some point
            if (resolution != null)
            {
                Android.Util.Log.Debug(MobileBarcodeScanner.TAG, "Selected Resolution: " + resolution.Width + "x" + resolution.Height);
                parameters.SetPreviewSize(resolution.Width, resolution.Height);
            }

            camera.SetParameters(parameters);

            SetCameraDisplayOrientation(this.activity);

            camera.SetPreviewDisplay(this.Holder);
            camera.StartPreview();

            PerformanceCounter.Stop(perf, "Setup Camera Parameters took {0}ms");

            // Docs suggest if Auto or Macro modes, we should invoke AutoFocus at least once
            var currentFocusMode = camera.GetParameters().FocusMode;

            if (currentFocusMode == Camera.Parameters.FocusModeAuto ||
                currentFocusMode == Camera.Parameters.FocusModeMacro)
            {
                AutoFocus();
            }
        }
        private void SetupAndStartCamera(SurfaceTexture surface = null)
        {
            try
            {
                if (_isSurfaceAvailable)
                {
                    if (_camera == null)
                    {
                        _camera = Camera.Open((int)_cameraType);
                        _camera.SetErrorCallback(this);

                        for (var ii = 0; ii < Camera.NumberOfCameras - 1; ii++)
                        {
                            var info = new Camera.CameraInfo();
                            Camera.GetCameraInfo(ii, info);
                            if (info.CanDisableShutterSound)
                            {
                                _camera.EnableShutterSound(false);
                            }
                        }

                        var parameters = _camera.GetParameters();
                        parameters.FlashMode          = Camera.Parameters.FlashModeOff;
                        parameters.VideoStabilization = false;
                        parameters.JpegQuality        = 100;
                        TurnOnContinuousFocus(parameters);

                        var landscapePictureDescendingSizes = parameters
                                                              .SupportedPictureSizes
                                                              .Where(p => p.Width > p.Height)
                                                              .OrderByDescending(p => p.Width * p.Height)
                                                              .ToList();
                        var landscapePreviewDescendingSizes = parameters
                                                              .SupportedPreviewSizes
                                                              .Where(p => p.Width > p.Height)
                                                              .OrderByDescending(p => p.Width * p.Height)
                                                              .ToList();

                        foreach (var pictureSize in landscapePictureDescendingSizes)
                        {
                            foreach (var previewSize in landscapePreviewDescendingSizes)
                            {
                                if (Math.Abs((double)pictureSize.Width / pictureSize.Height -
                                             (double)previewSize.Width / previewSize.Height) < 0.0001)
                                {
                                    _pictureSize = pictureSize;
                                    _previewSize = previewSize;
                                    break;
                                }
                            }

                            if (_pictureSize != null)
                            {
                                break;
                            }
                        }

                        if (_pictureSize == null ||
                            _previewSize == null)
                        {
                            _pictureSize = landscapePictureDescendingSizes.First();
                            _previewSize = landscapePreviewDescendingSizes.First();
                        }

                        parameters.SetPictureSize(_pictureSize.Width, _pictureSize.Height);
                        parameters.SetPreviewSize(_previewSize.Width, _previewSize.Height);

                        _camera.SetParameters(parameters);
                        _camera.SetPreviewTexture(_surfaceTexture);
                    }

                    if (surface != null)
                    {
                        _surfaceTexture = surface;
                    }

                    SetOrientation();
                    StartCamera();
                }
            }
            catch (Exception e)
            {
                _cameraModule.ErrorMessage = e.ToString();
            }
        }
Exemple #16
0
        private void OpenCamera()
        {
            try
            {
                var version = Build.VERSION.SdkInt;

                if (version >= BuildVersionCodes.Gingerbread)
                {
                    Android.Util.Log.Debug(MobileBarcodeScanner.TAG, "Checking Number of cameras...");

                    var numCameras = Camera.NumberOfCameras;
                    var camInfo    = new Camera.CameraInfo();
                    var found      = false;
                    Android.Util.Log.Debug(MobileBarcodeScanner.TAG, "Found " + numCameras + " cameras...");

                    var whichCamera = CameraFacing.Back;

                    if (_scannerHost.ScanningOptions.UseFrontCameraIfAvailable.HasValue &&
                        _scannerHost.ScanningOptions.UseFrontCameraIfAvailable.Value)
                    {
                        whichCamera = CameraFacing.Front;
                    }

                    for (var i = 0; i < numCameras; i++)
                    {
                        Camera.GetCameraInfo(i, camInfo);
                        if (camInfo.Facing == whichCamera)
                        {
                            Android.Util.Log.Debug(MobileBarcodeScanner.TAG,
                                                   "Found " + whichCamera + " Camera, opening...");
                            Camera = Camera.Open(i);

                            _cameraId = i;
                            found     = true;
                            break;
                        }
                    }

                    if (!found)
                    {
                        Android.Util.Log.Debug(MobileBarcodeScanner.TAG,
                                               "Finding " + whichCamera + " camera failed, opening camera 0...");
                        Camera    = Camera.Open(0);
                        _cameraId = 0;
                    }
                }
                else
                {
                    Camera = Camera.Open();
                }

                //if (Camera != null)
                //    Camera.SetPreviewCallback(_cameraEventListener);
                //else
                //    MobileBarcodeScanner.LogWarn(MobileBarcodeScanner.TAG, "Camera is null :(");
            }
            catch (Exception ex)
            {
                ShutdownCamera();
                MobileBarcodeScanner.LogError("Setup Error: {0}", ex);
            }
        }
Exemple #17
0
        void OnSurfaceCreated()
        {
            surfaceCreated      = true;
            lastPreviewAnalysis = DateTime.UtcNow.AddMilliseconds(this.scanningOptions.InitialDelayBeforeAnalyzingFrames);
            isAnalyzing         = true;

            Console.WriteLine("StartScanning");

            CheckCameraPermissions();

            var perf = PerformanceCounter.Start();

            GetExclusiveAccess();

            try {
                var version = Build.VERSION.SdkInt;

                if (version >= BuildVersionCodes.Gingerbread)
                {
                    Android.Util.Log.Debug(MobileBarcodeScanner.TAG, "Checking Number of cameras...");

                    var numCameras = Camera.NumberOfCameras;
                    var camInfo    = new Camera.CameraInfo();
                    var found      = false;
                    Android.Util.Log.Debug(MobileBarcodeScanner.TAG, "Found " + numCameras + " cameras...");

                    var whichCamera = CameraFacing.Back;

                    if (this.scanningOptions.UseFrontCameraIfAvailable.HasValue && this.scanningOptions.UseFrontCameraIfAvailable.Value)
                    {
                        whichCamera = CameraFacing.Front;
                    }

                    for (int i = 0; i < numCameras; i++)
                    {
                        Camera.GetCameraInfo(i, camInfo);
                        if (camInfo.Facing == whichCamera)
                        {
                            Android.Util.Log.Debug(MobileBarcodeScanner.TAG, "Found " + whichCamera + " Camera, opening...");
                            camera   = Camera.Open(i);
                            cameraId = i;
                            found    = true;
                            break;
                        }
                    }

                    if (!found)
                    {
                        Android.Util.Log.Debug(MobileBarcodeScanner.TAG, "Finding " + whichCamera + " camera failed, opening camera 0...");
                        camera   = Camera.Open(0);
                        cameraId = 0;
                    }
                }
                else
                {
                    camera = Camera.Open();
                }

                if (camera == null)
                {
                    Android.Util.Log.Debug(MobileBarcodeScanner.TAG, "Camera is null :(");
                }

                camera.SetPreviewCallback(this);
            } catch (Exception ex) {
                ShutdownCamera();

                Console.WriteLine("Setup Error: " + ex);
            }

            PerformanceCounter.Stop(perf, "Camera took {0}ms");
        }
        public async Task StartScanningAsync(Action <Result> scanResultCallback, MobileBarcodeScanningOptions options = null)
        {
            this.callback        = scanResultCallback;
            this.scanningOptions = options ?? MobileBarcodeScanningOptions.Default;

            lastPreviewAnalysis = DateTime.UtcNow.AddMilliseconds(this.scanningOptions.InitialDelayBeforeAnalyzingFrames);
            isAnalyzing         = true;

            Console.WriteLine("StartScanning");

            CheckCameraPermissions();

            var perf = PerformanceCounter.Start();

            GetExclusiveAccess();

            try {
                var version = Build.VERSION.SdkInt;

                if (version >= BuildVersionCodes.Gingerbread)
                {
                    Android.Util.Log.Debug(MobileBarcodeScanner.TAG, "Checking Number of cameras...");

                    var numCameras = Camera.NumberOfCameras;
                    var camInfo    = new Camera.CameraInfo();
                    var found      = false;
                    Android.Util.Log.Debug(MobileBarcodeScanner.TAG, "Found " + numCameras + " cameras...");

                    var whichCamera = CameraFacing.Back;

                    if (this.scanningOptions.UseFrontCameraIfAvailable.HasValue && this.scanningOptions.UseFrontCameraIfAvailable.Value)
                    {
                        whichCamera = CameraFacing.Front;
                    }

                    for (int i = 0; i < numCameras; i++)
                    {
                        Camera.GetCameraInfo(i, camInfo);
                        if (camInfo.Facing == whichCamera)
                        {
                            Android.Util.Log.Debug(MobileBarcodeScanner.TAG, "Found " + whichCamera + " Camera, opening...");
                            camera   = Camera.Open(i);
                            cameraId = i;
                            found    = true;
                            break;
                        }
                    }

                    if (!found)
                    {
                        Android.Util.Log.Debug(MobileBarcodeScanner.TAG, "Finding " + whichCamera + " camera failed, opening camera 0...");
                        camera   = Camera.Open(0);
                        cameraId = 0;
                    }
                }
                else
                {
                    camera = Camera.Open();
                }

                if (camera == null)
                {
                    Android.Util.Log.Debug(MobileBarcodeScanner.TAG, "Camera is null :(");
                }

                camera.SetPreviewCallback(this);
            } catch (Exception ex) {
                ShutdownCamera();

                Console.WriteLine("Setup Error: " + ex);
            }

            PerformanceCounter.Stop(perf, "Camera took {0}ms");

            if (!surfaceChanged)
            {
                await waitSurface.WaitAsync();
            }

            if (camera == null)
            {
                return;
            }

            perf = PerformanceCounter.Start();

            var parameters = camera.GetParameters();

            parameters.PreviewFormat = ImageFormatType.Nv21;


            var availableResolutions = new List <CameraResolution> ();

            foreach (var sps in parameters.SupportedPreviewSizes)
            {
                availableResolutions.Add(new CameraResolution {
                    Width  = sps.Width,
                    Height = sps.Height
                });
            }

            // Try and get a desired resolution from the options selector
            var resolution = scanningOptions.GetResolution(availableResolutions);

            // If the user did not specify a resolution, let's try and find a suitable one
            if (resolution == null)
            {
                // Loop through all supported sizes
                foreach (var sps in parameters.SupportedPreviewSizes)
                {
                    // Find one that's >= 640x360 but <= 1000x1000
                    // This will likely pick the *smallest* size in that range, which should be fine
                    if (sps.Width >= 640 && sps.Width <= 1000 && sps.Height >= 360 && sps.Height <= 1000)
                    {
                        resolution = new CameraResolution {
                            Width  = sps.Width,
                            Height = sps.Height
                        };
                        break;
                    }
                }
            }

            // Google Glass requires this fix to display the camera output correctly
            if (Build.Model.Contains("Glass"))
            {
                resolution = new CameraResolution {
                    Width  = 640,
                    Height = 360
                };
                // Glass requires 30fps
                parameters.SetPreviewFpsRange(30000, 30000);
            }

            // Hopefully a resolution was selected at some point
            if (resolution != null)
            {
                Android.Util.Log.Debug(MobileBarcodeScanner.TAG, "Selected Resolution: " + resolution.Width + "x" + resolution.Height);
                parameters.SetPreviewSize(resolution.Width, resolution.Height);
            }

            camera.SetParameters(parameters);

            SetCameraDisplayOrientation(this.activity);

            camera.SetPreviewDisplay(this.Holder);
            camera.StartPreview();

            PerformanceCounter.Stop(perf, "SurfaceChanged took {0}ms");

            AutoFocus();
        }
        private void SetCameraDisplayOrientation(int cameraId)
        {
            var rotation = Activity.WindowManager.DefaultDisplay.Rotation;
            var degrees  = 0;

            switch (rotation)
            {
            case SurfaceOrientation.Rotation0:
                degrees = 0;
                break;

            case SurfaceOrientation.Rotation90:
                degrees = 90;
                break;

            case SurfaceOrientation.Rotation180:
                degrees = 180;
                break;

            case SurfaceOrientation.Rotation270:
                degrees = 270;
                break;
            }

            var result = 0;
            var info   = new Camera.CameraInfo();

            Camera.GetCameraInfo(cameraId, info);
            if (info.Facing == CameraFacing.Back)
            {
                result = 360 - degrees + info.Orientation;
            }
            else if (info.Facing == CameraFacing.Front)
            {
                result  = 360 - degrees - info.Orientation;
                result += 360;
            }
            result = result % 360;
            _camera.SetDisplayOrientation(result);

            var parameters = _camera.GetParameters();

            parameters.PictureFormat = ImageFormat.Jpeg;
            parameters.JpegQuality   = 90;

            if (parameters.SupportedFocusModes != null && parameters.SupportedFocusModes.Contains(Camera.Parameters.FocusModeContinuousVideo))
            {
                parameters.FocusMode = Camera.Parameters.FocusModeContinuousVideo;
            }
            if (parameters.SupportedFlashModes != null && parameters.SupportedFlashModes.Contains(Camera.Parameters.FlashModeOff))
            {
                parameters.FlashMode = Camera.Parameters.FlashModeOff;
            }
            if (parameters.SupportedSceneModes != null && parameters.SupportedSceneModes.Contains(Camera.Parameters.SceneModeAuto))
            {
                parameters.SceneMode = Camera.Parameters.SceneModeAuto;
            }
            if (parameters.SupportedWhiteBalance != null && parameters.SupportedWhiteBalance.Contains(Camera.Parameters.WhiteBalanceAuto))
            {
                parameters.WhiteBalance = Camera.Parameters.WhiteBalanceAuto;
            }
            _camera.SetParameters(parameters);
        }