From 9294a952e2418eb29f9d80057e046781bfa0a412 Mon Sep 17 00:00:00 2001 From: kenyd Date: Sat, 19 Oct 2019 14:15:10 +0700 Subject: [PATCH 1/7] optimize code --- .../CPScannerViewRenderer.cs | 78 ++++---- Source/CameraPreview.Droid/CPSurfaceView.cs | 37 ++-- .../CameraCaptureListener.cs | 10 +- .../CameraCaptureSessionCallback.cs | 23 +-- .../CameraPreview.Droid/CameraController.cs | 104 +++++----- .../CameraPreview.Droid.csproj | 16 +- .../CameraPreviewSettings.cs | 30 +-- .../CameraStateListener.cs | 25 ++- .../CameraPreview.Droid/CompareSizesByArea.cs | 11 +- Source/CameraPreview.Droid/IDecoder.cs | 2 +- Source/CameraPreview.iOS/CPScannerView.cs | 178 +++++++++--------- .../CPScannerViewRenderer.cs | 47 ++--- .../CameraPreviewSettings.cs | 30 +-- .../CameraPreview.iOS/DefaultDecoderBase.cs | 7 +- .../DefaultOutputRecorder.cs | 51 +++-- Source/CameraPreview.iOS/IDecoder.cs | 6 +- Source/CameraPreview/CameraResolution.cs | 10 +- Source/CameraPreview/DefaultScanResult.cs | 3 +- Source/CameraPreview/ILogger.cs | 5 +- Source/CameraPreview/IScanResult.cs | 6 +- Source/CameraPreview/Logger.cs | 24 +-- Source/CameraPreview/PerformanceCounter.cs | 5 +- Source/CameraPreview/ScannerView.cs | 35 ++-- Source/CameraPreview/ScanningOptionsBase.cs | 10 +- 24 files changed, 362 insertions(+), 391 deletions(-) diff --git a/Source/CameraPreview.Droid/CPScannerViewRenderer.cs b/Source/CameraPreview.Droid/CPScannerViewRenderer.cs index 4b12a85..f20b027 100644 --- a/Source/CameraPreview.Droid/CPScannerViewRenderer.cs +++ b/Source/CameraPreview.Droid/CPScannerViewRenderer.cs @@ -1,6 +1,4 @@ -using System; -using System.ComponentModel; -using System.Threading.Tasks; +using System.ComponentModel; using Android.Content; using Android.Views; using CameraPreview; @@ -9,85 +7,85 @@ using Xamarin.Forms.Platform.Android; [assembly: ExportRenderer(typeof(ScannerView), typeof(CPScannerViewRenderer))] + namespace CameraPreview.Droid { public class CPScannerViewRenderer : ViewRenderer { - public CPScannerViewRenderer(Context context) : base(context) { } - protected ScannerView formsView; + protected ScannerView FormsView; + protected CPSurfaceView PlatformView; + private CameraAnalyzer _cameraAnalyzer; - protected CPSurfaceView nativeSurface; - CameraAnalyzer _cameraAnalyzer; protected override void OnElementChanged(ElementChangedEventArgs e) { base.OnElementChanged(e); + FormsView = Element; - formsView = Element; - - if (nativeSurface == null) + if (PlatformView == null) { - - nativeSurface = new CPSurfaceView(this.Context); - nativeSurface.LayoutParameters = new LayoutParams(LayoutParams.MatchParent, LayoutParams.MatchParent); - _cameraAnalyzer = nativeSurface.CameraAnalyzer; - - nativeSurface.SurfaceTextureAvailable += NativeSurface_SurfaceTextureAvailable; - nativeSurface.SurfaceTextureDestroyed += NativeSurface_SurfaceTextureDestroyed; - nativeSurface.SurfaceTextureSizeChanged += NativeSurface_SurfaceTextureSizeChanged; - base.SetNativeControl(nativeSurface); - - if (formsView.IsScanning) - nativeSurface.StartScanning(formsView.RaiseScanResult, formsView.Options); - - if (!formsView.IsAnalyzing) - nativeSurface.PauseAnalysis(); + PlatformView = new CPSurfaceView(this.Context) + { + LayoutParameters = new LayoutParams(LayoutParams.MatchParent, LayoutParams.MatchParent) + }; + _cameraAnalyzer = PlatformView.CameraAnalyzer; + + PlatformView.SurfaceTextureAvailable += NativeSurface_SurfaceTextureAvailable; + PlatformView.SurfaceTextureDestroyed += NativeSurface_SurfaceTextureDestroyed; + PlatformView.SurfaceTextureSizeChanged += NativeSurface_SurfaceTextureSizeChanged; + base.SetNativeControl(PlatformView); + + if (FormsView.IsScanning) + PlatformView.StartScanning(FormsView.RaiseScanResult, FormsView.Options); + + if (!FormsView.IsAnalyzing) + PlatformView.PauseAnalysis(); } } - void NativeSurface_SurfaceTextureAvailable(object sender, TextureView.SurfaceTextureAvailableEventArgs e) + private void NativeSurface_SurfaceTextureAvailable(object sender, + TextureView.SurfaceTextureAvailableEventArgs e) { _cameraAnalyzer.SetupCamera(e.Width, e.Height); } - void NativeSurface_SurfaceTextureDestroyed(object sender, TextureView.SurfaceTextureDestroyedEventArgs e) + private void NativeSurface_SurfaceTextureDestroyed(object sender, + TextureView.SurfaceTextureDestroyedEventArgs e) { _cameraAnalyzer.ShutdownCamera(); } - void NativeSurface_SurfaceTextureSizeChanged(object sender, TextureView.SurfaceTextureSizeChangedEventArgs e) + private void NativeSurface_SurfaceTextureSizeChanged(object sender, + TextureView.SurfaceTextureSizeChangedEventArgs e) { _cameraAnalyzer.ConfigureTransform(e.Width, e.Height); } - protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); - - if (nativeSurface == null) + if (PlatformView == null) return; switch (e.PropertyName) { case nameof(ScannerView.IsScanning): - if (formsView.IsScanning) - nativeSurface.StartScanning(formsView.RaiseScanResult, formsView.Options); + if (FormsView.IsScanning) + PlatformView.StartScanning(FormsView.RaiseScanResult, FormsView.Options); else - nativeSurface.StopScanning(); + PlatformView.StopScanning(); break; + case nameof(ScannerView.IsAnalyzing): - if (formsView.IsAnalyzing) - nativeSurface.ResumeAnalysis(); + if (FormsView.IsAnalyzing) + PlatformView.ResumeAnalysis(); else - nativeSurface.PauseAnalysis(); + PlatformView.PauseAnalysis(); break; } } } -} - - +} \ No newline at end of file diff --git a/Source/CameraPreview.Droid/CPSurfaceView.cs b/Source/CameraPreview.Droid/CPSurfaceView.cs index 6f35ca1..c0143a6 100644 --- a/Source/CameraPreview.Droid/CPSurfaceView.cs +++ b/Source/CameraPreview.Droid/CPSurfaceView.cs @@ -1,7 +1,5 @@ using System; using Android.Content; -using Android.Graphics; -using Android.Runtime; using Android.Util; using Android.Views; @@ -17,11 +15,13 @@ public CPSurfaceView(Context context) { Init(); } + public CPSurfaceView(Context context, IAttributeSet attrs) : this(context, attrs, 0) { } + public CPSurfaceView(Context context, IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle) { @@ -30,11 +30,10 @@ public CPSurfaceView(Context context, IAttributeSet attrs, int defStyle) private void Init() { - if (_cameraAnalyzer == null) - _cameraAnalyzer = new CameraAnalyzer(this); - - _cameraAnalyzer.ResumeAnalysis(); + if (CameraAnalyzer == null) + CameraAnalyzer = new CameraAnalyzer(this); + CameraAnalyzer.ResumeAnalysis(); } public void SetAspectRatio(int width, int height) @@ -49,15 +48,15 @@ public void SetAspectRatio(int width, int height) protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec) { base.OnMeasure(widthMeasureSpec, heightMeasureSpec); - int width = MeasureSpec.GetSize(widthMeasureSpec); - int height = MeasureSpec.GetSize(heightMeasureSpec); + var width = MeasureSpec.GetSize(widthMeasureSpec); + var height = MeasureSpec.GetSize(heightMeasureSpec); if (0 == _ratioWidth || 0 == _ratioHeight) { SetMeasuredDimension(width, height); } else { - if (width < (float)height * _ratioWidth / (float)_ratioHeight) + if (width < (float) height * _ratioWidth / (float) _ratioHeight) { SetMeasuredDimension(width, width * _ratioHeight / _ratioWidth); } @@ -75,34 +74,30 @@ public void StartScanning(Action scanResultCallback, ScanningOption CameraPreviewSettings.Instance.SetScannerOptions(options); - _cameraAnalyzer.ResultFound += (sender, result) => - { - scanResultCallback?.Invoke(result); - }; - _cameraAnalyzer.ResumeAnalysis(); + CameraAnalyzer.ResultFound += (sender, result) => { scanResultCallback?.Invoke(result); }; + CameraAnalyzer.ResumeAnalysis(); } public void StopScanning() { - _cameraAnalyzer.ShutdownCamera(); + CameraAnalyzer.ShutdownCamera(); //fix Android 7 bug: camera freezes because surfacedestroyed function isn't always called correct, the old surfaceview was still visible. this.Visibility = ViewStates.Gone; } public void PauseAnalysis() { - _cameraAnalyzer.PauseAnalysis(); + CameraAnalyzer.PauseAnalysis(); } public void ResumeAnalysis() { - _cameraAnalyzer.ResumeAnalysis(); + CameraAnalyzer.ResumeAnalysis(); } - public bool IsAnalyzing => _cameraAnalyzer.IsAnalyzing; + public bool IsAnalyzing => CameraAnalyzer.IsAnalyzing; - private CameraAnalyzer _cameraAnalyzer; - public CameraAnalyzer CameraAnalyzer => _cameraAnalyzer; + public CameraAnalyzer CameraAnalyzer { get; private set; } protected override void OnAttachedToWindow() { @@ -118,4 +113,4 @@ protected override void OnWindowVisibilityChanged(ViewStates visibility) Init(); } } -} +} \ No newline at end of file diff --git a/Source/CameraPreview.Droid/CameraCaptureListener.cs b/Source/CameraPreview.Droid/CameraCaptureListener.cs index 1b14308..5b42573 100644 --- a/Source/CameraPreview.Droid/CameraCaptureListener.cs +++ b/Source/CameraPreview.Droid/CameraCaptureListener.cs @@ -1,6 +1,4 @@ using Android.Hardware.Camera2; -using Java.IO; -using Java.Lang; namespace CameraPreview.Droid { @@ -15,12 +13,14 @@ public CameraCaptureListener(CameraController owner) this.owner = owner; } - public override void OnCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) + public override void OnCaptureCompleted(CameraCaptureSession session, CaptureRequest request, + TotalCaptureResult result) { } - public override void OnCaptureProgressed(CameraCaptureSession session, CaptureRequest request, CaptureResult partialResult) + public override void OnCaptureProgressed(CameraCaptureSession session, CaptureRequest request, + CaptureResult partialResult) { } } -} +} \ No newline at end of file diff --git a/Source/CameraPreview.Droid/CameraCaptureSessionCallback.cs b/Source/CameraPreview.Droid/CameraCaptureSessionCallback.cs index 98f16d7..233d156 100644 --- a/Source/CameraPreview.Droid/CameraCaptureSessionCallback.cs +++ b/Source/CameraPreview.Droid/CameraCaptureSessionCallback.cs @@ -1,15 +1,16 @@ using Android.Hardware.Camera2; + namespace CameraPreview.Droid { public class CameraCaptureSessionCallback : CameraCaptureSession.StateCallback { - private readonly CameraController owner; + private readonly CameraController _owner; public CameraCaptureSessionCallback(CameraController owner) { if (owner == null) throw new System.ArgumentNullException("owner"); - this.owner = owner; + this._owner = owner; } public override void OnConfigureFailed(CameraCaptureSession session) @@ -20,25 +21,25 @@ public override void OnConfigureFailed(CameraCaptureSession session) public override void OnConfigured(CameraCaptureSession session) { // The camera is already closed - if (null == owner.mCameraDevice) + if (null == _owner.mCameraDevice) { return; } // When the session is ready, we start displaying the preview. - owner.CaptureSession = session; + _owner.CaptureSession = session; try { // Auto focus should be continuous for camera preview. - owner.PreviewRequestBuilder.Set(CaptureRequest.ControlAfMode, (int)ControlAFMode.ContinuousPicture); - owner.PreviewRequestBuilder.Set(CaptureRequest.ControlAeMode, (int)ControlAEMode.OnAutoFlash); + _owner.PreviewRequestBuilder.Set(CaptureRequest.ControlAfMode, (int) ControlAFMode.ContinuousPicture); + _owner.PreviewRequestBuilder.Set(CaptureRequest.ControlAeMode, (int) ControlAEMode.OnAutoFlash); // Flash is automatically enabled when necessary. - //owner.SetAutoFlash(owner.PreviewRequestBuilder); + _owner.SetAutoFlash(_owner.PreviewRequestBuilder); // Finally, we start displaying the camera preview. - owner.PreviewRequest = owner.PreviewRequestBuilder.Build(); - owner.CaptureSession.SetRepeatingRequest(owner.PreviewRequest, - owner.CaptureCallback, owner.BackgroundHandler); + _owner.PreviewRequest = _owner.PreviewRequestBuilder.Build(); + _owner.CaptureSession.SetRepeatingRequest(_owner.PreviewRequest, + _owner.CaptureCallback, _owner.BackgroundHandler); } catch (CameraAccessException e) { @@ -46,4 +47,4 @@ public override void OnConfigured(CameraCaptureSession session) } } } -} +} \ No newline at end of file diff --git a/Source/CameraPreview.Droid/CameraController.cs b/Source/CameraPreview.Droid/CameraController.cs index 16e57fb..e014296 100644 --- a/Source/CameraPreview.Droid/CameraController.cs +++ b/Source/CameraPreview.Droid/CameraController.cs @@ -1,11 +1,8 @@ -using System; -using System.Collections.Generic; -using System.Linq; +using System.Collections.Generic; using Android; using Android.App; using Android.Content; using Android.Content.PM; -using Android.Content.Res; using Android.Graphics; using Android.Hardware.Camera2; using Android.Hardware.Camera2.Params; @@ -57,7 +54,7 @@ public CameraController(CPSurfaceView surfaceView) _cameraStateListener = new CameraStateListener(this); CaptureCallback = new CameraCaptureListener(this); _windowManager = _context - .GetSystemService(Context.WindowService).JavaCast(); + .GetSystemService(Context.WindowService).JavaCast(); StartBackgroundThread(); } @@ -69,16 +66,18 @@ public void OpenCamera(int width, int height) { throw new RuntimeException("Don't have access to Camera!"); } + SetUpCameraOutputs(width, height); ConfigureTransform(width, height); - var manager = (CameraManager)_context.GetSystemService(Context.CameraService); + var manager = (CameraManager) _context.GetSystemService(Context.CameraService); try { if (!mCameraOpenCloseLock.TryAcquire(2500, TimeUnit.Milliseconds)) { throw new RuntimeException("Time out waiting to lock camera opening."); } + manager.OpenCamera(_cameraId, _cameraStateListener, BackgroundHandler); } catch (CameraAccessException e) @@ -91,42 +90,43 @@ public void OpenCamera(int width, int height) } } - private void SetUpCameraOutputs(int width, int height) { - var manager = (CameraManager)_context.GetSystemService(Context.CameraService); + var manager = (CameraManager) _context.GetSystemService(Context.CameraService); try { for (var i = 0; i < manager.GetCameraIdList().Length; i++) { var cameraId = manager.GetCameraIdList()[i]; - CameraCharacteristics characteristics = manager.GetCameraCharacteristics(cameraId); + var characteristics = manager.GetCameraCharacteristics(cameraId); // We don't use a front facing camera in this sample. - var facing = (Integer)characteristics.Get(CameraCharacteristics.LensFacing); - if (facing != null && facing == (Integer.ValueOf((int)LensFacing.Front))) + var facing = (Integer) characteristics.Get(CameraCharacteristics.LensFacing); + if (facing != null && facing == (Integer.ValueOf((int) LensFacing.Front))) { continue; } - var map = (StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap); + var map = (StreamConfigurationMap) characteristics.Get(CameraCharacteristics + .ScalerStreamConfigurationMap); if (map == null) { continue; } // For still image captures, we use the largest available size. - Size largest = (Size)Collections.Max(Arrays.AsList(map.GetOutputSizes((int)ImageFormatType.Jpeg)), + var largest = (Size) Collections.Max(Arrays.AsList(map.GetOutputSizes((int) ImageFormatType.Jpeg)), new CompareSizesByArea()); - _imageReader = ImageReader.NewInstance(largest.Width, largest.Height, ImageFormatType.Jpeg, /*maxImages*/2); + _imageReader = ImageReader.NewInstance(largest.Width, largest.Height, + ImageFormatType.Jpeg, /*maxImages*/2); // Find out if we need to swap dimension to get the preview size relative to sensor // coordinate. var displayRotation = _windowManager.DefaultDisplay.Rotation; //noinspection ConstantConditions - _sensorOrientation = (int)characteristics.Get(CameraCharacteristics.SensorOrientation); - bool swappedDimensions = false; + _sensorOrientation = (int) characteristics.Get(CameraCharacteristics.SensorOrientation); + var swappedDimensions = false; switch (displayRotation) { case SurfaceOrientation.Rotation0: @@ -135,6 +135,7 @@ private void SetUpCameraOutputs(int width, int height) { swappedDimensions = true; } + break; case SurfaceOrientation.Rotation90: case SurfaceOrientation.Rotation270: @@ -142,13 +143,14 @@ private void SetUpCameraOutputs(int width, int height) { swappedDimensions = true; } + break; default: //Log.Error(TAG, "Display rotation is invalid: " + displayRotation); break; } - Point displaySize = new Point(); + var displaySize = new Point(); _windowManager.DefaultDisplay.GetSize(displaySize); var rotatedPreviewWidth = width; var rotatedPreviewHeight = height; @@ -192,14 +194,14 @@ private void SetUpCameraOutputs(int width, int height) } // Check if the flash is supported. - var available = (Boolean)characteristics.Get(CameraCharacteristics.FlashInfoAvailable); + var available = (Boolean) characteristics.Get(CameraCharacteristics.FlashInfoAvailable); if (available == null) { _flashSupported = false; } else { - _flashSupported = (bool)available; + _flashSupported = (bool) available; } _cameraId = cameraId; @@ -220,24 +222,23 @@ private void SetUpCameraOutputs(int width, int height) } private static Size ChooseOptimalSize(Size[] choices, - int textureViewWidth, - int textureViewHeight, - int maxWidth, - int maxHeight, - Size aspectRatio) + int textureViewWidth, + int textureViewHeight, + int maxWidth, + int maxHeight, + Size aspectRatio) { // Collect the supported resolutions that are at least as big as the preview Surface var bigEnough = new List(); // Collect the supported resolutions that are smaller than the preview Surface var notBigEnough = new List(); - int w = aspectRatio.Width; - int h = aspectRatio.Height; + var w = aspectRatio.Width; + var h = aspectRatio.Height; - for (var i = 0; i < choices.Length; i++) + foreach (var option in choices) { - Size option = choices[i]; if ((option.Width <= maxWidth) && (option.Height <= maxHeight) && - option.Height == option.Width * h / w) + option.Height == option.Width * h / w) { if (option.Width >= textureViewWidth && option.Height >= textureViewHeight) @@ -255,11 +256,11 @@ private static Size ChooseOptimalSize(Size[] choices, // largest of those not big enough. if (bigEnough.Count > 0) { - return (Size)Collections.Min(bigEnough, new CompareSizesByArea()); + return (Size) Collections.Min(bigEnough, new CompareSizesByArea()); } else if (notBigEnough.Count > 0) { - return (Size)Collections.Max(notBigEnough, new CompareSizesByArea()); + return (Size) Collections.Max(notBigEnough, new CompareSizesByArea()); } else { @@ -276,26 +277,29 @@ public void ConfigureTransform(int viewWidth, int viewHeight) { return; } + var windowManager = _context - .GetSystemService(Context.WindowService).JavaCast(); ; - var rotation = (int)windowManager.DefaultDisplay.Rotation; - Matrix matrix = new Matrix(); - RectF viewRect = new RectF(0, 0, viewWidth, viewHeight); - RectF bufferRect = new RectF(0, 0, _previewSize.Height, _previewSize.Width); - float centerX = viewRect.CenterX(); - float centerY = viewRect.CenterY(); - if ((int)SurfaceOrientation.Rotation90 == rotation || (int)SurfaceOrientation.Rotation270 == rotation) + .GetSystemService(Context.WindowService).JavaCast(); + ; + var rotation = (int) windowManager.DefaultDisplay.Rotation; + var matrix = new Matrix(); + var viewRect = new RectF(0, 0, viewWidth, viewHeight); + var bufferRect = new RectF(0, 0, _previewSize.Height, _previewSize.Width); + var centerX = viewRect.CenterX(); + var centerY = viewRect.CenterY(); + if ((int) SurfaceOrientation.Rotation90 == rotation || (int) SurfaceOrientation.Rotation270 == rotation) { bufferRect.Offset(centerX - bufferRect.CenterX(), centerY - bufferRect.CenterY()); matrix.SetRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.Fill); - float scale = Math.Max((float)viewHeight / _previewSize.Height, (float)viewWidth / _previewSize.Width); + var scale = Math.Max((float) viewHeight / _previewSize.Height, (float) viewWidth / _previewSize.Width); matrix.PostScale(scale, scale, centerX, centerY); matrix.PostRotate(90 * (rotation - 2), centerX, centerY); } - else if ((int)SurfaceOrientation.Rotation180 == rotation) + else if ((int) SurfaceOrientation.Rotation180 == rotation) { matrix.PostRotate(180, centerX, centerY); } + _surfaceView.SetTransform(matrix); } @@ -309,16 +313,19 @@ public void CloseCamera() CaptureSession.Close(); CaptureSession = null; } + if (null != mCameraDevice) { mCameraDevice.Close(); mCameraDevice = null; } + if (null != _imageReader) { _imageReader.Close(); _imageReader = null; } + StopBackgroundThread(); } catch (InterruptedException e) @@ -355,12 +362,12 @@ private void StopBackgroundThread() } } - private class ImageDecoder : Java.Lang.Object, IRunnable { private readonly IDecoder _decoder; private readonly Handler _backgroundHandler; - private CPSurfaceView _surfaceView; + private readonly CPSurfaceView _surfaceView; + public ImageDecoder(Handler backgroundHandler, CPSurfaceView surfaceView) { _decoder = CameraPreviewSettings.Instance.Decoder; @@ -390,6 +397,7 @@ public void Run() bitmap?.Recycle(); _decoder.HandleExceptionFromProcessImage?.Invoke(ex); } + _backgroundHandler.Post(new ImageDecoder(_backgroundHandler, _surfaceView)); } } @@ -398,7 +406,7 @@ public void CreateCameraPreviewSession() { try { - SurfaceTexture texture = _surfaceView.SurfaceTexture; + var texture = _surfaceView.SurfaceTexture; if (texture == null) { throw new IllegalStateException("texture is null"); @@ -408,15 +416,14 @@ public void CreateCameraPreviewSession() texture.SetDefaultBufferSize(_previewSize.Width, _previewSize.Height); // This is the output Surface we need to start preview. - Surface surface = new Surface(texture); + var surface = new Surface(texture); // We set up a CaptureRequest.Builder with the output Surface. PreviewRequestBuilder = mCameraDevice.CreateCaptureRequest(CameraTemplate.Preview); PreviewRequestBuilder.AddTarget(surface); // Here, we create a CameraCaptureSession for camera preview. - List surfaces = new List(); - surfaces.Add(surface); + var surfaces = new List {surface}; mCameraDevice.CreateCaptureSession(surfaces, new CameraCaptureSessionCallback(this), null); BackgroundHandler.Post(new ImageDecoder(BackgroundHandler, _surfaceView)); @@ -428,12 +435,11 @@ public void CreateCameraPreviewSession() } } - public void SetAutoFlash(CaptureRequest.Builder requestBuilder) { if (_flashSupported) { - requestBuilder.Set(CaptureRequest.ControlAeMode, (int)ControlAEMode.OnAutoFlash); + requestBuilder.Set(CaptureRequest.ControlAeMode, (int) ControlAEMode.OnAutoFlash); } } } diff --git a/Source/CameraPreview.Droid/CameraPreview.Droid.csproj b/Source/CameraPreview.Droid/CameraPreview.Droid.csproj index db85693..c80cac3 100644 --- a/Source/CameraPreview.Droid/CameraPreview.Droid.csproj +++ b/Source/CameraPreview.Droid/CameraPreview.Droid.csproj @@ -1,6 +1,6 @@ - + - + Debug AnyCPU @@ -9,7 +9,7 @@ Library CameraPreview.Droid CameraPreview.Droid - v8.1 + v10.0 true @@ -20,7 +20,8 @@ prompt 4 None - + + true @@ -31,7 +32,8 @@ 4 true false - + + @@ -111,7 +113,7 @@ ..\..\packages\Xamarin.Forms.3.6.0.264807\lib\MonoAndroid81\Xamarin.Forms.Xaml.dll - + @@ -155,4 +157,4 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/Source/CameraPreview.Droid/CameraPreviewSettings.cs b/Source/CameraPreview.Droid/CameraPreviewSettings.cs index 8237661..79a152b 100644 --- a/Source/CameraPreview.Droid/CameraPreviewSettings.cs +++ b/Source/CameraPreview.Droid/CameraPreviewSettings.cs @@ -1,42 +1,30 @@ -using System; -namespace CameraPreview.Droid +namespace CameraPreview.Droid { public class CameraPreviewSettings { - private static CameraPreviewSettings instance; - private ScanningOptionsBase _scanningOptions = ScanningOptionsBase.Default; - private CameraPreviewSettings() { } + private static CameraPreviewSettings _instance; - public static CameraPreviewSettings Instance + private CameraPreviewSettings() { - get - { - if (instance == null) - { - instance = new CameraPreviewSettings(); - } - return instance; - } } + public static CameraPreviewSettings Instance => _instance ?? (_instance = new CameraPreviewSettings()); + public IDecoder Decoder { get; set; } - public ScanningOptionsBase ScannerOptions => _scanningOptions; + public ScanningOptionsBase ScannerOptions { get; private set; } = ScanningOptionsBase.Default; public virtual void SetScannerOptions(ScanningOptionsBase value) { if (value == null) return; - _scanningOptions = value; + ScannerOptions = value; Decoder.ScanningOptionsUpdate(value); } public virtual void Init(IDecoder decoder) { - if (decoder == null) - Decoder = new DefaultDecoderBase(); - else - Decoder = decoder; + Decoder = decoder ?? new DefaultDecoderBase(); } } -} +} \ No newline at end of file diff --git a/Source/CameraPreview.Droid/CameraStateListener.cs b/Source/CameraPreview.Droid/CameraStateListener.cs index 51d774a..d8c9d58 100644 --- a/Source/CameraPreview.Droid/CameraStateListener.cs +++ b/Source/CameraPreview.Droid/CameraStateListener.cs @@ -1,41 +1,40 @@ -using System; -using Android.Hardware.Camera2; +using Android.Hardware.Camera2; namespace CameraPreview.Droid { public class CameraStateListener : CameraDevice.StateCallback { - private readonly CameraController owner; + private readonly CameraController _owner; public CameraStateListener(CameraController owner) { if (owner == null) throw new System.ArgumentNullException("owner"); - this.owner = owner; + this._owner = owner; } public override void OnOpened(CameraDevice cameraDevice) { // This method is called when the camera is opened. We start camera preview here. - owner.mCameraOpenCloseLock.Release(); - owner.mCameraDevice = cameraDevice; - owner.CreateCameraPreviewSession(); + _owner.mCameraOpenCloseLock.Release(); + _owner.mCameraDevice = cameraDevice; + _owner.CreateCameraPreviewSession(); } public override void OnDisconnected(CameraDevice cameraDevice) { - owner.mCameraOpenCloseLock.Release(); + _owner.mCameraOpenCloseLock.Release(); cameraDevice.Close(); - owner.mCameraDevice = null; + _owner.mCameraDevice = null; } public override void OnError(CameraDevice cameraDevice, CameraError error) { - owner.mCameraOpenCloseLock.Release(); + _owner.mCameraOpenCloseLock.Release(); cameraDevice.Close(); - owner.mCameraDevice = null; - if (owner == null) + _owner.mCameraDevice = null; + if (_owner == null) return; } } -} +} \ No newline at end of file diff --git a/Source/CameraPreview.Droid/CompareSizesByArea.cs b/Source/CameraPreview.Droid/CompareSizesByArea.cs index b232549..f41655a 100644 --- a/Source/CameraPreview.Droid/CompareSizesByArea.cs +++ b/Source/CameraPreview.Droid/CompareSizesByArea.cs @@ -1,17 +1,16 @@ using Android.Util; -using Java.Lang; using Java.Util; namespace CameraPreview.Droid { public class CompareSizesByArea : Java.Lang.Object, IComparator { - public int Compare(Object lhs, Object rhs) + public int Compare(Java.Lang.Object lhs, Java.Lang.Object rhs) { - var lhsSize = (Size)lhs; - var rhsSize = (Size)rhs; + var lhsSize = (Size) lhs; + var rhsSize = (Size) rhs; // We cast here to ensure the multiplications won't overflow - return Long.Signum((long)lhsSize.Width * lhsSize.Height - (long)rhsSize.Width * rhsSize.Height); + return Java.Lang.Long.Signum((long) lhsSize.Width * lhsSize.Height - (long) rhsSize.Width * rhsSize.Height); } } -} +} \ No newline at end of file diff --git a/Source/CameraPreview.Droid/IDecoder.cs b/Source/CameraPreview.Droid/IDecoder.cs index 5feac66..cb2ff5d 100644 --- a/Source/CameraPreview.Droid/IDecoder.cs +++ b/Source/CameraPreview.Droid/IDecoder.cs @@ -13,4 +13,4 @@ public interface IDecoder int ImageSizeY { get; } void ScanningOptionsUpdate(ScanningOptionsBase options); } -} +} \ No newline at end of file diff --git a/Source/CameraPreview.iOS/CPScannerView.cs b/Source/CameraPreview.iOS/CPScannerView.cs index ce54724..78d4ccd 100644 --- a/Source/CameraPreview.iOS/CPScannerView.cs +++ b/Source/CameraPreview.iOS/CPScannerView.cs @@ -2,11 +2,9 @@ using System.Collections.Generic; using System.Drawing; using System.Linq; -using System.Threading; using AVFoundation; using CoreFoundation; using CoreGraphics; -using CoreMedia; using CoreVideo; using Foundation; using ObjCRuntime; @@ -14,36 +12,37 @@ namespace CameraPreview.iOS { - public class CPScannerView : UIView + public class CpScannerView : UIView { public delegate void ScannerSetupCompleteDelegate(); + public event ScannerSetupCompleteDelegate OnScannerSetupComplete; - AVCaptureSession session; - AVCaptureVideoPreviewLayer previewLayer; - AVCaptureVideoDataOutput output; - IOutputRecorder outputRecorder; - DispatchQueue queue; - Action resultCallback; - volatile bool stopped = true; + private AVCaptureSession _session; + private AVCaptureVideoPreviewLayer _previewLayer; + private AVCaptureVideoDataOutput _output; + private IOutputRecorder _outputRecorder; + private DispatchQueue _queue; + private Action _resultCallback; + private volatile bool _stopped = true; - UIView layerView; + private UIView _layerView; public string CancelButtonText { get; set; } public string FlashButtonText { get; set; } - bool shouldRotatePreviewBuffer = false; + private bool _shouldRotatePreviewBuffer = false; - void Setup(CGRect frame) + private static void Setup(CGRect frame) { var started = DateTime.UtcNow; var total = DateTime.UtcNow - started; Logger.Log($"CPScannerView.Setup() took {total.TotalMilliseconds} ms."); } - bool analyzing = true; + private bool _analyzing = true; - bool SetupCaptureSession() + private bool SetupCaptureSession() { if (CameraPreviewSettings.Instance.Decoder == null) return false; @@ -52,17 +51,18 @@ bool SetupCaptureSession() var availableResolutions = new List(); - var consideredResolutions = new Dictionary { - { 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 } } + var consideredResolutions = new Dictionary + { + {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() + _session = new AVCaptureSession() { SessionPreset = AVCaptureSession.Preset640x480 }; @@ -80,10 +80,11 @@ bool SetupCaptureSession() break; //Front camera successfully set else if (device.Position == AVCaptureDevicePosition.Back && - (!CameraPreviewSettings.Instance.ScannerOptions.UseFrontCameraIfAvailable.HasValue - || !CameraPreviewSettings.Instance.ScannerOptions.UseFrontCameraIfAvailable.Value)) - break; //Back camera succesfully set + (!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"); @@ -109,13 +110,13 @@ bool SetupCaptureSession() { // 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(); + 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; + _session.SessionPreset = preset; } var input = AVCaptureDeviceInput.FromDevice(captureDevice); @@ -125,30 +126,32 @@ bool SetupCaptureSession() return false; } else - session.AddInput(input); + _session.AddInput(input); - var startedAVPreviewLayerAlloc = PerformanceCounter.Start(); + var startedAvPreviewLayerAlloc = PerformanceCounter.Start(); - previewLayer = new AVCaptureVideoPreviewLayer(session); + _previewLayer = new AVCaptureVideoPreviewLayer(_session); - PerformanceCounter.Stop(startedAVPreviewLayerAlloc, "Alloc AVCaptureVideoPreviewLayer took {0} ms."); + PerformanceCounter.Stop(startedAvPreviewLayerAlloc, "Alloc AVCaptureVideoPreviewLayer took {0} ms."); var perf2 = PerformanceCounter.Start(); #if __UNIFIED__ - previewLayer.VideoGravity = AVLayerVideoGravity.ResizeAspectFill; + _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)); + _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); + _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); + this.AddSubview(_layerView); ResizePreview(UIApplication.SharedApplication.StatusBarOrientation); @@ -157,38 +160,37 @@ bool SetupCaptureSession() var perf3 = PerformanceCounter.Start(); - session.StartRunning(); + _session.StartRunning(); PerformanceCounter.Stop(perf3, "PERF: session.StartRunning() took {0} ms"); var perf4 = PerformanceCounter.Start(); - var videoSettings = NSDictionary.FromObjectAndKey(new NSNumber((int)CVPixelFormatType.CV32BGRA), + var videoSettings = NSDictionary.FromObjectAndKey(new NSNumber((int) CVPixelFormatType.CV32BGRA), CVPixelBuffer.PixelFormatTypeKey); // create a VideoDataOutput and add it to the sesion - output = new AVCaptureVideoDataOutput + _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); + _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.AddOutput(_output); //session.StartRunning (); var perf5 = PerformanceCounter.Start(); - NSError err = null; - if (captureDevice.LockForConfiguration(out err)) + if (captureDevice.LockForConfiguration(out var err)) { if (captureDevice.IsFocusModeSupported(AVCaptureFocusMode.ContinuousAutoFocus)) captureDevice.FocusMode = AVCaptureFocusMode.ContinuousAutoFocus; @@ -236,28 +238,29 @@ public void DidRotate(UIInterfaceOrientation orientation) public void ResizePreview(UIInterfaceOrientation orientation) { - shouldRotatePreviewBuffer = orientation == UIInterfaceOrientation.Portrait || orientation == UIInterfaceOrientation.PortraitUpsideDown; + _shouldRotatePreviewBuffer = orientation == UIInterfaceOrientation.Portrait || + orientation == UIInterfaceOrientation.PortraitUpsideDown; - if (previewLayer == null) + if (_previewLayer == null) return; - previewLayer.Frame = new CGRect(0, 0, this.Frame.Width, this.Frame.Height); + _previewLayer.Frame = new CGRect(0, 0, this.Frame.Width, this.Frame.Height); - if (previewLayer.RespondsToSelector(new Selector("connection")) && previewLayer.Connection != null) + if (_previewLayer.RespondsToSelector(new Selector("connection")) && _previewLayer.Connection != null) { switch (orientation) { case UIInterfaceOrientation.LandscapeLeft: - previewLayer.Connection.VideoOrientation = AVCaptureVideoOrientation.LandscapeLeft; + _previewLayer.Connection.VideoOrientation = AVCaptureVideoOrientation.LandscapeLeft; break; case UIInterfaceOrientation.LandscapeRight: - previewLayer.Connection.VideoOrientation = AVCaptureVideoOrientation.LandscapeRight; + _previewLayer.Connection.VideoOrientation = AVCaptureVideoOrientation.LandscapeRight; break; case UIInterfaceOrientation.Portrait: - previewLayer.Connection.VideoOrientation = AVCaptureVideoOrientation.Portrait; + _previewLayer.Connection.VideoOrientation = AVCaptureVideoOrientation.Portrait; break; case UIInterfaceOrientation.PortraitUpsideDown: - previewLayer.Connection.VideoOrientation = AVCaptureVideoOrientation.PortraitUpsideDown; + _previewLayer.Connection.VideoOrientation = AVCaptureVideoOrientation.PortraitUpsideDown; break; } } @@ -265,17 +268,17 @@ public void ResizePreview(UIInterfaceOrientation orientation) public void StartScanning(Action scanResultHandler, ScanningOptionsBase options = null) { - if (!stopped) + if (!_stopped) return; - stopped = false; + _stopped = false; var perf = PerformanceCounter.Start(); Setup(this.Frame); CameraPreviewSettings.Instance.SetScannerOptions(options); - this.resultCallback = scanResultHandler; + this._resultCallback = scanResultHandler; Logger.Log("StartScanning"); @@ -290,67 +293,72 @@ public void StartScanning(Action scanResultHandler, ScanningOptions if (Runtime.Arch == Arch.SIMULATOR) { - var simView = new UIView(new CGRect(0, 0, this.Frame.Width, this.Frame.Height)); - simView.BackgroundColor = UIColor.LightGray; - simView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight; + var simView = new UIView(new CGRect(0, 0, this.Frame.Width, this.Frame.Height)) + { + BackgroundColor = UIColor.LightGray, + AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight + }; this.InsertSubview(simView, 0); } }); - if (!analyzing) - analyzing = true; + if (!_analyzing) + _analyzing = true; PerformanceCounter.Stop(perf, "PERF: StartScanning() Took {0} ms."); var evt = this.OnScannerSetupComplete; - if (evt != null) - evt(); + evt?.Invoke(); } public void StopScanning() { - if (stopped) + if (_stopped) return; Console.WriteLine("Stopping..."); - if (outputRecorder != null) - outputRecorder.CancelTokenSource.Cancel(); + _outputRecorder?.CancelTokenSource.Cancel(); //Try removing all existing outputs prior to closing the session try { - while (session.Outputs.Length > 0) - session.RemoveOutput(session.Outputs[0]); + while (_session.Outputs.Length > 0) + _session.RemoveOutput(_session.Outputs[0]); + } + catch (Exception exception) + { + System.Diagnostics.Debug.WriteLine(exception.Message); } - catch { } //Try to remove all existing inputs prior to closing the session try { - while (session.Inputs.Length > 0) - session.RemoveInput(session.Inputs[0]); + while (_session.Inputs.Length > 0) + _session.RemoveInput(_session.Inputs[0]); + } + catch (Exception exception) + { + System.Diagnostics.Debug.WriteLine(exception.Message); } - catch { } - if (session.Running) - session.StopRunning(); + if (_session.Running) + _session.StopRunning(); - stopped = true; + _stopped = true; } public void PauseAnalysis() { - analyzing = false; + _analyzing = false; } public void ResumeAnalysis() { - analyzing = true; + _analyzing = true; } - public bool IsAnalyzing { get { return analyzing; } } - + public bool IsAnalyzing => _analyzing; } -} +} \ No newline at end of file diff --git a/Source/CameraPreview.iOS/CPScannerViewRenderer.cs b/Source/CameraPreview.iOS/CPScannerViewRenderer.cs index edcfed6..1798edd 100644 --- a/Source/CameraPreview.iOS/CPScannerViewRenderer.cs +++ b/Source/CameraPreview.iOS/CPScannerViewRenderer.cs @@ -1,39 +1,40 @@ -using System; -using System.ComponentModel; +using System.ComponentModel; using CameraPreview; using CameraPreview.iOS; -using Foundation; using UIKit; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; [assembly: ExportRenderer(typeof(ScannerView), typeof(CPScannerViewRenderer))] + namespace CameraPreview.iOS { - public class CPScannerViewRenderer : ViewRenderer + public class CPScannerViewRenderer : ViewRenderer { - protected ScannerView formsView; - protected CPScannerView nativeView; + protected ScannerView FormsView; + protected CpScannerView PlatformView; protected override void OnElementChanged(ElementChangedEventArgs e) { AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight; - formsView = Element; + FormsView = Element; - if (nativeView == null) + if (PlatformView == null) { - nativeView = new CPScannerView(); - nativeView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight; + PlatformView = new CpScannerView + { + AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight + }; - base.SetNativeControl(nativeView); + base.SetNativeControl(PlatformView); - if (formsView.IsScanning) - nativeView.StartScanning(formsView.RaiseScanResult, formsView.Options); + if (FormsView.IsScanning) + PlatformView.StartScanning(FormsView.RaiseScanResult, FormsView.Options); - if (!formsView.IsAnalyzing) - nativeView.PauseAnalysis(); + if (!FormsView.IsAnalyzing) + PlatformView.PauseAnalysis(); } base.OnElementChanged(e); @@ -43,22 +44,22 @@ protected override void OnElementPropertyChanged(object sender, PropertyChangedE { base.OnElementPropertyChanged(sender, e); - if (nativeView == null) + if (PlatformView == null) return; switch (e.PropertyName) { case nameof(ScannerView.IsScanning): - if (formsView.IsScanning) - nativeView.StartScanning(formsView.RaiseScanResult, formsView.Options); + if (FormsView.IsScanning) + PlatformView.StartScanning(FormsView.RaiseScanResult, FormsView.Options); else - nativeView.StopScanning(); + PlatformView.StopScanning(); break; case nameof(ScannerView.IsAnalyzing): - if (formsView.IsAnalyzing) - nativeView.ResumeAnalysis(); + if (FormsView.IsAnalyzing) + PlatformView.ResumeAnalysis(); else - nativeView.PauseAnalysis(); + PlatformView.PauseAnalysis(); break; } } @@ -73,7 +74,7 @@ public override void LayoutSubviews() o = ViewController.InterfaceOrientation; // Tell the native view to rotate - nativeView.DidRotate(o); + PlatformView.DidRotate(o); } } } diff --git a/Source/CameraPreview.iOS/CameraPreviewSettings.cs b/Source/CameraPreview.iOS/CameraPreviewSettings.cs index 318606d..ae29638 100644 --- a/Source/CameraPreview.iOS/CameraPreviewSettings.cs +++ b/Source/CameraPreview.iOS/CameraPreviewSettings.cs @@ -1,42 +1,30 @@ -using System; -namespace CameraPreview.iOS +namespace CameraPreview.iOS { public class CameraPreviewSettings { - private static CameraPreviewSettings instance; - private ScanningOptionsBase _scanningOptions = ScanningOptionsBase.Default; - protected CameraPreviewSettings() { } + private static CameraPreviewSettings _instance; - public static CameraPreviewSettings Instance + protected CameraPreviewSettings() { - get - { - if (instance == null) - { - instance = new CameraPreviewSettings(); - } - return instance; - } } + public static CameraPreviewSettings Instance => _instance ?? (_instance = new CameraPreviewSettings()); + public IDecoder Decoder { get; set; } - public ScanningOptionsBase ScannerOptions => _scanningOptions; + public ScanningOptionsBase ScannerOptions { get; private set; } = ScanningOptionsBase.Default; public virtual void SetScannerOptions(ScanningOptionsBase value) { if (value == null) return; - _scanningOptions = value; + ScannerOptions = value; Decoder.ScanningOptionsUpdate(value); } public void Init(IDecoder decoder) { - if (decoder == null) - Decoder = new DefaultDecoderBase(); - else - Decoder = decoder; + Decoder = decoder ?? new DefaultDecoderBase(); } } -} +} \ No newline at end of file diff --git a/Source/CameraPreview.iOS/DefaultDecoderBase.cs b/Source/CameraPreview.iOS/DefaultDecoderBase.cs index 2829e25..ab74029 100644 --- a/Source/CameraPreview.iOS/DefaultDecoderBase.cs +++ b/Source/CameraPreview.iOS/DefaultDecoderBase.cs @@ -1,9 +1,4 @@ -using System; -using System.Threading; -using AVFoundation; -using CoreMedia; -using CoreVideo; -using Foundation; +using CoreVideo; namespace CameraPreview.iOS { diff --git a/Source/CameraPreview.iOS/DefaultOutputRecorder.cs b/Source/CameraPreview.iOS/DefaultOutputRecorder.cs index 3d489fe..32a2eda 100644 --- a/Source/CameraPreview.iOS/DefaultOutputRecorder.cs +++ b/Source/CameraPreview.iOS/DefaultOutputRecorder.cs @@ -9,18 +9,20 @@ namespace CameraPreview.iOS { public class DefaultOutputRecorder : AVCaptureVideoDataOutputSampleBufferDelegate, IOutputRecorder { - readonly Action _resultCallback; - public DefaultOutputRecorder(Action resultCallback) : base() + private readonly Action _resultCallback; + + public DefaultOutputRecorder(Action resultCallback) { _resultCallback = resultCallback; } - DateTime lastAnalysis = DateTime.MinValue; - volatile bool working = false; - volatile bool wasScanned = false; + private DateTime _lastAnalysis = DateTime.MinValue; + private volatile bool _working = false; + private volatile bool _wasScanned = false; [Export("captureOutput:didDropSampleBuffer:fromConnection:")] - public override void DidDropSampleBuffer(AVCaptureOutput captureOutput, CMSampleBuffer sampleBuffer, AVCaptureConnection connection) + public override void DidDropSampleBuffer(AVCaptureOutput captureOutput, CMSampleBuffer sampleBuffer, + AVCaptureConnection connection) { Logger.Log("Dropped Sample Buffer"); } @@ -28,45 +30,44 @@ public override void DidDropSampleBuffer(AVCaptureOutput captureOutput, CMSample public CancellationTokenSource CancelTokenSource { get; set; } = new CancellationTokenSource(); - public override void DidOutputSampleBuffer(AVCaptureOutput captureOutput, CMSampleBuffer sampleBuffer, AVCaptureConnection connection) + public override void DidOutputSampleBuffer(AVCaptureOutput captureOutput, CMSampleBuffer sampleBuffer, + AVCaptureConnection connection) { - var msSinceLastPreview = (DateTime.UtcNow - lastAnalysis).TotalMilliseconds; + var msSinceLastPreview = (DateTime.UtcNow - _lastAnalysis).TotalMilliseconds; var scannerOptions = CameraPreviewSettings.Instance.ScannerOptions; if (msSinceLastPreview < scannerOptions.DelayBetweenAnalyzingFrames - || (wasScanned && msSinceLastPreview < scannerOptions.DelayBetweenContinuousScans) - || working + || (_wasScanned && msSinceLastPreview < scannerOptions.DelayBetweenContinuousScans) + || _working || CancelTokenSource.IsCancellationRequested) { if (msSinceLastPreview < scannerOptions.DelayBetweenAnalyzingFrames) Logger.Log("Too soon between frames", LogLevel.Detail); - if (wasScanned && msSinceLastPreview < scannerOptions.DelayBetweenContinuousScans) + if (_wasScanned && msSinceLastPreview < scannerOptions.DelayBetweenContinuousScans) Logger.Log("Too soon since last scan", LogLevel.Detail); - if (sampleBuffer != null) - { - sampleBuffer.Dispose(); - sampleBuffer = null; - } + sampleBuffer?.Dispose(); + return; } - wasScanned = false; - working = true; - lastAnalysis = DateTime.UtcNow; + _wasScanned = false; + _working = true; + _lastAnalysis = DateTime.UtcNow; try { // Get the CoreVideo image using (var pixelBuffer = sampleBuffer.GetImageBuffer() as CVPixelBuffer) { + if (pixelBuffer == null) return; + // Lock the base address pixelBuffer.Lock(CVPixelBufferLock.ReadOnly); // MAYBE NEEDS READ/WRITE - - IScanResult result = CameraPreviewSettings.Instance.Decoder.Decode(pixelBuffer); + var result = CameraPreviewSettings.Instance.Decoder.Decode(pixelBuffer); _resultCallback?.Invoke(result); if (result.Success) - wasScanned = true; + _wasScanned = true; pixelBuffer.Unlock(CVPixelBufferLock.ReadOnly); } @@ -78,8 +79,6 @@ public override void DidOutputSampleBuffer(AVCaptureOutput captureOutput, CMSamp // delivering frames. // sampleBuffer.Dispose(); - sampleBuffer = null; - } catch (Exception e) { @@ -87,10 +86,8 @@ public override void DidOutputSampleBuffer(AVCaptureOutput captureOutput, CMSamp } finally { - working = false; + _working = false; } - } } - } diff --git a/Source/CameraPreview.iOS/IDecoder.cs b/Source/CameraPreview.iOS/IDecoder.cs index e9b1c47..b592926 100644 --- a/Source/CameraPreview.iOS/IDecoder.cs +++ b/Source/CameraPreview.iOS/IDecoder.cs @@ -1,5 +1,4 @@ -using System; -using System.Threading; +using System.Threading; using AVFoundation; using CoreVideo; @@ -8,6 +7,7 @@ namespace CameraPreview.iOS public interface IDecoder { IScanResult Decode(CVPixelBuffer pixelBuffer); + void ScanningOptionsUpdate(ScanningOptionsBase options); } @@ -15,4 +15,4 @@ public interface IOutputRecorder : IAVCaptureVideoDataOutputSampleBufferDelegate { CancellationTokenSource CancelTokenSource { get; } } -} +} \ No newline at end of file diff --git a/Source/CameraPreview/CameraResolution.cs b/Source/CameraPreview/CameraResolution.cs index 3761783..579f7b5 100644 --- a/Source/CameraPreview/CameraResolution.cs +++ b/Source/CameraPreview/CameraResolution.cs @@ -1,9 +1,13 @@ -using System; -namespace CameraPreview +namespace CameraPreview { public class CameraResolution { + public CameraResolution() + { + } + public int Width { get; set; } + public int Height { get; set; } } -} +} \ No newline at end of file diff --git a/Source/CameraPreview/DefaultScanResult.cs b/Source/CameraPreview/DefaultScanResult.cs index 0e35454..bd3b862 100644 --- a/Source/CameraPreview/DefaultScanResult.cs +++ b/Source/CameraPreview/DefaultScanResult.cs @@ -1,4 +1,5 @@ using System; + namespace CameraPreview { public class DefaultScanResult : IScanResult @@ -7,4 +8,4 @@ public class DefaultScanResult : IScanResult public bool Success => true; } -} +} \ No newline at end of file diff --git a/Source/CameraPreview/ILogger.cs b/Source/CameraPreview/ILogger.cs index fea81b5..ad95393 100644 --- a/Source/CameraPreview/ILogger.cs +++ b/Source/CameraPreview/ILogger.cs @@ -1,5 +1,4 @@ -using System; -namespace CameraPreview +namespace CameraPreview { public interface ILogger { @@ -13,4 +12,4 @@ public enum LogLevel Warring, Error } -} +} \ No newline at end of file diff --git a/Source/CameraPreview/IScanResult.cs b/Source/CameraPreview/IScanResult.cs index 4ee459d..4ba23a3 100644 --- a/Source/CameraPreview/IScanResult.cs +++ b/Source/CameraPreview/IScanResult.cs @@ -1,9 +1,9 @@ -using System; -namespace CameraPreview +namespace CameraPreview { public interface IScanResult { long Timestamp { get; } + bool Success { get; } } -} +} \ No newline at end of file diff --git a/Source/CameraPreview/Logger.cs b/Source/CameraPreview/Logger.cs index bcccf2e..12bc685 100644 --- a/Source/CameraPreview/Logger.cs +++ b/Source/CameraPreview/Logger.cs @@ -1,24 +1,15 @@ -using System; -namespace CameraPreview +namespace CameraPreview { public class Logger { - private static Logger instance; + private static Logger _instance; - private Logger() { } - - public static Logger Instance + private Logger() { - get - { - if (instance == null) - { - instance = new Logger(); - } - return instance; - } } + public static Logger Instance => _instance ?? (_instance = new Logger()); + public static void Log(string message, LogLevel level = LogLevel.Normal) { if (Instance.LoggerObj == null) @@ -27,9 +18,10 @@ public static void Log(string message, LogLevel level = LogLevel.Normal) System.Diagnostics.Debug.WriteLine(message); return; } - instance.LoggerObj.Log(message, level); + + _instance.LoggerObj.Log(message, level); } public ILogger LoggerObj { get; set; } } -} +} \ No newline at end of file diff --git a/Source/CameraPreview/PerformanceCounter.cs b/Source/CameraPreview/PerformanceCounter.cs index 7f7d64d..f37b645 100644 --- a/Source/CameraPreview/PerformanceCounter.cs +++ b/Source/CameraPreview/PerformanceCounter.cs @@ -6,8 +6,7 @@ namespace CameraPreview { public class PerformanceCounter { - - static Dictionary counters = new Dictionary(); + private static readonly Dictionary counters = new Dictionary(); public static string Start() { @@ -47,4 +46,4 @@ public static void Stop(string guid, string msg) Logger.Log(string.Format(msg, elapsed.TotalMilliseconds)); } } -} +} \ No newline at end of file diff --git a/Source/CameraPreview/ScannerView.cs b/Source/CameraPreview/ScannerView.cs index cf7da6b..0cdeecc 100644 --- a/Source/CameraPreview/ScannerView.cs +++ b/Source/CameraPreview/ScannerView.cs @@ -1,5 +1,4 @@ -using System; -using System.Windows.Input; +using System.Windows.Input; using Xamarin.Forms; namespace CameraPreview @@ -7,6 +6,7 @@ namespace CameraPreview public class ScannerView : View { public delegate void ScanResultDelegate(IScanResult result); + public event ScanResultDelegate OnScanResult; public ScannerView() @@ -23,12 +23,13 @@ public void RaiseScanResult(IScanResult result) } public static readonly BindableProperty OptionsProperty = - BindableProperty.Create(nameof(Options), typeof(ScanningOptionsBase), typeof(ScannerView), ScanningOptionsBase.Default); + BindableProperty.Create(nameof(Options), typeof(ScanningOptionsBase), typeof(ScannerView), + ScanningOptionsBase.Default); public ScanningOptionsBase Options { - get { return (ScanningOptionsBase)GetValue(OptionsProperty); } - set { SetValue(OptionsProperty, value); } + get => (ScanningOptionsBase) GetValue(OptionsProperty); + set => SetValue(OptionsProperty, value); } public static readonly BindableProperty IsScanningProperty = @@ -36,8 +37,8 @@ public ScanningOptionsBase Options public bool IsScanning { - get { return (bool)GetValue(IsScanningProperty); } - set { SetValue(IsScanningProperty, value); } + get => (bool) GetValue(IsScanningProperty); + set => SetValue(IsScanningProperty, value); } public static readonly BindableProperty IsAnalyzingProperty = @@ -45,25 +46,27 @@ public bool IsScanning public bool IsAnalyzing { - get { return (bool)GetValue(IsAnalyzingProperty); } - set { SetValue(IsAnalyzingProperty, value); } + get => (bool) GetValue(IsAnalyzingProperty); + set => SetValue(IsAnalyzingProperty, value); } public static readonly BindableProperty ResultProperty = BindableProperty.Create(nameof(Result), typeof(IScanResult), typeof(ScannerView), default(IScanResult)); + public IScanResult Result { - get { return (IScanResult)GetValue(ResultProperty); } - set { SetValue(ResultProperty, value); } + get => (IScanResult) GetValue(ResultProperty); + set => SetValue(ResultProperty, value); } public static readonly BindableProperty ScanResultCommandProperty = - BindableProperty.Create(nameof(ScanResultCommand), typeof(ICommand), typeof(ScannerView), default(ICommand)); + BindableProperty.Create(nameof(ScanResultCommand), typeof(ICommand), typeof(ScannerView), + default(ICommand)); + public ICommand ScanResultCommand { - get { return (ICommand)GetValue(ScanResultCommandProperty); } - set { SetValue(ScanResultCommandProperty, value); } + get => (ICommand) GetValue(ScanResultCommandProperty); + set => SetValue(ScanResultCommandProperty, value); } } -} - +} \ No newline at end of file diff --git a/Source/CameraPreview/ScanningOptionsBase.cs b/Source/CameraPreview/ScanningOptionsBase.cs index 2027cd5..ea39bca 100644 --- a/Source/CameraPreview/ScanningOptionsBase.cs +++ b/Source/CameraPreview/ScanningOptionsBase.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; namespace CameraPreview { @@ -26,10 +25,7 @@ public ScanningOptionsBase() public int DelayBetweenAnalyzingFrames { get; set; } public int InitialDelayBeforeAnalyzingFrames { get; set; } - public static ScanningOptionsBase Default - { - get { return new ScanningOptionsBase(); } - } + public static ScanningOptionsBase Default => new ScanningOptionsBase(); public CameraResolution GetResolution(List availableResolutions) { @@ -45,4 +41,4 @@ public CameraResolution GetResolution(List availableResolution return r; } } -} +} \ No newline at end of file From 08048ac9fc43975b51fa1ab2a42ceb6b2d8397e8 Mon Sep 17 00:00:00 2001 From: kenyd Date: Sat, 19 Oct 2019 14:19:56 +0700 Subject: [PATCH 2/7] add default constructor --- Source/CameraPreview.Droid/CompareSizesByArea.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Source/CameraPreview.Droid/CompareSizesByArea.cs b/Source/CameraPreview.Droid/CompareSizesByArea.cs index f41655a..2498f92 100644 --- a/Source/CameraPreview.Droid/CompareSizesByArea.cs +++ b/Source/CameraPreview.Droid/CompareSizesByArea.cs @@ -5,6 +5,10 @@ namespace CameraPreview.Droid { public class CompareSizesByArea : Java.Lang.Object, IComparator { + public CompareSizesByArea() + { + } + public int Compare(Java.Lang.Object lhs, Java.Lang.Object rhs) { var lhsSize = (Size) lhs; From b6e051c6a55d139d26b548cfdc2dbd690ccab220 Mon Sep 17 00:00:00 2001 From: kenyd Date: Sat, 19 Oct 2019 14:23:42 +0700 Subject: [PATCH 3/7] better code --- Source/CameraPreview.Droid/CameraAnalyzer.cs | 3 ++- Source/CameraPreview.Droid/IDecoder.cs | 6 ++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/Source/CameraPreview.Droid/CameraAnalyzer.cs b/Source/CameraPreview.Droid/CameraAnalyzer.cs index 7e2211f..aeaa1c2 100644 --- a/Source/CameraPreview.Droid/CameraAnalyzer.cs +++ b/Source/CameraPreview.Droid/CameraAnalyzer.cs @@ -10,7 +10,8 @@ public class CameraAnalyzer private DateTime _lastPreviewAnalysis = DateTime.UtcNow; private bool _wasScanned; private bool _cameraSetup; - private IDecoder _decoder; + private readonly IDecoder _decoder; + public CameraAnalyzer(CPSurfaceView surfaceView) { _cameraController = new CameraController(surfaceView); diff --git a/Source/CameraPreview.Droid/IDecoder.cs b/Source/CameraPreview.Droid/IDecoder.cs index cb2ff5d..f975d53 100644 --- a/Source/CameraPreview.Droid/IDecoder.cs +++ b/Source/CameraPreview.Droid/IDecoder.cs @@ -6,11 +6,17 @@ namespace CameraPreview.Droid public interface IDecoder { IScanResult Decode(Bitmap image); + Func CanProcessImage { get; set; } + Func FinishProcessImage { get; set; } + Action HandleExceptionFromProcessImage { get; set; } + int ImageSizeX { get; } + int ImageSizeY { get; } + void ScanningOptionsUpdate(ScanningOptionsBase options); } } \ No newline at end of file From 12db08b373cd290a80b714b861c6c22514319a17 Mon Sep 17 00:00:00 2001 From: kenyd Date: Sat, 19 Oct 2019 20:58:34 +0700 Subject: [PATCH 4/7] no message --- Source/CameraPreview.Droid/DefaultDecoderBase.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Source/CameraPreview.Droid/DefaultDecoderBase.cs b/Source/CameraPreview.Droid/DefaultDecoderBase.cs index 884eeca..de740f4 100644 --- a/Source/CameraPreview.Droid/DefaultDecoderBase.cs +++ b/Source/CameraPreview.Droid/DefaultDecoderBase.cs @@ -6,7 +6,9 @@ namespace CameraPreview.Droid public class DefaultDecoderBase : IDecoder { public Func CanProcessImage { get; set; } + public Func FinishProcessImage { get; set; } + public Action HandleExceptionFromProcessImage { get; set; } public int ImageSizeX => 229; @@ -22,5 +24,4 @@ public virtual void ScanningOptionsUpdate(ScanningOptionsBase options) { } } -} - +} \ No newline at end of file From 3a83a580ff06ba4369e5f9d9466a5b79ac1acc6f Mon Sep 17 00:00:00 2001 From: kenyd Date: Sun, 20 Oct 2019 09:05:45 +0700 Subject: [PATCH 5/7] format code --- Source/CameraPreview.iOS/DefaultOutputRecorder.cs | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/Source/CameraPreview.iOS/DefaultOutputRecorder.cs b/Source/CameraPreview.iOS/DefaultOutputRecorder.cs index 32a2eda..0378105 100644 --- a/Source/CameraPreview.iOS/DefaultOutputRecorder.cs +++ b/Source/CameraPreview.iOS/DefaultOutputRecorder.cs @@ -17,8 +17,8 @@ public DefaultOutputRecorder(Action resultCallback) } private DateTime _lastAnalysis = DateTime.MinValue; - private volatile bool _working = false; - private volatile bool _wasScanned = false; + private volatile bool _working; + private volatile bool _wasScanned; [Export("captureOutput:didDropSampleBuffer:fromConnection:")] public override void DidDropSampleBuffer(AVCaptureOutput captureOutput, CMSampleBuffer sampleBuffer, @@ -29,7 +29,6 @@ public override void DidDropSampleBuffer(AVCaptureOutput captureOutput, CMSample public CancellationTokenSource CancelTokenSource { get; set; } = new CancellationTokenSource(); - public override void DidOutputSampleBuffer(AVCaptureOutput captureOutput, CMSampleBuffer sampleBuffer, AVCaptureConnection connection) { @@ -40,14 +39,12 @@ public override void DidOutputSampleBuffer(AVCaptureOutput captureOutput, CMSamp || _working || CancelTokenSource.IsCancellationRequested) { - if (msSinceLastPreview < scannerOptions.DelayBetweenAnalyzingFrames) Logger.Log("Too soon between frames", LogLevel.Detail); if (_wasScanned && msSinceLastPreview < scannerOptions.DelayBetweenContinuousScans) Logger.Log("Too soon since last scan", LogLevel.Detail); sampleBuffer?.Dispose(); - return; } @@ -90,4 +87,4 @@ public override void DidOutputSampleBuffer(AVCaptureOutput captureOutput, CMSamp } } } -} +} \ No newline at end of file From a754ecc0d56819ddd636a55b1d3cb2c8fa8ad741 Mon Sep 17 00:00:00 2001 From: kenyd Date: Sun, 20 Oct 2019 09:24:12 +0700 Subject: [PATCH 6/7] update TargetFrameworkVersion --- .../ZXing/ZXing.Net.Droid/ZXing.Net.Droid.csproj | 14 ++++++++------ Plugins/ZXing/ZXing.Net.Droid/ZXingDecoder.cs | 5 +++-- Plugins/ZXing/ZXing.Net.iOS/ZXing.Net.iOS.csproj | 16 +++++++++++----- .../CameraPreview.iOS/DefaultOutputRecorder.cs | 1 + 4 files changed, 23 insertions(+), 13 deletions(-) diff --git a/Plugins/ZXing/ZXing.Net.Droid/ZXing.Net.Droid.csproj b/Plugins/ZXing/ZXing.Net.Droid/ZXing.Net.Droid.csproj index 2395458..e040a06 100644 --- a/Plugins/ZXing/ZXing.Net.Droid/ZXing.Net.Droid.csproj +++ b/Plugins/ZXing/ZXing.Net.Droid/ZXing.Net.Droid.csproj @@ -1,4 +1,4 @@ - + Debug @@ -8,7 +8,7 @@ Library ZXing.Net.Droid ZXing.Net.Droid - v8.1 + v10.0 true @@ -19,7 +19,8 @@ prompt 4 None - + + true @@ -30,7 +31,8 @@ 4 true false - + + @@ -41,7 +43,7 @@ ..\..\..\packages\ZXing.Net.0.16.4\lib\MonoAndroid\zxing.monoandroid.dll - + @@ -63,6 +65,6 @@ - + \ No newline at end of file diff --git a/Plugins/ZXing/ZXing.Net.Droid/ZXingDecoder.cs b/Plugins/ZXing/ZXing.Net.Droid/ZXingDecoder.cs index c1809dd..d7b3990 100644 --- a/Plugins/ZXing/ZXing.Net.Droid/ZXingDecoder.cs +++ b/Plugins/ZXing/ZXing.Net.Droid/ZXingDecoder.cs @@ -3,13 +3,13 @@ using CameraPreview; using CameraPreview.Droid; using ZXing.Net.Xamarin.Forms; -using ZXing; namespace ZXing.Net.Droid { public class ZXingDecoder : DefaultDecoderBase { BarcodeReader _reader; + public ZXingDecoder() { _reader = new BarcodeReader(); @@ -31,6 +31,7 @@ public override IScanResult Decode(Bitmap image) result.Timestamp = res.Timestamp; result.Text = res.Text; } + PerformanceCounter.Stop(decoder, "ZXing Decoder take {0} ms."); return result; } @@ -56,4 +57,4 @@ public override void ScanningOptionsUpdate(ScanningOptionsBase options) } } } -} +} \ No newline at end of file diff --git a/Plugins/ZXing/ZXing.Net.iOS/ZXing.Net.iOS.csproj b/Plugins/ZXing/ZXing.Net.iOS/ZXing.Net.iOS.csproj index 46c8f11..d7337a3 100644 --- a/Plugins/ZXing/ZXing.Net.iOS/ZXing.Net.iOS.csproj +++ b/Plugins/ZXing/ZXing.Net.iOS/ZXing.Net.iOS.csproj @@ -1,4 +1,4 @@ - + Debug @@ -25,22 +25,26 @@ 62396 NSUrlSessionHandler false - - + + + + true pdbonly true bin\Release - + + prompt 4 iPhone Developer true SdkOnly NSUrlSessionHandler - + + true @@ -70,6 +74,8 @@ {547CB727-881C-43B7-864E-AEAC7ED5EFDC} CameraPreview.iOS + false + false diff --git a/Source/CameraPreview.iOS/DefaultOutputRecorder.cs b/Source/CameraPreview.iOS/DefaultOutputRecorder.cs index 0378105..dba6148 100644 --- a/Source/CameraPreview.iOS/DefaultOutputRecorder.cs +++ b/Source/CameraPreview.iOS/DefaultOutputRecorder.cs @@ -61,6 +61,7 @@ public override void DidOutputSampleBuffer(AVCaptureOutput captureOutput, CMSamp // Lock the base address pixelBuffer.Lock(CVPixelBufferLock.ReadOnly); // MAYBE NEEDS READ/WRITE + // https://stackoverflow.com/questions/34569750/get-pixel-value-from-cvpixelbufferref-in-swift/42303821 var result = CameraPreviewSettings.Instance.Decoder.Decode(pixelBuffer); _resultCallback?.Invoke(result); if (result.Success) From 67a70ec62f64561e9940653a184735f3d8674468 Mon Sep 17 00:00:00 2001 From: kenyd Date: Sun, 20 Oct 2019 09:27:55 +0700 Subject: [PATCH 7/7] no message --- .../CameraPreviewSettingsForZXing.cs | 5 +-- Plugins/ZXing/ZXing.Net.Droid/ZXingDecoder.cs | 2 +- .../ZXing.Net.Xamarin.Forms/ZXingOptions.cs | 6 +-- .../ZXing.Net.Xamarin.Forms/ZXingOverlay.cs | 41 +++++++++---------- .../ZXing.Net.Xamarin.Forms/ZXingResult.cs | 5 +-- .../CVPixelBufferBGRA32LuminanceSource.cs | 15 ++++--- .../CameraPreviewSettingsForZXing.cs | 5 +-- Plugins/ZXing/ZXing.Net.iOS/ZXingDecoder.cs | 12 +++--- 8 files changed, 45 insertions(+), 46 deletions(-) diff --git a/Plugins/ZXing/ZXing.Net.Droid/CameraPreviewSettingsForZXing.cs b/Plugins/ZXing/ZXing.Net.Droid/CameraPreviewSettingsForZXing.cs index a75f08f..bda8efd 100644 --- a/Plugins/ZXing/ZXing.Net.Droid/CameraPreviewSettingsForZXing.cs +++ b/Plugins/ZXing/ZXing.Net.Droid/CameraPreviewSettingsForZXing.cs @@ -1,5 +1,4 @@ -using System; -using CameraPreview.Droid; +using CameraPreview.Droid; namespace ZXing.Net.Droid { @@ -10,4 +9,4 @@ public static void Init() CameraPreviewSettings.Instance.Init(new ZXingDecoder()); } } -} +} \ No newline at end of file diff --git a/Plugins/ZXing/ZXing.Net.Droid/ZXingDecoder.cs b/Plugins/ZXing/ZXing.Net.Droid/ZXingDecoder.cs index d7b3990..b3b4b9c 100644 --- a/Plugins/ZXing/ZXing.Net.Droid/ZXingDecoder.cs +++ b/Plugins/ZXing/ZXing.Net.Droid/ZXingDecoder.cs @@ -8,7 +8,7 @@ namespace ZXing.Net.Droid { public class ZXingDecoder : DefaultDecoderBase { - BarcodeReader _reader; + private readonly BarcodeReader _reader; public ZXingDecoder() { diff --git a/Plugins/ZXing/ZXing.Net.Xamarin.Forms/ZXingOptions.cs b/Plugins/ZXing/ZXing.Net.Xamarin.Forms/ZXingOptions.cs index 722b60a..6d64d5c 100644 --- a/Plugins/ZXing/ZXing.Net.Xamarin.Forms/ZXingOptions.cs +++ b/Plugins/ZXing/ZXing.Net.Xamarin.Forms/ZXingOptions.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using CameraPreview; +using CameraPreview; namespace ZXing.Net.Xamarin.Forms { @@ -19,4 +17,4 @@ public ZXingOptions() : base() public bool? AssumeGS1 { get; set; } } -} +} \ No newline at end of file diff --git a/Plugins/ZXing/ZXing.Net.Xamarin.Forms/ZXingOverlay.cs b/Plugins/ZXing/ZXing.Net.Xamarin.Forms/ZXingOverlay.cs index b1cfc6e..131cfd9 100644 --- a/Plugins/ZXing/ZXing.Net.Xamarin.Forms/ZXingOverlay.cs +++ b/Plugins/ZXing/ZXing.Net.Xamarin.Forms/ZXingOverlay.cs @@ -1,13 +1,11 @@ -using System; -using System.Windows.Input; -using Xamarin.Forms; +using Xamarin.Forms; namespace ZXing.Net.Xamarin.Forms { public class ZXingOverlay : Grid { - Label topText; - Label botText; + private readonly Label _topText; + private readonly Label _botText; public ZXingOverlay() { @@ -16,10 +14,10 @@ public ZXingOverlay() VerticalOptions = LayoutOptions.FillAndExpand; HorizontalOptions = LayoutOptions.FillAndExpand; - RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) }); - RowDefinitions.Add(new RowDefinition { Height = new GridLength(2, GridUnitType.Star) }); - RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) }); - ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); + RowDefinitions.Add(new RowDefinition {Height = new GridLength(1, GridUnitType.Star)}); + RowDefinitions.Add(new RowDefinition {Height = new GridLength(2, GridUnitType.Star)}); + RowDefinitions.Add(new RowDefinition {Height = new GridLength(1, GridUnitType.Star)}); + ColumnDefinitions.Add(new ColumnDefinition {Width = new GridLength(1, GridUnitType.Star)}); Children.Add(new BoxView @@ -47,41 +45,42 @@ public ZXingOverlay() Opacity = 0.6, }, 0, 1); - topText = new Label + _topText = new Label { VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center, TextColor = Color.White, }; - topText.SetBinding(Label.TextProperty, new Binding(nameof(TopText))); - Children.Add(topText, 0, 0); + _topText.SetBinding(Label.TextProperty, new Binding(nameof(TopText))); + Children.Add(_topText, 0, 0); - botText = new Label + _botText = new Label { VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center, TextColor = Color.White, }; - botText.SetBinding(Label.TextProperty, new Binding(nameof(BottomText))); - Children.Add(botText, 0, 2); + _botText.SetBinding(Label.TextProperty, new Binding(nameof(BottomText))); + Children.Add(_botText, 0, 2); } public static readonly BindableProperty TopTextProperty = BindableProperty.Create(nameof(TopText), typeof(string), typeof(ZXingOverlay), string.Empty); + public string TopText { - get { return (string)GetValue(TopTextProperty); } - set { SetValue(TopTextProperty, value); } + get => (string) GetValue(TopTextProperty); + set => SetValue(TopTextProperty, value); } public static readonly BindableProperty BottomTextProperty = BindableProperty.Create(nameof(BottomText), typeof(string), typeof(ZXingOverlay), string.Empty); + public string BottomText { - get { return (string)GetValue(BottomTextProperty); } - set { SetValue(BottomTextProperty, value); } + get => (string) GetValue(BottomTextProperty); + set => SetValue(BottomTextProperty, value); } } -} - +} \ No newline at end of file diff --git a/Plugins/ZXing/ZXing.Net.Xamarin.Forms/ZXingResult.cs b/Plugins/ZXing/ZXing.Net.Xamarin.Forms/ZXingResult.cs index 8e120c6..0bb8d6b 100644 --- a/Plugins/ZXing/ZXing.Net.Xamarin.Forms/ZXingResult.cs +++ b/Plugins/ZXing/ZXing.Net.Xamarin.Forms/ZXingResult.cs @@ -1,5 +1,4 @@ -using System; -using CameraPreview; +using CameraPreview; namespace ZXing.Net.Xamarin.Forms { @@ -11,4 +10,4 @@ public class ZXingResult : IScanResult public string Text { get; set; } } -} +} \ No newline at end of file diff --git a/Plugins/ZXing/ZXing.Net.iOS/CVPixelBufferBGRA32LuminanceSource.cs b/Plugins/ZXing/ZXing.Net.iOS/CVPixelBufferBGRA32LuminanceSource.cs index 857715c..e00f432 100644 --- a/Plugins/ZXing/ZXing.Net.iOS/CVPixelBufferBGRA32LuminanceSource.cs +++ b/Plugins/ZXing/ZXing.Net.iOS/CVPixelBufferBGRA32LuminanceSource.cs @@ -1,9 +1,9 @@ -using System; -namespace ZXing.Net.iOS +namespace ZXing.Net.iOS { public class CVPixelBufferBGRA32LuminanceSource : BaseLuminanceSource { - public unsafe CVPixelBufferBGRA32LuminanceSource(byte* cvPixelByteArray, int cvPixelByteArrayLength, int width, int height) + public unsafe CVPixelBufferBGRA32LuminanceSource(byte* cvPixelByteArray, int cvPixelByteArrayLength, int width, + int height) : base(width, height) { CalculateLuminance(cvPixelByteArray, cvPixelByteArrayLength); @@ -17,15 +17,18 @@ public CVPixelBufferBGRA32LuminanceSource(byte[] luminances, int width, int heig unsafe void CalculateLuminance(byte* rgbRawBytes, int bytesLen) { - for (int rgbIndex = 0, luminanceIndex = 0; rgbIndex < bytesLen && luminanceIndex < luminances.Length; luminanceIndex++) + for (int rgbIndex = 0, luminanceIndex = 0; + rgbIndex < bytesLen && luminanceIndex < luminances.Length; + luminanceIndex++) { // Calculate luminance cheaply, favoring green. var b = rgbRawBytes[rgbIndex++]; var g = rgbRawBytes[rgbIndex++]; var r = rgbRawBytes[rgbIndex++]; var alpha = rgbRawBytes[rgbIndex++]; - var luminance = (byte)((RChannelWeight * r + GChannelWeight * g + BChannelWeight * b) >> ChannelWeight); - luminances[luminanceIndex] = (byte)(((luminance * alpha) >> 8) + (255 * (255 - alpha) >> 8)); + var luminance = + (byte) ((RChannelWeight * r + GChannelWeight * g + BChannelWeight * b) >> ChannelWeight); + luminances[luminanceIndex] = (byte) (((luminance * alpha) >> 8) + (255 * (255 - alpha) >> 8)); } } diff --git a/Plugins/ZXing/ZXing.Net.iOS/CameraPreviewSettingsForZXing.cs b/Plugins/ZXing/ZXing.Net.iOS/CameraPreviewSettingsForZXing.cs index ecb03b7..8a9bc31 100644 --- a/Plugins/ZXing/ZXing.Net.iOS/CameraPreviewSettingsForZXing.cs +++ b/Plugins/ZXing/ZXing.Net.iOS/CameraPreviewSettingsForZXing.cs @@ -1,5 +1,4 @@ -using System; -using CameraPreview.iOS; +using CameraPreview.iOS; namespace ZXing.Net.iOS { @@ -10,4 +9,4 @@ public static void Init() CameraPreviewSettings.Instance.Init(new ZXingDecoder()); } } -} +} \ No newline at end of file diff --git a/Plugins/ZXing/ZXing.Net.iOS/ZXingDecoder.cs b/Plugins/ZXing/ZXing.Net.iOS/ZXingDecoder.cs index 708a546..1703d28 100644 --- a/Plugins/ZXing/ZXing.Net.iOS/ZXingDecoder.cs +++ b/Plugins/ZXing/ZXing.Net.iOS/ZXingDecoder.cs @@ -9,6 +9,7 @@ namespace ZXing.Net.iOS public class ZXingDecoder : DefaultDecoderBase { BarcodeReader _reader; + public ZXingDecoder() : base() { _reader = new BarcodeReader(); @@ -19,10 +20,10 @@ public override IScanResult Decode(CVPixelBuffer pixelBuffer) var decoder = PerformanceCounter.Start(); unsafe { - var rawData = (byte*)pixelBuffer.BaseAddress.ToPointer(); - int rawDatalen = (int)(pixelBuffer.Height * pixelBuffer.Width * 4); - int width = (int)pixelBuffer.Width; - int height = (int)pixelBuffer.Height; + var rawData = (byte*) pixelBuffer.BaseAddress.ToPointer(); + int rawDatalen = (int) (pixelBuffer.Height * pixelBuffer.Width * 4); + int width = (int) pixelBuffer.Width; + int height = (int) pixelBuffer.Height; var luminanceSource = new CVPixelBufferBGRA32LuminanceSource(rawData, rawDatalen, width, height); var res = _reader.Decode(luminanceSource); var result = new ZXingResult(); @@ -37,6 +38,7 @@ public override IScanResult Decode(CVPixelBuffer pixelBuffer) result.Timestamp = res.Timestamp; result.Text = res.Text; } + PerformanceCounter.Stop(decoder, "ZXing Decoder take {0} ms."); return result; } @@ -63,4 +65,4 @@ public override void ScanningOptionsUpdate(ScanningOptionsBase options) } } } -} +} \ No newline at end of file