Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
kartikaysharma01 committed Mar 7, 2021
1 parent f5c9506 commit 99fd9fe
Show file tree
Hide file tree
Showing 16 changed files with 120 additions and 146 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -651,7 +651,7 @@ class ContinuousScanActivity : AppCompatActivity() {
}
R.id.troubleScanning -> {
hideAllViews()
hintBarcodeDisp!!.dispose()
hintBarcodeDisp?.dispose()
binding.quickView.setOnClickListener(null)
binding.quickViewSearchByBarcode.text = null
binding.quickViewSearchByBarcode.visibility = View.VISIBLE
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

package openfoodfacts.github.scrachx.openfood.camera

import android.animation.AnimatorSet
Expand All @@ -25,46 +24,53 @@ class CameraReticleAnimator(graphicOverlay: GraphicOverlay) {
private val animatorSet: AnimatorSet

init {
val rippleFadeInAnimator = ValueAnimator.ofFloat(0f, 1f).setDuration(DURATION_RIPPLE_FADE_IN_MS)
rippleFadeInAnimator.addUpdateListener { animation ->
rippleAlphaScale = animation.animatedValue as Float
graphicOverlay.postInvalidate()
val rippleFadeInAnimator = ValueAnimator.ofFloat(0f, 1f).setDuration(DURATION_RIPPLE_FADE_IN_MS).apply {
addUpdateListener { animation ->
rippleAlphaScale = animation.animatedValue as Float
graphicOverlay.postInvalidate()
}
}

val rippleFadeOutAnimator = ValueAnimator.ofFloat(1f, 0f).setDuration(DURATION_RIPPLE_FADE_OUT_MS).apply {
startDelay = START_DELAY_RIPPLE_FADE_OUT_MS
addUpdateListener { animation ->
rippleAlphaScale = animation.animatedValue as Float
graphicOverlay.postInvalidate()
}
}

val rippleExpandAnimator = ValueAnimator.ofFloat(0f, 1f).setDuration(DURATION_RIPPLE_EXPAND_MS).apply {
startDelay = START_DELAY_RIPPLE_EXPAND_MS
interpolator = FastOutSlowInInterpolator()
addUpdateListener { animation ->
rippleSizeScale = animation.animatedValue as Float
graphicOverlay.postInvalidate()
}
}

val rippleFadeOutAnimator = ValueAnimator.ofFloat(1f, 0f).setDuration(DURATION_RIPPLE_FADE_OUT_MS)
rippleFadeOutAnimator.startDelay = START_DELAY_RIPPLE_FADE_OUT_MS
rippleFadeOutAnimator.addUpdateListener { animation ->
rippleAlphaScale = animation.animatedValue as Float
graphicOverlay.postInvalidate()
val rippleStrokeWidthShrinkAnimator = ValueAnimator.ofFloat(1f, 0.5f).setDuration(DURATION_RIPPLE_STROKE_WIDTH_SHRINK_MS).apply {
startDelay = START_DELAY_RIPPLE_STROKE_WIDTH_SHRINK_MS
interpolator = FastOutSlowInInterpolator()
addUpdateListener { animation ->
rippleStrokeWidthScale = animation.animatedValue as Float
graphicOverlay.postInvalidate()
}
}

val rippleExpandAnimator = ValueAnimator.ofFloat(0f, 1f).setDuration(DURATION_RIPPLE_EXPAND_MS)
rippleExpandAnimator.startDelay = START_DELAY_RIPPLE_EXPAND_MS
rippleExpandAnimator.interpolator = FastOutSlowInInterpolator()
rippleExpandAnimator.addUpdateListener { animation ->
rippleSizeScale = animation.animatedValue as Float
graphicOverlay.postInvalidate()
val fakeAnimatorForRestartDelay = ValueAnimator.ofInt(0, 0).setDuration(DURATION_RESTART_DORMANCY_MS).apply {
startDelay = START_DELAY_RESTART_DORMANCY_MS
}

val rippleStrokeWidthShrinkAnimator =
ValueAnimator.ofFloat(1f, 0.5f).setDuration(DURATION_RIPPLE_STROKE_WIDTH_SHRINK_MS)
rippleStrokeWidthShrinkAnimator.startDelay = START_DELAY_RIPPLE_STROKE_WIDTH_SHRINK_MS
rippleStrokeWidthShrinkAnimator.interpolator = FastOutSlowInInterpolator()
rippleStrokeWidthShrinkAnimator.addUpdateListener { animation ->
rippleStrokeWidthScale = animation.animatedValue as Float
graphicOverlay.postInvalidate()
animatorSet = AnimatorSet().apply {
playTogether(
rippleFadeInAnimator,
rippleFadeOutAnimator,
rippleExpandAnimator,
rippleStrokeWidthShrinkAnimator,
fakeAnimatorForRestartDelay
)
}

val fakeAnimatorForRestartDelay = ValueAnimator.ofInt(0, 0).setDuration(DURATION_RESTART_DORMANCY_MS)
fakeAnimatorForRestartDelay.startDelay = START_DELAY_RESTART_DORMANCY_MS
animatorSet = AnimatorSet()
animatorSet.playTogether(
rippleFadeInAnimator,
rippleFadeOutAnimator,
rippleExpandAnimator,
rippleStrokeWidthShrinkAnimator,
fakeAnimatorForRestartDelay
)
}

fun start() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -153,10 +153,10 @@ class CameraSource(private val graphicOverlay: GraphicOverlay) {

fun updateFlashMode(flashActive: Boolean) {
val parameters = camera?.parameters
if(flashActive && requestedCameraId == CAMERA_FACING_BACK) {
if (flashActive && requestedCameraId == CAMERA_FACING_BACK) {
requestedFlashState = true
parameters?.flashMode = Parameters.FLASH_MODE_TORCH
} else{
} else {
requestedFlashState = false
parameters?.flashMode = Parameters.FLASH_MODE_OFF
}
Expand All @@ -165,10 +165,10 @@ class CameraSource(private val graphicOverlay: GraphicOverlay) {

fun setFocusMode(autoFocusActive: Boolean) {
val parameters = camera?.parameters
if(autoFocusActive) {
if (autoFocusActive) {
requestedFocusState = true
Log.i(TAG,"Supported focus mode = " + parameters?.supportedFocusModes)
if(parameters?.supportedFocusModes?.contains(Parameters.FOCUS_MODE_CONTINUOUS_VIDEO) == true) {
Log.i(TAG, "Supported focus mode = " + parameters?.supportedFocusModes)
if (parameters?.supportedFocusModes?.contains(Parameters.FOCUS_MODE_CONTINUOUS_VIDEO) == true) {
parameters.focusMode = Parameters.FOCUS_MODE_CONTINUOUS_VIDEO
} else {
Log.i(TAG, "Camera continuous mode is not supported on this device.")
Expand All @@ -180,12 +180,12 @@ class CameraSource(private val graphicOverlay: GraphicOverlay) {
camera?.parameters = parameters
}

fun switchCamera() : Camera {
fun switchCamera(): Camera {
camera?.release()
requestedCameraId =
if(requestedCameraId == CAMERA_FACING_BACK){
if (requestedCameraId == CAMERA_FACING_BACK) {
CAMERA_FACING_FRONT
} else{
} else {
CAMERA_FACING_BACK
}
return createCamera()
Expand All @@ -205,20 +205,20 @@ class CameraSource(private val graphicOverlay: GraphicOverlay) {
setRotation(camera, parameters)

val previewFpsRange = selectPreviewFpsRange(camera)
?: throw IOException("Could not find suitable preview frames per second range.")
?: throw IOException("Could not find suitable preview frames per second range.")
parameters.setPreviewFpsRange(
previewFpsRange[Parameters.PREVIEW_FPS_MIN_INDEX],
previewFpsRange[Parameters.PREVIEW_FPS_MAX_INDEX]
previewFpsRange[Parameters.PREVIEW_FPS_MIN_INDEX],
previewFpsRange[Parameters.PREVIEW_FPS_MAX_INDEX]
)

parameters.previewFormat = IMAGE_FORMAT

if(requestedFlashState && requestedCameraId == CAMERA_FACING_BACK){
if (requestedFlashState && requestedCameraId == CAMERA_FACING_BACK) {
parameters.flashMode = Parameters.FLASH_MODE_TORCH
}

if(requestedFocusState){
if(parameters.supportedFocusModes.contains(Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
if (requestedFocusState) {
if (parameters.supportedFocusModes.contains(Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
parameters.focusMode = Parameters.FOCUS_MODE_CONTINUOUS_VIDEO
} else {
Log.i(TAG, "Camera continuous mode is not supported on this device.")
Expand Down Expand Up @@ -255,12 +255,12 @@ class CameraSource(private val graphicOverlay: GraphicOverlay) {

// Camera preview size is based on the landscape mode, so we need to also use the aspect
// ration of display in the same mode for comparison.
val displayAspectRatioInLandscape: Float =
if (isPortraitMode(graphicOverlay.context)) {
graphicOverlay.height.toFloat() / graphicOverlay.width
} else {
graphicOverlay.width.toFloat() / graphicOverlay.height
}
val displayAspectRatioInLandscape: Float =
if (isPortraitMode(graphicOverlay.context)) {
graphicOverlay.height.toFloat() / graphicOverlay.width
} else {
graphicOverlay.width.toFloat() / graphicOverlay.height
}

val sizePair: CameraSizePair = selectSizePair(camera, displayAspectRatioInLandscape)
?: throw IOException("Could not find suitable preview size.")
Expand Down Expand Up @@ -445,8 +445,6 @@ class CameraSource(private val graphicOverlay: GraphicOverlay) {
}




companion object {

const val CAMERA_FACING_BACK = CameraInfo.CAMERA_FACING_BACK
Expand Down Expand Up @@ -515,8 +513,8 @@ class CameraSource(private val graphicOverlay: GraphicOverlay) {
for (sizePair in validPreviewSizes) {
val size = sizePair.preview
val diff =
abs(size.width - DEFAULT_REQUESTED_CAMERA_PREVIEW_WIDTH) +
abs(size.height - DEFAULT_REQUESTED_CAMERA_PREVIEW_HEIGHT)
abs(size.width - DEFAULT_REQUESTED_CAMERA_PREVIEW_WIDTH) +
abs(size.height - DEFAULT_REQUESTED_CAMERA_PREVIEW_HEIGHT)
if (diff < minDiff) {
selectedPair = sizePair
minDiff = diff
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

package openfoodfacts.github.scrachx.openfood.camera

import android.content.Context
Expand Down Expand Up @@ -62,6 +61,20 @@ class CameraSourcePreview(context: Context, attrs: AttributeSet) : FrameLayout(c
}
}

/**
* Called from layout when this view should
* assign a size and position to each of its children.
*
* Derived classes with children should override
* this method and call layout on each of
* their children.
*
* @param changed This is a new size or position for this view
* @param left Left position, relative to parent
* @param top Top position, relative to parent
* @param right Right position, relative to parent
* @param bottom Bottom position, relative to parent
*/
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
val layoutWidth = right - left
val layoutHeight = bottom - top
Expand All @@ -81,7 +94,7 @@ class CameraSourcePreview(context: Context, attrs: AttributeSet) : FrameLayout(c
}

// Match the width of the child view to its parent.
if (layoutWidth*previewHeight <= layoutHeight*previewWidth) {
if (layoutWidth * previewHeight <= layoutHeight * previewWidth) {
val scaledChildWidth = previewWidth * layoutHeight / previewHeight

for (i in 0 until childCount) {
Expand All @@ -100,7 +113,7 @@ class CameraSourcePreview(context: Context, attrs: AttributeSet) : FrameLayout(c
try {
startIfReady()
} catch (e: IOException) {
Log.e(TAG, "Could not start camera source.", e)
Log.e(LOG_TAG, "Could not start camera source.", e)
}
}

Expand All @@ -110,19 +123,18 @@ class CameraSourcePreview(context: Context, attrs: AttributeSet) : FrameLayout(c
try {
startIfReady()
} catch (e: IOException) {
Log.e(TAG, "Could not start camera source.", e)
Log.e(LOG_TAG, "Could not start camera source.", e)
}
}

override fun surfaceDestroyed(surface: SurfaceHolder) {
surfaceAvailable = false
}

override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
}
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) = Unit
}

companion object {
private const val TAG = "CameraSourcePreview"
private const val LOG_TAG = "CameraSourcePreview"
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@

package openfoodfacts.github.scrachx.openfood.camera

/**
* Metadata info of a camera frame.
*/
class FrameMetadata(val width: Int, val height: Int, val rotation: Int)
data class FrameMetadata(val width: Int, val height: Int, val rotation: Int)
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

package openfoodfacts.github.scrachx.openfood.camera

import java.nio.ByteBuffer
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

package openfoodfacts.github.scrachx.openfood.camera

import android.os.SystemClock
Expand All @@ -8,14 +7,11 @@ import com.google.android.gms.tasks.OnFailureListener
import com.google.android.gms.tasks.Task
import com.google.android.gms.tasks.TaskExecutors
import com.google.mlkit.vision.common.InputImage
import openfoodfacts.github.scrachx.openfood.utils.CameraInputInfo
import openfoodfacts.github.scrachx.openfood.utils.InputInfo
import openfoodfacts.github.scrachx.openfood.utils.ScopedExecutor
import java.nio.ByteBuffer

/** Abstract base class of [FrameProcessor]. */
abstract class
FrameProcessorBase<T> : FrameProcessor {
abstract class FrameProcessorBase<T> : FrameProcessor {

// To keep the latest frame and its metadata.
@GuardedBy("this")
Expand All @@ -35,9 +31,9 @@ FrameProcessorBase<T> : FrameProcessor {

@Synchronized
override fun process(
data: ByteBuffer,
frameMetadata: FrameMetadata,
graphicOverlay: GraphicOverlay
data: ByteBuffer,
frameMetadata: FrameMetadata,
graphicOverlay: GraphicOverlay
) {
latestFrame = data
latestFrameMetaData = frameMetadata
Expand All @@ -56,20 +52,20 @@ FrameProcessorBase<T> : FrameProcessor {
val frame = processingFrame ?: return
val frameMetaData = processingFrameMetaData ?: return
val image = InputImage.fromByteBuffer(
frame,
frameMetaData.width,
frameMetaData.height,
frameMetaData.rotation,
InputImage.IMAGE_FORMAT_NV21
frame,
frameMetaData.width,
frameMetaData.height,
frameMetaData.rotation,
InputImage.IMAGE_FORMAT_NV21
)
val startMs = SystemClock.elapsedRealtime()
detectInImage(image)
.addOnSuccessListener(executor) { results: T ->
Log.d(TAG, "Latency is: ${SystemClock.elapsedRealtime() - startMs}")
this@FrameProcessorBase.onSuccess(CameraInputInfo(frame, frameMetaData), results, graphicOverlay)
processLatestFrame(graphicOverlay)
}
.addOnFailureListener(executor) { OnFailureListener { this@FrameProcessorBase.onFailure(it) } }
.addOnSuccessListener(executor) { results: T ->
Log.d(LOG_TAG, "Latency is: ${SystemClock.elapsedRealtime() - startMs}")
this@FrameProcessorBase.onSuccess(results, graphicOverlay)
processLatestFrame(graphicOverlay)
}
.addOnFailureListener(executor) { OnFailureListener { this@FrameProcessorBase.onFailure(it) } }
}

override fun stop() {
Expand All @@ -82,14 +78,13 @@ FrameProcessorBase<T> : FrameProcessor {
* Be called when the detection succeeds.
*/
protected abstract fun onSuccess(
inputInfo: InputInfo,
results: T,
graphicOverlay: GraphicOverlay
)

protected abstract fun onFailure(e: Exception)

companion object {
private const val TAG = "FrameProcessorBase"
private const val LOG_TAG = "FrameProcessorBase"
}
}
Loading

0 comments on commit 99fd9fe

Please sign in to comment.