-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStoneCameraViewModel.kt
More file actions
504 lines (404 loc) · 17.3 KB
/
StoneCameraViewModel.kt
File metadata and controls
504 lines (404 loc) · 17.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
// StoneCameraViewModel.kt
package co.stonephone.stonecamera
import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.Context
import android.content.SharedPreferences
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CameraManager
import android.net.Uri
import android.util.Log
import android.view.MotionEvent
import androidx.annotation.OptIn
import androidx.camera.core.*
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.video.Quality
import androidx.camera.video.QualitySelector
import androidx.camera.video.Recorder
import androidx.camera.video.Recording
import androidx.camera.video.VideoCapture
import androidx.camera.view.PreviewView
import androidx.compose.runtime.*
import androidx.compose.runtime.snapshots.SnapshotStateMap
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import co.stonephone.stonecamera.plugins.IPlugin
import co.stonephone.stonecamera.plugins.PluginSetting
import co.stonephone.stonecamera.plugins.PluginUseCase
import co.stonephone.stonecamera.utils.StoneCameraInfo
import co.stonephone.stonecamera.utils.Translatable
import co.stonephone.stonecamera.utils.TranslatableString
import co.stonephone.stonecamera.utils.createCameraSelectorForId
import co.stonephone.stonecamera.utils.i18n
import co.stonephone.stonecamera.utils.selectCameraForStepZoomLevel
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.launch
import java.util.concurrent.Executors
@Suppress("UNCHECKED_CAST")
class StoneCameraViewModel(
context: Context,
private val registeredPlugins: List<IPlugin>
) :
ViewModel() {
private val prefs: SharedPreferences =
context.getSharedPreferences("stone_camera_prefs", Context.MODE_PRIVATE)
private val cameraExecutor = Executors.newSingleThreadExecutor()
//--------------------------------------------------------------------------------
// Mutable state that drives the UI
//--------------------------------------------------------------------------------
private var _previewView: PreviewView? by mutableStateOf(null)
val previewView: PreviewView? get() = _previewView
private var _cameraProvider: ProcessCameraProvider? = null
val cameraProvider: ProcessCameraProvider? get() = _cameraProvider
private var lifecycleOwner: LifecycleOwner? = null
var camera: Camera? by mutableStateOf(null)
private set
private var _selectedCameraId: String? = null
var facing by mutableStateOf(CameraSelector.LENS_FACING_BACK)
private set
var isRecording by mutableStateOf(false)
private set
var isPaused by mutableStateOf(false)
private set
@Translatable
var selectedMode by mutableStateOf("photo".i18n())
private set
private val _plugins = mutableListOf<IPlugin>()
val plugins: List<IPlugin> get() = _plugins
var pluginSettings: List<PluginSetting> = mutableListOf()
// Mutable map to hold observable settings
var settings: SnapshotStateMap<String, Any?> = mutableStateMapOf()
private val previewViewTouchHandlers = mutableListOf<(MotionEvent) -> Boolean>()
fun registerTouchHandler(handler: (MotionEvent) -> Boolean) {
previewViewTouchHandlers.add(handler)
}
fun unregisterTouchHandler(handler: (MotionEvent) -> Boolean) {
previewViewTouchHandlers.remove(handler)
}
// This list is loaded/updated externally (from the composable) once we have a context,
// or you can do it in the init block if you don’t need context changes.
var cameras: List<StoneCameraInfo> by mutableStateOf(emptyList())
private set
// The filtered list of cameras (facing)
// Update whenever `facing` changes or `cameras` changes
var facingCameras by mutableStateOf(emptyList<StoneCameraInfo>())
private set
//--------------------------------------------------------------------------------
// Core CameraX use-cases (built once and shared)
//--------------------------------------------------------------------------------
var preview: Preview = createPreview()
var imageCapture by mutableStateOf(createImageCapture())
var imageAnalysis by mutableStateOf(createImageAnalysis())
val recorder: Recorder = Recorder.Builder()
.setQualitySelector(QualitySelector.from(Quality.HD))
.build()
val videoCapture: VideoCapture<Recorder> = VideoCapture.withOutput(recorder)
//--------------------------------------------------------------------------------
// Init
//--------------------------------------------------------------------------------
init {
// Some settings affect use-cases, e.g. aspect ratio
pluginSettings = registeredPlugins.flatMap { it.settings(this) }
pluginSettings.forEach { setting ->
settings[setting.key] = getPluginSetting(setting.key)
}
// Rebuild use-cases to match our persisted prefs
recreateUseCases()
}
//--------------------------------------------------------------------------------
// Public methods to manipulate the above states
//--------------------------------------------------------------------------------
fun onCameraProvider(provider: ProcessCameraProvider) {
_cameraProvider = provider
bindUseCases()
}
fun onLifecycleOwner(owner: LifecycleOwner) {
lifecycleOwner = owner
bindUseCases()
}
fun onPreviewView(view: PreviewView) {
_previewView = view
bindUseCases()
}
@SuppressLint("ClickableViewAccessibility")
private fun initializePlugins() {
_plugins.clear() // Clear any previously initialized plugins
previewView?.setOnTouchListener { _, event ->
previewViewTouchHandlers.forEach { handler ->
handler(event)
}
true // If no handler consumes the event
}
registeredPlugins.forEach { plugin ->
plugin.initialize(this) // Initialize the plugin
_plugins.add(plugin) // Add to the initialized plugins list
}
pluginSettings = registeredPlugins.flatMap { it.settings(this) }
pluginSettings.forEach { setting ->
settings[setting.key] = getPluginSetting(setting.key)
}
}
fun <T> getPluginSetting(settingKey: String): T? {
val setting = pluginSettings.find { it.key == settingKey } ?: return null
val defaultValue = setting.defaultValue
@Suppress("UNCHECKED_CAST")
return when (defaultValue) {
is TranslatableString -> prefs.getString(settingKey, defaultValue.resolve()) as? T
is Float -> prefs.getFloat(settingKey, defaultValue) as? T
else -> null
}
}
// Retrieve a setting with automatic recomposition support
fun <T> getSetting(settingKey: String): T? {
val _value = settings[settingKey]
val value = when (_value) {
is TranslatableString -> _value
is String -> _value.i18n()
is Float -> prefs.getFloat(settingKey, _value)
else -> null
}
@Suppress("UNCHECKED_CAST")
return value as? T
}
// Update a setting and notify observers
fun setSetting(settingKey: String, value: Any?) {
val setting = pluginSettings.find { it.key == settingKey } ?: return
when (setting) {
is PluginSetting.EnumSetting -> {
prefs.edit().putString(settingKey, (value as TranslatableString).raw).apply()
}
is PluginSetting.ScalarSetting -> {
prefs.edit().putFloat(settingKey, value as Float).apply()
}
is PluginSetting.CustomSetting -> {
prefs.edit().putString(settingKey, value as String).apply()
}
}
// Update the observable state map
settings[settingKey] = value
setting.onChange(this, value)
}
fun loadCameras(allCameras: List<StoneCameraInfo>) {
cameras = allCameras
// Update facingCameras to match the current 'facing'
updateFacingCameras()
}
fun setSelectedCamera(cameraId: String) {
if (cameraId != _selectedCameraId) {
_selectedCameraId = cameraId
bindUseCases()
}
}
fun toggleCameraFacing() {
val newFacing = if (facing == CameraSelector.LENS_FACING_BACK) {
CameraSelector.LENS_FACING_FRONT
} else {
CameraSelector.LENS_FACING_BACK
}
facing = newFacing
updateFacingCameras()
}
private fun updateFacingCameras() {
facingCameras = cameras.filter { it.lensFacing == facing }
// Optionally reset the cameraId and zoom
if (facingCameras.isNotEmpty()) {
// pick the default (zoom=1.0)
val (newCam, _) = selectCameraForStepZoomLevel(1f, facingCameras)
setSelectedCamera(newCam.cameraId)
}
}
/**
* Switch between Photo and Video modes.
*/
fun selectMode(mode: TranslatableString) {
plugins.forEach {
it.onModeSelected(this, selectedMode, mode)
}
selectedMode = mode
bindUseCases()
}
fun capturePhoto() {
StoneCameraAppHelpers.capturePhoto(this, imageCapture)
}
fun beforeCapturePhoto(contentValues: ContentValues): ContentValues {
return plugins.fold(contentValues) { cv, plugin ->
plugin.beforeCapturePhoto(this, cv)
}
}
fun onCaptureProcessProgressed(progress: Int) {
plugins.forEach { it.onCaptureProcessProgressed(this, progress) }
}
fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
plugins.forEach { it.onImageSaved(this, outputFileResults) }
}
fun onCaptureStarted() {
plugins.forEach { it.onCaptureStarted(this) }
}
//-----------------W---------------------------------------------------------------
// Recording logic
//--------------------------------------------------------------------------------
private var currentRecording: Recording? = null
fun startRecording(
videoCapture: VideoCapture<Recorder>,
onVideoSaved: (Uri) -> Unit
) {
isRecording = true
currentRecording = StoneCameraAppHelpers.startRecording(
videoCapture = videoCapture,
onVideoSaved = { uri ->
isRecording = false
onVideoSaved(uri)
}
)
}
fun stopRecording() {
currentRecording?.stop()
isRecording = false
}
fun pauseRecording() {
currentRecording?.pause()
isPaused = true
}
fun resumeRecording() {
currentRecording?.resume()
isPaused = false
}
/**
* Adjust the brightness of the camera preview and captured images.
* @param brightnessLevel A value between -1.0 (darkest) and 1.0 (brightest).
*/
fun setBrightness(brightnessLevel: Float) {
val clampedBrightness = brightnessLevel.coerceIn(-1.0f, 1.0f)
camera?.cameraControl?.setExposureCompensationIndex(
calculateExposureCompensationIndex(clampedBrightness)
)
}
/**
* Helper to map brightness level (-1.0 to 1.0) to CameraX exposure compensation index.
*/
private fun calculateExposureCompensationIndex(brightnessLevel: Float): Int {
val exposureRange = camera?.cameraInfo?.exposureState?.exposureCompensationRange ?: return 0
val maxIndex = exposureRange.upper
val minIndex = exposureRange.lower
// Map brightness level to exposure index range
return ((brightnessLevel + 1.0f) / 2.0f * (maxIndex - minIndex) + minIndex).toInt()
}
private fun bindUseCases() {
// TODO consider a job that can be interrupted?
// These dependencies load in asynchronously, and can be destroyed & re-created at various points (e.g. rotating)
if (previewView == null || _cameraProvider == null || lifecycleOwner == null || _selectedCameraId == null) return
else {
try {
preview.surfaceProvider = previewView!!.surfaceProvider
val cameraSelector = createCameraSelectorForId(_selectedCameraId!!)
val manager = MyApplication.getAppContext()
.getSystemService(Context.CAMERA_SERVICE) as CameraManager
val chars = manager.getCameraCharacteristics(_selectedCameraId!!)
val level = chars.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL)
val numConcurrentUseCases = when (level) {
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY -> 1
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED -> 2
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_FULL -> 3
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_3 -> 3
else -> 1
}
previewViewTouchHandlers.clear()
_cameraProvider!!.unbindAll()
val selectedModePlugin = plugins.find { it.modeLabel == selectedMode }
val requiredUseCases: List<PluginUseCase> =
selectedModePlugin?.modeUseCases ?: emptyList()
// All use-cases (including not needed by selected plugin), but retaining the order from the selected plugin
val prioritisedUseCases =
requiredUseCases + PluginUseCase.entries.filter { it !in requiredUseCases }
// TODO tell plugins if only some use-cases are available
val availableUseCases = prioritisedUseCases.take(numConcurrentUseCases)
val useCases = availableUseCases.map { useCase ->
when (useCase) {
PluginUseCase.PHOTO -> imageCapture
PluginUseCase.ANALYSIS -> imageAnalysis
PluginUseCase.VIDEO -> videoCapture
}
}
camera = _cameraProvider!!.bindToLifecycle(
lifecycleOwner!!,
cameraSelector,
preview,
*useCases.toTypedArray()
)
initializePlugins()
_previewView = plugins.fold(previewView!!) { v, plugin ->
plugin.onPreviewView(this, v)
}
} catch (e: Exception) {
// Handle binding errors
e.printStackTrace()
}
}
}
fun recreateUseCases() {
preview = createPreview()
imageCapture = createImageCapture()
imageAnalysis = createImageAnalysis()
// TODO videoCapture
this.bindUseCases()
}
fun createPreview(): Preview {
return plugins.fold(Preview.Builder()) { builder, plugin ->
plugin.onPreview(this, builder)
}.build()
}
fun createImageCapture(): ImageCapture {
return plugins.fold(ImageCapture.Builder()) { builder, plugin ->
plugin.onImageCapture(this, builder)
}.build()
}
@OptIn(ExperimentalGetImage::class)
fun createImageAnalysis(): ImageAnalysis {
val analysis = ImageAnalysis.Builder()
.setBackpressureStrategy(ImageAnalysis.STRATEGY_BLOCK_PRODUCER)
.build()
.also {
it.setAnalyzer(cameraExecutor, ImageAnalysis.Analyzer { imageProxy ->
val inputImage = imageProxy.image ?: return@Analyzer
// Create a list to store the work objects
val workList = mutableListOf<CompletableDeferred<Unit>>()
val analysisPlugins = plugins.filter { it.onImageAnalysis != null }
// Dispatch work to each plugin
for (plugin in analysisPlugins) {
val work = plugin.onImageAnalysis!!(this, imageProxy, inputImage)
workList.add(work)
}
// Use coroutines to run the plugins in parallel and wait for all to complete
CoroutineScope(Dispatchers.IO).launch {
try {
// Await all work to finish
workList.awaitAll()
} catch (e: Exception) {
Log.e("Analyzer", "Error in one or more plugins", e)
} finally {
// Close the ImageProxy after all plugins are done
imageProxy.close()
}
}
})
}
return analysis;
}
}
class StoneCameraViewModelFactory(
private val context: Context,
private val lifecycleOwner: LifecycleOwner,
private val plugins: List<IPlugin>
) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(StoneCameraViewModel::class.java)) {
return StoneCameraViewModel(context, plugins) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}