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){ Console.WriteLine ("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), // If you want to cap the frame rate at a given speed, in this sample: 15 frames per second MinFrameDuration = new CMTime (1, 15) }; // configure the output queue = new MonoTouch.CoreFoundation.DispatchQueue ("myQueue"); outputRecorder = new OutputRecorder (); output.SetSampleBufferDelegateAndQueue (outputRecorder, queue); session.AddOutput (output); session.StartRunning (); return 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); if (captureDevice == null) { Console.WriteLine("No captureDevice - this won't work on the simulator, try a physical device"); return(false); } //Configure for 15 FPS. Note use of LockForConigfuration()/UnlockForConfiguration() NSError error = null; captureDevice.LockForConfiguration(out error); if (error != null) { Console.WriteLine(error); captureDevice.UnlockForConfiguration(); return(false); } if (UIDevice.CurrentDevice.CheckSystemVersion(7, 0)) { captureDevice.ActiveVideoMinFrameDuration = new CMTime(1, 15); } captureDevice.UnlockForConfiguration(); 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); } session.AddInput(input); // create a VideoDataOutput and add it to the sesion var output = new AVCaptureVideoDataOutput() { WeakVideoSettings = new CVPixelBufferAttributes() { PixelFormatType = CVPixelFormatType.CV32BGRA }.Dictionary, }; // configure the output queue = new CoreFoundation.DispatchQueue("myQueue"); outputRecorder = new OutputRecorder(); output.SetSampleBufferDelegate(outputRecorder, queue); session.AddOutput(output); session.StartRunning(); return(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); if (captureDevice == null) { Image <Bgr, Byte> img = new Image <Bgr, byte> (512, 512, new Bgr(255, 255, 255)); CvInvoke.PutText( img, "Capture device not found.", new Point(10, 200), FontFace.HersheyComplex, 1, new MCvScalar(), 2); ImageView.Image = img.ToUIImage(); return(false); } var input = AVCaptureDeviceInput.FromDevice(captureDevice); if (input == null) { Console.WriteLine("No input device"); return(false); } session.AddInput(input); // create a VideoDataOutput and add it to the sesion AVVideoSettingsUncompressed settingUncomp = new AVVideoSettingsUncompressed(); settingUncomp.PixelFormatType = CVPixelFormatType.CV32BGRA; var output = new AVCaptureVideoDataOutput() { UncompressedVideoSetting = settingUncomp, // If you want to cap the frame rate at a given speed, in this sample: 15 frames per second //MinFrameDuration = new CMTime (1, 15) }; // configure the output queue = new DispatchQueue("myQueue"); outputRecorder = new OutputRecorder(ImageView); output.SetSampleBufferDelegateQueue(outputRecorder, queue); session.AddOutput(output); session.StartRunning(); return(true); }
private void 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); if (captureDevice == null) { RenderImageMessage("Capture device not found."); return; } var input = AVCaptureDeviceInput.FromDevice(captureDevice); if (input == null) { RenderImageMessage("No input device"); return; } session.AddInput(input); // create a VideoDataOutput and add it to the sesion AVVideoSettingsUncompressed settingUncomp = new AVVideoSettingsUncompressed(); settingUncomp.PixelFormatType = CVPixelFormatType.CV32BGRA; var output = new AVCaptureVideoDataOutput() { UncompressedVideoSetting = settingUncomp, // If you want to cap the frame rate at a given speed, in this sample: 15 frames per second //MinFrameDuration = new CMTime (1, 15) }; // configure the output queue = new DispatchQueue("myQueue"); outputRecorder = new OutputRecorder(ImageView); output.SetSampleBufferDelegateQueue(outputRecorder, queue); session.AddOutput(output); session.StartRunning(); }
public void CaptureMovie() { //start recording if (!isRecording && CameraMode == CameraModes.Video) { var outputUrl = ApplicationDocumentsDirectory().Append($"Video_{DateTime.Now.ToString("yyMMdd_hhmmss")}", false).AppendPathExtension("mov"); VideoFileUrl = outputUrl.AbsoluteString; // string localFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments); // var localPath = System.IO.Path.Combine(localFolder, $"Video_{DateTime.Now.ToString("yyMMdd_hhmmss")}.mov"); // var outputUrl = ApplicationDocumentsDirectory().Append($"Video_{DateTime.Now.ToString("yyMMdd-hhmmss")}", false).AppendPathExtension("mov"); var _delegate = new OutputRecorder(); _delegate.SavedMovie += (sender, e) => { Video?.Invoke(this, VideoFileUrl); /// SavedMovie(this, new ListEventArgs(outputUrl.AbsoluteString, e.error?.LocalizedDescription)); //Analytics.TrackEvent("Trigger seconds SavedMovie Event"); }; movieFileOutput.StartRecordingToOutputFile(outputUrl, _delegate); //takePhotoButton.Hidden = true; //stopRecordButton.Hidden = false; StartedRecordingVideo?.Invoke(this, EventArgs.Empty); } else if (isRecording && CameraMode == CameraModes.Video) { movieFileOutput.StopRecording(); //takePhotoButton.Hidden = false; //stopRecordButton.Hidden = true; } else if (CameraMode == CameraModes.Snapshot) { var cb = new PhotoRecorderDelegate(); cb.SavedPhoto += (object sender, ListEventArgs e) => { /// SavedMovie(this, e); PhotoPath?.Invoke(this, e.MovieUrl); }; var dictionary = new NSDictionary <NSString, NSObject> ( AVVideo.CodecKey, AVVideo.CodecJPEG ); var setting = AVCapturePhotoSettings.FromFormat(dictionary); setting.IsHighResolutionPhotoEnabled = true; setting.IsAutoStillImageStabilizationEnabled = true; photoFileOutput.CapturePhoto(setting, cb); } isRecording = !isRecording; }
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); if (captureDevice == null) { Console.WriteLine ("No captureDevice - this won't work on the simulator, try a physical device"); return false; } //Configure for 15 FPS. Note use of LockForConigfuration()/UnlockForConfiguration() NSError error = null; captureDevice.LockForConfiguration (out error); if (error != null) { Console.WriteLine (error); captureDevice.UnlockForConfiguration (); return false; } if (UIDevice.CurrentDevice.CheckSystemVersion (7, 0)) captureDevice.ActiveVideoMinFrameDuration = new CMTime (1, 15); captureDevice.UnlockForConfiguration (); 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; } session.AddInput (input); // create a VideoDataOutput and add it to the sesion var settings = new CVPixelBufferAttributes { PixelFormatType = CVPixelFormatType.CV32BGRA }; using (var output = new AVCaptureVideoDataOutput { WeakVideoSettings = settings.Dictionary }) { queue = new DispatchQueue ("myQueue"); outputRecorder = new OutputRecorder (); output.SetSampleBufferDelegate (outputRecorder, queue); session.AddOutput (output); } session.StartRunning (); return 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); 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); } session.AddInput(input); // create a VideoDataOutput and add it to the sesion var output = new AVCaptureVideoDataOutput() { VideoSettings = new AVVideoSettings(CVPixelFormatType.CV32BGRA), // If you want to cap the frame rate at a given speed, in this sample: 15 frames per second MinFrameDuration = new CMTime(1, 15) }; // configure the output queue = new MonoTouch.CoreFoundation.DispatchQueue("myQueue"); outputRecorder = new OutputRecorder(); output.SetSampleBufferDelegate(outputRecorder, queue); session.AddOutput(output); session.StartRunning(); return(true); }
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 BarcodeReaderiOS(null, (img) => { var src = new RGBLuminanceSourceiOS(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(false); } 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); 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 (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); }
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"); 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 = 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 (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); }
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; }
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 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); } var startedAVPreviewLayerAlloc = PerformanceCounter.Start(); previewLayer = new AVCaptureVideoPreviewLayer(session); PerformanceCounter.Stop(startedAVPreviewLayerAlloc, "Alloc AVCaptureVideoPreviewLayer took {0} ms."); var perf2 = PerformanceCounter.Start(); previewLayer.VideoGravity = AVLayerVideoGravity.ResizeAspectFill; previewLayer.Frame = new CGRect(0, 0, Frame.Width, Frame.Height); previewLayer.Position = new CGPoint(Layer.Bounds.Width / 2, (Layer.Bounds.Height / 2)); layerView = new UIView(new CGRect(0, 0, Frame.Width, 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); } 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 ScanResult(result, null)); 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); var perf5 = PerformanceCounter.Start(); if (captureDevice.LockForConfiguration(out var err)) { captureDeviceOriginalConfig = new AVConfigs { FocusMode = captureDevice.FocusMode, ExposureMode = captureDevice.ExposureMode, WhiteBalanceMode = captureDevice.WhiteBalanceMode, AutoFocusRangeRestriction = captureDevice.AutoFocusRangeRestriction, }; if (captureDevice.HasFlash) { captureDeviceOriginalConfig.FlashMode = captureDevice.FlashMode; } if (captureDevice.HasTorch) { captureDeviceOriginalConfig.TorchMode = captureDevice.TorchMode; } if (captureDevice.FocusPointOfInterestSupported) { captureDeviceOriginalConfig.FocusPointOfInterest = captureDevice.FocusPointOfInterest; } if (captureDevice.ExposurePointOfInterestSupported) { captureDeviceOriginalConfig.ExposurePointOfInterest = captureDevice.ExposurePointOfInterest; } 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); }
bool SetupCaptureSession() { session = new AVCaptureSession () { SessionPreset = AVCaptureSession.PresetMedium }; AVCaptureDevice[] capDevices = AVCaptureDevice.DevicesWithMediaType(AVMediaType.Video); AVCaptureDeviceInput input = null; if (capDevices.Length != 0) input = AVCaptureDeviceInput.FromDevice (capDevices[0]); if (input == null){ new UIAlertView("Error", "Camera not available", null, "OK", null).Show(); Console.WriteLine ("Camera not available"); return false; } session.AddInput (input); var output = new AVCaptureVideoDataOutput () { VideoSettings = new AVVideoSettings (CVPixelFormatType.CV32BGRA), MinFrameDuration = new CMTime (1, 30) //second parameter is frames per second }; queue = new MonoTouch.CoreFoundation.DispatchQueue ("myQueue"); outputRecorder = new OutputRecorder (); output.SetSampleBufferDelegateAndQueue (outputRecorder, queue); session.AddOutput (output); session.StartRunning (); return true; }
bool SetupCaptureSession() { var started = DateTime.UtcNow; // 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); } 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(); 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 (); } 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(); // 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 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.ModeContinuousAutoFocus)) { captureDevice.FocusMode = AVCaptureFocusMode.ModeContinuousAutoFocus; } else if (captureDevice.IsFocusModeSupported(AVCaptureFocusMode.ModeAutoFocus)) { captureDevice.FocusMode = AVCaptureFocusMode.ModeAutoFocus; } 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); }
bool SetupCaptureSession() { var started = DateTime.UtcNow; // configure the capture session for low resolution, change this if your code // can cope with more data or volume session = new AVCaptureSession() { SessionPreset = AVCaptureSession.PresetPhoto }; // create a device input and attach it to the session // var captureDevice = AVCaptureDevice.DefaultDeviceWithMediaType (AVMediaType.Video); 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); } 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."); 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(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); }
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); if (captureDevice == null) { Image<Bgr, Byte> img = new Image<Bgr, byte> (512, 512, new Bgr (255, 255, 255)); CvInvoke.PutText ( img, "Capture device not found.", new Point (10, 200), FontFace.HersheyComplex, 1, new MCvScalar (), 2); ImageView.Image = img.ToUIImage(); return false; } var input = AVCaptureDeviceInput.FromDevice (captureDevice); if (input == null){ Console.WriteLine ("No input device"); return false; } session.AddInput (input); // create a VideoDataOutput and add it to the sesion AVVideoSettingsUncompressed settingUncomp = new AVVideoSettingsUncompressed(); settingUncomp.PixelFormatType = CVPixelFormatType.CV32BGRA; var output = new AVCaptureVideoDataOutput () { UncompressedVideoSetting = settingUncomp, // If you want to cap the frame rate at a given speed, in this sample: 15 frames per second //MinFrameDuration = new CMTime (1, 15) }; // configure the output queue = new DispatchQueue ("myQueue"); outputRecorder = new OutputRecorder (ImageView); output.SetSampleBufferDelegateQueue(outputRecorder, queue); session.AddOutput (output); session.StartRunning (); return true; }