/******************************* MAIN FUNCTIONS *******************************/
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();
			var captureDevice = AVCaptureDevice.DefaultDeviceWithMediaType (AVMediaType.Video);
			var input = AVCaptureDeviceInput.FromDevice (captureDevice);
			CaptureSession = new AVCaptureSession();
			CaptureSession.AddInput (input as AVCaptureInput);

			var captureMetadataOutput = new AVCaptureMetadataOutput();
			metadataDelegate = new MetadataObjectsDelegate();
			metadataDelegate.outer = this;
			captureMetadataOutput.SetDelegate(metadataDelegate, DispatchQueue.MainQueue);
			CaptureSession.AddOutput(captureMetadataOutput);
			captureMetadataOutput.MetadataObjectTypes = AVMetadataObjectType.QRCode;

			VideoPreviewLayer = new AVCaptureVideoPreviewLayer (CaptureSession);
			VideoPreviewLayer.VideoGravity = AVLayerVideoGravity.ResizeAspectFill;
			VideoPreviewLayer.Frame = View.Layer.Bounds;
			View.Layer.AddSublayer (VideoPreviewLayer);

			View.BringSubviewToFront (messageLabel);

			QRCodeFrameView = new UIView ();
			QRCodeFrameView.Layer.BorderColor = UIColor.Green.CGColor;
			QRCodeFrameView.Layer.BorderWidth = 2;
			View.AddSubview (QRCodeFrameView);
			View.BringSubviewToFront (QRCodeFrameView);

			CaptureSession.StartRunning();

			cancelButton.Clicked += (sender, e) => {
				this.DismissViewController (true, null);
			};
		}
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			sessionManager = new SessionManager ();
			sessionManager.StartRunning ();

			previewLayer = new AVCaptureVideoPreviewLayer (sessionManager.CaptureSession) {
				Frame = previewView.Bounds,
				VideoGravity = AVLayerVideoGravity.ResizeAspectFill
			};

			if (previewLayer.Connection != null && previewLayer.Connection.SupportsVideoOrientation)
				previewLayer.Connection.VideoOrientation = AVCaptureVideoOrientation.LandscapeLeft;
			previewView.Layer.AddSublayer (previewLayer);
			previewView.Layer.MasksToBounds = true;

			barcodeTargetLayer = new CALayer () {
				Frame = View.Layer.Bounds
			};
			View.Layer.AddSublayer (barcodeTargetLayer);

			synth = new Synth ();
			synth.LoadPreset (this);

			// the loop that continuously looks for barcodes to detect
			stepTimer = NSTimer.CreateScheduledTimer (0.15, this, new Selector ("step:"), null, true);
		}
		bool SetupCaptureSession ()
		{
			// configure the capture session for low resolution, change this if your code
			// can cope with more data or volume
			session = new AVCaptureSession () {
				SessionPreset = AVCaptureSession.PresetMedium
			};

			// create a device input and attach it to the session
			var captureDevice = AVCaptureDevice.DefaultDeviceWithMediaType (AVMediaType.Video);
			var input = AVCaptureDeviceInput.FromDevice (captureDevice);
			if (input == null){
				// No input device
				return false;
			}
			session.AddInput (input);

			// create a VideoDataOutput and add it to the sesion
			var output = new AVCaptureVideoDataOutput () {
				VideoSettings = new AVVideoSettings (CVPixelFormatType.CV32BGRA)
			};

			// configure the output
			queue = new DispatchQueue ("myQueue");
			qrScanner = new QrScanner (this);
			output.SetSampleBufferDelegateAndQueue (qrScanner, queue);
			session.AddOutput (output);

			previewLayer = new AVCaptureVideoPreviewLayer (session);
			previewLayer.Orientation = AVCaptureVideoOrientation.Portrait;
			previewLayer.VideoGravity = "AVLayerVideoGravityResizeAspectFill";

			session.StartRunning ();
			return true;
		}
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			sessionManager = new SessionManager ();
			sessionManager.StartRunning ();

			previewLayer = new AVCaptureVideoPreviewLayer (sessionManager.CaptureSession) {
				Frame = previewView.Bounds,
				VideoGravity = AVLayerVideoGravity.ResizeAspectFill
			};

			if (previewLayer.Connection != null && previewLayer.Connection.SupportsVideoOrientation)
				previewLayer.Connection.VideoOrientation = AVCaptureVideoOrientation.LandscapeLeft;
			previewView.Layer.AddSublayer (previewLayer);
			previewView.Layer.MasksToBounds = true;

			barcodeTargetLayer = new CALayer () {
				Frame = View.Layer.Bounds
			};
			View.Layer.AddSublayer (barcodeTargetLayer);

			synth = new Synth ();
			synth.LoadPreset (this);
		}
        public void SetupLiveCameraStream()
        {
            captureSession = new AVCaptureSession();

            var viewLayer = liveCameraStream.Layer;

            Console.WriteLine(viewLayer.Frame.Width);

            var videoPreviewLayer = new AVCaptureVideoPreviewLayer(captureSession)
            {
                Frame = liveCameraStream.Bounds
            };
            liveCameraStream.Layer.AddSublayer(videoPreviewLayer);

            Console.WriteLine(liveCameraStream.Layer.Frame.Width);

            var captureDevice = AVCaptureDevice.DefaultDeviceWithMediaType(AVMediaType.Video);
            ConfigureCameraForDevice(captureDevice);
            captureDeviceInput = AVCaptureDeviceInput.FromDevice(captureDevice);

            var dictionary = new NSMutableDictionary();
            dictionary[AVVideo.CodecKey] = new NSNumber((int)AVVideoCodec.JPEG);
            stillImageOutput = new AVCaptureStillImageOutput()
            {
                OutputSettings = new NSDictionary()
            };

            captureSession.AddOutput(stillImageOutput);
            captureSession.AddInput(captureDeviceInput);
            captureSession.StartRunning();

            ViewWillLayoutSubviews();
        }
		public void ConfigureCaptureSession (AVCaptureSession captureSession, AVCaptureStillImageOutput captureOutput)
		{
			if (previewLayer != null) {
				previewLayer.RemoveFromSuperLayer ();
				previewLayer = null;
			}

			previewLayer = new AVCaptureVideoPreviewLayer (captureSession) {
				VideoGravity = AVPlayerLayer.GravityResizeAspect,
				Frame = Bounds
			};

			Layer.AddSublayer (previewLayer);

			CaptureOutput = captureOutput;

			CaptureOutput.AddObserver (this, capturingStillImageKeypath, NSKeyValueObservingOptions.New, IntPtr.Zero);
		}
Esempio n. 7
0
        public void InitAndStartCamera()
        {
            session = new AVCaptureSession
            {
                SessionPreset = AVCaptureSession.PresetMedium
            };
            var captureDevice = AVCaptureDevice.DefaultDeviceWithMediaType(AVMediaType.Video);

            NSError error;
            var videoInput = AVCaptureDeviceInput.FromDevice(captureDevice, out error);

            if (videoInput == null || !session.CanAddInput(videoInput)) return;
            session.AddInput(videoInput);
            previewLayer = new AVCaptureVideoPreviewLayer(session) { Frame = rootView.Bounds };
            previewLayer.Connection.VideoOrientation = configDicByRotationChanged[UIApplication.SharedApplication.StatusBarOrientation];
            previewLayer.VideoGravity = AVLayerVideoGravity.ResizeAspectFill;
            cameraView.Layer.AddSublayer(previewLayer);
            session.StartRunning();
        }
		void Initialize ()
		{
			CaptureSession = new AVCaptureSession ();
			previewLayer = new AVCaptureVideoPreviewLayer (CaptureSession) {
				Frame = Bounds,
				VideoGravity = AVLayerVideoGravity.ResizeAspectFill
			};

			var videoDevices = AVCaptureDevice.DevicesWithMediaType (AVMediaType.Video);
			var cameraPosition = (cameraOptions == CameraOptions.Front) ? AVCaptureDevicePosition.Front : AVCaptureDevicePosition.Back;
			var device = videoDevices.FirstOrDefault (d => d.Position == cameraPosition);

			if (device == null) {
				return;
			}

			NSError error;
			var input = new AVCaptureDeviceInput (device, out error);
			CaptureSession.AddInput (input);
			Layer.AddSublayer (previewLayer);
			CaptureSession.StartRunning ();
			IsPreviewing = true;
		}
Esempio n. 9
0
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			session = new AVCaptureSession ();

			var camera = AVCaptureDevice.DefaultDeviceWithMediaType(AVMediaType.Video);
			var input = AVCaptureDeviceInput.FromDevice(camera);
			session.AddInput(input);

			output = new AVCaptureMetadataOutput();
			var metadataDelegate = new MetadataOutputDelegate();
			output.SetDelegate(metadataDelegate, DispatchQueue.MainQueue);
			session.AddOutput(output);

			output.MetadataObjectTypes = new NSString[] {
				AVMetadataObject.TypeQRCode,
				AVMetadataObject.TypeEAN13Code
			};

			var previewLayer = new AVCaptureVideoPreviewLayer(session);
			//var view = new ContentView(UIColor.LightGray, previewLayer, metadataDelegate);

			previewLayer.MasksToBounds = true;
			previewLayer.VideoGravity = AVCaptureVideoPreviewLayer.GravityResizeAspectFill;
			previewLayer.Frame = UIScreen.MainScreen.Bounds;
			this.View.Layer.AddSublayer(previewLayer);

			metadataDelegate.MetadataFound += (s, e) => {
				session.StopRunning();
				new UIAlertView("Scanned!",e.StringValue, null ,"OK",null).Show();
			};

			session.StartRunning();

		}
        void Initialize(bool defaultTorchOn, bool vibrationOnDetected, bool startScanningOnCreate, int scanInterval)
        {
            Configuration.IsScanning = startScanningOnCreate;
            CaptureSession           = new AVCaptureSession();
            CaptureSession.BeginConfiguration();
            this.AutoresizingMask = UIViewAutoresizing.FlexibleDimensions;
            previewLayer          = new AVCaptureVideoPreviewLayer(CaptureSession)
            {
                Frame        = this.Bounds,
                VideoGravity = AVLayerVideoGravity.ResizeAspectFill
            };
            var videoDevices   = AVCaptureDevice.DevicesWithMediaType(AVMediaType.Video);
            var cameraPosition = AVCaptureDevicePosition.Back;
            //var cameraPosition = (cameraOptions == CameraOptions.Front) ? AVCaptureDevicePosition.Front : AVCaptureDevicePosition.Back;
            var device = videoDevices.FirstOrDefault(d => d.Position == cameraPosition);


            if (device == null)
            {
                return;
            }

            NSError error;
            var     input = new AVCaptureDeviceInput(device, out error);

            CaptureSession.AddInput(input);
            CaptureSession.SessionPreset = AVFoundation.AVCaptureSession.Preset1280x720;
            Layer.AddSublayer(previewLayer);

            CaptureSession.CommitConfiguration();



            VideoDataOutput = new AVCaptureVideoDataOutput
            {
                AlwaysDiscardsLateVideoFrames = true,
                WeakVideoSettings             = new CVPixelBufferAttributes {
                    PixelFormatType = CVPixelFormatType.CV32BGRA
                }
                .Dictionary
            };


            captureVideoDelegate             = new CaptureVideoDelegate(vibrationOnDetected, scanInterval);
            captureVideoDelegate.OnDetected += (list) =>
            {
                InvokeOnMainThread(() => {
                    //CaptureSession.StopRunning();
                    this.OnDetected?.Invoke(list);
                });
            };
            VideoDataOutput.SetSampleBufferDelegateQueue(captureVideoDelegate, CoreFoundation.DispatchQueue.MainQueue);

            CaptureSession.AddOutput(VideoDataOutput);
            InvokeOnMainThread(() =>
            {
                CaptureSession.StartRunning();
                //Torch on by default
                if (defaultTorchOn && !GoogleVisionBarCodeScanner.Methods.IsTorchOn())
                {
                    GoogleVisionBarCodeScanner.Methods.ToggleFlashlight();
                }
            });
        }
		private void SetupCamera()
		{
			CaptureSession = null;
			CaptureSession = new AVCaptureSession();
			CaptureSession.SessionPreset = AVCaptureSession.PresetPhoto;

			currentDevice = null;
			inputDevice1 = null;
			inputDevice2 = null;

			foreach (AVCaptureDevice device in AVCaptureDevice.DevicesWithMediaType(AVMediaType.Video))
			{
				if (device.Position == AVCaptureDevicePosition.Front)
				{
					inputDevice1 = device;
				}
				else if (device.Position == AVCaptureDevicePosition.Back)
				{
					inputDevice2 = device;
				}
			}

			NSError error;
			if (inputDevice1.HasFlash)
			{
				inputDevice1.LockForConfiguration(out error);
				inputDevice1.FlashMode = AVCaptureFlashMode.Off;
				FlashButton.TitleLabel.Text = "Flash Off";
			}

			if (inputDevice2.HasFlash)
			{
				inputDevice2.LockForConfiguration(out error);
				inputDevice2.FlashMode = AVCaptureFlashMode.Off;
				FlashButton.TitleLabel.Text = "Flash Off";
			}


			frontCamera = AVCaptureDeviceInput.FromDevice(inputDevice1, out error);
			rearCamera = AVCaptureDeviceInput.FromDevice(inputDevice2, out error);
			currentDevice = inputDevice2;

			if (CaptureSession.CanAddInput(rearCamera))
			{
				CaptureSession.AddInput(rearCamera);
			}

			AVCaptureVideoPreviewLayer previewLayer = new AVCaptureVideoPreviewLayer(CaptureSession);
			previewLayer.VideoGravity = AVLayerVideoGravity.ResizeAspectFill;
			previewLayer.Frame = View.Frame;
			View.Layer.InsertSublayer(previewLayer, 0);

			StillImageOutput = new AVCaptureStillImageOutput();
			StillImageOutput.OutputSettings = new NSDictionary(AVVideo.CodecKey, AVVideo.CodecJPEG);

			CaptureSession.AddOutput(StillImageOutput);

			CaptureSession.StartRunning();
		}
Esempio n. 12
0
        bool SetupCaptureSession()
        {
            // configure the capture session for low resolution, change this if your code
            // can cope with more data or volume
            session = new AVCaptureSession()
            {
                SessionPreset = AVCaptureSession.Preset640x480
            };

            // create a device input and attach it to the session
//			var captureDevice = AVCaptureDevice.DefaultDeviceWithMediaType (AVMediaType.Video);
            AVCaptureDevice captureDevice = null;
            var             devices       = AVCaptureDevice.DevicesWithMediaType(AVMediaType.Video);

            foreach (var device in devices)
            {
                captureDevice = device;
                if (options.UseFrontCameraIfAvailable.HasValue &&
                    options.UseFrontCameraIfAvailable.Value &&
                    device.Position == AVCaptureDevicePosition.Front)
                {
                    break;                     //Front camera successfully set
                }
                else if (device.Position == AVCaptureDevicePosition.Back && (!options.UseFrontCameraIfAvailable.HasValue || !options.UseFrontCameraIfAvailable.Value))
                {
                    break;                     //Back camera succesfully set
                }
            }
            if (captureDevice == null)
            {
                Console.WriteLine("No captureDevice - this won't work on the simulator, try a physical device");
                if (overlayView != null)
                {
                    this.AddSubview(overlayView);
                    this.BringSubviewToFront(overlayView);
                }
                return(false);
            }

            var input = AVCaptureDeviceInput.FromDevice(captureDevice);

            if (input == null)
            {
                Console.WriteLine("No input - this won't work on the simulator, try a physical device");
                if (overlayView != null)
                {
                    this.AddSubview(overlayView);
                    this.BringSubviewToFront(overlayView);
                }
                return(false);
            }
            else
            {
                session.AddInput(input);
            }


            foundResult = false;
            //Detect barcodes with built in avcapture stuff
            AVCaptureMetadataOutput metadataOutput = new AVCaptureMetadataOutput();

            var dg = new CaptureDelegate(metaDataObjects =>
            {
                if (foundResult)
                {
                    return;
                }

                //Console.WriteLine("Found MetaData Objects");

                var mdo = metaDataObjects.FirstOrDefault();

                if (mdo == null)
                {
                    return;
                }

                var readableObj = mdo as AVMetadataMachineReadableCodeObject;

                if (readableObj == null)
                {
                    return;
                }

                foundResult = true;

                //Console.WriteLine("Barcode: " + readableObj.StringValue);

                var zxingFormat = ZXingBarcodeFormatFromAVCaptureBarcodeFormat(readableObj.Type.ToString());

                var rs = new ZXing.Result(readableObj.StringValue, null, null, zxingFormat);

                resultCallback(rs);
            });

            metadataOutput.SetDelegate(dg, DispatchQueue.MainQueue);
            session.AddOutput(metadataOutput);

            //Setup barcode formats
            if (ScanningOptions.PossibleFormats != null && ScanningOptions.PossibleFormats.Count > 0)
            {
                var formats = AVMetadataObjectType.None;

                foreach (var f in ScanningOptions.PossibleFormats)
                {
                    formats |= AVCaptureBarcodeFormatFromZXingBarcodeFormat(f);
                }

                formats &= ~AVMetadataObjectType.None;

                metadataOutput.MetadataObjectTypes = formats;
            }
            else
            {
                metadataOutput.MetadataObjectTypes = metadataOutput.AvailableMetadataObjectTypes;
            }



            previewLayer = new AVCaptureVideoPreviewLayer(session);

            //Framerate set here (15 fps)
            if (previewLayer.RespondsToSelector(new Selector("connection")))
            {
                if (UIDevice.CurrentDevice.CheckSystemVersion(7, 0))
                {
                    var perf1 = PerformanceCounter.Start();

                    NSError lockForConfigErr = null;

                    captureDevice.LockForConfiguration(out lockForConfigErr);
                    if (lockForConfigErr == null)
                    {
                        captureDevice.ActiveVideoMinFrameDuration = new CMTime(1, 10);
                        captureDevice.UnlockForConfiguration();
                    }

                    PerformanceCounter.Stop(perf1, "PERF: ActiveVideoMinFrameDuration Took {0} ms");
                }
                else
                {
                    previewLayer.Connection.VideoMinFrameDuration = new CMTime(1, 10);
                }
            }

                        #if __UNIFIED__
            previewLayer.VideoGravity = AVLayerVideoGravity.ResizeAspectFill;
                        #else
            previewLayer.LayerVideoGravity = AVLayerVideoGravity.ResizeAspectFill;
                        #endif
            previewLayer.Frame    = new CGRect(0, 0, this.Frame.Width, this.Frame.Height);
            previewLayer.Position = new CGPoint(this.Layer.Bounds.Width / 2, (this.Layer.Bounds.Height / 2));

            layerView = new UIView(new CGRect(0, 0, this.Frame.Width, this.Frame.Height));
            layerView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
            layerView.Layer.AddSublayer(previewLayer);

            this.AddSubview(layerView);

            ResizePreview(UIApplication.SharedApplication.StatusBarOrientation);

            if (overlayView != null)
            {
                this.AddSubview(overlayView);
                this.BringSubviewToFront(overlayView);

                //overlayView.LayoutSubviews ();
            }

            session.StartRunning();

            Console.WriteLine("RUNNING!!!");



            //output.AlwaysDiscardsLateVideoFrames = true;


            Console.WriteLine("SetupCamera Finished");

            //session.AddOutput (output);
            //session.StartRunning ();


            if (captureDevice.IsFocusModeSupported(AVCaptureFocusMode.ContinuousAutoFocus))
            {
                NSError err = null;
                if (captureDevice.LockForConfiguration(out err))
                {
                    if (captureDevice.IsFocusModeSupported(AVCaptureFocusMode.ContinuousAutoFocus))
                    {
                        captureDevice.FocusMode = AVCaptureFocusMode.ContinuousAutoFocus;
                    }
                    else if (captureDevice.IsFocusModeSupported(AVCaptureFocusMode.AutoFocus))
                    {
                        captureDevice.FocusMode = AVCaptureFocusMode.AutoFocus;
                    }

                    if (captureDevice.IsExposureModeSupported(AVCaptureExposureMode.ContinuousAutoExposure))
                    {
                        captureDevice.ExposureMode = AVCaptureExposureMode.ContinuousAutoExposure;
                    }
                    else if (captureDevice.IsExposureModeSupported(AVCaptureExposureMode.AutoExpose))
                    {
                        captureDevice.ExposureMode = AVCaptureExposureMode.AutoExpose;
                    }

                    if (captureDevice.IsWhiteBalanceModeSupported(AVCaptureWhiteBalanceMode.ContinuousAutoWhiteBalance))
                    {
                        captureDevice.WhiteBalanceMode = AVCaptureWhiteBalanceMode.ContinuousAutoWhiteBalance;
                    }
                    else if (captureDevice.IsWhiteBalanceModeSupported(AVCaptureWhiteBalanceMode.AutoWhiteBalance))
                    {
                        captureDevice.WhiteBalanceMode = AVCaptureWhiteBalanceMode.AutoWhiteBalance;
                    }

                    if (UIDevice.CurrentDevice.CheckSystemVersion(7, 0) && captureDevice.AutoFocusRangeRestrictionSupported)
                    {
                        captureDevice.AutoFocusRangeRestriction = AVCaptureAutoFocusRangeRestriction.Near;
                    }

                    if (captureDevice.FocusPointOfInterestSupported)
                    {
                        captureDevice.FocusPointOfInterest = new CGPoint(0.5f, 0.5f);
                    }

                    if (captureDevice.ExposurePointOfInterestSupported)
                    {
                        captureDevice.ExposurePointOfInterest = new CGPoint(0.5f, 0.5f);
                    }

                    captureDevice.UnlockForConfiguration();
                }
                else
                {
                    Console.WriteLine("Failed to Lock for Config: " + err.Description);
                }
            }

            return(true);
        }
Esempio n. 13
0
        bool SetupCaptureSession()
        {
            var started = DateTime.UtcNow;

            var availableResolutions = new List <CameraResolution> ();

            var consideredResolutions = new Dictionary <NSString, CameraResolution> {
                { AVCaptureSession.Preset352x288, new CameraResolution   {
                      Width = 352, Height = 288
                  } },
                { AVCaptureSession.PresetMedium, new CameraResolution    {
                      Width = 480, Height = 360
                  } },                                                                                                          //480x360
                { AVCaptureSession.Preset640x480, new CameraResolution   {
                      Width = 640, Height = 480
                  } },
                { AVCaptureSession.Preset1280x720, new CameraResolution  {
                      Width = 1280, Height = 720
                  } },
                { AVCaptureSession.Preset1920x1080, new CameraResolution {
                      Width = 1920, Height = 1080
                  } }
            };

            // configure the capture session for low resolution, change this if your code
            // can cope with more data or volume
            session = new AVCaptureSession()
            {
                SessionPreset = AVCaptureSession.Preset640x480
            };

            // create a device input and attach it to the session
//			var captureDevice = AVCaptureDevice.DefaultDeviceWithMediaType (AVMediaType.Video);
            AVCaptureDevice captureDevice = null;
            var             devices       = AVCaptureDevice.DevicesWithMediaType(AVMediaType.Video);

            foreach (var device in devices)
            {
                captureDevice = device;
                if (options.UseFrontCameraIfAvailable.HasValue &&
                    options.UseFrontCameraIfAvailable.Value &&
                    device.Position == AVCaptureDevicePosition.Front)
                {
                    break;                     //Front camera successfully set
                }
                else if (device.Position == AVCaptureDevicePosition.Back && (!options.UseFrontCameraIfAvailable.HasValue || !options.UseFrontCameraIfAvailable.Value))
                {
                    break;                     //Back camera succesfully set
                }
            }
            if (captureDevice == null)
            {
                Console.WriteLine("No captureDevice - this won't work on the simulator, try a physical device");
                if (overlayView != null)
                {
                    this.AddSubview(overlayView);
                    this.BringSubviewToFront(overlayView);
                }
                return(false);
            }

            CameraResolution resolution = null;

            // Find resolution
            // Go through the resolutions we can even consider
            foreach (var cr in consideredResolutions)
            {
                // Now check to make sure our selected device supports the resolution
                // so we can add it to the list to pick from
                if (captureDevice.SupportsAVCaptureSessionPreset(cr.Key))
                {
                    availableResolutions.Add(cr.Value);
                }
            }

            resolution = options.GetResolution(availableResolutions);

            // See if the user selected a resolution
            if (resolution != null)
            {
                // Now get the preset string from the resolution chosen
                var preset = (from c in consideredResolutions
                              where c.Value.Width == resolution.Width &&
                              c.Value.Height == resolution.Height
                              select c.Key).FirstOrDefault();

                // If we found a matching preset, let's set it on the session
                if (!string.IsNullOrEmpty(preset))
                {
                    session.SessionPreset = preset;
                }
            }

            var input = AVCaptureDeviceInput.FromDevice(captureDevice);

            if (input == null)
            {
                Console.WriteLine("No input - this won't work on the simulator, try a physical device");
                if (overlayView != null)
                {
                    this.AddSubview(overlayView);
                    this.BringSubviewToFront(overlayView);
                }
                return(false);
            }
            else
            {
                session.AddInput(input);
            }


            var startedAVPreviewLayerAlloc = DateTime.UtcNow;

            previewLayer = new AVCaptureVideoPreviewLayer(session);

            var totalAVPreviewLayerAlloc = DateTime.UtcNow - startedAVPreviewLayerAlloc;

            Console.WriteLine("PERF: Alloc AVCaptureVideoPreviewLayer took {0} ms.", totalAVPreviewLayerAlloc.TotalMilliseconds);


            //Framerate set here (15 fps)
            if (UIDevice.CurrentDevice.CheckSystemVersion(7, 0))
            {
                var perf1 = PerformanceCounter.Start();

                NSError lockForConfigErr = null;

                captureDevice.LockForConfiguration(out lockForConfigErr);
                if (lockForConfigErr == null)
                {
                    captureDevice.ActiveVideoMinFrameDuration = new CMTime(1, 10);
                    captureDevice.UnlockForConfiguration();
                }

                PerformanceCounter.Stop(perf1, "PERF: ActiveVideoMinFrameDuration Took {0} ms");
            }
            else
            {
                previewLayer.Connection.VideoMinFrameDuration = new CMTime(1, 10);
            }


            var perf2 = PerformanceCounter.Start();

                        #if __UNIFIED__
            previewLayer.VideoGravity = AVLayerVideoGravity.ResizeAspectFill;
                        #else
            previewLayer.LayerVideoGravity = AVLayerVideoGravity.ResizeAspectFill;
                        #endif
            previewLayer.Frame    = new CGRect(0, 0, this.Frame.Width, this.Frame.Height);
            previewLayer.Position = new CGPoint(this.Layer.Bounds.Width / 2, (this.Layer.Bounds.Height / 2));

            layerView = new UIView(new CGRect(0, 0, this.Frame.Width, this.Frame.Height));
            layerView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
            layerView.Layer.AddSublayer(previewLayer);

            this.AddSubview(layerView);

            ResizePreview(UIApplication.SharedApplication.StatusBarOrientation);

            if (overlayView != null)
            {
                this.AddSubview(overlayView);
                this.BringSubviewToFront(overlayView);

                //overlayView.LayoutSubviews ();
            }

            PerformanceCounter.Stop(perf2, "PERF: Setting up layers took {0} ms");

            var perf3 = PerformanceCounter.Start();

            session.StartRunning();

            PerformanceCounter.Stop(perf3, "PERF: session.StartRunning() took {0} ms");

            var perf4 = PerformanceCounter.Start();

            var videoSettings = NSDictionary.FromObjectAndKey(new NSNumber((int)CVPixelFormatType.CV32BGRA),
                                                              CVPixelBuffer.PixelFormatTypeKey);


            // create a VideoDataOutput and add it to the sesion
            output = new AVCaptureVideoDataOutput {
                WeakVideoSettings = videoSettings
            };

            // configure the output
            queue = new DispatchQueue("ZxingScannerView");             // (Guid.NewGuid().ToString());

            var barcodeReader = new BarcodeReader(null, (img) =>
            {
                var src = new RGBLuminanceSource(img);                 //, bmp.Width, bmp.Height);

                //Don't try and rotate properly if we're autorotating anyway
                if (ScanningOptions.AutoRotate.HasValue && ScanningOptions.AutoRotate.Value)
                {
                    return(src);
                }

                var tmpInterfaceOrientation = UIInterfaceOrientation.Portrait;
                InvokeOnMainThread(() => tmpInterfaceOrientation = UIApplication.SharedApplication.StatusBarOrientation);

                switch (tmpInterfaceOrientation)
                {
                case UIInterfaceOrientation.Portrait:
                    return(src.rotateCounterClockwise().rotateCounterClockwise().rotateCounterClockwise());

                case UIInterfaceOrientation.PortraitUpsideDown:
                    return(src.rotateCounterClockwise().rotateCounterClockwise().rotateCounterClockwise());

                case UIInterfaceOrientation.LandscapeLeft:
                    return(src);

                case UIInterfaceOrientation.LandscapeRight:
                    return(src);
                }

                return(src);
            }, null, null);             //(p, w, h, f) => new RGBLuminanceSource(p, w, h, RGBLuminanceSource.BitmapFormat.Unknown));

            if (ScanningOptions.TryHarder.HasValue)
            {
                Console.WriteLine("TRY_HARDER: " + ScanningOptions.TryHarder.Value);
                barcodeReader.Options.TryHarder = ScanningOptions.TryHarder.Value;
            }
            if (ScanningOptions.PureBarcode.HasValue)
            {
                barcodeReader.Options.PureBarcode = ScanningOptions.PureBarcode.Value;
            }
            if (ScanningOptions.AutoRotate.HasValue)
            {
                Console.WriteLine("AUTO_ROTATE: " + ScanningOptions.AutoRotate.Value);
                barcodeReader.AutoRotate = ScanningOptions.AutoRotate.Value;
            }
            if (!string.IsNullOrEmpty(ScanningOptions.CharacterSet))
            {
                barcodeReader.Options.CharacterSet = ScanningOptions.CharacterSet;
            }
            if (ScanningOptions.TryInverted.HasValue)
            {
                barcodeReader.TryInverted = ScanningOptions.TryInverted.Value;
            }

            if (ScanningOptions.PossibleFormats != null && ScanningOptions.PossibleFormats.Count > 0)
            {
                barcodeReader.Options.PossibleFormats = new List <BarcodeFormat>();

                foreach (var pf in ScanningOptions.PossibleFormats)
                {
                    barcodeReader.Options.PossibleFormats.Add(pf);
                }
            }

            outputRecorder = new OutputRecorder(ScanningOptions, img =>
            {
                if (!IsAnalyzing)
                {
                    return;
                }

                try
                {
                    //var sw = new System.Diagnostics.Stopwatch();
                    //sw.Start();

                    var rs = barcodeReader.Decode(img);

                    //sw.Stop();

                    //Console.WriteLine("Decode Time: {0} ms", sw.ElapsedMilliseconds);

                    if (rs != null)
                    {
                        resultCallback(rs);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("DECODE FAILED: " + ex);
                }
            });

            output.AlwaysDiscardsLateVideoFrames = true;
            output.SetSampleBufferDelegate(outputRecorder, queue);

            PerformanceCounter.Stop(perf4, "PERF: SetupCamera Finished.  Took {0} ms.");

            session.AddOutput(output);
            //session.StartRunning ();


            var perf5 = PerformanceCounter.Start();

            NSError err = null;
            if (captureDevice.LockForConfiguration(out err))
            {
                if (captureDevice.IsFocusModeSupported(AVCaptureFocusMode.ContinuousAutoFocus))
                {
                    captureDevice.FocusMode = AVCaptureFocusMode.ContinuousAutoFocus;
                }
                else if (captureDevice.IsFocusModeSupported(AVCaptureFocusMode.AutoFocus))
                {
                    captureDevice.FocusMode = AVCaptureFocusMode.AutoFocus;
                }

                if (captureDevice.IsExposureModeSupported(AVCaptureExposureMode.ContinuousAutoExposure))
                {
                    captureDevice.ExposureMode = AVCaptureExposureMode.ContinuousAutoExposure;
                }
                else if (captureDevice.IsExposureModeSupported(AVCaptureExposureMode.AutoExpose))
                {
                    captureDevice.ExposureMode = AVCaptureExposureMode.AutoExpose;
                }

                if (captureDevice.IsWhiteBalanceModeSupported(AVCaptureWhiteBalanceMode.ContinuousAutoWhiteBalance))
                {
                    captureDevice.WhiteBalanceMode = AVCaptureWhiteBalanceMode.ContinuousAutoWhiteBalance;
                }
                else if (captureDevice.IsWhiteBalanceModeSupported(AVCaptureWhiteBalanceMode.AutoWhiteBalance))
                {
                    captureDevice.WhiteBalanceMode = AVCaptureWhiteBalanceMode.AutoWhiteBalance;
                }

                if (UIDevice.CurrentDevice.CheckSystemVersion(7, 0) && captureDevice.AutoFocusRangeRestrictionSupported)
                {
                    captureDevice.AutoFocusRangeRestriction = AVCaptureAutoFocusRangeRestriction.Near;
                }

                if (captureDevice.FocusPointOfInterestSupported)
                {
                    captureDevice.FocusPointOfInterest = new PointF(0.5f, 0.5f);
                }

                if (captureDevice.ExposurePointOfInterestSupported)
                {
                    captureDevice.ExposurePointOfInterest = new PointF(0.5f, 0.5f);
                }

                captureDevice.UnlockForConfiguration();
            }
            else
            {
                Console.WriteLine("Failed to Lock for Config: " + err.Description);
            }

            PerformanceCounter.Stop(perf5, "PERF: Setup Focus in {0} ms.");

            return(true);
        }
Esempio n. 14
0
        private bool SetupCaptureSession()
        {
            if (CameraPreviewSettings.Instance.Decoder == null)
            {
                return(false);
            }

            var started = DateTime.UtcNow;

            var availableResolutions = new List <CameraResolution>();

            var consideredResolutions = new Dictionary <NSString, CameraResolution>
            {
                { AVCaptureSession.Preset352x288, new CameraResolution {
                      Width = 352, Height = 288
                  } },
                { AVCaptureSession.PresetMedium, new CameraResolution {
                      Width = 480, Height = 360
                  } },                                                                             //480x360
                { AVCaptureSession.Preset640x480, new CameraResolution {
                      Width = 640, Height = 480
                  } },
                { AVCaptureSession.Preset1280x720, new CameraResolution {
                      Width = 1280, Height = 720
                  } },
                { AVCaptureSession.Preset1920x1080, new CameraResolution {
                      Width = 1920, Height = 1080
                  } }
            };

            // configure the capture session for low resolution, change this if your code
            // can cope with more data or volume
            _session = new AVCaptureSession()
            {
                SessionPreset = AVCaptureSession.Preset640x480
            };

            // create a device input and attach it to the session
            //          var captureDevice = AVCaptureDevice.DefaultDeviceWithMediaType (AVMediaType.Video);
            AVCaptureDevice captureDevice = null;
            var             devices       = AVCaptureDevice.DevicesWithMediaType(AVMediaType.Video);

            foreach (var device in devices)
            {
                captureDevice = device;
                if (CameraPreviewSettings.Instance.ScannerOptions.UseFrontCameraIfAvailable.HasValue &&
                    CameraPreviewSettings.Instance.ScannerOptions.UseFrontCameraIfAvailable.Value &&
                    device.Position == AVCaptureDevicePosition.Front)
                {
                    break; //Front camera successfully set
                }
                else if (device.Position == AVCaptureDevicePosition.Back &&
                         (!CameraPreviewSettings.Instance.ScannerOptions.UseFrontCameraIfAvailable.HasValue ||
                          !CameraPreviewSettings.Instance.ScannerOptions.UseFrontCameraIfAvailable.Value))
                {
                    break; //Back camera successfully set
                }
            }

            if (captureDevice == null)
            {
                Console.WriteLine("No captureDevice - this won't work on the simulator, try a physical device");
                return(false);
            }

            CameraResolution resolution = null;

            // Find resolution
            // Go through the resolutions we can even consider
            foreach (var cr in consideredResolutions)
            {
                // Now check to make sure our selected device supports the resolution
                // so we can add it to the list to pick from
                if (captureDevice.SupportsAVCaptureSessionPreset(cr.Key))
                {
                    availableResolutions.Add(cr.Value);
                }
            }

            resolution = CameraPreviewSettings.Instance.ScannerOptions.GetResolution(availableResolutions);

            // See if the user selected a resolution
            if (resolution != null)
            {
                // Now get the preset string from the resolution chosen
                var preset = (from c in consideredResolutions
                              where c.Value.Width == resolution.Width &&
                              c.Value.Height == resolution.Height
                              select c.Key).FirstOrDefault();

                // If we found a matching preset, let's set it on the session
                if (!string.IsNullOrEmpty(preset))
                {
                    _session.SessionPreset = preset;
                }
            }

            var input = AVCaptureDeviceInput.FromDevice(captureDevice);

            if (input == null)
            {
                Console.WriteLine("No input - this won't work on the simulator, try a physical device");
                return(false);
            }
            else
            {
                _session.AddInput(input);
            }


            var startedAvPreviewLayerAlloc = PerformanceCounter.Start();

            _previewLayer = new AVCaptureVideoPreviewLayer(_session);

            PerformanceCounter.Stop(startedAvPreviewLayerAlloc, "Alloc AVCaptureVideoPreviewLayer took {0} ms.");

            var perf2 = PerformanceCounter.Start();

#if __UNIFIED__
            _previewLayer.VideoGravity = AVLayerVideoGravity.ResizeAspectFill;
#else
            previewLayer.LayerVideoGravity = AVLayerVideoGravity.ResizeAspectFill;
#endif
            _previewLayer.Frame    = new CGRect(0, 0, this.Frame.Width, this.Frame.Height);
            _previewLayer.Position = new CGPoint(this.Layer.Bounds.Width / 2, (this.Layer.Bounds.Height / 2));

            _layerView = new UIView(new CGRect(0, 0, this.Frame.Width, this.Frame.Height))
            {
                AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
            };
            _layerView.Layer.AddSublayer(_previewLayer);

            this.AddSubview(_layerView);

            ResizePreview(UIApplication.SharedApplication.StatusBarOrientation);


            PerformanceCounter.Stop(perf2, "PERF: Setting up layers took {0} ms");

            var perf3 = PerformanceCounter.Start();

            _session.StartRunning();

            PerformanceCounter.Stop(perf3, "PERF: session.StartRunning() took {0} ms");

            var perf4 = PerformanceCounter.Start();

            var videoSettings = NSDictionary.FromObjectAndKey(new NSNumber((int)CVPixelFormatType.CV32BGRA),
                                                              CVPixelBuffer.PixelFormatTypeKey);


            // create a VideoDataOutput and add it to the sesion
            _output = new AVCaptureVideoDataOutput
            {
                WeakVideoSettings = videoSettings
            };

            // configure the output
            _queue          = new DispatchQueue("CamerPreviewView"); // (Guid.NewGuid().ToString());
            _outputRecorder = new DefaultOutputRecorder(_resultCallback);
            _output.AlwaysDiscardsLateVideoFrames = true;
            _output.SetSampleBufferDelegateQueue(_outputRecorder, _queue);

            PerformanceCounter.Stop(perf4, "PERF: SetupCamera Finished.  Took {0} ms.");

            _session.AddOutput(_output);
            //session.StartRunning ();


            var perf5 = PerformanceCounter.Start();

            if (captureDevice.LockForConfiguration(out var err))
            {
                if (captureDevice.IsFocusModeSupported(AVCaptureFocusMode.ContinuousAutoFocus))
                {
                    captureDevice.FocusMode = AVCaptureFocusMode.ContinuousAutoFocus;
                }
                else if (captureDevice.IsFocusModeSupported(AVCaptureFocusMode.AutoFocus))
                {
                    captureDevice.FocusMode = AVCaptureFocusMode.AutoFocus;
                }

                if (captureDevice.IsExposureModeSupported(AVCaptureExposureMode.ContinuousAutoExposure))
                {
                    captureDevice.ExposureMode = AVCaptureExposureMode.ContinuousAutoExposure;
                }
                else if (captureDevice.IsExposureModeSupported(AVCaptureExposureMode.AutoExpose))
                {
                    captureDevice.ExposureMode = AVCaptureExposureMode.AutoExpose;
                }

                if (captureDevice.IsWhiteBalanceModeSupported(AVCaptureWhiteBalanceMode.ContinuousAutoWhiteBalance))
                {
                    captureDevice.WhiteBalanceMode = AVCaptureWhiteBalanceMode.ContinuousAutoWhiteBalance;
                }
                else if (captureDevice.IsWhiteBalanceModeSupported(AVCaptureWhiteBalanceMode.AutoWhiteBalance))
                {
                    captureDevice.WhiteBalanceMode = AVCaptureWhiteBalanceMode.AutoWhiteBalance;
                }

                if (UIDevice.CurrentDevice.CheckSystemVersion(7, 0) && captureDevice.AutoFocusRangeRestrictionSupported)
                {
                    captureDevice.AutoFocusRangeRestriction = AVCaptureAutoFocusRangeRestriction.Near;
                }

                if (captureDevice.FocusPointOfInterestSupported)
                {
                    captureDevice.FocusPointOfInterest = new PointF(0.5f, 0.5f);
                }

                if (captureDevice.ExposurePointOfInterestSupported)
                {
                    captureDevice.ExposurePointOfInterest = new PointF(0.5f, 0.5f);
                }

                captureDevice.UnlockForConfiguration();
            }
            else
            {
                Logger.Log("Failed to Lock for Config: " + err.Description);
            }

            PerformanceCounter.Stop(perf5, "PERF: Setup Focus in {0} ms.");

            return(true);
        }
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			this.View.BackgroundColor = UIColor.White;

			NSError error;

			// Setup detector options.
			var options = new CIDetectorOptions {
				Accuracy = FaceDetectorAccuracy.High,
				// Can give a hint here about the rects to detect. 1.4 would be for A4 sheets of paper for instance.
				AspectRatio = 1.41f,
				
			};

			// Create a rectangle detector. Note that you can also create QR detector or a face detector.
			// Most of this code will also work with other detectors (like streaming to a preview layer and grabbing images).
			this.detector = CIDetector.CreateRectangleDetector (context: null, detectorOptions: options);

			// Create the session. The AVCaptureSession is the managing instance of the whole video handling.
			var captureSession = new AVCaptureSession ()
			{ 
				// Defines what quality we want to use for the images we grab. Photo gives highest resolutions.
				SessionPreset = AVCaptureSession.PresetPhoto
			};

			// Find a suitable AVCaptureDevice for video input.
			var device = AVCaptureDevice.DefaultDeviceWithMediaType(AVMediaType.Video);
			if (device == null)
			{
				// This will not work on the iOS Simulator - there is no camera. :-)
				throw new InvalidProgramException ("Failed to get AVCaptureDevice for video input!");
			}

			// Create a device input with the device and add it to the session.
			var videoInput = AVCaptureDeviceInput.FromDevice (device, out error);
			if (videoInput == null)
			{
				throw new InvalidProgramException ("Failed to get AVCaptureDeviceInput from AVCaptureDevice!");
			}

			// Let session read from the input, this is our source.
			captureSession.AddInput (videoInput);

			// Create output for the video stream. This is the destination.
			var videoOutput = new AVCaptureVideoDataOutput () {
				AlwaysDiscardsLateVideoFrames = true
			};

			// Define the video format we want to use. Note that Xamarin exposes the CompressedVideoSetting and UncompressedVideoSetting 
			// properties on AVCaptureVideoDataOutput un Unified API, but I could not get these to work. The VideoSettings property is deprecated,
			// so I use the WeakVideoSettings instead which takes an NSDictionary as input.
			this.videoSettingsDict = new NSMutableDictionary ();
			this.videoSettingsDict.Add (CVPixelBuffer.PixelFormatTypeKey, NSNumber.FromUInt32((uint)CVPixelFormatType.CV32BGRA));
			videoOutput.WeakVideoSettings = this.videoSettingsDict;

			// Create a delegate to report back to us when an image has been captured.
			// We want to grab the camera stream and feed it through a AVCaptureVideoDataOutputSampleBufferDelegate
			// which allows us to get notified if a new image is availeble. An implementation of that delegate is VideoFrameSampleDelegate in this project.
			this.sampleBufferDelegate = new VideoFrameSamplerDelegate ();

			// Processing happens via Grand Central Dispatch (GCD), so we need to provide a queue.
			// This is pretty much like a system managed thread (see: http://zeroheroblog.com/ios/concurrency-in-ios-grand-central-dispatch-gcd-dispatch-queues).
			this.sessionQueue =  new DispatchQueue ("AVSessionQueue");

			// Assign the queue and the delegate to the output. Now all output will go through the delegate.
			videoOutput.SetSampleBufferDelegate(this.sampleBufferDelegate, this.sessionQueue);

			// Add output to session.
			captureSession.AddOutput(videoOutput);

			// We also want to visualize the input stream. The raw stream can be fed into an AVCaptureVideoPreviewLayer, which is a subclass of CALayer.
			// A CALayer can be added to a UIView. We add that layer to the controller's main view.
			var layer = this.View.Layer;
			this.videoLayer = AVCaptureVideoPreviewLayer.FromSession (captureSession);
			this.videoLayer.Frame = layer.Bounds;
			layer.AddSublayer (this.videoLayer);

			// All setup! Start capturing!
			captureSession.StartRunning ();

			// This is just for information and allows you to get valid values for the detection framerate. 
			Console.WriteLine ("Available capture framerates:");
			var rateRanges = device.ActiveFormat.VideoSupportedFrameRateRanges;
			foreach (var r in rateRanges)
			{
				Console.WriteLine (r.MinFrameRate + "; " + r.MaxFrameRate + "; " + r.MinFrameDuration + "; " + r.MaxFrameDuration);
			}

			// Configure framerate. Kind of weird way of doing it but the only one that works.
			device.LockForConfiguration (out error);
			// CMTime constructor means: 1 = one second, DETECTION_FPS = how many samples per unit, which is 1 second in this case.
			device.ActiveVideoMinFrameDuration = new CMTime(1, DETECTION_FPS);
			device.ActiveVideoMaxFrameDuration = new CMTime(1, DETECTION_FPS);
			device.UnlockForConfiguration ();

			// Put a small image view at the top left that shows the live image with the detected rectangle(s).
			this.imageViewOverlay = new UIImageView
			{ 
				ContentMode = UIViewContentMode.ScaleAspectFit,
				BackgroundColor = UIColor.Gray
			};
			this.imageViewOverlay.Layer.BorderColor = UIColor.Red.CGColor;
			this.imageViewOverlay.Layer.BorderWidth = 3f;
			this.Add (this.imageViewOverlay);

			// Put another image view top right that shows the image with perspective correction.
			this.imageViewPerspective = new UIImageView
			{ 
				ContentMode = UIViewContentMode.ScaleAspectFit,
				BackgroundColor = UIColor.Gray
			};
			this.imageViewPerspective.Layer.BorderColor = UIColor.Red.CGColor;
			this.imageViewPerspective.Layer.BorderWidth = 3f;
			this.Add (this.imageViewPerspective);

			// Add some lables for information.
			this.mainWindowLbl = new UILabel
			{
				Text = "Live stream from camera. Point camera to a rectangular object.",
				TextAlignment = UITextAlignment.Center
			};
			this.Add (this.mainWindowLbl);

			this.detectionWindowLbl = new UILabel
			{
				Text = "Detected rectangle overlay",
				TextAlignment = UITextAlignment.Center
			};
			this.Add (this.detectionWindowLbl);

			this.perspectiveWindowLbl = new UILabel
			{
				Text = "Perspective corrected",
				TextAlignment = UITextAlignment.Center
			};
			this.Add (this.perspectiveWindowLbl);
		}
Esempio n. 16
0
        public UiCameraPreview(CameraPreview camera)
        {
            this._CameraOptions = camera.Camera;
            this._IsPreviewing  = camera.IsPreviewing;
            this._Camera        = camera;

            this.CaptureSession = new AVCaptureSession();
            this._PreviewLayer  = new AVCaptureVideoPreviewLayer(this.CaptureSession)
            {
                Frame        = this.Bounds,
                VideoGravity = AVLayerVideoGravity.ResizeAspectFill
            };
            this.Layer.AddSublayer(this._PreviewLayer);

            this.Initialize();

            MessagingCenter.Subscribe <LifeCyclePayload>(this, "", (p) =>
            {
                switch (p.Status)
                {
                case LifeCycle.OnSleep:
                    //Sleep状態になるときにリソース解放
                    this.Release();
                    break;

                case LifeCycle.OnResume:
                    //Resume状態になるときに初期化
                    this.Initialize();
                    break;
                }
            });

            // Adjust size and orientation of preview image
            this._Notification = UIApplication.Notifications.ObserveDidChangeStatusBarOrientation((sender, args) =>
            {
                switch (UIApplication.SharedApplication.StatusBarOrientation)
                {
                case UIInterfaceOrientation.Portrait:
                    this._PreviewLayer.Connection.VideoOrientation = AVCaptureVideoOrientation.Portrait;
                    break;

                case UIInterfaceOrientation.PortraitUpsideDown:
                    this._PreviewLayer.Connection.VideoOrientation = AVCaptureVideoOrientation.PortraitUpsideDown;
                    break;

                case UIInterfaceOrientation.LandscapeLeft:
                    this._PreviewLayer.Connection.VideoOrientation = AVCaptureVideoOrientation.LandscapeLeft;
                    break;

                case UIInterfaceOrientation.LandscapeRight:
                    this._PreviewLayer.Connection.VideoOrientation = AVCaptureVideoOrientation.LandscapeRight;
                    break;

                default:
                    break;
                }
            });
            this._Camera.SizeChanged += (sender, args) =>
            {
                var rect = this._Camera.Bounds;
                this._PreviewLayer.Frame = new CGRect(new CGPoint(rect.X, rect.Y), new CGSize(rect.Width, rect.Height));
            };
        }
        bool SetupCaptureSession()
        {
            var availableResolutions = new List <CameraResolution>();

            var consideredResolutions = new Dictionary <NSString, CameraResolution> {
                { AVCaptureSession.Preset352x288, new CameraResolution   {
                      Width = 352, Height = 288
                  } },
                { AVCaptureSession.PresetMedium, new CameraResolution    {
                      Width = 480, Height = 360
                  } },                                                                                                     //480x360
                { AVCaptureSession.Preset640x480, new CameraResolution   {
                      Width = 640, Height = 480
                  } },
                { AVCaptureSession.Preset1280x720, new CameraResolution  {
                      Width = 1280, Height = 720
                  } },
                { AVCaptureSession.Preset1920x1080, new CameraResolution {
                      Width = 1920, Height = 1080
                  } }
            };

            // configure the capture session for low resolution, change this if your code
            // can cope with more data or volume
            session = new AVCaptureSession()
            {
                SessionPreset = AVCaptureSession.Preset640x480
            };

            // create a device input and attach it to the session
            //			var captureDevice = AVCaptureDevice.DefaultDeviceWithMediaType (AVMediaType.Video);
            AVCaptureDevice captureDevice = null;
            var             devices       = AVCaptureDevice.DevicesWithMediaType(AVMediaType.Video);

            foreach (var device in devices)
            {
                captureDevice = device;
                if (ScanningOptions.UseFrontCameraIfAvailable.HasValue &&
                    ScanningOptions.UseFrontCameraIfAvailable.Value &&
                    device.Position == AVCaptureDevicePosition.Front)
                {
                    break;                     //Front camera successfully set
                }
                else if (device.Position == AVCaptureDevicePosition.Back && (!ScanningOptions.UseFrontCameraIfAvailable.HasValue || !ScanningOptions.UseFrontCameraIfAvailable.Value))
                {
                    break;                     //Back camera succesfully set
                }
            }
            if (captureDevice == null)
            {
                Console.WriteLine("No captureDevice - this won't work on the simulator, try a physical device");
                if (overlayView != null)
                {
                    AddSubview(overlayView);
                    BringSubviewToFront(overlayView);
                }
                return(false);
            }

            CameraResolution resolution = null;

            // Find resolution
            // Go through the resolutions we can even consider
            foreach (var cr in consideredResolutions)
            {
                // Now check to make sure our selected device supports the resolution
                // so we can add it to the list to pick from
                if (captureDevice.SupportsAVCaptureSessionPreset(cr.Key))
                {
                    availableResolutions.Add(cr.Value);
                }
            }

            resolution = ScanningOptions.GetResolution(availableResolutions);

            // See if the user selected a resolution
            if (resolution != null)
            {
                // Now get the preset string from the resolution chosen
                var preset = (from c in consideredResolutions
                              where c.Value.Width == resolution.Width &&
                              c.Value.Height == resolution.Height
                              select c.Key).FirstOrDefault();

                // If we found a matching preset, let's set it on the session
                if (!string.IsNullOrEmpty(preset))
                {
                    session.SessionPreset = preset;
                }
            }

            var input = AVCaptureDeviceInput.FromDevice(captureDevice);

            if (input == null)
            {
                Console.WriteLine("No input - this won't work on the simulator, try a physical device");
                if (overlayView != null)
                {
                    AddSubview(overlayView);
                    BringSubviewToFront(overlayView);
                }
                return(false);
            }
            else
            {
                session.AddInput(input);
            }


            foundResult = false;
            //Detect barcodes with built in avcapture stuff
            var metadataOutput = new AVCaptureMetadataOutput();

            captureDelegate = new CaptureDelegate(metaDataObjects =>
            {
                if (!analyzing)
                {
                    return;
                }

                var msSinceLastPreview = (DateTime.UtcNow - lastAnalysis).TotalMilliseconds;

                if (msSinceLastPreview < ScanningOptions.DelayBetweenAnalyzingFrames ||
                    (wasScanned && msSinceLastPreview < ScanningOptions.DelayBetweenContinuousScans) ||
                    working)
                {
                    return;
                }

                try
                {
                    working      = true;
                    wasScanned   = false;
                    lastAnalysis = DateTime.UtcNow;

                    var mdo = metaDataObjects.FirstOrDefault();

                    if (!(mdo is AVMetadataMachineReadableCodeObject readableObj))
                    {
                        return;
                    }

                    if (readableObj.Type == AVMetadataObjectType.CatBody ||
                        readableObj.Type == AVMetadataObjectType.DogBody ||
                        readableObj.Type == AVMetadataObjectType.Face ||
                        readableObj.Type == AVMetadataObjectType.HumanBody ||
                        readableObj.Type == AVMetadataObjectType.SalientObject)
                    {
                        return;
                    }

                    wasScanned = true;

                    var zxingFormat = ZXingBarcodeFormatFromAVCaptureBarcodeFormat(readableObj.Type.ToString());

                    var rs = new ZXing.Result(readableObj.StringValue, null, null, zxingFormat);

                    resultCallback(rs);
                }
                finally
                {
                    working = false;
                }
            });

            metadataOutput.SetDelegate(captureDelegate, DispatchQueue.MainQueue);
            session.AddOutput(metadataOutput);

            //Setup barcode formats
            if (ScanningOptions?.PossibleFormats?.Any() ?? false)
            {
                var formats = AVMetadataObjectType.None;

                foreach (var f in ScanningOptions.PossibleFormats)
                {
                    formats |= AVCaptureBarcodeFormatFromZXingBarcodeFormat(f);
                }

                formats &= ~AVMetadataObjectType.None;

                metadataOutput.MetadataObjectTypes = formats;
            }
            else
            {
                var availableMetaObjTypes = metadataOutput.AvailableMetadataObjectTypes;


                metadataOutput.MetadataObjectTypes = metadataOutput.AvailableMetadataObjectTypes;
            }

            previewLayer = new AVCaptureVideoPreviewLayer(session);
            previewLayer.VideoGravity = AVLayerVideoGravity.ResizeAspectFill;
            previewLayer.Frame        = new CGRect(0, 0, this.Frame.Width, this.Frame.Height);
            previewLayer.Position     = new CGPoint(this.Layer.Bounds.Width / 2, (this.Layer.Bounds.Height / 2));

            layerView = new UIView(new CGRect(0, 0, this.Frame.Width, this.Frame.Height));
            layerView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
            layerView.Layer.AddSublayer(previewLayer);

            AddSubview(layerView);

            ResizePreview(UIApplication.SharedApplication.StatusBarOrientation);

            if (overlayView != null)
            {
                AddSubview(overlayView);
                BringSubviewToFront(overlayView);
            }

            session.StartRunning();

            if (captureDevice.IsFocusModeSupported(AVCaptureFocusMode.ContinuousAutoFocus))
            {
                NSError err = null;
                if (captureDevice.LockForConfiguration(out err))
                {
                    if (captureDevice.IsFocusModeSupported(AVCaptureFocusMode.ContinuousAutoFocus))
                    {
                        captureDevice.FocusMode = AVCaptureFocusMode.ContinuousAutoFocus;
                    }
                    else if (captureDevice.IsFocusModeSupported(AVCaptureFocusMode.AutoFocus))
                    {
                        captureDevice.FocusMode = AVCaptureFocusMode.AutoFocus;
                    }

                    if (captureDevice.IsExposureModeSupported(AVCaptureExposureMode.ContinuousAutoExposure))
                    {
                        captureDevice.ExposureMode = AVCaptureExposureMode.ContinuousAutoExposure;
                    }
                    else if (captureDevice.IsExposureModeSupported(AVCaptureExposureMode.AutoExpose))
                    {
                        captureDevice.ExposureMode = AVCaptureExposureMode.AutoExpose;
                    }

                    if (captureDevice.IsWhiteBalanceModeSupported(AVCaptureWhiteBalanceMode.ContinuousAutoWhiteBalance))
                    {
                        captureDevice.WhiteBalanceMode = AVCaptureWhiteBalanceMode.ContinuousAutoWhiteBalance;
                    }
                    else if (captureDevice.IsWhiteBalanceModeSupported(AVCaptureWhiteBalanceMode.AutoWhiteBalance))
                    {
                        captureDevice.WhiteBalanceMode = AVCaptureWhiteBalanceMode.AutoWhiteBalance;
                    }

                    if (UIDevice.CurrentDevice.CheckSystemVersion(7, 0) && captureDevice.AutoFocusRangeRestrictionSupported)
                    {
                        captureDevice.AutoFocusRangeRestriction = AVCaptureAutoFocusRangeRestriction.Near;
                    }

                    if (captureDevice.FocusPointOfInterestSupported)
                    {
                        captureDevice.FocusPointOfInterest = new CGPoint(0.5f, 0.5f);
                    }

                    if (captureDevice.ExposurePointOfInterestSupported)
                    {
                        captureDevice.ExposurePointOfInterest = new CGPoint(0.5f, 0.5f);
                    }

                    captureDevice.UnlockForConfiguration();
                }
                else
                {
                    Console.WriteLine("Failed to Lock for Config: " + err.Description);
                }
            }

            return(true);
        }
Esempio n. 18
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad ();
            weAreRecording = false;
            lblError.Hidden = true;

            btnStartRecording.SetTitle("Start Recording", UIControlState.Normal);

            //Set up session
            session = new AVCaptureSession ();

            //Set up inputs and add them to the session
            //this will only work if using a physical device!

            Console.WriteLine ("getting device inputs");
            try{
                //add video capture device
                device = AVCaptureDevice.DefaultDeviceWithMediaType (AVMediaType.Video);
                input = AVCaptureDeviceInput.FromDevice (device);
                session.AddInput (input);

                //add audio capture device
                audioDevice = AVCaptureDevice.DefaultDeviceWithMediaType(AVMediaType.Audio);
                audioInput = AVCaptureDeviceInput.FromDevice(audioDevice);
                session.AddInput(audioInput);

            }
            catch(Exception ex){
                //show the label error.  This will always show when running in simulator instead of physical device.
                lblError.Hidden = false;
                return;
            }

            //Set up preview layer (shows what the input device sees)
            Console.WriteLine ("setting up preview layer");
            previewlayer = new AVCaptureVideoPreviewLayer (session);
            previewlayer.Frame = this.View.Bounds;

            //this code makes UI controls sit on top of the preview layer!  Allows you to just place the controls in interface builder
            UIView cameraView = new UIView ();
            cameraView = new UIView ();
            cameraView.Layer.AddSublayer (previewlayer);
            this.View.AddSubview (cameraView);
            this.View.SendSubviewToBack (cameraView);

            Console.WriteLine ("Configuring output");
            output = new AVCaptureMovieFileOutput ();

            long totalSeconds = 10000;
            Int32 preferredTimeScale = 30;
            CMTime maxDuration = new CMTime (totalSeconds, preferredTimeScale);
            output.MinFreeDiskSpaceLimit = 1024 * 1024;
            output.MaxRecordedDuration = maxDuration;

            if (session.CanAddOutput (output)) {
                session.AddOutput (output);
            }

            session.SessionPreset = AVCaptureSession.PresetMedium;

            Console.WriteLine ("About to start running session");

            session.StartRunning ();

            //toggle recording button was pushed.
            btnStartRecording.TouchUpInside += startStopPushed;

            //Console.ReadLine ();
        }
Esempio n. 19
0
        public override async void ViewDidLoad()
        {
            base.ViewDidLoad();

            NavigationController.SetNavigationBarHidden(true, false);

            CGRect ScreenBounds = UIScreen.MainScreen.Bounds;

            View.Frame   = ScreenBounds;
            View.Bounds  = ScreenBounds;
            previewLayer = new AVCaptureVideoPreviewLayer
            {
                BackgroundColor = UIColor.LightGray.CGColor,
                MasksToBounds   = true,
                VideoGravity    = AVLayerVideoGravity.ResizeAspectFill,
                Frame           = this.View.Bounds
            };

            View.Layer.AddSublayer(previewLayer);

            //PreivewImage
            PreviewImage = new UIImageView()
            {
                Frame = new RectangleF(0, 0,
                                       (float)ScreenBounds.Width / 4,
                                       (float)View.Frame.Height / 4),
                Alpha = 0.75f,
                UserInteractionEnabled = true
            };

            //TakePhoto button
            TakePhotoButton = new UIButton(UIButtonType.System)
            {
                Frame = new RectangleF((float)ScreenBounds.Width - 70f,
                                       ((float)View.Frame.Height / 2) - 30f,
                                       60f, 60f),
                BackgroundColor = UIColor.Black.ColorWithAlpha(0.25f),
            };
            TakePhotoButton.TintColor = UIColor.White;
            TakePhotoButton.SetImage(UIImage.FromFile("Images/Camera.png"), UIControlState.Normal);
            TakePhotoButton.Layer.CornerRadius = 30f;
            TakePhotoButton.SetCommand(this.ViewModel.DescribeImageCommand);

            //SwapCamera button
            SwapCameraButton = new UIButton(UIButtonType.System)
            {
                Frame = new RectangleF((float)ScreenBounds.Width / 2 - 30f,
                                       10f,
                                       60f, 60f),
                BackgroundColor = UIColor.Black.ColorWithAlpha(0.25f),
            };
            SwapCameraButton.TintColor = UIColor.White;
            SwapCameraButton.SetImage(UIImage.FromFile("Images/SwitchCamera.png"), UIControlState.Normal);
            SwapCameraButton.Layer.CornerRadius = 30f;
            SwapCameraButton.SetCommand(this.ViewModel.SwapCameraCommand);

            //Settings button
            SettingsButton = new UIButton(UIButtonType.System)
            {
                Frame = new RectangleF((float)ScreenBounds.Width - 70f,
                                       10f,
                                       60f, 60f),
                BackgroundColor = UIColor.Black.ColorWithAlpha(0.25f),
            };
            SettingsButton.TintColor = UIColor.White;
            SettingsButton.SetImage(UIImage.FromFile("Images/Settings.png"), UIControlState.Normal);
            SettingsButton.Layer.CornerRadius = 30f;
            SettingsButton.SetCommand(this.ViewModel.GotoSettingsCommand);

            //Message Label
            MessageText = new UITextView
            {
                Frame                  = new RectangleF(40f, (float)View.Frame.Height - 180f, (float)UIScreen.MainScreen.Bounds.Width - 80f, 180f),
                TextAlignment          = UITextAlignment.Center,
                TextColor              = UIColor.White,
                Text                   = Strings.AppName.Localize(),
                UserInteractionEnabled = false,
                BackgroundColor        = UIColor.FromRGBA(255, 255, 255, 0)
            };
            MessageText.Font = MessageText.Font.WithSize(24.0f);

            View.AddSubview(TakePhotoButton);
            View.AddSubview(SwapCameraButton);
            View.AddSubview(SettingsButton);
            View.AddSubview(PreviewImage);

            View.AddSubview(MessageText);

            // Tap
            PreviewImage.AddGestureRecognizer(new UITapGestureRecognizer(tap =>
            {
                if (PreviewImageCollapsed)
                {
                    PreviewImage.Frame = new RectangleF(0, 0,
                                                        (float)ScreenBounds.Width,
                                                        (float)View.Frame.Height);
                    PreviewImage.Alpha = 1f;
                }
                else
                {
                    PreviewImage.Frame = new RectangleF(0, 0,
                                                        (float)ScreenBounds.Width / 4,
                                                        (float)View.Frame.Height / 4);
                    PreviewImage.Alpha = 0.75f;
                }
                PreviewImageCollapsed = !PreviewImageCollapsed;
            }));

            this.RegisterMessages();
            this.bindings = new List <Binding>()
            {
                this.SetBinding(() => ViewModel.StatusMessage, () => MessageText.Text, BindingMode.OneWay)
            };

            await ViewModel.InitializeStreamingAsync();

            await ViewModel.CheckShowConsentAsync();
        }
        bool SetupCaptureSession()
        {
            session = new AVCaptureSession();

            AVCaptureDevice device = AVCaptureDevice.DefaultDeviceWithMediaType(AVMediaType.Video);

            if (device == null) {
                Console.WriteLine("No video camera (in simulator?)");
                return false; // simulator?
            }

            NSError error = null;

            AVCaptureDeviceInput input = AVCaptureDeviceInput.FromDevice(device, out error);

            if (input == null)
                Console.WriteLine("Error: " + error);
            else
                session.AddInput(input);

            AVCaptureMetadataOutput output = new AVCaptureMetadataOutput();

            var dg = new CaptureDelegate(this);
            output.SetDelegate(dg,	MonoTouch.CoreFoundation.DispatchQueue.MainQueue);
            session.AddOutput(output);

            // This could be any list of supported barcode types
            output.MetadataObjectTypes = new NSString[] {AVMetadataObject.TypeQRCode, AVMetadataObject.TypeAztecCode};
            // OR you could just accept "all" with the following line;
            //			output.MetadataObjectTypes = output.AvailableMetadataObjectTypes;  // empty
            // DEBUG: use this if you're curious about the available types
            //			foreach (var t in output.AvailableMetadataObjectTypes)
            //				Console.WriteLine(t);

            AVCaptureVideoPreviewLayer previewLayer = new AVCaptureVideoPreviewLayer(session);
            //previewLayer.Frame = new RectangleF(0,0, View.Frame.Size.Width, View.Frame.Size.Height);
            previewLayer.Frame = new RectangleF(0, 0, 320, 290);
            previewLayer.VideoGravity = AVLayerVideoGravity.ResizeAspectFill.ToString();
            View.Layer.AddSublayer (previewLayer);

            session.StartRunning();

            Console.WriteLine("StartRunning");
            return true;
        }
Esempio n. 21
0
        bool SetupCaptureSession()
        {
            // configure the capture session for low resolution, change this if your code
            // can cope with more data or volume
            session = new AVCaptureSession()
            {
                SessionPreset = AVCaptureSession.Preset640x480
            };

            // create a device input and attach it to the session
//			var captureDevice = AVCaptureDevice.DefaultDeviceWithMediaType (AVMediaType.Video);
            AVCaptureDevice captureDevice = null;
            var             devices       = AVCaptureDevice.DevicesWithMediaType(AVMediaType.Video);

            foreach (var device in devices)
            {
                captureDevice = device;
                if (options.UseFrontCameraIfAvailable.HasValue &&
                    options.UseFrontCameraIfAvailable.Value &&
                    device.Position == AVCaptureDevicePosition.Front)
                {
                    break;                     //Front camera successfully set
                }
                else if (device.Position == AVCaptureDevicePosition.Back && (!options.UseFrontCameraIfAvailable.HasValue || !options.UseFrontCameraIfAvailable.Value))
                {
                    break;                     //Back camera succesfully set
                }
            }
            if (captureDevice == null)
            {
                Console.WriteLine("No captureDevice - this won't work on the simulator, try a physical device");
                if (overlayView != null)
                {
                    this.AddSubview(overlayView);
                    this.BringSubviewToFront(overlayView);
                }
                return(false);
            }

            var input = AVCaptureDeviceInput.FromDevice(captureDevice);

            if (input == null)
            {
                Console.WriteLine("No input - this won't work on the simulator, try a physical device");
                if (overlayView != null)
                {
                    this.AddSubview(overlayView);
                    this.BringSubviewToFront(overlayView);
                }
                return(false);
            }
            else
            {
                session.AddInput(input);
            }


            previewLayer = new AVCaptureVideoPreviewLayer(session);

            //Framerate set here (15 fps)
            if (previewLayer.RespondsToSelector(new Selector("connection")))
            {
                previewLayer.Connection.VideoMinFrameDuration = new CMTime(1, 10);
            }

            previewLayer.LayerVideoGravity = AVLayerVideoGravity.ResizeAspectFill;
            previewLayer.Frame             = new RectangleF(0, 0, this.Frame.Width, this.Frame.Height);
            previewLayer.Position          = new PointF(this.Layer.Bounds.Width / 2, (this.Layer.Bounds.Height / 2));

            layerView = new UIView(new RectangleF(0, 0, this.Frame.Width, this.Frame.Height));
            layerView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
            layerView.Layer.AddSublayer(previewLayer);

            this.AddSubview(layerView);

            ResizePreview(UIApplication.SharedApplication.StatusBarOrientation);

            if (overlayView != null)
            {
                this.AddSubview(overlayView);
                this.BringSubviewToFront(overlayView);

                //overlayView.LayoutSubviews ();
            }

            session.StartRunning();

            Console.WriteLine("RUNNING!!!");

            // create a VideoDataOutput and add it to the sesion
            output = new AVCaptureVideoDataOutput()
            {
                //videoSettings
                VideoSettings = new AVVideoSettings(CVPixelFormatType.CV32BGRA),
            };

            // configure the output
            queue = new MonoTouch.CoreFoundation.DispatchQueue("ZxingScannerView");             // (Guid.NewGuid().ToString());

            var barcodeReader = new BarcodeReader(null, (img) =>
            {
                var src = new RGBLuminanceSource(img);                 //, bmp.Width, bmp.Height);

                //Don't try and rotate properly if we're autorotating anyway
                if (ScanningOptions.AutoRotate.HasValue && ScanningOptions.AutoRotate.Value)
                {
                    return(src);
                }

                var tmpInterfaceOrientation = UIInterfaceOrientation.Portrait;
                InvokeOnMainThread(() => tmpInterfaceOrientation = UIApplication.SharedApplication.StatusBarOrientation);

                switch (tmpInterfaceOrientation)
                {
                case UIInterfaceOrientation.Portrait:
                    return(src.rotateCounterClockwise().rotateCounterClockwise().rotateCounterClockwise());

                case UIInterfaceOrientation.PortraitUpsideDown:
                    return(src.rotateCounterClockwise().rotateCounterClockwise().rotateCounterClockwise());

                case UIInterfaceOrientation.LandscapeLeft:
                    return(src);

                case UIInterfaceOrientation.LandscapeRight:
                    return(src);
                }

                return(src);
            }, null, null);             //(p, w, h, f) => new RGBLuminanceSource(p, w, h, RGBLuminanceSource.BitmapFormat.Unknown));

            if (ScanningOptions.TryHarder.HasValue)
            {
                Console.WriteLine("TRY_HARDER: " + ScanningOptions.TryHarder.Value);
                barcodeReader.Options.TryHarder = ScanningOptions.TryHarder.Value;
            }
            if (ScanningOptions.PureBarcode.HasValue)
            {
                barcodeReader.Options.PureBarcode = ScanningOptions.PureBarcode.Value;
            }
            if (ScanningOptions.AutoRotate.HasValue)
            {
                Console.WriteLine("AUTO_ROTATE: " + ScanningOptions.AutoRotate.Value);
                barcodeReader.AutoRotate = ScanningOptions.AutoRotate.Value;
            }
            if (!string.IsNullOrEmpty(ScanningOptions.CharacterSet))
            {
                barcodeReader.Options.CharacterSet = ScanningOptions.CharacterSet;
            }
            if (ScanningOptions.TryInverted.HasValue)
            {
                barcodeReader.TryInverted = ScanningOptions.TryInverted.Value;
            }

            if (ScanningOptions.PossibleFormats != null && ScanningOptions.PossibleFormats.Count > 0)
            {
                barcodeReader.Options.PossibleFormats = new List <BarcodeFormat>();

                foreach (var pf in ScanningOptions.PossibleFormats)
                {
                    barcodeReader.Options.PossibleFormats.Add(pf);
                }
            }

            outputRecorder = new OutputRecorder(ScanningOptions, img =>
            {
                if (!IsAnalyzing)
                {
                    return;
                }

                try
                {
                    var started = DateTime.Now;
                    var rs      = barcodeReader.Decode(img);
                    var total   = DateTime.Now - started;

                    Console.WriteLine("Decode Time: " + total.TotalMilliseconds + " ms");

                    if (rs != null)
                    {
                        resultCallback(rs);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("DECODE FAILED: " + ex);
                }
            });

            output.AlwaysDiscardsLateVideoFrames = true;
            output.SetSampleBufferDelegate(outputRecorder, queue);


            Console.WriteLine("SetupCamera Finished");

            session.AddOutput(output);
            //session.StartRunning ();


            if (captureDevice.IsFocusModeSupported(AVCaptureFocusMode.ModeContinuousAutoFocus))
            {
                NSError err = null;
                if (captureDevice.LockForConfiguration(out err))
                {
                    captureDevice.FocusMode = AVCaptureFocusMode.ModeContinuousAutoFocus;

                    if (captureDevice.FocusPointOfInterestSupported)
                    {
                        captureDevice.FocusPointOfInterest = new PointF(0.5f, 0.5f);
                    }

                    captureDevice.UnlockForConfiguration();
                }
                else
                {
                    Console.WriteLine("Failed to Lock for Config: " + err.Description);
                }
            }

            return(true);
        }
Esempio n. 22
0
		bool SetupCaptureSession ()
		{
			// configure the capture session for low resolution, change this if your code
			// can cope with more data or volume
			session = new AVCaptureSession () {
				SessionPreset = AVCaptureSession.Preset640x480
			};
			
			// create a device input and attach it to the session
			var captureDevice = AVCaptureDevice.DefaultDeviceWithMediaType (AVMediaType.Video);
			if (captureDevice == null){
				Console.WriteLine ("No captureDevice - this won't work on the simulator, try a physical device");
				return false;
			}

			var input = AVCaptureDeviceInput.FromDevice (captureDevice);
			if (input == null){
				Console.WriteLine ("No input - this won't work on the simulator, try a physical device");
				return false;
			}
			else
				session.AddInput (input);


			previewLayer = new AVCaptureVideoPreviewLayer(session);

			//Framerate set here (15 fps)
			if (previewLayer.RespondsToSelector(new Selector("connection")))
				previewLayer.Connection.VideoMinFrameDuration = new CMTime(1, 10);

			previewLayer.LayerVideoGravity = AVLayerVideoGravity.ResizeAspectFill;
			previewLayer.Frame = this.Frame;
			previewLayer.Position = new PointF(this.Layer.Bounds.Width / 2, (this.Layer.Bounds.Height / 2));

			layerView = new UIView(this.Frame);
			layerView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
			layerView.Layer.AddSublayer(previewLayer);

			this.AddSubview(layerView);

			ResizePreview(UIApplication.SharedApplication.StatusBarOrientation);

			if (overlayView != null)
			{
				this.AddSubview (overlayView);
				this.BringSubviewToFront (overlayView);

				//overlayView.LayoutSubviews ();
			}

			session.StartRunning ();

			Console.WriteLine ("RUNNING!!!");

			// create a VideoDataOutput and add it to the sesion
			output = new AVCaptureVideoDataOutput () {
				//videoSettings
				VideoSettings = new AVVideoSettings (CVPixelFormatType.CV32BGRA),
			};

			// configure the output
			queue = new MonoTouch.CoreFoundation.DispatchQueue("ZxingScannerView"); // (Guid.NewGuid().ToString());

			var barcodeReader = new BarcodeReader(null, (img) => 	
			{
				var src = new RGBLuminanceSource(img); //, bmp.Width, bmp.Height);

				//Don't try and rotate properly if we're autorotating anyway
				if (options.AutoRotate.HasValue && options.AutoRotate.Value)
					return src;

				switch (UIDevice.CurrentDevice.Orientation)
				{
					case UIDeviceOrientation.Portrait:
						return src.rotateCounterClockwise().rotateCounterClockwise().rotateCounterClockwise();
					case UIDeviceOrientation.PortraitUpsideDown:
						return src.rotateCounterClockwise().rotateCounterClockwise().rotateCounterClockwise();
					case UIDeviceOrientation.LandscapeLeft:
						return src;
					case UIDeviceOrientation.LandscapeRight:
						return src;
				}

				return src;

			}, null, null); //(p, w, h, f) => new RGBLuminanceSource(p, w, h, RGBLuminanceSource.BitmapFormat.Unknown));

			if (this.options.TryHarder.HasValue)
			{
				Console.WriteLine("TRY_HARDER: " + this.options.TryHarder.Value);
				barcodeReader.Options.TryHarder = this.options.TryHarder.Value;
			}
			if (this.options.PureBarcode.HasValue)
				barcodeReader.Options.PureBarcode = this.options.PureBarcode.Value;
			if (this.options.AutoRotate.HasValue)
			{
				Console.WriteLine("AUTO_ROTATE: " + this.options.AutoRotate.Value);
				barcodeReader.AutoRotate = this.options.AutoRotate.Value;
			}
			if (!string.IsNullOrEmpty (this.options.CharacterSet))
				barcodeReader.Options.CharacterSet = this.options.CharacterSet;
			if (this.options.TryInverted.HasValue)
				barcodeReader.TryInverted = this.options.TryInverted.Value;

			if (this.options.PossibleFormats != null && this.options.PossibleFormats.Count > 0)
			{
				barcodeReader.Options.PossibleFormats = new List<BarcodeFormat>();
				
				foreach (var pf in this.options.PossibleFormats)
					barcodeReader.Options.PossibleFormats.Add(pf);
			}

			outputRecorder = new OutputRecorder (this.options, img => 
			{
				try
				{
					var started = DateTime.Now;
					var rs = barcodeReader.Decode(img);
					var total = DateTime.Now - started;

					Console.WriteLine("Decode Time: " + total.TotalMilliseconds + " ms");

					if (rs != null)
						resultCallback(rs);
				}
				catch (Exception ex)
				{
					Console.WriteLine("DECODE FAILED: " + ex);
				}
			});

			output.AlwaysDiscardsLateVideoFrames = true;
			output.SetSampleBufferDelegate (outputRecorder, queue);


			Console.WriteLine("SetupCamera Finished");

			session.AddOutput (output);
			//session.StartRunning ();


			if (captureDevice.IsFocusModeSupported(AVCaptureFocusMode.ModeContinuousAutoFocus))
			{
				NSError err = null;
				if (captureDevice.LockForConfiguration(out err))
				{
					captureDevice.FocusMode = AVCaptureFocusMode.ModeContinuousAutoFocus;

					if (captureDevice.FocusPointOfInterestSupported)
						captureDevice.FocusPointOfInterest = new PointF(0.5f, 0.5f);

					captureDevice.UnlockForConfiguration();
				}
				else
					Console.WriteLine("Failed to Lock for Config: " + err.Description);
			}

			return true;
		}
Esempio n. 23
0
        bool SetupCaptureSession()
        {
            var started = DateTime.UtcNow;

            var availableResolutions = new List <CameraResolution> ();

            var consideredResolutions = new Dictionary <NSString, CameraResolution> {
                { AVCaptureSession.Preset352x288, new CameraResolution   {
                      Width = 352, Height = 288
                  } },
                { AVCaptureSession.PresetMedium, new CameraResolution    {
                      Width = 480, Height = 360
                  } },                                                                                                          //480x360
                { AVCaptureSession.Preset640x480, new CameraResolution   {
                      Width = 640, Height = 480
                  } },
                { AVCaptureSession.Preset1280x720, new CameraResolution  {
                      Width = 1280, Height = 720
                  } },
                { AVCaptureSession.Preset1920x1080, new CameraResolution {
                      Width = 1920, Height = 1080
                  } }
            };

            // configure the capture session for low resolution, change this if your code
            // can cope with more data or volume
            session = new AVCaptureSession()
            {
                SessionPreset = AVCaptureSession.Preset640x480
            };

            // create a device input and attach it to the session
//			var captureDevice = AVCaptureDevice.DefaultDeviceWithMediaType (AVMediaType.Video);
            AVCaptureDevice captureDevice = null;
            var             devices       = AVCaptureDevice.DevicesWithMediaType(AVMediaType.Video);

            foreach (var device in devices)
            {
                captureDevice = device;
                if (ScanningOptions.UseFrontCameraIfAvailable.HasValue &&
                    ScanningOptions.UseFrontCameraIfAvailable.Value &&
                    device.Position == AVCaptureDevicePosition.Front)
                {
                    break;                     //Front camera successfully set
                }
                else if (device.Position == AVCaptureDevicePosition.Back && (!ScanningOptions.UseFrontCameraIfAvailable.HasValue || !ScanningOptions.UseFrontCameraIfAvailable.Value))
                {
                    break;                     //Back camera succesfully set
                }
            }
            if (captureDevice == null)
            {
                Console.WriteLine("No captureDevice - this won't work on the simulator, try a physical device");
                if (overlayView != null)
                {
                    this.AddSubview(overlayView);
                    this.BringSubviewToFront(overlayView);
                }
                return(false);
            }

            CameraResolution resolution = null;

            // Find resolution
            // Go through the resolutions we can even consider
            foreach (var cr in consideredResolutions)
            {
                // Now check to make sure our selected device supports the resolution
                // so we can add it to the list to pick from
                if (captureDevice.SupportsAVCaptureSessionPreset(cr.Key))
                {
                    availableResolutions.Add(cr.Value);
                }
            }

            resolution = ScanningOptions.GetResolution(availableResolutions);

            // See if the user selected a resolution
            if (resolution != null)
            {
                // Now get the preset string from the resolution chosen
                var preset = (from c in consideredResolutions
                              where c.Value.Width == resolution.Width &&
                              c.Value.Height == resolution.Height
                              select c.Key).FirstOrDefault();

                // If we found a matching preset, let's set it on the session
                if (!string.IsNullOrEmpty(preset))
                {
                    session.SessionPreset = preset;
                }
            }

            var input = AVCaptureDeviceInput.FromDevice(captureDevice);

            if (input == null)
            {
                Console.WriteLine("No input - this won't work on the simulator, try a physical device");
                if (overlayView != null)
                {
                    this.AddSubview(overlayView);
                    this.BringSubviewToFront(overlayView);
                }
                return(false);
            }
            else
            {
                session.AddInput(input);
            }


            var startedAVPreviewLayerAlloc = PerformanceCounter.Start();

            previewLayer = new AVCaptureVideoPreviewLayer(session);

            PerformanceCounter.Stop(startedAVPreviewLayerAlloc, "Alloc AVCaptureVideoPreviewLayer took {0} ms.");


            // //Framerate set here (15 fps)
            // if (UIDevice.CurrentDevice.CheckSystemVersion (7, 0))
            // {
            //  var perf1 = PerformanceCounter.Start ();

            //  NSError lockForConfigErr = null;

            //  captureDevice.LockForConfiguration (out lockForConfigErr);
            //  if (lockForConfigErr == null)
            //  {
            //      captureDevice.ActiveVideoMinFrameDuration = new CMTime (1, 10);
            //      captureDevice.UnlockForConfiguration ();
            //  }

            //  PerformanceCounter.Stop (perf1, "PERF: ActiveVideoMinFrameDuration Took {0} ms");
            // }
            //          else
            //              previewLayer.Connection.VideoMinFrameDuration = new CMTime(1, 10);


            var perf2 = PerformanceCounter.Start();

                        #if __UNIFIED__
            previewLayer.VideoGravity = AVLayerVideoGravity.ResizeAspectFill;
                        #else
            previewLayer.LayerVideoGravity = AVLayerVideoGravity.ResizeAspectFill;
                        #endif
            previewLayer.Frame    = new CGRect(0, 0, this.Frame.Width, this.Frame.Height);
            previewLayer.Position = new CGPoint(this.Layer.Bounds.Width / 2, (this.Layer.Bounds.Height / 2));

            layerView = new UIView(new CGRect(0, 0, this.Frame.Width, this.Frame.Height));
            layerView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
            layerView.Layer.AddSublayer(previewLayer);

            this.AddSubview(layerView);

            ResizePreview(UIApplication.SharedApplication.StatusBarOrientation);

            if (overlayView != null)
            {
                this.AddSubview(overlayView);
                this.BringSubviewToFront(overlayView);

                //overlayView.LayoutSubviews ();
            }

            PerformanceCounter.Stop(perf2, "PERF: Setting up layers took {0} ms");

            var perf3 = PerformanceCounter.Start();

            session.StartRunning();

            PerformanceCounter.Stop(perf3, "PERF: session.StartRunning() took {0} ms");

            var perf4 = PerformanceCounter.Start();

            var videoSettings = NSDictionary.FromObjectAndKey(new NSNumber((int)CVPixelFormatType.CV32BGRA),
                                                              CVPixelBuffer.PixelFormatTypeKey);


            // create a VideoDataOutput and add it to the sesion
            output = new AVCaptureVideoDataOutput {
                WeakVideoSettings = videoSettings
            };

            // configure the output
            queue = new DispatchQueue("ZxingScannerView");             // (Guid.NewGuid().ToString());

            var barcodeReader = ScanningOptions.BuildBarcodeReader();

            outputRecorder = new OutputRecorder(this, img =>
            {
                var ls = img;

                if (!IsAnalyzing)
                {
                    return(false);
                }

                try
                {
                    var perfDecode = PerformanceCounter.Start();

                    if (shouldRotatePreviewBuffer)
                    {
                        ls = ls.rotateCounterClockwise();
                    }

                    var result = barcodeReader.Decode(ls);

                    PerformanceCounter.Stop(perfDecode, "Decode Time: {0} ms");

                    if (result != null)
                    {
                        resultCallback(new MobileResult(result));
                        return(true);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("DECODE FAILED: " + ex);
                }

                return(false);
            });

            output.AlwaysDiscardsLateVideoFrames = true;
            output.SetSampleBufferDelegate(outputRecorder, queue);

            PerformanceCounter.Stop(perf4, "PERF: SetupCamera Finished.  Took {0} ms.");

            session.AddOutput(output);
            //session.StartRunning ();


            var perf5 = PerformanceCounter.Start();

            NSError err = null;
            if (captureDevice.LockForConfiguration(out err))
            {
                if (ScanningOptions.DisableAutofocus)
                {
                    captureDevice.FocusMode = AVCaptureFocusMode.Locked;
                }
                else
                {
                    if (captureDevice.IsFocusModeSupported(AVCaptureFocusMode.ContinuousAutoFocus))
                    {
                        captureDevice.FocusMode = AVCaptureFocusMode.ContinuousAutoFocus;
                    }
                    else if (captureDevice.IsFocusModeSupported(AVCaptureFocusMode.AutoFocus))
                    {
                        captureDevice.FocusMode = AVCaptureFocusMode.AutoFocus;
                    }
                }

                if (captureDevice.IsExposureModeSupported(AVCaptureExposureMode.ContinuousAutoExposure))
                {
                    captureDevice.ExposureMode = AVCaptureExposureMode.ContinuousAutoExposure;
                }
                else if (captureDevice.IsExposureModeSupported(AVCaptureExposureMode.AutoExpose))
                {
                    captureDevice.ExposureMode = AVCaptureExposureMode.AutoExpose;
                }

                if (captureDevice.IsWhiteBalanceModeSupported(AVCaptureWhiteBalanceMode.ContinuousAutoWhiteBalance))
                {
                    captureDevice.WhiteBalanceMode = AVCaptureWhiteBalanceMode.ContinuousAutoWhiteBalance;
                }
                else if (captureDevice.IsWhiteBalanceModeSupported(AVCaptureWhiteBalanceMode.AutoWhiteBalance))
                {
                    captureDevice.WhiteBalanceMode = AVCaptureWhiteBalanceMode.AutoWhiteBalance;
                }

                if (UIDevice.CurrentDevice.CheckSystemVersion(7, 0) && captureDevice.AutoFocusRangeRestrictionSupported)
                {
                    captureDevice.AutoFocusRangeRestriction = AVCaptureAutoFocusRangeRestriction.Near;
                }

                if (captureDevice.FocusPointOfInterestSupported)
                {
                    captureDevice.FocusPointOfInterest = new PointF(0.5f, 0.5f);
                }

                if (captureDevice.ExposurePointOfInterestSupported)
                {
                    captureDevice.ExposurePointOfInterest = new PointF(0.5f, 0.5f);
                }

                captureDevice.UnlockForConfiguration();
            }
            else
            {
                Console.WriteLine("Failed to Lock for Config: " + err.Description);
            }

            PerformanceCounter.Stop(perf5, "PERF: Setup Focus in {0} ms.");

            return(true);
        }
Esempio n. 24
0
		private void createPreview()
		{
			previewlayer = new AVCaptureVideoPreviewLayer (session);
			previewlayer.Frame = this.View.Bounds;

			this.cameraView = new UIView ();

			this.cameraView.Layer.AddSublayer (previewlayer);

		}
Esempio n. 25
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            this.View.BackgroundColor = UIColor.White;

            NSError error;


            // Create the session. The AVCaptureSession is the managing instance of the whole video handling.
            var captureSession = new AVCaptureSession()
            {
                // Defines what quality we want to use for the images we grab. Photo gives highest resolutions.
                SessionPreset = AVCaptureSession.PresetPhoto
            };

            // Find a suitable AVCaptureDevice for video input.
            var device = AVCaptureDevice.GetDefaultDevice(AVMediaType.Video);

            if (device == null)
            {
                // This will not work on the iOS Simulator - there is no camera. :-)
                throw new InvalidProgramException("Failed to get AVCaptureDevice for video input!");
            }

            // Create a device input with the device and add it to the session.
            var videoInput = AVCaptureDeviceInput.FromDevice(device, out error);

            if (videoInput == null)
            {
                throw new InvalidProgramException("Failed to get AVCaptureDeviceInput from AVCaptureDevice!");
            }

            // Let session read from the input, this is our source.
            captureSession.AddInput(videoInput);

            // Create output for the video stream. This is the destination.
            var videoOutput = new AVCaptureVideoDataOutput()
            {
                AlwaysDiscardsLateVideoFrames = true
            };

            // Define the video format we want to use. Note that Xamarin exposes the CompressedVideoSetting and UncompressedVideoSetting
            // properties on AVCaptureVideoDataOutput un Unified API, but I could not get these to work. The VideoSettings property is deprecated,
            // so I use the WeakVideoSettings instead which takes an NSDictionary as input.
            this.videoSettingsDict = new NSMutableDictionary();
            this.videoSettingsDict.Add(CVPixelBuffer.PixelFormatTypeKey, NSNumber.FromUInt32((uint)CVPixelFormatType.CV32BGRA));
            videoOutput.WeakVideoSettings = this.videoSettingsDict;

            // Create a delegate to report back to us when an image has been captured.
            // We want to grab the camera stream and feed it through a AVCaptureVideoDataOutputSampleBufferDelegate
            // which allows us to get notified if a new image is availeble. An implementation of that delegate is VideoFrameSampleDelegate in this project.
            this.sampleBufferDelegate = new VideoFrameSamplerDelegate();

            // Processing happens via Grand Central Dispatch (GCD), so we need to provide a queue.
            // This is pretty much like a system managed thread (see: http://zeroheroblog.com/ios/concurrency-in-ios-grand-central-dispatch-gcd-dispatch-queues).
            this.sessionQueue = new DispatchQueue("AVSessionQueue");

            // Assign the queue and the delegate to the output. Now all output will go through the delegate.
            videoOutput.SetSampleBufferDelegateQueue(this.sampleBufferDelegate, this.sessionQueue);

            // Add output to session.
            captureSession.AddOutput(videoOutput);

            // We also want to visualize the input stream. The raw stream can be fed into an AVCaptureVideoPreviewLayer, which is a subclass of CALayer.
            // A CALayer can be added to a UIView. We add that layer to the controller's main view.
            var layer = this.View.Layer;

            this.videoLayer       = AVCaptureVideoPreviewLayer.FromSession(captureSession);
            this.videoLayer.Frame = layer.Bounds;
            layer.AddSublayer(this.videoLayer);

            // All setup! Start capturing!
            captureSession.StartRunning();

            // Configure framerate. Kind of weird way of doing it but the only one that works.
            device.LockForConfiguration(out error);
            // CMTime constructor means: 1 = one second, DETECTION_FPS = how many samples per unit, which is 1 second in this case.
            device.ActiveVideoMinFrameDuration = new CMTime(1, DETECTION_FPS);
            device.ActiveVideoMaxFrameDuration = new CMTime(1, DETECTION_FPS);
            device.UnlockForConfiguration();
        }