forked from android/camera-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CaptureFragment.kt
576 lines (521 loc) · 23.6 KB
/
CaptureFragment.kt
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
/**
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Simple app to demonstrate CameraX Video capturing with Recorder ( to local files ), with the
* following simple control follow:
* - user starts capture.
* - this app disables all UI selections.
* - this app enables capture run-time UI (pause/resume/stop).
* - user controls recording with run-time UI, eventually tap "stop" to end.
* - this app informs CameraX recording to stop with recording.stop() (or recording.close()).
* - CameraX notify this app that the recording is indeed stopped, with the Finalize event.
* - this app starts VideoViewer fragment to view the captured result.
*/
package com.example.android.camerax.video.fragments
import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.res.Configuration
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CaptureRequest
import java.text.SimpleDateFormat
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.camera.camera2.interop.Camera2CameraControl
import androidx.camera.camera2.interop.Camera2CameraInfo
import androidx.camera.camera2.interop.CaptureRequestOptions
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavController
import androidx.navigation.Navigation
import com.example.android.camerax.video.R
import com.example.android.camerax.video.databinding.FragmentCaptureBinding
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.core.CameraSelector
import androidx.camera.core.Preview
import androidx.camera.video.*
import androidx.concurrent.futures.await
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.core.util.Consumer
import androidx.core.view.updateLayoutParams
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.whenCreated
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.android.camera.utils.GenericListAdapter
import com.example.android.camerax.video.extensions.getAspectRatio
import com.example.android.camerax.video.extensions.getAspectRatioString
import com.example.android.camerax.video.extensions.getNameString
import kotlinx.coroutines.*
import java.util.*
@SuppressLint("UnsafeOptInUsageError")
class CaptureFragment : Fragment() {
// UI with ViewBinding
private var _captureViewBinding: FragmentCaptureBinding? = null
private val captureViewBinding get() = _captureViewBinding!!
private val captureLiveStatus = MutableLiveData<String>()
/** Host's navigation controller */
private val navController: NavController by lazy {
Navigation.findNavController(requireActivity(), R.id.fragment_container)
}
private val cameraCapabilities = mutableListOf<CameraCapability>()
private lateinit var videoCapture: VideoCapture<Recorder>
private var currentRecording: Recording? = null
private lateinit var recordingState:VideoRecordEvent
// Camera UI states and inputs
enum class UiState {
IDLE, // Not recording, all UI controls are active.
RECORDING, // Camera is recording, only display Pause/Resume & Stop button.
FINALIZED, // Recording just completes, disable all RECORDING UI controls.
RECOVERY // For future use.
}
private var cameraIndex = 0
private var qualityIndex = DEFAULT_QUALITY_IDX
private var audioEnabled = false
private val mainThreadExecutor by lazy { ContextCompat.getMainExecutor(requireContext()) }
private var enumerationDeferred:Deferred<Unit>? = null
// main cameraX capture functions
/**
* Always bind preview + video capture use case combinations in this sample
* (VideoCapture can work on its own). The function should always execute on
* the main thread.
*/
private suspend fun bindCaptureUsecase() {
val cameraProvider = ProcessCameraProvider.getInstance(requireContext()).await()
val cameraSelector = getCameraSelector(cameraIndex)
// create the user required QualitySelector (video resolution): we know this is
// supported, a valid qualitySelector will be created.
val quality = cameraCapabilities[cameraIndex].qualities[qualityIndex]
val qualitySelector = QualitySelector.from(quality)
captureViewBinding.previewView.updateLayoutParams<ConstraintLayout.LayoutParams> {
val orientation = this@CaptureFragment.resources.configuration.orientation
dimensionRatio = quality.getAspectRatioString(quality,
(orientation == Configuration.ORIENTATION_PORTRAIT))
}
val preview = Preview.Builder()
.setTargetAspectRatio(quality.getAspectRatio(quality))
.build().apply {
setSurfaceProvider(captureViewBinding.previewView.surfaceProvider)
}
// build a recorder, which can:
// - record video/audio to MediaStore(only shown here), File, ParcelFileDescriptor
// - be used create recording(s) (the recording performs recording)
val recorder = Recorder.Builder()
.setQualitySelector(qualitySelector)
.build()
videoCapture = VideoCapture.withOutput(recorder)
try {
cameraProvider.unbindAll()
val camera = cameraProvider.bindToLifecycle(
viewLifecycleOwner,
cameraSelector,
videoCapture,
preview
)
val control = camera.cameraControl
val camControl = Camera2CameraControl.from(control)
val options = CaptureRequestOptions.Builder()
.setCaptureRequestOption(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_OFF)
.setCaptureRequestOption(CaptureRequest.SENSOR_SENSITIVITY, 3368)
.setCaptureRequestOption(CaptureRequest.SENSOR_EXPOSURE_TIME, 38860 * 100)
.build()
camControl.captureRequestOptions = options
} catch (exc: Exception) {
// we are on main thread, let's reset the controls on the UI.
Log.e(TAG, "Use case binding failed", exc)
resetUIandState("bindToLifecycle failed: $exc")
}
enableUI(true)
}
/**
* Kick start the video recording
* - config Recorder to capture to MediaStoreOutput
* - register RecordEvent Listener
* - apply audio request from user
* - start recording!
* After this function, user could start/pause/resume/stop recording and application listens
* to VideoRecordEvent for the current recording status.
*/
@SuppressLint("MissingPermission")
private fun startRecording() {
// create MediaStoreOutputOptions for our recorder: resulting our recording!
val name = "CameraX-recording-" +
SimpleDateFormat(FILENAME_FORMAT, Locale.US)
.format(System.currentTimeMillis()) + ".mp4"
val contentValues = ContentValues().apply {
put(MediaStore.Video.Media.DISPLAY_NAME, name)
}
val mediaStoreOutput = MediaStoreOutputOptions.Builder(
requireActivity().contentResolver,
MediaStore.Video.Media.EXTERNAL_CONTENT_URI)
.setContentValues(contentValues)
.build()
// configure Recorder and Start recording to the mediaStoreOutput.
currentRecording = videoCapture.output
.prepareRecording(requireActivity(), mediaStoreOutput)
.apply { if (audioEnabled) withAudioEnabled() }
.start(mainThreadExecutor, captureListener)
Log.i(TAG, "Recording started")
}
/**
* CaptureEvent listener.
*/
private val captureListener = Consumer<VideoRecordEvent> { event ->
// cache the recording state
if (event !is VideoRecordEvent.Status)
recordingState = event
updateUI(event)
if (event is VideoRecordEvent.Finalize) {
// display the captured video
lifecycleScope.launch {
navController.navigate(
CaptureFragmentDirections.actionCaptureToVideoViewer(
event.outputResults.outputUri
)
)
}
}
}
/**
* Retrieve the asked camera's type(lens facing type). In this sample, only 2 types:
* idx is even number: CameraSelector.LENS_FACING_BACK
* odd number: CameraSelector.LENS_FACING_FRONT
*/
private fun getCameraSelector(idx: Int) : CameraSelector {
if (cameraCapabilities.size == 0) {
Log.i(TAG, "Error: This device does not have any camera, bailing out")
requireActivity().finish()
}
return (cameraCapabilities[idx % cameraCapabilities.size].camSelector)
}
data class CameraCapability(val camSelector: CameraSelector, val qualities:List<Quality>)
/**
* Query and cache this platform's camera capabilities, run only once.
*/
init {
enumerationDeferred = lifecycleScope.async {
whenCreated {
val provider = ProcessCameraProvider.getInstance(requireContext()).await()
provider.unbindAll()
for (camSelector in arrayOf(
CameraSelector.DEFAULT_BACK_CAMERA,
CameraSelector.DEFAULT_FRONT_CAMERA
)) {
try {
// just get the camera.cameraInfo to query capabilities
// we are not binding anything here.
if (provider.hasCamera(camSelector)) {
val camera = provider.bindToLifecycle(requireActivity(), camSelector)
QualitySelector
.getSupportedQualities(camera.cameraInfo)
.filter { quality ->
listOf(Quality.UHD, Quality.FHD, Quality.HD, Quality.SD)
.contains(quality)
}.also {
cameraCapabilities.add(CameraCapability(camSelector, it))
}
val info = Camera2CameraInfo.from(camera.cameraInfo)
Log.d(TAG, "Camera ID: ${info.cameraId}")
val exposureTimeRange = info.getCameraCharacteristic(CameraCharacteristics.SENSOR_INFO_EXPOSURE_TIME_RANGE)
Log.d(TAG, "Camera Face (camera id: ${info.cameraId}) exposureTimeRange: $exposureTimeRange")
val sensitivityRange = info.getCameraCharacteristic(CameraCharacteristics.SENSOR_INFO_SENSITIVITY_RANGE)
Log.d(TAG, "Camera Face (camera id: ${info.cameraId}) sensitivityRange: $sensitivityRange")
}
} catch (exc: java.lang.Exception) {
Log.e(TAG, "Camera Face $camSelector is not supported")
}
}
}
}
}
/**
* One time initialize for CameraFragment (as a part of fragment layout's creation process).
* This function performs the following:
* - initialize but disable all UI controls except the Quality selection.
* - set up the Quality selection recycler view.
* - bind use cases to a lifecycle camera, enable UI controls.
*/
private fun initCameraFragment() {
initializeUI()
viewLifecycleOwner.lifecycleScope.launch {
if (enumerationDeferred != null) {
enumerationDeferred!!.await()
enumerationDeferred = null
}
initializeQualitySectionsUI()
bindCaptureUsecase()
}
}
/**
* Initialize UI. Preview and Capture actions are configured in this function.
* Note that preview and capture are both initialized either by UI or CameraX callbacks
* (except the very 1st time upon entering to this fragment in onCreateView()
*/
@SuppressLint("ClickableViewAccessibility", "MissingPermission")
private fun initializeUI() {
captureViewBinding.cameraButton.apply {
setOnClickListener {
cameraIndex = (cameraIndex + 1) % cameraCapabilities.size
// camera device change is in effect instantly:
// - reset quality selection
// - restart preview
qualityIndex = DEFAULT_QUALITY_IDX
initializeQualitySectionsUI()
enableUI(false)
viewLifecycleOwner.lifecycleScope.launch {
bindCaptureUsecase()
}
}
isEnabled = false
}
// audioEnabled by default is disabled.
captureViewBinding.audioSelection.isChecked = audioEnabled
captureViewBinding.audioSelection.setOnClickListener {
audioEnabled = captureViewBinding.audioSelection.isChecked
}
// React to user touching the capture button
captureViewBinding.captureButton.apply {
setOnClickListener {
if (!this@CaptureFragment::recordingState.isInitialized ||
recordingState is VideoRecordEvent.Finalize)
{
enableUI(false) // Our eventListener will turn on the Recording UI.
startRecording()
} else {
when (recordingState) {
is VideoRecordEvent.Start -> {
currentRecording?.pause()
captureViewBinding.stopButton.visibility = View.VISIBLE
}
is VideoRecordEvent.Pause -> currentRecording?.resume()
is VideoRecordEvent.Resume -> currentRecording?.pause()
else -> throw IllegalStateException("recordingState in unknown state")
}
}
}
isEnabled = false
}
captureViewBinding.stopButton.apply {
setOnClickListener {
// stopping: hide it after getting a click before we go to viewing fragment
captureViewBinding.stopButton.visibility = View.INVISIBLE
if (currentRecording == null || recordingState is VideoRecordEvent.Finalize) {
return@setOnClickListener
}
val recording = currentRecording
if (recording != null) {
recording.stop()
currentRecording = null
}
captureViewBinding.captureButton.setImageResource(R.drawable.ic_start)
}
// ensure the stop button is initialized disabled & invisible
visibility = View.INVISIBLE
isEnabled = false
}
captureLiveStatus.observe(viewLifecycleOwner) {
captureViewBinding.captureStatus.apply {
post { text = it }
}
}
captureLiveStatus.value = getString(R.string.Idle)
}
/**
* UpdateUI according to CameraX VideoRecordEvent type:
* - user starts capture.
* - this app disables all UI selections.
* - this app enables capture run-time UI (pause/resume/stop).
* - user controls recording with run-time UI, eventually tap "stop" to end.
* - this app informs CameraX recording to stop with recording.stop() (or recording.close()).
* - CameraX notify this app that the recording is indeed stopped, with the Finalize event.
* - this app starts VideoViewer fragment to view the captured result.
*/
private fun updateUI(event: VideoRecordEvent) {
val state = if (event is VideoRecordEvent.Status) recordingState.getNameString()
else event.getNameString()
when (event) {
is VideoRecordEvent.Status -> {
// placeholder: we update the UI with new status after this when() block,
// nothing needs to do here.
}
is VideoRecordEvent.Start -> {
showUI(UiState.RECORDING, event.getNameString())
}
is VideoRecordEvent.Finalize-> {
showUI(UiState.FINALIZED, event.getNameString())
}
is VideoRecordEvent.Pause -> {
captureViewBinding.captureButton.setImageResource(R.drawable.ic_resume)
}
is VideoRecordEvent.Resume -> {
captureViewBinding.captureButton.setImageResource(R.drawable.ic_pause)
}
}
val stats = event.recordingStats
val size = stats.numBytesRecorded / 1000
val time = java.util.concurrent.TimeUnit.NANOSECONDS.toSeconds(stats.recordedDurationNanos)
var text = "${state}: recorded ${size}KB, in ${time}second"
if(event is VideoRecordEvent.Finalize)
text = "${text}\nFile saved to: ${event.outputResults.outputUri}"
captureLiveStatus.value = text
Log.i(TAG, "recording event: $text")
}
/**
* Enable/disable UI:
* User could select the capture parameters when recording is not in session
* Once recording is started, need to disable able UI to avoid conflict.
*/
private fun enableUI(enable: Boolean) {
arrayOf(captureViewBinding.cameraButton,
captureViewBinding.captureButton,
captureViewBinding.stopButton,
captureViewBinding.audioSelection,
captureViewBinding.qualitySelection).forEach {
it.isEnabled = enable
}
// disable the camera button if no device to switch
if (cameraCapabilities.size <= 1) {
captureViewBinding.cameraButton.isEnabled = false
}
// disable the resolution list if no resolution to switch
if (cameraCapabilities[cameraIndex].qualities.size <= 1) {
captureViewBinding.qualitySelection.apply { isEnabled = false }
}
}
/**
* initialize UI for recording:
* - at recording: hide audio, qualitySelection,change camera UI; enable stop button
* - otherwise: show all except the stop button
*/
private fun showUI(state: UiState, status:String = "idle") {
captureViewBinding.let {
when(state) {
UiState.IDLE -> {
it.captureButton.setImageResource(R.drawable.ic_start)
it.stopButton.visibility = View.INVISIBLE
it.cameraButton.visibility= View.VISIBLE
it.audioSelection.visibility = View.VISIBLE
it.qualitySelection.visibility=View.VISIBLE
}
UiState.RECORDING -> {
it.cameraButton.visibility = View.INVISIBLE
it.audioSelection.visibility = View.INVISIBLE
it.qualitySelection.visibility = View.INVISIBLE
it.captureButton.setImageResource(R.drawable.ic_pause)
it.captureButton.isEnabled = true
it.stopButton.visibility = View.VISIBLE
it.stopButton.isEnabled = true
}
UiState.FINALIZED -> {
it.captureButton.setImageResource(R.drawable.ic_start)
it.stopButton.visibility = View.INVISIBLE
}
else -> {
val errorMsg = "Error: showUI($state) is not supported"
Log.e(TAG, errorMsg)
return
}
}
it.captureStatus.text = status
}
}
/**
* ResetUI (restart):
* in case binding failed, let's give it another change for re-try. In future cases
* we might fail and user get notified on the status
*/
private fun resetUIandState(reason: String) {
enableUI(true)
showUI(UiState.IDLE, reason)
cameraIndex = 0
qualityIndex = DEFAULT_QUALITY_IDX
audioEnabled = false
captureViewBinding.audioSelection.isChecked = audioEnabled
initializeQualitySectionsUI()
}
/**
* initializeQualitySectionsUI():
* Populate a RecyclerView to display camera capabilities:
* - one front facing
* - one back facing
* User selection is saved to qualityIndex, will be used
* in the bindCaptureUsecase().
*/
private fun initializeQualitySectionsUI() {
val selectorStrings = cameraCapabilities[cameraIndex].qualities.map {
it.getNameString()
}
// create the adapter to Quality selection RecyclerView
captureViewBinding.qualitySelection.apply {
layoutManager = LinearLayoutManager(context)
adapter = GenericListAdapter(
selectorStrings,
itemLayoutId = R.layout.video_quality_item
) { holderView, qcString, position ->
holderView.apply {
findViewById<TextView>(R.id.qualityTextView)?.text = qcString
// select the default quality selector
isSelected = (position == qualityIndex)
}
holderView.setOnClickListener { view ->
if (qualityIndex == position) return@setOnClickListener
captureViewBinding.qualitySelection.let {
// deselect the previous selection on UI.
it.findViewHolderForAdapterPosition(qualityIndex)
?.itemView
?.isSelected = false
}
// turn on the new selection on UI.
view.isSelected = true
qualityIndex = position
// rebind the use cases to put the new QualitySelection in action.
enableUI(false)
viewLifecycleOwner.lifecycleScope.launch {
bindCaptureUsecase()
}
}
}
isEnabled = false
}
}
// System function implementations
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_captureViewBinding = FragmentCaptureBinding.inflate(inflater, container, false)
return captureViewBinding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initCameraFragment()
}
override fun onDestroyView() {
_captureViewBinding = null
super.onDestroyView()
}
companion object {
// default Quality selection if no input from UI
const val DEFAULT_QUALITY_IDX = 0
val TAG:String = CaptureFragment::class.java.simpleName
private const val FILENAME_FORMAT = "yyyy-MM-dd-HH-mm-ss-SSS"
}
}